Skip to main content

bynk_project/
worker_groups.rs

1//! #3562 (slice G1): the Worker groups of `bynk.toml`.
2//!
3//! Under the `workers` target a context is one Worker. A group puts several
4//! contexts in one Worker, so a handful of contexts that belong together need
5//! not each cost a Worker and a network hop:
6//!
7//! ```toml
8//! [deploy.workers.core]
9//! contexts = ["shop.orders", "shop.catalogue", "shop.pricing"]
10//!
11//! [deploy.workers.payments]
12//! contexts = ["shop.payment"]
13//! name = "acme-payments"          # the Cloudflare script name; default is the key
14//! routes = ["pay.example.com/*"]
15//! ```
16//!
17//! The **key** is the group's identity (its ledger entry, its `--worker`
18//! selector, its `workers/<key>/` directory); `name` only overrides the
19//! script's name on Cloudflare. A context named in no group stays one Worker
20//! under its dashed name, so a project with no `[deploy.workers]` is unchanged.
21//!
22//! This module reads the table and checks everything that needs no project
23//! model: shapes, the grammar of names, a context in two groups, two groups
24//! sharing a script name, a route or domain claimed twice. What needs the
25//! project's contexts (an unknown context, a context that is not deployable,
26//! a key that collides with an implicit Worker's name) is checked against them
27//! by [`validate_against`].
28
29use crate::discovery::read_source;
30use crate::paths::{ProjectPathsError, did_you_mean};
31use std::collections::{BTreeMap, BTreeSet, HashMap};
32use std::path::{Path, PathBuf};
33
34/// One group's `[deploy.workers.<key>]` entry.
35#[derive(Debug, Clone, Default, PartialEq, Eq)]
36pub struct WorkerGroup {
37    /// The members, as qualified context names (`shop.orders`), in the order
38    /// the manifest lists them.
39    pub contexts: Vec<String>,
40    /// The Cloudflare script name; `None` means the group's key.
41    pub name: Option<String>,
42    /// Route patterns (`pay.example.com/*`) the Worker is attached to.
43    pub routes: Vec<String>,
44    /// Custom domains (`pay.example.com`) the Worker is attached to.
45    pub custom_domains: Vec<String>,
46}
47
48impl WorkerGroup {
49    /// The script's name on Cloudflare, given the group's key.
50    pub fn script_name<'a>(&'a self, key: &'a str) -> &'a str {
51        self.name.as_deref().unwrap_or(key)
52    }
53}
54
55/// The `[deploy.workers]` groups, by key.
56pub type WorkerGroups = BTreeMap<String, WorkerGroup>;
57
58/// The keys of a `[deploy.workers.<key>]` entry.
59pub const GROUP_KEYS: &[&str] = &["contexts", "name", "routes", "custom_domains"];
60
61fn bad(key: &str, reason: String) -> ProjectPathsError {
62    ProjectPathsError::BadWorkerGroup {
63        key: key.to_string(),
64        reason,
65    }
66}
67
68/// Whether `name` can be a Worker's key or script name: Cloudflare's own
69/// grammar, 1 to 63 lowercase letters, digits and `-`, not starting or ending
70/// with one. It becomes a directory, a command-line argument and a ledger key,
71/// so nothing else may reach them.
72pub fn is_worker_name(name: &str) -> bool {
73    (1..=63).contains(&name.len())
74        && name
75            .bytes()
76            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
77        && !name.starts_with('-')
78        && !name.ends_with('-')
79}
80
81/// Whether `name` is a qualified context name: dot-separated segments, each an
82/// identifier (letters, digits and `_`, not starting with a digit).
83pub fn is_qualified_name(name: &str) -> bool {
84    !name.is_empty()
85        && name.split('.').all(|seg| {
86            let mut bytes = seg.bytes();
87            bytes
88                .next()
89                .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
90                && bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
91        })
92}
93
94/// Whether `host` is a hostname a custom domain can name: dot-separated
95/// labels of letters, digits and `-`, at least two of them, no wildcard.
96fn is_hostname(host: &str) -> bool {
97    host.len() <= 253
98        && host.split('.').count() >= 2
99        && host.split('.').all(|label| {
100            (1..=63).contains(&label.len())
101                && label
102                    .bytes()
103                    .all(|b| b.is_ascii_alphanumeric() || b == b'-')
104                && !label.starts_with('-')
105                && !label.ends_with('-')
106        })
107}
108
109/// Whether `route` is a route pattern: a host (a leading `*.` allowed), then
110/// `/` and a path, with no scheme and no whitespace, as Cloudflare takes them.
111fn is_route_pattern(route: &str) -> bool {
112    let Some((host, _)) = route.split_once('/') else {
113        return false;
114    };
115    let host = host.strip_prefix("*.").unwrap_or(host);
116    is_hostname(host) && !route.bytes().any(|b| b.is_ascii_whitespace())
117}
118
119fn string_list(
120    key: &str,
121    field: &str,
122    value: &toml::Value,
123) -> Result<Vec<String>, ProjectPathsError> {
124    let shape = || {
125        bad(
126            key,
127            format!("`{field}` must be a list of strings, like `{field} = [\"…\"]`"),
128        )
129    };
130    let list = value.as_array().ok_or_else(shape)?;
131    list.iter()
132        .map(|v| v.as_str().map(str::to_string).ok_or_else(shape))
133        .collect()
134}
135
136/// A name that appears twice in `items`, if any.
137fn first_duplicate(items: &[String]) -> Option<&str> {
138    let mut seen = BTreeSet::new();
139    items
140        .iter()
141        .find(|item| !seen.insert(item.as_str()))
142        .map(String::as_str)
143}
144
145/// One `[deploy.workers.<key>]` entry.
146fn group_from(key: &str, value: &toml::Value) -> Result<WorkerGroup, ProjectPathsError> {
147    let entry = value
148        .as_table()
149        .ok_or_else(|| bad(key, "must be a table".to_string()))?;
150    if !is_worker_name(key) {
151        return Err(bad(
152            key,
153            "is not a valid Worker name: 1 to 63 lowercase letters, digits or `-`, not starting or ending with `-`"
154                .to_string(),
155        ));
156    }
157    for k in entry.keys() {
158        if !GROUP_KEYS.contains(&k.as_str()) {
159            let hint = did_you_mean(k, GROUP_KEYS.iter().copied())
160                .map(|h| format!(" — did you mean `{h}`?"))
161                .unwrap_or_default();
162            return Err(bad(
163                key,
164                format!(
165                    "has no key named `{k}`{hint} (its keys are `contexts`, `name`, `routes` and `custom_domains`)"
166                ),
167            ));
168        }
169    }
170    let Some(contexts) = entry.get("contexts") else {
171        return Err(bad(
172            key,
173            "needs `contexts`, like `contexts = [\"shop.orders\", \"shop.pricing\"]`".to_string(),
174        ));
175    };
176    let contexts = string_list(key, "contexts", contexts)?;
177    if contexts.is_empty() {
178        return Err(bad(
179            key,
180            "bynk.deploy.empty_group: `contexts` names no context".to_string(),
181        ));
182    }
183    if let Some(bad_name) = contexts.iter().find(|c| !is_qualified_name(c)) {
184        return Err(bad(
185            key,
186            format!(
187                "`contexts` holds `{bad_name}`, which is not a qualified context name like `shop.orders` (globs are not supported)"
188            ),
189        ));
190    }
191    if let Some(dup) = first_duplicate(&contexts) {
192        return Err(bad(key, format!("lists context `{dup}` twice")));
193    }
194    let name = match entry.get("name") {
195        None => None,
196        Some(v) => {
197            let n = v.as_str().filter(|n| is_worker_name(n)).ok_or_else(|| {
198                bad(
199                    key,
200                    "`name` must be a Worker name: 1 to 63 lowercase letters, digits or `-`, not starting or ending with `-`"
201                        .to_string(),
202                )
203            })?;
204            Some(n.to_string())
205        }
206    };
207    let routes = match entry.get("routes") {
208        None => Vec::new(),
209        Some(v) => string_list(key, "routes", v)?,
210    };
211    if let Some(r) = routes.iter().find(|r| !is_route_pattern(r)) {
212        return Err(bad(
213            key,
214            format!(
215                "`routes` holds `{r}`, which is not a route pattern like `pay.example.com/*` (a host, then `/` and a path, with no scheme)"
216            ),
217        ));
218    }
219    let custom_domains = match entry.get("custom_domains") {
220        None => Vec::new(),
221        Some(v) => string_list(key, "custom_domains", v)?,
222    };
223    if let Some(d) = custom_domains.iter().find(|d| !is_hostname(d)) {
224        return Err(bad(
225            key,
226            format!(
227                "`custom_domains` holds `{d}`, which is not a hostname like `pay.example.com` (no scheme, path or wildcard)"
228            ),
229        ));
230    }
231    Ok(WorkerGroup {
232        contexts,
233        name,
234        routes,
235        custom_domains,
236    })
237}
238
239/// A route or domain with its host lowercased (hostnames are case-insensitive;
240/// a path is not), so two spellings of one host are one claim.
241fn normalised_host(pattern: &str) -> String {
242    match pattern.split_once('/') {
243        Some((host, path)) => format!("{}/{path}", host.to_ascii_lowercase()),
244        None => pattern.to_ascii_lowercase(),
245    }
246}
247
248/// The rules across groups: a context in one group only, a script name used
249/// once, and a route or custom domain claimed once.
250fn check_across(groups: &WorkerGroups) -> Result<(), ProjectPathsError> {
251    let mut context_owner: BTreeMap<&str, &str> = BTreeMap::new();
252    let mut script_owner: BTreeMap<&str, &str> = BTreeMap::new();
253    let mut route_owner: BTreeMap<String, &str> = BTreeMap::new();
254    let mut domain_owner: BTreeMap<String, &str> = BTreeMap::new();
255    for (key, group) in groups {
256        for context in &group.contexts {
257            if let Some(first) = context_owner.insert(context, key) {
258                return Err(bad(
259                    key,
260                    format!(
261                        "bynk.deploy.context_in_two_groups: context `{context}` is already in `[deploy.workers.{first}]`; a context is in one Worker only"
262                    ),
263                ));
264            }
265        }
266        let script = group.script_name(key);
267        if let Some(first) = script_owner.insert(script, key) {
268            return Err(bad(
269                key,
270                format!(
271                    "bynk.deploy.group_name_conflict: its Worker would be named `{script}`, as `[deploy.workers.{first}]`'s is"
272                ),
273            ));
274        }
275        for route in &group.routes {
276            if let Some(first) = route_owner.insert(normalised_host(route), key) {
277                return Err(bad(
278                    key,
279                    format!(
280                        "bynk.deploy.duplicate_hostname: route `{route}` is also in `[deploy.workers.{first}]`"
281                    ),
282                ));
283            }
284        }
285        for domain in &group.custom_domains {
286            if let Some(first) = domain_owner.insert(normalised_host(domain), key) {
287                return Err(bad(
288                    key,
289                    format!(
290                        "bynk.deploy.duplicate_hostname: custom domain `{domain}` is also in `[deploy.workers.{first}]`"
291                    ),
292                ));
293            }
294        }
295    }
296    Ok(())
297}
298
299/// The `[deploy]` table's `workers` entries.
300pub fn deploy_workers_from(deploy: &toml::Table) -> Result<WorkerGroups, ProjectPathsError> {
301    let mut out = WorkerGroups::new();
302    let Some(value) = deploy.get("workers") else {
303        return Ok(out);
304    };
305    let all = value.as_table().ok_or_else(|| {
306        bad(
307            "",
308            "must be a table of Workers, like `[deploy.workers.core]`".to_string(),
309        )
310    })?;
311    for (key, value) in all {
312        out.insert(key.clone(), group_from(key, value)?);
313    }
314    check_across(&out)?;
315    Ok(out)
316}
317
318/// Read `bynk.toml`'s `[deploy.workers]` groups, honouring `overlay` (an
319/// open, unsaved buffer) and otherwise reading the manifest from disk, as
320/// `read_package_config` does. No manifest, or none of the table, is empty.
321pub fn try_read_worker_groups_with(
322    project_root: &Path,
323    overlay: &HashMap<PathBuf, String>,
324) -> Result<WorkerGroups, ProjectPathsError> {
325    let manifest = project_root.join("bynk.toml");
326    let content = match read_source(&manifest, overlay) {
327        Ok(text) => text,
328        Err(_) => match std::fs::read_to_string(&manifest) {
329            Ok(text) => text,
330            Err(_) => return Ok(WorkerGroups::new()),
331        },
332    };
333    let doc = content
334        .parse::<toml::Table>()
335        .map_err(|_| ProjectPathsError::Malformed)?;
336    match doc.get("deploy").and_then(|v| v.as_table()) {
337        Some(t) => deploy_workers_from(t),
338        None => Ok(WorkerGroups::new()),
339    }
340}
341
342/// [`try_read_worker_groups_with`], reading `bynk.toml` from disk.
343pub fn try_read_worker_groups(project_root: &Path) -> Result<WorkerGroups, ProjectPathsError> {
344    try_read_worker_groups_with(project_root, &HashMap::new())
345}
346
347/// A rule the groups break against the project's contexts.
348#[derive(Debug, Clone, PartialEq, Eq)]
349pub struct GroupIssue {
350    /// The diagnostic code, `bynk.deploy.*`.
351    pub code: &'static str,
352    /// The group's key the issue is in.
353    pub group: String,
354    /// What is wrong, and the fix.
355    pub message: String,
356}
357
358/// The units of a project, by kind, as [`validate_against`] needs them.
359pub struct ProjectUnits<'a> {
360    /// Every context's qualified name.
361    pub contexts: &'a BTreeSet<String>,
362    /// Every other unit (commons, adapters): not deployable.
363    pub other_units: &'a BTreeSet<String>,
364}
365
366/// Check `groups` against the project's units: every member exists and is a
367/// context, and no group's key or script name is an implicit Worker's (a
368/// context in no group is a Worker named by its dashed name).
369pub fn validate_against(groups: &WorkerGroups, units: &ProjectUnits<'_>) -> Vec<GroupIssue> {
370    let mut issues = Vec::new();
371    let grouped: BTreeSet<&str> = groups
372        .values()
373        .flat_map(|g| g.contexts.iter().map(String::as_str))
374        .collect();
375    let implicit: BTreeMap<String, &str> = units
376        .contexts
377        .iter()
378        .filter(|c| !grouped.contains(c.as_str()))
379        .map(|c| {
380            (
381                crate::paths::worker_dir_name(c).to_ascii_lowercase(),
382                c.as_str(),
383            )
384        })
385        .collect();
386    for (key, group) in groups {
387        for context in &group.contexts {
388            if units.other_units.contains(context) {
389                issues.push(GroupIssue {
390                    code: "bynk.deploy.not_a_context",
391                    group: key.clone(),
392                    message: format!(
393                        "`{context}` is not a `context`: only contexts are deployed as Workers, so it cannot be in `[deploy.workers.{key}]`"
394                    ),
395                });
396            } else if !units.contexts.contains(context) {
397                let hint = did_you_mean(context, units.contexts.iter().map(String::as_str))
398                    .map(|c| format!(" — did you mean `{c}`?"))
399                    .unwrap_or_default();
400                issues.push(GroupIssue {
401                    code: "bynk.deploy.unknown_context",
402                    group: key.clone(),
403                    message: format!(
404                        "`[deploy.workers.{key}]` names context `{context}`, which this project does not declare{hint}"
405                    ),
406                });
407            }
408        }
409        let named = group.name.as_deref().map(|n| ("name", n));
410        for (what, name) in std::iter::once(("key", key.as_str())).chain(named) {
411            if let Some(context) = implicit.get(name) {
412                issues.push(GroupIssue {
413                    code: "bynk.deploy.group_name_conflict",
414                    group: key.clone(),
415                    message: format!(
416                        "`[deploy.workers.{key}]`'s {what} `{name}` is the Worker of context `{context}`, which is in no group; name it in a group, or choose another {what}"
417                    ),
418                });
419            }
420        }
421    }
422    issues
423}
424
425#[cfg(test)]
426mod tests;