import { Actor, Assertion, Ref, Turn } from './actor.js'; import { Dictionary, Record } from '@preserves/core'; import { Dataspace } from './dataspace.js'; import { Worker } from 'worker_threads'; import { Relay, spawnRelay } from './relay.js'; import path from 'path'; import { attenuate, CRec, Lit, Pattern, PCompound, rfilter, ConstructorSpec } from './rewrite.js'; import { $BoxState, $SetBox } from './gen/box-protocol.js'; import { $Observe } from './gen/dataspace.js'; const Instance = Record.makeConstructor<{moduleName: string, arg: Assertion}>()( Symbol.for('Instance'), ['moduleName', 'arg']); function spawnWorker(t: Turn, moduleName: string, arg: Assertion) { const w = new Worker(path.join(__dirname, 'wload.js')); spawnRelay(t, { packetWriter: bs => w.postMessage(bs), setup(t: Turn, r: Relay) { w.on('message', bs => r.accept(bs)); w.on('error', err => Turn.for(t.actor, t => t.crash(err))); w.on('exit', code => Turn.for(t.actor, t => { if (code === 0) { t.quit(); } else { t.crash(new Error(`Worker crashed with code ${code}`)); } })); }, initialOid: 0, }).then(factory => Turn.for(new Actor(), t => { t.assert(factory!, Instance(moduleName, arg)); })); } function spawnModule(t: Turn, moduleName: string, arg: Assertion) { import(moduleName).then(m => t.freshen(t => t.spawn(t => m.default(t, arg)))); } // __setNextActorId(1000); Turn.for(new Actor(), async (t: Turn) => { const ds_unproxied = t.ref(new Dataspace()); const ds = ds_unproxied; // const { proxy: ds, revoker } = forwarder(t, ds_unproxied); // t.spawn(t => { // t.assert(ds, Observe(SetBox.constructorInfo.label, t.ref({ // message(t: Turn, [newValue]: [number]): void { // if (newValue === 30000) { // console.log('BOOM!'); // t.message(revoker, true); // } // } // }))); // }); const ds_for_box = attenuate( ds, rfilter( Pattern.PCompound(PCompound(ConstructorSpec.CRec(CRec($BoxState, 1)), new Dictionary())), Pattern.PCompound(PCompound(ConstructorSpec.CRec(CRec($Observe, 2)), new Dictionary([ [0, Pattern.Lit(Lit($SetBox))]]))))); const ds_for_client = attenuate( ds_unproxied, rfilter( Pattern.PCompound(PCompound(ConstructorSpec.CRec(CRec($SetBox, 1)), new Dictionary())), Pattern.PCompound(PCompound(ConstructorSpec.CRec(CRec($Observe, 2)), new Dictionary([ [0, Pattern.Lit(Lit($BoxState))]]))))); const boxpath = path.join(__dirname, 'box.js'); const clientpath = path.join(__dirname, 'client.js'); spawnModule(t, boxpath, [ds_for_box, 500000, 25000]); // spawnWorker(t, boxpath, [ds_for_box, 50000, 2500]); spawnModule(t, clientpath, ds_for_client); // spawnWorker(t, clientpath, ds_for_client); });