UNPKG

@electric-sql/d2ts

Version:

D2TS is a TypeScript implementation of Differential Dataflow.

97 lines 2.57 kB
import { DifferenceStreamWriter, } from './graph.js'; import { Antichain } from './order.js'; export class D2 { #streams = []; #operators = []; #frontierStack = []; #nextOperatorId = 0; #finalized = false; constructor({ initialFrontier }) { this.#frontierStack = [Antichain.create(initialFrontier)]; } #checkNotFinalized() { if (this.#finalized) { throw new Error('Graph already finalized'); } } getNextOperatorId() { this.#checkNotFinalized(); return this.#nextOperatorId++; } newInput() { this.#checkNotFinalized(); const writer = new DifferenceStreamWriter(); // Use the root stream builder that exposes the sendData and sendFrontier methods const streamBuilder = new RootStreamBuilder(this, writer); this.#streams.push(streamBuilder.connectReader()); return streamBuilder; } addOperator(operator) { this.#checkNotFinalized(); this.#operators.push(operator); } addStream(stream) { this.#checkNotFinalized(); this.#streams.push(stream); } frontier() { return this.#frontierStack[this.#frontierStack.length - 1]; } pushFrontier(newFrontier) { this.#frontierStack.push(newFrontier); } popFrontier() { this.#frontierStack.pop(); } finalize() { this.#checkNotFinalized(); this.#finalized = true; } step() { if (!this.#finalized) { throw new Error('Graph not finalized'); } for (const op of this.#operators) { op.run(); } } pendingWork() { return this.#operators.some((op) => op.hasPendingWork()); } run() { while (this.pendingWork()) { this.step(); } } } export class StreamBuilder { #graph; #writer; constructor(graph, writer) { this.#graph = graph; this.#writer = writer; } connectReader() { return this.#writer.newReader(); } get writer() { return this.#writer; } get graph() { return this.#graph; } pipe(...operators) { return operators.reduce((stream, operator) => { return operator(stream); }, this); } } export class RootStreamBuilder extends StreamBuilder { sendData(version, collection) { this.writer.sendData(version, collection); } sendFrontier(frontier) { this.writer.sendFrontier(frontier); } } //# sourceMappingURL=d2.js.map