use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard};
use lgwks_macros::Error;
use lgwks_std::id::Uuid;
use super::capability::{CapabilityError, is_ml_only, is_privileged};
use super::ensure;
use super::protocol::{SignalPattern, WidgetDescriptor, valid_signal_kind};
use crate::canvas_protocol::{Capability, SessionInvariant};
mod audit;
mod emit;
mod grant;
mod handles;
mod inspect;
mod limits;
pub use audit::{
AuditAction, AuditEvent, Caller, Decision, Emitter, Inspector, Permission, Reach, Scope,
Subject,
};
pub use grant::{
AuditFn, ClockFn, GrantFn, GrantVerificationResult, IdFn, SignalListener, SignedMlGrant,
TapListener, VerifyGrantFn,
};
pub use handles::{
IntentHandle, MlHandle, RegisteredHandle, Subscription, SubscriptionId, TapEvent, TapId,
};
pub use limits::Limit;
use limits::{tenant_count, within};
#[derive(Clone, Debug, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum BrokerError {
#[error("capability elevation: {0}")]
CapabilityElevation(Capability),
#[error("duplicate source id: {0}")]
DuplicateSourceId(String),
#[error("invalid handle")]
InvalidHandle,
#[error("malformed kind")]
MalformedKind,
#[error("rate limited")]
RateLimited,
#[error("ML grant required")]
MlGrantRequired,
#[error("ML grant invalid: {0:?}")]
MlGrantInvalid(GrantVerificationResult),
#[error("command bar already registered")]
CommandBarAlreadyRegistered,
#[error("invalid session")]
InvalidSession,
#[error(transparent)]
CapabilityDenied(#[from] CapabilityError),
#[error("cross-tenant inspection not granted")]
CrossTenantDenied,
#[error("limit exceeded: {0}")]
LimitExceeded(Limit),
}
struct TokenBucket {
refill_per_second: f64,
capacity: f64,
tokens: f64,
last_ms: u64,
}
impl TokenBucket {
fn new(now_ms: u64, refill_per_second: f64, capacity: f64) -> Self {
Self {
refill_per_second,
capacity,
tokens: capacity,
last_ms: now_ms,
}
}
fn consume(&mut self, now_ms: u64) -> bool {
if now_ms < self.last_ms {
self.last_ms = now_ms;
} else {
let elapsed_ms = now_ms.wrapping_sub(self.last_ms);
self.tokens = self
.capacity
.min(self.tokens + seconds_from_millis(elapsed_ms) * self.refill_per_second);
self.last_ms = now_ms;
}
if self.tokens >= 1.0 {
self.tokens -= 1.0;
true
} else {
false
}
}
}
fn seconds_from_millis(millis: u64) -> f64 {
let bytes = millis.to_le_bytes();
let low = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
let high = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
f64::from(high).mul_add(4_294_967_296.0, f64::from(low)) / 1_000.0
}
#[derive(Clone)]
struct WidgetRegistration {
descriptor: WidgetDescriptor,
session: SessionInvariant,
}
#[derive(Clone)]
struct MlRegistration {
grant: SignedMlGrant,
}
#[derive(Clone)]
struct CommandBarRegistration {
handle: IntentHandle,
session: SessionInvariant,
}
struct StoredSubscription {
handle: RegisteredHandle,
pattern: SignalPattern,
listener: SignalListener,
}
struct StoredTap {
owner: Uuid,
tenant: String,
listener: TapListener,
}
type WidgetKey = (String, String);
fn widget_key(registration: &WidgetRegistration) -> WidgetKey {
(
registration.session.tenant_id().to_owned(),
registration.descriptor.widget_id().to_owned(),
)
}
fn canonical_handle(nonce: Uuid, registration: &WidgetRegistration) -> RegisteredHandle {
RegisteredHandle::new(
nonce,
registration.session.session_id().to_owned(),
registration.descriptor.widget_id().to_owned(),
registration.session.tenant_id().to_owned(),
registration.session.user_sub().to_owned(),
)
}
struct BrokerState {
widgets: BTreeMap<Uuid, WidgetRegistration>,
source_ids: BTreeMap<WidgetKey, Uuid>,
ml_peers: BTreeMap<Uuid, MlRegistration>,
command_bar: Option<CommandBarRegistration>,
subscriptions: BTreeMap<Uuid, StoredSubscription>,
taps: BTreeMap<Uuid, StoredTap>,
rate_limiters: BTreeMap<WidgetKey, TokenBucket>,
rate_limited_counts: BTreeMap<WidgetKey, u64>,
ml_sessions: BTreeMap<Uuid, SessionInvariant>,
intent_limiters: BTreeMap<Uuid, TokenBucket>,
intent_limited_counts: BTreeMap<Uuid, u64>,
}
pub struct Broker {
now: ClockFn,
new_id: IdFn,
verify_grant: VerifyGrantFn,
grants: GrantFn,
audit: AuditFn,
audit_seq: AtomicU64,
state: Mutex<BrokerState>,
}
impl Broker {
#[must_use]
pub fn new(
now: ClockFn,
new_id: IdFn,
verify_grant: VerifyGrantFn,
grants: GrantFn,
audit: AuditFn,
) -> Self {
Self {
now,
new_id,
verify_grant,
grants,
audit,
audit_seq: AtomicU64::new(0),
state: Mutex::new(BrokerState {
widgets: BTreeMap::new(),
source_ids: BTreeMap::new(),
ml_peers: BTreeMap::new(),
command_bar: None,
subscriptions: BTreeMap::new(),
taps: BTreeMap::new(),
rate_limiters: BTreeMap::new(),
rate_limited_counts: BTreeMap::new(),
ml_sessions: BTreeMap::new(),
intent_limiters: BTreeMap::new(),
intent_limited_counts: BTreeMap::new(),
}),
}
}
fn lock(&self) -> MutexGuard<'_, BrokerState> {
match self.state.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
}
}
fn publish(&self, caller: Caller, action: AuditAction, reach: Reach, decision: Decision) {
let at_ms = (self.now)();
let seq = self.audit_seq.fetch_add(1, Ordering::SeqCst);
(self.audit)(&AuditEvent::new(
seq, at_ms, caller, action, reach, decision,
));
}
fn decide<T>(
&self,
caller: Caller,
action: AuditAction,
reach: Reach,
outcome: Result<T, BrokerError>,
) -> Result<T, BrokerError> {
self.publish(caller, action, reach, Decision::of(&outcome));
outcome
}
fn require(
&self,
session: &SessionInvariant,
permission: Permission,
) -> Result<(), BrokerError> {
ensure((self.grants)(session, &permission), || permission.refusal())
}
pub fn register(
&self,
descriptor: WidgetDescriptor,
session: SessionInvariant,
) -> Result<RegisteredHandle, BrokerError> {
let caller = Caller::of(&session);
let subject = Subject::Widget(descriptor.widget_id().to_owned());
let outcome = self.admit_widget(descriptor, session);
self.decide(caller, AuditAction::Register(subject), Reach::Own, outcome)
}
fn admit_widget(
&self,
descriptor: WidgetDescriptor,
session: SessionInvariant,
) -> Result<RegisteredHandle, BrokerError> {
let elevated = descriptor
.capabilities()
.iter()
.find(|capability| is_ml_only(capability) || is_privileged(capability));
match elevated {
Some(capability) => Err(BrokerError::CapabilityElevation(capability.clone())),
None => Ok(()),
}?;
let nonce = (self.new_id)();
let registration = WidgetRegistration {
descriptor,
session,
};
let key = widget_key(®istration);
let mut state = self.lock();
ensure(!state.source_ids.contains_key(&key), || {
BrokerError::DuplicateSourceId(key.1.clone())
})?;
within(state.widgets.len(), Limit::Widgets)?;
let owners = state.widgets.values().map(|held| held.session.tenant_id());
within(tenant_count(owners, &key.0), Limit::WidgetsPerTenant)?;
let handle = canonical_handle(nonce, ®istration);
state.source_ids.insert(key, nonce);
state.widgets.insert(nonce, registration);
Ok(handle)
}
pub fn unregister(&self, handle: &RegisteredHandle) {
let nonce = handle.nonce();
let removed = self.lock().widgets.remove(&nonce);
let (caller, outcome) = match removed {
None => (Caller::from_widget(handle), Err(BrokerError::InvalidHandle)),
Some(registration) => {
let key = widget_key(®istration);
let mut state = self.lock();
state
.subscriptions
.retain(|_, sub| sub.handle.nonce() != nonce);
state.taps.retain(|_, tap| tap.owner != nonce);
state.source_ids.remove(&key);
state.rate_limiters.remove(&key);
state.rate_limited_counts.remove(&key);
(Caller::of(®istration.session), Ok(()))
}
};
let subject = Subject::Widget(handle.descriptor_id().to_owned());
self.publish(
caller,
AuditAction::Revoke(subject),
Reach::Own,
Decision::of(&outcome),
);
}
pub fn register_ml_peer(
&self,
grant: SignedMlGrant,
session: SessionInvariant,
) -> Result<MlHandle, BrokerError> {
let caller = Caller::of(&session);
let outcome = self.admit_ml_peer(grant, session);
let action = AuditAction::Register(Subject::MlPeer);
self.decide(caller, action, Reach::Own, outcome)
}
fn admit_ml_peer(
&self,
grant: SignedMlGrant,
session: SessionInvariant,
) -> Result<MlHandle, BrokerError> {
let verdict = (self.verify_grant)(&grant);
ensure(verdict == GrantVerificationResult::Valid, || {
BrokerError::MlGrantInvalid(verdict.clone())
})?;
ensure(grant.capabilities().iter().any(is_ml_only), || {
BrokerError::MlGrantInvalid(GrantVerificationResult::InvalidGrant)
})?;
let nonce = (self.new_id)();
let mut state = self.lock();
within(state.ml_peers.len(), Limit::MlPeers)?;
let holders = state.ml_sessions.values().map(|held| held.tenant_id());
within(
tenant_count(holders, session.tenant_id()),
Limit::MlPeersPerTenant,
)?;
let handle = MlHandle::new(nonce, grant.tenant_id().to_owned());
state.ml_peers.insert(nonce, MlRegistration { grant });
state.ml_sessions.insert(nonce, session);
Ok(handle)
}
pub fn unregister_ml_peer(&self, handle: &MlHandle) {
let outcome = {
let mut state = self.lock();
state.ml_sessions.remove(&handle.nonce());
match state.ml_peers.remove(&handle.nonce()) {
Some(_) => Ok(()),
None => Err(BrokerError::InvalidHandle),
}
};
let caller = Caller::from_tenant(handle.tenant_id());
let action = AuditAction::Revoke(Subject::MlPeer);
self.publish(caller, action, Reach::Own, Decision::of(&outcome));
}
pub fn register_command_bar(
&self,
session: SessionInvariant,
) -> Result<IntentHandle, BrokerError> {
let caller = Caller::of(&session);
let outcome = self.admit_command_bar(session);
let action = AuditAction::Register(Subject::CommandBar);
self.decide(caller, action, Reach::Own, outcome)
}
fn admit_command_bar(&self, session: SessionInvariant) -> Result<IntentHandle, BrokerError> {
self.require(&session, Permission::Capability(Capability::IntentEmit))?;
let nonce = (self.new_id)();
let mut state = self.lock();
ensure(state.command_bar.is_none(), || {
BrokerError::CommandBarAlreadyRegistered
})?;
ensure(
!session.tenant_id().is_empty() && !session.user_sub().is_empty(),
|| BrokerError::InvalidSession,
)?;
let handle = IntentHandle::new(
nonce,
session.session_id().to_owned(),
session.tenant_id().to_owned(),
session.user_sub().to_owned(),
);
state.command_bar = Some(CommandBarRegistration {
handle: handle.clone(),
session,
});
Ok(handle)
}
pub fn unregister_command_bar(&self, handle: &IntentHandle) {
let nonce = handle.nonce();
let mut state = self.lock();
let held = state.command_bar.take_if(|bar| bar.handle.nonce() == nonce);
state.intent_limiters.remove(&nonce);
state.intent_limited_counts.remove(&nonce);
drop(state);
let (caller, outcome) = match held {
Some(bar) => (Caller::of(&bar.session), Ok(())),
None => (Caller::from_bar(handle), Err(BrokerError::InvalidHandle)),
};
let action = AuditAction::Revoke(Subject::CommandBar);
self.publish(caller, action, Reach::Own, Decision::of(&outcome));
}
}
fn require_valid_kind(kind: &str) -> Result<(), BrokerError> {
ensure(valid_signal_kind(kind), || BrokerError::MalformedKind)
}
#[cfg(test)]
mod tests {
use super::{TokenBucket, valid_signal_kind};
#[test]
fn widget_bucket_bursts_then_refills() -> Result<(), String> {
let mut bucket = TokenBucket::new(0, 100.0, 200.0);
for _ in 0..200 {
if !bucket.consume(0) {
return Err(String::from("burst must allow 200"));
}
}
if bucket.consume(0) {
return Err(String::from("201st frozen emit must limit"));
}
if !bucket.consume(1_000) {
return Err(String::from("one second must refill 100"));
}
Ok(())
}
#[test]
fn bucket_ignores_backwards_time() -> Result<(), String> {
let mut bucket = TokenBucket::new(10_000, 100.0, 200.0);
for _ in 0..200 {
bucket.consume(10_000);
}
if bucket.consume(0) {
return Err(String::from("backwards clock must not refill"));
}
Ok(())
}
#[test]
fn kinds_validate() -> Result<(), String> {
for bad in ["", ".", ".leading", "trailing.", "a..b", "has\ncontrol"] {
if valid_signal_kind(bad) {
return Err(format!("kind must be invalid: {bad:?}"));
}
}
let long = "k".repeat(129);
if valid_signal_kind(&long) {
return Err(String::from("129 chars must be invalid"));
}
for good in ["a", "intent.find", "forms.submitted.v2"] {
if !valid_signal_kind(good) {
return Err(format!("kind must be valid: {good:?}"));
}
}
Ok(())
}
}