1use 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#[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
37pub 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#[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 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 pub uses: Vec<WireArchHandlerUses>,
81}
82
83#[derive(Debug, Clone, serde::Serialize)]
85pub struct WireArchMember {
86 pub unit: String,
87 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 pub calls: Vec<WireArchCall>,
100}
101
102#[derive(Debug, Clone, serde::Serialize)]
104pub struct WireArchCall {
105 pub kind: &'static str,
108 pub unit: String,
110 pub container: String,
112 #[serde(skip_serializing_if = "Option::is_none")]
114 pub handler: Option<String>,
115 pub loc: WireLoc,
117}
118
119#[derive(Debug, Clone, serde::Serialize)]
120pub struct WireArchUse {
121 pub capability: String,
122 pub from: Option<String>,
125 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 pub suite: String,
136 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 pub loc: WireLoc,
154}
155
156#[derive(Debug, Clone, serde::Serialize)]
157pub struct WireArchSubscriber {
158 pub member: WireArchMember,
159 pub delivery: &'static str,
161 pub loc: WireLoc,
163}
164
165#[derive(Debug, Clone, serde::Serialize)]
166pub struct WireArchCapability {
167 pub name: String,
168 pub local: bool,
169 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 pub protocol: &'static str,
194 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 pub key: String,
206 pub state: Vec<String>,
208}
209
210#[derive(Debug, Clone, serde::Serialize)]
211pub struct WireArchEdge {
212 pub from: String,
213 pub to: String,
214 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
258fn 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
275pub 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 #[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 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}