@moq/net 0.3.5 → 0.4.1

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 (244) hide show
  1. package/announce.d.ts +7 -0
  2. package/announce.d.ts.map +1 -0
  3. package/announce.js +8 -0
  4. package/announce.js.map +1 -0
  5. package/announced.d.ts +49 -91
  6. package/announced.d.ts.map +1 -1
  7. package/announced.js +21 -156
  8. package/announced.js.map +1 -1
  9. package/bandwidth.d.ts +163 -0
  10. package/bandwidth.d.ts.map +1 -0
  11. package/bandwidth.js +304 -0
  12. package/bandwidth.js.map +1 -0
  13. package/bandwidth_api.d.ts +7 -0
  14. package/bandwidth_api.d.ts.map +1 -0
  15. package/bandwidth_api.js +8 -0
  16. package/bandwidth_api.js.map +1 -0
  17. package/broadcast.d.ts +23 -28
  18. package/broadcast.d.ts.map +1 -1
  19. package/broadcast.js +61 -40
  20. package/broadcast.js.map +1 -1
  21. package/connection/accept.d.ts +16 -1
  22. package/connection/accept.d.ts.map +1 -1
  23. package/connection/accept.js +48 -25
  24. package/connection/accept.js.map +1 -1
  25. package/connection/browser.d.ts.map +1 -1
  26. package/connection/browser.js +9 -7
  27. package/connection/browser.js.map +1 -1
  28. package/connection/connect.d.ts +30 -6
  29. package/connection/connect.d.ts.map +1 -1
  30. package/connection/connect.js +95 -46
  31. package/connection/connect.js.map +1 -1
  32. package/connection/established.d.ts +17 -21
  33. package/connection/established.d.ts.map +1 -1
  34. package/connection/established.js.map +1 -1
  35. package/connection/forward.d.ts +2 -0
  36. package/connection/forward.d.ts.map +1 -0
  37. package/connection/forward.js +166 -0
  38. package/connection/forward.js.map +1 -0
  39. package/connection/handshake.d.ts +1 -0
  40. package/connection/handshake.d.ts.map +1 -1
  41. package/connection/handshake.js +5 -2
  42. package/connection/handshake.js.map +1 -1
  43. package/connection/index.d.ts +5 -5
  44. package/connection/index.d.ts.map +1 -1
  45. package/connection/index.js +4 -5
  46. package/connection/index.js.map +1 -1
  47. package/connection/pool.d.ts +186 -0
  48. package/connection/pool.d.ts.map +1 -0
  49. package/connection/pool.js +361 -0
  50. package/connection/pool.js.map +1 -0
  51. package/connection/reload.d.ts +14 -93
  52. package/connection/reload.d.ts.map +1 -1
  53. package/connection/reload.js +217 -81
  54. package/connection/reload.js.map +1 -1
  55. package/connection/stats.d.ts +3 -26
  56. package/connection/stats.d.ts.map +1 -1
  57. package/connection/stats.js.map +1 -1
  58. package/connection/transport.d.ts +0 -7
  59. package/connection/transport.d.ts.map +1 -1
  60. package/consume.d.ts +1 -43
  61. package/consume.d.ts.map +1 -1
  62. package/consume.js +1 -1
  63. package/consume.js.map +1 -1
  64. package/error.d.ts +180 -29
  65. package/error.d.ts.map +1 -1
  66. package/error.js +331 -16
  67. package/error.js.map +1 -1
  68. package/errors.d.ts +7 -0
  69. package/errors.d.ts.map +1 -0
  70. package/errors.js +8 -0
  71. package/errors.js.map +1 -0
  72. package/group.d.ts +9 -43
  73. package/group.d.ts.map +1 -1
  74. package/group.js +283 -69
  75. package/group.js.map +1 -1
  76. package/hop.d.ts +107 -0
  77. package/hop.d.ts.map +1 -0
  78. package/hop.js +103 -0
  79. package/hop.js.map +1 -0
  80. package/ietf/adapter.d.ts +5 -1
  81. package/ietf/adapter.d.ts.map +1 -1
  82. package/ietf/adapter.js +27 -9
  83. package/ietf/adapter.js.map +1 -1
  84. package/ietf/aliases.d.ts +1 -78
  85. package/ietf/aliases.d.ts.map +1 -1
  86. package/ietf/cluster.d.ts +6 -120
  87. package/ietf/cluster.d.ts.map +1 -1
  88. package/ietf/cluster.js +81 -41
  89. package/ietf/cluster.js.map +1 -1
  90. package/ietf/connection.d.ts +6 -72
  91. package/ietf/connection.d.ts.map +1 -1
  92. package/ietf/connection.js +17 -49
  93. package/ietf/connection.js.map +1 -1
  94. package/ietf/error.d.ts +11 -0
  95. package/ietf/error.d.ts.map +1 -0
  96. package/ietf/error.js +193 -0
  97. package/ietf/error.js.map +1 -0
  98. package/ietf/filter.d.ts.map +1 -1
  99. package/ietf/filter.js +6 -1
  100. package/ietf/filter.js.map +1 -1
  101. package/ietf/goaway.d.ts.map +1 -1
  102. package/ietf/goaway.js +22 -5
  103. package/ietf/goaway.js.map +1 -1
  104. package/ietf/hidden.d.ts +2 -0
  105. package/ietf/hidden.d.ts.map +1 -0
  106. package/ietf/hidden.js +30 -0
  107. package/ietf/hidden.js.map +1 -0
  108. package/ietf/index.d.ts +1 -0
  109. package/ietf/index.d.ts.map +1 -1
  110. package/ietf/index.js +1 -0
  111. package/ietf/index.js.map +1 -1
  112. package/ietf/object.d.ts +8 -2
  113. package/ietf/object.d.ts.map +1 -1
  114. package/ietf/object.js +17 -3
  115. package/ietf/object.js.map +1 -1
  116. package/ietf/parameters.d.ts +7 -2
  117. package/ietf/parameters.d.ts.map +1 -1
  118. package/ietf/parameters.js +35 -17
  119. package/ietf/parameters.js.map +1 -1
  120. package/ietf/properties.d.ts +1 -0
  121. package/ietf/properties.d.ts.map +1 -1
  122. package/ietf/properties.js +14 -0
  123. package/ietf/properties.js.map +1 -1
  124. package/ietf/publish.d.ts +19 -2
  125. package/ietf/publish.d.ts.map +1 -1
  126. package/ietf/publish.js +40 -6
  127. package/ietf/publish.js.map +1 -1
  128. package/ietf/publish_namespace.d.ts +25 -0
  129. package/ietf/publish_namespace.d.ts.map +1 -1
  130. package/ietf/publish_namespace.js +63 -0
  131. package/ietf/publish_namespace.js.map +1 -1
  132. package/ietf/publisher.d.ts +1 -82
  133. package/ietf/publisher.d.ts.map +1 -1
  134. package/ietf/publisher.js +302 -181
  135. package/ietf/publisher.js.map +1 -1
  136. package/ietf/solicit.d.ts +1 -40
  137. package/ietf/solicit.d.ts.map +1 -1
  138. package/ietf/subscribe.d.ts +1 -5
  139. package/ietf/subscribe.d.ts.map +1 -1
  140. package/ietf/subscribe.js +11 -13
  141. package/ietf/subscribe.js.map +1 -1
  142. package/ietf/subscribe_namespace.d.ts +8 -2
  143. package/ietf/subscribe_namespace.d.ts.map +1 -1
  144. package/ietf/subscribe_namespace.js +18 -8
  145. package/ietf/subscribe_namespace.js.map +1 -1
  146. package/ietf/subscriber.d.ts +1 -65
  147. package/ietf/subscriber.d.ts.map +1 -1
  148. package/ietf/subscriber.js +325 -121
  149. package/ietf/subscriber.js.map +1 -1
  150. package/ietf/version.d.ts +12 -1
  151. package/ietf/version.d.ts.map +1 -1
  152. package/ietf/version.js +13 -0
  153. package/ietf/version.js.map +1 -1
  154. package/index.d.ts +11 -6
  155. package/index.d.ts.map +1 -1
  156. package/index.js +10 -5
  157. package/index.js.map +1 -1
  158. package/internal.d.ts +104 -1
  159. package/internal.d.ts.map +1 -1
  160. package/internal.js +76 -0
  161. package/internal.js.map +1 -1
  162. package/lite/announce.d.ts +60 -10
  163. package/lite/announce.d.ts.map +1 -1
  164. package/lite/announce.js +173 -31
  165. package/lite/announce.js.map +1 -1
  166. package/lite/connection.d.ts +9 -59
  167. package/lite/connection.d.ts.map +1 -1
  168. package/lite/connection.js +26 -32
  169. package/lite/connection.js.map +1 -1
  170. package/lite/fetch.d.ts +15 -1
  171. package/lite/fetch.d.ts.map +1 -1
  172. package/lite/fetch.js +39 -7
  173. package/lite/fetch.js.map +1 -1
  174. package/lite/goaway.d.ts.map +1 -1
  175. package/lite/goaway.js +7 -1
  176. package/lite/goaway.js.map +1 -1
  177. package/lite/group.d.ts +18 -4
  178. package/lite/group.d.ts.map +1 -1
  179. package/lite/group.js +31 -10
  180. package/lite/group.js.map +1 -1
  181. package/lite/priority.d.ts +1 -61
  182. package/lite/priority.d.ts.map +1 -1
  183. package/lite/priority.js +4 -5
  184. package/lite/priority.js.map +1 -1
  185. package/lite/publisher.d.ts +1 -69
  186. package/lite/publisher.d.ts.map +1 -1
  187. package/lite/publisher.js +593 -227
  188. package/lite/publisher.js.map +1 -1
  189. package/lite/setup.d.ts +7 -7
  190. package/lite/setup.d.ts.map +1 -1
  191. package/lite/setup.js +13 -13
  192. package/lite/setup.js.map +1 -1
  193. package/lite/subscribe.d.ts +71 -17
  194. package/lite/subscribe.d.ts.map +1 -1
  195. package/lite/subscribe.js +205 -53
  196. package/lite/subscribe.js.map +1 -1
  197. package/lite/subscriber.d.ts +15 -56
  198. package/lite/subscriber.d.ts.map +1 -1
  199. package/lite/subscriber.js +316 -188
  200. package/lite/subscriber.js.map +1 -1
  201. package/lite/track.d.ts +4 -10
  202. package/lite/track.d.ts.map +1 -1
  203. package/lite/track.js +34 -29
  204. package/lite/track.js.map +1 -1
  205. package/lite/version.d.ts +42 -6
  206. package/lite/version.d.ts.map +1 -1
  207. package/lite/version.js +126 -10
  208. package/lite/version.js.map +1 -1
  209. package/origin.d.ts +248 -29
  210. package/origin.d.ts.map +1 -1
  211. package/origin.js +1232 -37
  212. package/origin.js.map +1 -1
  213. package/package.json +8 -3
  214. package/path.d.ts +25 -7
  215. package/path.d.ts.map +1 -1
  216. package/path.js +5 -3
  217. package/path.js.map +1 -1
  218. package/stream.d.ts +2 -2
  219. package/stream.d.ts.map +1 -1
  220. package/stream.js +39 -25
  221. package/stream.js.map +1 -1
  222. package/tail.d.ts +11 -0
  223. package/tail.d.ts.map +1 -0
  224. package/tail.js +121 -0
  225. package/tail.js.map +1 -0
  226. package/time.d.ts +15 -2
  227. package/time.d.ts.map +1 -1
  228. package/time.js +28 -9
  229. package/time.js.map +1 -1
  230. package/track.d.ts +195 -84
  231. package/track.d.ts.map +1 -1
  232. package/track.js +694 -196
  233. package/track.js.map +1 -1
  234. package/wire.d.ts +69 -0
  235. package/wire.d.ts.map +1 -0
  236. package/wire.js +32 -0
  237. package/wire.js.map +1 -0
  238. package/zod.d.ts +1 -1
  239. package/zod.d.ts.map +1 -1
  240. package/zod.js.map +1 -1
  241. package/mock.d.ts +0 -66
  242. package/mock.d.ts.map +0 -1
  243. package/mock.js +0 -243
  244. package/mock.js.map +0 -1
