Skip to main content

bynk_project/
env_protocol.rs

1//! Back-half paydown 1D.5a (#4003): the cross-language `BYNK_*` protocol.
2//!
3//! The toolchain hands generated TypeScript a small set of names: environment
4//! variables on the `node`/`tsx` process that `bynk test` starts, and entries
5//! in a Worker's `env` (a `[vars]` entry or `--var`, a binding, a secret) that
6//! `bynk dev`, `bynk deploy` and the emitted `wrangler.toml` set. Rust writes
7//! each name and TypeScript reads it, so the two spellings must agree.
8//!
9//! This module is the one definition of each name. Every Rust writer uses
10//! these constants (or a `pub use` of one kept at its older path), so a
11//! misspelt name in Rust fails to compile. The TypeScript readers are written
12//! by hand and keep their string literals, so the emitted output does not
13//! change. `xtask/tests/env_protocol.rs` holds them to [`PROTOCOL`] instead:
14//! every `BYNK_` token a reader spells must be a name here, and every reader an
15//! entry lists must still spell its name.
16//!
17//! Only the protocol lives here. Names that Rust alone reads or sets
18//! (`BYNK_HOME`, `BYNK_NO_INSTALL`, `BYNK_PHASE_TIMING` and the like) stay with
19//! their owners, and test gates stay in the tests (#4003, Decision E). No name
20//! here may be renamed: each one is part of what a generated program reads.
21
22/// How a name reaches the TypeScript that reads it.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Carrier {
25    /// An environment variable on the test process (`process.env`).
26    Process,
27    /// A Worker variable: a `[vars]` entry or a `wrangler dev --var` (`env`).
28    WorkerVar,
29    /// A Worker binding's name in the generated `wrangler.toml` (`env`).
30    Binding,
31    /// A Worker secret (`env`).
32    Secret,
33}
34
35/// Whether an entry is one name, or the prefix of a family of names.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Shape {
38    /// The name exactly.
39    Exact,
40    /// A prefix to which a binding, context or kind name is appended. `members`
41    /// are the family's fixed names, where it has any.
42    Prefix { members: &'static [&'static str] },
43}
44
45/// Where the hand-written readers live. [`Reader::path`] joins a reader's file
46/// to its directory, so a directory that moves changes one line here. The test
47/// runtime's readers are `testing/<name>.ts` under [`ReaderDir::Runtime`] (1B.3a,
48/// #4047): the sources, not the spliced artifacts in `bynk-emit/src/testgen`.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum ReaderDir {
51    /// The emitted runtime's sources, `bynk-emit/runtime/src`.
52    Runtime,
53    /// The standard library's binding sources, `bynk-std/lib`.
54    Std,
55}
56
57impl ReaderDir {
58    /// Every reader directory, for a scan that wants them all.
59    pub const ALL: [ReaderDir; 2] = [ReaderDir::Runtime, ReaderDir::Std];
60
61    /// The directory, from the repository root.
62    pub const fn path(self) -> &'static str {
63        match self {
64            ReaderDir::Runtime => "bynk-emit/runtime/src",
65            ReaderDir::Std => "bynk-std/lib",
66        }
67    }
68}
69
70/// One hand-written TypeScript file that reads a protocol name.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct Reader {
73    pub dir: ReaderDir,
74    /// The file, relative to [`Reader::dir`].
75    pub file: &'static str,
76}
77
78impl Reader {
79    /// The reader's path from the repository root.
80    pub fn path(&self) -> String {
81        format!("{}/{}", self.dir.path(), self.file)
82    }
83}
84
85/// One protocol name.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub struct Entry {
88    pub name: &'static str,
89    pub carrier: Carrier,
90    pub shape: Shape,
91    /// The Rust that sets it, as a path.
92    pub set_by: &'static str,
93    /// The hand-written TypeScript files that read it. Empty when the only
94    /// reader is TypeScript the toolchain emits from this constant.
95    pub readers: &'static [Reader],
96    /// The Rust that emits a TypeScript reader of it, where one does.
97    pub emitted_by: Option<&'static str>,
98}
99
100// --- The test process (`bynk test`) ----------------------------------------
101
102/// `ndjson` when the driver wants one JSON event per line from a test run.
103pub const TEST_FORMAT: &str = "BYNK_TEST_FORMAT";
104/// The JSON test filter `bynk test --filter` hands the generated test main.
105pub const TEST_FILTER: &str = "BYNK_TEST_FILTER";
106/// The hex seed of a property-test run.
107pub const TEST_SEED: &str = "BYNK_TEST_SEED";
108/// How long, in milliseconds, a test waits for a deferred effect to settle.
109pub const TEST_SETTLE_MS: &str = "BYNK_TEST_SETTLE_MS";
110/// The JSON `[test.targets]` a remote test run reaches.
111pub const TEST_TARGETS: &str = "BYNK_TEST_TARGETS";
112/// The secrets of a remote test run, as JSON.
113pub const TEST_SECRETS: &str = "BYNK_TEST_SECRETS";
114/// The run id a remote test run tags what it writes with.
115pub const TEST_RUN_ID: &str = "BYNK_TEST_RUN_ID";
116/// `1` when a smoke run treats an undeclared wire shape as a failure.
117pub const TEST_STRICT_WIRE: &str = "BYNK_TEST_STRICT_WIRE";
118/// The file a smoke run writes the declared statuses it saw to.
119pub const SMOKE_DECLARED_FILE: &str = "BYNK_SMOKE_DECLARED_FILE";
120/// `1` when `bynk test --update-snapshots` rewrites snapshots.
121pub const UPDATE_SNAPSHOTS: &str = "BYNK_UPDATE_SNAPSHOTS";
122/// `1` when the driver wants the snapshot files a run touched reported.
123pub const SNAPSHOT_REPORT: &str = "BYNK_SNAPSHOT_REPORT";
124
125// --- A Worker's `env` ------------------------------------------------------
126
127/// `1` on every Worker `bynk dev` serves, so a provider can tell a development
128/// session from a deployment.
129pub const DEV: &str = "BYNK_DEV";
130/// The prefix of the `[dev]` acknowledgement variables
131/// (`crate::dev_ack::REMOTE_KINDS`).
132pub const DEV_ACK_PREFIX: &str = "BYNK_DEV_ACK_";
133/// `[dev] ai = "allow"`.
134pub const DEV_ACK_AI: &str = "BYNK_DEV_ACK_AI";
135/// `[dev] vectorize = "allow"`.
136pub const DEV_ACK_VECTORIZE: &str = "BYNK_DEV_ACK_VECTORIZE";
137/// `[dev] ai-search = "allow"`.
138pub const DEV_ACK_AI_SEARCH: &str = "BYNK_DEV_ACK_AI_SEARCH";
139/// `[dev] mtls = "allow"`.
140pub const DEV_ACK_MTLS: &str = "BYNK_DEV_ACK_MTLS";
141/// `[dev] analytics-sql = "allow"`.
142pub const DEV_ACK_ANALYTICS_SQL: &str = "BYNK_DEV_ACK_ANALYTICS_SQL";
143/// The prefix of the `[vars]` entry giving a local Vectorize index its
144/// dimensions and metric under `bynk dev`, followed by the binding name.
145pub const DEV_INDEX_PREFIX: &str = "BYNK_DEV_INDEX_";
146/// The prefix of the `[vars]` entry naming an Analytics Engine dataset's
147/// table, followed by the binding name. Reserved in `[test.targets]` vars.
148pub const DATASET_PREFIX: &str = "BYNK_DATASET_";
149/// The prefix of the secret a callee holds for the edge from one caller,
150/// followed by the caller's edge suffix.
151pub const CALL_FROM_PREFIX: &str = "BYNK_CALL_FROM_";
152/// The prefix of the secret a caller holds for the edge to one callee,
153/// followed by the callee's edge suffix.
154pub const CALL_TO_PREFIX: &str = "BYNK_CALL_TO_";
155/// The edge key from `bynk dev inspect`'s caller, `bynk.dev`: the
156/// [`CALL_FROM_PREFIX`] family's one fixed member.
157pub const CALL_FROM_BYNK_DEV: &str = "BYNK_CALL_FROM_BYNK__DEV";
158/// The `wrangler dev --var` that tells a generated container class its
159/// containers are off (`bynk dev` without Docker).
160pub const CONTAINERS_UNAVAILABLE: &str = "BYNK_CONTAINERS_UNAVAILABLE";
161/// The binding name of `bynk dev`'s agent-inspection registry.
162pub const INSPECT_REGISTRY: &str = "__BYNK_INSPECT_REGISTRY";
163/// The secret a `bynk migrate sweep` key is set under for the sweep.
164pub const MIGRATE_KEY: &str = "BYNK_MIGRATE_KEY";
165
166const fn runtime(file: &'static str) -> Reader {
167    Reader {
168        dir: ReaderDir::Runtime,
169        file,
170    }
171}
172
173const CLOUDFLARE_BINDING: Reader = Reader {
174    dir: ReaderDir::Std,
175    file: "cloudflare/cloudflare.binding.ts",
176};
177
178/// The generated test main, which emits the readers of the names it reads.
179const TEST_MAIN: &str = "bynk-emit::testgen::test_main";
180
181const fn process(
182    name: &'static str,
183    set_by: &'static str,
184    readers: &'static [Reader],
185    emitted_by: Option<&'static str>,
186) -> Entry {
187    Entry {
188        name,
189        carrier: Carrier::Process,
190        shape: Shape::Exact,
191        set_by,
192        readers,
193        emitted_by,
194    }
195}
196
197const fn worker(
198    name: &'static str,
199    carrier: Carrier,
200    shape: Shape,
201    set_by: &'static str,
202    readers: &'static [Reader],
203) -> Entry {
204    Entry {
205        name,
206        carrier,
207        shape,
208        set_by,
209        readers,
210        emitted_by: None,
211    }
212}
213
214/// Every protocol name, with who sets it and who reads it.
215pub const PROTOCOL: &[Entry] = &[
216    process(
217        TEST_FORMAT,
218        "bynk-driver::test_runner",
219        &[runtime("http.ts")],
220        Some(TEST_MAIN),
221    ),
222    process(
223        TEST_FILTER,
224        "bynk-driver::test_filter",
225        &[],
226        Some(TEST_MAIN),
227    ),
228    process(
229        TEST_SEED,
230        "bynk-driver::test_runner",
231        &[runtime("testing/property.ts")],
232        None,
233    ),
234    process(
235        TEST_SETTLE_MS,
236        "bynk-driver::test_runner",
237        &[runtime("testing/settle.ts")],
238        None,
239    ),
240    process(
241        TEST_TARGETS,
242        "bynk-driver::test_runner",
243        &[runtime("testing/remote.ts")],
244        None,
245    ),
246    process(
247        TEST_SECRETS,
248        "bynk-driver::test_runner",
249        &[runtime("testing/remote.ts")],
250        None,
251    ),
252    process(
253        TEST_RUN_ID,
254        "bynk-driver::test_runner",
255        &[runtime("testing/run_id.ts")],
256        None,
257    ),
258    process(
259        TEST_STRICT_WIRE,
260        "bynk-driver::test_runner",
261        &[runtime("http.ts")],
262        None,
263    ),
264    process(
265        SMOKE_DECLARED_FILE,
266        "bynk-driver::test_runner",
267        &[runtime("http.ts")],
268        None,
269    ),
270    process(
271        UPDATE_SNAPSHOTS,
272        "bynk-driver::test_runner",
273        &[runtime("testing/snapshot.ts")],
274        None,
275    ),
276    process(
277        SNAPSHOT_REPORT,
278        "bynk-driver::test_runner",
279        &[],
280        Some(TEST_MAIN),
281    ),
282    worker(
283        DEV,
284        Carrier::WorkerVar,
285        Shape::Exact,
286        "bynk::dev::dev_var_args",
287        &[CLOUDFLARE_BINDING],
288    ),
289    worker(
290        DEV_ACK_PREFIX,
291        Carrier::WorkerVar,
292        Shape::Prefix {
293            members: &[
294                DEV_ACK_AI,
295                DEV_ACK_VECTORIZE,
296                DEV_ACK_AI_SEARCH,
297                DEV_ACK_MTLS,
298                DEV_ACK_ANALYTICS_SQL,
299            ],
300        },
301        "bynk::dev::dev_var_args (bynk-project::dev_ack::REMOTE_KINDS)",
302        &[CLOUDFLARE_BINDING],
303    ),
304    worker(
305        DEV_INDEX_PREFIX,
306        Carrier::WorkerVar,
307        Shape::Prefix { members: &[] },
308        "bynk-emit::emitter::wrangler",
309        &[CLOUDFLARE_BINDING],
310    ),
311    worker(
312        DATASET_PREFIX,
313        Carrier::WorkerVar,
314        Shape::Prefix { members: &[] },
315        "bynk-emit::emitter::wrangler",
316        &[CLOUDFLARE_BINDING],
317    ),
318    worker(
319        CALL_FROM_PREFIX,
320        Carrier::Secret,
321        Shape::Prefix {
322            members: &[CALL_FROM_BYNK_DEV],
323        },
324        "bynk::deploy::secrets and bynk::dev (bynk-check::wire_format::edge_key_from)",
325        &[runtime("boundary.ts")],
326    ),
327    worker(
328        CALL_TO_PREFIX,
329        Carrier::Secret,
330        Shape::Prefix { members: &[] },
331        "bynk::deploy::secrets and bynk::dev (bynk-check::wire_format::edge_key_to)",
332        &[runtime("boundary.ts")],
333    ),
334    worker(
335        CONTAINERS_UNAVAILABLE,
336        Carrier::WorkerVar,
337        Shape::Exact,
338        "bynk::dev_containers",
339        &[runtime("container.ts")],
340    ),
341    worker(
342        INSPECT_REGISTRY,
343        Carrier::Binding,
344        Shape::Exact,
345        "bynk-emit::emitter::wrangler",
346        &[runtime("inspect.ts")],
347    ),
348    Entry {
349        name: MIGRATE_KEY,
350        carrier: Carrier::Secret,
351        shape: Shape::Exact,
352        set_by: "bynk::migrate",
353        readers: &[],
354        emitted_by: Some("bynk-emit::emitter::workers_entry"),
355    },
356];
357
358/// Every concrete name and prefix the protocol spells: each entry's name, and
359/// each prefix's fixed members.
360pub fn all_names() -> impl Iterator<Item = &'static str> {
361    PROTOCOL.iter().flat_map(|entry| {
362        let members: &'static [&'static str] = match entry.shape {
363            Shape::Exact => &[],
364            Shape::Prefix { members } => members,
365        };
366        std::iter::once(entry.name).chain(members.iter().copied())
367    })
368}
369
370/// The entry `token` belongs to: the entry it names, or the prefix entry it
371/// starts with (a family member such as `BYNK_DATASET_ANALYTICS_SIGNUPS`).
372pub fn entry_of(token: &str) -> Option<&'static Entry> {
373    PROTOCOL.iter().find(|entry| match entry.shape {
374        Shape::Exact => entry.name == token,
375        Shape::Prefix { .. } => token.starts_with(entry.name),
376    })
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382    use std::collections::BTreeSet;
383
384    #[test]
385    fn the_protocol_has_twenty_keys_and_twenty_four_names_a_reader_spells() {
386        assert_eq!(PROTOCOL.len(), 20);
387        // `BYNK_DEV_ACK_` is a family of five fixed members, so the keys come to
388        // 24 names a reader spells. The prefix itself is a token, not a name, and
389        // `BYNK_CALL_FROM_BYNK__DEV` is derived from its prefix at run time.
390        let spelt = all_names()
391            .filter(|n| *n != DEV_ACK_PREFIX && *n != CALL_FROM_BYNK_DEV)
392            .count();
393        assert_eq!(spelt, 24);
394    }
395
396    #[test]
397    fn names_are_unique() {
398        let mut seen = BTreeSet::new();
399        for name in all_names() {
400            assert!(seen.insert(name), "{name} is listed twice");
401        }
402    }
403
404    #[test]
405    fn names_are_upper_snake_in_the_bynk_namespace() {
406        for name in all_names() {
407            let rest = name
408                .strip_prefix("__BYNK_")
409                .or_else(|| name.strip_prefix("BYNK_"))
410                .unwrap_or_else(|| panic!("{name} is outside the BYNK_ namespace"));
411            assert!(!rest.is_empty(), "{name}");
412            assert!(
413                rest.bytes()
414                    .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_'),
415                "{name} is not upper snake case"
416            );
417        }
418    }
419
420    #[test]
421    fn prefixes_end_in_an_underscore_and_exact_names_do_not() {
422        for entry in PROTOCOL {
423            match entry.shape {
424                Shape::Prefix { members } => {
425                    assert!(entry.name.ends_with('_'), "{}", entry.name);
426                    for member in members {
427                        assert!(member.starts_with(entry.name), "{member}");
428                        assert!(member.len() > entry.name.len(), "{member}");
429                    }
430                }
431                Shape::Exact => assert!(!entry.name.ends_with('_'), "{}", entry.name),
432            }
433        }
434    }
435
436    #[test]
437    fn every_entry_has_a_reader() {
438        for entry in PROTOCOL {
439            assert!(
440                !entry.readers.is_empty() || entry.emitted_by.is_some(),
441                "{} has no reader",
442                entry.name
443            );
444        }
445    }
446
447    #[test]
448    fn process_variables_are_test_process_names() {
449        for entry in PROTOCOL.iter().filter(|e| e.carrier == Carrier::Process) {
450            assert_eq!(entry.shape, Shape::Exact, "{}", entry.name);
451            assert!(
452                entry.name.starts_with("BYNK_TEST_")
453                    || entry.name.starts_with("BYNK_SMOKE_")
454                    || entry.name.starts_with("BYNK_UPDATE_")
455                    || entry.name.starts_with("BYNK_SNAPSHOT_"),
456                "{}",
457                entry.name
458            );
459        }
460    }
461
462    #[test]
463    fn a_name_finds_its_entry_and_a_family_member_its_prefix() {
464        assert_eq!(entry_of(TEST_SEED).map(|e| e.name), Some(TEST_SEED));
465        assert_eq!(
466            entry_of("BYNK_DATASET_ANALYTICS_SIGNUPS").map(|e| e.name),
467            Some(DATASET_PREFIX)
468        );
469        assert_eq!(
470            entry_of(DEV_ACK_AI).map(|e| e.name),
471            Some(DEV_ACK_PREFIX),
472            "an acknowledgement belongs to its family"
473        );
474        assert_eq!(
475            entry_of(CALL_FROM_BYNK_DEV).map(|e| e.name),
476            Some(CALL_FROM_PREFIX)
477        );
478        // `BYNK_DEV` is exact: a longer name is not one of its members.
479        assert_eq!(entry_of("BYNK_DEV_COMMAND"), None);
480        assert_eq!(entry_of("BYNK_TEST_SEDE"), None);
481    }
482
483    #[test]
484    fn the_dev_acknowledgements_are_the_ack_family() {
485        let kinds: Vec<&str> = crate::dev_ack::REMOTE_KINDS.iter().map(|k| k.var).collect();
486        let Some(Shape::Prefix { members }) = entry_of(DEV_ACK_AI).map(|e| e.shape) else {
487            panic!("the acknowledgements are a prefix family");
488        };
489        assert_eq!(kinds, members);
490    }
491
492    #[test]
493    fn reader_paths_join_the_directory() {
494        assert_eq!(
495            CLOUDFLARE_BINDING.path(),
496            "bynk-std/lib/cloudflare/cloudflare.binding.ts"
497        );
498        assert_eq!(
499            runtime("testing/property.ts").path(),
500            "bynk-emit/runtime/src/testing/property.ts"
501        );
502    }
503}