Skip to main content

bynk_check/
worker_bindings.rs

1//! A Worker's binding names must be unique (`bynk.context.duplicate_binding`).
2//!
3//! A Worker's bindings come from derivations that know nothing of each other:
4//! the KV namespace's fixed [`crate::firstparty::KV_BINDING_NAME`], a consumed
5//! context's name (`a.b` → `A_B`), an agent's class name (`OrderEntity` →
6//! `ORDER_ENTITY`) and a derived capability's (`Billing` →
7//! `SERVICE_BILLING`). Two of them can meet: an agent `Kv` in a context that
8//! consumes `bynk.cloudflare { Kv }` is `KV` twice, and an agent
9//! `ServiceBilling` and a `capability Billing = Service` are both
10//! `SERVICE_BILLING`. Wrangler takes such a
11//! config without complaint and one binding hides the other, so the clash is
12//! a compile error. The names themselves are never adjusted to avoid it,
13//! because deployed Workers depend on them.
14//!
15//! The names are the emitter's (`bynk_emit::emitter::wrangler::
16//! worker_bindings`, the list `wrangler.toml` is written from); this module
17//! owns the check over them and the diagnostic.
18
19use std::collections::{BTreeMap, BTreeSet, HashMap};
20use std::path::PathBuf;
21
22use bynk_project::ParsedFile;
23use bynk_syntax::ast::{CommonsItem, ServiceProtocol, SourceUnit};
24use bynk_syntax::error::CompileError;
25use bynk_syntax::span::Span;
26
27use crate::firstparty;
28use crate::project_model::ErrorSink;
29
30/// A declaration's name in screaming snake case (`OrderEntity` →
31/// `ORDER_ENTITY`): the casing of an agent's binding and of a derived
32/// capability's. One function, so the two kinds of name the duplicate check
33/// compares cannot drift apart (review of #1968).
34pub fn screaming_snake(name: &str) -> String {
35    let mut out = String::new();
36    for (i, ch) in name.chars().enumerate() {
37        if i > 0 && ch.is_uppercase() {
38            out.push('_');
39        }
40        out.push(ch.to_ascii_uppercase());
41    }
42    out
43}
44
45/// S4a (#1966): the Worker binding name of a derived capability, the kind's
46/// prefix then the capability name in [`screaming_snake`] case (`Sessions` →
47/// `KV_SESSIONS`, `PriceCache` → `KV_PRICE_CACHE`).
48pub fn instance_binding_name(prefix: &str, capability: &str) -> String {
49    format!("{prefix}_{}", screaming_snake(capability))
50}
51
52/// What put a binding into a Worker's `wrangler.toml`: the source a
53/// `bynk.context.duplicate_binding` diagnostic names.
54///
55/// Each variant's doc also says whether a handler's `deps.env` type exposes
56/// it on Workers (#1950, `bynk_emit::emitter::bindings::handler_bindings`).
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum BindingSource {
59    /// A `[[services]]` Service Binding to another context's Worker: a
60    /// consumed context whose services the context calls (#1961 — consuming
61    /// one for its types or events alone binds nothing), or one subscribing to
62    /// an event it publishes. Handlers see a called context's binding; never a
63    /// subscriber's, which only the events fan-out calls.
64    Service { context: String },
65    /// The `[[kv_namespaces]]` binding the cloudflare adapter's `Kv` reads.
66    /// Never seen by handlers: they reach KV through the `WorkersKv` provider,
67    /// which takes the Worker's `env` at compose time.
68    Kv,
69    /// S4a (#1966): the `[[kv_namespaces]]` binding of a derived capability
70    /// (`capability Sessions = Kv`), one per instance. Never seen by handlers:
71    /// they reach it through the instance's `WorkersKv`.
72    KvInstance { capability: String },
73    /// Interop I5 (#1972): the `[[services]]` binding of a `Service`
74    /// instance (`capability Billing = Service @worker("legacy-billing")`), a
75    /// Service Binding to a Worker outside the project. Never seen by
76    /// handlers: they reach it through the instance's `WorkersService`.
77    ForeignService { capability: String, worker: String },
78    /// P5 (#2323): the `[[r2_buckets]]` binding of an `R2` instance
79    /// (`capability Archives = R2`), one bucket per instance, pinned to
80    /// `jurisdiction` when it names one. Never seen by handlers: they reach
81    /// it through the instance's `WorkersR2`.
82    R2Instance {
83        capability: String,
84        jurisdiction: Option<String>,
85    },
86    /// Standard-library P3 (#2342): the `[[ratelimits]]` binding of a
87    /// `RateLimit` instance (`capability LoginLimit = RateLimit @limit(100)
88    /// @period(60.seconds)`), allowing `limit` calls per key every `period`
89    /// seconds. Never seen by handlers: they reach it through the instance's
90    /// `WorkersRateLimit`.
91    RateLimitInstance {
92        capability: String,
93        limit: i64,
94        period: i64,
95    },
96    /// Standard-library P2 (#2578): the `[[queues.producers]]` binding of a
97    /// `Queue` instance (`capability OrderEvents = Queue @name("order-events")`),
98    /// sending to `queue` as written (`bynk deploy` environment-qualifies it).
99    /// Never seen by handlers: they reach it through the instance's
100    /// `WorkersQueue`.
101    QueueProducer { capability: String, queue: String },
102    /// Standard-library P3b (#2582): the `[[analytics_engine_datasets]]`
103    /// binding of an `Analytics` instance (`capability Signups = Analytics`),
104    /// one dataset per instance under a derived name. Never seen by handlers:
105    /// they reach it through the instance's `WorkersAnalytics`.
106    AnalyticsDataset { capability: String },
107    /// Standard-library P4a (#2602): the `[[d1_databases]]` binding of a `D1`
108    /// instance (`capability Orders = D1`), one database per instance under a
109    /// derived name, its id minted by `bynk deploy`. Never seen by handlers:
110    /// they reach it through the instance's `WorkersD1`.
111    D1Database { capability: String },
112    /// #3301: the `[[secrets_store_secrets]]` binding of a `StoredSecret`
113    /// instance (`capability StripeKey = StoredSecret @store("payments")
114    /// @secret("stripe-live")`), reading `secret` of the Secrets Store named
115    /// `store`. The store is linked by `bynk deploy`, which resolves its id,
116    /// and never created. Never seen by handlers: they reach it through the
117    /// instance's `WorkersStoredSecret`.
118    StoredSecret {
119        capability: String,
120        store: String,
121        secret: String,
122    },
123    /// #3302: the `[[send_email]]` binding of an `Email` instance
124    /// (`capability Mail = Email @allowedSenders([…])`), with the restrictions
125    /// its annotations carry. Never seen by handlers: they reach it through
126    /// the instance's `WorkersEmail`.
127    Email {
128        capability: String,
129        to: Option<String>,
130        allowed_recipients: Vec<String>,
131        allowed_senders: Vec<String>,
132    },
133    /// Hyperdrive H1 (#3318): the `[[hyperdrive]]` binding of a `Postgres`
134    /// instance (`capability Main = Postgres`). Its `id` is a placeholder until
135    /// the Hyperdrive configuration exists (created by hand until H2). Never
136    /// seen by handlers: they reach it through the instance's `WorkersPostgres`.
137    Postgres { capability: String },
138    /// Hyperdrive H5 (#3322): the `[[hyperdrive]]` binding of a `MySql`
139    /// instance (`capability Legacy = MySql`), the same stanza as `Postgres`'s.
140    /// `tls` is its `@tls("…")` when it carries one. Never seen by handlers:
141    /// they reach it through the instance's `WorkersMySql`.
142    MySql {
143        capability: String,
144        tls: Option<String>,
145    },
146    /// #3479: the `[[vectorize]]` binding of a `Vectorize` instance
147    /// (`capability Docs = Vectorize @dimensions(768) @metric("cosine")`), one
148    /// index per instance under a derived name that `bynk deploy`
149    /// environment-qualifies and creates with `dimensions` and `metric`, which
150    /// Cloudflare cannot change afterwards. `indexed` is each `@indexed`
151    /// entry as written (`name:type`). Never seen by handlers: they reach it
152    /// through the instance's `WorkersVectorize`.
153    VectorizeIndex {
154        capability: String,
155        dimensions: i64,
156        metric: String,
157        indexed: Vec<String>,
158    },
159    /// #3477: the Durable Object namespace of a `Container` instance
160    /// (`capability Renderer = Container @build("…") @port(8080)`): a
161    /// `[[durable_objects.bindings]]` entry for the generated class
162    /// `class_name` (`__Container_Renderer`), its `exports` entry, and a
163    /// `[[containers]]` entry whose image is built from `build`, the
164    /// project-relative directory of its `Dockerfile`. `sleep_after`
165    /// (seconds), `instance_type` and `forward` are applied when the class
166    /// starts the container, not in config. Never seen by handlers: they reach
167    /// it through the instance's `WorkersContainer`.
168    ContainerInstance {
169        capability: String,
170        class_name: String,
171        build: String,
172        // The path from the Worker's output directory (`<out>/workers/<worker>`)
173        // back to the project root (`../../..` for the default `out`), which
174        // the driver fills in from `[build] out`; empty until then.
175        root_from_worker: String,
176        port: i64,
177        sleep_after: Option<i64>,
178        instance_type: Option<String>,
179        forward: Vec<String>,
180    },
181    /// #3480: the `[[ai_search]]` binding of an `AiSearch` instance
182    /// (`capability Kb = AiSearch @instance("support-docs")`), naming the
183    /// account's instance `instance` as written, in every environment. The
184    /// instance is linked by `bynk deploy`, which checks it exists, and never
185    /// created. Never seen by handlers: they reach it through the instance's
186    /// `WorkersAiSearch`.
187    AiSearchInstance {
188        capability: String,
189        instance: String,
190    },
191    /// #3513 A: the `[[mtls_certificates]]` binding of an `MtlsCertificate`
192    /// instance (`capability Backend = MtlsCertificate @certificate("acme-client")`),
193    /// naming the account's client certificate `certificate` as written, in every
194    /// environment. The certificate is linked by `bynk deploy`, which resolves its id and
195    /// never uploads it. Never seen by handlers: they reach it through the instance's
196    /// `WorkersMtls`.
197    MtlsCertificate {
198        capability: String,
199        certificate: String,
200    },
201    /// #3300: the binding of a one-per-Worker capability of `bynk.cloudflare`
202    /// (`Version`'s `[version_metadata]`), declared when the Worker's
203    /// closure reaches the bare capability. Never seen by handlers: they
204    /// reach it through the capability's provider (`WorkersVersion`), which
205    /// takes the Worker's `env` at compose time.
206    Singleton { capability: String },
207    /// A `[[durable_objects.bindings]]` entry for one of the context's agents.
208    /// A handler that constructs an agent sees every local agent's binding.
209    Agent { class_name: String },
210    /// The `[[durable_objects.bindings]]` entry for the events fan-out class
211    /// of a context whose handlers emit. Never seen by handlers: they reach it
212    /// through `deps.__eventsDispatch`.
213    EventsFanout { class_name: String },
214}
215
216/// W30 (#2840): the `capability` of the `D1Database` source of a Worker's
217/// implicit idempotency database. Not an identifier, so no project's own derived
218/// `D1` capability can carry it: whether a binding is the implicit one is
219/// decided by its source, never by its name (a project's `capability
220/// Idempotency = D1` is bound as `D1_IDEMPOTENCY` too).
221pub const IMPLICIT_IDEMPOTENCY_CAPABILITY: &str = "@idempotency";
222
223/// W30 (#2840): the binding of a Worker's implicit idempotency database, named
224/// [`IDEMPOTENCY_BINDING`](crate::d1_migrations::IDEMPOTENCY_BINDING).
225pub fn idempotency_binding() -> WorkerBinding {
226    WorkerBinding {
227        name: crate::d1_migrations::IDEMPOTENCY_BINDING.to_string(),
228        source: BindingSource::D1Database {
229            capability: IMPLICIT_IDEMPOTENCY_CAPABILITY.to_string(),
230        },
231    }
232}
233
234impl BindingSource {
235    /// The source in a diagnostic's words.
236    pub fn describe(&self) -> String {
237        match self {
238            Self::Service { context } => format!("the Service Binding to context `{context}`"),
239            Self::Kv => format!(
240                "the KV namespace binding of `{}`'s `Kv`",
241                firstparty::CLOUDFLARE_UNIT
242            ),
243            Self::KvInstance { capability } => {
244                format!("the KV namespace binding of derived capability `{capability}`")
245            }
246            Self::ForeignService { capability, worker } => format!(
247                "the Service Binding of derived capability `{capability}` (to Worker `{worker}`)"
248            ),
249            Self::R2Instance { capability, .. } => {
250                format!("the R2 bucket binding of derived capability `{capability}`")
251            }
252            Self::RateLimitInstance { capability, .. } => {
253                format!("the rate limiting binding of derived capability `{capability}`")
254            }
255            Self::QueueProducer { capability, queue } => format!(
256                "the queue producer binding of derived capability `{capability}` (to queue `{queue}`)"
257            ),
258            Self::AnalyticsDataset { capability } => {
259                format!("the Analytics Engine binding of derived capability `{capability}`")
260            }
261            Self::D1Database { capability } if capability == IMPLICIT_IDEMPOTENCY_CAPABILITY => {
262                "the implicit idempotency database of a Worker that calls `Idempotency.claim`"
263                    .to_string()
264            }
265            Self::D1Database { capability } => {
266                format!("the D1 database binding of derived capability `{capability}`")
267            }
268            Self::StoredSecret {
269                capability, store, ..
270            } => format!(
271                "the Secrets Store binding of derived capability `{capability}` (to store `{store}`)"
272            ),
273            Self::Email { capability, .. } => {
274                format!("the `[[send_email]]` binding of derived capability `{capability}`")
275            }
276            Self::VectorizeIndex { capability, .. } => {
277                format!("the `[[vectorize]]` binding of derived capability `{capability}`")
278            }
279            Self::ContainerInstance { capability, .. } => {
280                format!(
281                    "the Durable Object binding of the container of derived capability `{capability}`"
282                )
283            }
284            Self::AiSearchInstance {
285                capability,
286                instance,
287            } => format!(
288                "the `[[ai_search]]` binding of derived capability `{capability}` (to instance `{instance}`)"
289            ),
290            Self::MtlsCertificate {
291                capability,
292                certificate,
293            } => format!(
294                "the `[[mtls_certificates]]` binding of derived capability `{capability}` (to certificate `{certificate}`)"
295            ),
296            Self::Postgres { capability } | Self::MySql { capability, .. } => {
297                format!("the `[[hyperdrive]]` binding of derived capability `{capability}`")
298            }
299            Self::Singleton { capability } => format!(
300                "the `{capability}` binding of `{}`",
301                firstparty::CLOUDFLARE_UNIT
302            ),
303            Self::Agent { class_name } => {
304                format!("the Durable Object binding of agent `{class_name}`")
305            }
306            Self::EventsFanout { .. } => {
307                "the Durable Object binding of the events fan-out".to_string()
308            }
309        }
310    }
311}
312
313/// One binding a Worker declares: the name its `env` field and its
314/// `wrangler.toml` entry share, and where that name came from.
315#[derive(Debug, Clone, PartialEq, Eq)]
316pub struct WorkerBinding {
317    pub name: String,
318    pub source: BindingSource,
319}
320
321/// The bindings in `bindings` whose name an earlier one already took, each
322/// paired with that earlier one, in list order.
323pub fn duplicate_bindings(bindings: &[WorkerBinding]) -> Vec<(&WorkerBinding, &WorkerBinding)> {
324    let mut first: HashMap<&str, &WorkerBinding> = HashMap::new();
325    let mut duplicates = Vec::new();
326    for binding in bindings {
327        match first.get(binding.name.as_str()) {
328            Some(earlier) => duplicates.push((*earlier, binding)),
329            None => {
330                first.insert(&binding.name, binding);
331            }
332        }
333    }
334    duplicates
335}
336
337/// `bynk.context.duplicate_binding`: each context's Worker declares every
338/// binding name once. `bindings` holds each context's bindings as its
339/// `wrangler.toml` would list them. One error per clash, at the declaration
340/// that brought in the second binding (an agent, or a `consumes` clause),
341/// preferring one the author wrote over `consumes bynk.cloudflare`, naming
342/// both sources. A clash between two sources with no declaration of their own
343/// (Service Bindings added for event subscribers) is reported at the
344/// context's name.
345pub fn phase_duplicate_bindings(
346    parsed: &[ParsedFile],
347    groups: &BTreeMap<String, Vec<usize>>,
348    bindings: &BTreeMap<String, Vec<WorkerBinding>>,
349    errors: &mut ErrorSink,
350) {
351    for (ctx, ctx_bindings) in bindings {
352        let indices = groups.get(ctx).map(Vec::as_slice).unwrap_or_default();
353        for (earlier, later) in duplicate_bindings(ctx_bindings) {
354            // At the declaration the author can change: the later source's,
355            // else the earlier's, but never the `bynk.cloudflare` clause
356            // while the other source has a declaration of its own.
357            let mut sources = [later, earlier];
358            sources.sort_by_key(|b| {
359                matches!(
360                    b.source,
361                    BindingSource::Kv | BindingSource::Singleton { .. }
362                )
363            });
364            let (file, span) = sources
365                .iter()
366                .find_map(|b| declared_at(parsed, indices, b))
367                .or_else(|| context_header(parsed, indices))
368                .map_or((None, Span::default()), |(file, span)| (Some(file), span));
369            errors.push_for(
370                file.as_deref(),
371                CompileError::new(
372                    "bynk.context.duplicate_binding",
373                    span,
374                    format!(
375                        "the Worker for `{ctx}` would declare two bindings named `{}`: {} and {}",
376                        later.name,
377                        earlier.source.describe(),
378                        later.source.describe(),
379                    ),
380                )
381                .with_note(
382                    "a Worker's bindings share one `env`, so each name must be unique; binding names follow agent, context and derived capability names, so rename the declaration behind one of them",
383                ),
384            );
385        }
386    }
387}
388
389/// Whether two identical declarations of `source` in different members of a
390/// group are one shared binding. A resource is identified by its declaration
391/// (a capability and its options), so identical ones share. An agent is not: its
392/// binding holds only the class's name, but its class is the code of the context
393/// that declares it, so two members' agents of one name are two classes.
394fn shareable(source: &BindingSource) -> bool {
395    !matches!(source, BindingSource::Agent { .. })
396}
397
398/// `bynk.deploy.binding_collision` (#3562): the members of a Worker group share
399/// one `wrangler.toml` and one `env`, so a binding name two members both
400/// declare is one binding when their declarations are identical (the same kind
401/// and options, so the point of co-location is shared state) and an error when
402/// they differ. `bindings` holds each context's bindings
403/// ([`phase_duplicate_bindings`] reports a name one context repeats). One error
404/// per clash, at the later member's declaration, naming both members and both
405/// sources.
406pub fn phase_group_binding_collisions(
407    worker_groups: &bynk_project::worker_groups::WorkerGroups,
408    parsed: &[ParsedFile],
409    groups: &BTreeMap<String, Vec<usize>>,
410    bindings: &BTreeMap<String, Vec<WorkerBinding>>,
411    errors: &mut ErrorSink,
412) {
413    worker_cycles(worker_groups, parsed, groups, bindings, errors);
414    for (key, group) in worker_groups {
415        group_service_names(key, &group.contexts, parsed, groups, errors);
416        group_websockets(key, &group.contexts, parsed, groups, errors);
417        crate::group_triggers::group_trigger_conflicts(
418            key,
419            &group.contexts,
420            parsed,
421            groups,
422            errors,
423        );
424        let mut first: HashMap<&str, (&str, &WorkerBinding)> = HashMap::new();
425        for ctx in &group.contexts {
426            let indices = groups.get(ctx).map(Vec::as_slice).unwrap_or_default();
427            for binding in bindings.get(ctx).into_iter().flatten() {
428                let Some(&(earlier_ctx, earlier)) = first.get(binding.name.as_str()) else {
429                    first.insert(&binding.name, (ctx, binding));
430                    continue;
431                };
432                if earlier_ctx == ctx
433                    || (shareable(&binding.source) && earlier.source == binding.source)
434                {
435                    continue;
436                }
437                let (file, span) = declared_at(parsed, indices, binding)
438                    .or_else(|| context_header(parsed, indices))
439                    .map_or((None, Span::default()), |(file, span)| (Some(file), span));
440                errors.push_for(
441                    file.as_deref(),
442                    CompileError::new(
443                        "bynk.deploy.binding_collision",
444                        span,
445                        format!(
446                            "contexts `{earlier_ctx}` and `{ctx}` share Worker `{key}`, which would declare two different bindings named `{}`: {} (from `{earlier_ctx}`) and {} (from `{ctx}`)",
447                            binding.name,
448                            earlier.source.describe(),
449                            binding.source.describe(),
450                        ),
451                    )
452                    .with_note(if shareable(&binding.source) {
453                        "members of one Worker share its bindings: give both contexts the same declaration so they share one binding, or rename one capability"
454                    } else {
455                        "a Durable Object class belongs to the context that declares it, whatever its name, so two members cannot each declare one with the same name: rename one of the agents"
456                    }),
457                );
458            }
459        }
460    }
461}
462
463/// `bynk.deploy.service_name_conflict` (#3562): a service is reached by its name
464/// (`/_bynk/call/<service>` carries no context), and a Worker answers every
465/// member's services, so two members of one group cannot each declare a service
466/// of one name. One error per repeat, at the later member's service.
467fn group_service_names(
468    key: &str,
469    members: &[String],
470    parsed: &[ParsedFile],
471    groups: &BTreeMap<String, Vec<usize>>,
472    errors: &mut ErrorSink,
473) {
474    let mut first: HashMap<String, &str> = HashMap::new();
475    for ctx in members {
476        let indices = groups.get(ctx).map(Vec::as_slice).unwrap_or_default();
477        for &i in indices {
478            let SourceUnit::Context(c) = parsed[i].unit() else {
479                continue;
480            };
481            for item in &c.items {
482                let CommonsItem::Service(service) = item else {
483                    continue;
484                };
485                let name = &service.name.name;
486                match first.get(name.as_str()) {
487                    None => {
488                        first.insert(name.clone(), ctx);
489                    }
490                    Some(earlier) if *earlier != ctx.as_str() => {
491                        errors.push_for(
492                            Some(&parsed[i].identity_path()),
493                            CompileError::new(
494                                "bynk.deploy.service_name_conflict",
495                                service.name.span,
496                                format!(
497                                    "contexts `{earlier}` and `{ctx}` share Worker `{key}`, and both declare a service named `{name}`"
498                                ),
499                            )
500                            .with_note(
501                                "a Worker answers its members' services by name, so each service name must be unique within a group: rename one of the services, or put the contexts in different groups",
502                            ),
503                        );
504                    }
505                    Some(_) => {}
506                }
507            }
508        }
509    }
510}
511
512/// `bynk.deploy.worker_cycle` (#3562): a Worker must be uploaded after the Workers
513/// it binds to (ADR 0193 D1), and the language rules out a cycle among *contexts*
514/// (`bynk.context.consumes_cycle`), but a group folds its members into one node,
515/// so two groups, or a group and a single context, can depend on each other with
516/// no cycle among their contexts (`A1 -> B1` and `B2 -> A2`, with `A1`, `A2` in one
517/// group and `B1`, `B2` in another). The graph is the Service Bindings the Workers
518/// would declare, read from `bindings` like deploy's ordering: a call, or the
519/// publisher-to-subscriber binding the events fan-out needs. A context stands for
520/// its group's Worker, and an edge inside a group is a Worker binding to itself
521/// and is no edge.
522///
523/// One error per strongly connected set of Workers **containing a group**, showing
524/// one representative cycle: the Workers and one context edge per hop, at the first
525/// hop's consumer. A cycle among Workers of contexts in no group is deliberately
526/// not reported: a subscriber that also calls its publisher closes one through the
527/// fan-out's binding, which `bynk dev` and the tests run, and `bynk deploy` refuses
528/// before uploading anything (Cloudflare rejects an upload whose binding target
529/// does not exist yet, code 10143). `bynk.context.consumes_cycle` owns a cycle
530/// among contexts' `consumes`: the bindings this reads are built only for a
531/// project with no error, so that cycle is reported first and this one once it is
532/// fixed, and a cycle is never reported twice.
533fn worker_cycles(
534    worker_groups: &bynk_project::worker_groups::WorkerGroups,
535    parsed: &[ParsedFile],
536    groups: &BTreeMap<String, Vec<usize>>,
537    bindings: &BTreeMap<String, Vec<WorkerBinding>>,
538    errors: &mut ErrorSink,
539) {
540    // A context's Worker: its group's key, else the context's own name.
541    let worker_of = |ctx: &str| -> String {
542        worker_groups
543            .iter()
544            .find(|(_, g)| g.contexts.iter().any(|c| c == ctx))
545            .map_or_else(|| ctx.to_string(), |(key, _)| key.clone())
546    };
547    // Worker -> (target Worker -> (consumer context, target context)), the first
548    // context edge that makes each Worker edge.
549    let mut edges: BTreeMap<String, BTreeMap<String, (String, String)>> = BTreeMap::new();
550    for (ctx, list) in bindings {
551        for binding in list {
552            let BindingSource::Service { context: target } = &binding.source else {
553                continue;
554            };
555            let (from, to) = (worker_of(ctx), worker_of(target));
556            if from != to {
557                edges
558                    .entry(from)
559                    .or_default()
560                    .entry(to)
561                    .or_insert_with(|| (ctx.clone(), target.clone()));
562            }
563        }
564    }
565    for scc in strongly_connected(&edges) {
566        if !scc.iter().any(|w| worker_groups.contains_key(w)) {
567            continue;
568        }
569        let Some(path) = cycle_through(&edges, &scc) else {
570            continue;
571        };
572        let hops: Vec<String> = path
573            .windows(2)
574            .map(|pair| {
575                let (consumer, target) = &edges[&pair[0]][&pair[1]];
576                format!(
577                    "`{}` to `{}` (`{consumer}` binds to `{target}`)",
578                    pair[0], pair[1]
579                )
580            })
581            .collect();
582        let (consumer, _) = &edges[&path[0]][&path[1]];
583        let indices = groups.get(consumer).map(Vec::as_slice).unwrap_or_default();
584        let (file, span) = context_header(parsed, indices)
585            .map_or((None, Span::default()), |(file, span)| (Some(file), span));
586        errors.push_for(
587            file.as_deref(),
588            CompileError::new(
589                "bynk.deploy.worker_cycle",
590                span,
591                format!(
592                    "the Workers {} bind to each other in a cycle: {}",
593                    path[..path.len() - 1]
594                        .iter()
595                        .map(|w| format!("`{w}`"))
596                        .collect::<Vec<_>>()
597                        .join(", "),
598                    hops.join(", ")
599                ),
600            )
601            .with_note(
602                "a Worker is uploaded after the Workers it binds to, so a cycle between Workers cannot be deployed. A group folds its members into one Worker: move a context out of its group, or into the other, so the Workers' dependencies run one way. (A publisher's Worker also binds to its subscribers, so a subscriber that calls its publisher closes a cycle too)",
603            ),
604        );
605    }
606}
607
608/// The strongly connected components of a graph with more than one node, each
609/// sorted, in order of their first node (Tarjan's algorithm, so the report is
610/// deterministic).
611fn strongly_connected(
612    edges: &BTreeMap<String, BTreeMap<String, (String, String)>>,
613) -> Vec<Vec<String>> {
614    struct State<'a> {
615        edges: &'a BTreeMap<String, BTreeMap<String, (String, String)>>,
616        index: BTreeMap<String, usize>,
617        low: BTreeMap<String, usize>,
618        on_stack: BTreeSet<String>,
619        stack: Vec<String>,
620        out: Vec<Vec<String>>,
621    }
622    fn visit(state: &mut State<'_>, node: &str) {
623        let n = state.index.len();
624        state.index.insert(node.to_string(), n);
625        state.low.insert(node.to_string(), n);
626        state.stack.push(node.to_string());
627        state.on_stack.insert(node.to_string());
628        let next: Vec<String> = state
629            .edges
630            .get(node)
631            .map(|m| m.keys().cloned().collect())
632            .unwrap_or_default();
633        for to in next {
634            if !state.index.contains_key(&to) {
635                visit(state, &to);
636                let low = state.low[node].min(state.low[&to]);
637                state.low.insert(node.to_string(), low);
638            } else if state.on_stack.contains(&to) {
639                let low = state.low[node].min(state.index[&to]);
640                state.low.insert(node.to_string(), low);
641            }
642        }
643        if state.low[node] == state.index[node] {
644            let mut component = Vec::new();
645            while let Some(top) = state.stack.pop() {
646                state.on_stack.remove(&top);
647                let done = top == node;
648                component.push(top);
649                if done {
650                    break;
651                }
652            }
653            if component.len() > 1 {
654                component.sort();
655                state.out.push(component);
656            }
657        }
658    }
659    let mut state = State {
660        edges,
661        index: BTreeMap::new(),
662        low: BTreeMap::new(),
663        on_stack: BTreeSet::new(),
664        stack: Vec::new(),
665        out: Vec::new(),
666    };
667    let nodes: BTreeSet<&String> = edges
668        .keys()
669        .chain(edges.values().flat_map(|m| m.keys()))
670        .collect();
671    for node in nodes {
672        if !state.index.contains_key(node) {
673            visit(&mut state, node);
674        }
675    }
676    state.out.sort();
677    state.out
678}
679
680/// One cycle inside `scc`, as a path that starts and ends at the component's
681/// first Worker: depth-first over the component's edges in name order.
682fn cycle_through(
683    edges: &BTreeMap<String, BTreeMap<String, (String, String)>>,
684    scc: &[String],
685) -> Option<Vec<String>> {
686    fn walk(
687        edges: &BTreeMap<String, BTreeMap<String, (String, String)>>,
688        scc: &[String],
689        path: &mut Vec<String>,
690    ) -> bool {
691        let here = path.last().expect("a path has a node").clone();
692        for next in edges.get(&here).into_iter().flat_map(|m| m.keys()) {
693            if !scc.contains(next) {
694                continue;
695            }
696            if *next == path[0] {
697                path.push(next.clone());
698                return true;
699            }
700            if !path.contains(next) {
701                path.push(next.clone());
702                if walk(edges, scc, path) {
703                    return true;
704                }
705                path.pop();
706            }
707        }
708        false
709    }
710    let mut path = vec![scc.first()?.clone()];
711    walk(edges, scc, &mut path).then_some(path)
712}
713
714/// `bynk.deploy.multiple_websocket_members` (#3562): a WebSocket upgrade is an
715/// `Upgrade: websocket` request, which names no path or service the group could
716/// route it by. A group with one member that declares `from websocket` services
717/// passes every upgrade to that member, which is right; with two, the first
718/// would take the upgrades meant for the second. So a group has at most one such
719/// member. One error, at the second.
720fn group_websockets(
721    key: &str,
722    members: &[String],
723    parsed: &[ParsedFile],
724    groups: &BTreeMap<String, Vec<usize>>,
725    errors: &mut ErrorSink,
726) {
727    let declares_websocket = |ctx: &String| {
728        groups.get(ctx).into_iter().flatten().any(|&i| {
729            matches!(parsed[i].unit(), SourceUnit::Context(c) if c.items.iter().any(|item| {
730                matches!(item, CommonsItem::Service(s) if matches!(s.protocol, ServiceProtocol::WebSocket { .. }))
731            }))
732        })
733    };
734    let mut hosts = members.iter().filter(|c| declares_websocket(c));
735    let (Some(first), Some(second)) = (hosts.next(), hosts.next()) else {
736        return;
737    };
738    let indices = groups.get(second).map(Vec::as_slice).unwrap_or_default();
739    let (file, span) = context_header(parsed, indices)
740        .map_or((None, Span::default()), |(file, span)| (Some(file), span));
741    errors.push_for(
742        file.as_deref(),
743        CompileError::new(
744            "bynk.deploy.multiple_websocket_members",
745            span,
746            format!(
747                "contexts `{first}` and `{second}` share Worker `{key}`, and both declare a `from websocket` service"
748            ),
749        )
750        .with_note(
751            "a WebSocket upgrade carries no path or service name for a group to route it by, so a group has at most one member that accepts them: put the contexts in different groups, or give one of them its own Worker",
752        ),
753    );
754}
755
756/// Where the context declares the source of `binding`: an agent's name, or
757/// the `consumes` clause naming a context (or `bynk.cloudflare`, for the KV
758/// namespace). `None` for a source with no declaration of its own: the events
759/// fan-out, or a Service Binding added for an event subscriber.
760fn declared_at(
761    parsed: &[ParsedFile],
762    indices: &[usize],
763    binding: &WorkerBinding,
764) -> Option<(PathBuf, Span)> {
765    indices.iter().find_map(|&i| {
766        let SourceUnit::Context(c) = parsed[i].unit() else {
767            return None;
768        };
769        let consumed = |target: &str| {
770            c.consumes
771                .iter()
772                .find(|d| d.target.joined() == target)
773                .map(|d| d.span)
774        };
775        let span = match &binding.source {
776            BindingSource::Agent { class_name } => c.items.iter().find_map(|item| {
777                let CommonsItem::Agent(a) = item else {
778                    return None;
779                };
780                (a.name.name == *class_name).then_some(a.name.span)
781            }),
782            BindingSource::Service { context } => consumed(context),
783            BindingSource::Kv | BindingSource::Singleton { .. } => {
784                consumed(firstparty::CLOUDFLARE_UNIT)
785            }
786            BindingSource::KvInstance { capability }
787            | BindingSource::ForeignService { capability, .. }
788            | BindingSource::R2Instance { capability, .. }
789            | BindingSource::RateLimitInstance { capability, .. }
790            | BindingSource::QueueProducer { capability, .. }
791            | BindingSource::AnalyticsDataset { capability }
792            | BindingSource::StoredSecret { capability, .. }
793            | BindingSource::Email { capability, .. }
794            | BindingSource::Postgres { capability }
795            | BindingSource::MySql { capability, .. }
796            | BindingSource::VectorizeIndex { capability, .. }
797            | BindingSource::ContainerInstance { capability, .. }
798            | BindingSource::AiSearchInstance { capability, .. }
799            | BindingSource::MtlsCertificate { capability, .. }
800            | BindingSource::D1Database { capability } => c.items.iter().find_map(|item| {
801                let CommonsItem::Capability(d) = item else {
802                    return None;
803                };
804                (d.name.name == *capability && d.derived.is_some()).then_some(d.span)
805            }),
806            BindingSource::EventsFanout { .. } => None,
807        }?;
808        Some((parsed[i].identity_path(), span))
809    })
810}
811
812/// The context's name in its first file: where a clash between two sources
813/// with no declaration of their own is reported.
814fn context_header(parsed: &[ParsedFile], indices: &[usize]) -> Option<(PathBuf, Span)> {
815    indices.iter().find_map(|&i| {
816        let SourceUnit::Context(c) = parsed[i].unit() else {
817            return None;
818        };
819        Some((parsed[i].identity_path(), c.name.span))
820    })
821}
822
823#[cfg(test)]
824mod tests {
825    use super::*;
826
827    fn service(name: &str, context: &str) -> WorkerBinding {
828        WorkerBinding {
829            name: name.to_string(),
830            source: BindingSource::Service {
831                context: context.to_string(),
832            },
833        }
834    }
835
836    #[test]
837    fn distinct_names_do_not_clash() {
838        assert!(duplicate_bindings(&[service("A", "a"), service("B", "b")]).is_empty());
839    }
840
841    /// Three bindings on one name are two clashes, each against the first.
842    #[test]
843    fn every_repeat_is_reported_against_the_first() {
844        let bindings = [
845            service("A_B", "a.b"),
846            service("A_B", "a_b"),
847            service("A_B", "x"),
848        ];
849        let duplicates = duplicate_bindings(&bindings);
850        assert_eq!(duplicates.len(), 2);
851        assert!(
852            duplicates
853                .iter()
854                .all(|(earlier, _)| *earlier == &bindings[0])
855        );
856        assert_eq!(duplicates[1].1, &bindings[2]);
857    }
858
859    fn kv(name: &str, capability: &str) -> WorkerBinding {
860        WorkerBinding {
861            name: name.to_string(),
862            source: BindingSource::KvInstance {
863                capability: capability.to_string(),
864            },
865        }
866    }
867
868    fn r2(name: &str, jurisdiction: Option<&str>) -> WorkerBinding {
869        WorkerBinding {
870            name: name.to_string(),
871            source: BindingSource::R2Instance {
872                capability: "Archives".to_string(),
873                jurisdiction: jurisdiction.map(str::to_string),
874            },
875        }
876    }
877
878    fn collisions(
879        members: &[&str],
880        bindings: &[(&str, Vec<WorkerBinding>)],
881    ) -> Vec<(String, String)> {
882        let table = format!(
883            "[deploy.workers.core]\ncontexts = [{}]\n",
884            members
885                .iter()
886                .map(|m| format!("\"{m}\""))
887                .collect::<Vec<_>>()
888                .join(", ")
889        );
890        let root = std::path::Path::new("/project");
891        let overlay = HashMap::from([(root.join("bynk.toml"), table)]);
892        let worker_groups =
893            bynk_project::worker_groups::try_read_worker_groups_with(root, &overlay).unwrap();
894        let bindings: BTreeMap<String, Vec<WorkerBinding>> = bindings
895            .iter()
896            .map(|(ctx, b)| (ctx.to_string(), b.clone()))
897            .collect();
898        let mut errors = ErrorSink::new();
899        phase_group_binding_collisions(
900            &worker_groups,
901            &[],
902            &BTreeMap::new(),
903            &bindings,
904            &mut errors,
905        );
906        errors
907            .into_all()
908            .into_iter()
909            .map(|e| (e.error.category.to_string(), e.error.message))
910            .collect()
911    }
912
913    /// Identical declarations in two members are one binding.
914    #[test]
915    fn identical_declarations_share_one_binding() {
916        assert!(
917            collisions(
918                &["a.x", "a.y"],
919                &[
920                    ("a.x", vec![kv("KV_MAIN", "Main")]),
921                    ("a.y", vec![kv("KV_MAIN", "Main")]),
922                ],
923            )
924            .is_empty()
925        );
926    }
927
928    /// The same name with different options is a collision, naming both members.
929    #[test]
930    fn differing_declarations_collide() {
931        let found = collisions(
932            &["a.x", "a.y"],
933            &[
934                ("a.x", vec![r2("ARCHIVES", None)]),
935                ("a.y", vec![r2("ARCHIVES", Some("eu"))]),
936            ],
937        );
938        assert_eq!(found.len(), 1, "{found:?}");
939        assert_eq!(found[0].0, "bynk.deploy.binding_collision");
940        assert!(
941            found[0].1.contains("`a.x` and `a.y` share Worker `core`"),
942            "{}",
943            found[0].1
944        );
945    }
946
947    /// A name one member repeats is the existing per-context error, not this one;
948    /// a context outside the group is not checked against it.
949    #[test]
950    fn only_clashes_between_members_are_reported() {
951        assert!(
952            collisions(
953                &["a.x", "a.y"],
954                &[
955                    (
956                        "a.x",
957                        vec![r2("ARCHIVES", None), r2("ARCHIVES", Some("eu"))]
958                    ),
959                    ("a.z", vec![r2("ARCHIVES", Some("eu"))]),
960                ],
961            )
962            .is_empty()
963        );
964    }
965
966    fn agent(name: &str) -> WorkerBinding {
967        WorkerBinding {
968            name: format!("AGENT_{}", name.to_uppercase()),
969            source: BindingSource::Agent {
970                class_name: name.to_string(),
971            },
972        }
973    }
974
975    /// An agent binding holds only the class name, so equal bindings can be two
976    /// different classes: two members each declaring `Cart` collide, though
977    /// their bindings compare equal.
978    #[test]
979    fn same_named_agents_in_two_members_collide() {
980        let found = collisions(
981            &["a.x", "a.y"],
982            &[("a.x", vec![agent("Cart")]), ("a.y", vec![agent("Cart")])],
983        );
984        assert_eq!(found.len(), 1, "{found:?}");
985        assert_eq!(found[0].0, "bynk.deploy.binding_collision");
986        // Agents of different names do not.
987        assert!(
988            collisions(
989                &["a.x", "a.y"],
990                &[("a.x", vec![agent("Cart")]), ("a.y", vec![agent("Order")])],
991            )
992            .is_empty()
993        );
994    }
995}