Skip to main content

bynk_lsp/
architecture_request.rs

1//! #851: `bynk/architectureModel` — the architecture-map custom LSP request.
2//!
3//! The third custom request in this server (after #846's `bynk/sequenceModel`
4//! and #847's `bynk/documentationModel`), and the same on-demand posture: no
5//! `workspace/*/refresh` nudge exists for a custom method and none is needed
6//! — the client re-issues the request each time "Bynk: Show Architecture Map"
7//! fires.
8//!
9//! Unlike both siblings, this request is **project-scoped**, not file-scoped:
10//! the params carry a `textDocument` only to resolve which project's
11//! committed round to read (the same `committed_analysis` gate every pull-
12//! based request uses), never to restrict the result to that one file. The
13//! wire model reflects that: every node/member/edge carries its own `uri` —
14//! not just a `range` against the request's document, the convention
15//! `sequence`/`documentation` can get away with because they're single-file.
16
17use std::collections::HashMap;
18use std::path::{Path, PathBuf};
19
20use bynk_ide::architecture::{self, ArchMember, ArchModel, CapabilityOrigin, NodeKind};
21use bynk_ide::{DeliveryKind, MemberKind};
22
23/// The `bynk/architectureModel` request payload — a bare text-document
24/// identifier used only to resolve the owning project (Decision B: the
25/// active file's nearest `bynk.toml`), never to scope the result to that file.
26///
27/// `rename_all = "camelCase"` is load-bearing — see `sequence_request`'s and
28/// `documentation_request`'s own params docs for why (the client sends
29/// `textDocument`; this shipped as a missing-field bug once already, in #846,
30/// before #847 caught and fixed it).
31#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
32#[serde(rename_all = "camelCase")]
33pub struct ArchitectureModelParams {
34    pub text_document: tower_lsp::lsp_types::TextDocumentIdentifier,
35}
36
37/// Build the project-wide architecture model from the round's own retained
38/// tables. A thin wrapper around [`architecture::architecture_model`] so the
39/// `lib.rs` handler stays a `committed_analysis` guard chain, like its two
40/// siblings.
41pub fn architecture_model_for(
42    unit_sources: &HashMap<String, Vec<PathBuf>>,
43    snapshots: &HashMap<PathBuf, String>,
44    sequence_info: &HashMap<String, bynk_ide::ContextSequenceInfo>,
45    facts: &bynk_ide::ArchitectureFacts,
46) -> ArchModel {
47    architecture::architecture_model(unit_sources, snapshots, sequence_info, facts)
48}
49
50// -- Wire shape: a plain serde mirror of `bynk_ide::architecture::ArchModel`.
51// -- Each `Located` lowers to a `{uri, range}` pair computed against *its
52// -- own* file's committed snapshot — never the request document's, since a
53// -- node's members may span several files of a multi-file unit, and two
54// -- nodes almost always live in different files entirely.
55
56#[derive(Debug, Clone, serde::Serialize)]
57pub struct WireLoc {
58    pub uri: tower_lsp::lsp_types::Url,
59    pub range: tower_lsp::lsp_types::Range,
60}
61
62#[derive(Debug, Clone, serde::Serialize)]
63pub struct WireArchModel {
64    pub nodes: Vec<WireArchNode>,
65    pub edges: Vec<WireArchEdge>,
66    /// #3583: every declared event with its emitters and subscribers.
67    pub events: Vec<WireArchEvent>,
68}
69
70#[derive(Debug, Clone, serde::Serialize)]
71pub struct WireArchNode {
72    pub name: String,
73    pub kind: &'static str,
74    pub loc: WireLoc,
75    pub capabilities: Vec<WireArchCapability>,
76    pub providers: Vec<WireArchProvider>,
77    pub services: Vec<WireArchService>,
78    pub agents: Vec<WireArchAgent>,
79    /// #3583: per handler, the capabilities it requires through `given`.
80    pub uses: Vec<WireArchHandlerUses>,
81}
82
83/// #3583: the handler (or provider operation) an event site or a use belongs to.
84#[derive(Debug, Clone, serde::Serialize)]
85pub struct WireArchMember {
86    pub unit: String,
87    /// `"service"`, `"agent"` or `"provider"`.
88    pub kind: &'static str,
89    pub container: String,
90    pub handler: String,
91    pub loc: WireLoc,
92}
93
94#[derive(Debug, Clone, serde::Serialize)]
95pub struct WireArchHandlerUses {
96    pub member: WireArchMember,
97    pub uses: Vec<WireArchUse>,
98    /// Model-diagrams slice 5: the services and agents the handler calls.
99    pub calls: Vec<WireArchCall>,
100}
101
102/// Model-diagrams slice 5: one service or agent a handler calls.
103#[derive(Debug, Clone, serde::Serialize)]
104pub struct WireArchCall {
105    /// `"service"` (a consumed context's service) or `"agent"` (one of the
106    /// caller's own agents).
107    pub kind: &'static str,
108    /// The unit that declares the callee.
109    pub unit: String,
110    /// The service or agent name.
111    pub container: String,
112    /// The agent handler dispatched to; absent for a service call.
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub handler: Option<String>,
115    /// The handler's first call to it.
116    pub loc: WireLoc,
117}
118
119#[derive(Debug, Clone, serde::Serialize)]
120pub struct WireArchUse {
121    pub capability: String,
122    /// The unit that declares the capability: this unit, a consumed one, or
123    /// `"bynk"`.
124    pub from: Option<String>,
125    /// Written on the service header (`default_given`), not on the handler.
126    pub inherited: bool,
127    pub loc: WireLoc,
128    #[serde(rename = "stubbedIn")]
129    pub stubbed_in: Vec<WireArchStub>,
130}
131
132#[derive(Debug, Clone, serde::Serialize)]
133pub struct WireArchStub {
134    /// The suite file, project-relative with `/` separators.
135    pub suite: String,
136    /// The suite's first `stub` of the capability.
137    pub loc: WireLoc,
138}
139
140#[derive(Debug, Clone, serde::Serialize)]
141pub struct WireArchEvent {
142    pub owner: String,
143    pub name: String,
144    pub loc: WireLoc,
145    pub emitters: Vec<WireArchEmitter>,
146    pub subscribers: Vec<WireArchSubscriber>,
147}
148
149#[derive(Debug, Clone, serde::Serialize)]
150pub struct WireArchEmitter {
151    pub member: WireArchMember,
152    /// The `Events.emit[E](…)` call.
153    pub loc: WireLoc,
154}
155
156#[derive(Debug, Clone, serde::Serialize)]
157pub struct WireArchSubscriber {
158    pub member: WireArchMember,
159    /// `"all"`, `"pattern"`, `"schema"` or `"patternSchema"`.
160    pub delivery: &'static str,
161    /// The `from Events(…)` header.
162    pub loc: WireLoc,
163}
164
165#[derive(Debug, Clone, serde::Serialize)]
166pub struct WireArchCapability {
167    pub name: String,
168    pub local: bool,
169    /// The providing unit's qualified name, for a consumed (non-local)
170    /// capability — `"bynk"` for the toolchain's built-in surface. `null` for
171    /// a locally-declared capability.
172    pub from: Option<String>,
173    pub loc: WireLoc,
174}
175
176#[derive(Debug, Clone, serde::Serialize)]
177pub struct WireArchProvider {
178    pub capability: String,
179    #[serde(rename = "providerName")]
180    pub provider_name: String,
181    pub external: bool,
182    pub loc: WireLoc,
183}
184
185#[derive(Debug, Clone, serde::Serialize)]
186pub struct WireArchService {
187    pub name: String,
188    #[serde(rename = "handlerCount")]
189    pub handler_count: usize,
190    pub loc: WireLoc,
191    /// Model-diagrams slice 4: `call`, `http`, `cron`, `queue`, `websocket`,
192    /// `events` or `email`.
193    pub protocol: &'static str,
194    /// Model-diagrams slice 4: the actors its handlers admit, sorted.
195    pub actors: Vec<String>,
196}
197
198#[derive(Debug, Clone, serde::Serialize)]
199pub struct WireArchAgent {
200    pub name: String,
201    #[serde(rename = "handlerCount")]
202    pub handler_count: usize,
203    pub loc: WireLoc,
204    /// Model-diagrams slice 5: the key as written (`id: ClientId`).
205    pub key: String,
206    /// Model-diagrams slice 5: the `store` field names, in declaration order.
207    pub state: Vec<String>,
208}
209
210#[derive(Debug, Clone, serde::Serialize)]
211pub struct WireArchEdge {
212    pub from: String,
213    pub to: String,
214    /// Selected capability labels (braced `consumes` form); empty for a
215    /// whole-unit consumes.
216    pub capabilities: Vec<String>,
217    pub loc: WireLoc,
218}
219
220fn kind_str(k: NodeKind) -> &'static str {
221    match k {
222        NodeKind::Context => "Context",
223        NodeKind::Adapter => "Adapter",
224    }
225}
226
227fn member_kind_str(k: MemberKind) -> &'static str {
228    match k {
229        MemberKind::Service => "service",
230        MemberKind::Agent => "agent",
231        MemberKind::Provider => "provider",
232    }
233}
234
235fn delivery_str(d: DeliveryKind) -> &'static str {
236    match d {
237        DeliveryKind::All => "all",
238        DeliveryKind::Pattern => "pattern",
239        DeliveryKind::Schema => "schema",
240        DeliveryKind::PatternSchema => "patternSchema",
241    }
242}
243
244fn wire_member(
245    project_root: &Path,
246    snapshots: &HashMap<PathBuf, String>,
247    m: &ArchMember,
248) -> Option<WireArchMember> {
249    Some(WireArchMember {
250        unit: m.unit.clone(),
251        kind: member_kind_str(m.kind),
252        container: m.container.clone(),
253        handler: m.handler.clone(),
254        loc: wire_loc(project_root, snapshots, &m.loc)?,
255    })
256}
257
258/// Lower a `Located` to a `{uri, range}` pair. `None` only on the defensive
259/// paths — a missing snapshot for `loc.file` (every `Located` here was built
260/// from a file `architecture_model` itself read out of `snapshots`, so this
261/// should not happen) or a path that cannot form a `file://` URI.
262fn wire_loc(
263    project_root: &Path,
264    snapshots: &HashMap<PathBuf, String>,
265    loc: &architecture::Located,
266) -> Option<WireLoc> {
267    let text = snapshots.get(&loc.file)?;
268    let uri = tower_lsp::lsp_types::Url::from_file_path(project_root.join(&loc.file)).ok()?;
269    Some(WireLoc {
270        uri,
271        range: crate::position::span_to_range(text, loc.span),
272    })
273}
274
275/// Lower the whole model. A node (or member, or edge) whose own location
276/// can't be resolved (see `wire_loc` above) is dropped rather than sent with
277/// a bogus location — click-to-code must never open the wrong file.
278pub fn to_wire(
279    model: &ArchModel,
280    project_root: &Path,
281    snapshots: &HashMap<PathBuf, String>,
282) -> WireArchModel {
283    WireArchModel {
284        nodes: model
285            .nodes
286            .iter()
287            .filter_map(|n| {
288                Some(WireArchNode {
289                    name: n.name.clone(),
290                    kind: kind_str(n.kind),
291                    loc: wire_loc(project_root, snapshots, &n.loc)?,
292                    capabilities: n
293                        .capabilities
294                        .iter()
295                        .filter_map(|c| {
296                            let (local, from) = match &c.origin {
297                                CapabilityOrigin::Local => (true, None),
298                                CapabilityOrigin::Consumed { from } => (false, Some(from.clone())),
299                            };
300                            Some(WireArchCapability {
301                                name: c.name.clone(),
302                                local,
303                                from,
304                                loc: wire_loc(project_root, snapshots, &c.loc)?,
305                            })
306                        })
307                        .collect(),
308                    providers: n
309                        .providers
310                        .iter()
311                        .filter_map(|p| {
312                            Some(WireArchProvider {
313                                capability: p.capability.clone(),
314                                provider_name: p.provider_name.clone(),
315                                external: p.external,
316                                loc: wire_loc(project_root, snapshots, &p.loc)?,
317                            })
318                        })
319                        .collect(),
320                    services: n
321                        .services
322                        .iter()
323                        .filter_map(|s| {
324                            Some(WireArchService {
325                                name: s.name.clone(),
326                                handler_count: s.handler_count,
327                                loc: wire_loc(project_root, snapshots, &s.loc)?,
328                                protocol: s.protocol,
329                                actors: s.actors.clone(),
330                            })
331                        })
332                        .collect(),
333                    agents: n
334                        .agents
335                        .iter()
336                        .filter_map(|a| {
337                            Some(WireArchAgent {
338                                name: a.name.clone(),
339                                handler_count: a.handler_count,
340                                loc: wire_loc(project_root, snapshots, &a.loc)?,
341                                key: a.key.clone(),
342                                state: a.state.clone(),
343                            })
344                        })
345                        .collect(),
346                    uses: wire_uses(&n.uses, project_root, snapshots),
347                })
348            })
349            .collect(),
350        events: wire_events(&model.events, project_root, snapshots),
351        edges: model
352            .edges
353            .iter()
354            .filter_map(|e| {
355                Some(WireArchEdge {
356                    from: e.from.clone(),
357                    to: e.to.clone(),
358                    capabilities: e.capabilities.clone(),
359                    loc: wire_loc(project_root, snapshots, &e.loc)?,
360                })
361            })
362            .collect(),
363    }
364}
365
366fn wire_uses(
367    handlers: &[architecture::ArchHandlerUses],
368    project_root: &Path,
369    snapshots: &HashMap<PathBuf, String>,
370) -> Vec<WireArchHandlerUses> {
371    handlers
372        .iter()
373        .filter_map(|h| {
374            Some(WireArchHandlerUses {
375                member: wire_member(project_root, snapshots, &h.member)?,
376                uses: h
377                    .uses
378                    .iter()
379                    .filter_map(|u| {
380                        Some(WireArchUse {
381                            capability: u.capability.clone(),
382                            from: u.from.clone(),
383                            inherited: u.inherited,
384                            loc: wire_loc(project_root, snapshots, &u.loc)?,
385                            stubbed_in: u
386                                .stubbed_in
387                                .iter()
388                                .filter_map(|s| {
389                                    Some(WireArchStub {
390                                        suite: s.suite.to_string_lossy().replace('\\', "/"),
391                                        loc: wire_loc(project_root, snapshots, &s.loc)?,
392                                    })
393                                })
394                                .collect(),
395                        })
396                    })
397                    .collect(),
398                calls: h
399                    .calls
400                    .iter()
401                    .filter_map(|c| {
402                        Some(WireArchCall {
403                            kind: member_kind_str(c.kind),
404                            unit: c.unit.clone(),
405                            container: c.container.clone(),
406                            handler: c.handler.clone(),
407                            loc: wire_loc(project_root, snapshots, &c.loc)?,
408                        })
409                    })
410                    .collect(),
411            })
412        })
413        .collect()
414}
415
416fn wire_events(
417    events: &[architecture::ArchEvent],
418    project_root: &Path,
419    snapshots: &HashMap<PathBuf, String>,
420) -> Vec<WireArchEvent> {
421    events
422        .iter()
423        .filter_map(|e| {
424            Some(WireArchEvent {
425                owner: e.owner.clone(),
426                name: e.name.clone(),
427                loc: wire_loc(project_root, snapshots, &e.loc)?,
428                emitters: e
429                    .emitters
430                    .iter()
431                    .filter_map(|x| {
432                        Some(WireArchEmitter {
433                            member: wire_member(project_root, snapshots, &x.member)?,
434                            loc: wire_loc(project_root, snapshots, &x.loc)?,
435                        })
436                    })
437                    .collect(),
438                subscribers: e
439                    .subscribers
440                    .iter()
441                    .filter_map(|x| {
442                        Some(WireArchSubscriber {
443                            member: wire_member(project_root, snapshots, &x.member)?,
444                            delivery: delivery_str(x.delivery),
445                            loc: wire_loc(project_root, snapshots, &x.loc)?,
446                        })
447                    })
448                    .collect(),
449            })
450        })
451        .collect()
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457    use std::fs;
458
459    fn setup_project(test_name: &str, files: &[(&str, &str)]) -> PathBuf {
460        let root = std::env::temp_dir().join(format!(
461            "bynk-lsp-architecture-request-test-{test_name}-{}",
462            std::process::id()
463        ));
464        let _ = fs::remove_dir_all(&root);
465        fs::create_dir_all(&root).expect("create test root");
466        for (rel, contents) in files {
467            let p = root.join(rel);
468            if let Some(parent) = p.parent() {
469                fs::create_dir_all(parent).expect("create parent");
470            }
471            fs::write(&p, contents).expect("write file");
472        }
473        root
474    }
475
476    const PROVIDER_SRC: &str = r#"context platformtime
477
478exports capability { Clock }
479
480capability Clock {
481  fn now() -> Effect[Int]
482}
483
484provides Clock = SystemClock {
485  fn now() -> Effect[Int] {
486    0
487  }
488}
489"#;
490    const CONSUMER_SRC: &str = r#"context ops.jobs
491
492consumes platformtime { Clock }
493
494service run {
495  on call() -> Effect[Int] by Caller given Clock {
496    let now <- Clock.now()
497    now
498  }
499}
500"#;
501
502    #[test]
503    fn params_deserialize_from_camel_case_wire_json() {
504        let json = serde_json::json!({
505            "textDocument": { "uri": "file:///a/b.bynk" }
506        });
507        let params: ArchitectureModelParams =
508            serde_json::from_value(json).expect("camelCase textDocument must deserialize");
509        assert_eq!(params.text_document.uri.as_str(), "file:///a/b.bynk");
510    }
511
512    /// Regression (the exact bug the advisor flagged): a node's own file
513    /// differs from the *other* node's file, and each member's `uri` must
514    /// point at the file it was actually declared in — not the request
515    /// document, not the first file the model happened to visit.
516    #[test]
517    fn each_node_uri_points_at_its_own_declaring_file_not_the_others() {
518        let root = setup_project(
519            "twofile",
520            &[
521                ("platformtime.bynk", PROVIDER_SRC),
522                ("jobs.bynk", CONSUMER_SRC),
523            ],
524        );
525        let diag = bynk_ide::diagnose_project(
526            &root,
527            &bynk_testkit::read_project_sources(&bynk_ide::AnalysisRoots::SingleTree(root.clone())),
528        );
529        let snapshots: HashMap<PathBuf, String> = diag
530            .files
531            .iter()
532            .map(|f| (f.source_path.clone(), f.text.clone()))
533            .collect();
534        let model = architecture_model_for(
535            &diag.unit_sources,
536            &snapshots,
537            &diag.sequence_info,
538            &diag.architecture_facts,
539        );
540        let wire = to_wire(&model, &root, &snapshots);
541
542        assert_eq!(wire.nodes.len(), 2);
543        let jobs = wire.nodes.iter().find(|n| n.name == "ops.jobs").unwrap();
544        let platformtime = wire
545            .nodes
546            .iter()
547            .find(|n| n.name == "platformtime")
548            .unwrap();
549
550        assert!(
551            jobs.loc.uri.as_str().ends_with("jobs.bynk"),
552            "got {}",
553            jobs.loc.uri
554        );
555        assert!(
556            platformtime.loc.uri.as_str().ends_with("platformtime.bynk"),
557            "got {}",
558            platformtime.loc.uri
559        );
560        assert_ne!(jobs.loc.uri, platformtime.loc.uri);
561
562        // The consumed capability entry lives in the *consuming* file
563        // (`jobs.bynk`'s `consumes` clause), even though the capability
564        // itself is declared over in `platformtime.bynk`.
565        assert_eq!(jobs.capabilities.len(), 1);
566        assert!(jobs.capabilities[0].loc.uri.as_str().ends_with("jobs.bynk"));
567        assert_eq!(jobs.capabilities[0].from.as_deref(), Some("platformtime"));
568
569        assert_eq!(wire.edges.len(), 1);
570        assert_eq!(wire.edges[0].from, "ops.jobs");
571        assert_eq!(wire.edges[0].to, "platformtime");
572        assert!(wire.edges[0].loc.uri.as_str().ends_with("jobs.bynk"));
573    }
574}