stasis-rs 0.9.3

Durable AI orchestration framework with runtime jobs, lineage, and memory integration
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use chrono::Utc;

use crate::application::runtime::in_memory_runtime::JobHandler;
use crate::application::runtime::job_lifecycle::StaleRecoverReport;
use crate::application::runtime::runtime_factory::RuntimeComposition;
use crate::application::runtime::runtime_factory::{RuntimeBackend, SurrealAuth};
use crate::application::runtime::stasis_runtime_builder::StasisRuntimeBuilder;
use crate::application::runtime::typed_job::{JobConsumer, TypedEnqueueBuilder};
use crate::domain::errors::Result;
use crate::domain::runtime::job::{JobState, NewJob};
use crate::domain::runtime::recurring::RecurringDefinition;
use crate::domain::runtime::resource_lease::{FencingToken, ResourceLease};
use crate::domain::runtime::typed_contract::{StasisEvent, StasisJob};
use crate::ports::outbound::runtime::job_store::JobStore;
use crate::ports::outbound::runtime::outbox_store::OutboxStore;
use crate::ports::outbound::runtime::recurring_store::RecurringStore;

/// Snapshot of high-level runtime queue, outbox, and recurring workload counts.
#[derive(Clone, Debug, Default)]
pub struct RuntimeStatsSnapshot {
    pub enqueued_jobs: usize,
    pub running_jobs: usize,
    pub succeeded_jobs: usize,
    pub failed_jobs: usize,
    pub dead_letter_jobs: usize,
    pub pending_outbox_events: usize,
    pub recurring_definitions: usize,
}

/// Backend-agnostic facade for runtime queue, outbox, and recurring operations.
#[derive(Clone)]
pub struct RuntimeSdk {
    runtime: RuntimeComposition,
}

/// Preferred public runtime naming.
pub type StasisRuntime = RuntimeSdk;

impl RuntimeSdk {
    /// Creates a new facade over a pre-built runtime composition.
    pub fn new(runtime: RuntimeComposition) -> Self {
        Self { runtime }
    }

    /// Builds an in-memory runtime facade with default wiring.
    pub async fn in_memory() -> Result<Self> {
        Self::from_builder(StasisRuntimeBuilder::new(RuntimeBackend::InMemory)).await
    }

    /// Builds a surreal-mem runtime facade with default wiring.
    pub async fn surreal_mem(
        namespace: impl Into<String>,
        database: impl Into<String>,
    ) -> Result<Self> {
        Self::from_builder(StasisRuntimeBuilder::new(RuntimeBackend::surreal_mem(
            namespace, database,
        )))
        .await
    }

    /// Builds a remote websocket surreal runtime facade with default wiring.
    pub async fn surreal_ws(
        endpoint: impl Into<String>,
        namespace: impl Into<String>,
        database: impl Into<String>,
    ) -> Result<Self> {
        Self::surreal_ws_with_auth(endpoint, namespace, database, None).await
    }

    /// Builds a remote websocket surreal runtime facade with optional root credentials.
    pub async fn surreal_ws_with_auth(
        endpoint: impl Into<String>,
        namespace: impl Into<String>,
        database: impl Into<String>,
        auth: Option<SurrealAuth>,
    ) -> Result<Self> {
        let mut backend = RuntimeBackend::surreal_ws(endpoint, namespace, database);
        if let Some(auth) = auth {
            backend = backend.with_surreal_auth(auth);
        }
        Self::from_builder(StasisRuntimeBuilder::new(backend)).await
    }

    /// Builds an embedded surreal-kv runtime facade with default wiring.
    pub async fn surreal_kv(
        path: impl Into<String>,
        namespace: impl Into<String>,
        database: impl Into<String>,
    ) -> Result<Self> {
        Self::surreal_kv_with_auth(path, namespace, database, None).await
    }

    /// Builds an embedded surreal-kv runtime facade with optional root credentials.
    pub async fn surreal_kv_with_auth(
        path: impl Into<String>,
        namespace: impl Into<String>,
        database: impl Into<String>,
        auth: Option<SurrealAuth>,
    ) -> Result<Self> {
        let mut backend = RuntimeBackend::surreal_kv(path, namespace, database);
        if let Some(auth) = auth {
            backend = backend.with_surreal_auth(auth);
        }
        Self::from_builder(StasisRuntimeBuilder::new(backend)).await
    }

