boatramp-server 0.2.6

boatramp HTTP server + API library (streaming static-site publishing)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! GraphQL federation executor: run a query plan and stitch the results.
//!
//! The planner (`graphql_plan`) produces an ordered list of fetches; this executor runs
//! each — a root fetch, or a dependent `_entities` fetch whose representations are built
//! from an earlier fetch's data — and merges every fetch's result into one response,
//! joining entities by their `@key`. Dispatching a fetch to its subgraph is abstracted
//! behind [`SubgraphFetcher`], so the stitching logic is tested with a mock and reused over
//! the real [`BackendRouter`] in the serving path — which routes each fetch to its
//! subgraph's backend (a wasm function, or the SQL data connector), letting a GraphQL→SQL
//! subgraph and a GraphQL→Wasi subgraph compose in one supergraph.
//!
//! Scope is **core federation**: object- and list-valued join points; entities are
//! stitched by representation order (which `_entities` preserves). Nested jumps work via
//! response paths into the already-stitched tree.

use crate::graphql_plan::QueryPlan;
use serde_json::{json, Map, Value};

/// Dispatches one planned fetch to a subgraph and returns its GraphQL response JSON
/// (an object with a `data` field, or a bare data object).
#[async_trait::async_trait]
pub(crate) trait SubgraphFetcher: Sync {
    async fn fetch(&self, subgraph: &str, query: &str, variables: Value) -> Value;
}

/// Execute `plan` with `fetcher`, returning the merged `{ "data": … }` response. `variables`
/// is the incoming operation's variables (a JSON object, or null) — forwarded to every root
/// fetch so a field argument bound to `$var` resolves; an `_entities` fetch also receives them
/// alongside its `representations`.
pub(crate) async fn execute(
    plan: &QueryPlan,
    fetcher: &dyn SubgraphFetcher,
    variables: &Value,
) -> Value {
    let mut data = json!({});
    for fetch in &plan.fetches {
        match &fetch.requires {
            None => {
                let resp = fetcher
                    .fetch(&fetch.subgraph, &fetch.query, variables.clone())
                    .await;
                merge(&mut data, fetch_data(&resp));
            }
            Some(req) => {
                // Build the entity representations from the already-stitched tree at the
                // provider's response path, run the `_entities` fetch, and stitch the
                // resolved entity fields back in at that path.
                let reprs = representations(&data, &req.path, &req.type_name, &req.key);
                let resp = fetcher
                    .fetch(
                        &fetch.subgraph,
                        &fetch.query,
                        with_representations(variables, reprs),
                    )
                    .await;
                let entities = resp
                    .pointer("/data/_entities")
                    .or_else(|| resp.pointer("/_entities"))
                    .cloned()
                    .unwrap_or_else(|| json!([]));
                stitch(&mut data, &req.path, &entities);
            }
        }
    }
    json!({ "data": data })
}

/// A fetch response's data object (unwrapping a `{ "data": … }` envelope).
fn fetch_data(resp: &Value) -> &Value {
    resp.get("data").unwrap_or(resp)
}

/// The variables for an `_entities` fetch: the incoming operation variables (when a JSON object)
/// plus the computed `representations` the `_entities(representations: $representations)` binds.
fn with_representations(variables: &Value, reprs: Value) -> Value {
    let mut map = match variables {
        Value::Object(m) => m.clone(),
        _ => serde_json::Map::new(),
    };
    map.insert("representations".to_string(), reprs);
    Value::Object(map)
}

