@reventlessdev/rescript-pulumi-aws 3.0.0-alpha.2 → 3.0.0-alpha.4

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,125 @@ export function request(ctx) {
585
547
  ${resultResponseCode}
586
548
  `->Pulumi.Input.make
587
549
 
550
+ // ---------------------------------------------------------------------------
551
+ // Paging a filtered read
552
+ // ---------------------------------------------------------------------------
553
+
554
+ /**
555
+ Rows a read may EXAMINE per page.
556
+
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)`
565
+
588
566
  /**
589
- The by-index door's response.
567
+ Decodes `after` into the window it names (`t`, the token opening it) and the row's
568
+ index among that window's matches (`n`). Pre-window cursors carried
569
+ `{token, index}` naming the window that follows — position -1 of it.
570
+
571
+ `p` is the one-character tag naming which read the window belongs to (`s` Scan,
572
+ `q` the owner-index Query). Absent reads as `s`: every cursor minted before the
573
+ tag existed came off a Scan. Only a door with more than one read tests it — see
574
+ `cursorPathGuard`.
575
+ */
576
+ let cursorDecode = (~args: string) => `
577
+ let _window = null;
578
+ let _from = 0;
579
+ let _cursorPath = null;
580
+ if (${args}.after != null && ${args}.after !== '') {
581
+ const _c = JSON.parse(util.base64Decode(${args}.after));
582
+ _window = (_c.t !== undefined ? _c.t : _c.token) ?? null;
583
+ _from = _c.n !== undefined ? _c.n + 1 : 0;
584
+ _cursorPath = _c.p ?? 's';
585
+ }`
590
586
 
591
- Cursors are the DynamoDB continuation token carrying the row's position in the
592
- page, exactly as `listAllItemsConnection` builds them the 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.
587
+ /**
588
+ Refuses a cursor minted on this door's other read. The two branches are selectable
589
+ by the SAME caller across requests an active-role switch mid-pagination flips
590
+ `_exempt` and a `nextToken` continues the operation that issued it, so replaying
591
+ one on the other branch answers a different question without saying so.
596
592
 
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.
593
+ Expects `_cursorPath` from `cursorDecode` and `_exempt` from the owner preamble.
600
594
  */
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) => ({
595
+ let cursorPathGuard = `
596
+ if (_cursorPath !== null && _cursorPath !== (_exempt ? 's' : 'q')) {
597
+ util.error('This cursor belongs to a different read of this list; restart from the first page.', 'CursorPathMismatch');
598
+ }`
599
+
600
+ /**
601
+ Cuts the requested page out of the returned window. Expects `items` (sorted, if the
602
+ door sorts) plus `_window` / `_from` from `cursorDecode`. `pathExpr` is the JS
603
+ expression naming which read minted these cursors, for a door that has two.
604
+ */
605
+ let connectionPageResponse = (~pathExpr: option<string>=?) => {
606
+ let tag = switch pathExpr {
607
+ | None => ""
608
+ | Some(e) => `, p: ${e}`
609
+ }
610
+ `
611
+ const _first = ctx.args.first ?? 50;
612
+ const _rest = items.slice(_from);
613
+ const _page = _rest.slice(0, _first);
614
+ const _more = _rest.length > _first;
615
+ const _next = ctx.result?.nextToken ?? null;
616
+ const _lastIndex = _page.length - 1;
617
+ // A row's cursor names its own position. The last row of a page that closes its
618
+ // window is the exception — no position follows it there, so it names the next
619
+ // window, or resuming from it answers blank.
620
+ const edges = _page.map((item, i) => ({
607
621
  node: item,
608
- cursor: util.base64Encode(JSON.stringify({ token: next, index: i })),
622
+ cursor: util.base64Encode(JSON.stringify(
623
+ (!_more && _next && i === _lastIndex)
624
+ ? { t: _next, n: -1${tag} }
625
+ : { t: _window, n: _from + i${tag} }
626
+ )),
609
627
  }));
610
- const boundary = next ? util.base64Encode(JSON.stringify({ token: next, index: -1 })) : null;
628
+ // A window the filter emptied leaves no row to cut a cursor from; the token is
629
+ // the window's, so a client can step past it rather than restart.
630
+ const _boundary = _next ? util.base64Encode(JSON.stringify({ t: _next, n: -1${tag} })) : null;
611
631
  return {
612
632
  edges,
613
633
  pageInfo: {
614
- hasNextPage: !!next,
634
+ hasNextPage: _more || !!_next,
615
635
  hasPreviousPage: !!ctx.args.after,
616
- startCursor: edges.length > 0 ? edges[0].cursor : boundary,
617
- endCursor: edges.length > 0 ? edges[edges.length - 1].cursor : boundary,
636
+ startCursor: edges.length > 0 ? edges[0].cursor : _boundary,
637
+ endCursor: edges.length > 0 ? edges[edges.length - 1].cursor : _boundary,
618
638
  },
619
- };
639
+ };`
640
+ }
641
+
642
+ /**
643
+ The by-index door's response. Pages out of a read window exactly as
644
+ `listAllItemsConnection` does, and satisfies the `Connection!` the field has always
645
+ declared — returning `ctx.result` raw did not.
646
+ */
647
+ let indexConnectionResponseCode = `
648
+ export function response(ctx) {
649
+ if (ctx.error) util.error(ctx.error.message, ctx.error.type);
650
+ const items = ctx.result?.items ?? [];${cursorDecode(~args="ctx.args")}${connectionPageResponse()}
620
651
  }`
621
652
 
622
653
  /** Refuses backward paging, for the reason `listAllItemsConnection` gives: the
623
654
  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. */
655
+ `last`/`before` cannot be honoured, and handing back the forward page would answer
656
+ a different question without saying so. The arguments stay declared — one that
657
+ came and went with the index's shape would make every client feature-detect — and
658
+ the local backend refuses them with the same message. */
630
659
  let indexBackwardPagingGuard = `
631
660
  if (args.before != null || args.last != null) {
632
661
  util.error('Backward pagination (last/before) is not supported on by-index connections; use first/after.', 'UnsupportedPagination');
633
662
  }`
634
663
 
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
- }`
664
+ /** Decodes the Relay `after` cursor back to the read window the response side
665
+ encoded, and sizes the window this read may examine. Mirrors
666
+ `listAllItemsConnection`'s request half. */
667
+ let indexCursorPreamble = `${cursorDecode(~args="args")}
668
+ const _first = args.first ?? 50;`
643
669
 
644
670
  // The arguments the by-index door declares, none of which is a column to match
645
671
  // on. `includeRetired` is a request to lift a restriction and the rest are
@@ -693,8 +719,8 @@ ${ownerFilterClause(~ownerField, ~elevatedGroups)}${retiredFilterClause(~retired
693
719
  operation: 'Query',
694
720
  query,
695
721
  index: '${index}',
696
- limit: (args.first ?? 50),
697
- nextToken: after,
722
+ limit: ${pageWindowBudget(~filtered="expression")},
723
+ nextToken: _window,
698
724
  scanIndexForward: (args.forward ?? true)
699
725
  };
700
726
  if (expression) {
@@ -756,8 +782,8 @@ ${ownerFilterClause(~ownerField, ~elevatedGroups)}${retiredFilterClause(~retired
756
782
  operation: 'Query',
757
783
  query,
758
784
  index: '${index}',
759
- limit: (args.first ?? 50),
760
- nextToken: after,
785
+ limit: ${pageWindowBudget(~filtered="expression")},
786
+ nextToken: _window,
761
787
  scanIndexForward: (args.forward ?? true)
762
788
  };
763
789
  if (expression) {
@@ -789,48 +815,36 @@ ${resultResponseCode}
789
815
  // ---------------------------------------------------------------------------
790
816
 
791
817
  /**
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
- */
818
+ Scan behind `filter: {search?, searchPrefix?, ids?, <field>Eq?, <field>From?,
819
+ <field>To?}` and `orderBy: {field, direction}`. `search` / `searchPrefix` become
820
+ `contains` / `begins_with` on `labelField` (case-sensitive — a case-insensitive
821
+ match wants a lowercased projected column); `ids` becomes `#id IN (…)`; the
822
+ per-field forms become `=` / `>=` / `<=`.
823
+
824
+ `orderBy` sorts in the JS runtime over the read window, not globally: Scan returns
825
+ items in indeterminate order and `ScanIndexForward` is Query-only. Empty and null
826
+ filter values mean "no filter", as they do in-memory.
827
+
828
+ With `ownerIndex` the door has **two** reads against the same data source, chosen
829
+ by whether the caller is exempt from owner scoping: a Query on the derived
830
+ `@owner` index for a scoped caller, the Scan above for everyone else. A user
831
+ `filter` still lands in a FilterExpression on top of the Query's key condition, so
832
+ a scoped caller searching their own rows can still get a short page but bounded
833
+ by their row count rather than the table's.
834
+ */
814
835
  let listAllItemsConnection = (
815
836
  ~labelField: string,
816
837
  ~filterFields: array<string>=[],
817
838
  ~rangeFields: array<string>=[],
818
839
  ~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.
840
+ // An always-on `attribute_exists(#<attr>)` clause, for a read model whose table
841
+ // co-hosts bookkeeping rows written outside the projection (the Plugins admin RM's
842
+ // `deploy-schema:*` / `plugin-info:*` rows carry no `name`). Those rows resolve
843
+ // non-null fields to null and take the whole Connection with them.
826
844
  ~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.
845
+ // The state's `@owner` field and the groups exempt from scoping. Baked in
846
+ // because no Lambda sits in this path to read a value at request time, so the
847
+ // elevated-group list changes only on redeploy.
834
848
  ~ownerField: option<string>=?,
835
849
  ~elevatedGroups: array<string>=[],
836
850
  // The state's `@retired` field, when it declares one. Baked in for the same
@@ -840,7 +854,14 @@ let listAllItemsConnection = (
840
854
  // The states that retire the row, for the state form of the annotation.
841
855
  // Absent is the boolean form, where the value is always `true`.
842
856
  ~retiredValues: option<array<string>>=?,
857
+ // The index `@owner` derives, and its sort key. Present turns the owner
858
+ // predicate from a post-read sieve into a key condition for a scoped caller.
859
+ ~ownerIndex: option<string>=?,
860
+ ~ownerIndexSortField: option<string>=?,
843
861
  ) => {
862
+ // The Query branch needs `ownerField` to key on; an index without one would
863
+ // have nothing to name in the key condition.
864
+ let ownerIndex = ownerField->Option.isSome ? ownerIndex : None
844
865
  let requireAttributeClause = switch requireAttribute {
845
866
  | Some(attr) => `
846
867
  names['#${attr}'] = '${attr}';
@@ -851,9 +872,11 @@ let listAllItemsConnection = (
851
872
  // it. The branch ORDER is the part that has to match: provider first, because
852
873
  // an IAM-signed service caller has no `sub` for a reason that has nothing to do
853
874
  // with being anonymous, and must not be refused as though it did.
854
- let ownerClause = switch ownerField {
855
- | None => ""
856
- | Some(field) =>
875
+ //
876
+ // Emitted in BOTH halves of the resolver when an owner index is in play: the
877
+ // response has to know which read minted the cursors it hands out, and that is
878
+ // the same question.
879
+ let ownerIdentityPreamble = {
857
880
  let elevatedLiteral = elevatedGroups->Array.map(g => `'${g}'`)->Array.join(", ")
858
881
  `
859
882
  // ── owner scoping (generated) ──
@@ -866,7 +889,16 @@ let listAllItemsConnection = (
866
889
  const _elevated = [${elevatedLiteral}];
867
890
  // No identity at all, or an identity with no \`sub\`, is the IAM service caller
868
891
  // the API also accepts — inside the trust boundary, and exempt.
869
- const _exempt = _sub == null || _groups.some(g => _elevated.indexOf(g) >= 0);
892
+ const _exempt = _sub == null || _groups.some(g => _elevated.indexOf(g) >= 0);`
893
+ }
894
+ let ownerClause = switch (ownerField, ownerIndex) {
895
+ | (None, _) => ""
896
+ // With an index the predicate is the Query's key condition, so nothing is
897
+ // pushed into the filter — and nothing may be: an expressionName the filter
898
+ // never references is a ValidationException, not a harmless extra.
899
+ | (Some(_), Some(_)) => ownerIdentityPreamble
900
+ | (Some(field), None) =>
901
+ `${ownerIdentityPreamble}
870
902
  if (!_exempt) {
871
903
  names['#owner'] = '${field}';
872
904
  values[':owner'] = util.dynamodb.toDynamoDB(_sub);
@@ -874,25 +906,15 @@ let listAllItemsConnection = (
874
906
  }`
875
907
  }
876
908
  // ── 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.
909
+ // Reuses `_exempt` when the owner clause computed it; either clause may be the
910
+ // only one present. `includeRetired` IS read from ctx.args, unlike the owner
911
+ // predicate it asks to lift a restriction rather than naming rows, and is
912
+ // honoured only inside `_exempt`.
885
913
  //
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.
914
+ // `attribute_not_exists OR = false` rather than `<> true`, because `<>` does not
915
+ // match a missing attribute and the view would empty out the day the annotation
916
+ // lands. The state form compares `<>` against the retiring state under the same
917
+ // guard.
896
918
  let retiredClause = switch retiredField {
897
919
  | None => ""
898
920
  | Some(field) =>
@@ -962,25 +984,28 @@ ${switch retiredValues {
962
984
  ->Array.join("")
963
985
  let sortFieldsLiteral =
964
986
  sortFields->Array.map(f => `'${f}'`)->Array.join(", ")
987
+ // When the Query branch already ordered on the index's own sort key, the page
988
+ // arrives globally ordered and re-sorting it here is the one way to break that
989
+ // order — a sort over a page is not a sort over the caller's rows.
990
+ let sortGuard = switch (ownerIndex, ownerIndexSortField) {
991
+ | (Some(_), Some(_)) => "!_indexOrdered && "
992
+ | _ => ""
993
+ }
965
994
  let sortBlock = if sortFields->Array.length == 0 {
966
995
  ""
967
996
  } 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.
997
+ // APPSYNC_JS 1.0.0 forbids comparator sorts, loops, recursion and ++/--, so
998
+ // this is a schwartzian transform: encode each item as `<sortKey>\x01<json>`,
999
+ // default-sort lexicographically, reverse for DESC, decode. Numbers are
1000
+ // zero-padded so lex order matches numeric order for non-negative values;
1001
+ // nulls split out and append to the end either way.
977
1002
  `
978
1003
  // Per-page sort (Scan returns items in indeterminate order; ScanIndexForward
979
1004
  // does not apply to Scan). Global ordering across pages requires v1.5 index
980
1005
  // promotion; @scanSort is per-page even then.
981
1006
  const orderBy = ctx.args.orderBy;
982
1007
  const sortFields = [${sortFieldsLiteral}];
983
- if (orderBy && orderBy.field && sortFields.indexOf(orderBy.field) >= 0) {
1008
+ if (${sortGuard}orderBy && orderBy.field && sortFields.indexOf(orderBy.field) >= 0) {
984
1009
  const field = orderBy.field;
985
1010
  const nulls = items.filter(it => it[field] === null || it[field] === undefined);
986
1011
  const nonNulls = items.filter(it => it[field] !== null && it[field] !== undefined);
@@ -996,6 +1021,58 @@ ${switch retiredValues {
996
1021
  items = encoded.map(e => JSON.parse(e.split('\\x01')[1])).concat(nulls);
997
1022
  }`
998
1023
  }
1024
+ // Did the Query branch order this page itself? Answered the same way in both
1025
+ // halves, because both need it: the request to set `scanIndexForward`, the
1026
+ // response to leave an already-ordered page alone.
1027
+ let indexOrderedExpr = switch (ownerIndex, ownerIndexSortField) {
1028
+ | (Some(_), Some(sf)) =>
1029
+ `!_exempt && !!(ctx.args.orderBy && ctx.args.orderBy.field === '${sf}')`
1030
+ | _ => "false"
1031
+ }
1032
+ // The two reads, chosen by the same test that used to choose a predicate.
1033
+ // Both target the one data source the resolver is attached to, so this is a
1034
+ // branch inside one resolver — no second field, no second data source, no
1035
+ // client change.
1036
+ let requestOperation = switch (ownerField, ownerIndex) {
1037
+ | (Some(field), Some(index)) => `
1038
+ const _indexOrdered = ${indexOrderedExpr};
1039
+ const req = _exempt
1040
+ ? {
1041
+ operation: 'Scan',
1042
+ limit: ${pageWindowBudget(~filtered="parts.length > 0")},
1043
+ nextToken: _window,
1044
+ }
1045
+ : {
1046
+ operation: 'Query',
1047
+ index: '${index}',
1048
+ query: {
1049
+ expression: '#owner = :owner',
1050
+ expressionNames: { '#owner': '${field}' },
1051
+ expressionValues: { ':owner': util.dynamodb.toDynamoDB(_sub) },
1052
+ },
1053
+ limit: ${pageWindowBudget(~filtered="parts.length > 0")},
1054
+ nextToken: _window,
1055
+ scanIndexForward: !(_indexOrdered && ctx.args.orderBy.direction === 'DESC'),
1056
+ };`
1057
+ | _ => `
1058
+ const req = {
1059
+ operation: 'Scan',
1060
+ limit: ${pageWindowBudget(~filtered="parts.length > 0")},
1061
+ nextToken: _window,
1062
+ };`
1063
+ }
1064
+ // Only a door with two reads tests the tag, and only that door stamps one.
1065
+ let requestPathGuard = ownerIndex->Option.isSome ? cursorPathGuard : ""
1066
+ let responsePathPreamble = switch ownerIndex {
1067
+ | None => ""
1068
+ | Some(_) => `${ownerIdentityPreamble}
1069
+ const _path = _exempt ? 's' : 'q';
1070
+ const _indexOrdered = ${indexOrderedExpr};`
1071
+ }
1072
+ let pageResponse = switch ownerIndex {
1073
+ | None => connectionPageResponse()
1074
+ | Some(_) => connectionPageResponse(~pathExpr="_path")
1075
+ }
999
1076
  `${importUtil}
1000
1077
  export function request(ctx) {
1001
1078
  // Scan cannot page backward (ScanIndexForward is Query-only). Fail loud rather than
@@ -1027,18 +1104,8 @@ export function request(ctx) {
1027
1104
  });
1028
1105
  parts.push('#id IN (' + placeholders.join(', ') + ')');
1029
1106
  }${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
- };
1107
+ ${cursorDecode(~args="ctx.args")}${requestPathGuard}
1108
+ const _first = ctx.args.first ?? 50;${requestOperation}
1042
1109
  if (parts.length > 0) {
1043
1110
  req.filter = {
1044
1111
  expression: parts.join(' AND '),
@@ -1050,30 +1117,9 @@ export function request(ctx) {
1050
1117
  }
1051
1118
  export function response(ctx) {
1052
1119
  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
- };
1120
+ let items = ctx.result?.items ?? [];${responsePathPreamble}${sortBlock}${cursorDecode(
1121
+ ~args="ctx.args",
1122
+ )}${pageResponse}
1077
1123
  }
1078
1124
  `->Pulumi.Input.make
1079
1125
  }
@@ -1085,14 +1131,10 @@ export function response(ctx) {
1085
1131
  /**
1086
1132
  The response of a cross-table field (`@resolves`) over a Query-shaped read.
1087
1133
 
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.
1134
+ The narrowing is the TARGET's, not the declaring view's the row is the target's,
1135
+ so it answers with the same `_owns` / `_live` guards its by-key doors use. A
1136
+ nested field takes no `includeRetired`, so a retired row never travels through
1137
+ one; `{list}Refs` + `@namedWhenRetired` is that door.
1096
1138
  */
1097
1139
  let resolvedFieldResponse = (
1098
1140
  ~multi: bool,
@@ -1303,14 +1345,10 @@ ${response}
1303
1345
 
1304
1346
  /** `@resolvesMany` — the parent's id array batch-read from the target's table.
1305
1347
 
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. */
1348
+ A plain string, because BatchGetItem's `tables` map keys on the literal name,
1349
+ which the adapter interpolates via `Pulumi.Output.apply`. Same shape and
1350
+ guards as `batchGetItemsByIds`; missing ids come back null and are dropped, so
1351
+ the field is shorter rather than null-holed. */
1314
1352
  let resolveIds = (
1315
1353
  ~idsField: string,
1316
1354
  ~sortField: option<string>,
@@ -1357,13 +1395,10 @@ export function response(ctx) {
1357
1395
  `
1358
1396
  }
1359
1397
 
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. */
1398
+ /** Batched-by-ids — reads `ctx.args.ids: [String!]!` through one BatchGetItem.
1399
+ Missing ids drop out; empty input short-circuits without hitting DDB. The
1400
+ table name is interpolated at deploy time, since BatchGetItem's `tables` map
1401
+ keys on the literal. Single-key tables only. */
1367
1402
  let batchGetItemsByIds = (
1368
1403
  ~ownerField: option<string>=?,
1369
1404
  ~retiredField: option<string>=?,
@@ -1387,12 +1422,9 @@ export function request(ctx) {
1387
1422
  }
1388
1423
  export function response(ctx) {
1389
1424
  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.
1425
+ // BatchGetItem returns null for keys that don't exist, preserving index
1426
+ // correspondence. The SDL declares \`[T!]!\`, so one missing id would null the
1427
+ // whole field drop them and return what was found.
1396
1428
  // The owner and retirement guards the list pushes into a FilterExpression,
1397
1429
  // applied after the read because BatchGetItem has none to push into. A row the
1398
1430
  // caller does not own is dropped rather than refused, for the reason the
@@ -1416,14 +1448,11 @@ export function response(ctx) {
1416
1448
  /** The reference door — `{list}Refs(ids)`: what a caller holding a pointer to a
1417
1449
  row may learn about it, and nothing else.
1418
1450
 
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. */
1451
+ The same BatchGetItem as `batchGetItemsByIds`, projected to
1452
+ `{id, label, retired, retiredState}` by the SDL type, so the response builds
1453
+ three fields rather than deciding what to withhold. `namedWhenRetired` decides
1454
+ a retired row: false drops it, true names it. The owner rule applies either
1455
+ way — that is not what the annotation lifts. */
1427
1456
  let refsByIds = (
1428
1457
  ~labelField: string,
1429
1458
  ~retiredField: option<string>,