sim-lib-expr-tree-server 0.1.0

Authoritative bounded EvalSite server for SIM expression-tree sessions.
Documentation
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Bounded authoritative session registry and request routing.

use std::{
    collections::{BTreeMap, BTreeSet},
    sync::{
        Arc, Mutex, MutexGuard,
        atomic::{AtomicU64, Ordering},
    },
};

use sim_kernel::{Cx, Env, Error, Expr, Symbol, Value};
use sim_lib_expr_tree::TreeHandle;
use sim_lib_server::{ServerAddress, SystemWallClock, WallClock};
use sim_lib_view::SurfaceCodec;
use sim_lib_view_expr_tree::ExpressionTreeSurfaceCodec;
use sim_value::access;

use crate::error::{ExpressionTreeServerError, ServerResult, internal};
use crate::model::{ExpressionTreeServerLimits, SessionId, WatchBatch, WatchId};
use crate::protocol;
use crate::session::SessionRecord;

mod route;

static NEXT_SERVER_NONCE: AtomicU64 = AtomicU64::new(1);

/// Authoritative bounded expression-tree session server.
pub struct ExpressionTreeServer {
    address: ServerAddress,
    codecs: Vec<Symbol>,
    clock: Arc<dyn WallClock>,
    limits: ExpressionTreeServerLimits,
    nonce: u64,
    registry: Mutex<Registry>,
}

struct Registry {
    sessions: BTreeMap<SessionId, SessionRecord>,
    in_flight: BTreeSet<SessionId>,
    next_session: u64,
    next_tick: u64,
}

struct RuntimeTarget {
    tree: TreeHandle,
    resource: Symbol,
}

impl RuntimeTarget {
    fn new(record: &SessionRecord) -> Self {
        Self {
            tree: record.tree.clone(),
            resource: record.resource(),
        }
    }
}

impl ExpressionTreeServer {
    /// Creates a server with explicit address, codecs, wall clock, and hard
    /// lifecycle limits.
    pub fn new(
        address: ServerAddress,
        codecs: Vec<Symbol>,
        clock: Arc<dyn WallClock>,
        limits: ExpressionTreeServerLimits,
    ) -> ServerResult<Self> {
        if codecs.is_empty() {
            return Err(ExpressionTreeServerError::new(
                "invalid-config",
                "at least one server codec is required",
            ));
        }
        if !limits.validate() {
            return Err(ExpressionTreeServerError::new(
                "invalid-config",
                "all expression-tree server limits must be nonzero",
            ));
        }
        Ok(Self {
            address,
            codecs,
            clock,
            limits,
            nonce: NEXT_SERVER_NONCE.fetch_add(1, Ordering::Relaxed),
            registry: Mutex::new(Registry {
                sessions: BTreeMap::new(),
                in_flight: BTreeSet::new(),
                next_session: 1,
                next_tick: 1,
            }),
        })
    }

    /// Creates a local server using the system wall clock and binary server
    /// frames.
    pub fn local() -> Self {
        Self::new(
            ServerAddress::Local,
            vec![Symbol::qualified("codec", "binary")],
            Arc::new(SystemWallClock),
            ExpressionTreeServerLimits::default(),
        )
        .expect("default expression-tree server configuration is valid")
    }

    /// Returns the configured server address.
    pub fn address(&self) -> &ServerAddress {
        &self.address
    }

    /// Returns the configured frame codecs.
    pub fn codecs(&self) -> &[Symbol] {
        &self.codecs
    }

    /// Returns the configured lifecycle limits.
    pub const fn limits(&self) -> ExpressionTreeServerLimits {
        self.limits
    }

    /// Creates one authoritative session, capturing the creator's runtime and
    /// immutable authority ceiling in the underlying expression tree.
    pub fn create_session(&self, cx: &mut Cx, storage_name: &str) -> ServerResult<SessionId> {
        let (id, tick) = {
            let mut registry = self.lock_registry()?;
            let tick = begin_request(&mut registry, self.limits);
            if registry.sessions.len() >= self.limits.max_sessions {
                return Err(ExpressionTreeServerError::new(
                    "session-limit",
                    format!("server session limit {} reached", self.limits.max_sessions),
                ));
            }
            let id = SessionId(format!(
                "{:016x}-{:016x}",
                self.nonce, registry.next_session
            ));
            registry.next_session = registry.next_session.saturating_add(1);
            (id, tick)
        };

        let value = cx
            .eval_expr(Expr::Call {
                operator: Box::new(Expr::Symbol(Symbol::qualified("expr-tree", "open"))),
                args: vec![Expr::String(storage_name.to_owned())],
            })
            .map_err(classify_kernel_error)?;
        let tree = value
            .object()
            .downcast_ref::<TreeHandle>()
            .cloned()
            .ok_or_else(|| {
                ExpressionTreeServerError::new(
                    "runtime-contract",
                    "expr-tree/open did not return a live TreeHandle",
                )
            })?;
        let clock = Arc::clone(&self.clock);
        tree.set_wall_clock(move || clock.now().ok().map(|time| time.unix_millis()))
            .map_err(classify_kernel_error)?;

        let mut registry = self.lock_registry()?;
        expire_idle(&mut registry, self.limits);
        if registry.sessions.len() >= self.limits.max_sessions {
            return Err(ExpressionTreeServerError::new(
                "session-limit",
                "session capacity changed while opening the tree",
            ));
        }
        registry
            .sessions
            .insert(id.clone(), SessionRecord::new(id.clone(), tree, tick));
        Ok(id)
    }

