bynk_check/queue_consumers.rs
1//! One consumer Worker per queue, across the whole project (#3644).
2//!
3//! Cloudflare Queues accept a single consumer Worker for each queue, so two
4//! contexts consuming one queue could never both deploy: the second
5//! `wrangler deploy` fails. `bynk.queue.duplicate_consumer` already refuses two
6//! handlers for a queue inside one context; this is the same rule across
7//! contexts, grouped or not (members of a `[deploy.workers]` group are one
8//! Worker, and also have one consumer for a queue, so a group needs no check of
9//! its own). Like `bynk.email.duplicate_address`, which it is modelled on, it
10//! reports only a claim by a *different* context, on the later one (contexts in
11//! name order, so the report does not depend on discovery order).
12//!
13//! It runs on every target, like the email check: `from queue` is a Cloudflare
14//! Queues binding, which has one consumer per queue wherever the project is
15//! built, and a project that names one queue from two contexts has no single
16//! consumer to deploy. That is deliberate, not a Workers-only rule.
17
18use std::collections::{BTreeMap, HashMap};
19
20use bynk_project::{ParsedFile, UnitKind};
21use bynk_syntax::ast::{CommonsItem, ServiceProtocol, SourceUnit};
22use bynk_syntax::error::CompileError;
23
24use crate::project_model::ErrorSink;
25
26/// Refuse a queue that two different contexts consume.
27pub fn phase_duplicate_queue_consumers(
28 parsed: &[ParsedFile],
29 groups: &BTreeMap<String, Vec<usize>>,
30 kinds: &BTreeMap<String, UnitKind>,
31 errors: &mut ErrorSink,
32) {
33 // queue name -> the first context to consume it.
34 let mut first: HashMap<&str, &str> = HashMap::new();
35 for (ctx_name, indices) in groups {
36 if kinds.get(ctx_name) != Some(&UnitKind::Context) {
37 continue;
38 }
39 let mut here = Vec::new();
40 for &i in indices {
41 let SourceUnit::Context(ctx) = parsed[i].unit() else {
42 continue;
43 };
44 for item in &ctx.items {
45 if let CommonsItem::Service(s) = item
46 && let ServiceProtocol::Queue { name } = &s.protocol
47 {
48 here.push((s.name.span, name.as_str(), i));
49 }
50 }
51 }
52 here.sort_by_key(|(span, _, _)| *span);
53 for (span, queue, i) in here {
54 match first.get(queue) {
55 Some(&other) if other != ctx_name.as_str() => errors.push_for(
56 Some(&parsed[i].identity_path()),
57 CompileError::new(
58 "bynk.queue.duplicate_consumer",
59 span,
60 format!(
61 "contexts `{other}` and `{ctx_name}` both consume queue `{queue}`"
62 ),
63 )
64 .with_note(
65 "Cloudflare allows one consumer Worker per queue, so the project could not deploy: move the queue to one context",
66 ),
67 ),
68 Some(_) => {}
69 None => {
70 first.insert(queue, ctx_name.as_str());
71 }
72 }
73 }
74 }
75}