From 1de1e9d382b97172c020212942d5db23a2069145 Mon Sep 17 00:00:00 2001 From: Tony Garnock-Jones Date: Sun, 28 May 2023 12:25:44 +0200 Subject: [PATCH] DataspaceObserver, for reflection --- packages/core/src/runtime/dataspace.ts | 53 ++++++++++++++++---------- 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/packages/core/src/runtime/dataspace.ts b/packages/core/src/runtime/dataspace.ts index 88cc787..9521e1f 100644 --- a/packages/core/src/runtime/dataspace.ts +++ b/packages/core/src/runtime/dataspace.ts @@ -15,11 +15,41 @@ export type DataspaceOptions = { dumpIndex?: boolean, }; +export class DataspaceObserver implements IndexObserver { + readonly captureMap = new KeyedDictionary, Handle, Ref>(); + + constructor( + public readonly target: Ref, + ) {} + + onAssert(captures: Assertion[], t: Turn) { + this.captureMap.set(captures, t.assert(this.target, captures)); + } + + onRetract(vs: Assertion[], t: Turn) { + t.retract(this.captureMap.get(vs)); + this.captureMap.delete(vs); + } + + onMessage(vs: Assertion[], t: Turn) { + t.message(this.target, vs); + } + + onRemoval(t: Turn) { + this.captureMap.forEach((handle, _captures) => t.retract(handle)); + } + + dump(): string { + return Array.from(this.captureMap.entries()).map((handle, values) => + `captured ${stringify(values)} handle ${handle}`).join('\n'); + } +} + export class Dataspace implements Partial { readonly options: DataspaceOptions; readonly index = new Index(); readonly handleMap = new IdentityMap(); - readonly observerMap = new IdentityMap>(); + readonly observerMap = new IdentityMap(); readonly data = this; constructor(options?: DataspaceOptions) { @@ -33,26 +63,7 @@ export class Dataspace implements Partial { const o = toObserve(v); if (o !== void 0) { const target = o.observer; - const captureMap = new KeyedDictionary, Handle, Ref>(); - const observer: IndexObserver = { - onAssert(captures, t: Turn) { - captureMap.set(captures, t.assert(target, captures)); - }, - onRetract(vs, t: Turn) { - t.retract(captureMap.get(vs)); - captureMap.delete(vs); - }, - onMessage(vs, t: Turn) { - t.message(target, vs); - }, - onRemoval(t: Turn) { - captureMap.forEach((handle, _captures) => t.retract(handle)); - }, - dump(): string { - return Array.from(captureMap.entries()).map((handle, values) => - `captured ${stringify(values)} handle ${handle}`).join('\n'); - }, - }; + const observer = new DataspaceObserver(target); this.observerMap.set(target, observer); this.index.addObserver(o.pattern, observer, Turn.active); }