import {greaterThan} from 'compare-utf8'; import type {ReadonlyJSONValue} from '../../shared/src/json.ts'; import {asyncIterableToArray} from './async-iterable-to-array.ts'; import {type IndexKey, encodeIndexScanKey} from './db/index.ts'; import type {IterableUnion} from './iterable-union.ts'; import { type KeyTypeForScanOptions, type ScanIndexOptions, type ScanOptionIndexedStartKey, type ScanOptions, isScanIndexOptions, normalizeScanOptionIndexedStartKey, } from './scan-options.ts'; import {type Closed, throwIfClosed} from './transaction-closed-error.ts'; import {type EntryForOptions, fromKeyForNonIndexScan} from './transactions.ts'; type ScanKey = string | IndexKey; type ToValue = ( entry: EntryForOptions, ) => Value; /** * This class is used for the results of {@link ReadTransaction.scan | scan}. It * implements `AsyncIterable` which allows you to use it in a `for * await` loop. There are also methods to iterate over the {@link keys}, * {@link entries} or {@link values}. */ export class ScanResultImpl< Options extends ScanOptions, V, > implements ScanResult, V> { readonly #iter: AsyncIterable>; readonly #options: Options; readonly #dbDelegateOptions: Closed; readonly #onLimitKey: (inclusiveLimitKey: string) => void; constructor( iter: AsyncIterable>, options: Options, dbDelegateOptions: Closed, onLimitKey: (inclusiveLimitKey: string) => void, ) { this.#iter = iter; this.#options = options; this.#dbDelegateOptions = dbDelegateOptions; this.#onLimitKey = onLimitKey; } /** The default AsyncIterable. This is the same as {@link values}. */ [Symbol.asyncIterator](): AsyncIterableIteratorToArray { return this.values(); } /** Async iterator over the values of the {@link ReadTransaction.scan | scan} call. */ values(): AsyncIterableIteratorToArray { return new AsyncIterableIteratorToArrayWrapperImpl( this.#newIterator(e => e[1] as V), ); } /** * Async iterator over the keys of the {@link ReadTransaction.scan | scan} * call. If the {@link ReadTransaction.scan | scan} is over an index the key * is a tuple of `[secondaryKey: string, primaryKey]` */ keys(): AsyncIterableIteratorToArray> { type K = KeyTypeForScanOptions; return new AsyncIterableIteratorToArrayWrapperImpl( this.#newIterator(e => e[0] as K), ); } /** * Async iterator over the entries of the {@link ReadTransaction.scan | scan} * call. An entry is a tuple of key values. If the * {@link ReadTransaction.scan | scan} is over an index the key is a tuple of * `[secondaryKey: string, primaryKey]` */ entries(): AsyncIterableIteratorToArray< readonly [KeyTypeForScanOptions, V] > { type Key = KeyTypeForScanOptions; type Entry = readonly [Key, V]; return new AsyncIterableIteratorToArrayWrapperImpl( this.#newIterator(e => [e[0] as Key, e[1] as V]), ); } /** Returns all the values as an array. Same as `values().toArray()` */ toArray(): Promise { return this.values().toArray(); } #newIterator(toValue: ToValue): AsyncIterableIterator { return scanIterator( toValue, this.#iter, this.#options, this.#dbDelegateOptions, this.#onLimitKey, ); } } export interface ScanResult extends AsyncIterable { /** The default AsyncIterable. This is the same as {@link values}. */ [Symbol.asyncIterator](): AsyncIterableIteratorToArray; /** Async iterator over the values of the {@link ReadTransaction.scan | scan} call. */ values(): AsyncIterableIteratorToArray; /** * Async iterator over the keys of the {@link ReadTransaction.scan | scan} * call. If the {@link ReadTransaction.scan | scan} is over an index the key * is a tuple of `[secondaryKey: string, primaryKey]` */ keys(): AsyncIterableIteratorToArray; /** * Async iterator over the entries of the {@link ReadTransaction.scan | scan} * call. An entry is a tuple of key values. If the * {@link ReadTransaction.scan | scan} is over an index the key is a tuple of * `[secondaryKey: string, primaryKey]` */ entries(): AsyncIterableIteratorToArray; /** Returns all the values as an array. Same as `values().toArray()` */ toArray(): Promise; } /** * An interface that adds a {@link toArray} method to `AsyncIterableIterator`. * * Usage: * * ```ts * const keys: string[] = await rep.scan().keys().toArray(); * ``` */ export interface AsyncIterableIteratorToArray< V, > extends AsyncIterableIterator { toArray(): Promise; } class AsyncIterableIteratorToArrayWrapperImpl< V, > implements AsyncIterableIterator { readonly #it: AsyncIterableIterator; constructor(it: AsyncIterableIterator) { this.#it = it; } next() { return this.#it.next(); } [Symbol.asyncIterator](): AsyncIterableIterator { return this.#it[Symbol.asyncIterator](); } toArray(): Promise { return asyncIterableToArray(this.#it); } } async function* scanIterator( toValue: ToValue, iter: AsyncIterable>, options: Options, closed: Closed, onLimitKey: (inclusiveLimitKey: string) => void, ): AsyncIterableIterator { throwIfClosed(closed); let {limit = Infinity} = options; const {prefix = ''} = options; let exclusive = options.start?.exclusive; const isIndexScan = isScanIndexOptions(options); // iter has already been moved to the first entry for await (const entry of iter) { const key = entry[0]; const keyToMatch: string = isIndexScan ? key[0] : (key as string); if (!keyToMatch.startsWith(prefix)) { return; } if (exclusive) { exclusive = true; if (isIndexScan) { // oxlint-disable-next-line @typescript-eslint/no-non-null-assertion if (shouldSkipIndexScan(key as IndexKey, options.start!.key)) { continue; } } else { // oxlint-disable-next-line @typescript-eslint/no-non-null-assertion if (shouldSkipNonIndexScan(key as string, options.start!.key)) { continue; } } } yield toValue(entry); if (--limit === 0) { // We do not do the limit optimization for index scans in subscriptions. if (!isIndexScan) { onLimitKey(key as string); } return; } } } function shouldSkipIndexScan( key: IndexKey, startKey: ScanOptionIndexedStartKey, ): boolean { const [secondaryStartKey, primaryStartKey] = normalizeScanOptionIndexedStartKey(startKey); const [secondaryKey, primaryKey] = normalizeScanOptionIndexedStartKey(key); if (secondaryKey !== secondaryStartKey) { return false; } if (primaryStartKey === undefined) { return true; } return primaryKey === primaryStartKey; } function shouldSkipNonIndexScan(key: string, startKey: string): boolean { return key === startKey; } export type Entry = readonly [key: string, value: V]; /** * This is called when doing a {@link ReadTransaction.scan | scan} without an * `indexName`. * * @param fromKey The `fromKey` is computed by `scan` and is the key of the * first entry to return in the iterator. It is based on `prefix` and * `start.key` of the {@link ScanNoIndexOptions}. */ export type GetScanIterator = ( fromKey: string, ) => IterableUnion>; /** * When using {@link makeScanResult} this is the type used for the function called when doing a {@link ReadTransaction.scan | scan} with an * `indexName`. * * @param indexName The name of the index we are scanning over. * @param fromSecondaryKey The `fromSecondaryKey` is computed by `scan` and is * the secondary key of the first entry to return in the iterator. It is based * on `prefix` and `start.key` of the {@link ScanIndexOptions}. * @param fromPrimaryKey The `fromPrimaryKey` is computed by `scan` and is the * primary key of the first entry to return in the iterator. It is based on * `prefix` and `start.key` of the {@link ScanIndexOptions}. */ export type GetIndexScanIterator = ( indexName: string, fromSecondaryKey: string, fromPrimaryKey: string | undefined, ) => IterableUnion; /** * A helper function that makes it easier to implement {@link ReadTransaction.scan} * with a custom backend. * * If you are implementing a custom backend and have an in memory pending async * iterable we provide two helper functions to make it easier to merge these * together. {@link mergeAsyncIterables} and {@link filterAsyncIterable}. * * For example: * * ```ts * const scanResult = makeScanResult( * options, * options.indexName * ? () => { * throw Error('not implemented'); * } * : fromKey => { * const persisted: AsyncIterable> = ...; * const pending: AsyncIterable> = ...; * const iter = await mergeAsyncIterables(persisted, pending); * const filteredIter = await filterAsyncIterable( * iter, * entry => entry[1] !== undefined, * ); * return filteredIter; * }, * ); * ``` */ export function makeScanResult( options: Options, getScanIterator: Options extends ScanIndexOptions ? GetIndexScanIterator : GetScanIterator, ): ScanResult, ReadonlyJSONValue> { type AsyncIter = AsyncIterable>; if (isScanIndexOptions(options)) { const [fromSecondaryKey, fromPrimaryKey] = fromKeyForIndexScan(options); return new ScanResultImpl( (getScanIterator as GetIndexScanIterator)( options.indexName, fromSecondaryKey, fromPrimaryKey, ) as AsyncIter, options, {closed: false}, _ => { // noop }, ); } const fromKey = fromKeyForNonIndexScan(options); return new ScanResultImpl( (getScanIterator as GetScanIterator)(fromKey) as AsyncIter, options, {closed: false}, _ => { // noop }, ); } export function fromKeyForIndexScan( options: ScanIndexOptions, ): readonly [secondary: string, primary?: string | undefined] { const {prefix, start} = options; const prefixNormalized: [secondary: string, primary?: string | undefined] = [ prefix ?? '', undefined, ]; if (!start) { return prefixNormalized; } const startKeyNormalized = normalizeScanOptionIndexedStartKey(start.key); if (greaterThan(startKeyNormalized[0], prefixNormalized[0])) { return startKeyNormalized; } if ( startKeyNormalized[0] === prefixNormalized[0] && startKeyNormalized[1] !== undefined ) { return startKeyNormalized; } return prefixNormalized; } export function fromKeyForIndexScanInternal(options: ScanIndexOptions): string { const {prefix, start} = options; let prefix2 = ''; if (prefix !== undefined) { prefix2 = encodeIndexScanKey(prefix, undefined); } if (!start) { return prefix2; } const {key} = start; const [secondary, primary] = normalizeScanOptionIndexedStartKey(key); const startKey = encodeIndexScanKey(secondary, primary); if (greaterThan(startKey, prefix2)) { return startKey; } return prefix2; }