1use std::collections::HashMap;
35use std::path::PathBuf;
36
37use bynk_check::analysis::ContextBoundaryInfo;
38use bynk_check::checker::{Ty, TyId, Types};
39use bynk_check::contract;
40use bynk_check::resolver::CrossContextService;
41use bynk_check::wire::{self, WireModel, WireRef};
42use bynk_syntax::ast::*;
43use bynk_syntax::span::{FileId, Span};
44
45const HTTP_RESULT: &str = bynk_check::builtin_names::types::HTTP_RESULT;
46
47pub use bynk_model::IrHandlerKind as BoundaryKind;
58pub use bynk_model::IrHttpMethod;
60
61#[derive(Debug, Clone)]
68pub enum Envelope {
69 Empty,
71 Bare { param: String, shape: WireRef },
74 Keyed { params: Vec<(String, WireRef)> },
77 Raw { param: String, content_type: String },
81}
82
83#[derive(Debug, Clone)]
88pub struct ContractForm {
89 pub normal_form: String,
90 pub hash: String,
91}
92
93#[derive(Debug, Clone, PartialEq)]
97pub enum ResponseOrigin {
98 DeclaredSuccess,
101 Constructed { span: Span },
104 BoundaryImplicit { why: &'static str },
106}
107
108#[derive(Debug, Clone, PartialEq)]
110pub struct HttpResponse {
111 pub status: u16,
112 pub variant: String,
116 pub origin: ResponseOrigin,
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum NoCrossContextReason {
123 NotACallHandler,
126 SingleContext,
129}
130
131#[derive(Debug, Clone)]
135pub struct WireContractModel {
136 pub unit: String,
137 pub service: String,
138 pub kind: BoundaryKind,
139 pub handler_span: Span,
140 pub handler_line: usize,
143 pub envelope: Envelope,
144 pub contract: Option<ContractForm>,
146 pub boundary: WireModel,
150 pub type_sites: HashMap<String, Span>,
153 pub responses: Vec<HttpResponse>,
155 pub ok_reachable: bool,
162 pub success: Option<WireRef>,
168 pub no_cross_context: Option<NoCrossContextReason>,
169}
170
171pub fn real_context_count(
190 boundary_info: &HashMap<String, ContextBoundaryInfo>,
191 unit_sources: &HashMap<String, Vec<PathBuf>>,
192) -> usize {
193 boundary_info
194 .keys()
195 .filter(|k| unit_sources.contains_key(k.as_str()))
196 .count()
197}
198
199pub fn wire_contract_at(
213 unit: &str,
214 text: &str,
215 offset: usize,
216 info: &ContextBoundaryInfo,
217 expr_types: &[(Span, TyId)],
218 tys: &Types,
219 context_count: usize,
220) -> Option<WireContractModel> {
221 let tokens = bynk_syntax::lexer::tokenize(text).ok()?;
222 let (parsed, _errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
223 let items: &[CommonsItem] = match parsed.as_ref()? {
224 SourceUnit::Context(c) => &c.items,
225 SourceUnit::Adapter(a) => &a.items,
226 SourceUnit::Commons(_) | SourceUnit::Suite(_) => return None,
227 };
228 for item in items {
229 if let CommonsItem::Service(s) = item
230 && let Some(h) = handler_at(&s.handlers, offset)
231 {
232 return wire_contract_for_service(
233 unit,
234 text,
235 &s.name.name,
236 h,
237 info,
238 expr_types,
239 tys,
240 context_count,
241 );
242 }
243 }
244 None
245}
246
247fn handler_at(handlers: &[Handler], offset: usize) -> Option<&Handler> {
248 handlers
249 .iter()
250 .find(|h| h.span.start <= offset && offset < h.span.end)
251}
252
253#[allow(clippy::too_many_arguments)]
267pub fn wire_contract_for_service(
268 unit: &str,
269 text: &str,
270 service_name: &str,
271 handler: &Handler,
272 info: &ContextBoundaryInfo,
273 expr_types: &[(Span, TyId)],
274 tys: &Types,
275 context_count: usize,
276) -> Option<WireContractModel> {
277 let real = info.services.get(service_name)?;
278 let mut synthetic = real.clone();
279 synthetic.handlers = vec![handler.clone()];
280 let services: HashMap<String, ServiceDecl> =
281 HashMap::from([(service_name.to_string(), synthetic)]);
282 let agents: HashMap<String, AgentDecl> = HashMap::new();
283
284 let boundary_names = wire::collect_boundary_types(&info.types, &services, &agents, &[]);
285 let insts =
286 wire::collect_generic_instantiations(&services, &agents, &boundary_names, &info.types, &[]);
287 let boundary = wire::boundary_model(&boundary_names, &info.types, insts, |_| {
290 wire::Provenance::Owned
291 });
292
293 let type_sites: HashMap<String, Span> = boundary_names
294 .iter()
295 .filter_map(|n| info.types.get(n).map(|d| (n.clone(), d.span)))
296 .collect();
297
298 let envelope = envelope_for(handler, &info.types);
299 let kind = bynk_model::lower_handler_kind_ir(&handler.kind);
300
301 let no_cross_context = if context_count <= 1 {
302 Some(NoCrossContextReason::SingleContext)
303 } else if kind != bynk_model::IrHandlerKind::Call {
304 Some(NoCrossContextReason::NotACallHandler)
305 } else {
306 None
307 };
308 let contract = if no_cross_context.is_none() {
309 Some(contract_form(service_name, handler, &info.types))
310 } else {
311 None
312 };
313
314 let success = if matches!(kind, BoundaryKind::Http { .. }) {
315 http_result_inner(&handler.return_type)
316 .filter(|t| !matches!(t, TypeRef::Unit(_)))
317 .map(|t| wire::wire_ref(t, &info.types))
318 } else {
319 None
320 };
321 let (responses, ok_reachable) = if matches!(kind, BoundaryKind::Http { .. }) {
322 (
323 http_responses(handler, real.span.file, expr_types, tys),
324 ok_is_reachable(handler, real.span.file, expr_types, tys),
325 )
326 } else {
327 (Vec::new(), false)
328 };
329
330 Some(WireContractModel {
331 unit: unit.to_string(),
332 service: service_name.to_string(),
333 kind,
334 handler_span: handler.span,
335 handler_line: line_of(text, handler.span.start),
336 envelope,
337 contract,
338 boundary,
339 type_sites,
340 responses,
341 ok_reachable,
342 success,
343 no_cross_context,
344 })
345}
346
347fn line_of(text: &str, offset: usize) -> usize {
349 text.get(..offset).unwrap_or(text).matches('\n').count() + 1
350}
351
352fn envelope_for(handler: &Handler, types: &HashMap<String, std::sync::Arc<TypeDecl>>) -> Envelope {
353 if let Some(content_type) = handler.raw_content_type() {
354 return Envelope::Raw {
355 param: "body".to_string(),
356 content_type: content_type.to_string(),
357 };
358 }
359 match handler.params.as_slice() {
360 [] => Envelope::Empty,
361 [p] => Envelope::Bare {
362 param: p.name.name.clone(),
363 shape: wire::wire_ref(&p.type_ref, types),
364 },
365 params => Envelope::Keyed {
366 params: params
367 .iter()
368 .map(|p| (p.name.name.clone(), wire::wire_ref(&p.type_ref, types)))
369 .collect(),
370 },
371 }
372}
373
374fn contract_form(
379 service_name: &str,
380 handler: &Handler,
381 types: &HashMap<String, std::sync::Arc<TypeDecl>>,
382) -> ContractForm {
383 let svc = CrossContextService {
384 name: service_name.to_string(),
385 params: handler
386 .params
387 .iter()
388 .map(|p| (p.name.name.clone(), p.type_ref.clone()))
389 .collect(),
390 return_type: handler.return_type.clone(),
391 span: handler.span,
392 foreign_callers: Vec::new(),
393 };
394 let normal_form = contract::service_normal_form(&svc, types);
395 let hash = contract::contract_hash(&normal_form);
396 ContractForm { normal_form, hash }
397}
398
399fn http_responses(
409 handler: &Handler,
410 file: FileId,
411 expr_types: &[(Span, TyId)],
412 tys: &Types,
413) -> Vec<HttpResponse> {
414 let declared_is_http_result =
415 matches!(strip_effect(&handler.return_type), TypeRef::HttpResult(..));
416
417 let mut out = Vec::new();
418 if declared_is_http_result {
419 out.push(HttpResponse {
420 status: 200,
421 variant: "Ok".to_string(),
422 origin: ResponseOrigin::DeclaredSuccess,
423 });
424 }
425
426 let mut walk = ResponseWalk {
427 expr_types,
428 file,
429 tys,
430 declared_is_http_result,
431 seen: out.iter().map(response_key).collect(),
432 saw_option_question: false,
433 out: Vec::new(),
434 };
435 walk.walk_block(&handler.body);
436 out.extend(walk.out);
437
438 if !handler.params.is_empty() {
439 out.push(HttpResponse {
440 status: 400,
441 variant: "StructuralMismatch".to_string(),
442 origin: ResponseOrigin::BoundaryImplicit {
443 why: "every param is structurally re-validated on the way in; a malformed or \
444 refinement-violating value fails closed with a 400 the handler body \
445 never names",
446 },
447 });
448 }
449 if handler.raw_content_type().is_some() {
450 out.push(HttpResponse {
451 status: 413,
452 variant: "PayloadTooLarge".to_string(),
453 origin: ResponseOrigin::BoundaryImplicit {
454 why: "a raw body is counted as it is read and cut off at the route's cap",
455 },
456 });
457 out.push(HttpResponse {
458 status: 415,
459 variant: "UnsupportedMediaType".to_string(),
460 origin: ResponseOrigin::BoundaryImplicit {
461 why: "the request's Content-Type is not the media type `@raw` declares",
462 },
463 });
464 }
465 let multipart = handler
468 .annotations
469 .iter()
470 .any(|a| a.name.name == "multipart");
471 if multipart {
472 out.push(HttpResponse {
473 status: 415,
474 variant: "UnsupportedMediaType".to_string(),
475 origin: ResponseOrigin::BoundaryImplicit {
476 why: "the request's Content-Type is not `multipart/form-data`",
477 },
478 });
479 out.push(HttpResponse {
480 status: 413,
481 variant: "PayloadTooLarge".to_string(),
482 origin: ResponseOrigin::BoundaryImplicit {
483 why: "the body, a file part or the part count is over the route's cap",
484 },
485 });
486 }
487 if handler.annotations.iter().any(|a| a.name.name == "form") {
488 out.push(HttpResponse {
489 status: 415,
490 variant: "UnsupportedMediaType".to_string(),
491 origin: ResponseOrigin::BoundaryImplicit {
492 why: "the request's Content-Type is not `application/x-www-form-urlencoded` (UTF-8)",
493 },
494 });
495 if handler.limit_max_body().is_some() {
496 out.push(HttpResponse {
497 status: 413,
498 variant: "PayloadTooLarge".to_string(),
499 origin: ResponseOrigin::BoundaryImplicit {
500 why: "a capped body is counted as it is read and cut off at the route's cap",
501 },
502 });
503 }
504 }
505 if walk.saw_option_question {
506 out.push(HttpResponse {
507 status: 404,
508 variant: "NotFound".to_string(),
509 origin: ResponseOrigin::BoundaryImplicit {
510 why: "an `Option?` short-circuits to 404 on `None` (ADR 0177)",
511 },
512 });
513 }
514 out
515}
516
517fn ok_is_reachable(
523 handler: &Handler,
524 file: FileId,
525 expr_types: &[(Span, TyId)],
526 tys: &Types,
527) -> bool {
528 let mut walk = ResponseWalk {
529 expr_types,
530 file,
531 tys,
532 declared_is_http_result: matches!(
533 strip_effect(&handler.return_type),
534 TypeRef::HttpResult(..)
535 ),
536 seen: Default::default(),
537 saw_option_question: false,
538 out: Vec::new(),
539 };
540 walk.walk_block(&handler.body);
541 if walk.out.iter().any(|r| r.variant == "Ok") {
542 return true;
543 }
544 let mut exprs = Vec::new();
545 for st in &handler.body.statements {
546 statement_exprs(st, &mut exprs);
547 }
548 exprs.push(&handler.body.tail);
549 exprs.into_iter().any(|e| walk.opaque_http_result(e))
550}
551
552pub fn http_result_inner(t: &TypeRef) -> Option<&TypeRef> {
556 match strip_effect(t) {
557 TypeRef::HttpResult(inner, _) => Some(inner.as_ref()),
558 _ => None,
559 }
560}
561
562pub fn response_payload(resp: &HttpResponse, success: Option<&WireRef>) -> Option<WireRef> {
570 match response_body(resp, success)? {
571 ResponseBody::Value(r) => Some(r),
572 _ => None,
573 }
574}
575
576#[derive(Debug, Clone)]
579pub enum ResponseBody {
580 Value(WireRef),
582 Message,
584 Redirect,
586 Raw,
588 Stream,
590}
591
592pub const REDIRECT_HEADER: &str = "Location";
594
595pub fn response_body(resp: &HttpResponse, success: Option<&WireRef>) -> Option<ResponseBody> {
599 if matches!(resp.origin, ResponseOrigin::BoundaryImplicit { .. }) {
600 return None;
601 }
602 Some(match http_variant(&resp.variant)?.payload {
603 HttpVariantPayload::Value => ResponseBody::Value(success?.clone()),
604 HttpVariantPayload::Message => ResponseBody::Message,
605 HttpVariantPayload::Location => ResponseBody::Redirect,
606 HttpVariantPayload::Streamed => ResponseBody::Stream,
607 HttpVariantPayload::Raw
608 | HttpVariantPayload::RawTagged
609 | HttpVariantPayload::RawStreamed
610 | HttpVariantPayload::RawError => ResponseBody::Raw,
611 HttpVariantPayload::None => return None,
612 })
613}
614
615fn strip_effect(t: &TypeRef) -> &TypeRef {
619 match t {
620 TypeRef::Effect(inner, _) => inner.as_ref(),
621 other => other,
622 }
623}
624
625struct ResponseWalk<'a> {
635 expr_types: &'a [(Span, TyId)],
636 file: FileId,
642 tys: &'a Types,
644 declared_is_http_result: bool,
655 seen: std::collections::HashSet<String>,
656 saw_option_question: bool,
657 out: Vec<HttpResponse>,
658}
659
660impl<'a> ResponseWalk<'a> {
661 fn expr_ty(&self, span: Span) -> Option<std::sync::Arc<Ty>> {
669 self.expr_types
670 .iter()
671 .find(|(s, _)| s.file == self.file && s.start == span.start && s.end == span.end)
672 .map(|(_, t)| self.tys.get(*t))
673 .filter(|t| !matches!(**t, Ty::Error))
674 }
675
676 fn is_http_result_expr(&self, span: Span) -> bool {
685 match self.expr_ty(span).as_deref() {
686 Some(Ty::HttpResult(_)) => true,
687 Some(_) => false,
688 None => self.declared_is_http_result,
689 }
690 }
691
692 fn is_http_result_ident(&self, span: Span) -> bool {
703 matches!(self.expr_ty(span).as_deref(), Some(Ty::HttpResult(_)))
704 }
705
706 fn push(&mut self, variant: HttpVariant, span: Span) {
707 self.push_status(variant, variant.status, span);
708 }
709
710 fn push_raw_error(&mut self, variant: HttpVariant, args: &[Expr], span: Span) {
713 if let Some(status) = args.first().and_then(raw_error_status) {
714 self.push_status(variant, status, span);
715 }
716 }
717
718 fn push_status(&mut self, variant: HttpVariant, status: u16, span: Span) {
719 if self.seen.insert(variant_key(variant.name, status)) {
720 self.out.push(HttpResponse {
721 status,
722 variant: variant.name.to_string(),
723 origin: ResponseOrigin::Constructed { span },
724 });
725 }
726 }
727
728 fn walk_block(&mut self, b: &Block) {
729 for s in &b.statements {
730 let mut exprs = Vec::new();
731 statement_exprs(s, &mut exprs);
732 for e in exprs {
733 self.walk_expr(e);
734 }
735 }
736 self.walk_expr(&b.tail);
737 }
738
739 fn walk_expr(&mut self, e: &Expr) {
740 self.classify(e);
741 for child in expr_children(e) {
742 self.walk_expr(child);
743 }
744 }
745
746 fn opaque_http_result(&self, e: &Expr) -> bool {
755 let named_variant = |n: &str| http_variant(n).is_some();
756 let leaf_opaque = match &e.kind {
757 ExprKind::Call { name, .. } => !named_variant(&name.name),
758 ExprKind::MethodCall { receiver, .. } => {
759 !matches!(&receiver.kind, ExprKind::Ident(id) if id.name == HTTP_RESULT)
760 }
761 ExprKind::Ident(id) => !named_variant(&id.name),
762 ExprKind::FieldAccess { receiver, .. } => {
763 !matches!(&receiver.kind, ExprKind::Ident(id) if id.name == HTTP_RESULT)
764 }
765 _ => false,
766 };
767 (leaf_opaque && matches!(self.expr_ty(e.span).as_deref(), Some(Ty::HttpResult(_))))
768 || expr_children(e)
769 .into_iter()
770 .any(|c| self.opaque_http_result(c))
771 }
772
773 fn classify(&mut self, e: &Expr) {
774 match &e.kind {
775 ExprKind::MethodCall {
776 receiver,
777 method,
778 args,
779 ..
780 } => {
781 if let ExprKind::Ident(id) = &receiver.kind
782 && id.name == HTTP_RESULT
783 && let Some(v) = http_variant(&method.name)
784 {
785 if v.status == AUTHOR_CHOSEN_STATUS {
786 self.push_raw_error(v, args, e.span);
787 } else {
788 self.push(v, e.span);
789 }
790 }
791 }
792 ExprKind::FieldAccess { receiver, field } => {
793 if let ExprKind::Ident(id) = &receiver.kind
794 && id.name == HTTP_RESULT
795 && let Some(v) = http_variant(&field.name)
796 {
797 self.push(v, e.span);
798 }
799 }
800 ExprKind::Ident(id) => {
801 if self.is_http_result_ident(e.span)
802 && let Some(v) = http_variant(&id.name)
803 {
804 self.push(v, e.span);
805 }
806 }
807 ExprKind::Call { name, args, .. } => {
808 if self.is_http_result_expr(e.span)
809 && let Some(v) = http_variant(&name.name)
810 {
811 if v.status == AUTHOR_CHOSEN_STATUS {
812 self.push_raw_error(v, args, e.span);
813 } else {
814 self.push(v, e.span);
815 }
816 }
817 }
818 ExprKind::Ok(_) => {
819 if self.is_http_result_expr(e.span)
820 && let Some(v) = http_variant("Ok")
821 {
822 self.push(v, e.span);
823 }
824 }
825 ExprKind::Question(inner) => {
826 if matches!(self.expr_ty(inner.span).as_deref(), Some(Ty::Option(_))) {
827 self.saw_option_question = true;
828 }
829 }
830 _ => {}
831 }
832 }
833}
834
835fn variant_key(variant: &str, status: u16) -> String {
838 match http_variant(variant) {
839 Some(v) if v.status == AUTHOR_CHOSEN_STATUS => format!("{variant} {status}"),
840 _ => variant.to_string(),
841 }
842}
843
844fn response_key(r: &HttpResponse) -> String {
845 variant_key(&r.variant, r.status)
846}
847
848#[cfg(test)]
849mod tests {
850 use super::*;
851 use std::path::PathBuf;
852
853 fn setup_project(test_name: &str, files: &[(&str, &str)]) -> PathBuf {
857 let root = std::env::temp_dir().join(format!(
858 "bynk-ide-wire-contract-test-{test_name}-{}",
859 std::process::id()
860 ));
861 let _ = std::fs::remove_dir_all(&root);
862 std::fs::create_dir_all(&root).expect("create test root");
863 for (rel, contents) in files {
864 let p = root.join(rel);
865 if let Some(parent) = p.parent() {
866 std::fs::create_dir_all(parent).expect("create parent");
867 }
868 std::fs::write(&p, contents).expect("write file");
869 }
870 root
871 }
872
873 const RATELIMIT_SRC: &str = r#"context ratelimit
878
879consumes bynk { Clock }
880
881type ClientId = String where NonEmpty
882
883type RateView = {
884 allowed: Bool,
885 remaining: Int,
886 resetAt: Int,
887}
888
889agent Limiter {
890 key client: ClientId
891
892 store count: Cell[Int]
893
894 on call hit(now: Int) -> Effect[RateView] {
895 let _ <- count.update((c) => c + 1)
896 RateView { allowed: count < 10, remaining: 10 - count, resetAt: now }
897 }
898}
899
900service api from http {
901 on GET("/check/:client") (client: ClientId) -> Effect[HttpResult[RateView]] by Visitor given Clock {
902 let now <- Clock.now()
903 let view <- Limiter(client).hit(now.toEpochMillis())
904 if view.allowed {
905 Ok(view)
906 } else {
907 TooManyRequests("rate limit exceeded")
908 }
909 }
910}
911"#;
912
913 fn find_offset(text: &str, needle: &str) -> usize {
914 text.find(needle)
915 .unwrap_or_else(|| panic!("`{needle}` not found in fixture"))
916 }
917
918 fn real_context_count(diag: &crate::ProjectDiagnostics) -> usize {
923 super::real_context_count(&diag.boundary_info, &diag.unit_sources)
924 }
925
926 const RAW_SRC: &str = r#"context uploads
927
928service api from http {
929 limits { maxBody: 1000 }
930
931 @raw(contentType: "image/png")
932 on PUT("/avatars/:user") (user: String, body: Bytes) -> Effect[HttpResult[String]] by Visitor {
933 Ok(user)
934 }
935}
936"#;
937
938 #[test]
939 fn a_raw_route_is_a_raw_envelope_whatever_its_other_params_with_413_and_415() {
940 let root = setup_project("uploads", &[("uploads.bynk", RAW_SRC)]);
941 let diag = crate::testkit::diagnose_project(&root);
942 let info = diag
943 .boundary_info
944 .get("uploads")
945 .expect("boundary_info entry for uploads");
946 let offset = find_offset(RAW_SRC, "PUT(\"/avatars/:user\")");
947 let model = wire_contract_at(
948 "uploads",
949 RAW_SRC,
950 offset,
951 info,
952 &[],
953 &diag.ty_intern,
954 real_context_count(&diag),
955 )
956 .expect("a wire contract at the PUT handler's header");
957
958 match &model.envelope {
959 Envelope::Raw {
960 param,
961 content_type,
962 } => {
963 assert_eq!(param, "body");
964 assert_eq!(content_type, "image/png");
965 }
966 other => panic!("expected Envelope::Raw, got {other:?}"),
967 }
968 let statuses: Vec<u16> = model.responses.iter().map(|r| r.status).collect();
969 assert!(statuses.contains(&413), "{statuses:?}");
970 assert!(statuses.contains(&415), "{statuses:?}");
971 }
972
973 #[test]
974 fn rate_limiter_get_check_client_is_a_bare_envelope_with_a_revalidated_client_id() {
975 let root = setup_project("ratelimit", &[("ratelimit.bynk", RATELIMIT_SRC)]);
976 let diag = crate::testkit::diagnose_project(&root);
977 let info = diag
978 .boundary_info
979 .get("ratelimit")
980 .expect("boundary_info entry for ratelimit");
981
982 let offset = find_offset(RATELIMIT_SRC, "GET(\"/check/:client\")");
983 let model = wire_contract_at(
984 "ratelimit",
985 RATELIMIT_SRC,
986 offset,
987 info,
988 &[],
989 &diag.ty_intern,
990 real_context_count(&diag),
991 )
992 .expect("a wire contract at the GET handler's header");
993
994 assert_eq!(model.unit, "ratelimit");
995 assert_eq!(model.service, "api");
996 assert_eq!(
997 model.kind,
998 BoundaryKind::Http {
999 method: IrHttpMethod::Get,
1000 path: "/check/:client".to_string(),
1001 }
1002 );
1003
1004 let (param, shape) = match &model.envelope {
1007 Envelope::Bare { param, shape } => (param, shape),
1008 other => panic!("expected Envelope::Bare, got {other:?}"),
1009 };
1010 assert_eq!(param, "client");
1011 assert!(
1012 matches!(shape, WireRef::Named { name } if name == "ClientId"),
1013 "the bare param's shape should resolve to the named ClientId type: {shape:?}"
1014 );
1015
1016 let client_id = model
1020 .boundary
1021 .types
1022 .iter()
1023 .find(|t| t.name == "ClientId")
1024 .expect("ClientId is a boundary type");
1025 assert_eq!(client_id.provenance, bynk_check::wire::Provenance::Owned);
1026 let bynk_check::wire::WireBody::Scalar(scalar) = &client_id.body else {
1027 panic!("ClientId should be a scalar, got {:?}", client_id.body);
1028 };
1029 assert!(
1030 scalar
1031 .predicates
1032 .iter()
1033 .any(|p| matches!(p, PredKind::NonEmpty)),
1034 "ClientId's predicates should include NonEmpty: {:?}",
1035 scalar.predicates
1036 );
1037 assert_eq!(
1038 scalar.revalidation,
1039 bynk_check::wire::Revalidation::ViaConstructor
1040 );
1041 assert!(model.type_sites.contains_key("ClientId"));
1042
1043 assert_eq!(
1047 model.no_cross_context,
1048 Some(NoCrossContextReason::SingleContext)
1049 );
1050 assert!(model.contract.is_none());
1051 }
1052
1053 fn walk_expr_tys(
1059 text: &str,
1060 offset: usize,
1061 file: FileId,
1062 expr_types: &[(Span, TyId)],
1063 tys: &Types,
1064 ) -> Vec<(String, Option<std::sync::Arc<Ty>>)> {
1065 fn collect<'e>(e: &'e Expr, out: &mut Vec<&'e Expr>) {
1066 out.push(e);
1067 for c in expr_children(e) {
1068 collect(c, out);
1069 }
1070 }
1071 let tokens = bynk_syntax::lexer::tokenize(text).expect("lexes");
1072 let (parsed, _) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
1073 let Some(SourceUnit::Context(c)) = parsed else {
1074 panic!("fixture is a context");
1075 };
1076 let handler = c
1077 .items
1078 .iter()
1079 .find_map(|i| match i {
1080 CommonsItem::Service(s) => handler_at(&s.handlers, offset),
1081 _ => None,
1082 })
1083 .expect("a handler at offset");
1084 let mut exprs = Vec::new();
1085 for s in &handler.body.statements {
1086 statement_exprs(s, &mut exprs);
1087 }
1088 exprs.push(&handler.body.tail);
1089 let mut all = Vec::new();
1090 for e in exprs {
1091 collect(e, &mut all);
1092 }
1093 let walk = ResponseWalk {
1094 expr_types,
1095 file,
1096 tys,
1097 declared_is_http_result: true,
1098 seen: Default::default(),
1099 saw_option_question: false,
1100 out: Vec::new(),
1101 };
1102 all.iter()
1103 .map(|e| {
1104 (
1105 text[e.span.start..e.span.end].to_string(),
1106 walk.expr_ty(e.span),
1107 )
1108 })
1109 .collect()
1110 }
1111
1112 #[test]
1113 fn rate_limiter_response_set_has_declared_constructed_and_boundary_implicit() {
1114 let root = setup_project("ratelimit-responses", &[("ratelimit.bynk", RATELIMIT_SRC)]);
1115 let diag = crate::testkit::diagnose_project(&root);
1116 let info = diag.boundary_info.get("ratelimit").expect("entry");
1117
1118 let rel = diag
1121 .files
1122 .iter()
1123 .find(|f| {
1124 f.source_path
1125 .file_name()
1126 .is_some_and(|n| n == "ratelimit.bynk")
1127 })
1128 .map(|f| f.source_path.clone())
1129 .expect("ratelimit.bynk in the round's files");
1130 let expr_types: &[(Span, TyId)] = diag
1131 .expr_types
1132 .get(&rel)
1133 .map(|v| v.as_slice())
1134 .unwrap_or(&[]);
1135
1136 assert!(
1137 !expr_types.is_empty(),
1138 "the clean fixture recorded no expr types"
1139 );
1140 let offset = find_offset(RATELIMIT_SRC, "GET(\"/check/:client\")");
1141 let walked = walk_expr_tys(
1145 RATELIMIT_SRC,
1146 offset,
1147 info.services["api"].span.file,
1148 expr_types,
1149 &diag.ty_intern,
1150 );
1151 for src in ["Ok(view)", "TooManyRequests(\"rate limit exceeded\")"] {
1152 let ty = walked
1153 .iter()
1154 .find(|(t, _)| t == src)
1155 .unwrap_or_else(|| panic!("`{src}` not walked: {walked:?}"))
1156 .1
1157 .as_deref();
1158 assert!(
1159 matches!(ty, Some(Ty::HttpResult(_))),
1160 "`{src}` should resolve to a recorded HttpResult, got {ty:?}"
1161 );
1162 }
1163 let model = wire_contract_at(
1164 "ratelimit",
1165 RATELIMIT_SRC,
1166 offset,
1167 info,
1168 expr_types,
1169 &diag.ty_intern,
1170 real_context_count(&diag),
1171 )
1172 .expect("a wire contract at the GET handler's header");
1173
1174 let statuses: Vec<(u16, &str)> = model
1175 .responses
1176 .iter()
1177 .map(|r| (r.status, r.variant.as_str()))
1178 .collect();
1179 assert!(
1180 statuses.contains(&(200, "Ok")),
1181 "declared success missing: {statuses:?}"
1182 );
1183 assert!(
1184 statuses.contains(&(429, "TooManyRequests")),
1185 "constructed TooManyRequests missing: {statuses:?}"
1186 );
1187 assert!(
1188 statuses.iter().any(|&(s, _)| s == 400),
1189 "boundary-implicit 400 (the handler has a param) missing: {statuses:?}"
1190 );
1191 assert!(
1192 model
1193 .responses
1194 .iter()
1195 .find(|r| r.status == 200)
1196 .is_some_and(|r| r.origin == ResponseOrigin::DeclaredSuccess)
1197 );
1198 assert!(
1199 model.responses.iter().any(|r| matches!(
1200 r.origin,
1201 ResponseOrigin::BoundaryImplicit { .. }
1202 ) && r.status == 400)
1203 );
1204 }
1205
1206 const PROVIDER_SRC: &str = r#"context billing
1209
1210type Quote = { amount: Int, currency: String }
1211
1212service Pricing {
1213 on call(sku: String, qty: Int) -> Effect[Quote] by Caller {
1214 Quote { amount: qty * 100, currency: "USD" }
1215 }
1216}
1217"#;
1218 const CONSUMER_SRC: &str = r#"context storefront
1219
1220consumes billing
1221
1222service checkout {
1223 on call(sku: String, qty: Int) -> Effect[Int] by Caller {
1224 let q <- billing.Pricing(sku, qty)
1225 q.amount
1226 }
1227}
1228"#;
1229
1230 #[test]
1231 fn two_context_call_handler_has_a_keyed_envelope_and_a_contract_hash() {
1232 let root = setup_project(
1233 "two-context",
1234 &[
1235 ("billing.bynk", PROVIDER_SRC),
1236 ("storefront.bynk", CONSUMER_SRC),
1237 ],
1238 );
1239 let diag = crate::testkit::diagnose_project(&root);
1240 let info = diag
1241 .boundary_info
1242 .get("billing")
1243 .expect("boundary_info entry for billing");
1244
1245 let offset = find_offset(PROVIDER_SRC, "on call(");
1246 let model = wire_contract_at(
1247 "billing",
1248 PROVIDER_SRC,
1249 offset,
1250 info,
1251 &[],
1252 &diag.ty_intern,
1253 real_context_count(&diag),
1254 )
1255 .expect("a wire contract at the `price` handler");
1256
1257 assert_eq!(model.kind, BoundaryKind::Call);
1258 let params = match &model.envelope {
1259 Envelope::Keyed { params } => params,
1260 other => panic!("expected Envelope::Keyed for a two-param call, got {other:?}"),
1261 };
1262 assert_eq!(
1263 params.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(),
1264 vec!["sku", "qty"],
1265 "keyed params stay in declaration order"
1266 );
1267
1268 assert!(model.no_cross_context.is_none(), "two contexts + on call");
1269 let contract = model.contract.expect("on call gets a contract form");
1270 assert_eq!(
1271 contract.hash,
1272 bynk_check::contract::contract_hash(&contract.normal_form)
1273 );
1274
1275 let svc = CrossContextService {
1279 name: "Pricing".to_string(),
1280 params: vec![
1281 (
1282 "sku".to_string(),
1283 TypeRef::Base(BaseType::String, Span::new(0, 0)),
1284 ),
1285 (
1286 "qty".to_string(),
1287 TypeRef::Base(BaseType::Int, Span::new(0, 0)),
1288 ),
1289 ],
1290 return_type: TypeRef::Named(Ident {
1291 name: "Quote".to_string(),
1292 span: Span::new(0, 0),
1293 }),
1294 span: Span::new(0, 0),
1295 foreign_callers: Vec::new(),
1296 };
1297 let independent_form = contract::service_normal_form(&svc, &info.types);
1298 assert_eq!(contract.normal_form, independent_form);
1299 assert_eq!(contract.hash, contract::contract_hash(&independent_form));
1300 }
1301
1302 #[test]
1303 fn zero_param_call_handler_is_the_empty_envelope() {
1304 let src = r#"context solo
1305
1306service Ping {
1307 on call() -> Effect[Int] by Caller {
1308 1
1309 }
1310}
1311"#;
1312 let root = setup_project("zero-param", &[("solo.bynk", src)]);
1313 let diag = crate::testkit::diagnose_project(&root);
1314 let info = diag.boundary_info.get("solo").expect("entry");
1315
1316 let offset = find_offset(src, "on call()");
1317 let model = wire_contract_at(
1318 "solo",
1319 src,
1320 offset,
1321 info,
1322 &[],
1323 &diag.ty_intern,
1324 real_context_count(&diag),
1325 )
1326 .expect("a wire contract at the `Ping` handler");
1327
1328 assert!(
1329 matches!(model.envelope, Envelope::Empty),
1330 "zero params: the request body is not read, not an empty keyed object"
1331 );
1332 assert_eq!(
1335 model.no_cross_context,
1336 Some(NoCrossContextReason::SingleContext)
1337 );
1338 }
1339
1340 #[test]
1346 fn bare_ident_collision_with_a_variant_name_is_not_misreported_without_expr_types() {
1347 const SRC: &str = r#"context oddnames
1348
1349service api from http {
1350 on GET("/x") () -> Effect[HttpResult[Int]] by Visitor {
1351 let Found = 1
1352 Found
1353 }
1354}
1355"#;
1356 let root = setup_project("ident-collision", &[("oddnames.bynk", SRC)]);
1357 let diag = crate::testkit::diagnose_project(&root);
1358 let info = diag
1359 .boundary_info
1360 .get("oddnames")
1361 .expect("boundary_info entry for oddnames");
1362
1363 let offset = find_offset(SRC, "GET(\"/x\")");
1364 let model = wire_contract_at(
1369 "oddnames",
1370 SRC,
1371 offset,
1372 info,
1373 &[],
1374 &diag.ty_intern,
1375 real_context_count(&diag),
1376 )
1377 .expect("a wire contract at the GET handler");
1378
1379 assert!(
1380 model.responses.iter().all(|r| r.variant != "Found"),
1381 "a bare `Found` local must not be misreported as HttpResult.Found \
1382 without a recorded expr type: {:?}",
1383 model.responses
1384 );
1385 }
1386
1387 #[test]
1394 fn bare_ident_variant_is_reported_from_real_expr_types() {
1395 const SRC: &str = r#"context flags
1396
1397service api from http {
1398 on DELETE("/flags/:name") (name: String) -> Effect[HttpResult[String]] by Visitor {
1399 NoContent
1400 }
1401}
1402"#;
1403 let root = setup_project("bare-ident-variant", &[("flags.bynk", SRC)]);
1404 let diag = crate::testkit::diagnose_project(&root);
1405 let info = diag.boundary_info.get("flags").expect("entry");
1406 let expr_types: &[(Span, TyId)] = diag
1407 .files
1408 .iter()
1409 .find(|f| f.source_path.file_name().is_some_and(|n| n == "flags.bynk"))
1410 .and_then(|f| diag.expr_types.get(&f.source_path))
1411 .map(|v| v.as_slice())
1412 .expect("flags.bynk's recorded expr types");
1413 assert!(
1414 expr_types.iter().all(|(s, _)| s.file != FileId::UNKNOWN),
1415 "the premise: analysis spans carry a real FileId"
1416 );
1417
1418 let offset = find_offset(SRC, "DELETE(");
1419 let model = wire_contract_at(
1420 "flags",
1421 SRC,
1422 offset,
1423 info,
1424 expr_types,
1425 &diag.ty_intern,
1426 real_context_count(&diag),
1427 )
1428 .expect("a wire contract at the DELETE handler");
1429
1430 assert!(
1431 model
1432 .responses
1433 .iter()
1434 .any(|r| r.status == 204 && r.variant == "NoContent"),
1435 "a tail `NoContent` must be reported as constructed: {:?}",
1436 model.responses
1437 );
1438 }
1439
1440 #[test]
1444 fn expr_ty_matches_by_range_and_treats_error_as_no_type() {
1445 let tys = Types::new();
1446 let file = FileId(0);
1447 let error = tys.intern(Ty::Error);
1448 let http = tys.intern(Ty::HttpResult(error));
1449 let expr_types = [
1450 (Span::new_in(file, 10, 20), http),
1451 (Span::new_in(file, 30, 40), error),
1452 (Span::new_in(FileId(1), 50, 60), http),
1453 ];
1454 let walk = ResponseWalk {
1455 expr_types: &expr_types,
1456 file,
1457 tys: &tys,
1458 declared_is_http_result: true,
1459 seen: Default::default(),
1460 saw_option_question: false,
1461 out: Vec::new(),
1462 };
1463
1464 assert!(matches!(
1466 walk.expr_ty(Span::new(10, 20)).as_deref(),
1467 Some(Ty::HttpResult(_))
1468 ));
1469 assert!(walk.is_http_result_ident(Span::new(10, 20)));
1470
1471 assert!(walk.expr_ty(Span::new(30, 40)).is_none());
1474 assert!(!walk.is_http_result_ident(Span::new(30, 40)));
1475 assert!(walk.is_http_result_expr(Span::new(30, 40)));
1476
1477 assert!(walk.expr_ty(Span::new(50, 60)).is_none());
1479 }
1480
1481 fn clean_expr_types<'d>(diag: &'d crate::ProjectDiagnostics, name: &str) -> &'d [(Span, TyId)] {
1485 for f in &diag.files {
1486 assert!(
1487 f.diagnostics.is_empty(),
1488 "{:?} has diagnostics: {:?}",
1489 f.source_path,
1490 f.diagnostics
1491 );
1492 }
1493 diag.files
1494 .iter()
1495 .find(|f| f.source_path.file_name().is_some_and(|n| n == name))
1496 .and_then(|f| diag.expr_types.get(&f.source_path))
1497 .map(|v| v.as_slice())
1498 .unwrap_or_else(|| panic!("{name}'s recorded expr types"))
1499 }
1500
1501 #[test]
1506 fn bare_ident_collision_with_a_variant_name_is_rejected_by_its_recorded_type() {
1507 const SRC: &str = r#"context oddnames
1508
1509service api from http {
1510 on GET("/x") () -> Effect[HttpResult[Int]] by Visitor {
1511 let Found = 1
1512 Ok(Found)
1513 }
1514}
1515"#;
1516 let root = setup_project("ident-collision-typed", &[("oddnames.bynk", SRC)]);
1517 let diag = crate::testkit::diagnose_project(&root);
1518 let info = diag.boundary_info.get("oddnames").expect("entry");
1519 let expr_types = clean_expr_types(&diag, "oddnames.bynk");
1520
1521 let offset = find_offset(SRC, "GET(\"/x\")");
1522 let walked = walk_expr_tys(
1523 SRC,
1524 offset,
1525 info.services["api"].span.file,
1526 expr_types,
1527 &diag.ty_intern,
1528 );
1529 assert!(
1530 walked.iter().any(|(t, ty)| t == "Found"
1531 && ty
1532 .as_deref()
1533 .is_some_and(|ty| !matches!(ty, Ty::HttpResult(_)))),
1534 "the tail `Found` should resolve to its recorded non-HttpResult type: {walked:?}"
1535 );
1536
1537 let model = wire_contract_at(
1538 "oddnames",
1539 SRC,
1540 offset,
1541 info,
1542 expr_types,
1543 &diag.ty_intern,
1544 real_context_count(&diag),
1545 )
1546 .expect("a wire contract at the GET handler");
1547 assert!(
1548 model.responses.iter().all(|r| r.variant != "Found"),
1549 "a bare `Found` local must not be reported as HttpResult.Found: {:?}",
1550 model.responses
1551 );
1552 }
1553
1554 #[test]
1558 fn option_question_in_a_handler_adds_the_boundary_implicit_404() {
1559 const SRC: &str = r#"context lookup
1560
1561fn find(n: String) -> Option[Int] {
1562 Some(1)
1563}
1564
1565service api from http {
1566 on GET("/x/:n") (n: String) -> Effect[HttpResult[Int]] by Visitor {
1567 let v = find(n)?
1568 Ok(v)
1569 }
1570}
1571"#;
1572 let root = setup_project("option-question", &[("lookup.bynk", SRC)]);
1573 let diag = crate::testkit::diagnose_project(&root);
1574 let info = diag.boundary_info.get("lookup").expect("entry");
1575 let expr_types = clean_expr_types(&diag, "lookup.bynk");
1576
1577 let model = wire_contract_at(
1578 "lookup",
1579 SRC,
1580 find_offset(SRC, "GET("),
1581 info,
1582 expr_types,
1583 &diag.ty_intern,
1584 real_context_count(&diag),
1585 )
1586 .expect("a wire contract at the GET handler");
1587 assert!(
1588 model.responses.iter().any(|r| r.status == 404
1589 && r.variant == "NotFound"
1590 && matches!(r.origin, ResponseOrigin::BoundaryImplicit { .. })),
1591 "an `Option?` short-circuit must add the boundary-implicit 404: {:?}",
1592 model.responses
1593 );
1594 }
1595
1596 #[test]
1603 fn a_sibling_files_span_at_the_same_range_is_not_this_files_type() {
1604 const A: &str = r#"context shop
1605
1606type Q = { n: Int }
1607
1608service api from http {
1609 on GET("/x") () -> Effect[HttpResult[Int]] by Visitor {
1610 let Found = 1
1611 Ok(Found)
1612 }
1613}
1614"#;
1615 let target = find_offset(A, "Ok(Found)") + "Ok(".len();
1616 let head = "context shop\n\nfn Q.r(self) -> HttpResult[Int] {\n";
1617 let pad = target
1618 .checked_sub(head.len())
1619 .expect("a.bynk's `Found` sits past b.bynk's header");
1620 let b = format!("{head}{}Ok(1)\n}}\n", " ".repeat(pad));
1621 assert_eq!(
1622 b.find("Ok(1)"),
1623 Some(target),
1624 "the padding lines the spans up"
1625 );
1626
1627 let root = setup_project("sibling-span", &[("shop/a.bynk", A), ("shop/b.bynk", &b)]);
1628 let diag = crate::testkit::diagnose_project(&root);
1629 let info = diag.boundary_info.get("shop").expect("entry");
1630 let expr_types = clean_expr_types(&diag, "a.bynk");
1631 let file = info.services["api"].span.file;
1632 assert!(
1633 expr_types.iter().any(|(s, t)| s.file != file
1634 && (s.start, s.end) == (target, target + 5)
1635 && matches!(*diag.ty_intern.get(*t), Ty::HttpResult(_))),
1636 "the premise: a.bynk's expr types hold b.bynk's `Ok(1)` at the same range"
1637 );
1638
1639 let model = wire_contract_at(
1640 "shop",
1641 A,
1642 find_offset(A, "GET("),
1643 info,
1644 expr_types,
1645 &diag.ty_intern,
1646 real_context_count(&diag),
1647 )
1648 .expect("a wire contract at the GET handler");
1649 assert!(
1650 model.responses.iter().all(|r| r.variant != "Found"),
1651 "b.bynk's `Ok(1)` must not type a.bynk's `Found`: {:?}",
1652 model.responses
1653 );
1654 }
1655
1656 #[test]
1661 fn user_sum_variant_named_like_an_http_variant_is_not_a_response() {
1662 const SRC: &str = r#"context catalogue
1663
1664type Item = { id: Int, name: String }
1665type Outcome = | Found(item: Item) | Absent
1666
1667service api from http {
1668 on GET("/outcome/:id") (id: String) -> Effect[HttpResult[Outcome]] by Visitor {
1669 Ok(Found(Item { id: 1, name: id }))
1670 }
1671}
1672"#;
1673 let root = setup_project("sum-variant-found", &[("catalogue.bynk", SRC)]);
1674 let diag = crate::testkit::diagnose_project(&root);
1675 let info = diag.boundary_info.get("catalogue").expect("entry");
1676 let expr_types = clean_expr_types(&diag, "catalogue.bynk");
1677 let model = wire_contract_at(
1678 "catalogue",
1679 SRC,
1680 find_offset(SRC, "GET("),
1681 info,
1682 expr_types,
1683 &diag.ty_intern,
1684 real_context_count(&diag),
1685 )
1686 .expect("a wire contract at the GET handler");
1687 let variants: Vec<&str> = model.responses.iter().map(|r| r.variant.as_str()).collect();
1688 assert_eq!(variants, ["Ok", "StructuralMismatch"], "{variants:?}");
1689 }
1690
1691 fn constructed_variants(test: &str, ctx_name: &str, src: &str) -> Vec<String> {
1693 let file = format!("{ctx_name}.bynk");
1694 let root = setup_project(test, &[(file.as_str(), src)]);
1695 let diag = crate::testkit::diagnose_project(&root);
1696 let info = diag.boundary_info.get(ctx_name).expect("entry");
1697 let expr_types = clean_expr_types(&diag, &file);
1698 wire_contract_at(
1699 ctx_name,
1700 src,
1701 find_offset(src, "GET("),
1702 info,
1703 expr_types,
1704 &diag.ty_intern,
1705 real_context_count(&diag),
1706 )
1707 .expect("a wire contract at the GET handler")
1708 .responses
1709 .into_iter()
1710 .map(|r| r.variant)
1711 .collect()
1712 }
1713
1714 #[test]
1717 fn every_http_variant_name_as_a_user_sum_variant_is_not_a_response() {
1718 const SRC: &str = r#"context names
1719
1720type Msg = { text: String }
1721type Shape =
1722 | Created(msg: Msg)
1723 | Accepted(msg: Msg)
1724 | NotFound(msg: Msg)
1725 | Conflict(msg: Msg)
1726 | Gone(msg: Msg)
1727 | Redirect(msg: Msg)
1728 | Found(msg: Msg)
1729 | NoContent
1730
1731service api from http {
1732 on GET("/x") () -> Effect[HttpResult[List[Shape]]] by Visitor {
1733 let m = Msg { text: "t" }
1734 Ok([Created(m), Accepted(m), NotFound(m), Conflict(m), Gone(m), Redirect(m), Found(m), NoContent])
1735 }
1736}
1737"#;
1738 let variants = constructed_variants("all-http-names", "names", SRC);
1739 assert_eq!(variants, ["Ok"], "only the declared `Ok`: {variants:?}");
1740 }
1741
1742 #[test]
1745 fn genuine_http_found_is_still_a_response() {
1746 const SRC: &str = r#"context moved
1747
1748type Item = { id: Int }
1749type Outcome = | Found(item: Item) | Absent
1750
1751fn lookup() -> Outcome {
1752 Found(Item { id: 1 })
1753}
1754
1755service api from http {
1756 on GET("/x") () -> Effect[HttpResult[Outcome]] by Visitor {
1757 match lookup() {
1758 Found(item) => Found("/elsewhere")
1759 Absent => HttpResult.NotFound
1760 }
1761 }
1762}
1763"#;
1764 let variants = constructed_variants("genuine-found", "moved", SRC);
1765 assert!(
1766 variants.iter().any(|v| v == "Found"),
1767 "a genuine `Found(\"/elsewhere\")` is the 302: {variants:?}"
1768 );
1769 assert!(variants.iter().any(|v| v == "NotFound"), "{variants:?}");
1770 }
1771}