Skip to main content

bynk_ide/
architecture.rs

1//! #851: the architecture-model query — a whole-project map of contexts and
2//! adapters, their `consumes` edges, and the capabilities/providers/services/
3//! agents each one binds, for the "Show Architecture Map" VS Code webview.
4//! The macro counterpart to #846's per-handler sequence diagram: where that
5//! query is file-scoped and cursor-anchored, this one is **project-scoped** —
6//! every span here is paired with the project-relative file it belongs to
7//! (a unit's declarations may span several files, per `unit_sources`), so a
8//! wire layer can open the right file on click-to-code rather than assuming
9//! the request's own document.
10//!
11//! Citation correction (found during implementation of #851; recorded in
12//! `design/pending/architecture-map-851.md`): the issue proposed this as "a
13//! pure, read-only query over the binding index and call graph"
14//! (`bynk-check/src/index.rs`). That index has no `Context`/`Adapter` symbol
15//! kind and its call graph does not carry `consumes` edges — its own comment
16//! notes cross-context dispatch is "the one uncovered relation". The actual
17//! source, used here exactly as `sequence::Builder::classify_cross_context`
18//! already does, is [`ContextSequenceInfo::cross_context`] for resolved
19//! consumed-context names (aliasing applied) plus a re-parse of each unit's
20//! own snapshot text for its local declarations and raw `consumes` clauses —
21//! there is no retained AST after a round, the same constraint
22//! `sequence_request`/`documentation_request` re-parse against.
23//!
24//! Capability binding (Decision C: show binding, defer residency): a braced
25//! `consumes U { Cap, … }` selection flattens `Cap` into the consumer's own
26//! namespace, so each selected capability is recorded directly on the
27//! consuming node (not only as an edge label) — this is what makes the
28//! built-in `consumes bynk { Clock }` binding visible on a single-context
29//! project even though the synthetic `bynk` unit has no project file and so
30//! never becomes a node itself (an edge to it would dangle); see
31//! [`architecture_model`]'s node-name filter. A whole-unit consumes (no
32//! braces) grants qualified access to every exported capability but flattens
33//! none of them, so it contributes an edge only, unlabelled — matching the
34//! issue's "labelled with selected capabilities where braced".
35//!
36//! This is an editor view, not a system-model item (crate-hygiene B4, #3012).
37//! It is built over a recovering parse of unsaved editor text, so its
38//! `SourceUnit`/`CommonsItem` matches fall under M-1's domain clause (the
39//! system-model ADR): the consumer doesn't hold a certified program. A fact
40//! the model carries, such as a handler kind or a protocol, is read from the
41//! model.
42
43use std::collections::{HashMap, HashSet};
44use std::path::PathBuf;
45
46use bynk_check::analysis::ContextSequenceInfo;
47use bynk_check::architecture_facts::{
48    ArchitectureFacts, CallTarget, DeliveryKind, FactSite, MemberFact, MemberKind,
49};
50use bynk_syntax::ast::*;
51use bynk_syntax::span::Span;
52
53/// A declaration site: which project-relative file it lives in, and its span
54/// within that file's text. Project-scoped models (unlike the file-scoped
55/// `sequence`/`documentation` ones) always need both — a node's members can
56/// come from different files of the same multi-file unit.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct Located {
59    pub file: PathBuf,
60    pub span: Span,
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum NodeKind {
65    Context,
66    Adapter,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum CapabilityOrigin {
71    /// A `capability { … }` declared directly in this unit.
72    Local,
73    /// Flattened in via a braced `consumes <from> { <name>, … }` selection.
74    Consumed { from: String },
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ArchCapability {
79    pub name: String,
80    pub origin: CapabilityOrigin,
81    pub loc: Located,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct ArchProvider {
86    pub capability: String,
87    pub provider_name: String,
88    /// `provides Cap = Name` with no brace block — supplied by an adapter's
89    /// external binding rather than a Bynk body (`ProviderDecl::external`).
90    pub external: bool,
91    pub loc: Located,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct ArchService {
96    pub name: String,
97    pub handler_count: usize,
98    pub loc: Located,
99    /// Model-diagrams slice 4: how the service is reached — `call` (no
100    /// `from`), `http`, `cron`, `queue`, `websocket`, `events` or `email` —
101    /// for the architecture map's ingress ports.
102    pub protocol: &'static str,
103    /// Model-diagrams slice 4: the actors its handlers admit (`by Visitor`,
104    /// `by who: A | B`), from the service-level `default_by` and each
105    /// handler's own `by`, deduplicated and sorted — the outside world drawn
106    /// around the system boundary.
107    pub actors: Vec<String>,
108}
109
110/// A service's protocol, as the architecture model names it.
111fn protocol_name(p: &ServiceProtocol) -> &'static str {
112    match p {
113        ServiceProtocol::Call => "call",
114        ServiceProtocol::Http => "http",
115        ServiceProtocol::Cron => "cron",
116        ServiceProtocol::Queue { .. } => "queue",
117        ServiceProtocol::WebSocket { .. } => "websocket",
118        ServiceProtocol::Events { .. } => "events",
119        ServiceProtocol::Email { .. } => "email",
120    }
121}
122
123/// The actors a service's handlers admit: each handler's own `by`, or the
124/// service's `default_by` where it has none; deduplicated and sorted.
125fn service_actors(s: &ServiceDecl) -> Vec<String> {
126    // A handler's own `by` replaces the service default rather than adding to
127    // it (as `sequence.rs` resolves it), so the default counts only for the
128    // handlers that inherit it.
129    let mut actors: Vec<String> = s
130        .handlers
131        .iter()
132        .filter_map(|h| h.by_clause.as_ref().or(s.default_by.as_ref()))
133        .flat_map(|by| by.actors.iter().map(|a| a.name.clone()))
134        .collect();
135    actors.sort();
136    actors.dedup();
137    actors
138}
139
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct ArchAgent {
142    pub name: String,
143    pub handler_count: usize,
144    pub loc: Located,
145    /// Model-diagrams slice 5: the key, as written (`id: ClientId`).
146    pub key: String,
147    /// Model-diagrams slice 5: the `store` field names, in declaration order.
148    pub state: Vec<String>,
149}
150
151/// One context/adapter node — the "services in, agents below" grouping the
152/// design notes describe, rendered as a single box with click-to-expand
153/// members.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct ArchNode {
156    /// The unit's qualified name (`demo.app`, `tokens`).
157    pub name: String,
158    pub kind: NodeKind,
159    /// The unit-name declaration site — the node box's own click target.
160    pub loc: Located,
161    pub capabilities: Vec<ArchCapability>,
162    pub providers: Vec<ArchProvider>,
163    pub services: Vec<ArchService>,
164    pub agents: Vec<ArchAgent>,
165    /// #3583: per handler, the capabilities it requires through `given`.
166    pub uses: Vec<ArchHandlerUses>,
167}
168
169/// #3583: the handler (or provider operation) an event site or a use belongs to.
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct ArchMember {
172    /// The declaring unit's qualified name.
173    pub unit: String,
174    pub kind: MemberKind,
175    /// The service, agent or provider name.
176    pub container: String,
177    /// The handler's request descriptor, or a provider operation's name.
178    pub handler: String,
179    pub loc: Located,
180}
181
182/// #3583: one capability a handler requires through `given`.
183#[derive(Debug, Clone, PartialEq, Eq)]
184pub struct ArchUse {
185    pub capability: String,
186    /// The unit that declares the capability (this unit, a consumed one, or `bynk`).
187    pub from: Option<String>,
188    /// Written on the service header (`default_given`), not on the handler.
189    pub inherited: bool,
190    pub loc: Located,
191    /// The suites that `stub` this capability for this unit, one per file.
192    pub stubbed_in: Vec<ArchStub>,
193}
194
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct ArchStub {
197    /// The suite file, project-relative.
198    pub suite: PathBuf,
199    /// The suite's first `stub` of the capability.
200    pub loc: Located,
201}
202
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub struct ArchHandlerUses {
205    pub member: ArchMember,
206    pub uses: Vec<ArchUse>,
207    /// Model-diagrams slice 5: the services and agents the handler calls.
208    pub calls: Vec<ArchCall>,
209}
210
211/// Model-diagrams slice 5: one service or agent a handler calls, at its first
212/// call.
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct ArchCall {
215    pub kind: MemberKind,
216    /// The unit that declares the callee: a consumed context for a service,
217    /// the caller's own unit for an agent.
218    pub unit: String,
219    /// The service or agent name.
220    pub container: String,
221    /// The agent handler dispatched to; `None` for a service call.
222    pub handler: Option<String>,
223    pub loc: Located,
224}
225
226/// #3583: one `Events.emit[E]` call.
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct ArchEmitter {
229    pub member: ArchMember,
230    pub loc: Located,
231}
232
233/// #3583: one `from Events(E)` subscriber's `on event` handler.
234#[derive(Debug, Clone, PartialEq, Eq)]
235pub struct ArchSubscriber {
236    pub member: ArchMember,
237    pub delivery: DeliveryKind,
238    pub loc: Located,
239}
240
241/// #3583: an event type with everything that emits or subscribes to it.
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub struct ArchEvent {
244    /// The context that declares the event.
245    pub owner: String,
246    pub name: String,
247    pub loc: Located,
248    pub emitters: Vec<ArchEmitter>,
249    pub subscribers: Vec<ArchSubscriber>,
250}
251
252/// A directed `consumes` edge between two nodes.
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub struct ArchEdge {
255    pub from: String,
256    pub to: String,
257    /// Selected capability labels (braced form, in source order); empty for
258    /// a whole-unit consumes.
259    pub capabilities: Vec<String>,
260    /// The `consumes` clause's own span, in the consuming (`from`) unit's file.
261    pub loc: Located,
262}
263
264#[derive(Debug, Clone, Default, PartialEq, Eq)]
265pub struct ArchModel {
266    pub nodes: Vec<ArchNode>,
267    pub edges: Vec<ArchEdge>,
268    /// #3583: every declared event, with its emitters and subscribers.
269    pub events: Vec<ArchEvent>,
270}
271
272/// Build the whole-project architecture model.
273///
274/// `unit_sources` and `snapshots` are `Analysis`/`ProjectDiagnostics`'s own
275/// fields (project-relative file lists per unit, and each file's committed
276/// text); `sequence_info` is the same table `bynk/sequenceModel` classifies
277/// against. A unit with no `sequence_info` entry (a `commons`, or the
278/// toolchain's synthetic `bynk` capability surface — excluded from
279/// `unit_sources`, per its own doc) contributes no node; a `consumes` edge
280/// that resolves to such a unit is dropped (nothing to draw an arrow to) but
281/// its selected capabilities are still recorded on the consuming node — see
282/// the module doc. `facts` is the checker's resolved event and `given` view
283/// (#3583).
284pub fn architecture_model(
285    unit_sources: &HashMap<String, Vec<PathBuf>>,
286    snapshots: &HashMap<PathBuf, String>,
287    sequence_info: &HashMap<String, ContextSequenceInfo>,
288    facts: &ArchitectureFacts,
289) -> ArchModel {
290    // Deterministic iteration order (ADR risk: "layout churn" — a `HashMap`
291    // walk shuffles between rounds otherwise).
292    let mut names: Vec<&String> = sequence_info
293        .keys()
294        .filter(|n| unit_sources.contains_key(n.as_str()))
295        .collect();
296    names.sort();
297    let node_names: HashSet<&str> = names.iter().map(|s| s.as_str()).collect();
298
299    let mut nodes = Vec::with_capacity(names.len());
300    let mut edges = Vec::new();
301
302    for name in names {
303        let mut files = unit_sources[name].clone();
304        files.sort();
305
306        let mut kind = None;
307        let mut loc = None;
308        let mut capabilities = Vec::new();
309        let mut providers = Vec::new();
310        let mut services = Vec::new();
311        let mut agents = Vec::new();
312
313        let info = sequence_info.get(name);
314
315        for file in &files {
316            let Some(text) = snapshots.get(file) else {
317                continue;
318            };
319            let Ok(tokens) = bynk_syntax::lexer::tokenize(text) else {
320                continue;
321            };
322            let (unit_opt, _errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
323            let Some(unit) = unit_opt else { continue };
324            let (this_kind, name_span, items, consumes): (
325                NodeKind,
326                Span,
327                &[CommonsItem],
328                &[ConsumesDecl],
329            ) = match &unit {
330                SourceUnit::Context(c) => (NodeKind::Context, c.name.span, &c.items, &c.consumes),
331                SourceUnit::Adapter(a) => (NodeKind::Adapter, a.name.span, &a.items, &a.consumes),
332                SourceUnit::Commons(_) | SourceUnit::Suite(_) => continue,
333            };
334            kind.get_or_insert(this_kind);
335            loc.get_or_insert(Located {
336                file: file.clone(),
337                span: name_span,
338            });
339
340            for item in items {
341                match item {
342                    CommonsItem::Capability(c) => capabilities.push(ArchCapability {
343                        name: c.name.name.clone(),
344                        origin: CapabilityOrigin::Local,
345                        loc: Located {
346                            file: file.clone(),
347                            span: c.name.span,
348                        },
349                    }),
350                    CommonsItem::Provider(p) => providers.push(ArchProvider {
351                        capability: p.capability.name.clone(),
352                        provider_name: p.provider_name.name.clone(),
353                        external: p.external,
354                        loc: Located {
355                            file: file.clone(),
356                            span: p.provider_name.span,
357                        },
358                    }),
359                    CommonsItem::Service(s) => services.push(ArchService {
360                        name: s.name.name.clone(),
361                        handler_count: s.handlers.len(),
362                        loc: Located {
363                            file: file.clone(),
364                            span: s.name.span,
365                        },
366                        protocol: protocol_name(&s.protocol),
367                        actors: service_actors(s),
368                    }),
369                    CommonsItem::Agent(a) => agents.push(ArchAgent {
370                        name: a.name.name.clone(),
371                        handler_count: a.handlers.len(),
372                        loc: Located {
373                            file: file.clone(),
374                            span: a.name.span,
375                        },
376                        key: format!(
377                            "{}: {}",
378                            a.key_name.name,
379                            bynk_syntax::print::type_ref_to_string(&a.key_type)
380                        ),
381                        state: a.store_fields.iter().map(|f| f.name.name.clone()).collect(),
382                    }),
383                    _ => {}
384                }
385            }
386
387            for decl in consumes {
388                let target = info
389                    .and_then(|i| i.cross_context.resolve_prefix(&decl.target.joined()))
390                    .unwrap_or_else(|| decl.target.joined());
391                // #2765: the braces may also name an exported type
392                // (`consumes bynk { TimedOut }`); only capabilities count here.
393                let selected_caps: Vec<&Ident> = decl
394                    .selected
395                    .iter()
396                    .flatten()
397                    .map(|item| &item.name)
398                    .filter(|id| {
399                        info.is_none_or(|i| {
400                            i.cross_context
401                                .consumed_capabilities
402                                .get(&target)
403                                .is_some_and(|m| m.contains_key(&id.name))
404                        })
405                    })
406                    .collect();
407                let cap_labels: Vec<String> =
408                    selected_caps.iter().map(|id| id.name.clone()).collect();
409
410                // A selected capability flattens into the consumer's own
411                // namespace regardless of whether `target` itself becomes a
412                // node (the built-in `bynk` surface never does) — record the
413                // binding on the node either way.
414                {
415                    for id in selected_caps {
416                        capabilities.push(ArchCapability {
417                            name: id.name.clone(),
418                            origin: CapabilityOrigin::Consumed {
419                                from: target.clone(),
420                            },
421                            loc: Located {
422                                file: file.clone(),
423                                span: id.span,
424                            },
425                        });
426                    }
427                }
428
429                // The edge itself is only meaningful between two real nodes —
430                // nothing to draw an arrow to for a synthetic/absent target.
431                if node_names.contains(target.as_str()) {
432                    edges.push(ArchEdge {
433                        from: name.clone(),
434                        to: target,
435                        capabilities: cap_labels,
436                        loc: Located {
437                            file: file.clone(),
438                            span: decl.span,
439                        },
440                    });
441                }
442            }
443        }
444
445        let (Some(kind), Some(loc)) = (kind, loc) else {
446            continue;
447        };
448        // A multi-file unit can declare the same thing more than once across
449        // its files in principle (a redundant `consumes X { Cap }` repeated
450        // in two files of the same context, say) — dedupe by identity, not
451        // by the whole struct (which would keep both copies apart on `loc`
452        // alone), keeping the first (file-sorted, so deterministic) copy.
453        capabilities.sort_by(|a, b| a.name.cmp(&b.name));
454        capabilities.dedup_by(|a, b| a.name == b.name && a.origin == b.origin);
455        providers.sort_by(|a, b| {
456            (&a.capability, &a.provider_name).cmp(&(&b.capability, &b.provider_name))
457        });
458        providers
459            .dedup_by(|a, b| a.capability == b.capability && a.provider_name == b.provider_name);
460        services.sort_by(|a, b| a.name.cmp(&b.name));
461        services.dedup_by(|a, b| a.name == b.name);
462        agents.sort_by(|a, b| a.name.cmp(&b.name));
463        agents.dedup_by(|a, b| a.name == b.name);
464
465        nodes.push(ArchNode {
466            name: name.clone(),
467            kind,
468            loc,
469            capabilities,
470            providers,
471            services,
472            agents,
473            uses: node_uses(name, facts),
474        });
475    }
476
477    // A multi-file unit can carry more than one `consumes` clause naming the
478    // same target across its files (e.g. `consumes X { A }` in one file and
479    // `consumes X { B }` in another) — merge same-`(from, to)` edges into one
480    // rather than drawing two arrows between the same pair of nodes, keeping
481    // the first (file-sorted) edge's own location and the union of every
482    // merged edge's capability labels.
483    edges.sort_by(|a, b| (&a.from, &a.to).cmp(&(&b.from, &b.to)));
484    let mut merged_edges: Vec<ArchEdge> = Vec::with_capacity(edges.len());
485    for edge in edges {
486        match merged_edges
487            .last_mut()
488            .filter(|last: &&mut ArchEdge| last.from == edge.from && last.to == edge.to)
489        {
490            Some(last) => {
491                for cap in edge.capabilities {
492                    if !last.capabilities.contains(&cap) {
493                        last.capabilities.push(cap);
494                    }
495                }
496            }
497            None => merged_edges.push(edge),
498        }
499    }
500    for edge in &mut merged_edges {
501        edge.capabilities.sort();
502    }
503
504    ArchModel {
505        nodes,
506        edges: merged_edges,
507        events: events_of(facts),
508    }
509}
510
511fn located(site: &FactSite) -> Located {
512    Located {
513        file: site.file.clone(),
514        span: site.span,
515    }
516}
517
518fn member_of(m: &MemberFact) -> ArchMember {
519    ArchMember {
520        unit: m.unit.clone(),
521        kind: m.kind,
522        container: m.container.clone(),
523        handler: m.handler.clone(),
524        loc: located(&m.site),
525    }
526}
527
528fn events_of(facts: &ArchitectureFacts) -> Vec<ArchEvent> {
529    facts
530        .events
531        .iter()
532        .map(|e| ArchEvent {
533            owner: e.owner.clone(),
534            name: e.name.clone(),
535            loc: located(&e.site),
536            emitters: e
537                .emitters
538                .iter()
539                .map(|x| ArchEmitter {
540                    member: member_of(&x.member),
541                    loc: located(&x.site),
542                })
543                .collect(),
544            subscribers: e
545                .subscribers
546                .iter()
547                .map(|x| ArchSubscriber {
548                    member: member_of(&x.member),
549                    delivery: x.delivery,
550                    loc: located(&x.site),
551                })
552                .collect(),
553        })
554        .collect()
555}
556
557/// One node's handlers and what each requires through `given`, with the suites
558/// that `stub` each capability (a suite stubs for the unit it targets).
559fn node_uses(unit: &str, facts: &ArchitectureFacts) -> Vec<ArchHandlerUses> {
560    let stubbed_in = |capability: &str| -> Vec<ArchStub> {
561        let mut out: Vec<ArchStub> = Vec::new();
562        for s in facts
563            .stubs
564            .iter()
565            .filter(|s| s.target == unit && s.capability == capability)
566        {
567            if !out.iter().any(|o| o.suite == s.site.file) {
568                out.push(ArchStub {
569                    suite: s.site.file.clone(),
570                    loc: located(&s.site),
571                });
572            }
573        }
574        out
575    };
576    facts
577        .uses
578        .iter()
579        .filter(|h| h.member.unit == unit)
580        .map(|h| ArchHandlerUses {
581            member: member_of(&h.member),
582            uses: h
583                .uses
584                .iter()
585                .map(|u| ArchUse {
586                    capability: u.capability.clone(),
587                    from: u.provider_unit.clone(),
588                    inherited: u.inherited,
589                    loc: located(&u.site),
590                    stubbed_in: stubbed_in(&u.capability),
591                })
592                .collect(),
593            calls: h
594                .calls
595                .iter()
596                .map(|c| match &c.target {
597                    CallTarget::Service { unit, service } => ArchCall {
598                        kind: MemberKind::Service,
599                        unit: unit.clone(),
600                        container: service.clone(),
601                        handler: None,
602                        loc: located(&c.site),
603                    },
604                    CallTarget::Agent { agent, handler } => ArchCall {
605                        kind: MemberKind::Agent,
606                        unit: unit.to_string(),
607                        container: agent.clone(),
608                        handler: Some(handler.clone()),
609                        loc: located(&c.site),
610                    },
611                })
612                .collect(),
613        })
614        .collect()
615}
616
617#[cfg(test)]
618mod tests {
619    use super::*;
620    use std::fs;
621
622    fn setup_project(test_name: &str, files: &[(&str, &str)]) -> PathBuf {
623        let root = std::env::temp_dir().join(format!(
624            "bynk-ide-architecture-test-{test_name}-{}",
625            std::process::id()
626        ));
627        let _ = fs::remove_dir_all(&root);
628        fs::create_dir_all(&root).expect("create test root");
629        for (rel, contents) in files {
630            let p = root.join(rel);
631            if let Some(parent) = p.parent() {
632                fs::create_dir_all(parent).expect("create parent");
633            }
634            fs::write(&p, contents).expect("write file");
635        }
636        root
637    }
638
639    fn build_model(diag: &crate::ProjectDiagnostics) -> ArchModel {
640        let snapshots: HashMap<PathBuf, String> = diag
641            .files
642            .iter()
643            .map(|f| (f.source_path.clone(), f.text.clone()))
644            .collect();
645        architecture_model(
646            &diag.unit_sources,
647            &snapshots,
648            &diag.sequence_info,
649            &diag.architecture_facts,
650        )
651    }
652
653    // -- Fixture: examples/rate-limiter's single context, self-contained (not
654    // -- read from `examples/` — same convention as `sequence.rs`'s tests).
655    // -- Its only consumes clause pulls a built-in capability (`Clock`) from
656    // -- the synthetic `bynk` surface — the case with no edge, only a bound
657    // -- capability.
658    const RATELIMIT_SRC: &str = r#"context ratelimit
659
660consumes bynk { Clock }
661
662type ClientId = String where NonEmpty
663
664type RateView = {
665  allowed:   Bool,
666  remaining: Int,
667  resetAt:   Int,
668}
669
670agent Limiter {
671  key client: ClientId
672
673  store count: Cell[Int]
674
675  on call hit(now: Int) -> Effect[RateView] {
676    let _ <- count.update((c) => c + 1)
677    RateView { allowed: count < 10, remaining: 10 - count, resetAt: now }
678  }
679}
680
681service api from http {
682  on GET("/check/:client") (client: ClientId) -> Effect[HttpResult[RateView]] by Visitor given Clock {
683    let now  <- Clock.now()
684    let view <- Limiter(client).hit(now.toEpochMillis())
685    if view.allowed {
686      Ok(view)
687    } else {
688      TooManyRequests("rate limit exceeded")
689    }
690  }
691}
692"#;
693
694    /// #2765: a type in the braces (`consumes bynk { Clock, TimedOut }`) is
695    /// not a capability binding.
696    #[test]
697    fn a_selected_type_is_not_a_consumed_capability() {
698        let src = RATELIMIT_SRC.replace(
699            "consumes bynk { Clock }",
700            "consumes bynk { Clock, TimedOut }",
701        );
702        let root = setup_project("type-selection", &[("ratelimit.bynk", &src)]);
703        let diag = crate::testkit::diagnose_project(&root);
704        let model = build_model(&diag);
705        let names: Vec<&str> = model.nodes[0]
706            .capabilities
707            .iter()
708            .map(|c| c.name.as_str())
709            .collect();
710        assert_eq!(names, vec!["Clock"]);
711    }
712
713    #[test]
714    fn single_context_binds_a_builtin_capability_with_no_dangling_edge() {
715        let root = setup_project("ratelimit", &[("ratelimit.bynk", RATELIMIT_SRC)]);
716        let diag = crate::testkit::diagnose_project(&root);
717        let model = build_model(&diag);
718
719        assert_eq!(
720            model.nodes.len(),
721            1,
722            "the built-in bynk surface is not a node"
723        );
724        let node = &model.nodes[0];
725        assert_eq!(node.name, "ratelimit");
726        assert_eq!(node.kind, NodeKind::Context);
727        assert_eq!(node.loc.file, PathBuf::from("ratelimit.bynk"));
728
729        assert_eq!(node.agents.len(), 1);
730        assert_eq!(node.agents[0].name, "Limiter");
731        assert_eq!(node.agents[0].handler_count, 1);
732
733        assert_eq!(node.services.len(), 1);
734        assert_eq!(node.services[0].name, "api");
735        assert_eq!(node.services[0].handler_count, 1);
736
737        assert_eq!(
738            node.capabilities,
739            vec![ArchCapability {
740                name: "Clock".to_string(),
741                origin: CapabilityOrigin::Consumed {
742                    from: "bynk".to_string()
743                },
744                loc: node.capabilities[0].loc.clone(),
745            }],
746            "Clock is bound via the built-in consumes, not locally declared"
747        );
748
749        assert!(
750            model.edges.is_empty(),
751            "no node exists for the synthetic bynk surface, so no edge is drawn to it"
752        );
753    }
754
755    // -- Fixture: two real contexts, a braced selected-capability consumes —
756    // -- the shape the issue's Done-when line calls for explicitly.
757    const PROVIDER_SRC: &str = r#"context platformtime
758
759exports capability { Clock }
760
761capability Clock {
762  fn now() -> Effect[Int]
763}
764
765provides Clock = SystemClock {
766  fn now() -> Effect[Int] {
767    0
768  }
769}
770"#;
771    const CONSUMER_SRC: &str = r#"context ops.jobs
772
773consumes platformtime { Clock }
774
775service run {
776  on call() -> Effect[Int] by Caller given Clock {
777    let now <- Clock.now()
778    now
779  }
780}
781"#;
782
783    #[test]
784    fn two_context_project_gets_a_labelled_consumes_edge() {
785        let root = setup_project(
786            "twoctx",
787            &[
788                ("platformtime.bynk", PROVIDER_SRC),
789                ("jobs.bynk", CONSUMER_SRC),
790            ],
791        );
792        let diag = crate::testkit::diagnose_project(&root);
793        let model = build_model(&diag);
794
795        let names: Vec<&str> = model.nodes.iter().map(|n| n.name.as_str()).collect();
796        assert_eq!(names, vec!["ops.jobs", "platformtime"], "sorted by name");
797
798        let provider_node = &model.nodes[1];
799        assert_eq!(provider_node.capabilities.len(), 1);
800        assert_eq!(provider_node.capabilities[0].name, "Clock");
801        assert_eq!(
802            provider_node.capabilities[0].origin,
803            CapabilityOrigin::Local
804        );
805        assert_eq!(provider_node.providers.len(), 1);
806        assert_eq!(provider_node.providers[0].provider_name, "SystemClock");
807        assert!(!provider_node.providers[0].external);
808
809        let consumer_node = &model.nodes[0];
810        assert_eq!(
811            consumer_node.capabilities,
812            vec![ArchCapability {
813                name: "Clock".to_string(),
814                origin: CapabilityOrigin::Consumed {
815                    from: "platformtime".to_string()
816                },
817                loc: consumer_node.capabilities[0].loc.clone(),
818            }]
819        );
820        // Regression: this node's declaration lives in `jobs.bynk`, not
821        // `platformtime.bynk` — a per-node uri computed from the wrong file
822        // would silently open the other context on click-to-code.
823        assert_eq!(consumer_node.loc.file, PathBuf::from("jobs.bynk"));
824
825        assert_eq!(model.edges.len(), 1);
826        let edge = &model.edges[0];
827        assert_eq!(edge.from, "ops.jobs");
828        assert_eq!(edge.to, "platformtime");
829        assert_eq!(edge.capabilities, vec!["Clock".to_string()]);
830        assert_eq!(edge.loc.file, PathBuf::from("jobs.bynk"));
831    }
832
833    // -- Regression: a multi-file unit's two files each `consumes` the same
834    // -- target (a different braced capability each) — the two `ConsumesDecl`s
835    // -- must merge into one edge (the union of both capability labels), not
836    // -- draw two arrows between the same pair of nodes, and the node's own
837    // -- bound-capability list must carry both without a stray duplicate.
838    const TWO_CAP_PROVIDER_SRC: &str = r#"context platformtime
839
840exports capability { Clock, Ping }
841
842capability Clock {
843  fn now() -> Effect[Int]
844}
845
846capability Ping {
847  fn ping() -> Effect[Int]
848}
849
850provides Clock = SystemClock {
851  fn now() -> Effect[Int] {
852    0
853  }
854}
855
856provides Ping = SystemPing {
857  fn ping() -> Effect[Int] {
858    1
859  }
860}
861"#;
862    const CONSUMER_FILE_A: &str = r#"context ops.jobs
863
864consumes platformtime { Clock }
865
866service run {
867  on call() -> Effect[Int] by Caller given Clock {
868    let now <- Clock.now()
869    now
870  }
871}
872"#;
873    const CONSUMER_FILE_B: &str = r#"context ops.jobs
874
875consumes platformtime { Ping }
876"#;
877
878    #[test]
879    fn a_multi_file_unit_s_repeated_consumes_target_merges_into_one_edge() {
880        let root = setup_project(
881            "multifile_consumes",
882            &[
883                ("platformtime.bynk", TWO_CAP_PROVIDER_SRC),
884                ("ops/jobs/a.bynk", CONSUMER_FILE_A),
885                ("ops/jobs/b.bynk", CONSUMER_FILE_B),
886            ],
887        );
888        let diag = crate::testkit::diagnose_project(&root);
889        let model = build_model(&diag);
890
891        assert_eq!(
892            model.edges.len(),
893            1,
894            "both consumes clauses target platformtime — one edge, not two"
895        );
896        let edge = &model.edges[0];
897        assert_eq!(edge.from, "ops.jobs");
898        assert_eq!(edge.to, "platformtime");
899        assert_eq!(
900            edge.capabilities,
901            vec!["Clock".to_string(), "Ping".to_string()]
902        );
903
904        let consumer = model.nodes.iter().find(|n| n.name == "ops.jobs").unwrap();
905        let cap_names: Vec<&str> = consumer
906            .capabilities
907            .iter()
908            .map(|c| c.name.as_str())
909            .collect();
910        assert_eq!(
911            cap_names,
912            vec!["Clock", "Ping"],
913            "no duplicate capability rows"
914        );
915    }
916
917    #[test]
918    fn whole_unit_consumes_draws_an_unlabelled_edge_with_no_bound_capability() {
919        const PLATFORM_SRC: &str = r#"context platform
920
921service Pinger {
922  on call(n: Int) -> Effect[Int] by Caller {
923    n
924  }
925}
926"#;
927        const CONSUMER_SRC: &str = r#"context consumer
928
929consumes platform
930
931service api {
932  on call(n: Int) -> Effect[Int] by Caller {
933    let v <- platform.Pinger(n)
934    v
935  }
936}
937"#;
938        let root = setup_project(
939            "wholeunit",
940            &[
941                ("platform.bynk", PLATFORM_SRC),
942                ("consumer.bynk", CONSUMER_SRC),
943            ],
944        );
945        let diag = crate::testkit::diagnose_project(&root);
946        let model = build_model(&diag);
947
948        assert_eq!(model.edges.len(), 1);
949        assert!(model.edges[0].capabilities.is_empty());
950        let consumer = model.nodes.iter().find(|n| n.name == "consumer").unwrap();
951        assert!(
952            consumer.capabilities.is_empty(),
953            "a whole-unit consumes flattens nothing into the local namespace"
954        );
955    }
956
957    // -- Model-diagrams slice 4: each service's protocol and the actors its
958    // -- handlers admit (the service default and each handler's own `by`).
959    const SERVICES_SRC: &str = r#"context shop
960
961actor Visitor {
962  identity = String
963}
964
965actor Admin {
966  identity = String
967}
968
969service internal {
970  on call(n: Int) -> Effect[Int] by Caller {
971    n
972  }
973}
974
975service web from http by Visitor {
976  on GET("/a") () -> Effect[HttpResult[Int]] {
977    Ok(1)
978  }
979
980  on GET("/admin") () -> Effect[HttpResult[Int]] by Admin {
981    Ok(2)
982  }
983}
984
985service staff from http by Visitor {
986  on GET("/ops") () -> Effect[HttpResult[Int]] by Admin {
987    Ok(3)
988  }
989}
990"#;
991
992    const CALLS_BILLING: &str = r#"context billing
993
994type Quote = { amount: Int, currency: String }
995
996service Pricing {
997  on call(sku: String, qty: Int) -> Effect[Quote] by Caller {
998    Quote { amount: qty * 100, currency: "USD" }
999  }
1000}
1001"#;
1002
1003    const CALLS_STOREFRONT: &str = r#"context storefront
1004
1005consumes billing
1006
1007agent Cart {
1008  key owner: String
1009
1010  store lines: Cell[Int]
1011  store total: Cell[Int]
1012
1013  on call add(n: Int) -> Effect[Int] {
1014    let _ <- lines.update((c) => c + n)
1015    n
1016  }
1017}
1018
1019service checkout {
1020  on call(sku: String, qty: Int) -> Effect[Int] by Caller {
1021    let q <- billing.Pricing(sku, qty)
1022    let again <- billing.Pricing(sku, 1)
1023    let n <- Cart(sku).add(qty)
1024    q.amount + again.amount + n
1025  }
1026}
1027"#;
1028
1029    #[test]
1030    fn handlers_carry_their_calls_and_agents_their_key_and_state() {
1031        let root = setup_project(
1032            "arch-calls",
1033            &[
1034                ("billing.bynk", CALLS_BILLING),
1035                ("storefront.bynk", CALLS_STOREFRONT),
1036            ],
1037        );
1038        let diag = crate::testkit::diagnose_project(&root);
1039        let model = build_model(&diag);
1040        let node = model
1041            .nodes
1042            .iter()
1043            .find(|n| n.name == "storefront")
1044            .expect("the storefront node");
1045
1046        let cart = &node.agents[0];
1047        assert_eq!(cart.key, "owner: String");
1048        assert_eq!(cart.state, vec!["lines".to_string(), "total".to_string()]);
1049
1050        let checkout = node
1051            .uses
1052            .iter()
1053            .find(|h| h.member.container == "checkout")
1054            .expect("the checkout handler");
1055        let calls: Vec<(MemberKind, &str, &str, Option<&str>)> = checkout
1056            .calls
1057            .iter()
1058            .map(|c| {
1059                (
1060                    c.kind,
1061                    c.unit.as_str(),
1062                    c.container.as_str(),
1063                    c.handler.as_deref(),
1064                )
1065            })
1066            .collect();
1067        // One entry per target, in source order: the second `Pricing` call
1068        // folds into the first.
1069        assert_eq!(
1070            calls,
1071            vec![
1072                (MemberKind::Service, "billing", "Pricing", None),
1073                (MemberKind::Agent, "storefront", "Cart", Some("add")),
1074            ]
1075        );
1076        let first = CALLS_STOREFRONT.find("billing.Pricing(sku, qty)").unwrap();
1077        assert_eq!(checkout.calls[0].loc.span.start, first);
1078
1079        let add = node
1080            .uses
1081            .iter()
1082            .find(|h| h.member.container == "Cart")
1083            .expect("the agent handler");
1084        assert!(add.calls.is_empty());
1085    }
1086
1087    #[test]
1088    fn calls_resolve_aliases_and_reach_nested_and_provider_bodies() {
1089        let storefront = r#"context storefront
1090
1091consumes billing as b
1092
1093capability Audit {
1094  fn note(n: Int) -> Effect[Int]
1095}
1096
1097provides Audit = Notes {
1098  fn note(n: Int) -> Effect[Int] {
1099    let q <- b.Pricing("x", n)
1100    q.amount
1101  }
1102}
1103
1104service checkout {
1105  on call(sku: String, qty: Int) -> Effect[Int] by Caller {
1106    if qty > 1 {
1107      let q <- b.Pricing(sku, qty)
1108      q.amount
1109    } else {
1110      0
1111    }
1112  }
1113}
1114"#;
1115        let root = setup_project(
1116            "arch-calls-alias",
1117            &[
1118                ("billing.bynk", CALLS_BILLING),
1119                ("storefront.bynk", storefront),
1120            ],
1121        );
1122        let diag = crate::testkit::diagnose_project(&root);
1123        let model = build_model(&diag);
1124        let node = model
1125            .nodes
1126            .iter()
1127            .find(|n| n.name == "storefront")
1128            .expect("the storefront node");
1129        let calls_of = |container: &str| -> Vec<(String, String)> {
1130            node.uses
1131                .iter()
1132                .find(|h| h.member.container == container)
1133                .expect("the handler")
1134                .calls
1135                .iter()
1136                .map(|c| (c.unit.clone(), c.container.clone()))
1137                .collect()
1138        };
1139        let pricing = vec![("billing".to_string(), "Pricing".to_string())];
1140        // Inside an `if` branch, through the `b` alias.
1141        assert_eq!(calls_of("checkout"), pricing);
1142        // In a provider operation's body.
1143        assert_eq!(calls_of("Notes"), pricing);
1144        let first = storefront.find("b.Pricing(sku, qty)").unwrap();
1145        let checkout = node
1146            .uses
1147            .iter()
1148            .find(|h| h.member.container == "checkout")
1149            .unwrap();
1150        assert_eq!(checkout.calls[0].loc.span.start, first);
1151    }
1152
1153    #[test]
1154    fn services_carry_their_protocol_and_actors() {
1155        let root = setup_project("arch-services", &[("shop.bynk", SERVICES_SRC)]);
1156        let diag = crate::testkit::diagnose_project(&root);
1157        let model = build_model(&diag);
1158        let node = model
1159            .nodes
1160            .iter()
1161            .find(|n| n.name == "shop")
1162            .expect("the shop node");
1163        let svc = |name: &str| {
1164            node.services
1165                .iter()
1166                .find(|s| s.name == name)
1167                .expect("service")
1168        };
1169        assert_eq!(svc("internal").protocol, "call");
1170        // #3891: an `on call` handler states its actor, so the service names one.
1171        assert_eq!(svc("internal").actors, vec!["Caller".to_string()]);
1172        assert_eq!(svc("web").protocol, "http");
1173        assert_eq!(
1174            svc("web").actors,
1175            vec!["Admin".to_string(), "Visitor".to_string()]
1176        );
1177        // Every handler overrides the default, so no handler admits it.
1178        assert_eq!(svc("staff").actors, vec!["Admin".to_string()]);
1179    }
1180}