Skip to main content

bynk_check/
stability.rs

1//! Experimental standard-library items and the project's opt-in to them
2//! (standard-library S3, #1963; track D2).
3//!
4//! A first-party item (a unit, an exported item, or a capability operation, by
5//! dotted path) is stable or experimental. Using an experimental one needs an
6//! entry covering it under `bynk.toml`'s `[unstable] allow`. One
7//! [`StabilityPolicy`] per project carries that list and the experimental items,
8//! and both the build and the editor build it the same way
9//! ([`StabilityPolicy::for_project`]), so they never disagree about a file.
10
11use crate::firstparty;
12use bynk_syntax::CompileError;
13use bynk_syntax::span::Span;
14use std::collections::HashMap;
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18/// The manifest the `[unstable]` diagnostics are attributed to.
19pub const MANIFEST: &str = "bynk.toml";
20/// The diagnostic for using an experimental item without opting in.
21pub const EXPERIMENTAL: &str = "bynk.stability.experimental";
22/// The warning for an `[unstable] allow` entry that reaches nothing experimental.
23pub const NOT_EXPERIMENTAL: &str = "bynk.project.unstable_not_experimental";
24/// The error for an `[unstable] allow` entry that names no first-party item.
25pub const UNKNOWN_ITEM: &str = "bynk.project.unstable_unknown_item";
26
27/// The stability facts one unit's checks need: the project's policy, for the
28/// paths a check computes itself (a capability operation), and the unit's
29/// imports that are blocked, by name, decided where provenance is known.
30#[derive(Debug, Clone, Default, PartialEq, Eq)]
31pub struct UnitStability {
32    pub policy: Arc<StabilityPolicy>,
33    /// Imported name → item path, for each import [`StabilityPolicy::blocks`].
34    pub blocked_imports: HashMap<String, String>,
35}
36
37/// A project's stability policy: what is experimental, and what it allows.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct StabilityPolicy {
40    /// The `[unstable] allow` entries, in manifest order.
41    pub allow: Vec<String>,
42    /// The experimental item paths; an item under one is experimental too.
43    /// [`firstparty::experimental_items`] unless a test supplies its own.
44    pub experimental: Vec<String>,
45    /// #3321: whether the project supplies a `schema.sql`, which switches on the
46    /// check of each literal `Postgres` statement (`pg_sql`). Not a stability
47    /// matter: the policy is the one project-wide value every unit's check
48    /// already carries (and is hashed into), so this rides with it rather than
49    /// through each of the ways a unit is checked.
50    pub pg_sql: bool,
51}
52
53impl Default for StabilityPolicy {
54    /// Blocks nothing. A check input built without
55    /// [`crate::resolver::ResolvedCommons::with_stability`] (a suite case body,
56    /// `resolve_recovering`) is under neither rule, so the default must fail
57    /// open: a default that knew the experimental items but no `allow` would
58    /// refuse them while ignoring the project's opt-in. The real policy is
59    /// built only by [`StabilityPolicy::for_project`].
60    fn default() -> Self {
61        Self::permissive()
62    }
63}
64
65impl StabilityPolicy {
66    /// The policy for the project at `project_root`, reading `[unstable]` from
67    /// the overlay's `bynk.toml` or the one on disk. No project root (a
68    /// single-file or in-memory build) allows nothing.
69    pub fn for_project(project_root: Option<&Path>, overlay: &HashMap<PathBuf, String>) -> Self {
70        let allow = project_root
71            .map(|root| bynk_project::read_unstable_config(root, overlay).allow)
72            .unwrap_or_default();
73        let pg_sql = project_root.is_some_and(|root| {
74            let schema = root.join(bynk_project::PG_SCHEMA_FILE);
75            overlay.contains_key(&schema) || schema.is_file()
76        });
77        Self {
78            allow,
79            experimental: firstparty::experimental_items(),
80            pg_sql,
81        }
82    }
83
84    /// A policy under which nothing is experimental: for a first-party unit's
85    /// own bodies, whose dependencies are the library's business.
86    pub fn permissive() -> Self {
87        Self {
88            allow: Vec::new(),
89            experimental: Vec::new(),
90            pg_sql: false,
91        }
92    }
93
94    /// Whether `path` is experimental.
95    pub fn is_experimental(&self, path: &str) -> bool {
96        self.experimental
97            .iter()
98            .any(|item| firstparty::covers(item, path))
99    }
100
101    /// Whether using `path` here is refused: it is experimental and no `allow`
102    /// entry covers it.
103    pub fn blocks(&self, path: &str) -> bool {
104        self.is_experimental(path) && !firstparty::allows(&self.allow, path)
105    }
106
107    /// The error for a use of `path` at `span`, when [`Self::blocks`] refuses it.
108    pub fn check(&self, path: &str, span: Span) -> Option<CompileError> {
109        self.blocks(path).then(|| {
110            CompileError::new(
111                EXPERIMENTAL,
112                span,
113                format!("`{path}` is experimental: it may change or disappear in any release"),
114            )
115            .with_note(format!(
116                "to use it anyway, add \"{path}\" to `[unstable] allow` in `bynk.toml`"
117            ))
118        })
119    }
120
121    /// The diagnostics for the `[unstable] allow` entries themselves, which
122    /// callers attribute to the project's `bynk.toml` ([`MANIFEST`]): an error
123    /// for one that names no first-party
124    /// item, and a warning for one that reaches nothing experimental (stable
125    /// now, so it can go; never an error, so stabilising an item breaks no
126    /// build).
127    pub fn manifest_diagnostics(&self) -> Vec<CompileError> {
128        let mut out = Vec::new();
129        for entry in &self.allow {
130            if !firstparty::names_first_party_item(entry) {
131                out.push(CompileError::new(
132                        UNKNOWN_ITEM,
133                        Span::default(),
134                        format!(
135                            "`bynk.toml`'s `[unstable] allow` lists `{entry}`, which names no standard-library item"
136                        ),
137                    )
138                    .with_note(
139                        "an entry is a unit (`bynk.cloudflare`), an item it exports (`bynk.cloudflare.Kv`) or an operation (`bynk.cloudflare.Kv.list`)",
140                    ));
141            } else if !firstparty::allow_entry_is_live(&self.experimental, entry) {
142                out.push(CompileError::new(
143                        NOT_EXPERIMENTAL,
144                        Span::default(),
145                        format!(
146                            "`bynk.toml`'s `[unstable] allow` lists `{entry}`, but nothing it covers is experimental"
147                        ),
148                    )
149                    .with_note("it is stable now; remove it from `[unstable] allow`"));
150            }
151        }
152        out
153    }
154
155    /// The names a unit imports that are experimental and not allowed, mapped
156    /// to their item paths: `imported_from` is name → providing unit, so the
157    /// path is `unit.name`. Decided once per unit, where provenance is known,
158    /// and carried to every check built from it.
159    pub fn blocked_imports(
160        &self,
161        imported_from: &HashMap<String, String>,
162    ) -> HashMap<String, String> {
163        imported_from
164            .iter()
165            .filter(|(_, unit)| firstparty::unit(unit).is_some())
166            .map(|(name, unit)| (name.clone(), format!("{unit}.{name}")))
167            .filter(|(_, path)| self.blocks(path))
168            .collect()
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn policy(allow: &[&str], experimental: &[&str]) -> StabilityPolicy {
177        StabilityPolicy {
178            allow: allow.iter().map(|s| s.to_string()).collect(),
179            experimental: experimental.iter().map(|s| s.to_string()).collect(),
180            pg_sql: false,
181        }
182    }
183
184    #[test]
185    fn an_experimental_item_is_blocked_until_allowed() {
186        let p = policy(&[], &["bynk.cloudflare.Kv.putTtl"]);
187        assert!(p.blocks("bynk.cloudflare.Kv.putTtl"));
188        assert!(!p.blocks("bynk.cloudflare.Kv.put"));
189        assert!(
190            !p.blocks("bynk.cloudflare.Kv"),
191            "its capability stays stable"
192        );
193        let err = p
194            .check("bynk.cloudflare.Kv.putTtl", Span::default())
195            .unwrap();
196        assert_eq!(err.category, "bynk.stability.experimental");
197        assert!(err.notes[0].contains("\"bynk.cloudflare.Kv.putTtl\""));
198
199        for allow in [
200            "bynk.cloudflare.Kv.putTtl",
201            "bynk.cloudflare.Kv",
202            "bynk.cloudflare",
203        ] {
204            assert!(
205                !policy(&[allow], &["bynk.cloudflare.Kv.putTtl"])
206                    .blocks("bynk.cloudflare.Kv.putTtl"),
207                "{allow}"
208            );
209        }
210    }
211
212    #[test]
213    fn manifest_entries_are_checked_for_existence_and_staleness() {
214        let p = policy(
215            &[
216                "bynk.cloudflare.Kv.putTtl",
217                "bynk.cloudflare",
218                "bynk.list",
219                "bynk.cloudflare.Kvv",
220                "user.thing",
221            ],
222            &["bynk.cloudflare.Kv.putTtl"],
223        );
224        let found: Vec<(String, String)> = p
225            .manifest_diagnostics()
226            .into_iter()
227            .map(|e| (e.category.to_string(), e.message.clone()))
228            .collect();
229        let codes: Vec<&str> = found.iter().map(|(c, _)| c.as_str()).collect();
230        assert_eq!(codes, [NOT_EXPERIMENTAL, UNKNOWN_ITEM, UNKNOWN_ITEM]);
231        assert!(found[0].1.contains("`bynk.list`"), "stale: {found:?}");
232        assert!(found[1].1.contains("`bynk.cloudflare.Kvv`"));
233        assert!(found[2].1.contains("`user.thing`"));
234    }
235
236    #[test]
237    fn blocked_imports_are_first_party_experimental_and_unallowed() {
238        let imported = HashMap::from([
239            ("join".to_string(), "bynk.string".to_string()),
240            ("reverse".to_string(), "bynk.list".to_string()),
241            ("Money".to_string(), "app.money".to_string()),
242        ]);
243        let p = policy(&[], &["bynk.string.join", "app.money"]);
244        assert_eq!(
245            p.blocked_imports(&imported),
246            HashMap::from([("join".to_string(), "bynk.string.join".to_string())]),
247            "a user unit is never experimental, whatever the list says"
248        );
249        assert!(
250            policy(&["bynk.string"], &["bynk.string.join"])
251                .blocked_imports(&imported)
252                .is_empty()
253        );
254    }
255
256    /// The project the end-to-end tests analyse: one reference of each kind to
257    /// a shipped first-party item, the function call inside a handler body
258    /// (where `imported_from` is not available, so the per-unit blocked imports
259    /// must have been carried there).
260    const PROJECT: &[(&str, &str)] = &[
261        (
262            "app/probe.test.bynk",
263            "suite app.probe\n\ncase \"a case calls an operation\" {\n\tlet _ <- Kv.putTtl(\"k\", \"v\", 120)\n\texpect Kv.putTtl called once\n}\n",
264        ),
265        (
266            "app/qual.bynk",
267            "context app.qual\n\nconsumes bynk\n\nservice ping {\n\ton call() -> Effect[Int] by Caller given bynk.Clock {\n\t\tlet _ <- bynk.Clock.now()\n\t\tEffect.pure(1)\n\t}\n}\n",
268        ),
269        (
270            "app/probe.bynk",
271            "context app.probe\n\nuses bynk.string\nuses bynk.locale.types\nconsumes bynk { Random }\nconsumes bynk.cloudflare { Kv }\n\nservice probe {\n\ton call(xs: List[String]) -> Effect[String] by Caller given Kv {\n\t\tlet _ <- Kv.putTtl(\"k\", \"v\", 120)\n\t\tlet joiner: (List[String], String) -> String = join\n\t\tEffect.pure(join(xs, \",\"))\n\t}\n}\n",
272        ),
273    ];
274
275    /// Every `bynk.stability.experimental` the analysis reports, as
276    /// `(item path, reported text)`.
277    fn experimental_uses(policy: StabilityPolicy) -> Vec<(String, String)> {
278        let analysed = crate::testkit::analyse_with(PROJECT, Some(policy));
279        let mut out: Vec<(String, String)> = analysed
280            .analysis
281            .errors
282            .iter()
283            .filter(|a| a.error.category == "bynk.stability.experimental")
284            .map(|a| {
285                let path = a.error.message.split('`').nth(1).unwrap_or("").to_string();
286                let (start, end) = (a.error.span.start, a.error.span.end);
287                let file = a.source_path.as_deref().expect("a use is in a file");
288                let (_, text) = PROJECT
289                    .iter()
290                    .find(|(rel, _)| file.ends_with(rel))
291                    .expect("a project file");
292                (path, text[start..end].to_string())
293            })
294            .collect();
295        out.sort();
296        out
297    }
298
299    /// End to end, through the analysis the editor runs: each kind of
300    /// reference to an experimental item is refused at its own span, and an
301    /// `allow` entry covering it lifts the refusal.
302    #[test]
303    fn every_reference_point_refuses_an_experimental_item() {
304        let experimental = &[
305            "bynk.Clock.now",
306            "bynk.Random",
307            "bynk.locale.types",
308            "bynk.string.join",
309            "bynk.cloudflare.Kv.putTtl",
310        ];
311        assert_eq!(
312            experimental_uses(policy(&[], experimental)),
313            [
314                ("bynk.Clock.now".to_string(), "now".to_string()),
315                ("bynk.Random".to_string(), "Random".to_string()),
316                (
317                    "bynk.cloudflare.Kv.putTtl".to_string(),
318                    "putTtl".to_string()
319                ),
320                (
321                    "bynk.locale.types".to_string(),
322                    "bynk.locale.types".to_string()
323                ),
324                ("bynk.string.join".to_string(), "join".to_string()),
325                ("bynk.string.join".to_string(), "join".to_string()),
326            ],
327            "a consumes selection, a uses, a capability operation (flattened and qualified), and a function called and passed as a value in a handler; never in a suite case"
328        );
329        assert!(
330            experimental_uses(policy(
331                &[
332                    "bynk.Clock",
333                    "bynk.Random",
334                    "bynk.locale",
335                    "bynk.string",
336                    "bynk.cloudflare.Kv"
337                ],
338                experimental
339            ))
340            .is_empty(),
341            "allow entries cover their path and everything under it"
342        );
343        assert!(
344            experimental_uses(StabilityPolicy::default()).is_empty(),
345            "the default fails open"
346        );
347    }
348
349    /// The codes a one-file project's analysis reports.
350    fn codes(source: &str) -> Vec<&'static str> {
351        crate::testkit::analyse(&[("app/probe.bynk", source)])
352            .analysis
353            .errors
354            .iter()
355            .map(|a| a.error.category)
356            .collect()
357    }
358
359    const FETCH_MATCH: &str = "context app.probe\n\nconsumes bynk { Fetch, Request, Method, FetchError }\n\nservice probe {\n\ton call(url: String) -> Effect[String] by Caller given Fetch {\n\t\tlet res <- Fetch.send(Request { method: Get, url: url, contentType: None, authorization: None, headers: Map.empty(), body: None })\n\t\tmatch res {\n\t\t\tOk(r) => Effect.pure(\"ok\")\n\t\t\tErr(Network) => Effect.pure(\"network\")\n\t\t\tErr(Timeout) => Effect.pure(\"timeout\")\n\t\t\tErr(InvalidHeader) => Effect.pure(\"header\")\n\t\t\tErr(InvalidBody) => Effect.pure(\"body\")\nWILDCARD\t\t}\n\t}\n}\n";
360
361    /// An extensible enum (S3, #1963): listing every variant it has today is
362    /// not enough; a wildcard is, and it is then not reported unreachable (the
363    /// future variant is still uncovered when it is reached).
364    #[test]
365    fn an_extensible_enum_needs_a_wildcard_which_is_then_reachable() {
366        assert_eq!(
367            codes(&FETCH_MATCH.replace("WILDCARD", "")),
368            ["bynk.types.extensible_match_needs_wildcard"]
369        );
370        assert_eq!(
371            codes(&FETCH_MATCH.replace("WILDCARD", "\t\t\tErr(_) => Effect.pure(\"later\")\n")),
372            Vec::<&str>::new(),
373            "a wildcard satisfies it, and is not `bynk.types.unreachable_arm`"
374        );
375        assert_eq!(
376            codes(&FETCH_MATCH.replace("WILDCARD", "\t\t\tother => Effect.pure(\"later\")\n")),
377            Vec::<&str>::new(),
378            "so does a binding"
379        );
380    }
381
382    /// A user's own enum of an extensible enum's name is not extensible: the
383    /// rule follows the first-party unit's enum, not the name.
384    #[test]
385    fn a_users_own_enum_of_the_same_name_is_not_extensible() {
386        assert_eq!(
387            codes(
388                "context app.probe\n\ntype FetchError = enum { Network, Timeout, InvalidHeader }\n\nfn label(e: FetchError) -> String {\n\tmatch e {\n\t\tNetwork => \"n\"\n\t\tTimeout => \"t\"\n\t\tInvalidHeader => \"h\"\n\t}\n}\n\nservice probe {\n\ton call() -> Effect[String] by Caller {\n\t\tEffect.pure(label(Network))\n\t}\n}\n"
389            ),
390            Vec::<&str>::new()
391        );
392    }
393
394    /// An input built without `with_stability` (a suite case body,
395    /// `resolve_recovering`) must fail open: the default is the permissive
396    /// policy, not the shipped experimental list with an empty `allow`.
397    #[test]
398    fn the_default_policy_fails_open() {
399        assert_eq!(StabilityPolicy::default(), StabilityPolicy::permissive());
400        assert_eq!(
401            UnitStability::default().policy.experimental,
402            Vec::<String>::new()
403        );
404    }
405
406    /// The shipped policy blocks only the experimental items: today
407    /// `bynk.cloudflare`'s `Service` (interop I5, #1972) and `R2` (P5,
408    /// #2323), and their operations with them, and the whole of `bynk.crypto`
409    /// (K4).
410    #[test]
411    fn the_shipped_policy_blocks_only_the_experimental_items() {
412        let p = StabilityPolicy::for_project(None, &HashMap::new());
413        // `bynk.testing` (#3458) exists only with `bynk-std`'s `test-support` feature.
414        let mut shipped = p.experimental.clone();
415        shipped.retain(|i| i != bynk_std::TESTING_UNIT);
416        assert_eq!(
417            shipped,
418            [
419                "bynk.Fetch.sendWith",
420                "bynk.Fetch.receiveBytes",
421                "bynk.Fetch.sendBytes",
422                "bynk.Fetch.receiveStream",
423                "bynk.Fetch.sendStream",
424                "bynk.Logger.log",
425                "bynk.cloudflare.Service",
426                "bynk.cloudflare.R2",
427                "bynk.cloudflare.RateLimit",
428                "bynk.cloudflare.EdgeCache",
429                "bynk.cloudflare.Queue",
430                "bynk.cloudflare.Analytics",
431                "bynk.cloudflare.Version",
432                "bynk.cloudflare.Ai",
433                "bynk.cloudflare.Images",
434                "bynk.cloudflare.StoredSecret",
435                "bynk.cloudflare.Email",
436                "bynk.cloudflare.Postgres",
437                "bynk.cloudflare.MySql",
438                "bynk.cloudflare.Vectorize",
439                "bynk.cloudflare.Container",
440                "bynk.cloudflare.AiSearch",
441                "bynk.cloudflare.MtlsCertificate",
442                "bynk.cloudflare.AnalyticsSql",
443                "bynk.cloudflare.RequestCf",
444                "bynk.cloudflare.Kv.getWith",
445                "bynk.cloudflare.Kv.putWith",
446                "bynk.cloudflare.Kv.getBytes",
447                "bynk.cloudflare.Kv.putBytes",
448                "bynk.cloudflare.Kv.listPage",
449                "bynk.crypto"
450            ]
451        );
452        assert!(!p.blocks("bynk.cloudflare.Kv.list"));
453        // #3300: the capability and its operation; its record is stable.
454        assert!(p.blocks("bynk.cloudflare.Version.current"));
455        assert!(!p.blocks("bynk.cloudflare.WorkerVersion"));
456        // #3301: the capability and its operation.
457        assert!(p.blocks("bynk.cloudflare.StoredSecret.get"));
458        // #3302: the capability and its operation; its records are stable.
459        assert!(p.blocks("bynk.cloudflare.Email.send"));
460        assert!(!p.blocks("bynk.cloudflare.Message"));
461        // Hyperdrive H1 (#3318): the capability and its operations; its records
462        // are stable.
463        assert!(p.blocks("bynk.cloudflare.Postgres.all"));
464        assert!(!p.blocks("bynk.cloudflare.PgValue"));
465        // Hyperdrive H5 (#3322): `MySql` the same.
466        assert!(p.blocks("bynk.cloudflare.MySql.all"));
467        assert!(!p.blocks("bynk.cloudflare.MySqlValue"));
468        // K5a (#2586): new operations of stable capabilities, alone.
469        assert!(p.blocks("bynk.Fetch.sendWith"));
470        assert!(!p.blocks("bynk.Fetch.send"));
471        assert!(!p.blocks("bynk.FetchOptions"));
472        // K5b (#2604): the byte-body operations, alone.
473        assert!(p.blocks("bynk.Fetch.receiveBytes"));
474        assert!(p.blocks("bynk.Fetch.sendBytes"));
475        assert!(!p.blocks("bynk.BytesResponse"));
476        // K5c (#2627): the streamed-body operations, alone.
477        assert!(p.blocks("bynk.Fetch.receiveStream"));
478        assert!(p.blocks("bynk.Fetch.sendStream"));
479        assert!(!p.blocks("bynk.StreamResponse"));
480        assert!(p.blocks("bynk.Logger.log"));
481        assert!(!p.blocks("bynk.Logger.warn"));
482        // P1 (#2590): the new operations of the stable `Kv`, alone.
483        assert!(p.blocks("bynk.cloudflare.Kv.putWith"));
484        assert!(p.blocks("bynk.cloudflare.Kv.listPage"));
485        assert!(!p.blocks("bynk.cloudflare.Kv.put"));
486        assert!(!p.blocks("bynk.cloudflare.KvPut"));
487        assert!(p.blocks("bynk.cloudflare.Service"));
488        assert!(p.blocks("bynk.cloudflare.Service.send"));
489        assert!(p.blocks("bynk.cloudflare.R2"));
490        assert!(p.blocks("bynk.cloudflare.R2.putWith"));
491        assert!(!p.blocks("bynk.cloudflare.R2Put"));
492        assert!(p.blocks("bynk.cloudflare.RateLimit.allow"));
493        assert!(p.blocks("bynk.cloudflare.Queue.sendBatch"));
494        assert!(!p.blocks("bynk.cloudflare.QueueSend"));
495        assert!(p.blocks("bynk.cloudflare.Analytics.write"));
496        assert!(!p.blocks("bynk.cloudflare.DataPoint"));
497        assert!(p.blocks("bynk.cloudflare.EdgeCache.purge"));
498        // P4d (#2652): D1 graduated, with its operations.
499        assert!(!p.blocks("bynk.cloudflare.D1"));
500        assert!(!p.blocks("bynk.cloudflare.D1.batch"));
501        assert!(!p.blocks("bynk.cloudflare.SqlValue"));
502        assert!(p.manifest_diagnostics().is_empty());
503    }
504}