    /// Builds a surreal-mem runtime facade with optional root credentials.
    pub async fn surreal_mem_with_auth(
        namespace: impl Into<String>,
        database: impl Into<String>,
        auth: Option<SurrealAuth>,
    ) -> Result<Self> {
        let mut backend = RuntimeBackend::surreal_mem(namespace, database);
        if let Some(auth) = auth {
            backend = backend.with_surreal_auth(auth);
        }
        Self::from_builder(StasisRuntimeBuilder::new(backend)).await
    }

    /// Builds a runtime facade from a fully configured runtime builder.
    pub async fn from_builder(builder: StasisRuntimeBuilder) -> Result<Self> {
        let runtime = builder.build().await?;
        Ok(Self::new(runtime))
    }

    /// Builds a runtime facade and returns composition-root bridge handles (MCP/agent).
    pub async fn from_builder_with_handles(
        builder: StasisRuntimeBuilder,
    ) -> Result<(
        Self,
        crate::application::runtime::stasis_runtime_builder::McpBridgeHandles,
    )> {
        let (runtime, handles) = builder.build_with_handles().await?;
        Ok((Self::new(runtime), handles))
    }

    /// Returns a shared reference to the underlying runtime composition.
    pub fn runtime(&self) -> &RuntimeComposition {
        &self.runtime
    }

    /// Consumes this facade and returns the owned runtime composition.
    pub fn into_runtime(self) -> RuntimeComposition {
        self.runtime
    }

