@electric-sql/d2mini
Version:
D2Mini is a minimal implementation of Differential Dataflow for performing in-memory incremental view maintenance.
81 lines • 2.08 kB
JavaScript
import { DifferenceStreamWriter, } from './graph.js';
export class D2 {
#streams = [];
#operators = [];
#nextOperatorId = 0;
#finalized = false;
constructor() { }
#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);
}
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(collection) {
this.writer.sendData(collection);
}
}
//# sourceMappingURL=d2.js.map