@rocicorp/zero 1.9.1-canary.0 → 1.9.1-canary.2
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.
- package/out/shared/src/promise-race.d.ts +14 -0
- package/out/shared/src/promise-race.d.ts.map +1 -1
- package/out/shared/src/promise-race.js +32 -1
- package/out/shared/src/promise-race.js.map +1 -1
- package/out/zero/package.js +1 -1
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +5 -1
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +48 -12
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/db/transaction-pool.d.ts +0 -13
- package/out/zero-cache/src/db/transaction-pool.d.ts.map +1 -1
- package/out/zero-cache/src/db/transaction-pool.js +3 -69
- package/out/zero-cache/src/db/transaction-pool.js.map +1 -1
- package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js +3 -2
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/server/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/server/replicator.js +1 -1
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/broadcast.d.ts +67 -77
- package/out/zero-cache/src/services/change-streamer/broadcast.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/broadcast.js +84 -92
- package/out/zero-cache/src/services/change-streamer/broadcast.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +2 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +7 -4
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/error-type-enum.d.ts +8 -0
- package/out/zero-cache/src/services/change-streamer/error-type-enum.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/forwarder.d.ts +13 -1
- package/out/zero-cache/src/services/change-streamer/forwarder.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/forwarder.js +42 -12
- package/out/zero-cache/src/services/change-streamer/forwarder.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.d.ts +34 -0
- package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.js +149 -40
- package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/subscriber.d.ts +22 -6
- package/out/zero-cache/src/services/change-streamer/subscriber.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/subscriber.js +39 -2
- package/out/zero-cache/src/services/change-streamer/subscriber.js.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.d.ts +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js +6 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
- package/out/zero-cache/src/services/replicator/replicator.d.ts +1 -1
- package/out/zero-cache/src/services/replicator/replicator.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/replicator.js +2 -2
- package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
- package/out/zero-cache/src/types/pg.d.ts.map +1 -1
- package/out/zero-cache/src/types/pg.js.map +1 -1
- package/out/zero-cache/src/types/streams.d.ts +4 -9
- package/out/zero-cache/src/types/streams.d.ts.map +1 -1
- package/out/zero-cache/src/types/streams.js.map +1 -1
- package/out/zero-cache/src/types/subscription.d.ts +2 -11
- package/out/zero-cache/src/types/subscription.d.ts.map +1 -1
- package/out/zero-cache/src/types/subscription.js +4 -25
- package/out/zero-cache/src/types/subscription.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/package.json +1 -1
|
@@ -2,16 +2,75 @@ import type { LogContext } from '@rocicorp/logger';
|
|
|
2
2
|
import type { WatermarkedChange } from './change-streamer-service.ts';
|
|
3
3
|
import type { Subscriber } from './subscriber.ts';
|
|
4
4
|
export type BroadcastReleaseMode = 'all-subscribers' | 'consensus-timeout';
|
|
5
|
+
/**
|
|
6
|
+
* Enables event-driven early release of a {@link Broadcast}. When provided and a
|
|
7
|
+
* majority has acked, the broadcast schedules its own consensus-timeout release
|
|
8
|
+
* proportional to how long the majority took to ack, instead of relying on the
|
|
9
|
+
* Forwarder's periodic progress tick.
|
|
10
|
+
*/
|
|
11
|
+
export type EarlyReleaseOptions = {
|
|
12
|
+
/** Time to wait, proportional to majority completion, before releasing. */
|
|
13
|
+
consensusTimeoutProportion: number;
|
|
14
|
+
/** Injectable timer, for deterministic testing. */
|
|
15
|
+
setTimeoutFn?: typeof setTimeout;
|
|
16
|
+
/** Injectable timer cancellation, for deterministic testing. */
|
|
17
|
+
clearTimeoutFn?: typeof clearTimeout;
|
|
18
|
+
};
|
|
5
19
|
/**
|
|
6
20
|
* Initiates and tracks the progress of a change broadcasted to
|
|
7
|
-
* a set of subscribers
|
|
21
|
+
* a set of subscribers, implementing **consensus-based timeouts**
|
|
22
|
+
* to effect short-term graceful degradation when a minority of
|
|
23
|
+
* subscribers are behind.
|
|
24
|
+
*
|
|
25
|
+
* ### Background
|
|
26
|
+
*
|
|
27
|
+
* The purpose of flow control is to pull upstream replication changes
|
|
28
|
+
* no faster than the rate they are processed by downstream subscribers
|
|
29
|
+
* in the steady state. In the change-streamer, this is done by occasionally
|
|
30
|
+
* waiting for ACKs from subscribers before continuing; without doing so,
|
|
31
|
+
* I/O buffers fill up and cause the system to spend most of its time in GC.
|
|
32
|
+
*
|
|
33
|
+
* However, the naive algorithm of always waiting for all subscribers (e.g.
|
|
34
|
+
* `Promise.all()`) can behave poorly in scenarios where subscribers
|
|
35
|
+
* are imbalanced:
|
|
36
|
+
* * New subscribers may have a backlog of changes to catch up with.
|
|
37
|
+
* Having all subscribers wait for the new subscriber to catch up results
|
|
38
|
+
* in delaying the entire application.
|
|
39
|
+
* * Broken TCP connections similarly require all subscribers to wait until
|
|
40
|
+
* connection liveness checks kick in and disconnect the subscriber.
|
|
8
41
|
*
|
|
9
|
-
*
|
|
42
|
+
* A simplistic approach is to add a limit to the amount of time waiting for
|
|
43
|
+
* subscribers, i.e. an ack timeout. However, deciding what this timeout
|
|
44
|
+
* should be is non-trivial because of the heterogeneous nature of changes;
|
|
45
|
+
* while most changes operate on single rows and are relatively predictable
|
|
46
|
+
* in terms of running time, some changes are table-wide operations and can
|
|
47
|
+
* legitimately take an arbitrary amount of time. In such scenarios, a
|
|
48
|
+
* timeout that is too short can stop progress on replication altogether.
|
|
10
49
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
50
|
+
* ### Consensus-based Timeout Algorithm
|
|
51
|
+
*
|
|
52
|
+
* To address these shortcomings, a "consensus-based timeout" algorithm is
|
|
53
|
+
* used:
|
|
54
|
+
* * Wait for more than half of the subscribers to finish. (In
|
|
55
|
+
* case of a single node, or the case of one replication-manager
|
|
56
|
+
* and one view-syncer, this reduces to waiting for all subscribers.)
|
|
57
|
+
* * Once more than half of the subscribers have finished, proceed after
|
|
58
|
+
* the configured timeout, proportional to the time it took for the
|
|
59
|
+
* majority of subscribers to ack, even if not all subscribers have
|
|
60
|
+
* finished.
|
|
61
|
+
*
|
|
62
|
+
* In other words, the subscribers themselves are used to determine the
|
|
63
|
+
* timeout of each batch of changes; the majority determines this when
|
|
64
|
+
* they complete, upon which a timeout is logically started.
|
|
65
|
+
*
|
|
66
|
+
* In the common case, the remaining subscribers finish soon afterward and
|
|
67
|
+
* the timeout never elapses. However, in pathological cases where a minority
|
|
68
|
+
* of subscribers have a disproportionate amount of load, some will still
|
|
69
|
+
* be processing (or otherwise unresponsive). These subscribers are given
|
|
70
|
+
* a bounded amount of time to catch up at each flushed batch, up to the
|
|
71
|
+
* timeout interval. This guarantees eventual catchup because the
|
|
72
|
+
* subscribers with a backlog of changes necessarily have a higher
|
|
73
|
+
* processing rate than the subscribers that finished (and are made to wait).
|
|
15
74
|
*/
|
|
16
75
|
export declare class Broadcast {
|
|
17
76
|
#private;
|
|
@@ -24,79 +83,10 @@ export declare class Broadcast {
|
|
|
24
83
|
* Broadcasts the `change` to the `subscribers` and tracks their
|
|
25
84
|
* completion.
|
|
26
85
|
*/
|
|
27
|
-
constructor(subscribers: Iterable<Subscriber>, change: WatermarkedChange);
|
|
86
|
+
constructor(lc: LogContext, subscribers: Iterable<Subscriber>, change: WatermarkedChange, earlyRelease?: EarlyReleaseOptions);
|
|
28
87
|
get isDone(): boolean;
|
|
29
88
|
get done(): Promise<void>;
|
|
30
89
|
get releaseMode(): BroadcastReleaseMode;
|
|
31
|
-
|
|
32
|
-
* Checks for pathological situations in which flow should be reenabled
|
|
33
|
-
* before all subscribers have acked.
|
|
34
|
-
*
|
|
35
|
-
* ### Background
|
|
36
|
-
*
|
|
37
|
-
* The purpose of flow control is to pull upstream replication changes
|
|
38
|
-
* no faster than the rate as they are processed by downstream subscribers
|
|
39
|
-
* in the steady state. In the change-streamer, this is done by occasionally
|
|
40
|
-
* waiting for ACKs from subscribers before continuing; without doing so,
|
|
41
|
-
* I/O buffers fill up and cause the system to spend most of its time in GC.
|
|
42
|
-
*
|
|
43
|
-
* However, the naive algorithm of always waiting for all subscribers (e.g.
|
|
44
|
-
* `Promise.all()`) can behave poorly in scenarios where subscribers
|
|
45
|
-
* are imbalanced:
|
|
46
|
-
* * New subscribers may have a backlog of changes to catch up with.
|
|
47
|
-
* Having all subscribers wait for the new subscriber to catch up results
|
|
48
|
-
* in delaying the entire application.
|
|
49
|
-
* * Broken TCP connections similarly require all subscribers to wait until
|
|
50
|
-
* connection liveness checks kick in and disconnect the subscriber.
|
|
51
|
-
*
|
|
52
|
-
* A simplistic approach is to add a limit to the amount of time waiting for
|
|
53
|
-
* subscribers, i.e. an ack timeout. However, deciding what this timeout
|
|
54
|
-
* should be is non-trivial because of the heterogeneous nature of changes;
|
|
55
|
-
* while most changes operate on single rows and are relatively predictable
|
|
56
|
-
* in terms of running time, some changes are table-wide operations and can
|
|
57
|
-
* legitimately take an arbitrary amount of time. In such scenarios, a
|
|
58
|
-
* timeout that is too short can stop progress on replication altogether.
|
|
59
|
-
*
|
|
60
|
-
* ### Consensus-based Timeout Algorithm
|
|
61
|
-
*
|
|
62
|
-
* To address these shortcomings, a "consensus-based timeout" algorithm is
|
|
63
|
-
* used:
|
|
64
|
-
* * Wait for more than half of the subscribers to finish. (In
|
|
65
|
-
* case of a single node, or the case of one replication-manager
|
|
66
|
-
* and one view-syncer, this reduces to waiting for all subscribers.)
|
|
67
|
-
* * Once more than half of the subscribers have finished, proceed after
|
|
68
|
-
* a fixed timeout elapses (e.g. 1 second), even if not all subscribers
|
|
69
|
-
* have finished.
|
|
70
|
-
*
|
|
71
|
-
* In other words, the subscribers themselves are used to determine the
|
|
72
|
-
* timeout of each batch of changes; the majority determines this when
|
|
73
|
-
* they complete, upon which a timeout is logically started.
|
|
74
|
-
*
|
|
75
|
-
* In the common case, the remaining subscribers finish soon afterward and
|
|
76
|
-
* the timeout never elapses. However, in pathological cases where a minority
|
|
77
|
-
* of subscribers have a disproportionate amount of load, some will still
|
|
78
|
-
* be processing (or otherwise unresponsive). These subscribers are given
|
|
79
|
-
* a bounded amount of time to catch up at each flushed batch, up to the
|
|
80
|
-
* timeout interval. This guarantees eventual catchup because the
|
|
81
|
-
* subscribers with a backlog of changes necessarily have a higher
|
|
82
|
-
* processing rate than the subscribers that finished (and are made to wait).
|
|
83
|
-
*
|
|
84
|
-
* ### Not implemented: Broken connection detection
|
|
85
|
-
*
|
|
86
|
-
* If a subscriber has not made progress for a certain interval, the
|
|
87
|
-
* algorithm could theoretically drop it preemptively, supplementing the
|
|
88
|
-
* existing websocket-level liveness checks.
|
|
89
|
-
*
|
|
90
|
-
* However, a more reliable approach would be to change the replicator
|
|
91
|
-
* to use non-blocking writes, and subsequently increase the frequency of
|
|
92
|
-
* connection-level liveness checks. The current synchronous replica writes
|
|
93
|
-
* can delay both ping responsiveness and change progress arbitrarily (e.g.
|
|
94
|
-
* a large index creation); an independently liveness check that is not
|
|
95
|
-
* delayed by synchronous writes on the subscriber would be a more failsafe
|
|
96
|
-
* solution.
|
|
97
|
-
*
|
|
98
|
-
* @returns `true` if the broadcast was already done or was marked done.
|
|
99
|
-
*/
|
|
100
|
-
checkProgress(lc: LogContext, flowControlConsensusPaddingMs: number, now: number): boolean;
|
|
90
|
+
logSlowRequests(now: number): void;
|
|
101
91
|
}
|
|
102
92
|
//# sourceMappingURL=broadcast.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"broadcast.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/broadcast.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,8BAA8B,CAAC;AACpE,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,iBAAiB,CAAC;AAEhD,MAAM,MAAM,oBAAoB,GAAG,iBAAiB,GAAG,mBAAmB,CAAC;AAE3E
|
|
1
|
+
{"version":3,"file":"broadcast.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/broadcast.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,8BAA8B,CAAC;AACpE,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,iBAAiB,CAAC;AAEhD,MAAM,MAAM,oBAAoB,GAAG,iBAAiB,GAAG,mBAAmB,CAAC;AAE3E;;;;;GAKG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC,2EAA2E;IAC3E,0BAA0B,EAAE,MAAM,CAAC;IACnC,mDAAmD;IACnD,YAAY,CAAC,EAAE,OAAO,UAAU,CAAC;IACjC,gEAAgE;IAChE,cAAc,CAAC,EAAE,OAAO,YAAY,CAAC;CACtC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDG;AACH,qBAAa,SAAS;;IACpB;;;OAGG;IACH,MAAM,CAAC,eAAe,CACpB,WAAW,EAAE,QAAQ,CAAC,UAAU,CAAC,EACjC,MAAM,EAAE,iBAAiB;IA0B3B;;;OAGG;gBAED,EAAE,EAAE,UAAU,EACd,WAAW,EAAE,QAAQ,CAAC,UAAU,CAAC,EACjC,MAAM,EAAE,iBAAiB,EACzB,YAAY,CAAC,EAAE,mBAAmB;IA4EpC,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED,IAAI,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAExB;IAED,IAAI,WAAW,IAAI,oBAAoB,CAEtC;IAED,eAAe,CAAC,GAAG,EAAE,MAAM;CA8B5B"}
|
|
@@ -2,14 +2,59 @@ import { resolver } from "@rocicorp/resolver";
|
|
|
2
2
|
//#region ../zero-cache/src/services/change-streamer/broadcast.ts
|
|
3
3
|
/**
|
|
4
4
|
* Initiates and tracks the progress of a change broadcasted to
|
|
5
|
-
* a set of subscribers
|
|
5
|
+
* a set of subscribers, implementing **consensus-based timeouts**
|
|
6
|
+
* to effect short-term graceful degradation when a minority of
|
|
7
|
+
* subscribers are behind.
|
|
6
8
|
*
|
|
7
|
-
*
|
|
9
|
+
* ### Background
|
|
8
10
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
11
|
+
* The purpose of flow control is to pull upstream replication changes
|
|
12
|
+
* no faster than the rate they are processed by downstream subscribers
|
|
13
|
+
* in the steady state. In the change-streamer, this is done by occasionally
|
|
14
|
+
* waiting for ACKs from subscribers before continuing; without doing so,
|
|
15
|
+
* I/O buffers fill up and cause the system to spend most of its time in GC.
|
|
16
|
+
*
|
|
17
|
+
* However, the naive algorithm of always waiting for all subscribers (e.g.
|
|
18
|
+
* `Promise.all()`) can behave poorly in scenarios where subscribers
|
|
19
|
+
* are imbalanced:
|
|
20
|
+
* * New subscribers may have a backlog of changes to catch up with.
|
|
21
|
+
* Having all subscribers wait for the new subscriber to catch up results
|
|
22
|
+
* in delaying the entire application.
|
|
23
|
+
* * Broken TCP connections similarly require all subscribers to wait until
|
|
24
|
+
* connection liveness checks kick in and disconnect the subscriber.
|
|
25
|
+
*
|
|
26
|
+
* A simplistic approach is to add a limit to the amount of time waiting for
|
|
27
|
+
* subscribers, i.e. an ack timeout. However, deciding what this timeout
|
|
28
|
+
* should be is non-trivial because of the heterogeneous nature of changes;
|
|
29
|
+
* while most changes operate on single rows and are relatively predictable
|
|
30
|
+
* in terms of running time, some changes are table-wide operations and can
|
|
31
|
+
* legitimately take an arbitrary amount of time. In such scenarios, a
|
|
32
|
+
* timeout that is too short can stop progress on replication altogether.
|
|
33
|
+
*
|
|
34
|
+
* ### Consensus-based Timeout Algorithm
|
|
35
|
+
*
|
|
36
|
+
* To address these shortcomings, a "consensus-based timeout" algorithm is
|
|
37
|
+
* used:
|
|
38
|
+
* * Wait for more than half of the subscribers to finish. (In
|
|
39
|
+
* case of a single node, or the case of one replication-manager
|
|
40
|
+
* and one view-syncer, this reduces to waiting for all subscribers.)
|
|
41
|
+
* * Once more than half of the subscribers have finished, proceed after
|
|
42
|
+
* the configured timeout, proportional to the time it took for the
|
|
43
|
+
* majority of subscribers to ack, even if not all subscribers have
|
|
44
|
+
* finished.
|
|
45
|
+
*
|
|
46
|
+
* In other words, the subscribers themselves are used to determine the
|
|
47
|
+
* timeout of each batch of changes; the majority determines this when
|
|
48
|
+
* they complete, upon which a timeout is logically started.
|
|
49
|
+
*
|
|
50
|
+
* In the common case, the remaining subscribers finish soon afterward and
|
|
51
|
+
* the timeout never elapses. However, in pathological cases where a minority
|
|
52
|
+
* of subscribers have a disproportionate amount of load, some will still
|
|
53
|
+
* be processing (or otherwise unresponsive). These subscribers are given
|
|
54
|
+
* a bounded amount of time to catch up at each flushed batch, up to the
|
|
55
|
+
* timeout interval. This guarantees eventual catchup because the
|
|
56
|
+
* subscribers with a backlog of changes necessarily have a higher
|
|
57
|
+
* processing rate than the subscribers that finished (and are made to wait).
|
|
13
58
|
*/
|
|
14
59
|
var Broadcast = class {
|
|
15
60
|
/**
|
|
@@ -19,6 +64,7 @@ var Broadcast = class {
|
|
|
19
64
|
static withoutTracking(subscribers, change) {
|
|
20
65
|
for (const sub of subscribers) sub.send(change);
|
|
21
66
|
}
|
|
67
|
+
#lc;
|
|
22
68
|
#pending;
|
|
23
69
|
#completed;
|
|
24
70
|
#done = resolver();
|
|
@@ -27,16 +73,23 @@ var Broadcast = class {
|
|
|
27
73
|
#watermark;
|
|
28
74
|
#majority;
|
|
29
75
|
#start = performance.now();
|
|
30
|
-
#
|
|
76
|
+
#earlyReleaseTimeoutProportion;
|
|
77
|
+
#setTimeout;
|
|
78
|
+
#clearTimeout;
|
|
79
|
+
#earlyReleaseTimer;
|
|
31
80
|
/**
|
|
32
81
|
* Broadcasts the `change` to the `subscribers` and tracks their
|
|
33
82
|
* completion.
|
|
34
83
|
*/
|
|
35
|
-
constructor(subscribers, change) {
|
|
84
|
+
constructor(lc, subscribers, change, earlyRelease) {
|
|
85
|
+
this.#lc = lc;
|
|
36
86
|
this.#pending = new Set(subscribers);
|
|
37
87
|
this.#completed = [];
|
|
38
88
|
this.#watermark = change[0];
|
|
39
89
|
this.#majority = Math.floor(this.#pending.size / 2) + 1;
|
|
90
|
+
this.#earlyReleaseTimeoutProportion = earlyRelease?.consensusTimeoutProportion;
|
|
91
|
+
this.#setTimeout = earlyRelease?.setTimeoutFn ?? setTimeout;
|
|
92
|
+
this.#clearTimeout = earlyRelease?.clearTimeoutFn ?? clearTimeout;
|
|
40
93
|
for (const sub of this.#pending) {
|
|
41
94
|
const changes = sub.numPending + 1;
|
|
42
95
|
sub.send(change).catch(() => {}).finally(() => this.#markCompleted(sub, changes));
|
|
@@ -44,19 +97,35 @@ var Broadcast = class {
|
|
|
44
97
|
if (this.#pending.size === 0) this.#setDone("all-subscribers");
|
|
45
98
|
}
|
|
46
99
|
#markCompleted(sub, changes) {
|
|
47
|
-
|
|
100
|
+
if (this.#isDone) return;
|
|
101
|
+
const elapsed = performance.now() - this.#start;
|
|
102
|
+
sub.trackResponseResult("on-time");
|
|
48
103
|
this.#completed.push({
|
|
49
104
|
sub,
|
|
50
105
|
changes,
|
|
51
106
|
elapsed
|
|
52
107
|
});
|
|
53
108
|
this.#pending.delete(sub);
|
|
54
|
-
if (this.#pending.size === 0)
|
|
109
|
+
if (this.#pending.size === 0) {
|
|
110
|
+
this.#setDone("all-subscribers");
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (this.#earlyReleaseTimeoutProportion !== void 0 && this.#earlyReleaseTimer === void 0 && this.#completed.length === this.#majority) {
|
|
114
|
+
const timeoutMs = Math.ceil(elapsed * this.#earlyReleaseTimeoutProportion);
|
|
115
|
+
this.#earlyReleaseTimer = this.#setTimeout(() => this.#setDone("consensus-timeout"), timeoutMs);
|
|
116
|
+
}
|
|
55
117
|
}
|
|
56
118
|
#setDone(releaseMode) {
|
|
57
119
|
if (this.#isDone) return;
|
|
120
|
+
if (releaseMode === "consensus-timeout") {
|
|
121
|
+
const elapsed = performance.now() - this.#start;
|
|
122
|
+
this.#logWithState(`continuing with ${this.#pending.size} subscriber(s) still pending`, elapsed);
|
|
123
|
+
}
|
|
124
|
+
this.#pending.forEach((sub) => sub.trackResponseResult("timed-out"));
|
|
58
125
|
this.#isDone = true;
|
|
59
126
|
this.#releaseMode = releaseMode;
|
|
127
|
+
this.#clearTimeout(this.#earlyReleaseTimer);
|
|
128
|
+
this.#earlyReleaseTimer = void 0;
|
|
60
129
|
this.#done.resolve();
|
|
61
130
|
}
|
|
62
131
|
get isDone() {
|
|
@@ -68,92 +137,15 @@ var Broadcast = class {
|
|
|
68
137
|
get releaseMode() {
|
|
69
138
|
return this.#releaseMode ?? "all-subscribers";
|
|
70
139
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
* before all subscribers have acked.
|
|
74
|
-
*
|
|
75
|
-
* ### Background
|
|
76
|
-
*
|
|
77
|
-
* The purpose of flow control is to pull upstream replication changes
|
|
78
|
-
* no faster than the rate as they are processed by downstream subscribers
|
|
79
|
-
* in the steady state. In the change-streamer, this is done by occasionally
|
|
80
|
-
* waiting for ACKs from subscribers before continuing; without doing so,
|
|
81
|
-
* I/O buffers fill up and cause the system to spend most of its time in GC.
|
|
82
|
-
*
|
|
83
|
-
* However, the naive algorithm of always waiting for all subscribers (e.g.
|
|
84
|
-
* `Promise.all()`) can behave poorly in scenarios where subscribers
|
|
85
|
-
* are imbalanced:
|
|
86
|
-
* * New subscribers may have a backlog of changes to catch up with.
|
|
87
|
-
* Having all subscribers wait for the new subscriber to catch up results
|
|
88
|
-
* in delaying the entire application.
|
|
89
|
-
* * Broken TCP connections similarly require all subscribers to wait until
|
|
90
|
-
* connection liveness checks kick in and disconnect the subscriber.
|
|
91
|
-
*
|
|
92
|
-
* A simplistic approach is to add a limit to the amount of time waiting for
|
|
93
|
-
* subscribers, i.e. an ack timeout. However, deciding what this timeout
|
|
94
|
-
* should be is non-trivial because of the heterogeneous nature of changes;
|
|
95
|
-
* while most changes operate on single rows and are relatively predictable
|
|
96
|
-
* in terms of running time, some changes are table-wide operations and can
|
|
97
|
-
* legitimately take an arbitrary amount of time. In such scenarios, a
|
|
98
|
-
* timeout that is too short can stop progress on replication altogether.
|
|
99
|
-
*
|
|
100
|
-
* ### Consensus-based Timeout Algorithm
|
|
101
|
-
*
|
|
102
|
-
* To address these shortcomings, a "consensus-based timeout" algorithm is
|
|
103
|
-
* used:
|
|
104
|
-
* * Wait for more than half of the subscribers to finish. (In
|
|
105
|
-
* case of a single node, or the case of one replication-manager
|
|
106
|
-
* and one view-syncer, this reduces to waiting for all subscribers.)
|
|
107
|
-
* * Once more than half of the subscribers have finished, proceed after
|
|
108
|
-
* a fixed timeout elapses (e.g. 1 second), even if not all subscribers
|
|
109
|
-
* have finished.
|
|
110
|
-
*
|
|
111
|
-
* In other words, the subscribers themselves are used to determine the
|
|
112
|
-
* timeout of each batch of changes; the majority determines this when
|
|
113
|
-
* they complete, upon which a timeout is logically started.
|
|
114
|
-
*
|
|
115
|
-
* In the common case, the remaining subscribers finish soon afterward and
|
|
116
|
-
* the timeout never elapses. However, in pathological cases where a minority
|
|
117
|
-
* of subscribers have a disproportionate amount of load, some will still
|
|
118
|
-
* be processing (or otherwise unresponsive). These subscribers are given
|
|
119
|
-
* a bounded amount of time to catch up at each flushed batch, up to the
|
|
120
|
-
* timeout interval. This guarantees eventual catchup because the
|
|
121
|
-
* subscribers with a backlog of changes necessarily have a higher
|
|
122
|
-
* processing rate than the subscribers that finished (and are made to wait).
|
|
123
|
-
*
|
|
124
|
-
* ### Not implemented: Broken connection detection
|
|
125
|
-
*
|
|
126
|
-
* If a subscriber has not made progress for a certain interval, the
|
|
127
|
-
* algorithm could theoretically drop it preemptively, supplementing the
|
|
128
|
-
* existing websocket-level liveness checks.
|
|
129
|
-
*
|
|
130
|
-
* However, a more reliable approach would be to change the replicator
|
|
131
|
-
* to use non-blocking writes, and subsequently increase the frequency of
|
|
132
|
-
* connection-level liveness checks. The current synchronous replica writes
|
|
133
|
-
* can delay both ping responsiveness and change progress arbitrarily (e.g.
|
|
134
|
-
* a large index creation); an independently liveness check that is not
|
|
135
|
-
* delayed by synchronous writes on the subscriber would be a more failsafe
|
|
136
|
-
* solution.
|
|
137
|
-
*
|
|
138
|
-
* @returns `true` if the broadcast was already done or was marked done.
|
|
139
|
-
*/
|
|
140
|
-
checkProgress(lc, flowControlConsensusPaddingMs, now) {
|
|
141
|
-
if (this.#isDone) return true;
|
|
142
|
-
if (this.#pending.size === 0) return true;
|
|
140
|
+
logSlowRequests(now) {
|
|
141
|
+
if (this.#isDone || this.#pending.size === 0) return;
|
|
143
142
|
const elapsed = now - this.#start;
|
|
144
143
|
if (this.#completed.length < this.#majority) {
|
|
145
|
-
if (elapsed >= 1e3) this.#logWithState(
|
|
146
|
-
return false;
|
|
147
|
-
}
|
|
148
|
-
if (now - this.#latestCompleted >= flowControlConsensusPaddingMs) {
|
|
149
|
-
this.#logWithState(lc, `continuing with ${this.#pending.size} subscriber(s) still pending`, elapsed);
|
|
150
|
-
this.#setDone("consensus-timeout");
|
|
151
|
-
return true;
|
|
144
|
+
if (elapsed >= 1e3) this.#logWithState(`waiting for at least ${this.#majority} subscribers to finish`, elapsed);
|
|
152
145
|
}
|
|
153
|
-
return false;
|
|
154
146
|
}
|
|
155
|
-
#logWithState(
|
|
156
|
-
lc.withContext("watermark", this.#watermark).info?.(`${msg} (${elapsed.toFixed(3)} ms)`, {
|
|
147
|
+
#logWithState(msg, elapsed) {
|
|
148
|
+
this.#lc.withContext("watermark", this.#watermark).info?.(`${msg} (${elapsed.toFixed(3)} ms)`, {
|
|
157
149
|
completed: this.#completed.map((d) => ({
|
|
158
150
|
id: d.sub.id,
|
|
159
151
|
processed: d.changes,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"broadcast.js","names":["#pending","#completed","#done","#watermark","#majority","#start","#markCompleted","#setDone","#latestCompleted","#isDone","#releaseMode","#logWithState"],"sources":["../../../../../../zero-cache/src/services/change-streamer/broadcast.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {resolver} from '@rocicorp/resolver';\nimport type {WatermarkedChange} from './change-streamer-service.ts';\nimport type {Subscriber} from './subscriber.ts';\n\nexport type BroadcastReleaseMode = 'all-subscribers' | 'consensus-timeout';\n\n/**\n * Initiates and tracks the progress of a change broadcasted to\n * a set of subscribers.\n *\n * Creating a `Broadcast` automatically initiates the send.\n *\n * By default, {@link Broadcast.done} resolves when all subscribers\n * have acked the change. However, {@link Broadcast.checkProgress()}\n * can be called to resolve the broadcast earlier based on the flow\n * control policy.\n */\nexport class Broadcast {\n /**\n * Sends the change to the subscribers without the tracking machinery.\n * This is suitable for fire-and-forget (i.e. pipelined) sends.\n */\n static withoutTracking(\n subscribers: Iterable<Subscriber>,\n change: WatermarkedChange,\n ) {\n for (const sub of subscribers) {\n void sub.send(change);\n }\n }\n\n readonly #pending: Set<Subscriber>;\n readonly #completed: Completed[];\n readonly #done = resolver();\n #isDone = false;\n #releaseMode: BroadcastReleaseMode | undefined;\n\n readonly #watermark: string;\n readonly #majority: number;\n\n readonly #start = performance.now();\n #latestCompleted = Number.MAX_VALUE;\n\n /**\n * Broadcasts the `change` to the `subscribers` and tracks their\n * completion.\n */\n constructor(subscribers: Iterable<Subscriber>, change: WatermarkedChange) {\n this.#pending = new Set(subscribers);\n this.#completed = [];\n this.#watermark = change[0];\n this.#majority = Math.floor(this.#pending.size / 2) + 1;\n\n for (const sub of this.#pending) {\n const changes = sub.numPending + 1; // add one for this `change`\n void sub\n .send(change)\n .catch(() => {})\n .finally(() => this.#markCompleted(sub, changes));\n }\n\n // set done if there are no subscribers (mainly for tests)\n if (this.#pending.size === 0) {\n this.#setDone('all-subscribers');\n }\n }\n\n #markCompleted(sub: Subscriber, changes: number) {\n const elapsed = (this.#latestCompleted = performance.now()) - this.#start;\n this.#completed.push({sub, changes, elapsed});\n this.#pending.delete(sub);\n if (this.#pending.size === 0) {\n this.#setDone('all-subscribers');\n }\n }\n\n #setDone(releaseMode: BroadcastReleaseMode) {\n if (this.#isDone) {\n return;\n }\n this.#isDone = true;\n this.#releaseMode = releaseMode;\n this.#done.resolve();\n }\n\n get isDone(): boolean {\n return this.#isDone;\n }\n\n get done(): Promise<void> {\n return this.#done.promise;\n }\n\n get releaseMode(): BroadcastReleaseMode {\n return this.#releaseMode ?? 'all-subscribers';\n }\n\n /**\n * Checks for pathological situations in which flow should be reenabled\n * before all subscribers have acked.\n *\n * ### Background\n *\n * The purpose of flow control is to pull upstream replication changes\n * no faster than the rate as they are processed by downstream subscribers\n * in the steady state. In the change-streamer, this is done by occasionally\n * waiting for ACKs from subscribers before continuing; without doing so,\n * I/O buffers fill up and cause the system to spend most of its time in GC.\n *\n * However, the naive algorithm of always waiting for all subscribers (e.g.\n * `Promise.all()`) can behave poorly in scenarios where subscribers\n * are imbalanced:\n * * New subscribers may have a backlog of changes to catch up with.\n * Having all subscribers wait for the new subscriber to catch up results\n * in delaying the entire application.\n * * Broken TCP connections similarly require all subscribers to wait until\n * connection liveness checks kick in and disconnect the subscriber.\n *\n * A simplistic approach is to add a limit to the amount of time waiting for\n * subscribers, i.e. an ack timeout. However, deciding what this timeout\n * should be is non-trivial because of the heterogeneous nature of changes;\n * while most changes operate on single rows and are relatively predictable\n * in terms of running time, some changes are table-wide operations and can\n * legitimately take an arbitrary amount of time. In such scenarios, a\n * timeout that is too short can stop progress on replication altogether.\n *\n * ### Consensus-based Timeout Algorithm\n *\n * To address these shortcomings, a \"consensus-based timeout\" algorithm is\n * used:\n * * Wait for more than half of the subscribers to finish. (In\n * case of a single node, or the case of one replication-manager\n * and one view-syncer, this reduces to waiting for all subscribers.)\n * * Once more than half of the subscribers have finished, proceed after\n * a fixed timeout elapses (e.g. 1 second), even if not all subscribers\n * have finished.\n *\n * In other words, the subscribers themselves are used to determine the\n * timeout of each batch of changes; the majority determines this when\n * they complete, upon which a timeout is logically started.\n *\n * In the common case, the remaining subscribers finish soon afterward and\n * the timeout never elapses. However, in pathological cases where a minority\n * of subscribers have a disproportionate amount of load, some will still\n * be processing (or otherwise unresponsive). These subscribers are given\n * a bounded amount of time to catch up at each flushed batch, up to the\n * timeout interval. This guarantees eventual catchup because the\n * subscribers with a backlog of changes necessarily have a higher\n * processing rate than the subscribers that finished (and are made to wait).\n *\n * ### Not implemented: Broken connection detection\n *\n * If a subscriber has not made progress for a certain interval, the\n * algorithm could theoretically drop it preemptively, supplementing the\n * existing websocket-level liveness checks.\n *\n * However, a more reliable approach would be to change the replicator\n * to use non-blocking writes, and subsequently increase the frequency of\n * connection-level liveness checks. The current synchronous replica writes\n * can delay both ping responsiveness and change progress arbitrarily (e.g.\n * a large index creation); an independently liveness check that is not\n * delayed by synchronous writes on the subscriber would be a more failsafe\n * solution.\n *\n * @returns `true` if the broadcast was already done or was marked done.\n */\n checkProgress(\n lc: LogContext,\n flowControlConsensusPaddingMs: number,\n now: number,\n ) {\n if (this.#isDone) {\n return true;\n }\n if (this.#pending.size === 0) {\n return true;\n }\n const elapsed = now - this.#start;\n if (this.#completed.length < this.#majority) {\n if (elapsed >= 1000) {\n this.#logWithState(\n lc,\n `waiting for at least ${this.#majority} subscribers to finish`,\n elapsed,\n );\n }\n return false;\n }\n // Note: In the implementation, #latestCompleted is always updated,\n // even after the majority is reached. This is fine and does not affect\n // the important properties of the algorithm.\n if (now - this.#latestCompleted >= flowControlConsensusPaddingMs) {\n this.#logWithState(\n lc,\n `continuing with ${this.#pending.size} subscriber(s) still pending`,\n elapsed,\n );\n this.#setDone('consensus-timeout');\n return true;\n }\n return false;\n }\n\n #logWithState(lc: LogContext, msg: string, elapsed: number) {\n lc.withContext('watermark', this.#watermark).info?.(\n `${msg} (${elapsed.toFixed(3)} ms)`,\n {\n completed: this.#completed.map(d => ({\n id: d.sub.id,\n processed: d.changes,\n elapsed: d.elapsed,\n })),\n pending: Array.from(this.#pending, sub => ({\n id: sub.id,\n ...sub.getStats(),\n })),\n },\n );\n }\n}\n\n/** Tracks the completed result of a single subscriber. */\ntype Completed = {\n sub: Subscriber;\n /** The number of changes processed. */\n changes: number;\n /** The elapsed milliseconds. */\n elapsed: number;\n};\n"],"mappings":";;;;;;;;;;;;;AAkBA,IAAa,YAAb,MAAuB;;;;;CAKrB,OAAO,gBACL,aACA,QACA;EACA,KAAK,MAAM,OAAO,aAChB,IAAS,KAAK,MAAM;CAExB;CAEA;CACA;CACA,QAAiB,SAAS;CAC1B,UAAU;CACV;CAEA;CACA;CAEA,SAAkB,YAAY,IAAI;CAClC,mBAAmB,OAAO;;;;;CAM1B,YAAY,aAAmC,QAA2B;EACxE,KAAKA,WAAW,IAAI,IAAI,WAAW;EACnC,KAAKC,aAAa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AKG,cACH,IACA,mBAAmB,KAAKX,SAAS,KAAK,+BACtC,OACF;GACA,KAAKO,SAAS,mBAAmB;GACjC,OAAO;EACT;EACA,OAAO;CACT;CAEA,cAAc,IAAgB,KAAa,SAAiB;EAC1D,GAAG,YAAY,aAAa,KAAKJ,UAAU,EAAE,OAC3C,GAAG,IAAI,IAAI,QAAQ,QAAQ,CAAC,EAAE,OAC9B;GACE,WAAW,KAAKF,WAAW,KAAI,OAAM;IACnC,IAAI,EAAE,IAAI;IACV,WAAW,EAAE;IACb,SAAS,EAAE;GACb,EAAE;GACF,SAAS,MAAM,KAAK,KAAKD,WAAU,SAAQ;IACzC,IAAI,IAAI;IACR,GAAG,IAAI,SAAS;GAClB,EAAE;EACJ,CACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"broadcast.js","names":["#lc","#pending","#completed","#done","#watermark","#majority","#start","#earlyReleaseTimeoutProportion","#setTimeout","#clearTimeout","#markCompleted","#setDone","#isDone","#earlyReleaseTimer","#logWithState","#releaseMode"],"sources":["../../../../../../zero-cache/src/services/change-streamer/broadcast.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {resolver} from '@rocicorp/resolver';\nimport type {WatermarkedChange} from './change-streamer-service.ts';\nimport type {Subscriber} from './subscriber.ts';\n\nexport type BroadcastReleaseMode = 'all-subscribers' | 'consensus-timeout';\n\n/**\n * Enables event-driven early release of a {@link Broadcast}. When provided and a\n * majority has acked, the broadcast schedules its own consensus-timeout release\n * proportional to how long the majority took to ack, instead of relying on the\n * Forwarder's periodic progress tick.\n */\nexport type EarlyReleaseOptions = {\n /** Time to wait, proportional to majority completion, before releasing. */\n consensusTimeoutProportion: number;\n /** Injectable timer, for deterministic testing. */\n setTimeoutFn?: typeof setTimeout;\n /** Injectable timer cancellation, for deterministic testing. */\n clearTimeoutFn?: typeof clearTimeout;\n};\n\n/**\n * Initiates and tracks the progress of a change broadcasted to\n * a set of subscribers, implementing **consensus-based timeouts**\n * to effect short-term graceful degradation when a minority of\n * subscribers are behind.\n *\n * ### Background\n *\n * The purpose of flow control is to pull upstream replication changes\n * no faster than the rate they are processed by downstream subscribers\n * in the steady state. In the change-streamer, this is done by occasionally\n * waiting for ACKs from subscribers before continuing; without doing so,\n * I/O buffers fill up and cause the system to spend most of its time in GC.\n *\n * However, the naive algorithm of always waiting for all subscribers (e.g.\n * `Promise.all()`) can behave poorly in scenarios where subscribers\n * are imbalanced:\n * * New subscribers may have a backlog of changes to catch up with.\n * Having all subscribers wait for the new subscriber to catch up results\n * in delaying the entire application.\n * * Broken TCP connections similarly require all subscribers to wait until\n * connection liveness checks kick in and disconnect the subscriber.\n *\n * A simplistic approach is to add a limit to the amount of time waiting for\n * subscribers, i.e. an ack timeout. However, deciding what this timeout\n * should be is non-trivial because of the heterogeneous nature of changes;\n * while most changes operate on single rows and are relatively predictable\n * in terms of running time, some changes are table-wide operations and can\n * legitimately take an arbitrary amount of time. In such scenarios, a\n * timeout that is too short can stop progress on replication altogether.\n *\n * ### Consensus-based Timeout Algorithm\n *\n * To address these shortcomings, a \"consensus-based timeout\" algorithm is\n * used:\n * * Wait for more than half of the subscribers to finish. (In\n * case of a single node, or the case of one replication-manager\n * and one view-syncer, this reduces to waiting for all subscribers.)\n * * Once more than half of the subscribers have finished, proceed after\n * the configured timeout, proportional to the time it took for the\n * majority of subscribers to ack, even if not all subscribers have\n * finished.\n *\n * In other words, the subscribers themselves are used to determine the\n * timeout of each batch of changes; the majority determines this when\n * they complete, upon which a timeout is logically started.\n *\n * In the common case, the remaining subscribers finish soon afterward and\n * the timeout never elapses. However, in pathological cases where a minority\n * of subscribers have a disproportionate amount of load, some will still\n * be processing (or otherwise unresponsive). These subscribers are given\n * a bounded amount of time to catch up at each flushed batch, up to the\n * timeout interval. This guarantees eventual catchup because the\n * subscribers with a backlog of changes necessarily have a higher\n * processing rate than the subscribers that finished (and are made to wait).\n */\nexport class Broadcast {\n /**\n * Sends the change to the subscribers without the tracking machinery.\n * This is suitable for fire-and-forget (i.e. pipelined) sends.\n */\n static withoutTracking(\n subscribers: Iterable<Subscriber>,\n change: WatermarkedChange,\n ) {\n for (const sub of subscribers) {\n void sub.send(change);\n }\n }\n\n readonly #lc: LogContext;\n readonly #pending: Set<Subscriber>;\n readonly #completed: Completed[];\n readonly #done = resolver();\n #isDone = false;\n #releaseMode: BroadcastReleaseMode | undefined;\n\n readonly #watermark: string;\n readonly #majority: number;\n\n readonly #start = performance.now();\n\n // When set, the broadcast schedules its own consensus-timeout release instead\n // of waiting for the Forwarder's periodic progress tick.\n readonly #earlyReleaseTimeoutProportion: number | undefined;\n readonly #setTimeout: typeof setTimeout;\n readonly #clearTimeout: typeof clearTimeout;\n #earlyReleaseTimer: ReturnType<typeof setTimeout> | undefined;\n\n /**\n * Broadcasts the `change` to the `subscribers` and tracks their\n * completion.\n */\n constructor(\n lc: LogContext,\n subscribers: Iterable<Subscriber>,\n change: WatermarkedChange,\n earlyRelease?: EarlyReleaseOptions,\n ) {\n this.#lc = lc;\n this.#pending = new Set(subscribers);\n this.#completed = [];\n this.#watermark = change[0];\n this.#majority = Math.floor(this.#pending.size / 2) + 1;\n this.#earlyReleaseTimeoutProportion =\n earlyRelease?.consensusTimeoutProportion;\n this.#setTimeout = earlyRelease?.setTimeoutFn ?? setTimeout;\n this.#clearTimeout = earlyRelease?.clearTimeoutFn ?? clearTimeout;\n\n for (const sub of this.#pending) {\n const changes = sub.numPending + 1; // add one for this `change`\n void sub\n .send(change)\n .catch(() => {})\n .finally(() => this.#markCompleted(sub, changes));\n }\n\n // set done if there are no subscribers (mainly for tests)\n if (this.#pending.size === 0) {\n this.#setDone('all-subscribers');\n }\n }\n\n #markCompleted(sub: Subscriber, changes: number) {\n if (this.#isDone) {\n return;\n }\n const elapsed = performance.now() - this.#start;\n sub.trackResponseResult('on-time');\n\n this.#completed.push({sub, changes, elapsed});\n this.#pending.delete(sub);\n if (this.#pending.size === 0) {\n this.#setDone('all-subscribers');\n return;\n }\n // Event-driven consensus-timeout: the moment a majority acks, arm a single\n // release timer proportional to how long the majority took to ack. The\n // broadcast resolves when it fires, unless all subscribers ack first.\n if (\n this.#earlyReleaseTimeoutProportion !== undefined &&\n this.#earlyReleaseTimer === undefined &&\n this.#completed.length === this.#majority\n ) {\n const timeoutMs = Math.ceil(\n elapsed * this.#earlyReleaseTimeoutProportion,\n );\n this.#earlyReleaseTimer = this.#setTimeout(\n () => this.#setDone('consensus-timeout'),\n timeoutMs,\n );\n }\n }\n\n #setDone(releaseMode: BroadcastReleaseMode) {\n if (this.#isDone) {\n return;\n }\n if (releaseMode === 'consensus-timeout') {\n const elapsed = performance.now() - this.#start;\n this.#logWithState(\n `continuing with ${this.#pending.size} subscriber(s) still pending`,\n elapsed,\n );\n }\n this.#pending.forEach(sub => sub.trackResponseResult('timed-out'));\n this.#isDone = true;\n this.#releaseMode = releaseMode;\n this.#clearTimeout(this.#earlyReleaseTimer);\n this.#earlyReleaseTimer = undefined;\n this.#done.resolve();\n }\n\n get isDone(): boolean {\n return this.#isDone;\n }\n\n get done(): Promise<void> {\n return this.#done.promise;\n }\n\n get releaseMode(): BroadcastReleaseMode {\n return this.#releaseMode ?? 'all-subscribers';\n }\n\n logSlowRequests(now: number) {\n if (this.#isDone || this.#pending.size === 0) {\n return;\n }\n const elapsed = now - this.#start;\n if (this.#completed.length < this.#majority) {\n if (elapsed >= 1000) {\n this.#logWithState(\n `waiting for at least ${this.#majority} subscribers to finish`,\n elapsed,\n );\n }\n }\n }\n\n #logWithState(msg: string, elapsed: number) {\n this.#lc\n .withContext('watermark', this.#watermark)\n .info?.(`${msg} (${elapsed.toFixed(3)} ms)`, {\n completed: this.#completed.map(d => ({\n id: d.sub.id,\n processed: d.changes,\n elapsed: d.elapsed,\n })),\n pending: Array.from(this.#pending, sub => ({\n id: sub.id,\n ...sub.getStats(),\n })),\n });\n }\n}\n\n/** Tracks the completed result of a single subscriber. */\ntype Completed = {\n sub: Subscriber;\n /** The number of changes processed. */\n changes: number;\n /** The elapsed millise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"}
|
|
@@ -8,7 +8,8 @@ import type { SubscriptionState } from '../replicator/schema/replication-state.t
|
|
|
8
8
|
import { type ChangeStreamerService } from './change-streamer.ts';
|
|
9
9
|
import { type PurgeLock, type TuningOptions as StorerOptions } from './storer.ts';
|
|
10
10
|
export type TuningOptions = StorerOptions & {
|
|
11
|
-
|
|
11
|
+
flowControlConsensusTimeoutProportion: number;
|
|
12
|
+
flowControlSlowSubscriberGracePeriodMs?: number | undefined;
|
|
12
13
|
};
|
|
13
14
|
/**
|
|
14
15
|
* Performs initialization and schema migrations to initialize a ChangeStreamerImpl.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"change-streamer-service.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/change-streamer-service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"change-streamer-service.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/change-streamer-service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAYjD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,uBAAuB,CAAC;AAGnD,OAAO,KAAK,EACV,YAAY,EAEb,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAEL,KAAK,gBAAgB,EAEtB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAGL,KAAK,0BAA0B,EAChC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,2CAA2C,CAAC;AAMjF,OAAO,EACL,KAAK,qBAAqB,EAG3B,MAAM,sBAAsB,CAAC;AAS9B,OAAO,EAEL,KAAK,SAAS,EACd,KAAK,aAAa,IAAI,aAAa,EACpC,MAAM,aAAa,CAAC;AAGrB,MAAM,MAAM,aAAa,GAAG,aAAa,GAAG;IAC1C,qCAAqC,EAAE,MAAM,CAAC;IAC9C,sCAAsC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC7D,CAAC;AAEF;;GAEG;AACH,wBAAsB,kBAAkB,CACtC,EAAE,EAAE,UAAU,EACd,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,MAAM,EACd,gBAAgB,EAAE,MAAM,EACxB,iBAAiB,EAAE,MAAM,EACzB,QAAQ,EAAE,UAAU,EACpB,YAAY,EAAE,YAAY,EAC1B,0BAA0B,EAAE,0BAA0B,EACtD,iBAAiB,EAAE,iBAAiB,EACpC,SAAS,EAAE,SAAS,GAAG,IAAI,EAC3B,SAAS,EAAE,OAAO,EAClB,IAAI,EAAE,aAAa,EACnB,YAAY,oBAAa,GACxB,OAAO,CAAC,qBAAqB,CAAC,CA4BhC;AAID,MAAM,MAAM,SAAS,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AAEnD;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,SAAS,EAAE,MAAM;IACjB,GAAG,EAAE,SAAS;IACd,IAAI,EAAE,MAAM;CACb,CAAC"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { unreachable } from "../../../../shared/src/asserts.js";
|
|
2
2
|
import { promiseVoid } from "../../../../shared/src/resolved-promises.js";
|
|
3
|
+
import { promiseOrAbort } from "../../../../shared/src/promise-race.js";
|
|
3
4
|
import "../change-source/protocol/current/downstream.js";
|
|
4
5
|
import { getOrCreateCounter } from "../../observability/metrics.js";
|
|
5
6
|
import { DEFAULT_MAX_RETRY_DELAY_MS, RunningState, UnrecoverableError } from "../running-state.js";
|
|
@@ -195,7 +196,10 @@ var ChangeStreamerImpl = class {
|
|
|
195
196
|
consumed[1],
|
|
196
197
|
consumed[2]
|
|
197
198
|
]), (err) => this.stop(err), opts);
|
|
198
|
-
this.#forwarder = new Forwarder(lc, {
|
|
199
|
+
this.#forwarder = new Forwarder(lc, {
|
|
200
|
+
flowControlConsensusTimeoutProportion: opts.flowControlConsensusTimeoutProportion,
|
|
201
|
+
flowControlSlowSubscriberGracePeriodMs: opts.flowControlSlowSubscriberGracePeriodMs
|
|
202
|
+
});
|
|
199
203
|
this.#replicationStatusPublisher = replicationStatusPublisher;
|
|
200
204
|
this.#purgeLock = initialPurgeLock;
|
|
201
205
|
this.#autoReset = autoReset;
|
|
@@ -255,13 +259,12 @@ var ChangeStreamerImpl = class {
|
|
|
255
259
|
unflushedBytes += json.length;
|
|
256
260
|
if (unflushedBytes < flushBytesThreshold) this.#forwarder.forward(entry);
|
|
257
261
|
else {
|
|
258
|
-
|
|
259
|
-
await stream.changes.doneOr(forwarded);
|
|
262
|
+
await promiseOrAbort(this.#forwarder.forwardWithFlowControl(entry), stream.changes.signal, this.#state.signal);
|
|
260
263
|
unflushedBytes = 0;
|
|
261
264
|
}
|
|
262
265
|
if (type === "commit" || type === "rollback") watermark = null;
|
|
263
266
|
const readyForMore = this.#storer.readyForMore();
|
|
264
|
-
if (readyForMore) await stream.changes.
|
|
267
|
+
if (readyForMore) await promiseOrAbort(readyForMore, stream.changes.signal, this.#state.signal);
|
|
265
268
|
}
|
|
266
269
|
} catch (e) {
|
|
267
270
|
err = e;
|