Skip to main content

bynk_project/
wrangler_keys.rs

1//! The keys of a generated `wrangler.toml`, and what a named environment does with each
2//! (back-half paydown 1C.2, Decisions B and D of #4039).
3//!
4//! Every top-level table the emitter writes is a [`WranglerKey`], and
5//! [`WranglerKey::environment_rule`] is one exhaustive `match`: a table the emitter writes cannot
6//! be left out of `[env.<name>]` by omission, which is the #3577 and #3586 bug class (`ai` and
7//! `ai_search` were written at the top level and never restated for a named environment). The
8//! emitter's `TomlBlock` headers take a key, the patchers and readers spell the keys through
9//! [`WranglerKey::top_key`], and `xtask`'s `wrangler_key_literals` probe fails a key spelled as a
10//! string literal anywhere else.
11//!
12//! The one-per-Worker tables of `bynk.cloudflare` (`version_metadata`, `ai`, `images` and
13//! `analytics`) are named by `bynk-std`'s registry, which is language surface, so they are a
14//! [`WranglerKey::Singleton`] holding the registry's own spelling. This crate sits below the
15//! registry and cannot enumerate them.
16
17/// A key of a generated `wrangler.toml`: a root entry, or a table or array of tables.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum WranglerKey {
20    // Root entries.
21    Name,
22    Main,
23    CompatibilityDate,
24    CompatibilityFlags,
25    WorkersDev,
26    Addresses,
27    // Tables, one per binding kind.
28    Services,
29    KvNamespaces,
30    R2Buckets,
31    RateLimits,
32    QueueProducers,
33    QueueConsumers,
34    AnalyticsEngineDatasets,
35    D1Databases,
36    SecretsStoreSecrets,
37    Hyperdrive,
38    SendEmail,
39    Vectorize,
40    AiSearch,
41    MtlsCertificates,
42    DurableObjectBindings,
43    Exports,
44    Containers,
45    ContainerImages,
46    // Worker-wide settings.
47    Vars,
48    Triggers,
49    Assets,
50    Cache,
51    Rules,
52    /// A one-per-Worker table named by `bynk-std`'s registry: `version_metadata`, `ai`, `images`
53    /// or `analytics`, held as the registry spells it.
54    Singleton(&'static str),
55}
56
57/// What a named environment's `[env.<name>]` block does with a key, from the generated file's
58/// top level.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum EnvironmentRule {
61    /// Not restated: Wrangler inherits it (#1890, #3328).
62    Inherited,
63    /// Copied as the top level has it, which the deploy has already made this environment's.
64    Copied,
65    /// The Worker's deployed name in the environment (#2028).
66    DeployedName,
67    /// Each entry's `field` is the resolved id of its `binding`. The table is left out when no
68    /// id is resolved.
69    ResolvedIds { field: &'static str },
70    /// Each entry's `field` is qualified for the environment.
71    Qualified { field: &'static str, form: Qualify },
72    /// The values of the variables whose names start with `prefix` are dataset names, qualified
73    /// for the environment (#3513 B); the others are copied.
74    QualifiedVars { prefix: &'static str },
75    /// Each queue, consumer and producer alike, is qualified for the environment.
76    QualifiedQueues,
77    /// Each Service Binding to a project Worker names its deployed name in the environment;
78    /// one to a foreign Worker is copied as declared (interop I5, #1972).
79    QualifiedServices,
80}
81
82/// How a name is qualified for an environment.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum Qualify {
85    /// `<name>-<environment>`, as Cloudflare names a Worker's own environment.
86    Suffix,
87    /// `<name>_<environment>`, a dataset being a SQL table name.
88    Dataset,
89}
90
91impl WranglerKey {
92    /// Every key but the registry's [`Self::Singleton`]s, for the tests and the probe.
93    pub const ALL: &'static [WranglerKey] = &[
94        Self::Name,
95        Self::Main,
96        Self::CompatibilityDate,
97        Self::CompatibilityFlags,
98        Self::WorkersDev,
99        Self::Addresses,
100        Self::Services,
101        Self::KvNamespaces,
102        Self::R2Buckets,
103        Self::RateLimits,
104        Self::QueueProducers,
105        Self::QueueConsumers,
106        Self::AnalyticsEngineDatasets,
107        Self::D1Databases,
108        Self::SecretsStoreSecrets,
109        Self::Hyperdrive,
110        Self::SendEmail,
111        Self::Vectorize,
112        Self::AiSearch,
113        Self::MtlsCertificates,
114        Self::DurableObjectBindings,
115        Self::Exports,
116        Self::Containers,
117        Self::ContainerImages,
118        Self::Vars,
119        Self::Triggers,
120        Self::Assets,
121        Self::Cache,
122        Self::Rules,
123    ];
124
125    /// The key as a header or root entry spells it, dotted for a sub-table
126    /// (`queues.producers`).
127    pub fn header(self) -> &'static str {
128        match self {
129            Self::Name => "name",
130            Self::Main => "main",
131            Self::CompatibilityDate => "compatibility_date",
132            Self::CompatibilityFlags => "compatibility_flags",
133            Self::WorkersDev => "workers_dev",
134            Self::Addresses => "addresses",
135            Self::Services => "services",
136            Self::KvNamespaces => "kv_namespaces",
137            Self::R2Buckets => "r2_buckets",
138            Self::RateLimits => "ratelimits",
139            Self::QueueProducers => "queues.producers",
140            Self::QueueConsumers => "queues.consumers",
141            Self::AnalyticsEngineDatasets => "analytics_engine_datasets",
142            Self::D1Databases => "d1_databases",
143            Self::SecretsStoreSecrets => "secrets_store_secrets",
144            Self::Hyperdrive => "hyperdrive",
145            Self::SendEmail => "send_email",
146            Self::Vectorize => "vectorize",
147            Self::AiSearch => "ai_search",
148            Self::MtlsCertificates => "mtls_certificates",
149            Self::DurableObjectBindings => "durable_objects.bindings",
150            Self::Exports => "exports",
151            Self::Containers => "containers",
152            Self::ContainerImages => "containers.images",
153            Self::Vars => "vars",
154            Self::Triggers => "triggers",
155            Self::Assets => "assets",
156            Self::Cache => "cache",
157            Self::Rules => "rules",
158            Self::Singleton(table) => table,
159        }
160    }
161
162    /// The top-level key it lives under: [`Self::header`] up to its first dot.
163    pub fn top_key(self) -> &'static str {
164        let header = self.header();
165        header.split_once('.').map_or(header, |(top, _)| top)
166    }
167
168    /// The key whose [`Self::top_key`] is `key`, the first of them in [`Self::ALL`] when two
169    /// share one (`queues`). `None` for a key the emitter does not write, and for a singleton
170    /// table, which only the registry names.
171    pub fn from_top_key(key: &str) -> Option<Self> {
172        Self::ALL.iter().copied().find(|k| k.top_key() == key)
173    }
174
175    /// What a named environment does with this key. One exhaustive `match`, so a key added
176    /// without a rule does not compile.
177    pub fn environment_rule(self) -> EnvironmentRule {
178        use EnvironmentRule::{
179            Copied, DeployedName, Inherited, Qualified, QualifiedQueues, QualifiedServices,
180            QualifiedVars, ResolvedIds,
181        };
182        match self {
183            Self::Name => DeployedName,
184            // #1890, #3328: inheritable, and nothing environment-specific about them.
185            Self::Main
186            | Self::CompatibilityDate
187            | Self::CompatibilityFlags
188            | Self::WorkersDev
189            | Self::Addresses
190            | Self::Assets
191            | Self::Cache
192            | Self::Rules => Inherited,
193            Self::KvNamespaces => ResolvedIds { field: "id" },
194            Self::R2Buckets => Qualified {
195                field: "bucket_name",
196                form: Qualify::Suffix,
197            },
198            Self::Vectorize => Qualified {
199                field: "index_name",
200                form: Qualify::Suffix,
201            },
202            Self::AnalyticsEngineDatasets => Qualified {
203                field: "dataset",
204                form: Qualify::Dataset,
205            },
206            Self::Vars => QualifiedVars {
207                prefix: crate::env_protocol::DATASET_PREFIX,
208            },
209            Self::QueueProducers | Self::QueueConsumers => QualifiedQueues,
210            Self::Services => QualifiedServices,
211            Self::Containers
212            | Self::ContainerImages
213            | Self::D1Databases
214            | Self::Hyperdrive
215            | Self::SecretsStoreSecrets
216            | Self::MtlsCertificates
217            | Self::SendEmail
218            | Self::AiSearch
219            | Self::RateLimits
220            | Self::DurableObjectBindings
221            | Self::Exports
222            | Self::Triggers
223            | Self::Singleton(_) => Copied,
224        }
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use std::collections::{BTreeMap, BTreeSet};
232
233    #[test]
234    fn headers_are_unique() {
235        let headers: BTreeSet<_> = WranglerKey::ALL.iter().map(|k| k.header()).collect();
236        assert_eq!(headers.len(), WranglerKey::ALL.len());
237    }
238
239    /// Two keys under one top-level key (`queues.producers`, `queues.consumers`) must agree on
240    /// what an environment does with it, since the block is made per top-level key.
241    #[test]
242    fn every_top_key_has_one_rule() {
243        let mut rules: BTreeMap<&str, EnvironmentRule> = BTreeMap::new();
244        for key in WranglerKey::ALL {
245            let rule = key.environment_rule();
246            assert_eq!(
247                *rules.entry(key.top_key()).or_insert(rule),
248                rule,
249                "`{}` has two rules",
250                key.top_key()
251            );
252        }
253    }
254
255    #[test]
256    fn a_dotted_header_has_its_top_key() {
257        assert_eq!(WranglerKey::QueueProducers.top_key(), "queues");
258        assert_eq!(
259            WranglerKey::DurableObjectBindings.top_key(),
260            "durable_objects"
261        );
262        assert_eq!(WranglerKey::ContainerImages.top_key(), "containers");
263        assert_eq!(WranglerKey::KvNamespaces.top_key(), "kv_namespaces");
264        assert_eq!(
265            WranglerKey::from_top_key("queues"),
266            Some(WranglerKey::QueueProducers)
267        );
268        assert_eq!(
269            WranglerKey::from_top_key("images"),
270            None,
271            "a singleton is the registry's"
272        );
273        assert_eq!(WranglerKey::from_top_key("nonsense"), None);
274    }
275
276    /// #1890 and #3328: the keys a named environment inherits.
277    #[test]
278    fn the_inherited_keys_are_the_ones_wrangler_inherits() {
279        let inherited: BTreeSet<_> = WranglerKey::ALL
280            .iter()
281            .filter(|k| k.environment_rule() == EnvironmentRule::Inherited)
282            .map(|k| k.header())
283            .collect();
284        assert_eq!(
285            inherited,
286            [
287                "main",
288                "compatibility_date",
289                "compatibility_flags",
290                "workers_dev",
291                "addresses",
292                "assets",
293                "cache",
294                "rules"
295            ]
296            .into_iter()
297            .collect()
298        );
299    }
300
301    #[test]
302    fn a_singleton_is_copied_under_the_registrys_spelling() {
303        let key = WranglerKey::Singleton("version_metadata");
304        assert_eq!(key.header(), "version_metadata");
305        assert_eq!(key.top_key(), "version_metadata");
306        assert_eq!(key.environment_rule(), EnvironmentRule::Copied);
307    }
308}