@tanstack/offline-transactions
Version:
Offline-first transaction capabilities for TanStack DB
111 lines (110 loc) • 3.28 kB
JavaScript
import { withSyncSpan } from "../telemetry/tracer.js";
class KeyScheduler {
constructor() {
this.pendingTransactions = [];
}
schedule(transaction) {
return withSyncSpan(
`scheduler.schedule`,
{
"transaction.id": transaction.id,
queueLength: this.pendingTransactions.length
},
() => {
if (this.pendingTransactions.some(
(pending) => pending.id === transaction.id
)) {
return false;
}
this.pendingTransactions.push(transaction);
this.pendingTransactions.sort(
(a, b) => a.createdAt.getTime() - b.createdAt.getTime()
);
return true;
}
);
}
getNext() {
return withSyncSpan(
`scheduler.getNext`,
{ pendingCount: this.pendingTransactions.length },
(span) => {
if (this.activeTransactionId !== void 0 || this.pendingTransactions.length === 0) {
span.setAttribute(`result`, `empty`);
return void 0;
}
const firstTransaction = this.pendingTransactions[0];
if (!this.isReadyToRun(firstTransaction)) {
span.setAttribute(`result`, `waiting_for_first`);
span.setAttribute(`transaction.id`, firstTransaction.id);
return void 0;
}
span.setAttribute(`result`, `found`);
span.setAttribute(`transaction.id`, firstTransaction.id);
return firstTransaction;
}
);
}
isReadyToRun(transaction) {
return Date.now() >= transaction.nextAttemptAt;
}
markStarted(transaction) {
this.activeTransactionId = transaction.id;
}
markCompleted(transaction) {
this.removeTransaction(transaction);
this.activeTransactionId = void 0;
}
markFailed(_transaction) {
this.activeTransactionId = void 0;
}
removeTransaction(transaction) {
const index = this.pendingTransactions.findIndex(
(tx) => tx.id === transaction.id
);
if (index >= 0) {
this.pendingTransactions.splice(index, 1);
}
}
updateTransaction(transaction) {
this.updateTransactions([transaction]);
}
getPendingCount() {
return this.pendingTransactions.length;
}
getRunningCount() {
return this.activeTransactionId === void 0 ? 0 : 1;
}
clear() {
this.pendingTransactions = [];
this.activeTransactionId = void 0;
}
/** @internal Reconcile one replay snapshot without canceling issued work. */
removePendingTransactions(transactionIds) {
const ids = new Set(transactionIds);
if (this.activeTransactionId !== void 0)
ids.delete(this.activeTransactionId);
this.pendingTransactions = this.pendingTransactions.filter(
({ id }) => !ids.has(id)
);
return [...ids];
}
getAllPendingTransactions() {
return [...this.pendingTransactions];
}
updateTransactions(updatedTransactions) {
const updatedById = new Map(
updatedTransactions.map((transaction) => [transaction.id, transaction])
);
this.pendingTransactions = this.pendingTransactions.map(
(transaction) => updatedById.get(transaction.id) ?? transaction
);
this.pendingTransactions.sort(
(a, b) => a.createdAt.getTime() - b.createdAt.getTime()
);
}
}
export {
KeyScheduler
};
//# sourceMappingURL=KeyScheduler.js.map