    /// Returns the current bounded snapshot for a session.
    pub fn snapshot(&self, session: &SessionId) -> ServerResult<Expr> {
        let mut registry = self.lock_registry()?;
        let tick = begin_request(&mut registry, self.limits);
        let record = session_mut(&mut registry, session)?;
        record.last_activity_tick = tick;
        record.snapshot(self.limits)
    }

    /// Returns the current optimistic revision.
    pub fn revision(&self, session: &SessionId) -> ServerResult<u64> {
        let mut registry = self.lock_registry()?;
        let tick = begin_request(&mut registry, self.limits);
        let record = session_mut(&mut registry, session)?;
        record.last_activity_tick = tick;
        Ok(record.revision)
    }

    /// Decodes and commits one standard Intent through the existing
    /// expression-tree `SurfaceCodec`.
    pub fn apply_intent(
        &self,
        cx: &mut Cx,
        session: &SessionId,
        expected_revision: u64,
        intent: &Expr,
    ) -> ServerResult<Expr> {
        let snapshot = self.snapshot(session)?;
        let current = snapshot_revision(&snapshot)?;
        if current != expected_revision {
            return Err(stale(expected_revision, current));
        }
        let codec = ExpressionTreeSurfaceCodec::new();
        let draft = codec
            .decode(cx, &snapshot, intent)
            .map_err(classify_kernel_error)?;
        let operation = codec.commit(cx, &draft).map_err(classify_kernel_error)?;
        cx.require_all(&operation.required_capabilities)
            .map_err(classify_kernel_error)?;
        self.commit_surface_operation(cx, session, Some(expected_revision), &operation.form)
    }

    /// Closes and removes one authoritative session.
    pub fn close_session(&self, session: &SessionId) -> ServerResult<bool> {
        let mut registry = self.lock_registry()?;
        begin_request(&mut registry, self.limits);
        if registry.in_flight.contains(session) {
            return Err(session_busy());
        }
        Ok(registry.sessions.remove(session).is_some())
    }

    /// Subscribes one bounded independent watch.
    pub fn subscribe(&self, session: &SessionId) -> ServerResult<WatchId> {
        let mut registry = self.lock_registry()?;
        let tick = begin_request(&mut registry, self.limits);
        let record = session_mut(&mut registry, session)?;
        record.last_activity_tick = tick;
        record.subscribe(self.limits)
    }

    /// Drains at most `limit` changes from one watch.
    pub fn poll_watch(
        &self,
        session: &SessionId,
        watch: &WatchId,
        limit: usize,
    ) -> ServerResult<WatchBatch> {
        let mut registry = self.lock_registry()?;
        let tick = begin_request(&mut registry, self.limits);
        let record = session_mut(&mut registry, session)?;
        record.last_activity_tick = tick;
        record.poll_watch(watch, limit.min(self.limits.watch_capacity))
    }

    /// Cancels a watch idempotently with respect to future event delivery.
    pub fn cancel_watch(&self, session: &SessionId, watch: &WatchId) -> ServerResult<()> {
        let mut registry = self.lock_registry()?;
        let tick = begin_request(&mut registry, self.limits);
        let record = session_mut(&mut registry, session)?;
        record.last_activity_tick = tick;
        record.cancel_watch(watch)
    }

    /// Advances the server's mandatory logical lifecycle clock and expires idle
    /// sessions. No wall-clock value participates in the comparison.
    pub fn maintenance_tick(&self, steps: u64) -> ServerResult<usize> {
        let mut registry = self.lock_registry()?;
        registry.next_tick = registry.next_tick.saturating_add(steps);
        let before = registry.sessions.len();
        expire_idle(&mut registry, self.limits);
        Ok(before.saturating_sub(registry.sessions.len()))
    }

    fn wall_observation(&self) -> Option<u64> {
        self.clock.now().ok().map(|time| time.unix_millis())
    }

    fn lock_registry(&self) -> ServerResult<MutexGuard<'_, Registry>> {
        self.registry.lock().map_err(internal)
    }

    #[cfg(test)]
    pub(crate) fn registry_is_unlocked_for_test(&self) -> bool {
        self.registry.try_lock().is_ok()
    }
}

impl Default for ExpressionTreeServer {
    fn default() -> Self {
        Self::local()
    }
}

fn begin_request(registry: &mut Registry, limits: ExpressionTreeServerLimits) -> u64 {
    let tick = registry.next_tick;
    registry.next_tick = registry.next_tick.saturating_add(1);
    expire_idle(registry, limits);
    tick
}

