@reventlessdev/rescript-pulumi-aws 3.0.0-alpha.3 → 3.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -30,19 +30,11 @@ export function response(ctx) {
30
30
  let importUtil = `import { util } from '@aws-appsync/utils';`
31
31
 
32
32
  /**
33
- The caller-is-exempt test, emitted into a resolver's response.
34
-
35
- Mirrors `Reventless.OwnerScope.resolve` the same branch order for the same
36
- reason the list predicate gives: an IAM-signed service caller has no `sub`
37
- because it is inside the trust boundary, not because it is anonymous, so the
38
- provider question is answered before the identity one.
39
-
40
- In the RESPONSE rather than the request, because a `GetItem` has no
41
- FilterExpression to carry a predicate: the row is fetched by key and the
42
- decision is made on what came back. A `Query` could filter server-side, and
43
- deliberately does not — a single-row read that filtered in one place and
44
- guarded in another would have two implementations of one rule, and the cheaper
45
- one is the one nobody would remember to change.
33
+ The caller-is-exempt test, emitted into a resolver's response. Mirrors
34
+ `Reventless.OwnerScope.resolve`, branch order included — an IAM-signed caller has
35
+ no `sub` because it is inside the trust boundary, not because it is anonymous.
36
+ In the response because `GetItem` has no FilterExpression; `Query` follows it so
37
+ one rule keeps one implementation.
46
38
  */
47
39
  let ownerGuardPreamble = (~ownerField: string, ~elevatedGroups: array<string>) => {
48
40
  let elevatedLiteral = elevatedGroups->Array.map(g => `'${g}'`)->Array.join(", ")
@@ -56,12 +48,9 @@ let ownerGuardPreamble = (~ownerField: string, ~elevatedGroups: array<string>) =
56
48
  }
57
49
 
58
50
  /**
59
- The exemption test on its own, for a door that narrows retirement but has no
60
- `@owner` field to have declared it already.
61
-
62
- Identical to the three lines `ownerGuardPreamble` opens with, and emitted only
63
- when that preamble is absent — two `const _exempt` in one function body is a
64
- syntax error, and two *different* definitions of exempt would be worse than one.
51
+ The exemption test alone, for a door that narrows retirement but declares no
52
+ `@owner`. Emitted only when `ownerGuardPreamble` is absent two `const _exempt`
53
+ in one body is a syntax error, and two different ones would be worse.
65
54
  */
66
55
  let exemptPreamble = (~elevatedGroups: array<string>) => {
67
56
  let elevatedLiteral = elevatedGroups->Array.map(g => `'${g}'`)->Array.join(", ")
@@ -75,22 +64,14 @@ let exemptPreamble = (~elevatedGroups: array<string>) => {
75
64
 
76
65
  /**
77
66
  A by-key read's retirement guard: `_live(row)`, true when the caller may see it.
67
+ The post-read half of what `listAllItemsConnection` pushes into a
68
+ FilterExpression — `GetItem` has none to push into.
78
69
 
79
- The post-read half of the predicate `listAllItemsConnection` pushes into a
80
- FilterExpression. `GetItem` and `BatchGetItem` have no filter to push into the
81
- row is fetched by key — so the decision is made on what came back, which is where
82
- the owner guard beside it already makes its own.
83
-
84
- `row[field] == null` keeps a row written before the annotation existed, matching
85
- the `attribute_not_exists` half of the list's clause and every other adapter's
86
- reading of an absent value.
87
-
88
- Asking is required, not merely permitted: `_exempt` alone leaves a retired row
89
- withheld until `includeRetired` is passed, so an operator's ordinary read is as
90
- narrow as anyone's. An archive that is always underfoot is not an archive.
70
+ `row[field] == null` keeps a row written before the annotation existed. Exemption
71
+ alone withholds a retired row until `includeRetired` is passed, so an operator's
72
+ ordinary read is as narrow as anyone's.
91
73
 
92
- `~ownerScoped` says whether an `ownerGuardPreamble` has already been emitted into
93
- the same body; when it has, this reuses its `_exempt` instead of redeclaring one.
74
+ `~ownerScoped` says an `ownerGuardPreamble` already declared `_exempt` here.
94
75
  */
95
76
  let retiredGuardPreamble = (
96
77
  ~retiredField: option<string>,
@@ -116,23 +97,15 @@ let retiredGuardPreamble = (
116
97
  }
117
98
 
118
99
  /**
119
- The `@owner` predicate for an index door, as a FilterExpression clause.
120
-
121
- Same rule and same branch order as `listAllItemsConnection`'s own owner clause —
122
- provider before identity, because an IAM-signed service caller has no `sub` for a
123
- reason that has nothing to do with being anonymous — and pushed into the read for
124
- the same reason: an index door takes a `limit`, and a page cut before the
125
- predicate would come back short with nothing said about why.
126
-
127
- **Not applied to a group-restricted index.** Where `indexConfig.authorization` is
128
- set, the door already runs `authorizeIndexedAccess`: the caller must be in the
129
- named group AND be the holder the auth table records for that index value. Those
130
- rows are, by construction, other people's — an order assigned to a fulfilment
131
- operator is owned by the customer who placed it — so ANDing `@owner` on top would
132
- return nothing and revoke exactly the access the auth table was written to grant.
133
- An explicit per-index rule is the deployment's answer for that door; this is the
134
- default for doors that have none. `QueryDbResolvers_AppSync` decides which is
135
- which and passes `ownerField` only for the latter.
100
+ The `@owner` predicate for an index door, as a FilterExpression clause. Same rule
101
+ and branch order as `listAllItemsConnection`'s, and pushed into the read for the
102
+ same reason.
103
+
104
+ **Not applied to a group-restricted index.** There `authorizeIndexedAccess`
105
+ already gates the caller, and the rows are by construction other people's an
106
+ order assigned to a fulfilment operator is owned by the customer who placed it —
107
+ so ANDing `@owner` on top would revoke exactly what the auth table granted.
108
+ `QueryDbResolvers_AppSync` passes `ownerField` only for doors with no such rule.
136
109
  */
137
110
  let ownerFilterClause = (~ownerField: option<string>, ~elevatedGroups: array<string>) =>
138
111
  switch ownerField {
@@ -158,16 +131,12 @@ let ownerFilterClause = (~ownerField: option<string>, ~elevatedGroups: array<str
158
131
 
159
132
  /**
160
133
  The same retirement predicate as `retiredGuardPreamble`, for a door that reads
161
- with `Query` and therefore has a FilterExpression to put it in.
134
+ with `Query` and so has a FilterExpression to put it in. Pushed into the read
135
+ rather than applied after it, or the page comes back short with nothing said
136
+ about why.
162
137
 
163
- Pushed into the read rather than applied to what came back, on
164
- `listAllItemsConnection`'s reasoning: an index door takes a `limit`, and
165
- narrowing after the read would hand back a page of fewer rows than the caller
166
- asked for while reporting nothing about why.
167
-
168
- Emits JS that appends to the `expression` / `names` / `values` the index
169
- templates already build, so it composes with a caller's own filter arguments
170
- instead of replacing them.
138
+ Appends to the `expression` / `names` / `values` the index templates already
139
+ build, so it composes with a caller's own filter arguments.
171
140
  */
172
141
  let retiredFilterClause = (
173
142
  ~retiredField: option<string>,
@@ -207,13 +176,9 @@ ${assignments}
207
176
  /**
208
177
  A by-key read's response, refusing a row the caller does not own.
209
178
 
210
- **Null, not an error** which is the opposite of what a first reading suggests,
211
- since "you may not read this" and "there is nothing here" are different answers
212
- and only one of them is true. Two things settle it. The in-process platform
213
- already answers `null` here, and a rule enforced differently per transport is
214
- the failure mode owner scoping exists to avoid. And an error would confirm the
215
- row exists to a caller who may not read it, which is a worse leak than the
216
- ambiguity it removes.
179
+ **Null, not an error.** The in-process platform answers `null` here, and a rule
180
+ enforced differently per transport is what owner scoping exists to avoid. An
181
+ error would also confirm the row exists to a caller who may not read it.
217
182
  */
218
183
  let ownerScopedResultResponse = (
219
184
  ~ownerField: option<string>,
@@ -303,12 +268,9 @@ ${resultResponseCode}
303
268
  /** Pipeline function (NONE datasource): decodes global ID and stashes typeName + localId.
304
269
 
305
270
  Written without a `try`: APPSYNC_JS rejects try statements outright
306
- (`@aws-appsync/no-try`), so a guarded version of this cannot be deployed at
307
- all. Nothing is lost by dropping it `util.base64Decode` does not throw on
308
- malformed input, it returns the bytes it made of it, so the catch could never
309
- run. An id that decodes to no `type:localId` pair therefore fails the one way
310
- that is left: both halves stash as null, which is also what the guarded
311
- version reported for a decode it could not parse. */
271
+ (`@aws-appsync/no-try`), and nothing is lost `util.base64Decode` returns
272
+ bytes rather than throwing on malformed input, so an unparseable id stashes
273
+ both halves as null, which is what a guarded version reported anyway. */
312
274
  let nodeDecodeGlobalId =
313
275
  `${importUtil}
314
276
  export function request(ctx) {
@@ -585,61 +547,190 @@ export function request(ctx) {
585
547
  ${resultResponseCode}
586
548
  `->Pulumi.Input.make
587
549
 
550
+ // ---------------------------------------------------------------------------
551
+ // Paging a filtered read
552
+ // ---------------------------------------------------------------------------
553
+
588
554
  /**
589
- The by-index door's response.
555
+ Rows a read may EXAMINE per page.
590
556
 
591
- Cursors are the DynamoDB continuation token carrying the row's position in the
592
- page, exactly as `listAllItemsConnection` builds themthe two doors page over
593
- the same kind of result, so they page the same way. The boundary cursor covers
594
- the case that door documents: a filtered page can come back empty while a token
595
- is still set, and a client has to be able to resume past it.
557
+ `Limit` applies before the FilterExpression, so reading `first` rows and returning
558
+ the survivors serves short usually empty pages under a selective filter. With
559
+ no loops in APPSYNC_JS the door reads wider instead and addresses the surplus by
560
+ position. 1 MB caps a page anyway, hence 1000; `filtered` is the JS expression
561
+ saying whether a filter was pushed down.
562
+ */
563
+ let pageWindowBudget = (~filtered: string) =>
564
+ `(${filtered} ? (_first > 1000 ? _first : 1000) : _first + _from)`
596
565
 
597
- This replaces returning `ctx.result` raw. The field has always been declared as
598
- returning a `Connection!`, and handing back DynamoDB's `{items, nextToken}`
599
- satisfied no part of that contract.
566
+ /**
567
+ The same budget for the full-list door, which may also read backward.
568
+
569
+ A backward page is the slice `[_from, _upTo)` of the window, so the read has to
570
+ reach `_upTo` rows into it — `_first + _from` would stop short and hand back a
571
+ page with its tail missing.
600
572
  */
601
- let indexConnectionResponseCode = `
602
- export function response(ctx) {
603
- if (ctx.error) util.error(ctx.error.message, ctx.error.type);
604
- const items = ctx.result?.items ?? [];
605
- const next = ctx.result?.nextToken ?? null;
606
- const edges = items.map((item, i) => ({
573
+ let listPageWindowBudget = {
574
+ let need = "(_backward ? _upTo : _first + _from)"
575
+ `(parts.length > 0 ? (${need} > 1000 ? ${need} : 1000) : ${need})`
576
+ }
577
+
578
+ /**
579
+ Decodes `after` into the window it names (`t`, the token opening it) and the row's
580
+ index among that window's matches (`n`). Pre-window cursors carried
581
+ `{token, index}` naming the window that follows — position -1 of it.
582
+
583
+ `p` is the one-character tag naming which read the window belongs to (`s` Scan,
584
+ `q` the owner-index Query). Absent reads as `s`: every cursor minted before the
585
+ tag existed came off a Scan. Only a door with more than one read tests it — see
586
+ `cursorPathGuard`.
587
+ */
588
+ let cursorDecode = (~args: string) => `
589
+ let _window = null;
590
+ let _from = 0;
591
+ let _cursorPath = null;
592
+ if (${args}.after != null && ${args}.after !== '') {
593
+ const _c = JSON.parse(util.base64Decode(${args}.after));
594
+ _window = (_c.t !== undefined ? _c.t : _c.token) ?? null;
595
+ _from = _c.n !== undefined ? _c.n + 1 : 0;
596
+ _cursorPath = _c.p ?? 's';
597
+ }`
598
+
599
+ /**
600
+ Refuses a cursor minted on this door's other read. The two branches are selectable
601
+ by the SAME caller across requests — an active-role switch mid-pagination flips
602
+ `_exempt` — and a `nextToken` continues the operation that issued it, so replaying
603
+ one on the other branch answers a different question without saying so.
604
+
605
+ Expects `_cursorPath` from `cursorDecode` and `_exempt` from the owner preamble.
606
+ */
607
+ let cursorPathGuard = `
608
+ if (_cursorPath !== null && _cursorPath !== (_exempt ? 's' : 'q')) {
609
+ util.error('This cursor belongs to a different read of this list; restart from the first page.', 'CursorPathMismatch');
610
+ }`
611
+
612
+ /**
613
+ The full-list door's cursor decode, which unlike `cursorDecode` may run backward.
614
+
615
+ A `{t, n}` cursor names a position INSIDE a read window, and a window is re-read
616
+ from its own token — which forward paging already relies on to resume mid-window.
617
+ Backward is the same move in the other direction: re-read the window `before`
618
+ names and cut the page that ends at `n`, `[n - first, n)`. No new cursor shape, no
619
+ index, and no assumption forward paging does not already make.
620
+
621
+ What it cannot do is cross into an EARLIER window: DynamoDB's continuation chain
622
+ walks one way, so a window cannot name the one before it. `_upTo <= 0` with a
623
+ non-null window is that case, and it is the only one still refused.
624
+
625
+ Declares `_first` (the response's slicing needs it before `connectionPageResponse`
626
+ would have declared it, so that one omits it here).
627
+ */
628
+ let listCursorPreamble = `
629
+ const _first = ctx.args.first ?? 50;
630
+ let _window = null;
631
+ let _from = 0;
632
+ let _cursorPath = null;
633
+ let _backward = false;
634
+ let _upTo = -1;
635
+ if (ctx.args.before != null && ctx.args.before !== '') {
636
+ const _c = JSON.parse(util.base64Decode(ctx.args.before));
637
+ _window = (_c.t !== undefined ? _c.t : _c.token) ?? null;
638
+ _cursorPath = _c.p ?? 's';
639
+ _backward = true;
640
+ _upTo = _c.n !== undefined ? _c.n : 0;
641
+ _from = (_upTo - _first) > 0 ? (_upTo - _first) : 0;
642
+ } else if (ctx.args.after != null && ctx.args.after !== '') {
643
+ const _c = JSON.parse(util.base64Decode(ctx.args.after));
644
+ _window = (_c.t !== undefined ? _c.t : _c.token) ?? null;
645
+ _from = _c.n !== undefined ? _c.n + 1 : 0;
646
+ _cursorPath = _c.p ?? 's';
647
+ }`
648
+
649
+ /**
650
+ Cuts the requested page out of the returned window. Expects `items` (sorted, if the
651
+ door sorts) plus `_window` / `_from` from `cursorDecode`. `pathExpr` is the JS
652
+ expression naming which read minted these cursors, for a door that has two.
653
+
654
+ `bidirectional` is the full-list door, whose page may have been cut backward: it
655
+ reads `_backward` / `_upTo` from `listCursorPreamble` and takes `_first` from
656
+ there rather than declaring its own.
657
+ */
658
+ let connectionPageResponse = (~pathExpr: option<string>=?, ~bidirectional: bool=false) => {
659
+ let tag = switch pathExpr {
660
+ | None => ""
661
+ | Some(e) => `, p: ${e}`
662
+ }
663
+ let firstDecl = bidirectional ? "" : "\n const _first = ctx.args.first ?? 50;"
664
+ let slice = bidirectional
665
+ ? `
666
+ const _rest = _backward ? items.slice(_from, _upTo) : items.slice(_from);
667
+ const _page = _backward ? _rest : _rest.slice(0, _first);
668
+ // A backward page was cut from ahead, so a next page provably exists — the one
669
+ // the caller came from — whatever this window's tail looks like.
670
+ const _more = _backward ? true : _rest.length > _first;`
671
+ : `
672
+ const _rest = items.slice(_from);
673
+ const _page = _rest.slice(0, _first);
674
+ const _more = _rest.length > _first;`
675
+ // Only what the door can actually serve. `!!ctx.args.after` said "a page
676
+ // precedes this one", which is a different claim: at a window boundary one does
677
+ // and this door cannot reach it, so the client drew a Prev that always errored.
678
+ let hasPrevious = bidirectional ? "_from > 0" : "!!ctx.args.after"
679
+ `${firstDecl}${slice}
680
+ const _next = ctx.result?.nextToken ?? null;
681
+ const _lastIndex = _page.length - 1;
682
+ // A row's cursor names its own position. The last row of a page that closes its
683
+ // window is the exception — no position follows it there, so it names the next
684
+ // window, or resuming from it answers blank.
685
+ const edges = _page.map((item, i) => ({
607
686
  node: item,
608
- cursor: util.base64Encode(JSON.stringify({ token: next, index: i })),
687
+ cursor: util.base64Encode(JSON.stringify(
688
+ (!_more && _next && i === _lastIndex)
689
+ ? { t: _next, n: -1${tag} }
690
+ : { t: _window, n: _from + i${tag} }
691
+ )),
609
692
  }));
610
- const boundary = next ? util.base64Encode(JSON.stringify({ token: next, index: -1 })) : null;
693
+ // A window the filter emptied leaves no row to cut a cursor from; the token is
694
+ // the window's, so a client can step past it rather than restart.
695
+ const _boundary = _next ? util.base64Encode(JSON.stringify({ t: _next, n: -1${tag} })) : null;
611
696
  return {
612
697
  edges,
613
698
  pageInfo: {
614
- hasNextPage: !!next,
615
- hasPreviousPage: !!ctx.args.after,
616
- startCursor: edges.length > 0 ? edges[0].cursor : boundary,
617
- endCursor: edges.length > 0 ? edges[edges.length - 1].cursor : boundary,
699
+ hasNextPage: _more || !!_next,
700
+ hasPreviousPage: ${hasPrevious},
701
+ startCursor: edges.length > 0 ? edges[0].cursor : _boundary,
702
+ endCursor: edges.length > 0 ? edges[edges.length - 1].cursor : _boundary,
618
703
  },
619
- };
704
+ };`
705
+ }
706
+
707
+ /**
708
+ The by-index door's response. Pages out of a read window exactly as
709
+ `listAllItemsConnection` does, and satisfies the `Connection!` the field has always
710
+ declared — returning `ctx.result` raw did not.
711
+ */
712
+ let indexConnectionResponseCode = `
713
+ export function response(ctx) {
714
+ if (ctx.error) util.error(ctx.error.message, ctx.error.type);
715
+ const items = ctx.result?.items ?? [];${cursorDecode(~args="ctx.args")}${connectionPageResponse()}
620
716
  }`
621
717
 
622
718
  /** Refuses backward paging, for the reason `listAllItemsConnection` gives: the
623
719
  cursor is DynamoDB's own continuation token, which only walks forward, so
624
- `last`/`before` cannot be honoured and handing back the forward page would answer
625
- a different question without saying so.
626
-
627
- The arguments stay declared one that came and went with the index's shape would
628
- make every client feature-detect — and the local backend refuses them with the
629
- same message, so the door reads the same either side of a deploy. */
720
+ `last`/`before` cannot be honoured, and handing back the forward page would answer
721
+ a different question without saying so. The arguments stay declared — one that
722
+ came and went with the index's shape would make every client feature-detect — and
723
+ the local backend refuses them with the same message. */
630
724
  let indexBackwardPagingGuard = `
631
725
  if (args.before != null || args.last != null) {
632
726
  util.error('Backward pagination (last/before) is not supported on by-index connections; use first/after.', 'UnsupportedPagination');
633
727
  }`
634
728
 
635
- /** Decodes the Relay `after` cursor back to the DynamoDB continuation token the
636
- response side encoded. Mirrors `listAllItemsConnection`'s request half. */
637
- let indexCursorPreamble = `
638
- let after = null;
639
- if (args.after != null && args.after !== '') {
640
- const parsed = JSON.parse(util.base64Decode(args.after));
641
- after = parsed.token ?? null;
642
- }`
729
+ /** Decodes the Relay `after` cursor back to the read window the response side
730
+ encoded, and sizes the window this read may examine. Mirrors
731
+ `listAllItemsConnection`'s request half. */
732
+ let indexCursorPreamble = `${cursorDecode(~args="args")}
733
+ const _first = args.first ?? 50;`
643
734
 
644
735
  // The arguments the by-index door declares, none of which is a column to match
645
736
  // on. `includeRetired` is a request to lift a restriction and the rest are
@@ -693,8 +784,8 @@ ${ownerFilterClause(~ownerField, ~elevatedGroups)}${retiredFilterClause(~retired
693
784
  operation: 'Query',
694
785
  query,
695
786
  index: '${index}',
696
- limit: (args.first ?? 50),
697
- nextToken: after,
787
+ limit: ${pageWindowBudget(~filtered="expression")},
788
+ nextToken: _window,
698
789
  scanIndexForward: (args.forward ?? true)
699
790
  };
700
791
  if (expression) {
@@ -756,8 +847,8 @@ ${ownerFilterClause(~ownerField, ~elevatedGroups)}${retiredFilterClause(~retired
756
847
  operation: 'Query',
757
848
  query,
758
849
  index: '${index}',
759
- limit: (args.first ?? 50),
760
- nextToken: after,
850
+ limit: ${pageWindowBudget(~filtered="expression")},
851
+ nextToken: _window,
761
852
  scanIndexForward: (args.forward ?? true)
762
853
  };
763
854
  if (expression) {
@@ -789,48 +880,36 @@ ${resultResponseCode}
789
880
  // ---------------------------------------------------------------------------
790
881
 
791
882
  /**
792
- * Scan with optional `filter` arg: `{search?, searchPrefix?, ids?, <field>Eq?, <field>From?, <field>To?}`
793
- * and optional `orderBy: {field, direction}`.
794
- *
795
- * `search` → `contains(labelField, :v)` case-sensitive on DynamoDB. Callers that
796
- * need case-insensitive matching should project a lowercased label column
797
- * (future Phase 6.1 / external full-text search).
798
- * `searchPrefix` `begins_with(labelField, :v)` — case-sensitive. Scan-only here;
799
- * Phase 6 `@searchable` provisions a GSI to promote this to a query.
800
- * `ids` → FilterExpression `#id IN (:id0, :id1, …)`. Simple scan-based
801
- * path; BatchGetItem optimisation is deferred (open question 1).
802
- * `<field>Eq` FilterExpression `#<field> = :<field>Eq`, one per `~filterFields` entry.
803
- * `<field>From` → FilterExpression `#<field> >= :<field>From`, one per `~rangeFields` entry.
804
- * `<field>To` → FilterExpression `#<field> <= :<field>To`, one per `~rangeFields` entry.
805
- * `orderBy` JS-runtime sort over the returned page when `orderBy.field` is in
806
- * `~sortFields`. **Per-page only**, not globalDynamoDB Scan returns
807
- * items in indeterminate order and `ScanIndexForward` does not apply
808
- * to Scan. Index-routed Query (v1.5) lifts this caveat for indexed
809
- * sort fields; `@scanSort` on a non-indexed field is per-page even then.
810
- *
811
- * Empty-string and null filter values are treated as "no filter" — consistent with the
812
- * in-memory adapter so clients don't need to conditionally omit keys.
813
- */
883
+ Scan behind `filter: {search?, searchPrefix?, ids?, <field>Eq?, <field>From?,
884
+ <field>To?}` and `orderBy: {field, direction}`. `search` / `searchPrefix` become
885
+ `contains` / `begins_with` on `labelField` (case-sensitive — a case-insensitive
886
+ match wants a lowercased projected column); `ids` becomes `#id IN (…)`; the
887
+ per-field forms become `=` / `>=` / `<=`.
888
+
889
+ `orderBy` sorts in the JS runtime over the read window, not globally: Scan returns
890
+ items in indeterminate order and `ScanIndexForward` is Query-only. Empty and null
891
+ filter values mean "no filter", as they do in-memory.
892
+
893
+ With `ownerIndex` the door has **two** reads against the same data source, chosen
894
+ by whether the caller is exempt from owner scoping: a Query on the derived
895
+ `@owner` index for a scoped caller, the Scan above for everyone else. A user
896
+ `filter` still lands in a FilterExpression on top of the Query's key condition, so
897
+ a scoped caller searching their own rows can still get a short page but bounded
898
+ by their row count rather than the table's.
899
+ */
814
900
  let listAllItemsConnection = (
815
901
  ~labelField: string,
816
902
  ~filterFields: array<string>=[],
817
903
  ~rangeFields: array<string>=[],
818
904
  ~sortFields: array<string>=[],
819
- // When set, emit an always-on `attribute_exists(#<attr>)` FilterExpression clause
820
- // (ANDed with any client filters) so rows lacking that attribute never enter the
821
- // Connection. Used for read models whose physical DynamoDB table co-hosts internal
822
- // bookkeeping rows written outside the projection (e.g. the Plugins admin RM, whose
823
- // table also holds `deploy-schema:*` / `plugin-info:*` rows with no `name`). Those
824
- // rows would otherwise resolve `name`/`status`/`version` to null and violate the
825
- // non-null GraphQL connection schema, nulling the whole connection.
905
+ // An always-on `attribute_exists(#<attr>)` clause, for a read model whose table
906
+ // co-hosts bookkeeping rows written outside the projection (the Plugins admin RM's
907
+ // `deploy-schema:*` / `plugin-info:*` rows carry no `name`). Those rows resolve
908
+ // non-null fields to null and take the whole Connection with them.
826
909
  ~requireAttribute: option<string>=?,
827
- // The state's `@owner` field, when it declares one, plus the groups exempt from
828
- // scoping. Baked into the generated source because this resolver runs inside
829
- // AppSync with no Lambda in the path — there is nothing here that could read a
830
- // configuration value at request time, so the deploy is the only chance to
831
- // state it. Changing the elevated-group list therefore requires a redeploy,
832
- // which is worth knowing and is why it is a deployment-level setting rather
833
- // than a per-request one.
910
+ // The state's `@owner` field and the groups exempt from scoping. Baked in
911
+ // because no Lambda sits in this path to read a value at request time, so the
912
+ // elevated-group list changes only on redeploy.
834
913
  ~ownerField: option<string>=?,
835
914
  ~elevatedGroups: array<string>=[],
836
915
  // The state's `@retired` field, when it declares one. Baked in for the same
@@ -840,7 +919,14 @@ let listAllItemsConnection = (
840
919
  // The states that retire the row, for the state form of the annotation.
841
920
  // Absent is the boolean form, where the value is always `true`.
842
921
  ~retiredValues: option<array<string>>=?,
922
+ // The index `@owner` derives, and its sort key. Present turns the owner
923
+ // predicate from a post-read sieve into a key condition for a scoped caller.
924
+ ~ownerIndex: option<string>=?,
925
+ ~ownerIndexSortField: option<string>=?,
843
926
  ) => {
927
+ // The Query branch needs `ownerField` to key on; an index without one would
928
+ // have nothing to name in the key condition.
929
+ let ownerIndex = ownerField->Option.isSome ? ownerIndex : None
844
930
  let requireAttributeClause = switch requireAttribute {
845
931
  | Some(attr) => `
846
932
  names['#${attr}'] = '${attr}';
@@ -851,9 +937,11 @@ let listAllItemsConnection = (
851
937
  // it. The branch ORDER is the part that has to match: provider first, because
852
938
  // an IAM-signed service caller has no `sub` for a reason that has nothing to do
853
939
  // with being anonymous, and must not be refused as though it did.
854
- let ownerClause = switch ownerField {
855
- | None => ""
856
- | Some(field) =>
940
+ //
941
+ // Emitted in BOTH halves of the resolver when an owner index is in play: the
942
+ // response has to know which read minted the cursors it hands out, and that is
943
+ // the same question.
944
+ let ownerIdentityPreamble = {
857
945
  let elevatedLiteral = elevatedGroups->Array.map(g => `'${g}'`)->Array.join(", ")
858
946
  `
859
947
  // ── owner scoping (generated) ──
@@ -866,7 +954,16 @@ let listAllItemsConnection = (
866
954
  const _elevated = [${elevatedLiteral}];
867
955
  // No identity at all, or an identity with no \`sub\`, is the IAM service caller
868
956
  // the API also accepts — inside the trust boundary, and exempt.
869
- const _exempt = _sub == null || _groups.some(g => _elevated.indexOf(g) >= 0);
957
+ const _exempt = _sub == null || _groups.some(g => _elevated.indexOf(g) >= 0);`
958
+ }
959
+ let ownerClause = switch (ownerField, ownerIndex) {
960
+ | (None, _) => ""
961
+ // With an index the predicate is the Query's key condition, so nothing is
962
+ // pushed into the filter — and nothing may be: an expressionName the filter
963
+ // never references is a ValidationException, not a harmless extra.
964
+ | (Some(_), Some(_)) => ownerIdentityPreamble
965
+ | (Some(field), None) =>
966
+ `${ownerIdentityPreamble}
870
967
  if (!_exempt) {
871
968
  names['#owner'] = '${field}';
872
969
  values[':owner'] = util.dynamodb.toDynamoDB(_sub);
@@ -874,25 +971,15 @@ let listAllItemsConnection = (
874
971
  }`
875
972
  }
876
973
  // ── retirement narrowing (generated) ──
877
- // Reuses `_exempt` when the owner clause already computed it, and computes its
878
- // own when it did not the two clauses are independently optional and either
879
- // may be the only one present.
880
- //
881
- // `includeRetired` IS read from ctx.args, unlike the owner predicate, and the
882
- // difference is deliberate: this argument does not say which rows the caller
883
- // wants, it asks to lift a restriction, and it is honoured only inside the
884
- // `_exempt` branch. A non-exempt caller passing it changes nothing.
974
+ // Reuses `_exempt` when the owner clause computed it; either clause may be the
975
+ // only one present. `includeRetired` IS read from ctx.args, unlike the owner
976
+ // predicate it asks to lift a restriction rather than naming rows, and is
977
+ // honoured only inside `_exempt`.
885
978
  //
886
- // `attribute_not_exists OR = false` rather than `<> true`: a row written before
887
- // the annotation existed carries no such attribute, and DynamoDB's `<>` does
888
- // not match a missing one the whole view would come back empty on the day
889
- // the annotation lands.
890
- //
891
- // The state form compares `<>` against the retiring state instead, under the
892
- // same `attribute_not_exists` guard and for the same reason. An equality
893
- // predicate over an enum-valued attribute indexes exactly as a boolean one
894
- // does, so the warning about an unindexed retirement field carries over
895
- // unchanged.
979
+ // `attribute_not_exists OR = false` rather than `<> true`, because `<>` does not
980
+ // match a missing attribute and the view would empty out the day the annotation
981
+ // lands. The state form compares `<>` against the retiring state under the same
982
+ // guard.
896
983
  let retiredClause = switch retiredField {
897
984
  | None => ""
898
985
  | Some(field) =>
@@ -962,25 +1049,28 @@ ${switch retiredValues {
962
1049
  ->Array.join("")
963
1050
  let sortFieldsLiteral =
964
1051
  sortFields->Array.map(f => `'${f}'`)->Array.join(", ")
1052
+ // When the Query branch already ordered on the index's own sort key, the page
1053
+ // arrives globally ordered and re-sorting it here is the one way to break that
1054
+ // order — a sort over a page is not a sort over the caller's rows.
1055
+ let sortGuard = switch (ownerIndex, ownerIndexSortField) {
1056
+ | (Some(_), Some(_)) => "!_indexOrdered && "
1057
+ | _ => ""
1058
+ }
965
1059
  let sortBlock = if sortFields->Array.length == 0 {
966
1060
  ""
967
1061
  } else {
968
- // APPSYNC_JS 1.0.0 forbids: Array.prototype.sort(comparator), arrow/function
969
- // expressions passed to sort, for/while loops, recursion, and ++/--. So we
970
- // can't run a comparator-driven sort and we can't write our own loop. Use a
971
- // schwartzian transform: encode each item as `<sortKey>\x01<json>`, run the
972
- // no-comparator default sort (lexicographic), reverse for DESC, and decode.
973
- // Numeric fields get zero-padded so lex order matches numeric order for
974
- // non-negative values (typical for IDs, counts, timestamps). Negatives sort
975
- // lexicographically — acceptable since DynamoDB sort keys are rarely signed
976
- // numbers. Nulls split out and append to the end regardless of direction.
1062
+ // APPSYNC_JS 1.0.0 forbids comparator sorts, loops, recursion and ++/--, so
1063
+ // this is a schwartzian transform: encode each item as `<sortKey>\x01<json>`,
1064
+ // default-sort lexicographically, reverse for DESC, decode. Numbers are
1065
+ // zero-padded so lex order matches numeric order for non-negative values;
1066
+ // nulls split out and append to the end either way.
977
1067
  `
978
1068
  // Per-page sort (Scan returns items in indeterminate order; ScanIndexForward
979
1069
  // does not apply to Scan). Global ordering across pages requires v1.5 index
980
1070
  // promotion; @scanSort is per-page even then.
981
1071
  const orderBy = ctx.args.orderBy;
982
1072
  const sortFields = [${sortFieldsLiteral}];
983
- if (orderBy && orderBy.field && sortFields.indexOf(orderBy.field) >= 0) {
1073
+ if (${sortGuard}orderBy && orderBy.field && sortFields.indexOf(orderBy.field) >= 0) {
984
1074
  const field = orderBy.field;
985
1075
  const nulls = items.filter(it => it[field] === null || it[field] === undefined);
986
1076
  const nonNulls = items.filter(it => it[field] !== null && it[field] !== undefined);
@@ -996,13 +1086,67 @@ ${switch retiredValues {
996
1086
  items = encoded.map(e => JSON.parse(e.split('\\x01')[1])).concat(nulls);
997
1087
  }`
998
1088
  }
1089
+ // Did the Query branch order this page itself? Answered the same way in both
1090
+ // halves, because both need it: the request to set `scanIndexForward`, the
1091
+ // response to leave an already-ordered page alone.
1092
+ let indexOrderedExpr = switch (ownerIndex, ownerIndexSortField) {
1093
+ | (Some(_), Some(sf)) =>
1094
+ `!_exempt && !!(ctx.args.orderBy && ctx.args.orderBy.field === '${sf}')`
1095
+ | _ => "false"
1096
+ }
1097
+ // The two reads, chosen by the same test that used to choose a predicate.
1098
+ // Both target the one data source the resolver is attached to, so this is a
1099
+ // branch inside one resolver — no second field, no second data source, no
1100
+ // client change.
1101
+ let requestOperation = switch (ownerField, ownerIndex) {
1102
+ | (Some(field), Some(index)) => `
1103
+ const _indexOrdered = ${indexOrderedExpr};
1104
+ const req = _exempt
1105
+ ? {
1106
+ operation: 'Scan',
1107
+ limit: ${listPageWindowBudget},
1108
+ nextToken: _window,
1109
+ }
1110
+ : {
1111
+ operation: 'Query',
1112
+ index: '${index}',
1113
+ query: {
1114
+ expression: '#owner = :owner',
1115
+ expressionNames: { '#owner': '${field}' },
1116
+ expressionValues: { ':owner': util.dynamodb.toDynamoDB(_sub) },
1117
+ },
1118
+ limit: ${listPageWindowBudget},
1119
+ nextToken: _window,
1120
+ scanIndexForward: !(_indexOrdered && ctx.args.orderBy.direction === 'DESC'),
1121
+ };`
1122
+ | _ => `
1123
+ const req = {
1124
+ operation: 'Scan',
1125
+ limit: ${listPageWindowBudget},
1126
+ nextToken: _window,
1127
+ };`
1128
+ }
1129
+ // Only a door with two reads tests the tag, and only that door stamps one.
1130
+ let requestPathGuard = ownerIndex->Option.isSome ? cursorPathGuard : ""
1131
+ let responsePathPreamble = switch ownerIndex {
1132
+ | None => ""
1133
+ | Some(_) => `${ownerIdentityPreamble}
1134
+ const _path = _exempt ? 's' : 'q';
1135
+ const _indexOrdered = ${indexOrderedExpr};`
1136
+ }
1137
+ let pageResponse = switch ownerIndex {
1138
+ | None => connectionPageResponse(~bidirectional=true)
1139
+ | Some(_) => connectionPageResponse(~pathExpr="_path", ~bidirectional=true)
1140
+ }
999
1141
  `${importUtil}
1000
1142
  export function request(ctx) {
1001
- // Scan cannot page backward (ScanIndexForward is Query-only). Fail loud rather than
1002
- // silently returning the forward page. The ordered {single}Items connection
1003
- // (queryItemsWithSortConditions) supports last/before direct backward callers there.
1004
- if (ctx.args.before != null || ctx.args.last != null) {
1005
- util.error('Backward pagination (last/before) is not supported on full-list connections; use first/after.', 'UnsupportedPagination');
1143
+ // 'before' IS served — the page is cut backward out of the window the cursor
1144
+ // names. 'last' is not: "the last N rows of the list" needs the end of the
1145
+ // list, which a forward-only Scan cursor cannot reach. The ordered
1146
+ // {single}Items connection (queryItemsWithSortConditions) has a real keyset
1147
+ // cursor and honours both direct callers who need 'last' there.
1148
+ if (ctx.args.last != null) {
1149
+ util.error('last is not supported on full-list connections; page backward with first and before.', 'UnsupportedPagination');
1006
1150
  }
1007
1151
  const filter = ctx.args.filter ?? {};
1008
1152
  const names = {};
@@ -1027,18 +1171,14 @@ export function request(ctx) {
1027
1171
  });
1028
1172
  parts.push('#id IN (' + placeholders.join(', ') + ')');
1029
1173
  }${filterClauses}${rangeClauses}${requireAttributeClause}${ownerClause}${retiredClause}
1030
- // The cursor is base64(JSON({ token, index })); decode the after arg back to the raw
1031
- // DynamoDB continuation token the response side emitted (Fix 1 round-trip).
1032
- let after = null;
1033
- if (ctx.args.after != null && ctx.args.after !== '') {
1034
- const parsed = JSON.parse(util.base64Decode(ctx.args.after));
1035
- after = parsed.token ?? null;
1036
- }
1037
- const req = {
1038
- operation: 'Scan',
1039
- limit: (ctx.args.first ?? 50),
1040
- nextToken: after,
1041
- };
1174
+ ${listCursorPreamble}${requestPathGuard}
1175
+ // The one page a cursor cannot reach: it begins in an earlier window, and a
1176
+ // continuation token cannot name the one before it. Refused by itself rather
1177
+ // than folded into the 'last' guard, because the two are different limits and a
1178
+ // caller can act on this one (page forward from the start).
1179
+ if (_backward && _upTo <= 0 && _window !== null) {
1180
+ util.error('The previous page begins in an earlier read window, which this cursor cannot name; page forward from the start.', 'UnsupportedPagination');
1181
+ }${requestOperation}
1042
1182
  if (parts.length > 0) {
1043
1183
  req.filter = {
1044
1184
  expression: parts.join(' AND '),
@@ -1050,30 +1190,7 @@ export function request(ctx) {
1050
1190
  }
1051
1191
  export function response(ctx) {
1052
1192
  if (ctx.error) util.error(ctx.error.message, ctx.error.type);
1053
- let items = ctx.result?.items ?? [];${sortBlock}
1054
- // One Scan continuation token per page; encode it (with the item's page index for a
1055
- // unique, opaque Relay cursor). The request side decodes .token back to the raw
1056
- // DynamoDB nextToken (Fix 1).
1057
- const next = ctx.result?.nextToken ?? null;
1058
- const edges = items.map((item, i) => ({
1059
- node: item,
1060
- cursor: util.base64Encode(JSON.stringify({ token: next, index: i })),
1061
- }));
1062
- // A filtered/1MB-capped page can be empty or short while next is still set (limit
1063
- // caps rows scanned, not returned). The token is page-level, so synthesise a
1064
- // boundary cursor from it alone so a client can resume past a fully-filtered-out
1065
- // page instead of restarting from page 1 (Fix 3). The request only reads .token,
1066
- // so index -1 is inert on resume.
1067
- const boundary = next ? util.base64Encode(JSON.stringify({ token: next, index: -1 })) : null;
1068
- return {
1069
- edges,
1070
- pageInfo: {
1071
- hasNextPage: !!next,
1072
- hasPreviousPage: !!ctx.args.after,
1073
- startCursor: edges.length > 0 ? edges[0].cursor : boundary,
1074
- endCursor: edges.length > 0 ? edges[edges.length - 1].cursor : boundary,
1075
- },
1076
- };
1193
+ let items = ctx.result?.items ?? [];${responsePathPreamble}${sortBlock}${listCursorPreamble}${pageResponse}
1077
1194
  }
1078
1195
  `->Pulumi.Input.make
1079
1196
  }
@@ -1085,14 +1202,10 @@ export function response(ctx) {
1085
1202
  /**
1086
1203
  The response of a cross-table field (`@resolves`) over a Query-shaped read.
1087
1204
 
1088
- The narrowing is the TARGET's, not the declaring view's: the row comes out of the
1089
- target's table, so whether this caller may see it is the target's question asked
1090
- here with the same `_owns` / `_live` guards every by-key door on that table asks.
1091
-
1092
- A nested field takes no `includeRetired` argument, so `_wantsRetired` is never
1093
- true and a retired row never travels through one. A reference that must keep
1094
- reading as a name after the archive took it is what `{list}Refs` + `@namedWhenRetired`
1095
- answers.
1205
+ The narrowing is the TARGET's, not the declaring view's the row is the target's,
1206
+ so it answers with the same `_owns` / `_live` guards its by-key doors use. A
1207
+ nested field takes no `includeRetired`, so a retired row never travels through
1208
+ one; `{list}Refs` + `@namedWhenRetired` is that door.
1096
1209
  */
1097
1210
  let resolvedFieldResponse = (
1098
1211
  ~multi: bool,
@@ -1303,14 +1416,10 @@ ${response}
1303
1416
 
1304
1417
  /** `@resolvesMany` — the parent's id array batch-read from the target's table.
1305
1418
 
1306
- Returns a plain string: the table name is interpolated by the adapter via
1307
- `Pulumi.Output.apply`, because BatchGetItem's `tables` map keys on the literal
1308
- name.
1309
-
1310
- Same shape as `batchGetItemsByIds`, and narrowed by the same guards — the
1311
- target's, since the rows are the target's. Missing ids come back as nulls in
1312
- the result array (BatchGetItem preserves index correspondence) and are
1313
- dropped, so the field is shorter rather than null-holed. */
1419
+ A plain string, because BatchGetItem's `tables` map keys on the literal name,
1420
+ which the adapter interpolates via `Pulumi.Output.apply`. Same shape and
1421
+ guards as `batchGetItemsByIds`; missing ids come back null and are dropped, so
1422
+ the field is shorter rather than null-holed. */
1314
1423
  let resolveIds = (
1315
1424
  ~idsField: string,
1316
1425
  ~sortField: option<string>,
@@ -1357,13 +1466,10 @@ export function response(ctx) {
1357
1466
  `
1358
1467
  }
1359
1468
 
1360
- /** Batched-by-ids — top-level Query resolver reading `ctx.args.ids: [String!]!`
1361
- and returning the matching items via a single BatchGetItem. Missing ids drop
1362
- out (BatchGetItem does not preserve cardinality); empty input short-circuits
1363
- to an empty result without hitting DDB. Table name is interpolated at deploy
1364
- time, since BatchGetItem's `tables` map keys on the literal table name.
1365
- Single-key tables only — composite-key BatchGetItem needs both pk + sk per
1366
- key entry, which this template doesn't construct. */
1469
+ /** Batched-by-ids — reads `ctx.args.ids: [String!]!` through one BatchGetItem.
1470
+ Missing ids drop out; empty input short-circuits without hitting DDB. The
1471
+ table name is interpolated at deploy time, since BatchGetItem's `tables` map
1472
+ keys on the literal. Single-key tables only. */
1367
1473
  let batchGetItemsByIds = (
1368
1474
  ~ownerField: option<string>=?,
1369
1475
  ~retiredField: option<string>=?,
@@ -1387,12 +1493,9 @@ export function request(ctx) {
1387
1493
  }
1388
1494
  export function response(ctx) {
1389
1495
  if (ctx.error) util.error(ctx.error.message, ctx.error.type);
1390
- // BatchGetItem returns null in the result array for keys that don't exist
1391
- // in the table, preserving index correspondence with the input. The SDL
1392
- // returns this field as \`[T!]!\` (non-null element list), so any single
1393
- // missing id makes the entire field fail with "Cannot return null for
1394
- // non-nullable type" and the caller sees data=null. Filter the nulls so
1395
- // the field returns just the items that were found.
1496
+ // BatchGetItem returns null for keys that don't exist, preserving index
1497
+ // correspondence. The SDL declares \`[T!]!\`, so one missing id would null the
1498
+ // whole field drop them and return what was found.
1396
1499
  // The owner and retirement guards the list pushes into a FilterExpression,
1397
1500
  // applied after the read because BatchGetItem has none to push into. A row the
1398
1501
  // caller does not own is dropped rather than refused, for the reason the
@@ -1416,14 +1519,11 @@ export function response(ctx) {
1416
1519
  /** The reference door — `{list}Refs(ids)`: what a caller holding a pointer to a
1417
1520
  row may learn about it, and nothing else.
1418
1521
 
1419
- The same BatchGetItem as `batchGetItemsByIds`, projected in the response to
1420
- `{id, label, retired, retiredState}`. The projection is the type's a caller
1421
- cannot ask for a price here because the SDL type has none — so the response
1422
- only has to *build* the three fields, never decide which to withhold.
1423
-
1424
- `namedWhenRetired` is what a retired row turns on: false drops it, exactly as
1425
- every other door does; true lets it through with the state that withdrew it.
1426
- The owner rule is applied either way and is not what the annotation lifts. */
1522
+ The same BatchGetItem as `batchGetItemsByIds`, projected to
1523
+ `{id, label, retired, retiredState}` by the SDL type, so the response builds
1524
+ three fields rather than deciding what to withhold. `namedWhenRetired` decides
1525
+ a retired row: false drops it, true names it. The owner rule applies either
1526
+ way — that is not what the annotation lifts. */
1427
1527
  let refsByIds = (
1428
1528
  ~labelField: string,
1429
1529
  ~retiredField: option<string>,