    /// Enqueues a single runtime job.
    pub async fn enqueue(&self, job: NewJob) -> Result<()> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.enqueue(job).await,
            RuntimeComposition::Surreal(rt) => rt.enqueue(job).await,
        }
    }

    /// Enqueues a typed job payload. Call `.queue(...)`, `.retry(...)`, then `.send().await`.
    pub fn enqueue_job<T: StasisJob>(&self, payload: T) -> TypedEnqueueBuilder<T> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.enqueue_job(payload),
            RuntimeComposition::Surreal(rt) => rt.enqueue_job(payload),
        }
    }

    /// Registers a raw job handler.
    pub fn register_handler<H: JobHandler + 'static>(&self, handler: H) -> Result<()> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.register_handler(handler),
            RuntimeComposition::Surreal(rt) => rt.register_handler(handler),
        }
    }

    /// Registers a typed job consumer.
    pub fn register_consumer<T, H>(&self, handler: H) -> Result<()>
    where
        T: StasisJob,
        H: JobConsumer<T> + 'static,
    {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.register_consumer(handler),
            RuntimeComposition::Surreal(rt) => rt.register_consumer(handler),
        }
    }

    /// Cancels a non-terminal job, completes pending waits, and fires the cancel hook.
    pub async fn cancel(&self, job_id: &str) -> Result<bool> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.cancel(job_id).await,
            RuntimeComposition::Surreal(rt) => rt.cancel(job_id).await,
        }
    }

    /// Recovers expired `Leased`/`Running` jobs as retryable failures.
    pub async fn recover_stale(&self) -> Result<StaleRecoverReport> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.recover_stale_now().await,
            RuntimeComposition::Surreal(rt) => rt.recover_stale_now().await,
        }
    }

    /// Replays a dead-lettered job back to `Enqueued`.
    pub async fn replay_dead_letter(&self, job_id: &str) -> Result<bool> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.replay_dead_letter_now(job_id).await,
            RuntimeComposition::Surreal(rt) => rt.replay_dead_letter_now(job_id).await,
        }
    }

    /// Operator abort: mark a non-terminal job dead-lettered.
    pub async fn fail(&self, job_id: &str) -> Result<bool> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.fail(job_id).await,
            RuntimeComposition::Surreal(rt) => rt.fail(job_id).await,
        }
    }

    /// Deletes a terminal job. Refuse in-flight jobs; cancel or fail first.
    pub async fn delete(&self, job_id: &str) -> Result<bool> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.delete(job_id).await,
            RuntimeComposition::Surreal(rt) => rt.delete(job_id).await,
        }
    }

    /// Publishes a typed signal. Duplicate `(type, key, payload)` ids are ignored.
    pub async fn signal<E: StasisEvent>(
        &self,
        correlation_key: impl Into<String>,
        event: E,
    ) -> Result<bool> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.signal(correlation_key, event).await,
            RuntimeComposition::Surreal(rt) => rt.signal(correlation_key, event).await,
        }
    }

    pub async fn acquire_lease(
        &self,
        resource: impl Into<String>,
        owner: impl Into<String>,
        ttl: std::time::Duration,
    ) -> Result<ResourceLease> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.acquire_lease(resource, owner, ttl).await,
            RuntimeComposition::Surreal(rt) => rt.acquire_lease(resource, owner, ttl).await,
        }
    }

    pub async fn force_acquire_lease(
        &self,
        resource: impl Into<String>,
        owner: impl Into<String>,
        ttl: std::time::Duration,
    ) -> Result<ResourceLease> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.force_acquire_lease(resource, owner, ttl).await,
            RuntimeComposition::Surreal(rt) => rt.force_acquire_lease(resource, owner, ttl).await,
        }
    }

    pub async fn renew_lease(
        &self,
        resource: impl Into<String>,
        owner: impl Into<String>,
        fencing_token: FencingToken,
        ttl: std::time::Duration,
    ) -> Result<ResourceLease> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => {
                rt.renew_lease(resource, owner, fencing_token, ttl).await
            }
            RuntimeComposition::Surreal(rt) => {
                rt.renew_lease(resource, owner, fencing_token, ttl).await
            }
        }
    }

    pub async fn release_lease(
        &self,
        resource: impl Into<String>,
        owner: impl Into<String>,
        fencing_token: FencingToken,
    ) -> Result<bool> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => {
                rt.release_lease(resource, owner, fencing_token).await
            }
            RuntimeComposition::Surreal(rt) => {
                rt.release_lease(resource, owner, fencing_token).await
            }
        }
    }

    pub async fn transfer_lease(
        &self,
        resource: impl Into<String>,
        from: impl Into<String>,
        to: impl Into<String>,
        fencing_token: FencingToken,
        ttl: std::time::Duration,
    ) -> Result<ResourceLease> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => {
                rt.transfer_lease(resource, from, to, fencing_token, ttl)
                    .await
            }
            RuntimeComposition::Surreal(rt) => {
                rt.transfer_lease(resource, from, to, fencing_token, ttl)
                    .await
            }
        }
    }

    pub async fn validate_fence(
        &self,
        resource: impl Into<String>,
        fencing_token: FencingToken,
    ) -> Result<bool> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.validate_fence(resource, fencing_token).await,
            RuntimeComposition::Surreal(rt) => rt.validate_fence(resource, fencing_token).await,
        }
    }

    pub async fn watch_lease(&self, resource: impl Into<String>) -> Result<Option<ResourceLease>> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.watch_lease(resource).await,
            RuntimeComposition::Surreal(rt) => rt.watch_lease(resource).await,
        }
    }

    /// Registers a recurring job definition.
    pub async fn register_recurring(&self, definition: RecurringDefinition) -> Result<()> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.register_recurring(definition).await,
            RuntimeComposition::Surreal(rt) => rt.register_recurring(definition).await,
        }
    }

    /// Lists all recurring definitions currently registered in the runtime store.
    pub async fn list_recurring(&self) -> Result<Vec<RecurringDefinition>> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.recurring_store.list().await,
            RuntimeComposition::Surreal(rt) => rt.recurring_store.list().await,
        }
    }

    /// Upserts a recurring definition (used by declarative reconcile updates).
    pub async fn save_recurring(&self, definition: RecurringDefinition) -> Result<()> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.recurring_store.save(definition).await,
            RuntimeComposition::Surreal(rt) => rt.recurring_store.save(definition).await,
        }
    }

    /// Attempts to process one job from a queue using the provided worker id.
    pub async fn process_once(&self, queue: &str, worker_id: &str) -> Result<Option<String>> {
        let now = Utc::now();
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.process_once(queue, worker_id, now).await,
            RuntimeComposition::Surreal(rt) => rt.process_once(queue, worker_id, now).await,
        }
    }

    /// Publishes pending outbox events up to `limit`.
    pub async fn publish_pending_events(&self, limit: usize) -> Result<usize> {
        let now = Utc::now();
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.publish_pending_events(limit, now).await,
            RuntimeComposition::Surreal(rt) => rt.publish_pending_events(limit, now).await,
        }
    }

    /// Materializes any due recurring jobs at the current wall-clock time.
    pub async fn materialize_recurring_now(&self, scheduler_id: &str) -> Result<usize> {
        match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.materialize_recurring_now(scheduler_id).await,
            RuntimeComposition::Surreal(rt) => rt.materialize_recurring_now(scheduler_id).await,
        }
    }

    /// Aggregates common runtime counts into a single snapshot.
    pub async fn stats_snapshot(&self, pending_limit: usize) -> Result<RuntimeStatsSnapshot> {
        Ok(RuntimeStatsSnapshot {
            enqueued_jobs: self.job_count_by_state(JobState::Enqueued).await?,
            running_jobs: self.job_count_by_state(JobState::Running).await?,
            succeeded_jobs: self.job_count_by_state(JobState::Succeeded).await?,
            failed_jobs: self.job_count_by_state(JobState::Failed).await?,
            dead_letter_jobs: self.job_count_by_state(JobState::DeadLetter).await?,
            pending_outbox_events: self.pending_outbox_count(pending_limit).await?,
            recurring_definitions: self.recurring_count().await?,
        })
    }

    /// Counts jobs currently in the specified state.
    pub async fn job_count_by_state(&self, state: JobState) -> Result<usize> {
        let jobs = match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.job_store.list_by_state(state).await?,
            RuntimeComposition::Surreal(rt) => rt.job_store.list_by_state(state).await?,
        };
        Ok(jobs.len())
    }

    /// Counts pending outbox events, bounded by `limit`.
    pub async fn pending_outbox_count(&self, limit: usize) -> Result<usize> {
        let pending = match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.outbox_store.list_pending(limit).await?,
            RuntimeComposition::Surreal(rt) => rt.outbox_store.list_pending(limit).await?,
        };
        Ok(pending.len())
    }

    /// Counts registered recurring definitions.
    pub async fn recurring_count(&self) -> Result<usize> {
        let definitions = match &self.runtime {
            RuntimeComposition::InMemory(rt) => rt.recurring_store.list().await?,
            RuntimeComposition::Surreal(rt) => rt.recurring_store.list().await?,
        };
        Ok(definitions.len())
    }
}

