cortexkit-bus-naming 0.3.1

Subject, stream, bucket, consumer and grant naming rules for the CortexKit message plane
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
use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;
use std::time::Duration;

use crate::{validate_consumer, AccountNames, ConsumerSpec, LimitError, NamingError};

/// One entry of the event-consumer table: a module allowed to read a filtered
/// slice of other modules' events through its own durable. Filters are relative
/// to `ck.{account}.`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EventConsumer {
    pub module_id: &'static str,
    pub durable: &'static str,
    pub filter_subjects: &'static [&'static str],
}

impl EventConsumer {
    /// Uses the same module-durable namespace as the flow engine's `m_basal`.
    pub fn durable_name(&self) -> Result<String, NamingError> {
        AccountNames::module_consumer_name(self.module_id)
    }
}

/// Who may read another module's events is a security decision, reviewed in
/// code. Runtime configuration must not extend this closed table or its filters.
pub const EVENT_CONSUMERS: &[EventConsumer] = &[
    EventConsumer {
        module_id: "prefrontal-core",
        durable: "m_prefrontal-core",
        filter_subjects: &[
            "event.broca.>",
            "event.basal.flow_instance_created.v1",
            "event.basal.flow_instance_extended.v1",
            "event.basal.flow_instance_ended.v1",
            "event.basal.flow_instance_expired.v1",
        ],
    },
    EventConsumer {
        module_id: "astrocyte",
        durable: "m_astrocyte",
        filter_subjects: &[
            "event.insula.>",
            "event.broca.step.finished.v1",
            "event.thalamus-harness.step.finished.v1",
            "event.thalamus.step.finished.v1",
            "event.thalamus-pi.step.finished.v1",
        ],
    },
    EventConsumer {
        module_id: "prefrontal-routing",
        durable: "m_prefrontal-routing",
        filter_subjects: &[
            "event.insula.>",
            "event.broca.step.finished.v1",
            "event.thalamus-harness.step.finished.v1",
        ],
    },
    EventConsumer {
        module_id: "magic-context",
        durable: "m_magic-context",
        filter_subjects: &[
            "event.thalamus-harness.compaction.>",
            "event.thalamus.compaction.>",
            "event.thalamus-pi.compaction.>",
            "event.broca.compaction.>",
        ],
    },
    EventConsumer {
        module_id: "thalamus-harness",
        durable: "m_thalamus-harness",
        filter_subjects: &["event.magic-context.compaction.>"],
    },
    EventConsumer {
        module_id: "thalamus",
        durable: "m_thalamus",
        filter_subjects: &["event.magic-context.compaction.>"],
    },
    EventConsumer {
        module_id: "thalamus-pi",
        durable: "m_thalamus-pi",
        filter_subjects: &["event.magic-context.compaction.>"],
    },
    EventConsumer {
        module_id: "broca",
        durable: "m_broca",
        filter_subjects: &["event.magic-context.compaction.>"],
    },
    // Intended for the browser and computer-use module's cursor badge, which
    // it clears when a runner's turn ends; turn starts let it ignore a late end
    // from an older turn. This entry grants the durable EVENT reader only. The
    // bus module derives live-hint subscriptions from these filters, and when
    // to subscribe is the consumer's own behaviour.
    EventConsumer {
        module_id: "cerebellum",
        durable: "m_cerebellum",
        filter_subjects: &[
            "event.thalamus-harness.turn_started.v1",
            "event.thalamus-harness.turn_ended.v1",
            "event.thalamus-pi.turn_started.v1",
            "event.thalamus-pi.turn_ended.v1",
        ],
    },
];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AckPolicy {
    Explicit,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeliverPolicy {
    All,
}

/// Configuration ck-bus bootstrap uses to create a durable pull reader of module
/// events. Every reader, including the flow engine's `m_basal`, gets the same
/// settings: pull, explicit ack, deliver-all, 30 s ack wait, 1,000 max pending.
///
/// The topology-only `ConsumerSpec` stays unchanged for existing callers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModuleEventConsumerSpec {
    pub consumer: ConsumerSpec,
    pub pull: bool,
    pub ack_policy: AckPolicy,
    pub deliver_policy: DeliverPolicy,
    pub ack_wait: Duration,
    pub max_ack_pending: i64,
}

/// Bootstrap policy for reliable command readers and bounded dead-letter diagnostics.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DeliveryConsumerSpec {
    pub consumer: ConsumerSpec,
    pub pull: bool,
    pub ack_policy: AckPolicy,
    pub deliver_policy: DeliverPolicy,
    pub ack_wait: Duration,
    /// -1 is unlimited: the application owns terminal disposition.
    pub max_deliver: i64,
    pub max_ack_pending: i64,
}

