1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
//! Shared multi-client attach/fan-out transport (DOC-48 §5.3.1, AC-7; issue
//! #3299, epic #3292; twin epic #3052).
//!
//! # Spec References
//!
//! - [`SPEC-WS-05~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-05~draft) §5.3.1
//! - [`SPEC-WS-07~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-07~draft) AC-7
//!
//! Why: DOC-48 §5.3.1 designates the multi-client SSE fan-out + per-session
//! event tagging used by tcode's workstream observation endpoint as
//! **harness-agnostic** — the same shape `trusty-agents` background sessions
//! need for epic #3052 (iOS thin client over VPN). Phase 1A
//! (`trusty-code::workstreams::sse`, issue #3297) proved the fan-out
//! algorithm against a concrete harness-private event type while keeping the
//! seam free of tcode-specific session types (only plain `String` session
//! ids and a `WorkstreamId`-shaped generic group id). This module is that
//! seam's landing zone: the same algorithm, generalised over an opaque group
//! id and an opaque event payload, with zero `axum`/tcode/HTTP dependency —
//! HTTP framing stays in each consumer (`trusty-code::workstreams::sse`
//! keeps its `axum::Router`; a future `trusty-agents` adopter keeps its own
//! transport).
//! What: [`SourceEvent`]/[`EventEnvelope`] (the AC-7.2 wire shape — a source
//! event and its forwarded counterpart share the same three fields, so one
//! type serves both; kept as a distinct alias-free struct with `#[derive]`
//! rather than reusing a tcode-specific ring-buffer envelope, per §5.3.1's
//! "generic envelope, no domain event coupling" requirement),
//! [`EventSource`] (a group-agnostic subscription trait — "subscribe once,
//! get a stream of session-tagged events"), [`MembershipProvider`] (a
//! group-membership check trait — "does this group currently contain this
//! session id", async so a store-backed implementation can await a lock),
//! and [`aggregate_live`] (the fan-out combinator: forwards an event
//! unconditionally per an optional `classify` bypass, or falls through to a
//! `MembershipProvider` lookup — this is the exact two-path decision
//! `trusty-code::workstreams::sse::aggregate_live` made inline, factored out
//! so `classify`'s domain-specific bypass rules — e.g. tcode's
//! `WorkstreamActivationChanged`/`WorkstreamStateInferred` — live entirely
//! in the caller, never in this crate).
//! Test: `transport_tests` exercises the combinator against an in-memory
//! `EventSource`/`MembershipProvider` pair; `trusty-code`'s own
//! `sse_tests::fan_out_tags_events_from_bound_sessions_only` and siblings
//! remain the end-to-end regression guard for the tcode adapter built on top.
//!
//! [`SourceEvent`]: crate::transport::SourceEvent
//! [`EventEnvelope`]: crate::transport::EventEnvelope
//! [`EventSource`]: crate::transport::EventSource
//! [`MembershipProvider`]: crate::transport::MembershipProvider
//! [`aggregate_live`]: crate::transport::aggregate_live
use Pin;
use async_trait;
use ;
use Serialize;
/// One event as it arrives from an [`EventSource`], before this module
/// decides whether to forward it.
///
/// Why: kept structurally identical to [`EventEnvelope`] (not merged into
/// one type) so a future `EventSource` impl that needs to distinguish
/// "received" from "forwarded" (e.g. for metrics) has a seam to hook into
/// without changing the wire type. `event_type` is a plain `String` (not an
/// enum) because it is meant to mirror the payload's own `kind()`-style
/// stable tag — the same convention `trusty-code`'s `SessionEventEnvelope`
/// already uses — without this crate needing to know the payload type's
/// shape.
/// Test: `transport_tests::forwards_event_when_membership_matches`.
/// The AC-7.2 wire envelope: `{session_id, event_type, payload}`.
///
/// Why: this is the literal shape AC-7.2 mandates for any harness-agnostic
/// SSE/attach consumer, generic over the payload type so neither tcode's
/// `Event` enum nor a future `trusty-agents` event type need be known here.
/// What: `session_id` is empty for a group-scoped event with no owning
/// session (mirrors `trusty-code::workstreams::sse::WorkstreamEventEnvelope`'s
/// `daemon_scoped` convention — that convention is a caller concern, not
/// enforced by this type).
/// Test: `transport_tests::forwards_event_when_membership_matches`.
/// A boxed, owned, `Send` stream — the shape [`EventSource::subscribe`]
/// returns, avoiding an associated-type-with-impl-Trait requirement on
/// implementors.
pub type BoxEventStream<P> = ;
/// The event-source seam: "subscribe once, get a stream of session-tagged
/// events."
///
/// Why: AC-7.1 requires the interface be "a trait ... `trusty-agents` can
/// implement without rework" — this trait names no concrete transport
/// (broadcast channel, SSE client, in-memory queue); an implementor owns
/// however it produces the stream. `Payload` is the implementor's own event
/// type (tcode's `Event` enum today; a `trusty-agents` harness event type
/// tomorrow).
/// What: one method, `subscribe`, called once per logical attach
/// (`aggregate_live` calls it exactly once — matching Phase 1A's "subscribe
/// ONCE to the daemon-global bus" design, not once per group member).
///
/// # Delivery guarantees
///
/// **At-most-once.** An implementor MAY silently drop events under
/// backpressure — e.g. the reference `trusty-code` adapter wraps a
/// `tokio::sync::broadcast` receiver and discards `Lagged(n)` errors, so a
/// slow subscriber simply misses the overwritten events. Callers that need
/// reliable delivery must layer their own buffering/replay on top;
/// reconnect/replay semantics (SSE ring-buffer replay etc., DOC-48 §5.3.1)
/// are deliberately the adopter's concern, not this trait's. Surfacing lag
/// to callers (a `Result<_, SourceLag>` item type) was considered and
/// deferred until `trusty-agents` adopts this seam (epic #3052), to avoid
/// speculatively complicating every implementor today.
/// Test: `transport_tests` implements this over a `tokio::sync::broadcast`
/// channel, the same primitive `trusty-code`'s adapter uses.
/// The group-membership seam: "does this group currently contain this
/// session id, right now."
///
/// Why: AC-7.3/§5.3.1 require the aggregation layer to re-check membership
/// live (not a snapshot taken at subscribe time), so a session added to a
/// group after a client attaches is picked up without a reconnect. `async`
/// so a store-backed implementation (tcode's `SharedWorkstreamStore`,
/// behind a `tokio::sync::Mutex`) can await its lock without this crate
/// knowing that detail.
/// What: `Group` is the implementor's own group-id type (tcode's
/// `WorkstreamId`; a future `trusty-agents` "logical unit" id for epic
/// #3052). `contains` returns `false` (never errors) when the group cannot
/// be resolved — mirrors Phase 1A's "a lookup failure is 'no match', not a
/// closed stream" bias, kept as this trait's documented contract so every
/// implementor behaves the same way.
/// Test: `transport_tests::membership_lookup_failure_is_treated_as_no_match`.
/// Build the live fan-out stream for one group.
///
/// Why: kept as a free function (not a method on a struct) so it stays
/// trivially unit-testable against an in-memory `EventSource`/
/// `MembershipProvider` pair, mirroring why
/// `trusty-code::workstreams::sse::aggregate_live` was a free function
/// before this extraction.
/// What: subscribes ONCE via `source.subscribe()`. For each event: if
/// `classify(payload, group)` returns `Some(bypass)`, the membership check
/// is skipped entirely and the event is forwarded iff `bypass` — this is
/// the seam a caller uses for group-scoped events that carry no session id
/// at all (tcode's `WorkstreamActivationChanged`/`WorkstreamStateInferred`).
/// If `classify` returns `None`, the event is forwarded iff
/// `membership.contains(group, session_id)` is `true` at THAT moment (not a
/// stale snapshot — re-checked on every event, per §5.3.1's "dynamic
/// membership" requirement).
/// Test: `transport_tests::forwards_event_when_membership_matches`,
/// `transport_tests::filters_event_when_membership_does_not_match`,
/// `transport_tests::classify_bypass_skips_membership_check`,
/// `transport_tests::membership_lookup_failure_is_treated_as_no_match`,
/// `transport_tests::concurrent_streams_over_one_source_stay_isolated`
/// (multi-client cross-subscriber isolation — epic #3052's property).