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

79 lines
2.4 KiB
TypeScript

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