@@ -1,17 +1,35 @@
1
1
  /* @ts-self-types="./reload.d.ts" */
2
- import { Effect, Signal } from "@moq/signals";
2
+ import { Effect, Once, Signal } from "@moq/signals";
3
3
  import * as Announce from "../announced.js";
4
- import { error } from "../error.js";
5
- import { empty as emptyPath } from "../path.js";
4
+ import { Allocator } from "../bandwidth.js";
5
+ import { error, SessionCode, SessionError } from "../error.js";
6
+ import * as Path from "../path.js";
7
+ import * as Time from "../time.js";
8
+ import { wireOf } from "../wire.js";
6
9
  import { connect } from "./connect.js";
7
10
  /**
8
- * How long to keep retrying before giving up, when {@link ReloadDelay.timeout} is unset.
11
+ * The backoff applied to whichever {@link ReloadDelay} fields a caller leaves out.
9
12
  *
10
- * Short on purpose: a failure that clears within it was transient, and one that doesn't should
11
- * surface as an error rather than leave the page silently reconnecting for minutes.
13
+ * The timeout is short on purpose: a failure that clears within it was transient, and one that
14
+ * doesn't should surface on {@link Reload.error} rather than leave the page silently
15
+ * reconnecting for minutes. A loop nobody watches wants `timeout: 0` instead, since there is
16
+ * no one to react. Giving up does not dispose the loop: a new URL or a disable/re-enable
17
+ * starts another sequence.
18
+ */
19
+ const DEFAULT_DELAY = {
20
+ initial: Time.Milli(1000),
21
+ multiplier: 2,
22
+ max: Time.Milli(5000),
23
+ timeout: Time.Milli(10000),
24
+ };
25
+ /** How often the send-rate estimate is sampled from the live transport. */
26
+ const BANDWIDTH_POLL = 100;
27
+ /**
28
+ * The reconnect loop behind a Connection handle: connects, waits for the session to end, then
29
+ * redials with exponential backoff.
30
+ *
31
+ * @internal
12
32
  */