fn expire_idle(registry: &mut Registry, limits: ExpressionTreeServerLimits) {
    let now = registry.next_tick;
    let Registry {
        sessions,
        in_flight,
        ..
    } = registry;
    sessions.retain(|id, session| {
        in_flight.contains(id)
            || now.saturating_sub(session.last_activity_tick) <= limits.max_idle_ticks
    });
}

fn session_mut<'a>(
    registry: &'a mut Registry,
    session: &SessionId,
) -> ServerResult<&'a mut SessionRecord> {
    if registry.in_flight.contains(session) {
        return Err(session_busy());
    }
    reserved_session_mut(registry, session)
}

fn reserved_session_mut<'a>(
    registry: &'a mut Registry,
    session: &SessionId,
) -> ServerResult<&'a mut SessionRecord> {
    registry.sessions.get_mut(session).ok_or_else(|| {
        ExpressionTreeServerError::new(
            "unknown-session",
            "session is absent, expired, cancelled, or belongs to another server",
        )
    })
}

fn session_busy() -> ExpressionTreeServerError {
    ExpressionTreeServerError::new(
        "session-busy",
        "another operation is already evaluating for this session",
    )
}

fn execute_runtime(cx: &mut Cx, target: &RuntimeTarget, operation: &Expr) -> ServerResult<Value> {
    validate_runtime_target(target, operation)?;
    let tree = cx
        .factory()
        .opaque(Arc::new(target.tree.clone()))
        .map_err(classify_kernel_error)?;
    let mut env = Env::child(Arc::new(cx.env().clone()));
    env.define(target.resource.clone(), tree);
    cx.with_env(env, |cx| cx.eval_expr(operation.clone()))
        .map_err(classify_kernel_error)
}

fn validate_runtime_target(target: &RuntimeTarget, operation: &Expr) -> ServerResult<()> {
    let Expr::Call { operator, args } = operation else {
        return Err(ExpressionTreeServerError::new(
            "invalid-operation",
            "surface operation must be a local map or expression-tree call",
        ));
    };
    let Expr::Symbol(operator) = operator.as_ref() else {
        return Err(ExpressionTreeServerError::new(
            "invalid-operation",
            "runtime operation must name an expression-tree function",
        ));
    };
    if operator.namespace.as_deref() != Some("expr-tree") {
        return Err(ExpressionTreeServerError::new(
            "invalid-operation",
            "runtime operation is outside the expression-tree family",
        ));
    }
    if !matches!(args.first(), Some(Expr::Symbol(resource)) if resource == &target.resource) {
        return Err(ExpressionTreeServerError::new(
            "session-mismatch",
            "runtime operation targets another expression-tree session",
        ));
    }
    Ok(())
}

fn operation_metadata(operation: &Expr) -> ServerResult<(String, Option<String>)> {
    if let Some(op) = protocol::operation(operation) {
        let path = access::field_str(operation, "path").map(str::to_owned);
        return Ok((op.name.to_string(), path));
    }
    let Expr::Call { operator, args } = operation else {
        return Err(ExpressionTreeServerError::new(
            "invalid-operation",
            "operation is neither a map nor a call",
        ));
    };
    let Expr::Symbol(operator) = operator.as_ref() else {
        return Err(ExpressionTreeServerError::new(
            "invalid-operation",
            "operation call has a non-symbol operator",
        ));
    };
    let path = args.get(1).and_then(|arg| match arg {
        Expr::String(path) => Some(path.clone()),
        _ => None,
    });
    Ok((operator.name.to_string(), path))
}

fn is_surface_local(operation: &Expr) -> bool {
    protocol::operation(operation)
        .is_some_and(|op| op.namespace.as_deref() == Some("expr-tree-view"))
}

fn is_revision_change(kind: &str) -> bool {
    !matches!(kind, "ref" | "list" | "status" | "explain" | "open-policy")
}

fn target_session(expr: &Expr) -> Option<SessionId> {
    let Expr::Call { operator, args } = expr else {
        return None;
    };
    let Expr::Symbol(operator) = operator.as_ref() else {
        return None;
    };
    if operator.namespace.as_deref() != Some("expr-tree") {
        return None;
    }
    match args.first() {
        Some(Expr::Symbol(resource)) => SessionId::from_resource(resource),
        _ => None,
    }
}

fn snapshot_revision(snapshot: &Expr) -> ServerResult<u64> {
    protocol::uint(snapshot, "revision").map_err(|_| {
        ExpressionTreeServerError::new(
            "invalid-expected-revision",
            "expected-current is not an expression-tree snapshot",
        )
    })
}

fn stale(expected: u64, current: u64) -> ExpressionTreeServerError {
    ExpressionTreeServerError::new(
        "stale-revision",
        format!("expected revision {expected}, current revision is {current}"),
    )
}

fn classify_kernel_error(error: Error) -> ExpressionTreeServerError {
    match error {
        Error::CapabilityDenied { capability } => ExpressionTreeServerError::new(
            "authority-denied",
            format!("caller lacks capability {capability}"),
        ),
        Error::TrustDenied { capability, .. } => ExpressionTreeServerError::new(
            "trust-denied",
            format!("caller trust does not permit capability {capability}"),
        ),
        other => ExpressionTreeServerError::new("operation-failed", other.to_string()),
    }
}