@milaboratories/pl-tree 1.8.47 → 1.8.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/_virtual/_rolldown/runtime.cjs +29 -0
  2. package/dist/accessors.cjs +236 -273
  3. package/dist/accessors.cjs.map +1 -1
  4. package/dist/accessors.d.ts +93 -93
  5. package/dist/accessors.js +235 -271
  6. package/dist/accessors.js.map +1 -1
  7. package/dist/dump.cjs +79 -80
  8. package/dist/dump.cjs.map +1 -1
  9. package/dist/dump.d.ts +16 -18
  10. package/dist/dump.js +79 -79
  11. package/dist/dump.js.map +1 -1
  12. package/dist/index.cjs +31 -35
  13. package/dist/index.d.ts +10 -10
  14. package/dist/index.js +9 -8
  15. package/dist/snapshot.cjs +50 -71
  16. package/dist/snapshot.cjs.map +1 -1
  17. package/dist/snapshot.d.ts +36 -38
  18. package/dist/snapshot.js +49 -69
  19. package/dist/snapshot.js.map +1 -1
  20. package/dist/state.cjs +487 -624
  21. package/dist/state.cjs.map +1 -1
  22. package/dist/state.d.ts +117 -116
  23. package/dist/state.js +486 -622
  24. package/dist/state.js.map +1 -1
  25. package/dist/sync.cjs +113 -133
  26. package/dist/sync.cjs.map +1 -1
  27. package/dist/sync.d.ts +37 -33
  28. package/dist/sync.js +111 -131
  29. package/dist/sync.js.map +1 -1
  30. package/dist/synchronized_tree.cjs +167 -232
  31. package/dist/synchronized_tree.cjs.map +1 -1
  32. package/dist/synchronized_tree.d.ts +66 -68
  33. package/dist/synchronized_tree.js +165 -211
  34. package/dist/synchronized_tree.js.map +1 -1
  35. package/dist/traversal_ops.d.ts +42 -42
  36. package/dist/value_and_error.cjs +9 -12
  37. package/dist/value_and_error.cjs.map +1 -1
  38. package/dist/value_and_error.d.ts +8 -5
  39. package/dist/value_and_error.js +9 -11
  40. package/dist/value_and_error.js.map +1 -1
  41. package/dist/value_or_error.d.ts +8 -5
  42. package/package.json +9 -9
  43. package/src/synchronized_tree.ts +10 -5
  44. package/dist/accessors.d.ts.map +0 -1
  45. package/dist/dump.d.ts.map +0 -1
  46. package/dist/index.cjs.map +0 -1
  47. package/dist/index.d.ts.map +0 -1
  48. package/dist/index.js.map +0 -1
  49. package/dist/snapshot.d.ts.map +0 -1
  50. package/dist/state.d.ts.map +0 -1
  51. package/dist/sync.d.ts.map +0 -1
  52. package/dist/synchronized_tree.d.ts.map +0 -1
  53. package/dist/test_utils.d.ts +0 -25
  54. package/dist/test_utils.d.ts.map +0 -1
  55. package/dist/traversal_ops.d.ts.map +0 -1
  56. package/dist/value_and_error.d.ts.map +0 -1
  57. package/dist/value_or_error.d.ts.map +0 -1
@@ -1,235 +1,170 @@
1
- 'use strict';
1
+ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
2
+ const require_accessors = require('./accessors.cjs');
3
+ const require_state = require('./state.cjs');
4
+ const require_sync = require('./sync.cjs');
5
+ let _milaboratories_pl_client = require("@milaboratories/pl-client");
6
+ let _milaboratories_computable = require("@milaboratories/computable");
7
+ let node_timers_promises = require("node:timers/promises");
8
+ node_timers_promises = require_runtime.__toESM(node_timers_promises);
2
9
 
