diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index af8f3639a0..13f4c2a6a0 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1938,6 +1938,26 @@ dependencies = [ "sha2 0.10.9", ] +[[package]] +name = "codex-agent-message-board-client" +version = "0.0.0" +dependencies = [ + "anyhow", + "chrono", + "codex-agent-message-board-extension", + "codex-http-client", + "codex-protocol", + "eventsource-stream", + "futures", + "http 1.4.0", + "pretty_assertions", + "serde", + "serde_json", + "tokio", + "url", + "wiremock", +] + [[package]] name = "codex-agent-message-board-extension" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 3d06aea813..adceeb5ed9 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -3,6 +3,7 @@ members = [ "aws-auth", "analytics", "agent-graph-store", + "agent-message-board-client", "agent-identity", "agent-roles", "backend-client", diff --git a/codex-rs/agent-message-board-client/BUILD.bazel b/codex-rs/agent-message-board-client/BUILD.bazel new file mode 100644 index 0000000000..cd4f32e259 --- /dev/null +++ b/codex-rs/agent-message-board-client/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "agent-message-board-client", + crate_name = "codex_agent_message_board_client", +) diff --git a/codex-rs/agent-message-board-client/Cargo.toml b/codex-rs/agent-message-board-client/Cargo.toml new file mode 100644 index 0000000000..b8b77a9245 --- /dev/null +++ b/codex-rs/agent-message-board-client/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "codex-agent-message-board-client" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lib] +test = false +doctest = false + +[lints] +workspace = true + +[dependencies] +anyhow = { workspace = true } +chrono = { workspace = true, features = ["serde"] } +codex-agent-message-board-extension = { workspace = true } +codex-http-client = { workspace = true } +codex-protocol = { workspace = true } +eventsource-stream = { workspace = true } +futures = { workspace = true } +http = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +tokio = { workspace = true, features = ["time"] } +url = { workspace = true } + +[dev-dependencies] +pretty_assertions = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } +wiremock = { workspace = true } diff --git a/codex-rs/agent-message-board-client/README.md b/codex-rs/agent-message-board-client/README.md new file mode 100644 index 0000000000..6fd746382c --- /dev/null +++ b/codex-rs/agent-message-board-client/README.md @@ -0,0 +1,20 @@ +# Remote agent message board + +`RemoteAgentMessageBoard` implements the existing board contract over an HTTP API. +Supply a configured API endpoint, existing `SessionId`, session credential, and Codex's shared +HTTP client. Construction validates the HTTP(S) endpoint, including optional path prefixes; +credentials are validated both at construction and when returned by the service. The backend can be deployed independently of Codex. + +Each board belongs to one agent tree, exactly like the local backend. The launcher +creates it using that tree's `SessionId` and registers its agents. Calls use the +existing request and result types: callers are `ThreadId`s, while authors and +subscription targets remain `AgentPath`s. + +Live SSE notifications are bound to the receiving turn. Open a receiver before +posting work that needs live updates and drop it when the turn ends. Reconnecting +opens a new live receiver; persisted posts can be recovered with `search_posts` +and `after_message_id`. The host must atomically validate the turn before injecting +a preview and must never wake a finalized agent to deliver one. + +See `protocol.rs` for the v1 requests. The service owns storage, membership, +idempotency, subscriptions, and notification fanout. This crate contains no server. diff --git a/codex-rs/agent-message-board-client/src/client.rs b/codex-rs/agent-message-board-client/src/client.rs new file mode 100644 index 0000000000..75bb1664e4 --- /dev/null +++ b/codex-rs/agent-message-board-client/src/client.rs @@ -0,0 +1,335 @@ +//! Typed remote implementation of the board contract. HTTP policy is supplied +//! by the caller; reads and writes never fall back to a private local board. + +use crate::protocol::AccessToken; +use crate::protocol::BoardNotification; +use crate::protocol::Call; +use crate::protocol::Failure; +use crate::protocol::MAX_BODY; +use crate::protocol::MAX_RESPONSE; +use crate::protocol::Operation; +use crate::protocol::Registration; +use crate::protocol::Watch; +use anyhow::Context; +use chrono::DateTime; +use chrono::Utc; +use codex_agent_message_board_extension::AgentMessageBoard; +use codex_agent_message_board_extension::ChannelQuery; +use codex_agent_message_board_extension::ChannelSummary; +use codex_agent_message_board_extension::CreateChannelRequest; +use codex_agent_message_board_extension::Page; +use codex_agent_message_board_extension::PostContent; +use codex_agent_message_board_extension::PostMetadata; +use codex_agent_message_board_extension::PostPreview; +use codex_agent_message_board_extension::PostQuery; +use codex_agent_message_board_extension::PostRequest; +use codex_agent_message_board_extension::ReadPostRequest; +use codex_agent_message_board_extension::ReadThreadRequest; +use codex_agent_message_board_extension::SubscriptionRequest; +use codex_agent_message_board_extension::SubscriptionState; +use codex_agent_message_board_extension::ThreadPage; +use codex_agent_message_board_extension::ThreadQuery; +use codex_agent_message_board_extension::ThreadSummary; +use codex_http_client::HttpClient; +use codex_http_client::HttpResponse; +use codex_protocol::AgentPath; +use codex_protocol::SessionId; +use codex_protocol::ThreadId; +use codex_protocol::error::CodexErr; +use codex_protocol::error::Result; +use eventsource_stream::Eventsource; +use futures::StreamExt; +use futures::future::BoxFuture; +use futures::stream::BoxStream; +use serde::de::DeserializeOwned; +use std::collections::HashMap; +use std::error::Error; +use std::sync::Arc; +use std::time::Duration; +use url::Url; + +/// A client for one session's board. Use the shared HTTP client's configured +/// proxy and CA policy. +#[derive(Clone)] +pub struct RemoteAgentMessageBoard { + http: HttpClient, + board_url: Url, + board: SessionId, + token: AccessToken, + clock: Arc BoxFuture<'static, Result>> + Send + Sync>, +} + +impl RemoteAgentMessageBoard { + /// Validate the HTTP(S) endpoint and append the board path to its optional path prefix. + pub fn new( + http: HttpClient, + endpoint: &str, + board: SessionId, + token: AccessToken, + ) -> anyhow::Result { + let mut board_url = Url::parse(endpoint).context("invalid message-board endpoint")?; + anyhow::ensure!( + matches!(board_url.scheme(), "http" | "https") && board_url.host_str().is_some(), + "message-board endpoint must be an HTTP(S) URL" + ); + anyhow::ensure!( + board_url.query().is_none() && board_url.fragment().is_none(), + "message-board endpoint must not contain a query or fragment" + ); + board_url.set_path(&format!( + "{}/v1/boards/{board}", + board_url.path().trim_end_matches('/') + )); + Ok(Self { + http, + board_url, + board, + token, + clock: Arc::new(|_| Box::pin(async { Ok(Utc::now()) })), + }) + } + + /// Supply the runtime's configured clock for research's simulated time. + pub fn with_clock( + mut self, + clock: impl Fn(ThreadId) -> BoxFuture<'static, Result>> + Send + Sync + 'static, + ) -> Self { + self.clock = Arc::new(clock); + self + } + + pub async fn create_board(&self) -> Result { + let response = self + .http + .request(http::Method::PUT, self.url("")) + .bearer_auth(&self.token.0) + .timeout(Duration::from_secs(/*secs*/ 30)) + .send() + .await + .map_err(transport_error)?; + decode(response).await + } + + pub async fn delete_board(&self) -> Result<()> { + let response = self + .http + .delete(self.url("")) + .bearer_auth(&self.token.0) + .timeout(Duration::from_secs(/*secs*/ 30)) + .send() + .await + .map_err(transport_error)?; + if response.status().is_success() { + Ok(()) + } else { + decode(response).await + } + } + + /// Register the session's agents. The returned session token is stable on retry. + pub async fn register_members( + &self, + members: HashMap, + ) -> Result { + let response = self + .http + .post(self.url("/members")) + .bearer_auth(&self.token.0) + .json(&Registration { members }) + .timeout(Duration::from_secs(/*secs*/ 30)) + .send() + .await + .map_err(transport_error)?; + decode(response).await + } + + /// Opens a live receiver and waits until the service has registered it. + /// Setup, including readiness or an error body, has a 30-second deadline. + /// Drop it when the turn ends. Reopening does not replay earlier previews. + pub async fn notifications( + &self, + caller: ThreadId, + turn_id: String, + ) -> Result { + let deadline = tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 30); + let response = tokio::time::timeout_at( + deadline, + self.http + .post(self.url("/notifications")) + .bearer_auth(&self.token.0) + .json(&Watch { + caller, + turn_id: turn_id.clone(), + }) + .send(), + ) + .await + .map_err(transport_error)? + .map_err(transport_error)?; + if !response.status().is_success() { + tokio::time::timeout_at(deadline, decode::<()>(response)) + .await + .map_err(transport_error)??; + return Err(transport_error("unexpected notification response")); + } + let mut events = response.bytes_stream().eventsource(); + let ready = tokio::time::timeout_at(deadline, events.next()) + .await + .map_err(transport_error)? + .ok_or_else(|| transport_error("notification stream closed before readiness"))? + .map_err(transport_error)?; + if ready.event != "ready" { + return Err(transport_error( + "notification stream did not acknowledge readiness", + )); + } + let stream = events + .map(|event| { + let event = event.map_err(transport_error)?; + if event.event != "notification" || event.data.len() > MAX_BODY { + return Err(transport_error("invalid board notification")); + } + serde_json::from_str(&event.data).map_err(CodexErr::from) + }) + .boxed(); + Ok(BoardNotifications { + caller, + turn_id, + stream, + }) + } + + fn url(&self, suffix: &str) -> Url { + let mut url = self.board_url.clone(); + url.set_path(&format!("{}{suffix}", url.path())); + url + } + + async fn call(&self, caller: ThreadId, operation: Operation) -> Result { + let timestamp = match &operation { + Operation::CreateChannel(_) => Some((self.clock)(caller).await?), + // The service can replay a committed post without a fresh timestamp. + // A new post still requires one; never substitute wall-clock time. + Operation::Post(_) => (self.clock)(caller).await.ok(), + Operation::ListChannels(_) + | Operation::ListThreads(_) + | Operation::SearchPosts(_) + | Operation::ReadThread(_) + | Operation::ReadPost(_) + | Operation::SetSubscription(_) => None, + }; + let call = Call { + caller, + timestamp, + operation, + }; + let body = serde_json::to_vec(&call)?; + if body.len() > MAX_BODY { + return Err(CodexErr::InvalidRequest( + "board request exceeds the service limit".into(), + )); + } + let response = self + .http + .post(self.url("/call")) + .bearer_auth(&self.token.0) + .header("content-type", "application/json") + .body(body) + .timeout(Duration::from_secs(/*secs*/ 30)) + .send() + .await + .map_err(transport_error)?; + decode(response).await + } +} + +macro_rules! operation { + ($method:ident, $variant:ident, $input:ty, $output:ty) => { + fn $method(&self, caller: ThreadId, request: $input) -> BoxFuture<'_, Result<$output>> { + Box::pin(self.call(caller, Operation::$variant(request))) + } + }; +} + +impl AgentMessageBoard for RemoteAgentMessageBoard { + fn identity(&self) -> SessionId { + self.board + } + operation!( + create_channel, + CreateChannel, + CreateChannelRequest, + ChannelSummary + ); + operation!( + list_channels, + ListChannels, + ChannelQuery, + Page + ); + operation!(post, Post, PostRequest, PostMetadata); + operation!(list_threads, ListThreads, ThreadQuery, Page); + operation!(search_posts, SearchPosts, PostQuery, Page); + operation!(read_thread, ReadThread, ReadThreadRequest, ThreadPage); + operation!(read_post, ReadPost, ReadPostRequest, PostContent); + operation!( + set_subscription, + SetSubscription, + SubscriptionRequest, + SubscriptionState + ); +} + +/// One active turn's live receiver. The host must also check the turn atomically +/// when injecting a returned notification, since the turn can end after `next`. +pub struct BoardNotifications { + caller: ThreadId, + turn_id: String, + stream: BoxStream<'static, Result>, +} + +impl BoardNotifications { + pub async fn next(&mut self) -> Result> { + let Some(notice) = self.stream.next().await.transpose()? else { + return Ok(None); + }; + if notice.recipient != self.caller || notice.turn_id != self.turn_id { + return Err(transport_error( + "notification belongs to another agent or turn", + )); + } + if notice.post.text_preview.chars().count() > 150 { + return Err(transport_error( + "board notification preview exceeds 150 characters", + )); + } + Ok(Some(notice)) + } +} + +async fn decode(mut response: HttpResponse) -> Result { + let status = response.status(); + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(transport_error)? { + if body.len().saturating_add(chunk.len()) > MAX_RESPONSE { + return Err(transport_error("board response exceeds the service limit")); + } + body.extend_from_slice(&chunk); + } + if !status.is_success() { + let failure: Failure = serde_json::from_slice(&body) + .with_context(|| format!("invalid board error response (HTTP {status})")) + .map_err(transport_error)?; + let message = format!("{}: {}", failure.code, failure.message); + return Err(if status.is_server_error() { + transport_error(message) + } else { + CodexErr::InvalidRequest(message) + }); + } + serde_json::from_slice(&body).map_err(CodexErr::from) +} + +fn transport_error(error: impl Into>) -> CodexErr { + CodexErr::Io(std::io::Error::other(error)) +} diff --git a/codex-rs/agent-message-board-client/src/lib.rs b/codex-rs/agent-message-board-client/src/lib.rs new file mode 100644 index 0000000000..1e181da375 --- /dev/null +++ b/codex-rs/agent-message-board-client/src/lib.rs @@ -0,0 +1,10 @@ +//! A typed client for a message-board API at a configured endpoint. +//! Runtime credentials are scoped to one session; tools never see them. + +mod client; +mod protocol; + +pub use client::BoardNotifications; +pub use client::RemoteAgentMessageBoard; +pub use protocol::AccessToken; +pub use protocol::BoardNotification; diff --git a/codex-rs/agent-message-board-client/src/protocol.rs b/codex-rs/agent-message-board-client/src/protocol.rs new file mode 100644 index 0000000000..267a7502d3 --- /dev/null +++ b/codex-rs/agent-message-board-client/src/protocol.rs @@ -0,0 +1,101 @@ +//! Versioned service requests reuse board operations; only host identity travels separately. + +use chrono::DateTime; +use chrono::Utc; +use codex_agent_message_board_extension::ChannelQuery; +use codex_agent_message_board_extension::CreateChannelRequest; +use codex_agent_message_board_extension::PostPreview; +use codex_agent_message_board_extension::PostQuery; +use codex_agent_message_board_extension::PostRequest; +use codex_agent_message_board_extension::ReadPostRequest; +use codex_agent_message_board_extension::ReadThreadRequest; +use codex_agent_message_board_extension::SubscriptionRequest; +use codex_agent_message_board_extension::ThreadQuery; +use codex_protocol::AgentPath; +use codex_protocol::ThreadId; +use serde::Deserialize; +use serde::Deserializer; +use serde::Serialize; +use std::collections::HashMap; +use std::fmt; + +pub(crate) const MAX_BODY: usize = 512 * 1024; +pub(crate) const MAX_RESPONSE: usize = 1024 * 1024; + +/// A host credential. Debug output must never reveal its contents. +#[derive(Clone, Serialize)] +#[serde(transparent)] +pub struct AccessToken(pub(crate) String); + +impl AccessToken { + pub fn new(value: String) -> anyhow::Result { + anyhow::ensure!( + (32..=4096).contains(&value.len()), + "credentials must contain 32–4096 bytes" + ); + anyhow::ensure!( + value.bytes().all(|b| b.is_ascii_graphic()), + "credential must be ASCII without whitespace" + ); + Ok(Self(value)) + } +} + +impl<'de> Deserialize<'de> for AccessToken { + fn deserialize>(deserializer: D) -> Result { + Self::new(String::deserialize(deserializer)?).map_err(serde::de::Error::custom) + } +} + +impl fmt::Debug for AccessToken { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("AccessToken([REDACTED])") + } +} + +#[derive(Serialize)] +pub(crate) struct Registration { + pub(crate) members: HashMap, +} + +#[derive(Serialize)] +pub(crate) struct Call { + pub(crate) caller: ThreadId, + pub(crate) timestamp: Option>, + #[serde(flatten)] + pub(crate) operation: Operation, +} + +#[derive(Serialize)] +#[serde(tag = "method", content = "params", rename_all = "snake_case")] +pub(crate) enum Operation { + CreateChannel(CreateChannelRequest), + ListChannels(ChannelQuery), + Post(PostRequest), + ListThreads(ThreadQuery), + SearchPosts(PostQuery), + ReadThread(ReadThreadRequest), + ReadPost(ReadPostRequest), + SetSubscription(SubscriptionRequest), +} + +#[derive(Serialize)] +pub(crate) struct Watch { + pub(crate) caller: ThreadId, + pub(crate) turn_id: String, +} + +/// A best-effort preview bound to the receiving turn. Hosts must atomically check +/// `turn_id` when admitting it; a received preview must never start a new turn. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct BoardNotification { + pub recipient: ThreadId, + pub turn_id: String, + pub post: PostPreview, +} + +#[derive(Deserialize)] +pub(crate) struct Failure { + pub(crate) code: String, + pub(crate) message: String, +} diff --git a/codex-rs/agent-message-board-client/tests/remote_board.rs b/codex-rs/agent-message-board-client/tests/remote_board.rs new file mode 100644 index 0000000000..0721d9da16 --- /dev/null +++ b/codex-rs/agent-message-board-client/tests/remote_board.rs @@ -0,0 +1,237 @@ +//! Exercise the HTTP adapter's clock, authentication and turn-bound stream. + +use chrono::DateTime; +use chrono::Utc; +use codex_agent_message_board_client::AccessToken; +use codex_agent_message_board_client::BoardNotification; +use codex_agent_message_board_client::RemoteAgentMessageBoard; +use codex_agent_message_board_extension::AgentMessageBoard; +use codex_agent_message_board_extension::PostContent; +use codex_agent_message_board_extension::PostDestination; +use codex_agent_message_board_extension::PostMetadata; +use codex_agent_message_board_extension::PostPreview; +use codex_agent_message_board_extension::PostRequest; +use codex_agent_message_board_extension::ReadPostRequest; +use codex_http_client::HttpClientBuilder; +use codex_protocol::AgentPath; +use codex_protocol::SessionId; +use codex_protocol::ThreadId; +use codex_protocol::error::CodexErr; +use codex_protocol::error::CodexErrorDetails; +use pretty_assertions::assert_eq; +use serde_json::json; +use std::collections::HashMap; +use std::num::NonZeroU32; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use wiremock::Mock; +use wiremock::MockServer; +use wiremock::ResponseTemplate; +use wiremock::matchers::body_json; +use wiremock::matchers::header; +use wiremock::matchers::method; +use wiremock::matchers::path; + +#[tokio::test] +async fn remote_board_preserves_the_host_contract() -> anyhow::Result<()> { + let server = MockServer::start().await; + let http = HttpClientBuilder::new().build_direct()?; + let board = SessionId::new(); + let caller = ThreadId::new(); + let members = HashMap::from([(caller, AgentPath::root())]); + let endpoint = format!("{}/board-service", server.uri()); + let base = format!("/board-service/v1/boards/{board}"); + let admin_token = AccessToken::new("administrator-credential-for-integration".into())?; + for invalid in [ + "not a URL", + "file:///tmp/board", + "https://board.test/?query", + "https://board.test/#fragment", + ] { + assert!( + RemoteAgentMessageBoard::new(http.clone(), invalid, board, admin_token.clone()) + .is_err() + ); + } + let admin = + RemoteAgentMessageBoard::new(http.clone(), &format!("{endpoint}/"), board, admin_token)?; + Mock::given(method("PUT")) + .and(path(&base)) + .and(header( + "authorization", + "Bearer administrator-credential-for-integration", + )) + .respond_with(ResponseTemplate::new(200).set_body_json(board)) + .expect(1) + .mount(&server) + .await; + assert_eq!(admin.create_board().await?, board); + let invalid_registration = Mock::given(method("POST")) + .and(path(format!("{base}/members"))) + .respond_with(ResponseTemplate::new(200).set_body_json("too-short")) + .expect(1) + .mount_as_scoped(&server) + .await; + let error = admin.register_members(members.clone()).await.unwrap_err(); + assert!(matches!(error.details(), CodexErrorDetails::Json(_))); + drop(invalid_registration); + Mock::given(method("POST")) + .and(path(format!("{base}/members"))) + .and(body_json(json!({"members": members}))) + .respond_with( + ResponseTemplate::new(200).set_body_json("runtime-credential-for-integration-32"), + ) + .expect(1) + .mount(&server) + .await; + let token = admin.register_members(members).await?; + let now: DateTime = "2026-09-24T12:00:00Z".parse()?; + let clock_available = Arc::new(AtomicBool::new(true)); + let clock = clock_available.clone(); + let client = + RemoteAgentMessageBoard::new(http, &endpoint, board, token)?.with_clock(move |_| { + let available = clock.load(Ordering::Relaxed); + Box::pin(async move { + if available { + Ok(now) + } else { + Err(CodexErr::Io(std::io::Error::other("clock unavailable"))) + } + }) + }); + let metadata: PostMetadata = serde_json::from_value(json!({ + "message_id": "00000000-0000-4000-8000-000000000001", "thread_id": "00000000-0000-4000-8000-000000000001", + "author": "/root", "channel_name": "results", "created_at": now, + }))?; + let post = PostRequest { + request_id: "call-1".into(), + destination: PostDestination::NewChannel("results".into()), + text: "Straße 🦀".into(), + agents_to_notify: vec![AgentPath::root()], + }; + Mock::given(method("POST")) + .and(path(format!("{base}/call"))) + .and(header( + "authorization", + "Bearer runtime-credential-for-integration-32", + )) + .and(body_json( + json!({"caller": caller, "timestamp": now, "method": "post", "params": post}), + )) + // The post committed, but a gateway failed to return its result. + .respond_with( + ResponseTemplate::new(503) + .set_body_json(json!({"code": "unavailable", "message": "response unavailable"})), + ) + .expect(1) + .mount(&server) + .await; + let board_handle: &dyn AgentMessageBoard = &client; + assert_eq!(board_handle.identity(), board); + assert!(board_handle.post(caller, post.clone()).await.is_err()); + clock_available.store(false, Ordering::Relaxed); + Mock::given(method("POST")) + .and(path(format!("{base}/call"))) + .and(body_json( + json!({"caller": caller, "timestamp": null, "method": "post", "params": post}), + )) + .respond_with(ResponseTemplate::new(200).set_body_json(&metadata)) + .expect(1) + .mount(&server) + .await; + assert_eq!(client.post(caller, post).await?, metadata); + let request = ReadPostRequest { + message_id: metadata.message_id, + offset_chars: 7, + limit_chars: NonZeroU32::MIN, + }; + let content = PostContent { + metadata: metadata.clone(), + text: "🦀".into(), + n_chars: 8, + next_offset_chars: 8, + }; + Mock::given(method("POST")) + .and(path(format!("{base}/call"))) + .and(body_json( + json!({"caller": caller, "timestamp": null, "method": "read_post", "params": request}), + )) + .respond_with(ResponseTemplate::new(200).set_body_json(&content)) + .expect(1) + .mount(&server) + .await; + assert_eq!(client.read_post(caller, request).await?, content); + let notice = BoardNotification { + recipient: caller, + turn_id: "turn-1".into(), + post: PostPreview { + metadata, + text_preview: "Straße 🦀".into(), + n_chars: 8, + truncated: false, + }, + }; + let mut stale = notice.clone(); + stale.turn_id = "turn-0".into(); + let mut oversized = notice.clone(); + oversized.post.text_preview = "🦀".repeat(151); + let events = [¬ice, &stale, &oversized] + .into_iter() + .map(|event| { + Ok(format!( + "event: notification\ndata: {}\n\n", + serde_json::to_string(event)? + )) + }) + .collect::>()?; + Mock::given(method("POST")) + .and(path(format!("{base}/notifications"))) + .and(body_json(json!({"caller": caller, "turn_id": "turn-1"}))) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-type", "text/event-stream") + .set_body_string(format!( + "event: ready\ndata: {{}}\n\n: heartbeat\n\n{events}" + )), + ) + .expect(1) + .mount(&server) + .await; + let mut receiver = client.notifications(caller, "turn-1".into()).await?; + assert_eq!(receiver.next().await?, Some(notice)); + assert!(receiver.next().await.is_err()); + assert!(receiver.next().await.is_err()); + let invalid_response = Mock::given(method("DELETE")) + .and(path(&base)) + .respond_with(ResponseTemplate::new(502).set_body_string("not JSON")) + .expect(1) + .mount_as_scoped(&server) + .await; + let error = admin.delete_board().await.unwrap_err(); + assert!(error.to_string().contains("HTTP 502")); + assert!( + anyhow::Error::new(error) + .chain() + .any(::is::) + ); + drop(invalid_response); + Mock::given(method("DELETE")) + .and(path(base)) + .respond_with( + ResponseTemplate::new(503) + .set_body_json(json!({"code": "unavailable", "message": "storage unavailable"})), + ) + .expect(1) + .mount(&server) + .await; + assert!( + admin + .delete_board() + .await + .unwrap_err() + .to_string() + .contains("storage unavailable") + ); + Ok(()) +}