Skip to main content

bynk_check/
containers.rs

1//! `Container` instances (#3477, slice C1): the validation of each option of
2//! `capability Renderer = Container @build("…") @port(8080) …`, and the name
3//! of the Durable Object class generated for an instance.
4//!
5//! These are the pure rules. Whether `<build>/Dockerfile` exists is a question
6//! about the project's files, which the driver answers
7//! ([`dockerfile_problem`]); the checker has no filesystem.
8
9use std::collections::{BTreeMap, HashMap};
10use std::path::Path;
11
12use bynk_project::{ParsedFile, UnitKind};
13use bynk_syntax::ast::CommonsItem;
14use bynk_syntax::error::CompileError;
15
16use crate::firstparty;
17use crate::project_model::ErrorSink;
18use crate::symbols::UnitTable;
19
20/// The prefix of the class generated for a `Container` instance, reserved
21/// beside `__EventsFanout`: `capability Renderer = Container` is
22/// `__Container_Renderer`. A user `agent` may not use it
23/// (`bynk.container.class_collision`).
24pub const CONTAINER_CLASS_PREFIX: &str = "__Container_";
25
26/// The name of the Durable Object class generated for the `Container`
27/// instance `capability`.
28pub fn container_class_name(capability: &str) -> String {
29    format!("{CONTAINER_CLASS_PREFIX}{capability}")
30}
31
32/// Why `@build`'s value is not a directory the project can name, or `None`
33/// when it is: relative, inside the project (no `..`, no absolute or drive
34/// path, no backslash) and not empty. A trailing `/` and `.` segments are
35/// tolerated, and [`normalise_build`] removes them.
36pub fn build_path_problem(path: &str) -> Option<&'static str> {
37    if path.is_empty() {
38        return Some("is empty");
39    }
40    if path.contains('\\') {
41        return Some("uses `\\`; write a `/`-separated path");
42    }
43    if path.contains(['\0', '\n', '\r']) || path.chars().any(char::is_control) {
44        return Some("holds a control character");
45    }
46    if path.starts_with('/')
47        || matches!(path.as_bytes(), [d, b':'] | [d, b':', b'/', ..] if d.is_ascii_alphabetic())
48    {
49        return Some("is absolute; it must be relative to the project root");
50    }
51    if path.split('/').any(|seg| seg == "..") {
52        return Some("leaves the project with `..`");
53    }
54    if normalise_build(path).is_empty() {
55        return Some("names the project root, not a directory beneath it");
56    }
57    None
58}
59
60/// `@build`'s directory as a project-relative path without a trailing `/`,
61/// empty segments or `.` segments (`./containers//renderer/` becomes
62/// `containers/renderer`).
63pub fn normalise_build(path: &str) -> String {
64    path.split('/')
65        .filter(|seg| !seg.is_empty() && *seg != ".")
66        .collect::<Vec<_>>()
67        .join("/")
68}
69
70/// The Dockerfile a `@build` directory names: `<dir>/Dockerfile`.
71pub fn dockerfile_path(build: &str) -> String {
72    format!("{}/Dockerfile", normalise_build(build))
73}
74
75/// Why `@port` is not a port, or `None` when it is (1 to 65535).
76pub fn port_problem(value: i64) -> Option<&'static str> {
77    (!(1..=65535).contains(&value)).then_some("is a TCP port, 1 to 65535")
78}
79
80/// `@sleepAfter` as whole seconds: more than zero and at most 6 hours, with no
81/// part second. `None` otherwise.
82pub fn sleep_after_seconds(millis: i64) -> Option<i64> {
83    (millis > 0
84        && millis % 1000 == 0
85        && millis / 1000 <= firstparty::CONTAINER_MAX_SLEEP_AFTER_SECONDS)
86        .then_some(millis / 1000)
87}
88
89/// Whether `name` is a Worker secret `@forward` may name: an identifier a
90/// process reads from its environment (letters, digits and `_`, not starting
91/// with a digit), at most 128 characters.
92pub fn is_forwardable_name(name: &str) -> bool {
93    let mut chars = name.chars();
94    chars
95        .next()
96        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
97        && name.len() <= 128
98        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
99}
100
101/// Why a `@forward` list is not one, or `None` when it is: at most
102/// [`firstparty::CONTAINER_MAX_FORWARD`] names, each a plain identifier, none
103/// repeated.
104pub fn forward_problem(items: &[String]) -> Option<String> {
105    if items.len() > firstparty::CONTAINER_MAX_FORWARD {
106        return Some(format!(
107            "`@forward` lists {} names, and a container takes at most {}",
108            items.len(),
109            firstparty::CONTAINER_MAX_FORWARD
110        ));
111    }
112    items.iter().enumerate().find_map(|(i, item)| {
113        if !is_forwardable_name(item) {
114            return Some(format!(
115                "`{}` is not a name a container's environment can hold",
116                item.escape_debug()
117            ));
118        }
119        items[..i]
120            .contains(item)
121            .then(|| format!("`{item}` is listed twice"))
122    })
123}
124
125/// The problem with the `Dockerfile` of a `@build` directory, looked up by
126/// `has_file` (project-relative path to whether it is a file), or `None` when
127/// it is there.
128pub fn dockerfile_problem(build: &str, has_file: &dyn Fn(&str) -> bool) -> Option<String> {
129    let file = dockerfile_path(build);
130    (!has_file(&file)).then(|| format!("`{file}` does not exist"))
131}
132
133/// `bynk.container.build_missing`: every `Container` instance's `@build`
134/// directory holds a `Dockerfile` under `project_root`. A `@build` that is not
135/// a project path is already refused when the option is read
136/// (`bynk.container.build_path`), so it is skipped here.
137pub fn phase_container_builds(
138    groups: &BTreeMap<String, Vec<usize>>,
139    kinds: &BTreeMap<String, UnitKind>,
140    parsed: &[ParsedFile],
141    unit_tables: &HashMap<String, UnitTable>,
142    project_root: &Path,
143    errors: &mut ErrorSink,
144) {
145    let has_file = |rel: &str| project_root.join(rel).is_file();
146    for (name, indices) in groups {
147        if kinds.get(name) != Some(&UnitKind::Context) {
148            continue;
149        }
150        let Some(table) = unit_tables.get(name) else {
151            continue;
152        };
153        for &i in indices {
154            if parsed[i].is_synthetic() {
155                continue;
156            }
157            let path = parsed[i].identity_path();
158            for item in parsed[i].items() {
159                let CommonsItem::Capability(c) = item else {
160                    continue;
161                };
162                let Some(build) = table
163                    .derived
164                    .get(&c.name.name)
165                    .and_then(|d| d.container_build())
166                else {
167                    continue;
168                };
169                let Some(problem) = dockerfile_problem(build, &has_file) else {
170                    continue;
171                };
172                errors.push_for(
173                    Some(&path),
174                    CompileError::new(
175                        "bynk.container.build_missing",
176                        c.span,
177                        format!(
178                            "the container `{}` has no Dockerfile: {problem}",
179                            c.name.name
180                        ),
181                    )
182                    .with_note(format!(
183                        "`@build(\"{build}\")` names the directory that holds the Dockerfile, relative to the project root; create `{}`",
184                        dockerfile_path(build)
185                    )),
186                );
187            }
188        }
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    #[test]
197    fn a_build_path_stays_inside_the_project() {
198        assert_eq!(build_path_problem("containers/renderer"), None);
199        assert_eq!(build_path_problem("./containers/renderer/"), None);
200        assert!(build_path_problem("").is_some());
201        assert!(build_path_problem("../x").is_some());
202        assert!(build_path_problem("a/../../x").is_some());
203        assert!(build_path_problem("/abs").is_some());
204        assert!(build_path_problem("C:/abs").is_some());
205        assert_eq!(build_path_problem("a:b/c"), None);
206        assert!(build_path_problem("a\\b").is_some());
207        assert!(build_path_problem(".").is_some());
208        assert!(build_path_problem("a\nb").is_some());
209    }
210
211    #[test]
212    fn a_build_path_is_normalised() {
213        assert_eq!(
214            normalise_build("./containers//renderer/"),
215            "containers/renderer"
216        );
217        assert_eq!(
218            dockerfile_path("containers/renderer/"),
219            "containers/renderer/Dockerfile"
220        );
221    }
222
223    #[test]
224    fn sleep_after_is_whole_seconds_up_to_six_hours() {
225        assert_eq!(sleep_after_seconds(300_000), Some(300));
226        assert_eq!(sleep_after_seconds(21_600_000), Some(21_600));
227        assert_eq!(sleep_after_seconds(21_601_000), None);
228        assert_eq!(sleep_after_seconds(0), None);
229        assert_eq!(sleep_after_seconds(1_500), None);
230    }
231
232    #[test]
233    fn forwarded_names_are_plain_identifiers() {
234        assert!(forward_problem(&["API_KEY".into(), "_x1".into()]).is_none());
235        assert!(forward_problem(&["1X".into()]).is_some());
236        assert!(forward_problem(&["A-B".into()]).is_some());
237        assert!(forward_problem(&["A".into(), "A".into()]).is_some());
238        assert!(port_problem(0).is_some() && port_problem(65536).is_some());
239        assert!(port_problem(8080).is_none());
240    }
241}