3
- var computable = require('@milaboratories/computable');
4
- var accessors = require('./accessors.cjs');
5
- var plClient = require('@milaboratories/pl-client');
6
- var state = require('./state.cjs');
7
- var sync = require('./sync.cjs');
8
- var tp = require('node:timers/promises');
9
-
10
- function _interopNamespaceDefault(e) {
11
- var n = Object.create(null);
12
- if (e) {
13
- Object.keys(e).forEach(function (k) {
14
- if (k !== 'default') {
15
- var d = Object.getOwnPropertyDescriptor(e, k);
16
- Object.defineProperty(n, k, d.get ? d : {
17
- enumerable: true,
18
- get: function () { return e[k]; }
19
- });
20
- }
21
- });
22
- }
23
- n.default = e;
24
- return Object.freeze(n);
25
- }
26
-
27
- var tp__namespace = /*#__PURE__*/_interopNamespaceDefault(tp);
28
-
29
- class SynchronizedTreeState {
30
- pl;
31
- root;
32
- logger;
33
- finalPredicate;
34
- state;
35
- pollingInterval;
36
- pruning;
37
- logStat;
38
- hooks;
39
- abortController = new AbortController();
40
- constructor(pl, root, ops, logger) {
41
- this.pl = pl;
42
- this.root = root;
43
- this.logger = logger;
44
- const { finalPredicateOverride, pruning, pollingInterval, stopPollingDelay, logStat } = ops;
45
- this.pruning = pruning;
46
- this.pollingInterval = pollingInterval;
47
- this.finalPredicate = finalPredicateOverride ?? pl.finalPredicate;
48
- this.logStat = logStat;
49
- this.state = new state.PlTreeState(root, this.finalPredicate);
50
- this.hooks = new computable.PollingComputableHooks(() => this.startUpdating(), () => this.stopUpdating(), { stopDebounce: stopPollingDelay }, (resolve, reject) => this.scheduleOnNextState(resolve, reject));
51
- }
52
- /** @deprecated use "entry" instead */
53
- accessor(rid = this.root) {
54
- if (this.terminated)
55
- throw new Error("tree synchronization is terminated");
56
- return this.entry(rid);
57
- }
58
- entry(rid = this.root) {
59
- if (this.terminated)
60
- throw new Error("tree synchronization is terminated");
61
- return new accessors.PlTreeEntry({ treeProvider: () => this.state, hooks: this.hooks }, rid);
62
- }
63
- /** Can be used to externally kick off the synchronization polling loop, and
64
- * await for the first synchronization to happen. */
65
- async refreshState() {
66
- if (this.terminated)
67
- throw new Error("tree synchronization is terminated");
68
- await this.hooks.refreshState();
69
- }
70
- currentLoopDelayInterrupt = undefined;
71
- scheduledOnNextState = [];
72
- /** Called from computable hooks when external observer asks for state refresh */
73
- scheduleOnNextState(resolve, reject) {
74
- if (this.terminated)
75
- reject(new Error("tree synchronization is terminated"));
76
- else {
77
- this.scheduledOnNextState.push({ resolve, reject });
78
- if (this.currentLoopDelayInterrupt) {
79
- this.currentLoopDelayInterrupt.abort();
80
- this.currentLoopDelayInterrupt = undefined;
81
- }
82
- }
83
- }
84
- /** Called from observer */
85
- startUpdating() {
86
- if (this.terminated)
87
- return;
88
- this.keepRunning = true;
89
- if (this.currentLoop === undefined)
90
- this.currentLoop = this.mainLoop();
91
- }
92
- /** Called from observer */
93
- stopUpdating() {
94
- this.keepRunning = false;
95
- }
96
- /** If true, main loop will continue polling pl state. */
97
- keepRunning = false;
98
- /** Actual state of main loop. */
99
- currentLoop = undefined;
100
- /** Executed from the main loop, and initialization procedure. */
101
- async refresh(stats, txOps) {
102
- if (this.terminated)
103
- throw new Error("tree synchronization is terminated");
104
- const request = sync.constructTreeLoadingRequest(this.state, this.pruning);
105
- const data = await this.pl.withReadTx("ReadingTree", async (tx) => {
106
- return await sync.loadTreeState(tx, request, stats);
107
- }, txOps);
108
- this.state.updateFromResourceData(data, true);
109
- }
110
- /** If true this tree state is permanently terminaed. */
111
- terminated = false;
112
- async mainLoop() {
113
- // will hold request stats
114
- let stat = this.logStat ? sync.initialTreeLoadingStat() : undefined;
115
- let lastUpdate = Date.now();
116
- while (true) {
117
- if (!this.keepRunning || this.terminated)
118
- break;
119
- // saving those who want to be notified about new state here
120
- // because those who will be added during the tree retrieval
121
- // should be notified only on the next round
122
- let toNotify = undefined;
123
- if (this.scheduledOnNextState.length > 0) {
124
- toNotify = this.scheduledOnNextState;
125
- this.scheduledOnNextState = [];
126
- }
127
- try {
128
- // resetting stats if we were asked to collect non-cumulative stats
129
- if (this.logStat === "per-request")
130
- stat = sync.initialTreeLoadingStat();
131
- // actual tree synchronization
132
- await this.refresh(stat);
133
- // logging stats if we were asked to
134
- if (stat && this.logger)
135
- this.logger.info(`Tree stat (success, after ${Date.now() - lastUpdate}ms): ${JSON.stringify(stat)}`);
136
- lastUpdate = Date.now();
137
- // notifying that we got new state
138
- if (toNotify !== undefined)
139
- for (const n of toNotify)
140
- n.resolve();
141
- }
142
- catch (e) {
143
- // logging stats if we were asked to (even if error occured)
144
- if (stat && this.logger)
145
- this.logger.info(`Tree stat (error, after ${Date.now() - lastUpdate}ms): ${JSON.stringify(stat)}`);
146
- lastUpdate = Date.now();
147
- // notifying that we failed to refresh the state
148
- if (toNotify !== undefined)
149
- for (const n of toNotify)
150
- n.reject(e);
151
- // catching tree update errors, as they may leave our tree in inconsistent state
152
- if (e instanceof state.TreeStateUpdateError) {
153
- // important error logging, this should never happen
154
- this.logger?.error(e);
155
- // marking everybody who used previous state as changed
156
- this.state.invalidateTree("stat update error");
157
- // creating new tree
158
- this.state = new state.PlTreeState(this.root, this.finalPredicate);
159
- // scheduling state update without delay
160
- continue;
161
- // unfortunately external observer may still see tree in its default
162
- // empty state, though this is best we can do in this exceptional
163
- // situation, and hope on caching layers inside computables to present
164
- // some stale state until we reconstruct the tree again
165
- }
166
- else
167
- this.logger?.warn(e);
168
- }
169
- if (!this.keepRunning || this.terminated)
170
- break;
171
- if (this.scheduledOnNextState.length === 0) {
172
- try {
173
- this.currentLoopDelayInterrupt = new AbortController();
174
- await tp__namespace.setTimeout(this.pollingInterval, AbortSignal.any([this.abortController.signal, this.currentLoopDelayInterrupt.signal]));
175
- }
176
- catch (e) {
177
- if (!plClient.isTimeoutOrCancelError(e))
178
- throw new Error("Unexpected error", { cause: e });
179
- break;
180
- }
181
- finally {
182
- this.currentLoopDelayInterrupt = undefined;
183
- }
184
- }
185
- }
186
- // reset only as a very last line
187
- this.currentLoop = undefined;
188
- }
189
- /**
190
- * Dumps the current state of the tree.
191
- * @returns An array of ExtendedResourceData objects representing the current state of the tree.
192
- */
193
- dumpState() {
194
- return this.state.dumpState();
195
- }
196
- /**
197
- * Terminates the internal loop, and permanently destoys all internal state, so
198
- * all computables using this state will resolve to errors.
199
- * */
200
- async terminate() {
201
- this.keepRunning = false;
202
- this.terminated = true;
203
- this.abortController.abort();
204
- if (this.currentLoop === undefined)
205
- return;
206
- await this.currentLoop;
207
- this.state.invalidateTree("synchronization terminated for the tree");
208
- }
209
- /** @deprecated */
210
- async awaitSyncLoopTermination() {
211
- if (this.currentLoop === undefined)
212
- return;
213
- await this.currentLoop;
214
- }
215
- static async init(pl, root, ops, logger) {
216
- const tree = new SynchronizedTreeState(pl, root, ops, logger);
217
- const stat = ops.logStat ? sync.initialTreeLoadingStat() : undefined;
218
- let ok = false;
219
- try {
220
- await tree.refresh(stat, {
221
- timeout: ops.initialTreeLoadingTimeout,
222
- });
223
- ok = true;
224
- }
225
- finally {
226
- // logging stats if we were asked to (even if error occured)
227
- if (stat && logger)
228
- logger.info(`Tree stat (initial load, ${ok ? "success" : "failure"}): ${JSON.stringify(stat)}`);
229
- }
230
- return tree;
231
- }
232
- }
10
+ //#region src/synchronized_tree.ts
11
+ var SynchronizedTreeState = class SynchronizedTreeState {
12
+ finalPredicate;
13
+ state;
14
+ pollingInterval;
15
+ pruning;
16
+ logStat;
17
+ hooks;
18
+ abortController = new AbortController();
19
+ constructor(pl, root, ops, logger) {
20
+ this.pl = pl;
21
+ this.root = root;
22
+ this.logger = logger;
23
+ const { finalPredicateOverride, pruning, pollingInterval, stopPollingDelay, logStat } = ops;
24
+ this.pruning = pruning;
25
+ this.pollingInterval = pollingInterval;
26
+ this.finalPredicate = finalPredicateOverride ?? pl.finalPredicate;
27
+ this.logStat = logStat;
28
+ this.state = new require_state.PlTreeState(root, this.finalPredicate);
29
+ this.hooks = new _milaboratories_computable.PollingComputableHooks(() => this.startUpdating(), () => this.stopUpdating(), { stopDebounce: stopPollingDelay }, (resolve, reject) => this.scheduleOnNextState(resolve, reject));
30
+ }
31
+ /** @deprecated use "entry" instead */
32
+ accessor(rid = this.root) {
33
+ if (this.terminated) throw new Error("tree synchronization is terminated");
34
+ return this.entry(rid);
35
+ }
36
+ entry(rid = this.root) {
37
+ if (this.terminated) throw new Error("tree synchronization is terminated");
38
+ return new require_accessors.PlTreeEntry({
39
+ treeProvider: () => this.state,
40
+ hooks: this.hooks
41
+ }, rid);
42
+ }
43
+ /** Can be used to externally kick off the synchronization polling loop, and
44
+ * await for the first synchronization to happen. */
45
+ async refreshState() {
46
+ if (this.terminated) throw new Error("tree synchronization is terminated");
47
+ await this.hooks.refreshState();
48
+ }
49
+ currentLoopDelayInterrupt = void 0;
50
+ scheduledOnNextState = [];
51
+ /** Called from computable hooks when external observer asks for state refresh */
52
+ scheduleOnNextState(resolve, reject) {
53
+ if (this.terminated) reject(/* @__PURE__ */ new Error("tree synchronization is terminated"));
54
+ else {
55
+ this.scheduledOnNextState.push({
56
+ resolve,
57
+ reject
58
+ });
59
+ if (this.currentLoopDelayInterrupt) {
60
+ this.currentLoopDelayInterrupt.abort();
61
+ this.currentLoopDelayInterrupt = void 0;
62
+ }
63
+ }
64
+ }
65
+ /** Called from observer */
66
+ startUpdating() {
67
+ if (this.terminated) return;
68
+ this.keepRunning = true;
69
+ if (this.currentLoop === void 0) this.currentLoop = this.mainLoop();
70
+ }
71
+ /** Called from observer */
72
+ stopUpdating() {
73
+ this.keepRunning = false;
74
+ }
75
+ /** If true, main loop will continue polling pl state. */
76
+ keepRunning = false;
77
+ /** Actual state of main loop. */
78
+ currentLoop = void 0;
79
+ /** Executed from the main loop, and initialization procedure. */
80
+ async refresh(stats, txOps) {
81
+ if (this.terminated) throw new Error("tree synchronization is terminated");
82
+ const request = require_sync.constructTreeLoadingRequest(this.state, this.pruning);
83
+ const data = await this.pl.withReadTx("ReadingTree", async (tx) => {
84
+ return await require_sync.loadTreeState(tx, request, stats);
85
+ }, txOps);
86
+ this.state.updateFromResourceData(data, true);
87
+ }
88
+ /** If true this tree state is permanently terminaed. */
89
+ terminated = false;
90
+ async mainLoop() {
91
+ let stat = this.logStat ? require_sync.initialTreeLoadingStat() : void 0;
92
+ let lastUpdate = Date.now();
93
+ while (true) {
94
+ if (!this.keepRunning || this.terminated) break;
95
+ let toNotify = void 0;
96
+ if (this.scheduledOnNextState.length > 0) {
97
+ toNotify = this.scheduledOnNextState;
98
+ this.scheduledOnNextState = [];
99
+ }
100
+ try {
101
+ if (this.logStat === "per-request") stat = require_sync.initialTreeLoadingStat();
102
+ await this.refresh(stat);
103
+ if (stat && this.logger) this.logger.info(`Tree stat (success, after ${Date.now() - lastUpdate}ms): ${JSON.stringify(stat)}`);
104
+ lastUpdate = Date.now();
105
+ if (toNotify !== void 0) for (const n of toNotify) n.resolve();
106
+ } catch (e) {
107
+ if (stat && this.logger) this.logger.info(`Tree stat (error, after ${Date.now() - lastUpdate}ms): ${JSON.stringify(stat)}`);
108
+ lastUpdate = Date.now();
109
+ if (toNotify !== void 0) for (const n of toNotify) n.reject(e);
110
+ if (e instanceof require_state.TreeStateUpdateError) {
111
+ this.logger?.error(e);
112
+ this.state.invalidateTree("stat update error");
113
+ this.state = new require_state.PlTreeState(this.root, this.finalPredicate);
114
+ continue;
115
+ } else this.logger?.warn(e);
116
+ }
117
+ if (!this.keepRunning || this.terminated) break;
118
+ if (this.scheduledOnNextState.length === 0) try {
119
+ this.currentLoopDelayInterrupt = new AbortController();
120
+ await node_timers_promises.setTimeout(this.pollingInterval, void 0, { signal: AbortSignal.any([this.abortController.signal, this.currentLoopDelayInterrupt.signal]) });
121
+ } catch (e) {
122
+ if (!(0, _milaboratories_pl_client.isTimeoutOrCancelError)(e)) throw new Error("Unexpected error", { cause: e });
123
+ if (this.abortController.signal.aborted) break;
124
+ } finally {
125
+ this.currentLoopDelayInterrupt = void 0;
126
+ }
127
+ }
128
+ this.currentLoop = void 0;
129
+ }
130
+ /**
131
+ * Dumps the current state of the tree.
132
+ * @returns An array of ExtendedResourceData objects representing the current state of the tree.
133
+ */
134
+ dumpState() {
135
+ return this.state.dumpState();
136
+ }
137
+ /**
138
+ * Terminates the internal loop, and permanently destoys all internal state, so
139
+ * all computables using this state will resolve to errors.
140
+ * */
141
+ async terminate() {
142
+ this.keepRunning = false;
143
+ this.terminated = true;
144
+ this.abortController.abort();
145
+ if (this.currentLoop === void 0) return;
146
+ await this.currentLoop;
147
+ this.state.invalidateTree("synchronization terminated for the tree");
148
+ }
149
+ /** @deprecated */
150
+ async awaitSyncLoopTermination() {
151
+ if (this.currentLoop === void 0) return;
152
+ await this.currentLoop;
153
+ }
154
+ static async init(pl, root, ops, logger) {
155
+ const tree = new SynchronizedTreeState(pl, root, ops, logger);
156
+ const stat = ops.logStat ? require_sync.initialTreeLoadingStat() : void 0;
157
+ let ok = false;
158
+ try {
159
+ await tree.refresh(stat, { timeout: ops.initialTreeLoadingTimeout });
160
+ ok = true;
161
+ } finally {
162
+ if (stat && logger) logger.info(`Tree stat (initial load, ${ok ? "success" : "failure"}): ${JSON.stringify(stat)}`);
163
+ }
164
+ return tree;
165
+ }
166
+ };
233
167
 
