Skip to main content

bynk_project/
dev_ack.rs

1//! #3478: the `[dev]` acknowledgements of remote-only bindings.
2//!
3//! Some Cloudflare bindings have no local simulation: under `bynk dev`, a call
4//! runs on the developer's Cloudflare account and may incur charges. `bynk dev`
5//! does not block such a call. It warns once, on the first one, unless the
6//! project has acknowledged it in `bynk.toml`:
7//!
8//! ```toml
9//! [dev]
10//! ai = "allow"
11//! ```
12//!
13//! One mechanism serves every such binding kind: a [`RemoteKind`] names the
14//! `[dev]` key and the variable `bynk dev` hands to `wrangler dev` (as
15//! `--var`) for an acknowledged kind, which the kind's provider reads to stay
16//! quiet. Vectorize and AI Search add one entry each. No tooling here states
17//! a price, an allowance or which operations are billed: the warning links to
18//! Cloudflare's own pages.
19
20use crate::discovery::read_source;
21use crate::env_protocol;
22use crate::paths::{ProjectPathsError, did_you_mean};
23use std::collections::{BTreeSet, HashMap};
24use std::path::{Path, PathBuf};
25
26/// A binding kind with no local simulation under `bynk dev`.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct RemoteKind {
29    /// The `[dev]` key that acknowledges it (`ai`).
30    pub key: &'static str,
31    /// The variable `bynk dev` sets to `allow` on an acknowledged kind's
32    /// Workers, which the kind's provider reads (`BYNK_DEV_ACK_AI`).
33    pub var: &'static str,
34}
35
36/// The remote-only binding kinds, by `[dev]` key.
37pub const REMOTE_KINDS: &[RemoteKind] = &[
38    RemoteKind {
39        key: "ai",
40        var: env_protocol::DEV_ACK_AI,
41    },
42    RemoteKind {
43        key: "vectorize",
44        var: env_protocol::DEV_ACK_VECTORIZE,
45    },
46    // #3480: AI Search is its own kind, not covered by `ai`.
47    RemoteKind {
48        key: "ai-search",
49        var: env_protocol::DEV_ACK_AI_SEARCH,
50    },
51    // #3513 A: an mTLS certificate binding runs on Cloudflare under `bynk dev`.
52    RemoteKind {
53        key: "mtls",
54        var: env_protocol::DEV_ACK_MTLS,
55    },
56    // #3513 B: an Analytics SQL query runs on Cloudflare under `bynk dev`.
57    RemoteKind {
58        key: "analytics-sql",
59        var: env_protocol::DEV_ACK_ANALYTICS_SQL,
60    },
61];
62
63/// The variable `bynk dev` sets to `1` on every Worker it serves, so a
64/// provider can tell a development session from a deployment. A deployed
65/// Worker has neither this nor any acknowledgement variable.
66pub use crate::env_protocol::DEV as DEV_VAR;
67
68/// The one value an acknowledgement takes.
69pub const ALLOW: &str = "allow";
70
71fn bad(key: &str, reason: String) -> ProjectPathsError {
72    ProjectPathsError::BadDevAck {
73        key: key.to_string(),
74        reason,
75    }
76}
77
78/// The remote-only kinds `[dev]` acknowledges. Any other value than
79/// `"allow"`, for a known key, is an error.
80pub fn dev_acks_from(dev: &toml::Table) -> Result<BTreeSet<&'static str>, ProjectPathsError> {
81    let mut out = BTreeSet::new();
82    for kind in REMOTE_KINDS {
83        let Some(value) = dev.get(kind.key) else {
84            continue;
85        };
86        match value.as_str() {
87            Some(ALLOW) => {
88                out.insert(kind.key);
89            }
90            Some(other) => {
91                let hint = did_you_mean(other, [ALLOW])
92                    .map(|s| format!(" (did you mean `{s}`?)"))
93                    .unwrap_or_default();
94                return Err(bad(
95                    kind.key,
96                    format!(
97                        "must be `\"allow\"`, the only acknowledgement, not `\"{other}\"`{hint}"
98                    ),
99                ));
100            }
101            None => {
102                return Err(bad(
103                    kind.key,
104                    "must be the string `\"allow\"`, like `ai = \"allow\"`".to_string(),
105                ));
106            }
107        }
108    }
109    Ok(out)
110}
111
112/// Read `bynk.toml`'s `[dev]` acknowledgements, honouring `overlay`. No
113/// manifest, or no `[dev]` table, acknowledges nothing.
114pub fn try_read_dev_acks_with(
115    project_root: &Path,
116    overlay: &HashMap<PathBuf, String>,
117) -> Result<BTreeSet<&'static str>, ProjectPathsError> {
118    let Ok(content) = read_source(&project_root.join("bynk.toml"), overlay) else {
119        return Ok(BTreeSet::new());
120    };
121    let doc = content
122        .parse::<toml::Table>()
123        .map_err(|_| ProjectPathsError::Malformed)?;
124    match doc.get("dev").and_then(|v| v.as_table()) {
125        Some(dev) => dev_acks_from(dev),
126        None => Ok(BTreeSet::new()),
127    }
128}
129
130/// [`try_read_dev_acks_with`], reading `bynk.toml` from disk.
131pub fn try_read_dev_acks(project_root: &Path) -> Result<BTreeSet<&'static str>, ProjectPathsError> {
132    let path = project_root.join("bynk.toml");
133    let overlay = match std::fs::read_to_string(&path) {
134        Ok(text) => HashMap::from([(path, text)]),
135        Err(_) => HashMap::new(),
136    };
137    try_read_dev_acks_with(project_root, &overlay)
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    fn acks(text: &str) -> Result<Vec<&'static str>, String> {
145        let doc: toml::Table = text.parse().unwrap();
146        dev_acks_from(doc["dev"].as_table().unwrap())
147            .map(|s| s.into_iter().collect())
148            .map_err(|e| e.to_string())
149    }
150
151    #[test]
152    fn allow_acknowledges_a_kind() {
153        assert_eq!(acks("[dev]\nai = \"allow\"\n"), Ok(vec!["ai"]));
154        // #3480: AI Search is acknowledged on its own, not by `ai`.
155        assert_eq!(
156            acks("[dev]\nai-search = \"allow\"\n"),
157            Ok(vec!["ai-search"])
158        );
159        // #3513 A: an mTLS certificate binding is acknowledged on its own.
160        assert_eq!(acks("[dev]\nmtls = \"allow\"\n"), Ok(vec!["mtls"]));
161        let e = acks("[dev]\nmtls = true\n").unwrap_err();
162        assert!(e.contains("`[dev]` `mtls`"), "{e}");
163        assert_eq!(
164            acks("[dev.hyperdrive.Main]\nconnection_env = \"X\"\n[dev]\n"),
165            Ok(vec![])
166        );
167    }
168
169    #[test]
170    fn nothing_else_acknowledges() {
171        let e = acks("[dev]\nai = \"alow\"\n").unwrap_err();
172        assert!(
173            e.contains("`[dev]` `ai`") && e.contains("did you mean `allow`"),
174            "{e}"
175        );
176        let e = acks("[dev]\nai = true\n").unwrap_err();
177        assert!(e.contains("must be the string"), "{e}");
178    }
179
180    #[test]
181    fn every_kind_has_its_own_key_and_variable() {
182        let keys: BTreeSet<_> = REMOTE_KINDS.iter().map(|k| k.key).collect();
183        let vars: BTreeSet<_> = REMOTE_KINDS.iter().map(|k| k.var).collect();
184        assert_eq!(keys.len(), REMOTE_KINDS.len());
185        assert_eq!(vars.len(), REMOTE_KINDS.len());
186        for k in REMOTE_KINDS {
187            assert!(k.var.starts_with("BYNK_DEV_ACK_"), "{}", k.var);
188        }
189    }
190}