/// Core owns distinct module durables on INBOX and CORE_WORK. Diagnostics use
/// `c_ckbus_dead` on each dead-letter stream, never an agent stream.
pub fn delivery_consumer_specs(
    account: &AccountNames,
) -> Result<Vec<DeliveryConsumerSpec>, crate::LimitError> {
    let names = account.streams();
    let specs = [
        (
            names.inbox.clone(),
            "m_prefrontal-core",
            account.inbox_bindings(),
            1,
        ),
        (
            names.core_work.clone(),
            "m_prefrontal-core",
            account.core_work_bindings(),
            1,
        ),
        (
            names.effect_dead.clone(),
            "c_ckbus_dead",
            vec![account.effect_dead()],
            1_000,
        ),
        (
            names.delivery_dead.clone(),
            "c_ckbus_dead",
            vec![account.delivery_dead()],
            1_000,
        ),
    ]
    .into_iter()
    .map(
        |(stream, durable, filter_subjects, max_ack_pending)| DeliveryConsumerSpec {
            consumer: ConsumerSpec {
                stream,
                durable: durable.into(),
                filter_subjects,
            },
            pull: true,
            ack_policy: AckPolicy::Explicit,
            deliver_policy: DeliverPolicy::All,
            ack_wait: Duration::from_secs(30),
            max_deliver: -1,
            max_ack_pending,
        },
    )
    .collect::<Vec<_>>();
    crate::validate_consumers(
        &specs
            .iter()
            .map(|spec| spec.consumer.clone())
            .collect::<Vec<_>>(),
        &crate::shipped_streams(account),
    )?;
    Ok(specs)
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventConsumerError {
    Naming(NamingError),
    Limits(LimitError),
    DuplicateModule(&'static str),
    DuplicateDurable(&'static str),
    DurableMismatch(&'static str),
    InvalidFilters(String),
}

impl fmt::Display for EventConsumerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Naming(error) => error.fmt(f),
            Self::Limits(error) => error.fmt(f),
            Self::DuplicateModule(id) => write!(f, "duplicate event-consumer module {id:?}"),
            Self::DuplicateDurable(name) => write!(f, "duplicate event-consumer durable {name:?}"),
            Self::DurableMismatch(id) => write!(f, "event-consumer durable must be m_{id}"),
            Self::InvalidFilters(id) => {
                write!(
                    f,
                    "event-consumer {id:?} needs nonempty, non-overlapping filters under event."
                )
            }
        }
    }
}

impl Error for EventConsumerError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Naming(error) => Some(error),
            Self::Limits(error) => Some(error),
            _ => None,
        }
    }
}

/// The flow engine's broad event reader, using the same pull settings as the
/// filtered readers. Bootstrap owns creation; grants only permit durable reads.
pub fn flow_engine_consumer_spec(
    account: &AccountNames,
    module_id: &str,
) -> Result<ModuleEventConsumerSpec, EventConsumerError> {
    module_event_spec(account, module_id, &["event.>"])
}

/// One bootstrap spec for every reviewed reader, scoped to this account.
pub fn event_consumer_specs(
    account: &AccountNames,
) -> Result<Vec<ModuleEventConsumerSpec>, EventConsumerError> {
    validate_table(EVENT_CONSUMERS)?;
    EVENT_CONSUMERS
        .iter()
        .map(|entry| module_event_spec(account, entry.module_id, entry.filter_subjects))
        .collect()
}

fn validate_table(entries: &[EventConsumer]) -> Result<(), EventConsumerError> {
    let mut modules = BTreeSet::new();
    let mut durables = BTreeSet::new();
    for entry in entries {
        if !modules.insert(entry.module_id) {
            return Err(EventConsumerError::DuplicateModule(entry.module_id));
        }
        if !durables.insert(entry.durable) {
            return Err(EventConsumerError::DuplicateDurable(entry.durable));
        }
        if entry.durable_name().map_err(EventConsumerError::Naming)? != entry.durable {
            return Err(EventConsumerError::DurableMismatch(entry.module_id));
        }
        validate_filters(entry.module_id, entry.filter_subjects)?;
    }
    Ok(())
}

fn validate_filters(module_id: &str, filters: &[&str]) -> Result<(), EventConsumerError> {
    if filters.is_empty()
        || filters
            .iter()
            .any(|filter| !filter.starts_with("event.") || filter.len() == "event.".len())
    {
        return Err(EventConsumerError::InvalidFilters(module_id.to_owned()));
    }
    // NATS rejects overlapping filters on one durable, including duplicates.
    // Check each module's static list without comparing different consumers.
    for (index, filter) in filters.iter().enumerate() {
        for previous in filters.iter().take(index) {
            if crate::limits::subject_filters_overlap(previous, filter)
                .map_err(EventConsumerError::Limits)?
            {
                return Err(EventConsumerError::InvalidFilters(module_id.to_owned()));
            }
        }
    }
    Ok(())
}

