@tanstack/db
Version:
A reactive client store for building super fast apps on sync
301 lines (300 loc) • 10.3 kB
JavaScript
const require_errors = require("../errors.cjs");
const require_scheduler = require("../scheduler.cjs");
const require_callbacks = require("../utils/callbacks.cjs");
const require_ref_proxy = require("../query/builder/ref-proxy.cjs");
const require_error_message = require("../error-message.cjs");
const require_collection_registry = require("../query/live/collection-registry.cjs");
const require_subscription = require("./subscription.cjs");
var CollectionChangesManager = class {
/**
* Creates a new CollectionChangesManager instance
*/
constructor() {
this.activeSubscribersCount = 0;
this.acquiringSubscribersCount = 0;
this.changeSubscriptions = /* @__PURE__ */ new Set();
this.batchedEvents = [];
this.shouldBatchEvents = false;
this.cM = /* @__PURE__ */ new Set();
this.f2 = false;
this.ex = /* @__PURE__ */ new Set();
this.stateRevision = 0;
this.layoutRevision = 0;
}
setDeps(deps) {
this.lifecycle = deps.lifecycle;
this.sync = deps.sync;
this.events = deps.events;
this.collection = deps.collection;
this.state = deps.state;
}
/**
* Emit an empty ready event to notify subscribers that the collection is ready
* This bypasses the normal empty array check in emitEvents
*/
emitEmptyReadyEvent() {
require_scheduler.withPublicationContext(() => {
try {
require_callbacks.runAllCallbacks([...this.changeSubscriptions].map((subscription) => () => subscription.emitEvents([])));
} catch (error) {
require_scheduler.recordPublicationError(error);
}
});
}
/**
* Enriches a change message with virtual properties ($hasPendingWrites, $origin, $key, $collectionId).
* Uses the "add-if-missing" pattern to preserve virtual properties from upstream collections.
*/
cK(change) {
return this.state.enrichChangeMessage(change);
}
eW(pending, change) {
if (!pending) return change;
if (pending.type === `insert`) {
if (change.type === `delete`) return void 0;
return {
...change,
type: `insert`,
previousValue: void 0
};
}
const previousValue = pending.type === `update` ? pending.previousValue ?? pending.value : pending.value;
if (change.type === `delete`) return {
...change,
value: previousValue,
previousValue: void 0
};
return {
...change,
type: `update`,
previousValue
};
}
/**
* Emit events either immediately or batch them for later emission
*/
emitEvents(changes, forceEmit = false, layoutChanged = false) {
if (changes.length > 0) this.stateRevision++;
if (layoutChanged) this.layoutRevision++;
if (this.shouldBatchEvents && !forceEmit) {
this.batchedEvents.push(...changes.map((change) => this.cK(change)));
return;
}
let rawEvents = changes;
if (forceEmit) {
if (this.batchedEvents.length > 0) {
const combined = /* @__PURE__ */ new Map();
for (const change of [...this.batchedEvents, ...changes]) combined.set(change.key, this.eW(combined.get(change.key), change));
rawEvents = [...combined.values()].flatMap((change) => {
return change ? [change] : [];
});
}
this.batchedEvents = [];
this.shouldBatchEvents = false;
}
if (this.aN) {
this.aN.publications.push({
changes: rawEvents,
layoutChanged
});
return;
}
this.e5(rawEvents, layoutChanged);
}
/**
* Defers subscriber delivery while a coherent multi-Collection publication
* installs all of its visible state. State and indexes still commit at their
* normal transaction boundaries.
*/
deferPublication() {
const deferral = this.aN ??= {
depth: 0,
discard: false,
layoutRevision: this.layoutRevision,
publications: []
};
deferral.depth++;
let closed = false;
const close = (discard) => {
if (closed || this.aN !== deferral) return;
closed = true;
deferral.discard ||= discard;
if (--deferral.depth > 0) return;
const publications = deferral.publications;
deferral.publications = [];
this.aN = void 0;
if (deferral.discard) {
if (this.layoutRevision !== deferral.layoutRevision) this.stateRevision++;
this.layoutRevision = deferral.layoutRevision;
return;
}
this.e5(publications.flatMap(({ changes }) => changes), publications.some(({ layoutChanged }) => layoutChanged));
};
return {
publish: () => close(false),
discard: () => close(true)
};
}
e5(rawEvents, layoutChanged) {
if (rawEvents.length === 0 && !layoutChanged) return;
const enrichedEvents = rawEvents.map((change) => this.cK(change));
const layoutListeners = [...this.cM];
const subscriptions = [...this.changeSubscriptions];
require_scheduler.withPublicationContext(() => {
const callbacks = subscriptions.map((subscription) => () => subscription.emitEvents(enrichedEvents));
if (rawEvents.length === 0) callbacks.unshift(...layoutListeners);
try {
require_callbacks.runAllCallbacks(callbacks);
} catch (error) {
require_scheduler.recordPublicationError(error);
}
});
}
/** Subscribe to layout-only publications. Internal observer channel. */
subscribeLayoutChanges(listener) {
this.cM.add(listener);
return () => this.cM.delete(listener);
}
/**
* Subscribe to changes in the collection
*/
subscribeChanges(callback, options = {}) {
if (options.where && options.whereExpression) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Cannot specify both 'where' and 'whereExpression' options. Use one or the other.` : require_error_message.codedMessage(95));
const { where, ...opts } = options;
let whereExpression = opts.whereExpression;
if (where) {
const result = where(require_ref_proxy.createSingleRowRefProxy());
whereExpression = require_ref_proxy.toExpression(result);
}
const defersAcquisition = opts.deferAcquisition === true;
this.ei(defersAcquisition);
let subscription;
const setupState = { closed: false };
try {
subscription = new require_subscription.CollectionSubscription(this.collection, callback, {
...opts,
whereExpression,
deferAcquisition: defersAcquisition,
onResumeAcquisition: () => this.gA(),
onUnsubscribe: () => {
setupState.closed = true;
this.eB(subscription?.isDeferringAcquisition() ?? false);
if (subscription) this.changeSubscriptions.delete(subscription);
}
});
if (options.onStatusChange) subscription.on(`status:change`, options.onStatusChange);
if (options.includeInitialState) subscription.requestSnapshot({
trackLoadSubsetPromise: false,
orderBy: options.orderBy,
limit: options.limit,
onLoadSubsetResult: options.onLoadSubsetResult
});
else if (options.includeInitialState === false) subscription.markAllStateAsSeen();
if (!setupState.closed) this.changeSubscriptions.add(subscription);
} catch (error) {
if (subscription) try {
subscription.unsubscribe();
} catch {}
else this.eB(defersAcquisition);
throw error;
}
return subscription;
}
/** Whether this Collection had a subscriber or a preload in this sync run. */
hasSubscriberOrPreload() {
return this.f2 || this.acquiringSubscribersCount > 0;
}
/** Listen for the first subscriber or preload in the current sync run. */
onFirstSubscriberOrPreload(listener) {
this.ex.add(listener);
return () => this.ex.delete(listener);
}
/**
* Record a subscriber or a preload in the current sync run. A live-query
* Collection listens for the first one to resume deferred acquisition on its
* own source subscriptions.
*/
markSubscriberOrPreload() {
if (this.f2) return;
this.f2 = true;
const errors = [];
for (const listener of [...this.ex]) try {
listener();
} catch (error) {
errors.push(error);
}
if (errors.length) throw errors[0];
}
/** A deferring subscription resumed: it may now start this sync run. */
gA() {
this.lifecycle.assertCanStartSync();
this.gT();
return () => this.e2(1);
}
gT() {
const syncRunGeneration = this.sync.getSyncRunGeneration();
this.markSubscriberOrPreload();
if (syncRunGeneration !== this.sync.getSyncRunGeneration()) return;
this.gr();
this.sync.resumeStart();
}
e2(delta) {
const previous = this.acquiringSubscribersCount;
this.acquiringSubscribersCount += delta;
this.events.emitSubscribersChange(this.acquiringSubscribersCount, previous);
if (delta === 1 && this.acquiringSubscribersCount > 0) this.markSubscriberOrPreload();
}
gr() {
if (this.lifecycle.status === `cleaned-up` || this.lifecycle.status === `idle`) this.sync.startSync();
}
/**
* Increment the active subscribers count and start sync if needed. A
* subscriber that defers acquisition starts no provider work. It still
* starts a live-query Collection, whose sync run reads local memory and
* defers its own acquisition, but no other Collection's sync run.
*/
ei(defersAcquisition) {
if (!defersAcquisition) this.lifecycle.assertCanStartSync();
this.activeSubscribersCount++;
this.lifecycle.cancelGCTimer();
let acquiring = false;
try {
if (!defersAcquisition) this.gT();
else if (!this.lifecycle.isCleaningUp() && require_collection_registry.getBuilderFromConfig(this.collection.config)) this.gr();
if (!defersAcquisition) {
acquiring = true;
this.e2(1);
}
} catch (error) {
this.activeSubscribersCount--;
if (acquiring) try {
this.e2(-1);
} catch {}
if (this.activeSubscribersCount === 0) this.lifecycle.startGCTimer();
throw error;
}
}
/**
* Decrement the active subscribers count and start GC timer if needed
*/
eB(wasDeferring) {
this.activeSubscribersCount--;
if (this.activeSubscribersCount === 0) this.lifecycle.startGCTimer();
else if (this.activeSubscribersCount < 0) throw new require_errors.NegativeActiveSubscribersError();
if (!wasDeferring) this.e2(-1);
}
/**
* Clean up the collection by stopping sync and clearing data
* This can be called manually or automatically by garbage collection
*/
cleanup() {
this.f2 = [...this.changeSubscriptions].some((subscription) => !subscription.isDeferringAcquisition());
this.stateRevision++;
this.batchedEvents = [];
this.shouldBatchEvents = false;
if (this.aN) this.aN.publications.length = 0;
this.aN = void 0;
}
};
exports.CollectionChangesManager = CollectionChangesManager;
//# sourceMappingURL=changes.cjs.map