/// Dispatch one fetch to a subgraph **function** over the in-process invoke path (no network
/// hop, no SSRF surface) — the subgraph name is the function name — mapping the result (or a
/// precise error) to a GraphQL response. An external gateway request is the root of the call
/// chain (`depth` 0); a **guest-initiated** run (via the `graphql` capability) dispatches at the
/// guest's own depth so its sub-fetches count against the shared call-depth cap. Used by the
/// [`BackendRouter`]'s function branch.
///
/// The caller's verified `bearer` is forwarded as the `Authorization` header so a subgraph
/// that authorizes per field sees the same principal on **every** fetch — a root fetch and a
/// dependent `_entities` hydration alike. Without it a subgraph's non-`public` field would see
/// an anonymous caller and refuse. `bearer` is the raw token (the gateway already stripped the
/// `Bearer ` scheme), so re-add it.
async fn invoke_subgraph(
    invoker: &dyn boatramp_handlers::Invoker,
    subgraph: &str,
    query: &str,
    variables: Value,
    bearer: Option<&str>,
    depth: u32,
) -> Value {
    let body = json!({ "query": query, "variables": variables })
        .to_string()
        .into_bytes();
    let mut headers = vec![("content-type".to_string(), b"application/json".to_vec())];
    if let Some(token) = bearer {
        headers.push((
            "authorization".to_string(),
            format!("Bearer {token}").into_bytes(),
        ));
    }
    let request = boatramp_handlers::InvokeRequest {
        method: "POST".to_string(),
        path: "/".to_string(),
        headers,
        body,
    };
    match invoker.invoke(subgraph, request, depth).await {
        Ok(resp) => serde_json::from_slice(&resp.body).unwrap_or_else(|_| {
            json!({ "errors": [{ "message": format!("subgraph `{subgraph}` returned invalid JSON") }] })
        }),
        // A registered subgraph with no deployed function of the same name — the registry
        // SDL and the actual subgraph function are decoupled, so surface this precisely
        // rather than as a generic outage (a silently-wrong result would be worse).
        Err(boatramp_handlers::InvokeError::NotFound) => json!({ "errors": [{
            "message": format!(
                "subgraph `{subgraph}` is registered but no function named `{subgraph}` is deployed"
            )
        }] }),
        Err(boatramp_handlers::InvokeError::Failed(msg)) => json!({ "errors": [{
            "message": format!("subgraph `{subgraph}` failed: {msg}")
        }] }),
    }
}

/// A [`SubgraphFetcher`] that dispatches each fetch to the **right backend**: a SQL-backed
/// subgraph (compiled to SQL against a managed database) or, by default, a wasm function.
/// This is where a GraphQL→SQL subgraph and a GraphQL→Wasi subgraph compose in one
/// supergraph — the gateway plans uniformly and this routes each fetch by its subgraph's
/// registered kind.
pub(crate) struct BackendRouter {
    invoker: std::sync::Arc<dyn boatramp_handlers::Invoker>,
    project: String,
    sql_provider: Option<std::sync::Arc<dyn boatramp_core::sql::SqlBackends>>,
    /// SQL-backed subgraphs: `name → (site, data config)`. A subgraph not here is a function.
    sql_subgraphs: std::collections::BTreeMap<
        String,
        (String, boatramp_core::config::HandlerGraphqlDataConfig),
    >,
    /// The request's verified app bearer token — bound to a SQL subgraph's claim-based
    /// `row_filter`, and forwarded as `Authorization` to a function subgraph so its per-field
    /// authorization sees the same principal.
    bearer: Option<String>,
    /// The call-chain depth at which sub-fetches are invoked. `0` for an external gateway
    /// request (the root); a guest-initiated run sets its own depth so the shared cap counts
    /// its sub-fetches. See [`BackendRouter::at_depth`].
    depth: u32,
}

impl BackendRouter {
    pub(crate) fn new(
        invoker: std::sync::Arc<dyn boatramp_handlers::Invoker>,
        project: String,
        sql_provider: Option<std::sync::Arc<dyn boatramp_core::sql::SqlBackends>>,
        sql_subgraphs: std::collections::BTreeMap<
            String,
            (String, boatramp_core::config::HandlerGraphqlDataConfig),
        >,
        bearer: Option<String>,
    ) -> Self {
        Self {
            invoker,
            project,
            sql_provider,
            sql_subgraphs,
            bearer,
            depth: 0,
        }
    }

    /// Dispatch this router's sub-fetches at call-chain `depth` (default `0`, the external
    /// gateway root). A guest-initiated run sets its own depth so the shared invoke depth cap
    /// counts a guest op → subgraph fetch → guest op chain and stops it looping.
    pub(crate) fn at_depth(mut self, depth: u32) -> Self {
        self.depth = depth;
        self
    }

