@peerbit/program 6.0.35 → 6.0.36

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.
@@ -42,7 +42,7 @@ import { AbortError, TimeoutError } from "@peerbit/time";
42
42
  import {} from "multiformats/block";
43
43
  import {} from "./address.js";
44
44
  import {} from "./client.js";
45
- import { Handler, addParent, } from "./handler.js";
45
+ import { Handler, TERMINAL_BASE_CHECKPOINT, TERMINAL_BASE_COMMIT, TERMINAL_BASE_RETRY, TERMINAL_OUTER_CLEANUP_RELEASE, TERMINAL_OUTER_CLEANUP_RETAIN, TerminalOperationNotStartedError, addParent, } from "./handler.js";
46
46
  import { getValuesWithType } from "./utils.js";
47
47
  export class ClosedError extends Error {
48
48
  constructor(message = "Not open. Please invoke 'client.open(...)' before calling this method") {
@@ -76,6 +76,7 @@ class ProgramHandler extends Handler {
76
76
  identity: properties.client.identity,
77
77
  client: properties.client,
78
78
  shouldMonitor: (p) => p instanceof Program,
79
+ getDependencies: (program) => program.allPrograms,
79
80
  load: Program.load,
80
81
  });
81
82
  }
@@ -129,8 +130,22 @@ let Program = (() => {
129
130
  }
130
131
  _node;
131
132
  _allPrograms;
133
+ _acceptsParentAttachments = true;
132
134
  _events;
133
135
  _closed;
136
+ _terminalCalls;
137
+ _dropDeletePending;
138
+ _failedTerminalChildren;
139
+ _emittedTerminalEvents;
140
+ _terminalBaseCommitVersion;
141
+ _terminalBaseCommitEpoch;
142
+ _terminalBaseCommitsByParent;
143
+ _rootTerminalBaseCommits;
144
+ _terminalRetryContexts;
145
+ _pendingTerminalTail;
146
+ _terminalLifecycleCallbackRunning = false;
147
+ _terminalOuterCleanupLeases;
148
+ _pendingInverseParentReleases;
134
149
  parents;
135
150
  children;
136
151
  _address;
@@ -182,6 +197,26 @@ let Program = (() => {
182
197
  set closed(closed) {
183
198
  this._closed = closed;
184
199
  }
200
+ get acceptsParentAttachments() {
201
+ // Program clones are borsh-created without running class field initializers.
202
+ return (this._acceptsParentAttachments !== false &&
203
+ (this._terminalOuterCleanupLeases?.size ?? 0) === 0);
204
+ }
205
+ get pendingTerminalOperation() {
206
+ return (this._pendingTerminalTail?.type ||
207
+ (this._dropDeletePending ? "drop" : undefined));
208
+ }
209
+ get terminalLifecycleCallbackRunning() {
210
+ return this._terminalLifecycleCallbackRunning;
211
+ }
212
+ /**
213
+ * Fence Handler reuse while a subclass performs irreversible terminal work
214
+ * before delegating to Program.end(). A subsequent successful reopen clears
215
+ * the fence in beforeOpen().
216
+ */
217
+ preventParentAttachments() {
218
+ this._acceptsParentAttachments = false;
219
+ }
185
220
  get node() {
186
221
  return this._node;
187
222
  }
@@ -190,6 +225,21 @@ let Program = (() => {
190
225
  }
191
226
  _eventOptions;
192
227
  async beforeOpen(node, options) {
228
+ if ((this._terminalOuterCleanupLeases?.size ?? 0) > 0) {
229
+ throw new Error("Program terminal cleanup must finish before the program can reopen");
230
+ }
231
+ if (this.closed) {
232
+ if (this._pendingTerminalTail || this._dropDeletePending) {
233
+ throw new Error("Program terminal cleanup must finish before the program can reopen");
234
+ }
235
+ this._terminalBaseCommitEpoch = (this._terminalBaseCommitEpoch ?? 0) + 1;
236
+ this._acceptsParentAttachments = true;
237
+ this._failedTerminalChildren = undefined;
238
+ this._emittedTerminalEvents?.clear();
239
+ this._emittedTerminalEvents = undefined;
240
+ this._terminalBaseCommitsByParent = undefined;
241
+ this._rootTerminalBaseCommits = undefined;
242
+ }
193
243
  // check that a discriminator exist
194
244
  const schema = getSchema(this.constructor);
195
245
  if (!schema || typeof schema.variant !== "string") {
@@ -353,42 +403,365 @@ let Program = (() => {
353
403
  }
354
404
  _subscriptionEventListener;
355
405
  _unsubscriptionEventListener;
356
- async processEnd(type) {
357
- if (!this.closed) {
406
+ [TERMINAL_BASE_CHECKPOINT]() {
407
+ return this._terminalBaseCommitVersion ?? 0;
408
+ }
409
+ [TERMINAL_OUTER_CLEANUP_RETAIN]() {
410
+ const lease = {};
411
+ const leases = this._terminalOuterCleanupLeases ||
412
+ (this._terminalOuterCleanupLeases = new Set());
413
+ leases.add(lease);
414
+ return lease;
415
+ }
416
+ [TERMINAL_OUTER_CLEANUP_RELEASE](lease) {
417
+ this._terminalOuterCleanupLeases?.delete(lease);
418
+ if (this._terminalOuterCleanupLeases?.size === 0) {
419
+ this._terminalOuterCleanupLeases = undefined;
420
+ this.reconcilePendingInverseParentReleases();
421
+ }
422
+ }
423
+ [TERMINAL_BASE_COMMIT](afterVersion, type, from) {
424
+ const commit = from
425
+ ? this._terminalBaseCommitsByParent?.get(from)?.[type]
426
+ : this._rootTerminalBaseCommits?.[type];
427
+ return commit && commit.version > afterVersion ? commit : undefined;
428
+ }
429
+ async [TERMINAL_BASE_RETRY](commit, operation) {
430
+ if (commit.epoch !== (this._terminalBaseCommitEpoch ?? 0)) {
431
+ throw new Error("Program terminal cleanup belongs to a stale open lifecycle");
432
+ }
433
+ const context = {
434
+ commit,
435
+ consumed: false,
436
+ promise: Promise.resolve(commit.result),
437
+ };
438
+ const contexts = this._terminalRetryContexts || (this._terminalRetryContexts = []);
439
+ contexts.push(context);
440
+ try {
441
+ return await operation();
442
+ }
443
+ finally {
444
+ const index = contexts.indexOf(context);
445
+ if (index !== -1)
446
+ contexts.splice(index, 1);
447
+ if (contexts.length === 0)
448
+ this._terminalRetryContexts = undefined;
449
+ }
450
+ }
451
+ consumeTerminalRetry(type, from) {
452
+ const context = this._terminalRetryContexts?.find((candidate) => !candidate.consumed &&
453
+ candidate.commit.type === type &&
454
+ candidate.commit.from === from);
455
+ if (!context)
456
+ return undefined;
457
+ context.consumed = true;
458
+ return context.promise;
459
+ }
460
+ recordTerminalBaseCommit(type, from, result, releasedParentReferences) {
461
+ const version = (this._terminalBaseCommitVersion ?? 0) + 1;
462
+ this._terminalBaseCommitVersion = version;
463
+ const commit = {
464
+ epoch: this._terminalBaseCommitEpoch ?? 0,
465
+ version,
466
+ type,
467
+ from,
468
+ result,
469
+ releasedParentReferences,
470
+ };
471
+ if (from) {
472
+ const commits = this._terminalBaseCommitsByParent?.get(from) ??
473
+ {};
474
+ commits[type] = commit;
475
+ const commitsByParent = this._terminalBaseCommitsByParent ||
476
+ (this._terminalBaseCommitsByParent = new WeakMap());
477
+ commitsByParent.set(from, commits);
478
+ }
479
+ else {
480
+ const commits = this._rootTerminalBaseCommits || (this._rootTerminalBaseCommits = {});
481
+ commits[type] = commit;
482
+ }
483
+ }
484
+ retainInverseParentRelease(from) {
485
+ if (!from)
486
+ return;
487
+ const pending = this._pendingInverseParentReleases ||
488
+ (this._pendingInverseParentReleases = new Map());
489
+ pending.set(from, (pending.get(from) ?? 0) + 1);
490
+ }
491
+ reconcilePendingInverseParentReleases(from) {
492
+ const pending = this._pendingInverseParentReleases;
493
+ if (!pending)
494
+ return;
495
+ const parents = from ? [from] : [...pending.keys()];
496
+ for (const parent of parents) {
497
+ let releasedReferences = pending.get(parent) ?? 0;
498
+ const retainedReferences = this.parents?.filter((candidate) => candidate === parent).length ?? 0;
499
+ while (releasedReferences > 0) {
500
+ const inverseReferences = parent.children?.filter((candidate) => candidate === this).length ??
501
+ 0;
502
+ if (inverseReferences > retainedReferences) {
503
+ const childIndex = parent.children.indexOf(this);
504
+ if (childIndex !== -1)
505
+ parent.children.splice(childIndex, 1);
506
+ }
507
+ releasedReferences -= 1;
508
+ }
509
+ pending.delete(parent);
510
+ }
511
+ if (pending.size === 0)
512
+ this._pendingInverseParentReleases = undefined;
513
+ }
514
+ isOutermostBaseTerminalOperation(type) {
515
+ const current = type === "close" ? this.close : this.drop;
516
+ const base = type === "close" ? Program.prototype.close : Program.prototype.drop;
517
+ return current === base;
518
+ }
519
+ async processEnd(type, from, hadParentReference) {
520
+ if (this.closed) {
521
+ this._clear();
522
+ return true;
523
+ }
524
+ // Lifecycle events retain their historical attempt semantics and parent-first
525
+ // ordering. A failed attempt emits once; retries in the same open epoch do not
526
+ // emit a duplicate event. The awaited onClose/onDrop callback below remains a
527
+ // committed-tail callback and only runs after children have drained.
528
+ const emittedTerminalEvents = this._emittedTerminalEvents ||
529
+ (this._emittedTerminalEvents = new Set());
530
+ const retryingTerminalAttempt = emittedTerminalEvents.has(type);
531
+ if (!emittedTerminalEvents.has(type)) {
532
+ emittedTerminalEvents.add(type);
358
533
  this.emitEvent(new CustomEvent(type, { detail: this }), true);
359
- if (type === "close") {
360
- this._eventOptions?.onClose?.(this);
534
+ }
535
+ const children = [...(this.children ?? [])];
536
+ const previousFailures = [...(this._failedTerminalChildren ?? [])];
537
+ const claimedFailures = new Set();
538
+ const attempts = [];
539
+ const tailsByChild = new Map();
540
+ const childPromises = children.map((child) => {
541
+ const previous = previousFailures.find((failure) => failure.program === child && !claimedFailures.has(failure));
542
+ if (previous)
543
+ claimedFailures.add(previous);
544
+ const attempt = {
545
+ child,
546
+ operation: previous?.operation ?? child.pendingTerminalOperation ?? type,
547
+ previous,
548
+ checkpoint: 0,
549
+ startedClosed: false,
550
+ ownerReferencesBefore: 0,
551
+ inverseOwnerReferencesBefore: 0,
552
+ skipped: false,
553
+ cleanupLease: previous?.cleanupLease,
554
+ };
555
+ attempts.push(attempt);
556
+ const run = async () => {
557
+ attempt.startedClosed = child.closed;
558
+ attempt.ownerReferencesBefore =
559
+ child.parents?.filter((parent) => parent === this).length ?? 0;
560
+ attempt.inverseOwnerReferencesBefore =
561
+ this.children?.filter((candidate) => candidate === child).length ?? 0;
562
+ if (child.closed &&
563
+ (attempt.operation === "close" || retryingTerminalAttempt) &&
564
+ !previous &&
565
+ !child.pendingTerminalOperation) {
566
+ return true;
567
+ }
568
+ attempt.cleanupLease ??= child[TERMINAL_OUTER_CLEANUP_RETAIN]();
569
+ attempt.checkpoint = child[TERMINAL_BASE_CHECKPOINT]();
570
+ const invoke = () => child[attempt.operation](this);
571
+ const result = await (previous?.commit
572
+ ? child[TERMINAL_BASE_RETRY](previous.commit, invoke)
573
+ : invoke());
574
+ const ownerReferencesAfter = child.parents?.filter((parent) => parent === this).length ?? 0;
575
+ let inverseOwnerReferencesAfter = this.children?.filter((candidate) => candidate === child).length ?? 0;
576
+ // A child override must not be able to hide a retained owner by deleting
577
+ // only the parent's inverse edge. Restore the minimum graph reachability
578
+ // required by the child's live owner references before validating progress.
579
+ while (inverseOwnerReferencesAfter < ownerReferencesAfter) {
580
+ this.children.push(child);
581
+ inverseOwnerReferencesAfter += 1;
582
+ }
583
+ // A successful retry may consume a previously committed parent release
584
+ // without changing the child's owner list again. Reconcile at most the one
585
+ // stale inverse edge represented by this occurrence before deciding whether
586
+ // the call made progress.
587
+ if (inverseOwnerReferencesAfter > ownerReferencesAfter) {
588
+ const childIndex = this.children.indexOf(child);
589
+ if (childIndex !== -1) {
590
+ this.children.splice(childIndex, 1);
591
+ inverseOwnerReferencesAfter -= 1;
592
+ }
593
+ }
594
+ const committedRelease = (previous?.commit?.releasedParentReferences ?? 0) > 0;
595
+ const releasedOwnerReference = ownerReferencesAfter < attempt.ownerReferencesBefore;
596
+ const repairedStaleInverseReference = attempt.inverseOwnerReferencesBefore >
597
+ attempt.ownerReferencesBefore &&
598
+ ownerReferencesAfter === attempt.ownerReferencesBefore &&
599
+ inverseOwnerReferencesAfter < attempt.inverseOwnerReferencesBefore;
600
+ if (!attempt.startedClosed &&
601
+ !child.closed &&
602
+ !committedRelease &&
603
+ !releasedOwnerReference &&
604
+ !repairedStaleInverseReference) {
605
+ throw new Error(`Child program at ${child.address} did not release parent ownership during ${attempt.operation}`);
606
+ }
607
+ return result;
608
+ };
609
+ const predecessor = tailsByChild.get(child);
610
+ const promise = predecessor
611
+ ? predecessor.then(run, (error) => {
612
+ // Duplicate appearances represent distinct ownership references.
613
+ // Do not spend the next reference while cleanup for the preceding
614
+ // release is unresolved; retain it for the recovery attempt.
615
+ attempt.skipped = true;
616
+ throw error;
617
+ })
618
+ : run();
619
+ tailsByChild.set(child, promise);
620
+ return promise;
621
+ });
622
+ const results = await Promise.allSettled(childPromises);
623
+ const failedChildren = [];
624
+ let firstChildError;
625
+ for (let index = 0; index < results.length; index++) {
626
+ const result = results[index];
627
+ const attempt = attempts[index];
628
+ const child = attempt.child;
629
+ if (result.status === "rejected") {
630
+ if (attempt.skipped) {
631
+ if (attempt.previous)
632
+ failedChildren.push(attempt.previous);
633
+ firstChildError ??= result.reason;
634
+ continue;
635
+ }
636
+ if (!attempt.startedClosed || attempt.previous) {
637
+ const ownerReferencesAfter = child.parents?.filter((parent) => parent === this).length ?? 0;
638
+ const commit = attempt.previous?.commit ||
639
+ child[TERMINAL_BASE_COMMIT](attempt.checkpoint, attempt.operation, this);
640
+ const baseProgressed = commit != null ||
641
+ child.closed !== attempt.startedClosed ||
642
+ ownerReferencesAfter !== attempt.ownerReferencesBefore;
643
+ const retainCleanupLease = baseProgressed ||
644
+ attempt.previous != null ||
645
+ !(result.reason instanceof TerminalOperationNotStartedError);
646
+ const cleanupLease = retainCleanupLease
647
+ ? attempt.cleanupLease
648
+ : undefined;
649
+ if (!retainCleanupLease && attempt.cleanupLease) {
650
+ child[TERMINAL_OUTER_CLEANUP_RELEASE](attempt.cleanupLease);
651
+ attempt.cleanupLease = undefined;
652
+ }
653
+ failedChildren.push({
654
+ program: child,
655
+ operation: attempt.operation === "drop" && !baseProgressed
656
+ ? "drop"
657
+ : commit || child.closed
658
+ ? attempt.operation
659
+ : "close",
660
+ commit,
661
+ cleanupLease,
662
+ });
663
+ }
664
+ else if (attempt.cleanupLease) {
665
+ child[TERMINAL_OUTER_CLEANUP_RELEASE](attempt.cleanupLease);
666
+ attempt.cleanupLease = undefined;
667
+ }
668
+ firstChildError ??= result.reason;
669
+ continue;
361
670
  }
362
- else if (type === "drop") {
363
- this._eventOptions?.onDrop?.(this);
671
+ if (attempt.cleanupLease) {
672
+ child[TERMINAL_OUTER_CLEANUP_RELEASE](attempt.cleanupLease);
673
+ attempt.cleanupLease = undefined;
364
674
  }
365
- else {
366
- throw new Error("Unsupported event type: " + type);
675
+ // A managed child's Handler may already have reconciled the inverse edge
676
+ // from its committed base release. Nested unmanaged children rely on this
677
+ // parent instead. Remove at most the one excess edge represented by this
678
+ // successful occurrence so both paths remain count-correct.
679
+ const childReferences = child.parents?.filter((parent) => parent === this).length ?? 0;
680
+ const childEdges = this.children?.filter((candidate) => candidate === child).length ?? 0;
681
+ if (childEdges > childReferences) {
682
+ const childIndex = this.children.indexOf(child);
683
+ if (childIndex !== -1)
684
+ this.children.splice(childIndex, 1);
367
685
  }
368
- const promises = [];
369
- if (this.children) {
370
- for (const program of this.children) {
371
- if (program.closed) {
372
- if (type === "close") {
373
- continue;
374
- }
375
- }
376
- promises.push(program[type](this)); // TODO types
377
- }
378
- this.children = [];
686
+ }
687
+ for (const previous of previousFailures) {
688
+ if (!claimedFailures.has(previous) && previous.cleanupLease) {
689
+ previous.program[TERMINAL_OUTER_CLEANUP_RELEASE](previous.cleanupLease);
690
+ previous.cleanupLease = undefined;
379
691
  }
380
- await Promise.all(promises);
381
- this._clear();
382
- this.closed = true;
383
- return true;
384
692
  }
385
- else {
386
- this._clear();
387
- return true;
693
+ this._failedTerminalChildren =
694
+ failedChildren.length > 0 ? failedChildren : undefined;
695
+ if (firstChildError !== undefined)
696
+ throw firstChildError;
697
+ this._clear();
698
+ this.closed = true;
699
+ this._pendingTerminalTail = {
700
+ type,
701
+ from,
702
+ hadParentReference,
703
+ eventEmitted: true,
704
+ callbackCompleted: false,
705
+ };
706
+ await this.finishTerminalTail();
707
+ return true;
708
+ }
709
+ async finishTerminalTail() {
710
+ const tail = this._pendingTerminalTail;
711
+ if (!tail)
712
+ return;
713
+ if (!tail.eventEmitted) {
714
+ tail.eventEmitted = true;
715
+ const emittedTerminalEvents = this._emittedTerminalEvents ||
716
+ (this._emittedTerminalEvents = new Set());
717
+ if (!emittedTerminalEvents.has(tail.type)) {
718
+ emittedTerminalEvents.add(tail.type);
719
+ this.emitEvent(new CustomEvent(tail.type, { detail: this }), true);
720
+ }
721
+ }
722
+ if (!tail.callbackCompleted) {
723
+ const callback = tail.type === "close"
724
+ ? this._eventOptions?.onClose
725
+ : this._eventOptions?.onDrop;
726
+ this._terminalLifecycleCallbackRunning = true;
727
+ try {
728
+ await callback?.(this);
729
+ }
730
+ finally {
731
+ this._terminalLifecycleCallbackRunning = false;
732
+ }
733
+ tail.callbackCompleted = true;
734
+ }
735
+ this.node?.services.pubsub.removeEventListener("subscribe", this._subscriptionEventListener);
736
+ this.node?.services.pubsub.removeEventListener("unsubscribe", this._unsubscriptionEventListener);
737
+ this._emittedEventsFor?.clear();
738
+ this._emittedEventsFor = undefined;
739
+ this._peerTopicsByHash?.clear();
740
+ this._peerTopicsByHash = undefined;
741
+ this._seedPeerTopicsFromSubscribers = undefined;
742
+ this._eventOptions = undefined;
743
+ if (tail.hadParentReference) {
744
+ const parentIndex = this.parents?.findIndex((parent) => parent === tail.from) ?? -1;
745
+ if (parentIndex !== -1) {
746
+ this.parents.splice(parentIndex, 1);
747
+ this.retainInverseParentRelease(tail.from);
748
+ }
388
749
  }
750
+ this._pendingTerminalTail = undefined;
389
751
  }
390
752
  async end(type, from) {
391
753
  if (this.closed) {
754
+ if (this._pendingTerminalTail &&
755
+ this._pendingTerminalTail.type !== type) {
756
+ throw new Error(`Program has pending ${this._pendingTerminalTail.type} cleanup; retry it before ${type}`);
757
+ }
758
+ if (this._pendingTerminalTail) {
759
+ await this.finishTerminalTail();
760
+ return true;
761
+ }
762
+ if (this._dropDeletePending && type === "close") {
763
+ throw new Error("Program has pending drop deletion; retry drop before close");
764
+ }
392
765
  if (type === "drop") {
393
766
  throw new ClosedError("Program is closed, can not drop");
394
767
  }
@@ -404,40 +777,130 @@ let Program = (() => {
404
777
  }
405
778
  else {
406
779
  this.parents.splice(parentIdx, 1);
780
+ this.retainInverseParentRelease(from);
407
781
  close = false;
408
782
  }
409
783
  }
410
784
  else if (from) {
411
- throw new Error("Could not find from in parents");
785
+ throw new TerminalOperationNotStartedError("Could not find from in parents");
412
786
  }
413
787
  }
414
- const end = close && (await this.processEnd(type));
415
- if (end) {
416
- this.node?.services.pubsub.removeEventListener("subscribe", this._subscriptionEventListener);
417
- this.node?.services.pubsub.removeEventListener("unsubscribe", this._unsubscriptionEventListener);
418
- this._emittedEventsFor?.clear();
419
- this._emittedEventsFor = undefined;
420
- this._peerTopicsByHash?.clear();
421
- this._peerTopicsByHash = undefined;
422
- this._seedPeerTopicsFromSubscribers = undefined;
423
- this._eventOptions = undefined;
424
- if (parentIdx !== -1) {
425
- this.parents.splice(parentIdx, 1); // We splice this here because this._end depends on this parent to exist
426
- }
788
+ if (close) {
789
+ // Establish the reuse fence synchronously once this call owns terminal
790
+ // shutdown. Non-terminal parent releases remain attachable.
791
+ this.preventParentAttachments();
427
792
  }
428
- return end;
793
+ return close && (await this.processEnd(type, from, parentIdx !== -1));
429
794
  }
430
- async close(from) {
431
- this._emittedEventsFor = undefined;
432
- return this.end("close", from);
795
+ performTerminalOperation(type, from) {
796
+ if (type === "close") {
797
+ this._emittedEventsFor = undefined;
798
+ return this.end("close", from);
799
+ }
800
+ return this.performDrop(from);
433
801
  }
434
- async drop(from) {
802
+ async performDrop(from) {
803
+ if (this.closed && this._dropDeletePending) {
804
+ await this.delete();
805
+ this._dropDeletePending = false;
806
+ return true;
807
+ }
435
808
  const dropped = await this.end("drop", from);
436
809
  if (dropped) {
810
+ // Remember the committed terminal transition before deletion. If rm()
811
+ // fails, a later drop retry must resume here instead of rejecting merely
812
+ // because Program.end() already made `closed` observable.
813
+ this._dropDeletePending = true;
437
814
  await this.delete();
815
+ this._dropDeletePending = false;
438
816
  }
439
817
  return dropped;
440
818
  }
819
+ terminalOperation(type, from) {
820
+ if (this._terminalLifecycleCallbackRunning) {
821
+ return Promise.reject(new TerminalOperationNotStartedError("Program lifecycle callbacks cannot wait for their own terminal operation"));
822
+ }
823
+ const retry = this.consumeTerminalRetry(type, from);
824
+ if (retry)
825
+ return retry;
826
+ const calls = this._terminalCalls || (this._terminalCalls = []);
827
+ const matching = calls.find((call) => call.type === type && call.from === from && call.terminal);
828
+ if (matching) {
829
+ return matching.promise;
830
+ }
831
+ if (type === "close") {
832
+ // Drop is the stronger terminal operation. A close admitted for the same
833
+ // owner while drop is pending observes that exact operation and promise.
834
+ const dropping = calls.find((call) => call.type === "drop" && call.from === from && call.terminal);
835
+ if (dropping) {
836
+ return dropping.promise;
837
+ }
838
+ }
839
+ const predecessor = calls.at(-1);
840
+ let resolve;
841
+ let reject;
842
+ const promise = new Promise((promiseResolve, promiseReject) => {
843
+ resolve = promiseResolve;
844
+ reject = promiseReject;
845
+ });
846
+ const parentIndex = this.parents?.findIndex((parent) => parent === from) ?? -1;
847
+ const terminal = this.closed || parentIndex === -1 || (this.parents?.length ?? 0) === 1;
848
+ const call = { type, from, terminal, promise };
849
+ calls.push(call);
850
+ const execute = () => {
851
+ let operation;
852
+ const ownerReferencesBefore = this.parents?.filter((parent) => parent === from).length ?? 0;
853
+ try {
854
+ operation = this.performTerminalOperation(type, from);
855
+ }
856
+ catch (error) {
857
+ reject(error);
858
+ return;
859
+ }
860
+ void operation.then((result) => {
861
+ const ownerReferencesAfter = this.parents?.filter((parent) => parent === from).length ?? 0;
862
+ this.recordTerminalBaseCommit(type, from, result, Math.max(0, ownerReferencesBefore - ownerReferencesAfter));
863
+ // Program only owns the base promise. A subclass may still be doing
864
+ // post-super terminal cleanup, so managed/embedded calls defer inverse-
865
+ // edge removal to the caller's outer cleanup lease. A non-terminal owner
866
+ // release leaves the child live and can reconcile immediately; an
867
+ // inherited base method is itself the full public operation.
868
+ if ((this._terminalOuterCleanupLeases?.size ?? 0) === 0 &&
869
+ (!result || this.isOutermostBaseTerminalOperation(type))) {
870
+ this.reconcilePendingInverseParentReleases(result ? undefined : from);
871
+ }
872
+ resolve(result);
873
+ }, reject);
874
+ };
875
+ if (predecessor) {
876
+ // Different owners and close-vs-drop calls are serialized. In particular,
877
+ // a drop admitted after close does not pretend destructive cleanup happened:
878
+ // it runs after close and receives ClosedError from the now-closed program.
879
+ void predecessor.promise.then(execute, execute);
880
+ }
881
+ else {
882
+ execute();
883
+ }
884
+ void promise.then(() => this.finishTerminalCall(call), () => this.finishTerminalCall(call));
885
+ return promise;
886
+ }
887
+ finishTerminalCall(call) {
888
+ const calls = this._terminalCalls;
889
+ const index = calls?.indexOf(call) ?? -1;
890
+ if (index !== -1) {
891
+ calls.splice(index, 1);
892
+ }
893
+ if (calls?.length === 0) {
894
+ this._terminalCalls = undefined;
895
+ }
896
+ }
897
+ close(from) {
898
+ this._emittedEventsFor = undefined;
899
+ return this.terminalOperation("close", from);
900
+ }
901
+ drop(from) {
902
+ return this.terminalOperation("drop", from);
903
+ }
441
904
  emitEvent(event, parents = false) {
442
905
  this.events.dispatchEvent(event);
443
906
  if (parents) {
@@ -694,10 +1157,17 @@ let Program = (() => {
694
1157
  if (this._allPrograms) {
695
1158
  return this._allPrograms;
696
1159
  }
697
- const arr = this.programs;
698
- const nexts = this.programs;
699
- for (const next of nexts) {
700
- arr.push(...next.allPrograms);
1160
+ const arr = [];
1161
+ const pending = [...this.programs];
1162
+ const visited = new Set([this]);
1163
+ while (pending.length > 0) {
1164
+ const next = pending.pop();
1165
+ if (visited.has(next))
1166
+ continue;
1167
+ visited.add(next);
1168
+ arr.push(next);
1169
+ const nested = next.programs;
1170
+ pending.push(...(Array.isArray(nested) ? nested : getValuesWithType(next, Program)));
701
1171
  }
702
1172
  this._allPrograms = arr;
703
1173
  return this._allPrograms;
@@ -749,6 +1219,7 @@ let Program = (() => {
749
1219
  remote: {
750
1220
  timeout: options?.timeout,
751
1221
  priority: 1,
1222
+ replicate: true,
752
1223
  },
753
1224
  });
754
1225
  if (!bytes) {