168
+ //#endregion
234
169
  exports.SynchronizedTreeState = SynchronizedTreeState;
235
- //# sourceMappingURL=synchronized_tree.cjs.map
170
+ //# sourceMappingURL=synchronized_tree.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"synchronized_tree.cjs","sources":["../src/synchronized_tree.ts"],"sourcesContent":["import { PollingComputableHooks } from \"@milaboratories/computable\";\nimport { PlTreeEntry } from \"./accessors\";\nimport type {\n FinalResourceDataPredicate,\n PlClient,\n ResourceId,\n TxOps,\n} from \"@milaboratories/pl-client\";\nimport { isTimeoutOrCancelError } from \"@milaboratories/pl-client\";\nimport type { ExtendedResourceData } from \"./state\";\nimport { PlTreeState, TreeStateUpdateError } from \"./state\";\nimport type { PruningFunction, TreeLoadingStat } from \"./sync\";\nimport { constructTreeLoadingRequest, initialTreeLoadingStat, loadTreeState } from \"./sync\";\nimport * as tp from \"node:timers/promises\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\n\ntype StatLoggingMode = \"cumulative\" | \"per-request\";\n\nexport type SynchronizedTreeOps = {\n /** Override final predicate from the PlClient */\n finalPredicateOverride?: FinalResourceDataPredicate;\n\n /** Pruning function to limit set of fields through which tree will\n * traverse during state synchronization */\n pruning?: PruningFunction;\n\n /** Interval after last sync to sleep before the next one */\n pollingInterval: number;\n /** For how long to continue polling after the last derived value access */\n stopPollingDelay: number;\n\n /** If one of the values, tree will log stats of each polling request */\n logStat?: StatLoggingMode;\n\n /** Timeout for initial tree loading. If not specified, will use default for RO tx from pl-client. */\n initialTreeLoadingTimeout?: number;\n};\n\ntype ScheduledRefresh = {\n resolve: () => void;\n reject: (err: any) => void;\n};\n\nexport class SynchronizedTreeState {\n private readonly finalPredicate: FinalResourceDataPredicate;\n private state: PlTreeState;\n private readonly pollingInterval: number;\n private readonly pruning?: PruningFunction;\n private readonly logStat?: StatLoggingMode;\n private readonly hooks: PollingComputableHooks;\n private readonly abortController = new AbortController();\n\n private constructor(\n private readonly pl: PlClient,\n private readonly root: ResourceId,\n ops: SynchronizedTreeOps,\n private readonly logger?: MiLogger,\n ) {\n const { finalPredicateOverride, pruning, pollingInterval, stopPollingDelay, logStat } = ops;\n this.pruning = pruning;\n this.pollingInterval = pollingInterval;\n this.finalPredicate = finalPredicateOverride ?? pl.finalPredicate;\n this.logStat = logStat;\n this.state = new PlTreeState(root, this.finalPredicate);\n this.hooks = new PollingComputableHooks(\n () => this.startUpdating(),\n () => this.stopUpdating(),\n { stopDebounce: stopPollingDelay },\n (resolve, reject) => this.scheduleOnNextState(resolve, reject),\n );\n }\n\n /** @deprecated use \"entry\" instead */\n public accessor(rid: ResourceId = this.root): PlTreeEntry {\n if (this.terminated) throw new Error(\"tree synchronization is terminated\");\n return this.entry(rid);\n }\n\n public entry(rid: ResourceId = this.root): PlTreeEntry {\n if (this.terminated) throw new Error(\"tree synchronization is terminated\");\n return new PlTreeEntry({ treeProvider: () => this.state, hooks: this.hooks }, rid);\n }\n\n /** Can be used to externally kick off the synchronization polling loop, and\n * await for the first synchronization to happen. */\n public async refreshState(): Promise<void> {\n if (this.terminated) throw new Error(\"tree synchronization is terminated\");\n await this.hooks.refreshState();\n }\n\n private currentLoopDelayInterrupt: AbortController | undefined = undefined;\n private scheduledOnNextState: ScheduledRefresh[] = [];\n\n /** Called from computable hooks when external observer asks for state refresh */\n private scheduleOnNextState(resolve: () => void, reject: (err: any) => void): void {\n if (this.terminated) reject(new Error(\"tree synchronization is terminated\"));\n else {\n this.scheduledOnNextState.push({ resolve, reject });\n if (this.currentLoopDelayInterrupt) {\n this.currentLoopDelayInterrupt.abort();\n this.currentLoopDelayInterrupt = undefined;\n }\n }\n }\n\n /** Called from observer */\n private startUpdating(): void {\n if (this.terminated) return;\n this.keepRunning = true;\n if (this.currentLoop === undefined) this.currentLoop = this.mainLoop();\n }\n\n /** Called from observer */\n private stopUpdating(): void {\n this.keepRunning = false;\n }\n\n /** If true, main loop will continue polling pl state. */\n private keepRunning = false;\n /** Actual state of main loop. */\n private currentLoop: Promise<void> | undefined = undefined;\n\n /** Executed from the main loop, and initialization procedure. */\n private async refresh(stats?: TreeLoadingStat, txOps?: TxOps): Promise<void> {\n if (this.terminated) throw new Error(\"tree synchronization is terminated\");\n const request = constructTreeLoadingRequest(this.state, this.pruning);\n const data = await this.pl.withReadTx(\n \"ReadingTree\",\n async (tx) => {\n return await loadTreeState(tx, request, stats);\n },\n txOps,\n );\n this.state.updateFromResourceData(data, true);\n }\n\n /** If true this tree state is permanently terminaed. */\n private terminated = false;\n\n private async mainLoop() {\n // will hold request stats\n let stat = this.logStat ? initialTreeLoadingStat() : undefined;\n\n let lastUpdate = Date.now();\n\n while (true) {\n if (!this.keepRunning || this.terminated) break;\n\n // saving those who want to be notified about new state here\n // because those who will be added during the tree retrieval\n // should be notified only on the next round\n let toNotify: ScheduledRefresh[] | undefined = undefined;\n if (this.scheduledOnNextState.length > 0) {\n toNotify = this.scheduledOnNextState;\n this.scheduledOnNextState = [];\n }\n\n try {\n // resetting stats if we were asked to collect non-cumulative stats\n if (this.logStat === \"per-request\") stat = initialTreeLoadingStat();\n\n // actual tree synchronization\n await this.refresh(stat);\n\n // logging stats if we were asked to\n if (stat && this.logger)\n this.logger.info(\n `Tree stat (success, after ${Date.now() - lastUpdate}ms): ${JSON.stringify(stat)}`,\n );\n lastUpdate = Date.now();\n\n // notifying that we got new state\n if (toNotify !== undefined) for (const n of toNotify) n.resolve();\n } catch (e: any) {\n // logging stats if we were asked to (even if error occured)\n if (stat && this.logger)\n this.logger.info(\n `Tree stat (error, after ${Date.now() - lastUpdate}ms): ${JSON.stringify(stat)}`,\n );\n lastUpdate = Date.now();\n\n // notifying that we failed to refresh the state\n if (toNotify !== undefined) for (const n of toNotify) n.reject(e);\n\n // catching tree update errors, as they may leave our tree in inconsistent state\n if (e instanceof TreeStateUpdateError) {\n // important error logging, this should never happen\n this.logger?.error(e);\n\n // marking everybody who used previous state as changed\n this.state.invalidateTree(\"stat update error\");\n // creating new tree\n this.state = new PlTreeState(this.root, this.finalPredicate);\n\n // scheduling state update without delay\n continue;\n\n // unfortunately external observer may still see tree in its default\n // empty state, though this is best we can do in this exceptional\n // situation, and hope on caching layers inside computables to present\n // some stale state until we reconstruct the tree again\n } else this.logger?.warn(e);\n }\n\n if (!this.keepRunning || this.terminated) break;\n\n if (this.scheduledOnNextState.length === 0) {\n try {\n this.currentLoopDelayInterrupt = new AbortController();\n await tp.setTimeout(\n this.pollingInterval,\n AbortSignal.any([this.abortController.signal, this.currentLoopDelayInterrupt.signal]),\n );\n } catch (e: unknown) {\n if (!isTimeoutOrCancelError(e)) throw new Error(\"Unexpected error\", { cause: e });\n break;\n } finally {\n this.currentLoopDelayInterrupt = undefined;\n }\n }\n }\n\n // reset only as a very last line\n this.currentLoop = undefined;\n }\n\n /**\n * Dumps the current state of the tree.\n * @returns An array of ExtendedResourceData objects representing the current state of the tree.\n */\n public dumpState(): ExtendedResourceData[] {\n return this.state.dumpState();\n }\n\n /**\n * Terminates the internal loop, and permanently destoys all internal state, so\n * all computables using this state will resolve to errors.\n * */\n public async terminate(): Promise<void> {\n this.keepRunning = false;\n this.terminated = true;\n this.abortController.abort();\n\n if (this.currentLoop === undefined) return;\n await this.currentLoop;\n\n this.state.invalidateTree(\"synchronization terminated for the tree\");\n }\n\n /** @deprecated */\n public async awaitSyncLoopTermination(): Promise<void> {\n if (this.currentLoop === undefined) return;\n await this.currentLoop;\n }\n\n public static async init(\n pl: PlClient,\n root: ResourceId,\n ops: SynchronizedTreeOps,\n logger?: MiLogger,\n ) {\n const tree = new SynchronizedTreeState(pl, root, ops, logger);\n\n const stat = ops.logStat ? initialTreeLoadingStat() : undefined;\n\n let ok = false;\n\n try {\n await tree.refresh(stat, {\n timeout: ops.initialTreeLoadingTimeout,\n });\n ok = true;\n } finally {\n // logging stats if we were asked to (even if error occured)\n if (stat && logger)\n logger.info(\n `Tree stat (initial load, ${ok ? \"success\" : \"failure\"}): ${JSON.stringify(stat)}`,\n );\n }\n\n return tree;\n }\n}\n"],"names":["PlTreeState","PollingComputableHooks","PlTreeEntry","constructTreeLoadingRequest","loadTreeState","initialTreeLoadingStat","TreeStateUpdateError","tp","isTimeoutOrCancelError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;MA2Ca,qBAAqB,CAAA;AAUb,IAAA,EAAA;AACA,IAAA,IAAA;AAEA,IAAA,MAAA;AAZF,IAAA,cAAc;AACvB,IAAA,KAAK;AACI,IAAA,eAAe;AACf,IAAA,OAAO;AACP,IAAA,OAAO;AACP,IAAA,KAAK;AACL,IAAA,eAAe,GAAG,IAAI,eAAe,EAAE;AAExD,IAAA,WAAA,CACmB,EAAY,EACZ,IAAgB,EACjC,GAAwB,EACP,MAAiB,EAAA;QAHjB,IAAA,CAAA,EAAE,GAAF,EAAE;QACF,IAAA,CAAA,IAAI,GAAJ,IAAI;QAEJ,IAAA,CAAA,MAAM,GAAN,MAAM;AAEvB,QAAA,MAAM,EAAE,sBAAsB,EAAE,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,OAAO,EAAE,GAAG,GAAG;AAC3F,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;AACtB,QAAA,IAAI,CAAC,eAAe,GAAG,eAAe;QACtC,IAAI,CAAC,cAAc,GAAG,sBAAsB,IAAI,EAAE,CAAC,cAAc;AACjE,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;AACtB,QAAA,IAAI,CAAC,KAAK,GAAG,IAAIA,iBAAW,CAAC,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC;QACvD,IAAI,CAAC,KAAK,GAAG,IAAIC,iCAAsB,CACrC,MAAM,IAAI,CAAC,aAAa,EAAE,EAC1B,MAAM,IAAI,CAAC,YAAY,EAAE,EACzB,EAAE,YAAY,EAAE,gBAAgB,EAAE,EAClC,CAA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AEtB,QAAA,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,yCAAyC,CAAC;IACtE;;AAGO,IAAA,MAAM,wBAAwB,GAAA;AACnC,QAAA,IAAI,IAAI,CAAC,WAAW,KAAK,SAAS;YAAE;QACpC,MAAM,IAAI,CAAC,WAAW;IACxB;IAEO,aAAa,IAAI,CACtB,EAAY,EACZ,IAAgB,EAChB,GAAwB,EACxB,MAAiB,EAAA;AAEjB,QAAA,MAAM,IAAI,GAAG,IAAI,qBAAqB,CAAC,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,CAAC;AAE7D,QAAA,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,GAAGH,2BAAsB,EAAE,GAAG,SAAS;QAE/D,IAAI,EAAE,GAAG,KAAK;AAEd,QAAA,IAAI;AACF,YAAA,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;gBACvB,OAAO,EAAE,GAAG,CAAC,yBAAyB;AACvC,aAAA,CAAC;YACF,EAAE,GAAG,IAAI;QACX;gBAAU;;YAER,IAAI,IAAI,IAAI,MAAM;gBAChB,MAAM,CAAC,IAAI,CACT,CAAA,yBAAA,EAA4B,EAAE,GAAG,SAAS,GAAG,SAAS,CAAA,GAAA,EAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA,CAAE,CACnF;QACL;AAEA,QAAA,OAAO,IAAI;IACb;AACD;;;;"}
1
+ {"version":3,"file":"synchronized_tree.cjs","names":["PlTreeState","PollingComputableHooks","PlTreeEntry","constructTreeLoadingRequest","loadTreeState","initialTreeLoadingStat","TreeStateUpdateError","tp"],"sources":["../src/synchronized_tree.ts"],"sourcesContent":["import { PollingComputableHooks } from \"@milaboratories/computable\";\nimport { PlTreeEntry } from \"./accessors\";\nimport type {\n FinalResourceDataPredicate,\n PlClient,\n ResourceId,\n TxOps,\n} from \"@milaboratories/pl-client\";\nimport { isTimeoutOrCancelError } from \"@milaboratories/pl-client\";\nimport type { ExtendedResourceData } from \"./state\";\nimport { PlTreeState, TreeStateUpdateError } from \"./state\";\nimport type { PruningFunction, TreeLoadingStat } from \"./sync\";\nimport { constructTreeLoadingRequest, initialTreeLoadingStat, loadTreeState } from \"./sync\";\nimport * as tp from \"node:timers/promises\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\n\ntype StatLoggingMode = \"cumulative\" | \"per-request\";\n\nexport type SynchronizedTreeOps = {\n /** Override final predicate from the PlClient */\n finalPredicateOverride?: FinalResourceDataPredicate;\n\n /** Pruning function to limit set of fields through which tree will\n * traverse during state synchronization */\n pruning?: PruningFunction;\n\n /** Interval after last sync to sleep before the next one */\n pollingInterval: number;\n /** For how long to continue polling after the last derived value access */\n stopPollingDelay: number;\n\n /** If one of the values, tree will log stats of each polling request */\n logStat?: StatLoggingMode;\n\n /** Timeout for initial tree loading. If not specified, will use default for RO tx from pl-client. */\n initialTreeLoadingTimeout?: number;\n};\n\ntype ScheduledRefresh = {\n resolve: () => void;\n reject: (err: any) => void;\n};\n\nexport class SynchronizedTreeState {\n private readonly finalPredicate: FinalResourceDataPredicate;\n private state: PlTreeState;\n private readonly pollingInterval: number;\n private readonly pruning?: PruningFunction;\n private readonly logStat?: StatLoggingMode;\n private readonly hooks: PollingComputableHooks;\n private readonly abortController = new AbortController();\n\n private constructor(\n private readonly pl: PlClient,\n private readonly root: ResourceId,\n ops: SynchronizedTreeOps,\n private readonly logger?: MiLogger,\n ) {\n const { finalPredicateOverride, pruning, pollingInterval, stopPollingDelay, logStat } = ops;\n this.pruning = pruning;\n this.pollingInterval = pollingInterval;\n this.finalPredicate = finalPredicateOverride ?? pl.finalPredicate;\n this.logStat = logStat;\n this.state = new PlTreeState(root, this.finalPredicate);\n this.hooks = new PollingComputableHooks(\n () => this.startUpdating(),\n () => this.stopUpdating(),\n { stopDebounce: stopPollingDelay },\n (resolve, reject) => this.scheduleOnNextState(resolve, reject),\n );\n }\n\n /** @deprecated use \"entry\" instead */\n public accessor(rid: ResourceId = this.root): PlTreeEntry {\n if (this.terminated) throw new Error(\"tree synchronization is terminated\");\n return this.entry(rid);\n }\n\n public entry(rid: ResourceId = this.root): PlTreeEntry {\n if (this.terminated) throw new Error(\"tree synchronization is terminated\");\n return new PlTreeEntry({ treeProvider: () => this.state, hooks: this.hooks }, rid);\n }\n\n /** Can be used to externally kick off the synchronization polling loop, and\n * await for the first synchronization to happen. */\n public async refreshState(): Promise<void> {\n if (this.terminated) throw new Error(\"tree synchronization is terminated\");\n await this.hooks.refreshState();\n }\n\n private currentLoopDelayInterrupt: AbortController | undefined = undefined;\n private scheduledOnNextState: ScheduledRefresh[] = [];\n\n /** Called from computable hooks when external observer asks for state refresh */\n private scheduleOnNextState(resolve: () => void, reject: (err: any) => void): void {\n if (this.terminated) reject(new Error(\"tree synchronization is terminated\"));\n else {\n this.scheduledOnNextState.push({ resolve, reject });\n if (this.currentLoopDelayInterrupt) {\n this.currentLoopDelayInterrupt.abort();\n this.currentLoopDelayInterrupt = undefined;\n }\n }\n }\n\n /** Called from observer */\n private startUpdating(): void {\n if (this.terminated) return;\n this.keepRunning = true;\n if (this.currentLoop === undefined) this.currentLoop = this.mainLoop();\n }\n\n /** Called from observer */\n private stopUpdating(): void {\n this.keepRunning = false;\n }\n\n /** If true, main loop will continue polling pl state. */\n private keepRunning = false;\n /** Actual state of main loop. */\n private currentLoop: Promise<void> | undefined = undefined;\n\n /** Executed from the main loop, and initialization procedure. */\n private async refresh(stats?: TreeLoadingStat, txOps?: TxOps): Promise<void> {\n if (this.terminated) throw new Error(\"tree synchronization is terminated\");\n const request = constructTreeLoadingRequest(this.state, this.pruning);\n const data = await this.pl.withReadTx(\n \"ReadingTree\",\n async (tx) => {\n return await loadTreeState(tx, request, stats);\n },\n txOps,\n );\n this.state.updateFromResourceData(data, true);\n }\n\n /** If true this tree state is permanently terminaed. */\n private terminated = false;\n\n private async mainLoop() {\n // will hold request stats\n let stat = this.logStat ? initialTreeLoadingStat() : undefined;\n\n let lastUpdate = Date.now();\n\n while (true) {\n if (!this.keepRunning || this.terminated) break;\n\n // saving those who want to be notified about new state here\n // because those who will be added during the tree retrieval\n // should be notified only on the next round\n let toNotify: ScheduledRefresh[] | undefined = undefined;\n if (this.scheduledOnNextState.length > 0) {\n toNotify = this.scheduledOnNextState;\n this.scheduledOnNextState = [];\n }\n\n try {\n // resetting stats if we were asked to collect non-cumulative stats\n if (this.logStat === \"per-request\") stat = initialTreeLoadingStat();\n\n // actual tree synchronization\n await this.refresh(stat);\n\n // logging stats if we were asked to\n if (stat && this.logger)\n this.logger.info(\n `Tree stat (success, after ${Date.now() - lastUpdate}ms): ${JSON.stringify(stat)}`,\n );\n lastUpdate = Date.now();\n\n // notifying that we got new state\n if (toNotify !== undefined) for (const n of toNotify) n.resolve();\n } catch (e: any) {\n // logging stats if we were asked to (even if error occured)\n if (stat && this.logger)\n this.logger.info(\n `Tree stat (error, after ${Date.now() - lastUpdate}ms): ${JSON.stringify(stat)}`,\n );\n lastUpdate = Date.now();\n\n // notifying that we failed to refresh the state\n if (toNotify !== undefined) for (const n of toNotify) n.reject(e);\n\n // catching tree update errors, as they may leave our tree in inconsistent state\n if (e instanceof TreeStateUpdateError) {\n // important error logging, this should never happen\n this.logger?.error(e);\n\n // marking everybody who used previous state as changed\n this.state.invalidateTree(\"stat update error\");\n // creating new tree\n this.state = new PlTreeState(this.root, this.finalPredicate);\n\n // scheduling state update without delay\n continue;\n\n // unfortunately external observer may still see tree in its default\n // empty state, though this is best we can do in this exceptional\n // situation, and hope on caching layers inside computables to present\n // some stale state until we reconstruct the tree again\n } else this.logger?.warn(e);\n }\n\n if (!this.keepRunning || this.terminated) break;\n\n if (this.scheduledOnNextState.length === 0) {\n try {\n this.currentLoopDelayInterrupt = new AbortController();\n await tp.setTimeout(this.pollingInterval, undefined, {\n signal: AbortSignal.any([\n this.abortController.signal,\n this.currentLoopDelayInterrupt.signal,\n ]),\n });\n } catch (e: unknown) {\n if (!isTimeoutOrCancelError(e)) throw new Error(\"Unexpected error\", { cause: e });\n // If the main abort controller fired, this is a permanent termination\n if (this.abortController.signal.aborted) break;\n // Otherwise it was just the loop delay interrupt (scheduleOnNextState),\n // continue to the next iteration\n } finally {\n this.currentLoopDelayInterrupt = undefined;\n }\n }\n }\n\n // reset only as a very last line\n this.currentLoop = undefined;\n }\n\n /**\n * Dumps the current state of the tree.\n * @returns An array of ExtendedResourceData objects representing the current state of the tree.\n */\n public dumpState(): ExtendedResourceData[] {\n return this.state.dumpState();\n }\n\n /**\n * Terminates the internal loop, and permanently destoys all internal state, so\n * all computables using this state will resolve to errors.\n * */\n public async terminate(): Promise<void> {\n this.keepRunning = false;\n this.terminated = true;\n this.abortController.abort();\n\n if (this.currentLoop === undefined) return;\n await this.currentLoop;\n\n this.state.invalidateTree(\"synchronization terminated for the tree\");\n }\n\n /** @deprecated */\n public async awaitSyncLoopTermination(): Promise<void> {\n if (this.currentLoop === undefined) return;\n await this.currentLoop;\n }\n\n public static async init(\n pl: PlClient,\n root: ResourceId,\n ops: SynchronizedTreeOps,\n logger?: MiLogger,\n ) {\n const tree = new SynchronizedTreeState(pl, root, ops, logger);\n\n const stat = ops.logStat ? initialTreeLoadingStat() : undefined;\n\n let ok = false;\n\n try {\n await tree.refresh(stat, {\n timeout: ops.initialTreeLoadingTimeout,\n });\n ok = true;\n } finally {\n // logging stats if we were asked to (even if error occured)\n if (stat && logger)\n logger.info(\n `Tree stat (initial load, ${ok ? \"success\" : \"failure\"}): ${JSON.stringify(stat)}`,\n );\n }\n\n return tree;\n }\n}\n"],"mappings":";;;;;;;;;;AA2CA,IAAa,wBAAb,MAAa,sBAAsB;CACjC,AAAiB;CACjB,AAAQ;CACR,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB,kBAAkB,IAAI,iBAAiB;CAExD,AAAQ,YACN,AAAiB,IACjB,AAAiB,MACjB,KACA,AAAiB,QACjB;EAJiB;EACA;EAEA;EAEjB,MAAM,EAAE,wBAAwB,SAAS,iBAAiB,kBAAkB,Y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7B,OAAI,CAAC,KAAK,eAAe,KAAK,WAAY;AAE1C,OAAI,KAAK,qBAAqB,WAAW,EACvC,KAAI;AACF,SAAK,4BAA4B,IAAI,iBAAiB;AACtD,UAAMO,qBAAG,WAAW,KAAK,iBAAiB,QAAW,EACnD,QAAQ,YAAY,IAAI,CACtB,KAAK,gBAAgB,QACrB,KAAK,0BAA0B,OAChC,CAAC,EACH,CAAC;YACK,GAAY;AACnB,QAAI,uDAAwB,EAAE,CAAE,OAAM,IAAI,MAAM,oBAAoB,EAAE,OAAO,GAAG,CAAC;AAEjF,QAAI,KAAK,gBAAgB,OAAO,QAAS;aAGjC;AACR,SAAK,4BAA4B;;;AAMvC,OAAK,cAAc;;;;;;CAOrB,AAAO,YAAoC;AACzC,SAAO,KAAK,MAAM,WAAW;;;;;;CAO/B,MAAa,YAA2B;AACtC,OAAK,cAAc;AACnB,OAAK,aAAa;AAClB,OAAK,gBAAgB,OAAO;AAE5B,MAAI,KAAK,gBAAgB,OAAW;AACpC,QAAM,KAAK;AAEX,OAAK,MAAM,eAAe,0CAA0C;;;CAItE,MAAa,2BAA0C;AACrD,MAAI,KAAK,gBAAgB,OAAW;AACpC,QAAM,KAAK;;CAGb,aAAoB,KAClB,IACA,MACA,KACA,QACA;EACA,MAAM,OAAO,IAAI,sBAAsB,IAAI,MAAM,KAAK,OAAO;EAE7D,MAAM,OAAO,IAAI,UAAUF,qCAAwB,GAAG;EAEtD,IAAI,KAAK;AAET,MAAI;AACF,SAAM,KAAK,QAAQ,MAAM,EACvB,SAAS,IAAI,2BACd,CAAC;AACF,QAAK;YACG;AAER,OAAI,QAAQ,OACV,QAAO,KACL,4BAA4B,KAAK,YAAY,UAAU,KAAK,KAAK,UAAU,KAAK,GACjF;;AAGL,SAAO"}
@@ -1,72 +1,70 @@
1
- import { PlTreeEntry } from "./accessors";
2
- import type { FinalResourceDataPredicate, PlClient, ResourceId } from "@milaboratories/pl-client";
3
- import type { ExtendedResourceData } from "./state";
4
- import type { PruningFunction } from "./sync";
5
- import type { MiLogger } from "@milaboratories/ts-helpers";
1
+ import { PlTreeEntry } from "./accessors.js";
2
+ import { ExtendedResourceData } from "./state.js";
3
+ import { PruningFunction } from "./sync.js";
4
+ import { FinalResourceDataPredicate, PlClient, ResourceId } from "@milaboratories/pl-client";
5
+ import { MiLogger } from "@milaboratories/ts-helpers";
6
+
7
+ //#region src/synchronized_tree.d.ts
6
8
  type StatLoggingMode = "cumulative" | "per-request";