    /// Resolve a fetch for a SQL-backed subgraph: open the site's database, introspect, and
    /// compile + run the fetch (the connector's own path), returning its GraphQL response.
    async fn run_sql(
        &self,
        subgraph: &str,
        site: &str,
        config: &boatramp_core::config::HandlerGraphqlDataConfig,
        query: &str,
        variables: Value,
    ) -> Value {
        let Some(provider) = &self.sql_provider else {
            return json!({ "errors": [{ "message": "the federation gateway has no SQL backend configured" }] });
        };
        let backend = match provider.database(&self.project, site, &config.source).await {
            Ok(backend) => backend,
            Err(err) => {
                return json!({ "errors": [{ "message": format!("subgraph `{subgraph}` database unavailable: {err}") }] })
            }
        };
        let schema = match crate::graphql_data::introspect::introspect_sqlite(backend.as_ref())
            .await
        {
            Ok(schema) => schema,
            Err(err) => {
                return json!({ "errors": [{ "message": format!("subgraph `{subgraph}` introspection failed: {err}") }] })
            }
        };
        let policy = crate::graphql_data::policy_from_config(config);
        let claims =
            crate::graphql_data::request_claims(&self.project, self.bearer.as_deref(), config)
                .await;
        let dialect = crate::graphql_data::dialect::Sqlite;
        let invoker = Some(self.invoker.as_ref());
        // A SQL subgraph resolves both root fetches and — so it's a full federation entity
        // resolver — `_entities` fetches (a keyed SELECT joined back by representation order).
        if crate::graphql_data::compile::is_entities_query(query) {
            crate::graphql_data::runner::execute_entities(
                backend.as_ref(),
                &dialect,
                &schema,
                &policy,
                &claims,
                query,
                &variables,
                invoker,
                self.bearer.as_deref(),
                self.depth,
            )
            .await
        } else {
            crate::graphql_data::runner::execute(
                backend.as_ref(),
                &dialect,
                &schema,
                &policy,
                &claims,
                query,
                &variables,
                invoker,
                self.bearer.as_deref(),
                self.depth,
            )
            .await
        }
    }
}

#[async_trait::async_trait]
impl SubgraphFetcher for BackendRouter {
    async fn fetch(&self, subgraph: &str, query: &str, variables: Value) -> Value {
        if let Some((site, config)) = self.sql_subgraphs.get(subgraph) {
            return self.run_sql(subgraph, site, config, query, variables).await;
        }
        invoke_subgraph(
            self.invoker.as_ref(),
            subgraph,
            query,
            variables,
            self.bearer.as_deref(),
            self.depth,
        )
        .await
    }
}

/// The server's [`SupergraphRunner`](boatramp_handlers::SupergraphRunner): runs a guest's
/// GraphQL operation against the project's composed supergraph in-process — the same planner +
/// executor an external `/graphql` request uses (via [`BackendRouter`]), plus two guest-specific
/// gates: a **forced safelist** (only pre-registered operations run — deny-by-default) and the
/// **shared depth cap** (sub-fetches dispatch at the guest's own depth so a run → subgraph fetch
/// → run chain cannot loop). The caller's own bearer is forwarded and re-verified per subgraph,
/// so a guest cannot escalate by running this.
pub(crate) struct FederationRunner {
    runtime: std::sync::Weak<crate::HandlerRuntimeInner>,
    project: String,
}

impl FederationRunner {
    /// A runner bound to `runtime`; scope it per request with [`FederationRunner::scoped`].
    pub(crate) fn new(runtime: std::sync::Weak<crate::HandlerRuntimeInner>) -> Self {
        Self {
            runtime,
            project: boatramp_core::project::DEFAULT_PROJECT.to_string(),
        }
    }

    /// A runner scoped to `project` (all registry/plan/execute lookups are project-qualified),
    /// as the guest grant needs — mirrors the invoker's per-tenant scoping.
    pub(crate) fn scoped(
        &self,
        project: boatramp_core::project::ProjectRef<'_>,
    ) -> std::sync::Arc<dyn boatramp_handlers::SupergraphRunner> {
        std::sync::Arc::new(Self {
            runtime: self.runtime.clone(),
            project: project.as_str().to_string(),
        })
    }
}

/// Strip a leading `Bearer ` scheme (case-insensitive) from a forwarded Authorization value,
/// leaving the raw token [`BackendRouter`] expects (it re-adds the scheme per subgraph).
fn strip_bearer(raw: &str) -> &str {
    raw.strip_prefix("Bearer ")
        .or_else(|| raw.strip_prefix("bearer "))
        .unwrap_or(raw)
}

