1use super::run::DevOptions;
2use super::serving::Serving;
3use bynk_driver::emsg;
4use std::path::Path;
5use std::path::PathBuf;
6
7#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct StandIn {
13 pub worker: String,
14 pub bindings: Vec<String>,
15}
16
17pub fn stand_in_name(context: &str, worker: &str) -> String {
28 let name = format!("bynk-stand-in-{context}-{worker}");
29 if name.len() <= 63 {
30 return name;
31 }
32 let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
34 (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
35 });
36 let suffix = format!("-{:08x}", hash as u32);
37 let mut cut = 63 - suffix.len();
38 while !name.is_char_boundary(cut) {
39 cut -= 1;
40 }
41 format!("{}{suffix}", name[..cut].trim_end_matches('-'))
42}
43
44pub fn foreign_services(config_text: &str, project_workers: &[String]) -> Vec<(String, String)> {
49 let Ok(doc) = config_text.parse::<toml::Table>() else {
50 return Vec::new();
51 };
52 let mut out: Vec<(String, String)> = doc
53 .get(bynk_project::wrangler_keys::WranglerKey::Services.top_key())
54 .and_then(toml::Value::as_array)
55 .into_iter()
56 .flatten()
57 .filter_map(|s| {
58 let binding = s.get("binding")?.as_str()?;
59 let worker = s.get("service")?.as_str()?;
60 (!project_workers.iter().any(|w| w == worker))
61 .then(|| (binding.to_string(), worker.to_string()))
62 })
63 .collect();
64 out.sort();
65 out
66}
67
68pub fn stand_ins(foreign: &[(String, String)], local: &[String]) -> Vec<StandIn> {
74 let mut by_worker: std::collections::BTreeMap<&str, Vec<String>> = Default::default();
75 for (binding, worker) in foreign {
76 if !local.iter().any(|l| l == worker) {
77 by_worker.entry(worker).or_default().push(binding.clone());
78 }
79 }
80 by_worker
81 .into_iter()
82 .map(|(worker, bindings)| StandIn {
83 worker: worker.to_string(),
84 bindings,
85 })
86 .collect()
87}
88
89pub fn stand_in_files(context: &str, stand_in: &StandIn) -> (String, String) {
94 let config = format!(
95 "# Generated by bynk dev — `{context}`'s local stand-in for Worker `{w}`.\nname = {name}\nmain = \"index.js\"\ncompatibility_date = \"{date}\"\n",
96 w = stand_in.worker,
97 name = toml::Value::String(stand_in_name(context, &stand_in.worker)),
98 date = bynk_emit::emitter::wrangler::COMPATIBILITY_DATE,
99 );
100 let body = format!(
101 "{} Run that Worker locally with `wrangler dev` and pass `--local-worker {}` to `bynk dev` to call it instead.",
102 bynk_emit::emitter::wrangler::foreign_service_double_body(
103 &stand_in.bindings.join("`, `"),
104 &stand_in.worker
105 ),
106 stand_in.worker
107 );
108 let script = format!(
109 "// Generated by bynk dev — a local stand-in for Worker `{w}`.\nexport default {{\n async fetch() {{\n return new Response({body}, {{\n status: {status},\n headers: {{ \"content-type\": \"text/plain; charset=utf-8\", \"x-bynk-stand-in\": {name} }},\n }});\n }},\n}};\n",
110 w = stand_in.worker,
111 body = serde_json::Value::String(body),
112 status = bynk_emit::emitter::wrangler::FOREIGN_SERVICE_DOUBLE_STATUS,
113 name = serde_json::Value::String(stand_in.worker.clone()),
114 );
115 (config, script)
116}
117
118pub(super) fn write_stand_ins(
122 build_dir: &Path,
123 plans: &[(String, Vec<StandIn>)],
124) -> std::io::Result<std::collections::BTreeMap<String, Vec<PathBuf>>> {
125 let root = build_dir.join("stand-ins");
126 match std::fs::remove_dir_all(&root) {
127 Ok(()) => {}
128 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
129 Err(e) => return Err(e),
130 }
131 let mut configs = std::collections::BTreeMap::new();
132 for (context, stand_ins) in plans {
133 for stand_in in stand_ins {
134 let dir = root.join(context).join(&stand_in.worker);
135 std::fs::create_dir_all(&dir)?;
136 let (config, script) = stand_in_files(context, stand_in);
137 std::fs::write(dir.join("wrangler.toml"), config)?;
138 std::fs::write(dir.join("index.js"), script)?;
139 configs
140 .entry(context.clone())
141 .or_insert_with(Vec::new)
142 .push(dir.join("wrangler.toml"));
143 }
144 }
145 Ok(configs)
146}
147
148pub fn stand_in_report(plans: &[(String, Vec<StandIn>)]) -> String {
151 let mut out = String::new();
152 for (context, stand_ins) in plans {
153 for s in stand_ins {
154 out.push_str(&format!(
155 "bynk dev: `{context}` binds Worker `{w}` ({}) to a local stand-in that answers 503; pass `--local-worker {w}` to reach a `wrangler dev` of it instead.\n",
156 s.bindings.join(", "),
157 w = s.worker,
158 ));
159 }
160 }
161 out
162}
163
164pub(super) fn plan_stand_ins(
168 workers_dir: &Path,
169 serving: &[Serving],
170 available: &[String],
171 opts: &DevOptions,
172 remote: bool,
173) -> Vec<(String, Vec<StandIn>)> {
174 let mut stand_in_plans: Vec<(String, Vec<StandIn>)> = Vec::new();
175 let known = crate::deploy::script_names_of(workers_dir, available);
176 let mut bound_foreign: Vec<String> = Vec::new();
177 for s in serving {
178 let config = std::fs::read_to_string(workers_dir.join(&s.worker).join("wrangler.toml"))
179 .unwrap_or_default();
180 let foreign = foreign_services(&config, &known);
181 bound_foreign.extend(foreign.iter().map(|(_, w)| w.clone()));
182 let planned = stand_ins(&foreign, &opts.local_workers);
183 if !remote && !planned.is_empty() {
184 stand_in_plans.push((s.worker.clone(), planned));
185 }
186 }
187 for local in &opts.local_workers {
188 if !bound_foreign.contains(local) {
189 emsg!(
190 "bynk: warning: `--local-worker {local}` names no Worker the served contexts bind with a `Service` instance."
191 );
192 }
193 }
194 stand_in_plans
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200 use crate::dev::test_support::group_project;
201 use crate::dev::test_support::names;
202 use crate::dev::test_support::pairs;
203
204 #[test]
208 fn a_renamed_groups_script_is_not_a_foreign_worker() {
209 let root = group_project("script", "");
210 let dir = root.join("core");
211 std::fs::create_dir_all(&dir).unwrap();
212 std::fs::write(dir.join("wrangler.toml"), "name = \"core-script\"\n").unwrap();
213 let known = crate::deploy::script_names_of(&root, &names(&["core"]));
214 assert_eq!(known, names(&["core-script"]));
215 let web = "[[services]]\nbinding = \"A\"\nservice = \"core-script\"\n\n[[services]]\nbinding = \"B\"\nservice = \"legacy\"\n";
216 assert_eq!(
217 foreign_services(web, &known),
218 vec![("B".to_string(), "legacy".to_string())]
219 );
220 let _ = std::fs::remove_dir_all(&root);
221 }
222
223 const BILLING_CONFIG: &str = "name = \"shop-billing\"\n\n[[services]]\nbinding = \"SHOP_FRONT\"\nservice = \"shop-front\"\n\n[[services]]\nbinding = \"SERVICE_LEDGER\"\nservice = \"ledger\"\n\n[[services]]\nbinding = \"SERVICE_BILLING\"\nservice = \"legacy-billing\"\n\n[[services]]\nbinding = \"SERVICE_INVOICES\"\nservice = \"legacy-billing\"\n";
226
227 #[test]
228 fn foreign_services_are_the_bindings_to_workers_outside_the_build() {
229 assert_eq!(
230 foreign_services(BILLING_CONFIG, &names(&["shop-billing", "shop-front"])),
231 pairs(&[
232 ("SERVICE_BILLING", "legacy-billing"),
233 ("SERVICE_INVOICES", "legacy-billing"),
234 ("SERVICE_LEDGER", "ledger"),
235 ])
236 );
237 assert!(foreign_services("not toml [", &[]).is_empty());
238 }
239
240 #[test]
243 fn stand_ins_are_one_per_foreign_worker_less_the_local_ones() {
244 let foreign = foreign_services(BILLING_CONFIG, &names(&["shop-front"]));
245 assert_eq!(
246 stand_ins(&foreign, &[]),
247 [
248 StandIn {
249 worker: "ledger".into(),
250 bindings: names(&["SERVICE_LEDGER"]),
251 },
252 StandIn {
253 worker: "legacy-billing".into(),
254 bindings: names(&["SERVICE_BILLING", "SERVICE_INVOICES"]),
255 },
256 ]
257 );
258 assert_eq!(
259 stand_ins(&foreign, &names(&["legacy-billing"])),
260 [StandIn {
261 worker: "ledger".into(),
262 bindings: names(&["SERVICE_LEDGER"]),
263 }]
264 );
265 }
266
267 #[test]
271 fn a_stand_in_is_named_for_its_worker_and_answers_503() {
272 let (config, script) = stand_in_files(
273 "shop-billing",
274 &StandIn {
275 worker: "legacy-billing".into(),
276 bindings: names(&["SERVICE_BILLING"]),
277 },
278 );
279 let doc: toml::Table = config.parse().expect("valid TOML");
280 assert_eq!(
281 doc["name"].as_str(),
282 Some("bynk-stand-in-shop-billing-legacy-billing")
283 );
284 assert_eq!(doc["main"].as_str(), Some("index.js"));
285 assert_eq!(
286 doc["compatibility_date"].as_str(),
287 Some(bynk_emit::emitter::wrangler::COMPATIBILITY_DATE)
288 );
289 assert!(script.contains("status: 503"), "{script}");
290 assert!(
291 script.contains("`--local-worker legacy-billing`"),
292 "{script}"
293 );
294 assert!(script.contains("`SERVICE_BILLING`"), "{script}");
295 }
296
297 #[test]
298 fn a_stand_in_name_fits_a_worker_name() {
299 assert_eq!(
300 stand_in_name("shop-billing", "legacy-billing"),
301 "bynk-stand-in-shop-billing-legacy-billing"
302 );
303 let long_context = "commerce-fulfilment-warehouse-allocation";
304 let a = stand_in_name(long_context, "legacy-billing-reconciliation");
305 let b = stand_in_name(long_context, "legacy-billing-reconciliation-eu");
306 assert!(a.len() <= 63 && b.len() <= 63, "{a} / {b}");
307 assert_ne!(a, b);
308 assert_eq!(
309 a,
310 stand_in_name(long_context, "legacy-billing-reconciliation")
311 );
312 assert!(!a.contains("--"), "{a}");
313 }
314
315 #[test]
316 fn the_stand_in_report_names_each_and_the_way_out() {
317 assert_eq!(stand_in_report(&[]), "");
318 let report = stand_in_report(&[(
319 "shop-billing".into(),
320 vec![StandIn {
321 worker: "legacy-billing".into(),
322 bindings: names(&["SERVICE_BILLING"]),
323 }],
324 )]);
325 assert_eq!(
326 report,
327 "bynk dev: `shop-billing` binds Worker `legacy-billing` (SERVICE_BILLING) to a local stand-in that answers 503; pass `--local-worker legacy-billing` to reach a `wrangler dev` of it instead.\n"
328 );
329 }
330}