7
- export type SynchronizedTreeOps = {
8
- /** Override final predicate from the PlClient */
9
- finalPredicateOverride?: FinalResourceDataPredicate;
10
- /** Pruning function to limit set of fields through which tree will
11
- * traverse during state synchronization */
12
- pruning?: PruningFunction;
13
- /** Interval after last sync to sleep before the next one */
14
- pollingInterval: number;
15
- /** For how long to continue polling after the last derived value access */
16
- stopPollingDelay: number;
17
- /** If one of the values, tree will log stats of each polling request */
18
- logStat?: StatLoggingMode;
19
- /** Timeout for initial tree loading. If not specified, will use default for RO tx from pl-client. */
20
- initialTreeLoadingTimeout?: number;
9
+ type SynchronizedTreeOps = {
10
+ /** Override final predicate from the PlClient */finalPredicateOverride?: FinalResourceDataPredicate;
11
+ /** Pruning function to limit set of fields through which tree will
12
+ * traverse during state synchronization */
13
+ pruning?: PruningFunction; /** Interval after last sync to sleep before the next one */
14
+ pollingInterval: number; /** For how long to continue polling after the last derived value access */
15
+ stopPollingDelay: number; /** If one of the values, tree will log stats of each polling request */
16
+ logStat?: StatLoggingMode; /** Timeout for initial tree loading. If not specified, will use default for RO tx from pl-client. */
17
+ initialTreeLoadingTimeout?: number;
21
18
  };
22
- export declare class SynchronizedTreeState {
23
- private readonly pl;
24
- private readonly root;
25
- private readonly logger?;
26
- private readonly finalPredicate;
27
- private state;
28
- private readonly pollingInterval;
29
- private readonly pruning?;
30
- private readonly logStat?;
31
- private readonly hooks;
32
- private readonly abortController;
33
- private constructor();
34
- /** @deprecated use "entry" instead */
35
- accessor(rid?: ResourceId): PlTreeEntry;
36
- entry(rid?: ResourceId): PlTreeEntry;
37
- /** Can be used to externally kick off the synchronization polling loop, and
38
- * await for the first synchronization to happen. */
39
- refreshState(): Promise<void>;
40
- private currentLoopDelayInterrupt;
41
- private scheduledOnNextState;
42
- /** Called from computable hooks when external observer asks for state refresh */
43
- private scheduleOnNextState;
44
- /** Called from observer */
45
- private startUpdating;
46
- /** Called from observer */
47
- private stopUpdating;
48
- /** If true, main loop will continue polling pl state. */
49
- private keepRunning;
50
- /** Actual state of main loop. */
51
- private currentLoop;
52
- /** Executed from the main loop, and initialization procedure. */
53
- private refresh;
54
- /** If true this tree state is permanently terminaed. */
55
- private terminated;
56
- private mainLoop;
57
- /**
58
- * Dumps the current state of the tree.
59
- * @returns An array of ExtendedResourceData objects representing the current state of the tree.
60
- */
61
- dumpState(): ExtendedResourceData[];
62
- /**
63
- * Terminates the internal loop, and permanently destoys all internal state, so
64
- * all computables using this state will resolve to errors.
65
- * */
66
- terminate(): Promise<void>;
67
- /** @deprecated */
68
- awaitSyncLoopTermination(): Promise<void>;
69
- static init(pl: PlClient, root: ResourceId, ops: SynchronizedTreeOps, logger?: MiLogger): Promise<SynchronizedTreeState>;
19
+ declare class SynchronizedTreeState {
20
+ private readonly pl;
21
+ private readonly root;
22
+ private readonly logger?;
23
+ private readonly finalPredicate;
24
+ private state;
25
+ private readonly pollingInterval;
26
+ private readonly pruning?;
27
+ private readonly logStat?;
28
+ private readonly hooks;
29
+ private readonly abortController;
30
+ private constructor();
31
+ /** @deprecated use "entry" instead */
32
+ accessor(rid?: ResourceId): PlTreeEntry;
33
+ entry(rid?: ResourceId): PlTreeEntry;
34
+ /** Can be used to externally kick off the synchronization polling loop, and
35
+ * await for the first synchronization to happen. */
36
+ refreshState(): Promise<void>;
37
+ private currentLoopDelayInterrupt;
38
+ private scheduledOnNextState;
39
+ /** Called from computable hooks when external observer asks for state refresh */
40
+ private scheduleOnNextState;
41
+ /** Called from observer */
42
+ private startUpdating;
43
+ /** Called from observer */
44
+ private stopUpdating;
45
+ /** If true, main loop will continue polling pl state. */
46
+ private keepRunning;
47
+ /** Actual state of main loop. */
48
+ private currentLoop;
49
+ /** Executed from the main loop, and initialization procedure. */
50
+ private refresh;
51
+ /** If true this tree state is permanently terminaed. */
52
+ private terminated;
53
+ private mainLoop;
54
+ /**
55
+ * Dumps the current state of the tree.
56
+ * @returns An array of ExtendedResourceData objects representing the current state of the tree.
57
+ */
58
+ dumpState(): ExtendedResourceData[];
59
+ /**
60
+ * Terminates the internal loop, and permanently destoys all internal state, so
61
+ * all computables using this state will resolve to errors.
62
+ * */
63
+ terminate(): Promise<void>;
64
+ /** @deprecated */
65
+ awaitSyncLoopTermination(): Promise<void>;
66
+ static init(pl: PlClient, root: ResourceId, ops: SynchronizedTreeOps, logger?: MiLogger): Promise<SynchronizedTreeState>;
70
67
  }
71
- export {};
68
+ //#endregion
69
+ export { SynchronizedTreeOps, SynchronizedTreeState };
72
70
  //# sourceMappingURL=synchronized_tree.d.ts.map