#[async_trait::async_trait]
impl boatramp_handlers::SupergraphRunner for FederationRunner {
    async fn run(
        &self,
        request: boatramp_handlers::GraphqlRequest,
        depth: u32,
    ) -> Result<Vec<u8>, boatramp_handlers::SupergraphRunError> {
        use boatramp_handlers::SupergraphRunError;
        let Some(inner) = self.runtime.upgrade() else {
            return Err(SupergraphRunError::Failed(
                "handler runtime is shutting down".into(),
            ));
        };
        let kv = inner.kv.as_ref();
        let project = self.project.as_str();

        // Deny-by-default operation surface: a guest may run only a pre-registered (safelisted)
        // operation — by its hash for `run-persisted`, or the hash of the supplied `query` for
        // `run`. The subgraph field guards remain the hard enforcement; this is the floor.
        let hash = match (&request.query, &request.persisted_hash) {
            (Some(query), _) => crate::graphql_apq::sha256_hex(query),
            (None, Some(hash)) => hash.clone(),
            (None, None) => {
                return Err(SupergraphRunError::PlanFailed(
                    "no query or persisted hash supplied".into(),
                ))
            }
        };
        let Some(query) = crate::graphql_apq::safelisted_query(kv, project, &hash).await else {
            return Err(SupergraphRunError::NotSafelisted);
        };

        // Query-guard the resolved operation (depth/complexity), exactly as at the edge.
        let limits = crate::graphql_guard::limits_from(
            &boatramp_core::config::HandlerGraphqlConfig::default(),
        );
        if let crate::graphql_guard::GuardVerdict::Reject(reason) =
            crate::graphql_guard::guard_query(&query, &limits)
        {
            return Err(SupergraphRunError::PlanFailed(reason));
        }

        // Compose + plan against the project's registered subgraphs (the unified graph).
        let supergraph = crate::graphql_registry::supergraph(kv, project)
            .await
            .map_err(|e| {
                SupergraphRunError::Failed(format!("supergraph composition failed: {e}"))
            })?;
        let plan = crate::graphql_plan::plan(&query, &supergraph)
            .map_err(|_| SupergraphRunError::PlanFailed("the query cannot be planned".into()))?;

        let Some(invoker) = inner.invoker.get() else {
            return Err(SupergraphRunError::Failed("no invoker configured".into()));
        };
        let sql_subgraphs = crate::graphql_registry::sql_subgraphs(kv, project).await;
        // Forward the guest's own bearer (re-verified per subgraph — no escalation), and dispatch
        // sub-fetches at this run's depth so the shared cap counts them.
        let bearer = request
            .authorization
            .as_deref()
            .map(|raw| strip_bearer(raw).to_string());
        let router = BackendRouter::new(
            invoker.scoped(boatramp_core::project::ProjectRef::new(project)),
            project.to_string(),
            inner.sql.clone(),
            sql_subgraphs,
            bearer,
        )
        .at_depth(depth);
        // The guest's operation variables (a JSON object string) — forwarded to the fetches so a
        // mutation/field argument bound to `$var` resolves. An unparseable/empty value is `{}`.
        let variables: Value =
            serde_json::from_str(&request.variables).unwrap_or_else(|_| json!({}));
        let response = execute(&plan, &router, &variables).await;
        serde_json::to_vec(&response)
            .map_err(|e| SupergraphRunError::Failed(format!("serializing response: {e}")))
    }
}

/// Deep-merge `src` into `dst`: objects merge key-by-key; anything else overwrites.
fn merge(dst: &mut Value, src: &Value) {
    match (dst, src) {
        (Value::Object(d), Value::Object(s)) => {
            for (k, v) in s {
                merge(d.entry(k.clone()).or_insert(Value::Null), v);
            }
        }
        (d, s) => *d = s.clone(),
    }
}

fn navigate<'a>(data: &'a Value, path: &[String]) -> Option<&'a Value> {
    let mut cur = data;
    for seg in path {
        cur = cur.get(seg)?;
    }
    Some(cur)
}

fn navigate_mut<'a>(data: &'a mut Value, path: &[String]) -> Option<&'a mut Value> {
    let mut cur = data;
    for seg in path {
        cur = cur.get_mut(seg)?;
    }
    Some(cur)
}

/// The `_entities` representations for the object(s) at `path`: `{ __typename, <key…> }`
/// for each (an object contributes one; an array contributes one per element).
fn representations(data: &Value, path: &[String], type_name: &str, key: &[String]) -> Value {
    let mut out = Vec::new();
    if let Some(node) = navigate(data, path) {
        collect_reprs(node, type_name, key, &mut out);
    }
    Value::Array(out)
}