#[cfg(test)]
mod tests {
    use std::env;
    use std::fs;
    use std::time::{SystemTime, UNIX_EPOCH};

    use crate::application::runtime::runtime_factory::RuntimeComposition;

    use super::RuntimeSdk;

    #[tokio::test]
    async fn runtime_sdk_in_memory_constructor_builds() {
        let runtime = RuntimeSdk::in_memory()
            .await
            .expect("in-memory runtime should build");
        let stats = runtime
            .stats_snapshot(10)
            .await
            .expect("stats snapshot should succeed");
        assert_eq!(stats.enqueued_jobs, 0);
    }

    #[tokio::test]
    async fn runtime_sdk_surreal_mem_constructor_builds() {
        let runtime = RuntimeSdk::surreal_mem("stasis", "runtime")
            .await
            .expect("surreal-mem runtime should build");
        assert!(matches!(runtime.runtime(), RuntimeComposition::Surreal(_)));
    }

    #[tokio::test]
    async fn runtime_sdk_surreal_ws_constructor_rejects_invalid_endpoint() {
        let result = RuntimeSdk::surreal_ws("not-a-valid-endpoint", "stasis", "runtime").await;
        assert!(result.is_err(), "invalid websocket endpoint should fail");
        let err = result.err().expect("result should contain an error");
        assert!(err.to_string().contains("connect surreal db"));
    }

    #[tokio::test]
    async fn runtime_sdk_surreal_kv_constructor_builds() {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system clock should be after epoch")
            .as_nanos();
        let path = env::temp_dir().join(format!("stasis-surrealkv-{nanos}"));
        let path_str = path.to_string_lossy().into_owned();

        let runtime = RuntimeSdk::surreal_kv(path_str, "stasis", "runtime")
            .await
            .expect("surreal-kv runtime should build");
        assert!(matches!(runtime.runtime(), RuntimeComposition::Surreal(_)));

        drop(runtime);
        let _ = fs::remove_dir_all(path);
    }
}