@tanstack/db
Version:
A reactive client store for building super fast apps on sync
581 lines (580 loc) • 21.8 kB
JavaScript
import { createSourceRecord } from "../utils/source-record.js";
import { collectCollectionSources } from "./ir.js";
import { createDeferred } from "../deferred.js";
import { runAllCallbacks } from "../utils/callbacks.js";
import { normalizeError } from "../utils/error.js";
import { samePublishedValue } from "../utils.js";
import { codedMessage, devBuild } from "../error-message.js";
import { buildHealthTree, healthNode } from "../collection/health-tree.js";
import { isFailedStatus } from "../live-query-primitives.js";
import { compileQuery } from "./compiler/index.js";
import { normalizeExpressionPaths } from "./compiler/expressions.js";
import { getCollectionBuilder } from "./live/collection-registry.js";
import { scheduleQueryGraphRun } from "./live/graph-scheduler.js";
import { SubsetDemandController, hasPendingJoinedWork } from "./live/subset-demand-controller.js";
import { OrderedSourceLoader } from "./live/ordered-source-loader.js";
import { buildQueryFromConfig, computeSubscriptionOrderByHints, extractCollectionFromSource, extractCollectionsFromQuery, reconcileChangesForD2, sendChangesToInput, sourcePermitsInitialReadiness, splitUpdates } from "./live/utils.js";
import { D2, output } from "@tanstack/db-ivm";
var effectCounter = 0;
function stoppedSourceError(collectionId, status) {
return new Error(/* @__PURE__ */ devBuild() && process.env.NODE_ENV !== `production` ? `Source collection '${collectionId}' entered ${status} state` : codedMessage(135, {
collectionId,
status
}));
}
function createEffect(config) {
const id = config.id ?? `live-query-effect-${++effectCounter}`;
const abortController = new AbortController();
const ctx = {
effectId: id,
signal: abortController.signal
};
const inFlightHandlers = /* @__PURE__ */ new Set();
let disposed = false;
const onBatchProcessed = (events) => {
if (disposed) return;
if (events.length === 0) return;
if (config.onBatch) try {
const result = config.onBatch(events, ctx);
if (result instanceof Promise) trackPromise(result.catch((error) => {
reportError(error, events[0], config.onError);
}), inFlightHandlers);
} catch (error) {
reportError(error, events[0], config.onError);
}
for (const event of events) {
if (abortController.signal.aborted) break;
const handler = getHandlerForEvent(event, config);
if (!handler) continue;
try {
const result = handler(event, ctx);
if (result instanceof Promise) trackPromise(result.catch((error) => {
reportError(error, event, config.onError);
}), inFlightHandlers);
} catch (error) {
reportError(error, event, config.onError);
}
}
};
let disposalPromise;
const dispose = () => {
if (disposalPromise) return disposalPromise;
const completion = createDeferred();
const attempt = completion.promise;
disposalPromise = attempt;
disposed = true;
abortController.abort();
(async () => {
let cleanupFailed = false;
let cleanupError;
try {
runner.dispose();
} catch (error) {
cleanupFailed = true;
cleanupError = error;
}
if (inFlightHandlers.size > 0) await Promise.allSettled([...inFlightHandlers]);
if (cleanupFailed) throw cleanupError;
})().then(completion.resolve, completion.reject);
attempt.then(() => {}, () => {
if (disposalPromise === attempt) disposalPromise = void 0;
});
return attempt;
};
const effect = {
dispose,
get disposed() {
return disposed;
}
};
const runner = new EffectPipelineRunner({
effect,
query: config.query,
skipInitial: config.skipInitial ?? false,
onBatchProcessed,
onHealthChange: config.onHealthChange,
onSourceError: (error) => {
if (disposed) return;
if (config.onSourceError) try {
config.onSourceError(error);
} catch (callbackError) {
console.error(/* @__PURE__ */ devBuild() && process.env.NODE_ENV !== `production` ? `[Effect '${id}'] onSourceError callback threw:` : codedMessage(220, { id }), callbackError);
}
else console.error(/* @__PURE__ */ devBuild() && process.env.NODE_ENV !== `production` ? `[Effect '${id}'] ${error.message}. Disposing effect.` : codedMessage(221, {
id,
message: error.message
}));
dispose().catch((cleanupError) => {
console.error(/* @__PURE__ */ devBuild() && process.env.NODE_ENV !== `production` ? `[Effect '${id}'] failed to dispose after a source error:` : codedMessage(222, { id }), cleanupError);
});
}
});
try {
runner.start();
} catch (error) {
try {
runner.dispose();
} catch (cleanupError) {
console.error(/* @__PURE__ */ devBuild() && process.env.NODE_ENV !== `production` ? `[Effect '${id}'] failed to dispose after a startup error:` : codedMessage(223, { id }), cleanupError);
}
throw error;
}
return effect;
}
function followHeldAcquisition(acquisition, replacementAfterFailure, handlers) {
acquisition.then(() => handlers.settled(true), () => {
const replacement = replacementAfterFailure();
if (replacement) handlers.replaced(replacement);
else handlers.settled(false);
});
}
var EffectPipelineRunner = class {
constructor(config) {
this.subscriptions = createSourceRecord();
this.lazySourcesCallbacks = createSourceRecord();
this.lazySources = /* @__PURE__ */ new Set();
this.demand = new SubsetDemandController();
this.optimizableOrderByCollections = createSourceRecord();
this.b7 = /* @__PURE__ */ new Map();
this.af = /* @__PURE__ */ new Set();
this.f1 = /* @__PURE__ */ new Set();
this.aJ = false;
this.unsubscribeCallbacks = /* @__PURE__ */ new Set();
this.b3 = /* @__PURE__ */ new Map();
this.aT = /* @__PURE__ */ new Map();
this.ac = /* @__PURE__ */ new Set();
this.ao = false;
this.ce = false;
this.subscribedToAllCollections = false;
this.bh = /* @__PURE__ */ new Set();
this.br = false;
this.disposed = false;
this.skipInitial = config.skipInitial;
this.onBatchProcessed = config.onBatchProcessed;
this.onSourceError = config.onSourceError;
this.onHealthChange = config.onHealthChange;
this.dependent = {
kind: `effect`,
active: true,
end: () => config.effect.dispose()
};
this.query = buildQueryFromConfig({ query: config.query });
this.queryCompareOptions = extractCollectionFromSource(this.query).compareOptions;
this.collections = extractCollectionsFromQuery(this.query);
this.ai = collectCollectionSources(this.query);
this.fw();
}
/** Compile the D2 graph and query pipeline */
fw() {
this.graph = new D2();
const inputs = createSourceRecord();
for (const source of this.ai) inputs[source.sourceId] = this.graph.newInput();
this.inputs = inputs;
const compilation = compileQuery(this.query, this.inputs, this.collections, this.subscriptions, this.lazySourcesCallbacks, this.lazySources, this.optimizableOrderByCollections, () => {});
this.sourceWhereClauses = compilation.sourceWhereClauses;
compilation.pipeline.pipe(output((data) => {
data.getInner().reduce(accumulateEffectChanges, this.aT);
}));
this.graph.finalize();
}
isDisposed() {
return this.disposed;
}
/** Subscribe to source collections and start processing */
start() {
if (this.ai.length === 0) return;
if (!this.skipInitial) this.ao = true;
const pendingBuffers = /* @__PURE__ */ new Map();
for (const source of this.ai) {
if (this.isDisposed()) return;
const { sourceId, alias, collection } = source;
const collectionId = collection.id;
const handleSourceCleanup = () => {
if (this.disposed) return;
this.onSourceError(new Error(/* @__PURE__ */ devBuild() && process.env.NODE_ENV !== `production` ? `Source collection '${collectionId}' was cleaned up while effect depends on it` : codedMessage(134, { collectionId })));
};
const cleanupStartUnsubscribe = collection._onCleanupStart(handleSourceCleanup);
if (this.isDisposed()) {
cleanupStartUnsubscribe();
return;
}
this.unsubscribeCallbacks.add(cleanupStartUnsubscribe);
this.b3.set(sourceId, /* @__PURE__ */ new Map());
const dependencyBuilder = getCollectionBuilder(collection);
if (dependencyBuilder) this.bh.add(dependencyBuilder);
const whereClause = this.sourceWhereClauses?.get(sourceId);
const whereExpression = whereClause ? normalizeExpressionPaths(whereClause, alias) : void 0;
pendingBuffers.set(sourceId, []);
const isLazy = this.lazySources.has(sourceId);
const orderByInfo = this.optimizableOrderByCollections[sourceId];
const changeCallback = (changes) => {
const bufferedChanges = pendingBuffers.get(sourceId);
if (bufferedChanges) bufferedChanges.push(changes);
else this.cj(sourceId, changes);
};
if (isFailedStatus(collection.status)) {
this.onSourceError(stoppedSourceError(collectionId, collection.status));
return;
}
const subscription = collection.subscribeChanges(changeCallback, {
...this.ew(alias, isLazy, orderByInfo, whereExpression),
owner: this.dependent,
onLoadSubsetError: ({ error }) => this.onSourceError(normalizeError(error)),
onLoadSubsetResult: (result) => {
this.gs(result, () => this.subscriptions[sourceId]?.pendingTruncateReplacement);
}
});
this.subscriptions[sourceId] = subscription;
const unsubscribe = () => {
delete this.subscriptions[sourceId];
subscription.unsubscribe();
};
if (this.isDisposed()) {
unsubscribe();
return;
}
this.unsubscribeCallbacks.add(unsubscribe);
if (Object.values(this.optimizableOrderByCollections).some((info) => info.joinedFilterSourceIds?.includes(sourceId))) this.unsubscribeCallbacks.add(subscription.on(`status:ready`, () => {
if (!this.disposed) this.scheduleGraphRun();
}));
const lazyCallbacks = this.lazySourcesCallbacks[sourceId];
if (lazyCallbacks) {
lazyCallbacks.setDemand = (plan, keys) => this.setDemand(subscription, plan, keys);
for (const plan of lazyCallbacks.plans ?? []) if (plan.initialKeys.size > 0) lazyCallbacks.setDemand(plan, plan.initialKeys);
}
if (orderByInfo) {
this.ac = /* @__PURE__ */ new Map();
const loader = new OrderedSourceLoader(orderByInfo, subscription, alias, (result, holdPublication) => {
this.gs(result, () => subscription.pendingTruncateReplacement);
const holdsInitialPublication = this.skipInitial && !this.ao;
if (holdPublication || holdsInitialPublication) this.dz(Promise.resolve(result), () => subscription.pendingTruncateReplacement);
}, () => false, void 0, () => orderByInfo.joinedFilterSourceIds?.some((joinedSourceId) => this.hasPendingJoinedWork(joinedSourceId)) ?? false);
this.b7.set(sourceId, loader);
loader.start();
this.unsubscribeCallbacks.add(collection.on(`loadedSubsets:invalidated`, () => {
if (this.disposed) return;
loader.revalidateLoadedCoverage();
this.scheduleGraphRun();
}));
}
const handleSourceStatus = (status) => {
if (this.disposed) return;
if (status === `crashed` || status === `error` && !this.ce) {
this.onSourceError(stoppedSourceError(collectionId, status));
return;
}
if (status === `cleaned-up`) {
handleSourceCleanup();
return;
}
if (this.skipInitial && !this.ao && this.cD()) this.ao = true;
this.g1();
};
const statusUnsubscribe = collection.on(`status:change`, ({ status }) => handleSourceStatus(status));
this.unsubscribeCallbacks.add(statusUnsubscribe);
this.unsubscribeCallbacks.add(collection.on(`health:change`, () => this.g4()));
}
this.subscribedToAllCollections = true;
for (const [sourceId, buffer] of pendingBuffers) {
pendingBuffers.delete(sourceId);
for (const changes of buffer) this.cj(sourceId, changes, false);
}
this.fL();
this.g1();
if (this.skipInitial && !this.ao && this.cD()) this.ao = true;
}
/** Handle incoming changes from a source collection */
cj(sourceId, changes, scheduleGraph = true) {
if (this.optimizableOrderByCollections[sourceId]) {
const source = this.ai.find((candidate) => candidate.sourceId === sourceId);
this.b7.get(sourceId)?.onSourceChanges(changes, this.b3.get(sourceId), (key) => source.collection._hasOptimisticOverlay(key));
changes = [...splitUpdates(changes)];
}
this.fA(sourceId, changes);
if (scheduleGraph) this.scheduleGraphRun();
}
setDemand(subscription, plan, keys) {
const update = this.demand.setDemand(subscription, plan, keys);
if (update.ready instanceof Promise) {
this.gs(update.ready, () => subscription.pendingTruncateReplacement);
update.ready.then(() => {
if (!this.disposed) this.scheduleGraphRun();
}, () => {});
}
}
/**
* Schedule a graph run via the transaction-scoped scheduler.
*
* When called within a transaction, the run is deferred until the
* transaction flushes, coalescing multiple changes into a single graph
* execution. Without a transaction, the graph runs immediately.
*
* Dependencies are discovered from source collections that are themselves
* live query collections, ensuring parent queries run before effects.
*/
scheduleGraphRun() {
scheduleQueryGraphRun(this, this.bh, () => {
if (!this.disposed && this.subscribedToAllCollections) this.fL();
});
}
/** Keep the Effect's gate, and `skipInitial` suppression, open until a pending initial load settles. */
gs(result, replacementAfterFailure) {
if (!(result instanceof Promise) || this.ce || this.disposed) return;
this.f1.add(result);
const release = () => {
if (this.f1.delete(result) && !this.disposed) this.scheduleGraphRun();
};
followHeldAcquisition(result, replacementAfterFailure, {
settled: (succeeded) => succeeded ? release() : void Promise.resolve().then(release),
replaced: (replacement) => {
this.gs(replacement, replacementAfterFailure);
release();
}
});
}
/** Hold Effect callback publication across one authoritative repair chain. */
dz(promise, replacementAfterFailure) {
if (this.disposed) return;
if (this.af.size === 0) this.aJ = false;
this.af.add(promise);
const finish = (succeeded) => {
if (!this.af.delete(promise)) return;
if (!succeeded) this.aJ = true;
if (succeeded && !this.aJ && this.af.size === 0 && !this.disposed) this.scheduleGraphRun();
};
followHeldAcquisition(promise, replacementAfterFailure, {
settled: finish,
replaced: (replacement) => {
if (this.af.delete(promise) && !this.disposed) this.dz(replacement, replacementAfterFailure);
}
});
}
/**
* Send changes to the D2 input for the given lexical source.
* Returns the number of multiset entries sent.
*/
fA(sourceId, changes) {
if (this.disposed || !this.inputs || !this.graph) return 0;
const input = this.inputs[sourceId];
if (!input) return 0;
const sentRows = this.b3.get(sourceId);
const reconciled = reconcileChangesForD2(changes, sentRows);
return sendChangesToInput(input, reconciled);
}
/**
* Run the D2 graph until quiescence, then emit accumulated events once.
*
* All output across the entire while-loop is accumulated into a single
* batch so that users see one `onBatchProcessed` invocation per scheduler
* run, even when ordered loading causes multiple graph steps.
*/
fL() {
if (this.br || this.disposed || !this.graph) return;
this.br = true;
try {
if (!this.graph.pendingWork()) this.loadMoreIfNeeded();
while (!this.isDisposed() && this.graph.pendingWork()) {
this.graph.run();
if (this.disposed) break;
this.loadMoreIfNeeded();
}
this.flushPendingChanges();
this.g1();
if (this.skipInitial && !this.ao && this.cD()) this.ao = true;
} finally {
this.br = false;
}
}
/** Classify accumulated changes into DeltaEvents and invoke the callback */
flushPendingChanges() {
if (this.aT.size === 0) return;
if (this.aJ || this.af.size > 0) return;
if (this.cU()) return;
const shouldPublish = !this.skipInitial || this.ao;
const events = [];
for (const [key, changes] of this.aT) {
const event = classifyDelta(key, changes, this.ac);
if (event) {
if (event.type === `exit`) this.ac.delete(key);
else if (this.ac instanceof Map) this.ac.set(key, event.value);
else this.ac.add(key);
if (shouldPublish) events.push(event);
}
}
this.aT = /* @__PURE__ */ new Map();
if (events.length > 0) this.onBatchProcessed(events);
}
/** Check the source-readiness part of initial readiness for every source. */
gv() {
return this.ai.every(({ collection }) => sourcePermitsInitialReadiness(collection));
}
/** Latch the Effect's initial gate and report whether it has been reached. */
g1() {
if (!this.ce && this.cD()) {
this.ce = true;
const tree = this.g6();
if (tree.hasErrors) this.g4();
else this.fD = tree;
}
return this.ce;
}
/** The health tree for this effect's sources, in query order. */
g6() {
return healthNode(this, void 0, {
alias: `root`,
collectionId: `effect`,
kind: `live-query`,
status: this.ce ? `ready` : `loading`,
failureReason: null,
error: null,
reloading: false,
sources: this.ai.map(({ sourceId, alias, collection }) => buildHealthTree(collection, {
alias,
id: sourceId
}, this))
});
}
g4() {
if (this.disposed || !this.ce || !this.onHealthChange) return;
const tree = this.g6();
if (tree === this.fD) return;
this.fD = tree;
this.onHealthChange(tree);
}
cD() {
return !this.aJ && this.af.size === 0 && this.f1.size === 0 && !this.cU() && this.gv();
}
cU() {
return Object.values(this.optimizableOrderByCollections).some((info) => info.joinedFilterSourceIds?.some((sourceId) => this.hasPendingJoinedWork(sourceId)));
}
/**
* Build subscription options for an alias based on whether it uses ordered
* loading, is lazy, or should pass orderBy/limit hints.
*/
ew(alias, isLazy, orderByInfo, whereExpression) {
if (this.query.limit === 0) return {
includeInitialState: false,
whereExpression
};
if (orderByInfo) return {
includeInitialState: false,
whereExpression
};
const includeInitialState = !isLazy;
const hints = computeSubscriptionOrderByHints(this.query, alias, this.queryCompareOptions);
return {
includeInitialState,
whereExpression,
...hints.orderBy ? { orderBy: hints.orderBy } : {},
...hints.limit !== void 0 ? { limit: hints.limit } : {}
};
}
/**
* After each graph run step, check if any ordered query's topK operator
* needs more data. If so, load more rows via requestLimitedSnapshot.
*/
loadMoreIfNeeded() {
for (const loader of this.b7.values()) try {
loader.loadMore();
} catch (error) {
if (!this.disposed && !Object.values(this.subscriptions).some((subscription) => Object.is(subscription.lastError, error))) throw error;
}
}
hasPendingJoinedWork(joinedSourceId) {
return hasPendingJoinedWork(joinedSourceId, this.lazySourcesCallbacks, this.subscriptions, (planId) => this.demand.hasPendingDemand(planId));
}
/** Tear down subscriptions and clear state */
dispose() {
if (this.disposed) return;
this.disposed = true;
this.subscribedToAllCollections = false;
try {
runAllCallbacks(this.unsubscribeCallbacks);
} finally {
this.unsubscribeCallbacks.clear();
this.ff();
}
}
ff() {
this.b3.clear();
this.aT.clear();
this.ac.clear();
this.af.clear();
this.f1.clear();
this.aJ = false;
this.lazySources.clear();
this.demand.clear();
this.bh.clear();
for (const loader of this.b7.values()) loader.dispose();
this.b7.clear();
for (const key of Object.keys(this.lazySourcesCallbacks)) delete this.lazySourcesCallbacks[key];
for (const key of Object.keys(this.optimizableOrderByCollections)) delete this.optimizableOrderByCollections[key];
this.graph = void 0;
this.inputs = void 0;
this.sourceWhereClauses = void 0;
}
};
function getHandlerForEvent(event, config) {
switch (event.type) {
case `enter`: return config.onEnter;
case `exit`: return config.onExit;
case `update`: return config.onUpdate;
}
}
function accumulateEffectChanges(acc, [[key, tupleData], multiplicity]) {
const [value] = tupleData;
const changes = acc.get(key) || {
deletes: 0,
inserts: 0
};
if (multiplicity < 0) {
changes.deletes += Math.abs(multiplicity);
changes.deleteValue ??= value;
} else if (multiplicity > 0) {
changes.inserts += multiplicity;
changes.insertValue = value;
}
acc.set(key, changes);
return acc;
}
function classifyDelta(key, changes, publishedRows) {
const { inserts, deletes, insertValue, deleteValue } = changes;
const wasPresent = publishedRows.has(key);
const previousValue = publishedRows instanceof Map ? publishedRows.get(key) : deleteValue;
const isPresent = Number(wasPresent) + inserts - deletes > 0;
if (!wasPresent && isPresent) return {
type: `enter`,
key,
value: insertValue
};
if (wasPresent && !isPresent) return {
type: `exit`,
key,
value: previousValue
};
if (wasPresent && isPresent && insertValue !== void 0 && (publishedRows instanceof Set || !samePublishedValue(previousValue, insertValue))) return {
type: `update`,
key,
value: insertValue,
previousValue
};
}
function trackPromise(promise, inFlightHandlers) {
inFlightHandlers.add(promise);
const finish = () => {
inFlightHandlers.delete(promise);
};
promise.then(finish, finish);
}
function reportError(error, event, onError) {
const normalised = normalizeError(error);
if (onError) try {
onError(normalised, event);
} catch (onErrorError) {
console.error(/* @__PURE__ */ devBuild() && process.env.NODE_ENV !== `production` ? `[Effect] Error in onError handler:` : codedMessage(224), onErrorError);
console.error(/* @__PURE__ */ devBuild() && process.env.NODE_ENV !== `production` ? `[Effect] Original error:` : codedMessage(225), normalised);
}
else console.error(/* @__PURE__ */ devBuild() && process.env.NODE_ENV !== `production` ? `[Effect] Unhandled error in handler:` : codedMessage(226), normalised);
}
export { createEffect };
//# sourceMappingURL=effect.js.map