fn collect_reprs(node: &Value, type_name: &str, key: &[String], out: &mut Vec<Value>) {
    match node {
        Value::Array(items) => {
            for item in items {
                collect_reprs(item, type_name, key, out);
            }
        }
        Value::Object(_) => {
            let mut repr = Map::new();
            repr.insert("__typename".to_string(), json!(type_name));
            for k in key {
                if let Some(v) = node.get(k) {
                    repr.insert(k.clone(), v.clone());
                }
            }
            out.push(Value::Object(repr));
        }
        _ => {}
    }
}

/// Merge the resolved `entities` back into the tree at `path`, by representation order
/// (an object join point takes the first entity; a list join point takes them positionally).
fn stitch(data: &mut Value, path: &[String], entities: &Value) {
    let Some(node) = navigate_mut(data, path) else {
        return;
    };
    let ents = entities.as_array().cloned().unwrap_or_default();
    match node {
        Value::Array(items) => {
            for (item, ent) in items.iter_mut().zip(ents.iter()) {
                merge(item, ent);
            }
        }
        Value::Object(_) => {
            if let Some(ent) = ents.first() {
                merge(node, ent);
            }
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graphql_federation::compose;
    use crate::graphql_plan::plan;
    use std::collections::HashMap;

    const ACCOUNTS: &str = r#"
        type Query { me: User }
        type User @key(fields: "id") { id: ID! name: String }
    "#;
    const ACCOUNTS_LIST: &str = r#"
        type Query { users: [User] }
        type User @key(fields: "id") { id: ID! name: String }
    "#;
    const REVIEWS: &str = r#"
        type Query { topReviews: [Review] }
        type Review { id: ID! body: String }
        extend type User @key(fields: "id") { id: ID! @external reviews: [Review] }
    "#;

    /// A mock runner returning a canned response per subgraph.
    struct Mock(HashMap<&'static str, Value>);

    #[async_trait::async_trait]
    impl SubgraphFetcher for Mock {
        async fn fetch(&self, subgraph: &str, _query: &str, _variables: Value) -> Value {
            self.0.get(subgraph).cloned().unwrap_or_else(|| json!({}))
        }
    }

    /// A runner that honors the real federation contract instead of returning a canned
    /// answer: a root fetch returns its data; an `_entities` fetch reads the
    /// `representations` variable and resolves each representation **by its key, in
    /// order** — exactly what an async-graphql federation subgraph's `_entities` resolver
    /// does. Using it end-to-end exercises the whole representations→`_entities`→stitch
    /// round-trip against a faithful subgraph, not a stub that echoes the expected result.
    struct ContractRunner;

    #[async_trait::async_trait]
    impl SubgraphFetcher for ContractRunner {
        async fn fetch(&self, subgraph: &str, query: &str, variables: Value) -> Value {
            match subgraph {
                "accounts" => json!({ "data": { "users": [
                    { "__typename": "User", "id": "1", "name": "Alice" },
                    { "__typename": "User", "id": "2", "name": "Bob" },
                ] } }),
                "reviews" => {
                    assert!(
                        query.contains("_entities"),
                        "entity fetch must use _entities"
                    );
                    let reprs = variables
                        .get("representations")
                        .and_then(|v| v.as_array())
                        .cloned()
                        .unwrap_or_default();
                    let entities: Vec<Value> = reprs
                        .iter()
                        .map(|r| {
                            let id = r.get("id").and_then(|v| v.as_str()).unwrap_or("");
                            json!({ "reviews": [ { "body": format!("review for {id}") } ] })
                        })
                        .collect();
                    json!({ "data": { "_entities": entities } })
                }
                other => json!({ "errors": [{ "message": format!("unknown subgraph {other}") }] }),
            }
        }
    }

    /// An [`Invoker`](boatramp_handlers::Invoker) with no functions deployed — every
    /// target resolves to `NotFound`, so [`invoke_subgraph`] must report the
    /// registered-but-undeployed subgraph precisely.
    struct MissingInvoker;

    #[async_trait::async_trait]
    impl boatramp_handlers::Invoker for MissingInvoker {
        async fn invoke(
            &self,
            _target: &str,
            _request: boatramp_handlers::InvokeRequest,
            _depth: u32,
        ) -> Result<boatramp_handlers::InvokeResponse, boatramp_handlers::InvokeError> {
            Err(boatramp_handlers::InvokeError::NotFound)
        }
    }

    /// An [`Invoker`](boatramp_handlers::Invoker) that reflects the `Authorization` header it
    /// received back into its response — modelling a subgraph that authorizes per field: with a
    /// forwarded bearer it resolves (echoing the identity), without one it refuses with
    /// `UNAUTHENTICATED`. It lets a test prove the gateway forwards the caller's identity on the
    /// invoke path (root and `_entities` alike) rather than dropping it.
    struct AuthEchoInvoker;

    #[async_trait::async_trait]
    impl boatramp_handlers::Invoker for AuthEchoInvoker {
        async fn invoke(
            &self,
            _target: &str,
            request: boatramp_handlers::InvokeRequest,
            _depth: u32,
        ) -> Result<boatramp_handlers::InvokeResponse, boatramp_handlers::InvokeError> {
            let authz = request
                .headers
                .iter()
                .find(|(k, _)| k.eq_ignore_ascii_case("authorization"))
                .map(|(_, v)| String::from_utf8_lossy(v).into_owned());
            let body = match authz {
                Some(value) => json!({ "data": { "identity": value } }),
                None => json!({ "errors": [
                    { "message": "unauthenticated", "extensions": { "code": "UNAUTHENTICATED" } }
                ] }),
            };
            Ok(boatramp_handlers::InvokeResponse {
                status: 200,
                headers: vec![("content-type".to_string(), b"application/json".to_vec())],
                body: serde_json::to_vec(&body).unwrap(),
            })
        }
    }

    #[tokio::test]
    async fn merges_root_fetches_from_distinct_subgraphs() {
        let sg = compose(&[
            ("accounts".into(), ACCOUNTS.into()),
            ("reviews".into(), REVIEWS.into()),
        ])
        .unwrap();
        let plan = plan("{ me { name } topReviews { body } }", &sg).unwrap();
        let mock = Mock(HashMap::from([
            ("accounts", json!({ "data": { "me": { "name": "Alice" } } })),
            (
                "reviews",
                json!({ "data": { "topReviews": [{ "body": "ok" }] } }),
            ),
        ]));
        let out = execute(&plan, &mock, &json!({})).await;
        assert_eq!(out["data"]["me"]["name"], json!("Alice"));
        assert_eq!(out["data"]["topReviews"][0]["body"], json!("ok"));
    }

    #[tokio::test]
    async fn stitches_a_cross_subgraph_entity_field() {
        let sg = compose(&[
            ("accounts".into(), ACCOUNTS.into()),
            ("reviews".into(), REVIEWS.into()),
        ])
        .unwrap();
        let plan = plan("{ me { name reviews { body } } }", &sg).unwrap();
        let mock = Mock(HashMap::from([
            (
                "accounts",
                json!({ "data": { "me": { "name": "Alice", "__typename": "User", "id": "1" } } }),
            ),
            (
                "reviews",
                json!({ "data": { "_entities": [{ "reviews": [{ "body": "great" }] }] } }),
            ),
        ]));
        let out = execute(&plan, &mock, &json!({})).await;
        // The `me` object now carries both its accounts fields and the stitched reviews.
        assert_eq!(out["data"]["me"]["name"], json!("Alice"));
        assert_eq!(out["data"]["me"]["reviews"][0]["body"], json!("great"));
    }

    #[tokio::test]
    async fn executes_a_list_entity_fetch_joining_each_element_by_its_key() {
        let sg = compose(&[
            ("accounts".into(), ACCOUNTS_LIST.into()),
            ("reviews".into(), REVIEWS.into()),
        ])
        .unwrap();
        let plan = plan("{ users { name reviews { body } } }", &sg).unwrap();
        let out = execute(&plan, &ContractRunner, &json!({})).await;
        // Each list element is joined to *its own* reviews by key — proving the
        // representations→`_entities`→stitch round-trip preserves per-element identity
        // (element 2 gets review-for-2, not review-for-1), which a canned mock can't show.
        assert_eq!(out["data"]["users"][0]["name"], json!("Alice"));
        assert_eq!(
            out["data"]["users"][0]["reviews"][0]["body"],
            json!("review for 1")
        );
        assert_eq!(out["data"]["users"][1]["name"], json!("Bob"));
        assert_eq!(
            out["data"]["users"][1]["reviews"][0]["body"],
            json!("review for 2")
        );
    }

    #[tokio::test]
    async fn a_function_subgraph_that_is_not_deployed_is_reported_precisely() {
        // A router with no SQL subgraphs routes every fetch to the invoke path.
        let router = BackendRouter::new(
            std::sync::Arc::new(MissingInvoker),
            "default".to_string(),
            None,
            std::collections::BTreeMap::new(),
            None,
        );
        let resp = router.fetch("accounts", "{ me { id } }", json!({})).await;
        let msg = resp["errors"][0]["message"].as_str().unwrap_or_default();
        assert!(
            msg.contains("no function named `accounts` is deployed"),
            "unexpected error: {msg}"
        );
    }

    #[tokio::test]
    async fn forwards_the_callers_verified_bearer_to_a_function_subgraph() {
        let router = BackendRouter::new(
            std::sync::Arc::new(AuthEchoInvoker),
            "default".to_string(),
            None,
            std::collections::BTreeMap::new(),
            Some("t-acme".to_string()),
        );
        // A root fetch carries the caller's identity as `Bearer <token>`...
        let root = router.fetch("orders", "{ me { id } }", json!({})).await;
        assert_eq!(root["data"]["identity"], json!("Bearer t-acme"));
        // ...and so does a dependent `_entities` hydration fetch (same dispatch path).
        let entity = router
            .fetch(
                "orders",
                "query($r: [_Any!]!) { _entities(representations: $r) { id } }",
                json!({ "representations": [{ "__typename": "Order", "id": "1" }] }),
            )
            .await;
        assert_eq!(
            entity["data"]["identity"],
            json!("Bearer t-acme"),
            "the bearer must ride the _entities fetch too, or a stitched field would go anonymous"
        );
    }

    #[tokio::test]
    async fn an_anonymous_gateway_call_forwards_no_bearer_so_an_authed_field_is_refused() {
        let router = BackendRouter::new(
            std::sync::Arc::new(AuthEchoInvoker),
            "default".to_string(),
            None,
            std::collections::BTreeMap::new(),
            None,
        );
        let resp = router.fetch("orders", "{ me { id } }", json!({})).await;
        assert_eq!(
            resp["errors"][0]["extensions"]["code"],
            json!("UNAUTHENTICATED"),
            "with no forwarded identity a subgraph's authed field must refuse, not resolve anonymously"
        );
    }

    #[test]
    fn merge_is_a_deep_object_merge() {
        let mut a = json!({ "me": { "name": "x" } });
        merge(&mut a, &json!({ "me": { "age": 3 }, "other": 1 }));
        assert_eq!(a, json!({ "me": { "name": "x", "age": 3 }, "other": 1 }));
    }

    /// An invoker that reflects the call-chain `depth` it was dispatched at back into its
    /// response, so a test can prove `BackendRouter::at_depth` threads the guest's depth through
    /// to the sub-fetch (the recursion-safety guarantee).
    struct DepthEchoInvoker;

    #[async_trait::async_trait]
    impl boatramp_handlers::Invoker for DepthEchoInvoker {
        async fn invoke(
            &self,
            _target: &str,
            _request: boatramp_handlers::InvokeRequest,
            depth: u32,
        ) -> Result<boatramp_handlers::InvokeResponse, boatramp_handlers::InvokeError> {
            Ok(boatramp_handlers::InvokeResponse {
                status: 200,
                headers: vec![("content-type".to_string(), b"application/json".to_vec())],
                body: serde_json::to_vec(&json!({ "data": { "depth": depth } })).unwrap(),
            })
        }
    }

    #[tokio::test]
    async fn at_depth_dispatches_function_fetches_at_that_depth() {
        // The external gateway is the root (depth 0)...
        let root = BackendRouter::new(
            std::sync::Arc::new(DepthEchoInvoker),
            "default".to_string(),
            None,
            std::collections::BTreeMap::new(),
            None,
        );
        assert_eq!(
            root.fetch("s", "{ x }", json!({})).await["data"]["depth"],
            json!(0)
        );
        // ...a guest-initiated run dispatches its sub-fetches at its own depth, so the shared
        // invoke cap counts a run → subgraph → run chain and stops it looping.
        let scoped = BackendRouter::new(
            std::sync::Arc::new(DepthEchoInvoker),
            "default".to_string(),
            None,
            std::collections::BTreeMap::new(),
            None,
        )
        .at_depth(4);
        assert_eq!(
            scoped.fetch("s", "{ x }", json!({})).await["data"]["depth"],
            json!(4)
        );
    }
}