fn module_event_spec(
    account: &AccountNames,
    module_id: &str,
    filters: &[&str],
) -> Result<ModuleEventConsumerSpec, EventConsumerError> {
    validate_filters(module_id, filters)?;
    let consumer = ConsumerSpec {
        durable: AccountNames::module_consumer_name(module_id)
            .map_err(EventConsumerError::Naming)?,
        stream: account.streams().event.clone(),
        filter_subjects: filters
            .iter()
            .map(|filter| format!("ck.{}.{filter}", account.account()))
            .collect(),
    };
    validate_consumer(&consumer, &crate::shipped_streams(account))
        .map_err(EventConsumerError::Limits)?;
    Ok(ModuleEventConsumerSpec {
        consumer,
        pull: true,
        ack_policy: AckPolicy::Explicit,
        deliver_policy: DeliverPolicy::All,
        ack_wait: Duration::from_secs(30),
        max_ack_pending: 1_000,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn event_consumer_table_rejects_duplicate_modules() {
        let entry = EVENT_CONSUMERS[0];
        assert_eq!(
            validate_table(&[
                entry,
                EventConsumer {
                    durable: "m_other",
                    ..entry
                }
            ]),
            Err(EventConsumerError::DuplicateModule("prefrontal-core"))
        );
    }

    #[test]
    fn event_consumer_table_rejects_duplicate_durables() {
        let entry = EVENT_CONSUMERS[0];
        assert_eq!(
            validate_table(&[
                entry,
                EventConsumer {
                    module_id: "other",
                    ..entry
                }
            ]),
            Err(EventConsumerError::DuplicateDurable("m_prefrontal-core"))
        );
    }

    #[test]
    fn event_consumer_table_requires_canonical_durable_names() {
        let entry = EventConsumer {
            durable: "m_other",
            ..EVENT_CONSUMERS[0]
        };
        assert_eq!(
            validate_table(&[entry]),
            Err(EventConsumerError::DurableMismatch("prefrontal-core"))
        );
    }

    #[test]
    fn event_consumer_filters_must_be_nonempty_and_under_event() {
        for filters in [
            &[][..],
            &["peer.>"][..],
            &["event"][..],
            &["event."][..],
            &["> "][..],
        ] {
            let entry = EventConsumer {
                filter_subjects: filters,
                ..EVENT_CONSUMERS[0]
            };
            assert!(matches!(
                validate_table(&[entry]),
                Err(EventConsumerError::InvalidFilters(_))
            ));
        }
        let names = AccountNames::derive("box_readers").unwrap();
        assert!(module_event_spec(&names, "reader", &["event.broca.>.run"]).is_err());
    }

    #[test]
    fn event_consumer_filters_refuse_overlap_within_one_module() {
        let names = AccountNames::derive("box_readers").unwrap();
        for filters in [
            &["event.insula.>", "event.*.step.finished.v1"][..],
            &["event.*.step.finished.v1", "event.insula.>"][..],
            &["event.runner_a.>", "event.runner_a.step.finished.v1"][..],
            &[
                "event.runner_a.step.finished.v1",
                "event.runner_a.step.finished.v1",
            ][..],
        ] {
            assert_eq!(
                module_event_spec(&names, "reader", filters),
                Err(EventConsumerError::InvalidFilters("reader".into())),
                "{filters:?}"
            );
        }
        assert!(module_event_spec(
            &names,
            "reader",
            &["event.insula.>", "event.runner_a.step.finished.v1"]
        )
        .is_ok());
    }

    #[test]
    fn prefrontal_core_filter_is_exact_for_basal_lifecycle_events() {
        let names = AccountNames::derive("box_readers").unwrap();
        let reader = event_consumer_specs(&names)
            .unwrap()
            .into_iter()
            .find(|spec| spec.consumer.durable == "m_prefrontal-core")
            .expect("prefrontal-core reader is in the reviewed table");

        assert_eq!(
            reader.consumer.filter_subjects,
            [
                "ck.box_readers.event.broca.>",
                "ck.box_readers.event.basal.flow_instance_created.v1",
                "ck.box_readers.event.basal.flow_instance_extended.v1",
                "ck.box_readers.event.basal.flow_instance_ended.v1",
                "ck.box_readers.event.basal.flow_instance_expired.v1",
            ]
        );
    }
}