### GET Request Example Source: https://docs.rs/asupersync/0.2.9/asupersync/http/h1/http_client/index.html Demonstrates how to initialize an HttpClient and perform a basic GET request to a specified URL. ```APIDOC ## GET /api ### Description Performs a GET request using the HttpClient to the specified URL. ### Method GET ### Request Example ```rust let client = HttpClient::new(); let cx = Cx::for_testing(); let resp = client.get(&cx, "http://example.com/api").await?; ``` ### Response #### Success Response (200) - **resp** (Response) - The HTTP response object containing status and body. ``` -------------------------------- ### WebSocket Server Example Source: https://docs.rs/asupersync/0.2.9/asupersync/net/websocket/index.html Example demonstrating how to set up a WebSocket server, accept upgrade requests, and echo received messages back to clients. ```APIDOC ## WebSocket Server Usage ### Description This example illustrates how to create a WebSocket acceptor, handle incoming upgrade requests, and implement an echo server that sends back received messages. ### Method `WebSocketAcceptor::new`, `acceptor.accept`, `ws.recv`, `ws.send` ### Endpoint Listens for incoming connections on a specified protocol (e.g., "chat"). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `request_bytes`, `tcp_stream` (provided during accept) ### Request Example ```rust use asupersync::net::websocket::{WebSocketAcceptor, Message}; // Create acceptor let acceptor = WebSocketAcceptor::new().protocol("chat"); // Accept upgrade request let ws = acceptor.accept(&cx, request_bytes, tcp_stream).await?; // Echo messages while let Some(msg) = ws.recv(&cx).await? { ws.send(&cx, msg).await?; } ``` ### Response #### Success Response (200) Echoed messages sent back to the client. #### Response Example ``` (No direct response example for echo, as it mirrors received messages) ``` ``` -------------------------------- ### SSE Example Source: https://docs.rs/asupersync/0.2.9/asupersync/web/sse/index.html An example demonstrating how to create and return an SSE response using the `Sse` and `SseEvent` types from the `asupersync::web::sse` module. ```APIDOC ## Example ```rust use asupersync::web::sse::{SseEvent, Sse}; fn handler() -> Sse { Sse::new(vec![ SseEvent::default().data("hello"), SseEvent::default().event("ping").data("alive"), ]) } ``` ``` -------------------------------- ### WebSocket Client Example Source: https://docs.rs/asupersync/0.2.9/asupersync/net/websocket/index.html Example demonstrating how to connect to a WebSocket server, send messages, and receive messages using the asupersync WebSocket client. ```APIDOC ## WebSocket Client Usage ### Description This example shows how to establish a WebSocket connection, send text messages, and continuously receive messages from a server. ### Method `WebSocket::connect` (for connection), `ws.send` (for sending), `ws.recv` (for receiving) ### Endpoint `ws://example.com/chat` (example URL) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `Message::text("Hello!")` (for sending a text message) ### Request Example ```rust use asupersync::net::websocket::{WebSocket, Message}; // Connect to a WebSocket server let ws = WebSocket::connect(&cx, "ws://example.com/chat").await?; // Send a message ws.send(&cx, Message::text("Hello!")).await?; // Receive messages while let Some(msg) = ws.recv(&cx).await? { println!("Received: {:?}", msg); } ``` ### Response #### Success Response (200) Messages received from the server. #### Response Example ``` Received: Text("Welcome!") Received: Binary(...) ``` ``` -------------------------------- ### Spawn Task Example Source: https://docs.rs/asupersync/0.2.9/asupersync/cx/scope/struct.Scope.html Example demonstrating how to spawn a task using `scope.spawn` and await its result using `handle.join`. The spawned task can access the capability context for tracing. ```rust let handle = scope.spawn(&mut state, &cx, |cx| async move { cx.trace("Child task running"); compute_value().await }); let result = handle.join(&cx).await?; ``` -------------------------------- ### Example Usage of EpochId Source: https://docs.rs/asupersync/0.2.9/asupersync/epoch/struct.EpochId.html Demonstrates basic usage of EpochId, including getting the genesis epoch, advancing to the next epoch, and checking epoch order. Requires the `asupersync` crate. ```rust let current = EpochId::GENESIS; let next = current.next(); assert!(current.is_before(next)); ``` -------------------------------- ### Saga Usage Example Source: https://docs.rs/asupersync/0.2.9/asupersync/remote/struct.Saga.html Example demonstrating how to define steps and compensations within a Saga. ```APIDOC use asupersync::remote::Saga; let mut saga = Saga::new(); // Step 1: Create resource saga.step( "create resource", || Ok("resource-1".to_string()), move || format!("deleted resource-1"), )?; // Step 2: Configure saga.step("configure", || Ok(()), || "reset config".into())?; // Complete on success saga.complete(); ``` -------------------------------- ### VirtualClock - Example Usage Source: https://docs.rs/asupersync/0.2.9/asupersync/time/struct.VirtualClock.html Demonstrates how to use the VirtualClock for testing. ```APIDOC ### Example ```rust use asupersync::time::{TimeSource, VirtualClock}; use asupersync::types::Time; let clock = VirtualClock::new(); assert_eq!(clock.now(), Time::ZERO); clock.advance(1_000_000_000); // 1 second assert_eq!(clock.now(), Time::from_secs(1)); ``` ``` -------------------------------- ### Usage Example Source: https://docs.rs/asupersync/0.2.9/asupersync/lab/dual_run/struct.DualRunHarness.html Example demonstrating how to use the DualRunHarness to set up and run a differential test. ```APIDOC ### Usage ```rust let result = DualRunHarness::phase1( "cancel.race.one_loser", "cancellation.race", "v1", "Race two tasks, cancel loser, verify drain", 42, ) .lab(|config| { let mut lab = LabRuntime::new(config); // ... run scenario ... make_happy_semantics() }) .live(|seed, entropy_seed| { // ... run scenario on current-thread runtime ... make_happy_semantics() }) .run(); assert!(result.passed()); ``` ``` -------------------------------- ### CrashPack Usage Example Source: https://docs.rs/asupersync/0.2.9/asupersync/trace/crashpack/index.html Example demonstrating how to build a CrashPack with failure information and a fingerprint. ```APIDOC ## CrashPack Usage Example ### Description This example shows how to create a `CrashPack` using its builder, configuring it with essential details like a seed, configuration hash, failure information, and a trace fingerprint. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A (Code Example) ### Request Example N/A (Code Example) ### Response N/A (Code Example) ### Code ```rust use asupersync::trace::crashpack::{CrashPack, CrashPackConfig, FailureInfo, FailureOutcome}; use asupersync::types::{TaskId, RegionId, Time}; let pack = CrashPack::builder(CrashPackConfig { seed: 42, config_hash: 0xDEAD, ..Default::default() }) .failure(FailureInfo { task: TaskId::testing_default(), region: RegionId::testing_default(), outcome: FailureOutcome::Panicked { message: "oops".to_string() }, virtual_time: Time::from_secs(5), }) .fingerprint(0xCAFE_BABE) .build() .expect("crash pack builder should have failure metadata"); assert_eq!(pack.manifest.schema_version, CRASHPACK_SCHEMA_VERSION); ``` ``` -------------------------------- ### Create and Start a Redis Docker Fixture Source: https://docs.rs/asupersync/0.2.9/asupersync/test_logging/struct.DockerFixtureService.html Instantiates a Redis Docker container, maps a host port, sets a health check command, starts the container, and waits for it to become healthy. Ensure the necessary imports and `port` variable are defined. ```rust let mut redis = DockerFixtureService::new("redis", "redis:7-alpine") .with_port_map(port, 6379) .with_health_cmd(vec!["redis-cli", "ping"]); redis.start()?; wait_until_healthy(&redis, Duration::from_secs(10))?; ``` -------------------------------- ### Example: Two-Phase Commit Choreography Source: https://docs.rs/asupersync/0.2.9/asupersync/obligation/choreography/index.html An example demonstrating the construction and validation of a two-phase commit choreography using the Asupersync DSL. ```APIDOC ## Example: Two-Phase Commit Choreography ```rust use asupersync::obligation::choreography::*; let protocol = GlobalProtocol::builder("two_phase_commit") .participant("coordinator", "saga-coordinator") .participant("worker", "saga-participant") .interaction( Interaction::comm("coordinator", "reserve", "ReserveMsg", "worker") .then(Interaction::choice( "coordinator", "commit_ready", Interaction::comm("coordinator", "commit", "CommitMsg", "worker") .then(Interaction::end()) .expect("comm interactions accept continuations"), Interaction::comm("coordinator", "abort", "AbortMsg", "worker") .then(Interaction::end()) .expect("comm interactions accept continuations"), )) .expect("comm interactions accept continuations"), ) .build(); let errors = protocol.validate(); assert!(errors.is_empty(), "Validation errors: {errors:?}"); // Knowledge-of-choice: coordinator decides, so it must be the sender // in the first communication after the branch. This is validated // automatically. assert!(protocol.is_deadlock_free()); ``` ``` -------------------------------- ### Async File Create and Write Example Source: https://docs.rs/asupersync/0.2.9/asupersync/fs/index.html Demonstrates creating a file, writing data to it, synchronizing changes, and then reading the content back asynchronously. Ensure proper error handling with `?`. ```rust use asupersync::fs::File; async fn example() -> std::io::Result<()> { // Create and write let mut file = File::create("test.txt").await?; file.write_all(b"hello").await?; file.sync_all().await?; drop(file); // Read back let mut file = File::open("test.txt").await?; let mut contents = String::new(); file.read_to_string(&mut contents).await?; Ok(()) } ``` -------------------------------- ### Get Child Names in Start Order Source: https://docs.rs/asupersync/0.2.9/asupersync/supervision/struct.CompiledSupervisor.html Returns a vector of child names in their deterministic start order. This order is used for supervisor startup. ```rust pub fn child_start_order_names(&self) -> Vec<&str> ``` -------------------------------- ### Get Drain Start Time Source: https://docs.rs/asupersync/0.2.9/asupersync/server/shutdown/struct.ShutdownSignal.html Returns the time when the drain phase began, if applicable. Returns `None` if the drain phase has not yet started. ```rust pub fn drain_start(&self) -> Option