Skip to main content

bynk_emit/emitter/
workers_group.rs

1//! A Worker group's `index.ts` (#3562, G2b step 2c-4b).
2//!
3//! A `[deploy.workers.<key>]` group is one Worker over several contexts. Each
4//! member's entry is emitted as `<member>.index.ts` in *member mode*
5//! (`workers_entry.rs`), which marks the router's own misses; the group's entry
6//! is the Worker's `main` and dispatches to the members:
7//!
8//! - `fetch` tries the members in the order the manifest lists them. A marked
9//!   response is a miss and the next member is tried; the first unmarked one is
10//!   the answer (a handler's own `404` included). If every member misses, the
11//!   answer is the first marked response that is not a `404` (the synthesised
12//!   `405`/`204`), with the `Allow` of all such responses merged, since two
13//!   members may serve one path under different methods; else the single-context
14//!   `Not Found`.
15//! - `scheduled` runs every member whose cron matches, `queue` goes to the member
16//!   consuming `batch.queue`, `email` to the member claiming the recipient.
17//! - Agent, events fan-out and container classes are re-exported by name (a
18//!   member entry exports `isMiss`, so `export *` over members would collide).
19//!
20//! A request to the internal `/_bynk/call`, `/_bynk/event`, `/_bynk/migrate` or
21//! (in a `bynk dev` build only) `/_bynk/inspect` prefix that no member claims is answered as a standalone Worker answers it
22//! unauthenticated: the same method gate, then the same `413` or `401` the
23//! runtime's `verifyCall` gives. Answering `404` for an unknown service while a
24//! known one answers `401` would let an unsigned caller list a group's services.
25
26use crate::ts_build::{
27    arrow_of, binary, block, call, const_typed, expr_stmt, ident, if_, index, member, method_call,
28    new, num_lit, paren, ret, str_lit,
29};
30use bynk_check::wire_format as wf;
31use bynk_ts::{
32    TsArrowBody, TsBinaryOp, TsDecl, TsExpr, TsLit, TsObjectEntry, TsParam, TsProgram, TsStmt,
33    TsSwitchCase, TsType, TsTypeMember, TsUnaryOp,
34};
35
36/// What the group's entry needs to know of one member.
37pub struct GroupMember {
38    /// The member's qualified context name.
39    pub context: String,
40    /// The import specifier of its `<member>.index.ts` (`./shop-orders.index.js`).
41    pub specifier: String,
42    /// Its cron expressions (its entry has `scheduled` iff there are any).
43    pub crons: Vec<String>,
44    /// The queues it consumes (its entry has `queue` iff there are any).
45    pub queues: Vec<String>,
46    /// The addresses its `from email` services claim (its entry has `email` iff
47    /// there are any).
48    pub addresses: Vec<String>,
49    /// The Durable Object classes its entry exports: its agents. (The events
50    /// fan-out is the group's, not a member's.)
51    pub classes: Vec<String>,
52}
53
54/// The group as a whole.
55pub struct GroupEntry<'a> {
56    pub key: &'a str,
57    pub members: &'a [GroupMember],
58    /// The container classes of `containers.ts`, exported once for the Worker.
59    pub container_classes: &'a [String],
60    /// Whether any member publishes events: the Worker exports the one events
61    /// fan-out class, from `events_fanout.ts` (#3562, G3-1).
62    pub has_fanout: bool,
63    /// Whether any member subscribes to events (answers `/_bynk/event/`).
64    pub has_events: bool,
65    /// Whether any member hosts a migratable agent (answers `/_bynk/migrate/`).
66    pub has_migrate: bool,
67    /// Whether this is a `bynk dev` build with agents to inspect (answers
68    /// `/_bynk/inspect/`). A deploy build has no such route, in the group or a
69    /// member, and the entry says nothing of it.
70    pub has_inspect: bool,
71}
72
73// The node builders of this file. Each is a one-line wrapper over a `bynk_ts`
74// constructor, so the entry below reads as the TypeScript it emits.
75
76/// `globalThis.<name>`.
77fn global(name: &str) -> TsExpr {
78    member(ident("globalThis"), name)
79}
80
81fn as_never(expr: TsExpr) -> TsExpr {
82    TsExpr::As {
83        expr: Box::new(expr),
84        ty: ty("never"),
85    }
86}
87
88/// `(p) => body`, an expression-bodied arrow over untyped parameters.
89fn lambda(params: &[&str], body: TsExpr) -> TsExpr {
90    arrow_of(
91        params.iter().map(|p| TsParam::new(*p, None)).collect(),
92        false,
93        TsArrowBody::Expr(Box::new(body)),
94    )
95}
96
97fn ty(name: &str) -> TsType {
98    TsType::named(name)
99}
100
101/// `Promise<T>`, as the handlers write it.
102fn promise(inner: TsType) -> TsType {
103    TsType::named_with_args("Promise", vec![inner])
104}
105
106fn response_ty() -> TsType {
107    ty("globalThis.Response")
108}
109
110/// `stmt`, with no blank line before it: this entry keeps its re-exports, its handler
111/// types and its member constants in tight runs, as it always wrote them.
112fn tight(mut stmt: TsStmt) -> TsStmt {
113    stmt.no_blank_before = true;
114    stmt
115}
116
117/// `if (cond) { body }` on one line: the braced form of the one-line guards
118/// this entry used to write without braces.
119fn guard(cond: TsExpr, body: TsStmt) -> TsStmt {
120    if_(cond, TsStmt::inline_block(vec![body], None))
121}
122
123/// `new globalThis.Response(body, init)`.
124fn new_response(body: TsExpr, init: TsExpr) -> TsExpr {
125    new(global("Response"), vec![body, init])
126}
127
128/// `{ status: <n> }`.
129fn status(n: u32) -> TsExpr {
130    TsExpr::object(vec![("status".to_string(), num_lit(n))])
131}
132
133fn function(
134    name: &str,
135    is_async: bool,
136    params: Vec<TsParam>,
137    return_type: TsType,
138    body: Vec<TsStmt>,
139) -> TsStmt {
140    TsStmt::decl(
141        TsDecl::Function {
142            name: name.to_string(),
143            generics: Vec::new(),
144            params,
145            return_type: Some(return_type),
146            body,
147            is_async,
148            inline: false,
149        },
150        None,
151    )
152}
153
154/// `["a", "b"]`, as a TypeScript array literal of strings.
155fn array(items: &[String]) -> TsExpr {
156    TsExpr::array(items.iter().map(str_lit).collect())
157}
158
159/// `await __verifyCall(request, env, "")`.
160fn verify_call() -> TsExpr {
161    TsExpr::Await(Box::new(call(
162        ident("__verifyCall"),
163        vec![ident("request"), ident("env"), str_lit("")],
164    )))
165}
166
167/// `if (request.method !== <method>) return new Response(<body>, { status: <n>,
168/// <headers> });`, the method gate every internal prefix starts with.
169fn method_gate(method: &str, body: TsExpr, status_code: u32, headers: Option<TsExpr>) -> TsStmt {
170    let mut init = vec![("status".to_string(), num_lit(status_code))];
171    if let Some(headers) = headers {
172        init.push(("headers".to_string(), headers));
173    }
174    guard(
175        binary(
176            TsBinaryOp::StrictNotEq,
177            member(ident("request"), "method"),
178            str_lit(method),
179        ),
180        ret(new_response(body, TsExpr::object(init))),
181    )
182}
183
184/// `if (path.startsWith(<prefix>)) { <body> }`.
185fn prefix_branch(prefix: &str, mut body: Vec<TsStmt>) -> TsStmt {
186    body.push(ret(call(ident("__refused"), vec![verify_call()])));
187    TsStmt::if_stmt(
188        method_call(ident("path"), "startsWith", vec![str_lit(prefix)]),
189        block(body),
190        None,
191    )
192}
193
194/// The unclaimed-request fallback: what a standalone Worker answers to an
195/// unauthenticated request for an internal prefix (see the module doc).
196fn unclaimed(entry: &GroupEntry<'_>) -> TsStmt {
197    let allow = |method: &str| TsExpr::object(vec![("allow".to_string(), str_lit(method))]);
198    let mut body = vec![const_typed(
199        "path",
200        None,
201        member(
202            new(global("URL"), vec![member(ident("request"), "url")]),
203            "pathname",
204        ),
205    )];
206    // Every Worker answers `/_bynk/call/`.
207    body.push(prefix_branch(
208        wf::CALL_PATH_PREFIX,
209        vec![method_gate(
210            wf::CALL_METHOD,
211            TsExpr::Lit(TsLit::Null),
212            405,
213            Some(allow(wf::CALL_METHOD)),
214        )],
215    ));
216    if entry.has_events {
217        body.push(guard(
218            method_call(ident("path"), "startsWith", vec![str_lit("/_bynk/event/")]),
219            ret(call(ident("__refused"), vec![verify_call()])),
220        ));
221    }
222    let caller_gate = |caller: &str, body: &str| {
223        guard(
224            binary(
225                TsBinaryOp::StrictNotEq,
226                method_call(
227                    member(ident("request"), "headers"),
228                    "get",
229                    vec![str_lit(wf::CALLER_HEADER)],
230                ),
231                str_lit(caller),
232            ),
233            ret(new_response(str_lit(body), status(401))),
234        )
235    };
236    if entry.has_migrate {
237        let key_missing = binary(
238            TsBinaryOp::StrictNotEq,
239            TsExpr::Unary {
240                op: TsUnaryOp::Typeof,
241                expr: Box::new(index(
242                    paren(TsExpr::As {
243                        expr: Box::new(TsExpr::As {
244                            expr: Box::new(ident("env")),
245                            ty: ty("unknown"),
246                        }),
247                        ty: TsType::named_with_args(
248                            "globalThis.Record",
249                            vec![ty("string"), ty("unknown")],
250                        ),
251                    }),
252                    str_lit(wf::MIGRATE_KEY),
253                )),
254            },
255            str_lit("string"),
256        );
257        body.push(prefix_branch(
258            wf::MIGRATE_PATH_PREFIX,
259            vec![
260                guard(
261                    key_missing,
262                    ret(new_response(str_lit("Not found"), status(404))),
263                ),
264                method_gate(
265                    wf::CALL_METHOD,
266                    TsExpr::Lit(TsLit::Null),
267                    405,
268                    Some(allow(wf::CALL_METHOD)),
269                ),
270                caller_gate(wf::MIGRATE_CALLER, "Unauthorized"),
271            ],
272        ));
273    }
274    if entry.has_inspect {
275        body.push(prefix_branch(
276            super::workers_entry::INSPECT_PREFIX,
277            vec![
278                method_gate("POST", str_lit("Method Not Allowed"), 405, None),
279                caller_gate("bynk.dev", "Unauthorized"),
280            ],
281        ));
282    }
283    body.push(ret(new_response(str_lit("Not Found"), status(404))));
284    function(
285        "__unclaimed",
286        true,
287        vec![
288            TsParam::new("request", Some(ty("globalThis.Request"))),
289            TsParam::new("env", Some(ty("unknown"))),
290        ],
291        promise(response_ty()),
292        body,
293    )
294}
295
296/// `fetch`: the members in order (see the module doc). Every marked response
297/// that is not a `404` is kept, so that if no member owns the request the answer
298/// lists the methods the whole Worker serves on the path, not one member's.
299fn fetch_method() -> TsObjectEntry {
300    TsObjectEntry::method(
301        "fetch",
302        true,
303        vec![
304            TsParam::new("request", Some(ty("globalThis.Request"))),
305            TsParam::new("env", Some(ty("unknown"))),
306            TsParam::new("ctx", Some(ty("__Ctx"))),
307        ],
308        Some(promise(response_ty())),
309        vec![ret(call(
310            ident("__fetch"),
311            vec![
312                ident("request"),
313                call(ident("__loopback"), vec![ident("env"), ident("ctx")]),
314                ident("ctx"),
315            ],
316        ))],
317    )
318}
319
320/// The dispatcher: members in manifest order, the first answer that is not a
321/// router's own miss wins. `env` already answers a call to a member in process
322/// ([`loopback`]).
323fn dispatch() -> TsStmt {
324    let held_empty = binary(
325        TsBinaryOp::StrictEq,
326        member(ident("held"), "length"),
327        num_lit(0),
328    );
329    let each_member = TsStmt::for_of(
330        "member",
331        ident("__members"),
332        block(vec![
333            const_typed(
334                "response",
335                None,
336                TsExpr::Await(Box::new(method_call(
337                    member(ident("member"), "entry"),
338                    "fetch",
339                    vec![ident("request"), as_never(ident("env")), ident("ctx")],
340                ))),
341            ),
342            guard(
343                TsExpr::Unary {
344                    op: TsUnaryOp::Not,
345                    expr: Box::new(method_call(
346                        ident("member"),
347                        "isMiss",
348                        vec![ident("response")],
349                    )),
350                },
351                ret(ident("response")),
352            ),
353            guard(
354                binary(
355                    TsBinaryOp::StrictNotEq,
356                    member(ident("response"), "status"),
357                    num_lit(404),
358                ),
359                expr_stmt(method_call(ident("held"), "push", vec![ident("response")])),
360            ),
361        ]),
362        None,
363    );
364    function(
365        "__fetch",
366        true,
367        vec![
368            TsParam::new("request", Some(ty("globalThis.Request"))),
369            TsParam::new("env", Some(ty("unknown"))),
370            TsParam::new("ctx", Some(ty("__Ctx"))),
371        ],
372        promise(response_ty()),
373        vec![
374            const_typed(
375                "held",
376                Some(TsType::array(response_ty())),
377                TsExpr::array(vec![]),
378            ),
379            each_member,
380            ret(TsExpr::Conditional {
381                test: Box::new(held_empty),
382                consequent: Box::new(TsExpr::Await(Box::new(call(
383                    ident("__unclaimed"),
384                    vec![ident("request"), ident("env")],
385                )))),
386                alternate: Box::new(call(ident("__withAllowed"), vec![ident("held")])),
387            }),
388        ],
389    )
390}
391
392/// A call from one member to another is a call from the Worker to itself, so it
393/// need not leave the Worker (#3562, G3-2): the binding a member names the other by
394/// answers in process, by running the request through the group's own dispatcher.
395/// It is the same request, signed, contract-checked, admitted and decoded as one
396/// over a Service Binding, so a value is copied across it, a callee's fault reaches
397/// the caller as the same `CalleeFaulted`, and a refusal is the same refusal; only
398/// the hop is gone. Anything the callee's `fetch` throws is the plain `500` a Service
399/// Binding would hand the caller (which maps it to `Transport`), never the callee's
400/// own exception. (The events fan-out's Durable Object runs elsewhere and keeps
401/// the Service Binding.)
402fn loopback(entry: &GroupEntry<'_>) -> Vec<TsStmt> {
403    if entry.members.len() < 2 {
404        return vec![function(
405            "__loopback",
406            false,
407            vec![
408                TsParam::new("env", Some(ty("unknown"))),
409                TsParam::new("_ctx", Some(ty("__Ctx"))),
410            ],
411            ty("unknown"),
412            vec![ret(ident("env"))],
413        )];
414    }
415    let names: Vec<String> = entry
416        .members
417        .iter()
418        .map(|m| crate::emitter::bindings::service_binding(&m.context).name)
419        .collect();
420    let record = || TsType::named_with_args("globalThis.Record", vec![ty("string"), ty("unknown")]);
421    let answers_in_process = arrow_of(
422        vec![TsParam::new("request", Some(ty("globalThis.Request")))],
423        true,
424        TsArrowBody::Multiline(vec![TsStmt::try_catch(
425            block(vec![ret(TsExpr::Await(Box::new(call(
426                ident("__fetch"),
427                vec![ident("request"), ident("inner"), ident("ctx")],
428            ))))]),
429            None::<String>,
430            block(vec![ret(new_response(
431                str_lit("Internal Server Error"),
432                status(500),
433            ))]),
434            None,
435        )]),
436    );
437    vec![
438        const_typed(
439            "__memberBindings",
440            Some(TsType::readonly_array(ty("string"))),
441            array(&names),
442        ),
443        function(
444            "__loopback",
445            false,
446            vec![
447                TsParam::new("env", Some(ty("unknown"))),
448                TsParam::new("ctx", Some(ty("__Ctx"))),
449            ],
450            ty("unknown"),
451            vec![
452                const_typed(
453                    "inner",
454                    Some(record()),
455                    TsExpr::object_entries(vec![TsObjectEntry::Spread(paren(TsExpr::As {
456                        expr: Box::new(ident("env")),
457                        ty: record(),
458                    }))]),
459                ),
460                TsStmt::for_of(
461                    "name",
462                    ident("__memberBindings"),
463                    block(vec![TsStmt::assign(
464                        index(ident("inner"), ident("name")),
465                        TsExpr::object(vec![("fetch".to_string(), answers_in_process)]),
466                        None,
467                    )]),
468                    None,
469                ),
470                ret(ident("inner")),
471            ],
472        ),
473    ]
474}
475
476/// `__refused`: a verification failure becomes the `401`, a response stays.
477fn refused() -> TsStmt {
478    function(
479        "__refused",
480        false,
481        vec![TsParam::new(
482            "verified",
483            Some(TsType::union(vec![ty("string"), response_ty()])),
484        )],
485        response_ty(),
486        vec![ret(TsExpr::Conditional {
487            test: Box::new(binary(
488                TsBinaryOp::StrictEq,
489                TsExpr::Unary {
490                    op: TsUnaryOp::Typeof,
491                    expr: Box::new(ident("verified")),
492                },
493                str_lit("string"),
494            )),
495            consequent: Box::new(new_response(str_lit("Unauthorized"), status(401))),
496            alternate: Box::new(ident("verified")),
497        })],
498    )
499}
500
501/// The first held `405`/`204`, answering with the union of every member's
502/// `Allow` (RFC 9110 §10.2.1: the methods the target resource supports).
503fn with_allowed() -> TsStmt {
504    let trimmed = method_call(
505        method_call(
506            paren(binary(
507                TsBinaryOp::NullishCoalescing,
508                method_call(member(ident("r"), "headers"), "get", vec![str_lit("allow")]),
509                str_lit(""),
510            )),
511            "split",
512            vec![str_lit(",")],
513        ),
514        "map",
515        vec![lambda(&["m"], method_call(ident("m"), "trim", vec![]))],
516    );
517    let methods = method_call(
518        ident("held"),
519        "flatMap",
520        vec![lambda(
521            &["r"],
522            method_call(
523                trimmed,
524                "filter",
525                vec![lambda(
526                    &["m"],
527                    binary(TsBinaryOp::StrictNotEq, ident("m"), str_lit("")),
528                )],
529            ),
530        )],
531    );
532    let unique_sorted = method_call(
533        method_call(
534            TsExpr::array(vec![TsExpr::Spread(Box::new(new(
535                global("Set"),
536                vec![ident("methods")],
537            )))]),
538            "sort",
539            vec![],
540        ),
541        "join",
542        vec![str_lit(", ")],
543    );
544    function(
545        "__withAllowed",
546        false,
547        vec![TsParam::new(
548            "held",
549            Some(TsType::readonly_array(response_ty())),
550        )],
551        response_ty(),
552        vec![
553            const_typed("first", None, index(ident("held"), num_lit(0))),
554            guard(
555                binary(
556                    TsBinaryOp::StrictEq,
557                    member(ident("held"), "length"),
558                    num_lit(1),
559                ),
560                ret(ident("first")),
561            ),
562            const_typed("methods", None, methods),
563            const_typed(
564                "merged",
565                None,
566                new_response(member(ident("first"), "body"), ident("first")),
567            ),
568            expr_stmt(method_call(
569                member(ident("merged"), "headers"),
570                "set",
571                vec![str_lit("allow"), unique_sorted],
572            )),
573            ret(ident("merged")),
574        ],
575    )
576}
577
578/// `{ readonly <name>: string }`.
579fn readonly_string(name: &str) -> TsType {
580    TsType::Object(vec![TsTypeMember::readonly_prop(name, ty("string"))])
581}
582
583/// `<m>.<handler>(<arg> as never, __loopback(env, ctx) as never, ctx)`: a member's
584/// handler, run on the loopback env.
585fn run_member(member_index: usize, handler: &str, arg: &str) -> TsExpr {
586    method_call(
587        ident(format!("__m{member_index}")),
588        handler,
589        vec![
590            as_never(ident(arg)),
591            as_never(call(ident("__loopback"), vec![ident("env"), ident("ctx")])),
592            ident("ctx"),
593        ],
594    )
595}
596
597/// `scheduled`: every member whose cron matches runs.
598fn scheduled(members: &[(usize, &GroupMember)]) -> TsObjectEntry {
599    let runs: Vec<TsExpr> = members
600        .iter()
601        .filter(|(_, m)| !m.crons.is_empty())
602        .map(|(i, m)| {
603            TsExpr::Spread(Box::new(paren(TsExpr::Conditional {
604                test: Box::new(method_call(
605                    array(&m.crons),
606                    "includes",
607                    vec![member(ident("event"), "cron")],
608                )),
609                consequent: Box::new(TsExpr::array(vec![run_member(*i, "scheduled", "event")])),
610                alternate: Box::new(TsExpr::array(vec![])),
611            })))
612        })
613        .collect();
614    TsObjectEntry::method(
615        "scheduled",
616        true,
617        vec![
618            TsParam::new("event", Some(readonly_string("cron"))),
619            TsParam::new("env", Some(ty("unknown"))),
620            TsParam::new("ctx", Some(ty("__Ctx"))),
621        ],
622        Some(promise(ty("void"))),
623        vec![expr_stmt(TsExpr::Await(Box::new(method_call(
624            global("Promise"),
625            "all",
626            vec![TsExpr::multiline_array(runs)],
627        ))))],
628    )
629}
630
631/// `queue`: the member consuming `batch.queue`.
632fn queue(members: &[(usize, &GroupMember)]) -> TsObjectEntry {
633    let mut cases: Vec<TsSwitchCase> = members
634        .iter()
635        .filter(|(_, m)| !m.queues.is_empty())
636        .map(|(i, m)| TsSwitchCase {
637            labels: m.queues.iter().map(str_lit).collect(),
638            body: vec![ret(run_member(*i, "queue", "batch"))],
639            default_braced: false,
640            case_braced: false,
641            span: None,
642        })
643        .collect();
644    cases.push(TsSwitchCase {
645        labels: Vec::new(),
646        body: vec![TsStmt::return_stmt(None, None)],
647        default_braced: false,
648        case_braced: true,
649        span: None,
650    });
651    TsObjectEntry::method(
652        "queue",
653        true,
654        vec![
655            TsParam::new("batch", Some(readonly_string("queue"))),
656            TsParam::new("env", Some(ty("unknown"))),
657            TsParam::new("ctx", Some(ty("__Ctx"))),
658        ],
659        Some(promise(ty("void"))),
660        vec![TsStmt::switch_stmt(
661            member(ident("batch"), "queue"),
662            cases,
663            None,
664        )],
665    )
666}
667
668/// `email`: the member claiming the recipient, by the runtime's own rule (an
669/// exact address, case-insensitively, before a `*@domain` catch-all). With no
670/// claimant the first email member gets it, and its runtime rejects an unknown
671/// recipient.
672fn email(members: &[(usize, &GroupMember)]) -> TsObjectEntry {
673    let routes: Vec<TsExpr> = members
674        .iter()
675        .filter(|(_, m)| !m.addresses.is_empty())
676        .flat_map(|(i, m)| {
677            m.addresses.iter().map(move |a| {
678                TsExpr::object(vec![
679                    ("address".to_string(), str_lit(a.to_lowercase())),
680                    ("member".to_string(), ident(format!("__m{i}"))),
681                ])
682            })
683        })
684        .collect();
685    let first = members
686        .iter()
687        .find(|(_, m)| !m.addresses.is_empty())
688        .map_or(0, |(i, _)| *i);
689    let routes_ty = TsType::readonly_array(TsType::Object(vec![
690        TsTypeMember::readonly_prop("address", ty("string")),
691        TsTypeMember::readonly_prop("member", ty("__Email")),
692    ]));
693    let by_address = |address: TsExpr| {
694        method_call(
695            ident("routes"),
696            "find",
697            vec![lambda(
698                &["r"],
699                binary(TsBinaryOp::StrictEq, member(ident("r"), "address"), address),
700            )],
701        )
702    };
703    let claimant = binary(
704        TsBinaryOp::NullishCoalescing,
705        by_address(ident("to")),
706        by_address(TsExpr::template_lit(
707            vec!["*@".to_string(), String::new()],
708            vec![ident("domain")],
709        )),
710    );
711    let claiming = paren(binary(
712        TsBinaryOp::NullishCoalescing,
713        TsExpr::OptionalMember {
714            object: Box::new(ident("claimant")),
715            property: "member".to_string(),
716        },
717        ident(format!("__m{first}")),
718    ));
719    TsObjectEntry::method(
720        "email",
721        true,
722        vec![
723            TsParam::new("message", Some(readonly_string("to"))),
724            TsParam::new("env", Some(ty("unknown"))),
725            TsParam::new("ctx", Some(ty("__Ctx"))),
726        ],
727        Some(promise(ty("void"))),
728        vec![
729            const_typed(
730                "to",
731                None,
732                method_call(member(ident("message"), "to"), "toLowerCase", vec![]),
733            ),
734            const_typed(
735                "domain",
736                None,
737                method_call(
738                    ident("to"),
739                    "slice",
740                    vec![binary(
741                        TsBinaryOp::Add,
742                        method_call(ident("to"), "lastIndexOf", vec![str_lit("@")]),
743                        num_lit(1),
744                    )],
745                ),
746            ),
747            const_typed("routes", Some(routes_ty), TsExpr::multiline_array(routes)),
748            const_typed("claimant", None, claimant),
749            expr_stmt(TsExpr::Await(Box::new(method_call(
750                claiming,
751                "email",
752                vec![
753                    as_never(ident("message")),
754                    as_never(call(ident("__loopback"), vec![ident("env"), ident("ctx")])),
755                    ident("ctx"),
756                ],
757            )))),
758        ],
759    )
760}
761
762/// `type <name> = { <method>(<arg>: never, env: never, ctx: __Ctx): Promise<<ret>> };`:
763/// the slice of a member's default export the group calls.
764fn handler_type(name: &str, method: &str, arg: &str, ret_ty: TsType) -> TsStmt {
765    tight(TsStmt::decl(
766        TsDecl::TypeAlias {
767            name: name.to_string(),
768            type_params: Vec::new(),
769            ty: TsType::Object(vec![TsTypeMember::method(
770                method,
771                vec![
772                    TsParam::new(arg, Some(ty("never"))),
773                    TsParam::new("env", Some(ty("never"))),
774                    TsParam::new("ctx", Some(ty("__Ctx"))),
775                ],
776                promise(ret_ty),
777            )]),
778        },
779        None,
780    ))
781}
782
783/// The member imports and the class re-exports.
784fn imports_and_exports(entry: &GroupEntry<'_>, members: &[(usize, &GroupMember)]) -> Vec<TsStmt> {
785    let mut stmts = Vec::new();
786    for (i, m) in members {
787        stmts.push(TsStmt::decl(
788            TsDecl::ImportDefault {
789                alias: format!("__entry{i}"),
790                named: vec![format!("isMiss as __miss{i}")],
791                from: m.specifier.clone(),
792            },
793            None,
794        ));
795    }
796    let re_export = |names: Vec<String>, from: &str| {
797        tight(TsStmt::decl(
798            TsDecl::ReExport {
799                names,
800                from: from.to_string(),
801            },
802            None,
803        ))
804    };
805    for (_, m) in members {
806        if !m.classes.is_empty() {
807            stmts.push(re_export(m.classes.clone(), &m.specifier));
808        }
809    }
810    if entry.has_fanout {
811        stmts.push(re_export(
812            vec![crate::emitter::wrangler::EVENTS_FANOUT_CLASS_NAME.to_string()],
813            "./events_fanout.js",
814        ));
815    }
816    if !entry.container_classes.is_empty() {
817        stmts.push(re_export(
818            entry.container_classes.to_vec(),
819            "./containers.js",
820        ));
821    }
822    stmts
823}
824
825/// The handler types, each member's typed view of its entry, and the member table.
826fn member_table(members: &[(usize, &GroupMember)]) -> Vec<TsStmt> {
827    let has = |f: &dyn Fn(&GroupMember) -> bool| members.iter().any(|(_, m)| f(m));
828    let mut stmts = vec![
829        TsStmt::decl(
830            TsDecl::TypeAlias {
831                name: "__Ctx".to_string(),
832                type_params: Vec::new(),
833                ty: TsType::Object(vec![TsTypeMember::method(
834                    "waitUntil",
835                    vec![TsParam::new(
836                        "promise",
837                        Some(TsType::named_with_args(
838                            "globalThis.Promise",
839                            vec![ty("unknown")],
840                        )),
841                    )],
842                    ty("void"),
843                )]),
844            },
845            None,
846        ),
847        tight(TsStmt::decl(
848            TsDecl::TypeAlias {
849                name: "__Fetch".to_string(),
850                type_params: Vec::new(),
851                ty: TsType::Object(vec![TsTypeMember::method(
852                    "fetch",
853                    vec![
854                        TsParam::new("request", Some(ty("globalThis.Request"))),
855                        TsParam::new("env", Some(ty("never"))),
856                        TsParam::new("ctx", Some(ty("__Ctx"))),
857                    ],
858                    promise(response_ty()),
859                )]),
860            },
861            None,
862        )),
863    ];
864    if has(&|m| !m.crons.is_empty()) {
865        stmts.push(handler_type(
866            "__Scheduled",
867            "scheduled",
868            "event",
869            ty("void"),
870        ));
871    }
872    if has(&|m| !m.queues.is_empty()) {
873        stmts.push(handler_type("__Queue", "queue", "batch", ty("void")));
874    }
875    if has(&|m| !m.addresses.is_empty()) {
876        stmts.push(handler_type("__Email", "email", "message", ty("void")));
877    }
878    for (i, m) in members {
879        let mut handlers = vec![ty("__Fetch")];
880        if !m.crons.is_empty() {
881            handlers.push(ty("__Scheduled"));
882        }
883        if !m.queues.is_empty() {
884            handlers.push(ty("__Queue"));
885        }
886        if !m.addresses.is_empty() {
887            handlers.push(ty("__Email"));
888        }
889        stmts.push(tight(const_typed(
890            format!("__m{i}"),
891            Some(TsType::intersection(handlers)),
892            ident(format!("__entry{i}")),
893        )));
894    }
895    let row_ty = TsType::readonly_array(TsType::Object(vec![
896        TsTypeMember::readonly_prop("entry", ty("__Fetch")),
897        TsTypeMember::readonly_prop(
898            "isMiss",
899            TsType::Fn {
900                rest: false,
901                params: vec![response_ty()],
902                names: vec!["response".to_string()],
903                ret: Box::new(ty("boolean")),
904            },
905        ),
906    ]));
907    let rows = members
908        .iter()
909        .map(|(i, _)| {
910            TsExpr::object(vec![
911                ("entry".to_string(), ident(format!("__m{i}"))),
912                ("isMiss".to_string(), ident(format!("__miss{i}"))),
913            ])
914        })
915        .collect();
916    stmts.push(const_typed(
917        "__members",
918        Some(row_ty),
919        TsExpr::multiline_array(rows),
920    ));
921    stmts
922}
923
924/// The group's `index.ts`.
925pub fn emit_group_entry(entry: &GroupEntry<'_>) -> TsProgram {
926    let mut program = TsProgram::new();
927    program.push(TsStmt::comment(
928        "Generated by bynk — do not edit by hand.",
929        None,
930    ));
931    let names: Vec<&str> = entry.members.iter().map(|m| m.context.as_str()).collect();
932    program.push(TsStmt::comment(
933        format!(
934            "Worker entry point for group `{}`: members {} (tried in this order).",
935            entry.key,
936            names.join(", ")
937        ),
938        None,
939    ));
940    let members: Vec<(usize, &GroupMember)> = entry.members.iter().enumerate().collect();
941    let has = |f: &dyn Fn(&GroupMember) -> bool| members.iter().any(|(_, m)| f(m));
942    let (has_cron, has_queue, has_email) = (
943        has(&|m| !m.crons.is_empty()),
944        has(&|m| !m.queues.is_empty()),
945        has(&|m| !m.addresses.is_empty()),
946    );
947    // The runtime import is a tree node, so the build's runtime-module pass
948    // finds it, as it does a member entry's.
949    for stmt in crate::emitter::runtime_files::runtime_import_stmts(
950        false,
951        &["__verifyCall".to_string()],
952        "../../runtime.js",
953    ) {
954        program.push(stmt);
955    }
956    for stmt in imports_and_exports(entry, &members) {
957        program.push(stmt);
958    }
959    for stmt in member_table(&members) {
960        program.push(stmt);
961    }
962    program.push(refused());
963    program.push(with_allowed());
964    program.push(unclaimed(entry));
965    program.push(dispatch());
966    for stmt in loopback(entry) {
967        program.push(stmt);
968    }
969    let mut handlers = vec![fetch_method()];
970    if has_cron {
971        handlers.push(scheduled(&members));
972    }
973    if has_queue {
974        handlers.push(queue(&members));
975    }
976    if has_email {
977        handlers.push(email(&members));
978    }
979    program.push(TsStmt::decl(
980        TsDecl::ExportDefault(TsExpr::multiline_object_entries(handlers)),
981        None,
982    ));
983    program
984}
985
986#[cfg(test)]
987mod tests {
988    use super::*;
989
990    fn member(context: &str) -> GroupMember {
991        GroupMember {
992            context: context.into(),
993            specifier: format!("./{context}.index.js"),
994            crons: vec!["* * * * *".into()],
995            queues: vec!["jobs".into()],
996            addresses: vec!["[email protected]".into()],
997            classes: vec![],
998        }
999    }
1000
1001    fn printed(entry: &GroupEntry<'_>) -> String {
1002        bynk_ts::print(&emit_group_entry(entry), "x.bynk", "", "index.ts").text
1003    }
1004
1005    fn entry_of(members: &[GroupMember]) -> GroupEntry<'_> {
1006        GroupEntry {
1007            key: "core",
1008            members,
1009            container_classes: &[],
1010            has_fanout: false,
1011            has_events: false,
1012            has_migrate: false,
1013            has_inspect: false,
1014        }
1015    }
1016
1017    /// #3562, G3-2: a handler of one member reaching another goes in process, so
1018    /// each of `scheduled`, `queue` and `email` runs its member on the loopback env.
1019    #[test]
1020    fn every_handler_runs_its_member_on_the_loopback_env() {
1021        let members = [member("app.a"), member("app.b")];
1022        let text = printed(&entry_of(&members));
1023        for handler in ["scheduled", "queue", "email"] {
1024            let at = text
1025                .find(&format!("async {handler}("))
1026                .unwrap_or_else(|| panic!("no {handler} handler:\n{text}"));
1027            let body = &text[at..];
1028            assert!(
1029                body.contains("__loopback(env, ctx) as never"),
1030                "{handler} does not pass the loopback env:\n{text}"
1031            );
1032            assert!(
1033                !body.contains("(env as never"),
1034                "{handler} passes the raw env:\n{text}"
1035            );
1036        }
1037    }
1038
1039    /// A callee that throws out of `fetch` is a plain `500` to its caller, as over
1040    /// a Service Binding, not the callee's exception.
1041    #[test]
1042    fn a_callee_that_throws_is_a_plain_500() {
1043        let members = [member("app.a"), member("app.b")];
1044        let text = printed(&entry_of(&members));
1045        assert!(text.contains("} catch {"), "{text}");
1046        assert!(text.contains("status: 500"), "{text}");
1047    }
1048
1049    /// A single-member group has nothing to loop back to: `__loopback` is the identity,
1050    /// and no member-binding table is built.
1051    #[test]
1052    fn a_lone_member_has_an_identity_loopback() {
1053        let members = [member("app.a")];
1054        let text = printed(&entry_of(&members));
1055        assert!(
1056            text.contains(
1057                "function __loopback(env: unknown, _ctx: __Ctx): unknown {\n  return env;\n}"
1058            ),
1059            "{text}"
1060        );
1061        assert!(!text.contains("__memberBindings"), "{text}");
1062    }
1063
1064    /// The member imports bind the default export and `isMiss` together, and every
1065    /// string the entry writes (specifiers, crons, queues, addresses) is escaped as
1066    /// a TypeScript string literal.
1067    #[test]
1068    fn member_imports_pair_the_entry_with_its_miss_marker() {
1069        let members = [member("app.a"), member("app.b")];
1070        let text = printed(&entry_of(&members));
1071        assert!(
1072            text.contains("import __entry0, { isMiss as __miss0 } from \"./app.a.index.js\";"),
1073            "{text}"
1074        );
1075        assert!(
1076            text.contains("import __entry1, { isMiss as __miss1 } from \"./app.b.index.js\";"),
1077            "{text}"
1078        );
1079        assert!(text.contains("{ entry: __m1, isMiss: __miss1 },"), "{text}");
1080    }
1081
1082    /// Queues that share a member stack their `case` labels over one body, and the
1083    /// catch-all `default` follows.
1084    #[test]
1085    fn a_members_queues_share_one_case_body() {
1086        let mut a = member("app.a");
1087        a.queues = vec!["jobs".into(), "mail".into()];
1088        let members = [a];
1089        let text = printed(&entry_of(&members));
1090        assert!(
1091            text.contains(
1092                "      case \"jobs\":\n      case \"mail\":\n        return __m0.queue(batch as never, __loopback(env, ctx) as never, ctx);\n      default:\n        return;"
1093            ),
1094            "{text}"
1095        );
1096    }
1097
1098    /// The internal prefixes a group answers unauthenticated depend on what its
1099    /// members host: `/_bynk/migrate/` and `/_bynk/inspect/` only when asked for.
1100    #[test]
1101    fn the_unclaimed_fallback_answers_only_the_prefixes_the_group_serves() {
1102        let members = [member("app.a")];
1103        let plain = printed(&entry_of(&members));
1104        assert!(plain.contains("async function __unclaimed("), "{plain}");
1105        assert!(!plain.contains("/_bynk/migrate/"), "{plain}");
1106        assert!(!plain.contains("/_bynk/inspect/"), "{plain}");
1107        let mut entry = entry_of(&members);
1108        entry.has_migrate = true;
1109        entry.has_inspect = true;
1110        let full = printed(&entry);
1111        assert!(full.contains("/_bynk/migrate/"), "{full}");
1112        assert!(full.contains("/_bynk/inspect/"), "{full}");
1113    }
1114
1115    /// The entry binds every name it uses: the member imports, the handler types
1116    /// and the runtime's `__verifyCall` account for all of them, in every shape of
1117    /// group (a lone member, several; fan-out, events, migrate, inspect).
1118    #[test]
1119    fn the_entry_binds_every_name_it_uses() {
1120        let sets = [
1121            vec![member("app.a")],
1122            vec![member("app.a"), member("app.b"), member("app.c")],
1123        ];
1124        for members in &sets {
1125            for bits in 0..16u32 {
1126                let mut entry = entry_of(members);
1127                entry.has_fanout = bits & 1 != 0;
1128                entry.has_events = bits & 2 != 0;
1129                entry.has_migrate = bits & 4 != 0;
1130                entry.has_inspect = bits & 8 != 0;
1131                let unbound = bynk_ts::unbound_names(&emit_group_entry(&entry));
1132                assert!(
1133                    unbound.is_empty(),
1134                    "{} members, {bits:#06b}: {unbound:?}",
1135                    members.len()
1136                );
1137            }
1138        }
1139    }
1140}