Skip to main content

bynk_project/
worker_layout.rs

1//! Where each context's generated files go under a Workers build (#3562, G2b).
2//!
3//! A context is one Worker, and its files go under `workers/<dir>/`, `<dir>`
4//! being the dashed context name. A `[deploy.workers.<key>]` group puts several
5//! contexts in one Worker, so they share one directory, `workers/<key>/`, and
6//! each member's own files carry a prefix (`<member>.handlers.ts`) so two
7//! members never write the same file. The files that belong to the Worker as a
8//! whole (`index.ts`, `wrangler.toml`) take no prefix.
9//!
10//! [`WorkerLayout::identity`] is the layout of a project with no group: every
11//! context in a directory of its own, every file under its usual name.
12
13use crate::paths::worker_dir_name;
14use crate::worker_groups::WorkerGroups;
15use std::collections::BTreeMap;
16use std::path::PathBuf;
17
18/// A context's place in a Worker: the Worker's directory, and the prefix its
19/// own files take when other contexts share the directory.
20#[derive(Debug, Clone, PartialEq, Eq)]
21struct Place {
22    dir: String,
23    /// `Some` when the context is a member of a group: its file prefix.
24    prefix: Option<String>,
25    /// The Worker's name on Cloudflare: the group's `name`, else its key; a
26    /// context's own Worker is named by its dashed name.
27    script: String,
28}
29
30/// Where each context's generated files go.
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
32pub struct WorkerLayout {
33    /// The contexts that are members of a group; every other context is
34    /// [`Self::place`]d by its dashed name.
35    members: BTreeMap<String, Place>,
36    /// Each group's members in the order its `contexts` list gives them, by the
37    /// group's directory: the order the group's entry tries them in.
38    order: BTreeMap<String, Vec<String>>,
39}
40
41impl WorkerLayout {
42    /// The layout of a project with no `[deploy.workers]` group.
43    pub fn identity() -> Self {
44        Self::default()
45    }
46
47    /// The layout a project's build uses, from its `bynk.toml` (with `overlay`
48    /// over the files on disk). The one place the build, the checker and the
49    /// editor learn where each context's Worker is, so they cannot disagree.
50    /// A manifest with no `[deploy.workers]` table, or one that does not read
51    /// (the manifest checks report that), is [`Self::identity`].
52    pub fn for_project(
53        project_root: &std::path::Path,
54        overlay: &std::collections::HashMap<PathBuf, String>,
55    ) -> Self {
56        match crate::worker_groups::try_read_worker_groups_with(project_root, overlay) {
57            Ok(groups) if !groups.is_empty() => Self::from_groups(&groups),
58            _ => Self::identity(),
59        }
60    }
61
62    /// The layout of `groups`: a member goes in its group's directory, under a
63    /// prefix; every other context is as in [`Self::identity`].
64    pub fn from_groups(groups: &WorkerGroups) -> Self {
65        let order = groups
66            .iter()
67            .map(|(key, group)| (key.clone(), group.contexts.clone()))
68            .collect();
69        let members = groups
70            .iter()
71            .flat_map(|(key, group)| {
72                group.contexts.iter().map(move |ctx| {
73                    (
74                        ctx.clone(),
75                        Place {
76                            dir: key.clone(),
77                            prefix: Some(worker_dir_name(ctx)),
78                            script: group.script_name(key).to_string(),
79                        },
80                    )
81                })
82            })
83            .collect();
84        Self { members, order }
85    }
86
87    /// Whether `context` is a member of a group, so its entry is one of several
88    /// behind the group's dispatcher and marks the requests it does not own.
89    pub fn is_member(&self, context: &str) -> bool {
90        self.members.contains_key(context)
91    }
92
93    fn place(&self, context: &str) -> Place {
94        self.members.get(context).cloned().unwrap_or_else(|| Place {
95            dir: worker_dir_name(context),
96            prefix: None,
97            script: worker_dir_name(context),
98        })
99    }
100
101    /// The directory name, under `workers/`, of the Worker `context` is in.
102    pub fn dir(&self, context: &str) -> String {
103        self.place(context).dir
104    }
105
106    /// The name of the Worker `context` is in on Cloudflare: what a Service
107    /// Binding to it, and its own `wrangler.toml`, call it. The group's `name`
108    /// or key for a member, the dashed context name otherwise. (The directory
109    /// and the names derived for its resources stay the key, the group's
110    /// identity, so that renaming a script does not move them.)
111    pub fn script_name(&self, context: &str) -> String {
112        self.place(context).script
113    }
114
115    /// Every group, by its directory (the group's key), with its members in the
116    /// order the manifest lists them.
117    pub fn groups(&self) -> impl Iterator<Item = (&str, &[String])> {
118        self.order
119            .iter()
120            .map(|(dir, members)| (dir.as_str(), members.as_slice()))
121    }
122
123    /// The members of the group whose directory is `dir`, in the order the
124    /// manifest lists them; `None` for a context's own Worker.
125    pub fn group_members(&self, dir: &str) -> Option<&[String]> {
126        self.order.get(dir).map(Vec::as_slice)
127    }
128
129    /// The path of a file that belongs to the Worker as a whole (`index.ts`,
130    /// `wrangler.toml`): `workers/<dir>/<name>`.
131    pub fn worker_file(&self, context: &str, name: &str) -> PathBuf {
132        PathBuf::from(format!("workers/{}/{name}", self.dir(context)))
133    }
134
135    /// The path of one of `context`'s own files: `workers/<dir>/<name>`, or,
136    /// when other contexts share the directory, `workers/<dir>/<member>.<name>`.
137    pub fn member_file(&self, context: &str, name: &str) -> PathBuf {
138        let place = self.place(context);
139        match place.prefix {
140            Some(prefix) => PathBuf::from(format!("workers/{}/{prefix}.{name}", place.dir)),
141            None => PathBuf::from(format!("workers/{}/{name}", place.dir)),
142        }
143    }
144
145    /// The import specifier, from a module in `context`'s Worker directory, of
146    /// one of its own files: `./<name>` stripped of its extension and given
147    /// `.js`, with the member prefix in a group (`./shop-orders.compose.js`).
148    pub fn own_module_specifier(&self, context: &str, name: &str) -> String {
149        let file = self.member_file(context, name);
150        let file = file.file_name().unwrap_or_default().to_string_lossy();
151        let stem = file.rsplit_once('.').map_or(&*file, |(stem, _)| stem);
152        format!("./{stem}.js")
153    }
154
155    /// The project-relative synthetic source path of `context`'s handlers
156    /// module, which the emitter's relative-import machinery resolves against.
157    pub fn handlers_source_path(&self, context: &str) -> PathBuf {
158        self.member_file(context, "handlers.bynk")
159    }
160
161    /// The project-relative output path of `context`'s handlers module.
162    pub fn handlers_output_path(&self, context: &str) -> PathBuf {
163        self.member_file(context, "handlers.ts")
164    }
165
166    /// The synthetic source path of one file's module in a context split across
167    /// files (#1820): `handlers/<stem>.bynk` beside the handlers barrel.
168    pub fn file_source_path(&self, context: &str, source: &std::path::Path) -> PathBuf {
169        let stem = source.file_stem().unwrap_or_default().to_string_lossy();
170        self.member_file(context, &format!("handlers/{stem}.bynk"))
171    }
172
173    /// The specifier by which one of `context`'s own modules (its compose and
174    /// entry) imports its handlers module: `./handlers.js`, or
175    /// `./<member>.handlers.js` in a group.
176    pub fn own_handlers_specifier(&self, context: &str) -> String {
177        format!("./{}", self.handlers_file_stem(context))
178    }
179
180    fn handlers_file_stem(&self, context: &str) -> String {
181        let file = self.handlers_output_path(context);
182        let name = file.file_name().unwrap_or_default().to_string_lossy();
183        format!("{}.js", name.trim_end_matches(".ts"))
184    }
185
186    /// The import specifier, from a module in `from`'s Worker directory, of
187    /// `to`'s handlers module: `../<dir>/handlers.js` across Workers,
188    /// `./<member>.handlers.js` within one.
189    pub fn handlers_specifier(&self, from: &str, to: &str) -> String {
190        let name = self.handlers_file_stem(to);
191        // A context naming its own handlers from a module one directory down
192        // (a split context's) goes up and back in, as it always has.
193        if from != to && self.dir(from) == self.dir(to) {
194            format!("./{name}")
195        } else {
196            format!("../{}/{name}", self.dir(to))
197        }
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use crate::worker_groups::WorkerGroup;
205
206    fn groups() -> WorkerGroups {
207        WorkerGroups::from([(
208            "core".to_string(),
209            WorkerGroup {
210                contexts: vec!["shop.orders".to_string(), "shop.pricing".to_string()],
211                ..WorkerGroup::default()
212            },
213        )])
214    }
215
216    /// With no group, a context's files are where they have always been.
217    #[test]
218    fn identity_is_one_directory_per_context() {
219        let layout = WorkerLayout::identity();
220        assert_eq!(layout.dir("shop.orders"), "shop-orders");
221        assert_eq!(
222            layout.worker_file("shop.orders", "wrangler.toml"),
223            PathBuf::from("workers/shop-orders/wrangler.toml")
224        );
225        assert_eq!(
226            layout.member_file("shop.orders", "compose.ts"),
227            PathBuf::from("workers/shop-orders/compose.ts")
228        );
229    }
230
231    /// A group's members share its directory, each under its own prefix; a
232    /// Worker-wide file takes none.
233    #[test]
234    fn members_share_the_groups_directory_under_a_prefix() {
235        let layout = WorkerLayout::from_groups(&groups());
236        assert_eq!(layout.dir("shop.pricing"), "core");
237        assert_eq!(
238            layout.member_file("shop.orders", "compose.ts"),
239            PathBuf::from("workers/core/shop-orders.compose.ts")
240        );
241        assert_eq!(
242            layout.member_file("shop.pricing", "compose.ts"),
243            PathBuf::from("workers/core/shop-pricing.compose.ts")
244        );
245        assert_eq!(
246            layout.worker_file("shop.pricing", "index.ts"),
247            PathBuf::from("workers/core/index.ts")
248        );
249    }
250
251    /// Only a member of a group is a member: a project with no group has none.
252    #[test]
253    fn only_a_group_member_is_a_member() {
254        assert!(!WorkerLayout::identity().is_member("shop.orders"));
255        let layout = WorkerLayout::from_groups(&groups());
256        assert!(layout.is_member("shop.orders"));
257        assert!(!layout.is_member("shop.payment"));
258    }
259
260    /// A Worker's name on Cloudflare is the group's `name`, else its key; a
261    /// context's own is its dashed name. A member's own modules are imported under
262    /// its prefix, and a group lists its members in manifest order.
263    #[test]
264    fn a_groups_script_name_modules_and_members() {
265        let mut named = groups();
266        named.get_mut("core").unwrap().name = Some("acme-core".to_string());
267        let layout = WorkerLayout::from_groups(&named);
268        assert_eq!(layout.script_name("shop.orders"), "acme-core");
269        assert_eq!(layout.dir("shop.orders"), "core");
270        assert_eq!(layout.script_name("shop.payment"), "shop-payment");
271        assert_eq!(
272            layout.own_module_specifier("shop.pricing", "compose.ts"),
273            "./shop-pricing.compose.js"
274        );
275        assert_eq!(
276            WorkerLayout::identity().own_module_specifier("shop.pricing", "events_fanout.ts"),
277            "./events_fanout.js"
278        );
279        assert_eq!(
280            layout.group_members("core"),
281            Some(["shop.orders".to_string(), "shop.pricing".to_string()].as_slice())
282        );
283        assert_eq!(layout.group_members("shop-payment"), None);
284    }
285
286    /// A context in no group stays as in the identity layout.
287    #[test]
288    fn an_ungrouped_context_is_unchanged() {
289        let layout = WorkerLayout::from_groups(&groups());
290        assert_eq!(layout.dir("shop.payment"), "shop-payment");
291        assert_eq!(
292            layout.member_file("shop.payment", "compose.ts"),
293            PathBuf::from("workers/shop-payment/compose.ts")
294        );
295    }
296
297    /// Without a group the handlers paths and specifiers are the ones every
298    /// Workers build has always used.
299    #[test]
300    fn identity_handlers_paths_are_unchanged() {
301        let layout = WorkerLayout::identity();
302        assert_eq!(
303            layout.handlers_source_path("shop.orders"),
304            PathBuf::from("workers/shop-orders/handlers.bynk")
305        );
306        assert_eq!(
307            layout.handlers_output_path("shop.orders"),
308            PathBuf::from("workers/shop-orders/handlers.ts")
309        );
310        assert_eq!(
311            layout.file_source_path(
312                "shop.orders",
313                std::path::Path::new("shop/orders/place.bynk")
314            ),
315            PathBuf::from("workers/shop-orders/handlers/place.bynk")
316        );
317        assert_eq!(
318            layout.own_handlers_specifier("shop.orders"),
319            "./handlers.js"
320        );
321        assert_eq!(
322            layout.handlers_specifier("shop.orders", "shop.pricing"),
323            "../shop-pricing/handlers.js"
324        );
325    }
326
327    /// In a group a member's handlers sit beside its siblings' under its prefix,
328    /// and an import within the Worker is local; one out of it is not.
329    #[test]
330    fn members_handlers_are_prefixed_and_imported_locally() {
331        let layout = WorkerLayout::from_groups(&groups());
332        assert_eq!(
333            layout.handlers_output_path("shop.pricing"),
334            PathBuf::from("workers/core/shop-pricing.handlers.ts")
335        );
336        assert_eq!(
337            layout.file_source_path("shop.orders", std::path::Path::new("o/place.bynk")),
338            PathBuf::from("workers/core/shop-orders.handlers/place.bynk")
339        );
340        assert_eq!(
341            layout.handlers_specifier("shop.orders", "shop.pricing"),
342            "./shop-pricing.handlers.js"
343        );
344        assert_eq!(
345            layout.handlers_specifier("shop.orders", "billing"),
346            "../billing/handlers.js"
347        );
348    }
349
350    /// A context importing its own handlers (a split context's agent deps) keeps
351    /// the specifier it has always had, so a build without groups is unchanged.
352    #[test]
353    fn a_contexts_own_handlers_import_keeps_its_spelling() {
354        assert_eq!(
355            WorkerLayout::identity().handlers_specifier("shop.orders", "shop.orders"),
356            "../shop-orders/handlers.js"
357        );
358    }
359}