use std::sync::Arc;
use lgwks_std::id::Uuid;
use super::super::ensure;
use super::super::pattern::match_pattern;
use super::super::protocol::{JsonValue, PartialIntent, SignalEnvelope, SignalPattern, SourceKind};
use super::super::time::format_millis;
use super::audit::same_scope;
use super::inspect::caller_of;
use super::limits::{payload_within, tenant_count, within};
use super::{
AuditAction, Broker, BrokerError, BrokerState, Caller, CommandBarRegistration, Decision,
Emitter, IntentHandle, Limit, MlHandle, MlRegistration, Reach, RegisteredHandle,
SignalListener, StoredSubscription, Subject, SubscriptionId, TapEvent, TapListener,
TokenBucket, WidgetRegistration, canonical_handle, require_valid_kind, widget_key,
};
use crate::canvas_protocol::SessionInvariant;
impl Broker {
fn route(
&self,
listeners: &[SignalListener],
taps: &[TapListener],
envelope: SignalEnvelope,
throttled: u64,
now_ms: u64,
) -> SignalEnvelope {
let (matched, fanout_duration_ns) = deliver(listeners, &envelope);
let action = AuditAction::Route {
signal_id: envelope.signal_id().to_owned(),
kind: envelope.kind().to_owned(),
source_id: envelope.source_id().to_owned(),
};
let caller = Caller::of(envelope.session_invariant());
self.publish(caller, action, Reach::Own, Decision::Allowed);
fire_taps(
taps,
&TapEvent::new(
redact_payload(&envelope),
matched,
fanout_duration_ns,
throttled,
now_ms,
),
);
envelope
}
fn audit_refusal<T>(
&self,
outcome: Result<T, BrokerError>,
emitter: Emitter,
resolve: impl FnOnce(&BrokerState) -> Caller,
) -> Result<T, BrokerError> {
if let Err(ref error) = outcome {
let who = resolve(&self.lock());
self.audit_denial(who, AuditAction::Emit(emitter), error);
}
outcome
}
fn begin_emit(&self, kind: &str, payload: &JsonValue) -> Result<(u64, Uuid), BrokerError> {
require_valid_kind(kind)?;
payload_within(payload)?;
Ok(((self.now)(), (self.new_id)()))
}
pub fn emit(
&self,
handle: &RegisteredHandle,
kind: &str,
payload: JsonValue,
) -> Result<SignalEnvelope, BrokerError> {
let outcome = self.emit_widget(handle, kind, payload);
self.audit_refusal(outcome, Emitter::Widget, |state| caller_of(state, handle))
}
fn emit_widget(
&self,
handle: &RegisteredHandle,
kind: &str,
payload: JsonValue,
) -> Result<SignalEnvelope, BrokerError> {
let (now_ms, signal_id) = self.begin_emit(kind, &payload)?;
let mut state = self.lock();
let registration = state
.widgets
.get(&handle.nonce())
.cloned()
.ok_or(BrokerError::InvalidHandle)?;
let key = widget_key(®istration);
let bucket = state.rate_limiters.entry(key.clone());
let bucket = bucket.or_insert_with(|| TokenBucket::new(now_ms, 100.0, 200.0));
ensure(bucket.consume(now_ms), || {
let count = state.rate_limited_counts.entry(key.clone()).or_insert(0);
*count = count.saturating_add(1);
BrokerError::RateLimited
})?;
let envelope = stamp_widget(kind, payload, ®istration, now_ms, &signal_id);
let throttled = {
let slot = state.rate_limited_counts.entry(key).or_insert(0);
let taken = *slot;
*slot = 0;
taken
};
let skip = (!registration.descriptor.self_listen()).then_some(handle.nonce());
let listeners = matching_listeners(&state, &envelope, skip);
let taps = tap_listeners(&state);
drop(state);
Ok(self.route(&listeners, &taps, envelope, throttled, now_ms))
}
pub fn subscribe(
&self,
handle: &RegisteredHandle,
pattern: SignalPattern,
listener: SignalListener,
) -> Result<SubscriptionId, BrokerError> {
let id = (self.new_id)();
let mut state = self.lock();
let who = caller_of(&state, handle);
let outcome = admit_subscription(&mut state, handle, id, pattern, listener);
drop(state);
self.decide(
who,
AuditAction::Register(Subject::Subscription),
Reach::Own,
outcome,
)
}
pub fn unsubscribe(
&self,
handle: &RegisteredHandle,
id: &SubscriptionId,
) -> Result<(), BrokerError> {
let mut state = self.lock();
let who = caller_of(&state, handle);
let owned = state
.subscriptions
.get(&id.0)
.is_some_and(|held| held.handle.nonce() == handle.nonce());
let outcome = if owned {
state.subscriptions.remove(&id.0);
Ok(())
} else {
Err(BrokerError::InvalidHandle)
};
drop(state);
self.decide(
who,
AuditAction::Revoke(Subject::Subscription),
Reach::Own,
outcome,
)
}
pub fn emit_intent(
&self,
handle: &IntentHandle,
partial: PartialIntent,
) -> Result<SignalEnvelope, BrokerError> {
let outcome = self.emit_bar(handle, partial);
self.audit_refusal(outcome, Emitter::Intent, |state| {
match state.command_bar.as_ref() {
Some(bar) if bar.handle.nonce() == handle.nonce() => Caller::of(&bar.session),
Some(_) | None => Caller::from_bar(handle),
}
})
}
fn emit_bar(
&self,
handle: &IntentHandle,
partial: PartialIntent,
) -> Result<SignalEnvelope, BrokerError> {
let (now_ms, signal_id) = self.begin_emit(partial.kind(), partial.payload())?;
let mut state = self.lock();
let registration = state
.command_bar
.as_ref()
.filter(|registration| registration.handle.nonce() == handle.nonce())
.cloned()
.ok_or(BrokerError::InvalidHandle)?;
let claims_match = handle.tenant_id() == registration.session.tenant_id()
&& handle.user_sub() == registration.session.user_sub();
ensure(claims_match, || BrokerError::InvalidHandle)?;
let bucket = state.intent_limiters.entry(handle.nonce());
let bucket = bucket.or_insert_with(|| TokenBucket::new(now_ms, 5.0, 5.0));
ensure(bucket.consume(now_ms), || {
let count = state
.intent_limited_counts
.entry(handle.nonce())
.or_insert(0);
*count = count.saturating_add(1);
BrokerError::RateLimited
})?;
let envelope = stamp_intent(&partial, ®istration, now_ms, &signal_id);
let throttled = {
let slot = state
.intent_limited_counts
.entry(handle.nonce())
.or_insert(0);
let taken = *slot;
*slot = 0;
taken
};
let listeners = matching_listeners(&state, &envelope, None);
let taps = tap_listeners(&state);
drop(state);
Ok(self.route(&listeners, &taps, envelope, throttled, now_ms))
}
pub fn emit_prediction(
&self,
handle: &MlHandle,
kind: &str,
payload: JsonValue,
) -> Result<SignalEnvelope, BrokerError> {
let outcome = self.emit_peer(handle, kind, payload);
self.audit_refusal(outcome, Emitter::Prediction, |state| {
match state.ml_sessions.get(&handle.nonce()) {
Some(session) => Caller::of(session),
None => Caller::from_tenant(handle.tenant_id()),
}
})
}
fn emit_peer(
&self,
handle: &MlHandle,
kind: &str,
payload: JsonValue,
) -> Result<SignalEnvelope, BrokerError> {
let (now_ms, signal_id) = self.begin_emit(kind, &payload)?;
let state = self.lock();
let registration = state
.ml_peers
.get(&handle.nonce())
.cloned()
.ok_or(BrokerError::InvalidHandle)?;
let session = state
.ml_sessions
.get(&handle.nonce())
.cloned()
.ok_or(BrokerError::InvalidHandle)?;
let envelope = stamp_ml(kind, payload, &session, ®istration, &signal_id, now_ms);
let listeners = matching_listeners(&state, &envelope, None);
let taps = tap_listeners(&state);
drop(state);
Ok(self.route(&listeners, &taps, envelope, 0, now_ms))
}
}
fn matching_listeners(
state: &BrokerState,
envelope: &SignalEnvelope,
skip_nonce: Option<Uuid>,
) -> Vec<SignalListener> {
let mut listeners = Vec::new();
for sub in state.subscriptions.values() {
if skip_nonce == Some(sub.handle.nonce()) {
continue;
}
let seen = envelope.session_invariant();
let in_scope = same_scope(
sub.handle.session_id(),
sub.handle.tenant_id(),
seen.session_id(),
seen.tenant_id(),
);
if in_scope && match_pattern(envelope, &sub.pattern) {
listeners.push(Arc::clone(&sub.listener));
}
}
listeners
}
fn admit_subscription(
state: &mut BrokerState,
handle: &RegisteredHandle,
id: Uuid,
pattern: SignalPattern,
listener: SignalListener,
) -> Result<SubscriptionId, BrokerError> {
let registration = state
.widgets
.get(&handle.nonce())
.ok_or(BrokerError::InvalidHandle)?;
let owner = canonical_handle(handle.nonce(), registration);
within(state.subscriptions.len(), Limit::Subscriptions)?;
let holders = state
.subscriptions
.values()
.map(|held| held.handle.tenant_id());
within(
tenant_count(holders, owner.tenant_id()),
Limit::SubscriptionsPerTenant,
)?;
state.subscriptions.insert(
id,
StoredSubscription {
handle: owner,
pattern,
listener,
},
);
Ok(SubscriptionId(id))
}
fn deliver(listeners: &[SignalListener], envelope: &SignalEnvelope) -> (usize, u64) {
let started = std::time::Instant::now();
for listener in listeners {
listener(envelope.clone());
}
let nanos = started.elapsed().as_nanos().min(u128::from(u64::MAX));
let bytes = nanos.to_le_bytes();
let clamped = u64::from_le_bytes([
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
]);
(listeners.len(), clamped)
}
fn stamp_widget(
kind: &str,
payload: JsonValue,
registration: &WidgetRegistration,
now_ms: u64,
signal_id: &Uuid,
) -> SignalEnvelope {
SignalEnvelope::new(
signal_id.to_string(),
String::from(kind),
SourceKind::Widget,
registration.descriptor.widget_id().to_owned(),
registration.session.clone(),
payload,
format_millis(now_ms),
)
}
fn stamp_ml(
kind: &str,
payload: JsonValue,
session: &SessionInvariant,
registration: &MlRegistration,
signal_id: &Uuid,
now_ms: u64,
) -> SignalEnvelope {
SignalEnvelope::new(
signal_id.to_string(),
String::from(kind),
SourceKind::Ml,
registration.grant.tenant_id().to_owned(),
session.clone(),
payload,
format_millis(now_ms),
)
}
fn stamp_intent(
partial: &PartialIntent,
registration: &CommandBarRegistration,
now_ms: u64,
signal_id: &Uuid,
) -> SignalEnvelope {
SignalEnvelope::new(
signal_id.to_string(),
partial.kind().to_owned(),
SourceKind::User,
format!("command-bar:{}", registration.session.user_sub()),
registration.session.clone(),
partial.payload().clone(),
format_millis(now_ms),
)
}
fn redact_payload(envelope: &SignalEnvelope) -> SignalEnvelope {
SignalEnvelope::new(
envelope.signal_id().to_owned(),
envelope.kind().to_owned(),
envelope.source_kind(),
envelope.source_id().to_owned(),
envelope.session_invariant().clone(),
JsonValue::Null,
envelope.emitted_at().to_owned(),
)
}
fn fire_taps(taps: &[TapListener], event: &TapEvent) {
for tap in taps {
tap(event.clone());
}
}
fn tap_listeners(state: &BrokerState) -> Vec<TapListener> {
state
.taps
.values()
.map(|held| Arc::clone(&held.listener))
.collect()
}