dynamo-bao 0.4.2 → 0.6.0

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.
package/src/model.js CHANGED
@@ -33,8 +33,10 @@ const {
33
33
  UNIQUE_CONSTRAINT_KEY,
34
34
  SYSTEM_FIELDS,
35
35
  ITERATION_INDEX_NAME,
36
+ SEARCH_INDEX_NAME,
36
37
  ITERATION_PK_FIELD,
37
38
  ITERATION_SK_FIELD,
39
+ SEARCH_TEXT_FIELD,
38
40
  } = require("./constants");
39
41
  const {
40
42
  ConfigurationError,
@@ -63,6 +65,8 @@ class BaoModel {
63
65
  static uniqueConstraints = {};
64
66
  static iterable = false;
65
67
  static iterationBuckets = 100;
68
+ static searchable = false;
69
+ static searchConfig = null;
66
70
 
67
71
  static defaultQueryLimit = 100;
68
72
 
@@ -269,29 +273,549 @@ class BaoModel {
269
273
  yield* this._iterateSingleBucket(bucketNum, options);
270
274
  }
271
275
 
272
- static async *_iterateSingleBucket(bucketNum, options = {}) {
273
- const { batchSize = 100, filter = null } = options;
274
- const tenantId = this.manager.getTenantId();
276
+ static _assertSearchable() {
277
+ if (!this.searchable || !this.searchConfig) {
278
+ throw new Error(
279
+ `Model ${this.name} is not configured as searchable. ` +
280
+ `Add a searchable: { fields: [...] } block in YAML to enable search.`,
281
+ );
282
+ }
283
+ if (!this.iterable) {
284
+ throw new Error(
285
+ `searchAll requires iterable: true. For non-iterable models, use ` +
286
+ `query/queryByIndex with a filter on _searchText.`,
287
+ );
288
+ }
289
+ const indexName = this.manager.getIterationIndexName();
290
+ if (indexName !== SEARCH_INDEX_NAME) {
291
+ throw new Error(
292
+ `searchAll requires the '${SEARCH_INDEX_NAME}' GSI. Current config ` +
293
+ `resolves the iteration index to '${indexName}'. To enable search:\n` +
294
+ ` 1) Run 'bao-update-table' to add ${SEARCH_INDEX_NAME} to the table.\n` +
295
+ ` 2) Set 'db.iterationIndexName: "${SEARCH_INDEX_NAME}"' in your config.\n` +
296
+ ` 3) (If the model already has data) run 'bao-rebuild-search-text <ModelName>'.`,
297
+ );
298
+ }
299
+ }
275
300
 
276
- let iterPk;
301
+ /**
302
+ * @description
303
+ * Search a `searchable: { fields: [...] }`-configured iterable model by
304
+ * substring(s) of `_searchText`. Each term becomes one
305
+ * `contains(_searchText, :term)` predicate. Multiple terms are combined
306
+ * with `$and` (default) or `$or`. Each term is normalized with the same
307
+ * rules used to build `_searchText` at write time, so user input matches
308
+ * what's stored.
309
+ *
310
+ * Reads from the bucketed `iter_search_index` GSI. By default fans out
311
+ * across every bucket in parallel; sequential mode is available via
312
+ * `parallel: false`. Returns one page of results plus an opaque cursor
313
+ * for resumption. To paginate, pass the cursor back on subsequent calls;
314
+ * `cursor === null` indicates the search is exhausted.
315
+ *
316
+ * @param {string[]} terms - One or more substring terms. Empty/whitespace
317
+ * terms are dropped; throws if zero usable terms remain after
318
+ * normalization.
319
+ * @param {Object} [options]
320
+ * @param {('$and'|'$or')} [options.operator='$and'] - How multi-term queries
321
+ * are combined.
322
+ * @param {number} [options.batchSize=100] - DynamoDB Query Limit per page.
323
+ * Each Query examines up to this many items before applying
324
+ * FilterExpression.
325
+ * @param {number} [options.limit=100] - Maximum total items returned by
326
+ * this call. Pass `Infinity` to opt out (caller is responsible for
327
+ * ensuring the call doesn't exhaust capacity).
328
+ * @param {number} [options.maxQueriesPerBucket=50] - Per-bucket cap on
329
+ * DynamoDB Query roundtrips per call. Bounds worst-case capacity for
330
+ * sparse-match searches. When hit, the call returns whatever it found
331
+ * plus a non-null cursor pointing at the next page.
332
+ * @param {boolean} [options.parallel=true] - When true, all unexhausted
333
+ * buckets are queried concurrently in rounds; results are interleaved.
334
+ * When false, buckets are walked sequentially in order.
335
+ * @param {string|null} [options.cursor=null] - Opaque cursor from a
336
+ * previous call. Pass to resume; omit (or pass `null`) for a fresh
337
+ * search. Cursor is invalidated if `terms`, `operator`, or the model's
338
+ * `searchConfig` change.
339
+ * @param {Object} [options.filter] - Additional filter combined via AND
340
+ * with the search predicate. Must reference only attributes projected
341
+ * on `iter_search_index` (i.e., `_searchText` and the index/base keys).
342
+ * @returns {Promise<{items: BaoModel[], cursor: string|null}>} `items` is
343
+ * never longer than `limit`. `cursor` is `null` when the search is
344
+ * fully exhausted; otherwise pass it back to get the next page.
345
+ * @throws {Error} If the model is not `searchable`, not `iterable`, the
346
+ * resolved iteration index is not `iter_search_index`, `limit` is
347
+ * invalid, the cursor is malformed, or the cursor was generated for a
348
+ * different query.
349
+ * @example
350
+ * // First page
351
+ * const { items, cursor } = await Post.searchAll(["alice"], { limit: 50 });
352
+ * // "Load more"
353
+ * const next = await Post.searchAll(["alice"], { limit: 50, cursor });
354
+ * // Drain everything
355
+ * let cur = null, all = [];
356
+ * do {
357
+ * const page = await Post.searchAll(["alice"], { limit: 100, cursor: cur });
358
+ * all.push(...page.items);
359
+ * cur = page.cursor;
360
+ * } while (cur);
361
+ */
362
+ static async searchAll(terms, options = {}) {
363
+ this._assertSearchable();
364
+ return this._searchPaged({
365
+ terms,
366
+ options,
367
+ activeBucketIndices: Array.from(
368
+ { length: this.iterationBuckets },
369
+ (_, b) => b,
370
+ ),
371
+ });
372
+ }
373
+
374
+ /**
375
+ * @description
376
+ * Search a single iteration bucket. Same predicate semantics and return
377
+ * shape as {@link BaoModel.searchAll}, but scoped to one bucket. Useful
378
+ * for partitioned workers (each handles a subset of buckets).
379
+ *
380
+ * @param {number} bucketNum - Bucket index, in `[0, iterationBuckets)`.
381
+ * @param {string[]} terms - Substring terms (see `searchAll`).
382
+ * @param {Object} [options] - Same options as `searchAll` (cursor scoped
383
+ * to this bucket).
384
+ * @returns {Promise<{items: BaoModel[], cursor: string|null}>}
385
+ * @throws {Error} On invalid bucket number, non-searchable model, etc.
386
+ */
387
+ static async searchBucket(bucketNum, terms, options = {}) {
388
+ this._assertSearchable();
389
+ if (
390
+ !Number.isInteger(bucketNum) ||
391
+ bucketNum < 0 ||
392
+ bucketNum >= this.iterationBuckets
393
+ ) {
394
+ throw new Error(
395
+ `Invalid bucket number ${bucketNum}. Must be 0-${this.iterationBuckets - 1}`,
396
+ );
397
+ }
398
+ return this._searchPaged({
399
+ terms,
400
+ options,
401
+ activeBucketIndices: [bucketNum],
402
+ });
403
+ }
404
+
405
+ /**
406
+ * @private
407
+ * Shared paged-search engine for searchAll and searchBucket. Honors the
408
+ * `parallel`, `limit`, `maxQueriesPerBucket`, and `cursor` options;
409
+ * returns `{ items, cursor }` with `cursor === null` on exhaustion.
410
+ */
411
+ static async _searchPaged({ terms, options, activeBucketIndices }) {
412
+ const {
413
+ buildSearchPredicate,
414
+ validateLimit,
415
+ predicateHash,
416
+ encodeCursor,
417
+ decodeCursor,
418
+ } = require("./utils/search-text");
419
+
420
+ const {
421
+ operator = "$and",
422
+ batchSize = 100,
423
+ filter = null,
424
+ limit = 100,
425
+ maxQueriesPerBucket = 50,
426
+ parallel = true,
427
+ cursor: incomingCursor = null,
428
+ } = options;
429
+
430
+ validateLimit(limit);
431
+ if (
432
+ !Number.isInteger(maxQueriesPerBucket) ||
433
+ maxQueriesPerBucket < 1
434
+ ) {
435
+ throw new Error(
436
+ "maxQueriesPerBucket must be a positive integer.",
437
+ );
438
+ }
439
+
440
+ const searchPredicate = buildSearchPredicate(terms, this.searchConfig, {
441
+ operator,
442
+ });
443
+ const expectedHash = predicateHash(terms, operator, this.searchConfig);
444
+ // Tenant is baked into iter_pk values stashed in bucketCursors, so a
445
+ // cursor from one tenant can't safely be resumed under another. Capture
446
+ // the current tenant for write-side; validate on resume below.
447
+ const currentTenantId = this.manager.getTenantId() || null;
448
+
449
+ // Decode the cursor or initialize per-bucket state for a fresh call.
450
+ // bucketCursors maps bucketIdx -> lek (or null for "start of bucket").
451
+ // pendingItemKeys is the over-pull from a previous parallel round.
452
+ let bucketCursors;
453
+ let pendingItemKeys = [];
454
+ if (incomingCursor) {
455
+ const decoded = decodeCursor(incomingCursor);
456
+ if (decoded.predicateHash !== expectedHash) {
457
+ throw new Error(
458
+ `Cursor was generated for a different query (terms/operator/searchConfig changed). Start a new search.`,
459
+ );
460
+ }
461
+ if (decoded.modelPrefix !== this.modelPrefix) {
462
+ throw new Error(
463
+ `Cursor was generated for model "${decoded.modelPrefix}", not "${this.modelPrefix}".`,
464
+ );
465
+ }
466
+ // Cross-tenant cursor reuse would Query under tenant B with a
467
+ // tenant-A iter_pk in ExclusiveStartKey — DynamoDB rejects with an
468
+ // opaque ValidationException. Surface a clear error first.
469
+ if (decoded.tenantId !== currentTenantId) {
470
+ throw new Error(
471
+ `Cursor was generated under tenant "${decoded.tenantId || "(none)"}", ` +
472
+ `not "${currentTenantId || "(none)"}". Cursors are tenant-scoped.`,
473
+ );
474
+ }
475
+ // Cursors are scoped to the bucket set used to generate them, so a
476
+ // searchAll cursor can't be passed into searchBucket(N) (and vice
477
+ // versa) without silently mixing items across scopes via
478
+ // pendingItemKeys. Reject mismatch with a clear message.
479
+ const decodedScope = (decoded.scope || []).slice().sort((a, b) => a - b);
480
+ const expectedScope = activeBucketIndices.slice().sort((a, b) => a - b);
481
+ const scopesMatch =
482
+ decodedScope.length === expectedScope.length &&
483
+ decodedScope.every((s, i) => s === expectedScope[i]);
484
+ if (!scopesMatch) {
485
+ throw new Error(
486
+ `Cursor scope mismatch. Cursor was generated for buckets ` +
487
+ `[${decodedScope.join(", ")}], but this call covers ` +
488
+ `[${expectedScope.join(", ")}]. Resume the cursor with the same ` +
489
+ `API call (searchAll or searchBucket) that produced it.`,
490
+ );
491
+ }
492
+ bucketCursors = { ...decoded.bucketCursors };
493
+ pendingItemKeys = decoded.pendingItemKeys || [];
494
+ } else {
495
+ bucketCursors = {};
496
+ for (const b of activeBucketIndices) bucketCursors[b] = null;
497
+ }
498
+
499
+ const items = [];
500
+
501
+ // Phase 1: drain pending items from a prior over-pull. Hydrate via
502
+ // batchFind (current row state — deletions surface as missing items).
503
+ // Preserve insertion order from the original pendingItemKeys list so
504
+ // the user sees a deterministic page-to-page sequence.
505
+ if (pendingItemKeys.length > 0) {
506
+ const { items: found } = await this.batchFind(pendingItemKeys);
507
+ for (const k of pendingItemKeys) {
508
+ if (found[k]) items.push(found[k]);
509
+ }
510
+ }
511
+
512
+ const queriesByBucket = {};
513
+ for (const b of Object.keys(bucketCursors)) queriesByBucket[b] = 0;
514
+
515
+ // Collapse the iterationBuckets===1 case: PK shape uses null bucketArg,
516
+ // but we still index state by 0 internally for consistency.
517
+ const bucketArg = (b) => (this.iterationBuckets === 1 ? null : b);
518
+
519
+ const pullPage = async (bucketIdx) => {
520
+ const lek = bucketCursors[bucketIdx];
521
+ queriesByBucket[bucketIdx] = (queriesByBucket[bucketIdx] || 0) + 1;
522
+ const page = await this._searchSingleBucketPage(bucketArg(bucketIdx), {
523
+ batchSize,
524
+ filter,
525
+ searchPredicate,
526
+ exclusiveStartKey: lek || null,
527
+ });
528
+ if (page.lek) bucketCursors[bucketIdx] = page.lek;
529
+ else delete bucketCursors[bucketIdx]; // exhausted
530
+ return page.items;
531
+ };
532
+
533
+ const eligibleBuckets = () =>
534
+ Object.keys(bucketCursors)
535
+ .map((b) => parseInt(b, 10))
536
+ .filter((b) => (queriesByBucket[b] || 0) < maxQueriesPerBucket)
537
+ .sort((a, b) => a - b);
538
+
539
+ if (parallel) {
540
+ while (items.length < limit && eligibleBuckets().length > 0) {
541
+ const round = eligibleBuckets();
542
+ const pages = await Promise.all(round.map(pullPage));
543
+ for (const pageItems of pages) items.push(...pageItems);
544
+ }
545
+ } else {
546
+ // Sequential: walk eligible buckets in order, pulling pages until
547
+ // exhausted / per-bucket cap / global limit hit.
548
+ for (const bucket of eligibleBuckets()) {
549
+ while (
550
+ bucketCursors[bucket] !== undefined &&
551
+ (queriesByBucket[bucket] || 0) < maxQueriesPerBucket &&
552
+ items.length < limit
553
+ ) {
554
+ const pageItems = await pullPage(bucket);
555
+ items.push(...pageItems);
556
+ }
557
+ if (items.length >= limit) break;
558
+ }
559
+ }
560
+
561
+ // Slice to limit; over-pull at the boundary gets stashed in the cursor
562
+ // as pendingItemKeys for the next call to return first. Both modes can
563
+ // over-pull: parallel mode by up to (active buckets - 1) × batchSize,
564
+ // sequential mode by up to one batchSize (its loop guard is at the top
565
+ // so the page that pushes us past `limit` is fully kept).
566
+ let kept = items;
567
+ let overflowKeys = [];
568
+ if (items.length > limit) {
569
+ kept = items.slice(0, limit);
570
+ overflowKeys = items
571
+ .slice(limit)
572
+ .map((m) => m.getPrimaryId());
573
+ }
574
+
575
+ const bucketsRemaining = Object.keys(bucketCursors).length > 0;
576
+ const hasMore = bucketsRemaining || overflowKeys.length > 0;
577
+ const cursorOut = hasMore
578
+ ? encodeCursor({
579
+ bucketCursors,
580
+ predicateHash: expectedHash,
581
+ modelPrefix: this.modelPrefix,
582
+ scope: activeBucketIndices,
583
+ tenantId: currentTenantId,
584
+ pendingItemKeys: overflowKeys,
585
+ })
586
+ : null;
587
+
588
+ return { items: kept, cursor: cursorOut };
589
+ }
590
+
591
+ /**
592
+ * @description
593
+ * Split a free-form query string into an array of terms suitable for
594
+ * passing to {@link BaoModel.searchAll}. Whitespace separates terms;
595
+ * double-quoted phrases are kept together as a single term.
596
+ *
597
+ * @param {string} queryString - Raw user input.
598
+ * @returns {string[]} Array of terms (possibly empty).
599
+ * @example
600
+ * Post.tokenizeSearchQuery('"hello world" foo');
601
+ * // => ["hello world", "foo"]
602
+ */
603
+ static tokenizeSearchQuery(queryString) {
604
+ const { tokenizeSearchQuery } = require("./utils/search-text");
605
+ return tokenizeSearchQuery(queryString);
606
+ }
607
+
608
+ /**
609
+ * @description
610
+ * Normalize a single search term using the same rules the model used to
611
+ * build `_searchText` at write time: lowercase (unless
612
+ * `caseSensitive: true`), strip punctuation, collapse whitespace. Useful
613
+ * when post-filtering hydrated rows in JS, or when manually constructing
614
+ * a `_searchText` filter against a model that has no `searchConfig`.
615
+ *
616
+ * Idempotent — calling multiple times returns the same result.
617
+ *
618
+ * @param {string} term - Raw user input.
619
+ * @returns {string} Normalized term.
620
+ * @example
621
+ * const term = Post.normalizeSearchTerm("Hello, World!"); // "hello world"
622
+ * results.filter((p) => p._dyData._searchText?.includes(term));
623
+ */
624
+ static normalizeSearchTerm(term) {
625
+ const { normalizeSearchTerm } = require("./utils/search-text");
626
+ return normalizeSearchTerm(term, this.searchConfig || {});
627
+ }
628
+
629
+ // Attributes projected onto each iteration index, by index name. The base
630
+ // table key (_pk/_sk) and the index key (_iter_pk/_iter_sk) are always
631
+ // projected by DynamoDB. iter_search_index additionally INCLUDEs
632
+ // _searchText. iter_index (legacy) is KEYS_ONLY.
633
+ static _PROJECTED_ATTRS_BY_INDEX = {
634
+ [SEARCH_INDEX_NAME]: new Set([
635
+ "_pk",
636
+ "_sk",
637
+ ITERATION_PK_FIELD,
638
+ ITERATION_SK_FIELD,
639
+ SEARCH_TEXT_FIELD,
640
+ ]),
641
+ [ITERATION_INDEX_NAME]: new Set([
642
+ "_pk",
643
+ "_sk",
644
+ ITERATION_PK_FIELD,
645
+ ITERATION_SK_FIELD,
646
+ ]),
647
+ };
648
+
649
+ static _assertFilterFitsIterIndex(indexName, expressionAttributeNames) {
650
+ const projected = this._PROJECTED_ATTRS_BY_INDEX[indexName];
651
+ if (!projected) return; // Unknown index — skip the preflight.
652
+ const referenced = Object.values(expressionAttributeNames);
653
+ const unprojected = referenced.filter((name) => !projected.has(name));
654
+ if (unprojected.length === 0) return;
655
+ const list = unprojected.join(", ");
656
+ const example = unprojected[0];
657
+ const projectedList = Array.from(projected).join(", ");
658
+ throw new Error(
659
+ `Filter on '${indexName}' references attribute(s) that aren't ` +
660
+ `projected: [${list}]. The index projects: [${projectedList}]. ` +
661
+ `DynamoDB can't filter on anything else at the index level — ` +
662
+ `filter the hydrated batch in JS instead, e.g.:\n` +
663
+ ` for await (const batch of Model.iterateAll()) {\n` +
664
+ ` for (const item of batch) {\n` +
665
+ ` if (item.${example} === ...) { /* keep */ }\n` +
666
+ ` }\n` +
667
+ ` }`,
668
+ );
669
+ }
670
+
671
+ static _getIterationPk(bucketNum) {
672
+ const tenantId = this.manager.getTenantId();
277
673
  if (this.iterationBuckets === 1) {
278
- iterPk = tenantId
674
+ return tenantId
279
675
  ? `[${tenantId}]#${this.modelPrefix}#iter`
280
676
  : `${this.modelPrefix}#iter`;
281
- } else {
282
- const bucket = bucketNum.toString().padStart(3, "0");
283
- iterPk = tenantId
284
- ? `[${tenantId}]#${this.modelPrefix}#iter#${bucket}`
285
- : `${this.modelPrefix}#iter#${bucket}`;
286
677
  }
678
+ const bucket = bucketNum.toString().padStart(3, "0");
679
+ return tenantId
680
+ ? `[${tenantId}]#${this.modelPrefix}#iter#${bucket}`
681
+ : `${this.modelPrefix}#iter#${bucket}`;
682
+ }
683
+
684
+ /**
685
+ * @private
686
+ * Send a Query against the iteration GSI, translating DynamoDB's
687
+ * "missing index" ValidationException into a friendlier error pointing
688
+ * at `bao-update-table`. Single source of truth for both the streaming
689
+ * `_iterateSingleBucket` and the paged `_searchSingleBucketPage` paths
690
+ * — keeping the translation in one place prevents the two from drifting.
691
+ *
692
+ * @param {Object} params - Full QueryCommand input.
693
+ * @param {string} indexName - The expected index (used in the error
694
+ * message; pre-resolved by callers via getIterationIndexName()).
695
+ * @returns {Promise<Object>} The raw QueryCommand response.
696
+ */
697
+ static async _runIterationQuery(params, indexName) {
698
+ const { QueryCommand } = require("./dynamodb-client");
699
+ try {
700
+ return await this.documentClient.send(new QueryCommand(params));
701
+ } catch (error) {
702
+ // DynamoDB reports a missing index as a ValidationException with a
703
+ // message like "The table does not have the specified index: <name>".
704
+ // We only translate when the message explicitly references an index
705
+ // — translating raw ResourceNotFoundException would mask a missing
706
+ // *table* with a "run bao-update-table" hint that wouldn't help.
707
+ const message = error.message || "";
708
+ const isMissingIndex =
709
+ /does not have the specified index/i.test(message) ||
710
+ message.includes(`specified index: ${indexName}`) ||
711
+ (error.name === "ResourceNotFoundException" &&
712
+ message.toLowerCase().includes("index"));
713
+ if (isMissingIndex) {
714
+ throw new Error(
715
+ `Index '${indexName}' is missing on table '${this.table}'. ` +
716
+ `Run 'bao-update-table' to add it.`,
717
+ );
718
+ }
719
+ throw error;
720
+ }
721
+ }
722
+
723
+ /**
724
+ * @private
725
+ * Single Query roundtrip against the iter_search_index for one bucket.
726
+ * Returns hydrated items + lastEvaluatedKey. Used by the paged
727
+ * searchAll/searchBucket implementation that needs explicit page-by-page
728
+ * control (instead of the do/while loop in _iterateSingleBucket).
729
+ *
730
+ * @param {number|null} bucketNum - Bucket index, or `null` for single-bucket models.
731
+ * @param {Object} options
732
+ * @param {number} options.batchSize - DynamoDB Query Limit.
733
+ * @param {Object} [options.filter] - User filter.
734
+ * @param {Object} [options.searchPredicate] - Predicate from buildSearchPredicate.
735
+ * @param {Object} [options.exclusiveStartKey] - DynamoDB LEK to resume from.
736
+ * @returns {Promise<{items: BaoModel[], lek: Object|null}>}
737
+ */
738
+ static async _searchSingleBucketPage(bucketNum, options = {}) {
739
+ const {
740
+ batchSize = 100,
741
+ filter = null,
742
+ searchPredicate = null,
743
+ exclusiveStartKey = null,
744
+ } = options;
745
+ const iterPk = this._getIterationPk(bucketNum);
746
+ const indexName = this.manager.getIterationIndexName();
747
+
748
+ const params = {
749
+ TableName: this.table,
750
+ IndexName: indexName,
751
+ KeyConditionExpression: "#pk = :pk",
752
+ ExpressionAttributeNames: { "#pk": ITERATION_PK_FIELD },
753
+ ExpressionAttributeValues: { ":pk": iterPk },
754
+ Limit: batchSize,
755
+ ReturnConsumedCapacity: "TOTAL",
756
+ };
757
+ if (exclusiveStartKey) params.ExclusiveStartKey = exclusiveStartKey;
758
+
759
+ const filterParts = [];
760
+ if (filter) {
761
+ const { FilterExpressionBuilder } = require("./filter-expression");
762
+ const filterBuilder = new FilterExpressionBuilder();
763
+ const filterExpression = filterBuilder.build(filter, this);
764
+ if (filterExpression) {
765
+ this._assertFilterFitsIterIndex(
766
+ indexName,
767
+ filterExpression.ExpressionAttributeNames,
768
+ );
769
+ filterParts.push(filterExpression.FilterExpression);
770
+ Object.assign(
771
+ params.ExpressionAttributeNames,
772
+ filterExpression.ExpressionAttributeNames,
773
+ );
774
+ Object.assign(
775
+ params.ExpressionAttributeValues,
776
+ filterExpression.ExpressionAttributeValues,
777
+ );
778
+ }
779
+ }
780
+ if (searchPredicate) {
781
+ filterParts.push(searchPredicate.FilterExpression);
782
+ Object.assign(
783
+ params.ExpressionAttributeNames,
784
+ searchPredicate.ExpressionAttributeNames,
785
+ );
786
+ Object.assign(
787
+ params.ExpressionAttributeValues,
788
+ searchPredicate.ExpressionAttributeValues,
789
+ );
790
+ }
791
+ if (filterParts.length > 0) {
792
+ params.FilterExpression = filterParts
793
+ .map((p) => `(${p})`)
794
+ .join(" AND ");
795
+ }
796
+
797
+ const response = await this._runIterationQuery(params, indexName);
798
+
799
+ let items = [];
800
+ if (response.Items && response.Items.length > 0) {
801
+ const objectIds = response.Items.map((item) => item[ITERATION_SK_FIELD]);
802
+ const { items: found } = await this.batchFind(objectIds);
803
+ items = Object.values(found);
804
+ }
805
+ return { items, lek: response.LastEvaluatedKey || null };
806
+ }
807
+
808
+ static async *_iterateSingleBucket(bucketNum, options = {}) {
809
+ const { batchSize = 100, filter = null, searchPredicate = null } = options;
810
+ const iterPk = this._getIterationPk(bucketNum);
811
+ const indexName = this.manager.getIterationIndexName();
287
812
 
288
813
  let lastEvaluatedKey = null;
289
814
 
290
815
  do {
291
- const { QueryCommand } = require("./dynamodb-client");
292
816
  const params = {
293
817
  TableName: this.table,
294
- IndexName: ITERATION_INDEX_NAME,
818
+ IndexName: indexName,
295
819
  KeyConditionExpression: "#pk = :pk",
296
820
  ExpressionAttributeNames: { "#pk": ITERATION_PK_FIELD },
297
821
  ExpressionAttributeValues: { ":pk": iterPk },
@@ -303,12 +827,21 @@ class BaoModel {
303
827
  params.ExclusiveStartKey = lastEvaluatedKey;
304
828
  }
305
829
 
830
+ const filterParts = [];
306
831
  if (filter) {
307
832
  const { FilterExpressionBuilder } = require("./filter-expression");
308
833
  const filterBuilder = new FilterExpressionBuilder();
309
834
  const filterExpression = filterBuilder.build(filter, this);
310
835
  if (filterExpression) {
311
- params.FilterExpression = filterExpression.FilterExpression;
836
+ // Preflight: filter attributes must be in the GSI's projection.
837
+ // Otherwise DynamoDB returns an opaque "does not project one or
838
+ // more filter attributes" ValidationException; we surface a clearer
839
+ // error before the round-trip.
840
+ this._assertFilterFitsIterIndex(
841
+ indexName,
842
+ filterExpression.ExpressionAttributeNames,
843
+ );
844
+ filterParts.push(filterExpression.FilterExpression);
312
845
  Object.assign(
313
846
  params.ExpressionAttributeNames,
314
847
  filterExpression.ExpressionAttributeNames,
@@ -319,8 +852,22 @@ class BaoModel {
319
852
  );
320
853
  }
321
854
  }
855
+ if (searchPredicate) {
856
+ filterParts.push(searchPredicate.FilterExpression);
857
+ Object.assign(
858
+ params.ExpressionAttributeNames,
859
+ searchPredicate.ExpressionAttributeNames,
860
+ );
861
+ Object.assign(
862
+ params.ExpressionAttributeValues,
863
+ searchPredicate.ExpressionAttributeValues,
864
+ );
865
+ }
866
+ if (filterParts.length > 0) {
867
+ params.FilterExpression = filterParts.map((p) => `(${p})`).join(" AND ");
868
+ }
322
869
 
323
- const response = await this.documentClient.send(new QueryCommand(params));
870
+ const response = await this._runIterationQuery(params, indexName);
324
871
 
325
872
  if (response.Items && response.Items.length > 0) {
326
873
  const objectIds = response.Items.map(