cordis-core 0.0.4

A typed, scope-based plugin runtime inspired by Cordis
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
# cordis-rs

A typed, scope-based asynchronous plugin runtime inspired by Cordis.

- **MSRV:** Rust 1.85
- **Edition:** Rust 2024
- **Status:** production-core complete; public API remains pre-1.0 (`0.0.x`)

The public API keeps Cordis' context, service, event, plugin and automatic
cleanup model, while replacing Proxy/string-key behavior with Rust types,
`Arc`, native async traits and explicit activation state.

## Core mapping

| Cordis / TypeScript | cordis-rs |
|---|---|
| `ctx.database` | `ctx.get::<DatabaseKey>()?` or an extension trait |
| string service key | `ServiceKey` (`TypeId` internally) |
| declaration merging | framework-specific extension traits |
| string event | concrete Rust event type |
| `inject: ['database']` | `Dependency::required::<DatabaseKey>()` |
| optional injection | `Dependency::optional::<CacheKey>()` |
| disposer function | activation-owned reverse async cleanup stack |
| plugin fork | persistent `PluginHandle` + replaceable activation |
| service epoch | per-service generation + dependency snapshot |

## Plugin API

`Plugin` and `Resource` use native Rust async methods. Plugin authors do not
need `async-trait`.

```rust
use std::sync::Arc;
use cordis_core::{Dependency, Plugin, PluginContext, Result};

struct FeatureConfig {
    greeting: String,
}

struct FeaturePlugin;

impl Plugin for FeaturePlugin {
    type Config = FeatureConfig;

    fn name(&self) -> &'static str {
        "feature"
    }

    fn dependencies(&self) -> Vec<Dependency> {
        Vec::new()
    }

    async fn apply(
        &self,
        ctx: PluginContext,
        config: Arc<Self::Config>,
    ) -> Result<()> {
        println!("{}", config.greeting);
        ctx.defer(|| async {
            println!("feature activation disposed");
            Ok(())
        })?;
        Ok(())
    }
}
```

The caller still passes an owned configuration:

```rust
# use cordis_core::{App, Result};
# use std::sync::Arc;
# struct FeatureConfig { greeting: String }
# struct FeaturePlugin;
# impl cordis_core::Plugin for FeaturePlugin {
#   type Config = FeatureConfig;
#   fn name(&self) -> &'static str { "feature" }
#   async fn apply(&self, _: cordis_core::PluginContext, _: Arc<Self::Config>) -> Result<()> { Ok(()) }
# }
# async fn example() -> Result<()> {
let app = App::new();
let plugin = app.install(
    FeaturePlugin,
    FeatureConfig { greeting: "hello".into() },
).await?;
plugin.wait_active().await?;
# plugin.dispose().await?;
# Ok(())
# }
```

Internally the configuration becomes `Arc<Config>`, so reload works without
requiring `Config: Clone`.

## Typed services

A key type describes the value type independently of its runtime name:

```rust
use std::sync::Arc;
use cordis_core::{Plugin, PluginContext, Result, ServiceKey};

trait Database: Send + Sync {
    fn name(&self) -> &'static str;
}

struct DatabaseKey;
impl ServiceKey for DatabaseKey {
    type Value = dyn Database;
    const NAME: &'static str = "database";
}

struct DatabasePlugin;
impl Plugin for DatabasePlugin {
    type Config = Arc<dyn Database>;

    fn name(&self) -> &'static str { "database-provider" }

    async fn apply(
        &self,
        ctx: PluginContext,
        database: Arc<Self::Config>,
    ) -> Result<()> {
        // Config is Arc<Arc<dyn Database>> here; clone the inner Arc.
        ctx.provide::<DatabaseKey>(database.as_ref().clone())?;
        Ok(())
    }
}
```

A service registration is staged during `apply`. It becomes externally visible
only after `apply` succeeds. The providing activation can see its own staged
service. Listener and query registrations are staged in the same way.

`ServiceHandle<K>` supports:

