1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3
4use crate::builtin_names::methods::{OF, UNSAFE};
5use crate::checker::{
6 self, CapabilityInfo, CapabilityOpInfo, Ty, TyId, TypedExpr, Types, statement_at_boundary,
7};
8use crate::hints::HintSink;
9use crate::index::{RefSink, SymbolKind};
10use crate::kernel_op::{FormStatic, JsonStatic, StaticOp, YamlStatic};
11use crate::locals::LocalsSink;
12use crate::requirements::RequirementSink;
13use crate::resolver::{self, ResolvedCommons};
14use crate::symbols::{ConsumedType, UnitTable, record_provides_clause_ref, resolve_given_cap_ref};
15use bynk_project::detect_provider_dependency_cycles;
16use bynk_syntax::ast::*;
17use bynk_syntax::error::{Applicability, CompileError};
18use bynk_syntax::span::Span;
19
20pub(crate) fn derived_from(
24 decl: &CapabilityDecl,
25 flattened_caps: &HashMap<String, String>,
26) -> Option<(String, String)> {
27 decl.derived.as_ref().and_then(|d| {
28 flattened_caps
29 .get(&d.base.name)
30 .map(|unit| (unit.clone(), d.base.name.clone()))
31 })
32}
33
34pub fn build_capability_op_info(
41 op: &CapabilityOp,
42 types: &HashMap<String, Arc<TypeDecl>>,
43 tys: &Arc<Types>,
44) -> CapabilityOpInfo {
45 let vars: HashSet<String> = op.type_params.iter().map(|p| p.name.name.clone()).collect();
46 CapabilityOpInfo {
47 name: op.name.name.clone(),
48 type_params: op.type_params.iter().map(|p| p.name.name.clone()).collect(),
49 params: op
50 .params
51 .iter()
52 .map(|p| checker::resolve_type_ref_in(&p.type_ref, types, &vars, tys))
53 .map(|t| t.unwrap_or_else(|| tys.intern(Ty::Unit)))
54 .collect(),
55 param_names: op.params.iter().map(|p| p.name.name.clone()).collect(),
56 return_ty: checker::resolve_type_ref_in(&op.return_type, types, &vars, tys)
57 .unwrap_or_else(|| tys.intern(Ty::Unit)),
58 codable_params: checker::codable::codable_op_params(op),
59 reply_policy: checker::codable::op_reply_policy(op),
60 boundary_conflict: None,
61 }
62}
63
64pub fn check_context_constraints(
70 typed: &checker::TypedCommons,
71 consumed_types: &HashMap<String, ConsumedType>,
72 local_type_names: &HashSet<String>,
73 tys: &Arc<Types>,
74) -> Vec<CompileError> {
75 let mut errors = Vec::new();
76 for item in &typed.commons.items {
77 if let CommonsItem::Fn(f) = item
80 && f.given.is_empty()
81 {
82 walk_block_for_constraints(
83 &f.body,
84 typed,
85 consumed_types,
86 local_type_names,
87 &mut errors,
88 tys,
89 );
90 for c in f.requires.iter().chain(&f.ensures) {
92 walk_expr_for_constraints(
93 &c.predicate,
94 typed,
95 consumed_types,
96 local_type_names,
97 &mut errors,
98 tys,
99 );
100 }
101 }
102 }
103 errors
104}
105
106pub fn check_handler_constraints(
112 typed: &checker::TypedCommons,
113 consumed_types: &HashMap<String, ConsumedType>,
114 local_type_names: &HashSet<String>,
115 tys: &Arc<Types>,
116) -> Vec<CompileError> {
117 let mut errors = Vec::new();
118 for item in &typed.commons.items {
119 let (bodies, predicates): (Vec<&Block>, Vec<&Expr>) = match item {
120 CommonsItem::Service(s) => {
121 check_handler_inputs_not_external_opaque(s, typed, consumed_types, &mut errors);
122 (s.handlers.iter().map(|h| &h.body).collect(), Vec::new())
123 }
124 CommonsItem::Agent(a) => (
127 a.handlers.iter().map(|h| &h.body).collect(),
128 a.invariants
129 .iter()
130 .map(|i| &i.predicate)
131 .chain(a.transitions.iter().map(|t| &t.predicate))
132 .collect(),
133 ),
134 CommonsItem::Provider(p) => (p.ops.iter().map(|op| &op.body).collect(), Vec::new()),
135 CommonsItem::Fn(f)
140 if !f.given.is_empty() && checker::given_fn_refusal(f, true).is_none() =>
141 {
142 (
143 vec![&f.body],
144 f.requires
145 .iter()
146 .chain(&f.ensures)
147 .map(|c| &c.predicate)
148 .collect(),
149 )
150 }
151 _ => continue,
152 };
153 for body in bodies {
154 walk_block_for_constraints(
155 body,
156 typed,
157 consumed_types,
158 local_type_names,
159 &mut errors,
160 tys,
161 );
162 }
163 for e in predicates {
164 walk_expr_for_constraints(e, typed, consumed_types, local_type_names, &mut errors, tys);
165 }
166 }
167 errors
168}
169
170fn decode_targets(e: &Expr, typed: &checker::TypedCommons) -> Vec<TyId> {
174 use checker::Callee;
175 use checker::codable::{WitnessKind, witness_list};
176 match typed.callees.get(&e.id) {
177 Some(Callee::Intrinsic {
178 op:
179 StaticOp::Json(JsonStatic::Decode | JsonStatic::DecodeSql)
180 | StaticOp::Yaml(YamlStatic::Decode)
181 | StaticOp::Form(FormStatic::Decode),
182 ..
183 }) => match typed.expr_ty(e.id).as_deref() {
184 Some(Ty::Result(t, _)) => vec![*t],
185 _ => Vec::new(),
186 },
187 Some(Callee::D1Select { row, .. }) => vec![*row],
189 Some(
190 Callee::Fn(decl, ws)
191 | Callee::FnValue(decl, ws)
192 | Callee::Method(decl, ws)
193 | Callee::Static(decl, ws),
194 ) => witness_list(decl, &typed.types)
195 .iter()
196 .zip(ws)
197 .filter(|(w, _)| w.kind == WitnessKind::Codec)
198 .map(|(_, t)| *t)
199 .collect(),
200 _ => Vec::new(),
201 }
202}
203
204fn external_opaque_in(
209 t: TyId,
210 typed: &checker::TypedCommons,
211 consumed: &HashMap<String, ConsumedType>,
212 tys: &Arc<Types>,
213) -> Option<(String, String)> {
214 fn names(t: TyId, tys: &Arc<Types>, out: &mut Vec<String>) {
215 match &*tys.get(t) {
216 Ty::Named { name, args, .. } => {
217 out.push(name.clone());
218 args.iter().for_each(|a| names(*a, tys, out));
219 }
220 Ty::Option(a) | Ty::List(a) | Ty::Set(a) => names(*a, tys, out),
221 Ty::Result(a, b) | Ty::Map(a, b) => {
222 names(*a, tys, out);
223 names(*b, tys, out);
224 }
225 _ => {}
226 }
227 }
228 let mut stack = Vec::new();
229 names(t, tys, &mut stack);
230 external_opaque_reaching(stack, typed, consumed)
231}
232
233fn external_opaque_reaching(
235 mut stack: Vec<String>,
236 typed: &checker::TypedCommons,
237 consumed: &HashMap<String, ConsumedType>,
238) -> Option<(String, String)> {
239 let mut seen: HashSet<String> = HashSet::new();
240 while let Some(n) = stack.pop() {
241 if !seen.insert(n.clone()) {
242 continue;
243 }
244 let decl = typed.types.get(&n);
245 if let Some(ct) = consumed.get(&n)
246 && (ct.visibility == Visibility::Opaque
247 || decl.is_some_and(|d| matches!(d.body, TypeBody::Opaque { .. })))
248 {
249 return Some((n, ct.owning_context.clone()));
250 }
251 let Some(decl) = decl else {
252 continue;
253 };
254 let vars: HashSet<&str> = decl
255 .type_params
256 .iter()
257 .map(|p| p.name.name.as_str())
258 .collect();
259 let mut found = Vec::new();
260 match &decl.body {
261 TypeBody::Record(r) => r
262 .fields
263 .iter()
264 .for_each(|f| crate::project_model::type_ref_names(&f.type_ref, &vars, &mut found)),
265 TypeBody::Sum(sum) => sum.variants.iter().for_each(|v| {
266 v.payload.iter().for_each(|p| {
267 crate::project_model::type_ref_names(&p.type_ref, &vars, &mut found)
268 })
269 }),
270 TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
271 }
272 stack.extend(found);
273 }
274 None
275}
276
277fn check_decode_of_external_opaque(
284 e: &Expr,
285 typed: &checker::TypedCommons,
286 consumed: &HashMap<String, ConsumedType>,
287 errors: &mut Vec<CompileError>,
288 tys: &Arc<Types>,
289) {
290 if consumed.is_empty() {
291 return;
292 }
293 for t in decode_targets(e, typed) {
294 if let Some((name, owner)) = external_opaque_in(t, typed, consumed, tys) {
295 errors.push(
296 CompileError::new(
297 "bynk.context.external_decode",
298 e.span,
299 format!(
300 "cannot decode `{}` here — `{name}` is owned by context `{owner}`",
301 tys.display(t),
302 ),
303 )
304 .with_note(
305 "decoding creates a value, and values of an externally-owned opaque type can only be created inside the owning context; take the value from a service of `{owner}` instead".replace("{owner}", &owner),
306 ),
307 );
308 return;
309 }
310 }
311}
312
313fn check_handler_inputs_not_external_opaque(
322 s: &ServiceDecl,
323 typed: &checker::TypedCommons,
324 consumed: &HashMap<String, ConsumedType>,
325 errors: &mut Vec<CompileError>,
326) {
327 if consumed.is_empty() || matches!(s.protocol, ServiceProtocol::Call | ServiceProtocol::Cron) {
328 return;
329 }
330 if let ServiceProtocol::WebSocket { in_type, .. } = &s.protocol {
333 let mut names = Vec::new();
334 crate::project_model::type_ref_names(in_type, &HashSet::new(), &mut names);
335 if let Some((name, owner)) = external_opaque_reaching(names, typed, consumed) {
336 errors.push(
337 CompileError::new(
338 "bynk.context.external_decode",
339 in_type.span(),
340 format!(
341 "cannot take inbound frames of this type here — `{name}` is owned by context `{owner}`"
342 ),
343 )
344 .with_note(
345 "a frame is decoded from bytes this context did not produce, which creates a value; values of an externally-owned opaque type can only be created inside the owning context",
346 ),
347 );
348 return;
349 }
350 }
351 for h in &s.handlers {
352 for p in &h.params {
353 let mut names = Vec::new();
354 crate::project_model::type_ref_names(&p.type_ref, &HashSet::new(), &mut names);
355 if let Some((name, owner)) = external_opaque_reaching(names, typed, consumed) {
356 errors.push(
357 CompileError::new(
358 "bynk.context.external_decode",
359 p.type_ref.span(),
360 format!(
361 "cannot take `{}` as an input here — `{name}` is owned by context `{owner}`",
362 p.name.name,
363 ),
364 )
365 .with_note(
366 "an input is decoded from bytes this context did not produce, which creates a value; values of an externally-owned opaque type can only be created inside the owning context",
367 ),
368 );
369 }
370 }
371 }
372}
373
374fn walk_block_for_constraints(
375 block: &Block,
376 typed: &checker::TypedCommons,
377 consumed: &HashMap<String, ConsumedType>,
378 local: &HashSet<String>,
379 errors: &mut Vec<CompileError>,
380 tys: &Arc<Types>,
381) {
382 let mut exprs = Vec::new();
383 for stmt in &block.statements {
384 statement_exprs(stmt, &mut exprs);
385 }
386 exprs.push(&block.tail);
387 for e in exprs {
388 walk_expr_for_constraints(e, typed, consumed, local, errors, tys);
389 }
390}
391
392#[allow(clippy::only_used_in_recursion)]
406fn walk_expr_for_constraints(
407 e: &Expr,
408 typed: &checker::TypedCommons,
409 consumed: &HashMap<String, ConsumedType>,
410 local: &HashSet<String>,
411 errors: &mut Vec<CompileError>,
412 tys: &Arc<Types>,
413) {
414 check_decode_of_external_opaque(e, typed, consumed, errors, tys);
415 match &e.kind {
416 ExprKind::RecordConstruction { type_name, .. } => {
423 if let Some(ct) = consumed.get(&type_name.name)
424 && ct.visibility == Visibility::Opaque
425 {
426 errors.push(
427 CompileError::new(
428 "bynk.context.external_construction",
429 type_name.span,
430 format!(
431 "cannot construct `{}` here — it is owned by context `{}`",
432 type_name.name, ct.owning_context,
433 ),
434 )
435 .with_note(
436 "values of an externally-owned type can only be created inside the owning context",
437 ),
438 );
439 }
440 }
441 ExprKind::MethodCall {
443 receiver, method, ..
444 } => {
445 if let ExprKind::Ident(id) = &receiver.kind
446 && let Some(ct) = consumed.get(&id.name)
447 {
448 let is_construct = method.name == OF
449 || method.name == UNSAFE
450 || matches!(
451 typed.types.get(&id.name).map(|d| &d.body),
452 Some(TypeBody::Sum(s)) if s.variants.iter().any(|v| v.name.name == method.name),
453 );
454 if is_construct {
455 errors.push(
456 CompileError::new(
457 "bynk.context.external_construction",
458 id.span.merge(method.span),
459 format!(
460 "cannot construct `{}.{}` here — `{}` is owned by context `{}`",
461 id.name, method.name, id.name, ct.owning_context,
462 ),
463 )
464 .with_note(
465 "values of an externally-owned type can only be created inside the owning context",
466 ),
467 );
468 }
469 }
470 }
471 ExprKind::FieldAccess { receiver, field } => {
475 if let ExprKind::Ident(id) = &receiver.kind
476 && let Some(ct) = consumed.get(&id.name)
477 && ct.visibility == Visibility::Opaque
478 && typed
479 .types
480 .get(&id.name)
481 .map(|d| matches!(d.body, TypeBody::Sum(_)))
482 .unwrap_or(false)
483 {
484 errors.push(
485 CompileError::new(
486 "bynk.context.opaque_inspection",
487 id.span.merge(field.span),
488 format!(
489 "cannot inspect opaquely-exported type `{}` from outside context `{}`",
490 id.name, ct.owning_context,
491 ),
492 )
493 .with_note(
494 "opaque exports hide the type's shape; the owning context did not expose variants or fields",
495 ),
496 );
497 } else if let Some((name, ct)) = opaque_export_of(receiver, typed, consumed) {
498 errors.push(
499 CompileError::new(
500 "bynk.context.opaque_inspection",
501 field.span,
502 format!(
503 "cannot read field `{}` of opaquely-exported type `{name}` from outside context `{}`",
504 field.name, ct.owning_context,
505 ),
506 )
507 .with_note(
508 "opaque exports hide the type's shape; a consumer can hold and pass the value, and call its methods, but not read its fields",
509 ),
510 );
511 }
512 }
513 ExprKind::Match { discriminant, arms } => {
516 let mut discriminant_reported = false;
517 let hidden_record = matches!(&discriminant.kind, ExprKind::Ident(i) if bynk_syntax::ast::is_generated_binding(&i.name))
521 && matches!(
522 arms.first().map(|a| &a.pattern),
523 Some(Pattern::Record { .. })
524 );
525 if !hidden_record && let Some(ty) = typed.expr_ty(discriminant.id).as_deref() {
526 let display = ty.display(tys);
527 if let Some(ct) = consumed.get(&display)
528 && ct.visibility == Visibility::Opaque
529 {
530 discriminant_reported = true;
531 errors.push(
532 CompileError::new(
533 "bynk.context.opaque_inspection",
534 discriminant.span,
535 format!(
536 "cannot `match` on opaquely-exported type `{}` from outside context `{}`",
537 display, ct.owning_context,
538 ),
539 )
540 .with_note(
541 "opaque exports hide the type's shape; the owning context did not expose variants",
542 ),
543 );
544 }
545 }
546 for arm in arms {
550 opaque_record_patterns(&arm.pattern, consumed, !discriminant_reported, errors);
551 }
552 }
553 ExprKind::Is { pattern, .. } => opaque_record_patterns(pattern, consumed, true, errors),
554 _ => {}
555 }
556 for child in expr_children(e) {
557 walk_expr_for_constraints(child, typed, consumed, local, errors, tys);
558 }
559}
560
561fn opaque_record_patterns(
565 pattern: &Pattern,
566 consumed: &HashMap<String, ConsumedType>,
567 top: bool,
568 errors: &mut Vec<CompileError>,
569) {
570 match pattern {
571 Pattern::Record {
572 type_name, fields, ..
573 } => {
574 if top
575 && let Some(ct) = consumed.get(&type_name.name)
576 && ct.visibility == Visibility::Opaque
577 {
578 errors.push(
579 CompileError::new(
580 "bynk.context.opaque_inspection",
581 pattern.span(),
582 format!(
583 "cannot match fields of opaquely-exported type `{}` from outside context `{}`",
584 type_name.name, ct.owning_context,
585 ),
586 )
587 .with_note(
588 "opaque exports hide the type's shape; a consumer can hold and pass the value, and call its methods, but not read its fields",
589 ),
590 );
591 }
592 for (_, sub) in fields {
593 if let Some(sub) = sub {
594 opaque_record_patterns(sub, consumed, true, errors);
595 }
596 }
597 }
598 Pattern::List { elems, .. } => {
599 for e in elems {
600 opaque_record_patterns(e, consumed, true, errors);
601 }
602 }
603 Pattern::Variant { bindings, .. } => {
604 for b in bindings {
605 opaque_record_patterns(b.pattern(), consumed, true, errors);
606 }
607 }
608 Pattern::Or(alts, _) => {
609 for a in alts {
610 opaque_record_patterns(a, consumed, top, errors);
611 }
612 }
613 Pattern::Refined { inner, .. } => opaque_record_patterns(inner, consumed, top, errors),
614 Pattern::Wildcard(_)
615 | Pattern::Binding(_)
616 | Pattern::Literal { .. }
617 | Pattern::Range(_) => {}
618 }
619}
620
621fn opaque_export_of<'c>(
625 e: &Expr,
626 typed: &checker::TypedCommons,
627 consumed: &'c HashMap<String, ConsumedType>,
628) -> Option<(String, &'c ConsumedType)> {
629 let ty = typed.expr_ty(e.id)?;
630 let Ty::Named { name, .. } = &*ty else {
631 return None;
632 };
633 let ct = consumed.get(name)?;
634 (ct.visibility == Visibility::Opaque).then(|| (name.clone(), ct))
635}
636
637#[allow(clippy::too_many_arguments)]
648pub fn check_context_declarations(
649 typed: &mut checker::TypedCommons,
650 table: &UnitTable,
651 cross_context: &resolver::CrossContextInfo,
652 is_context: bool,
653 uses_commons_type_names: &HashSet<String>,
654 subscriber_visible_types: &HashMap<String, Arc<TypeDecl>>,
663 refs: &mut RefSink,
664 hints: &mut HintSink,
665 locals: &mut LocalsSink,
666 requirements: &mut RequirementSink,
667 tys: &Arc<Types>,
668) -> Vec<CompileError> {
669 let mut errors = Vec::new();
670 let no_vars: HashSet<String> = HashSet::new();
671
672 let resolved = ResolvedCommons::new(
680 typed.commons.clone(),
681 typed.types.clone(),
682 &table.types,
683 typed.fns.clone(),
684 typed.methods.clone(),
685 table.agents.clone(),
686 &table.events,
687 cross_context.clone(),
688 HashMap::new(),
689 is_context,
690 uses_commons_type_names.clone(),
691 )
692 .with_local_fns(&table.fns)
693 .with_assets(typed.assets.clone())
695 .with_embeds(typed.embeds.clone())
696 .with_consts(typed.consts.clone())
697 .with_shadowed_imports(typed.shadowed_imports.clone())
698 .with_scope_facts_of(typed)
699 .with_stability(typed.stability.clone());
700
701 check_capability_decls(table, &typed.types, &no_vars, refs);
703 for item in &typed.commons.items {
707 if let CommonsItem::Capability(c) = item
708 && let Some(d) = &c.derived
709 {
710 crate::symbols::record_capability_clause_ref(&d.base, cross_context, refs);
711 }
712 }
713
714 let mut capability_info_map: HashMap<String, CapabilityInfo> = table
716 .capabilities
717 .iter()
718 .map(|(name, decl)| {
719 let ops = decl
720 .ops
721 .iter()
722 .map(|op| build_capability_op_info(op, &typed.types, tys))
723 .collect();
724 (
725 name.clone(),
726 CapabilityInfo {
727 name: name.clone(),
728 ops,
729 derived_from: derived_from(decl, &cross_context.flattened_caps),
730 },
731 )
732 })
733 .collect();
734 let mut receiving_cache: Option<checker::Projection> = None;
738 for (cap, unit) in &cross_context.flattened_caps {
739 let Some(xcap) = cross_context
740 .consumed_capabilities
741 .get(unit)
742 .and_then(|m| m.get(cap))
743 else {
744 continue;
745 };
746 let unit_types = cross_context
753 .consumed_types
754 .get(unit)
755 .unwrap_or(&typed.types);
756 let (receiving, _) = receiving_cache.get_or_insert_with(|| {
757 checker::projected_types(&typed.types, &cross_context.consumed_types, tys)
758 });
759 let ops = xcap
760 .ops
761 .iter()
762 .map(|op| {
763 let vars: HashSet<String> = op.type_params.iter().cloned().collect();
764 let mut conflict: Option<(String, String, bool)> = None;
765 let mut resolve = |tr: &TypeRef, in_param: bool| {
766 let ty = checker::resolve_type_ref_in(tr, unit_types, &vars, tys)
767 .unwrap_or_else(|| tys.intern(Ty::Unit));
768 if conflict.is_none()
769 && let Some(name) =
770 checker::rebrand_conflict(ty, unit_types, &typed.types, receiving, tys)
771 {
772 conflict = Some((unit.clone(), name, in_param));
773 }
774 checker::rebrand_return_type(ty, &typed.types, tys)
775 };
776 let params = op.params.iter().map(|(_, tr)| resolve(tr, true)).collect();
777 let return_ty = resolve(&op.return_type, false);
778 CapabilityOpInfo {
779 name: op.name.clone(),
780 type_params: op.type_params.clone(),
781 params,
782 param_names: op.params.iter().map(|(n, _)| n.clone()).collect(),
783 return_ty,
784 codable_params: op.codable_params.clone(),
785 reply_policy: op.reply_policy,
786 boundary_conflict: conflict,
787 }
788 })
789 .collect();
790 capability_info_map.insert(
791 cap.clone(),
792 CapabilityInfo {
793 name: cap.clone(),
794 ops,
795 derived_from: None,
796 },
797 );
798 }
799
800 check_provider_decls(
801 typed,
802 table,
803 cross_context,
804 &resolved,
805 &capability_info_map,
806 refs,
807 hints,
808 locals,
809 requirements,
810 &mut errors,
811 tys,
812 );
813 check_service_decls(
814 typed,
815 table,
816 cross_context,
817 &resolved,
818 &capability_info_map,
819 refs,
820 hints,
821 locals,
822 requirements,
823 &mut errors,
824 tys,
825 );
826 check_given_fns(
827 typed,
828 cross_context,
829 &resolved,
830 &capability_info_map,
831 refs,
832 hints,
833 locals,
834 requirements,
835 &mut errors,
836 tys,
837 );
838 check_agent_decls(
839 typed,
840 table,
841 cross_context,
842 is_context,
843 uses_commons_type_names,
844 &capability_info_map,
845 &no_vars,
846 refs,
847 hints,
848 locals,
849 requirements,
850 &mut errors,
851 tys,
852 );
853 check_provider_agent_calls(table, &typed.callees, &mut errors);
855 let paths = crate::capability_paths::CapabilityGraph::build(
858 table,
859 &typed.callees,
860 requirements.current(),
861 typed.commons.span.file,
862 );
863 requirements.record_paths(paths);
864
865 check_event_field_defaults(
866 table,
867 &resolved,
868 subscriber_visible_types,
869 &mut typed.expr_types,
870 &mut typed.callees,
871 refs,
872 hints,
873 locals,
874 &mut errors,
875 tys,
876 );
877
878 check_event_annotations(table, &mut errors);
879
880 check_class_declarations(table, &mut errors);
883
884 errors
885}
886
887fn check_class_declarations(table: &UnitTable, errors: &mut Vec<CompileError>) {
892 let mut fates: HashMap<&str, Span> = HashMap::new();
893 let mut agents: Vec<&AgentDecl> = table.agents.values().map(|a| &**a).collect();
894 agents.sort_by_key(|a| a.span.start);
895 for a in agents {
896 let Some(old) = &a.replaces else { continue };
897 if table.agents.contains_key(&old.name) {
898 errors.push(
899 CompileError::new(
900 "bynk.agent.replaces_live",
901 old.span,
902 format!(
903 "agent `{}` replaces `{}`, but `{}` is still declared",
904 a.name.name, old.name, old.name
905 ),
906 )
907 .with_note("a rename moves the old class's data to the new one; remove the old declaration"),
908 );
909 }
910 if let Some(prev) = fates.insert(&old.name, old.span) {
911 errors.push(
912 CompileError::new(
913 "bynk.agent.class_conflict",
914 old.span,
915 format!("agent class `{}` is renamed more than once", old.name),
916 )
917 .with_label(prev, "first renamed here"),
918 );
919 }
920 }
921 for r in &table.removed_agents {
922 if table.agents.contains_key(&r.name.name) {
923 errors.push(
924 CompileError::new(
925 "bynk.agent.removed_live",
926 r.name.span,
927 format!(
928 "`removed agent {}` names a class that is still declared",
929 r.name.name
930 ),
931 )
932 .with_note(
933 "removing a class deletes its stored data; remove the declaration first",
934 ),
935 );
936 }
937 if let Some(prev) = fates.insert(&r.name.name, r.name.span) {
938 errors.push(
939 CompileError::new(
940 "bynk.agent.class_conflict",
941 r.name.span,
942 format!(
943 "agent class `{}` is both renamed and removed, or removed twice",
944 r.name.name
945 ),
946 )
947 .with_label(prev, "its other fate is declared here"),
948 );
949 }
950 }
951}
952
953#[allow(clippy::too_many_arguments)]
973fn check_event_field_defaults(
974 table: &UnitTable,
975 resolved: &ResolvedCommons,
976 subscriber_visible_types: &HashMap<String, Arc<TypeDecl>>,
977 expr_types: &mut HashMap<ExprId, TypedExpr>,
978 callees: &mut HashMap<ExprId, checker::Callee>,
979 refs: &mut RefSink,
980 hints: &mut HintSink,
981 locals: &mut LocalsSink,
982 errors: &mut Vec<CompileError>,
983 tys: &Arc<Types>,
984) {
985 for event in table.events.values() {
986 for field in &event.body.fields {
987 let Some(init) = &field.init else {
988 continue;
989 };
990 let before = errors.len();
991 checker::check_event_field_default(
992 init,
993 &field.type_ref,
994 "event field default",
995 resolved,
996 tys,
997 expr_types,
998 callees,
999 errors,
1000 refs,
1001 hints,
1002 locals,
1003 );
1004 if errors.len() > before {
1005 continue;
1006 }
1007 if let Err(reason) = crate::wire_default::lower_event_field_default_wire(
1008 init,
1009 &field.type_ref,
1010 subscriber_visible_types,
1011 ) {
1012 errors.push(
1013 CompileError::new(
1014 "bynk.types.bad_field_default",
1015 init.span,
1016 format!(
1017 "event field `{}`'s default cannot be represented on the wire: {reason}",
1018 field.name.name
1019 ),
1020 )
1021 .with_note(
1022 "a default is spliced into the same codec a real wire value passes \
1023 through, so it must be buildable with no reference to any type's \
1024 generated value namespace — only literals, sum-variant tags, and record \
1025 literals qualify",
1026 ),
1027 );
1028 }
1029 }
1030 }
1031}
1032
1033fn check_event_annotations(table: &UnitTable, errors: &mut Vec<CompileError>) {
1041 for event in table.events.values() {
1042 let mut schema_count = 0usize;
1043 for ann in &event.annotations {
1044 if ann.name.name != "schema" {
1045 errors.push(
1046 CompileError::new(
1047 "bynk.event.unknown_annotation",
1048 ann.name.span,
1049 format!(
1050 "unknown event annotation `@{}` — expected `@schema`",
1051 ann.name.name
1052 ),
1053 )
1054 .with_note("event annotations are a closed set"),
1055 );
1056 continue;
1057 }
1058 schema_count += 1;
1059 if schema_count > 1 {
1060 errors.push(
1061 CompileError::new(
1062 "bynk.event.bad_schema_version",
1063 ann.span,
1064 "`@schema` may appear at most once on an event",
1065 )
1066 .with_note("the event's schema version is a single value, not a set"),
1067 );
1068 continue;
1069 }
1070 match ann.args.as_slice() {
1071 [arg] if arg.label.is_none() => {
1072 if !matches!(&arg.value.kind, ExprKind::IntLit { value, .. } if *value > 0) {
1073 errors.push(crate::annotation_consts::with_const_origin(
1074 CompileError::new(
1075 "bynk.event.bad_schema_version",
1076 arg.span,
1077 "`@schema`'s argument must be a positive `Int` literal, or an `Int` constant bound to one",
1078 ),
1079 arg,
1080 ));
1081 }
1082 }
1083 [arg] => {
1084 errors.push(CompileError::new(
1085 "bynk.event.bad_schema_version",
1086 arg.span,
1087 "`@schema` takes one positional argument, not a labelled one",
1088 ));
1089 }
1090 [] => {
1091 errors.push(
1092 CompileError::new(
1093 "bynk.event.bad_schema_version",
1094 ann.span,
1095 "`@schema` requires one argument — the schema version",
1096 )
1097 .with_note("write `@schema(2)`, for example"),
1098 );
1099 }
1100 _ => {
1101 errors.push(CompileError::new(
1102 "bynk.event.bad_schema_version",
1103 ann.span,
1104 "`@schema` takes exactly one argument",
1105 ));
1106 }
1107 }
1108 }
1109 }
1110}
1111
1112fn check_capability_decls(
1116 table: &UnitTable,
1117 types: &HashMap<String, Arc<TypeDecl>>,
1118 no_vars: &HashSet<String>,
1119 refs: &mut RefSink,
1120) {
1121 for (name, decl) in &table.capabilities {
1122 refs.set_owner(name);
1123 for op in &decl.ops {
1124 let vars: HashSet<String> = if op.type_params.is_empty() {
1128 no_vars.clone()
1129 } else {
1130 op.type_params.iter().map(|p| p.name.name.clone()).collect()
1131 };
1132 for p in &op.params {
1133 checker::record_type_refs(&p.type_ref, types, &vars, refs);
1134 }
1135 checker::record_type_refs(&op.return_type, types, &vars, refs);
1136 }
1137 }
1138 refs.clear_owner();
1139}
1140
1141#[allow(clippy::too_many_arguments)]
1146fn check_provider_decls(
1147 typed: &mut checker::TypedCommons,
1148 table: &UnitTable,
1149 cross_context: &resolver::CrossContextInfo,
1150 resolved: &ResolvedCommons,
1151 capability_info_map: &HashMap<String, CapabilityInfo>,
1152 refs: &mut RefSink,
1153 hints: &mut HintSink,
1154 locals: &mut LocalsSink,
1155 requirements: &mut RequirementSink,
1156 errors: &mut Vec<CompileError>,
1157 tys: &Arc<Types>,
1158) {
1159 for provider in table.providers.values() {
1160 refs.set_owner(&provider.provider_name.name);
1161 if table.capabilities.contains_key(&provider.capability.name)
1164 || cross_context
1165 .flattened_caps
1166 .contains_key(&provider.capability.name)
1167 {
1168 record_provides_clause_ref(&provider.capability, cross_context, refs);
1169 }
1170 let mut provider_caps: HashMap<String, CapabilityInfo> = HashMap::new();
1173 for cap_ref in &provider.given {
1174 if let Some(info) =
1175 resolve_given_cap_ref(cap_ref, capability_info_map, cross_context, errors, refs)
1176 {
1177 provider_caps.insert(cap_ref.key().to_string(), info);
1178 }
1179 }
1180 for op in &provider.ops {
1181 checker::check_handler_body(
1188 resolved,
1189 checker::HandlerBodyCheck {
1190 capabilities: provider_caps.clone(),
1191 declared_capabilities: capability_info_map.clone(),
1192 ..checker::HandlerBodyCheck::new(
1193 &op.body,
1194 &op.return_type,
1195 &op.params,
1196 &provider.given,
1197 )
1198 },
1199 checker::CheckSinks {
1200 tys,
1201 expr_types: &mut typed.expr_types,
1202 errors,
1203 refs,
1204 hints,
1205 locals,
1206 requirements,
1207 callees: &mut typed.callees,
1208 },
1209 );
1210 }
1211 }
1212
1213 detect_provider_dependency_cycles(&table.providers, errors);
1218}
1219
1220#[allow(clippy::too_many_arguments)]
1225fn check_given_fns(
1226 typed: &mut checker::TypedCommons,
1227 cross_context: &resolver::CrossContextInfo,
1228 resolved: &ResolvedCommons,
1229 capability_info_map: &HashMap<String, CapabilityInfo>,
1230 refs: &mut RefSink,
1231 hints: &mut HintSink,
1232 locals: &mut LocalsSink,
1233 requirements: &mut RequirementSink,
1234 errors: &mut Vec<CompileError>,
1235 tys: &Arc<Types>,
1236) {
1237 let fns: Vec<Arc<FnDecl>> = typed
1238 .commons
1239 .items
1240 .iter()
1241 .filter_map(|i| match i {
1242 CommonsItem::Fn(f) if !f.given.is_empty() => Some(Arc::new(f.clone())),
1243 _ => None,
1244 })
1245 .collect();
1246 for f in fns {
1247 if checker::given_fn_refusal(&f, resolved.is_context).is_some() {
1248 continue;
1249 }
1250 refs.set_owner(f.name.display());
1251 let mut capabilities: HashMap<String, CapabilityInfo> = HashMap::new();
1252 for cap_ref in &f.given {
1253 if let Some(info) =
1254 resolve_given_cap_ref(cap_ref, capability_info_map, cross_context, errors, refs)
1255 {
1256 capabilities.insert(cap_ref.key().to_string(), info);
1257 }
1258 }
1259 checker::check_context_fn(
1260 &f,
1261 checker::FnCaps {
1262 capabilities,
1263 declared_capabilities: capability_info_map.clone(),
1264 },
1265 resolved,
1266 &mut typed.expr_types,
1267 &mut typed.callees,
1268 errors,
1269 refs,
1270 hints,
1271 locals,
1272 requirements,
1273 tys,
1274 );
1275 refs.clear_owner();
1276 }
1277}
1278
1279pub(crate) fn agent_calls_in(
1283 body: &Block,
1284 callees: &HashMap<ExprId, checker::Callee>,
1285) -> Vec<(String, String, Span)> {
1286 fn walk(
1287 e: &Expr,
1288 callees: &HashMap<ExprId, checker::Callee>,
1289 out: &mut Vec<(String, String, Span)>,
1290 ) {
1291 if let ExprKind::MethodCall { method, .. } = &e.kind
1292 && let Some(checker::Callee::Agent { agent, handler }) = callees.get(&e.id)
1293 {
1294 out.push((agent.clone(), handler.clone(), method.span));
1295 }
1296 for c in expr_children(e) {
1297 walk(c, callees, out);
1298 }
1299 }
1300 let mut top = Vec::new();
1301 for s in &body.statements {
1302 statement_exprs(s, &mut top);
1303 }
1304 top.push(&body.tail);
1305 let mut out = Vec::new();
1306 for e in top {
1307 walk(e, callees, &mut out);
1308 }
1309 out
1310}
1311
1312struct AgentNeed<'t> {
1315 cap: &'t CapRef,
1316 agent: String,
1317 handler: String,
1318}
1319
1320fn agent_handler_needs<'t>(
1325 table: &'t UnitTable,
1326 callees: &HashMap<ExprId, checker::Callee>,
1327 agent: &str,
1328 handler: &str,
1329 seen: &mut HashSet<(String, String)>,
1330 out: &mut Vec<AgentNeed<'t>>,
1331) {
1332 if !seen.insert((agent.to_string(), handler.to_string())) {
1333 return;
1334 }
1335 let Some(h) = table.agents.get(agent).and_then(|a| {
1336 a.handlers
1337 .iter()
1338 .find(|h| h.method_name.as_ref().is_some_and(|n| n.name == handler))
1339 }) else {
1340 return;
1341 };
1342 for c in &h.given {
1343 if !out.iter().any(|n| n.cap.key() == c.key()) {
1344 out.push(AgentNeed {
1345 cap: c,
1346 agent: agent.to_string(),
1347 handler: handler.to_string(),
1348 });
1349 }
1350 }
1351 for (a, m, _) in agent_calls_in(&h.body, callees) {
1352 agent_handler_needs(table, callees, &a, &m, seen, out);
1353 }
1354}
1355
1356fn check_provider_agent_calls(
1362 table: &UnitTable,
1363 callees: &HashMap<ExprId, checker::Callee>,
1364 errors: &mut Vec<CompileError>,
1365) {
1366 for provider in table.providers.values() {
1367 let entries: Vec<(String, Span)> = provider
1368 .given
1369 .iter()
1370 .map(|c| (c.key().to_string(), c.span))
1371 .collect();
1372 for op in &provider.ops {
1373 for (agent, handler, span) in agent_calls_in(&op.body, callees) {
1374 let mut needs = Vec::new();
1375 agent_handler_needs(
1376 table,
1377 callees,
1378 &agent,
1379 &handler,
1380 &mut HashSet::new(),
1381 &mut needs,
1382 );
1383 for need in needs {
1384 let key = need.cap.key();
1385 if entries.iter().any(|(k, _)| k == key) {
1386 continue;
1387 }
1388 let written = match need.cap.prefix() {
1391 Some(prefix) => format!("{prefix}.{key}"),
1392 None => key.to_string(),
1393 };
1394 let mut err = CompileError::new(
1395 "bynk.provider.agent_call_undeclared_capability",
1396 span,
1397 format!(
1398 "agent handler `{agent}.{handler}` needs `{written}`, but provider `{}` does not list it in `given`",
1399 provider.provider_name.name
1400 ),
1401 );
1402 if (need.agent.as_str(), need.handler.as_str())
1403 != (agent.as_str(), handler.as_str())
1404 {
1405 err = err.with_note(format!(
1406 "`{agent}.{handler}` calls `{}.{}`, which is `given {written}`",
1407 need.agent, need.handler
1408 ));
1409 }
1410 err = err.with_note(format!(
1411 "a provider hands an agent handler only the capabilities in its own `given`; add `{written}` to the provider's `given` clause"
1412 ));
1413 if let Some((_, last)) = entries.last()
1418 && !need.cap.is_cross_context()
1419 {
1420 err = err.with_suggestion(
1421 format!("add `{written}` to the `given` clause"),
1422 vec![(Span::new(last.end, last.end), format!(", {written}"))],
1423 Applicability::MachineApplicable,
1424 );
1425 }
1426 errors.push(err);
1427 }
1428 }
1429 }
1430 }
1431}
1432
1433pub(crate) fn check_one_call_handler(table: &UnitTable, errors: &mut Vec<CompileError>) {
1439 let mut services: Vec<&ServiceDecl> = table
1440 .services
1441 .values()
1442 .filter(|s| matches!(s.protocol, ServiceProtocol::Call))
1443 .collect();
1444 services.sort_by(|a, b| a.name.name.cmp(&b.name.name));
1445 for service in services {
1446 let calls: Vec<_> = service
1447 .handlers
1448 .iter()
1449 .filter(|h| h.kind == HandlerKind::Call)
1450 .collect();
1451 for extra in calls.iter().skip(1) {
1452 errors.push(
1453 CompileError::new(
1454 "bynk.service.duplicate_call_handler",
1455 extra.span,
1456 format!(
1457 "the service `{}` has more than one `on call` handler — it needs exactly one",
1458 service.name.name
1459 ),
1460 )
1461 .with_label(calls[0].span, "the service's `on call` handler")
1462 .with_note(
1463 "a service is called by its name, so it has one entry; to offer a second operation, declare a second service",
1464 ),
1465 );
1466 }
1467 }
1468}
1469
1470pub(crate) fn check_service_protocols(
1483 table: &UnitTable,
1484 visible_types: &HashMap<String, Arc<TypeDecl>>,
1485 errors: &mut Vec<CompileError>,
1486 tys: &Arc<Types>,
1487) {
1488 let mut ws_services: Vec<&ServiceDecl> = table
1493 .services
1494 .values()
1495 .filter(|s| matches!(s.protocol, ServiceProtocol::WebSocket { .. }))
1496 .collect();
1497 ws_services.sort_by(|a, b| a.name.name.cmp(&b.name.name));
1498 for extra in ws_services.iter().skip(1) {
1499 errors.push(
1500 CompileError::new(
1501 "bynk.service.websocket_multiple",
1502 extra.name.span,
1503 format!(
1504 "this context holds more than one `from websocket` service (`{}`) — at v1 the upgrade routes by the `Upgrade: websocket` header alone, so a context may host only one",
1505 extra.name.name
1506 ),
1507 )
1508 .with_note("split the WebSocket services into separate contexts; per-path routing of multiple WebSocket endpoints is a named follow-on"),
1509 );
1510 }
1511 for service in table.services.values() {
1512 if matches!(service.protocol, ServiceProtocol::WebSocket { .. }) {
1516 let opens: Vec<&Handler> = service
1517 .handlers
1518 .iter()
1519 .filter(|h| matches!(h.kind, HandlerKind::Open))
1520 .collect();
1521 if opens.is_empty() {
1522 errors.push(
1523 CompileError::new(
1524 "bynk.service.websocket_open_arity",
1525 service.name.span,
1526 format!(
1527 "the `from websocket` service `{}` has no `on open` handler — it needs exactly one (the edge upgrade)",
1528 service.name.name
1529 ),
1530 )
1531 .with_note("a `from websocket` service holds exactly one `on open`, and optionally one `on message` (inbound) and one `on close`"),
1532 );
1533 } else if opens.len() > 1 {
1534 errors.push(CompileError::new(
1535 "bynk.service.websocket_open_arity",
1536 opens[1].span,
1537 format!(
1538 "the `from websocket` service `{}` has more than one `on open` handler — it needs exactly one",
1539 service.name.name
1540 ),
1541 ));
1542 }
1543 for open in &opens {
1552 for p in &open.params {
1553 if !is_string_constructible(&p.type_ref, visible_types) {
1556 errors.push(
1557 CompileError::new(
1558 "bynk.service.websocket_param_not_stringy",
1559 p.type_ref.span(),
1560 format!(
1561 "the `on open` parameter `{}` must have a type constructible from `String` (got `{}`)",
1562 p.name.name,
1563 ts_type_ref_display(&p.type_ref),
1564 ),
1565 )
1566 .with_note(
1567 "it arrives as a query-string value; use `String`, a refined `String`, or an opaque type whose base is `String`, and parse an `Int` with `Int.parse` in the body",
1568 ),
1569 );
1570 }
1571 }
1572 }
1573 let ServiceProtocol::WebSocket { in_type, .. } = &service.protocol else {
1577 unreachable!("guarded by the enclosing match");
1578 };
1579 let resolve_ty = |t: &TypeRef| {
1585 checker::resolve_type_ref_in(t, &table.types, &HashSet::new(), tys)
1586 .unwrap_or(tys.intern(Ty::Unit))
1587 };
1588 let messages: Vec<&Handler> = service
1589 .handlers
1590 .iter()
1591 .filter(|h| matches!(h.kind, HandlerKind::Message))
1592 .collect();
1593 let closes: Vec<&Handler> = service
1594 .handlers
1595 .iter()
1596 .filter(|h| matches!(h.kind, HandlerKind::Close))
1597 .collect();
1598 if messages.len() > 1 {
1599 errors.push(CompileError::new(
1600 "bynk.service.websocket_open_arity",
1601 messages[1].span,
1602 format!(
1603 "the `from websocket` service `{}` has more than one `on message` handler — it needs at most one",
1604 service.name.name
1605 ),
1606 ));
1607 }
1608 if closes.len() > 1 {
1609 errors.push(CompileError::new(
1610 "bynk.service.websocket_open_arity",
1611 closes[1].span,
1612 format!(
1613 "the `from websocket` service `{}` has more than one `on close` handler — it needs at most one",
1614 service.name.name
1615 ),
1616 ));
1617 }
1618 for message in &messages {
1619 let frame_params = message
1620 .params
1621 .iter()
1622 .filter(|p| resolve_ty(&p.type_ref) == resolve_ty(in_type))
1623 .count();
1624 if frame_params != 1 {
1625 errors.push(
1626 CompileError::new(
1627 "bynk.ws.message_frame_param",
1628 message.span,
1629 format!(
1630 "a WebSocket `on message` handler must have exactly one parameter of the service's inbound frame type `{}` (the decoded frame), but found {frame_params}",
1631 ts_type_ref_display(in_type)
1632 ),
1633 )
1634 .with_note(
1635 "declare the frame as a parameter, e.g. `on message by user: Actor (frame: ClientFrame)`; any other parameters are route values recovered from the connection",
1636 ),
1637 );
1638 }
1639 }
1640 if let [open] = opens.as_slice() {
1646 let op = &open.params;
1647 let route_mismatch = |p: &Param, errors: &mut Vec<CompileError>| {
1648 errors.push(
1649 CompileError::new(
1650 "bynk.ws.route_param_mismatch",
1651 p.span,
1652 format!(
1653 "the route parameter `{}: {}` does not match the `on open` parameter at this position — `on message`/`on close` route values are recovered positionally from the connection, so they must be a type-compatible prefix of the `on open` parameters",
1654 p.name.name,
1655 ts_type_ref_display(&p.type_ref)
1656 ),
1657 )
1658 .with_note(
1659 "give the inbound/close handler the same leading parameters (name aside) as `on open`, in the same order",
1660 ),
1661 );
1662 };
1663 if let [message] = messages.as_slice() {
1664 let mut idx = 0usize;
1665 for p in &message.params {
1666 if resolve_ty(&p.type_ref) == resolve_ty(in_type) {
1667 continue; }
1669 if op
1670 .get(idx)
1671 .is_none_or(|o| resolve_ty(&p.type_ref) != resolve_ty(&o.type_ref))
1672 {
1673 route_mismatch(p, errors);
1674 }
1675 idx += 1;
1676 }
1677 }
1678 if let [close] = closes.as_slice() {
1679 for (i, p) in close.params.iter().enumerate() {
1680 if op
1681 .get(i)
1682 .is_none_or(|o| resolve_ty(&p.type_ref) != resolve_ty(&o.type_ref))
1683 {
1684 route_mismatch(p, errors);
1685 }
1686 }
1687 }
1688 }
1689 if let [open] = opens.as_slice() {
1698 let actors_of = |h: &Handler| -> Option<std::collections::BTreeSet<String>> {
1699 h.by_clause
1700 .as_ref()
1701 .map(|by| by.actors.iter().map(|a| a.name.clone()).collect())
1702 };
1703 let render = |h: &Handler| -> String {
1704 match &h.by_clause {
1705 Some(by) => by
1706 .actors
1707 .iter()
1708 .map(|a| a.name.as_str())
1709 .collect::<Vec<_>>()
1710 .join(" | "),
1711 None => "no `by` clause".to_string(),
1712 }
1713 };
1714 let open_actors = actors_of(open);
1715 for h in messages.iter().chain(closes.iter()) {
1716 if actors_of(h) != open_actors {
1717 let which = if matches!(h.kind, HandlerKind::Message) {
1718 "on message"
1719 } else {
1720 "on close"
1721 };
1722 errors.push(
1723 CompileError::new(
1724 "bynk.ws.lifecycle_by_mismatch",
1725 h.by_clause.as_ref().map_or(h.span, |by| by.span),
1726 format!(
1727 "the `{which}` handler of `{}` is `by` {}, but `on open` is `by` {} — a connection's principal is established once, at `on open`, so the lifecycle handlers must name the same actor(s)",
1728 service.name.name,
1729 render(h),
1730 render(open),
1731 ),
1732 )
1733 .with_note(
1734 "give `on message`/`on close` the same `by` actor (or the same actor-sum members) as `on open`; the binder name may differ. The principal is carried from `on open` for the connection's life, never re-verified per frame",
1735 ),
1736 );
1737 }
1738 }
1739 }
1740 let local_agents: std::collections::HashSet<String> =
1745 table.agents.keys().cloned().collect();
1746 for open in &opens {
1747 if !open.given.is_empty() {
1752 errors.push(
1753 CompileError::new(
1754 "bynk.ws.open_given_unsupported",
1755 open.span,
1756 "a WebSocket `on open` handler cannot declare `given` capabilities — on Workers it runs inside the connection-hosting Durable Object, which has no composition root to supply them",
1757 )
1758 .with_note(
1759 "move capability use into the agent handler the connection transfers to (it carries its own `given`)",
1760 ),
1761 );
1762 }
1763 use crate::websocket::{WsOpenShape, analyse_open_shape};
1764 match analyse_open_shape(&open.body, &local_agents) {
1765 WsOpenShape::One(_) => {}
1766 WsOpenShape::None => errors.push(
1767 CompileError::new(
1768 "bynk.ws.open_transfer_shape",
1769 open.span,
1770 "a WebSocket `on open` handler must transfer its `connection` into exactly one agent — e.g. `Room(roomId).join(…, connection)` — so the upgrade can be routed to the hosting Durable Object",
1771 )
1772 .with_note(
1773 "transfer the connection to an agent unconditionally (not inside an `if`/`match`); key it by a handler parameter, a `const` or a literal so the upgrade can be routed",
1774 ),
1775 ),
1776 WsOpenShape::Multiple => errors.push(CompileError::new(
1777 "bynk.ws.open_transfer_shape",
1778 open.span,
1779 "a WebSocket `on open` handler transfers its `connection` into more than one agent — the upgrade has no single Durable Object to route to",
1780 )),
1781 }
1782 }
1783 }
1784 if matches!(service.protocol, ServiceProtocol::Events { .. }) {
1788 let mut events = service
1789 .handlers
1790 .iter()
1791 .filter(|h| h.kind == HandlerKind::Event);
1792 if let (Some(first), Some(second)) = (events.next(), events.next()) {
1793 errors.push(
1794 CompileError::new(
1795 "bynk.event.duplicate_handler",
1796 second.span,
1797 format!(
1798 "the `from Events` service `{}` has more than one `on event` handler — it needs exactly one",
1799 service.name.name
1800 ),
1801 )
1802 .with_label(first.span, "the service's `on event` handler")
1803 .with_note(
1804 "to react to one event in two ways, declare two services: each subscriber is delivered to independently",
1805 ),
1806 );
1807 }
1808 }
1809 for handler in &service.handlers {
1810 let matches_protocol = matches!(
1811 (&service.protocol, &handler.kind),
1812 (ServiceProtocol::Call, HandlerKind::Call)
1813 | (ServiceProtocol::Http, HandlerKind::Http { .. })
1814 | (ServiceProtocol::Http, HandlerKind::Rejected)
1815 | (ServiceProtocol::Cron, HandlerKind::Cron { .. })
1816 | (ServiceProtocol::Queue { .. }, HandlerKind::Message)
1817 | (ServiceProtocol::Email { .. }, HandlerKind::Message)
1818 | (
1822 ServiceProtocol::WebSocket { .. },
1823 HandlerKind::Open | HandlerKind::Message | HandlerKind::Close
1824 )
1825 | (ServiceProtocol::Events { .. }, HandlerKind::Event)
1827 );
1828 if matches_protocol {
1829 if let ServiceProtocol::Events { event_type, .. } = &service.protocol
1837 && handler.kind == HandlerKind::Event
1838 {
1839 if let TypeRef::Effect(inner, _) = &handler.return_type
1843 && !matches!(inner.as_ref(), TypeRef::Unit(_))
1844 {
1845 errors.push(
1846 CompileError::new(
1847 "bynk.event.return_not_effect_unit",
1848 handler.return_type.span(),
1849 format!(
1850 "an `on event` handler must return `Effect[()]`, but got `{}`",
1851 ts_type_ref_display(&handler.return_type)
1852 ),
1853 )
1854 .with_note(
1855 "emission is fire-and-forget: nothing receives a subscriber's result",
1856 ),
1857 );
1858 }
1859 if let Some(param) = handler.params.first() {
1860 let header_name = type_ref_named(event_type);
1861 let param_name = type_ref_named(¶m.type_ref);
1862 if header_name.is_none() || header_name != param_name {
1863 errors.push(
1864 CompileError::new(
1865 "bynk.event.handler_param_type_mismatch",
1866 param.type_ref.span(),
1867 format!(
1868 "this handler's parameter type does not match the header's event type `{}`",
1869 type_ref_to_display(event_type)
1870 ),
1871 )
1872 .with_note(
1873 "an `on event(e: E)` handler's parameter must be the same event type its `from Events(E)` header names",
1874 ),
1875 );
1876 }
1877 }
1878 match handler.params.len() {
1894 0 => errors.push(
1895 CompileError::new(
1896 "bynk.event.bad_params",
1897 handler.span,
1898 "`on event` handlers take at least one parameter (the event payload)",
1899 )
1900 .with_note("add the payload parameter — e.g. `on event(e: E)`"),
1901 ),
1902 1 => {}
1903 2 => {
1904 let env_param = &handler.params[1];
1905 if type_ref_named(&env_param.type_ref) != Some("EventEnvelope") {
1906 errors.push(
1907 CompileError::new(
1908 "bynk.event.bad_params",
1909 env_param.type_ref.span(),
1910 "an `on event` handler's second parameter must be `EventEnvelope`",
1911 )
1912 .with_note(
1913 "the payload comes first; `EventEnvelope` carries runtime metadata about the emission (eventId, publisherId, emittedAt, schemaVersion)",
1914 ),
1915 );
1916 }
1917 }
1918 n => errors.push(CompileError::new(
1919 "bynk.event.bad_params",
1920 handler.params[2].span,
1921 format!(
1922 "`on event` handlers take at most two parameters (the event payload and, optionally, `EventEnvelope`), got {n}"
1923 ),
1924 )),
1925 }
1926 }
1927 continue;
1928 }
1929 match &service.protocol {
1930 ServiceProtocol::Call => {
1931 let suggested = match &handler.kind {
1932 HandlerKind::Http { .. } | HandlerKind::Rejected => "from http",
1933 HandlerKind::Cron { .. } => "from cron",
1934 HandlerKind::Message => "from queue(\"…\")",
1935 HandlerKind::Open | HandlerKind::Close => "from websocket(in: …, out: …)",
1936 HandlerKind::Event => "from Events(EventType)",
1937 HandlerKind::Call => continue,
1938 };
1939 errors.push(
1940 CompileError::new(
1941 "bynk.service.missing_from",
1942 handler.span,
1943 format!(
1944 "this handler needs a protocol on the service header — add `{suggested}` to `service {}`",
1945 service.name.name,
1946 ),
1947 )
1948 .with_note("a service with no `from` clause admits only `on call` handlers"),
1949 );
1950 }
1951 wire => {
1952 errors.push(
1953 CompileError::new(
1954 "bynk.service.mixed_protocols",
1955 handler.span,
1956 format!(
1957 "a `{}` service admits only its own handler form; this handler does not match",
1958 protocol_label(wire),
1959 ),
1960 )
1961 .with_note(
1962 "a service is one protocol adapter — split differing handlers into separate services",
1963 ),
1964 );
1965 }
1966 }
1967 }
1968 }
1969}
1970
1971fn protocol_label(p: &ServiceProtocol) -> &'static str {
1972 match p {
1973 ServiceProtocol::Call => "call",
1974 ServiceProtocol::Http => "from http",
1975 ServiceProtocol::Cron => "from cron",
1976 ServiceProtocol::Queue { .. } => "from queue",
1977 ServiceProtocol::WebSocket { .. } => "from websocket",
1978 ServiceProtocol::Events { .. } => "from Events",
1979 ServiceProtocol::Email { .. } => "from email",
1980 }
1981}
1982
1983fn type_ref_named(t: &TypeRef) -> Option<&str> {
1988 match t {
1989 TypeRef::Named(id) => Some(id.name.as_str()),
1990 _ => None,
1991 }
1992}
1993
1994pub fn ts_type_ref_display(r: &TypeRef) -> String {
2002 match r {
2003 TypeRef::Base(b, _) => b.name().to_string(),
2004 TypeRef::Named(id) => crate::symbols::display_type_name(&id.name).to_string(),
2005 TypeRef::Result(t, e, _) => format!(
2006 "Result[{}, {}]",
2007 ts_type_ref_display(t),
2008 ts_type_ref_display(e)
2009 ),
2010 TypeRef::Option(t, _) => format!("Option[{}]", ts_type_ref_display(t)),
2011 TypeRef::Effect(t, _) => format!("Effect[{}]", ts_type_ref_display(t)),
2012 TypeRef::HttpResult(t, _) => format!("HttpResult[{}]", ts_type_ref_display(t)),
2013 TypeRef::QueueResult(_) => "QueueResult".to_string(),
2014 TypeRef::Asset(_) => "Asset".to_string(),
2015 TypeRef::RequestHeaders(_) => "RequestHeaders".to_string(),
2016 TypeRef::RequestQuery(_) => "RequestQuery".to_string(),
2017 TypeRef::RequestCookies(_) => "RequestCookies".to_string(),
2018 TypeRef::TokenClaims(_) => "TokenClaims".to_string(),
2019 TypeRef::BoundaryRejection(_) => "BoundaryRejection".to_string(),
2020 TypeRef::List(t, _) => format!("List[{}]", ts_type_ref_display(t)),
2021 TypeRef::Set(t, _) => format!("Set[{}]", ts_type_ref_display(t)),
2022 TypeRef::Query(t, _) => format!("Query[{}]", ts_type_ref_display(t)),
2023 TypeRef::Stream(t, _) => format!("Stream[{}]", ts_type_ref_display(t)),
2024 TypeRef::Connection(t, _) => format!("Connection[{}]", ts_type_ref_display(t)),
2025 TypeRef::History(t, _) => format!("History[{}]", ts_type_ref_display(t)),
2026 TypeRef::Map(k, v, _) => format!(
2027 "Map[{}, {}]",
2028 ts_type_ref_display(k),
2029 ts_type_ref_display(v)
2030 ),
2031 TypeRef::ValidationError(_) => "ValidationError".to_string(),
2032 TypeRef::DecodeError(_) => "DecodeError".to_string(),
2033 TypeRef::Unit(_) => "()".to_string(),
2034 TypeRef::App { name, args, .. } => format!(
2036 "{}[{}]",
2037 name.name,
2038 args.iter()
2039 .map(ts_type_ref_display)
2040 .collect::<Vec<_>>()
2041 .join(", ")
2042 ),
2043 TypeRef::Fn(params, ret, _) => {
2044 let lhs = match params.len() {
2045 0 => "()".to_string(),
2046 1 if !matches!(params[0], TypeRef::Fn(..)) => ts_type_ref_display(¶ms[0]),
2047 _ => format!(
2048 "({})",
2049 params
2050 .iter()
2051 .map(ts_type_ref_display)
2052 .collect::<Vec<_>>()
2053 .join(", ")
2054 ),
2055 };
2056 format!("{lhs} -> {}", ts_type_ref_display(ret))
2057 }
2058 }
2059}
2060
2061pub fn type_ref_to_display(t: &TypeRef) -> String {
2065 match t {
2066 TypeRef::Named(id) => crate::symbols::display_type_name(&id.name).to_string(),
2067 TypeRef::Base(b, _) => b.name().to_string(),
2068 other => format!("{other:?}"),
2069 }
2070}
2071
2072fn check_by_clause_contracts(
2088 by: &bynk_syntax::ast::ByClause,
2089 params: Option<&[bynk_syntax::ast::Param]>,
2090 protocol: &ServiceProtocol,
2091 table: &UnitTable,
2092 refs: &mut RefSink,
2093 errors: &mut Vec<CompileError>,
2094) {
2095 use crate::actors::{self, Scheme};
2096
2097 if let (Some(params), Some(binder)) = (params, &by.binder)
2102 && params.iter().any(|p| p.name.name == binder.name)
2103 {
2104 errors.push(
2105 CompileError::new(
2106 "bynk.actor.binder_shadows_param",
2107 binder.span,
2108 format!(
2109 "the actor binder `{}` collides with a handler parameter of the same name",
2110 binder.name,
2111 ),
2112 )
2113 .with_note("rename the `by` binder or the parameter"),
2114 );
2115 }
2116 if by.is_sum() && by.binder.is_none() {
2119 errors.push(
2120 CompileError::new(
2121 "bynk.actor.sum_requires_binder",
2122 by.span,
2123 "a multi-actor `by` clause must bind the resolved actor",
2124 )
2125 .with_note("write `by who: A | B (…)` and `match who { … }` in the body"),
2126 );
2127 }
2128 let mut members: Vec<(&bynk_syntax::ast::Ident, actors::Contract)> = Vec::new();
2134 for actor_ref in &by.actors {
2135 let local = table.actors.get(&actor_ref.name);
2136 if by.is_sum()
2139 && local.is_some_and(|a| a.refinement.is_some() && !is_caller_refinement(a, table))
2140 {
2141 errors.push(
2142 CompileError::new(
2143 "bynk.actor.refinement_in_sum",
2144 actor_ref.span,
2145 format!(
2146 "the refinement actor `{}` cannot be a peer in a multi-actor sum",
2147 actor_ref.name
2148 ),
2149 )
2150 .with_note(
2151 "a refinement narrows a base actor — match it inside the \
2152 resolved arm, not as a sum member",
2153 ),
2154 );
2155 continue;
2156 }
2157 let contract = if let Some(a) = local {
2158 refs.record(actor_ref.span, SymbolKind::Actor, &actor_ref.name);
2159 let scheme_actor = match &a.refinement {
2164 Some(r) => table.actors.get(&r.base.name),
2165 None => Some(a),
2166 };
2167 if is_caller_refinement(a, table) {
2168 actors::prelude_actor("Caller")
2170 } else {
2171 scheme_actor
2172 .and_then(|sa| sa.auth.as_ref())
2173 .and_then(|au| Scheme::from_name(&au.name))
2174 .filter(|s| s.admitted())
2175 .map(|scheme| actors::Contract {
2176 scheme,
2177 identity: actors::Identity::Unit,
2178 })
2179 }
2180 } else {
2181 actors::prelude_actor(&actor_ref.name)
2182 };
2183 let Some(contract) = contract else {
2184 if local.is_none() {
2185 errors.push(
2186 CompileError::new(
2187 "bynk.actor.unknown_actor",
2188 actor_ref.span,
2189 format!("unknown actor `{}`", actor_ref.name),
2190 )
2191 .with_note(
2192 "name a declared `actor` or a prelude actor \
2193 (`Visitor`, `Scheduler`, `Producer`, `Sender`, `Caller`)",
2194 ),
2195 );
2196 }
2197 continue;
2198 };
2199 if !actors::scheme_admissible(protocol, contract.scheme) {
2200 errors.push(
2201 CompileError::new(
2202 "bynk.actor.scheme_not_admissible",
2203 by.span,
2204 format!(
2205 "a `{}` actor is not admissible on a `{}` handler",
2206 contract.scheme.as_str(),
2207 protocol_label(protocol),
2208 ),
2209 )
2210 .with_note(match protocol {
2211 _ if contract.scheme == Scheme::Foreign => {
2214 "a `Foreign` actor is admitted only on an `on call` handler"
2215 }
2216 ServiceProtocol::Http => {
2217 "public HTTP routes take an anonymous actor — write `by v: Visitor`"
2218 }
2219 _ => "internal protocols (call/cron/queue) take an `Internal` actor",
2220 }),
2221 );
2222 }
2223 let is_caller = (!table.actors.contains_key(&actor_ref.name)
2228 && actors::prelude_actor(&actor_ref.name).map(|c| c.identity)
2229 == Some(actors::Identity::CallerId))
2230 || local.is_some_and(|a| is_caller_refinement(a, table));
2231 if is_caller && !matches!(protocol, ServiceProtocol::Call) {
2232 errors.push(
2233 CompileError::new(
2234 "bynk.actor.scheme_not_admissible",
2235 by.span,
2236 format!(
2237 "the `Caller` actor is not admissible on a `{}` handler",
2238 protocol_label(protocol),
2239 ),
2240 )
2241 .with_note(
2242 "`Caller` carries the calling context's identity — it is only \
2243 admissible on `on call`; cron takes `Scheduler`, queue takes `Producer`",
2244 ),
2245 );
2246 }
2247 if by.is_sum() && contract.scheme == actors::Scheme::Oidc {
2251 errors.push(
2252 CompileError::new(
2253 "bynk.actor.oidc_not_in_sum",
2254 actor_ref.span,
2255 format!(
2256 "the `Oidc` actor `{}` cannot be a peer in a multi-actor sum",
2257 actor_ref.name
2258 ),
2259 )
2260 .with_note(
2261 "OIDC is single-actor this slice — give the route a single \
2262 `by user: <OidcActor>` clause",
2263 ),
2264 );
2265 }
2266 if by.is_sum() && contract.scheme == actors::Scheme::SignedCookie {
2270 errors.push(
2271 CompileError::new(
2272 "bynk.actor.signed_cookie_not_in_sum",
2273 actor_ref.span,
2274 format!(
2275 "the `SignedCookie` actor `{}` cannot be a peer in a multi-actor sum",
2276 actor_ref.name
2277 ),
2278 )
2279 .with_note(
2280 "a signed cookie is single-actor in this slice — give the route a single \
2281 `by user: <SignedCookieActor>` clause",
2282 ),
2283 );
2284 }
2285 members.push((actor_ref, contract));
2286 }
2287 if let Some(params) = params
2291 && members
2292 .iter()
2293 .any(|(_, c)| c.scheme == actors::Scheme::Signature)
2294 && !params.iter().any(|p| p.name.name == "body")
2295 {
2296 errors.push(
2297 CompileError::new(
2298 "bynk.actor.signature_requires_body",
2299 by.span,
2300 "a `Signature` handler must take a `body` parameter (the signature is over the body)",
2301 )
2302 .with_note("add a `(body: T)` parameter to the handler"),
2303 );
2304 }
2305 if let Some(params) = params
2308 && members
2309 .iter()
2310 .any(|(_, c)| c.scheme == actors::Scheme::Signature)
2311 && let Some(body) = params
2312 .iter()
2313 .find(|p| p.name.name == "body" && is_byte_stream(&p.type_ref))
2314 {
2315 errors.push(
2316 CompileError::new(
2317 "bynk.http.stream_body_signature",
2318 body.type_ref.span(),
2319 "a `Signature` route cannot take a streamed `body`",
2320 )
2321 .with_note(
2322 "the signature is an HMAC over the whole body, verified before the handler runs; take `body: Bytes` for a signed webhook, or sign the head (a header or the path) and verify the content out of band",
2323 ),
2324 );
2325 }
2326 if by.is_sum() {
2331 let mut seen: Vec<actors::Scheme> = Vec::new();
2332 let mut seen_catch_all = false;
2333 for (actor_ref, contract) in &members {
2334 if seen_catch_all {
2335 errors.push(
2336 CompileError::new(
2337 "bynk.actor.unreachable_sum_arm",
2338 actor_ref.span,
2339 format!(
2340 "actor `{}` is unreachable — an earlier `None` peer accepts every caller",
2341 actor_ref.name
2342 ),
2343 )
2344 .with_note("a catch-all (`None`, e.g. `Visitor`) peer must come last"),
2345 );
2346 continue;
2347 }
2348 if contract.scheme == actors::Scheme::None {
2349 seen_catch_all = true;
2350 } else if contract.scheme == actors::Scheme::Foreign {
2351 } else if seen.contains(&contract.scheme) {
2356 errors.push(
2357 CompileError::new(
2358 "bynk.actor.duplicate_sum_scheme",
2359 actor_ref.span,
2360 format!(
2361 "actor `{}` repeats the `{}` scheme of an earlier peer",
2362 actor_ref.name,
2363 contract.scheme.as_str()
2364 ),
2365 )
2366 .with_note(
2367 "peers in a sum are distinguished by scheme — two same-scheme \
2368 peers can't both be reached",
2369 ),
2370 );
2371 } else {
2372 seen.push(contract.scheme);
2373 }
2374 }
2375 }
2376}
2377
2378fn check_scheme_arg_kinds(actor: &ActorDecl, errors: &mut Vec<CompileError>) {
2385 use crate::actors::Scheme;
2386 let signed_cookie =
2387 actor.auth.as_ref().and_then(|a| Scheme::from_name(&a.name)) == Some(Scheme::SignedCookie);
2388 let mut seen: HashSet<&str> = HashSet::new();
2389 for arg in &actor.auth_config {
2390 if signed_cookie && !seen.insert(arg.key.name.as_str()) {
2391 errors.push(
2392 CompileError::new(
2393 "bynk.actor.signed_cookie_duplicate_key",
2394 arg.key.span,
2395 format!(
2396 "the scheme config key `{}` is given more than once",
2397 arg.key.name
2398 ),
2399 )
2400 .with_note(
2401 "only the first value would be read, so the second is refused: keep one",
2402 ),
2403 );
2404 }
2405 if !signed_cookie
2406 && matches!(
2407 arg.value,
2408 bynk_syntax::ast::SchemeArgValue::Duration { .. }
2409 | bynk_syntax::ast::SchemeArgValue::Ident(_)
2410 )
2411 {
2412 errors.push(
2413 CompileError::new(
2414 "bynk.actor.scheme_arg_kind",
2415 arg.span,
2416 format!(
2417 "the scheme config value for `{}` must be a string or an integer",
2418 arg.key.name
2419 ),
2420 )
2421 .with_note(
2422 "a duration or a bare name is accepted only by `SignedCookie`; give a whole number (a `Signature` `tolerance` is in seconds: `tolerance = 300`) or a quoted string",
2423 ),
2424 );
2425 }
2426 }
2427}
2428
2429const SIGNED_COOKIE_KEYS: &[&str] = &["cookie", "secret", "previous", "ttl", "sameSite"];
2431
2432const SIGNED_COOKIE_LONG_TTL_SECS: i64 = 30 * 24 * 60 * 60;
2434
2435fn is_cookie_token(name: &str) -> bool {
2437 !name.is_empty()
2438 && name
2439 .bytes()
2440 .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
2441}
2442
2443fn check_signed_cookie_actor(
2447 actor: &ActorDecl,
2448 auth: &Ident,
2449 table: &UnitTable,
2450 types: &HashMap<String, Arc<TypeDecl>>,
2451 errors: &mut Vec<CompileError>,
2452) {
2453 let bad_arg = |span: Span, key: &str, want: &str, errors: &mut Vec<CompileError>| {
2454 errors.push(
2455 CompileError::new(
2456 "bynk.actor.signed_cookie_bad_arg",
2457 span,
2458 format!("a `SignedCookie` actor's `{key}` must be {want}"),
2459 )
2460 .with_note(
2461 "write `auth = SignedCookie(secret = \"<ENV_NAME>\", ttl = 12.hours)`; the optional keys are `cookie`, `previous` and `sameSite`",
2462 ),
2463 );
2464 };
2465 for arg in &actor.auth_config {
2466 if !SIGNED_COOKIE_KEYS.contains(&arg.key.name.as_str()) {
2467 errors.push(
2468 CompileError::new(
2469 "bynk.actor.signed_cookie_unknown_key",
2470 arg.key.span,
2471 format!("unknown `SignedCookie` config key `{}`", arg.key.name),
2472 )
2473 .with_note("the keys are `secret`, `ttl`, `cookie`, `previous` and `sameSite`"),
2474 );
2475 }
2476 }
2477 match actor.scheme_arg("secret") {
2479 None => errors.push(
2480 CompileError::new(
2481 "bynk.actor.signed_cookie_missing_secret",
2482 auth.span,
2483 "a `SignedCookie` actor must name its signing secret",
2484 )
2485 .with_note(
2486 "write `auth = SignedCookie(secret = \"<ENV_NAME>\", ttl = 12.hours)` — the env var holding the signing key (`bynk deploy` mints it when unset)",
2487 ),
2488 ),
2489 Some(arg) if arg.value.as_str().is_none() => {
2490 bad_arg(arg.span, "secret", "an env binding name, as a string", errors);
2491 }
2492 Some(_) => {}
2493 }
2494 let previous = actor.scheme_arg("previous");
2495 if let Some(arg) = previous
2496 && arg.value.as_str().is_none()
2497 {
2498 bad_arg(
2499 arg.span,
2500 "previous",
2501 "an env binding name, as a string",
2502 errors,
2503 );
2504 }
2505 let mine: Vec<(&str, &str, Span)> = ["secret", "previous"]
2509 .iter()
2510 .filter_map(|k| {
2511 let a = actor.scheme_arg(k)?;
2512 Some((*k, a.value.as_str()?, a.span))
2513 })
2514 .collect();
2515 if let [(_, a, _), (_, b, span)] = mine.as_slice()
2516 && a == b
2517 {
2518 errors.push(
2519 CompileError::new(
2520 "bynk.actor.signed_cookie_secret_shared",
2521 *span,
2522 "a `SignedCookie` actor's `previous` key is the same variable as its `secret`",
2523 )
2524 .with_note("`previous` is the key being rotated out — give it its own variable"),
2525 );
2526 }
2527 for other in table.actors.values() {
2528 if other.name.name == actor.name.name {
2529 continue;
2530 }
2531 let other_names: Vec<&str> = ["secret", "previous"]
2532 .iter()
2533 .filter_map(|k| other.scheme_arg(k)?.value.as_str())
2534 .collect();
2535 for (key, value, span) in &mine {
2536 if other_names.contains(value) {
2537 errors.push(
2538 CompileError::new(
2539 "bynk.actor.signed_cookie_secret_shared",
2540 *span,
2541 format!(
2542 "the `{key}` `{value}` of `SignedCookie` actor `{}` is also used by actor `{}`",
2543 actor.name.name, other.name.name
2544 ),
2545 )
2546 .with_note(
2547 "a session key signs one actor's cookies only — sharing it would let a credential for one actor be replayed against another; give each its own variable",
2548 ),
2549 );
2550 }
2551 }
2552 }
2553 match actor.scheme_arg("ttl") {
2555 None => {
2556 let mut err = CompileError::new(
2557 "bynk.actor.signed_cookie_missing_ttl",
2558 auth.span,
2559 "a `SignedCookie` actor must declare a `ttl`",
2560 )
2561 .with_note(
2562 "an immortal session cookie is the failure to avoid — write `ttl = 12.hours`; a stateless cookie cannot be revoked before it expires, so keep it short",
2563 );
2564 if let Some(last) = actor.auth_config.last() {
2569 let at = Span::new_in(last.span.file, last.span.end, last.span.end);
2570 err = err.with_suggestion(
2571 "add `ttl = 12.hours` (a stateless cookie cannot be revoked before it expires, so keep it short)",
2572 vec![(at, ", ttl = 12.hours".to_string())],
2573 Applicability::MaybeIncorrect,
2574 );
2575 }
2576 errors.push(err);
2577 }
2578 Some(arg) => match arg.value.as_duration_millis() {
2579 Some(ms) if ms > 0 && ms % 1000 == 0 => {
2580 if ms / 1000 > SIGNED_COOKIE_LONG_TTL_SECS {
2581 errors.push(
2582 CompileError::new(
2583 "bynk.actor.signed_cookie_ttl_long",
2584 arg.span,
2585 "this `SignedCookie` `ttl` is longer than 30 days",
2586 )
2587 .with_note(
2588 "a stateless signed cookie cannot be revoked before it expires: a copy a user already took keeps working for the whole `ttl`. Shorten it, or use a server-side session (see `examples/sessions`) if you need to log out everywhere",
2589 ),
2590 );
2591 }
2592 }
2593 _ => errors.push(
2594 CompileError::new(
2595 "bynk.actor.signed_cookie_bad_ttl",
2596 arg.span,
2597 "a `SignedCookie` `ttl` must be a positive whole number of seconds",
2598 )
2599 .with_note(
2600 "write a `Duration` literal such as `ttl = 12.hours` or `ttl = 30.minutes`",
2601 ),
2602 ),
2603 },
2604 }
2605 if let Some(arg) = actor.scheme_arg("cookie") {
2607 match arg.value.as_str() {
2608 None => bad_arg(arg.span, "cookie", "a cookie name, as a string", errors),
2609 Some(name) if !is_cookie_token(name) => errors.push(
2610 CompileError::new(
2611 "bynk.actor.signed_cookie_bad_name",
2612 arg.span,
2613 format!("`{name}` is not a legal cookie name"),
2614 )
2615 .with_note(
2616 "a cookie name is an RFC 6265 token: letters, digits and ``!#$%&'*+-.^_`|~``, no spaces, `=`, `;`, `,` or quotes",
2617 ),
2618 ),
2619 Some(name) if !name.to_ascii_lowercase().starts_with("__host-") => errors.push(
2620 CompileError::new(
2621 "bynk.actor.signed_cookie_unprefixed",
2622 arg.span,
2623 format!("the session cookie `{name}` is not a `__Host-` cookie"),
2624 )
2625 .with_note(
2626 "a `__Host-` name stops a sibling subdomain setting or overwriting the cookie; the default is `__Host-session`",
2627 ),
2628 ),
2629 Some(_) => {}
2630 }
2631 }
2632 if let Some(arg) = actor.scheme_arg("sameSite")
2633 && !matches!(
2634 arg.value.as_ident(),
2635 Some("Lax" | "Strict" | "Unrestricted")
2636 )
2637 {
2638 bad_arg(
2639 arg.span,
2640 "sameSite",
2641 "`Lax`, `Strict` or `Unrestricted`",
2642 errors,
2643 );
2644 }
2645 match &actor.identity {
2646 None => errors.push(
2647 CompileError::new(
2648 "bynk.actor.signed_cookie_identity_not_string_constructible",
2649 auth.span,
2650 "a `SignedCookie` actor must declare a string-constructible `identity`",
2651 )
2652 .with_note(
2653 "the verified identity is minted from the cookie's `sub` claim — declare `identity = T` where `T` is a refined or opaque `String`",
2654 ),
2655 ),
2656 Some(id) if !is_string_constructible(id, types) => errors.push(
2657 CompileError::new(
2658 "bynk.actor.signed_cookie_identity_not_string_constructible",
2659 id.span(),
2660 "a `SignedCookie` actor's identity must be string-constructible",
2661 )
2662 .with_note(
2663 "the identity is minted from the cookie's `sub` claim (a string) — use a refined or opaque `String` type",
2664 ),
2665 ),
2666 Some(_) => {}
2667 }
2668}
2669
2670fn check_signed_cookie_route(
2675 handler: &Handler,
2676 table: &UnitTable,
2677 types: &HashMap<String, Arc<TypeDecl>>,
2678 errors: &mut Vec<CompileError>,
2679) {
2680 let Some(seam) = crate::actors::signed_cookie_seam_for(handler, &table.actors) else {
2681 return;
2682 };
2683 if let Some(p) = handler.params.iter().find(|p| p.name.name == "cookies")
2685 && let TypeRef::Named(rec) = &p.type_ref
2686 && let Some(TypeBody::Record(r)) = types.get(&rec.name).map(|d| &d.body)
2687 {
2688 for f in &r.fields {
2689 let wire = f.wire_name().unwrap_or_else(|| f.name.name.clone());
2690 if wire == seam.cookie {
2691 errors.push(
2692 CompileError::new(
2693 "bynk.actor.signed_cookie_read_directly",
2694 f.span,
2695 format!(
2696 "the field `{}` reads the session cookie `{}` that the `SignedCookie` actor `{}` consumes",
2697 f.name.name, seam.cookie, seam.actor
2698 ),
2699 )
2700 .with_note(
2701 "the signed value is verified at the boundary and never reaches the handler — read the identity from the `by` binder; the router also hides this cookie from a raw `RequestCookies` view",
2702 ),
2703 );
2704 }
2705 }
2706 }
2707 for ann in handler
2708 .annotations
2709 .iter()
2710 .filter(|a| a.name.name == "cache")
2711 {
2712 let public = ann.args.iter().any(|a| {
2713 a.label.as_ref().is_some_and(|n| n.name == "scope")
2714 && matches!(&a.value.kind, ExprKind::Ident(id) if id.name == "public")
2715 });
2716 if public {
2717 errors.push(
2718 CompileError::new(
2719 "bynk.actor.signed_cookie_public_cache",
2720 ann.span,
2721 "a `@cache(scope: public)` route is guarded by a `SignedCookie` actor, so a shared cache could replay one user's response to another",
2722 )
2723 .with_note("use `scope: private`, or drop `@cache`"),
2724 );
2725 }
2726 }
2727}
2728
2729pub(crate) fn is_caller_refinement(actor: &bynk_syntax::ast::ActorDecl, table: &UnitTable) -> bool {
2732 actor
2733 .refinement
2734 .as_ref()
2735 .is_some_and(|r| r.base.name == "Caller" && !table.actors.contains_key("Caller"))
2736}
2737
2738fn check_missing_by(handler: &Handler, protocol: &ServiceProtocol, errors: &mut Vec<CompileError>) {
2741 if crate::actors::default_actor(protocol).is_some() {
2742 return;
2743 }
2744 if matches!(protocol, ServiceProtocol::Call) {
2745 if handler.kind == HandlerKind::Call {
2747 errors.push(missing_by_on_call(handler));
2748 }
2749 return;
2750 }
2751 let (msg, note) = match protocol {
2754 ServiceProtocol::WebSocket { .. } => (
2755 "a WebSocket `on open` handler must declare its actor with a `by` clause",
2756 "the upgrade authenticates at the edge before accepting the connection — name the actor (`by user: Participant`), there is no anonymous upgrade",
2757 ),
2758 _ => (
2759 "an HTTP handler must declare its actor with a `by` clause",
2760 "HTTP has no safe default actor — a public route writes `by v: Visitor`; an authenticated route names its actor",
2761 ),
2762 };
2763 errors.push(
2764 CompileError::new("bynk.actor.missing_by_on_http", handler.span, msg).with_note(note),
2765 );
2766}
2767
2768fn given_anchor_after_by(handler: &Handler) -> Span {
2772 let ret = handler.return_type.span();
2773 match &handler.by_clause {
2774 Some(by) if by.span.start >= ret.end => by.span,
2775 _ => ret,
2776 }
2777}
2778
2779fn missing_by_on_call(handler: &Handler) -> CompileError {
2783 let at = handler.return_type.span().end;
2784 CompileError::new(
2785 "bynk.actor.missing_by_on_call",
2786 handler.span,
2787 "an `on call` handler must declare its actor with a `by` clause",
2788 )
2789 .with_note(
2790 "`by Caller` admits any context that consumes this one; a refinement or a `Foreign` actor narrows it. \
2791 Migrate a project with `bynk check --fix=bynk.actor.missing_by_on_call`",
2792 )
2793 .with_suggestion(
2794 "add `by Caller`",
2795 vec![(Span::new_in(handler.span.file, at, at), " by Caller".to_string())],
2796 Applicability::MachineApplicable,
2797 )
2798}
2799
2800fn check_foreign_secret_dupes(table: &UnitTable, errors: &mut Vec<CompileError>) {
2802 use crate::actors::Scheme;
2803 let mut by_position: Vec<&ActorDecl> = table.actors.values().collect();
2811 by_position.sort_by_key(|a| a.name.span.start);
2812 let mut secret_owner: HashMap<&str, (&str, bool)> = HashMap::new();
2813 for actor in by_position {
2814 let Some(arg) = actor.scheme_arg("secret") else {
2815 continue;
2816 };
2817 let Some(secret) = arg.value.as_str() else {
2818 continue;
2819 };
2820 let foreign = actor
2821 .auth
2822 .as_ref()
2823 .is_some_and(|au| Scheme::from_name(&au.name) == Some(Scheme::Foreign));
2824 match secret_owner.get(secret) {
2825 Some((other, other_foreign)) if foreign || *other_foreign => {
2826 errors.push(
2827 CompileError::new(
2828 "bynk.actor.foreign_duplicate_secret",
2829 arg.span,
2830 format!(
2831 "actor `{}` uses the secret `{secret}` already named by actor `{other}`, and one of them is a foreign caller",
2832 actor.name.name
2833 ),
2834 )
2835 .with_note(
2836 "a foreign caller is told apart by the secret its calls verify under, and \
2837 `bynk deploy` mints it — give it a name no other actor uses",
2838 ),
2839 );
2840 }
2841 Some(_) => {}
2842 None => {
2843 secret_owner.insert(secret, (&actor.name.name, foreign));
2844 }
2845 }
2846 }
2847}
2848
2849fn check_refinement_actor(
2853 actor: &bynk_syntax::ast::ActorDecl,
2854 table: &UnitTable,
2855 refs: &mut RefSink,
2856 errors: &mut Vec<CompileError>,
2857) {
2858 use crate::actors::{self, Scheme};
2859 if let Some(r) = &actor.refinement
2864 && is_caller_refinement(actor, table)
2865 {
2866 if let Err(span) = actors::parse_caller_predicate(&r.predicate) {
2869 errors.push(
2870 CompileError::new(
2871 "bynk.actor.refinement_predicate_unsupported",
2872 span,
2873 "a refinement over `Caller` must be `IsContext(<context>, …)`, composed with `&&`, `||`, `!`",
2874 )
2875 .with_note(
2876 "the calling context is the only thing a `Caller` carries; claims such as \
2877 `hasClaim` belong to a `Bearer` actor",
2878 ),
2879 );
2880 }
2881 return;
2882 }
2883 if let Some(r) = &actor.refinement {
2884 let base = table.actors.get(&r.base.name);
2885 let base_is_bearer = base.is_some_and(|b| {
2886 b.refinement.is_none()
2887 && b.auth.as_ref().and_then(|a| Scheme::from_name(&a.name)) == Some(Scheme::Bearer)
2888 });
2889 if base_is_bearer {
2890 refs.record(r.base.span, SymbolKind::Actor, &r.base.name);
2891 } else {
2892 errors.push(
2893 CompileError::new(
2894 "bynk.actor.refinement_base_unsupported",
2895 r.base.span,
2896 format!(
2897 "the base actor `{}` of refinement `{}` must be a declared `Bearer` actor",
2898 r.base.name, actor.name.name,
2899 ),
2900 )
2901 .with_note(
2902 "authorisation invariants test JWT claims, which only a `Bearer` actor \
2903 carries — refine a `Bearer` actor, not `None`/`Internal`/`Signature`",
2904 ),
2905 );
2906 }
2907 if let Err(span) = actors::parse_claim_predicate(&r.predicate) {
2908 errors.push(
2909 CompileError::new(
2910 "bynk.actor.refinement_predicate_unsupported",
2911 span,
2912 "a refinement predicate must be `hasClaim(\"…\")` or `claimEquals(\"…\", \"…\")`, composed with `&&`, `||`, `!`",
2913 )
2914 .with_note(
2915 "claims are untyped JSON, so the predicate vocabulary is a closed set this \
2916 slice; a general typed-claims surface is a later slice (`IsContext(…)` \
2917 belongs to a refinement over `Caller`)",
2918 ),
2919 );
2920 }
2921 }
2922}
2923
2924fn check_actor_contracts(
2925 table: &UnitTable,
2926 resolved: &ResolvedCommons,
2927 refs: &mut RefSink,
2928 errors: &mut Vec<CompileError>,
2929) {
2930 use crate::actors::Scheme;
2931
2932 for actor in table.actors.values() {
2934 refs.set_owner(&actor.name.name);
2935 if actor.refinement.is_some() {
2936 check_refinement_actor(actor, table, refs, errors);
2937 continue;
2938 }
2939 let Some(auth) = &actor.auth else {
2940 continue;
2941 };
2942 check_scheme_arg_kinds(actor, errors);
2943 match Scheme::from_name(&auth.name) {
2944 None => errors.push(
2945 CompileError::new(
2946 "bynk.actor.unknown_scheme",
2947 auth.span,
2948 format!("unknown authentication scheme `{}`", auth.name),
2949 )
2950 .with_note(
2951 "the authentication schemes are `None`, `Internal`, `Bearer`, `Signature`, `Oidc`, `Foreign`, and `SignedCookie`",
2952 ),
2953 ),
2954 Some(Scheme::Foreign) => {
2959 match actor.scheme_arg("secret") {
2960 None => errors.push(
2961 CompileError::new(
2962 "bynk.actor.foreign_missing_secret",
2963 auth.span,
2964 "a `Foreign` actor must name the secret its calls are signed with",
2965 )
2966 .with_note("write `auth = Foreign(secret = \"<ENV_NAME>\")`"),
2967 ),
2968 Some(arg) if arg.value.as_str().is_none() => errors.push(
2969 CompileError::new(
2970 "bynk.actor.foreign_secret_not_string",
2971 arg.span,
2972 "a `Foreign` actor's secret must name an env binding, as a string",
2973 )
2974 .with_note("write `auth = Foreign(secret = \"<ENV_NAME>\")`"),
2975 ),
2976 Some(arg) => {
2977 if arg.value.as_str().is_some_and(|v| {
2978 v.starts_with(crate::wire_format::EDGE_FROM_PREFIX)
2979 || v.starts_with(crate::wire_format::EDGE_TO_PREFIX)
2980 }) {
2981 errors.push(
2982 CompileError::new(
2983 "bynk.actor.foreign_reserved_secret",
2984 arg.span,
2985 "a `Foreign` actor's secret may not use a `BYNK_CALL_` edge key's name",
2986 )
2987 .with_note(
2988 "those names are the keys `bynk deploy` mints between contexts — \
2989 pick another, such as `LEGACY_CALL_KEY`",
2990 ),
2991 );
2992 }
2993 }
2994 }
2995 if crate::wire_format::is_edge_name(&actor.name.name) {
2996 errors.push(
2997 CompileError::new(
2998 "bynk.actor.foreign_name_is_context_name",
2999 actor.name.span,
3000 format!(
3001 "foreign actor `{}` is named like a context",
3002 actor.name.name
3003 ),
3004 )
3005 .with_note(
3006 "a foreign caller sends its actor's name as its caller, so it must \
3007 not read as a context's name: start it with a capital letter",
3008 ),
3009 );
3010 }
3011 let context = resolved.commons.name.joined();
3017 if !crate::wire_format::is_edge_name(&context) {
3018 errors.push(
3019 CompileError::new(
3020 "bynk.actor.foreign_context_name_unkeyable",
3021 auth.span,
3022 format!(
3023 "context `{context}` cannot admit foreign caller `{}`: no call key can be named from the context's name",
3024 actor.name.name
3025 ),
3026 )
3027 .with_note(
3028 "an edge key is named from the context's name, which must be lowercase \
3029 letters and digits in dot-separated segments, each starting with a \
3030 letter, with single underscores between runs (no `__`, no trailing `_`)",
3031 ),
3032 );
3033 }
3034 if let Some(id) = &actor.identity {
3035 errors.push(
3036 CompileError::new(
3037 "bynk.actor.foreign_identity_unsupported",
3038 id.span(),
3039 "a `Foreign` actor does not support a declared `identity`",
3040 )
3041 .with_note(
3042 "the actor is the identity: a handler tells foreign callers apart by \
3043 `match`ing its `by` sum",
3044 ),
3045 );
3046 }
3047 }
3048 Some(Scheme::Bearer) => {
3051 if actor.scheme_arg("secret").is_none() {
3052 errors.push(
3053 CompileError::new(
3054 "bynk.actor.bearer_missing_secret",
3055 auth.span,
3056 "a `Bearer` actor must name its signing secret",
3057 )
3058 .with_note(
3059 "write `auth = Bearer(secret = \"<ENV_NAME>\")` — the env var the \
3060 `Secrets` capability resolves to the JWT signing key",
3061 ),
3062 );
3063 }
3064 match &actor.identity {
3065 None => errors.push(
3066 CompileError::new(
3067 "bynk.actor.bearer_identity_not_string_constructible",
3068 auth.span,
3069 "a `Bearer` actor must declare a string-constructible `identity`",
3070 )
3071 .with_note(
3072 "the verified identity is minted from the token's `sub` claim — \
3073 declare `identity = T` where `T` is a refined or opaque `String`",
3074 ),
3075 ),
3076 Some(id) if !is_string_constructible(id, &resolved.types) => errors.push(
3077 CompileError::new(
3078 "bynk.actor.bearer_identity_not_string_constructible",
3079 id.span(),
3080 "a `Bearer` actor's identity must be string-constructible",
3081 )
3082 .with_note(
3083 "the identity is minted from the token's `sub` claim (a string) — \
3084 use a refined or opaque `String` type",
3085 ),
3086 ),
3087 Some(_) => {}
3088 }
3089 }
3090 Some(Scheme::Signature) => {
3094 if actor.scheme_arg("secret").is_none() {
3095 errors.push(
3096 CompileError::new(
3097 "bynk.actor.signature_missing_secret",
3098 auth.span,
3099 "a `Signature` actor must name its signing secret",
3100 )
3101 .with_note(
3102 "write `auth = Signature(secret = \"<ENV_NAME>\", header = \"<Header>\")`",
3103 ),
3104 );
3105 }
3106 if actor.scheme_arg("header").is_none() {
3107 errors.push(
3108 CompileError::new(
3109 "bynk.actor.signature_missing_header",
3110 auth.span,
3111 "a `Signature` actor must name the signature header",
3112 )
3113 .with_note(
3114 "write `header = \"<Header-Name>\"` — the request header carrying the HMAC",
3115 ),
3116 );
3117 }
3118 if let Some(tol) = actor.scheme_arg("tolerance")
3119 && actor.scheme_arg("timestamp").is_none()
3120 {
3121 errors.push(
3122 CompileError::new(
3123 "bynk.actor.signature_tolerance_without_timestamp",
3124 tol.span,
3125 "`tolerance` requires a `timestamp` header to check against",
3126 )
3127 .with_note("add `timestamp = \"<Header>\"`, or drop `tolerance`"),
3128 );
3129 }
3130 if let Some(id) = &actor.identity {
3131 errors.push(
3132 CompileError::new(
3133 "bynk.actor.signature_identity_unsupported",
3134 id.span(),
3135 "a `Signature` actor does not yet support a declared `identity`",
3136 )
3137 .with_note(
3138 "a signature attests authenticity, not a principal — the event is the \
3139 body param; use `by Webhook ()`",
3140 ),
3141 );
3142 }
3143 }
3144 Some(Scheme::Oidc) => {
3151 if actor.scheme_arg("issuer").is_none() {
3152 errors.push(
3153 CompileError::new(
3154 "bynk.actor.oidc_missing_issuer",
3155 auth.span,
3156 "an `Oidc` actor must name its `issuer`",
3157 )
3158 .with_note(
3159 "write `auth = Oidc(issuer = \"https://issuer.example\", audience = \"<aud>\", jwks = \"<jwks-url>\")` — \
3160 the `iss` the verified token must carry",
3161 ),
3162 );
3163 }
3164 if actor.scheme_arg("audience").is_none() {
3165 errors.push(
3166 CompileError::new(
3167 "bynk.actor.oidc_missing_audience",
3168 auth.span,
3169 "an `Oidc` actor must name its `audience`",
3170 )
3171 .with_note(
3172 "add `audience = \"<aud>\"` — the `aud` claim the token must be issued for (this API)",
3173 ),
3174 );
3175 }
3176 if actor.scheme_arg("jwks").is_none() {
3177 errors.push(
3178 CompileError::new(
3179 "bynk.actor.oidc_missing_jwks",
3180 auth.span,
3181 "an `Oidc` actor must name its `jwks` endpoint",
3182 )
3183 .with_note(
3184 "add `jwks = \"https://issuer.example/.well-known/jwks.json\"` — the public key set the verifier fetches",
3185 ),
3186 );
3187 }
3188 if let Some(arg) = actor.scheme_arg("trustFrom") {
3191 match arg.value.as_str() {
3192 None => errors.push(
3193 CompileError::new(
3194 "bynk.actor.oidc_trust_from_not_string",
3195 arg.span,
3196 "`trustFrom` names an environment variable, as a string",
3197 )
3198 .with_note(
3199 "write `trustFrom = \"MY_OIDC_TRUST\"`; when it is set, its JSON `{\"issuer\", \"jwks\", \"audience\"?}` replaces the declared trust roots",
3200 ),
3201 ),
3202 Some(name) => {
3203 let clashes = table.actors.values().any(|other| {
3204 other
3205 .scheme_arg("secret")
3206 .and_then(|a| a.value.as_str())
3207 == Some(name)
3208 });
3209 if clashes {
3210 errors.push(
3211 CompileError::new(
3212 "bynk.actor.oidc_trust_from_is_secret",
3213 arg.span,
3214 format!(
3215 "`trustFrom` names `{name}`, which an actor uses as its `secret`"
3216 ),
3217 )
3218 .with_note(
3219 "give the trust override its own environment variable: a secret is a key, not trust roots",
3220 ),
3221 );
3222 }
3223 }
3224 }
3225 }
3226 match &actor.identity {
3227 None => errors.push(
3228 CompileError::new(
3229 "bynk.actor.oidc_identity_not_string_constructible",
3230 auth.span,
3231 "an `Oidc` actor must declare a string-constructible `identity`",
3232 )
3233 .with_note(
3234 "the verified identity is minted from the token's `sub` claim — \
3235 declare `identity = T` where `T` is a refined or opaque `String`",
3236 ),
3237 ),
3238 Some(id) if !is_string_constructible(id, &resolved.types) => errors.push(
3239 CompileError::new(
3240 "bynk.actor.oidc_identity_not_string_constructible",
3241 id.span(),
3242 "an `Oidc` actor's identity must be string-constructible",
3243 )
3244 .with_note(
3245 "the identity is minted from the token's `sub` claim (a string) — \
3246 use a refined or opaque `String` type",
3247 ),
3248 ),
3249 Some(_) => {}
3250 }
3251 }
3252 Some(Scheme::SignedCookie) => {
3254 check_signed_cookie_actor(actor, auth, table, &resolved.types, errors);
3255 }
3256 Some(_) => {}
3257 }
3258 if !matches!(
3273 Scheme::from_name(actor.auth.as_ref().map(|a| a.name.as_str()).unwrap_or("")),
3274 Some(Scheme::Signature | Scheme::Foreign)
3275 ) && let Some(id) = &actor.identity
3276 {
3277 let ownable = matches!(id, TypeRef::Named(n) if
3278 resolved.is_local_type(&n.name) || resolved.is_uses_commons_type(&n.name));
3279 if !ownable {
3280 errors.push(
3281 CompileError::new(
3282 "bynk.actor.identity_not_sealed",
3283 id.span(),
3284 "an actor identity must be a context-ownable value type",
3285 )
3286 .with_note(
3287 "declare the identity as a type in this context so it is sealed — \
3288 minted only inside the context and unforgeable downstream",
3289 ),
3290 );
3291 }
3292 }
3293 }
3294
3295 check_foreign_secret_dupes(table, errors);
3296
3297 for service in table.services.values() {
3299 refs.set_owner(&service.name.name);
3300 for handler in &service.handlers {
3301 match &handler.by_clause {
3302 Some(by) => {
3303 check_by_clause_contracts(
3304 by,
3305 Some(&handler.params),
3306 &service.protocol,
3307 table,
3308 refs,
3309 errors,
3310 );
3311 check_signed_cookie_route(handler, table, &resolved.types, errors);
3312 }
3313 _ if handler.kind == HandlerKind::Rejected => {}
3316 None => check_missing_by(handler, &service.protocol, errors),
3317 }
3318 }
3319 if let Some(default_by) = &service.default_by {
3329 let inherited = service.handlers.iter().any(|h| {
3330 h.by_clause
3331 .as_ref()
3332 .is_some_and(|b| b.span == default_by.span)
3333 });
3334 if !inherited {
3335 check_by_clause_contracts(default_by, None, &service.protocol, table, refs, errors);
3336 }
3337 }
3338 }
3339}
3340
3341#[allow(clippy::too_many_arguments)]
3342fn check_service_decls(
3343 typed: &mut checker::TypedCommons,
3344 table: &UnitTable,
3345 cross_context: &resolver::CrossContextInfo,
3346 resolved: &ResolvedCommons,
3347 capability_info_map: &HashMap<String, CapabilityInfo>,
3348 refs: &mut RefSink,
3349 hints: &mut HintSink,
3350 locals: &mut LocalsSink,
3351 requirements: &mut RequirementSink,
3352 errors: &mut Vec<CompileError>,
3353 tys: &Arc<Types>,
3354) {
3355 crate::email::check_service_protocols_and_email(table, &typed.types, errors, tys);
3358
3359 check_actor_contracts(table, resolved, refs, errors);
3361
3362 check_rejected_handlers(table, errors);
3364
3365 validate_field_names(table, &typed.types, &typed.consts, errors);
3367
3368 let cf_is_std = cf_type_is_std(cross_context, table);
3369 let mut route_first_span: HashMap<(HttpMethod, String), Span> = HashMap::new();
3372 for service in table.services.values() {
3373 for handler in &service.handlers {
3374 let HandlerKind::Http { method, path } = &handler.kind else {
3375 continue;
3376 };
3377 validate_http_handler(handler, *method, path, &typed.types, cf_is_std, errors);
3378 let key = (*method, path.clone());
3379 if let Some(prev) = route_first_span.get(&key).copied() {
3380 errors.push(
3381 CompileError::new(
3382 "bynk.http.duplicate_route",
3383 handler.span,
3384 format!(
3385 "duplicate HTTP route: another handler already declares `{} {}`",
3386 method.as_str(),
3387 path,
3388 ),
3389 )
3390 .with_label(prev, "previously declared here"),
3391 );
3392 } else {
3393 route_first_span.insert(key, handler.span);
3394 }
3395 }
3396 }
3397
3398 for service in table.services.values() {
3402 let service_cap = service.limits.as_ref().and_then(|p| p.max_body());
3403 for handler in &service.handlers {
3404 validate_handler_annotations(handler, service_cap, errors);
3405 }
3406 }
3407 for agent in table.agents.values() {
3408 for handler in &agent.handlers {
3409 validate_handler_annotations(handler, None, errors);
3410 }
3411 }
3412
3413 for service in table.services.values() {
3415 validate_service_cors(service, errors);
3416 }
3417
3418 for service in table.services.values() {
3422 if let Some(policy) = &service.security {
3423 validate_security_policy(service, policy, errors);
3424 }
3425 }
3426
3427 for service in table.services.values() {
3431 if let Some(policy) = &service.limits {
3432 validate_limits_policy(service, policy, errors);
3433 }
3434 }
3435
3436 for service in table.services.values() {
3439 if let Some(policy) = &service.json {
3440 validate_json_policy(service, policy, errors);
3441 }
3442 if !matches!(service.protocol, ServiceProtocol::Http) {
3443 continue;
3444 }
3445 for handler in &service.handlers {
3446 if !matches!(handler.kind, HandlerKind::Http { .. })
3447 || effective_json_options(service.json.as_ref(), handler) != JsonOptions::Plain
3448 {
3449 continue;
3450 }
3451 let TypeRef::Effect(inner, _) = &handler.return_type else {
3452 continue;
3453 };
3454 let TypeRef::HttpResult(body, _) = inner.as_ref() else {
3455 continue;
3456 };
3457 if let Some(payload) = null_payload_option(body, &resolved.types, &mut HashSet::new()) {
3458 errors.push(
3459 CompileError::new(
3460 "bynk.json.nested_option_plain",
3461 body.span(),
3462 format!(
3463 "`Option[{payload}]`: `Some({some})` and `None` would both write `null` in plain JSON",
3464 some = if payload == "()" { "()" } else { "…" },
3465 ),
3466 )
3467 .with_note(
3468 "an `Option` payload that can itself be `null` (`Option[T]` or `()`) is ambiguous; model it as a sum type, or keep this route tagged with `@json(options: tagged)`",
3469 ),
3470 );
3471 }
3472 }
3473 }
3474
3475 let mut schedule_first_span: HashMap<String, Span> = HashMap::new();
3480 for service in table.services.values() {
3481 for handler in &service.handlers {
3482 let HandlerKind::Cron { expr } = &handler.kind else {
3483 continue;
3484 };
3485 validate_cron_handler(handler, expr, errors);
3486 if let Some(prev) = schedule_first_span.get(expr).copied() {
3487 errors.push(
3488 CompileError::new(
3489 "bynk.cron.duplicate_schedule",
3490 handler.span,
3491 format!(
3492 "duplicate cron schedule: another handler already declares `{expr}`",
3493 ),
3494 )
3495 .with_label(prev, "previously declared here"),
3496 );
3497 } else {
3498 schedule_first_span.insert(expr.clone(), handler.span);
3499 }
3500 }
3501 }
3502
3503 let mut consumer_first_span: HashMap<String, Span> = HashMap::new();
3508 for service in table.services.values() {
3509 let ServiceProtocol::Queue { name } = &service.protocol else {
3510 continue;
3511 };
3512 for handler in &service.handlers {
3513 if !matches!(handler.kind, HandlerKind::Message) {
3514 continue;
3515 }
3516 validate_queue_handler(handler, name, errors);
3517 if let Some(prev) = consumer_first_span.get(name).copied() {
3518 errors.push(
3519 CompileError::new(
3520 "bynk.queue.duplicate_consumer",
3521 handler.span,
3522 format!(
3523 "duplicate queue consumer: another handler already consumes `{name}`",
3524 ),
3525 )
3526 .with_label(prev, "previously declared here"),
3527 );
3528 } else {
3529 consumer_first_span.insert(name.clone(), handler.span);
3530 }
3531 }
3532 }
3533
3534 for service in table.services.values() {
3536 refs.set_owner(&service.name.name);
3537 for handler in &service.handlers {
3538 let mut handler_caps: HashMap<String, CapabilityInfo> = HashMap::new();
3541 for cap_ref in &handler.given {
3542 if let Some(info) =
3543 resolve_given_cap_ref(cap_ref, capability_info_map, cross_context, errors, refs)
3544 {
3545 handler_caps.insert(cap_ref.key().to_string(), info);
3546 }
3547 }
3548 if !matches!(handler.return_type, TypeRef::Effect(_, _)) {
3550 errors.push(CompileError::new(
3551 "bynk.service.return_not_effect",
3552 handler.return_type.span(),
3553 format!(
3554 "service handler must return `Effect[T]`, but got `{}`",
3555 ts_type_ref_display(&handler.return_type)
3556 ),
3557 ));
3558 }
3559 let actor_binding =
3561 handler_actor_binding(handler, &service.protocol, table, resolved, tys);
3562 if let Some((binder, ty)) = &actor_binding {
3567 typed
3568 .actor_bindings
3569 .insert(handler.span, (binder.clone(), *ty));
3570 }
3571 let is_ws_lifecycle = matches!(
3583 (&handler.kind, &service.protocol),
3584 (
3585 HandlerKind::Open | HandlerKind::Message | HandlerKind::Close,
3586 ServiceProtocol::WebSocket { .. }
3587 )
3588 );
3589 let params_for_check: Vec<Param> = match (&handler.kind, &service.protocol) {
3590 (
3591 HandlerKind::Open | HandlerKind::Message | HandlerKind::Close,
3592 ServiceProtocol::WebSocket { out_type, .. },
3593 ) => {
3594 let mut ps = vec![open_connection_param(out_type, handler.span)];
3595 ps.extend(handler.params.iter().cloned());
3596 ps
3597 }
3598 _ => handler.params.clone(),
3599 };
3600 let borrowed_held: std::collections::HashSet<String> = if is_ws_lifecycle
3603 && matches!(handler.kind, HandlerKind::Message | HandlerKind::Close)
3604 {
3605 std::iter::once("connection".to_string()).collect()
3606 } else {
3607 std::collections::HashSet::new()
3608 };
3609 checker::check_handler_body(
3610 resolved,
3611 checker::HandlerBodyCheck {
3612 capabilities: handler_caps,
3613 declared_capabilities: capability_info_map.clone(),
3614 given_anchor: Some(given_anchor_after_by(handler)),
3615 report_unused: true,
3616 actor_binding,
3617 borrowed_held,
3618 oidc_binder: crate::actors::oidc_seam_for(handler, &table.actors)
3619 .and_then(|seam| seam.binder),
3620 service_handler: !is_ws_lifecycle,
3623 ..checker::HandlerBodyCheck::new(
3624 &handler.body,
3625 &handler.return_type,
3626 ¶ms_for_check,
3627 &handler.given,
3628 )
3629 },
3630 checker::CheckSinks {
3631 tys,
3632 expr_types: &mut typed.expr_types,
3633 errors,
3634 refs,
3635 hints,
3636 locals,
3637 requirements,
3638 callees: &mut typed.callees,
3639 },
3640 );
3641 }
3642 if let Some(first) = service.default_given.first() {
3651 let inherited = service
3652 .handlers
3653 .iter()
3654 .any(|h| h.given.first().is_some_and(|g| g.span == first.span));
3655 if !inherited {
3656 for cap_ref in &service.default_given {
3657 let _ = resolve_given_cap_ref(
3658 cap_ref,
3659 capability_info_map,
3660 cross_context,
3661 errors,
3662 refs,
3663 );
3664 }
3665 }
3666 }
3667 }
3668}
3669
3670fn open_connection_param(out_type: &TypeRef, span: Span) -> Param {
3674 Param {
3675 name: Ident {
3676 name: "connection".to_string(),
3677 span,
3678 },
3679 type_ref: TypeRef::Connection(Box::new(out_type.clone()), span),
3680 span,
3681 }
3682}
3683
3684fn handler_actor_binding(
3691 handler: &Handler,
3692 _protocol: &ServiceProtocol,
3693 table: &UnitTable,
3694 resolved: &ResolvedCommons,
3695 tys: &Arc<Types>,
3696) -> Option<(String, checker::TyId)> {
3697 let by = handler.by_clause.as_ref()?;
3698 let binder = by.binder.as_ref()?;
3700 if handler.params.iter().any(|p| p.name.name == binder.name) {
3704 return None;
3705 }
3706 let binder_ty = if by.is_sum() {
3709 tys.intern(checker::Ty::ActorSum(
3710 by.actors
3711 .iter()
3712 .map(|a| {
3713 (
3714 a.name.clone(),
3715 actor_identity_ty(&a.name, table, resolved, tys),
3716 )
3717 })
3718 .collect(),
3719 ))
3720 } else {
3721 tys.intern(checker::Ty::Actor(actor_identity_ty(
3722 &by.primary().name,
3723 table,
3724 resolved,
3725 tys,
3726 )))
3727 };
3728 Some((binder.name.clone(), binder_ty))
3729}
3730
3731fn actor_identity_ty(
3734 actor_name: &str,
3735 table: &UnitTable,
3736 resolved: &ResolvedCommons,
3737 tys: &Arc<Types>,
3738) -> checker::TyId {
3739 actor_identity_ty_guarded(actor_name, table, resolved, &mut Vec::new(), tys)
3740}
3741
3742fn actor_identity_ty_guarded<'a>(
3750 actor_name: &'a str,
3751 table: &'a UnitTable,
3752 resolved: &ResolvedCommons,
3753 seen: &mut Vec<&'a str>,
3754 tys: &Arc<Types>,
3755) -> checker::TyId {
3756 use crate::actors::{Identity, prelude_actor};
3757 if let Some(local) = table.actors.get(actor_name) {
3758 if let Some(r) = &local.refinement {
3761 if seen.contains(&actor_name) {
3762 return tys.intern(checker::Ty::Unit);
3763 }
3764 seen.push(actor_name);
3765 if let Some((key, _)) = table.actors.get_key_value(&r.base.name) {
3768 return actor_identity_ty_guarded(key.as_str(), table, resolved, seen, tys);
3769 }
3770 if is_caller_refinement(local, table) {
3772 return tys.intern(checker::Ty::Base(bynk_syntax::ast::BaseType::String));
3773 }
3774 return tys.intern(checker::Ty::Unit);
3775 }
3776 return match &local.identity {
3777 Some(id) => checker::resolve_type_ref(id, &resolved.types, tys)
3778 .unwrap_or_else(|| tys.intern(checker::Ty::Unit)),
3779 None => tys.intern(checker::Ty::Unit),
3780 };
3781 }
3782 match prelude_actor(actor_name).map(|c| c.identity) {
3783 Some(Identity::CallerId) => {
3784 tys.intern(checker::Ty::Base(bynk_syntax::ast::BaseType::String))
3785 }
3786 Some(Identity::Declared(name)) => checker::resolve_type_ref(
3792 &bynk_syntax::ast::TypeRef::Named(bynk_syntax::ast::Ident {
3793 name,
3794 span: bynk_syntax::span::Span::default(),
3795 }),
3796 &resolved.types,
3797 tys,
3798 )
3799 .unwrap_or_else(|| tys.intern(checker::Ty::Unit)),
3800 _ => tys.intern(checker::Ty::Unit),
3801 }
3802}
3803
3804const STORAGE_KINDS: &[&str] = &["Cell", "Map", "Set", "Log", "Queue", "Cache"];
3808
3809struct AnnotationSpec {
3815 name: &'static str,
3816 kinds: &'static [&'static str],
3817 functional: bool,
3818}
3819
3820const ANNOTATIONS: &[AnnotationSpec] = &[
3821 AnnotationSpec {
3822 name: "ttl",
3823 kinds: &["Cache"],
3824 functional: true,
3825 },
3826 AnnotationSpec {
3827 name: "retain",
3828 kinds: &["Log"],
3829 functional: true,
3830 },
3831 AnnotationSpec {
3832 name: "indexed",
3833 kinds: &["Map"],
3834 functional: true,
3835 },
3836 AnnotationSpec {
3837 name: "bounded",
3838 kinds: &["Queue", "Log"],
3839 functional: false,
3840 },
3841];
3842
3843fn validate_store_annotations(
3849 f: &StoreField,
3850 head: &str,
3851 types: &HashMap<String, Arc<TypeDecl>>,
3852 errors: &mut Vec<CompileError>,
3853) {
3854 for ann in &f.annotations {
3855 let name = ann.name.name.as_str();
3856 let Some(spec) = ANNOTATIONS.iter().find(|s| s.name == name) else {
3857 errors.push(
3858 CompileError::new(
3859 "bynk.store.unknown_annotation",
3860 ann.name.span,
3861 format!(
3862 "unknown storage annotation `@{name}` — expected one of {}",
3863 ANNOTATIONS
3864 .iter()
3865 .map(|s| format!("@{}", s.name))
3866 .collect::<Vec<_>>()
3867 .join(", ")
3868 ),
3869 )
3870 .with_note("storage annotations are a closed set (ADR 0111)"),
3871 );
3872 continue;
3873 };
3874 if !spec.kinds.contains(&head) {
3875 errors.push(CompileError::new(
3876 "bynk.store.annotation_kind_mismatch",
3877 ann.span,
3878 format!(
3879 "`@{name}` applies to {}, not `{head}`",
3880 spec.kinds
3881 .iter()
3882 .map(|k| format!("`{k}`"))
3883 .collect::<Vec<_>>()
3884 .join("/")
3885 ),
3886 ));
3887 continue;
3888 }
3889 if !spec.functional {
3890 errors.push(
3891 CompileError::new(
3892 "bynk.store.annotation_unsupported",
3893 ann.span,
3894 format!("`@{name}` is recognised but has no effect yet"),
3895 )
3896 .with_note(if head == "Log" {
3897 "leave the annotation off; to limit a `Log`, use `@retain`, which drops \
3898 entries older than a period"
3899 } else {
3900 "leave the annotation off"
3901 }),
3902 );
3903 continue;
3904 }
3905 if name == "indexed" {
3909 validate_indexed_keys(f, types, ann, errors);
3910 }
3911 }
3912}
3913
3914fn validate_indexed_keys(
3919 f: &StoreField,
3920 types: &HashMap<String, Arc<TypeDecl>>,
3921 ann: &Annotation,
3922 errors: &mut Vec<CompileError>,
3923) {
3924 let value_fields: Option<&[RecordField]> = f
3926 .kind
3927 .args
3928 .get(1)
3929 .and_then(|v| match v {
3930 TypeRef::Named(id) => types.get(&id.name),
3931 _ => None,
3932 })
3933 .and_then(|decl| match &decl.body {
3934 TypeBody::Record(r) => Some(r.fields.as_slice()),
3935 _ => None,
3936 });
3937 for arg in &ann.args {
3938 let Some(label) = &arg.label else {
3940 errors.push(CompileError::new(
3941 "bynk.index.bad_argument",
3942 arg.span,
3943 "`@indexed` arguments are `by: <field>` labels naming a field to index on",
3944 ));
3945 continue;
3946 };
3947 if label.name != "by" {
3948 errors.push(CompileError::new(
3949 "bynk.index.bad_argument",
3950 arg.span,
3951 format!("`@indexed` takes `by:` arguments, not `{}:`", label.name),
3952 ));
3953 continue;
3954 }
3955 let ExprKind::Ident(key) = &arg.value.kind else {
3956 errors.push(CompileError::new(
3957 "bynk.index.bad_argument",
3958 arg.value.span,
3959 "`@indexed(by: …)` names a field of the map's value type",
3960 ));
3961 continue;
3962 };
3963 match value_fields.and_then(|fs| fs.iter().find(|rf| rf.name.name == key.name)) {
3965 None => {
3966 errors.push(CompileError::new(
3967 "bynk.index.unknown_key",
3968 arg.value.span,
3969 format!(
3970 "`@indexed(by: {0})` — the map's value type has no field `{0}`",
3971 key.name
3972 ),
3973 ));
3974 }
3975 Some(field) if !type_ref_is_keyable(&field.type_ref, types) => {
3976 errors.push(
3977 CompileError::new(
3978 "bynk.index.unkeyable_key",
3979 arg.value.span,
3980 format!(
3981 "`@indexed(by: {0})` — field `{0}` is not value-keyable; an index key must be `Int`, `String`, or a refined/opaque type over them",
3982 key.name
3983 ),
3984 ),
3985 );
3986 }
3987 Some(_) => {}
3988 }
3989 }
3990}
3991
3992fn check_store_keyable(
4000 t: &TypeRef,
4001 what: &str,
4002 types: &HashMap<String, Arc<TypeDecl>>,
4003 errors: &mut Vec<CompileError>,
4004) {
4005 if let TypeRef::Named(id) = t
4006 && !types.contains_key(&id.name)
4007 {
4008 return;
4009 }
4010 if !type_ref_is_keyable(t, types) {
4011 errors.push(
4012 CompileError::new(
4013 "bynk.store.unkeyable_key",
4014 t.span(),
4015 format!(
4016 "{what} must be value-keyable — `String`, `Int`, or a refined/opaque type over them"
4017 ),
4018 )
4019 .with_note(
4020 "only `String` and `Int` keys (or a refined or opaque type over them) are supported, matching value `Map` keys and `@indexed` fields; key a record by one of its id fields, and an enum by its name as a `String`",
4021 ),
4022 );
4023 }
4024}
4025
4026fn type_ref_is_keyable(t: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
4029 match t {
4030 TypeRef::Base(BaseType::Int | BaseType::String, _) => true,
4031 TypeRef::Named(id) => matches!(
4032 types.get(&id.name).map(|d| &d.body),
4033 Some(TypeBody::Refined { base, .. } | TypeBody::Opaque { base, .. })
4034 if matches!(base, BaseType::Int | BaseType::String)
4035 ),
4036 _ => false,
4037 }
4038}
4039
4040fn validate_index_hygiene(
4052 agent: &AgentDecl,
4053 types: &HashMap<String, Arc<TypeDecl>>,
4054 errors: &mut Vec<CompileError>,
4055) {
4056 let mut store_maps: HashSet<String> = HashSet::new();
4057 let mut declared: HashMap<String, Vec<(String, Span)>> = HashMap::new();
4059 let mut value_fields: HashMap<String, Vec<RecordField>> = HashMap::new();
4061 for f in &agent.store_fields {
4062 if f.kind.head.name != "Map" || f.kind.args.len() != 2 {
4063 continue;
4064 }
4065 store_maps.insert(f.name.name.clone());
4066 if let Some(TypeBody::Record(r)) = f
4067 .kind
4068 .args
4069 .get(1)
4070 .and_then(|v| match v {
4071 TypeRef::Named(id) => types.get(&id.name),
4072 _ => None,
4073 })
4074 .map(|d| &d.body)
4075 {
4076 value_fields.insert(f.name.name.clone(), r.fields.clone());
4077 }
4078 for an in f.annotations.iter().filter(|a| a.name.name == "indexed") {
4079 for arg in &an.args {
4080 if arg.label.as_ref().map(|l| l.name.as_str()) == Some("by")
4081 && let ExprKind::Ident(k) = &arg.value.kind
4082 {
4083 declared
4084 .entry(f.name.name.clone())
4085 .or_default()
4086 .push((k.name.clone(), arg.value.span));
4087 }
4088 }
4089 }
4090 }
4091 if store_maps.is_empty() {
4092 return;
4093 }
4094 let mut used: HashSet<(String, String)> = HashSet::new();
4098 let mut missing_seen: HashSet<(String, String)> = HashSet::new();
4099 for h in &agent.handlers {
4100 walk_block_for_index_filters(&h.body, &store_maps, &mut |map, field, span| {
4101 used.insert((map.to_string(), field.to_string()));
4102 let is_declared = declared
4103 .get(map)
4104 .is_some_and(|v| v.iter().any(|(f, _)| f == field));
4105 if is_declared {
4106 return;
4107 }
4108 let keyable = value_fields.get(map).is_some_and(|fs| {
4109 fs.iter()
4110 .any(|rf| rf.name.name == field && type_ref_is_keyable(&rf.type_ref, types))
4111 });
4112 if keyable && missing_seen.insert((map.to_string(), field.to_string())) {
4113 errors.push(
4114 CompileError::new(
4115 "bynk.index.missing",
4116 span,
4117 format!(
4118 "a query filters `{map}` by equality on `{field}`, which is not indexed — add `@indexed(by: {field})` to route this lookup through an index instead of a scan"
4119 ),
4120 )
4121 .with_note("a perf hint, not an error — the scan still compiles and runs"),
4122 );
4123 }
4124 });
4125 }
4126 for (map, fields) in &declared {
4128 for (field, span) in fields {
4129 if !used.contains(&(map.clone(), field.clone())) {
4130 errors.push(
4131 CompileError::new(
4132 "bynk.index.unused",
4133 *span,
4134 format!(
4135 "`@indexed(by: {field})` on `{map}` is never used — no query filters `{map}` by equality on `{field}`, yet the index is maintained on every write"
4136 ),
4137 )
4138 .with_note("remove it, or add a query that filters by equality on this field"),
4139 );
4140 }
4141 }
4142 }
4143}
4144
4145fn routable_eq_filter<'a>(
4149 store_maps: &HashSet<String>,
4150 e: &'a Expr,
4151) -> Option<(&'a str, &'a str, Span)> {
4152 let ExprKind::MethodCall {
4153 receiver,
4154 method,
4155 args,
4156 ..
4157 } = &e.kind
4158 else {
4159 return None;
4160 };
4161 if method.name != "filter" {
4162 return None;
4163 }
4164 let ExprKind::Ident(map) = &receiver.kind else {
4165 return None;
4166 };
4167 if !store_maps.contains(&map.name) {
4168 return None;
4169 }
4170 let [arg] = args.as_slice() else {
4171 return None;
4172 };
4173 let ExprKind::Lambda(lam) = &arg.kind else {
4174 return None;
4175 };
4176 let [param] = lam.params.as_slice() else {
4177 return None;
4178 };
4179 let pname = param.name.name.as_str();
4180 let ExprKind::BinOp(BinOp::Eq, lhs, rhs) = &lam.body.kind else {
4181 return None;
4182 };
4183 let field_of = |x: &'a Expr| -> Option<&'a str> {
4184 if let ExprKind::FieldAccess { receiver, field } = &x.kind
4185 && let ExprKind::Ident(r) = &receiver.kind
4186 && r.name == pname
4187 {
4188 Some(field.name.as_str())
4189 } else {
4190 None
4191 }
4192 };
4193 let field = field_of(lhs).or_else(|| field_of(rhs))?;
4194 Some((map.name.as_str(), field, e.span))
4195}
4196
4197fn walk_block_for_index_filters(
4200 block: &Block,
4201 store_maps: &HashSet<String>,
4202 cb: &mut dyn FnMut(&str, &str, Span),
4203) {
4204 let mut exprs = Vec::new();
4205 for stmt in &block.statements {
4206 statement_exprs(stmt, &mut exprs);
4207 }
4208 exprs.push(&block.tail);
4209 for e in exprs {
4210 walk_expr_for_index_filters(e, store_maps, cb);
4211 }
4212}
4213
4214fn walk_expr_for_index_filters(
4219 e: &Expr,
4220 store_maps: &HashSet<String>,
4221 cb: &mut dyn FnMut(&str, &str, Span),
4222) {
4223 if let Some((map, field, span)) = routable_eq_filter(store_maps, e) {
4224 cb(map, field, span);
4225 }
4226 for child in expr_children(e) {
4227 walk_expr_for_index_filters(child, store_maps, cb);
4228 }
4229}
4230
4231#[allow(clippy::type_complexity)]
4236fn store_field_scopes(
4237 agent: &AgentDecl,
4238 types: &HashMap<String, Arc<TypeDecl>>,
4239 no_vars: &HashSet<String>,
4240 refs: &mut RefSink,
4241 errors: &mut Vec<CompileError>,
4242 tys: &Arc<Types>,
4243) -> (
4244 HashMap<String, TyId>,
4245 HashMap<String, (TyId, TyId)>,
4246 HashMap<String, TyId>,
4247 HashMap<String, (TyId, TyId, i64)>,
4248 HashMap<String, TyId>,
4249) {
4250 let mut cells: HashMap<String, TyId> = HashMap::new();
4251 let mut maps: HashMap<String, (TyId, TyId)> = HashMap::new();
4252 let mut sets: HashMap<String, TyId> = HashMap::new();
4253 let mut caches: HashMap<String, (TyId, TyId, i64)> = HashMap::new();
4254 let mut logs: HashMap<String, TyId> = HashMap::new();
4255 let arity_err = |f: &StoreField, kind: &str, want: usize, errors: &mut Vec<CompileError>| {
4256 errors.push(CompileError::new(
4257 "bynk.store.kind_arity",
4258 f.kind.span,
4259 format!(
4260 "`{kind}` takes exactly {want} type argument(s), found {}",
4261 f.kind.args.len()
4262 ),
4263 ));
4264 };
4265 for f in &agent.store_fields {
4266 let head = f.kind.head.name.as_str();
4267 if !STORAGE_KINDS.contains(&head) {
4268 errors.push(
4269 CompileError::new(
4270 "bynk.store.unknown_kind",
4271 f.kind.head.span,
4272 format!(
4273 "unknown storage kind `{head}` — expected one of {}",
4274 STORAGE_KINDS.join(", ")
4275 ),
4276 )
4277 .with_note("a `store` field's type is a storage kind, not an ordinary type"),
4278 );
4279 continue;
4280 }
4281 validate_store_annotations(f, head, types, errors);
4283 match head {
4284 "Cell" => {
4285 if f.kind.args.len() != 1 {
4286 arity_err(f, "Cell", 1, errors);
4287 continue;
4288 }
4289 let elem = &f.kind.args[0];
4290 checker::record_type_refs(elem, types, no_vars, refs);
4291 if let Some(ty) = checker::resolve_type_ref(elem, types, tys) {
4292 cells.insert(f.name.name.clone(), ty);
4293 }
4294 }
4295 "Map" => {
4296 if f.kind.args.len() != 2 {
4297 arity_err(f, "Map", 2, errors);
4298 continue;
4299 }
4300 checker::record_type_refs(&f.kind.args[0], types, no_vars, refs);
4301 checker::record_type_refs(&f.kind.args[1], types, no_vars, refs);
4302 check_store_keyable(&f.kind.args[0], "a `Map` key", types, errors);
4303 if let (Some(k), Some(v)) = (
4304 checker::resolve_type_ref(&f.kind.args[0], types, tys),
4305 checker::resolve_type_ref(&f.kind.args[1], types, tys),
4306 ) {
4307 maps.insert(f.name.name.clone(), (k, v));
4308 }
4309 }
4310 "Set" => {
4311 if f.kind.args.len() != 1 {
4312 arity_err(f, "Set", 1, errors);
4313 continue;
4314 }
4315 let elem = &f.kind.args[0];
4316 checker::record_type_refs(elem, types, no_vars, refs);
4317 check_store_keyable(elem, "a `Set` element", types, errors);
4318 if let Some(ty) = checker::resolve_type_ref(elem, types, tys) {
4319 sets.insert(f.name.name.clone(), ty);
4320 }
4321 }
4322 "Cache" => {
4324 if f.kind.args.len() != 2 {
4325 arity_err(f, "Cache", 2, errors);
4326 continue;
4327 }
4328 checker::record_type_refs(&f.kind.args[0], types, no_vars, refs);
4329 checker::record_type_refs(&f.kind.args[1], types, no_vars, refs);
4330 check_store_keyable(&f.kind.args[0], "a `Cache` key", types, errors);
4331 let ttl = cache_ttl_millis(f, errors);
4334 if let (Some(k), Some(v), Some(ttl)) = (
4335 checker::resolve_type_ref(&f.kind.args[0], types, tys),
4336 checker::resolve_type_ref(&f.kind.args[1], types, tys),
4337 ttl,
4338 ) {
4339 caches.insert(f.name.name.clone(), (k, v, ttl));
4340 }
4341 }
4342 "Log" => {
4346 if f.kind.args.len() != 1 {
4347 arity_err(f, "Log", 1, errors);
4348 continue;
4349 }
4350 let elem = &f.kind.args[0];
4351 checker::record_type_refs(elem, types, no_vars, refs);
4352 if let Some(t) = checker::resolve_type_ref(elem, types, tys) {
4353 logs.insert(f.name.name.clone(), t);
4354 }
4355 }
4356 other => {
4357 errors.push(
4358 CompileError::new(
4359 "bynk.store.kind_unsupported",
4360 f.kind.head.span,
4361 format!(
4362 "storage kind `{other}` is not yet supported — use `Cell`, `Map`, \
4363 `Set`, `Cache` or `Log`"
4364 ),
4365 )
4366 .with_note("`Queue` is the one storage kind with no implementation yet"),
4367 );
4368 }
4369 }
4370 }
4371 (cells, maps, sets, caches, logs)
4372}
4373
4374fn cache_ttl_millis(f: &StoreField, errors: &mut Vec<CompileError>) -> Option<i64> {
4384 let ttl = f.annotations.iter().find(|a| a.name.name == "ttl");
4385 let Some(ttl) = ttl else {
4386 errors.push(
4387 CompileError::new(
4388 "bynk.store.cache_ttl_required",
4389 f.kind.span,
4390 "a `Cache` field requires a `@ttl(<duration>)` annotation — its entry lifetime",
4391 )
4392 .with_note("a keyed store with no expiry is a `Map`, not a `Cache`"),
4393 );
4394 return None;
4395 };
4396 match ttl.args.first().map(|a| &a.value.kind) {
4397 Some(ExprKind::DurationLit { millis, .. }) => Some(*millis),
4398 _ => {
4399 let span = ttl.args.first().map_or(ttl.span, |a| a.span);
4400 errors.push(
4401 CompileError::new(
4402 "bynk.store.cache_ttl_required",
4403 span,
4404 "`@ttl`'s argument must be a duration literal, e.g. `5.minutes`, or a `Duration` constant bound to one",
4405 )
4406 .with_note("a keyed store with no expiry is a `Map`, not a `Cache`"),
4407 );
4408 None
4409 }
4410 }
4411}
4412
4413#[allow(clippy::too_many_arguments)]
4414fn check_agent_decls(
4415 typed: &mut checker::TypedCommons,
4416 table: &UnitTable,
4417 cross_context: &resolver::CrossContextInfo,
4418 is_context: bool,
4419 uses_commons_type_names: &HashSet<String>,
4420 capability_info_map: &HashMap<String, CapabilityInfo>,
4421 no_vars: &HashSet<String>,
4422 refs: &mut RefSink,
4423 hints: &mut HintSink,
4424 locals: &mut LocalsSink,
4425 requirements: &mut RequirementSink,
4426 errors: &mut Vec<CompileError>,
4427 tys: &Arc<Types>,
4428) {
4429 for agent in table.agents.values() {
4430 refs.set_owner(&agent.name.name);
4431 #[allow(clippy::type_complexity)]
4438 let (store_cells, store_maps, store_sets, store_caches, store_logs): (
4439 HashMap<String, TyId>,
4440 HashMap<String, (TyId, TyId)>,
4441 HashMap<String, TyId>,
4442 HashMap<String, (TyId, TyId, i64)>,
4443 HashMap<String, TyId>,
4444 ) = if agent.store_fields.is_empty() {
4445 (
4446 HashMap::new(),
4447 HashMap::new(),
4448 HashMap::new(),
4449 HashMap::new(),
4450 HashMap::new(),
4451 )
4452 } else {
4453 store_field_scopes(agent, &typed.types, no_vars, refs, errors, tys)
4454 };
4455 validate_index_hygiene(agent, &typed.types, errors);
4458 checker::record_type_refs(&agent.key_type, &typed.types, no_vars, refs);
4460 for field in &agent.store_fields {
4461 for arg in &field.kind.args {
4462 checker::record_type_refs(arg, &typed.types, no_vars, refs);
4463 }
4464 }
4465 let agent_state_name = format!("{}State", agent.name.name);
4469 if let Some(user) = table.types.get(&agent_state_name) {
4474 errors.push(
4475 CompileError::new(
4476 "bynk.agent.state_name_conflict",
4477 user.name.span,
4478 format!(
4479 "type `{agent_state_name}` has the name of agent `{}`'s state record",
4480 agent.name.name
4481 ),
4482 )
4483 .with_note(format!(
4484 "inside `{}`'s handlers, `{agent_state_name}` is the record of its `Cell` fields, so this type would be replaced there; rename it",
4485 agent.name.name
4486 )),
4487 );
4488 }
4489 let state_record_fields: Vec<RecordField> = agent
4490 .store_fields
4491 .iter()
4492 .filter(|f| f.kind.head.name == "Cell" && f.kind.args.len() == 1)
4493 .map(|f| RecordField {
4494 annotations: Vec::new(),
4495 documentation: None,
4496 trivia: Default::default(),
4497 name: f.name.clone(),
4498 type_ref: f.kind.args[0].clone(),
4499 refinement: None,
4500 init: f.init.clone(),
4501 span: f.span,
4502 })
4503 .collect();
4504 let synthetic_state = TypeDecl {
4507 derives: Vec::new(),
4508 derives_kw: None,
4509 name: Ident {
4510 name: agent_state_name.clone(),
4511 span: agent.span,
4512 },
4513 type_params: Vec::new(),
4514 body: TypeBody::Record(RecordBody {
4515 trailing_comments: Default::default(),
4516 fields: state_record_fields,
4517 span: agent.span,
4518 }),
4519 documentation: None,
4520 span: agent.span,
4521 trivia: Trivia::default(),
4522 private: None,
4523 };
4524 let mut types_for_handler = typed.types.clone();
4525 types_for_handler.insert(agent_state_name.clone(), Arc::new(synthetic_state.clone()));
4526 let resolved_for_handler = ResolvedCommons::new(
4533 typed.commons.clone(),
4534 types_for_handler,
4535 &table.types,
4536 typed.fns.clone(),
4537 typed.methods.clone(),
4538 table.agents.clone(),
4539 &table.events,
4540 cross_context.clone(),
4541 HashMap::new(),
4542 is_context,
4543 uses_commons_type_names.clone(),
4544 )
4545 .with_local_fns(&table.fns)
4546 .with_assets(typed.assets.clone())
4548 .with_embeds(typed.embeds.clone())
4549 .with_consts(typed.consts.clone())
4550 .with_shadowed_imports(typed.shadowed_imports.clone())
4551 .with_scope_facts_of(typed)
4552 .with_stability(typed.stability.clone());
4553 for field in &agent.store_fields {
4558 if field.kind.head.name != "Cell" || field.kind.args.len() != 1 {
4559 continue; }
4561 let elem = &field.kind.args[0];
4562 if let Some(init) = &field.init {
4563 checker::check_state_initialiser(
4564 init,
4565 elem,
4566 &resolved_for_handler,
4567 tys,
4568 &mut typed.expr_types,
4569 &mut typed.callees,
4570 errors,
4571 refs,
4572 hints,
4573 locals,
4574 );
4575 } else if !checker::is_zeroable(elem, None, &typed.types) {
4576 errors.push(
4577 CompileError::new(
4578 "bynk.agents.non_zeroable_state_field",
4579 field.span,
4580 format!(
4581 "agent `{}` store cell `{}` has no defined zero value, so a fresh \
4582 key cannot be initialised",
4583 agent.name.name, field.name.name
4584 ),
4585 )
4586 .with_note(
4587 "add an initialiser (`store name: Cell[T] = value`), or use \
4588 `Cell[Option[…]]` (None means \"never set\")",
4589 ),
4590 );
4591 }
4592 }
4593 let state_ty = tys.intern(Ty::Named {
4594 name: agent_state_name.clone(),
4595 kind: checker::NamedKind::Record,
4596 args: Vec::new(),
4597 });
4598 let key_ty = checker::resolve_type_ref(&agent.key_type, &typed.types, tys)
4599 .unwrap_or_else(|| tys.intern(Ty::Unit));
4600 let mut self_scope: HashMap<String, TyId> = HashMap::new();
4601 let agent_self_name = format!("__{}Self", agent.name.name);
4605 let self_decl = TypeDecl {
4606 derives: Vec::new(),
4607 derives_kw: None,
4608 name: Ident {
4609 name: agent_self_name.clone(),
4610 span: agent.span,
4611 },
4612 type_params: Vec::new(),
4613 body: TypeBody::Record(RecordBody {
4614 trailing_comments: Default::default(),
4615 fields: vec![RecordField {
4616 annotations: Vec::new(),
4617 documentation: None,
4618 trivia: Default::default(),
4619 name: Ident {
4620 name: agent.key_name.name.clone(),
4621 span: agent.key_name.span,
4622 },
4623 type_ref: agent.key_type.clone(),
4624 refinement: None,
4625 init: None,
4626 span: agent.key_name.span,
4627 }],
4628 span: agent.span,
4629 }),
4630 documentation: None,
4631 span: agent.span,
4632 trivia: Trivia::default(),
4633 private: None,
4634 };
4635 let mut types_for_handler = resolved_for_handler.types.clone();
4636 types_for_handler.insert(agent_self_name.clone(), Arc::new(self_decl.clone()));
4637 let resolved_for_handler = ResolvedCommons::new(
4641 typed.commons.clone(),
4642 types_for_handler,
4643 &table.types,
4644 typed.fns.clone(),
4645 typed.methods.clone(),
4646 table.agents.clone(),
4647 &table.events,
4648 cross_context.clone(),
4649 HashMap::new(),
4650 is_context,
4651 uses_commons_type_names.clone(),
4652 )
4653 .with_local_fns(&table.fns)
4654 .with_assets(typed.assets.clone())
4656 .with_embeds(typed.embeds.clone())
4657 .with_consts(typed.consts.clone())
4658 .with_shadowed_imports(typed.shadowed_imports.clone())
4659 .with_scope_facts_of(typed)
4660 .with_stability(typed.stability.clone());
4661 self_scope.insert(
4662 "self".to_string(),
4663 tys.intern(Ty::Named {
4664 name: agent_self_name.clone(),
4665 kind: checker::NamedKind::Record,
4666 args: Vec::new(),
4667 }),
4668 );
4669 for (name, ty) in &store_cells {
4673 self_scope.insert(name.clone(), *ty);
4674 }
4675 let _ = key_ty;
4676
4677 let store_fields: HashMap<String, checker::StoreField> = store_cells
4681 .iter()
4682 .map(|(name, t)| (name.clone(), checker::StoreField::Cell(*t)))
4683 .chain(
4684 store_maps
4685 .iter()
4686 .map(|(name, (k, v))| (name.clone(), checker::StoreField::Map(*k, *v))),
4687 )
4688 .chain(
4689 store_sets
4690 .iter()
4691 .map(|(name, t)| (name.clone(), checker::StoreField::Set(*t))),
4692 )
4693 .chain(store_caches.iter().map(|(name, (k, v, ttl))| {
4694 (name.clone(), checker::StoreField::Cache(*k, *v, *ttl))
4695 }))
4696 .chain(
4697 store_logs
4698 .iter()
4699 .map(|(name, t)| (name.clone(), checker::StoreField::Log(*t))),
4700 )
4701 .collect();
4702
4703 checker::check_invariants(
4706 &agent.invariants,
4707 &store_cells,
4708 &agent.name.name,
4709 &resolved_for_handler,
4710 tys,
4711 &mut typed.expr_types,
4712 errors,
4713 refs,
4714 hints,
4715 locals,
4716 requirements,
4717 &mut typed.callees,
4718 );
4719
4720 checker::check_transitions(
4723 &agent.transitions,
4724 state_ty,
4725 &agent.name.name,
4726 &resolved_for_handler,
4727 &mut typed.expr_types,
4728 errors,
4729 refs,
4730 hints,
4731 locals,
4732 requirements,
4733 &mut typed.callees,
4734 tys,
4735 );
4736
4737 for step in &agent.migrations {
4741 let Some(TypeRef::Named(id)) = step.old.as_ref().map(|o| &o.type_ref) else {
4742 continue;
4743 };
4744 let Some(decl) = resolved_for_handler.types.get(&id.name).cloned() else {
4745 continue;
4746 };
4747 let TypeBody::Record(r) = &decl.body else {
4748 continue;
4749 };
4750 for field in &r.fields {
4751 let Some(init) = &field.init else {
4752 continue;
4753 };
4754 let before = errors.len();
4755 checker::check_event_field_default(
4756 init,
4757 &field.type_ref,
4758 "old-state field default",
4759 &resolved_for_handler,
4760 tys,
4761 &mut typed.expr_types,
4762 &mut typed.callees,
4763 errors,
4764 refs,
4765 hints,
4766 locals,
4767 );
4768 if errors.len() > before {
4769 continue;
4770 }
4771 if let Err(reason) = crate::wire_default::lower_event_field_default_wire(
4772 init,
4773 &field.type_ref,
4774 &resolved_for_handler.types,
4775 ) {
4776 errors.push(CompileError::new(
4777 "bynk.types.bad_field_default",
4778 init.span,
4779 format!(
4780 "old-state field `{}`'s default cannot be represented on the wire: \
4781 {reason}",
4782 field.name.name
4783 ),
4784 ));
4785 }
4786 }
4787 }
4788
4789 checker::check_migrations(
4793 agent,
4794 &store_cells,
4795 &resolved_for_handler.types,
4796 &resolved_for_handler,
4797 tys,
4798 &mut typed.expr_types,
4799 errors,
4800 refs,
4801 hints,
4802 locals,
4803 requirements,
4804 &mut typed.callees,
4805 );
4806 errors.extend(crate::agent_state::may_violate_diagnostics(
4811 agent,
4812 &resolved_for_handler.types,
4813 ));
4814
4815 for handler in &agent.handlers {
4816 if let Some(by) = &handler.by_clause {
4824 errors.push(
4825 CompileError::new(
4826 "bynk.actor.by_on_agent",
4827 by.span,
4828 "`by` is a service-edge clause; an agent handler has no actor",
4829 )
4830 .with_note(
4831 "an agent `on call` handler is invoked across the agent boundary, not \
4832 from an ingress — remove the `by` clause",
4833 ),
4834 );
4835 }
4836 let mut handler_caps: HashMap<String, CapabilityInfo> = HashMap::new();
4837 for cap_ref in &handler.given {
4838 if let Some(info) =
4839 resolve_given_cap_ref(cap_ref, capability_info_map, cross_context, errors, refs)
4840 {
4841 handler_caps.insert(cap_ref.key().to_string(), info);
4842 }
4843 }
4844 if !matches!(handler.return_type, TypeRef::Effect(_, _)) {
4846 errors.push(CompileError::new(
4847 "bynk.agent.return_not_effect",
4848 handler.return_type.span(),
4849 format!(
4850 "agent handler must return `Effect[T]`, but got `{}`",
4851 ts_type_ref_display(&handler.return_type)
4852 ),
4853 ));
4854 }
4855 checker::check_handler_body(
4856 &resolved_for_handler,
4857 checker::HandlerBodyCheck {
4858 capabilities: handler_caps,
4859 declared_capabilities: capability_info_map.clone(),
4860 agent_state_ty: Some(state_ty),
4861 agent_self_scope: Some(self_scope.clone()),
4862 given_anchor: Some(handler.return_type.span()),
4863 report_unused: true,
4864 store_fields: store_fields.clone(),
4865 ..checker::HandlerBodyCheck::new(
4866 &handler.body,
4867 &handler.return_type,
4868 &handler.params,
4869 &handler.given,
4870 )
4871 },
4872 checker::CheckSinks {
4873 tys,
4874 expr_types: &mut typed.expr_types,
4875 errors,
4876 refs,
4877 hints,
4878 locals,
4879 requirements,
4880 callees: &mut typed.callees,
4881 },
4882 );
4883 }
4884 }
4885}
4886
4887fn validate_service_cors(service: &ServiceDecl, errors: &mut Vec<CompileError>) {
4890 if let Some(policy) = &service.cors {
4891 validate_cors_policy(service, policy, errors);
4892 }
4893 warn_cross_site_cookie_without_credentials(service, errors);
4894}
4895
4896fn warn_cross_site_cookie_without_credentials(
4902 service: &ServiceDecl,
4903 errors: &mut Vec<CompileError>,
4904) {
4905 if !matches!(service.protocol, ServiceProtocol::Http) {
4906 return;
4907 }
4908 if service.cors.as_ref().is_some_and(|c| c.credentials()) {
4909 return;
4910 }
4911 let mut hit: Option<Span> = None;
4912 for handler in &service.handlers {
4913 let mut exprs: Vec<&Expr> = Vec::new();
4914 for s in &handler.body.statements {
4915 bynk_syntax::ast::statement_exprs(s, &mut exprs);
4916 }
4917 exprs.push(&handler.body.tail);
4918 let mut visit = |e: &Expr| {
4919 if hit.is_some() {
4920 return;
4921 }
4922 let ExprKind::MethodCall { method, args, .. } = &e.kind else {
4923 return;
4924 };
4925 if method.name != "withCookie" && method.name != "clearCookie" {
4926 return;
4927 }
4928 let Some(arg) = args.first() else { return };
4929 let ExprKind::RecordConstruction {
4930 type_name, fields, ..
4931 } = &arg.kind
4932 else {
4933 return;
4934 };
4935 let unrestricted = type_name.name == "Cookie" && fields.iter().any(|f| {
4936 f.name.name == "sameSite"
4937 && matches!(
4938 f.value.as_ref().map(|v| &v.kind),
4939 Some(ExprKind::FieldAccess { field, .. }) if field.name == "Unrestricted"
4940 )
4941 });
4942 if unrestricted {
4943 hit = Some(arg.span);
4944 }
4945 };
4946 fn walk(e: &Expr, f: &mut dyn FnMut(&Expr)) {
4947 f(e);
4948 for c in bynk_syntax::ast::expr_children(e) {
4949 walk(c, f);
4950 }
4951 }
4952 for e in exprs {
4953 walk(e, &mut visit);
4954 }
4955 if hit.is_some() {
4956 break;
4957 }
4958 }
4959 let Some(span) = hit else { return };
4960 errors.push(
4961 CompileError::new(
4962 "bynk.http.cookie_cross_site_without_credentials",
4963 span,
4964 format!(
4965 "service `{}` sets a `SameSite.Unrestricted` cookie but does not declare `cors {{ credentials: true }}`, so a cross-origin `fetch` can never send it back",
4966 service.name.name
4967 ),
4968 )
4969 .with_note(
4970 "add `cors { origins: [...], credentials: true }` if a page on another origin must send it back; a cookie used only in cross-site navigations, embeds or SSO callbacks needs no `cors`, and `SameSite.Lax` suits one that need not cross sites",
4971 ),
4972 );
4973}
4974
4975fn validate_cors_policy(
4980 service: &ServiceDecl,
4981 policy: &CorsPolicy,
4982 errors: &mut Vec<CompileError>,
4983) {
4984 if !matches!(service.protocol, ServiceProtocol::Http) {
4987 errors.push(
4988 CompileError::new(
4989 "bynk.http.cors_not_http",
4990 policy.span,
4991 "a `cors { }` policy is only valid on a `from http` service",
4992 )
4993 .with_note("CORS governs cross-origin browser access, which only the HTTP surface has"),
4994 );
4995 return;
4996 }
4997
4998 for field in &policy.fields {
5001 if !matches!(
5002 field.name.name.as_str(),
5003 "origins" | "headers" | "credentials" | "maxAge"
5004 ) {
5005 errors.push(
5006 CompileError::new(
5007 "bynk.http.cors_unknown_field",
5008 field.name.span,
5009 format!("unknown `cors` field `{}`", field.name.name),
5010 )
5011 .with_note("known fields are `origins`, `headers`, `credentials`, and `maxAge`"),
5012 );
5013 }
5014 }
5015
5016 match policy.field("origins") {
5018 None => errors.push(CompileError::new(
5019 "bynk.http.cors_invalid_origins",
5020 policy.span,
5021 "a `cors { }` policy must declare `origins` — the allowed origins, or `[\"*\"]`",
5022 )),
5023 Some(expr) => match &expr.kind {
5024 ExprKind::ListLit(items, ..) if !items.is_empty() => {
5025 for item in items {
5026 if !matches!(item.kind, ExprKind::StrLit(_)) {
5027 errors.push(CompileError::new(
5028 "bynk.http.cors_invalid_origins",
5029 item.span,
5030 "each `cors` origin must be a string literal (e.g. \"https://app.example.com\" or \"*\")",
5031 ));
5032 }
5033 }
5034 }
5035 _ => errors.push(CompileError::new(
5036 "bynk.http.cors_invalid_origins",
5037 expr.span,
5038 "`cors` `origins` must be a non-empty list of string literals",
5039 )),
5040 },
5041 }
5042
5043 if let Some(expr) = policy.field("headers") {
5045 let ok = matches!(&expr.kind, ExprKind::ListLit(items, ..)
5046 if items.iter().all(|i| matches!(i.kind, ExprKind::StrLit(_))));
5047 if !ok {
5048 errors.push(CompileError::new(
5049 "bynk.http.cors_invalid_field",
5050 expr.span,
5051 "`cors` `headers` must be a list of string literals",
5052 ));
5053 }
5054 }
5055
5056 if let Some(expr) = policy.field("credentials")
5058 && !matches!(expr.kind, ExprKind::BoolLit(_))
5059 {
5060 errors.push(CompileError::new(
5061 "bynk.http.cors_invalid_field",
5062 expr.span,
5063 "`cors` `credentials` must be `true` or `false`",
5064 ));
5065 }
5066
5067 if let Some(expr) = policy.field("maxAge")
5069 && !matches!(expr.kind, ExprKind::DurationLit { .. })
5070 {
5071 errors.push(CompileError::new(
5072 "bynk.http.cors_invalid_field",
5073 expr.span,
5074 "`cors` `maxAge` must be a `Duration` literal (e.g. `1.hour`)",
5075 ));
5076 }
5077
5078 if policy.credentials() && policy.is_wildcard() {
5082 errors.push(
5083 CompileError::new(
5084 "bynk.http.cors_wildcard_credentials",
5085 policy.span,
5086 "`cors` cannot combine `credentials: true` with the wildcard origin `[\"*\"]`",
5087 )
5088 .with_note(
5089 "the Fetch spec forbids credentialed requests against a wildcard origin — \
5090 list the exact origins instead",
5091 ),
5092 );
5093 }
5094}
5095
5096fn validate_security_policy(
5102 service: &ServiceDecl,
5103 policy: &SecurityPolicy,
5104 errors: &mut Vec<CompileError>,
5105) {
5106 if !matches!(service.protocol, ServiceProtocol::Http) {
5109 errors.push(
5110 CompileError::new(
5111 "bynk.http.security_not_http",
5112 policy.span,
5113 "a `security { }` policy is only valid on a `from http` service",
5114 )
5115 .with_note(
5116 "security response headers govern the browser-facing HTTP surface, \
5117 which only a `from http` service has",
5118 ),
5119 );
5120 return;
5121 }
5122
5123 for field in &policy.fields {
5126 if !matches!(field.name.name.as_str(), "hsts" | "nosniff") {
5127 errors.push(
5128 CompileError::new(
5129 "bynk.http.security_unknown_field",
5130 field.name.span,
5131 format!("unknown `security` field `{}`", field.name.name),
5132 )
5133 .with_note("known fields are `hsts` and `nosniff`"),
5134 );
5135 }
5136 }
5137
5138 if let Some(expr) = policy.field("hsts")
5141 && !matches!(&expr.kind, ExprKind::DurationLit { millis, .. } if *millis > 0)
5142 {
5143 errors.push(CompileError::new(
5144 "bynk.http.security_invalid_field",
5145 expr.span,
5146 "`security` `hsts` must be a positive `Duration` literal (e.g. `180.days`)",
5147 ));
5148 }
5149
5150 if let Some(expr) = policy.field("nosniff")
5152 && !matches!(expr.kind, ExprKind::BoolLit(_))
5153 {
5154 errors.push(CompileError::new(
5155 "bynk.http.security_invalid_field",
5156 expr.span,
5157 "`security` `nosniff` must be `true` or `false`",
5158 ));
5159 }
5160}
5161
5162fn validate_limits_policy(
5168 service: &ServiceDecl,
5169 policy: &LimitsPolicy,
5170 errors: &mut Vec<CompileError>,
5171) {
5172 if !matches!(service.protocol, ServiceProtocol::Http) {
5175 errors.push(
5176 CompileError::new(
5177 "bynk.http.limits_not_http",
5178 policy.span,
5179 "a `limits { }` policy is only valid on a `from http` service",
5180 )
5181 .with_note(
5182 "a request-body size ceiling governs the HTTP surface, \
5183 which only a `from http` service has",
5184 ),
5185 );
5186 return;
5187 }
5188
5189 for field in &policy.fields {
5192 if !matches!(field.name.name.as_str(), "maxBody" | "maxFile" | "maxParts") {
5193 errors.push(
5194 CompileError::new(
5195 "bynk.http.limits_unknown_field",
5196 field.name.span,
5197 format!("unknown `limits` field `{}`", field.name.name),
5198 )
5199 .with_note("the fields are `maxBody`, and (for `@multipart` routes) `maxFile` and `maxParts`"),
5200 );
5201 }
5202 }
5203 for name in ["maxFile", "maxParts"] {
5205 if let Some(expr) = policy.field(name)
5206 && !matches!(&expr.kind, ExprKind::IntLit { value: n, .. } if *n > 0)
5207 {
5208 errors.push(CompileError::new(
5209 "bynk.http.limits_invalid_field",
5210 expr.span,
5211 format!("`limits` `{name}` must be a positive `Int` literal"),
5212 ));
5213 }
5214 }
5215
5216 if let Some(expr) = policy.field("maxBody")
5221 && !matches!(&expr.kind, ExprKind::IntLit { value: n, .. } if *n > 0)
5222 {
5223 errors.push(CompileError::new(
5224 "bynk.http.limits_invalid_field",
5225 expr.span,
5226 "`limits` `maxBody` must be a positive `Int` literal — a byte count (e.g. `1_048_576`)",
5227 ));
5228 }
5229}
5230
5231fn validate_json_policy(
5236 service: &ServiceDecl,
5237 policy: &JsonPolicy,
5238 errors: &mut Vec<CompileError>,
5239) {
5240 if !matches!(service.protocol, ServiceProtocol::Http) {
5241 errors.push(
5242 CompileError::new(
5243 "bynk.http.json_not_http",
5244 policy.span,
5245 "a `json { }` policy is only valid on a `from http` service",
5246 )
5247 .with_note("the response JSON encoding governs the HTTP surface, which only a `from http` service has"),
5248 );
5249 return;
5250 }
5251 for field in &policy.fields {
5252 if field.name.name != "options" {
5253 errors.push(
5254 CompileError::new(
5255 "bynk.http.json_unknown_field",
5256 field.name.span,
5257 format!("unknown `json` field `{}`", field.name.name),
5258 )
5259 .with_note("the only field is `options`"),
5260 );
5261 }
5262 }
5263 if let Some(expr) = policy.field("options")
5264 && JsonOptions::from_expr(expr).is_none()
5265 {
5266 errors.push(CompileError::new(
5267 "bynk.http.json_invalid_field",
5268 expr.span,
5269 "`json` `options` must be `tagged` or `plain`",
5270 ));
5271 }
5272}
5273
5274fn validate_json_args(ann: &Annotation, errors: &mut Vec<CompileError>) {
5276 let mut options: Option<&AnnotationArg> = None;
5277 for arg in &ann.args {
5278 match arg.label.as_ref().map(|l| l.name.as_str()) {
5279 Some("options") => options = Some(arg),
5280 _ => errors.push(
5281 CompileError::new(
5282 "bynk.http.json_unknown_arg",
5283 arg.span,
5284 "`@json` accepts only the `options:` argument",
5285 )
5286 .with_note("write `@json(options: plain)`"),
5287 ),
5288 }
5289 }
5290 match options {
5291 None => errors.push(
5292 CompileError::new(
5293 "bynk.http.json_invalid_arg",
5294 ann.span,
5295 "`@json` needs an `options:` argument",
5296 )
5297 .with_note("write `@json(options: plain)`"),
5298 ),
5299 Some(arg) if JsonOptions::from_expr(&arg.value).is_none() => {
5300 errors.push(CompileError::new(
5301 "bynk.http.json_invalid_arg",
5302 arg.span,
5303 "`@json` `options` must be `tagged` or `plain`",
5304 ));
5305 }
5306 Some(_) => {}
5307 }
5308}
5309
5310pub(crate) fn null_payload_option(
5316 t: &TypeRef,
5317 types: &HashMap<String, Arc<TypeDecl>>,
5318 seen: &mut HashSet<String>,
5319) -> Option<String> {
5320 match t {
5321 TypeRef::Option(inner, _) => {
5322 if matches!(inner.as_ref(), TypeRef::Option(..) | TypeRef::Unit(_)) {
5323 return Some(ts_type_ref_display(inner));
5324 }
5325 null_payload_option(inner, types, seen)
5326 }
5327 TypeRef::List(a, _)
5328 | TypeRef::Set(a, _)
5329 | TypeRef::Effect(a, _)
5330 | TypeRef::HttpResult(a, _) => null_payload_option(a, types, seen),
5331 TypeRef::Map(k, v, _) | TypeRef::Result(k, v, _) => {
5332 null_payload_option(k, types, seen).or_else(|| null_payload_option(v, types, seen))
5333 }
5334 TypeRef::Named(id) => {
5335 if !seen.insert(id.name.clone()) {
5336 return None;
5337 }
5338 match types.get(&id.name).map(|d| &d.body) {
5339 Some(TypeBody::Record(r)) => r
5340 .fields
5341 .iter()
5342 .find_map(|f| null_payload_option(&f.type_ref, types, seen)),
5343 Some(TypeBody::Sum(s)) => s
5344 .variants
5345 .iter()
5346 .flat_map(|v| &v.payload)
5347 .find_map(|f| null_payload_option(&f.type_ref, types, seen)),
5348 _ => None,
5349 }
5350 }
5351 TypeRef::App { name, args, .. } => {
5352 if !seen.insert(bynk_check_wire_key(&name.name, args)) {
5353 return None;
5354 }
5355 let fields = crate::wire::record_inst_fields(&name.name, args, types)
5356 .map(|fs| fs.into_iter().map(|(_, t)| t).collect::<Vec<_>>())
5357 .or_else(|| {
5358 crate::wire::sum_inst_variants(&name.name, args, types).map(|vs| {
5359 vs.into_iter()
5360 .flat_map(|(_, fs)| fs.into_iter().map(|(_, t)| t))
5361 .collect()
5362 })
5363 })
5364 .unwrap_or_default();
5365 args.iter()
5366 .find_map(|a| null_payload_option(a, types, seen))
5367 .or_else(|| {
5368 fields
5369 .iter()
5370 .find_map(|f| null_payload_option(f, types, seen))
5371 })
5372 }
5373 _ => None,
5374 }
5375}
5376
5377fn bynk_check_wire_key(name: &str, args: &[TypeRef]) -> String {
5379 crate::wire::inst_codec_suffix(name, args)
5380}
5381
5382fn check_rejected_handlers(table: &UnitTable, errors: &mut Vec<CompileError>) {
5387 for service in table.services.values() {
5388 let mut first: Option<Span> = None;
5389 for handler in &service.handlers {
5390 if handler.kind != HandlerKind::Rejected {
5391 continue;
5392 }
5393 if let Some(prev) = first {
5394 errors.push(
5395 CompileError::new(
5396 "bynk.http.duplicate_rejected",
5397 handler.span,
5398 format!(
5399 "service `{}` already declares `on rejected`",
5400 service.name.name
5401 ),
5402 )
5403 .with_label(prev, "first declared here"),
5404 );
5405 continue;
5406 }
5407 first = Some(handler.span);
5408 let signature = |span: Span, msg: &str| {
5409 CompileError::new("bynk.http.rejected_signature", span, msg.to_string()).with_note(
5410 "write `on rejected(why: BoundaryRejection) -> Effect[HttpResult[()]] { … }`",
5411 )
5412 };
5413 match handler.params.as_slice() {
5414 [p] if matches!(p.type_ref, TypeRef::BoundaryRejection(_)) => {}
5415 [p] => errors.push(signature(
5416 p.span,
5417 "`on rejected` takes the rejection, typed `BoundaryRejection`",
5418 )),
5419 _ => errors.push(signature(
5420 handler.span,
5421 "`on rejected` takes exactly one parameter, the `BoundaryRejection`",
5422 )),
5423 }
5424 if let Some(by) = &handler.by_clause {
5425 errors.push(signature(
5426 by.span,
5427 "`on rejected` has no `by`: it runs before any actor is known",
5428 ));
5429 }
5430 if let Some(g) = handler.given.first() {
5431 errors.push(signature(
5432 g.span,
5433 "`on rejected` has no `given`: it renders a response body and uses no capability",
5434 ));
5435 }
5436 let inner = match &handler.return_type {
5437 TypeRef::Effect(inner, _) => inner.as_ref(),
5438 other => other,
5439 };
5440 let unit_result = matches!(inner, TypeRef::HttpResult(t, _) if matches!(t.as_ref(), TypeRef::Unit(_)));
5441 if !unit_result {
5442 errors.push(signature(
5443 handler.return_type.span(),
5444 "`on rejected` returns `HttpResult[()]` (or `Effect[HttpResult[()]]`)",
5445 ));
5446 }
5447 }
5448 }
5449}
5450
5451fn reserved_route_char(
5457 seg: &str,
5458 path: &str,
5459 handler: &Handler,
5460 errors: &mut Vec<CompileError>,
5461) -> bool {
5462 let Some(ch) = seg.chars().find(|c| matches!(c, '*' | '{' | '}')) else {
5463 return false;
5464 };
5465 errors.push(
5466 CompileError::new(
5467 "bynk.http.reserved_route_syntax",
5468 handler.span,
5469 format!("`{ch}` in the route `{path}` is reserved for a future route form"),
5470 )
5471 .with_note(if seg.starts_with(':') {
5472 format!("drop `{ch}` from the parameter's name: a `:name` segment already takes any value, so check it in the handler")
5473 } else {
5474 format!("to match a literal `{ch}`, take the segment as a `:name` parameter and check it in the handler")
5475 }),
5476 );
5477 true
5478}
5479
5480fn validate_http_handler(
5491 handler: &Handler,
5492 method: HttpMethod,
5493 path: &str,
5494 types: &HashMap<String, Arc<TypeDecl>>,
5495 cf_is_std: bool,
5496 errors: &mut Vec<CompileError>,
5497) {
5498 if !path.starts_with('/') {
5499 errors.push(CompileError::new(
5500 "bynk.http.invalid_path",
5501 handler.span,
5502 format!("HTTP path `{path}` must start with `/`"),
5503 ));
5504 }
5505 if path.starts_with("/_bynk/") || path == "/_bynk" {
5506 errors.push(
5507 CompileError::new(
5508 "bynk.http.reserved_prefix",
5509 handler.span,
5510 format!("HTTP path `{path}` uses the reserved `/_bynk/` prefix",),
5511 )
5512 .with_note("paths under `/_bynk/` are reserved for internal Bynk dispatch"),
5513 );
5514 }
5515 let assets_dir = crate::assets::SERVED_PREFIX.trim_end_matches('/');
5519 if path == assets_dir || path.starts_with(crate::assets::SERVED_PREFIX) {
5520 errors.push(
5521 CompileError::new(
5522 "bynk.http.reserved_prefix",
5523 handler.span,
5524 format!("HTTP path `{path}` uses the reserved `{}` prefix", crate::assets::SERVED_PREFIX),
5525 )
5526 .with_note("paths under `/_assets/` are reserved for static assets, which the platform serves before the Worker runs"),
5527 );
5528 }
5529 let mut path_param_names: Vec<&str> = Vec::new();
5531 let mut refused = false;
5534 for seg in path.split('/').filter(|s| !s.is_empty()) {
5535 if reserved_route_char(seg, path, handler, errors) {
5536 refused = true;
5537 continue;
5538 }
5539 if let Some(rest) = seg.strip_prefix(':') {
5540 if rest.is_empty() {
5541 errors.push(CompileError::new(
5542 "bynk.http.invalid_path",
5543 handler.span,
5544 format!("HTTP path `{path}` has an empty parameter segment `:`"),
5545 ));
5546 } else {
5547 path_param_names.push(rest);
5548 }
5549 }
5550 }
5551 for name in &path_param_names {
5553 if !handler.params.iter().any(|p| p.name.name == *name) {
5554 errors.push(CompileError::new(
5555 "bynk.http.unbound_path_param",
5556 handler.span,
5557 format!("path parameter `:{name}` has no matching handler parameter `{name}`",),
5558 ));
5559 }
5560 }
5561 for p in &handler.params {
5563 let is_path = path_param_names.iter().any(|n| n == &p.name.name.as_str());
5564 let is_body = p.name.name == "body";
5565 let is_headers = !is_path && p.name.name == "headers";
5568 if is_headers && !matches!(p.type_ref, TypeRef::RequestHeaders(_)) {
5569 errors.push(
5570 CompileError::new(
5571 "bynk.http.headers_wrong_type",
5572 p.type_ref.span(),
5573 format!(
5574 "an HTTP handler's `headers` parameter must be typed `RequestHeaders` (got `{}`)",
5575 ts_type_ref_display(&p.type_ref),
5576 ),
5577 )
5578 .with_note("`headers: RequestHeaders` gives the handler the request's headers"),
5579 );
5580 }
5581 let is_query = !is_path && p.name.name == "query";
5584 if is_query {
5585 validate_query_param(p, types, errors);
5586 }
5587 let is_cookies = !is_path && p.name.name == "cookies";
5590 if is_cookies {
5591 validate_cookies_param(p, types, errors);
5592 }
5593 let is_cf = !is_path && p.name.name == "cf";
5596 if is_cf
5597 && !(cf_is_std && matches!(&p.type_ref, TypeRef::Named(id) if id.name == "RequestCf"))
5598 {
5599 errors.push(
5600 CompileError::new(
5601 "bynk.http.cf_wrong_type",
5602 p.type_ref.span(),
5603 format!(
5604 "an HTTP handler's `cf` parameter must be typed `RequestCf` (got `{}`)",
5605 ts_type_ref_display(&p.type_ref),
5606 ),
5607 )
5608 .with_note(
5609 "`cf: RequestCf` gives the handler what Cloudflare derived about the request; it is the `RequestCf` of `bynk.cloudflare` (`consumes bynk.cloudflare { RequestCf }`), not a type of your own",
5610 ),
5611 );
5612 }
5613 if is_body
5615 && let Some(kind) = handler
5616 .annotations
5617 .iter()
5618 .find(|a| matches!(a.name.name.as_str(), "form" | "multipart"))
5619 .map(|a| a.name.name.as_str())
5620 {
5621 validate_form_body(p, kind, types, errors);
5622 if let Some(by) = handler.by_clause.as_ref().filter(|b| b.is_sum()) {
5623 errors.push(
5624 CompileError::new(
5625 "bynk.http.form_on_sum_route",
5626 by.span,
5627 format!("a `@{kind}` route cannot take a sum of actors"),
5628 )
5629 .with_note(
5630 "a multi-actor route reads and verifies the body as JSON itself; name one actor, or split the route",
5631 ),
5632 );
5633 }
5634 }
5635 if is_body
5638 && is_byte_stream(&p.type_ref)
5639 && let Some(by) = handler.by_clause.as_ref().filter(|b| b.is_sum())
5640 {
5641 errors.push(
5642 CompileError::new(
5643 "bynk.http.stream_body_on_sum_route",
5644 by.span,
5645 "a route with a streamed `body` cannot take a sum of actors",
5646 )
5647 .with_note(
5648 "a multi-actor route reads and verifies the body itself before the handler runs; name one actor, or split the route",
5649 ),
5650 );
5651 }
5652 if !refused && !is_path && !is_body && !is_headers && !is_query && !is_cookies && !is_cf {
5653 errors.push(
5654 CompileError::new(
5655 "bynk.http.extra_param",
5656 p.span,
5657 format!(
5658 "handler parameter `{}` is not a path parameter and is not named `body`, `headers`, `query`, `cookies` or `cf`",
5659 p.name.name
5660 ),
5661 )
5662 .with_note(
5663 "HTTP handler parameters must match a `:name` path segment, or be named `body`, `headers`, `query`, `cookies` or `cf`",
5664 ),
5665 );
5666 }
5667 if is_path && !is_string_constructible(&p.type_ref, types) {
5669 errors.push(
5670 CompileError::new(
5671 "bynk.http.path_param_not_stringy",
5672 p.type_ref.span(),
5673 format!(
5674 "path parameter `{}` must have a type constructible from `String` (got `{}`)",
5675 p.name.name,
5676 ts_type_ref_display(&p.type_ref),
5677 ),
5678 )
5679 .with_note(
5680 "use `String`, a refined `String`, or an opaque type whose base is `String`",
5681 ),
5682 );
5683 }
5684 if is_body && method.forbids_body() {
5685 errors.push(
5686 CompileError::new(
5687 "bynk.http.body_on_get_or_delete",
5688 p.span,
5689 format!(
5690 "`on http {}` handlers may not declare a `body` parameter",
5691 method.as_str()
5692 ),
5693 )
5694 .with_note("GET and DELETE requests conventionally carry no body"),
5695 );
5696 }
5697 }
5698 let return_ok = match &handler.return_type {
5700 TypeRef::Effect(inner, _) => matches!(inner.as_ref(), TypeRef::HttpResult(_, _)),
5701 _ => false,
5702 };
5703 if !return_ok {
5704 errors.push(CompileError::new(
5705 "bynk.http.return_not_effect_http_result",
5706 handler.return_type.span(),
5707 format!(
5708 "`on http` handler must return `Effect[HttpResult[T]]`, but got `{}`",
5709 ts_type_ref_display(&handler.return_type),
5710 ),
5711 ));
5712 }
5713}
5714
5715fn is_query_leaf(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
5719 let stringy_base = |b: &BaseType| {
5720 matches!(
5721 b,
5722 BaseType::String | BaseType::Int | BaseType::Bool | BaseType::Decimal
5723 )
5724 };
5725 match r {
5726 TypeRef::Base(b, _) => stringy_base(b),
5727 TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
5728 Some(TypeBody::Refined { base, .. }) | Some(TypeBody::Opaque { base, .. }) => {
5729 stringy_base(base)
5730 }
5731 Some(TypeBody::Sum(s)) => s.variants.iter().all(|v| v.payload.is_empty()),
5732 _ => false,
5733 },
5734 _ => false,
5735 }
5736}
5737
5738fn cf_type_is_std(cross_context: &resolver::CrossContextInfo, table: &UnitTable) -> bool {
5743 cross_context
5744 .consumed_types
5745 .get("bynk.cloudflare")
5746 .is_some_and(|t| t.contains_key("RequestCf"))
5747 && !table.types.contains_key("RequestCf")
5748}
5749
5750pub(crate) fn is_query_field_type(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
5753 match r {
5754 TypeRef::Option(inner, _) | TypeRef::List(inner, _) => is_query_leaf(inner, types),
5755 other => is_query_leaf(other, types),
5756 }
5757}
5758
5759#[derive(Clone, Copy, PartialEq, Eq)]
5762enum RequestSurface {
5763 Cookies,
5764 Query,
5765 Form,
5766}
5767
5768pub(crate) fn cookie_records_of(table: &UnitTable) -> HashSet<String> {
5772 let mut out = HashSet::new();
5773 for service in table.services.values() {
5774 for h in &service.handlers {
5775 if !matches!(h.kind, HandlerKind::Http { .. }) {
5776 continue;
5777 }
5778 for p in &h.params {
5779 if p.name.name == "cookies"
5780 && let TypeRef::Named(id) = &p.type_ref
5781 {
5782 out.insert(id.name.clone());
5783 }
5784 }
5785 }
5786 }
5787 out
5788}
5789
5790fn is_http_token(s: &str) -> bool {
5792 !s.is_empty()
5793 && s.chars()
5794 .all(|c| c.is_ascii_graphic() && !"()<>@,;:\\\"/[]?={}".contains(c))
5795}
5796
5797pub(crate) fn validate_field_names(
5804 table: &UnitTable,
5805 types: &HashMap<String, Arc<TypeDecl>>,
5806 consts: &HashMap<String, ConstDecl>,
5807 errors: &mut Vec<CompileError>,
5808) {
5809 let mut uses: HashMap<String, Vec<RequestSurface>> = HashMap::new();
5810 for service in table.services.values() {
5811 for h in &service.handlers {
5812 if !matches!(h.kind, HandlerKind::Http { .. }) {
5813 continue;
5814 }
5815 for p in &h.params {
5816 let surface = match p.name.name.as_str() {
5817 "cookies" => Some(RequestSurface::Cookies),
5818 "query" => Some(RequestSurface::Query),
5819 "body"
5820 if h.annotations
5821 .iter()
5822 .any(|a| matches!(a.name.name.as_str(), "form" | "multipart")) =>
5823 {
5824 Some(RequestSurface::Form)
5825 }
5826 _ => None,
5827 };
5828 if let (Some(s), TypeRef::Named(id)) = (surface, &p.type_ref) {
5829 uses.entry(id.name.clone()).or_default().push(s);
5830 }
5831 }
5832 }
5833 }
5834 let mut names: Vec<&String> = types.keys().collect();
5835 names.sort();
5836 for name in names {
5837 let TypeBody::Record(rec) = &types[name].body else {
5838 continue;
5839 };
5840 if rec.fields.iter().all(|f| f.annotations.is_empty()) {
5841 continue;
5842 }
5843 let surfaces = uses.get(name).cloned().unwrap_or_default();
5844 let mut wire: Vec<(String, Span)> = Vec::new();
5845 let mut reported_not_request = false;
5846 for f in &rec.fields {
5847 let mut external: Option<(String, Span)> = None;
5848 for ann in &f.annotations {
5849 if ann.name.name != "name" {
5850 errors.push(
5851 CompileError::new(
5852 "bynk.types.field_annotation_unknown",
5853 ann.span,
5854 format!("unknown field annotation `@{}`", ann.name.name),
5855 )
5856 .with_note("the only field annotation is `@name(\"…\")`"),
5857 );
5858 continue;
5859 }
5860 let arg = match ann.args.as_slice() {
5861 [a] if a.label.is_none() => Some(a),
5862 _ => None,
5863 };
5864 let literal = arg.and_then(|a| match &a.value.kind {
5865 ExprKind::StrLit(s) => Some(s.clone()),
5866 _ => None,
5867 });
5868 let Some(literal) = literal else {
5869 let mut err = CompileError::new(
5870 "bynk.types.field_name_bad_arg",
5871 ann.span,
5872 "`@name` takes exactly one string literal, or a `String` constant bound to one",
5873 )
5874 .with_note("write `@name(\"__Host-sid\")`, or `const SidCookie: String = \"__Host-sid\"` and `@name(SidCookie)`");
5875 if let Some(a) = arg
5877 && let ExprKind::Ident(id) = &a.value.kind
5878 {
5879 err = err.with_note(match consts.get(&id.name) {
5880 Some(c) if matches!(c.ty, TypeRef::Base(BaseType::String, _)) => format!(
5881 "`{}` is declared `String`, but its value does not end at a string literal: every constant it passes through must be declared exactly `String`, and the last bound to a string literal",
5882 id.name,
5883 ),
5884 Some(c) => format!(
5885 "`{}` is declared `{}`; `@name` needs a constant declared exactly `String` and bound to a string literal (or to another such constant)",
5886 id.name,
5887 ts_type_ref_display(&c.ty),
5888 ),
5889 None => format!("`{}` is not a constant in scope", id.name),
5890 });
5891 }
5892 errors.push(err);
5893 continue;
5894 };
5895 let (at, origin) = match arg {
5898 Some(a) if a.from_const.is_some() => (a.value.span, Some(a)),
5899 _ => (ann.span, None),
5900 };
5901 if external.is_some() {
5902 errors.push(CompileError::new(
5903 "bynk.types.field_name_duplicate",
5904 ann.span,
5905 format!("field `{}` has more than one `@name`", f.name.name),
5906 ));
5907 continue;
5908 }
5909 if surfaces.is_empty() {
5910 if reported_not_request {
5912 external = Some((literal, at));
5913 continue;
5914 }
5915 reported_not_request = true;
5916 errors.push(
5917 CompileError::new(
5918 "bynk.types.field_name_not_request_record",
5919 ann.span,
5920 format!(
5921 "`@name` is on a field of `{name}`, which is not the `cookies`, `query` or `@form`/`@multipart` `body` record of an HTTP handler"
5922 ),
5923 )
5924 .with_note(
5925 "`@name` renames the key a request reader looks for; on any other record it would do nothing",
5926 ),
5927 );
5928 } else {
5929 let bad = if surfaces.contains(&RequestSurface::Cookies)
5930 && !is_http_token(&literal)
5931 {
5932 Some(
5933 "a cookie name must be an RFC 9110 token (no spaces, quotes or separators)",
5934 )
5935 } else if literal.is_empty() {
5936 Some("a wire name must not be empty")
5937 } else {
5938 None
5939 };
5940 if let Some(why) = bad {
5941 let shown = match origin.and_then(|a| a.from_const.as_ref()) {
5942 Some(c) => format!(
5943 "`@name({})` is not a valid name here: {why} (`{literal}`)",
5944 c.name.name
5945 ),
5946 None => {
5947 format!("`@name(\"{literal}\")` is not a valid name here: {why}")
5948 }
5949 };
5950 let err = CompileError::new("bynk.types.field_name_invalid", at, shown);
5951 errors.push(match origin {
5952 Some(a) => crate::annotation_consts::with_const_origin(err, a),
5953 None => err,
5954 });
5955 }
5956 }
5957 external = Some((literal, at));
5958 }
5959 let (key, span) = external.unwrap_or_else(|| (f.name.name.clone(), f.name.span));
5960 wire.push((key, span));
5961 }
5962 if surfaces.is_empty() {
5963 continue;
5965 }
5966 let case_matters = surfaces
5967 .iter()
5968 .any(|s| matches!(s, RequestSurface::Cookies | RequestSurface::Query));
5969 for (i, (a, span)) in wire.iter().enumerate() {
5970 for (b, _) in &wire[..i] {
5971 if a == b {
5972 errors.push(CompileError::new(
5973 "bynk.types.field_name_duplicate",
5974 *span,
5975 format!("two fields of `{name}` read the same wire name `{a}`"),
5976 ));
5977 } else if case_matters && a.eq_ignore_ascii_case(b) {
5978 errors.push(
5979 CompileError::new(
5980 "bynk.types.field_name_case_conflict",
5981 *span,
5982 format!("wire names `{a}` and `{b}` of `{name}` differ only in case"),
5983 )
5984 .with_note("cookie and query names are case-sensitive but easily confused; rename one"),
5985 );
5986 }
5987 }
5988 }
5989 }
5990}
5991
5992fn validate_cookies_param(
5997 p: &Param,
5998 types: &HashMap<String, Arc<TypeDecl>>,
5999 errors: &mut Vec<CompileError>,
6000) {
6001 if matches!(p.type_ref, TypeRef::RequestCookies(_)) {
6003 return;
6004 }
6005 let record = match &p.type_ref {
6006 TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
6007 Some(TypeBody::Record(r)) => Some(r),
6008 _ => None,
6009 },
6010 _ => None,
6011 };
6012 let Some(record) = record else {
6013 errors.push(
6014 CompileError::new(
6015 "bynk.http.cookies_wrong_type",
6016 p.type_ref.span(),
6017 format!(
6018 "an HTTP handler's `cookies` parameter must be a record type or `RequestCookies` (got `{}`)",
6019 ts_type_ref_display(&p.type_ref),
6020 ),
6021 )
6022 .with_note(
6023 "`cookies: Session` decodes the request's `Cookie` header into the record `Session`, one field per cookie name, and answers `400` when it does not fit; `cookies: RequestCookies` reads them raw, for a name a field cannot spell (`__Host-sid`)",
6024 ),
6025 );
6026 return;
6027 };
6028 for f in &record.fields {
6029 if !is_query_field_type(&f.type_ref, types) {
6030 errors.push(
6031 CompileError::new(
6032 "bynk.http.cookies_field_not_stringy",
6033 f.type_ref.span(),
6034 format!(
6035 "field `{}` of the `cookies` record has type `{}`, which a cookie cannot carry",
6036 f.name.name,
6037 ts_type_ref_display(&f.type_ref),
6038 ),
6039 )
6040 .with_note(
6041 "a cookie field is a `String`, `Int`, `Bool`, `Decimal`, an enum, or a refined or opaque type over one, optionally in an `Option` or a `List` (a name sent twice)",
6042 ),
6043 );
6044 }
6045 }
6046}
6047
6048fn validate_query_param(
6051 p: &Param,
6052 types: &HashMap<String, Arc<TypeDecl>>,
6053 errors: &mut Vec<CompileError>,
6054) {
6055 if matches!(p.type_ref, TypeRef::RequestQuery(_)) {
6056 return;
6057 }
6058 let record = match &p.type_ref {
6059 TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
6060 Some(TypeBody::Record(r)) => Some(r),
6061 _ => None,
6062 },
6063 _ => None,
6064 };
6065 let Some(record) = record else {
6066 errors.push(
6067 CompileError::new(
6068 "bynk.http.query_wrong_type",
6069 p.type_ref.span(),
6070 format!(
6071 "an HTTP handler's `query` parameter must be a record type or `RequestQuery` (got `{}`)",
6072 ts_type_ref_display(&p.type_ref),
6073 ),
6074 )
6075 .with_note(
6076 "`query: Filter` decodes the query string into the record `Filter` and answers `400` when it does not fit; `query: RequestQuery` reads it raw",
6077 ),
6078 );
6079 return;
6080 };
6081 for f in &record.fields {
6082 if !is_query_field_type(&f.type_ref, types) {
6083 errors.push(
6084 CompileError::new(
6085 "bynk.http.query_field_not_stringy",
6086 f.type_ref.span(),
6087 format!(
6088 "field `{}` of the `query` record has type `{}`, which a query string cannot carry",
6089 f.name.name,
6090 ts_type_ref_display(&f.type_ref),
6091 ),
6092 )
6093 .with_note(
6094 "a query field is a `String`, `Int`, `Bool`, `Decimal`, an enum, or a refined or opaque type over one, optionally in an `Option` or a `List` (a repeated key)",
6095 ),
6096 );
6097 }
6098 }
6099}
6100
6101fn validate_handler_annotations(
6110 handler: &Handler,
6111 service_cap: Option<i64>,
6112 errors: &mut Vec<CompileError>,
6113) {
6114 let is_get = matches!(
6115 handler.kind,
6116 HandlerKind::Http {
6117 method: HttpMethod::Get,
6118 ..
6119 }
6120 );
6121 let is_body_method = matches!(
6125 handler.kind,
6126 HandlerKind::Http {
6127 method: HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch,
6128 ..
6129 }
6130 );
6131 let mut seen_cache = false;
6132 let mut seen_limit = false;
6133 let mut seen_raw = false;
6134 let mut seen_form = false;
6135 let mut seen_json = false;
6136 let mut body_kind: Option<&str> = None;
6139 for ann in &handler.annotations {
6140 match ann.name.name.as_str() {
6141 "cache" => {
6142 if seen_cache {
6143 errors.push(CompileError::new(
6144 "bynk.http.cache_duplicate",
6145 ann.span,
6146 "a handler carries at most one `@cache` annotation",
6147 ));
6148 continue;
6149 }
6150 seen_cache = true;
6151 if !is_get {
6152 errors.push(
6153 CompileError::new(
6154 "bynk.http.cache_on_non_get",
6155 ann.span,
6156 "`@cache` is only valid on an `on http GET` handler",
6157 )
6158 .with_note(
6159 "conditional caching applies to safe, idempotent reads — a `GET` route",
6160 ),
6161 );
6162 continue;
6163 }
6164 validate_cache_args(ann, errors);
6165 let public = ann.args.iter().any(|a| {
6168 a.label.as_ref().is_some_and(|n| n.name == "scope")
6169 && matches!(&a.value.kind, ExprKind::Ident(id) if id.name == "public")
6170 });
6171 if public && handler.params.iter().any(|p| p.name.name == "cookies") {
6172 errors.push(
6173 CompileError::new(
6174 "bynk.http.cache_public_reads_cookies",
6175 ann.span,
6176 "a `@cache(scope: public)` handler reads `cookies`, so a shared cache could replay one user's response to another",
6177 )
6178 .with_note("use `scope: private`, or drop the `cookies` parameter"),
6179 );
6180 }
6181 }
6182 "limit" => {
6183 if seen_limit {
6184 errors.push(CompileError::new(
6185 "bynk.http.limit_duplicate",
6186 ann.span,
6187 "a handler carries at most one `@limit` annotation",
6188 ));
6189 continue;
6190 }
6191 seen_limit = true;
6192 if !is_body_method {
6193 errors.push(
6194 CompileError::new(
6195 "bynk.http.limit_on_bodyless",
6196 ann.span,
6197 "`@limit` is only valid on a body-taking `on http` route (POST/PUT/PATCH)",
6198 )
6199 .with_note(
6200 "a request-body size cap applies to routes that read a body — a GET or DELETE has none",
6201 ),
6202 );
6203 continue;
6204 }
6205 validate_limit_args(
6206 ann,
6207 handler
6208 .annotations
6209 .iter()
6210 .any(|a| a.name.name == "multipart"),
6211 errors,
6212 );
6213 }
6214 "raw" => {
6215 if seen_raw {
6216 errors.push(CompileError::new(
6217 "bynk.http.raw_duplicate",
6218 ann.span,
6219 "a handler carries at most one `@raw` annotation",
6220 ));
6221 continue;
6222 }
6223 seen_raw = true;
6224 if let Some(other) = body_kind.filter(|k| *k != "raw") {
6225 errors.push(body_kind_conflict(ann, "raw", other));
6226 continue;
6227 }
6228 body_kind = Some("raw");
6229 let body = handler.params.iter().find(|p| p.name.name == "body");
6230 let Some(body) = body.filter(|_| is_body_method) else {
6231 errors.push(
6232 CompileError::new(
6233 "bynk.http.raw_on_bodyless",
6234 ann.span,
6235 "`@raw` is only valid on a POST/PUT/PATCH `on http` route with a `body` parameter",
6236 )
6237 .with_note(
6238 "a raw request body is the `body: Bytes` parameter of a body-taking route",
6239 ),
6240 );
6241 continue;
6242 };
6243 validate_raw_args(ann, errors);
6244 if !matches!(body.type_ref, TypeRef::Base(BaseType::Bytes, _))
6245 && !is_byte_stream(&body.type_ref)
6246 {
6247 errors.push(
6248 CompileError::new(
6249 "bynk.http.raw_body_not_bytes",
6250 body.type_ref.span(),
6251 format!(
6252 "the `body` of a `@raw` handler must be `Bytes` or `Stream[Bytes]`, but it is `{}`",
6253 ts_type_ref_display(&body.type_ref),
6254 ),
6255 )
6256 .with_note("a raw body is handed to the handler as its octets, undecoded: whole as `Bytes`, or chunk by chunk as a `Stream[Bytes]`"),
6257 );
6258 }
6259 let route_cap = handler.limit_max_body();
6260 if route_cap.or(service_cap).is_none() {
6261 errors.push(
6262 CompileError::new(
6263 "bynk.http.raw_body_unbounded",
6264 ann.span,
6265 "a `@raw` route needs a request-body cap",
6266 )
6267 .with_note(
6268 "add `@limit(maxBody: …)` to the handler or `limits { maxBody = … }` to the service; an unbounded binary upload is the denial of service ADR 0165 exists to stop",
6269 ),
6270 );
6271 }
6272 }
6273 kind @ ("form" | "multipart") => {
6274 if seen_form {
6277 errors.push(CompileError::new(
6278 "bynk.http.form_duplicate",
6279 ann.span,
6280 format!("a handler carries at most one `@{kind}` annotation"),
6281 ));
6282 continue;
6283 }
6284 seen_form = true;
6285 if let Some(other) = body_kind.filter(|k| *k != kind) {
6286 errors.push(body_kind_conflict(ann, kind, other));
6287 continue;
6288 }
6289 body_kind = Some(kind);
6290 let has_body = handler.params.iter().any(|p| p.name.name == "body");
6291 if !is_body_method || !has_body {
6292 errors.push(
6293 CompileError::new(
6294 "bynk.http.form_on_bodyless",
6295 ann.span,
6296 format!(
6297 "`@{kind}` is only valid on a POST/PUT/PATCH `on http` route with a `body` parameter"
6298 ),
6299 )
6300 .with_note(format!(
6301 "a {kind} body is the `body` parameter of a body-taking route"
6302 )),
6303 );
6304 continue;
6305 }
6306 if let Some(arg) = ann.args.first() {
6307 errors.push(
6308 CompileError::new(
6309 "bynk.http.form_unknown_arg",
6310 arg.span,
6311 format!("`@{kind}` takes no arguments"),
6312 )
6313 .with_note(format!(
6314 "write `@{kind}`: the media type is fixed, and the caps are `@limit` and `limits {{ }}`"
6315 )),
6316 );
6317 }
6318 if kind == "multipart" && handler.limit_max_body().or(service_cap).is_none() {
6321 errors.push(
6322 CompileError::new(
6323 "bynk.http.multipart_body_unbounded",
6324 ann.span,
6325 "a `@multipart` route needs a request-body cap",
6326 )
6327 .with_note(
6328 "add `@limit(maxBody: …)` to the handler or `limits { maxBody: … }` to the service; a multipart body is buffered whole, so an unbounded upload is the denial of service ADR 0165 exists to stop",
6329 ),
6330 );
6331 } else if kind == "multipart"
6332 && handler
6333 .limit_max_body()
6334 .or(service_cap)
6335 .is_some_and(|cap| cap > MULTIPART_LARGE_CAP)
6336 {
6337 errors.push(
6338 CompileError::new(
6339 "bynk.http.multipart_large_cap",
6340 ann.span,
6341 "this `@multipart` route's body cap is over 32 MiB",
6342 )
6343 .with_note(
6344 "the body is buffered with a parsed copy beside it, and a Worker has 128 MB for everything; lower `maxBody`, or hold large uploads to a presigned or multipart-to-R2 flow",
6345 ),
6346 );
6347 }
6348 }
6349 "json" => {
6350 if seen_json {
6351 errors.push(CompileError::new(
6352 "bynk.http.json_duplicate",
6353 ann.span,
6354 "a handler carries at most one `@json` annotation",
6355 ));
6356 continue;
6357 }
6358 seen_json = true;
6359 if !matches!(handler.kind, HandlerKind::Http { .. }) {
6360 errors.push(
6361 CompileError::new(
6362 "bynk.http.json_on_non_http",
6363 ann.span,
6364 "`@json` is only valid on an `on http` handler",
6365 )
6366 .with_note("it chooses how an HTTP response body writes `Option`"),
6367 );
6368 continue;
6369 }
6370 validate_json_args(ann, errors);
6371 }
6372 other => {
6373 errors.push(
6374 CompileError::new(
6375 "bynk.http.unknown_handler_annotation",
6376 ann.name.span,
6377 format!(
6378 "unknown handler annotation `@{other}` — the handler annotations are `@cache`, `@limit`, `@raw`, `@form`, `@multipart` and `@json`"
6379 ),
6380 )
6381 .with_note("handler annotations are a closed set (ADR 0163, ADR 0165)"),
6382 );
6383 }
6384 }
6385 }
6386}
6387
6388pub(crate) fn is_byte_stream(r: &TypeRef) -> bool {
6391 matches!(r, TypeRef::Stream(inner, _) if matches!(**inner, TypeRef::Base(BaseType::Bytes, _)))
6392}
6393
6394const MULTIPART_LARGE_CAP: i64 = 32 * 1024 * 1024;
6397
6398fn body_kind_conflict(ann: &Annotation, this: &str, other: &str) -> CompileError {
6402 CompileError::new(
6403 "bynk.http.body_kind_conflict",
6404 ann.span,
6405 format!("a handler cannot carry both `@{other}` and `@{this}`"),
6406 )
6407 .with_note("`@raw`, `@form` and `@multipart` each fix the wire format of the one `body` parameter; use one")
6408}
6409
6410fn is_bool_leaf(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
6413 match r {
6414 TypeRef::Base(b, _) => matches!(b, BaseType::Bool),
6415 TypeRef::Named(id) => matches!(
6416 types.get(&id.name).map(|t| &t.body),
6417 Some(TypeBody::Refined { base, .. } | TypeBody::Opaque { base, .. })
6418 if matches!(base, BaseType::Bool)
6419 ),
6420 _ => false,
6421 }
6422}
6423
6424pub fn is_std_bynk_type(
6427 name: &str,
6428 types: &std::collections::HashMap<String, Arc<TypeDecl>>,
6429 decl: &TypeDecl,
6430) -> bool {
6431 types.get(name).is_some_and(|d| d.span == decl.span)
6432 && crate::firstparty::unit(bynk_std::BYNK_UNIT)
6433 .is_some_and(|unit| decl.span.file == crate::project_model::firstparty_file_id(unit))
6434}
6435
6436pub fn is_std_file_type(
6440 name: &str,
6441 types: &std::collections::HashMap<String, Arc<TypeDecl>>,
6442) -> bool {
6443 name == "File"
6444 && types.get(name).is_some_and(|decl| {
6445 crate::firstparty::unit(bynk_std::BYNK_UNIT).is_some_and(|unit| {
6446 decl.span.file == crate::project_model::firstparty_file_id(unit)
6447 })
6448 })
6449}
6450
6451fn is_file_field_type(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
6455 let named = |t: &TypeRef| matches!(t, TypeRef::Named(id) if is_std_file_type(&id.name, types));
6456 match r {
6457 TypeRef::Option(inner, _) | TypeRef::List(inner, _) => named(inner),
6458 other => named(other),
6459 }
6460}
6461
6462fn file_path(t: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> Option<Vec<String>> {
6466 fn walk(
6467 t: &TypeRef,
6468 types: &HashMap<String, Arc<TypeDecl>>,
6469 visited: &mut std::collections::HashSet<String>,
6470 ) -> Option<Vec<String>> {
6471 match t {
6472 TypeRef::Named(id) if is_std_file_type(&id.name, types) => Some(Vec::new()),
6473 TypeRef::Named(id) => named(&id.name, types, visited),
6474 TypeRef::App { name, args, .. } => named(&name.name, types, visited)
6475 .or_else(|| args.iter().find_map(|a| walk(a, types, visited))),
6476 TypeRef::Option(a, _) | TypeRef::List(a, _) | TypeRef::Set(a, _) => {
6477 walk(a, types, visited)
6478 }
6479 TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
6480 walk(a, types, visited).or_else(|| walk(b, types, visited))
6481 }
6482 _ => None,
6483 }
6484 }
6485 fn named(
6486 name: &str,
6487 types: &HashMap<String, Arc<TypeDecl>>,
6488 visited: &mut std::collections::HashSet<String>,
6489 ) -> Option<Vec<String>> {
6490 if !visited.insert(name.to_string()) {
6491 return None;
6492 }
6493 let decl = types.get(name)?;
6494 let found = match &decl.body {
6495 TypeBody::Record(r) => r.fields.iter().find_map(|f| {
6496 walk(&f.type_ref, types, visited).map(|mut p| {
6497 p.insert(0, f.name.name.clone());
6498 p
6499 })
6500 }),
6501 TypeBody::Sum(s) => s.variants.iter().find_map(|v| {
6502 v.payload.iter().find_map(|f| {
6503 walk(&f.type_ref, types, visited).map(|mut p| {
6504 p.insert(0, f.name.name.clone());
6505 p
6506 })
6507 })
6508 }),
6509 _ => None,
6510 };
6511 visited.remove(name);
6512 found
6513 }
6514 walk(t, types, &mut std::collections::HashSet::new())
6515}
6516
6517fn validate_form_body(
6523 p: &Param,
6524 kind: &str,
6525 types: &HashMap<String, Arc<TypeDecl>>,
6526 errors: &mut Vec<CompileError>,
6527) {
6528 let multipart = kind == "multipart";
6529 let record = match &p.type_ref {
6530 TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
6531 Some(TypeBody::Record(r)) => Some(r),
6532 _ => None,
6533 },
6534 _ => None,
6535 };
6536 let Some(record) = record else {
6537 errors.push(
6538 CompileError::new(
6539 "bynk.http.form_body_not_record",
6540 p.type_ref.span(),
6541 format!(
6542 "the `body` of a `@{kind}` handler must be a record type (got `{}`)",
6543 ts_type_ref_display(&p.type_ref),
6544 ),
6545 )
6546 .with_note(
6547 "a form body decodes into a record, one field per form key: `body: SignupForm`",
6548 ),
6549 );
6550 return;
6551 };
6552 for f in &record.fields {
6553 let is_file = multipart && is_file_field_type(&f.type_ref, types);
6554 if !is_file && !is_query_field_type(&f.type_ref, types) {
6555 errors.push(
6556 CompileError::new(
6557 "bynk.http.form_field_not_stringy",
6558 f.type_ref.span(),
6559 format!(
6560 "field `{}` of the `@{kind}` body record has type `{}`, which a {kind} body cannot carry",
6561 f.name.name,
6562 ts_type_ref_display(&f.type_ref),
6563 ),
6564 )
6565 .with_note(if multipart {
6566 "a multipart field is a `String`, `Int`, `Bool`, `Decimal`, an enum, or a refined or opaque type over one, or a `File`, optionally in an `Option` or a `List` (a repeated part); keys are flat, so a nested record is not allowed"
6567 } else {
6568 "a form field is a `String`, `Int`, `Bool`, `Decimal`, an enum, or a refined or opaque type over one, optionally in an `Option` or a `List` (a repeated key); form keys are flat, so a nested record is not allowed"
6569 }),
6570 );
6571 } else if f.init.is_none() && is_bool_leaf(&f.type_ref, types) {
6572 errors.push(
6573 CompileError::new(
6574 "bynk.http.form_bool_without_default",
6575 f.type_ref.span(),
6576 format!(
6577 "`Bool` field `{}` of a `@{kind}` body has no default, so an unchecked checkbox is a `400`",
6578 f.name.name,
6579 ),
6580 )
6581 .with_note(
6582 "a browser sends nothing for an unchecked checkbox; give the field `= false`, or make it an `Option[Bool]`",
6583 ),
6584 );
6585 }
6586 }
6587}
6588
6589fn validate_cache_args(ann: &Annotation, errors: &mut Vec<CompileError>) {
6595 let mut max_age: Option<&AnnotationArg> = None;
6596 let mut scope: Option<&AnnotationArg> = None;
6597 let mut immutable: Option<&AnnotationArg> = None;
6598 for arg in &ann.args {
6599 match arg.label.as_ref().map(|l| l.name.as_str()) {
6600 Some("maxAge") => max_age = Some(arg),
6601 Some("scope") => scope = Some(arg),
6602 Some("immutable") => immutable = Some(arg),
6603 _ => {
6604 errors.push(
6605 CompileError::new(
6606 "bynk.http.cache_unknown_arg",
6607 arg.span,
6608 "`@cache` accepts only the `maxAge:`, `scope:` and `immutable:` arguments",
6609 )
6610 .with_note("write `@cache(maxAge: 5.minutes, scope: private)`"),
6611 );
6612 }
6613 }
6614 }
6615 match max_age.map(|a| &a.value.kind) {
6629 Some(ExprKind::DurationLit { millis, .. }) if *millis > 0 && *millis % 1000 == 0 => {}
6630 Some(ExprKind::DurationLit { millis, .. }) if *millis > 0 => {
6631 errors.push(
6632 CompileError::new(
6633 "bynk.http.cache_max_age_fractional_seconds",
6634 max_age.unwrap().span,
6635 "`@cache` `maxAge` must be a whole number of seconds",
6636 )
6637 .with_note(
6638 "`Cache-Control: max-age` is whole seconds — a value with a fractional \
6639 second would silently drop the remainder rather than round or reject, \
6640 so it is not honoured exactly",
6641 ),
6642 );
6643 }
6644 Some(_) => {
6645 let arg = max_age.unwrap();
6646 errors.push(crate::annotation_consts::with_const_origin(
6647 CompileError::new(
6648 "bynk.http.cache_bad_max_age",
6649 arg.span,
6650 "`@cache` `maxAge` must be a positive `Duration` literal (e.g. `5.minutes`), or a `Duration` constant bound to one",
6651 ),
6652 arg,
6653 ));
6654 }
6655 None => {
6656 errors.push(
6657 CompileError::new(
6658 "bynk.http.cache_bad_max_age",
6659 ann.span,
6660 "`@cache` requires a `maxAge:` argument — the freshness window",
6661 )
6662 .with_note(
6663 "the `ETag` revalidation is automatic; only the freshness window is declared",
6664 ),
6665 );
6666 }
6667 }
6668 if let Some(scope) = scope {
6670 let ok = matches!(
6671 &scope.value.kind,
6672 ExprKind::Ident(id) if id.name == "public" || id.name == "private"
6673 );
6674 if !ok {
6675 errors.push(CompileError::new(
6676 "bynk.http.cache_bad_scope",
6677 scope.span,
6678 "`@cache` `scope` must be `public` or `private`",
6679 ));
6680 }
6681 }
6682 if let Some(immutable) = immutable
6686 && !matches!(immutable.value.kind, ExprKind::BoolLit(_))
6687 {
6688 errors.push(
6689 CompileError::new(
6690 "bynk.http.cache_bad_immutable",
6691 immutable.span,
6692 "`@cache` `immutable` must be `true` or `false`",
6693 )
6694 .with_note(
6695 "`immutable: true` promises the response at this URL never changes, so caches \
6696 do not revalidate it within `maxAge` — true of content-addressed paths",
6697 ),
6698 );
6699 }
6700}
6701
6702fn validate_limit_args(ann: &Annotation, is_multipart: bool, errors: &mut Vec<CompileError>) {
6709 let mut max_body: Option<&AnnotationArg> = None;
6710 let mut multipart_args = 0;
6711 for arg in &ann.args {
6712 match arg.label.as_ref().map(|l| l.name.as_str()) {
6713 Some("maxBody") => max_body = Some(arg),
6714 Some(name @ ("maxFile" | "maxParts")) => {
6716 multipart_args += 1;
6717 if !is_multipart {
6718 errors.push(
6719 CompileError::new(
6720 "bynk.http.limit_on_non_multipart",
6721 arg.span,
6722 format!("`@limit` `{name}` is only valid on a `@multipart` route"),
6723 )
6724 .with_note(
6725 "a per-file or part-count cap governs the parts of a multipart body",
6726 ),
6727 );
6728 } else if !matches!(&arg.value.kind, ExprKind::IntLit { value: n, .. } if *n > 0) {
6729 errors.push(crate::annotation_consts::with_const_origin(
6730 CompileError::new(
6731 "bynk.http.limit_bad_max_file",
6732 arg.span,
6733 format!(
6734 "`@limit` `{name}` must be a positive `Int` literal, or an `Int` constant bound to one"
6735 ),
6736 ),
6737 arg,
6738 ));
6739 }
6740 }
6741 _ => {
6742 errors.push(
6743 CompileError::new(
6744 "bynk.http.limit_unknown_arg",
6745 arg.span,
6746 "`@limit` accepts only the `maxBody:` argument (and, on a `@multipart` route, `maxFile:` and `maxParts:`)",
6747 )
6748 .with_note("write `@limit(maxBody: 26_214_400)`"),
6749 );
6750 }
6751 }
6752 }
6753 if max_body.is_none() && multipart_args > 0 {
6756 return;
6757 }
6758 match max_body.map(|a| &a.value.kind) {
6760 Some(ExprKind::IntLit { value: n, .. }) if *n > 0 => {}
6761 Some(_) => {
6762 let arg = max_body.unwrap();
6763 errors.push(crate::annotation_consts::with_const_origin(
6764 CompileError::new(
6765 "bynk.http.limit_bad_max_body",
6766 arg.span,
6767 "`@limit` `maxBody` must be a positive `Int` literal — a byte count (e.g. `26_214_400`), or an `Int` constant bound to one",
6768 ),
6769 arg,
6770 ));
6771 }
6772 None => {
6773 errors.push(
6774 CompileError::new(
6775 "bynk.http.limit_bad_max_body",
6776 ann.span,
6777 "`@limit` requires a `maxBody:` argument — the byte ceiling",
6778 )
6779 .with_note(
6780 "the ceiling is a policy the compiler cannot derive; only the author knows it",
6781 ),
6782 );
6783 }
6784 }
6785}
6786
6787fn validate_raw_args(ann: &Annotation, errors: &mut Vec<CompileError>) {
6791 let mut content_type: Option<&AnnotationArg> = None;
6792 for arg in &ann.args {
6793 match arg.label.as_ref().map(|l| l.name.as_str()) {
6794 Some("contentType") => content_type = Some(arg),
6795 _ => {
6796 errors.push(
6797 CompileError::new(
6798 "bynk.http.raw_unknown_arg",
6799 arg.span,
6800 "`@raw` accepts only the `contentType:` argument",
6801 )
6802 .with_note("write `@raw(contentType: \"application/octet-stream\")`"),
6803 );
6804 }
6805 }
6806 }
6807 match content_type.map(|a| &a.value.kind) {
6808 Some(ExprKind::StrLit(s)) if bynk_syntax::ast::is_media_type(s) => {}
6809 Some(_) => {
6810 let arg = content_type.unwrap();
6811 errors.push(crate::annotation_consts::with_const_origin(
6812 CompileError::new(
6813 "bynk.http.raw_bad_content_type",
6814 arg.span,
6815 "`@raw` `contentType` must be a media type string literal (or a `String` constant bound to one) — `type/subtype`, or `\"*/*\"` to accept any",
6816 ),
6817 arg,
6818 ));
6819 }
6820 None => {
6821 errors.push(
6822 CompileError::new(
6823 "bynk.http.raw_bad_content_type",
6824 ann.span,
6825 "`@raw` requires a `contentType:` argument — the media type the route accepts",
6826 )
6827 .with_note("use `\"*/*\"` to accept any content type"),
6828 );
6829 }
6830 }
6831}
6832
6833fn check_cron_schedule(handler: &Handler, expr: &str, errors: &mut Vec<CompileError>) {
6838 match bynk_syntax::cron::is_cron_expression(expr) {
6839 Err(fault) => {
6840 let mut err = CompileError::new(
6841 "bynk.cron.invalid_schedule",
6842 handler.span,
6843 format!("cron schedule `{expr}` is invalid: {}", fault.message()),
6844 )
6845 .with_note(
6846 "the fields are: minute hour day-of-month month day-of-week, separated by exactly one space",
6847 );
6848 let single_spaced = expr.split_whitespace().collect::<Vec<_>>().join(" ");
6849 if single_spaced != expr
6850 && bynk_syntax::cron::is_cron_expression(&single_spaced).is_ok()
6851 {
6852 err = err.with_note(format!(
6853 "write it with single spaces: `{single_spaced}` (Cloudflare matches the schedule character for character)"
6854 ));
6855 }
6856 errors.push(err);
6857 }
6858 Ok(()) => {
6859 if bynk_syntax::cron::numeric_weekday(expr) {
6860 errors.push(
6861 CompileError::new(
6862 "bynk.cron.numeric_weekday",
6863 handler.span,
6864 format!("cron schedule `{expr}` names a day of the week by number"),
6865 )
6866 .with_note(
6867 "on Cloudflare `1` is Sunday, so a number is a day earlier than standard cron's (`5` is Thursday, not Friday); write the name (`FRI`) to be explicit",
6868 ),
6869 );
6870 }
6871 if let Some(when) = bynk_syntax::cron::uneven_step(expr) {
6872 errors.push(
6873 CompileError::new(
6874 "bynk.cron.uneven_step",
6875 handler.span,
6876 format!("cron schedule `{expr}` has an uneven step"),
6877 )
6878 .with_note(when)
6879 .with_note(
6880 "list the times you mean, or use a step that divides the field's range",
6881 ),
6882 );
6883 }
6884 }
6885 }
6886}
6887
6888fn validate_cron_handler(handler: &Handler, expr: &str, errors: &mut Vec<CompileError>) {
6893 if handler.params.len() > 1 {
6896 errors.push(
6897 CompileError::new(
6898 "bynk.cron.bad_params",
6899 handler.params[1].span,
6900 "`on schedule` handlers take at most one parameter (the scheduled time)",
6901 )
6902 .with_note("a scheduled trigger's only input is the time it fired"),
6903 );
6904 } else if let Some(p) = handler.params.first()
6905 && !matches!(p.type_ref, TypeRef::Base(BaseType::Instant, _))
6906 {
6907 errors.push(
6908 CompileError::new(
6909 "bynk.cron.bad_params",
6910 p.type_ref.span(),
6911 format!(
6912 "an `on schedule` parameter must be `Instant` (the scheduled time), got `{}`",
6913 ts_type_ref_display(&p.type_ref),
6914 ),
6915 )
6916 .with_note(
6917 "declare it as `at: Instant`; where the body needs the number, use `at.toEpochMillis()`",
6918 ),
6919 );
6920 }
6921 check_cron_schedule(handler, expr, errors);
6922 let return_ok = match &handler.return_type {
6924 TypeRef::Effect(inner, _) => match inner.as_ref() {
6925 TypeRef::Result(ok, _err, _) => matches!(ok.as_ref(), TypeRef::Unit(_)),
6926 _ => false,
6927 },
6928 _ => false,
6929 };
6930 if !return_ok {
6931 errors.push(CompileError::new(
6932 "bynk.cron.return_not_effect_result",
6933 handler.return_type.span(),
6934 format!(
6935 "`on cron` handler must return `Effect[Result[(), E]]`, but got `{}`",
6936 ts_type_ref_display(&handler.return_type),
6937 ),
6938 ));
6939 }
6940}
6941
6942fn validate_queue_handler(handler: &Handler, name: &str, errors: &mut Vec<CompileError>) {
6949 if name.is_empty() {
6950 errors.push(CompileError::new(
6951 "bynk.queue.invalid_name",
6952 handler.span,
6953 "`on queue` requires a non-empty queue name",
6954 ));
6955 } else if !crate::project_model::is_queue_name(name) {
6956 errors.push(
6957 CompileError::new(
6958 "bynk.queue.invalid_name",
6959 handler.span,
6960 format!("`{name}` is not a queue name Cloudflare accepts"),
6961 )
6962 .with_note(
6963 "a queue name is 1 to 63 lowercase letters, digits or `-`, and starts and ends with a letter or digit",
6964 ),
6965 );
6966 }
6967 if handler.params.len() != 1 {
6969 errors.push(
6970 CompileError::new(
6971 "bynk.queue.bad_params",
6972 handler.span,
6973 format!(
6974 "`on message` handlers take exactly one parameter (the message), got {}",
6975 handler.params.len(),
6976 ),
6977 )
6978 .with_note("a queue consumer processes one message per invocation"),
6979 );
6980 }
6981 let return_ok = match &handler.return_type {
6983 TypeRef::Effect(inner, _) => matches!(inner.as_ref(), TypeRef::QueueResult(_)),
6984 _ => false,
6985 };
6986 if !return_ok {
6987 errors.push(CompileError::new(
6988 "bynk.queue.return_not_queue_result",
6989 handler.return_type.span(),
6990 format!(
6991 "`on message` handler must return `Effect[QueueResult]`, but got `{}`",
6992 ts_type_ref_display(&handler.return_type),
6993 ),
6994 ));
6995 }
6996}
6997
6998fn is_string_constructible(r: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
7001 match r {
7002 TypeRef::Base(BaseType::String, _) => true,
7003 TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
7004 Some(TypeBody::Refined { base, .. }) => *base == BaseType::String,
7005 Some(TypeBody::Opaque { base, .. }) => *base == BaseType::String,
7006 _ => false,
7007 },
7008 _ => false,
7009 }
7010}
7011
7012pub fn type_ref_is_held(r: &TypeRef) -> bool {
7021 match r {
7022 TypeRef::Connection(..) => true,
7023 TypeRef::Option(inner, _) | TypeRef::Effect(inner, _) => type_ref_is_held(inner),
7024 _ => false,
7025 }
7026}
7027
7028pub fn validate_store_field_value_types(
7035 f: &StoreField,
7036 types: &std::collections::HashMap<String, Arc<TypeDecl>>,
7037 errors: &mut Vec<CompileError>,
7038) {
7039 let head = f.kind.head.name.as_str();
7040 let reject_held_storage = |span: Span, errors: &mut Vec<CompileError>| {
7041 errors.push(
7042 CompileError::new(
7043 "bynk.held.unsupported_storage",
7044 span,
7045 format!(
7046 "a held value cannot be stored in a `{head}` — held resources may only live in `Cell[Option[Connection]]` or `Map[K, Connection]` (§2.9.3)"
7047 ),
7048 )
7049 .with_note(
7050 "`Set` needs value-equality, and `Log`/`Cache` would retain or evict a held resource without disposing it",
7051 ),
7052 );
7053 };
7054 match head {
7055 "Cell" => match f.kind.args.first() {
7057 Some(v) if type_ref_is_held(v) => {} Some(v) => reject_fn_types(v, "an agent store field", types, errors),
7059 None => {}
7060 },
7061 "Map" => match f.kind.args.as_slice() {
7062 [k, v] => {
7063 reject_fn_types(k, "an agent store field", types, errors); if !type_ref_is_held(v) {
7065 reject_fn_types(v, "an agent store field", types, errors);
7066 }
7067 }
7068 args => {
7069 for arg in args {
7070 reject_fn_types(arg, "an agent store field", types, errors);
7071 }
7072 }
7073 },
7074 "Set" | "Cache" | "Log" => {
7076 for arg in &f.kind.args {
7077 if type_ref_is_held(arg) {
7078 reject_held_storage(arg.span(), errors);
7079 } else {
7080 reject_fn_types(arg, "an agent store field", types, errors);
7081 }
7082 }
7083 }
7084 _ => {
7085 for arg in &f.kind.args {
7086 reject_fn_types(arg, "an agent store field", types, errors);
7087 }
7088 }
7089 }
7090}
7091
7092pub const CAPABILITY_SIGNATURE: &str = "a capability operation signature";
7097pub const RECORD_FIELD: &str = "a record field";
7098pub const SUM_PAYLOAD: &str = "a sum-variant payload";
7099pub const REQUEST_RECORD_PARAM: &str = "a request record parameter";
7103
7104pub fn reject_fn_types(
7105 r: &TypeRef,
7106 what: &str,
7107 types: &std::collections::HashMap<String, Arc<TypeDecl>>,
7108 errors: &mut Vec<CompileError>,
7109) {
7110 match r {
7111 TypeRef::Fn(_, _, span) => {
7112 errors.push(
7113 CompileError::new(
7114 "bynk.types.function_at_boundary",
7115 *span,
7116 format!(
7117 "a function type cannot appear in {what} — functions cannot serialise or cross a boundary"
7118 ),
7119 )
7120 .with_note(
7121 "function types are confined to fn/lambda parameters, returns, and locals",
7122 ),
7123 );
7124 }
7125 TypeRef::Query(_, span) => {
7128 errors.push(
7129 CompileError::new(
7130 "bynk.types.query_at_boundary",
7131 *span,
7132 format!(
7133 "a `Query` type cannot appear in {what} — a query is built and executed in place, never persisted or sent across a boundary"
7134 ),
7135 )
7136 .with_note(
7137 "terminate the query (`.collect`/`.first`/…) and store or send the result instead",
7138 ),
7139 );
7140 }
7141 TypeRef::TokenClaims(span) => {
7144 errors.push(
7145 CompileError::new(
7146 "bynk.types.claims_at_boundary",
7147 *span,
7148 format!(
7149 "a `TokenClaims` type cannot appear in {what} — it is a verified token's claims, read in the handler that received the token, never persisted or sent"
7150 ),
7151 )
7152 .with_note(
7153 "read the claim you need (`who.claims.get(\"repository\")`) and store or send that value instead",
7154 ),
7155 );
7156 }
7157 TypeRef::RequestHeaders(span) => {
7162 errors.push(
7163 CompileError::new(
7164 "bynk.types.headers_at_boundary",
7165 *span,
7166 format!(
7167 "a `RequestHeaders` type cannot appear in {what} — it is the request's headers, read in the handler that receives them, never persisted or sent"
7168 ),
7169 )
7170 .with_note(
7171 "read the header you need (`headers.get(\"…\")`) and store or send that value instead",
7172 ),
7173 );
7174 }
7175 TypeRef::RequestQuery(span) => {
7178 errors.push(
7179 CompileError::new(
7180 "bynk.types.request_query_at_boundary",
7181 *span,
7182 format!(
7183 "a `RequestQuery` type cannot appear in {what} — it is the request's query string, read in the handler that receives it, never persisted or sent"
7184 ),
7185 )
7186 .with_note(
7187 "read the value you need (`query.get(\"…\")`) and store or send that value instead",
7188 ),
7189 );
7190 }
7191 TypeRef::RequestCookies(span) => {
7194 errors.push(
7195 CompileError::new(
7196 "bynk.types.request_cookies_at_boundary",
7197 *span,
7198 format!(
7199 "a `RequestCookies` type cannot appear in {what} — it is the request's cookies, read in the handler that receives it, never persisted or sent"
7200 ),
7201 )
7202 .with_note(
7203 "read the value you need (`cookies.get(\"…\")`) and store or send that value instead",
7204 ),
7205 );
7206 }
7207 TypeRef::BoundaryRejection(span) => {
7210 errors.push(
7211 CompileError::new(
7212 "bynk.types.rejection_at_boundary",
7213 *span,
7214 format!(
7215 "a `BoundaryRejection` type cannot appear in {what} — it describes a request the router refused, read by `on rejected`, never persisted or sent"
7216 ),
7217 )
7218 .with_note(
7219 "match on the rejection in `on rejected` and store or send what you need from it instead",
7220 ),
7221 );
7222 }
7223 TypeRef::Stream(..) if stream_passes(what) => {}
7228 TypeRef::Stream(_, span) => {
7232 errors.push(
7233 CompileError::new(
7234 "bynk.types.stream_at_boundary",
7235 *span,
7236 format!(
7237 "a `Stream` type cannot appear in {what} — a stream is a live value-over-time source, never persisted or sent across a boundary"
7238 ),
7239 )
7240 .with_note(
7241 "drain the stream (`.collect()`) and store or send the resulting `List` instead",
7242 ),
7243 );
7244 }
7245 TypeRef::Connection(_, span) => {
7249 errors.push(
7250 CompileError::new(
7251 "bynk.types.held_at_boundary",
7252 *span,
7253 format!(
7254 "a `Connection` type cannot appear in {what} — a held resource is built and disposed in place, never persisted or sent across a boundary"
7255 ),
7256 )
7257 .with_note(
7258 "hold the connection in agent state (`Cell[Option[Connection]]` / `Map[K, Connection]`) instead of crossing a boundary with it",
7259 ),
7260 );
7261 }
7262 TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
7265 reject_fn_types(a, what, types, errors);
7266 reject_fn_types(b, what, types, errors);
7267 }
7268 TypeRef::Option(a, _)
7269 | TypeRef::Effect(a, _)
7270 | TypeRef::HttpResult(a, _)
7271 | TypeRef::List(a, _)
7272 | TypeRef::Set(a, _) => reject_fn_types(a, what, types, errors),
7273 TypeRef::History(_, _) => {}
7277 TypeRef::App { name, args, span } => {
7290 if !stream_passes(what)
7291 && let Some(rg) = bynk_syntax::ast::recursive_generic_path(
7292 &TypeRef::App {
7293 name: name.clone(),
7294 args: Vec::new(),
7295 span: *span,
7296 },
7297 types,
7298 )
7299 {
7300 errors.push(recursive_generic_at_boundary(&rg, *span, what));
7301 }
7302 for a in args {
7303 reject_fn_types(a, what, types, errors);
7304 }
7305 if !stream_passes(what)
7309 && let Some(path) =
7310 bynk_syntax::ast::stream_path(&TypeRef::Named(name.clone()), types)
7311 {
7312 errors.push(stream_carrying_at_boundary(&name.name, &path, *span, what));
7313 }
7314 }
7315 TypeRef::Asset(span) => {
7318 errors.push(
7319 CompileError::new(
7320 "bynk.types.asset_at_boundary",
7321 *span,
7322 format!(
7323 "an `Asset` type cannot appear in {what} — an asset names a file the platform serves, not a value to persist or send"
7324 ),
7325 )
7326 .with_note("store or send the asset's `.url` (a `String`) instead"),
7327 );
7328 }
7329 TypeRef::Named(id)
7333 if what != CAPABILITY_SIGNATURE
7334 && crate::checker::is_sql_statement_type(&id.name, types) =>
7335 {
7336 errors.push(statement_at_boundary(id.span, what, &id.name));
7337 }
7338 TypeRef::Named(id)
7345 if what != CAPABILITY_SIGNATURE && is_crypto_key_type(&id.name, types) =>
7346 {
7347 errors.push(
7348 CompileError::new(
7349 "bynk.types.key_at_boundary",
7350 id.span,
7351 format!(
7352 "a `{}` cannot appear in {what} — a key is held non-extractable by the platform and lives for the call that imported it, never persisted, logged or sent across a boundary",
7353 id.name
7354 ),
7355 )
7356 .with_note(
7357 "keep the key bytes in `Secrets` and import the key again where it is used (`Crypto.importSigningKey` / `Crypto.importVerifyKey`)",
7358 ),
7359 );
7360 }
7361 TypeRef::Named(id)
7365 if what != REQUEST_RECORD_PARAM && record_has_field_names(&id.name, types) =>
7366 {
7367 errors.push(
7368 CompileError::new(
7369 "bynk.types.field_name_record_not_boundary",
7370 id.span,
7371 format!(
7372 "`{}` has `@name` fields, so it can only be a `cookies`, `query` or `@form`/`@multipart` `body` parameter, not {what}",
7373 id.name
7374 ),
7375 )
7376 .with_note(
7377 "a record's JSON form uses its field names, so a `@name` rename would split the two; use a separate record for this position",
7378 ),
7379 );
7380 }
7381 TypeRef::Named(id) if !stream_passes(what) && is_std_file_type(&id.name, types) => {
7386 errors.push(file_at_boundary(&id.name, &[], id.span, what));
7387 }
7388 TypeRef::Named(id) if !stream_passes(what) => {
7391 if let Some(path) = file_path(r, types) {
7392 errors.push(file_at_boundary(&id.name, &path, id.span, what));
7393 }
7394 if let Some(path) = bynk_syntax::ast::stream_path(r, types) {
7395 errors.push(stream_carrying_at_boundary(&id.name, &path, id.span, what));
7396 }
7397 if let Some(rg) = bynk_syntax::ast::recursive_generic_path(r, types) {
7399 errors.push(recursive_generic_at_boundary(&rg, id.span, what));
7400 }
7401 }
7402 TypeRef::Base(..)
7403 | TypeRef::Named(_)
7404 | TypeRef::QueueResult(_)
7405 | TypeRef::ValidationError(_)
7406 | TypeRef::DecodeError(_)
7407 | TypeRef::Unit(_) => {}
7408 }
7409}
7410
7411fn record_has_field_names(name: &str, types: &HashMap<String, Arc<TypeDecl>>) -> bool {
7413 matches!(
7414 types.get(name).map(|t| &t.body),
7415 Some(TypeBody::Record(r)) if r.fields.iter().any(|f| !f.annotations.is_empty())
7416 )
7417}
7418
7419fn file_at_boundary(name: &str, path: &[String], span: Span, what: &str) -> CompileError {
7422 let reach = if path.is_empty() {
7423 String::new()
7424 } else {
7425 let chain = path
7426 .iter()
7427 .map(|f| format!("`{f}`"))
7428 .collect::<Vec<_>>()
7429 .join(", then ");
7430 format!(" (it is reached through {chain})")
7431 };
7432 CompileError::new(
7433 "bynk.types.file_at_boundary",
7434 span,
7435 format!(
7436 "`{name}` cannot appear in {what} — it holds a file part of a multipart request in memory, never persisted, sent across a boundary or returned{reach}"
7437 ),
7438 )
7439 .with_note(
7440 "take the part's `bytes` (and `filename`, `contentType`) in the `@multipart` handler and store them where they belong, as `R2.put(key, f.bytes)` does",
7441 )
7442}
7443
7444fn stream_passes(what: &str) -> bool {
7449 [CAPABILITY_SIGNATURE, RECORD_FIELD, SUM_PAYLOAD].contains(&what)
7450}
7451
7452pub(crate) fn recursive_generic_at_boundary(
7457 rg: &bynk_syntax::ast::RecursiveGenericPath,
7458 span: Span,
7459 what: &str,
7460) -> CompileError {
7461 let err = CompileError::new(
7462 "bynk.generics.recursive_generic_at_boundary",
7463 span,
7464 format!(
7465 "recursive generic {} `{}` cannot appear in {what} — it has no codec yet",
7466 rg.noun, rg.name
7467 ),
7468 );
7469 let chain = rg
7470 .path
7471 .iter()
7472 .map(|f| format!("`{f}`"))
7473 .collect::<Vec<_>>()
7474 .join(", then ");
7475 let reach = if rg.path.is_empty() {
7476 String::new()
7477 } else {
7478 format!(" (it is reached through {chain})")
7479 };
7480 err.with_note(format!(
7481 "a recursive generic type declares and works inside a context, but has no codec yet{reach}; \
7482 use a concrete recursive type, or keep it inside the context"
7483 ))
7484}
7485
7486fn stream_carrying_at_boundary(
7489 name: &str,
7490 path: &[String],
7491 span: Span,
7492 what: &str,
7493) -> CompileError {
7494 let chain = path
7495 .iter()
7496 .map(|f| format!("`{f}`"))
7497 .collect::<Vec<_>>()
7498 .join(", then ");
7499 CompileError::new(
7500 "bynk.types.stream_at_boundary",
7501 span,
7502 format!(
7503 "`{name}` cannot appear in {what} — it carries a `Stream`, a live value-over-time source, never persisted or sent across a boundary"
7504 ),
7505 )
7506 .with_note(format!(
7507 "the stream is reached through {chain}; drain it (`.collect()`) into a type without one before it crosses"
7508 ))
7509}
7510
7511pub(crate) fn is_crypto_key_type(
7516 name: &str,
7517 types: &std::collections::HashMap<String, Arc<TypeDecl>>,
7518) -> bool {
7519 crate::firstparty::CRYPTO_KEY_TYPES.contains(&name)
7520 && types.get(name).is_some_and(|decl| {
7521 crate::firstparty::unit(crate::firstparty::CRYPTO_UNIT).is_some_and(|unit| {
7522 decl.span.file == crate::project_model::firstparty_file_id(unit)
7523 })
7524 })
7525}
7526
7527#[cfg(test)]
7533mod actor_binding_persistence_tests {
7534 use super::*;
7535 use crate::checker::CheckedProgram;
7536 use crate::{resolver, symbols};
7537 use bynk_project::UnitKind;
7538 use bynk_syntax::ast::{ActorDecl, Commons, CommonsItem, ServiceDecl, SourceUnit};
7539 use bynk_syntax::{lexer, parser};
7540
7541 fn checked_context_commons(source: &str) -> (checker::TypedCommons, Vec<CompileError>) {
7552 let tokens = lexer::tokenize(source).expect("lex");
7553 let unit = parser::parse_unit(&tokens, source).expect("parse");
7554 let SourceUnit::Context(ctx) = unit else {
7555 panic!("expected a context unit, got {unit:?}")
7556 };
7557 let commons = Commons {
7558 name: ctx.name,
7559 items: ctx.items,
7560 uses: ctx.uses,
7561 documentation: ctx.documentation,
7562 form: ctx.form,
7563 span: ctx.span,
7564 trivia: ctx.trivia,
7565 trailing_comments: ctx.trailing_comments,
7566 };
7567 let resolved = resolver::resolve(commons).expect("resolve");
7568 let mut typed = checker::check(resolved).expect("check");
7569 let services: HashMap<String, ServiceDecl> = typed
7570 .commons
7571 .items
7572 .iter()
7573 .filter_map(|item| match item {
7574 CommonsItem::Service(s) => Some((s.name.name.clone(), s.clone())),
7575 _ => None,
7576 })
7577 .collect();
7578 let actors: HashMap<String, ActorDecl> = typed
7579 .commons
7580 .items
7581 .iter()
7582 .filter_map(|item| match item {
7583 CommonsItem::Actor(a) => Some((a.name.name.clone(), a.clone())),
7584 _ => None,
7585 })
7586 .collect();
7587 let table = symbols::UnitTable {
7588 kind: Some(UnitKind::Context),
7589 types: typed.types.clone(),
7590 services,
7591 actors,
7592 ..symbols::UnitTable::default()
7593 };
7594 let tys = typed.ty_intern.clone();
7595 let errors = check_context_declarations(
7596 &mut typed,
7597 &table,
7598 &resolver::CrossContextInfo::default(),
7599 true,
7600 &HashSet::new(),
7601 &HashMap::new(),
7602 &mut RefSink::new(),
7603 &mut HintSink::new(),
7604 &mut LocalsSink::new(),
7605 &mut RequirementSink::new(),
7606 &tys,
7607 );
7608 (typed, errors)
7609 }
7610
7611 fn checked_context_program(source: &str) -> CheckedProgram {
7612 let (typed, errors) = checked_context_commons(source);
7613 checker::certify(typed, errors).expect("certify")
7614 }
7615
7616 fn find_service<'a>(typed: &'a checker::TypedCommons, name: &str) -> &'a ServiceDecl {
7617 typed
7618 .commons
7619 .items
7620 .iter()
7621 .find_map(|item| match item {
7622 CommonsItem::Service(s) if s.name.name == name => Some(s),
7623 _ => None,
7624 })
7625 .unwrap_or_else(|| panic!("no service named `{name}` in this fixture"))
7626 }
7627
7628 #[test]
7629 fn single_actor_by_clause_persists_the_binder_and_sealed_identity_ty() {
7630 let program = checked_context_program(
7631 r#"
7632context demo
7633
7634type UserId = String
7635
7636actor Buyer { auth = Internal, identity = UserId }
7637
7638service Api {
7639 on call(ping: String) -> Effect[String] by u: Buyer {
7640 Effect.pure(ping)
7641 }
7642}
7643"#,
7644 );
7645 let handler = &find_service(program.program(), "Api").handlers[0];
7646 let (binder, ty) = program
7647 .program()
7648 .actor_binding(handler.span)
7649 .unwrap_or_else(|| panic!("expected a persisted actor binding for this handler"));
7650 assert_eq!(binder, "u");
7651 let tys = &program.program().ty_intern;
7652 let Ty::Actor(identity_ty) = &*tys.get(*ty) else {
7653 panic!("expected Ty::Actor, got {:?}", tys.get(*ty))
7654 };
7655 assert_eq!(
7656 identity_ty.display(tys),
7657 "UserId",
7658 "the actor's own declared `identity = UserId` type, sealed"
7659 );
7660 }
7661
7662 #[test]
7663 fn prelude_caller_actor_persists_a_string_identity_binding() {
7664 let program = checked_context_program(
7667 r#"
7668context demo
7669
7670service Api {
7671 on call(ping: String) -> Effect[String] by c: Caller {
7672 Effect.pure(c.identity)
7673 }
7674}
7675"#,
7676 );
7677 let handler = &find_service(program.program(), "Api").handlers[0];
7678 let (binder, ty) = program
7679 .program()
7680 .actor_binding(handler.span)
7681 .unwrap_or_else(|| panic!("expected a persisted actor binding for this handler"));
7682 assert_eq!(binder, "c");
7683 let string_ty = program
7684 .program()
7685 .ty_intern
7686 .intern(Ty::Base(bynk_syntax::ast::BaseType::String));
7687 let expected = program.program().ty_intern.intern(Ty::Actor(string_ty));
7688 assert_eq!(*ty, expected);
7689 }
7690
7691 #[test]
7692 fn sum_by_clause_persists_an_actor_sum_binding() {
7693 let program = checked_context_program(
7702 r#"
7703context demo
7704
7705type UserId = String
7706
7707actor User { auth = Bearer(secret = "AUTH_SECRET"), identity = UserId }
7708
7709service Api from http {
7710 on GET("/whoami") () -> Effect[HttpResult[String]] by who: User | Visitor {
7711 match who {
7712 User(_) => Ok("user")
7713 Visitor => Ok("visitor")
7714 }
7715 }
7716}
7717"#,
7718 );
7719 let handler = &find_service(program.program(), "Api").handlers[0];
7720 let (binder, ty) = program
7721 .program()
7722 .actor_binding(handler.span)
7723 .unwrap_or_else(|| panic!("expected a persisted actor binding for this handler"));
7724 assert_eq!(binder, "who");
7725 let tys = &program.program().ty_intern;
7726 let Ty::ActorSum(members) = &*tys.get(*ty) else {
7727 panic!("expected Ty::ActorSum, got {:?}", tys.get(*ty))
7728 };
7729 assert_eq!(members.len(), 2);
7730 assert_eq!(members[0].0, "User");
7731 assert_eq!(members[0].1.display(tys), "UserId");
7732 assert_eq!(members[1].0, "Visitor");
7733 assert_eq!(
7734 members[1].1.display(tys),
7735 "()",
7736 "Visitor is a unit-identity prelude actor"
7737 );
7738 }
7739
7740 #[test]
7741 fn binderless_by_clause_persists_no_binding() {
7742 let program = checked_context_program(
7743 r#"
7744context demo
7745
7746type UserId = String
7747
7748actor Buyer { auth = Internal, identity = UserId }
7749
7750service Api {
7751 on call(ping: String) -> Effect[String] by Buyer {
7752 Effect.pure(ping)
7753 }
7754}
7755"#,
7756 );
7757 let handler = &find_service(program.program(), "Api").handlers[0];
7758 assert!(
7759 program.program().actor_binding(handler.span).is_none(),
7760 "a binder-less `by <Actor>` clause verifies-and-discards — no identity is bound, \
7761 so no persisted entry should exist for it either"
7762 );
7763 }
7764
7765 #[test]
7766 fn no_by_clause_persists_no_binding() {
7767 let program = checked_context_program(
7768 r#"
7769context demo
7770
7771service Api {
7772 on call(ping: String) -> Effect[String] by Caller {
7773 Effect.pure(ping)
7774 }
7775}
7776"#,
7777 );
7778 let handler = &find_service(program.program(), "Api").handlers[0];
7779 assert!(program.program().actor_binding(handler.span).is_none());
7780 }
7781
7782 #[test]
7783 fn binder_shadowing_a_param_persists_no_binding() {
7784 let (typed, _errors) = checked_context_commons(
7795 r#"
7796context demo
7797
7798type UserId = String
7799
7800actor Buyer { auth = Internal, identity = UserId }
7801
7802service Api {
7803 on call(u: String) -> Effect[String] by u: Buyer {
7804 Effect.pure(u)
7805 }
7806}
7807"#,
7808 );
7809 let handler = &find_service(&typed, "Api").handlers[0];
7810 assert!(typed.actor_binding(handler.span).is_none());
7811 }
7812
7813 #[test]
7814 fn multiple_handlers_persist_distinct_bindings_keyed_per_handler() {
7815 let program = checked_context_program(
7823 r#"
7824context demo
7825
7826type UserId = String
7827
7828actor Buyer { auth = Bearer(secret = "AUTH_JWT_SECRET"), identity = UserId }
7829
7830service Api from http {
7831 on GET("/a") () -> Effect[HttpResult[String]] by u: Buyer {
7832 Ok("a")
7833 }
7834 on GET("/b") () -> Effect[HttpResult[String]] by v: Buyer {
7835 Ok("b")
7836 }
7837 on GET("/c") () -> Effect[HttpResult[String]] by Visitor {
7838 Ok("c")
7839 }
7840}
7841"#,
7842 );
7843 let service = find_service(program.program(), "Api");
7844 assert_eq!(service.handlers.len(), 3);
7845 let (first, second, third) = (
7846 &service.handlers[0],
7847 &service.handlers[1],
7848 &service.handlers[2],
7849 );
7850 let (binder, _) = program
7851 .program()
7852 .actor_binding(first.span)
7853 .unwrap_or_else(|| panic!("expected a persisted binding for the first handler"));
7854 assert_eq!(binder, "u");
7855 let (binder, _) = program
7856 .program()
7857 .actor_binding(second.span)
7858 .unwrap_or_else(|| panic!("expected a persisted binding for the second handler"));
7859 assert_eq!(binder, "v");
7860 assert!(
7861 program.program().actor_binding(third.span).is_none(),
7862 "the third handler binds no actor (`by Visitor`, no binder)"
7863 );
7864 assert_eq!(
7865 program.program().actor_bindings.len(),
7866 2,
7867 "exactly the two `by`-bearing handlers, nothing extra persisted for the third"
7868 );
7869 }
7870}