feat: implement channels protocol + ADR-047 (openable ALPNs are operations)
ADR-047: the unifying decision that dissolves into per-ALPN ops (, ) with a marker on . Each openable ALPN registers its own ops with their own , , , and the marker. The field is replaced by (Sub/Pub). The generic ops (channel/close, channel/control, channel/resources/subscribe) stay, keyed by channel_id. Resolves Gaps A-G from the research findings (Gap B broker named out-of-scope for alkcall; Gap C relay wrapper is consumer concern; Gap D connection-owner allocates; Gap E extension trait; Gap F boolean marker on wire; Gap G ACL/ownership complementary). ADR-037 amended: dissolves; removed; generic ops stay; preview dropped from resources/subscribe. Spec docs updated: channel-operations.md (unified model, opener ledger, ACL flow), operation-registry.md (channel_open marker, ChannelOpenSpec), README.md (ADR-047), open-questions.md (OQ-31..38 resolved). Source changes: - spec.rs: ChannelOpenSpec struct, channel_open field on OperationSpec, with_channel_open builder, 3 tests - discovery.rs: spec_to_json emits channel_open boolean, operation_spec_schema includes channel_open, 2 tests - from_call.rs: rebuild_spec_for parses channel_open marker, derive_alpn_from_op_name helper, 6 tests Channels module (src/channels/, 10 files, ~2400 lines): - wire.rs: 8-byte chunk header (ChunkHeader, parse/write_header, read_header/write_chunk/write_eof async helpers), 12 tests - reassembly.rs: MpscRecvStream (tokio::mpsc::Receiver<Bytes> → AsyncRead), MpscSendStream (AsyncWrite → tokio::mpsc::Sender<Bytes>), REQ-CH-01 shutdown sentinel, REQ-CH-02 sender-drop EOF, 10 tests - mux.rs: MuxHandle (clone-able, register(channel_id)), MuxRunner (per-channel pump tasks, exits when handles drop), OpenerLedger (ADR-047 §7), 4 tests - manager.rs: ChannelManager (channel map, open_channel, install_channel_zero, route_payload, teardown_channel, clear_all), 11 tests - source.rs: ChannelBidiStreamSource (yield-once accept_bi), channel_source helper, 4 tests - adapter.rs: ChannelsAdapter (ProtocolHandler for alknet/channels, demux loop, install_channel_zero hook), 1 test - operations.rs: ChannelOperations (registers channel/close, channel/control, channel/resources/subscribe), ChannelCore (check_open/on_close wrappers), 4 tests - policy.rs: ChannelLifecyclePolicy trait, NoCap, PerIdentityChannelPolicy (default 256, per_identity_caps override), default_policy, 8 tests - env.rs: ChannelOperationEnv extension trait (ADR-047 §4), ChannelsSessionEnv impl, 2 tests - client.rs: ChannelClient (from_connection, call_open_op, take_call_connection), 1 test Verification: 432 tests pass (66 new channels + 10 marker + 356 existing), clippy clean, fmt clean, cargo doc generates. Cargo.toml: +bytes dependency.
This commit is contained in:
1 parent
ea66398c88
commit
f305f8c0a5
23 files changed
+3753
-204
No files matched your search
@@ -0,0 +1,137 @@
|
||||
//! `ChannelClient` — the client-side type for a channels connection
|
||||
//! (ADR-043). Transport-agnostic `from_connection` primary: takes an
|
||||
//! established `Connection` (the consumer dials the transport and
|
||||
//! establishes the channels ALPN), runs the demux/mux, and exposes
|
||||
//! `open_channel(alpn, params)` to open data channels via the
|
||||
//! per-ALPN open ops on channel 0.
|
||||
//!
|
||||
//! The dial (TLS, QUIC, WebSocket) lives in the consumer —
|
||||
//! `ChannelClient` is transport-agnostic by construction (ADR-043).
|
||||
//!
|
||||
//! See `docs/architecture/channel-client.md` for the spec.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::core::types::{Connection, StreamError};
|
||||
use crate::protocol::connection::CallConnection;
|
||||
use crate::protocol::wire::ResponseEnvelope;
|
||||
|
||||
use super::manager::ChannelManager;
|
||||
use super::mux::MuxRunner;
|
||||
|
||||
/// The client-side handle for a channels connection. Constructed via
|
||||
/// [`ChannelClient::from_connection`] from an established
|
||||
/// `Connection`. Holds the `ChannelManager` (for the demux/mux state)
|
||||
/// and the `CallConnection` (for calling open ops on channel 0).
|
||||
///
|
||||
/// The consumer dials the transport and establishes the
|
||||
/// `alknet/channels` ALPN, then hands the `Connection` to
|
||||
/// `from_connection`. The client runs the demux/mux in spawned tasks
|
||||
/// and exposes `open_channel` to call the per-ALPN open ops
|
||||
/// (`channels/<alpn>/sub`, `channels/<alpn>/pub`) on channel 0.
|
||||
pub struct ChannelClient {
|
||||
manager: ChannelManager,
|
||||
call_connection: Arc<Mutex<Option<CallConnection>>>,
|
||||
}
|
||||
|
||||
impl ChannelClient {
|
||||
/// Construct from an established `Connection` (the consumer dials
|
||||
/// the transport and establishes the `alknet/channels` ALPN).
|
||||
/// Installs channel 0 (pre-negotiated as `alknet/call`,
|
||||
/// ADR-036), wraps it as a `CallConnection`, spawns the demux and
|
||||
/// mux tasks, and returns the client.
|
||||
///
|
||||
/// The `CallAdapter`'s dispatch loop runs on channel 0; the
|
||||
/// `ChannelClient` holds the `CallConnection` so the consumer can
|
||||
/// call `open_channel` (which calls the per-ALPN open ops on
|
||||
/// channel 0).
|
||||
pub async fn from_connection(connection: Connection) -> Result<Self, StreamError> {
|
||||
let bidi = connection.accept_bi().await?;
|
||||
let (reader, writer) = tokio::io::split(bidi);
|
||||
let (mux_handle, mux_runner) = MuxRunner::new(Box::new(writer));
|
||||
let manager = ChannelManager::with_defaults(mux_handle, connection.remote_addr());
|
||||
|
||||
// Install channel 0 — the call adapter's read/write halves.
|
||||
let (channel0_send, channel0_recv) = manager
|
||||
.install_channel_zero(None)
|
||||
.await
|
||||
.map_err(|_| StreamError::StreamClosed)?;
|
||||
let channel0_source =
|
||||
super::source::channel_source(channel0_recv, channel0_send, connection.remote_addr());
|
||||
let channel0_conn = Connection::from_source(channel0_source, b"alknet/call".to_vec());
|
||||
let call_connection = CallConnection::new(channel0_conn);
|
||||
|
||||
// Spawn the mux runner (write side).
|
||||
let _mux_task = tokio::spawn(async move {
|
||||
if let Err(e) = mux_runner.run().await {
|
||||
tracing::warn!(error = %e, "channel client: mux runner ended with error");
|
||||
}
|
||||
});
|
||||
|
||||
// Spawn the demux loop (read side). The loop reads 8-byte
|
||||
// chunk headers and routes payloads to the manager. It ends
|
||||
// on transport EOF, clearing the channel map (REQ-CH-02).
|
||||
let demux_manager = manager.clone();
|
||||
let _demux_task = tokio::spawn(async move {
|
||||
super::adapter::ChannelsAdapter::run_demux_loop_for_client(
|
||||
&demux_manager,
|
||||
Box::new(reader),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
manager,
|
||||
call_connection: Arc::new(Mutex::new(Some(call_connection))),
|
||||
})
|
||||
}
|
||||
|
||||
/// The `ChannelManager` — for relay logic and tests.
|
||||
pub fn manager(&self) -> &ChannelManager {
|
||||
&self.manager
|
||||
}
|
||||
|
||||
/// Call a per-ALPN open op (`channels/<alpn>/sub` or
|
||||
/// `channels/<alpn>/pub`) on channel 0. Returns the
|
||||
/// `ResponseEnvelope` (which carries `channel_id` on success).
|
||||
///
|
||||
/// The consumer uses this to open a data channel: call
|
||||
/// `channels/tty/sub` with the ALPN-specific params; the responder
|
||||
/// allocates the `channel_id` and returns it; the consumer then
|
||||
/// reads/writes on the channel's `BiStream` (obtained via
|
||||
/// `manager.open_channel_stream(channel_id)` or the relay
|
||||
/// machinery).
|
||||
pub async fn call_open_op(&self, operation_id: &str, input: Value) -> ResponseEnvelope {
|
||||
let guard = self.call_connection.lock().await;
|
||||
match guard.as_ref() {
|
||||
Some(conn) => conn.call(operation_id, input).await,
|
||||
None => ResponseEnvelope::error(
|
||||
"channel-client",
|
||||
crate::protocol::wire::CallError::internal("channel client closed"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the `CallConnection` — used by the consumer to register
|
||||
/// imported ops (`from_call`) on the connection's overlay. After
|
||||
/// this, `call_open_op` returns an error (the connection is owned
|
||||
/// by the consumer).
|
||||
pub async fn take_call_connection(&self) -> Option<CallConnection> {
|
||||
self.call_connection.lock().await.take()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channel_client_is_not_send_safe_across_await_by_default() {
|
||||
// Smoke test: ChannelClient compiles. The actual send/sync
|
||||
// bounds are exercised by the integration tests.
|
||||
let _ = std::marker::PhantomData::<ChannelClient>;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user