13
- const DEFAULT_TIMEOUT = 10000;
14
- /** Maintains a MoQ connection, reconnecting with exponential backoff when it drops. */
15
33
  export class Reload {
16
34
  /** Relay URL to connect to; updating it triggers a reconnect. */
17
35
  url;
@@ -19,6 +37,14 @@ export class Reload {
19
37
  enabled;
20
38
  /** Current connection status. */
21
39
  status = new Signal("disconnected");
40
+ /**
41
+ * The failure that stopped retrying the current URL, or undefined while the loop is live.
42
+ *
43
+ * Set on an auth rejection or when the retry window expires. Cleared when a new URL or a
44
+ * disable/re-enable starts another sequence, not on a page hide/show. Transient drops
45
+ * that are still being retried leave this empty.
46
+ */
47
+ error;
22
48
  /** The currently established session, or undefined while disconnected. */
23
49
  established = new Signal(undefined);
24
50
  /**
@@ -28,6 +54,14 @@ export class Reload {
28
54
  * See {@link Established.probe}.
29
55
  */
30
56
  probe;
57
+ /**
58
+ * Divides this connection's send-rate estimate among the tracks sharing it.
59
+ *
60
+ * The same instance across reconnects, so reservations survive a drop. The
61
+ * estimate is `undefined` while disconnected, which tells a sender to hold
62
+ * its rate rather than encode at zero.
63
+ */
64
+ bandwidth;
31
65
  /** WebTransport options applied to each connection attempt (not reactive). */
32
66
  webtransport;
33
67
  /** WebSocket fallback options applied to each connection attempt (not reactive). */
@@ -37,23 +71,50 @@ export class Reload {
37
71
  * reactive). Undefined defers to the default for the URL. See {@link Established.discovery}.
38
72
  */
39
73
  discovery;
40
- /** Backoff settings for the reconnect loop. */
74
+ /**
75
+ * The origin whose broadcasts are served, spanning reconnects (not reactive).
76
+ *
77
+ * Each session announces the origin's table when it attaches, so a broadcast published
78
+ * while offline surfaces on the next connection and a reconnect re-announces everything
79
+ * still published. See the `publish` connect option.
80
+ */
81
+ publish;
82
+ /**
83
+ * The origin fed with the peer's announced broadcasts, spanning reconnects (not
84
+ * reactive).
85
+ *
86
+ * The entries a session fed retract when it dies, and the next session re-populates the
87
+ * table, so a consumer watching the origin sees offline/online transitions across a
88
+ * reconnect. See the `consume` connect option.
89
+ */
90
+ consume;
91
+ /** Backoff settings for the reconnect loop; an unset field uses its default. */
41
92
  delay;
42
93
  /** The reactive effect scope driving the connect loop; closed by {@link Reload.close}. */
43
94
  #signals = new Effect();
95
+ // Sampled from the live session; undefined while disconnected or the transport has none.
96
+ #estimate = new Signal(undefined);
44
97
  /**
45
- * Resolves when the reconnect loop stops via {@link Reload.close}.
46
- *
47
- * Rejects when the loop gives up instead, carrying the failure that was in flight when the
48
- * retry window expired.
98
+ * Settles once this loop is disposed via {@link Reload.close}: `null` on a clean close,
99
+ * or the abort {@link Error}. Peek it synchronously (`undefined` while open), observe it
100
+ * reactively, or `await` it. Attempt failures live on {@link Reload.error} instead.
49
101
  */
50
- closed;
51
- #closedResolve;
52
- #closedReject;
102
+ get closed() {
103
+ return this.#closed;
104
+ }
105
+ #closed = new Once();
106
+ #error = new Signal(undefined);
53
107
  // The current wait between attempts, doubling per failure, and when the retry window expires.
54
108
  // Both are undefined between sequences, so a later edit to `delay` applies to the next one.
55
109
  #delay;
56
110
  #deadline;
111
+ // The URL the current retry sequence is for. Cleared when disabled, URL-less, or given
112
+ // up, so the next attempt starts a fresh backoff window.
113
+ #sequenceHref;
114
+ // The href that exhausted its retry sequence. Survives a page hide/show so resume does
115
+ // not redial credentials the peer already refused. Cleared when the URL changes or the
116
+ // loop is disabled.
117
+ #givenUpHref;
57
118
  // Increased by 1 each time to trigger a reload.
58
119
  #tick = new Signal(0);
59
120
  // True after the browser freezes or hides the page until it visibly resumes.
@@ -63,25 +124,30 @@ export class Reload {
63
124
  #url;
64
125
  constructor(props) {
65
126
  this.url = Signal.from(props?.url);
66
- this.enabled = Signal.from(props?.enabled ?? false);
67
- this.delay = props?.delay ?? { initial: 1000, multiplier: 2, max: 5000 };
127
+ this.enabled = Signal.from(props?.enabled ?? true);
128
+ this.delay = props?.delay ?? {};
68
129
  this.webtransport = props?.webtransport;
69
130
  this.websocket = props?.websocket;
70
131
  this.discovery = props?.discovery;
71
- this.closed = new Promise((resolve, reject) => {
72
- this.#closedResolve = resolve;
73
- this.#closedReject = reject;
74
- });
75
- // A caller is free to never await `closed`, and giving up rejects it unprompted. Marking the
76
- // rejection handled here keeps that from surfacing as an `unhandledrejection`; a consumer
77
- // awaiting the same promise still receives it.
78
- this.closed.catch(() => { });
79
- if (typeof window !== "undefined" && typeof document !== "undefined") {
80
- this.#signals.event(window, "pagehide", () => this.#suspended.set(true));
81
- this.#signals.event(window, "pageshow", () => this.#suspended.set(false));
82
- this.#signals.event(window, "unload", () => this.#suspended.set(true));
83
- this.#signals.event(document, "visibilitychange", () => {
84
- if (!document.hidden)
132
+ this.publish = props?.publish;
133
+ this.consume = props?.consume;
134
+ // Requests on the consume origin stay pending across a reconnect, and before the
135
+ // first session establishes, rather than reading as unroutable the moment no session
136
+ // is attached. Released only when this loop is disposed: giving up the current URL
137
+ // is recoverable (a new URL or a disable/re-enable starts another sequence), so a
138
+ // request must keep waiting rather than go unroutable in the gap.
139
+ if (this.consume) {
140
+ this.#signals.cleanup(wireOf(this.consume).expect());
141
+ }
142
+ this.error = this.#error;
143
+ const win = globalThis.window;
144
+ const doc = globalThis.document;
145
+ if (typeof win !== "undefined" && typeof doc !== "undefined") {
146
+ this.#signals.event(win, "pagehide", () => this.#suspended.set(true));
147
+ this.#signals.event(win, "pageshow", () => this.#suspended.set(false));
148
+ this.#signals.event(win, "unload", () => this.#suspended.set(true));
149
+ this.#signals.event(doc, "visibilitychange", () => {
150
+ if (!doc.hidden)
85
151
  this.#suspended.set(false);
86
152
  });
87
153
  }
@@ -89,6 +155,32 @@ export class Reload {
89
155
  const connection = effect.get(this.established);
90
156
  return connection && effect.get(connection.probe);
91
157
  });
158
+ this.bandwidth = new Allocator(this.#estimate);
159
+ this.#signals.cleanup(() => this.bandwidth.close());
160
+ // The transport has no event for the send-rate estimate, so sample on our
161
+ // own schedule and skip a tick while the previous snapshot is outstanding.
162
+ this.#signals.run((effect) => {
163
+ effect.set(this.#estimate, undefined);
164
+ const connection = effect.get(this.established);
165
+ if (!connection)
166
+ return;
167
+ let pending = false;
168
+ const sample = async () => {
169
+ if (pending)
170
+ return;
171
+ pending = true;
172
+ try {
173
+ const stats = await effect.race(connection.stats());
174
+ if (stats)
175
+ this.#estimate.set(stats.estimatedSendRate);
176
+ }
177
+ finally {
178
+ pending = false;
179
+ }
180
+ };
181
+ void sample();
182
+ effect.interval(() => void sample(), BANDWIDTH_POLL);
183
+ });
92
184
  this.#url = this.#signals.computed((effect) => effect.get(this.url)?.href);
93
185
  // Create a reactive root so cleanup is easier.
94
186
  this.#signals.run(this.#connect.bind(this));
@@ -96,14 +188,34 @@ export class Reload {
96
188
  #connect(effect) {
97
189
  // Will retry when the tick changes.
98
190
  effect.get(this.#tick);
99
- const suspended = effect.get(this.#suspended);
100
191
  const enabled = effect.get(this.enabled);
101
- if (!enabled || suspended)
192
+ if (!enabled) {
193
+ this.#givenUpHref = undefined;
194
+ this.#resetSequence();
195
+ return;
196
+ }
197
+ // Hide/freeze pauses an in-flight sequence without recovering from give-up.
198
+ const suspended = effect.get(this.#suspended);
199
+ if (suspended) {
200
+ this.#resetSequence();
102
201
  return;
202
+ }
103
203
  const href = effect.get(this.#url);
104
- if (!href)
204
+ if (!href) {
205
+ this.#givenUpHref = undefined;
206
+ this.#resetSequence();
105
207
  return;
208
+ }
106
209
  const url = new URL(href);
210
+ if (this.#givenUpHref === href) {
211
+ return;
212
+ }
213
+ if (this.#sequenceHref !== href) {
214
+ this.#resetSequence();
215
+ this.#sequenceHref = href;
216
+ this.#error.set(undefined);
217
+ this.#givenUpHref = undefined;
218
+ }
107
219
  effect.set(this.status, "connecting", "disconnected");
108
220
  // This run's teardown, handed to connect() so a rerun cancels the attempt in flight.
109
221
  const signal = effect.abort;
@@ -112,10 +224,13 @@ export class Reload {
112
224
  // later dropped from a connect failure or a peer that flaps immediately.
113
225
  let connected;
114
226
  try {
115
- const connection = await connect(url, {
227
+ const connection = await connect({
228
+ url,
116
229
  websocket: this.websocket,
117
230
  webtransport: this.webtransport,
118
231
  discovery: this.discovery,
232
+ publish: this.publish,
233
+ consume: this.consume,
119
234
  signal,
120
235
  });
121
236
  // Hand the connection to the effect, which closes it now if this run is already over.
@@ -126,12 +241,13 @@ export class Reload {
126
241
  effect.set(this.status, "connected", "disconnected");
127
242
  connected = performance.now();
128
243
  // A cancelled effect resolves undefined, so the sentinel tells the session
129
- // closing apart from this run being torn down.
130
- const closed = await Promise.race([effect.cancel, connection.closed.then(() => true)]);
131
- if (!closed)
244
+ // closing (null for clean, an Error otherwise) apart from this run being
245
+ // torn down.
246
+ const closed = await effect.race(connection.closed);
247
+ if (closed === undefined)
132
248
  return;
133
249
  console.warn("connection closed, reconnecting");
134
- this.#retry(effect, connected);
250
+ this.#retry(effect, connected, closed ?? undefined);
135
251
  }
136
252
  catch (err) {
137
253
  // Treat teardown as cancellation, not a connection failure.
@@ -148,6 +264,16 @@ export class Reload {
148
264
  * `cause` the error that killed it, if it died with one.
149
265
  */
150
266
  #retry(effect, connected, cause) {
267
+ // Resolved per sequence rather than at construction, so an edit to `delay` (including
268
+ // one that drops a field back to its default) applies to the next retry. Field by
269
+ // field rather than by spread: a caller building `{ initial: maybeInitial }` from an
270
+ // optional value passes an explicit undefined, which a spread would take as the
271
+ // answer, turning the backoff into NaN or the window into forever.
272
+ const delay = this.delay ?? {};
273
+ const initial = delay.initial ?? DEFAULT_DELAY.initial;
274
+ const multiplier = delay.multiplier ?? DEFAULT_DELAY.multiplier;
275
+ const max = delay.max ?? DEFAULT_DELAY.max;
276
+ const timeout = delay.timeout ?? DEFAULT_DELAY.timeout;
151
277
  // Any session is dead now: report disconnected during the backoff rather than
152
278
  // when the retry reruns the effect.
153
279
  this.established.set(undefined);
@@ -156,44 +282,66 @@ export class Reload {
156
282
  // start a fresh retry window: a one-off drop should reconnect promptly. Anything
157
283
  // shorter is a peer that accepts and immediately severs, which has to keep
158
284
  // escalating or we hammer it forever at the initial delay.
159
- if (connected !== undefined && performance.now() - connected >= this.delay.initial) {
285
+ if (connected !== undefined && performance.now() - connected >= initial) {
160
286
  this.#delay = undefined;
161
287
  this.#deadline = undefined;
162
288
  }
289
+ // An auth rejection stops this URL however long the session lived. UNAUTHORIZED is a
290
+ // specified code rather than one we guessed at, so this is the peer saying these
291
+ // credentials will never work; retrying them just burns the window. Matches
292
+ // moq-tokio's reconnect loop, which stops on the same close. A new URL or a
293
+ // disable/re-enable starts another sequence; the handle itself is not disposed.
294
+ //
295
+ // Only a session close says that. The stream registry gives 2 to DELIVERY_TIMEOUT,
296
+ // so a stream reset during the SETUP exchange would otherwise suppress reconnect
297
+ // for good.
298
+ if (cause instanceof SessionError && cause.code === SessionCode.Unauthorized) {
299
+ console.warn("session rejected as unauthorized, not retrying");
300
+ this.#giveUp(cause);
301
+ return;
302
+ }
163
303
  const now = performance.now();
164
- const timeout = this.delay.timeout ?? DEFAULT_TIMEOUT;
165
- this.#delay ??= this.delay.initial;
304
+ this.#delay ??= initial;
166
305
  this.#deadline ??= timeout > 0 ? now + timeout : Number.POSITIVE_INFINITY;
167
306
  if (now >= this.#deadline) {
168
307
  console.warn("reconnect timed out");
169
308
  // A graceful close has no error, so report the timeout itself.
170
- this.#closedReject(cause === undefined ? new Error("reconnect timed out") : error(cause));
309
+ this.#giveUp(cause === undefined ? new Error("reconnect timed out") : error(cause));
171
310
  return;
172
311
  }
173
312
  // Equal jitter, so a fleet of tabs knocked offline together doesn't reconnect on the same
174
313
  // tick, and never past the deadline the retry window promised.
175
314
  const wait = Math.min(this.#delay * (0.5 + Math.random() / 2), this.#deadline - now);
176
- this.#delay = Math.min(this.#delay * this.delay.multiplier, this.delay.max);
315
+ this.#delay = Math.min(this.#delay * multiplier, max);
177
316
  const tick = this.#tick.peek() + 1;
178
317
  effect.timer(() => this.#tick.update((prev) => Math.max(prev, tick)), wait);
179
318
  }
319
+ #giveUp(cause) {
320
+ this.#error.set(cause);
321
+ this.#givenUpHref = this.#sequenceHref;
322
+ this.#resetSequence();
323
+ }
324
+ #resetSequence() {
325
+ this.#delay = undefined;
326
+ this.#deadline = undefined;
327
+ this.#sequenceHref = undefined;
328
+ }
180
329
  /**
181
- * Subscribe to broadcast announcements under an optional prefix, spanning reconnects.
330
+ * Subscribe to broadcast announcements matching `scope`, spanning reconnects.
182
331
  *
183
332
  * The same {@link Announce.Consumer} stream as {@link Established.announced}, but everything active
184
- * is retracted (an `active: false` update) whenever the connection drops and re-announced on
333
+ * is retracted (a `retracted` update) whenever the connection drops and re-announced on
185
334
  * reconnect, so a consumer draining `next()` never clings to a dead route across a reconnect.
186
335
  *
187
336
  * Stays empty while the relay lacks {@link Established.discovery}.
188
337
  */
189
- announced(prefix = emptyPath()) {
190
- const producer = new Announce.Producer(prefix);
338
+ announced(scope = Path.Pattern.all(), options) {
339
+ // With a consume origin the table already spans reconnects (the forwarder retracts
340
+ // a dead session's entries), so its stream is the same thing with less machinery.
341
+ if (this.consume)
342
+ return this.consume.announced(scope, options);
343
+ const producer = new Announce.Producer();
191
344
  const consumer = producer.consume();
192
- // Closing the consumer closes the shared state, so stop appending after that.
193
- let closed = false;
194
- void consumer.closed.then(() => {
195
- closed = true;
196
- });
197
345
  const pump = new Effect();
198
346
  pump.run((effect) => {
199
347
  const conn = effect.get(this.established);
@@ -203,20 +351,21 @@ export class Reload {
203
351
  // consumer empty rather than opening a subscription that can't be answered.
204
352
  if (!conn.discovery)
205
353
  return;
206
- const upstream = conn.announced(prefix);
354
+ const upstream = conn.announced(scope, options);
207
355
  effect.cleanup(() => upstream.close());
208
- // Track what this connection announced so we can retract it if the connection drops.
209
- const active = new Set();
356
+ // Track what this connection announced so we can retract it if the connection
357
+ // drops; the last event rides along for the retraction.
358
+ const active = new Map();
210
359
  effect.spawn(async () => {
211
360
  try {
212
361
  for (;;) {
213
- const entry = await Promise.race([effect.cancel, upstream.next()]);
362
+ const entry = await effect.race(upstream.next());
214
363
  if (!entry)
215
364
  break;
216
- if (entry.active)
217
- active.add(entry.path);
365
+ if (Announce.isActive(entry.kind))
366
+ active.set(entry.prefix, entry);
218
367
  else
219
- active.delete(entry.path);
368
+ active.delete(entry.prefix);
220
369
  producer.append(entry);
221
370
  }
222
371
  }
@@ -226,9 +375,9 @@ export class Reload {
226
375
  finally {
227
376
  // Retract everything from the connection that just went away, so a per-broadcast
228
377
  // watcher tears down instead of clinging to the dead route.
229
- if (!closed) {
230
- for (const path of active) {
231
- producer.append({ path, active: false });
378
+ if (consumer.closed.peek() === undefined) {
379
+ for (const entry of active.values()) {
380
+ producer.append({ ...entry, kind: "retracted" });
232
381
  }
233
382
  }
234
383
  }
@@ -238,20 +387,6 @@ export class Reload {
238
387
  void consumer.closed.then(() => pump.close());
239
388
  return consumer;
240
389
  }
241
- /**
242
- * A reactive handle to one broadcast, spanning reconnects.
243
- *
244
- * The same {@link Announce.Broadcast} as {@link Established.announcedBroadcast}, but it
245
- * follows the reconnect loop: the broadcast drops to `undefined` when the connection dies
246
- * and resolves again once the new connection announces the path. Use it instead of
247
- * consuming off {@link Reload.established} whenever the broadcast may come online after you
248
- * do, which is exactly the case a blind `consume` loses.
249
- *
250
- * Close the handle when done; {@link Reload.close} only drops it to `undefined`.
251
- */
252
- announcedBroadcast(path) {
253
- return new Announce.Broadcast({ connection: this.established, path });
254
- }
255
390
  /**
256
391
  * Snapshot the live connection's transport counters, or undefined while disconnected.
257
392
  * See {@link Established.stats}.
@@ -259,10 +394,11 @@ export class Reload {
259
394
  async stats() {
260
395
  return this.established.peek()?.stats();
261
396
  }
262
- /** Stop reconnecting, close the current connection, and resolve {@link Reload.closed}. */
263
- close() {
397
+ /** Stop reconnecting, close the current connection, and settle {@link Reload.closed}. Idempotent. */
398
+ close(abort) {
264
399
  this.#signals.close();
265
- this.#closedResolve();
400
+ if (this.#closed.peek() === undefined)
401
+ this.#closed.set(abort ?? null);
266
402
  }
267
403
  }
268
404
  //# sourceMappingURL=reload.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reload.js","sourceRoot":"","sources":["../../src/connection/reload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAe,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEpC,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAqB,OAAO,EAAiD,MAAM,cAAc,CAAC;AAuCzG;;;;;GAKG;AACH,MAAM,eAAe,GAAG,KAAK,CAAC;AAK9B,uFAAuF;AACvF,MAAM,OAAO,MAAM;IAClB,iEAAiE;IACjE,GAAG,CAA0B;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AAQ,CAAC,SAAS,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;IACvE,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,KAAK;QACV,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC;IACzC,CAAC;IAED,0FAA0F;IAC1F,KAAK;QACJ,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QACtB,IAAI,CAAC,cAAc,EAAE,CAAC;IACvB,CAAC;CACD","sourcesContent":["import { Effect, type Getter, Signal } from \"@moq/signals\";\nimport * as Announce from \"../announced.ts\";\nimport { error } from \"../error.ts\";\nimport type * as Path from \"../path.ts\";\nimport { empty as emptyPath } from \"../path.ts\";\nimport { type ConnectProps, connect, type WebSocketOptions, type WebTransportProps } from \"./connect.ts\";\nimport type { Established } from \"./established.ts\";\nimport type { Probe, Stats } from \"./stats.ts\";\n\n/**\n * Exponential backoff settings for {@link Reload}'s reconnect loop.\n *\n * The delays carry jitter, so a fleet of tabs knocked offline together doesn't reconnect in\n * lockstep. Every failure is retried; {@link ReloadDelay.timeout} is what stops the loop.\n */\nexport type ReloadDelay = {\n\t/** The delay in milliseconds before reconnecting (default: 1000). */\n\tinitial: DOMHighResTimeStamp;\n\n\t/** The multiplier for the delay (default: 2). */\n\tmultiplier: number;\n\n\t/** The maximum delay in milliseconds (default: 5000). */\n\tmax: DOMHighResTimeStamp;\n\n\t/**\n\t * Maximum total time in milliseconds to spend retrying before giving up (default:\n\t * 10000). Resets after each successful connection. Set to 0 for unlimited retries.\n\t */\n\ttimeout?: DOMHighResTimeStamp;\n};\n\n/** Connection and retry options for {@link Reload}. */\nexport type ReloadProps = Omit<ConnectProps, \"signal\"> & {\n\t/** Whether to reload the connection when it disconnects (default: true). */\n\tenabled?: boolean | Signal<boolean>;\n\n\t/** The URL of the relay server. */\n\turl?: URL | Signal<URL | undefined>;\n\n\t/** Backoff settings for the reconnect loop. */\n\tdelay?: ReloadDelay;\n};\n\n/**\n * How long to keep retrying before giving up, when {@link ReloadDelay.timeout} is unset.\n *\n * Short on purpose: a failure that clears within it was transient, and one that doesn't should\n * surface as an error rather than leave the page silently reconnecting for minutes.\n */\nconst DEFAULT_TIMEOUT = 10000;\n\n/** Current state of a {@link Reload} connection. */\nexport type ReloadStatus = \"connecting\" | \"connected\" | \"disconnected\";\n\n/** Maintains a MoQ connection, reconnecting with exponential backoff when it drops. */\nexport class Reload {\n\t/** Relay URL to connect to; updating it triggers a reconnect. */\n\turl: Signal<URL | undefined>;\n\n\t/** Whether reconnecting is active. */\n\tenabled: Signal<boolean>;\n\n\t/** Current connection status. */\n\tstatus = new Signal<ReloadStatus>(\"disconnected\");\n\n\t/** The currently established session, or undefined while disconnected. */\n\testablished = new Signal<Established | undefined>(undefined);\n\n\t/**\n\t * The current connection's PROBE estimates, spanning reconnects.\n\t *\n\t * Undefined while disconnected: the estimates belong to a single connection.\n\t * See {@link Established.probe}.\n\t */\n\treadonly probe: Getter<Probe | undefined>;\n\n\t/** WebTransport options applied to each connection attempt (not reactive). */\n\twebtransport?: WebTransportProps;\n\n\t/** WebSocket fallback options applied to each connection attempt (not reactive). */\n\twebsocket: WebSocketOptions | undefined;\n\n\t/**\n\t * Whether the relay supports broadcast discovery, applied to each connection attempt (not\n\t * reactive). Undefined defers to the default for the URL. See {@link Established.discovery}.\n\t */\n\tdiscovery?: boolean;\n\n\t/** Backoff settings for the reconnect loop. */\n\tdelay: ReloadDelay;\n\n\t/** The reactive effect scope driving the connect loop; closed by {@link Reload.close}. */\n\t#signals = new Effect();\n\n\t/**\n\t * Resolves when the reconnect loop stops via {@link Reload.close}.\n\t *\n\t * Rejects when the loop gives up instead, carrying the failure that was in flight when the\n\t * retry window expired.\n\t */\n\tclosed: Promise<void>;\n\t#closedResolve!: () => void;\n\t#closedReject!: (err: Error) => void;\n\n\t// The current wait between attempts, doubling per failure, and when the retry window expires.\n\t// Both are undefined between sequences, so a later edit to `delay` applies to the next one.\n\t#delay: DOMHighResTimeStamp | undefined;\n\t#deadline: DOMHighResTimeStamp | undefined;\n\n\t// Increased by 1 each time to trigger a reload.\n\t#tick = new Signal(0);\n\n\t// True after the browser freezes or hides the page until it visibly resumes.\n\t#suspended = new Signal(false);\n\n\t// Use the serialized URL as the reactive connection key. URL objects use identity\n\t// equality, but replacing one with an equivalent instance should not reconnect.\n\t#url: Getter<string | undefined>;\n\tconstructor(props?: ReloadProps) {\n\t\tthis.url = Signal.from(props?.url);\n\t\tthis.enabled = Signal.from(props?.enabled ?? false);\n\t\tthis.delay = props?.delay ?? { initial: 1000, multiplier: 2, max: 5000 };\n\t\tthis.webtransport = props?.webtransport;\n\t\tthis.websocket = props?.websocket;\n\t\tthis.discovery = props?.discovery;\n\n\t\tthis.closed = new Promise((resolve, reject) => {\n\t\t\tthis.#closedResolve = resolve;\n\t\t\tthis.#closedReject = reject;\n\t\t});\n\n\t\t// A caller is free to never await `closed`, and giving up rejects it unprompted. Marking the\n\t\t// rejection handled here keeps that from surfacing as an `unhandledrejection`; a consumer\n\t\t// awaiting the same promise still receives it.\n\t\tthis.closed.catch(() => {});\n\n\t\tif (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n\t\t\tthis.#signals.event(window, \"pagehide\", () => this.#suspended.set(true));\n\t\t\tthis.#signals.event(window, \"pageshow\", () => this.#suspended.set(false));\n\t\t\tthis.#signals.event(window, \"unload\", () => this.#suspended.set(true));\n\t\t\tthis.#signals.event(document, \"visibilitychange\", () => {\n\t\t\t\tif (!document.hidden) this.#suspended.set(false);\n\t\t\t});\n\t\t}\n\n\t\tthis.probe = this.#signals.computed((effect) => {\n\t\t\tconst connection = effect.get(this.established);\n\t\t\treturn connection && effect.get(connection.probe);\n\t\t});\n\n\t\tthis.#url = this.#signals.computed((effect) => effect.get(this.url)?.href);\n\t\t// Create a reactive root so cleanup is easier.\n\t\tthis.#signals.run(this.#connect.bind(this));\n\t}\n\n\t#connect(effect: Effect): void {\n\t\t// Will retry when the tick changes.\n\t\teffect.get(this.#tick);\n\n\t\tconst suspended = effect.get(this.#suspended);\n\t\tconst enabled = effect.get(this.enabled);\n\t\tif (!enabled || suspended) return;\n\n\t\tconst href = effect.get(this.#url);\n\t\tif (!href) return;\n\t\tconst url = new URL(href);\n\n\t\teffect.set(this.status, \"connecting\", \"disconnected\");\n\n\t\t// This run's teardown, handed to connect() so a rerun cancels the attempt in flight.\n\t\tconst signal = effect.abort;\n\n\t\teffect.spawn(async () => {\n\t\t\t// Set once the session is live, so #retry can tell a healthy session that\n\t\t\t// later dropped from a connect failure or a peer that flaps immediately.\n\t\t\tlet connected: DOMHighResTimeStamp | undefined;\n\n\t\t\ttry {\n\t\t\t\tconst connection = await connect(url, {\n\t\t\t\t\twebsocket: this.websocket,\n\t\t\t\t\twebtransport: this.webtransport,\n\t\t\t\t\tdiscovery: this.discovery,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\n\t\t\t\t// Hand the connection to the effect, which closes it now if this run is already over.\n\t\t\t\teffect.cleanup(() => connection.close());\n\t\t\t\tif (signal.aborted) return;\n\n\t\t\t\teffect.set(this.established, connection);\n\t\t\t\teffect.set(this.status, \"connected\", \"disconnected\");\n\n\t\t\t\tconnected = performance.now();\n\n\t\t\t\t// A cancelled effect resolves undefined, so the sentinel tells the session\n\t\t\t\t// closing apart from this run being torn down.\n\t\t\t\tconst closed = await Promise.race([effect.cancel, connection.closed.then(() => true)]);\n\t\t\t\tif (!closed) return;\n\n\t\t\t\tconsole.warn(\"connection closed, reconnecting\");\n\t\t\t\tthis.#retry(effect, connected);\n\t\t\t} catch (err) {\n\t\t\t\t// Treat teardown as cancellation, not a connection failure.\n\t\t\t\tif (signal.aborted) return;\n\n\t\t\t\tconsole.warn(\"connection error:\", err);\n\t\t\t\tthis.#retry(effect, connected, err);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Schedule the next connect attempt after the current backoff, or stop once the retry window\n\t * has expired. `connected` is when the dead session was established, if it ever was, and\n\t * `cause` the error that killed it, if it died with one.\n\t */\n\t#retry(effect: Effect, connected: DOMHighResTimeStamp | undefined, cause?: unknown): void {\n\t\t// Any session is dead now: report disconnected during the backoff rather than\n\t\t// when the retry reruns the effect.\n\t\tthis.established.set(undefined);\n\t\tthis.status.set(\"disconnected\");\n\n\t\t// A session that outlived the initial delay was healthy, so clear the backoff and\n\t\t// start a fresh retry window: a one-off drop should reconnect promptly. Anything\n\t\t// shorter is a peer that accepts and immediately severs, which has to keep\n\t\t// escalating or we hammer it forever at the initial delay.\n\t\tif (connected !== undefined && performance.now() - connected >= this.delay.initial) {\n\t\t\tthis.#delay = undefined;\n\t\t\tthis.#deadline = undefined;\n\t\t}\n\n\t\tconst now = performance.now();\n\t\tconst timeout = this.delay.timeout ?? DEFAULT_TIMEOUT;\n\t\tthis.#delay ??= this.delay.initial;\n\t\tthis.#deadline ??= timeout > 0 ? now + timeout : Number.POSITIVE_INFINITY;\n\n\t\tif (now >= this.#deadline) {\n\t\t\tconsole.warn(\"reconnect timed out\");\n\t\t\t// A graceful close has no error, so report the timeout itself.\n\t\t\tthis.#closedReject(cause === undefined ? new Error(\"reconnect timed out\") : error(cause));\n\t\t\treturn;\n\t\t}\n\n\t\t// Equal jitter, so a fleet of tabs knocked offline together doesn't reconnect on the same\n\t\t// tick, and never past the deadline the retry window promised.\n\t\tconst wait = Math.min(this.#delay * (0.5 + Math.random() / 2), this.#deadline - now);\n\t\tthis.#delay = Math.min(this.#delay * this.delay.multiplier, this.delay.max);\n\n\t\tconst tick = this.#tick.peek() + 1;\n\t\teffect.timer(() => this.#tick.update((prev) => Math.max(prev, tick)), wait);\n\t}\n\n\t/**\n\t * Subscribe to broadcast announcements under an optional prefix, spanning reconnects.\n\t *\n\t * The same {@link Announce.Consumer} stream as {@link Established.announced}, but everything active\n\t * is retracted (an `active: false` update) whenever the connection drops and re-announced on\n\t * reconnect, so a consumer draining `next()` never clings to a dead route across a reconnect.\n\t *\n\t * Stays empty while the relay lacks {@link Established.discovery}.\n\t */\n\tannounced(prefix: Path.Valid = emptyPath()): Announce.Consumer {\n\t\tconst producer = new Announce.Producer(prefix);\n\t\tconst consumer = producer.consume();\n\n\t\t// Closing the consumer closes the shared state, so stop appending after that.\n\t\tlet closed = false;\n\t\tvoid consumer.closed.then(() => {\n\t\t\tclosed = true;\n\t\t});\n\n\t\tconst pump = new Effect();\n\t\tpump.run((effect) => {\n\t\t\tconst conn = effect.get(this.established);\n\t\t\tif (!conn) return;\n\n\t\t\t// Without discovery the upstream announce stream never yields, so leave the\n\t\t\t// consumer empty rather than opening a subscription that can't be answered.\n\t\t\tif (!conn.discovery) return;\n\n\t\t\tconst upstream = conn.announced(prefix);\n\t\t\teffect.cleanup(() => upstream.close());\n\n\t\t\t// Track what this connection announced so we can retract it if the connection drops.\n\t\t\tconst active = new Set<Path.Valid>();\n\n\t\t\teffect.spawn(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\tconst entry = await Promise.race([effect.cancel, upstream.next()]);\n\t\t\t\t\t\tif (!entry) break;\n\t\t\t\t\t\tif (entry.active) active.add(entry.path);\n\t\t\t\t\t\telse active.delete(entry.path);\n\t\t\t\t\t\tproducer.append(entry);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// A dropped connection resets the announce stream; the retractions below cover it.\n\t\t\t\t} finally {\n\t\t\t\t\t// Retract everything from the connection that just went away, so a per-broadcast\n\t\t\t\t\t// watcher tears down instead of clinging to the dead route.\n\t\t\t\t\tif (!closed) {\n\t\t\t\t\t\tfor (const path of active) {\n\t\t\t\t\t\t\tproducer.append({ path, active: false });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\tthis.#signals.cleanup(() => pump.close());\n\t\tvoid consumer.closed.then(() => pump.close());\n\n\t\treturn consumer;\n\t}\n\n\t/**\n\t * A reactive handle to one broadcast, spanning reconnects.\n\t *\n\t * The same {@link Announce.Broadcast} as {@link Established.announcedBroadcast}, but it\n\t * follows the reconnect loop: the broadcast drops to `undefined` when the connection dies\n\t * and resolves again once the new connection announces the path. Use it instead of\n\t * consuming off {@link Reload.established} whenever the broadcast may come online after you\n\t * do, which is exactly the case a blind `consume` loses.\n\t *\n\t * Close the handle when done; {@link Reload.close} only drops it to `undefined`.\n\t */\n\tannouncedBroadcast(path: Path.Valid): Announce.Broadcast {\n\t\treturn new Announce.Broadcast({ connection: this.established, path });\n\t}\n\n\t/**\n\t * Snapshot the live connection's transport counters, or undefined while disconnected.\n\t * See {@link Established.stats}.\n\t */\n\tasync stats(): Promise<Stats | undefined> {\n\t\treturn this.established.peek()?.stats();\n\t}\n\n\t/** Stop reconnecting, close the current connection, and resolve {@link Reload.closed}. */\n\tclose() {\n\t\tthis.#signals.close();\n\t\tthis.#closedResolve();\n\t}\n}\n"]}
1
+ {"version":3,"file":"reload.js","sourceRoot":"","sources":["../../src/connection/reload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAgC,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAClF,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE/D,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAqB,OAAO,EAA+C,MAAM,cAAc,CAAC;AAuDvG;;;;;;;;GAQG;AACH,MAAM,aAAa,GAA0B;IAC5C,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;IACzB,UAAU,EAAE,CAAC;IACb,GAAG,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;IACrB,OA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,IAAI,IAAI,CAAC,CAAC;IACxE,CAAC;CACD","sourcesContent":["import { Effect, type GetPromise, type Getter, Once, Signal } from \"@moq/signals\";\nimport * as Announce from \"../announced.ts\";\nimport { Allocator } from \"../bandwidth.ts\";\nimport { error, SessionCode, SessionError } from \"../error.ts\";\nimport type { Consumer as OriginConsumer, Producer as OriginProducer } from \"../origin.ts\";\nimport * as Path from \"../path.ts\";\nimport * as Time from \"../time.ts\";\nimport { wireOf } from \"../wire.ts\";\nimport { type ConnectProps, connect, type WebSocketProps, type WebTransportProps } from \"./connect.ts\";\nimport type { Established } from \"./established.ts\";\nimport type { Probe, Stats } from \"./stats.ts\";\n\n/**\n * Exponential backoff settings for the reconnect loop.\n *\n * The delays carry jitter, so a fleet of tabs knocked offline together doesn't reconnect in\n * lockstep. Every failure is retried; {@link ReloadDelay.timeout} is what stops the current\n * URL. A new URL or a disable/re-enable starts another sequence.\n */\nexport type ReloadDelay = {\n\t/** The delay before reconnecting (default: 1000ms). */\n\tinitial?: Time.Milli;\n\n\t/** The multiplier for the delay (default: 2). */\n\tmultiplier?: number;\n\n\t/** The maximum delay (default: 5000ms). */\n\tmax?: Time.Milli;\n\n\t/**\n\t * Maximum total time to spend retrying the current URL before giving up\n\t * (default: 10000ms). Resets after each successful connection, a URL change, or a\n\t * disable/re-enable. Set to 0 for unlimited retries.\n\t */\n\ttimeout?: Time.Milli;\n};\n\n/**\n * Connection and retry options for {@link Reload}.\n *\n * {@link ConnectProps.transport} is excluded: a supplied session is good for exactly one\n * connection, so the reconnect loop has nothing to reuse once that session drops. Call\n * {@link connect} directly when you have a session to hand over.\n *\n * @internal\n */\nexport type ReloadProps = Omit<ConnectProps, \"url\" | \"signal\" | \"transport\"> & {\n\t/** A reload owns the abort signal for each connection attempt. */\n\tsignal?: never;\n\n\t/** A one-shot transport cannot be reused by the reconnect loop. */\n\ttransport?: never;\n\n\t/** Whether to reload the connection when it disconnects (default: true). */\n\tenabled?: boolean | Signal<boolean>;\n\n\t/** The URL of the relay server. */\n\turl?: URL | Signal<URL | undefined>;\n\n\t/** Backoff settings for the reconnect loop; every field falls back to its default. */\n\tdelay?: ReloadDelay;\n};\n\n/**\n * The backoff applied to whichever {@link ReloadDelay} fields a caller leaves out.\n *\n * The timeout is short on purpose: a failure that clears within it was transient, and one that\n * doesn't should surface on {@link Reload.error} rather than leave the page silently\n * reconnecting for minutes. A loop nobody watches wants `timeout: 0` instead, since there is\n * no one to react. Giving up does not dispose the loop: a new URL or a disable/re-enable\n * starts another sequence.\n */\nconst DEFAULT_DELAY: Required<ReloadDelay> = {\n\tinitial: Time.Milli(1000),\n\tmultiplier: 2,\n\tmax: Time.Milli(5000),\n\ttimeout: Time.Milli(10000),\n};\n\n/** How often the send-rate estimate is sampled from the live transport. */\nconst BANDWIDTH_POLL = 100;\n\n/** Current state of a reconnecting connection. */\nexport type ReloadStatus = \"connecting\" | \"connected\" | \"disconnected\";\n\n/**\n * The reconnect loop behind a Connection handle: connects, waits for the session to end, then\n * redials with exponential backoff.\n *\n * @internal\n */\nexport class Reload {\n\t/** Relay URL to connect to; updating it triggers a reconnect. */\n\turl: Signal<URL | undefined>;\n\n\t/** Whether reconnecting is active. */\n\tenabled: Signal<boolean>;\n\n\t/** Current connection status. */\n\tstatus = new Signal<ReloadStatus>(\"disconnected\");\n\n\t/**\n\t * The failure that stopped retrying the current URL, or undefined while the loop is live.\n\t *\n\t * Set on an auth rejection or when the retry window expires. Cleared when a new URL or a\n\t * disable/re-enable starts another sequence, not on a page hide/show. Transient drops\n\t * that are still being retried leave this empty.\n\t */\n\treadonly error: Getter<Error | undefined>;\n\n\t/** The currently established session, or undefined while disconnected. */\n\testablished = new Signal<Established | undefined>(undefined);\n\n\t/**\n\t * The current connection's PROBE estimates, spanning reconnects.\n\t *\n\t * Undefined while disconnected: the estimates belong to a single connection.\n\t * See {@link Established.probe}.\n\t */\n\treadonly probe: Getter<Probe | undefined>;\n\n\t/**\n\t * Divides this connection's send-rate estimate among the tracks sharing it.\n\t *\n\t * The same instance across reconnects, so reservations survive a drop. The\n\t * estimate is `undefined` while disconnected, which tells a sender to hold\n\t * its rate rather than encode at zero.\n\t */\n\treadonly bandwidth: Allocator;\n\n\t/** WebTransport options applied to each connection attempt (not reactive). */\n\twebtransport?: WebTransportProps;\n\n\t/** WebSocket fallback options applied to each connection attempt (not reactive). */\n\twebsocket: WebSocketProps | undefined;\n\n\t/**\n\t * Whether the relay supports broadcast discovery, applied to each connection attempt (not\n\t * reactive). Undefined defers to the default for the URL. See {@link Established.discovery}.\n\t */\n\tdiscovery?: boolean;\n\n\t/**\n\t * The origin whose broadcasts are served, spanning reconnects (not reactive).\n\t *\n\t * Each session announces the origin's table when it attaches, so a broadcast published\n\t * while offline surfaces on the next connection and a reconnect re-announces everything\n\t * still published. See the `publish` connect option.\n\t */\n\tpublish?: OriginConsumer;\n\n\t/**\n\t * The origin fed with the peer's announced broadcasts, spanning reconnects (not\n\t * reactive).\n\t *\n\t * The entries a session fed retract when it dies, and the next session re-populates the\n\t * table, so a consumer watching the origin sees offline/online transitions across a\n\t * reconnect. See the `consume` connect option.\n\t */\n\tconsume?: OriginProducer;\n\n\t/** Backoff settings for the reconnect loop; an unset field uses its default. */\n\tdelay: ReloadDelay;\n\n\t/** The reactive effect scope driving the connect loop; closed by {@link Reload.close}. */\n\t#signals = new Effect();\n\n\t// Sampled from the live session; undefined while disconnected or the transport has none.\n\t#estimate = new Signal<number | undefined>(undefined);\n\n\t/**\n\t * Settles once this loop is disposed via {@link Reload.close}: `null` on a clean close,\n\t * or the abort {@link Error}. Peek it synchronously (`undefined` while open), observe it\n\t * reactively, or `await` it. Attempt failures live on {@link Reload.error} instead.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#closed;\n\t}\n\n\t#closed = new Once<Error | null>();\n\t#error = new Signal<Error | undefined>(undefined);\n\n\t// The current wait between attempts, doubling per failure, and when the retry window expires.\n\t// Both are undefined between sequences, so a later edit to `delay` applies to the next one.\n\t#delay: DOMHighResTimeStamp | undefined;\n\t#deadline: DOMHighResTimeStamp | undefined;\n\n\t// The URL the current retry sequence is for. Cleared when disabled, URL-less, or given\n\t// up, so the next attempt starts a fresh backoff window.\n\t#sequenceHref: string | undefined;\n\n\t// The href that exhausted its retry sequence. Survives a page hide/show so resume does\n\t// not redial credentials the peer already refused. Cleared when the URL changes or the\n\t// loop is disabled.\n\t#givenUpHref: string | undefined;\n\n\t// Increased by 1 each time to trigger a reload.\n\t#tick = new Signal(0);\n\n\t// True after the browser freezes or hides the page until it visibly resumes.\n\t#suspended = new Signal(false);\n\n\t// Use the serialized URL as the reactive connection key. URL objects use identity\n\t// equality, but replacing one with an equivalent instance should not reconnect.\n\t#url: Getter<string | undefined>;\n\tconstructor(props?: ReloadProps) {\n\t\tthis.url = Signal.from(props?.url);\n\t\tthis.enabled = Signal.from(props?.enabled ?? true);\n\t\tthis.delay = props?.delay ?? {};\n\t\tthis.webtransport = props?.webtransport;\n\t\tthis.websocket = props?.websocket;\n\t\tthis.discovery = props?.discovery;\n\t\tthis.publish = props?.publish;\n\t\tthis.consume = props?.consume;\n\n\t\t// Requests on the consume origin stay pending across a reconnect, and before the\n\t\t// first session establishes, rather than reading as unroutable the moment no session\n\t\t// is attached. Released only when this loop is disposed: giving up the current URL\n\t\t// is recoverable (a new URL or a disable/re-enable starts another sequence), so a\n\t\t// request must keep waiting rather than go unroutable in the gap.\n\t\tif (this.consume) {\n\t\t\tthis.#signals.cleanup(wireOf(this.consume).expect());\n\t\t}\n\n\t\tthis.error = this.#error;\n\n\t\tconst win = globalThis.window;\n\t\tconst doc = globalThis.document;\n\t\tif (typeof win !== \"undefined\" && typeof doc !== \"undefined\") {\n\t\t\tthis.#signals.event(win, \"pagehide\", () => this.#suspended.set(true));\n\t\t\tthis.#signals.event(win, \"pageshow\", () => this.#suspended.set(false));\n\t\t\tthis.#signals.event(win, \"unload\", () => this.#suspended.set(true));\n\t\t\tthis.#signals.event(doc, \"visibilitychange\", () => {\n\t\t\t\tif (!doc.hidden) this.#suspended.set(false);\n\t\t\t});\n\t\t}\n\n\t\tthis.probe = this.#signals.computed((effect) => {\n\t\t\tconst connection = effect.get(this.established);\n\t\t\treturn connection && effect.get(connection.probe);\n\t\t});\n\n\t\tthis.bandwidth = new Allocator(this.#estimate);\n\t\tthis.#signals.cleanup(() => this.bandwidth.close());\n\n\t\t// The transport has no event for the send-rate estimate, so sample on our\n\t\t// own schedule and skip a tick while the previous snapshot is outstanding.\n\t\tthis.#signals.run((effect) => {\n\t\t\teffect.set(this.#estimate, undefined);\n\t\t\tconst connection = effect.get(this.established);\n\t\t\tif (!connection) return;\n\n\t\t\tlet pending = false;\n\t\t\tconst sample = async () => {\n\t\t\t\tif (pending) return;\n\t\t\t\tpending = true;\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = await effect.race(connection.stats());\n\t\t\t\t\tif (stats) this.#estimate.set(stats.estimatedSendRate);\n\t\t\t\t} finally {\n\t\t\t\t\tpending = false;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tvoid sample();\n\t\t\teffect.interval(() => void sample(), BANDWIDTH_POLL);\n\t\t});\n\n\t\tthis.#url = this.#signals.computed((effect) => effect.get(this.url)?.href);\n\t\t// Create a reactive root so cleanup is easier.\n\t\tthis.#signals.run(this.#connect.bind(this));\n\t}\n\n\t#connect(effect: Effect): void {\n\t\t// Will retry when the tick changes.\n\t\teffect.get(this.#tick);\n\n\t\tconst enabled = effect.get(this.enabled);\n\t\tif (!enabled) {\n\t\t\tthis.#givenUpHref = undefined;\n\t\t\tthis.#resetSequence();\n\t\t\treturn;\n\t\t}\n\n\t\t// Hide/freeze pauses an in-flight sequence without recovering from give-up.\n\t\tconst suspended = effect.get(this.#suspended);\n\t\tif (suspended) {\n\t\t\tthis.#resetSequence();\n\t\t\treturn;\n\t\t}\n\n\t\tconst href = effect.get(this.#url);\n\t\tif (!href) {\n\t\t\tthis.#givenUpHref = undefined;\n\t\t\tthis.#resetSequence();\n\t\t\treturn;\n\t\t}\n\t\tconst url = new URL(href);\n\n\t\tif (this.#givenUpHref === href) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.#sequenceHref !== href) {\n\t\t\tthis.#resetSequence();\n\t\t\tthis.#sequenceHref = href;\n\t\t\tthis.#error.set(undefined);\n\t\t\tthis.#givenUpHref = undefined;\n\t\t}\n\n\t\teffect.set(this.status, \"connecting\", \"disconnected\");\n\n\t\t// This run's teardown, handed to connect() so a rerun cancels the attempt in flight.\n\t\tconst signal = effect.abort;\n\n\t\teffect.spawn(async () => {\n\t\t\t// Set once the session is live, so #retry can tell a healthy session that\n\t\t\t// later dropped from a connect failure or a peer that flaps immediately.\n\t\t\tlet connected: DOMHighResTimeStamp | undefined;\n\n\t\t\ttry {\n\t\t\t\tconst connection = await connect({\n\t\t\t\t\turl,\n\t\t\t\t\twebsocket: this.websocket,\n\t\t\t\t\twebtransport: this.webtransport,\n\t\t\t\t\tdiscovery: this.discovery,\n\t\t\t\t\tpublish: this.publish,\n\t\t\t\t\tconsume: this.consume,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\n\t\t\t\t// Hand the connection to the effect, which closes it now if this run is already over.\n\t\t\t\teffect.cleanup(() => connection.close());\n\t\t\t\tif (signal.aborted) return;\n\n\t\t\t\teffect.set(this.established, connection);\n\t\t\t\teffect.set(this.status, \"connected\", \"disconnected\");\n\n\t\t\t\tconnected = performance.now();\n\n\t\t\t\t// A cancelled effect resolves undefined, so the sentinel tells the session\n\t\t\t\t// closing (null for clean, an Error otherwise) apart from this run being\n\t\t\t\t// torn down.\n\t\t\t\tconst closed = await effect.race(connection.closed);\n\t\t\t\tif (closed === undefined) return;\n\n\t\t\t\tconsole.warn(\"connection closed, reconnecting\");\n\t\t\t\tthis.#retry(effect, connected, closed ?? undefined);\n\t\t\t} catch (err) {\n\t\t\t\t// Treat teardown as cancellation, not a connection failure.\n\t\t\t\tif (signal.aborted) return;\n\n\t\t\t\tconsole.warn(\"connection error:\", err);\n\t\t\t\tthis.#retry(effect, connected, err);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Schedule the next connect attempt after the current backoff, or stop once the retry window\n\t * has expired. `connected` is when the dead session was established, if it ever was, and\n\t * `cause` the error that killed it, if it died with one.\n\t */\n\t#retry(effect: Effect, connected: DOMHighResTimeStamp | undefined, cause?: unknown): void {\n\t\t// Resolved per sequence rather than at construction, so an edit to `delay` (including\n\t\t// one that drops a field back to its default) applies to the next retry. Field by\n\t\t// field rather than by spread: a caller building `{ initial: maybeInitial }` from an\n\t\t// optional value passes an explicit undefined, which a spread would take as the\n\t\t// answer, turning the backoff into NaN or the window into forever.\n\t\tconst delay = this.delay ?? {};\n\t\tconst initial = delay.initial ?? DEFAULT_DELAY.initial;\n\t\tconst multiplier = delay.multiplier ?? DEFAULT_DELAY.multiplier;\n\t\tconst max = delay.max ?? DEFAULT_DELAY.max;\n\t\tconst timeout = delay.timeout ?? DEFAULT_DELAY.timeout;\n\n\t\t// Any session is dead now: report disconnected during the backoff rather than\n\t\t// when the retry reruns the effect.\n\t\tthis.established.set(undefined);\n\t\tthis.status.set(\"disconnected\");\n\n\t\t// A session that outlived the initial delay was healthy, so clear the backoff and\n\t\t// start a fresh retry window: a one-off drop should reconnect promptly. Anything\n\t\t// shorter is a peer that accepts and immediately severs, which has to keep\n\t\t// escalating or we hammer it forever at the initial delay.\n\t\tif (connected !== undefined && performance.now() - connected >= initial) {\n\t\t\tthis.#delay = undefined;\n\t\t\tthis.#deadline = undefined;\n\t\t}\n\n\t\t// An auth rejection stops this URL however long the session lived. UNAUTHORIZED is a\n\t\t// specified code rather than one we guessed at, so this is the peer saying these\n\t\t// credentials will never work; retrying them just burns the window. Matches\n\t\t// moq-tokio's reconnect loop, which stops on the same close. A new URL or a\n\t\t// disable/re-enable starts another sequence; the handle itself is not disposed.\n\t\t//\n\t\t// Only a session close says that. The stream registry gives 2 to DELIVERY_TIMEOUT,\n\t\t// so a stream reset during the SETUP exchange would otherwise suppress reconnect\n\t\t// for good.\n\t\tif (cause instanceof SessionError && cause.code === SessionCode.Unauthorized) {\n\t\t\tconsole.warn(\"session rejected as unauthorized, not retrying\");\n\t\t\tthis.#giveUp(cause);\n\t\t\treturn;\n\t\t}\n\n\t\tconst now = performance.now();\n\t\tthis.#delay ??= initial;\n\t\tthis.#deadline ??= timeout > 0 ? now + timeout : Number.POSITIVE_INFINITY;\n\n\t\tif (now >= this.#deadline) {\n\t\t\tconsole.warn(\"reconnect timed out\");\n\t\t\t// A graceful close has no error, so report the timeout itself.\n\t\t\tthis.#giveUp(cause === undefined ? new Error(\"reconnect timed out\") : error(cause));\n\t\t\treturn;\n\t\t}\n\n\t\t// Equal jitter, so a fleet of tabs knocked offline together doesn't reconnect on the same\n\t\t// tick, and never past the deadline the retry window promised.\n\t\tconst wait = Math.min(this.#delay * (0.5 + Math.random() / 2), this.#deadline - now);\n\t\tthis.#delay = Math.min(this.#delay * multiplier, max);\n\n\t\tconst tick = this.#tick.peek() + 1;\n\t\teffect.timer(() => this.#tick.update((prev) => Math.max(prev, tick)), wait);\n\t}\n\n\t#giveUp(cause: Error): void {\n\t\tthis.#error.set(cause);\n\t\tthis.#givenUpHref = this.#sequenceHref;\n\t\tthis.#resetSequence();\n\t}\n\n\t#resetSequence(): void {\n\t\tthis.#delay = undefined;\n\t\tthis.#deadline = undefined;\n\t\tthis.#sequenceHref = undefined;\n\t}\n\n\t/**\n\t * Subscribe to broadcast announcements matching `scope`, spanning reconnects.\n\t *\n\t * The same {@link Announce.Consumer} stream as {@link Established.announced}, but everything active\n\t * is retracted (a `retracted` update) whenever the connection drops and re-announced on\n\t * reconnect, so a consumer draining `next()` never clings to a dead route across a reconnect.\n\t *\n\t * Stays empty while the relay lacks {@link Established.discovery}.\n\t */\n\tannounced(scope: Path.Pattern = Path.Pattern.all(), options?: Announce.Options): Announce.Consumer {\n\t\t// With a consume origin the table already spans reconnects (the forwarder retracts\n\t\t// a dead session's entries), so its stream is the same thing with less machinery.\n\t\tif (this.consume) return this.consume.announced(scope, options);\n\n\t\tconst producer = new Announce.Producer();\n\t\tconst consumer = producer.consume();\n\n\t\tconst pump = new Effect();\n\t\tpump.run((effect) => {\n\t\t\tconst conn = effect.get(this.established);\n\t\t\tif (!conn) return;\n\n\t\t\t// Without discovery the upstream announce stream never yields, so leave the\n\t\t\t// consumer empty rather than opening a subscription that can't be answered.\n\t\t\tif (!conn.discovery) return;\n\n\t\t\tconst upstream = conn.announced(scope, options);\n\t\t\teffect.cleanup(() => upstream.close());\n\n\t\t\t// Track what this connection announced so we can retract it if the connection\n\t\t\t// drops; the last event rides along for the retraction.\n\t\t\tconst active = new Map<Path.Valid, Announce.Update>();\n\n\t\t\teffect.spawn(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\tconst entry = await effect.race(upstream.next());\n\t\t\t\t\t\tif (!entry) break;\n\t\t\t\t\t\tif (Announce.isActive(entry.kind)) active.set(entry.prefix, entry);\n\t\t\t\t\t\telse active.delete(entry.prefix);\n\t\t\t\t\t\tproducer.append(entry);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// A dropped connection resets the announce stream; the retractions below cover it.\n\t\t\t\t} finally {\n\t\t\t\t\t// Retract everything from the connection that just went away, so a per-broadcast\n\t\t\t\t\t// watcher tears down instead of clinging to the dead route.\n\t\t\t\t\tif (consumer.closed.peek() === undefined) {\n\t\t\t\t\t\tfor (const entry of active.values()) {\n\t\t\t\t\t\t\tproducer.append({ ...entry, kind: \"retracted\" });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\tthis.#signals.cleanup(() => pump.close());\n\t\tvoid consumer.closed.then(() => pump.close());\n\n\t\treturn consumer;\n\t}\n\n\t/**\n\t * Snapshot the live connection's transport counters, or undefined while disconnected.\n\t * See {@link Established.stats}.\n\t */\n\tasync stats(): Promise<Stats | undefined> {\n\t\treturn this.established.peek()?.stats();\n\t}\n\n\t/** Stop reconnecting, close the current connection, and settle {@link Reload.closed}. Idempotent. */\n\tclose(abort?: Error) {\n\t\tthis.#signals.close();\n\t\tif (this.#closed.peek() === undefined) this.#closed.set(abort ?? null);\n\t}\n}\n"]}
@@ -14,10 +14,10 @@ import * as Time from "../time";
14
14
  * Every field is optional. The qmux/WebSocket fallback implements no `getStats()` at
15
15
  * all and reports nothing; see {@link Probe} for what the peer measures.
16
16
  *
17
- * The field names match Rust's `moq_net::ConnectionStats` but the counters keep each
17
+ * The field names match Rust's `moq_net::session::Stats` but the counters keep each
18
18
  * stack's own semantics rather than being normalized. Notably W3C excludes
19
- * retransmissions and QUIC overhead from the byte counts where quinn includes them,
20
- * and counts packets where quinn counts datagrams.
19
+ * retransmissions and QUIC overhead from the byte counts where native QUIC includes
20
+ * them, and counts packets where native QUIC counts datagrams.
21
21
  *
22
22
  * @public
23
23
  */
@@ -66,27 +66,4 @@ export interface Probe {
66
66
  /** The peer's estimate of the bitrate it is receiving from us, in bits per second. */
67
67
  estimatedRecvRate?: number;
68
68
  }
69
- /**
70
- * The subset of the W3C `WebTransportConnectionStats` dictionary we consume.
71
- * `getStats()` is not in TypeScript's DOM lib yet, so it is declared here.
72
- *
73
- * @internal
74
- */
75
- export interface TransportStats {
76
- smoothedRtt?: number;
77
- estimatedSendRate?: number | null;
78
- bytesSent?: number;
79
- bytesReceived?: number;
80
- bytesLost?: number;
81
- packetsSent?: number;
82
- packetsReceived?: number;
83
- packetsLost?: number;
84
- }
85
- /**
86
- * Snapshot `quic` via `getStats()`, or an empty snapshot when the transport doesn't
87
- * implement it (the qmux/WebSocket fallback, older browsers) or the call fails.
88
- *
89
- * @internal
90
- */
91
- export declare function transportStats(quic: WebTransport): Promise<Stats>;
92
69
  //# sourceMappingURL=stats.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"stats.d.ts","sourceRoot":"","sources":["../../src/connection/stats.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AAEn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