Compare commits
12 Commits
feat/http/
...
c34b4d2df4
| Author | SHA1 | Date | |
|---|---|---|---|
| c34b4d2df4 | |||
| 2905e55e72 | |||
| c58eccd5a6 | |||
| b673b7f317 | |||
| 4ac8d308e6 | |||
| 62bebe5122 | |||
| a1e4752fdf | |||
| d841cc35b9 | |||
| 5c37e5b3af | |||
| 67b1adba98 | |||
| f12e227df0 | |||
| acaa0513e4 |
@@ -20,7 +20,7 @@ use crate::protocol::connection::CallConnection;
|
||||
use crate::protocol::wire::ResponseEnvelope;
|
||||
use crate::registry::context::OperationContext;
|
||||
use crate::registry::registration::{
|
||||
Handler, HandlerKind, HandlerRegistration, OperationProvenance,
|
||||
Handler, HandlerKind, HandlerRegistration, OperationProvenance, StreamingHandler,
|
||||
};
|
||||
use crate::registry::spec::{
|
||||
AccessControl, ErrorDefinition, OperationSpec, OperationType, Visibility,
|
||||
@@ -123,14 +123,23 @@ fn build_bundles(
|
||||
});
|
||||
}
|
||||
|
||||
let handler = make_forwarding_handler(
|
||||
let kind = match spec.op_type {
|
||||
OperationType::Subscription => HandlerKind::Stream(make_streaming_forwarding_handler(
|
||||
Arc::new(op_summary.connection.clone()),
|
||||
remote_name,
|
||||
op_summary.credentials_auth_token.clone(),
|
||||
);
|
||||
)),
|
||||
OperationType::Query | OperationType::Mutation => {
|
||||
HandlerKind::Once(make_forwarding_handler(
|
||||
Arc::new(op_summary.connection.clone()),
|
||||
remote_name,
|
||||
op_summary.credentials_auth_token.clone(),
|
||||
))
|
||||
}
|
||||
};
|
||||
bundles.push(HandlerRegistration::new(
|
||||
spec,
|
||||
HandlerKind::Once(handler),
|
||||
kind,
|
||||
OperationProvenance::FromCall,
|
||||
None,
|
||||
None,
|
||||
@@ -311,8 +320,10 @@ fn parse_access_control(v: &Value) -> AccessControl {
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct a forwarding handler for a `FromCall` leaf: on invocation, calls
|
||||
/// the remote op via the `CallConnection` and returns its `ResponseEnvelope`.
|
||||
/// Construct a forwarding handler for a `FromCall` `Query`/`Mutation` leaf:
|
||||
/// on invocation, calls the remote op via the `CallConnection` and returns
|
||||
/// its `ResponseEnvelope` (single `call_with_payload()`, `HandlerKind::Once`).
|
||||
/// `Subscription` ops use [`make_streaming_forwarding_handler`] instead.
|
||||
///
|
||||
/// Per ADR-032 §3, the handler populates `forwarded_for` on the
|
||||
/// `call.requested` payload from the hub's `OperationContext.identity` (the
|
||||
@@ -325,12 +336,6 @@ fn parse_access_control(v: &Value) -> AccessControl {
|
||||
/// If `context.identity` is `None` (the hub chose not to disclose, or has not
|
||||
/// authenticated an originator), `forwarded_for` is omitted — the spoke
|
||||
/// receives only the hub's identity.
|
||||
///
|
||||
/// For a `Subscription` op, the handler calls `subscribe` and streams until
|
||||
/// `completed`/`aborted` (the streaming path is exercised at the
|
||||
/// `CallConnection` layer; the handler here forwards the first response for
|
||||
/// query/mutation and delegates streaming to the caller via the returned
|
||||
/// envelope).
|
||||
fn make_forwarding_handler(
|
||||
connection: Arc<CallConnection>,
|
||||
remote_name: String,
|
||||
@@ -359,6 +364,40 @@ fn make_forwarding_handler(
|
||||
})
|
||||
}
|
||||
|
||||
/// Construct a streaming forwarding handler for a `FromCall` `Subscription`
|
||||
/// leaf: on invocation, calls `CallConnection::subscribe_with_payload()` and
|
||||
/// forwards the remote stream end-to-end. Each `call.responded` from the
|
||||
/// remote becomes a stream item, `call.completed` ends the stream, and
|
||||
/// `call.aborted` drops it (ADR-049 §8). No truncation, no first-value
|
||||
/// fallback.
|
||||
///
|
||||
/// `forwarded_for` is populated from `context.identity` (ADR-032 §3) and
|
||||
/// `auth_token` from the hub's own call-protocol token, exactly as the
|
||||
/// request/response forwarding handler does — both via `build_forwarded_payload`
|
||||
/// (no new payload-construction code). The `subscribe_with_payload` path
|
||||
/// registers the request in `PendingRequestMap`, so the abort cascade
|
||||
/// (ADR-016 §6) is already wired: a parent abort drops the
|
||||
/// `SubscriptionStream`, which sends `call.aborted` to the remote node.
|
||||
fn make_streaming_forwarding_handler(
|
||||
connection: Arc<CallConnection>,
|
||||
remote_name: String,
|
||||
credentials_auth_token: Option<String>,
|
||||
) -> StreamingHandler {
|
||||
use crate::registry::registration::make_streaming_handler;
|
||||
use futures::stream::{once, StreamExt};
|
||||
make_streaming_handler(move |input, context| {
|
||||
let connection = Arc::clone(&connection);
|
||||
let remote_name = remote_name.clone();
|
||||
let auth_token = credentials_auth_token.clone();
|
||||
once(async move {
|
||||
let payload =
|
||||
build_forwarded_payload(&remote_name, input, &context, auth_token.as_deref());
|
||||
connection.subscribe_with_payload(payload).await
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
}
|
||||
|
||||
/// Build the `call.requested` payload for a forwarded call, populating
|
||||
/// `forwarded_for` from the hub's `OperationContext.identity` (ADR-032 §3).
|
||||
/// `forwarded_for` is omitted when `context.identity` is `None` (the hub
|
||||
@@ -391,7 +430,7 @@ fn build_forwarded_payload(
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::protocol::connection::CallConnection;
|
||||
use crate::registry::registration::make_handler;
|
||||
use crate::registry::registration::{make_handler, make_streaming_handler};
|
||||
use crate::registry::spec::OperationType;
|
||||
use alknet_core::auth::Identity;
|
||||
use alknet_core::types::{Capabilities, MockConnection};
|
||||
@@ -724,6 +763,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn op_summary_typed(name: &str, op_type: &str, conn: &CallConnection) -> OpSummary {
|
||||
OpSummary {
|
||||
name: name.to_string(),
|
||||
schema: sample_schema_json(name, op_type),
|
||||
connection: conn.clone(),
|
||||
credentials_auth_token: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_bundles_same_peer_collision_returns_same_peer_collision_error() {
|
||||
let conn = CallConnection::new(stub_connection());
|
||||
@@ -824,4 +872,234 @@ mod tests {
|
||||
assert_eq!(bundles.len(), 1);
|
||||
assert_eq!(bundles[0].spec.name, "worker/exec");
|
||||
}
|
||||
|
||||
// --- ADR-049 §8: streaming forwarding for Subscription ops -------------
|
||||
|
||||
#[test]
|
||||
fn build_bundles_subscription_op_produces_stream_kind() {
|
||||
let conn = CallConnection::new(stub_connection());
|
||||
let discovered = vec![op_summary_typed("events/stream", "subscription", &conn)];
|
||||
let bundles = build_bundles(discovered, &None, &None).expect("bundles");
|
||||
assert_eq!(bundles.len(), 1);
|
||||
assert_eq!(bundles[0].spec.op_type, OperationType::Subscription);
|
||||
assert!(
|
||||
matches!(bundles[0].handler, HandlerKind::Stream(_)),
|
||||
"Subscription op must register HandlerKind::Stream"
|
||||
);
|
||||
assert_eq!(bundles[0].provenance, OperationProvenance::FromCall);
|
||||
assert!(bundles[0].composition_authority.is_none());
|
||||
assert!(bundles[0].scoped_env.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_bundles_query_op_produces_once_kind() {
|
||||
let conn = CallConnection::new(stub_connection());
|
||||
let discovered = vec![op_summary_typed("fs/readFile", "query", &conn)];
|
||||
let bundles = build_bundles(discovered, &None, &None).expect("bundles");
|
||||
assert_eq!(bundles.len(), 1);
|
||||
assert_eq!(bundles[0].spec.op_type, OperationType::Query);
|
||||
assert!(
|
||||
matches!(bundles[0].handler, HandlerKind::Once(_)),
|
||||
"Query op must register HandlerKind::Once"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_bundles_mutation_op_produces_once_kind() {
|
||||
let conn = CallConnection::new(stub_connection());
|
||||
let discovered = vec![op_summary_typed("fs/writeFile", "mutation", &conn)];
|
||||
let bundles = build_bundles(discovered, &None, &None).expect("bundles");
|
||||
assert_eq!(bundles.len(), 1);
|
||||
assert_eq!(bundles[0].spec.op_type, OperationType::Mutation);
|
||||
assert!(
|
||||
matches!(bundles[0].handler, HandlerKind::Once(_)),
|
||||
"Mutation op must register HandlerKind::Once"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_bundles_mixed_op_types_route_to_correct_kind() {
|
||||
let conn = CallConnection::new(stub_connection());
|
||||
let discovered = vec![
|
||||
op_summary_typed("fs/readFile", "query", &conn),
|
||||
op_summary_typed("fs/writeFile", "mutation", &conn),
|
||||
op_summary_typed("events/stream", "subscription", &conn),
|
||||
];
|
||||
let bundles = build_bundles(discovered, &None, &None).expect("bundles");
|
||||
assert_eq!(bundles.len(), 3);
|
||||
let by_name: std::collections::HashMap<&str, &HandlerKind> = bundles
|
||||
.iter()
|
||||
.map(|b| (b.spec.name.as_str(), &b.handler))
|
||||
.collect();
|
||||
assert!(matches!(by_name["fs/readFile"], HandlerKind::Once(_)));
|
||||
assert!(matches!(by_name["fs/writeFile"], HandlerKind::Once(_)));
|
||||
assert!(matches!(by_name["events/stream"], HandlerKind::Stream(_)));
|
||||
}
|
||||
|
||||
/// Verify `make_streaming_forwarding_handler` produces a `StreamingHandler`
|
||||
/// that builds the forwarded payload with `forwarded_for` populated from
|
||||
/// `context.identity` (ADR-032) and calls `subscribe_with_payload`. Since
|
||||
/// `subscribe_with_payload` on a mock connection returns a closed stream
|
||||
/// (no transport), we capture the payload by intercepting the build step:
|
||||
/// the handler's contract is "build payload via `build_forwarded_payload`,
|
||||
/// then call `subscribe_with_payload(payload)`". We mirror the existing
|
||||
/// `forwarding_handler_populates_forwarded_for` test by constructing the
|
||||
/// handler and exercising the payload-construction path it relies on, plus
|
||||
/// asserting the produced stream terminates (the mock-connection path
|
||||
/// yields one error envelope then ends — no truncation, no hang).
|
||||
#[tokio::test]
|
||||
async fn streaming_forwarding_handler_populates_forwarded_for_and_streams() {
|
||||
use futures::stream::StreamExt;
|
||||
|
||||
let conn = Arc::new(CallConnection::new(stub_connection()));
|
||||
let captured_payload = Arc::new(StdMutex::new(None::<Value>));
|
||||
let captured = Arc::clone(&captured_payload);
|
||||
|
||||
let handler: StreamingHandler = {
|
||||
let conn = Arc::clone(&conn);
|
||||
make_streaming_handler(move |input, context| {
|
||||
let conn = Arc::clone(&conn);
|
||||
let captured = Arc::clone(&captured);
|
||||
let remote_name = "events/stream".to_string();
|
||||
use futures::stream::{once, StreamExt};
|
||||
once(async move {
|
||||
let payload = build_forwarded_payload(&remote_name, input, &context, None);
|
||||
*captured.lock().unwrap() = Some(payload.clone());
|
||||
conn.subscribe_with_payload(payload).await
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
};
|
||||
|
||||
let ctx = test_context(Some(alice_identity()));
|
||||
let mut stream = handler(json!({}), ctx);
|
||||
let first = stream.next().await;
|
||||
assert!(
|
||||
first.is_some(),
|
||||
"streaming forwarding handler must produce at least one envelope"
|
||||
);
|
||||
if let Some(env) = first {
|
||||
assert!(
|
||||
env.result.is_err(),
|
||||
"mock connection has no transport, so the stream yields an error envelope"
|
||||
);
|
||||
}
|
||||
let second = stream.next().await;
|
||||
assert!(
|
||||
second.is_none(),
|
||||
"stream must terminate after the error (no truncation, no hang)"
|
||||
);
|
||||
|
||||
let payload = captured_payload.lock().unwrap().clone().expect("captured");
|
||||
assert_eq!(payload["operationId"], "events/stream");
|
||||
assert_eq!(payload["forwarded_for"]["id"], "alice");
|
||||
}
|
||||
|
||||
/// The streaming forwarding handler omits `forwarded_for` when
|
||||
/// `context.identity` is `None`, mirroring the request/response handler.
|
||||
#[tokio::test]
|
||||
async fn streaming_forwarding_handler_omits_forwarded_for_when_identity_none() {
|
||||
use futures::stream::StreamExt;
|
||||
|
||||
let conn = Arc::new(CallConnection::new(stub_connection()));
|
||||
let captured_payload = Arc::new(StdMutex::new(None::<Value>));
|
||||
let captured = Arc::clone(&captured_payload);
|
||||
|
||||
let handler: StreamingHandler = {
|
||||
let conn = Arc::clone(&conn);
|
||||
make_streaming_handler(move |input, context| {
|
||||
let conn = Arc::clone(&conn);
|
||||
let captured = Arc::clone(&captured);
|
||||
let remote_name = "events/stream".to_string();
|
||||
use futures::stream::{once, StreamExt};
|
||||
once(async move {
|
||||
let payload = build_forwarded_payload(&remote_name, input, &context, None);
|
||||
*captured.lock().unwrap() = Some(payload.clone());
|
||||
conn.subscribe_with_payload(payload).await
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
};
|
||||
|
||||
let ctx = test_context(None);
|
||||
let mut stream = handler(json!({}), ctx);
|
||||
let _ = stream.next().await;
|
||||
let payload = captured_payload.lock().unwrap().clone().expect("captured");
|
||||
assert!(
|
||||
payload.get("forwarded_for").is_none(),
|
||||
"forwarded_for must be omitted when context.identity is None"
|
||||
);
|
||||
assert_eq!(payload["operationId"], "events/stream");
|
||||
}
|
||||
|
||||
/// The streaming forwarding handler populates `auth_token` when the hub's
|
||||
/// own call-protocol token is provided.
|
||||
#[tokio::test]
|
||||
async fn streaming_forwarding_handler_sets_auth_token_when_provided() {
|
||||
use futures::stream::StreamExt;
|
||||
|
||||
let conn = Arc::new(CallConnection::new(stub_connection()));
|
||||
let captured_payload = Arc::new(StdMutex::new(None::<Value>));
|
||||
let captured = Arc::clone(&captured_payload);
|
||||
|
||||
let handler: StreamingHandler = {
|
||||
let conn = Arc::clone(&conn);
|
||||
make_streaming_handler(move |input, context| {
|
||||
let conn = Arc::clone(&conn);
|
||||
let captured = Arc::clone(&captured);
|
||||
let remote_name = "events/stream".to_string();
|
||||
use futures::stream::{once, StreamExt};
|
||||
once(async move {
|
||||
let payload = build_forwarded_payload(
|
||||
&remote_name,
|
||||
input,
|
||||
&context,
|
||||
Some("alk_hub_token"),
|
||||
);
|
||||
*captured.lock().unwrap() = Some(payload.clone());
|
||||
conn.subscribe_with_payload(payload).await
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
};
|
||||
|
||||
let ctx = test_context(Some(alice_identity()));
|
||||
let mut stream = handler(json!({}), ctx);
|
||||
let _ = stream.next().await;
|
||||
let payload = captured_payload.lock().unwrap().clone().expect("captured");
|
||||
assert_eq!(payload["auth_token"], "alk_hub_token");
|
||||
assert_eq!(payload["forwarded_for"]["id"], "alice");
|
||||
}
|
||||
|
||||
/// `make_streaming_forwarding_handler` produces a `StreamingHandler` (not a
|
||||
/// `Handler`) — verifies the helper returns the right type and that
|
||||
/// `build_bundles` wires it into `HandlerKind::Stream`.
|
||||
#[test]
|
||||
fn make_streaming_forwarding_handler_returns_streaming_handler() {
|
||||
let handler = make_streaming_forwarding_handler(
|
||||
Arc::new(CallConnection::new(stub_connection())),
|
||||
"events/stream".to_string(),
|
||||
None,
|
||||
);
|
||||
let reg = HandlerRegistration::new(
|
||||
OperationSpec::new(
|
||||
"events/stream",
|
||||
OperationType::Subscription,
|
||||
Visibility::External,
|
||||
json!({}),
|
||||
json!({}),
|
||||
vec![],
|
||||
AccessControl::default(),
|
||||
),
|
||||
HandlerKind::Stream(handler),
|
||||
OperationProvenance::FromCall,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
);
|
||||
assert!(matches!(reg.handler, HandlerKind::Stream(_)));
|
||||
assert_eq!(reg.provenance, OperationProvenance::FromCall);
|
||||
assert!(reg.composition_authority.is_none());
|
||||
assert!(reg.scoped_env.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,11 +168,26 @@ impl CallConnection {
|
||||
operation_id: &str,
|
||||
input: Value,
|
||||
) -> impl Stream<Item = ResponseEnvelope> {
|
||||
let request_id = generate_request_id();
|
||||
let payload = serde_json::json!({
|
||||
"operationId": operation_id,
|
||||
"input": input,
|
||||
});
|
||||
self.subscribe_with_payload(payload).await
|
||||
}
|
||||
|
||||
/// Subscribe to a remote op with a caller-constructed `call.requested`
|
||||
/// payload. The payload MUST include `operationId` and `input`; the
|
||||
/// caller may add `forwarded_for` (ADR-032) and `auth_token` (ADR-017 §7)
|
||||
/// for the hub forwarding path used by `from_call`'s streaming forwarding
|
||||
/// handler. Mirrors [`call_with_payload`](Self::call_with_payload) so the
|
||||
/// forwarding handler can populate `forwarded_for` + `auth_token` on the
|
||||
/// subscription payload (the plain [`subscribe`](Self::subscribe) builds
|
||||
/// the payload internally and omits those fields).
|
||||
pub async fn subscribe_with_payload(
|
||||
&self,
|
||||
payload: Value,
|
||||
) -> impl Stream<Item = ResponseEnvelope> {
|
||||
let request_id = generate_request_id();
|
||||
|
||||
let connection = match &self.connection {
|
||||
Some(c) => c,
|
||||
|
||||
@@ -17,6 +17,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use alknet_core::auth::{AuthToken, Identity, IdentityProvider};
|
||||
use alknet_core::types::StreamError;
|
||||
use futures::stream::StreamExt;
|
||||
use serde_json::Value;
|
||||
use tokio::task::JoinHandle;
|
||||
use tracing::{debug, warn};
|
||||
@@ -30,11 +31,37 @@ use super::wire::{
|
||||
use crate::protocol::adapter::SessionOverlaySource;
|
||||
use crate::registry::context::{AbortPolicy, OperationContext, ScopedPeerEnv};
|
||||
use crate::registry::env::{LocalOperationEnv, OperationEnv, PeerCompositeEnv};
|
||||
use crate::registry::registration::OperationRegistry;
|
||||
use crate::registry::registration::{OperationRegistry, ResponseStream};
|
||||
use crate::registry::spec::OperationType;
|
||||
|
||||
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const SWEEPER_INTERVAL: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Outcome of dispatching a `call.requested` event. The dispatcher branches on
|
||||
/// the registered operation's `op_type` (ADR-049 §6): `Query`/`Mutation` produce
|
||||
/// a single [`ResponseEnvelope`] (`Once`), `Subscription` produces a
|
||||
/// [`ResponseStream`] (`Stream`) that `handle_stream` pumps to the wire.
|
||||
///
|
||||
/// This enum is the branch point the spec describes ("branches on `op_type` in
|
||||
/// `handle_stream`"): `dispatch` returns it and `handle_stream` matches on it,
|
||||
/// keeping the Once path (one frame, no `call.completed`) and the Stream path
|
||||
/// (each envelope → frame, `call.completed` on natural end) visibly distinct.
|
||||
pub enum DispatchResult {
|
||||
Once(ResponseEnvelope),
|
||||
Stream(ResponseStream),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DispatchResult {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
DispatchResult::Once(env) => f.debug_tuple("Once").field(env).finish(),
|
||||
DispatchResult::Stream(_) => {
|
||||
f.debug_tuple("Stream").field(&"<ResponseStream>").finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared dispatcher for an established `CallConnection`. Constructed by
|
||||
/// both `CallAdapter` (accept path) and `CallClient` (connect path) and used
|
||||
/// to run the dispatch loop. Holds no per-connection state; the
|
||||
@@ -166,6 +193,36 @@ impl Dispatcher {
|
||||
request_id: String,
|
||||
payload: Value,
|
||||
) -> ResponseEnvelope {
|
||||
match self.dispatch(connection, request_id, payload).await {
|
||||
DispatchResult::Once(envelope) => envelope,
|
||||
DispatchResult::Stream(mut stream) => stream.next().await.unwrap_or_else(|| {
|
||||
ResponseEnvelope::error(
|
||||
String::new(),
|
||||
CallError::internal(
|
||||
"dispatch_requested called on a Subscription op; use the streaming path",
|
||||
),
|
||||
)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Dispatch a `call.requested` event, branching on the registered
|
||||
/// operation's `op_type` (ADR-049 §6). `Query`/`Mutation` → `invoke()` →
|
||||
/// [`DispatchResult::Once`]; `Subscription` → `invoke_streaming()` →
|
||||
/// [`DispatchResult::Stream`]. Unknown ops and ACL failures resolve via
|
||||
/// the registry's own envelope/error paths (Once for `invoke`, a single
|
||||
/// error envelope for `invoke_streaming`).
|
||||
///
|
||||
/// For the streaming branch the root context's deadline is cleared
|
||||
/// (`deadline: None`): subscriptions are long-running and unbounded — the
|
||||
/// 30s request/response deadline does not apply (ADR-049 §6, call-protocol
|
||||
/// Timeouts). The Once branch keeps the deadline from `build_root_context`.
|
||||
pub async fn dispatch(
|
||||
&self,
|
||||
connection: &Arc<CallConnection>,
|
||||
request_id: String,
|
||||
payload: Value,
|
||||
) -> DispatchResult {
|
||||
let operation_id = payload
|
||||
.get("operationId")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -180,7 +237,13 @@ impl Dispatcher {
|
||||
|
||||
let input = payload.get("input").cloned().unwrap_or(Value::Null);
|
||||
|
||||
let context = self.build_root_context(
|
||||
let is_subscription = self
|
||||
.registry
|
||||
.registration(&operation_name)
|
||||
.map(|r| r.spec.op_type == OperationType::Subscription)
|
||||
.unwrap_or(false);
|
||||
|
||||
let mut context = self.build_root_context(
|
||||
request_id.clone(),
|
||||
&operation_name,
|
||||
identity,
|
||||
@@ -188,7 +251,16 @@ impl Dispatcher {
|
||||
connection,
|
||||
);
|
||||
|
||||
self.registry.invoke(&operation_name, input, context).await
|
||||
if is_subscription {
|
||||
context.deadline = None;
|
||||
let stream = self
|
||||
.registry
|
||||
.invoke_streaming(&operation_name, input, context);
|
||||
DispatchResult::Stream(stream)
|
||||
} else {
|
||||
let envelope = self.registry.invoke(&operation_name, input, context).await;
|
||||
DispatchResult::Once(envelope)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle_abort(&self, connection: &Arc<CallConnection>, request_id: &str) {
|
||||
@@ -225,16 +297,22 @@ impl Dispatcher {
|
||||
let request_id = envelope.id.clone();
|
||||
let payload = envelope.payload.clone();
|
||||
|
||||
let response = self
|
||||
.dispatch_requested(&connection, request_id.clone(), payload)
|
||||
.await;
|
||||
|
||||
match self
|
||||
.dispatch(&connection, request_id.clone(), payload)
|
||||
.await
|
||||
{
|
||||
DispatchResult::Once(response) => {
|
||||
let event: EventEnvelope = response.into();
|
||||
if let Err(err) = writer.write_frame(&event).await {
|
||||
warn!(error = %err, "failed to write response frame; closing stream");
|
||||
break;
|
||||
}
|
||||
}
|
||||
DispatchResult::Stream(stream) => {
|
||||
self.pump_stream(&mut writer, &request_id, stream).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
EVENT_ABORTED => {
|
||||
let request_id = envelope.id.clone();
|
||||
self.handle_abort(&connection, &request_id).await;
|
||||
@@ -246,6 +324,43 @@ impl Dispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
/// Pump a subscription's [`ResponseStream`] to the wire: each
|
||||
/// [`ResponseEnvelope`] becomes an [`EventEnvelope`] frame (`call.responded`
|
||||
/// for `Ok`, `call.error` for `Err`). On natural stream end (the stream
|
||||
/// returned `None` without the last item being an `Err`), write a
|
||||
/// `call.completed` frame. An `Err` envelope is terminal — the stream
|
||||
/// ends after it and we do NOT write `call.completed` (ADR-049 §6).
|
||||
///
|
||||
/// If a frame write fails the pump stops early; the stream is dropped on
|
||||
/// return, releasing the handler's resources via `Drop` (ADR-016). The
|
||||
/// pump is cancellable: it runs inside the `handle_stream` task, so a
|
||||
/// `call.aborted` for this request ID (handled by `handle_abort` on
|
||||
/// another stream) or connection close cancels the task and drops the
|
||||
/// stream.
|
||||
pub(crate) async fn pump_stream<W: tokio::io::AsyncWrite + Unpin>(
|
||||
&self,
|
||||
writer: &mut super::wire::FrameFramedWriter<W>,
|
||||
request_id: &str,
|
||||
mut stream: ResponseStream,
|
||||
) {
|
||||
let mut last_was_error = false;
|
||||
while let Some(envelope) = stream.next().await {
|
||||
last_was_error = envelope.result.is_err();
|
||||
let event: EventEnvelope = envelope.into();
|
||||
if let Err(err) = writer.write_frame(&event).await {
|
||||
warn!(error = %err, "failed to write streaming frame; closing stream");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if !last_was_error {
|
||||
let completed = EventEnvelope::completed(request_id);
|
||||
if let Err(err) = writer.write_frame(&completed).await {
|
||||
warn!(error = %err, "failed to write call.completed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the shared dispatch loop over an established `CallConnection`:
|
||||
/// spawn the pending-entry sweeper, accept bidirectional streams until the
|
||||
/// connection closes, dispatch each stream via `handle_stream`, and fail
|
||||
@@ -325,9 +440,9 @@ impl Clone for Dispatcher {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::protocol::wire::EVENT_RESPONDED;
|
||||
use crate::protocol::wire::{EVENT_COMPLETED, EVENT_ERROR, EVENT_RESPONDED};
|
||||
use crate::registry::registration::{
|
||||
make_handler, HandlerKind, HandlerRegistration, OperationProvenance,
|
||||
make_handler, make_streaming_handler, HandlerKind, HandlerRegistration, OperationProvenance,
|
||||
};
|
||||
use crate::registry::spec::{AccessControl, OperationSpec, OperationType, Visibility};
|
||||
use alknet_core::auth::{AuthToken, Identity, IdentityProvider};
|
||||
@@ -874,4 +989,388 @@ mod tests {
|
||||
Some(&serde_json::json!({ "v": 42 }))
|
||||
);
|
||||
}
|
||||
|
||||
// --- streaming dispatch branch (ADR-049 §6) ---------------------------
|
||||
|
||||
fn subscription_spec(name: &str, acl: AccessControl) -> OperationSpec {
|
||||
OperationSpec::new(
|
||||
name,
|
||||
OperationType::Subscription,
|
||||
Visibility::External,
|
||||
serde_json::json!({}),
|
||||
serde_json::json!({}),
|
||||
vec![],
|
||||
acl,
|
||||
)
|
||||
}
|
||||
|
||||
fn encode_frame(envelope: &EventEnvelope) -> Vec<u8> {
|
||||
let body = serde_json::to_vec(envelope).expect("serialize envelope");
|
||||
let mut buf = (body.len() as u32).to_be_bytes().to_vec();
|
||||
buf.extend_from_slice(&body);
|
||||
buf
|
||||
}
|
||||
|
||||
async fn read_all_frames(
|
||||
reader: &mut (impl tokio::io::AsyncRead + Unpin),
|
||||
) -> Vec<EventEnvelope> {
|
||||
let mut buf = Vec::new();
|
||||
use tokio::io::AsyncReadExt;
|
||||
let _ = reader.read_to_end(&mut buf).await;
|
||||
let mut frames = Vec::new();
|
||||
let mut cursor = std::io::Cursor::new(buf);
|
||||
loop {
|
||||
let mut len_buf = [0u8; 4];
|
||||
match tokio::io::AsyncReadExt::read_exact(&mut cursor, &mut len_buf).await {
|
||||
Ok(_) => {}
|
||||
Err(_) => break,
|
||||
}
|
||||
let len = u32::from_be_bytes(len_buf) as usize;
|
||||
let mut body = vec![0u8; len];
|
||||
if tokio::io::AsyncReadExt::read_exact(&mut cursor, &mut body)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
let envelope: EventEnvelope =
|
||||
serde_json::from_slice(&body).expect("deserialize written frame");
|
||||
frames.push(envelope);
|
||||
}
|
||||
frames
|
||||
}
|
||||
|
||||
fn registry_with_subscription(
|
||||
name: &str,
|
||||
handler: crate::registry::registration::StreamingHandler,
|
||||
) -> Arc<OperationRegistry> {
|
||||
let mut registry = OperationRegistry::new();
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
subscription_spec(name, AccessControl::default()),
|
||||
HandlerKind::Stream(handler),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
Arc::new(registry)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_subscription_returns_stream_result() {
|
||||
let handler = make_streaming_handler(|input, ctx| {
|
||||
futures::stream::iter(vec![
|
||||
ResponseEnvelope::ok(ctx.request_id.clone(), input.clone()),
|
||||
ResponseEnvelope::ok(ctx.request_id.clone(), serde_json::json!({"done": true})),
|
||||
])
|
||||
});
|
||||
let registry = registry_with_subscription("events/stream", handler);
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = Dispatcher::new(registry, provider);
|
||||
let conn = Arc::new(CallConnection::new(stub_connection()));
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"operationId": "/events/stream",
|
||||
"input": { "v": 1 },
|
||||
});
|
||||
match dp.dispatch(&conn, "sub-1".to_string(), payload).await {
|
||||
DispatchResult::Stream(mut stream) => {
|
||||
use futures::stream::StreamExt;
|
||||
let first = stream.next().await.expect("first envelope");
|
||||
assert_eq!(first.request_id, "sub-1");
|
||||
assert_eq!(first.result, Ok(serde_json::json!({ "v": 1 })));
|
||||
let second = stream.next().await.expect("second envelope");
|
||||
assert_eq!(second.result, Ok(serde_json::json!({ "done": true })));
|
||||
assert!(
|
||||
stream.next().await.is_none(),
|
||||
"stream ends after two values"
|
||||
);
|
||||
}
|
||||
other => panic!("expected Stream, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_subscription_clears_deadline_to_none() {
|
||||
let handler = make_streaming_handler(|_input, ctx| {
|
||||
let deadline = ctx.deadline;
|
||||
futures::stream::iter(vec![ResponseEnvelope::ok(
|
||||
ctx.request_id.clone(),
|
||||
serde_json::json!({ "deadline_is_none": deadline.is_none() }),
|
||||
)])
|
||||
});
|
||||
let registry = registry_with_subscription("events/stream", handler);
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = Dispatcher::new(registry, provider);
|
||||
let conn = Arc::new(CallConnection::new(stub_connection()));
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"operationId": "/events/stream",
|
||||
"input": {},
|
||||
});
|
||||
match dp.dispatch(&conn, "sub-dl".to_string(), payload).await {
|
||||
DispatchResult::Stream(mut stream) => {
|
||||
use futures::stream::StreamExt;
|
||||
let env = stream.next().await.expect("one envelope");
|
||||
let out = env.result.expect("ok");
|
||||
assert_eq!(out["deadline_is_none"], Value::Bool(true));
|
||||
}
|
||||
other => panic!("expected Stream, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_query_keeps_deadline_some() {
|
||||
let mut registry = OperationRegistry::new();
|
||||
let handler = make_handler(|_input, ctx| async move {
|
||||
let deadline_is_some = ctx.deadline.is_some();
|
||||
ResponseEnvelope::ok(
|
||||
ctx.request_id.clone(),
|
||||
serde_json::json!({ "deadline_is_some": deadline_is_some }),
|
||||
)
|
||||
});
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
external_spec("echo/run", AccessControl::default()),
|
||||
HandlerKind::Once(handler),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
let registry = Arc::new(registry);
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = Dispatcher::new(registry, provider);
|
||||
let conn = Arc::new(CallConnection::new(stub_connection()));
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"operationId": "/echo/run",
|
||||
"input": {},
|
||||
});
|
||||
match dp.dispatch(&conn, "q-1".to_string(), payload).await {
|
||||
DispatchResult::Once(env) => {
|
||||
let out = env.result.expect("ok");
|
||||
assert_eq!(out["deadline_is_some"], Value::Bool(true));
|
||||
}
|
||||
other => panic!("expected Once, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn handle_stream_subscription_pumps_each_frame_then_completed() {
|
||||
let handler = make_streaming_handler(|input, ctx| {
|
||||
let first = input.clone();
|
||||
let rid = ctx.request_id.clone();
|
||||
futures::stream::iter(vec![
|
||||
ResponseEnvelope::ok(rid.clone(), first),
|
||||
ResponseEnvelope::ok(rid.clone(), serde_json::json!({"n": 2})),
|
||||
ResponseEnvelope::ok(rid, serde_json::json!({"n": 3})),
|
||||
])
|
||||
});
|
||||
let registry = registry_with_subscription("events/stream", handler);
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = Dispatcher::new(registry, provider);
|
||||
let conn = Arc::new(CallConnection::new(stub_connection()));
|
||||
|
||||
let request = EventEnvelope::requested(
|
||||
"sub-pump-1",
|
||||
serde_json::json!({
|
||||
"operationId": "/events/stream",
|
||||
"input": { "n": 1 },
|
||||
}),
|
||||
);
|
||||
let recv = tokio::io::BufReader::new(std::io::Cursor::new(encode_frame(&request)));
|
||||
let (send, mut sink) = tokio::io::duplex(8 * 1024);
|
||||
let send = alknet_core::types::SendStream::from_mock(send);
|
||||
let recv = alknet_core::types::RecvStream::from_mock(recv);
|
||||
|
||||
dp.handle_stream(conn, send, recv).await;
|
||||
|
||||
let frames = read_all_frames(&mut sink).await;
|
||||
assert_eq!(frames.len(), 4, "3 responded + 1 completed");
|
||||
for (i, f) in frames[..3].iter().enumerate() {
|
||||
assert_eq!(f.r#type, EVENT_RESPONDED, "frame {i} is call.responded");
|
||||
assert_eq!(f.id, "sub-pump-1");
|
||||
}
|
||||
assert_eq!(frames[3].r#type, EVENT_COMPLETED);
|
||||
assert_eq!(frames[3].id, "sub-pump-1");
|
||||
assert_eq!(frames[3].payload, serde_json::json!({}));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn handle_stream_subscription_error_is_terminal_no_completed() {
|
||||
let handler = make_streaming_handler(|_input, ctx| {
|
||||
let rid = ctx.request_id.clone();
|
||||
futures::stream::iter(vec![
|
||||
ResponseEnvelope::ok(rid.clone(), serde_json::json!({"ok": true})),
|
||||
ResponseEnvelope::error(rid.clone(), CallError::internal("boom")),
|
||||
])
|
||||
});
|
||||
let registry = registry_with_subscription("events/stream", handler);
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = Dispatcher::new(registry, provider);
|
||||
let conn = Arc::new(CallConnection::new(stub_connection()));
|
||||
|
||||
let request = EventEnvelope::requested(
|
||||
"sub-err-1",
|
||||
serde_json::json!({
|
||||
"operationId": "/events/stream",
|
||||
"input": {},
|
||||
}),
|
||||
);
|
||||
let recv = tokio::io::BufReader::new(std::io::Cursor::new(encode_frame(&request)));
|
||||
let (send, mut sink) = tokio::io::duplex(8 * 1024);
|
||||
let send = alknet_core::types::SendStream::from_mock(send);
|
||||
let recv = alknet_core::types::RecvStream::from_mock(recv);
|
||||
|
||||
dp.handle_stream(conn, send, recv).await;
|
||||
|
||||
let frames = read_all_frames(&mut sink).await;
|
||||
assert_eq!(frames.len(), 2, "1 responded + 1 error, no completed");
|
||||
assert_eq!(frames[0].r#type, EVENT_RESPONDED);
|
||||
assert_eq!(frames[1].r#type, EVENT_ERROR);
|
||||
assert_eq!(frames[1].id, "sub-err-1");
|
||||
assert_eq!(
|
||||
frames[1].payload.get("code"),
|
||||
Some(&Value::String("INTERNAL".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn handle_stream_query_dispatch_unchanged_one_frame_no_completed() {
|
||||
let registry = Arc::new(registry_with(
|
||||
"echo/run",
|
||||
Visibility::External,
|
||||
AccessControl::default(),
|
||||
));
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = Dispatcher::new(registry, provider);
|
||||
let conn = Arc::new(CallConnection::new(stub_connection()));
|
||||
|
||||
let request = EventEnvelope::requested(
|
||||
"q-pump-1",
|
||||
serde_json::json!({
|
||||
"operationId": "/echo/run",
|
||||
"input": { "msg": "hi" },
|
||||
}),
|
||||
);
|
||||
let recv = tokio::io::BufReader::new(std::io::Cursor::new(encode_frame(&request)));
|
||||
let (send, mut sink) = tokio::io::duplex(8 * 1024);
|
||||
let send = alknet_core::types::SendStream::from_mock(send);
|
||||
let recv = alknet_core::types::RecvStream::from_mock(recv);
|
||||
|
||||
dp.handle_stream(conn, send, recv).await;
|
||||
|
||||
let frames = read_all_frames(&mut sink).await;
|
||||
assert_eq!(frames.len(), 1, "query: exactly one frame, no completed");
|
||||
assert_eq!(frames[0].r#type, EVENT_RESPONDED);
|
||||
assert_eq!(frames[0].id, "q-pump-1");
|
||||
assert_eq!(
|
||||
frames[0].payload.get("output"),
|
||||
Some(&serde_json::json!({ "msg": "hi" }))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn handle_stream_subscription_unknown_op_yields_single_error_no_completed() {
|
||||
let registry = Arc::new(OperationRegistry::new());
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = Dispatcher::new(registry, provider);
|
||||
let conn = Arc::new(CallConnection::new(stub_connection()));
|
||||
|
||||
let request = EventEnvelope::requested(
|
||||
"sub-missing-1",
|
||||
serde_json::json!({
|
||||
"operationId": "/no/such/stream",
|
||||
"input": {},
|
||||
}),
|
||||
);
|
||||
let recv = tokio::io::BufReader::new(std::io::Cursor::new(encode_frame(&request)));
|
||||
let (send, mut sink) = tokio::io::duplex(8 * 1024);
|
||||
let send = alknet_core::types::SendStream::from_mock(send);
|
||||
let recv = alknet_core::types::RecvStream::from_mock(recv);
|
||||
|
||||
dp.handle_stream(conn, send, recv).await;
|
||||
|
||||
let frames = read_all_frames(&mut sink).await;
|
||||
assert_eq!(frames.len(), 1, "unknown op: single error, no completed");
|
||||
assert_eq!(frames[0].r#type, EVENT_ERROR);
|
||||
assert_eq!(frames[0].id, "sub-missing-1");
|
||||
assert_eq!(
|
||||
frames[0].payload.get("code"),
|
||||
Some(&Value::String("NOT_FOUND".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn handle_stream_aborted_for_streaming_request_drops_stream() {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc as StdArc;
|
||||
|
||||
let dropped = StdArc::new(AtomicBool::new(false));
|
||||
let dropped_clone = StdArc::clone(&dropped);
|
||||
let handler = make_streaming_handler(move |_input, ctx| {
|
||||
let rid = ctx.request_id.clone();
|
||||
let flag = StdArc::clone(&dropped_clone);
|
||||
struct DropGuard(StdArc<AtomicBool>);
|
||||
impl Drop for DropGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
let guard = DropGuard(StdArc::clone(&flag));
|
||||
futures::stream::poll_fn(move |_cx| {
|
||||
if flag.load(Ordering::SeqCst) {
|
||||
return std::task::Poll::Ready(None);
|
||||
}
|
||||
std::task::Poll::Ready(Some(ResponseEnvelope::ok(
|
||||
rid.clone(),
|
||||
serde_json::json!({"tick": 1}),
|
||||
)))
|
||||
})
|
||||
.map(move |env| {
|
||||
let _keep_guard = &guard;
|
||||
env
|
||||
})
|
||||
});
|
||||
let registry = registry_with_subscription("events/stream", handler);
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = Dispatcher::new(registry, provider);
|
||||
let conn = Arc::new(CallConnection::new(stub_connection()));
|
||||
|
||||
let request = EventEnvelope::requested(
|
||||
"sub-abort-1",
|
||||
serde_json::json!({
|
||||
"operationId": "/events/stream",
|
||||
"input": {},
|
||||
}),
|
||||
);
|
||||
let recv = tokio::io::BufReader::new(std::io::Cursor::new(encode_frame(&request)));
|
||||
let (send, _sink) = tokio::io::duplex(8 * 1024);
|
||||
let send = alknet_core::types::SendStream::from_mock(send);
|
||||
let recv = alknet_core::types::RecvStream::from_mock(recv);
|
||||
|
||||
let conn_clone = Arc::clone(&conn);
|
||||
let dp_clone = dp.clone();
|
||||
let handle = tokio::spawn(async move {
|
||||
dp_clone.handle_stream(conn_clone, send, recv).await;
|
||||
});
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
dp.handle_abort(&conn, "sub-abort-1").await;
|
||||
assert!(
|
||||
!conn.pending().lock().contains("sub-abort-1"),
|
||||
"abort removes the pending entry"
|
||||
);
|
||||
|
||||
handle.abort();
|
||||
let _ = handle.await;
|
||||
assert!(
|
||||
dropped.load(Ordering::SeqCst),
|
||||
"stream future dropped → Drop guard released handler resources"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
use alknet_core::types::Capabilities;
|
||||
use futures::stream::Stream;
|
||||
use futures::stream::{self, Stream};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::context::{CompositionAuthority, OperationContext, ScopedPeerEnv};
|
||||
@@ -156,6 +156,63 @@ impl OperationRegistry {
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn invoke_streaming(
|
||||
&self,
|
||||
name: &str,
|
||||
input: Value,
|
||||
context: OperationContext,
|
||||
) -> ResponseStream {
|
||||
let request_id = context.request_id.clone();
|
||||
let name_owned = name.to_string();
|
||||
|
||||
let registration = match self.operations.get(name) {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
return Box::pin(stream::once(async move {
|
||||
ResponseEnvelope::not_found(request_id, &name_owned)
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
if registration.spec.visibility == Visibility::Internal && !context.internal {
|
||||
return Box::pin(stream::once(async move {
|
||||
ResponseEnvelope::not_found(request_id, &name_owned)
|
||||
}));
|
||||
}
|
||||
|
||||
let acl = ®istration.spec.access_control;
|
||||
let identity = if context.internal {
|
||||
context
|
||||
.handler_identity
|
||||
.as_ref()
|
||||
.and_then(|ca| ca.as_identity())
|
||||
} else {
|
||||
context.identity.clone()
|
||||
};
|
||||
|
||||
if let AccessResult::Forbidden(message) = acl.check(identity.as_ref()) {
|
||||
return Box::pin(stream::once(async move {
|
||||
ResponseEnvelope::forbidden(request_id, message)
|
||||
}));
|
||||
}
|
||||
|
||||
let streaming_handler = match ®istration.handler {
|
||||
HandlerKind::Stream(h) => Arc::clone(h),
|
||||
HandlerKind::Once(_) => {
|
||||
return Box::pin(stream::once(async move {
|
||||
ResponseEnvelope::error(
|
||||
request_id,
|
||||
CallError::invalid_operation_type(
|
||||
"invoke_streaming() called on a Query/Mutation op; use invoke()",
|
||||
),
|
||||
)
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
streaming_handler(input, context)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for OperationRegistry {
|
||||
@@ -1006,4 +1063,189 @@ mod tests {
|
||||
assert!(!err.retryable);
|
||||
assert!(err.details.is_none());
|
||||
}
|
||||
|
||||
async fn collect_stream(mut s: ResponseStream) -> Vec<ResponseEnvelope> {
|
||||
use futures::stream::StreamExt;
|
||||
let mut out = Vec::new();
|
||||
while let Some(env) = s.next().await {
|
||||
out.push(env);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_on_subscription_dispatches_handler_stream() {
|
||||
let mut registry = OperationRegistry::new();
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
subscription_spec("events/stream"),
|
||||
HandlerKind::Stream(echo_streaming_handler()),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
let ctx = root_context("req-is-1", None, None, false, ScopedPeerEnv::empty());
|
||||
let stream = registry.invoke_streaming("events/stream", serde_json::json!({"v": 7}), ctx);
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(items[0].request_id, "req-is-1");
|
||||
assert_eq!(items[0].result, Ok(serde_json::json!({"v": 7})));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_on_unknown_op_yields_single_not_found() {
|
||||
let registry = OperationRegistry::new();
|
||||
let ctx = root_context("req-is-2", None, None, false, ScopedPeerEnv::empty());
|
||||
let stream = registry.invoke_streaming("missing", serde_json::json!({}), ctx);
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
match &items[0].result {
|
||||
Err(e) => {
|
||||
assert_eq!(e.code, "NOT_FOUND");
|
||||
assert!(e.message.contains("missing"));
|
||||
}
|
||||
other => panic!("expected NOT_FOUND, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_on_query_op_yields_invalid_operation_type() {
|
||||
let mut registry = OperationRegistry::new();
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
external_spec("echo", AccessControl::default()),
|
||||
HandlerKind::Once(echo_handler()),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
let ctx = root_context("req-is-3", None, None, false, ScopedPeerEnv::empty());
|
||||
let stream = registry.invoke_streaming("echo", serde_json::json!({}), ctx);
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
match &items[0].result {
|
||||
Err(e) => assert_eq!(e.code, "INVALID_OPERATION_TYPE"),
|
||||
other => panic!("expected INVALID_OPERATION_TYPE, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_internal_op_from_external_yields_not_found() {
|
||||
let mut registry = OperationRegistry::new();
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
internal_subscription_spec(AccessControl::default()),
|
||||
HandlerKind::Stream(echo_streaming_handler()),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
let ctx = root_context("req-is-4", None, None, false, ScopedPeerEnv::empty());
|
||||
let stream = registry.invoke_streaming("events/stream", serde_json::json!({}), ctx);
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
match &items[0].result {
|
||||
Err(e) => {
|
||||
assert_eq!(e.code, "NOT_FOUND");
|
||||
assert!(e.message.contains("events/stream"));
|
||||
}
|
||||
other => panic!("expected NOT_FOUND, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_acl_denied_yields_forbidden() {
|
||||
let mut registry = OperationRegistry::new();
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
subscription_spec_with_acl(AccessControl {
|
||||
required_scopes: vec!["admin".to_string()],
|
||||
..Default::default()
|
||||
}),
|
||||
HandlerKind::Stream(echo_streaming_handler()),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
let ctx = root_context(
|
||||
"req-is-5",
|
||||
Some(identity_with_scopes("caller", &["user"])),
|
||||
None,
|
||||
false,
|
||||
ScopedPeerEnv::empty(),
|
||||
);
|
||||
let stream = registry.invoke_streaming("events/stream", serde_json::json!({}), ctx);
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
match &items[0].result {
|
||||
Err(e) => {
|
||||
assert_eq!(e.code, "FORBIDDEN");
|
||||
assert!(e.message.contains("admin"));
|
||||
}
|
||||
other => panic!("expected FORBIDDEN, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_internal_call_uses_handler_identity_for_acl() {
|
||||
let mut registry = OperationRegistry::new();
|
||||
let composing_authority = CompositionAuthority::new("agent-chat", ["admin".to_string()]);
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
internal_subscription_spec(AccessControl {
|
||||
required_scopes: vec!["admin".to_string()],
|
||||
..Default::default()
|
||||
}),
|
||||
HandlerKind::Stream(echo_streaming_handler()),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
let ctx = root_context(
|
||||
"req-is-6",
|
||||
Some(identity_with_scopes("user", &["user"])),
|
||||
Some(composing_authority),
|
||||
true,
|
||||
ScopedPeerEnv::empty(),
|
||||
);
|
||||
let stream = registry.invoke_streaming("events/stream", serde_json::json!({"ok": 1}), ctx);
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(items[0].request_id, "req-is-6");
|
||||
assert_eq!(items[0].result, Ok(serde_json::json!({"ok": 1})));
|
||||
}
|
||||
|
||||
fn subscription_spec_with_acl(acl: AccessControl) -> OperationSpec {
|
||||
OperationSpec::new(
|
||||
"events/stream",
|
||||
OperationType::Subscription,
|
||||
Visibility::External,
|
||||
serde_json::json!({}),
|
||||
serde_json::json!({}),
|
||||
vec![],
|
||||
acl,
|
||||
)
|
||||
}
|
||||
|
||||
fn internal_subscription_spec(acl: AccessControl) -> OperationSpec {
|
||||
OperationSpec::new(
|
||||
"events/stream",
|
||||
OperationType::Subscription,
|
||||
Visibility::Internal,
|
||||
serde_json::json!({}),
|
||||
serde_json::json!({}),
|
||||
vec![],
|
||||
acl,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ use alknet_call::registry::env::LocalOperationEnv;
|
||||
use alknet_call::registry::registration::OperationRegistry;
|
||||
use alknet_core::auth::{AuthToken, Identity, IdentityProvider};
|
||||
use alknet_core::types::Capabilities;
|
||||
use futures::stream::BoxStream;
|
||||
use serde_json::Value;
|
||||
|
||||
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
@@ -70,11 +71,43 @@ impl GatewayDispatch {
|
||||
self.registry.invoke(&operation_name, input, context).await
|
||||
}
|
||||
|
||||
pub fn invoke_streaming(
|
||||
&self,
|
||||
identity: Option<Identity>,
|
||||
op: &str,
|
||||
input: Value,
|
||||
) -> BoxStream<'static, ResponseEnvelope> {
|
||||
let operation_name = strip_leading_slash(op).to_string();
|
||||
let request_id = uuid::Uuid::new_v4().to_string();
|
||||
let context = self.build_root_context_streaming(&request_id, &operation_name, identity);
|
||||
self.registry
|
||||
.invoke_streaming(&operation_name, input, context)
|
||||
}
|
||||
|
||||
fn build_root_context(
|
||||
&self,
|
||||
request_id: &str,
|
||||
operation_name: &str,
|
||||
identity: Option<Identity>,
|
||||
) -> OperationContext {
|
||||
self.build_root_context_inner(request_id, operation_name, identity, true)
|
||||
}
|
||||
|
||||
fn build_root_context_streaming(
|
||||
&self,
|
||||
request_id: &str,
|
||||
operation_name: &str,
|
||||
identity: Option<Identity>,
|
||||
) -> OperationContext {
|
||||
self.build_root_context_inner(request_id, operation_name, identity, false)
|
||||
}
|
||||
|
||||
fn build_root_context_inner(
|
||||
&self,
|
||||
request_id: &str,
|
||||
operation_name: &str,
|
||||
identity: Option<Identity>,
|
||||
bounded: bool,
|
||||
) -> OperationContext {
|
||||
let registration = self.registry.registration(operation_name);
|
||||
let (composition_authority, capabilities, scoped_env) = match registration {
|
||||
@@ -97,7 +130,7 @@ impl GatewayDispatch {
|
||||
forwarded_for: None,
|
||||
capabilities,
|
||||
metadata: HashMap::new(),
|
||||
deadline: Some(Instant::now() + DEFAULT_TIMEOUT),
|
||||
deadline: bounded.then(|| Instant::now() + DEFAULT_TIMEOUT),
|
||||
scoped_env,
|
||||
env,
|
||||
abort_policy: AbortPolicy::default(),
|
||||
@@ -117,10 +150,11 @@ mod tests {
|
||||
services_list_handler, services_list_spec, services_schema_handler, services_schema_spec,
|
||||
};
|
||||
use alknet_call::registry::registration::{
|
||||
make_handler, HandlerKind, HandlerRegistration, OperationProvenance,
|
||||
make_handler, make_streaming_handler, HandlerKind, HandlerRegistration, OperationProvenance,
|
||||
};
|
||||
use alknet_call::registry::spec::{AccessControl, OperationSpec, OperationType, Visibility};
|
||||
use alknet_core::auth::AuthToken;
|
||||
use futures::stream::StreamExt;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
|
||||
struct StaticIdentityProvider {
|
||||
@@ -235,6 +269,53 @@ mod tests {
|
||||
registry
|
||||
}
|
||||
|
||||
fn subscription_spec(name: &str, visibility: Visibility, acl: AccessControl) -> OperationSpec {
|
||||
OperationSpec::new(
|
||||
name,
|
||||
OperationType::Subscription,
|
||||
visibility,
|
||||
serde_json::json!({}),
|
||||
serde_json::json!({}),
|
||||
vec![],
|
||||
acl,
|
||||
)
|
||||
}
|
||||
|
||||
fn echo_streaming_handler() -> HandlerKind {
|
||||
HandlerKind::Stream(make_streaming_handler(|input, context| {
|
||||
futures::stream::iter(vec![ResponseEnvelope::ok(context.request_id, input)])
|
||||
}))
|
||||
}
|
||||
|
||||
fn registry_with_subscription(
|
||||
name: &str,
|
||||
visibility: Visibility,
|
||||
acl: AccessControl,
|
||||
) -> OperationRegistry {
|
||||
let mut registry = OperationRegistry::new();
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
subscription_spec(name, visibility, acl),
|
||||
echo_streaming_handler(),
|
||||
OperationProvenance::Local,
|
||||
None,
|
||||
None,
|
||||
Capabilities::new(),
|
||||
))
|
||||
.unwrap();
|
||||
registry
|
||||
}
|
||||
|
||||
async fn collect_stream(
|
||||
mut stream: BoxStream<'static, ResponseEnvelope>,
|
||||
) -> Vec<ResponseEnvelope> {
|
||||
let mut out = Vec::new();
|
||||
while let Some(env) = stream.next().await {
|
||||
out.push(env);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn dispatch(
|
||||
registry: Arc<OperationRegistry>,
|
||||
provider: Arc<dyn IdentityProvider>,
|
||||
@@ -548,4 +629,195 @@ mod tests {
|
||||
fn assert_concrete<T: Sized>() {}
|
||||
assert_concrete::<GatewayDispatch>();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_on_subscription_returns_handler_stream() {
|
||||
let registry = Arc::new(registry_with_subscription(
|
||||
"events/stream",
|
||||
Visibility::External,
|
||||
AccessControl::default(),
|
||||
));
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = dispatch(registry, provider);
|
||||
|
||||
let stream = dp.invoke_streaming(None, "events/stream", serde_json::json!({ "v": 7 }));
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!(items[0].result, Ok(serde_json::json!({ "v": 7 })));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_strips_leading_slash_from_operation_name() {
|
||||
let registry = Arc::new(registry_with_subscription(
|
||||
"events/stream",
|
||||
Visibility::External,
|
||||
AccessControl::default(),
|
||||
));
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = dispatch(registry, provider);
|
||||
|
||||
let stream = dp.invoke_streaming(None, "/events/stream", serde_json::json!({}));
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
assert!(items[0].result.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_on_unknown_op_yields_single_not_found() {
|
||||
let registry = Arc::new(OperationRegistry::new());
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = dispatch(registry, provider);
|
||||
|
||||
let stream = dp.invoke_streaming(None, "no/such", serde_json::json!({}));
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
match &items[0].result {
|
||||
Err(e) => {
|
||||
assert_eq!(e.code, "NOT_FOUND");
|
||||
assert!(e.message.contains("no/such"));
|
||||
}
|
||||
other => panic!("expected NOT_FOUND, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_on_internal_op_from_external_yields_not_found() {
|
||||
let registry = Arc::new(registry_with_subscription(
|
||||
"secret/stream",
|
||||
Visibility::Internal,
|
||||
AccessControl::default(),
|
||||
));
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = dispatch(registry, provider);
|
||||
|
||||
let stream = dp.invoke_streaming(None, "secret/stream", serde_json::json!({}));
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
match &items[0].result {
|
||||
Err(e) => {
|
||||
assert_eq!(e.code, "NOT_FOUND");
|
||||
assert!(e.message.contains("secret/stream"));
|
||||
}
|
||||
other => panic!("expected NOT_FOUND, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_with_none_identity_and_restricted_op_yields_forbidden() {
|
||||
let registry = Arc::new(registry_with_subscription(
|
||||
"admin/stream",
|
||||
Visibility::External,
|
||||
AccessControl {
|
||||
required_scopes: vec!["admin".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = dispatch(registry, provider);
|
||||
|
||||
let stream = dp.invoke_streaming(None, "admin/stream", serde_json::json!({}));
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
match &items[0].result {
|
||||
Err(e) => {
|
||||
assert_eq!(e.code, "FORBIDDEN");
|
||||
assert_eq!(e.message, "authentication required");
|
||||
}
|
||||
other => panic!("expected FORBIDDEN, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_streaming_on_query_op_yields_invalid_operation_type() {
|
||||
let registry = Arc::new(registry_with(
|
||||
"echo/run",
|
||||
Visibility::External,
|
||||
AccessControl::default(),
|
||||
));
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = dispatch(registry, provider);
|
||||
|
||||
let stream = dp.invoke_streaming(None, "echo/run", serde_json::json!({}));
|
||||
let items = collect_stream(stream).await;
|
||||
assert_eq!(items.len(), 1);
|
||||
match &items[0].result {
|
||||
Err(e) => assert_eq!(e.code, "INVALID_OPERATION_TYPE"),
|
||||
other => panic!("expected INVALID_OPERATION_TYPE, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_on_subscription_op_returns_invalid_operation_type() {
|
||||
let registry = Arc::new(registry_with_subscription(
|
||||
"events/stream",
|
||||
Visibility::External,
|
||||
AccessControl::default(),
|
||||
));
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = dispatch(registry, provider);
|
||||
|
||||
let response = dp
|
||||
.invoke(None, "events/stream", serde_json::json!({}))
|
||||
.await;
|
||||
match response.result {
|
||||
Err(e) => assert_eq!(e.code, "INVALID_OPERATION_TYPE"),
|
||||
other => panic!("expected INVALID_OPERATION_TYPE, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_root_context_streaming_sets_deadline_none() {
|
||||
let registry = Arc::new(registry_with_subscription(
|
||||
"events/stream",
|
||||
Visibility::External,
|
||||
AccessControl::default(),
|
||||
));
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = dispatch(registry, provider);
|
||||
|
||||
let ctx = dp.build_root_context_streaming("req-st-1", "events/stream", None);
|
||||
assert!(!ctx.internal, "internal must be false for wire-ingress");
|
||||
assert!(ctx.forwarded_for.is_none(), "forwarded_for must be None");
|
||||
assert!(ctx.parent_request_id.is_none(), "root has no parent");
|
||||
assert!(
|
||||
ctx.deadline.is_none(),
|
||||
"deadline must be None for streaming"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_root_context_streaming_carries_registration_bundle_fields() {
|
||||
let authority = alknet_call::registry::context::CompositionAuthority::new(
|
||||
"agent",
|
||||
["fs:read".to_string()],
|
||||
);
|
||||
let scoped = ScopedPeerEnv::new(["fs/readFile"]);
|
||||
let caps = Capabilities::new().with_api_key("google", "k".to_string());
|
||||
|
||||
let mut registry = OperationRegistry::new();
|
||||
registry
|
||||
.register(HandlerRegistration::new(
|
||||
subscription_spec(
|
||||
"agent/stream",
|
||||
Visibility::External,
|
||||
AccessControl::default(),
|
||||
),
|
||||
echo_streaming_handler(),
|
||||
OperationProvenance::Local,
|
||||
Some(authority),
|
||||
Some(scoped.clone()),
|
||||
caps,
|
||||
))
|
||||
.unwrap();
|
||||
let registry = Arc::new(registry);
|
||||
let provider: Arc<dyn IdentityProvider> = Arc::new(StaticIdentityProvider::new());
|
||||
let dp = dispatch(registry, provider);
|
||||
|
||||
let ctx = dp.build_root_context_streaming("req-st-2", "agent/stream", None);
|
||||
assert!(ctx.handler_identity.is_some());
|
||||
assert_eq!(ctx.handler_identity.as_ref().unwrap().label, "agent");
|
||||
assert!(ctx.scoped_env.allows("fs/readFile"));
|
||||
assert!(ctx.capabilities.get("google").is_some());
|
||||
assert!(ctx.deadline.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: call/client/from-call-streaming-forwarding
|
||||
name: Implement from_call streaming forwarding handler (Subscription → CallConnection::subscribe → StreamingHandler)
|
||||
status: pending
|
||||
status: completed
|
||||
depends_on: [call/registry/streaming-handler-handlerkind]
|
||||
scope: narrow
|
||||
risk: medium
|
||||
@@ -169,4 +169,4 @@ or the pending entry's removal handles it).
|
||||
|
||||
## Summary
|
||||
|
||||
> To be filled on completion
|
||||
> Branched build_bundles on spec.op_type: Subscription → make_streaming_forwarding_handler (HandlerKind::Stream), Query/Mutation → existing make_forwarding_handler (HandlerKind::Once). Added CallConnection::subscribe_with_payload() mirroring call_with_payload (registers in PendingRequestMap, abort cascade wired). Streaming forwarding handler reuses build_forwarded_payload for forwarded_for + auth_token (ADR-032). composition_authority: None, scoped_env: None for FromCall streaming leaves. Added 7 unit tests covering all branches and forwarding behavior.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: call/protocol/dispatch-streaming-branch
|
||||
name: Wire Dispatcher::handle_stream streaming branch (Subscription → invoke_streaming → write each → call.completed)
|
||||
status: pending
|
||||
status: completed
|
||||
depends_on: [call/registry/invoke-streaming]
|
||||
scope: narrow
|
||||
risk: medium
|
||||
@@ -171,4 +171,4 @@ task; aborting the connection cancels it).
|
||||
|
||||
## Summary
|
||||
|
||||
> To be filled on completion
|
||||
> Added DispatchResult enum (Once(ResponseEnvelope) | Stream(ResponseStream)) and Dispatcher::dispatch() branching on op_type (looked up via registry.registration). handle_stream matches on DispatchResult — the branch is visible there (spec framing). Streaming pump writes each ResponseEnvelope → EventEnvelope frame; call.completed on natural end only when !last_was_error (Err is terminal, no call.completed after). deadline: None for streaming branch. Abort via Drop (no new code). Existing Query/Mutation path unchanged. Added 7 unit tests (dispatch branch, deadline clearing, pump frames, error terminal, query unchanged, unknown op, abort drops stream). 306 tests pass.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: call/registry/invoke-streaming
|
||||
name: Implement OperationRegistry::invoke_streaming() returning ResponseStream
|
||||
status: pending
|
||||
status: completed
|
||||
depends_on: [call/registry/streaming-handler-handlerkind]
|
||||
scope: narrow
|
||||
risk: medium
|
||||
@@ -167,4 +167,4 @@ streams. The error envelope carries the `request_id` from the context.
|
||||
|
||||
## Summary
|
||||
|
||||
> To be filled on completion
|
||||
> Added OperationRegistry::invoke_streaming() in crates/alknet-call/src/registry/registration.rs — the streaming dispatch path for Subscription operations. Same visibility + ACL checks as invoke() (provably identical security axis), then dispatches the StreamingHandler and returns its ResponseStream. Pre-handler errors (not-found, forbidden, INVALID_OPERATION_TYPE for non-Subscription ops) yield a single error ResponseEnvelope via stream::once, then end. Added 6 unit tests covering all paths (subscription dispatch, unknown op, query op cross-kind error, internal op from external, ACL denied, internal call using handler_identity).
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: http/adapters/from-openapi-sse-streaming
|
||||
name: Implement from_openapi Subscription forwarding as StreamingHandler (SSE response → BoxStream<ResponseEnvelope>)
|
||||
status: pending
|
||||
status: completed
|
||||
depends_on: [call/registry/streaming-handler-handlerkind]
|
||||
scope: narrow
|
||||
risk: medium
|
||||
@@ -240,4 +240,4 @@ HandlerRegistration::new(spec, handler, OperationProvenance::FromOpenAPI, None,
|
||||
|
||||
## Summary
|
||||
|
||||
> To be filled on completion
|
||||
> Branched build_registration on op_type: Subscription → make_streaming_handler + forward_stream() (HandlerKind::Stream), Query/Mutation → existing make_handler + forward() (HandlerKind::Once). forward_stream() sends Accept: text/event-stream, streams SSE chunks via stream::unfold over response.bytes_stream(), reusing parse_sse_frames; each data: frame → one ResponseEnvelope::ok(), HTTP error → single ResponseEnvelope::error(), SSE end → ResponseStream ends. Removed stream_subscription() collect-all placeholder. Added 4 tests + updated integration test. 234 tests pass.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: http/gateway/invoke-streaming
|
||||
name: Implement GatewayDispatch::invoke_streaming() returning BoxStream<ResponseEnvelope>
|
||||
status: pending
|
||||
status: completed
|
||||
depends_on: [call/registry/invoke-streaming]
|
||||
scope: narrow
|
||||
risk: medium
|
||||
@@ -127,4 +127,4 @@ don't duplicate the logic.
|
||||
|
||||
## Summary
|
||||
|
||||
> To be filled on completion
|
||||
> Added GatewayDispatch::invoke_streaming() returning BoxStream<ResponseEnvelope>. Security axis provably identical to invoke() via shared build_root_context_inner(bounded: bool); extracted build_root_context_streaming for deadline: None (unbounded subscriptions). Calls OperationRegistry::invoke_streaming(). to_mcp untouched. Added 9 unit tests (all error paths + streaming dispatch + deadline: None verification). 243 tests pass.
|
||||
Reference in New Issue
Block a user