```rust
use std::sync::Arc;

use cordis_core::{App, Plugin, PluginContext, Result, ServiceHandle, ServiceKey};

struct ConfigKey;
impl ServiceKey for ConfigKey {
    type Value = usize;
    const NAME: &'static str = "config";
}

struct Provider;
impl Plugin for Provider {
    type Config = Arc<tokio::sync::Mutex<Option<ServiceHandle<ConfigKey>>>>;

    fn name(&self) -> &'static str {
        "provider"
    }

    async fn apply(&self, ctx: PluginContext, slot: Arc<Self::Config>) -> Result<()> {
        let handle = ctx.provide::<ConfigKey>(Arc::new(1))?;
        *slot.lock().await = Some(handle);
        Ok(())
    }
}

# fn main() {
#     tokio::runtime::Runtime::new().unwrap().block_on(async {
let app = App::new();
let slot = Arc::new(tokio::sync::Mutex::new(None));
let provider = app.install(Provider, slot.clone()).await.unwrap();
provider.wait_active().await.unwrap();

let guard = slot.lock().await;
let handle = guard.as_ref().unwrap();
handle.replace(Arc::new(2)).unwrap(); // new generation; dependents reload
handle.touch().unwrap();              // same value, new generation
handle.remove();                      // dependents reconcile
drop(guard);
provider.dispose().await.unwrap();
#     });
# }
```

Dropping a handle does not remove the registration; the activation owns it.

### Async trait-object services

Native `async fn` in traits is not dyn-compatible on Rust 1.85. A service used
as `dyn Database` should expose `BoxFuture`, or let the service crate choose
`async-trait` itself:

```rust
use futures::future::BoxFuture;
use cordis_core::Result;

trait AsyncDatabase: Send + Sync {
    fn health(&self) -> BoxFuture<'_, Result<()>>;
}
```

The runtime itself does not depend on `async-trait`.

## Suspension and reload

A plugin registration is persistent; its activation is disposable.

```text
required missing -> Suspended
required appears -> Starting -> Active
required removed -> Stopping -> Suspended
required/optional generation changed -> Stopping -> Starting -> Active
apply failed -> Failed
manual retry/reload -> Starting
handle disposed -> Disposed
```

Declare dependencies on the plugin:

```rust
use std::sync::Arc;

use cordis_core::{App, Dependency, Plugin, PluginContext, PluginStatus, Result, ServiceKey};

struct DatabaseKey;
impl ServiceKey for DatabaseKey {
    type Value = usize;
    const NAME: &'static str = "database";
}

struct CacheKey;
impl ServiceKey for CacheKey {
    type Value = usize;
    const NAME: &'static str = "cache";
}

struct Feature;
impl Plugin for Feature {
    type Config = ();

    fn name(&self) -> &'static str {
        "feature"
    }

    fn dependencies(&self) -> Vec<Dependency> {
        vec![
            Dependency::required::<DatabaseKey>(),
            Dependency::optional::<CacheKey>(),
        ]
    }

    async fn apply(&self, ctx: PluginContext, _config: Arc<Self::Config>) -> Result<()> {
        // optional services may be missing at activation time
        let _cache = ctx.try_get::<CacheKey>();
        ctx.get::<DatabaseKey>()?;
        Ok(())
    }
}

# fn main() {
#     tokio::runtime::Runtime::new().unwrap().block_on(async {
let app = App::new();
let handle = app.install(Feature, ()).await.unwrap();
// required `database` is missing -> Suspended; optional `cache` is tolerated
assert!(matches!(
    handle.status(),
    PluginStatus::Suspended { missing } if &*missing == ["database"]
));
#     });
# }
```

Semantics:

- missing **required** service suspends the plugin without running `apply`;
- required service appearance activates it;
- required service removal disposes the activation and suspends it;
- required service replacement/touch reloads it;
- optional appearance, removal and generation change also reload it;
- unrelated service changes do not reload it;
- a failed dependency snapshot does not spin-retry;
- dependency change or `PluginHandle::retry()` can retry a failure.

`install()` returns a handle even when the initial state is `Suspended` or
`Failed`. Registration errors such as installing after shutdown still return
`Err`.

```rust
use std::sync::Arc;

use cordis_core::{App, Plugin, PluginContext, PluginStatus, Result};

struct MyPlugin;
impl Plugin for MyPlugin {
    type Config = ();

    fn name(&self) -> &'static str {
        "my-plugin"
    }

    async fn apply(&self, _ctx: PluginContext, _config: Arc<Self::Config>) -> Result<()> {
        Ok(())
    }
}

# fn main() {
#     tokio::runtime::Runtime::new().unwrap().block_on(async {
let app = App::new();
let handle = app.install(MyPlugin, ()).await.unwrap();

match handle.status() {
    PluginStatus::Suspended { missing } => println!("missing: {missing:?}"),
    PluginStatus::Failed { message, .. } => eprintln!("failed: {message}"),
    _ => {}
}

let mut statuses = handle.subscribe();
handle.wait_active().await.unwrap();
handle.reload().await.unwrap();
assert!(statuses.changed().await.is_ok()); // reload moved through Stopping/Starting
handle.retry().await.unwrap();
handle.dispose().await.unwrap();
#     });
# }
```

