diff --git a/.bazelignore b/.bazelignore index 6d732dc99..e636fb559 100644 --- a/.bazelignore +++ b/.bazelignore @@ -64,6 +64,7 @@ plugins/reference-assets/core/node_modules plugins/reference-assets/react/node_modules plugins/shared-constants/core/node_modules plugins/stage-revert-data/core/node_modules +plugins/streaming-data/core/node_modules tools/asset-testing-library/core/node_modules docs/storybook/node_modules plugins/reference-assets/mocks/node_modules diff --git a/docs/site/src/content/docs/plugins/core/streaming-data.mdx b/docs/site/src/content/docs/plugins/core/streaming-data.mdx new file mode 100644 index 000000000..48ea3ba7b --- /dev/null +++ b/docs/site/src/content/docs/plugins/core/streaming-data.mdx @@ -0,0 +1,174 @@ +--- +title: Streaming Data +--- + +import CoreOnly from "../../../../components/CoreOnly.astro"; + + + +The Streaming Data Plugin loads large collections into Player in batches without storing them in the data model. A flow declares each collection in its schema, the app registers the sources that load them, and content decides when loading starts. The plugin holds each record once, serves the list at the collection's binding, writes the collection's status to the data model, and saves changes through `EXTERNAL` states. + +The plugin doesn't sort, search, filter, or page. Whatever shows the collection, such as a table asset, does that work on the records the plugin serves. + +## Usage + +Register the plugin with a source for each collection, and add its `commitRecordsHandler` to the app's [External State Plugin](/plugins/multiplatform/external-state) so flows can save changes: + +```ts +import { Player } from "@player-ui/player"; +import { ExternalStatePlugin } from "@player-ui/external-state-plugin"; +import { StreamingDataPlugin } from "@player-ui/streaming-data-plugin-core"; + +const streamingData = new StreamingDataPlugin({ + transactions: { + key: (transaction) => transaction.id, + async *load({ params, signal }) { + let page = 0; + let totalPages = 1; + while (page < totalPages) { + const response = await fetch( + `/accounts/${params.accountId}/transactions?page=${page}`, + { signal }, + ); + const body = await response.json(); + totalPages = body.totalPages; + page += 1; + yield { records: body.records, totalBatches: totalPages }; + } + }, + async commit(changes, { params, signal }) { + const response = await fetch( + `/accounts/${params.accountId}/transactions`, + { + method: "POST", + body: JSON.stringify(changes), + signal, + }, + ); + return response.json(); + }, + }, +}); + +const player = new Player({ + plugins: [ + streamingData, + new ExternalStatePlugin([streamingData.commitRecordsHandler]), + ], +}); +``` + +A source has three parts: + +- `key(record)` returns the record's unique key, or an empty string for a draft that hasn't been saved yet. +- `load({ params, signal })` returns an async iterable of batches. Each batch has `records`, and optionally `totalBatches`, which the plugin copies to the status. The `signal` aborts when the flow ends or a new load replaces this one. +- `commit(changes, { params, signal })` is optional. It receives the records to `create`, the records to `update` (each with its `key`, the changed fields in `patch`, and the whole `record` with them applied), and the records to `remove` (each with its `key` and the `record` the collection holds, so a source can address a delete with more than the key). It resolves with the saved `records` as the backend returned them, the `removed` keys, and the records that `failed`, each with a `key` and a `reason`. + +The plugin creates `AbortController`s for the `signal`s, and uses only `abort()`, `signal.aborted`, and `signal.addEventListener("abort", ...)`. JavaScript engines without `AbortController`, such as the ones Player uses on iOS and Android, need one added before a flow that declares a collection starts. Flows without a collection don't need it. + +## Declaring a collection + +A collection is a schema entry with a `source`: + +```json +{ + "schema": { + "ROOT": { + "transactions": { + "type": "TransactionType", + "isArray": true, + "source": { + "ref": "transactions", + "status": "transactionsStatus", + "params": { "accountId": "{{accountId}}" } + } + } + } + } +} +``` + +- `ref` names the source the app registered. +- `status` is where the plugin writes the collection's status. It defaults to `Status`. +- `params` are the source's inputs. The plugin resolves their templates when loading starts. + +A collection can sit inside nested types, but not inside an array or record entry. The plugin logs an error for a declaration it can't use and ignores it. + +## Loading + +Reading a collection never starts a load. Content starts one with the `loadStreamingData` expression, usually in a navigation `onStart`: + +```json +{ + "VIEW_transactions": { + "state_type": "VIEW", + "ref": "transactions-view", + "onStart": "loadStreamingData('transactions')", + "transitions": {} + } +} +``` + +Loading the same collection again with the same params does nothing. With different params, the plugin drops the records and loads again. After a load fails, `retryStreamingData('transactions')` starts it over. + +While a load runs, the plugin writes this status to the status binding: + +| Field | Meaning | +| ------------------------------------------------ | ----------------------------------------------------------------------------------- | +| `started`, `loading`, `completed` | Where the load is | +| `loadedBatches`, `totalBatches`, `loadedRecords` | How much has arrived | +| `error` | Why the load failed, if it did: a `message`, and a `kind` if the source gave one | +| `committing` | Whether a save is running | +| `lastCommit` | The latest save's `outcome`, `saved` and `failed` counts, `failedKeys`, and `error` | + +To show progress when the source reports `totalBatches`, divide `loadedBatches` by it, as in `{{transactionsStatus.loadedBatches}} / {{transactionsStatus.totalBatches}}`. + +When a load or save fails, `error.message` is the message of the error the source threw, and the plugin copies a string `kind` from that error to `error.kind` without interpreting it. The source defines the kinds, such as `throttled` or `unavailable`, so content can branch on a stable value instead of the message. + +## Reading records + +The collection's binding serves the plugin's array by reference, so reading `transactions` doesn't copy it and `transactions.0.amount` reads one field of one record. Records are frozen, the binding is read-only, and the collection stays out of `serialize()`. The plugin logs a warning for each write or delete it ignores. + +When records change, the plugin tells Player as narrowly as it can, so a view only resolves again what reads the change: appended records announce `transactions.length`, and a replaced record announces its own index. Removals move records, so they announce the whole collection. + +Code that keeps more than the array, such as a table's sort keys, can get the collection with `getCollection(binding)` and `subscribe` to its changes: `appended`, `updated`, `removed`, `reset`, and `committed`. + +## Saving + +Saves run in `EXTERNAL` states with the `commit-records` ref. The handler collects the changes, calls the source's `commit`, merges the returned records by key, and transitions with `saved`, `partial`, or `failed`. It never throws. + +To change every selected record, name the keys in `param.update`, a binding to copy each record to in `param.rowBinding`, and the expressions that change it in `eachRow`: + +```json +{ + "EXTERNAL_categorize": { + "state_type": "EXTERNAL", + "ref": "commit-records", + "param": { + "binding": "transactions", + "update": "selectedKeys", + "rowBinding": "row" + }, + "eachRow": ["{{row.category}} = 'travel'"], + "transitions": { + "saved": "VIEW_transactions", + "partial": "VIEW_transactions", + "failed": "VIEW_transactions" + } + } +} +``` + +`eachRow` goes on the state beside `param`, not inside it, because Player resolves the templates in `param` when the state starts. The plugin fails a save with `eachRow` inside `param` and logs why. + +`param.save` names a binding holding a draft record: a draft without a key is created, and a draft with a key saves its changed fields. `param.remove` names a binding holding the key, or keys, to remove. One state can combine all three. + +If an `eachRow` expression fails, the plugin sends nothing, not even the removals, and fails the save instead of the flow: `lastCommit.error` says why, and `failedKeys` lists every record that `update` and `remove` name. + +Player drops the current view when an `EXTERNAL` state starts. So that the view can show the save running, the handler keeps the view that started the save current until the flow moves on. If that view is an overlay that closes when the flow leaves it, such as a modal, the handler shows the view underneath instead. Tell the plugin which views are overlays with the `isOverlay` option: + +```ts +new StreamingDataPlugin(sources, { + isOverlay: (state) => state.attributes?.overlay === true, +}); +``` diff --git a/plugins/streaming-data/core/BUILD b/plugins/streaming-data/core/BUILD new file mode 100644 index 000000000..db2e16663 --- /dev/null +++ b/plugins/streaming-data/core/BUILD @@ -0,0 +1,23 @@ +load("@rules_player//javascript:defs.bzl", "js_pipeline") +load("@npm//:defs.bzl", "npm_link_all_packages") +load("//tools:defs.bzl", "tsup_config", "vitest_config") + +npm_link_all_packages(name = "node_modules") + +tsup_config(name = "tsup_config") + +vitest_config(name = "vitest_config") + +js_pipeline( + package_name = "@player-ui/streaming-data-plugin-core", + peer_deps = [ + ":node_modules/@player-ui/external-state-plugin", + ":node_modules/@player-ui/player", + ], + test_deps = [ + "//:vitest_config", + ], + deps = [ + "//:node_modules/queue-microtask", + ], +) diff --git a/plugins/streaming-data/core/package.json b/plugins/streaming-data/core/package.json new file mode 100644 index 000000000..f6395d645 --- /dev/null +++ b/plugins/streaming-data/core/package.json @@ -0,0 +1,9 @@ +{ + "name": "@player-ui/streaming-data-plugin-core", + "version": "0.0.0-PLACEHOLDER", + "main": "src/index.ts", + "peerDependencies": { + "@player-ui/external-state-plugin": "workspace:^", + "@player-ui/player": "workspace:^" + } +} diff --git a/plugins/streaming-data/core/src/CollectionState.ts b/plugins/streaming-data/core/src/CollectionState.ts new file mode 100644 index 000000000..e2f1f5600 --- /dev/null +++ b/plugins/streaming-data/core/src/CollectionState.ts @@ -0,0 +1,84 @@ +import type { BindingInstance } from "@player-ui/player"; +import type { RecordCollection } from "./RecordCollection"; +import type { + CollectionSourceDeclaration, + CollectionStatus, + RecordSource, +} from "./types"; + +/** One load of a collection: the params it resolved, and how to cancel it */ +export interface ActiveLoad { + params: Readonly>; + paramsKey: string; + controller: AbortController; +} + +export const INITIAL_STATUS: CollectionStatus = { + started: false, + loading: false, + completed: false, + loadedBatches: 0, + loadedRecords: 0, + committing: false, +}; + +/** The per-flow state of one declared collection */ +export class CollectionState { + readonly binding: BindingInstance; + + readonly declaration: CollectionSourceDeclaration; + + readonly source?: RecordSource; + + readonly collection: RecordCollection; + + private currentStatus: CollectionStatus = INITIAL_STATUS; + + private currentLoad?: ActiveLoad; + + private revisionCount = 0; + + constructor( + binding: BindingInstance, + declaration: CollectionSourceDeclaration, + collection: RecordCollection, + source?: RecordSource, + ) { + this.binding = binding; + this.declaration = declaration; + this.collection = collection; + this.source = source; + } + + get status(): CollectionStatus { + return this.currentStatus; + } + + get load(): ActiveLoad | undefined { + return this.currentLoad; + } + + /** Merges a status change; returns the new status */ + patch(change: Partial): CollectionStatus { + this.currentStatus = { ...this.currentStatus, ...change }; + return this.currentStatus; + } + + /** Starts the status over from INITIAL_STATUS, dropping the last load's error and totals */ + reset(change: Partial): CollectionStatus { + this.currentStatus = { ...INITIAL_STATUS, ...change }; + return this.currentStatus; + } + + /** Makes `load` the current load, cancelling the one before it */ + begin(load: ActiveLoad): void { + this.currentLoad?.controller.abort(); + this.currentLoad = load; + } + + /** A new value for each change notice written to the data model */ + nextRevision(): number { + this.revisionCount += 1; + return this.revisionCount; + } +} diff --git a/plugins/streaming-data/core/src/RecordCollection.ts b/plugins/streaming-data/core/src/RecordCollection.ts new file mode 100644 index 000000000..4a96f187b --- /dev/null +++ b/plugins/streaming-data/core/src/RecordCollection.ts @@ -0,0 +1,140 @@ +import type { + CollectionChange, + CollectionHandle, + CommitOutcome, +} from "./types"; + +type Listener = (change: CollectionChange) => void; + +/** What a merge changed */ +export interface MergeSummary { + /** Where the replaced records are, in the list as it was before any removal */ + updatedIndexes: number[]; + appended: number; + removed: number; +} + +// Spreading a very large batch into push() overflows the argument limit. +const PUSH_CHUNK = 10_000; + +/** + * The records of one collection, held once, frozen, and indexed by key. Changes made in place keep + * the same array, so a consumer holding it sees them; every change is announced to subscribers. + */ +export class RecordCollection implements CollectionHandle { + readonly binding: string; + + readonly statusBinding: string; + + private readonly keyOf: (record: R) => string; + + private list: R[] = []; + + private positions = new Map(); + + private readonly listeners = new Set>(); + + constructor( + binding: string, + statusBinding: string, + keyOf: (record: R) => string, + ) { + this.binding = binding; + this.statusBinding = statusBinding; + this.keyOf = keyOf; + } + + get records(): ReadonlyArray { + return this.list; + } + + key(record: R): string { + return this.keyOf(record); + } + + indexOf(key: string): number { + return this.positions.get(key) ?? -1; + } + + get(key: string): R | undefined { + const index = this.positions.get(key); + return index === undefined ? undefined : this.list[index]; + } + + subscribe(listener: Listener): () => void { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + + /** Adds a batch of loaded records; a record whose key is already held replaces that one */ + append(records: ReadonlyArray): MergeSummary { + return this.merge(records, []); + } + + /** + * Replaces held records by key, in place, adds records with new keys at the end, and drops the + * removed keys. Announces each kind of change that happened. + */ + merge( + records: ReadonlyArray, + removed: ReadonlyArray, + ): MergeSummary { + const updated: R[] = []; + const updatedIndexes: number[] = []; + const added: R[] = []; + + records.forEach((record) => { + Object.freeze(record); + const index = this.positions.get(this.keyOf(record)); + if (index === undefined) { + added.push(record); + } else { + this.list[index] = record; + updated.push(record); + updatedIndexes.push(index); + } + }); + + for (let start = 0; start < added.length; start += PUSH_CHUNK) { + const first = this.list.length; + const chunk = added.slice(start, start + PUSH_CHUNK); + this.list.push(...chunk); + chunk.forEach((record, offset) => + this.positions.set(this.keyOf(record), first + offset), + ); + } + + const gone = removed.filter((key) => this.positions.has(key)); + if (gone.length > 0) this.drop(new Set(gone)); + + if (updated.length > 0) this.emit({ type: "updated", records: updated }); + if (added.length > 0) this.emit({ type: "appended", records: added }); + if (gone.length > 0) this.emit({ type: "removed", keys: gone }); + return { updatedIndexes, appended: added.length, removed: gone.length }; + } + + /** Drops every record, before a new load replaces them */ + clear(): void { + this.list = []; + this.positions = new Map(); + this.emit({ type: "reset" }); + } + + /** Announces that a save which changed records has been merged */ + committed(outcome: CommitOutcome): void { + this.emit({ type: "committed", outcome }); + } + + private drop(keys: ReadonlySet): void { + this.list = this.list.filter((record) => !keys.has(this.keyOf(record))); + this.positions = new Map( + this.list.map((record, index) => [this.keyOf(record), index]), + ); + } + + private emit(change: CollectionChange): void { + this.listeners.forEach((listener) => listener(change)); + } +} diff --git a/plugins/streaming-data/core/src/StreamingDataPlugin.ts b/plugins/streaming-data/core/src/StreamingDataPlugin.ts new file mode 100644 index 000000000..b9ac9b102 --- /dev/null +++ b/plugins/streaming-data/core/src/StreamingDataPlugin.ts @@ -0,0 +1,707 @@ +import type { + BatchSetTransaction, + BindingInstance, + BindingParser, + DataController, + DataModelMiddleware, + ExpressionEvaluator, + ExpressionHandler, + InProgressState, + Logger, + NavigationFlowExternalState, + NavigationFlowViewState, + Player, + PlayerPlugin, + Updates, + ViewController, + ViewInstance, +} from "@player-ui/player"; +import { resolveDataRefs } from "@player-ui/player"; +import type { ExternalStateHandler } from "@player-ui/external-state-plugin"; +import queueMicrotask from "queue-microtask"; +import { collectChanges, requestedKeys } from "./collectChanges"; +import type { ChangeContext } from "./collectChanges"; +import { ActiveLoad, CollectionState } from "./CollectionState"; +import { + CollectionDeclaration, + findCollectionDeclarations, +} from "./findCollectionDeclarations"; +import { MergeSummary, RecordCollection } from "./RecordCollection"; +import { StreamingDataPluginSymbol } from "./symbols"; +import { toCommitRequest } from "./toCommitRequest"; +import type { + CollectionError, + CollectionHandle, + CollectionStatus, + CommitOutcome, + CommitResult, + LastCommit, + RecordChanges, + RecordSource, +} from "./types"; + +/** Starts loading a collection: loadStreamingData(binding) */ +export const LOAD_EXPRESSION_NAME = "loadStreamingData"; + +/** Loads a collection again after its load failed: retryStreamingData(binding) */ +export const RETRY_EXPRESSION_NAME = "retryStreamingData"; + +/** The `ref` of the EXTERNAL state that saves a collection's changes */ +export const COMMIT_RECORDS_REF = "commit-records"; + +type Controllers = InProgressState["controllers"]; + +/** Options for StreamingDataPlugin */ +export interface StreamingDataPluginOptions { + /** + * Whether a VIEW state shows as an overlay that closes when the flow leaves it, such as a + * modal. A save started from an overlay shows the last view underneath it instead. + */ + isOverlay?: (state: NavigationFlowViewState) => boolean; +} + +// Player compares every changed binding with every binding each node read, so a long list of +// notices costs more than resolving everything once. +const MAX_RECORD_NOTICES = 50; + +const messageOf = (error: unknown): string => + error instanceof Error ? error.message : String(error); + +const isIndexable = ( + value: unknown, +): value is Record => + typeof value === "object" && value !== null; + +/** The thrown error's message and, when it carries a string `kind`, that kind */ +const toCollectionError = (error: unknown): CollectionError => { + const kind = isIndexable(error) ? error.kind : undefined; + return { + message: messageOf(error), + ...(typeof kind === "string" ? { kind } : undefined), + }; +}; + +/** Walks a relative binding path into a value without copying anything */ +const getIn = (value: unknown, path: ReadonlyArray): unknown => + path.reduce( + (current, segment) => (isIndexable(current) ? current[segment] : undefined), + value, + ); + +/** Whether two dotted bindings are equal or one sits underneath the other */ +const overlaps = (a: string, b: string): boolean => { + const left = a.split("."); + const right = b.split("."); + const shared = Math.min(left.length, right.length); + return left + .slice(0, shared) + .every((segment, index) => segment === right[index]); +}; + +const failedCommit = ( + failedKeys: string[], + error?: CollectionError, +): LastCommit => ({ + outcome: "failed", + saved: 0, + failed: failedKeys.length, + failedKeys, + ...(error ? { error } : undefined), +}); + +const outcomeOf = (result: CommitResult): CommitOutcome => { + if (result.failed.length === 0) return "saved"; + return result.records.length + result.removed.length > 0 + ? "partial" + : "failed"; +}; + +const keysOf = (changes: RecordChanges): string[] => [ + ...changes.update.map(({ key }) => key), + ...changes.remove.map(({ key }) => key), +]; + +/** + * Loads large collections into Player in batches without storing them in the data model. + * + * A flow declares each collection in its schema, with the source that loads it, the binding its + * status goes to, and the source's params. The app registers sources by name. Content starts a + * load with loadStreamingData(binding), usually in a navigation onStart; reads never start one. + * The plugin holds each record once, serves the array by reference at the collection's binding, + * writes status to the status binding, and tells subscribers what changed. The collection's + * binding is read-only and stays out of the serialized data model. + * + * Saves run in `commit-records` EXTERNAL states through commitRecordsHandler, which the app adds to + * its ExternalStatePlugin: the handler collects the changes, calls the source's commit, merges the + * returned records by key, and returns `saved`, `partial`, or `failed`. It never throws. Player + * drops the current view when an EXTERNAL state starts, so the handler keeps the view that started + * the save current, and updating, until the flow moves on; that view can show the save's progress. + * A save started from an overlay (see StreamingDataPluginOptions) shows the view underneath it. + * + * The plugin doesn't sort, search, filter, or page; whatever shows the collection does. + */ +export class StreamingDataPlugin implements PlayerPlugin { + name = "StreamingDataPlugin"; + + readonly symbol: symbol = StreamingDataPluginSymbol; + + /** The handler for `commit-records` EXTERNAL states; see the class description */ + readonly commitRecordsHandler: ExternalStateHandler; + + private readonly sources: ReadonlyMap>; + + /** Authorizes this plugin's own change notices through the middleware */ + private readonly writeSymbol: symbol = Symbol("streaming-data-refresh"); + + private declared: CollectionDeclaration[] = []; + + // Per-flow state, replaced whenever a new flow starts. + private states = new Map(); + + /** The same states as a list, since every data model read checks them */ + private stateList: CollectionState[] = []; + + private flowAbort?: AbortController; + + private dataController?: DataController; + + private parser?: BindingParser; + + private evaluator?: ExpressionEvaluator; + + private viewController?: ViewController; + + private lastView?: ViewInstance; + + private lastViewState?: NavigationFlowViewState; + + /** The last VIEW state that wasn't an overlay */ + private backgroundState?: NavigationFlowViewState; + + private readonly isOverlay: (state: NavigationFlowViewState) => boolean; + + private logger?: Logger; + + constructor( + sources: Readonly>>, + options: StreamingDataPluginOptions = {}, + ) { + this.sources = new Map(Object.entries(sources)); + this.isOverlay = options.isOverlay ?? (() => false); + this.commitRecordsHandler = { + ref: COMMIT_RECORDS_REF, + handlerFunction: (state, controllers) => + this.commitRecords(state, controllers), + }; + } + + apply(player: Player): void { + this.logger = player.logger; + + player.hooks.schema.tap(this.name, (schema) => { + const { declarations, problems } = findCollectionDeclarations( + schema.schema, + ); + problems.forEach(({ binding, problem }) => + this.logger?.error( + `[${this.name}] Ignoring the source declared at '${binding}': ${problem}`, + ), + ); + this.declared = declarations; + }); + + player.hooks.bindingParser.tap(this.name, (parser) => { + this.parser = parser; + }); + + player.hooks.expressionEvaluator.tap(this.name, (evaluator) => { + this.evaluator = evaluator; + evaluator.addExpressionFunction(LOAD_EXPRESSION_NAME, this.loadHandler); + evaluator.addExpressionFunction(RETRY_EXPRESSION_NAME, this.retryHandler); + }); + + player.hooks.dataController.tap(this.name, (dataController) => + this.startFlow(dataController), + ); + + player.hooks.viewController.tap(this.name, (viewController) => { + this.viewController = viewController; + }); + + player.hooks.view.tap(this.name, (view) => { + this.lastView = view; + }); + + player.hooks.flowController.tap(this.name, (flowController) => { + flowController.hooks.flow.tap(this.name, (flow) => { + flow.hooks.transition.tap(this.name, (_from, to) => { + if (to.value.state_type !== "VIEW") return; + this.lastViewState = to.value; + if (!this.isOverlay(to.value)) this.backgroundState = to.value; + }); + }); + }); + + player.hooks.onEnd.tap(this.name, () => this.teardownFlow()); + } + + /** The collection at `binding` in the current flow, for consumers such as a table */ + getCollection(binding: string): CollectionHandle | undefined { + return this.find(binding)?.collection; + } + + /** The status of the collection at `binding` */ + getStatus(binding: string): CollectionStatus | undefined { + return this.find(binding)?.status; + } + + /** + * Starts loading the collection at `binding`. Does nothing if it already started with the same + * params; with different params, drops the records and loads again. + */ + load(binding: string): void { + const state = this.find(binding); + if (state) this.start(state, false); + } + + /** Loads the collection at `binding` again, if its last load failed */ + retry(binding: string): void { + const state = this.find(binding); + if (state) this.start(state, true); + } + + /** Saves `changes` through the collection's source; see commitRecordsHandler */ + async commit( + binding: string, + changes: RecordChanges, + ): Promise { + const state = this.find(binding); + return state ? this.commitChanges(state, changes) : "failed"; + } + + /** Changes records locally, without saving: merges `records` by key and drops `removed` */ + merge(binding: string, records: object[], removed: string[] = []): void { + const state = this.find(binding); + if (!state) return; + const change = state.collection.merge(records, removed); + this.patchStatus(state, { loadedRecords: state.collection.records.length }); + this.notifyChanged(state, change); + } + + private readonly middleware: DataModelMiddleware = { + name: "streaming-data", + + get: (binding, options, next) => { + const state = this.match(binding); + if (!state) return next?.get(binding, options); + const relative = binding.relative(state.binding); + const { records } = state.collection; + return relative.length === 0 ? records : getIn(records, relative); + }, + + set: (transaction, options, next) => { + const ours: BatchSetTransaction = []; + const others: BatchSetTransaction = []; + transaction.forEach((entry) => + (this.match(entry[0]) ? ours : others).push(entry), + ); + if (ours.length === 0) return next?.set(transaction, options) ?? []; + + const passed = + others.length > 0 ? (next?.set(others, options) ?? []) : []; + if (options?.writeSymbol !== this.writeSymbol) { + ours.forEach(([binding]) => + this.logger?.warn( + `[${this.name}] Ignoring a write to read-only ${binding.asString()}`, + ), + ); + return passed; + } + // A change notice: nothing to store, but subscribers re-read the binding. + const notices: Updates = ours.map(([binding, value]) => ({ + binding, + oldValue: undefined, + newValue: value, + force: true, + })); + return [...passed, ...notices]; + }, + + delete: (binding, options, next) => { + if (this.match(binding)) { + this.logger?.warn( + `[${this.name}] Ignoring a delete of read-only ${binding.asString()}`, + ); + return undefined; + } + return next?.delete(binding, options); + }, + }; + + private startFlow(dataController: DataController): void { + this.teardownFlow(); + this.dataController = dataController; + this.states = this.createStates(); + this.stateList = [...this.states.values()]; + // Some JS engines, such as Player's iOS and Android ones, have no AbortController; a flow + // without a collection must still run there. + const flowAbort = + this.stateList.length > 0 ? new AbortController() : undefined; + this.flowAbort = flowAbort; + + dataController.hooks.resolveDataStages.tap(this.name, (pipeline) => [ + ...pipeline, + this.middleware, + ]); + + // Player is still setting up the flow, including validation, when this hook runs. + queueMicrotask(() => { + if (this.dataController !== dataController || flowAbort?.signal.aborted) + return; + this.states.forEach((state) => this.patchStatus(state, {})); + }); + } + + private createStates(): Map { + const { parser } = this; + const states = new Map(); + if (!parser) return states; + const used: string[] = []; + + this.declared.forEach(({ binding, source: declaration }) => { + const parsed = parser.parse(binding); + const bindingString = parsed.asString(); + const statusBinding = parser + .parse(declaration.status ?? `${binding}Status`) + .asString(); + const clash = used.find( + (other) => + overlaps(other, bindingString) || overlaps(other, statusBinding), + ); + if (clash || overlaps(bindingString, statusBinding)) { + this.logger?.error( + `[${this.name}] Ignoring '${binding}': it or its status overlaps '${ + clash ?? statusBinding + }'`, + ); + return; + } + used.push(bindingString, statusBinding); + + const source = this.sources.get(declaration.ref); + const keyOf = (record: object): string => source?.key(record) ?? ""; + const collection = new RecordCollection( + bindingString, + statusBinding, + keyOf, + ); + states.set( + bindingString, + new CollectionState(parsed, declaration, collection, source), + ); + }); + + return states; + } + + private resolveParams( + state: CollectionState, + ): Readonly> { + const { dataController, evaluator } = this; + const params = state.declaration.params ?? {}; + if (!dataController) return params; + return resolveDataRefs(params, { + model: dataController, + evaluate: evaluator + ? (expression) => evaluator.evaluate(expression) + : false, + formatted: false, + }); + } + + private start(state: CollectionState, retry: boolean): void { + const { flowAbort } = this; + if (!flowAbort || (retry && !state.status.error)) return; + + const params = this.resolveParams(state); + const paramsKey = JSON.stringify(params); + if (!retry && state.load?.paramsKey === paramsKey) return; + + const controller = new AbortController(); + flowAbort.signal.addEventListener("abort", () => controller.abort(), { + once: true, + }); + const load: ActiveLoad = { params, paramsKey, controller }; + state.begin(load); + // Started outside the expression or read that asked for it, which mustn't write to the model. + queueMicrotask(() => { + this.run(state, load); + }); + } + + private async run(state: CollectionState, load: ActiveLoad): Promise { + const { dataController } = this; + const isCurrent = (): boolean => + !load.controller.signal.aborted && + state.load === load && + this.dataController === dataController; + if (!isCurrent()) return; + + if (state.collection.records.length > 0) { + state.collection.clear(); + this.notifyChanged(state); + } + const { committing, lastCommit } = state.status; + this.writeStatus( + state, + state.reset({ committing, lastCommit, started: true, loading: true }), + ); + + const { source } = state; + if (!source) { + this.patchStatus(state, { + loading: false, + error: { + message: `No source is registered as '${state.declaration.ref}'`, + }, + }); + return; + } + + try { + for await (const batch of source.load({ + params: load.params, + signal: load.controller.signal, + })) { + if (!isCurrent()) return; + const change = state.collection.append(batch.records); + const loadedBatches = state.status.loadedBatches + 1; + const totalBatches = batch.totalBatches ?? state.status.totalBatches; + this.patchStatus(state, { + loadedBatches, + totalBatches, + loadedRecords: state.collection.records.length, + }); + this.notifyChanged(state, change); + } + if (isCurrent()) + this.patchStatus(state, { loading: false, completed: true }); + } catch (error) { + if (!isCurrent()) return; + const reason = toCollectionError(error); + this.logger?.error( + `[${this.name}] Loading '${state.collection.binding}' failed: ${reason.message}`, + ); + this.patchStatus(state, { loading: false, error: reason }); + } + } + + /** + * Gives Player a current view again after the save's EXTERNAL state dropped it: the view that + * started the save, or the view underneath it when that one is an overlay. + * + * Player has no supported way to keep a view current through an EXTERNAL state, so this sets + * `currentView` itself, and for an overlay builds a new instance of the view underneath, which + * view plugins such as beacons see as a new view. Replace it once Player core has such an API. + */ + private showViewDuringSave(): void { + const { viewController, lastView, lastViewState, backgroundState } = this; + if (!viewController || viewController.currentView) return; + if (lastViewState && this.isOverlay(lastViewState)) { + if (backgroundState) viewController.onView(backgroundState); + } else if (lastView) { + viewController.currentView = lastView; + } + } + + private async commitRecords( + externalState: NavigationFlowExternalState, + controllers: Controllers, + ): Promise { + this.showViewDuringSave(); + const request = toCommitRequest(externalState); + if ("problem" in request) { + this.logger?.error(`[${this.name}] Can't save: ${request.problem}`); + return "failed"; + } + const state = this.find(request.binding); + if (!state) return "failed"; + + const { data, expression } = controllers; + const context: ChangeContext = { + get: (binding) => data.get(binding), + set: (binding, value) => { + data.set([[binding, value]]); + }, + delete: (binding) => data.delete(binding), + // Otherwise Player fails the flow and the expression returns, so the save would still send + // what the earlier expressions changed. + evaluate: (exp) => + expression.evaluate(exp, { model: data, throwErrors: true }), + }; + try { + const changes = collectChanges(state.collection, request, context); + return await this.commitChanges(state, changes); + } catch (error) { + const reason = toCollectionError(error); + this.logger?.error( + `[${this.name}] Saving '${request.binding}' failed: ${reason.message}`, + ); + this.patchStatus(state, { + committing: false, + lastCommit: failedCommit( + requestedKeys(state.collection, request, context), + reason, + ), + }); + return "failed"; + } + } + + private async commitChanges( + state: CollectionState, + changes: RecordChanges, + ): Promise { + const { dataController, flowAbort } = this; + const count = + changes.create.length + changes.update.length + changes.remove.length; + if (count === 0) { + this.patchStatus(state, { + lastCommit: { outcome: "saved", saved: 0, failed: 0, failedKeys: [] }, + }); + state.collection.committed("saved"); + return "saved"; + } + + const { source } = state; + if (!source?.commit || !flowAbort) { + this.patchStatus(state, { + lastCommit: failedCommit(keysOf(changes), { + message: "This collection's source can't save.", + }), + }); + return "failed"; + } + + this.patchStatus(state, { committing: true }); + try { + const params = state.load?.params ?? this.resolveParams(state); + const result = await source.commit(changes, { + params, + signal: flowAbort.signal, + }); + // The flow ended while the save ran; its records are gone. + if (this.dataController !== dataController) return outcomeOf(result); + + const change = state.collection.merge(result.records, result.removed); + const outcome = outcomeOf(result); + const saved = result.records.length + result.removed.length; + this.patchStatus(state, { + committing: false, + loadedRecords: state.collection.records.length, + lastCommit: { + outcome, + saved, + failed: result.failed.length, + failedKeys: result.failed.map(({ key }) => key), + }, + }); + if (saved > 0) state.collection.committed(outcome); + this.notifyChanged(state, change); + return outcome; + } catch (error) { + const reason = toCollectionError(error); + if (this.dataController === dataController) { + this.logger?.error( + `[${this.name}] Saving '${state.collection.binding}' failed: ${reason.message}`, + ); + this.patchStatus(state, { + committing: false, + lastCommit: failedCommit(keysOf(changes), reason), + }); + } + return "failed"; + } + } + + /** Merges a status change and writes it to the status binding */ + private patchStatus( + state: CollectionState, + change: Partial, + ): void { + this.writeStatus(state, state.patch(change)); + } + + private writeStatus(state: CollectionState, status: CollectionStatus): void { + this.dataController?.set([[state.collection.statusBinding, status]]); + } + + /** + * Tells Player what changed, so whatever reads it resolves again. Player treats a change as + * touching every binding inside it, so announcing the whole collection would resolve every row a + * view shows. Appends announce `.length`, which only readers of the whole list care + * about, and replaced records announce their own indexes. Removals move records to other + * indexes, so they announce the whole collection, as a merge too big to list does. + */ + private notifyChanged(state: CollectionState, change?: MergeSummary): void { + const { binding } = state.collection; + const bindings = + change && + change.removed === 0 && + change.updatedIndexes.length <= MAX_RECORD_NOTICES + ? [ + ...change.updatedIndexes.map((index) => `${binding}.${index}`), + ...(change.appended > 0 ? [`${binding}.length`] : []), + ] + : [binding]; + if (bindings.length === 0) return; + const revision = state.nextRevision(); + this.dataController?.set( + bindings.map((changed) => [changed, revision]), + { writeSymbol: this.writeSymbol }, + ); + } + + private match(binding: BindingInstance): CollectionState | undefined { + return this.stateList.find((state) => state.binding.contains(binding)); + } + + private find(binding: string): CollectionState | undefined { + const state = + this.states.get(binding) ?? + (this.parser + ? this.states.get(this.parser.parse(binding).asString()) + : undefined); + if (!state) + this.logger?.warn( + `[${this.name}] No collection is declared at '${binding}'`, + ); + return state; + } + + private teardownFlow(): void { + this.flowAbort?.abort(); + this.flowAbort = undefined; + this.dataController = undefined; + this.lastView = undefined; + this.lastViewState = undefined; + this.backgroundState = undefined; + // Dropped so a large collection can be collected as soon as the flow ends. + this.states = new Map(); + this.stateList = []; + } + + private readonly loadHandler: ExpressionHandler<[string]> = ( + context, + binding, + ) => { + this.load(binding); + }; + + private readonly retryHandler: ExpressionHandler<[string]> = ( + context, + binding, + ) => { + this.retry(binding); + }; +} diff --git a/plugins/streaming-data/core/src/__tests__/RecordCollection.test.ts b/plugins/streaming-data/core/src/__tests__/RecordCollection.test.ts new file mode 100644 index 000000000..63f43b032 --- /dev/null +++ b/plugins/streaming-data/core/src/__tests__/RecordCollection.test.ts @@ -0,0 +1,107 @@ +import { describe, it, expect } from "vitest"; +import { RecordCollection } from "../RecordCollection"; +import type { CollectionChange } from "../types"; + +interface Item { + id: string; + name: string; +} + +const item = (id: string, name = id.toUpperCase()): Item => ({ id, name }); + +const collectionOf = (...items: Item[]) => { + const collection = new RecordCollection( + "items", + "itemsStatus", + ({ id }) => id, + ); + const changes: Array> = []; + collection.append(items); + collection.subscribe((change) => changes.push(change)); + return { collection, changes }; +}; + +describe("RecordCollection", () => { + it("appends to the same list, freezes each record, and indexes it by key", () => { + const { collection, changes } = collectionOf(item("a")); + const list = collection.records; + + expect(collection.append([item("b"), item("c")])).toEqual({ + updatedIndexes: [], + appended: 2, + removed: 0, + }); + expect(collection.records).toBe(list); + expect(collection.records.map(({ id }) => id)).toEqual(["a", "b", "c"]); + expect(Object.isFrozen(collection.get("c"))).toBe(true); + expect(collection.indexOf("b")).toBe(1); + expect(collection.indexOf("z")).toBe(-1); + expect(changes).toEqual([ + { type: "appended", records: [item("b"), item("c")] }, + ]); + }); + + it("replaces records by key in place and reports where they are", () => { + const { collection, changes } = collectionOf( + item("a"), + item("b"), + item("c"), + ); + const list = collection.records; + + expect(collection.merge([item("c", "C2"), item("d")], [])).toEqual({ + updatedIndexes: [2], + appended: 1, + removed: 0, + }); + expect(collection.records).toBe(list); + expect(collection.get("c")?.name).toBe("C2"); + expect(changes.map(({ type }) => type)).toEqual(["updated", "appended"]); + }); + + it("drops removed keys into a new list and re-indexes the rest", () => { + const { collection, changes } = collectionOf( + item("a"), + item("b"), + item("c"), + ); + const list = collection.records; + + expect(collection.merge([], ["a", "missing"])).toEqual({ + updatedIndexes: [], + appended: 0, + removed: 1, + }); + expect(collection.records).not.toBe(list); + expect(collection.indexOf("c")).toBe(1); + expect(changes).toEqual([{ type: "removed", keys: ["a"] }]); + }); + + it("appends a batch too large to spread into one push", () => { + const { collection } = collectionOf(); + const many = Array.from({ length: 25_000 }, (_, index) => + item(`k${index}`), + ); + + collection.append(many); + + expect(collection.records).toHaveLength(25_000); + expect(collection.indexOf("k24999")).toBe(24_999); + }); + + it("announces a reset, and a merged save, to subscribers until they stop listening", () => { + const { collection, changes } = collectionOf(item("a")); + const stop = collection.subscribe(() => undefined); + + collection.committed("partial"); + collection.clear(); + stop(); + + expect(changes).toEqual([ + { type: "committed", outcome: "partial" }, + { type: "reset" }, + ]); + expect(collection.records).toEqual([]); + expect(collection.indexOf("a")).toBe(-1); + }); +}); diff --git a/plugins/streaming-data/core/src/__tests__/StreamingDataPlugin.test.ts b/plugins/streaming-data/core/src/__tests__/StreamingDataPlugin.test.ts new file mode 100644 index 000000000..50fd59059 --- /dev/null +++ b/plugins/streaming-data/core/src/__tests__/StreamingDataPlugin.test.ts @@ -0,0 +1,784 @@ +import { describe, it, expect, vitest } from "vitest"; +import { Player } from "@player-ui/player"; +import type { Flow, Logger, PlayerPlugin } from "@player-ui/player"; +import { ExternalStatePlugin } from "@player-ui/external-state-plugin"; +import { StreamingDataPlugin } from ".."; +import type { + CommitResult, + RecordBatch, + RecordChanges, + RecordSource, + SourceContext, +} from ".."; + +interface Item { + id: string; + name: string; +} + +const item = (id: string, name = id.toUpperCase()): Item => ({ id, name }); + +const RETURNS = { + saved: "VIEW_main", + partial: "VIEW_main", + failed: "VIEW_main", +}; + +const flow: Flow = { + id: "streaming-data-test", + views: [ + { + id: "main", + type: "info", + saving: { + asset: { + id: "saving", + type: "text", + value: "Saving: {{itemsStatus.committing}}", + }, + }, + }, + { id: "form", type: "info" }, + ], + schema: { + ROOT: { + items: { + type: "ItemType", + isArray: true, + source: { + ref: "items", + status: "itemsStatus", + params: { group: "{{group}}" }, + }, + }, + }, + ItemType: { id: { type: "StringType" }, name: { type: "StringType" } }, + }, + data: { group: "g1" }, + navigation: { + BEGIN: "FLOW_1", + FLOW_1: { + startState: "VIEW_main", + VIEW_main: { + state_type: "VIEW", + ref: "main", + transitions: { + Rename: "EXTERNAL_rename", + Remove: "EXTERNAL_remove", + Misplaced: "EXTERNAL_misplaced", + Broken: "EXTERNAL_broken", + Form: "VIEW_form", + Done: "END_done", + }, + }, + VIEW_form: { + state_type: "VIEW", + ref: "form", + attributes: { overlay: true }, + transitions: { Rename: "EXTERNAL_rename" }, + }, + EXTERNAL_rename: { + state_type: "EXTERNAL", + ref: "commit-records", + param: { binding: "items", update: "selected", rowBinding: "row" }, + eachRow: ["{{row.name}} = 'renamed'"], + transitions: RETURNS, + }, + EXTERNAL_remove: { + state_type: "EXTERNAL", + ref: "commit-records", + param: { binding: "items", remove: "selected" }, + transitions: RETURNS, + }, + EXTERNAL_misplaced: { + state_type: "EXTERNAL", + ref: "commit-records", + param: { + binding: "items", + update: "selected", + rowBinding: "row", + eachRow: ["{{row.name}} = 'renamed'"], + }, + transitions: RETURNS, + }, + EXTERNAL_broken: { + state_type: "EXTERNAL", + ref: "commit-records", + param: { + binding: "items", + update: "selected", + remove: "doomed", + rowBinding: "row", + }, + eachRow: ["{{row.name}} = 'renamed'", "missing()"], + transitions: RETURNS, + }, + END_done: { state_type: "END", outcome: "done" }, + }, + }, +}; + +/** Saves every change it's given */ +const saveAll = (changes: RecordChanges): CommitResult => ({ + records: changes.update.map(({ record }) => record), + removed: changes.remove.map(({ key }) => key), + failed: [], +}); + +/** A source whose batches, failures, and saves the test controls */ +const feed = ( + commitWith: ((changes: RecordChanges) => CommitResult) | null, +) => { + const queue: Array | Error | "end"> = []; + let wake: (() => void) | undefined; + const loads: SourceContext[] = []; + const commits: Array> = []; + let held: Promise | undefined; + + const send = (next: RecordBatch | Error | "end") => { + queue.push(next); + wake?.(); + wake = undefined; + }; + const nextSent = () => + new Promise((resolve) => { + wake = resolve; + }); + async function* batches(): AsyncGenerator> { + for (;;) { + if (queue.length === 0) await nextSent(); + const next = queue.shift(); + if (next === "end" || next === undefined) return; + if (next instanceof Error) throw next; + yield next; + } + } + const source: RecordSource = { + key: ({ id }) => id, + load: (context) => { + loads.push(context); + return batches(); + }, + ...(commitWith && { + commit: async (changes) => { + commits.push(changes); + if (held) await held; + return commitWith(changes); + }, + }), + }; + /** Makes saves wait until the function it returns is called */ + const holdSaves = () => { + let release = () => {}; + held = new Promise((resolve) => { + release = resolve; + }); + return release; + }; + return { + source, + loads, + commits, + holdSaves, + push: (records: Item[], totalBatches?: number) => + send({ records, totalBatches }), + end: () => send("end"), + fail: (message: string, kind?: unknown) => + send( + kind === undefined + ? new Error(message) + : Object.assign(new Error(message), { kind }), + ), + }; +}; + +/** Reads data while the flow is being set up, before plugins after it tap the data pipeline */ +class ReadsDataEarlyPlugin implements PlayerPlugin { + name = "reads-data-early"; + + apply(player: Player) { + player.hooks.dataController.tap(this.name, (dataController) => { + dataController.get("group"); + }); + } +} + +interface SetupOptions { + content?: Flow; + commitWith?: ((changes: RecordChanges) => CommitResult) | null; + pluginsBefore?: PlayerPlugin[]; +} + +const setup = ({ + content = flow, + commitWith = saveAll, + pluginsBefore = [], +}: SetupOptions = {}) => { + const source = feed(commitWith); + const plugin = new StreamingDataPlugin( + { items: source.source }, + { + isOverlay: (state) => + (state as { attributes?: { overlay?: boolean } }).attributes + ?.overlay === true, + }, + ); + const player = new Player({ + plugins: [ + ...pluginsBefore, + plugin, + new ExternalStatePlugin([plugin.commitRecordsHandler]), + ], + }); + const log = { warn: vitest.fn(), error: vitest.fn() }; + const ignore = () => undefined; + const handler: Logger = { + trace: ignore, + debug: ignore, + info: ignore, + ...log, + }; + player.logger.addHandler(handler); + const announced: string[] = []; + player.hooks.dataController.tap("test", (dataController) => { + dataController.hooks.onUpdate.tap("test", (updates) => + updates.forEach(({ binding }) => announced.push(binding.asString())), + ); + }); + const done = player.start(content).catch(() => undefined); + + const controllers = () => { + const state = player.getState(); + if (state.status !== "in-progress") + throw new Error(`The flow is ${state.status}`); + return state.controllers; + }; + const get = (binding: string) => controllers().data.get(binding); + const status = () => get("itemsStatus"); + const evaluate = (expression: string) => + controllers().expression.evaluate(expression); + const stateName = () => controllers().flow.current?.currentState?.name; + const saving = () => + controllers().view.currentView?.lastUpdate?.saving?.asset?.value; + const viewId = () => controllers().view.currentView?.lastUpdate?.id; + return { + ...source, + plugin, + player, + done, + log, + announced, + get, + status, + evaluate, + stateName, + saving, + viewId, + controllers, + }; +}; + +type Setup = ReturnType; + +const loadAll = async (test: Setup, items: Item[]) => { + test.evaluate("loadStreamingData('items')"); + test.push(items); + test.end(); + await vitest.waitFor(() => expect(test.status()?.completed).toBe(true)); +}; + +const names = (test: Setup) => test.get("items").map(({ name }: Item) => name); + +describe("StreamingDataPlugin", () => { + it("loads only when content asks, with its params resolved, and serves the records by reference", async () => { + const test = setup(); + await vitest.waitFor(() => + expect(test.status()).toMatchObject({ started: false, loading: false }), + ); + expect(test.get("items")).toEqual([]); + expect(test.loads).toHaveLength(0); + + test.evaluate("loadStreamingData('items')"); + test.push([item("a"), item("b")], 2); + await vitest.waitFor(() => + expect(test.status()).toMatchObject({ loadedBatches: 1 }), + ); + + expect(test.loads[0]?.params).toEqual({ group: "g1" }); + expect(test.status()).toMatchObject({ + started: true, + loading: true, + completed: false, + totalBatches: 2, + loadedRecords: 2, + }); + expect(test.get("items")).toBe(test.plugin.getCollection("items")?.records); + expect(test.get("items.1.name")).toBe("B"); + expect(Object.isFrozen(test.get("items.0"))).toBe(true); + + test.push([item("c")]); + test.end(); + await vitest.waitFor(() => + expect(test.status()).toMatchObject({ completed: true, loading: false }), + ); + expect(test.status()).toMatchObject({ loadedBatches: 2, loadedRecords: 3 }); + expect(test.player.getState().status).toBe("in-progress"); + }); + + it("serves the collection when a plugin registered before it already read data", async () => { + const test = setup({ pluginsBefore: [new ReadsDataEarlyPlugin()] }); + await loadAll(test, [item("a")]); + + expect(test.get("items")).toHaveLength(1); + expect(test.get("items.0.name")).toBe("A"); + }); + + it("keeps the collection read-only and out of the serialized data", async () => { + const test = setup(); + await loadAll(test, [item("a")]); + + test.controllers().data.set([["items.0.name", "changed"]]); + + expect(test.get("items.0.name")).toBe("A"); + expect(test.log.warn).toHaveBeenCalledWith( + "[StreamingDataPlugin] Ignoring a write to read-only items.0.name", + ); + + test.controllers().data.delete("items.0"); + + expect(test.get("items")).toHaveLength(1); + expect(test.log.warn).toHaveBeenCalledWith( + "[StreamingDataPlugin] Ignoring a delete of read-only items.0", + ); + expect(test.controllers().data.serialize()).not.toHaveProperty("items"); + }); + + it("logs mistakes in declared sources, and ignores what they would have declared", async () => { + const test = setup({ + content: { + ...flow, + schema: { + ...flow.schema, + ROOT: { + ...flow.schema?.ROOT, + broken: { type: "ItemType", isArray: true, source: { ref: "" } }, + copies: { + type: "ItemType", + isArray: true, + source: { ref: "items", status: "itemsStatus" }, + }, + nested: { + type: "ItemType", + isArray: true, + source: { ref: "items", status: "nested.status" }, + }, + unknown: { + type: "ItemType", + isArray: true, + source: { ref: "nowhere" }, + }, + }, + }, + }, + }); + await vitest.waitFor(() => + expect(test.status()).toMatchObject({ started: false }), + ); + + expect(test.log.error.mock.calls.map(([message]) => message)).toEqual([ + "[StreamingDataPlugin] Ignoring the source declared at 'broken': `ref` must name a source", + "[StreamingDataPlugin] Ignoring 'copies': it or its status overlaps 'itemsStatus'", + "[StreamingDataPlugin] Ignoring 'nested': it or its status overlaps 'nested.status'", + ]); + + test.evaluate("loadStreamingData('copies')"); + expect(test.log.warn).toHaveBeenCalledWith( + "[StreamingDataPlugin] No collection is declared at 'copies'", + ); + + test.evaluate("loadStreamingData('unknown')"); + await vitest.waitFor(() => + expect(test.get("unknownStatus")).toMatchObject({ + loading: false, + error: { message: "No source is registered as 'nowhere'" }, + }), + ); + }); + + it("announces appends at the length and replaced records at their indexes, so readers of other records stay put", async () => { + const test = setup(); + test.evaluate("loadStreamingData('items')"); + test.push([item("a"), item("b"), item("c")]); + await vitest.waitFor(() => expect(test.status()?.loadedRecords).toBe(3)); + expect(test.announced).toContain("items.length"); + expect(test.announced).not.toContain("items"); + + test.announced.length = 0; + test.plugin.merge("items", [item("b", "B2")]); + expect(test.announced).toContain("items.1"); + expect(test.announced).not.toContain("items"); + expect(test.announced).not.toContain("items.length"); + + test.announced.length = 0; + test.plugin.merge("items", [], ["a"]); + expect(test.announced).toContain("items"); + }); + + it("ignores a second load with the same params, and starts over when the params change", async () => { + const test = setup(); + await loadAll(test, [item("a")]); + + test.evaluate("loadStreamingData('items')"); + await Promise.resolve(); + expect(test.loads).toHaveLength(1); + + test.controllers().data.set([["group", "g2"]]); + test.evaluate("loadStreamingData('items')"); + await vitest.waitFor(() => expect(test.loads).toHaveLength(2)); + + expect(test.loads[0]?.signal.aborted).toBe(true); + expect(test.loads[1]?.params).toEqual({ group: "g2" }); + expect(test.get("items")).toEqual([]); + expect(test.status()).toMatchObject({ loading: true, loadedRecords: 0 }); + }); + + it("starts over when Try again follows a failed load", async () => { + const test = setup(); + test.evaluate("loadStreamingData('items')"); + test.push([item("a")], 3); + test.fail("Offline"); + await vitest.waitFor(() => + expect(test.status()?.error).toStrictEqual({ message: "Offline" }), + ); + expect(test.status()).toMatchObject({ loading: false, loadedRecords: 1 }); + + test.evaluate("retryStreamingData('items')"); + await vitest.waitFor(() => expect(test.loads).toHaveLength(2)); + expect(test.status()).toMatchObject({ + started: true, + loading: true, + loadedBatches: 0, + loadedRecords: 0, + }); + expect(test.status()?.error).toBeUndefined(); + expect(test.status()?.totalBatches).toBeUndefined(); + expect(test.get("items")).toEqual([]); + + test.push([item("a")]); + test.end(); + await vitest.waitFor(() => expect(test.status()?.completed).toBe(true)); + expect(test.get("items")).toHaveLength(1); + }); + + it("puts a string kind from a failed load on the status's error, and drops it with the error", async () => { + const test = setup(); + test.evaluate("loadStreamingData('items')"); + test.fail("Busy", "throttled"); + await vitest.waitFor(() => + expect(test.status()?.error).toStrictEqual({ + message: "Busy", + kind: "throttled", + }), + ); + + test.evaluate("retryStreamingData('items')"); + await vitest.waitFor(() => expect(test.loads).toHaveLength(2)); + expect(test.status()?.error).toBeUndefined(); + + test.fail("Odd", 42); + await vitest.waitFor(() => + expect(test.status()?.error).toStrictEqual({ message: "Odd" }), + ); + }); + + it("cancels the load and drops the records when the flow ends", async () => { + const test = setup(); + test.evaluate("loadStreamingData('items')"); + test.push([item("a")], 2); + await vitest.waitFor(() => expect(test.status()?.loadedRecords).toBe(1)); + + test.controllers().flow.transition("Done"); + await test.done; + + await vitest.waitFor(() => + expect(test.loads[0]?.signal.aborted).toBe(true), + ); + expect(test.plugin.getCollection("items")).toBeUndefined(); + }); + + it("runs a flow that declares no collection where AbortController doesn't exist", async () => { + vitest.stubGlobal("AbortController", undefined); + try { + const test = setup({ content: { ...flow, schema: undefined } }); + await vitest.waitFor(() => + expect(test.player.getState().status).toBe("in-progress"), + ); + test.controllers().flow.transition("Done"); + await test.done; + expect(test.player.getState().status).toBe("completed"); + } finally { + vitest.unstubAllGlobals(); + } + }); + + it("saves the changes eachRow makes to each selected record, merges what the source returns, and transitions by outcome", async () => { + const test = setup(); + await loadAll(test, [item("a"), item("b"), item("c")]); + test.controllers().data.set([["selected", ["a", "c"]]]); + + test.controllers().flow.transition("Rename"); + await vitest.waitFor(() => + expect(test.status()?.lastCommit?.outcome).toBe("saved"), + ); + await vitest.waitFor(() => expect(test.stateName()).toBe("VIEW_main")); + + expect(test.commits).toHaveLength(1); + expect(test.commits[0]?.update).toEqual([ + { + key: "a", + patch: { name: "renamed" }, + record: { id: "a", name: "renamed" }, + }, + { + key: "c", + patch: { name: "renamed" }, + record: { id: "c", name: "renamed" }, + }, + ]); + expect(names(test)).toEqual(["renamed", "B", "renamed"]); + expect(test.status()).toMatchObject({ + committing: false, + lastCommit: { outcome: "saved", saved: 2, failed: 0, failedKeys: [] }, + }); + expect(test.get("row")).toBeUndefined(); + }); + + it("removes the records the source removed", async () => { + const test = setup(); + await loadAll(test, [item("a"), item("b"), item("c")]); + test.controllers().data.set([["selected", ["b", "missing"]]]); + + test.controllers().flow.transition("Remove"); + await vitest.waitFor(() => + expect(test.status()?.lastCommit?.outcome).toBe("saved"), + ); + + expect(test.commits[0]).toEqual({ + create: [], + update: [], + remove: [{ key: "b", record: { id: "b", name: "B" } }], + }); + expect(names(test)).toEqual(["A", "C"]); + expect(test.plugin.getCollection("items")?.indexOf("c")).toBe(1); + expect(test.status()).toMatchObject({ + loadedRecords: 2, + lastCommit: { saved: 1 }, + }); + }); + + it("saves nothing, and calls it saved, when nothing changed", async () => { + const test = setup(); + await loadAll(test, [item("a")]); + test.controllers().data.set([["selected", []]]); + + test.controllers().flow.transition("Rename"); + await vitest.waitFor(() => + expect(test.status()?.lastCommit?.outcome).toBe("saved"), + ); + + expect(test.commits).toHaveLength(0); + expect(test.status()?.lastCommit).toEqual({ + outcome: "saved", + saved: 0, + failed: 0, + failedKeys: [], + }); + }); + + it("reports a partial save, keeping the records that failed as they were", async () => { + const test = setup({ + commitWith: (changes) => ({ + records: changes.update + .filter(({ key }) => key === "a") + .map(({ record }) => record), + removed: [], + failed: [{ key: "c", reason: "Locked" }], + }), + }); + await loadAll(test, [item("a"), item("b"), item("c")]); + test.controllers().data.set([["selected", ["a", "c"]]]); + + test.controllers().flow.transition("Rename"); + await vitest.waitFor(() => + expect(test.status()?.lastCommit?.outcome).toBe("partial"), + ); + + expect(names(test)).toEqual(["renamed", "B", "C"]); + expect(test.status()?.lastCommit).toEqual({ + outcome: "partial", + saved: 1, + failed: 1, + failedKeys: ["c"], + }); + }); + + it("fails a save the source rejects, without changing any record", async () => { + const test = setup({ + commitWith: () => { + throw new Error("Offline"); + }, + }); + await loadAll(test, [item("a"), item("b")]); + test.controllers().data.set([["selected", ["a", "b"]]]); + + test.controllers().flow.transition("Rename"); + await vitest.waitFor(() => + expect(test.status()?.lastCommit?.outcome).toBe("failed"), + ); + await vitest.waitFor(() => expect(test.stateName()).toBe("VIEW_main")); + + expect(names(test)).toEqual(["A", "B"]); + expect(test.status()).toMatchObject({ + committing: false, + lastCommit: { + outcome: "failed", + saved: 0, + failed: 2, + failedKeys: ["a", "b"], + }, + }); + expect(test.status()?.lastCommit?.error).toStrictEqual({ + message: "Offline", + }); + expect(test.log.error).toHaveBeenCalledWith( + "[StreamingDataPlugin] Saving 'items' failed: Offline", + ); + }); + + it("puts a string kind from a rejected save on lastCommit's error, and drops it on the next save", async () => { + let rejection: Error | undefined = Object.assign(new Error("Signed out"), { + kind: "session-expired", + }); + const test = setup({ + commitWith: (changes) => { + if (rejection) throw rejection; + return saveAll(changes); + }, + }); + await loadAll(test, [item("a")]); + test.controllers().data.set([["selected", ["a"]]]); + + test.controllers().flow.transition("Rename"); + await vitest.waitFor(() => + expect(test.status()?.lastCommit?.outcome).toBe("failed"), + ); + expect(test.status()?.lastCommit?.error).toStrictEqual({ + message: "Signed out", + kind: "session-expired", + }); + + await vitest.waitFor(() => expect(test.stateName()).toBe("VIEW_main")); + rejection = undefined; + test.controllers().flow.transition("Rename"); + await vitest.waitFor(() => + expect(test.status()?.lastCommit?.outcome).toBe("saved"), + ); + expect(test.status()?.lastCommit).not.toHaveProperty("error"); + }); + + it("fails a save when the collection's source can't save", async () => { + const test = setup({ commitWith: null }); + await loadAll(test, [item("a")]); + test.controllers().data.set([["selected", ["a"]]]); + + test.controllers().flow.transition("Rename"); + await vitest.waitFor(() => + expect(test.status()?.lastCommit?.outcome).toBe("failed"), + ); + + expect(test.status()?.lastCommit).toMatchObject({ + failedKeys: ["a"], + error: { message: "This collection's source can't save." }, + }); + expect(names(test)).toEqual(["A"]); + }); + + it("sends nothing, not even removals, when an eachRow expression fails, and fails every record the save names", async () => { + const test = setup(); + await loadAll(test, [item("a"), item("b"), item("c")]); + test.controllers().data.set([ + ["selected", ["a", "b", "missing"]], + ["doomed", "c"], + ]); + + test.controllers().flow.transition("Broken"); + await vitest.waitFor(() => + expect(test.status()?.lastCommit?.outcome).toBe("failed"), + ); + await vitest.waitFor(() => expect(test.stateName()).toBe("VIEW_main")); + + expect(test.commits).toHaveLength(0); + expect(names(test)).toEqual(["A", "B", "C"]); + expect(test.get("row")).toBeUndefined(); + expect(test.status()).toMatchObject({ + committing: false, + lastCommit: { + outcome: "failed", + saved: 0, + failed: 3, + failedKeys: ["a", "b", "c"], + }, + }); + expect(test.status()?.lastCommit?.error?.message).toContain( + "Error evaluating expression: missing()", + ); + expect(test.player.getState().status).toBe("in-progress"); + }); + + it("keeps the view that started a save current, so it can show the save running", async () => { + const test = setup(); + await loadAll(test, [item("a")]); + test.controllers().data.set([["selected", ["a"]]]); + const release = test.holdSaves(); + + test.controllers().flow.transition("Rename"); + await vitest.waitFor(() => expect(test.saving()).toBe("Saving: true")); + expect(test.stateName()).toBe("EXTERNAL_rename"); + + release(); + await vitest.waitFor(() => expect(test.stateName()).toBe("VIEW_main")); + await vitest.waitFor(() => expect(test.saving()).toBe("Saving: false")); + }); + + it("shows the view underneath while a save started from an overlay runs", async () => { + const test = setup(); + await loadAll(test, [item("a")]); + test.controllers().data.set([["selected", ["a"]]]); + test.controllers().flow.transition("Form"); + await vitest.waitFor(() => expect(test.viewId()).toBe("form")); + const release = test.holdSaves(); + + test.controllers().flow.transition("Rename"); + await vitest.waitFor(() => expect(test.saving()).toBe("Saving: true")); + expect(test.viewId()).toBe("main"); + expect(test.stateName()).toBe("EXTERNAL_rename"); + + release(); + await vitest.waitFor(() => expect(test.stateName()).toBe("VIEW_main")); + expect(test.get("items.0.name")).toBe("renamed"); + }); + + it("fails a save whose eachRow sits inside param, where Player resolves its templates", async () => { + const test = setup(); + await loadAll(test, [item("a")]); + test.controllers().data.set([["selected", ["a"]]]); + + test.controllers().flow.transition("Misplaced"); + await vitest.waitFor(() => expect(test.stateName()).toBe("VIEW_main")); + + expect(test.commits).toHaveLength(0); + expect(test.log.error).toHaveBeenCalledWith( + "[StreamingDataPlugin] Can't save: `eachRow` goes on the state beside `param`, where Player leaves it as written", + ); + }); +}); diff --git a/plugins/streaming-data/core/src/__tests__/collectChanges.test.ts b/plugins/streaming-data/core/src/__tests__/collectChanges.test.ts new file mode 100644 index 000000000..e4ca02cf8 --- /dev/null +++ b/plugins/streaming-data/core/src/__tests__/collectChanges.test.ts @@ -0,0 +1,156 @@ +import { describe, it, expect } from "vitest"; +import { collectChanges } from "../collectChanges"; +import type { ChangeContext } from "../collectChanges"; +import { RecordCollection } from "../RecordCollection"; +import type { CommitRecordsRequest } from "../types"; + +interface Item { + id: string; + name: string; + note?: string; +} + +const collection = new RecordCollection( + "items", + "itemsStatus", + ({ id }) => id, +); +collection.append([ + { id: "a", name: "A" }, + { id: "b", name: "B", note: "keep" }, +]); + +/** A data model held in a map, where `{{row.name}} = 'x'` sets the row's name and `fail()` throws */ +const contextOf = (data: Record) => { + const model = new Map(Object.entries(data)); + const context: ChangeContext = { + get: (binding) => model.get(binding), + set: (binding, value) => { + model.set(binding, value); + }, + delete: (binding) => { + model.delete(binding); + }, + evaluate: (expression) => { + if (expression === "fail()") throw new Error("Broken"); + const [, field, value] = + /^\{\{row\.(\w+)\}\} = '(\w*)'$/.exec(expression) ?? []; + if (field) + model.set("row", { ...(model.get("row") as object), [field]: value }); + }, + }; + return { model, context }; +}; + +const request = ( + change: Partial, +): CommitRecordsRequest => ({ binding: "items", eachRow: [], ...change }); + +describe("collectChanges", () => { + it("runs eachRow on a copy of each held record, keeps what changed, and clears the row", () => { + const { model, context } = contextOf({ selected: ["a", "b", "z", 3] }); + + const changes = collectChanges( + collection, + request({ + update: "selected", + rowBinding: "row", + eachRow: ["{{row.name}} = 'A'", "{{row.note}} = 'new'"], + }), + context, + ); + + expect(changes.update).toEqual([ + { + key: "a", + patch: { note: "new" }, + record: { id: "a", name: "A", note: "new" }, + }, + { + key: "b", + patch: { name: "A", note: "new" }, + record: { id: "b", name: "A", note: "new" }, + }, + ]); + expect(collection.get("a")).toEqual({ id: "a", name: "A" }); + expect(model.has("row")).toBe(false); + }); + + it("clears the row when an eachRow expression throws", () => { + const { model, context } = contextOf({ selected: ["a", "b"] }); + + expect(() => + collectChanges( + collection, + request({ + update: "selected", + rowBinding: "row", + eachRow: ["{{row.name}} = 'x'", "fail()"], + }), + context, + ), + ).toThrow("Broken"); + expect(model.has("row")).toBe(false); + }); + + it("creates a draft without a key, and saves the changed fields of one with a key", () => { + const created = collectChanges( + collection, + request({ save: "draft" }), + contextOf({ draft: { id: "", name: "New" } }).context, + ); + expect(created).toEqual({ + create: [{ id: "", name: "New" }], + update: [], + remove: [], + }); + + const updated = collectChanges( + collection, + request({ save: "draft" }), + contextOf({ draft: { id: "b", name: "B2" } }).context, + ); + expect(updated.update).toEqual([ + { + key: "b", + patch: { name: "B2", note: null }, + record: { id: "b", name: "B2", note: null }, + }, + ]); + }); + + it("ignores a draft that isn't an object or whose key isn't held", () => { + const { context } = contextOf({ draft: { id: "z", name: "Z" }, list: [] }); + + expect( + collectChanges(collection, request({ save: "draft" }), context), + ).toEqual({ + create: [], + update: [], + remove: [], + }); + expect( + collectChanges(collection, request({ save: "list" }), context).create, + ).toEqual([]); + }); + + it("removes the held records among one key or a list of them, each with its key", () => { + expect( + collectChanges( + collection, + request({ remove: "key" }), + contextOf({ key: "a" }).context, + ).remove, + ).toEqual([{ key: "a", record: { id: "a", name: "A" } }]); + + const removed = collectChanges( + collection, + request({ remove: "keys" }), + contextOf({ keys: ["b", "z", ""] }).context, + ).remove; + expect(removed).toEqual([ + { key: "b", record: { id: "b", name: "B", note: "keep" } }, + ]); + expect(removed[0]?.record).toBe(collection.get("b")); + }); +}); diff --git a/plugins/streaming-data/core/src/__tests__/findCollectionDeclarations.test.ts b/plugins/streaming-data/core/src/__tests__/findCollectionDeclarations.test.ts new file mode 100644 index 000000000..bd3a47b94 --- /dev/null +++ b/plugins/streaming-data/core/src/__tests__/findCollectionDeclarations.test.ts @@ -0,0 +1,127 @@ +import { describe, it, expect } from "vitest"; +import { SchemaController } from "@player-ui/player"; +import type { Schema } from "@player-ui/player"; +import { findCollectionDeclarations } from "../findCollectionDeclarations"; + +const parse = (schema: unknown) => + new SchemaController(schema as Schema.Schema).schema; + +describe("findCollectionDeclarations", () => { + it("finds nothing in a schema without declarations", () => { + const none = { declarations: [], problems: [] }; + expect(findCollectionDeclarations(new Map())).toEqual(none); + expect( + findCollectionDeclarations( + parse({ ROOT: { name: { type: "StringType" } } }), + ), + ).toEqual(none); + }); + + it("finds declarations in nested types, and reports one inside an array or record", () => { + const transactions = { + ref: "transactions", + status: "ledger.transactionsStatus", + params: { accountId: "{{accountId}}" }, + }; + const parsed = parse({ + ROOT: { + ledger: { type: "LedgerType" }, + list: { type: "NestedType", isArray: true }, + map: { type: "NestedType", isRecord: true }, + name: { type: "StringType" }, + }, + LedgerType: { + transactions: { + type: "TransactionType", + isArray: true, + source: transactions, + }, + }, + NestedType: { + hidden: { + type: "TransactionType", + isArray: true, + source: { ref: "transactions" }, + }, + }, + }); + + const problem = "a collection can't sit inside an array or record"; + expect(findCollectionDeclarations(parsed)).toEqual({ + declarations: [{ binding: "ledger.transactions", source: transactions }], + problems: [ + { binding: "list.[].hidden", problem }, + { binding: "map.{}.hidden", problem }, + ], + }); + }); + + it("reads a schema with entries that aren't data types", () => { + const transactions = { ref: "transactions" }; + const parsed = parse({ + ROOT: { + kind: "array", + other: { type: "OtherType" }, + ledger: { type: "LedgerType" }, + }, + OtherType: { type: "array", items: "StringType" }, + LedgerType: { + transactions: { + type: "TransactionType", + isArray: true, + source: transactions, + }, + }, + }); + + expect(findCollectionDeclarations(parsed)).toEqual({ + declarations: [{ binding: "ledger.transactions", source: transactions }], + problems: [], + }); + }); + + it("skips parsed entries that are not objects", () => { + const parsed = new Map([ + ["empty", null], + ["kind", "array"], + ["count", 1], + ["list", [{ source: { ref: "transactions" } }]], + ]); + expect(findCollectionDeclarations(parsed)).toEqual({ + declarations: [], + problems: [], + }); + }); + + it.each([ + ["is not an object", "transactions", "`source` must be an object"], + ["is a list", ["transactions"], "`source` must be an object"], + ["has no ref", {}, "`ref` must name a source"], + ["has an empty ref", { ref: "" }, "`ref` must name a source"], + [ + "has a status that is not text", + { ref: "transactions", status: 1 }, + "`status` must be a binding", + ], + [ + "has an empty status", + { ref: "transactions", status: "" }, + "`status` must be a binding", + ], + [ + "has params that are not an object", + { ref: "transactions", params: ["accountId"] }, + "`params` must be an object", + ], + ])("reports a source that %s", (_, source, problem) => { + const parsed = parse({ + ROOT: { + transactions: { type: "TransactionType", isArray: true, source }, + }, + }); + expect(findCollectionDeclarations(parsed)).toEqual({ + declarations: [], + problems: [{ binding: "transactions", problem }], + }); + }); +}); diff --git a/plugins/streaming-data/core/src/__tests__/toCommitRequest.test.ts b/plugins/streaming-data/core/src/__tests__/toCommitRequest.test.ts new file mode 100644 index 000000000..c248169b4 --- /dev/null +++ b/plugins/streaming-data/core/src/__tests__/toCommitRequest.test.ts @@ -0,0 +1,98 @@ +import { describe, it, expect } from "vitest"; +import { toCommitRequest } from "../toCommitRequest"; + +describe("toCommitRequest", () => { + it("reads a bulk update, with eachRow from beside param", () => { + expect( + toCommitRequest({ + param: { + binding: "transactions", + update: "table.selectedKeys", + rowBinding: "row", + }, + eachRow: ["{{row.category}} = 'travel'", "{{row.reviewed}} = true"], + }), + ).toEqual({ + binding: "transactions", + update: "table.selectedKeys", + rowBinding: "row", + eachRow: ["{{row.category}} = 'travel'", "{{row.reviewed}} = true"], + save: undefined, + remove: undefined, + }); + }); + + it("takes one eachRow expression, or none for a save or a removal", () => { + expect( + toCommitRequest({ + param: { binding: "transactions", update: "keys", rowBinding: "row" }, + eachRow: "{{row.category}} = 'travel'", + }), + ).toMatchObject({ eachRow: ["{{row.category}} = 'travel'"] }); + expect( + toCommitRequest({ + param: { binding: "transactions", save: "draft", remove: "key" }, + }), + ).toEqual({ + binding: "transactions", + eachRow: [], + save: "draft", + remove: "key", + update: undefined, + rowBinding: undefined, + }); + }); + + it.each([ + ["param is missing", {}, "`param` must be an object"], + ["param is a list", { param: [] }, "`param` must be an object"], + [ + "eachRow is inside param, where Player would resolve its templates", + { param: { binding: "transactions", eachRow: ["{{row.a}} = 1"] } }, + "`eachRow` goes on the state beside `param`, where Player leaves it as written", + ], + [ + "binding is missing", + { param: { save: "draft" } }, + "`param.binding` must name a collection", + ], + [ + "binding is empty", + { param: { binding: "" } }, + "`param.binding` must name a collection", + ], + [ + "rowBinding is not a binding", + { param: { binding: "transactions", update: "keys", rowBinding: 3 } }, + "`param.update` and `param.rowBinding` must be bindings", + ], + [ + "save is empty", + { param: { binding: "transactions", save: "" } }, + "`param.save` and `param.remove` must be bindings", + ], + [ + "eachRow holds something other than expressions", + { + param: { binding: "transactions", update: "keys", rowBinding: "row" }, + eachRow: [1], + }, + "`eachRow` must be an expression or a list of them", + ], + [ + "update has no rowBinding", + { + param: { binding: "transactions", update: "keys" }, + eachRow: ["{{row.a}} = 1"], + }, + "`param.update` needs `param.rowBinding` and `eachRow`", + ], + [ + "update has no eachRow", + { param: { binding: "transactions", update: "keys", rowBinding: "row" } }, + "`param.update` needs `param.rowBinding` and `eachRow`", + ], + ])("says why it is no request when %s", (_case, state, problem) => { + expect(toCommitRequest(state)).toEqual({ problem }); + }); +}); diff --git a/plugins/streaming-data/core/src/collectChanges.ts b/plugins/streaming-data/core/src/collectChanges.ts new file mode 100644 index 000000000..3d3ab780c --- /dev/null +++ b/plugins/streaming-data/core/src/collectChanges.ts @@ -0,0 +1,118 @@ +import type { + CollectionHandle, + CommitRecordsRequest, + RecordChanges, + RecordUpdate, +} from "./types"; + +/** The data model and expression calls collecting changes needs */ +export interface ChangeContext { + get(binding: string): unknown; + set(binding: string, value: unknown): void; + delete(binding: string): void; + evaluate(expression: string): unknown; +} + +const isPlainObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const keysAt = ( + context: ChangeContext, + binding: string | undefined, +): string[] => { + if (!binding) return []; + const value = context.get(binding); + const keys = Array.isArray(value) ? value : [value]; + return keys.filter( + (key): key is string => typeof key === "string" && key !== "", + ); +}; + +/** The keys of the held records a request updates or removes */ +export function requestedKeys( + collection: CollectionHandle, + request: CommitRecordsRequest, + context: ChangeContext, +): string[] { + const keys = new Set([ + ...keysAt(context, request.update), + ...keysAt(context, request.remove), + ]); + return [...keys].filter((key) => collection.get(key) !== undefined); +} + +/** The fields of `after` that differ from `record`; a field `after` dropped becomes null */ +const changedFields = ( + record: object, + after: Record, +): Record => { + const before = new Map(Object.entries(record)); + const patch: Record = {}; + Object.keys(after).forEach((field) => { + if (after[field] !== before.get(field)) patch[field] = after[field]; + }); + before.forEach((value, field) => { + if (!(field in after) && value !== undefined && value !== null) + patch[field] = null; + }); + return patch; +}; + +/** + * The changes a commit-records request asks for. Records come back from the data model untyped, + * so they're treated as the collection's record type from here on; the source checks what it + * sends. + */ +export function collectChanges( + collection: CollectionHandle, + request: CommitRecordsRequest, + context: ChangeContext, +): RecordChanges { + const changes: RecordChanges = { create: [], update: [], remove: [] }; + const toUpdate = ( + key: string, + record: R, + after: Record, + ): void => { + const patch = changedFields(record, after); + if (Object.keys(patch).length === 0) return; + const update: RecordUpdate = { + key, + patch: patch as Partial, + record: { ...record, ...patch }, + }; + changes.update.push(update); + }; + + const { rowBinding, eachRow } = request; + if (rowBinding && eachRow.length > 0) { + try { + keysAt(context, request.update).forEach((key) => { + const record = collection.get(key); + if (!record) return; + context.set(rowBinding, record); + eachRow.forEach((expression) => context.evaluate(expression)); + const after = context.get(rowBinding); + if (isPlainObject(after)) toUpdate(key, record, after); + }); + } finally { + context.delete(rowBinding); + } + } + + if (request.save) { + const draft = context.get(request.save); + if (isPlainObject(draft)) { + const key = collection.key(draft as R); + const record = key ? collection.get(key) : undefined; + if (!key) changes.create.push(draft as R); + else if (record) toUpdate(key, record, draft); + } + } + + changes.remove = keysAt(context, request.remove).flatMap((key) => { + const record = collection.get(key); + return record ? [{ key, record }] : []; + }); + return changes; +} diff --git a/plugins/streaming-data/core/src/findCollectionDeclarations.ts b/plugins/streaming-data/core/src/findCollectionDeclarations.ts new file mode 100644 index 000000000..37d6ccaf7 --- /dev/null +++ b/plugins/streaming-data/core/src/findCollectionDeclarations.ts @@ -0,0 +1,71 @@ +import type { CollectionSourceDeclaration } from "./types"; + +export interface CollectionDeclaration { + binding: string; + source: CollectionSourceDeclaration; +} + +export interface DeclarationProblem { + binding: string; + problem: string; +} + +const isPlainObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const sourceProblem = (source: unknown): string | undefined => { + if (!isPlainObject(source)) return "`source` must be an object"; + if (typeof source.ref !== "string" || source.ref === "") + return "`ref` must name a source"; + if ( + source.status !== undefined && + (typeof source.status !== "string" || source.status === "") + ) { + return "`status` must be a binding"; + } + if (source.params !== undefined && !isPlainObject(source.params)) { + return "`params` must be an object"; + } + return undefined; +}; + +const isSourceDeclaration = ( + source: unknown, +): source is CollectionSourceDeclaration => sourceProblem(source) === undefined; + +/** Player's parsed schema marks the items of an array entry with `[]` and of a record with `{}` */ +const isInsideArrayOrRecord = (binding: string): boolean => + binding.split(".").some((segment) => segment === "[]" || segment === "{}"); + +/** + * Every schema entry with a `source`, read from the schema Player parsed for the flow + * (`SchemaController.schema`, keyed by binding). A collection can't sit inside an array or + * record entry. + */ +export function findCollectionDeclarations( + parsedSchema: ReadonlyMap, +): { + declarations: CollectionDeclaration[]; + problems: DeclarationProblem[]; +} { + const declarations: CollectionDeclaration[] = []; + const problems: DeclarationProblem[] = []; + + parsedSchema.forEach((dataType, binding) => { + if (!isPlainObject(dataType) || dataType.source === undefined) return; + const { source } = dataType; + + if (isInsideArrayOrRecord(binding)) { + problems.push({ + binding, + problem: "a collection can't sit inside an array or record", + }); + } else if (isSourceDeclaration(source)) { + declarations.push({ binding, source }); + } else { + problems.push({ binding, problem: sourceProblem(source) ?? "" }); + } + }); + + return { declarations, problems }; +} diff --git a/plugins/streaming-data/core/src/index.ts b/plugins/streaming-data/core/src/index.ts new file mode 100644 index 000000000..a4a153eb6 --- /dev/null +++ b/plugins/streaming-data/core/src/index.ts @@ -0,0 +1,5 @@ +export * from "./StreamingDataPlugin"; +export * from "./RecordCollection"; +export * from "./findCollectionDeclarations"; +export * from "./symbols"; +export * from "./types"; diff --git a/plugins/streaming-data/core/src/symbols.ts b/plugins/streaming-data/core/src/symbols.ts new file mode 100644 index 000000000..7d67af2bb --- /dev/null +++ b/plugins/streaming-data/core/src/symbols.ts @@ -0,0 +1 @@ +export const StreamingDataPluginSymbol = Symbol.for("StreamingDataPlugin"); diff --git a/plugins/streaming-data/core/src/toCommitRequest.ts b/plugins/streaming-data/core/src/toCommitRequest.ts new file mode 100644 index 000000000..7ebce7bb3 --- /dev/null +++ b/plugins/streaming-data/core/src/toCommitRequest.ts @@ -0,0 +1,49 @@ +import type { CommitRecordsRequest } from "./types"; + +const isPlainObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const optionalBinding = (value: unknown): value is string | undefined => + value === undefined || (typeof value === "string" && value !== ""); + +/** + * A commit-records state's request, or why it isn't one. `eachRow` sits on the state beside + * `param`, not in it: Player resolves the templates in `param` when the state starts, which would + * replace every {{binding}} in the expressions with its value at that moment. + */ +export function toCommitRequest( + state: Readonly>, +): CommitRecordsRequest | { problem: string } { + const { param, eachRow = [] } = state; + if (!isPlainObject(param)) return { problem: "`param` must be an object" }; + if ("eachRow" in param) { + return { + problem: + "`eachRow` goes on the state beside `param`, where Player leaves it as written", + }; + } + const { binding, update, rowBinding, save, remove } = param; + if (typeof binding !== "string" || binding === "") { + return { problem: "`param.binding` must name a collection" }; + } + if (!optionalBinding(update) || !optionalBinding(rowBinding)) { + return { + problem: "`param.update` and `param.rowBinding` must be bindings", + }; + } + if (!optionalBinding(save) || !optionalBinding(remove)) { + return { problem: "`param.save` and `param.remove` must be bindings" }; + } + const expressions = Array.isArray(eachRow) ? eachRow : [eachRow]; + if ( + !expressions.every( + (expression): expression is string => typeof expression === "string", + ) + ) { + return { problem: "`eachRow` must be an expression or a list of them" }; + } + if (update && (!rowBinding || expressions.length === 0)) { + return { problem: "`param.update` needs `param.rowBinding` and `eachRow`" }; + } + return { binding, update, rowBinding, eachRow: expressions, save, remove }; +} diff --git a/plugins/streaming-data/core/src/types.ts b/plugins/streaming-data/core/src/types.ts new file mode 100644 index 000000000..fe64fb17e --- /dev/null +++ b/plugins/streaming-data/core/src/types.ts @@ -0,0 +1,150 @@ +/** One batch of records a source's load delivers */ +export interface RecordBatch { + records: R[]; + /** How many batches the load delivers in all, if the source knows; it may revise this */ + totalBatches?: number; +} + +/** What a source receives for a load or a save */ +export interface SourceContext { + /** The collection's `params` with every template resolved, as they were when loading started */ + params: Readonly>; + /** Aborted when the flow ends or a new load replaces this one */ + signal: AbortSignal; +} + +/** One record a save changes: the changed fields, and the whole record with them applied */ +export interface RecordUpdate { + key: string; + patch: Partial; + record: R; +} + +/** One record a save removes: its key, and the record as the collection holds it */ +export interface RecordRemoval { + key: string; + record: R; +} + +/** What a save asks the source to change */ +export interface RecordChanges { + create: R[]; + update: Array>; + remove: Array>; +} + +/** A record the source couldn't save, and why */ +export interface CommitFailure { + key: string; + reason: string; +} + +/** What a save changed: the saved records as the backend returned them, and the keys it removed */ +export interface CommitResult { + records: R[]; + removed: string[]; + failed: CommitFailure[]; +} + +/** + * Loads a collection in batches and, optionally, saves changes to it. The plugin freezes records + * and shares them, so a consumer that sorts or searches them keeps its own keys, made as records + * arrive, instead of adding fields to them. + */ +export interface RecordSource { + /** The record's key; an empty string for a draft that hasn't been saved yet */ + key(record: R): string; + load(context: SourceContext): AsyncIterable>; + commit?( + changes: RecordChanges, + context: SourceContext, + ): Promise>; +} + +/** A collection's declaration: the `source` property of its schema entry */ +export interface CollectionSourceDeclaration { + /** The name a source is registered under */ + ref: string; + /** Where the plugin writes the collection's status; defaults to `Status` */ + status?: string; + /** The source's inputs, as templates the plugin resolves when loading starts */ + params?: Record; +} + +/** How a save ended */ +export type CommitOutcome = "saved" | "partial" | "failed"; + +/** Why a load or a save failed */ +export interface CollectionError { + message: string; + /** A machine-readable reason, if the source gave one; the source defines the values */ + kind?: string; +} + +/** The latest save's result */ +export interface LastCommit { + outcome: CommitOutcome; + /** Records saved, including removed ones */ + saved: number; + failed: number; + failedKeys: string[]; + /** Why the save failed as a whole, if it did */ + error?: CollectionError; +} + +/** A collection's status, which the plugin writes to the collection's status binding */ +export interface CollectionStatus { + started: boolean; + loading: boolean; + completed: boolean; + loadedBatches: number; + totalBatches?: number; + loadedRecords: number; + /** True while a save is in flight */ + committing: boolean; + lastCommit?: LastCommit; + /** Why loading failed, if it did */ + error?: CollectionError; +} + +/** A change to a collection's records, for consumers that keep more than the array */ +export type CollectionChange = + | { type: "appended"; records: ReadonlyArray } + | { type: "updated"; records: ReadonlyArray } + | { type: "removed"; keys: ReadonlyArray } + | { type: "reset" } + /** A save that changed at least one record has been merged */ + | { type: "committed"; outcome: CommitOutcome }; + +/** A loaded collection, as consumers such as a table see it */ +export interface CollectionHandle { + readonly binding: string; + readonly statusBinding: string; + /** Every record held, in load order; the same array until records are removed or reset */ + readonly records: ReadonlyArray; + key(record: R): string; + /** The record's position in `records`, or -1 */ + indexOf(key: string): number; + get(key: string): R | undefined; + /** Returns a function that stops the notices */ + subscribe(listener: (change: CollectionChange) => void): () => void; +} + +/** A `commit-records` EXTERNAL state's `param`, plus the `eachRow` beside it */ +export interface CommitRecordsRequest { + /** The collection to save */ + binding: string; + /** A binding holding the key, or list of keys, of the records `eachRow` may change */ + update?: string; + /** Where each record is copied while `eachRow` runs */ + rowBinding?: string; + /** + * Expressions that change the record at `rowBinding`, from the state's `eachRow`. Not in `param`: + * Player resolves the templates in `param` when the state starts. + */ + eachRow: string[]; + /** A binding holding a draft: created without a key, otherwise its changed fields are saved */ + save?: string; + /** A binding holding the key, or list of keys, of the records to remove */ + remove?: string; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 550808318..213118cb4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1083,6 +1083,15 @@ importers: specifier: workspace:^ version: link:../../../core/types + plugins/streaming-data/core: + dependencies: + '@player-ui/external-state-plugin': + specifier: workspace:^ + version: link:../../external-state/core + '@player-ui/player': + specifier: workspace:^ + version: link:../../../core/player + plugins/types-provider/core: dependencies: '@player-ui/player':