@tanstack/offline-transactions
Version:
Offline-first transaction capabilities for TanStack DB
106 lines (105 loc) • 3 kB
JavaScript
;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const tracer = require("../telemetry/tracer.cjs");
class KeyScheduler {
constructor() {
this.pendingTransactions = [];
this.isRunning = false;
}
schedule(transaction) {
tracer.withSyncSpan(
`scheduler.schedule`,
{
"transaction.id": transaction.id,
queueLength: this.pendingTransactions.length
},
() => {
this.pendingTransactions.push(transaction);
this.pendingTransactions.sort(
(a, b) => a.createdAt.getTime() - b.createdAt.getTime()
);
}
);
}
getNext() {
return tracer.withSyncSpan(
`scheduler.getNext`,
{ pendingCount: this.pendingTransactions.length },
(span) => {
if (this.isRunning || 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.isRunning = true;
}
markCompleted(transaction) {
this.removeTransaction(transaction);
this.isRunning = false;
}
markFailed(_transaction) {
this.isRunning = false;
}
removeTransaction(transaction) {
const index = this.pendingTransactions.findIndex(
(tx) => tx.id === transaction.id
);
if (index >= 0) {
this.pendingTransactions.splice(index, 1);
}
}
updateTransaction(transaction) {
const index = this.pendingTransactions.findIndex(
(tx) => tx.id === transaction.id
);
if (index >= 0) {
this.pendingTransactions[index] = transaction;
this.pendingTransactions.sort(
(a, b) => a.createdAt.getTime() - b.createdAt.getTime()
);
}
}
getPendingCount() {
return this.pendingTransactions.length;
}
getRunningCount() {
return this.isRunning ? 1 : 0;
}
clear() {
this.pendingTransactions = [];
this.isRunning = false;
}
getAllPendingTransactions() {
return [...this.pendingTransactions];
}
updateTransactions(updatedTransactions) {
for (const updatedTx of updatedTransactions) {
const index = this.pendingTransactions.findIndex(
(tx) => tx.id === updatedTx.id
);
if (index >= 0) {
this.pendingTransactions[index] = updatedTx;
}
}
this.pendingTransactions.sort(
(a, b) => a.createdAt.getTime() - b.createdAt.getTime()
);
}
}
exports.KeyScheduler = KeyScheduler;
//# sourceMappingURL=KeyScheduler.cjs.map