@milaboratories/pl-tree 1.7.5 → 1.7.7

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 (45) hide show
  1. package/dist/accessors.cjs +297 -0
  2. package/dist/accessors.cjs.map +1 -0
  3. package/dist/accessors.d.ts +6 -6
  4. package/dist/accessors.js +288 -0
  5. package/dist/accessors.js.map +1 -0
  6. package/dist/dump.cjs +86 -0
  7. package/dist/dump.cjs.map +1 -0
  8. package/dist/dump.d.ts +1 -1
  9. package/dist/dump.js +84 -0
  10. package/dist/dump.js.map +1 -0
  11. package/dist/index.cjs +36 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.js +7 -10
  14. package/dist/index.js.map +1 -1
  15. package/dist/snapshot.cjs +88 -0
  16. package/dist/snapshot.cjs.map +1 -0
  17. package/dist/snapshot.d.ts +6 -5
  18. package/dist/snapshot.js +83 -0
  19. package/dist/snapshot.js.map +1 -0
  20. package/dist/state.cjs +631 -0
  21. package/dist/state.cjs.map +1 -0
  22. package/dist/state.d.ts +7 -5
  23. package/dist/state.js +627 -0
  24. package/dist/state.js.map +1 -0
  25. package/dist/sync.cjs +156 -0
  26. package/dist/sync.cjs.map +1 -0
  27. package/dist/sync.d.ts +2 -2
  28. package/dist/sync.js +151 -0
  29. package/dist/sync.js.map +1 -0
  30. package/dist/synchronized_tree.cjs +235 -0
  31. package/dist/synchronized_tree.cjs.map +1 -0
  32. package/dist/synchronized_tree.d.ts +4 -4
  33. package/dist/synchronized_tree.js +214 -0
  34. package/dist/synchronized_tree.js.map +1 -0
  35. package/dist/test_utils.d.ts +2 -2
  36. package/dist/traversal_ops.d.ts +1 -1
  37. package/dist/value_and_error.cjs +20 -0
  38. package/dist/value_and_error.cjs.map +1 -0
  39. package/dist/value_and_error.js +17 -0
  40. package/dist/value_and_error.js.map +1 -0
  41. package/package.json +16 -14
  42. package/src/snapshot.test.ts +4 -3
  43. package/src/state.test.ts +6 -4
  44. package/dist/index.mjs +0 -904
  45. package/dist/index.mjs.map +0 -1
