bynk_check/group_triggers.rs
1//! What a Worker answers, when several contexts share it (#3562, G2b step 2c).
2//!
3//! A `[deploy.workers.<key>]` group is one Worker, with one `fetch`, one `queue`
4//! and one `email` entry, so each thing it is routed by must belong to one
5//! member. These are the rules a single context already keeps among its own
6//! services (`bynk.http.duplicate_route`), kept across the members of a group,
7//! with the same keys:
8//!
9//! - an HTTP route is its method and path.
10//!
11//! An email address and a queue are not checked here: a project already refuses
12//! two contexts claiming one address (`bynk.email.duplicate_address`) or
13//! consuming one queue (`bynk.queue.duplicate_consumer`), grouped or not.
14//!
15//! A cron expression is not one of these: two members may share it, and both
16//! their handlers run.
17//!
18//! One error per clash, at the later member's declaration, naming both members.
19
20use std::collections::{BTreeMap, HashMap};
21
22use bynk_project::ParsedFile;
23use bynk_syntax::ast::{CommonsItem, HandlerKind, HttpMethod, SourceUnit};
24use bynk_syntax::error::CompileError;
25
26use crate::project_model::ErrorSink;
27
28/// What one member claimed first, by key: the member, so a later member's
29/// clash can name it.
30#[derive(Default)]
31struct Claims<'a> {
32 routes: HashMap<(HttpMethod, String), &'a str>,
33}
34
35/// Check the members of one group for a route or queue two of them claim.
36pub fn group_trigger_conflicts(
37 key: &str,
38 members: &[String],
39 parsed: &[ParsedFile],
40 groups: &BTreeMap<String, Vec<usize>>,
41 errors: &mut ErrorSink,
42) {
43 let mut claims = Claims::default();
44 for ctx in members {
45 let indices = groups.get(ctx).map(Vec::as_slice).unwrap_or_default();
46 for &i in indices {
47 let SourceUnit::Context(c) = parsed[i].unit() else {
48 continue;
49 };
50 let path = parsed[i].identity_path();
51 let mut clash = |code: &'static str, span, what: String, earlier: &str, note: &str| {
52 errors.push_for(
53 Some(&path),
54 CompileError::new(
55 code,
56 span,
57 format!(
58 "contexts `{earlier}` and `{ctx}` share Worker `{key}`, and both {what}"
59 ),
60 )
61 .with_note(note.to_string()),
62 );
63 };
64 for item in &c.items {
65 let CommonsItem::Service(service) = item else {
66 continue;
67 };
68 for handler in &service.handlers {
69 let HandlerKind::Http { method, path } = &handler.kind else {
70 continue;
71 };
72 match claims.routes.get(&(*method, path.clone())) {
73 Some(&earlier) if earlier != ctx => clash(
74 "bynk.deploy.route_conflict",
75 handler.span,
76 format!("declare the route `{} {path}`", method.as_str()),
77 earlier,
78 "a Worker answers a route with one handler: change one route, or put the contexts in different groups",
79 ),
80 Some(_) => {}
81 None => {
82 claims.routes.insert((*method, path.clone()), ctx);
83 }
84 }
85 }
86 }
87 }
88 }
89}