Skip to main content

bynk_emit/emitter/
bindings.rs

1//! One binding model per build (back-half paydown 1C.1a, Decisions A to E of
2//! #4031).
3//!
4//! [`WorkerBindings`] holds every binding each context's Worker declares, in
5//! the order its `wrangler.toml` lists them, and each Worker's own list (its
6//! members' merged). It is derived once from the [`ComposePlan`] and the
7//! checked unit tables by [`WorkerBindings::derive`]; nothing else computes
8//! which bindings a Worker has.
9//!
10//! The vocabulary ([`BindingSource`], [`WorkerBinding`]) stays in
11//! `bynk-check`, which needs it for the duplicate-binding diagnostics. The
12//! model, its derivation and its order are the emitter's. The order is a
13//! stable sort by `rank`, one exhaustive `match`, so a new kind of binding
14//! fails to compile until it is placed, rather than being silently left out of
15//! `wrangler.toml`.
16
17use std::collections::{BTreeMap, HashMap, HashSet};
18
19use bynk_check::firstparty;
20use bynk_check::symbols::{DerivedInstance, UnitTable};
21use bynk_project::worker_layout::WorkerLayout;
22
23pub use bynk_check::worker_bindings::{BindingSource, WorkerBinding};
24
25use super::compose::{ComposePlan, ComposeUnit};
26use super::wrangler::EVENTS_FANOUT_CLASS_NAME;
27
28/// Every binding of every Worker in a build.
29#[derive(Debug, Clone, PartialEq, Eq, Default)]
30pub struct WorkerBindings {
31    /// Each context's bindings, in the order its `wrangler.toml` lists them.
32    contexts: BTreeMap<String, Vec<WorkerBinding>>,
33    /// Each Worker's (by [`WorkerLayout::dir`]): its members' merged, an
34    /// identical declaration one binding (#3562), in the manifest's member
35    /// order.
36    workers: BTreeMap<String, Vec<WorkerBinding>>,
37}
38
39impl WorkerBindings {
40    /// Derive every context's bindings from the plan's facts and the unit
41    /// tables' agents and derived instances, then each Worker's.
42    pub fn derive(
43        plan: &ComposePlan,
44        unit_tables: &HashMap<String, UnitTable>,
45        layout: &WorkerLayout,
46    ) -> Self {
47        let mut contexts = BTreeMap::new();
48        for (name, unit) in plan.contexts() {
49            let Some(table) = unit_tables.get(name) else {
50                continue;
51            };
52            contexts.insert(name.clone(), context_bindings(name, unit, table, plan));
53        }
54        let workers = workers_of(&contexts, layout);
55        Self { contexts, workers }
56    }
57
58    /// A model holding exactly `workers`' bindings, each keyed as both a
59    /// context and a Worker directory: what a reader of the model is tested
60    /// against, without compiling a project.
61    #[doc(hidden)]
62    pub fn of_workers(workers: BTreeMap<String, Vec<WorkerBinding>>) -> Self {
63        Self {
64            contexts: workers.clone(),
65            workers,
66        }
67    }
68
69    /// The bindings of context `context`'s Worker; none for a name that is not
70    /// a context.
71    pub fn of(&self, context: &str) -> &[WorkerBinding] {
72        self.contexts.get(context).map_or(&[], Vec::as_slice)
73    }
74
75    /// The bindings of the Worker in directory `dir`: its members' merged.
76    pub fn of_worker(&self, dir: &str) -> &[WorkerBinding] {
77        self.workers.get(dir).map_or(&[], Vec::as_slice)
78    }
79
80    /// Every context's bindings, by context name: what the duplicate and group
81    /// checks read, and what the integration harness binds on each
82    /// participant's `env`.
83    pub fn by_context(&self) -> &BTreeMap<String, Vec<WorkerBinding>> {
84        &self.contexts
85    }
86
87    /// #3477: a container's image is built from a directory of the project,
88    /// which `wrangler` reaches from the Worker's output directory. Sets each
89    /// container binding's path back to the project root, in every context's
90    /// list and every Worker's, once for the build.
91    pub fn locate_containers(&mut self, root_from_worker: &str) {
92        for binding in self.contexts.values_mut().chain(self.workers.values_mut()) {
93            for binding in binding {
94                if let BindingSource::ContainerInstance {
95                    root_from_worker: slot,
96                    ..
97                } = &mut binding.source
98                {
99                    root_from_worker.clone_into(slot);
100                }
101            }
102        }
103    }
104}
105
106/// Context `name`'s bindings: what it calls, what subscribes to its events, the
107/// bare resources its closure reaches, its derived instances, the implicit
108/// idempotency database, and its agents and fan-out.
109fn context_bindings(
110    name: &str,
111    unit: &ComposeUnit,
112    table: &UnitTable,
113    plan: &ComposePlan,
114) -> Vec<WorkerBinding> {
115    // A Worker holds a Service Binding to each context it calls, and to each
116    // context subscribing to an event it publishes (Events track, slice 0,
117    // spine #936, ADR 0284): the reverse direction of an ordinary `consumes`
118    // edge, which nothing upstream gives the publisher. #1961: a consumed
119    // context is bound only when called, never merely for being consumed, or a
120    // subscriber and its publisher would bind each other.
121    let mut targets: Vec<String> = unit.called.clone();
122    targets.extend(
123        plan.events
124            .published_by(name)
125            .flat_map(|(_, subs)| subs.iter().map(|s| s.context.clone())),
126    );
127    targets.sort();
128    targets.dedup();
129    let agents: Vec<String> = table.agents.keys().cloned().collect();
130    // The instances in capability order; the implicit idempotency database
131    // after them.
132    let mut instances: Vec<(&String, WorkerBinding)> = table
133        .derived
134        .iter()
135        // L7 (#2414): Workers Cache is a Worker-wide `[cache]` setting, not an
136        // `env` binding.
137        .filter(|(_, d)| !d.is_edge_cache())
138        .map(|(cap, d)| (cap, instance_binding(cap, d)))
139        .collect();
140    instances.sort_by(|a, b| a.0.cmp(b.0));
141    let mut instances: Vec<WorkerBinding> = instances.into_iter().map(|(_, b)| b).collect();
142    if unit.idempotency {
143        instances.push(bynk_check::worker_bindings::idempotency_binding());
144    }
145    let singletons: Vec<WorkerBinding> = unit
146        .bare_singletons
147        .iter()
148        .map(|c| singleton_binding(c))
149        .collect();
150    ordered(
151        &agents,
152        &targets,
153        unit.bare_kv,
154        instances,
155        singletons,
156        unit.publishes,
157    )
158}
159
160/// The binding of derived instance `cap`, by its base capability: every
161/// instantiable kind by name, with no catch-all, so a new kind cannot silently
162/// bind as a KV namespace (P3, #2342).
163fn instance_binding(cap: &str, d: &DerivedInstance) -> WorkerBinding {
164    let capability = cap.to_string();
165    let source = match (d.base_unit.as_str(), d.base_cap.as_str()) {
166        (firstparty::CLOUDFLARE_UNIT, "Service") => BindingSource::ForeignService {
167            capability,
168            worker: d.worker().unwrap_or_default().to_string(),
169        },
170        (firstparty::CLOUDFLARE_UNIT, "R2") => BindingSource::R2Instance {
171            capability,
172            jurisdiction: d.jurisdiction().map(str::to_string),
173        },
174        (firstparty::CLOUDFLARE_UNIT, "RateLimit") => {
175            let (limit, period) = d.rate_limit().unwrap_or_default();
176            BindingSource::RateLimitInstance {
177                capability,
178                limit,
179                period,
180            }
181        }
182        (firstparty::CLOUDFLARE_UNIT, "Analytics") => {
183            BindingSource::AnalyticsDataset { capability }
184        }
185        (firstparty::CLOUDFLARE_UNIT, "D1") => BindingSource::D1Database { capability },
186        (firstparty::CLOUDFLARE_UNIT, "Queue") => BindingSource::QueueProducer {
187            capability,
188            queue: d.queue().unwrap_or_default().to_string(),
189        },
190        (firstparty::CLOUDFLARE_UNIT, "StoredSecret") => BindingSource::StoredSecret {
191            capability,
192            store: d.store().unwrap_or_default().to_string(),
193            secret: d.stored_secret().unwrap_or_default().to_string(),
194        },
195        (firstparty::CLOUDFLARE_UNIT, "Postgres") => BindingSource::Postgres { capability },
196        (firstparty::CLOUDFLARE_UNIT, "MySql") => BindingSource::MySql {
197            capability,
198            tls: d.tls().map(str::to_string),
199        },
200        (firstparty::CLOUDFLARE_UNIT, "Email") => BindingSource::Email {
201            capability,
202            to: d.email_to().map(str::to_string),
203            allowed_recipients: d.email_allowed_recipients().to_vec(),
204            allowed_senders: d.email_allowed_senders().to_vec(),
205        },
206        (firstparty::CLOUDFLARE_UNIT, "Vectorize") => BindingSource::VectorizeIndex {
207            capability,
208            dimensions: d.vectorize_dimensions().unwrap_or_default(),
209            metric: d.vectorize_metric().unwrap_or_default().to_string(),
210            indexed: d.vectorize_indexed().to_vec(),
211        },
212        (firstparty::CLOUDFLARE_UNIT, "Container") => BindingSource::ContainerInstance {
213            class_name: bynk_check::containers::container_class_name(&capability),
214            capability,
215            build: bynk_check::containers::normalise_build(d.container_build().unwrap_or_default()),
216            root_from_worker: String::new(),
217            port: d.container_port().unwrap_or_default(),
218            sleep_after: d.container_sleep_after(),
219            instance_type: d.container_instance_type().map(str::to_string),
220            forward: d.container_forward().to_vec(),
221        },
222        (firstparty::CLOUDFLARE_UNIT, "AiSearch") => BindingSource::AiSearchInstance {
223            capability,
224            instance: d.ai_search_instance().unwrap_or_default().to_string(),
225        },
226        (firstparty::CLOUDFLARE_UNIT, "MtlsCertificate") => BindingSource::MtlsCertificate {
227            capability,
228            certificate: d.mtls_certificate().unwrap_or_default().to_string(),
229        },
230        (firstparty::CLOUDFLARE_UNIT, "Kv") => BindingSource::KvInstance { capability },
231        (unit, base) => {
232            unreachable!("`{unit}.{base}` is instantiable but has no binding kind")
233        }
234    };
235    WorkerBinding {
236        name: d.binding.clone(),
237        source,
238    }
239}
240
241/// The order of the bindings of one Worker: Service Bindings by target, then
242/// those to foreign Workers by capability, then the KV namespaces, the other
243/// instances by kind, the one-per-Worker bindings, and the Durable Objects by
244/// class name. `wrangler.toml` lists exactly this order, the Worker's `Env`
245/// interface types it, and the duplicate check reads it, so a new kind of
246/// binding is declared, typed and checked from one place (#1944). Each kind
247/// derives its name independently, so two can meet (an agent `Kv` and the KV
248/// namespace are both `KV`); names are never adjusted to avoid that, because
249/// deployed Workers depend on them. The duplicate check runs first.
250///
251/// `agents` are the context's agents (any order), `targets` the contexts it
252/// binds (any order), `instances` its derived instances in capability order and
253/// `singletons` the one-per-Worker bindings in capability order.
254fn ordered(
255    agents: &[String],
256    targets: &[String],
257    bare_kv: bool,
258    instances: Vec<WorkerBinding>,
259    singletons: Vec<WorkerBinding>,
260    publishes: bool,
261) -> Vec<WorkerBinding> {
262    let mut targets: Vec<&String> = targets.iter().collect();
263    targets.sort();
264    let mut bindings: Vec<WorkerBinding> =
265        targets.into_iter().map(|t| service_binding(t)).collect();
266    if bare_kv {
267        bindings.push(kv_binding());
268    }
269    bindings.extend(instances);
270    bindings.extend(singletons);
271    // Events track, slice 0 (spine #936, ADR 0284): a context whose handlers
272    // emit gets its own fan-out DO among the agents', in the order of the
273    // class names. Sources by provenance, not by name: an agent that happened
274    // to share the fan-out's class name is still an agent.
275    let mut objects: Vec<(&str, WorkerBinding)> = agents
276        .iter()
277        .map(|class_name| (class_name.as_str(), agent_binding(class_name)))
278        .collect();
279    if publishes {
280        objects.push((EVENTS_FANOUT_CLASS_NAME, events_fanout_binding()));
281    }
282    objects.sort_by(|a, b| a.0.cmp(b.0));
283    bindings.extend(objects.into_iter().map(|(_, binding)| binding));
284    // Stable, so inside a rank the input's order stands: services by target,
285    // instances by capability, the implicit database after the others.
286    bindings.sort_by_key(|b| rank(&b.source));
287    bindings
288}
289
290/// Where a kind of binding falls in a Worker's list. One exhaustive `match`:
291/// a new [`BindingSource`] does not compile until it has a place.
292fn rank(source: &BindingSource) -> u8 {
293    match source {
294        BindingSource::Service { .. } => 0,
295        // Interop I5 (#1972): Service Bindings to foreign Workers, beside the
296        // ones to project contexts.
297        BindingSource::ForeignService { .. } => 1,
298        BindingSource::Kv => 2,
299        BindingSource::KvInstance { .. } => 3,
300        // P5 (#2323): the R2 buckets, after the KV namespaces.
301        BindingSource::R2Instance { .. } => 4,
302        // P3 (#2342): the rate limiters, after the buckets.
303        BindingSource::RateLimitInstance { .. } => 5,
304        // P2 (#2578): the queue producers, after the rate limiters.
305        BindingSource::QueueProducer { .. } => 6,
306        // P3b (#2582): the Analytics Engine datasets, after the producers.
307        BindingSource::AnalyticsDataset { .. } => 7,
308        // P4a (#2602): the D1 databases, after the datasets.
309        BindingSource::D1Database { .. } => 8,
310        // #3301: the Secrets Store secrets, after the databases.
311        BindingSource::StoredSecret { .. } => 9,
312        // Hyperdrive H1 (#3318): after the Secrets Store secrets.
313        BindingSource::Postgres { .. } | BindingSource::MySql { .. } => 10,
314        // #3302: the outbound email bindings.
315        BindingSource::Email { .. } => 11,
316        // #3479: the Vectorize indexes, after the email bindings.
317        BindingSource::VectorizeIndex { .. } => 12,
318        // #3477: the containers' Durable Object namespaces, after the indexes.
319        BindingSource::ContainerInstance { .. } => 13,
320        // #3480: the AI Search instances.
321        BindingSource::AiSearchInstance { .. } => 14,
322        // #3513 A: the mTLS certificates, after the AI Search instances.
323        BindingSource::MtlsCertificate { .. } => 15,
324        // #3300: the one-per-Worker bindings.
325        BindingSource::Singleton { .. } => 16,
326        // The agents' Durable Objects and the events fan-out, by class name.
327        BindingSource::Agent { .. } | BindingSource::EventsFanout { .. } => 17,
328    }
329}
330
331// #1958: the constructors below are the only callers of the two name
332// functions, so every place that declares, types or reads a binding (the
333// emitted `env.X`, the fan-out's routing table, the integration harness)
334// gets its name from the one constructor for its kind. A constructor is
335// `pub(crate)` exactly when something outside this file reads its name.
336
337/// The Service Binding to context `target`'s Worker.
338pub fn service_binding(target: &str) -> WorkerBinding {
339    WorkerBinding {
340        name: consumed_binding_name(target),
341        source: BindingSource::Service {
342            context: target.to_string(),
343        },
344    }
345}
346
347/// The bare KV namespace binding the cloudflare adapter's `Kv` reads. Its one
348/// TypeScript read is the default of `WorkersKv`'s `binding` parameter in
349/// `bynk-std`'s `cloudflare.binding.ts`, pinned to `KV_BINDING_NAME` by a test.
350pub(crate) fn kv_binding() -> WorkerBinding {
351    WorkerBinding {
352        name: bynk_check::firstparty::KV_BINDING_NAME.to_string(),
353        source: BindingSource::Kv,
354    }
355}
356
357/// #3300: the binding of `bynk.cloudflare`'s one-per-Worker capability
358/// `capability` (`Version` → `CF_VERSION_METADATA`), by the registry's fixed
359/// name. Its one TypeScript read is the default of its provider's `binding`
360/// parameter in `cloudflare.binding.ts`.
361pub fn singleton_binding(capability: &str) -> WorkerBinding {
362    let singleton =
363        bynk_check::firstparty::singleton(bynk_check::firstparty::CLOUDFLARE_UNIT, capability)
364            .unwrap_or_else(|| panic!("`{capability}` is not a one-per-Worker capability"));
365    WorkerBinding {
366        name: singleton.binding.to_string(),
367        source: BindingSource::Singleton {
368            capability: capability.to_string(),
369        },
370    }
371}
372
373/// The Durable Object binding of agent `class_name`.
374pub(crate) fn agent_binding(class_name: &str) -> WorkerBinding {
375    WorkerBinding {
376        name: agent_binding_name(class_name),
377        source: BindingSource::Agent {
378            class_name: class_name.to_string(),
379        },
380    }
381}
382
383/// The Durable Object binding of the events fan-out class.
384pub(crate) fn events_fanout_binding() -> WorkerBinding {
385    WorkerBinding {
386        name: agent_binding_name(EVENTS_FANOUT_CLASS_NAME),
387        source: BindingSource::EventsFanout {
388            class_name: EVENTS_FANOUT_CLASS_NAME.to_string(),
389        },
390    }
391}
392
393/// Service Binding identifier for a consumed context: uppercase with
394/// underscores. `commerce.payment` → `COMMERCE_PAYMENT`.
395fn consumed_binding_name(target: &str) -> String {
396    target.replace('.', "_").to_uppercase()
397}
398
399/// Durable Object binding identifier for an agent class. We use the
400/// class name in screaming snake case so handlers can grab it by a
401/// predictable name (`OrderEntity` → `ORDER_ENTITY`), the casing derived
402/// capabilities' bindings share.
403fn agent_binding_name(class_name: &str) -> String {
404    bynk_check::worker_bindings::screaming_snake(class_name)
405}
406
407/// #1950: the bindings a handler's `deps.env` type exposes on Workers — the
408/// projection of the Worker's [`WorkerBindings`] list that handlers reach directly, which
409/// `BindingSource`'s variant docs state per kind. `consumed` is the consumed
410/// contexts the handler calls (#1961), `agents` every local agent when the
411/// handler constructs one (else empty); order as in the Worker's list.
412///
413/// bynk_ts::TsExpr by the same constructors, so each name and source is the Worker's
414/// own: a called context is never an adapter (an adapter may not declare a
415/// `service`, `bynk.adapter.disallowed_item`), and the Worker binds every
416/// context any of its bodies calls, so it has a Service Binding; every local
417/// agent has a Durable Object binding. The
418/// KV namespace, the events fan-out and subscribers' Service Bindings never
419/// reach handlers.
420pub(crate) fn handler_bindings(consumed: &[String], agents: &[String]) -> Vec<WorkerBinding> {
421    let mut consumed: Vec<&String> = consumed.iter().collect();
422    consumed.sort();
423    let mut agents: Vec<&String> = agents.iter().collect();
424    agents.sort();
425    consumed
426        .into_iter()
427        .map(|t| service_binding(t))
428        .chain(agents.into_iter().map(|a| agent_binding(a)))
429        .collect()
430}
431
432/// Each Worker's bindings: its members' merged, an identical declaration one
433/// binding (#3562). A group's members are in the manifest's order; every other
434/// context is its own Worker.
435fn workers_of(
436    contexts: &BTreeMap<String, Vec<WorkerBinding>>,
437    layout: &WorkerLayout,
438) -> BTreeMap<String, Vec<WorkerBinding>> {
439    let mut by_dir: BTreeMap<String, Vec<&str>> = BTreeMap::new();
440    for ctx in contexts.keys() {
441        by_dir.entry(layout.dir(ctx)).or_default().push(ctx);
442    }
443    by_dir
444        .into_keys()
445        .map(|dir| {
446            let order: Vec<String> = layout.group_members(&dir).map_or_else(
447                || {
448                    contexts
449                        .keys()
450                        .filter(|c| layout.dir(c) == dir)
451                        .cloned()
452                        .collect()
453                },
454                <[String]>::to_vec,
455            );
456            let merged = merge_group_bindings(
457                order
458                    .iter()
459                    .filter_map(|c| contexts.get(c))
460                    .map(Vec::as_slice),
461            );
462            (dir, merged)
463        })
464        .collect()
465}
466
467/// The bindings of one Worker from its members' (#3562): each name once, at its
468/// first declaration. Two members declaring one name is one binding when the
469/// declarations are identical; when they differ it is the error
470/// [`bynk_check::worker_bindings::phase_group_binding_collisions`] reports, so a build that reaches the emit
471/// has none.
472fn merge_group_bindings<'a>(
473    members: impl IntoIterator<Item = &'a [WorkerBinding]>,
474) -> Vec<WorkerBinding> {
475    let mut seen: HashSet<&str> = HashSet::new();
476    let mut merged: Vec<WorkerBinding> = Vec::new();
477    for bindings in members {
478        for binding in bindings {
479            if seen.insert(binding.name.as_str()) {
480                merged.push(binding.clone());
481            }
482        }
483    }
484    merged
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490
491    fn names(bindings: &[WorkerBinding]) -> Vec<&str> {
492        bindings.iter().map(|b| b.name.as_str()).collect()
493    }
494
495    fn instance(name: &str, source: BindingSource) -> WorkerBinding {
496        WorkerBinding {
497            name: name.to_string(),
498            source,
499        }
500    }
501
502    fn cap(c: &str) -> String {
503        c.to_string()
504    }
505
506    /// The fan-out's binding name, which its class name (`__BynkEventsFanout`)
507    /// gives a leading `___`.
508    fn fanout() -> String {
509        events_fanout_binding().name
510    }
511
512    #[test]
513    fn services_are_in_target_order_and_before_everything_else() {
514        let bindings = ordered(
515            &[cap("Cart")],
516            &[cap("shop.orders"), cap("shop.billing")],
517            true,
518            vec![],
519            vec![],
520            false,
521        );
522        assert_eq!(
523            names(&bindings),
524            ["SHOP_BILLING", "SHOP_ORDERS", "KV", "CART"]
525        );
526    }
527
528    #[test]
529    fn every_kind_is_in_emission_order() {
530        let at = |name: &str, source| instance(name, source);
531        // Fed in capability order, as `context_bindings` feeds them: the sort
532        // alone puts the kinds in rank order.
533        let instances = vec![
534            at(
535                "MTLS_A",
536                BindingSource::MtlsCertificate {
537                    capability: cap("A"),
538                    certificate: cap("c"),
539                },
540            ),
541            at(
542                "AI_B",
543                BindingSource::AiSearchInstance {
544                    capability: cap("B"),
545                    instance: cap("i"),
546                },
547            ),
548            at(
549                "CONTAINER_C",
550                BindingSource::ContainerInstance {
551                    capability: cap("C"),
552                    class_name: cap("C"),
553                    build: cap("."),
554                    root_from_worker: String::new(),
555                    port: 80,
556                    sleep_after: None,
557                    instance_type: None,
558                    forward: vec![],
559                },
560            ),
561            at(
562                "VEC_D",
563                BindingSource::VectorizeIndex {
564                    capability: cap("D"),
565                    dimensions: 3,
566                    metric: cap("cosine"),
567                    indexed: vec![],
568                },
569            ),
570            at(
571                "MAIL_E",
572                BindingSource::Email {
573                    capability: cap("E"),
574                    to: None,
575                    allowed_recipients: vec![],
576                    allowed_senders: vec![],
577                },
578            ),
579            at(
580                "PG_F",
581                BindingSource::Postgres {
582                    capability: cap("F"),
583                },
584            ),
585            at(
586                "SECRET_G",
587                BindingSource::StoredSecret {
588                    capability: cap("G"),
589                    store: cap("s"),
590                    secret: cap("x"),
591                },
592            ),
593            at(
594                "D1_H",
595                BindingSource::D1Database {
596                    capability: cap("H"),
597                },
598            ),
599            bynk_check::worker_bindings::idempotency_binding(),
600            at(
601                "DS_I",
602                BindingSource::AnalyticsDataset {
603                    capability: cap("I"),
604                },
605            ),
606            at(
607                "Q_J",
608                BindingSource::QueueProducer {
609                    capability: cap("J"),
610                    queue: cap("q"),
611                },
612            ),
613            at(
614                "RL_K",
615                BindingSource::RateLimitInstance {
616                    capability: cap("K"),
617                    limit: 1,
618                    period: 60,
619                },
620            ),
621            at(
622                "R2_L",
623                BindingSource::R2Instance {
624                    capability: cap("L"),
625                    jurisdiction: None,
626                },
627            ),
628            at(
629                "KV_M",
630                BindingSource::KvInstance {
631                    capability: cap("M"),
632                },
633            ),
634            at(
635                "FOREIGN_N",
636                BindingSource::ForeignService {
637                    capability: cap("N"),
638                    worker: cap("w"),
639                },
640            ),
641        ];
642        let bindings = ordered(
643            &[cap("Zed"), cap("Alpha")],
644            &[cap("shop.a")],
645            true,
646            instances,
647            vec![singleton_binding("Version")],
648            true,
649        );
650        assert_eq!(
651            names(&bindings),
652            [
653                "SHOP_A",
654                "FOREIGN_N",
655                "KV",
656                "KV_M",
657                "R2_L",
658                "RL_K",
659                "Q_J",
660                "DS_I",
661                "D1_H",
662                // The implicit idempotency database is last among the
663                // databases, as it is pushed after the sorted instances.
664                bynk_check::d1_migrations::IDEMPOTENCY_BINDING,
665                "SECRET_G",
666                "PG_F",
667                "MAIL_E",
668                "VEC_D",
669                "CONTAINER_C",
670                "AI_B",
671                "MTLS_A",
672                "CF_VERSION_METADATA",
673                "ALPHA",
674                "ZED",
675                fanout().as_str(),
676            ]
677        );
678    }
679
680    #[test]
681    fn an_agent_sharing_the_fanout_class_name_is_still_an_agent() {
682        let bindings = ordered(
683            &[cap(EVENTS_FANOUT_CLASS_NAME)],
684            &[],
685            false,
686            vec![],
687            vec![],
688            true,
689        );
690        assert_eq!(bindings.len(), 2);
691        assert!(matches!(bindings[0].source, BindingSource::Agent { .. }));
692        assert!(matches!(
693            bindings[1].source,
694            BindingSource::EventsFanout { .. }
695        ));
696    }
697
698    /// #1950: the handler projection is drawn from the Worker's own list, each
699    /// binding identical (name and source, a Service Binding and an agent's
700    /// alike), and leaves out the KV namespace and the events fan-out.
701    #[test]
702    fn handler_bindings_are_a_subset_of_the_worker_bindings() {
703        let worker = ordered(
704            &[cap("OrderEntity")],
705            &[cap("shop.payment"), cap("audit")],
706            true,
707            vec![],
708            vec![],
709            true,
710        );
711        let handler = handler_bindings(&[cap("shop.payment")], &[cap("OrderEntity")]);
712        assert_eq!(names(&handler), ["SHOP_PAYMENT", "ORDER_ENTITY"]);
713        for binding in &handler {
714            assert!(worker.contains(binding), "{binding:?} not in {worker:?}");
715        }
716    }
717
718    /// A consumed context `kv` and the KV namespace are both `KV`: the later
719    /// one is paired with the earlier.
720    #[test]
721    fn a_shared_name_pairs_the_later_binding_with_the_earlier() {
722        let bindings = ordered(&[], &[cap("kv")], true, vec![], vec![], false);
723        let duplicates = bynk_check::worker_bindings::duplicate_bindings(&bindings);
724        assert_eq!(duplicates.len(), 1);
725        let (earlier, later) = duplicates[0];
726        assert_eq!(
727            earlier.source,
728            BindingSource::Service { context: cap("kv") }
729        );
730        assert_eq!(later.source, BindingSource::Kv);
731    }
732
733    /// #3562: a name two members of a group both declare is one binding, at its
734    /// first declaration.
735    #[test]
736    fn a_group_merges_an_identical_declaration_into_one_binding() {
737        let kv = |name: &str| {
738            instance(
739                name,
740                BindingSource::KvInstance {
741                    capability: cap(name),
742                },
743            )
744        };
745        let first = vec![kv("A"), kv("B")];
746        let second = vec![kv("B"), kv("C")];
747        let merged = merge_group_bindings([first.as_slice(), second.as_slice()]);
748        assert_eq!(names(&merged), ["A", "B", "C"]);
749    }
750
751    fn plan_with(units: Vec<(&str, super::super::compose::ComposeUnitFacts)>) -> ComposePlan {
752        ComposePlan::decide(&super::super::compose::ComposeFacts {
753            units: units.into_iter().map(|(n, f)| (n.to_string(), f)).collect(),
754            ..Default::default()
755        })
756    }
757
758    fn context(
759        f: impl FnOnce(&mut super::super::compose::ComposeUnitFacts),
760    ) -> super::super::compose::ComposeUnitFacts {
761        let mut facts = super::super::compose::ComposeUnitFacts {
762            is_context: true,
763            has_services: true,
764            ..Default::default()
765        };
766        f(&mut facts);
767        facts
768    }
769
770    #[test]
771    fn derive_reads_the_plans_facts() {
772        let plan = plan_with(vec![
773            (
774                "shop",
775                context(|f| {
776                    f.called = vec![cap("billing")];
777                    f.bare_kv = true;
778                    f.bare_singletons = vec![cap("Version")];
779                    f.idempotency = true;
780                    f.publishes = true;
781                }),
782            ),
783            ("billing", context(|_| {})),
784        ]);
785        let tables: HashMap<String, UnitTable> = [
786            (cap("shop"), UnitTable::default()),
787            (cap("billing"), UnitTable::default()),
788        ]
789        .into();
790        let model = WorkerBindings::derive(&plan, &tables, &WorkerLayout::identity());
791        assert_eq!(
792            names(model.of("shop")),
793            [
794                "BILLING",
795                "KV",
796                bynk_check::d1_migrations::IDEMPOTENCY_BINDING,
797                "CF_VERSION_METADATA",
798                fanout().as_str(),
799            ]
800        );
801        assert!(model.of("billing").is_empty());
802        assert!(model.of("nowhere").is_empty());
803        assert_eq!(model.by_context().len(), 2);
804        assert_eq!(model.of_worker("shop"), model.of("shop"));
805    }
806
807    #[test]
808    fn an_event_subscriber_is_bound_by_its_publisher() {
809        let mut plan = plan_with(vec![
810            ("shop", context(|f| f.publishes = true)),
811            ("audit", context(|_| {})),
812        ]);
813        plan.events.subscriptions.insert(
814            (cap("shop"), cap("OrderPlaced")),
815            vec![super::super::compose::EventSubscription {
816                context: cap("audit"),
817                service: cap("Audit"),
818                wants_envelope: false,
819            }],
820        );
821        let tables: HashMap<String, UnitTable> = [
822            (cap("shop"), UnitTable::default()),
823            (cap("audit"), UnitTable::default()),
824        ]
825        .into();
826        let model = WorkerBindings::derive(&plan, &tables, &WorkerLayout::identity());
827        assert_eq!(names(model.of("shop")), ["AUDIT", fanout().as_str()]);
828        // The reverse direction is not bound: a cycle no upload order satisfies.
829        assert!(model.of("audit").is_empty());
830    }
831
832    #[test]
833    fn locating_containers_reaches_every_list() {
834        let container = instance(
835            "BOX",
836            BindingSource::ContainerInstance {
837                capability: cap("Box"),
838                class_name: cap("Box"),
839                build: cap("."),
840                root_from_worker: String::new(),
841                port: 80,
842                sleep_after: None,
843                instance_type: None,
844                forward: vec![],
845            },
846        );
847        let mut model = WorkerBindings {
848            contexts: [(cap("shop"), vec![container.clone()])].into(),
849            workers: [(cap("shop"), vec![container])].into(),
850        };
851        model.locate_containers("../../..");
852        for list in [model.of("shop"), model.of_worker("shop")] {
853            let BindingSource::ContainerInstance {
854                root_from_worker, ..
855            } = &list[0].source
856            else {
857                panic!("a container");
858            };
859            assert_eq!(root_from_worker, "../../..");
860        }
861    }
862}