bynk_emit/testgen/harness.rs
1//! The integration and remote harness, runnable-test records and the attack/property predicates.
2//!
3//! Crate-hygiene D1 (#2982, PR 2): split out of `tests_emit.rs`.
4
5use super::*;
6use crate::emitter::bindings::{BindingSource, WorkerBinding};
7// #1759: every namespace a test module imports, from one definition.
8use crate::emitter::emit::test_scaffold_ns as test_ns;
9use bynk_check::checker::Types;
10use bynk_check::d1_migrations::{D1Migrations, d1_database_name};
11use bynk_check::test_suites::{self};
12use bynk_check::wire_format;
13use bynk_syntax::ast::{
14 BaseType, Block, Commons, CommonsForm, Expr, ExprKind, FnDecl, FnName, Ident, PropertyDecl,
15 QualifiedName, Trivia, TypeBody, TypeDecl, TypeRef,
16};
17use bynk_syntax::span::Span;
18use bynk_ts::{TsArrowBody, TsBindingName, TsDecl, TsExpr, TsStmt, TsType};
19use std::sync::Arc;
20
21/// Emit the `__makeHarness()` factory: an in-process env per participant whose
22/// Service Bindings call the sibling participants' real Worker `fetch` and whose
23/// Durable-Object namespaces back the participant's own agents in memory, plus a
24/// root env binding every participant (the test cases call in through it). A
25/// fresh harness per case gives each case clean agent state.
26/// #1479: returns the real [`TsStmt`] itself (was pre-printed `String`) —
27/// the one real declaration this function ever built; its caller now prints
28/// it directly, the same shape `emit_test_deps`'s own identical conversion
29/// used.
30///
31/// #1959: each participant's `env` holds the bindings its own Worker declares
32/// (`bindings_of`, the list its `wrangler.toml` is written from), by the same
33/// names: a Service Binding forwards to that participant's Worker, the KV
34/// namespace is a fresh in-memory namespace of the participant's own (each
35/// deployed Worker gets its own: `bynk deploy` provisions one per Worker), and
36/// each agent and the events fan-out is an in-memory Durable Object namespace
37/// constructed with the participant's `env`.
38///
39/// #2136: `__buildHarness` builds it, and `__makeHarness` memoises it per case
40/// in `__bynkHarness` (the case resets it before its first call), so every
41/// driver a case calls reaches the same
42/// participants and agent state. `exposed` names the participants whose own
43/// `env` the harness also returns, for a driver that calls that Worker's
44/// `scheduled` or `queue` entry directly.
45pub(super) fn emit_integration_harness<'a>(
46 participants: &[String],
47 bindings_of: &dyn Fn(&String) -> &'a Vec<WorkerBinding>,
48 sends: &dyn Fn(&String) -> bool,
49 foreign_secrets: &dyn Fn(&String) -> Vec<String>,
50 exposed: &[String],
51 // #2134: put the running case's `env` entries (`__bynkEnv`) on each
52 // participant's `env`, first, so the harness's own keys and bindings
53 // below are never replaced by one.
54 with_env: bool,
55 // P4b (#2608): each `D1` database's migrations, run on each participant's
56 // fresh database.
57 d1_migrations: &D1Migrations,
58) -> Vec<TsStmt> {
59 let mut body = Vec::new();
60 // Declare every participant env first so sibling references resolve.
61 //
62 // P7.2: deferred, not narrowed. `env_{ns}` is later passed positionally into
63 // `worker_{dns}.fetch(req, env_{dns})`, whose own generated `Env` interface
64 // (`emitter/workers.rs`'s `export interface Env { ... }`) types each binding
65 // precisely (`ServiceBinding`, `DurableObjectNamespace`, ...) — `Record<string,
66 // unknown>` would not structurally satisfy that on assignment, and correctly
67 // referencing each participant's own generated `Env` type from this shared
68 // harness scope needs its own naming/qualification scheme this slice hasn't
69 // worked out. Left as `any`, named here rather than guessed at.
70 for p in participants {
71 let ns = test_ns(p);
72 body.push(TsStmt::const_stmt(
73 TsBindingName::Ident(env_binding(&ns)),
74 Some(TsType::named("any")),
75 TsExpr::object(vec![]),
76 None,
77 ));
78 }
79 for p in participants {
80 let ns = test_ns(p);
81 let env = env_binding(&ns);
82 if with_env {
83 body.push(expr_stmt(call(
84 ident("globalThis.Object.assign"),
85 vec![ident(env.clone()), ident("__bynkEnv")],
86 )));
87 }
88 // #2137: the harness clock the participant's test-build `Clock` reads.
89 body.push(TsStmt::assign(
90 member(ident(env.clone()), "__bynkClock"),
91 ident("__bynkClock"),
92 None,
93 ));
94 // I2 (#1971): every participant holds the local key for each edge it
95 // is on, as under `bynk dev`: from the test cases' caller, from each
96 // participant that binds to it (a caller or an event publisher), and
97 // to each participant it binds to.
98 let callers = std::iter::once(HARNESS_CALLER).chain(
99 participants
100 .iter()
101 .filter(|q| {
102 bindings_of(q).iter().any(
103 |b| matches!(&b.source, BindingSource::Service { context } if context == p),
104 )
105 })
106 .map(String::as_str),
107 );
108 let callees = bindings_of(p).iter().filter_map(|b| {
109 let BindingSource::Service { context } = &b.source else {
110 return None;
111 };
112 participants.contains(context).then_some(context.as_str())
113 });
114 for key in callers
115 .filter_map(wire_format::edge_key_from)
116 .chain(callees.filter_map(wire_format::edge_key_to))
117 .chain(foreign_secrets(p))
118 {
119 body.push(TsStmt::assign(
120 member(ident(env.clone()), &key),
121 str_lit(crate::LOCAL_CALL_KEY),
122 None,
123 ));
124 }
125 for binding in bindings_of(p) {
126 let value = match &binding.source {
127 // #1856: a context that is no participant has no Worker here.
128 BindingSource::Service { context } => {
129 if !participants.contains(context) {
130 continue;
131 }
132 let dns = test_ns(context);
133 service_binding_forward(
134 &worker_binding_name(&dns),
135 &env_binding(&dns),
136 sends(context),
137 )
138 }
139 // S4a (#1966): each instance its own fresh namespace.
140 BindingSource::Kv | BindingSource::KvInstance { .. } => {
141 call(ident("__makeIntegrationKv"), vec![])
142 }
143 // P5 (#2323): each instance its own fresh bucket.
144 BindingSource::R2Instance { .. } => call(ident("__makeIntegrationR2"), vec![]),
145 // P3 (#2342): each instance its own fresh limiter, counting on
146 // the harness clock this module always carries, so a case can
147 // recover one with `advance Clock by`.
148 BindingSource::RateLimitInstance { limit, period, .. } => call(
149 ident("__makeIntegrationRateLimit"),
150 vec![
151 num_lit(limit.to_string()),
152 num_lit(period.to_string()),
153 TsExpr::Arrow {
154 params: Vec::new(),
155 is_async: false,
156 generics: Vec::new(),
157 return_type: None,
158 body: Box::new(TsArrowBody::Expr(Box::new(ident("__bynkClockNow")))),
159 },
160 ],
161 ),
162 // P2 (#2578): each instance its own recorder; nothing is
163 // delivered to a consumer participant.
164 BindingSource::QueueProducer { .. } => {
165 call(ident("__makeIntegrationQueue"), vec![])
166 }
167 // P3b (#2582): each instance its own fresh recorder.
168 BindingSource::AnalyticsDataset { .. } => {
169 call(ident("__makeIntegrationAnalytics"), vec![])
170 }
171 // P4a (#2602): each instance its own in-memory database, and
172 // P4b (#2608) runs its migrations on it first.
173 BindingSource::D1Database { .. } => call(
174 ident("__makeIntegrationD1"),
175 d1_migrations_args(Some(&bynk_check::d1_migrations::migrations_of(
176 d1_migrations,
177 &d1_database_name(&bynk_project::worker_dir_name(p), &binding.name),
178 binding,
179 ))),
180 ),
181 // #3301: the account's store is never reached in a test, so
182 // the binding faults, naming itself, until the case stubs it.
183 BindingSource::StoredSecret { .. } => call(
184 ident("__makeIntegrationSecretsStoreSecret"),
185 vec![str_lit(&binding.name)],
186 ),
187 // #3318: a test never reaches Postgres, so reading the
188 // connection string faults, naming the binding, until the case
189 // stubs the instance.
190 // Hyperdrive H5 (#3322): a `MySql` participant the same, with
191 // no double to opt in to.
192 BindingSource::MySql { .. } => call(
193 ident("__makeIntegrationHyperdrive"),
194 vec![str_lit(&binding.name)],
195 ),
196 BindingSource::Postgres { .. } => {
197 match d1_migrations.get(bynk_check::d1_migrations::PG_TEST_KEY) {
198 // #3321: `[test] postgres = "pglite"`: a database of its own
199 // for the participant's binding, reset for each case and
200 // given the project's `schema.sql`.
201 Some(schema) => call(
202 ident("__makeIntegrationPgliteBinding"),
203 vec![
204 str_lit(format!(
205 "{}-{}",
206 bynk_project::worker_dir_name(p),
207 binding.name
208 )),
209 str_lit(schema.iter().map(|f| f.sql.as_str()).collect::<String>()),
210 ],
211 ),
212 None => call(
213 ident("__makeIntegrationHyperdrive"),
214 vec![str_lit(&binding.name)],
215 ),
216 }
217 }
218 // #3302: an in-memory outbox per participant.
219 BindingSource::Email { .. } => call(ident("__makeIntegrationEmail"), vec![]),
220 // #3479: each instance its own in-memory exact index, built from
221 // its declaration.
222 BindingSource::VectorizeIndex {
223 dimensions,
224 metric,
225 indexed,
226 ..
227 } => call(
228 ident("__makeIntegrationVectorize"),
229 vec![
230 num_lit(dimensions.to_string()),
231 str_lit(metric),
232 TsExpr::Array {
233 items: indexed.iter().map(str_lit).collect(),
234 multiline: false,
235 },
236 ],
237 ),
238 // #3480: a test never reaches AI Search, so the binding faults,
239 // naming itself, until the case stubs the instance.
240 BindingSource::AiSearchInstance { .. } => call(
241 ident("__makeIntegrationAiSearch"),
242 vec![str_lit(&binding.name)],
243 ),
244 // #3513 A: a test never reaches the origin, so the binding faults,
245 // naming the instance, until the case stubs its `send`.
246 BindingSource::MtlsCertificate { capability, .. } => {
247 call(ident("__makeIntegrationMtls"), vec![str_lit(capability)])
248 }
249 // #3477: there is no in-process container, so the binding faults,
250 // naming itself, until the case stubs the instance.
251 BindingSource::ContainerInstance { .. } => call(
252 ident("__makeIntegrationContainer"),
253 vec![str_lit(&binding.name)],
254 ),
255 // One-per-Worker bindings: a fixed version (#3300), and Workers AI
256 // (#3478) and Images (#3515), which fault until stubbed.
257 BindingSource::Singleton { capability } => singleton_integration_double(capability),
258 // Interop I5 (#1972): the foreign Worker is not here, so its
259 // binding answers as `bynk dev`'s default double does.
260 BindingSource::ForeignService { worker, .. } => {
261 foreign_service_double(&binding.name, worker)
262 }
263 BindingSource::Agent { class_name } => call(
264 ident("__makeIntegrationDoNamespace"),
265 vec![member(ident(ns.clone()), class_name), ident(env.clone())],
266 ),
267 BindingSource::EventsFanout { class_name } => call(
268 ident("__makeIntegrationDoNamespace"),
269 vec![
270 member(ident(fanout_alias(&ns)), class_name),
271 ident(env.clone()),
272 ],
273 ),
274 };
275 body.push(TsStmt::assign(
276 member(ident(env.clone()), &binding.name),
277 value,
278 None,
279 ));
280 push_dataset_var(&mut body, &env, binding, p);
281 }
282 }
283 // Root env binds to every participant.
284 // P7.2: deferred, same reason as `env_{ns}` above.
285 body.push(TsStmt::const_stmt(
286 TsBindingName::Ident("rootEnv".to_string()),
287 Some(TsType::named("any")),
288 TsExpr::object(vec![]),
289 None,
290 ));
291 // I2 (#1971): the test cases call in through `rootEnv`, as
292 // [`HARNESS_CALLER`], so it holds the key for the edge to each participant.
293 for key in participants
294 .iter()
295 .filter_map(|p| wire_format::edge_key_to(p))
296 {
297 body.push(TsStmt::assign(
298 member(ident("rootEnv"), &key),
299 str_lit(crate::LOCAL_CALL_KEY),
300 None,
301 ));
302 }
303 for p in participants {
304 let ns = test_ns(p);
305 let binding = crate::emitter::bindings::service_binding(p).name;
306 body.push(TsStmt::assign(
307 member(ident("rootEnv"), binding),
308 service_binding_forward(&worker_binding_name(&ns), &env_binding(&ns), sends(p)),
309 None,
310 ));
311 }
312 let mut fields = vec![("env".to_string(), ident("rootEnv"))];
313 for p in exposed {
314 let env = env_binding(&test_ns(p));
315 fields.push((env.clone(), ident(env)));
316 }
317 body.push(TsStmt::return_stmt(Some(TsExpr::object(fields)), None));
318 let build = TsStmt::decl(
319 TsDecl::Function {
320 name: "__buildHarness".to_string(),
321 generics: Vec::new(),
322 params: Vec::new(),
323 return_type: None,
324 body,
325 is_async: false,
326 inline: false,
327 },
328 None,
329 );
330 let mut stmts = vec![build];
331 stmts.extend(harness_memo());
332 stmts
333}
334
335/// #2134: the module-level `__bynkEnv`, the running case's `env` entries, under `comment` (which
336/// says who sets it). The comment sits flush above the `let`, and both directly after the
337/// preceding statement.
338pub(super) fn env_declaration(comment: &str) -> Vec<TsStmt> {
339 let mut note = TsStmt::comment(comment, None);
340 let mut slot = crate::ts_build::let_decl(
341 "__bynkEnv",
342 Some(TsType::named_with_args(
343 "globalThis.Record",
344 vec![TsType::named("string"), TsType::named("string")],
345 )),
346 Some(TsExpr::object(Vec::new())),
347 );
348 note.no_blank_before = true;
349 slot.no_blank_before = true;
350 vec![note, slot]
351}
352
353/// The per-case memo of the harness: `let __bynkHarness: … | undefined;` and `__makeHarness`, which
354/// builds it on first use. The two sit on consecutive lines, directly after `__buildHarness`.
355fn harness_memo() -> Vec<TsStmt> {
356 use crate::ts_build::{ident, let_typed, paren, ret};
357 let mut slot = let_typed(
358 "__bynkHarness",
359 TsType::union(vec![
360 TsType::named_with_args("ReturnType", vec![TsType::type_of(ident("__buildHarness"))]),
361 TsType::named("undefined"),
362 ]),
363 );
364 let mut make = TsStmt::decl(
365 TsDecl::Function {
366 name: "__makeHarness".to_string(),
367 generics: Vec::new(),
368 params: Vec::new(),
369 return_type: None,
370 body: vec![ret(paren(TsExpr::NullishAssign {
371 target: Box::new(ident("__bynkHarness")),
372 value: Box::new(crate::ts_build::call(ident("__buildHarness"), Vec::new())),
373 }))],
374 is_async: false,
375 inline: false,
376 },
377 None,
378 );
379 slot.no_blank_before = true;
380 make.no_blank_before = true;
381 vec![slot, make]
382}
383
384/// #2138: the harness of a remote run — each participant's binding reaches
385/// its URL in the test target (`BYNK_TEST_TARGETS`, keyed by worker name)
386/// through `__bynkRemoteBinding`, so every driver's request goes to the real
387/// runtime. Memoised per case like the in-process harness, so a case body
388/// lowers identically against either.
389pub(super) fn emit_remote_harness(participants: &[String]) -> Vec<TsStmt> {
390 use crate::ts_build::{assign, const_typed, ident, member, ret, str_lit};
391 let mut body = vec![const_typed(
392 "rootEnv",
393 TsType::named("{ [binding: string]: __ServiceBinding }"),
394 TsExpr::object(Vec::new()),
395 )];
396 for p in participants {
397 let binding = crate::emitter::bindings::service_binding(p).name;
398 body.push(assign(
399 member(ident("rootEnv"), binding),
400 crate::ts_build::call(
401 ident("__bynkRemoteBinding"),
402 vec![str_lit(worker_dir_name(p))],
403 ),
404 ));
405 }
406 body.push(ret(TsExpr::object(vec![(
407 "env".to_string(),
408 ident("rootEnv"),
409 )])));
410 let build = TsStmt::decl(
411 TsDecl::Function {
412 name: "__buildHarness".to_string(),
413 generics: Vec::new(),
414 params: Vec::new(),
415 return_type: None,
416 body,
417 is_async: false,
418 inline: false,
419 },
420 None,
421 );
422 let mut stmts = vec![
423 TestRuntimeModule::Remote.splice(),
424 // #2138 (track §3.6): the `--settle` retry the case bodies use.
425 TestRuntimeModule::Settle.splice(),
426 build,
427 ];
428 stmts.extend(harness_memo());
429 stmts
430}
431
432/// Build the [`checker::TypedCommons`] used to lower integration case bodies —
433/// the harness view ([`test_suites::integration_view`]: `uses` commons plus
434/// participant types/fns/methods, closed over the types they reach, #1814),
435/// so static calls and constructors resolve.
436pub(super) fn integration_typed_commons(
437 view: &test_suites::SuiteView,
438 tys: &Arc<checker::Types>,
439) -> checker::TypedCommons {
440 let test_suites::SuiteView {
441 types,
442 fns,
443 methods,
444 ..
445 } = view.clone();
446 checker::TypedCommons {
447 commons: Arc::new(Commons {
448 name: QualifiedName {
449 parts: vec![Ident {
450 name: HARNESS_CALLER.to_string(),
451 span: Span::default(),
452 }],
453 span: Span::default(),
454 },
455 items: Vec::new(),
456 uses: Vec::new(),
457 documentation: None,
458 form: CommonsForm::Brace,
459 span: Span::default(),
460 trivia: Trivia::default(),
461 trailing_comments: Vec::new(),
462 }),
463 types,
464 fns,
465 methods,
466 expr_types: HashMap::new(),
467 callees: HashMap::new(),
468 warnings: vec![],
469 // T3.6b (R4.1): the *caller's* table, not a fresh one. A synthesised
470 // commons starts with an empty `expr_types`, but the case/property
471 // checks below fill it in — interning into the table they were handed
472 // — and the lowering then resolves those ids back through this field.
473 // A table of its own would make every one of those reads a
474 // wrong-table lookup.
475 ty_intern: Arc::clone(tys),
476 actor_bindings: HashMap::new(),
477 assets: HashMap::new(),
478 embeds: HashMap::new(),
479 consts: HashMap::new(),
480 shadowed_imports: HashMap::new(),
481 extensible_enums: Default::default(),
482 unselected_types: Default::default(),
483 stability: Default::default(),
484 exec_plan: Default::default(),
485 }
486}
487
488pub(super) fn sanitise_suite(s: &str) -> String {
489 let mut out = String::new();
490 for ch in s.chars() {
491 if ch.is_ascii_alphanumeric() {
492 out.push(ch.to_ascii_lowercase());
493 } else {
494 out.push('_');
495 }
496 }
497 while out.contains("__") {
498 out = out.replace("__", "_");
499 }
500 let trimmed = out.trim_matches('_').to_string();
501 if trimmed.is_empty() {
502 "suite".to_string()
503 } else {
504 trimmed
505 }
506}
507
508/// Discovered, named test ready to be invoked from the top-level runner.
509pub struct RunnableTest {
510 /// Joined target name (e.g., `commerce.payment`), or `system · <suite>`
511 /// for a wired (`system`) suite — the runner's module identity and sort key.
512 pub(super) target_name: String,
513 /// The module's output path relative to the project root.
514 pub(super) module_path: PathBuf,
515 /// v0.67: `"unit"` or `"integration"` — the suite kind for discovery, mirrors
516 /// the runner's `suite-begin` `kind`.
517 pub(super) kind: &'static str,
518 /// v0.67: the JSON suite name for discovery — the joined target name (unit)
519 /// or the bare suite name (integration). Differs from `target_name` only for
520 /// integration, which the runner prefixes with `system · ` (#2185).
521 pub(super) suite_name: String,
522 /// #2138: the cases a remote build skipped (`--skip-unsupported`), and why.
523 pub(super) skipped: Vec<crate::emit_model::RemoteSkip>,
524 /// #2138: under `--against dev`, the distinct `env` maps of its cases.
525 pub(super) envs: Vec<BTreeMap<String, String>>,
526 /// #2138: a remote build's module, whose cases report `retries`.
527 pub(super) remote: bool,
528 /// The module inlines the generative-property runtime (it declares a
529 /// `property` or attacks a contract), so its failed cases report `kind`,
530 /// `seed` and `counterexample`.
531 pub(super) generative: bool,
532 /// #3437: the module carries the execution-context double (`send.ts`), whose
533 /// `report` records a detached effect's failures; the runner drains them
534 /// after each case.
535 pub(super) detach_reports: bool,
536 /// v0.67: the suite's cases, in declaration (emission) order, retained for
537 /// `--no-run` discovery.
538 pub(super) cases: Vec<DiscoveredCase>,
539 /// #2842: the snapshot files (`snapshots/…snap.json`) the module's suites take
540 /// a snapshot into. The module exports `__bynkSnapshotReport` iff non-empty.
541 pub snapshot_files: Vec<String>,
542}
543
544/// v0.67: the `path:line:col` of a test-name literal, structured for discovery.
545/// Reuses [`bynk_syntax::span::line_col`] and the same forward-slash
546/// normalisation `assert_location` applies (bynk-emit/src/emitter/lower.rs), so a
547/// discovered case and a run-failure resolve to consistent coordinates.
548pub(super) fn discovered_location(source: &str, rel_path: &str, span: Span) -> TestLocation {
549 let (line, col) = bynk_syntax::span::line_col(source, span.start);
550 TestLocation {
551 path: rel_path.replace('\\', "/"),
552 line: line as u32,
553 col: col as u32,
554 }
555}
556
557/// v0.67: fold the combined runnable manifest into the discovery suites, ordered
558/// by the runner's sort key (`target_name`) so the discovery document matches a
559/// run's suite order.
560pub fn discovery_manifest(tests: &[RunnableTest]) -> Vec<DiscoveredSuite> {
561 let mut sorted: Vec<&RunnableTest> = tests.iter().collect();
562 sorted.sort_by(|a, b| a.target_name.cmp(&b.target_name));
563 sorted
564 .into_iter()
565 .map(|t| DiscoveredSuite {
566 name: t.suite_name.clone(),
567 kind: t.kind,
568 cases: t.cases.clone(),
569 skipped: t.skipped.clone(),
570 envs: t.envs.clone(),
571 })
572 .collect()
573}
574
575/// Whether a `case` body uses an observation (`Cap.op called …`) or
576/// `trace(Cap.op)` anywhere (v0.117) — the signal to wrap `deps` with the
577/// recording proxy. Bodies that don't observe emit unchanged.
578pub(super) fn case_observes(block: &Block) -> bool {
579 let mut found = false;
580 let mut check = |e: &Expr| {
581 if matches!(e.kind, ExprKind::Observation(_) | ExprKind::Trace { .. }) {
582 found = true;
583 }
584 };
585 // #1851: every expression of a statement, a principal's identity
586 // included, not a hand-picked value.
587 let mut exprs = Vec::new();
588 for s in &block.statements {
589 bynk_syntax::ast::statement_exprs(s, &mut exprs);
590 }
591 for e in exprs {
592 bynk_model::walk_exprs(e, &mut check);
593 }
594 bynk_model::walk_exprs(&block.tail, &mut check);
595 found
596}
597
598/// v0.178 (#662): build the target's service table for a test-body check —
599/// each service's protocol word and its `on call` handler signature, so a
600/// `svc.call(args)` in a case can be resolved rather than string-matched. A
601/// service with no `on call` handler carries `None`, which turns `svc.call(...)`
602/// into `bynk.test.service_no_call_handler` instead of a silent runtime crash.
603pub(super) fn target_service_handler_kinds(
604 table: Option<&UnitTable>,
605) -> HashMap<String, Vec<bynk_model::IrHandlerKind>> {
606 let Some(t) = table else {
607 return HashMap::new();
608 };
609 t.services
610 .iter()
611 .map(|(name, decl)| {
612 (
613 name.clone(),
614 decl.handlers
615 .iter()
616 .map(|h| bynk_model::lower_handler_kind_ir(&h.kind))
617 .collect(),
618 )
619 })
620 .collect()
621}
622
623/// I3 (#1971), #2020: the target's handlers that bind an actor sum, whose
624/// `deps.who` a call-site principal builds: an `on call` sum (`by who: Caller
625/// | Legacy`), keyed `(service, "call")`, and an http sum (`by who: User |
626/// Visitor`), keyed `(service, <emitted method name>)`. Mirrors the order
627/// `bynk_model::lower_actor_seam_ir` resolves a handler's seam in.
628pub(super) fn target_sum_handlers(table: Option<&UnitTable>) -> HashSet<(String, String)> {
629 let Some(t) = table else {
630 return HashSet::new();
631 };
632 let mut out = HashSet::new();
633 for (name, decl) in &t.services {
634 for h in &decl.handlers {
635 let key = match bynk_model::lower_handler_kind_ir(&h.kind) {
636 bynk_model::IrHandlerKind::Call
637 if bynk_check::actors::call_admission_for(h, &t.actors)
638 .is_some_and(|a| a.sum.is_some()) =>
639 {
640 "call".to_string()
641 }
642 bynk_model::IrHandlerKind::Http { method, path }
643 if bynk_check::actors::sum_members_for(h, &t.actors).is_some() =>
644 {
645 crate::emitter::http_handler_method_name_ir(method, &path)
646 }
647 bynk_model::IrHandlerKind::Call
648 | bynk_model::IrHandlerKind::Http { .. }
649 | bynk_model::IrHandlerKind::Cron { .. }
650 | bynk_model::IrHandlerKind::Message
651 | bynk_model::IrHandlerKind::Open
652 | bynk_model::IrHandlerKind::Close
653 | bynk_model::IrHandlerKind::Event
654 | bynk_model::IrHandlerKind::Rejected => continue,
655 };
656 out.insert((name.clone(), key));
657 }
658 // #2856: a Bearer/Oidc route whose `by` has no binder mints no
659 // identity (`deps` carries no `identity` field), so an in-process call
660 // must not pass one; recorded under a `nobinder:` key.
661 for h in &decl.handlers {
662 if let bynk_model::IrHandlerKind::Http { method, path } =
663 bynk_model::lower_handler_kind_ir(&h.kind)
664 && (bynk_check::actors::bearer_seam_for(h, &t.actors)
665 .is_some_and(|s| s.binder.is_none())
666 || bynk_check::actors::oidc_seam_for(h, &t.actors)
667 .is_some_and(|s| s.binder.is_none()))
668 {
669 out.insert((
670 name.clone(),
671 format!(
672 "nobinder:{}",
673 crate::emitter::http_handler_method_name_ir(method, &path)
674 ),
675 ));
676 }
677 }
678 // #2380 (L5): an `Oidc` route that binds its actor, recorded under an
679 // `oidc:` key, so an in-process call gives it `deps.claims`.
680 for h in &decl.handlers {
681 if let bynk_model::IrHandlerKind::Http { method, path } =
682 bynk_model::lower_handler_kind_ir(&h.kind)
683 && bynk_check::actors::oidc_seam_for(h, &t.actors)
684 .is_some_and(|s| s.binder.is_some())
685 {
686 out.insert((
687 name.clone(),
688 format!(
689 "oidc:{}",
690 crate::emitter::http_handler_method_name_ir(method, &path)
691 ),
692 ));
693 }
694 }
695 }
696 out
697}
698
699/// v0.119: `Some((run_var, agent_name))` when `prop` is a history property — its
700/// single `for all` binding is `run: History[Agent]`.
701pub(super) fn prop_history_binding(prop: &PropertyDecl) -> Option<(&str, &str)> {
702 prop.forall.bindings.iter().find_map(|b| {
703 let TypeRef::History(inner, _) = &b.type_ref else {
704 return None;
705 };
706 let TypeRef::Named(id) = &**inner else {
707 return None;
708 };
709 Some((b.name.name.as_str(), id.name.as_str()))
710 })
711}
712
713pub(super) fn prop_is_history(prop: &PropertyDecl) -> bool {
714 prop_history_binding(prop).is_some()
715}
716
717/// Emit a single test module TypeScript file plus the [`RunnableTest`]
718/// pointer used by the top-level runner.
719#[allow(clippy::too_many_arguments)]
720/// v0.115 (testing track slice 3): can this contracted free function be attacked
721/// by the runner — *a contract is a property that is always on.* The runner
722/// generates arguments over the parameters' refinement domains, filters by the
723/// `requires` (inputs failing a precondition are discarded, exactly as a
724/// `for all … where` does), calls the function, and the dev/test call-site guard
725/// asserts each `ensures`, throwing a shrinkable `BynkContractError` on
726/// violation. Returns `false` when there is nothing to attack: no `ensures`, no
727/// (nameable) parameters, an effectful return (its inputs include the world —
728/// dev-guard only), a non-primitive parameter (its generated fields are `bigint`
729/// and could mix with `number` arithmetic — dev-guard only), or a parameter the
730/// generator cannot inhabit (an over-narrow / `Matches`-pinned refinement) —
731/// never a false error, mirroring an over-narrow `where`.
732pub(super) fn is_attackable_contract(
733 f: &FnDecl,
734 resolved: &ResolvedCommons,
735 tys: &Arc<Types>,
736) -> bool {
737 if !matches!(&f.name, FnName::Free(_)) {
738 return false;
739 }
740 if f.ensures.is_empty() || f.params.is_empty() {
741 return false;
742 }
743 if matches!(&f.return_type, TypeRef::Effect(_, _)) {
744 return false;
745 }
746 if f.params.iter().any(|p| p.name.name == "_") {
747 return false;
748 }
749 for p in &f.params {
750 let Some(ty) = checker::resolve_type_ref(&p.type_ref, &resolved.types, tys) else {
751 return false;
752 };
753 // Restrict to primitive (or refined-over-primitive) parameters: a
754 // generated composite carries `bigint` fields that would mix with the
755 // function's `number` arithmetic. Composite-param contracts are covered
756 // by the dev guard.
757 if numeric_or_scalar_base(ty, &resolved.types, tys).is_none() {
758 return false;
759 }
760 if !test_suites::prop_binding_generable(
761 ty,
762 &resolved.types,
763 test_suites::PROP_GEN_DEPTH,
764 tys,
765 ) {
766 return false;
767 }
768 }
769 true
770}
771
772/// The primitive base type a parameter erases to — `Some(base)` for a base type
773/// or a refinement/opaque over one, `None` for a composite (record/sum/list/map/
774/// option/result/etc.). Used to gate a contract as attackable — every param
775/// must erase to a primitive `binding_gen`/`destructure_vals` can actually
776/// generate/coerce. (Previously also used to conditionally `Number(…)`-wrap a
777/// call argument at the attacked function's own call site — v0.114's
778/// generator/erasure split; #1426 made that redundant: `destructure_vals`
779/// coerces every `Int`-drawing local at the bind site now, so every argument
780/// reaching the call is already a real `number`.)
781pub(super) fn numeric_or_scalar_base(
782 ty: checker::TyId,
783 types: &HashMap<String, Arc<TypeDecl>>,
784 tys: &Arc<Types>,
785) -> Option<BaseType> {
786 match &*tys.get(ty) {
787 checker::Ty::Base(b) => Some(*b),
788 checker::Ty::Named { name, .. } => match &types.get(name)?.body {
789 TypeBody::Refined { base, .. } | TypeBody::Opaque { base, .. } => Some(*base),
790 TypeBody::Record(_) | TypeBody::Sum(_) => None,
791 },
792 checker::Ty::Error
793 | checker::Ty::Never
794 | checker::Ty::Result(..)
795 | checker::Ty::Option(_)
796 | checker::Ty::Effect(_)
797 | checker::Ty::HttpResult(_)
798 | checker::Ty::QueueResult
799 | checker::Ty::HttpOutcome(_)
800 | checker::Ty::BoundaryRejection
801 | checker::Ty::Asset
802 | checker::Ty::RequestHeaders
803 | checker::Ty::RequestQuery
804 | checker::Ty::RequestCookies
805 | checker::Ty::TokenClaims
806 | checker::Ty::List(_)
807 | checker::Ty::Map(..)
808 | checker::Ty::Set(_)
809 | checker::Ty::Query(_)
810 | checker::Ty::Stream(_)
811 | checker::Ty::Connection(_)
812 | checker::Ty::TestConnection(_)
813 | checker::Ty::ValidationError
814 | checker::Ty::DecodeError
815 | checker::Ty::Unit
816 | checker::Ty::Actor(_)
817 | checker::Ty::ActorSum(_)
818 | checker::Ty::Fn { .. }
819 | checker::Ty::Var(_) => None,
820 }
821}
822
823/// v0.115: the target unit's contracted free functions the runner can attack, in
824/// deterministic (name) order, paired with the resolved view for gen/coercion.
825pub(super) fn attackable_contracts(
826 target_name: &str,
827 unit_tables: &HashMap<String, UnitTable>,
828 unit_uses: &HashMap<String, Vec<String>>,
829 unit_consumes: &HashMap<String, Vec<String>>,
830 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
831 tys: &Arc<Types>,
832) -> Option<(ResolvedCommons, Vec<FnDecl>)> {
833 let (resolved, _) = test_suites::build_privileged_resolved(
834 target_name,
835 unit_tables,
836 unit_uses,
837 unit_consumes,
838 unit_consumes_aliases,
839 )?;
840 let table = unit_tables.get(target_name)?;
841 let mut fns: Vec<FnDecl> = table
842 .fns
843 .values()
844 .map(std::sync::Arc::as_ref)
845 .filter(|f| is_attackable_contract(f, &resolved, tys))
846 .cloned()
847 .collect();
848 fns.sort_by_key(|a| a.name.display());
849 Some((resolved, fns))
850}
851
852/// #917: the type-only namespace qualifier every named type reachable from
853/// `target_name` renders through inside the test module that targets it. A
854/// test module imports the target, the contexts it consumes and its `uses`
855/// commons only as namespaces (`import * as orders from …`), never inlining
856/// their declarations the way a `uses`r module's own production emission does,
857/// so *every* name here is foreign and needs one.
858///
859/// #2075: the precedence is `synthetic_typed_commons_for_target`'s, so a name
860/// qualifies through the declaration the case was checked against: the
861/// target's own type, then a consumed unit's (#2062: a consumed *context*'s
862/// too, whose codecs a `Json.decode[Order]` in a case now generates), then a
863/// `uses`d commons'. A consumed type that collides with a `uses`d one never
864/// reaches here: the checker refuses that unit (`bynk.consumes.name_conflict`).
865pub(super) fn json_codec_qual_for_target(
866 target_name: &str,
867 unit_tables: &HashMap<String, UnitTable>,
868 unit_uses: &HashMap<String, Vec<String>>,
869 unit_consumes: &HashMap<String, Vec<String>>,
870 // #3536: the suites' own `type`s; one named like a first-party type the
871 // target's braces leave out is the suite's, never that type's namespace.
872 suite_types: &[bynk_syntax::ast::TypeDecl],
873) -> HashMap<String, String> {
874 let mut qual = HashMap::new();
875 let left_out = |n: &String| {
876 unit_tables.get(target_name).is_some_and(|t| {
877 t.unselected_consumed_types.contains(n) && suite_types.iter().any(|s| s.name.name == *n)
878 })
879 };
880 // #2702: only the target's own types are all visible (a unit-tier suite sees
881 // its target's private declarations, ADR 0683 decision I); another unit's
882 // `private` type is not in scope, so it must not claim a name.
883 let mut qualify = |units: Option<&Vec<String>>, own: bool| {
884 for u in units.into_iter().flatten() {
885 let ns = test_ns(u);
886 if let Some(table) = unit_tables.get(u) {
887 for n in table.types.keys() {
888 if own || (is_public_type(table, n) && !left_out(n)) {
889 qual.entry(n.clone()).or_insert_with(|| ns_qualifier(&ns));
890 }
891 }
892 }
893 }
894 };
895 // Highest precedence first; `or_insert` keeps the first claim.
896 qualify(Some(&vec![target_name.to_string()]), true);
897 qualify(unit_consumes.get(target_name), false);
898 qualify(unit_uses.get(target_name), false);
899 qual
900}
901
902/// The integration double of a one-per-Worker binding, as the participant's
903/// `env` holds it: the same for every participant, or faulting until the case
904/// stubs the operation.
905/// #3513 B: `Analytics.dataset()` reads the dataset's name from the variable the deployed
906/// Worker's `[vars]` carries, so the harness sets it beside an `Analytics` binding.
907fn push_dataset_var(body: &mut Vec<TsStmt>, env: &str, binding: &WorkerBinding, context: &str) {
908 if !matches!(binding.source, BindingSource::AnalyticsDataset { .. }) {
909 return;
910 }
911 body.push(TsStmt::assign(
912 member(
913 ident(env.to_string()),
914 crate::emitter::wrangler::dataset_var_name(&binding.name),
915 ),
916 str_lit(crate::emitter::wrangler::analytics_dataset_name(
917 &bynk_project::worker_dir_name(context),
918 &binding.name,
919 )),
920 None,
921 ));
922}
923
924fn singleton_integration_double(capability: &str) -> TsExpr {
925 let factory = match capability {
926 // #3300: a fixed version.
927 "Version" => "__makeIntegrationVersionMetadata",
928 // #3478: a Workers AI binding that faults until stubbed.
929 "Ai" => "__makeIntegrationAi",
930 // #3515: an Images binding that faults until stubbed.
931 "Images" => "__makeIntegrationImages",
932 // #3513 B: Analytics SQL never answers in a test; it faults until stubbed.
933 "AnalyticsSql" => "__makeIntegrationAnalyticsSql",
934 other => unreachable!("singleton `{other}` has no integration binding"),
935 };
936 call(ident(factory), vec![])
937}
938
939#[cfg(test)]
940mod tests {
941 use super::*;
942
943 // -- sanitise_suite / sanitise_case_name ----------------------------------
944 #[test]
945 fn sanitise_suite_lowercases_collapses_and_trims() {
946 assert_eq!(sanitise_suite("My Suite"), "my_suite");
947 assert_eq!(sanitise_suite("Foo__Bar"), "foo_bar");
948 assert_eq!(sanitise_suite(" Hello "), "hello");
949 assert_eq!(sanitise_suite("a1B2"), "a1b2");
950 assert_eq!(sanitise_suite("!!!"), "suite"); // empty after trim -> fallback
951 assert_eq!(sanitise_suite(""), "suite");
952 }
953
954 /// No stored golden holds a remote harness, so its text is pinned here: the build, then the
955 /// memo, exactly as they were written as text before they were nodes (1B.5a).
956 #[test]
957 fn the_remote_harness_prints_as_it_always_did() {
958 let stmts = emit_remote_harness(&["shop".to_string(), "pay".to_string()]);
959 let printed: String = stmts[2..]
960 .iter()
961 .map(|s| bynk_ts::print_stmt(s, 0))
962 .collect();
963 let shop = crate::emitter::bindings::service_binding("shop").name;
964 let pay = crate::emitter::bindings::service_binding("pay").name;
965 assert_eq!(
966 printed,
967 format!(
968 "function __buildHarness() {{\n const rootEnv: {{ [binding: string]: __ServiceBinding }} = {{}};\n rootEnv.{shop} = __bynkRemoteBinding(\"{}\");\n rootEnv.{pay} = __bynkRemoteBinding(\"{}\");\n return {{ env: rootEnv }};\n}}\nlet __bynkHarness: ReturnType<typeof __buildHarness> | undefined;\nfunction __makeHarness() {{\n return (__bynkHarness ??= __buildHarness());\n}}\n",
969 worker_dir_name("shop"),
970 worker_dir_name("pay"),
971 )
972 );
973 }
974}