package/dist/state.js ADDED
@@ -0,0 +1,627 @@
1
+ import { resourceIdToString, isNotNullResourceId, NullResourceId, isNullResourceId, stringifyWithResourceId } from '@milaboratories/pl-client';
2
+ import { ChangeSource, KeyedChangeSource } from '@milaboratories/computable';
3
+ import { PlTreeEntry } from './accessors.js';
4
+ import { cachedDecode, cachedDeserialize, notEmpty } from '@milaboratories/ts-helpers';
5
+
6
+ class TreeStateUpdateError extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ }
10
+ }
11
+ class PlTreeField {
12
+ name;
13
+ type;
14
+ value;
15
+ error;
16
+ status;
17
+ valueIsFinal;
18
+ resourceVersion;
19
+ change = new ChangeSource();
20
+ constructor(name, type, value, error, status, valueIsFinal,
21
+ /** Last version of resource this field was observed, used to garbage collect fields in tree patching procedure */
22
+ resourceVersion) {
23
+ this.name = name;
24
+ this.type = type;
25
+ this.value = value;
26
+ this.error = error;
27
+ this.status = status;
28
+ this.valueIsFinal = valueIsFinal;
29
+ this.resourceVersion = resourceVersion;
30
+ }
31
+ get state() {
32
+ return {
33
+ name: this.name,
34
+ type: this.type,
35
+ status: this.status,
36
+ value: this.value,
37
+ error: this.error,
38
+ valueIsFinal: this.valueIsFinal,
39
+ };
40
+ }
41
+ }
42
+ const InitialResourceVersion = 0;
43
+ /** Never store instances of this class, always get fresh instance from {@link PlTreeState} */
44
+ class PlTreeResource {
45
+ /** Tracks number of other resources referencing this resource. Used to perform garbage collection in tree patching procedure */
46
+ refCount = 0;
47
+ /** Increments each time resource is checked for difference with new state */
48
+ version = InitialResourceVersion;
49
+ /** Set to resource version when resource state, or it's fields have changed */
50
+ dataVersion = InitialResourceVersion;
51
+ fieldsMap = new Map();
52
+ kv = new Map();
53
+ resourceRemoved = new ChangeSource();
54
+ // following change source are removed when resource is marked as final
55
+ finalChanged = new ChangeSource();
56
+ resourceStateChange = new ChangeSource();
57
+ lockedChange = new ChangeSource();
58
+ inputAndServiceFieldListChanged = new ChangeSource();
59
+ outputFieldListChanged = new ChangeSource();
60
+ dynamicFieldListChanged = new ChangeSource();
61
+ // kvChangedGlobal? = new ChangeSource();
62
+ kvChangedPerKey = new KeyedChangeSource();
63
+ id;
64
+ originalResourceId;
65
+ kind;
66
+ type;
67
+ data;
68
+ dataAsString;
69
+ dataAsJson;
70
+ error;
71
+ inputsLocked;
72
+ outputsLocked;
73
+ resourceReady;
74
+ finalFlag;
75
+ /** Set externally by the tree, using {@link FinalResourceDataPredicate} */
76
+ _finalState = false;
77
+ logger;
78
+ constructor(initialState, logger) {
79
+ this.id = initialState.id;
80
+ this.originalResourceId = initialState.originalResourceId;
81
+ this.kind = initialState.kind;
82
+ this.type = initialState.type;
83
+ this.data = initialState.data;
84
+ this.error = initialState.error;
85
+ this.inputsLocked = initialState.inputsLocked;
86
+ this.outputsLocked = initialState.outputsLocked;
87
+ this.resourceReady = initialState.resourceReady;
88
+ this.finalFlag = initialState.final;
89
+ this.logger = logger;
90
+ }
91
+ // TODO add logging
92
+ info(msg) {
93
+ if (this.logger !== undefined)
94
+ this.logger.info(msg);
95
+ }
96
+ warn(msg) {
97
+ if (this.logger !== undefined)
98
+ this.logger.warn(msg);
99
+ }
100
+ get final() {
101
+ return this.finalFlag;
102
+ }
103
+ get finalState() {
104
+ return this._finalState;
105
+ }
106
+ get fields() {
107
+ return [...this.fieldsMap.values()];
108
+ }
109
+ getField(watcher, _step, onUnstable = () => { }) {
110
+ const step = typeof _step === 'string' ? { field: _step } : _step;
111
+ const field = this.fieldsMap.get(step.field);
112
+ if (field === undefined) {
113
+ if (step.errorIfFieldNotFound || step.errorIfFieldNotSet)
114
+ throw new Error(`Field "${step.field}" not found in resource ${resourceIdToString(this.id)}`);
115
+ if (!this.inputsLocked)
116
+ this.inputAndServiceFieldListChanged?.attachWatcher(watcher);
117
+ else if (step.assertFieldType === 'Service' || step.assertFieldType === 'Input') {
118
+ if (step.allowPermanentAbsence)
119
+ // stable absence of field
120
+ return undefined;
121
+ else
122
+ throw new Error(`Service or input field not found ${step.field}.`);
123
+ }
124
+ if (!this.outputsLocked)
125
+ this.outputFieldListChanged?.attachWatcher(watcher);
126
+ else if (step.assertFieldType === 'Output') {
127
+ if (step.allowPermanentAbsence)
128
+ // stable absence of field
129
+ return undefined;
130
+ else
131
+ throw new Error(`Output field not found ${step.field}.`);
132
+ }
133
+ this.dynamicFieldListChanged?.attachWatcher(watcher);
134
+ if (!this._finalState && !step.stableIfNotFound)
135
+ onUnstable('field_not_found:' + step.field);
136
+ return undefined;
137
+ }
138
+ else {
139
+ if (step.assertFieldType !== undefined && field.type !== step.assertFieldType)
140
+ throw new Error(`Unexpected field type: expected ${step.assertFieldType} but got ${field.type} for the field name ${step.field}`);
141
+ const ret = {};
142
+ if (isNotNullResourceId(field.value))
143
+ ret.value = field.value;
144
+ if (isNotNullResourceId(field.error))
145
+ ret.error = field.error;
146
+ if (ret.value === undefined && ret.error === undefined)
147
+ // this method returns value and error of the field, thus those values are considered to be accessed;
148
+ // any existing but not resolved field here is considered to be unstable, in the sense it is
149
+ // considered to acquire some resolved value eventually
150
+ onUnstable('field_not_resolved:' + step.field);
151
+ field.change.attachWatcher(watcher);
152
+ return ret;
153
+ }
154
+ }
155
+ getInputsLocked(watcher) {
156
+ if (!this.inputsLocked)
157
+ // reverse transition can't happen, so there is no reason to wait for value to change
158
+ this.resourceStateChange?.attachWatcher(watcher);
159
+ return this.inputsLocked;
160
+ }
161
+ getOutputsLocked(watcher) {
162
+ if (!this.outputsLocked)
163
+ // reverse transition can't happen, so there is no reason to wait for value to change
164
+ this.resourceStateChange?.attachWatcher(watcher);
165
+ return this.outputsLocked;
166
+ }
167
+ get isReadyOrError() {
168
+ return (this.error !== NullResourceId
169
+ || this.resourceReady
170
+ || this.originalResourceId !== NullResourceId);
171
+ }
172
+ getIsFinal(watcher) {
173
+ this.finalChanged?.attachWatcher(watcher);
174
+ return this._finalState;
175
+ }
176
+ getIsReadyOrError(watcher) {
177
+ if (!this.isReadyOrError)
178
+ // reverse transition can't happen, so there is no reason to wait for value to change if it is already true
179
+ this.resourceStateChange?.attachWatcher(watcher);
180
+ return this.isReadyOrError;
181
+ }
182
+ getError(watcher) {
183
+ if (isNullResourceId(this.error)) {
184
+ this.resourceStateChange?.attachWatcher(watcher);
185
+ return undefined;
186
+ }
187
+ else {
188
+ // reverse transition can't happen, so there is no reason to wait for value to change, if error already set
189
+ return this.error;
190
+ }
191
+ }
192
+ listInputFields(watcher) {
193
+ const ret = [];
194
+ this.fieldsMap.forEach((field, name) => {
195
+ if (field.type === 'Input' || field.type === 'Service')
196
+ ret.push(name);
197
+ });
198
+ if (!this.inputsLocked)
199
+ this.inputAndServiceFieldListChanged?.attachWatcher(watcher);
200
+ return ret;
201
+ }
202
+ listOutputFields(watcher) {
203
+ const ret = [];
204
+ this.fieldsMap.forEach((field, name) => {
205
+ if (field.type === 'Output')
206
+ ret.push(name);
207
+ });
208
+ if (!this.outputsLocked)
209
+ this.outputFieldListChanged?.attachWatcher(watcher);
210
+ return ret;
211
+ }
212
+ listDynamicFields(watcher) {
213
+ const ret = [];
214
+ this.fieldsMap.forEach((field, name) => {
215
+ if (field.type !== 'Input' && field.type !== 'Output')
216
+ ret.push(name);
217
+ });
218
+ this.dynamicFieldListChanged?.attachWatcher(watcher);
219
+ return ret;
220
+ }
221
+ getKeyValue(watcher, key) {
222
+ this.kvChangedPerKey?.attachWatcher(key, watcher);
223
+ return this.kv.get(key);
224
+ }
225
+ getKeyValueString(watcher, key) {
226
+ const bytes = this.getKeyValue(watcher, key);
227
+ if (bytes === undefined)
228
+ return undefined;
229
+ return cachedDecode(bytes);
230
+ }
231
+ getKeyValueAsJson(watcher, key) {
232
+ const bytes = this.getKeyValue(watcher, key);
233
+ if (bytes === undefined)
234
+ return undefined;
235
+ return cachedDeserialize(bytes);
236
+ }
237
+ getDataAsString() {
238
+ if (this.data === undefined)
239
+ return undefined;
240
+ if (this.dataAsString === undefined)
241
+ this.dataAsString = cachedDecode(this.data);
242
+ return this.dataAsString;
243
+ }
244
+ getDataAsJson() {
245
+ if (this.data === undefined)
246
+ return undefined;
247
+ if (this.dataAsJson === undefined)
248
+ this.dataAsJson = cachedDeserialize(this.data);
249
+ return this.dataAsJson;
250
+ }
251
+ verifyReadyState() {
252
+ if (this.resourceReady && !this.inputsLocked)
253
+ throw new Error(`ready without input or output lock: ${stringifyWithResourceId(this.basicState)}`);
254
+ }
255
+ get basicState() {
256
+ return {
257
+ id: this.id,
258
+ kind: this.kind,
259
+ type: this.type,
260
+ data: this.data,
261
+ resourceReady: this.resourceReady,
262
+ inputsLocked: this.inputsLocked,
263
+ outputsLocked: this.outputsLocked,
264
+ error: this.error,
265
+ originalResourceId: this.originalResourceId,
266
+ final: this.finalFlag,
267
+ };
268
+ }
269
+ get extendedState() {
270
+ return {
271
+ ...this.basicState,
272
+ fields: this.fields,
273
+ kv: Array.from(this.kv.entries()).map(([key, value]) => ({ key, value })),
274
+ };
275
+ }
276
+ /** Called when {@link FinalResourceDataPredicate} returns true for the state. */
277
+ markFinal() {
278
+ if (this._finalState)
279
+ return;
280
+ this._finalState = true;
281
+ notEmpty(this.finalChanged).markChanged('marked final');
282
+ this.finalChanged = undefined;
283
+ this.resourceStateChange = undefined;
284
+ this.dynamicFieldListChanged = undefined;
285
+ this.inputAndServiceFieldListChanged = undefined;
286
+ this.outputFieldListChanged = undefined;
287
+ this.lockedChange = undefined;
288
+ // this.kvChangedGlobal = undefined;
289
+ this.kvChangedPerKey = undefined;
290
+ }
291
+ /** Used for invalidation */
292
+ markAllChanged() {
293
+ this.fieldsMap.forEach((field) => field.change.markChanged('marked all changed'));
294
+ this.finalChanged?.markChanged('marked all changed');
295
+ this.resourceStateChange?.markChanged('marked all changed');
296
+ this.lockedChange?.markChanged('marked all changed');
297
+ this.inputAndServiceFieldListChanged?.markChanged('marked all changed');
298
+ this.outputFieldListChanged?.markChanged('marked all changed');
299
+ this.dynamicFieldListChanged?.markChanged('marked all changed');
300
+ // this.kvChangedGlobal?.markChanged('marked all changed');
301
+ this.kvChangedPerKey?.markAllChanged('marked all changed');
302
+ this.resourceRemoved.markChanged('marked all changed');
303
+ }
304
+ }
305
+ class PlTreeState {
306
+ root;
307
+ isFinalPredicate;
308
+ /** resource heap */
309
+ resources = new Map();
310
+ resourcesAdded = new ChangeSource();
311
+ /** Resets to false if any invalid state transitions are registered,
312
+ * after that tree will produce errors for any read or write operations */
313
+ _isValid = true;
314
+ invalidationMessage;
315
+ constructor(
316
+ /** This will be the only resource not deleted during GC round */
317
+ root, isFinalPredicate) {
318
+ this.root = root;
319
+ this.isFinalPredicate = isFinalPredicate;
320
+ }
321
+ forEachResource(cb) {
322
+ this.resources.forEach((v) => cb(v));
323
+ }
324
+ checkValid() {
325
+ if (!this._isValid)
326
+ throw new Error(this.invalidationMessage ?? 'tree is in invalid state');
327
+ }
328
+ get(watcher, rid) {
329
+ this.checkValid();
330
+ const res = this.resources.get(rid);
331
+ if (res === undefined) {
332
+ // to make recovery from resource not found possible, considering some
333
+ // race conditions, where computable is created before tree is updated
334
+ this.resourcesAdded.attachWatcher(watcher);
335
+ throw new Error(`resource ${resourceIdToString(rid)} not found in the tree`);
336
+ }
337
+ res.resourceRemoved.attachWatcher(watcher);
338
+ return res;
339
+ }
340
+ updateFromResourceData(resourceData, allowOrphanInputs = false) {
341
+ this.checkValid();
342
+ // All resources for which recount should be incremented, first are aggregated in this list
343
+ const incrementRefs = [];
344
+ const decrementRefs = [];
345
+ // patching / creating resources
346
+ for (const rd of resourceData) {
347
+ let resource = this.resources.get(rd.id);
348
+ const statBeforeMutation = resource?.basicState;
349
+ const unexpectedTransitionError = (reason) => {
350
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
351
+ const { fields, ...rdWithoutFields } = rd;
352
+ this.invalidateTree();
353
+ throw new TreeStateUpdateError(`Unexpected resource state transition (${reason}): ${stringifyWithResourceId(rdWithoutFields)} -> ${stringifyWithResourceId(statBeforeMutation)}`);
354
+ };
355
+ if (resource !== undefined) {
356
+ // updating existing resource
357
+ if (resource.finalState)
358
+ unexpectedTransitionError('resource state can\t be updated after it is marked as final');
359
+ let changed = false;
360
+ // updating resource version, even if it was not changed
361
+ resource.version += 1;
362
+ // duplicate / original
363
+ if (resource.originalResourceId !== rd.originalResourceId) {
364
+ if (resource.originalResourceId !== NullResourceId)
365
+ unexpectedTransitionError('originalResourceId can\'t change after it is set');
366
+ resource.originalResourceId = rd.originalResourceId;
367
+ // duplicate status of the resource counts as ready for the external observer
368
+ notEmpty(resource.resourceStateChange).markChanged(`originalResourceId changed for ${resourceIdToString(resource.id)}`);
369
+ changed = true;
370
+ }
371
+ // error
372
+ if (resource.error !== rd.error) {
373
+ if (isNotNullResourceId(resource.error))
374
+ unexpectedTransitionError('resource can\'t change attached error after it is set');
375
+ resource.error = rd.error;
376
+ incrementRefs.push(resource.error);
377
+ notEmpty(resource.resourceStateChange).markChanged(`error changed for ${resourceIdToString(resource.id)}`);
378
+ changed = true;
379
+ }
380
+ // updating fields
381
+ for (const fd of rd.fields) {
382
+ let field = resource.fieldsMap.get(fd.name);
383
+ if (!field) {
384
+ // new field
385
+ field = new PlTreeField(fd.name, fd.type, fd.value, fd.error, fd.status, fd.valueIsFinal, resource.version);
386
+ if (isNotNullResourceId(fd.value))
387
+ incrementRefs.push(fd.value);
388
+ if (isNotNullResourceId(fd.error))
389
+ incrementRefs.push(fd.error);
390
+ if (fd.type === 'Input' || fd.type === 'Service') {
391
+ if (resource.inputsLocked)
392
+ unexpectedTransitionError(`adding ${fd.type} (${fd.name}) field while inputs locked`);
393
+ notEmpty(resource.inputAndServiceFieldListChanged).markChanged(`new ${fd.type} field ${fd.name} added to ${resourceIdToString(resource.id)}`);
394
+ }
395
+ else if (fd.type === 'Output') {
396
+ if (resource.outputsLocked)
397
+ unexpectedTransitionError(`adding ${fd.type} (${fd.name}) field while outputs locked`);
398
+ notEmpty(resource.outputFieldListChanged).markChanged(`new ${fd.type} field ${fd.name} added to ${resourceIdToString(resource.id)}`);
399
+ }
400
+ else {
401
+ notEmpty(resource.dynamicFieldListChanged).markChanged(`new ${fd.type} field ${fd.name} added to ${resourceIdToString(resource.id)}`);
402
+ }
403
+ resource.fieldsMap.set(fd.name, field);
404
+ changed = true;
405
+ }
406
+ else {
407
+ // change of old field
408
+ // in principle this transition is possible, see assertions below
409
+ if (field.type !== fd.type) {
410
+ if (field.type !== 'Dynamic')
411
+ unexpectedTransitionError(`field changed type ${field.type} -> ${fd.type}`);
412
+ notEmpty(resource.dynamicFieldListChanged).markChanged(`field ${fd.name} changed type from Dynamic to ${fd.type} in ${resourceIdToString(resource.id)}`);
413
+ if (field.type === 'Input' || field.type === 'Service') {
414
+ if (resource.inputsLocked)
415
+ unexpectedTransitionError(`adding input field "${fd.name}", while corresponding list is locked`);
416
+ notEmpty(resource.inputAndServiceFieldListChanged).markChanged(`field ${fd.name} changed to type ${fd.type} in ${resourceIdToString(resource.id)}`);
417
+ }
418
+ if (field.type === 'Output') {
419
+ if (resource.outputsLocked)
420
+ unexpectedTransitionError(`adding output field "${fd.name}", while corresponding list is locked`);
421
+ notEmpty(resource.outputFieldListChanged).markChanged(`field ${fd.name} changed to type ${fd.type} in ${resourceIdToString(resource.id)}`);
422
+ }
423
+ field.type = fd.type;
424
+ field.change.markChanged(`field ${fd.name} type changed to ${fd.type} in ${resourceIdToString(resource.id)}`);
425
+ changed = true;
426
+ }
427
+ // field value
428
+ if (field.value !== fd.value) {
429
+ if (isNotNullResourceId(field.value))
430
+ decrementRefs.push(field.value);
431
+ field.value = fd.value;
432
+ if (isNotNullResourceId(fd.value))
433
+ incrementRefs.push(fd.value);
434
+ field.change.markChanged(`field ${fd.name} value changed in ${resourceIdToString(resource.id)}`);
435
+ changed = true;
436
+ }
437
+ // field error
438
+ if (field.error !== fd.error) {
439
+ if (isNotNullResourceId(field.error))
440
+ decrementRefs.push(field.error);
441
+ field.error = fd.error;
442
+ if (isNotNullResourceId(fd.error))
443
+ incrementRefs.push(fd.error);
444
+ field.change.markChanged(`field ${fd.name} error changed in ${resourceIdToString(resource.id)}`);
445
+ changed = true;
446
+ }
447
+ // field status
448
+ if (field.status !== fd.status) {
449
+ field.status = fd.status;
450
+ field.change.markChanged(`field ${fd.name} status changed to ${fd.status} in ${resourceIdToString(resource.id)}`);
451
+ changed = true;
452
+ }
453
+ // field valueIsFinal flag
454
+ if (field.valueIsFinal !== fd.valueIsFinal) {
455
+ field.valueIsFinal = fd.valueIsFinal;
456
+ field.change.markChanged(`field ${fd.name} valueIsFinal changed to ${fd.valueIsFinal} in ${resourceIdToString(resource.id)}`);
457
+ changed = true;
458
+ }
459
+ field.resourceVersion = resource.version;
460
+ }
461
+ }
462
+ // detecting removed fields
463
+ resource.fieldsMap.forEach((field, fieldName, fields) => {
464
+ if (field.resourceVersion !== resource.version) {
465
+ if (field.type === 'Input' || field.type === 'Service' || field.type === 'Output')
466
+ unexpectedTransitionError(`removal of ${field.type} field ${fieldName}`);
467
+ field.change.markChanged(`dynamic field ${fieldName} removed from ${resourceIdToString(resource.id)}`);
468
+ fields.delete(fieldName);
469
+ if (isNotNullResourceId(field.value))
470
+ decrementRefs.push(field.value);
471
+ if (isNotNullResourceId(field.error))
472
+ decrementRefs.push(field.error);
473
+ notEmpty(resource.dynamicFieldListChanged).markChanged(`dynamic field ${fieldName} removed from ${resourceIdToString(resource.id)}`);
474
+ }
475
+ });
476
+ // inputsLocked
477
+ if (resource.inputsLocked !== rd.inputsLocked) {
478
+ if (resource.inputsLocked)
479
+ unexpectedTransitionError('inputs unlocking is not permitted');
480
+ resource.inputsLocked = rd.inputsLocked;
481
+ notEmpty(resource.lockedChange).markChanged(`inputs locked for ${resourceIdToString(resource.id)}`);
482
+ changed = true;
483
+ }
484
+ // outputsLocked
485
+ if (resource.outputsLocked !== rd.outputsLocked) {
486
+ if (resource.outputsLocked)
487
+ unexpectedTransitionError('outputs unlocking is not permitted');
488
+ resource.outputsLocked = rd.outputsLocked;
489
+ notEmpty(resource.lockedChange).markChanged(`outputs locked for ${resourceIdToString(resource.id)}`);
490
+ changed = true;
491
+ }
492
+ // ready flag
493
+ if (resource.resourceReady !== rd.resourceReady) {
494
+ const readyStateBefore = resource.resourceReady;
495
+ resource.resourceReady = rd.resourceReady;
496
+ resource.verifyReadyState();
497
+ if (!resource.isReadyOrError)
498
+ unexpectedTransitionError(`resource can't lose it's ready or error state (ready state before ${readyStateBefore})`);
499
+ notEmpty(resource.resourceStateChange).markChanged(`ready flag changed to ${rd.resourceReady} for ${resourceIdToString(resource.id)}`);
500
+ changed = true;
501
+ }
502
+ // syncing kv
503
+ for (const kv of rd.kv) {
504
+ const current = resource.kv.get(kv.key);
505
+ if (current === undefined) {
506
+ resource.kv.set(kv.key, kv.value);
507
+ notEmpty(resource.kvChangedPerKey).markChanged(kv.key, `kv added for ${resourceIdToString(resource.id)}: ${kv.key}`);
508
+ }
509
+ else if (Buffer.compare(current, kv.value) !== 0) {
510
+ resource.kv.set(kv.key, kv.value);
511
+ notEmpty(resource.kvChangedPerKey).markChanged(kv.key, `kv changed for ${resourceIdToString(resource.id)}: ${kv.key}`);
512
+ }
513
+ }
514
+ if (resource.kv.size > rd.kv.length) {
515
+ // only it this case it makes sense to check for deletions
516
+ const newStateKeys = new Set(rd.kv.map((kv) => kv.key));
517
+ // deleting keys not present in resource anymore
518
+ resource.kv.forEach((_value, key, map) => {
519
+ if (!newStateKeys.has(key)) {
520
+ map.delete(key);
521
+ notEmpty(resource.kvChangedPerKey).markChanged(key, `kv deleted for ${resourceIdToString(resource.id)}: ${key}`);
522
+ }
523
+ });
524
+ }
525
+ if (changed) {
526
+ // if resource was changed, updating resource data version
527
+ resource.dataVersion = resource.version;
528
+ if (this.isFinalPredicate(resource))
529
+ resource.markFinal();
530
+ }
531
+ }
532
+ else {
533
+ // creating new resource
534
+ resource = new PlTreeResource(rd);
535
+ resource.verifyReadyState();
536
+ if (isNotNullResourceId(resource.error))
537
+ incrementRefs.push(resource.error);
538
+ for (const fd of rd.fields) {
539
+ const field = new PlTreeField(fd.name, fd.type, fd.value, fd.error, fd.status, fd.valueIsFinal, InitialResourceVersion);
540
+ if (isNotNullResourceId(fd.value))
541
+ incrementRefs.push(fd.value);
542
+ if (isNotNullResourceId(fd.error))
543
+ incrementRefs.push(fd.error);
544
+ resource.fieldsMap.set(fd.name, field);
545
+ }
546
+ // adding kv
547
+ for (const kv of rd.kv)
548
+ resource.kv.set(kv.key, kv.value);
549
+ // checking that resource is final, and if so, marking it
550
+ if (this.isFinalPredicate(resource))
551
+ resource.markFinal();
552
+ // adding the resource to the heap
553
+ this.resources.set(resource.id, resource);
554
+ this.resourcesAdded.markChanged(`new resource ${resourceIdToString(resource.id)} added`);
555
+ }
556
+ }
557
+ // applying refCount increments
558
+ for (const rid of incrementRefs) {
559
+ const res = this.resources.get(rid);
560
+ if (!res) {
561
+ this.invalidateTree();
562
+ throw new TreeStateUpdateError(`orphan resource ${rid}`);
563
+ }
564
+ res.refCount++;
565
+ }
566
+ // recursively applying refCount decrements / doing garbage collection
567
+ let currentRefs = decrementRefs;
568
+ while (currentRefs.length > 0) {
569
+ const nextRefs = [];
570
+ for (const rid of currentRefs) {
571
+ const res = this.resources.get(rid);
572
+ if (!res) {
573
+ this.invalidateTree();
574
+ throw new TreeStateUpdateError(`orphan resource ${rid}`);
575
+ }
576
+ res.refCount--;
577
+ // garbage collection
578
+ if (res.refCount === 0 && res.id !== this.root) {
579
+ // removing fields
580
+ res.fieldsMap.forEach((field) => {
581
+ if (isNotNullResourceId(field.value))
582
+ nextRefs.push(field.value);
583
+ if (isNotNullResourceId(field.error))
584
+ nextRefs.push(field.error);
585
+ field.change.markChanged(`field ${field.name} removed during garbage collection of ${resourceIdToString(res.id)}`);
586
+ });
587
+ if (isNotNullResourceId(res.error))
588
+ nextRefs.push(res.error);
589
+ res.resourceRemoved.markChanged(`resource removed during garbage collection: ${resourceIdToString(res.id)}`);
590
+ this.resources.delete(rid);
591
+ }
592
+ }
593
+ currentRefs = nextRefs;
594
+ }
595
+ // checking for orphans (maybe removed in the future)
596
+ if (!allowOrphanInputs) {
597
+ for (const rd of resourceData) {
598
+ if (!this.resources.has(rd.id)) {
599
+ this.invalidateTree();
600
+ throw new TreeStateUpdateError(`orphan input resource ${rd.id}`);
601
+ }
602
+ }
603
+ }
604
+ }
605
+ /** @deprecated use "entry" instead */
606
+ accessor(rid = this.root) {
607
+ this.checkValid();
608
+ return this.entry(rid);
609
+ }
610
+ entry(rid = this.root) {
611
+ this.checkValid();
612
+ return new PlTreeEntry({ treeProvider: () => this }, rid);
613
+ }
614
+ invalidateTree(msg) {
615
+ this._isValid = false;
616
+ this.invalidationMessage = msg;
617
+ this.resources.forEach((res) => {
618
+ res.markAllChanged();
619
+ });
620
+ }
621
+ dumpState() {
622
+ return Array.from(this.resources.values()).map((res) => res.extendedState);
623
+ }
624
+ }
625
+
626
+ export { PlTreeResource, PlTreeState, TreeStateUpdateError };
627
+ //# sourceMappingURL=state.js.map