syndicate-js/packages/core/examples/box-and-client.ts

67 lines
2.1 KiB
TypeScript

#!/usr/bin/env -S npx ts-node -O '{"module": "commonjs"}'
/// SPDX-License-Identifier: GPL-3.0-or-later
/// SPDX-FileCopyrightText: Copyright © 2016-2023 Tony Garnock-Jones <tonyg@leastfixedpoint.com>
import {
Pattern as P,
assertObserve,
Record,
Dataspace, Turn,
} from '..';
const BoxState = Record.makeConstructor<{value: number}>()(Symbol.for('BoxState'), ['value']);
const SetBox = Record.makeConstructor<{newValue: number}>()(Symbol.for('SetBox'), ['newValue']);
const N = 100000;
console.time('box-and-client-' + N.toString());
Dataspace.boot(ds => {
Turn.active.spawn(() => {
Turn.activeFacet.actor.name = 'box';
const boxValue = Turn.active.field<number>(0, 'value');
Turn.active.assertDataflow(() => {
// console.log('recomputing published BoxState', boxValue.value);
return {
target: ds,
assertion: BoxState(boxValue.value),
};
});
Turn.active.dataflow(() => {
// console.log('dataflow saw new value', boxValue.value);
if (boxValue.value === N) {
Turn.active.stop(Turn.activeFacet, () => {
console.log('terminated box root facet');
});
}
});
assertObserve(ds, P.rec(SetBox.constructorInfo.label, P.bind()), {
message([v]: [number]) {
boxValue.value = v;
// console.log('box updated value', v);
}
});
});
Turn.active.spawn(() => {
Turn.activeFacet.actor.name = 'client';
assertObserve(ds, P.rec(BoxState.constructorInfo.label, P.bind()), {
assert([v]: [number], _handle) {
// console.log('client sending SetBox', v + 1);
Turn.active.message(ds, SetBox(v + 1));
}
});
assertObserve(ds, P.rec(BoxState.constructorInfo.label, P._), {
retract() {
console.log('box gone');
console.timeEnd('box-and-client-' + N.toString());
}
});
});
});