Skip to main content

bynk/
dev_inspect.rs

1//! `bynk dev inspect` (#3581, the dev agent-inspection track): list the agent
2//! instances a running `bynk dev` session has seen, and read one's stored state.
3//!
4//! A running session writes `.bynk/dev/session.json` (see [`SessionFile`]) naming
5//! each served context and the URL it answers on. This command reads it, signs a
6//! request under the local call key as `bynk.dev`, and prints the Worker's answer
7//! as JSON on stdout. The request is the published call signature, as `bynk
8//! migrate sweep`'s wake is, so a Worker that was not built by `bynk dev` has no
9//! such route and answers `404`.
10
11use bynk_driver::emsg;
12use std::collections::BTreeMap;
13use std::path::{Path, PathBuf};
14
15use serde::{Deserialize, Serialize};
16use serde_json::{Value, json};
17
18/// Where a running session records itself, under the managed build directory.
19pub fn session_path(project_root: &Path) -> PathBuf {
20    project_root.join(".bynk").join("dev").join("session.json")
21}
22
23/// One served Worker, as the session file records it.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct SessionWorker {
26    /// The qualified context it serves: the callee its signatures are bound to.
27    pub context: String,
28    /// `http://localhost:<port>`.
29    pub url: String,
30    /// A Worker group's members (#3562, G6), in the order the
31    /// group's entry tries them. The group is one Worker with one registry, but
32    /// each member decides before it verifies whether a request is its own, so a
33    /// request is signed for the member that answers it. Empty for a Worker that
34    /// is one context, whose `context` is the audience of every request.
35    #[serde(default, skip_serializing_if = "Vec::is_empty")]
36    pub members: Vec<InspectMember>,
37}
38
39/// One member of a group, as `bynk-inspect.json` records it (`classes` empty for one
40/// that hosts no agent).
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct InspectMember {
43    pub context: String,
44    pub classes: Vec<String>,
45}
46
47impl SessionWorker {
48    /// The audience of the listing: the first member that hosts an agent answers it
49    /// (the registry is the Worker's, so it lists every member's instances).
50    fn lister(&self) -> &str {
51        self.members
52            .iter()
53            .find(|m| !m.classes.is_empty())
54            .map_or(&self.context, |m| &m.context)
55    }
56
57    /// The audience of a read of `class`: the member that owns the class.
58    fn owner(&self, class: &str) -> &str {
59        self.members
60            .iter()
61            .find(|m| m.classes.iter().any(|c| c == class))
62            .map_or(self.lister(), |m| &m.context)
63    }
64
65    /// Whether `context` is one this Worker serves.
66    fn serves(&self, context: &str) -> bool {
67        let dotted = context_of_worker(context);
68        self.context == context || self.members.iter().any(|m| m.context == dotted)
69    }
70}
71
72/// The session file: each served Worker by its worker-dir name.
73#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
74pub struct Session {
75    pub workers: BTreeMap<String, SessionWorker>,
76}
77
78/// A written session file, removed when dropped (when the session stops).
79pub struct SessionFile(PathBuf);
80
81impl SessionFile {
82    /// Record `session` for the project at `project_root`. A failure is reported
83    /// and the session serves without it: `bynk dev inspect` then says there is
84    /// no running session.
85    pub fn write(project_root: &Path, session: &Session) -> SessionFile {
86        let path = session_path(project_root);
87        let text = serde_json::to_string_pretty(session).expect("a session serialises");
88        if let Err(e) = std::fs::write(&path, text) {
89            emsg!(
90                "bynk: warning: could not write {}: {e}; `bynk dev inspect` will not find this session",
91                path.display()
92            );
93        }
94        SessionFile(path)
95    }
96}
97
98impl Drop for SessionFile {
99    fn drop(&mut self) {
100        let _ = std::fs::remove_file(&self.0);
101    }
102}
103
104/// The agent-hosting members a group's build records beside its entry
105/// (`bynk-inspect.json`); none for a Worker that is one context, or an unreadable file.
106pub fn inspect_members(worker_dir: &Path) -> Vec<InspectMember> {
107    #[derive(Deserialize)]
108    struct File {
109        members: Vec<InspectMember>,
110    }
111    std::fs::read_to_string(worker_dir.join(bynk_emit::INSPECT_MEMBERS_FILE))
112        .ok()
113        .and_then(|text| serde_json::from_str::<File>(&text).ok())
114        .map_or_else(Vec::new, |f| f.members)
115}
116
117/// The qualified context a worker-dir name serves.
118pub fn context_of_worker(worker: &str) -> String {
119    worker.replace('-', ".")
120}
121
122/// What `bynk dev inspect` was asked.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub enum Inspect {
125    /// `inspect agents [--context C] [--class A]`.
126    Agents {
127        context: Option<String>,
128        class: Option<String>,
129    },
130    /// `inspect agent <Class> <key>`: its state, paged by `page`.
131    Agent {
132        context: Option<String>,
133        class: String,
134        key: String,
135        page: Page,
136    },
137}
138
139/// Which page of a collection to read (`--field`, `--after`, `--limit`).
140#[derive(Debug, Clone, PartialEq, Eq, Default)]
141pub struct Page {
142    pub field: Option<String>,
143    pub after: Option<String>,
144    pub limit: Option<u32>,
145}
146
147impl Page {
148    fn query(&self) -> Vec<(&'static str, String)> {
149        let mut q = Vec::new();
150        if let Some(f) = &self.field {
151            q.push(("field", f.clone()));
152        }
153        if let Some(a) = &self.after {
154            q.push(("after", a.clone()));
155        }
156        if let Some(l) = self.limit {
157            q.push(("limit", l.to_string()));
158        }
159        q
160    }
161}
162
163/// The signed `POST` of one inspect request: its URL and headers.
164pub fn signed_request(
165    base: &str,
166    context: &str,
167    path: &str,
168    query: &[(&str, String)],
169    now: u64,
170) -> (String, Vec<(String, String)>) {
171    let headers = crate::migrate::sweep::signed_headers_as(
172        bynk_emit::INSPECT_CALLER,
173        bynk_emit::LOCAL_CALL_KEY,
174        context,
175        path,
176        "",
177        now,
178    );
179    let mut url = format!("{}{path}", base.trim_end_matches('/'));
180    for (i, (k, v)) in query.iter().enumerate() {
181        url.push(if i == 0 { '?' } else { '&' });
182        url.push_str(k);
183        url.push('=');
184        url.push_str(&percent_encode(v));
185    }
186    (url, headers)
187}
188
189/// Percent-encode everything but unreserved characters, for a query value or a path segment.
190pub(crate) fn percent_encode(s: &str) -> String {
191    let mut out = String::new();
192    for b in s.bytes() {
193        match b {
194            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
195                out.push(b as char)
196            }
197            _ => out.push_str(&format!("%{b:02X}")),
198        }
199    }
200    out
201}
202
203/// Whether a registry key (its wire form) is the one the user typed: a string key
204/// by its text, any other by its JSON.
205pub fn key_matches(key: &Value, typed: &str) -> bool {
206    match key {
207        Value::String(s) => s == typed,
208        other => serde_json::from_str::<Value>(typed).is_ok_and(|v| &v == other),
209    }
210}
211
212/// One HTTP exchange with a Worker: the status and the body.
213pub trait Post {
214    fn post(&self, url: &str, headers: &[(String, String)]) -> Result<(u16, String), String>;
215}
216
217/// The real transport: plain HTTP to a local Worker.
218pub struct Local(ureq::Agent);
219
220impl Local {
221    pub fn new() -> Self {
222        Local(
223            ureq::Agent::config_builder()
224                .http_status_as_error(false)
225                .timeout_global(Some(std::time::Duration::from_secs(15)))
226                .build()
227                .into(),
228        )
229    }
230}
231
232impl Default for Local {
233    fn default() -> Self {
234        Self::new()
235    }
236}
237
238impl Post for Local {
239    fn post(&self, url: &str, headers: &[(String, String)]) -> Result<(u16, String), String> {
240        let mut request = self.0.post(url);
241        for (k, v) in headers {
242            request = request.header(k.as_str(), v.as_str());
243        }
244        let mut response = request.send("").map_err(|e| e.to_string())?;
245        let status = response.status().as_u16();
246        let text = response
247            .body_mut()
248            .read_to_string()
249            .map_err(|e| e.to_string())?;
250        Ok((status, text))
251    }
252}
253
254fn unix_now() -> u64 {
255    std::time::SystemTime::now()
256        .duration_since(std::time::UNIX_EPOCH)
257        .map(|d| d.as_secs())
258        .unwrap_or_default()
259}
260
261fn selected<'a>(
262    session: &'a Session,
263    context: &Option<String>,
264) -> Result<Vec<(&'a String, &'a SessionWorker)>, String> {
265    let chosen: Vec<_> = session
266        .workers
267        .iter()
268        .filter(|(dir, w)| context.as_ref().is_none_or(|c| w.serves(c) || c == *dir))
269        .collect();
270    if chosen.is_empty() {
271        return Err(match context {
272            Some(c) => format!("the session serves no context `{c}`"),
273            None => "the session serves no context".to_string(),
274        });
275    }
276    Ok(chosen)
277}
278
279fn call(
280    http: &dyn Post,
281    worker: &SessionWorker,
282    audience: &str,
283    path: &str,
284    query: &[(&str, String)],
285) -> Result<Value, String> {
286    let (url, headers) = signed_request(&worker.url, audience, path, query, unix_now());
287    let (status, body) = http.post(&url, &headers)?;
288    match status {
289        200 => serde_json::from_str(&body).map_err(|e| format!("unreadable answer: {e}")),
290        401 => {
291            Err("refused the signature: is this `bynk dev` session built by this `bynk`?".into())
292        }
293        404 => Err("has no inspect route: is this a `bynk dev` session?".into()),
294        s => Err(format!("answered {s}")),
295    }
296}
297
298/// The listing of one Worker. A Worker that hosts no agent has no inspect route (the
299/// emitter adds it only where there is a class to read), so a `404` is "no agents
300/// here", an empty listing, and not a failure.
301fn listing(
302    http: &dyn Post,
303    worker: &SessionWorker,
304    query: &[(&str, String)],
305) -> Result<Value, String> {
306    let (url, headers) = signed_request(
307        &worker.url,
308        worker.lister(),
309        "/_bynk/inspect/agents",
310        query,
311        unix_now(),
312    );
313    match http.post(&url, &headers)? {
314        (404, _) => Ok(json!({ "instances": [] })),
315        (200, body) => serde_json::from_str(&body).map_err(|e| format!("unreadable answer: {e}")),
316        (401, _) => Err(
317            "refused the signature: is this `bynk dev` session built by this `bynk`?".to_string(),
318        ),
319        (s, _) => Err(format!("answered {s}")),
320    }
321}
322
323/// Run `what` against the session, returning the JSON to print. A context that
324/// cannot be reached is named in `errors` and the rest still answer.
325pub fn run(session: &Session, what: &Inspect, http: &dyn Post) -> Result<Value, String> {
326    match what {
327        Inspect::Agents { context, class } => {
328            let mut agents = Vec::new();
329            let mut errors = Vec::new();
330            let query: Vec<(&str, String)> = class.iter().map(|c| ("class", c.clone())).collect();
331            for (_, w) in selected(session, context)? {
332                match listing(http, w, &query) {
333                    Ok(v) => {
334                        for i in v["instances"].as_array().into_iter().flatten() {
335                            agents.push(json!({
336                                "context": i["class"].as_str().map_or(w.lister(), |c| w.owner(c)),
337                                "class": i["class"],
338                                "key": i["key"],
339                                "id": i["id"],
340                            }));
341                        }
342                    }
343                    Err(e) => errors.push(json!({ "context": w.lister(), "error": e })),
344                }
345            }
346            Ok(json!({ "agents": agents, "errors": errors }))
347        }
348        Inspect::Agent {
349            context,
350            class,
351            key,
352            page,
353        } => read_agent(session, context, class, key, page, http),
354    }
355}
356
357fn read_agent(
358    session: &Session,
359    context: &Option<String>,
360    class: &str,
361    key: &str,
362    page: &Page,
363    http: &dyn Post,
364) -> Result<Value, String> {
365    let class_query = [("class", class.to_string())];
366    let mut failed = Vec::new();
367    for (_, w) in selected(session, context)? {
368        // A Worker that is down, or refuses, is skipped: the instance may be in another.
369        let listed = match listing(http, w, &class_query) {
370            Ok(v) => v,
371            Err(e) => {
372                failed.push(format!("{}: {e}", w.lister()));
373                continue;
374            }
375        };
376        let found = listed["instances"]
377            .as_array()
378            .into_iter()
379            .flatten()
380            .find(|i| i["class"] == class && key_matches(&i["key"], key));
381        let Some(instance) = found else { continue };
382        let id = instance["id"].as_str().unwrap_or_default().to_string();
383        let mut query = vec![("id", id.clone())];
384        query.extend(page.query());
385        let path = format!("/_bynk/inspect/agent/{}", percent_encode(class));
386        let owner = w.owner(class);
387        let mut state = call(http, w, owner, &path, &query)?;
388        if let Some(obj) = state.as_object_mut() {
389            obj.insert("context".into(), json!(owner));
390            obj.insert("key".into(), instance["key"].clone());
391            obj.insert("id".into(), json!(id));
392        }
393        return Ok(state);
394    }
395    let mut message = format!(
396        "no instance of `{class}` with key `{key}` has been addressed in this session \
397         (an instance is listed once a handler addresses it)"
398    );
399    if !failed.is_empty() {
400        message.push_str(&format!(
401            "; these contexts could not be asked: {} (a session killed without stopping \
402             leaves a stale `.bynk/dev/session.json`)",
403            failed.join("; ")
404        ));
405    }
406    Err(message)
407}
408
409/// `bynk dev inspect`: find the session under `project_root`, run `what`, print
410/// the JSON.
411pub fn command(project_root: &Path, what: &Inspect) -> std::process::ExitCode {
412    let text = match std::fs::read_to_string(session_path(project_root)) {
413        Ok(t) => t,
414        Err(_) => {
415            emsg!(
416                "bynk: error: no running `bynk dev` session for this project (start one with `bynk dev`)"
417            );
418            return std::process::ExitCode::FAILURE;
419        }
420    };
421    let session: Session = match serde_json::from_str(&text) {
422        Ok(s) => s,
423        Err(e) => {
424            emsg!("bynk: error: unreadable session file: {e}");
425            return std::process::ExitCode::FAILURE;
426        }
427    };
428    match run(&session, what, &Local::new()) {
429        Ok(v) => {
430            println!("{}", serde_json::to_string_pretty(&v).expect("json prints"));
431            std::process::ExitCode::SUCCESS
432        }
433        Err(e) => {
434            emsg!("bynk: error: {e}");
435            std::process::ExitCode::FAILURE
436        }
437    }
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443    use std::cell::RefCell;
444
445    fn session() -> Session {
446        Session {
447            workers: BTreeMap::from([(
448                "shop-orders".to_string(),
449                SessionWorker {
450                    context: "shop.orders".to_string(),
451                    url: "http://localhost:8787".to_string(),
452                    members: vec![],
453                },
454            )]),
455        }
456    }
457
458    /// Answers by path, recording each request.
459    struct Fake(RefCell<Vec<String>>);
460
461    impl Post for Fake {
462        fn post(&self, url: &str, headers: &[(String, String)]) -> Result<(u16, String), String> {
463            self.0.borrow_mut().push(url.to_string());
464            assert!(
465                headers
466                    .iter()
467                    .any(|(k, v)| k == "X-Bynk-Caller" && v == "bynk.dev"),
468                "{headers:?}"
469            );
470            if url.contains("/_bynk/inspect/agents") {
471                Ok((200, r#"{"context":"shop.orders","instances":[{"class":"Ledger","key":"u1","id":"abc"},{"class":"Ledger","key":7,"id":"def"}]}"#.into()))
472            } else if url.contains("/_bynk/inspect/agent/Ledger") {
473                Ok((200, r#"{"class":"Ledger","exists":true,"readable":true,"cells":{"n":1},"collections":{}}"#.into()))
474            } else {
475                Ok((404, String::new()))
476            }
477        }
478    }
479
480    #[test]
481    fn the_context_of_a_worker_is_its_dotted_name() {
482        assert_eq!(context_of_worker("shop-orders"), "shop.orders");
483    }
484
485    #[test]
486    fn a_typed_key_matches_a_string_by_text_and_anything_else_by_json() {
487        assert!(key_matches(&json!("u1"), "u1"));
488        assert!(!key_matches(&json!("u1"), "\"u1\""));
489        assert!(key_matches(&json!(7), "7"));
490        assert!(key_matches(&json!({"a": 1}), r#"{"a":1}"#));
491        assert!(!key_matches(&json!(7), "8"));
492    }
493
494    #[test]
495    fn a_request_is_signed_as_bynk_dev_and_carries_its_query() {
496        let (url, headers) = signed_request(
497            "http://localhost:8787/",
498            "shop.orders",
499            "/_bynk/inspect/agent/Ledger",
500            &[("id", "a b".to_string()), ("limit", "5".to_string())],
501            1_700_000_000,
502        );
503        assert_eq!(
504            url,
505            "http://localhost:8787/_bynk/inspect/agent/Ledger?id=a%20b&limit=5"
506        );
507        assert!(
508            headers
509                .iter()
510                .any(|(k, v)| k == "X-Bynk-Caller" && v == "bynk.dev")
511        );
512        assert!(headers.iter().any(|(k, _)| k == "X-Bynk-Signature"));
513    }
514
515    #[test]
516    fn the_caller_key_var_is_the_edge_key_of_the_caller_name() {
517        let suffix = bynk_emit::INSPECT_CALLER.to_uppercase().replace('.', "__");
518        assert_eq!(
519            bynk_emit::INSPECT_CALLER_KEY_VAR,
520            format!("BYNK_CALL_FROM_{suffix}")
521        );
522        // #4003: and the protocol table's fixed `BYNK_CALL_FROM_` member is that key.
523        assert_eq!(
524            bynk_emit::wire_format::edge_key_from(bynk_emit::INSPECT_CALLER).as_deref(),
525            Some(bynk_project::env_protocol::CALL_FROM_BYNK_DEV)
526        );
527    }
528
529    #[test]
530    fn agents_are_listed_with_their_context() {
531        let http = Fake(RefCell::default());
532        let out = run(
533            &session(),
534            &Inspect::Agents {
535                context: None,
536                class: None,
537            },
538            &http,
539        )
540        .unwrap();
541        assert_eq!(out["agents"].as_array().unwrap().len(), 2);
542        assert_eq!(out["agents"][0]["context"], "shop.orders");
543        assert_eq!(out["agents"][0]["key"], "u1");
544        assert_eq!(out["errors"], json!([]));
545    }
546
547    #[test]
548    fn an_agent_is_found_by_key_and_read_by_id() {
549        let http = Fake(RefCell::default());
550        let what = Inspect::Agent {
551            context: None,
552            class: "Ledger".into(),
553            key: "7".into(),
554            page: Page {
555                limit: Some(10),
556                ..Page::default()
557            },
558        };
559        let out = run(&session(), &what, &http).unwrap();
560        assert_eq!(out["id"], "def");
561        assert_eq!(out["key"], 7);
562        assert_eq!(out["context"], "shop.orders");
563        assert_eq!(out["cells"]["n"], 1);
564        let seen = http.0.borrow();
565        assert!(
566            seen.last()
567                .unwrap()
568                .ends_with("/_bynk/inspect/agent/Ledger?id=def&limit=10"),
569            "{seen:?}"
570        );
571    }
572
573    #[test]
574    fn an_unaddressed_instance_says_so() {
575        let http = Fake(RefCell::default());
576        let what = Inspect::Agent {
577            context: Some("shop.orders".into()),
578            class: "Ledger".into(),
579            key: "nobody".into(),
580            page: Page::default(),
581        };
582        let e = run(&session(), &what, &http).unwrap_err();
583        assert!(e.contains("has been addressed"), "{e}");
584    }
585
586    /// Two Workers: `shop.api` hosts no agent, so it has no inspect route and answers
587    /// `404`; `shop.orders` hosts `Ledger`. The one without agents must not hide the other.
588    fn two_workers() -> Session {
589        let mut session = session();
590        session.workers.insert(
591            "shop-api".to_string(),
592            SessionWorker {
593                context: "shop.api".to_string(),
594                url: "http://localhost:8788".to_string(),
595                members: vec![],
596            },
597        );
598        // `shop-api` sorts before `shop-orders`.
599        session.workers.insert(
600            "shop-orders".to_string(),
601            SessionWorker {
602                context: "shop.orders".to_string(),
603                url: "http://localhost:8787".to_string(),
604                members: vec![],
605            },
606        );
607        session
608    }
609
610    struct Routes;
611
612    impl Post for Routes {
613        fn post(&self, url: &str, _: &[(String, String)]) -> Result<(u16, String), String> {
614            if url.starts_with("http://localhost:8788") {
615                return Ok((404, "Not Found".into()));
616            }
617            Fake(RefCell::default()).post(url, &[("X-Bynk-Caller".into(), "bynk.dev".into())])
618        }
619    }
620
621    #[test]
622    fn a_worker_without_agents_does_not_hide_the_one_that_has_them() {
623        let out = run(
624            &two_workers(),
625            &Inspect::Agent {
626                context: None,
627                class: "Ledger".into(),
628                key: "u1".into(),
629                page: Page::default(),
630            },
631            &Routes,
632        )
633        .unwrap();
634        assert_eq!(out["context"], "shop.orders");
635        assert_eq!(out["key"], "u1");
636        // And listing says nothing is wrong with it.
637        let listed = run(
638            &two_workers(),
639            &Inspect::Agents {
640                context: None,
641                class: None,
642            },
643            &Routes,
644        )
645        .unwrap();
646        assert_eq!(listed["errors"], json!([]));
647        assert_eq!(listed["agents"].as_array().unwrap().len(), 2);
648    }
649
650    #[test]
651    fn a_worker_that_is_down_is_skipped_and_named_when_nothing_matches() {
652        struct OneDown;
653        impl Post for OneDown {
654            fn post(&self, url: &str, h: &[(String, String)]) -> Result<(u16, String), String> {
655                if url.starts_with("http://localhost:8788") {
656                    return Err("connection refused".into());
657                }
658                Routes.post(url, h)
659            }
660        }
661        let found = run(
662            &two_workers(),
663            &Inspect::Agent {
664                context: None,
665                class: "Ledger".into(),
666                key: "u1".into(),
667                page: Page::default(),
668            },
669            &OneDown,
670        );
671        assert!(found.is_ok(), "{found:?}");
672        let missing = run(
673            &two_workers(),
674            &Inspect::Agent {
675                context: None,
676                class: "Ledger".into(),
677                key: "nobody".into(),
678                page: Page::default(),
679            },
680            &OneDown,
681        )
682        .unwrap_err();
683        assert!(
684            missing.contains("shop.api: connection refused"),
685            "{missing}"
686        );
687    }
688
689    #[test]
690    fn an_unknown_context_is_refused() {
691        let http = Fake(RefCell::default());
692        let e = run(
693            &session(),
694            &Inspect::Agents {
695                context: Some("nope".into()),
696                class: None,
697            },
698            &http,
699        )
700        .unwrap_err();
701        assert!(e.contains("no context `nope`"), "{e}");
702    }
703
704    #[test]
705    fn a_worker_that_is_down_is_reported_and_the_rest_answer() {
706        struct Down;
707        impl Post for Down {
708            fn post(&self, _: &str, _: &[(String, String)]) -> Result<(u16, String), String> {
709                Err("connection refused".into())
710            }
711        }
712        let out = run(
713            &session(),
714            &Inspect::Agents {
715                context: None,
716                class: None,
717            },
718            &Down,
719        )
720        .unwrap();
721        assert_eq!(out["agents"], json!([]));
722        assert_eq!(out["errors"][0]["context"], "shop.orders");
723    }
724
725    #[test]
726    fn the_session_file_is_written_and_removed() {
727        let dir = std::env::temp_dir().join(format!("bynk-session-{}", std::process::id()));
728        std::fs::create_dir_all(dir.join(".bynk").join("dev")).unwrap();
729        {
730            let _file = SessionFile::write(&dir, &session());
731            let read: Session =
732                serde_json::from_str(&std::fs::read_to_string(session_path(&dir)).unwrap())
733                    .unwrap();
734            assert_eq!(read, session());
735        }
736        assert!(!session_path(&dir).exists());
737        let _ = std::fs::remove_dir_all(&dir);
738    }
739
740    /// One Worker, a group `core` of `shop.api` (no agent), `shop.orders` (`Ledger`) and
741    /// `shop.stock` (`Shelf`).
742    fn group() -> Session {
743        Session {
744            workers: BTreeMap::from([(
745                "core".to_string(),
746                SessionWorker {
747                    context: "core".to_string(),
748                    url: "http://localhost:8787".to_string(),
749                    members: vec![
750                        InspectMember {
751                            context: "shop.orders".to_string(),
752                            classes: vec!["Ledger".to_string()],
753                        },
754                        InspectMember {
755                            context: "shop.stock".to_string(),
756                            classes: vec!["Shelf".to_string()],
757                        },
758                    ],
759                },
760            )]),
761        }
762    }
763
764    /// Answers as the group's entry does: a request is answered only if it is signed for
765    /// the member that owns it (the listing: the first agent-hosting member; a read: the
766    /// class's owner), and refused with `401` otherwise.
767    struct Entry;
768
769    impl Entry {
770        fn signed_for(url: &str, headers: &[(String, String)], audience: &str) -> bool {
771            let path = url
772                .trim_start_matches("http://localhost:8787")
773                .split('?')
774                .next()
775                .unwrap();
776            let stamp: u64 = headers
777                .iter()
778                .find(|(k, _)| k.eq_ignore_ascii_case(bynk_check::wire_format::TIMESTAMP_HEADER))
779                .unwrap()
780                .1
781                .parse()
782                .unwrap();
783            crate::migrate::sweep::signed_headers_as(
784                bynk_emit::INSPECT_CALLER,
785                bynk_emit::LOCAL_CALL_KEY,
786                audience,
787                path,
788                "",
789                stamp,
790            ) == headers
791        }
792    }
793
794    impl Post for Entry {
795        fn post(&self, url: &str, headers: &[(String, String)]) -> Result<(u16, String), String> {
796            if url.contains("/_bynk/inspect/agents") {
797                return if Self::signed_for(url, headers, "shop.orders") {
798                    Ok((200, r#"{"context":"shop.orders","instances":[{"class":"Ledger","key":"u1","id":"a"},{"class":"Shelf","key":"s1","id":"b"}]}"#.into()))
799                } else {
800                    Ok((401, String::new()))
801                };
802            }
803            let owner = if url.contains("/agent/Shelf") {
804                "shop.stock"
805            } else {
806                "shop.orders"
807            };
808            if Self::signed_for(url, headers, owner) {
809                Ok((
810                    200,
811                    r#"{"exists":true,"readable":true,"cells":{},"collections":{}}"#.into(),
812                ))
813            } else {
814                Ok((401, String::new()))
815            }
816        }
817    }
818
819    #[test]
820    fn a_group_lists_every_members_agents_under_the_member_that_owns_each() {
821        let what = Inspect::Agents {
822            context: None,
823            class: None,
824        };
825        let out = run(&group(), &what, &Entry).unwrap();
826        assert_eq!(out["errors"], json!([]), "{out}");
827        let contexts: Vec<(&str, &str)> = out["agents"]
828            .as_array()
829            .unwrap()
830            .iter()
831            .map(|a| (a["class"].as_str().unwrap(), a["context"].as_str().unwrap()))
832            .collect();
833        assert_eq!(
834            contexts,
835            [("Ledger", "shop.orders"), ("Shelf", "shop.stock")]
836        );
837    }
838
839    #[test]
840    fn a_group_read_is_signed_for_the_member_that_owns_the_class() {
841        for (class, key, owner) in [
842            ("Ledger", "u1", "shop.orders"),
843            ("Shelf", "s1", "shop.stock"),
844        ] {
845            let what = Inspect::Agent {
846                context: None,
847                class: class.to_string(),
848                key: key.to_string(),
849                page: Page::default(),
850            };
851            let out = run(&group(), &what, &Entry).unwrap();
852            assert_eq!(out["context"], owner, "{out}");
853        }
854    }
855
856    #[test]
857    fn a_member_context_selects_the_group_that_serves_it() {
858        let what = Inspect::Agents {
859            context: Some("shop.stock".to_string()),
860            class: None,
861        };
862        assert!(run(&group(), &what, &Entry).is_ok());
863        let what = Inspect::Agents {
864            context: Some("shop.nowhere".to_string()),
865            class: None,
866        };
867        assert!(run(&group(), &what, &Entry).is_err());
868    }
869
870    /// `inspect --context` takes every name `dev --context` does: a member's dashed
871    /// form, and a member that hosts no agent (the group is served, and has none to list).
872    #[test]
873    fn a_context_names_a_member_dashed_or_agentless() {
874        let mut session = group();
875        let worker = session.workers.get_mut("core").unwrap();
876        worker.members.insert(
877            0,
878            InspectMember {
879                context: "shop.api".to_string(),
880                classes: vec![],
881            },
882        );
883        // The listing is still signed for the first member that hosts an agent.
884        assert_eq!(session.workers["core"].lister(), "shop.orders");
885        for context in ["shop-stock", "shop.api", "shop-api"] {
886            let what = Inspect::Agents {
887                context: Some(context.to_string()),
888                class: None,
889            };
890            let out = run(&session, &what, &Entry).unwrap();
891            assert_eq!(out["errors"], json!([]), "{context}: {out}");
892        }
893    }
894}