## Events and queries

```rust
use std::sync::Arc;

use cordis_core::{App, Plugin, PluginContext, Result};

#[derive(Debug)]
struct Message {
    text: &'static str,
}

struct Chat;
impl Plugin for Chat {
    type Config = ();

    fn name(&self) -> &'static str {
        "chat"
    }

    async fn apply(&self, ctx: PluginContext, _config: Arc<Self::Config>) -> Result<()> {
        ctx.on::<Message, _, _>(|_ctx, message| async move {
            println!("received: {}", message.text);
            Ok(())
        })?;
        Ok(())
    }
}

# fn main() {
#     tokio::runtime::Runtime::new().unwrap().block_on(async {
let app = App::new();
let handle = app.install(Chat, ()).await.unwrap();
handle.wait_active().await.unwrap();

let ctx = app.context();
ctx.emit(Message { text: "serial" }).await.unwrap(); // serial, registration order
ctx.parallel(Message { text: "parallel" }).await.unwrap(); // concurrent
handle.dispose().await.unwrap();
#     });
# }
```

Ignoring `ListenerHandle` does not unregister the listener. Use
`handle.cancel()` for early removal; activation disposal removes it
automatically.

Typed query handlers return `Option<Response>`. Queries run in registration
order and stop at the first `Some` or error.

## Cleanup guarantees

- registrations belong to the current activation;
- cleanup runs in reverse registration order;
- cleanup continues after errors and returns the first cleanup error;
- tasks/resources start only when the activation commits;
- task cleanup signals its `CancellationToken`, waits five seconds, then aborts;
- failed `apply` rolls back every staged effect;
- apply, reload, retry and dispose transitions are serialized;
- concurrent dispose callers share one cleanup execution and result;
- declared dependency graphs unload consumers before providers;
- plugin/task/handler/cleanup panics become ordinary runtime errors.

## Compatibility alias

`PluginScope` remains a type alias for `PluginHandle` during the early API
transition. New code should use `PluginHandle`.

## Run the examples

Runnable examples live under `examples/`:

```bash
cargo run --example minimal            # provider + consumer with dependency injection
cargo run --example suspension_reload  # suspend/activate/reload/replace lifecycle
cargo run --example events_queries     # serial/parallel events, first-answer queries
cargo run --example tasks_resources    # cooperative tasks and managed resources
cargo run --example extension_trait    # trait-object services and extension traits
cargo run --example isolation_lifecycle # isolate(), Ready/Fork/Dispose events
```

## Implemented contract tests

Black-box tests live under `tests/` and cover services, events, queries,
cleanup, tasks/resources, compile-time constraints, staging, suspension,
required/optional reload, replacement, unrelated changes, failure retry and
non-Clone configuration reuse.

```bash
cargo fmt --check
cargo clippy --all-targets --all-features -- -D warnings
cargo build --examples
cargo test --all-features
cargo test --doc
```

More implementation detail is documented in
[`docs/suspension-reload.md`](docs/suspension-reload.md).

## Production facilities

- `Plugin::provides()` supplies static provider metadata; cycles are rejected
  during registration and provider transitions quiesce transitive consumers in
  reverse topological order.
- Service revisions are debounced for one millisecond and reconciled from the
  latest generation snapshot, coalescing bursts without losing final state.
- `Context::isolate::<K>()` and `PluginContext::isolate::<K>()` create a fresh
  typed slot for `K` while inheriting all other services.
- `Ready`, `Fork`, and `Dispose` are typed lifecycle events.
- `PluginHandle::diagnostics()` returns timestamped status history.
- `ErasedPlugin` and `App::install_erased()` provide an object-safe registry
  boundary without imposing a serialization format.

## Intentional non-goals

JSON/TOML deserialization belongs to the framework above this crate. Named
runtime service qualifiers are also omitted: use distinct `ServiceKey` types or
typed isolation, which preserves compile-time result types. Dependency-graph
ordering requires providers to accurately implement `Plugin::provides()`.