unifi-protect 5.4.2 → 5.4.3
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/README.md +28 -1
- package/dist/client/client.d.ts +8 -5
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.js +13 -8
- package/dist/client/client.js.map +1 -1
- package/dist/client/connection.d.ts +9 -6
- package/dist/client/connection.d.ts.map +1 -1
- package/dist/client/connection.js +17 -7
- package/dist/client/connection.js.map +1 -1
- package/dist/devices/device.js.map +1 -1
- package/dist/errors.d.ts +3 -2
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +3 -2
- package/dist/errors.js.map +1 -1
- package/dist/event-bus.d.ts +28 -8
- package/dist/event-bus.d.ts.map +1 -1
- package/dist/event-bus.js +70 -15
- package/dist/event-bus.js.map +1 -1
- package/dist/schema-manifest.json +1 -1
- package/dist/testing.d.ts +3 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +7 -0
- package/dist/testing.js.map +1 -0
- package/dist/transport/events-stream.d.ts +7 -5
- package/dist/transport/events-stream.d.ts.map +1 -1
- package/dist/transport/events-stream.js +19 -13
- package/dist/transport/events-stream.js.map +1 -1
- package/dist/transport/http.d.ts +16 -12
- package/dist/transport/http.d.ts.map +1 -1
- package/dist/transport/http.js +43 -16
- package/dist/transport/http.js.map +1 -1
- package/dist/transport/livestream-session.d.ts +5 -3
- package/dist/transport/livestream-session.d.ts.map +1 -1
- package/dist/transport/livestream-session.js +8 -4
- package/dist/transport/livestream-session.js.map +1 -1
- package/dist/transport/talkback-session-double.d.ts +129 -0
- package/dist/transport/talkback-session-double.d.ts.map +1 -0
- package/dist/transport/talkback-session-double.js +187 -0
- package/dist/transport/talkback-session-double.js.map +1 -0
- package/dist/util/cli/commands/camera-talkback.js.map +1 -1
- package/dist/util/cli/commands/capture.js.map +1 -1
- package/dist/util/cli/commands/decode.js.map +1 -1
- package/dist/util/cli/commands/doctor.js.map +1 -1
- package/dist/util/cli/commands/watch-events.js.map +1 -1
- package/dist/util/cli/commands/watch-livestream.js.map +1 -1
- package/dist/util/cli/commands/watch-raw.js.map +1 -1
- package/dist/util/cli/commands/watch-state.js.map +1 -1
- package/dist/util/cli/shared.js.map +1 -1
- package/package.json +10 -6
- package/src/client/client.ts +16 -10
- package/src/client/connection.ts +23 -9
- package/src/devices/device.ts +1 -1
- package/src/errors.ts +3 -2
- package/src/event-bus.ts +87 -17
- package/src/testing.ts +7 -0
- package/src/transport/events-stream.ts +22 -14
- package/src/transport/http.ts +53 -16
- package/src/transport/livestream-session.ts +8 -4
- package/src/transport/talkback-session-double.ts +317 -0
- package/src/util/cli/commands/camera-talkback.ts +1 -1
- package/src/util/cli/commands/capture.ts +2 -2
- package/src/util/cli/commands/decode.ts +1 -1
- package/src/util/cli/commands/doctor.ts +2 -2
- package/src/util/cli/commands/watch-events.ts +1 -1
- package/src/util/cli/commands/watch-livestream.ts +1 -1
- package/src/util/cli/commands/watch-raw.ts +1 -1
- package/src/util/cli/commands/watch-state.ts +4 -4
- package/src/util/cli/shared.ts +2 -2
|
@@ -300,10 +300,11 @@ export class EventStream implements AsyncDisposable {
|
|
|
300
300
|
}
|
|
301
301
|
|
|
302
302
|
/**
|
|
303
|
-
* Wait for the next emission of a stream event.
|
|
303
|
+
* Wait for the next emission of a stream event. A wait still pending when the stream tears down, for any reason, rejects with a {@link ProtectAbortedError}, so a
|
|
304
|
+
* wait that is never awaited needs a rejection handler; an abort of the signal rejects it with an `AbortError` whose `cause` is the signal's reason.
|
|
304
305
|
*
|
|
305
306
|
* @param event - The event to await.
|
|
306
|
-
* @param opts - Optional abort signal.
|
|
307
|
+
* @param opts - Optional abort signal that cancels the wait.
|
|
307
308
|
*
|
|
308
309
|
* @returns A promise resolving to the event's argument tuple.
|
|
309
310
|
*/
|
|
@@ -313,7 +314,8 @@ export class EventStream implements AsyncDisposable {
|
|
|
313
314
|
}
|
|
314
315
|
|
|
315
316
|
/**
|
|
316
|
-
* Stream every subsequent emission of a stream event until the signal aborts.
|
|
317
|
+
* Stream every subsequent emission of a stream event until the signal aborts or the stream tears down, for any reason. The teardown ends the iteration cleanly once
|
|
318
|
+
* every emission made before it has been delivered; an abort rejects it with an `AbortError` whose `cause` is the signal's reason.
|
|
317
319
|
*
|
|
318
320
|
* @param event - The event to stream.
|
|
319
321
|
* @param opts - Stream options, including the abort signal.
|
|
@@ -326,8 +328,8 @@ export class EventStream implements AsyncDisposable {
|
|
|
326
328
|
}
|
|
327
329
|
|
|
328
330
|
/**
|
|
329
|
-
* The realtime event firehose: every decoded {@link TypedEvent}, until the caller's signal aborts
|
|
330
|
-
*
|
|
331
|
+
* The realtime event firehose: every decoded {@link TypedEvent}, until the caller's signal aborts or the stream tears down, for any reason. Sugar over
|
|
332
|
+
* `stream("packet")` that unwraps the single-element argument tuple to the event itself.
|
|
331
333
|
*
|
|
332
334
|
* @param opts - Optional abort signal that terminates the iteration.
|
|
333
335
|
*
|
|
@@ -335,12 +337,12 @@ export class EventStream implements AsyncDisposable {
|
|
|
335
337
|
*/
|
|
336
338
|
async *packets(opts: { signal?: AbortSignal } = {}): AsyncGenerator<TypedEvent> {
|
|
337
339
|
|
|
338
|
-
// The underlying `stream` rail rejects with
|
|
339
|
-
// return on the caller's own abort - a `for await` over the firehose ends quietly on Ctrl-C rather than
|
|
340
|
-
// error still propagates.
|
|
340
|
+
// The underlying `stream` rail rejects with an `AbortError` when its signal fires (node:events' `on` contract), and ends cleanly when the stream tears down. For
|
|
341
|
+
// the firehose sugar we smooth the abort into a clean return on the caller's own abort - a `for await` over the firehose ends quietly on Ctrl-C rather than
|
|
342
|
+
// forcing every consumer to wrap it in try/catch. Any other error still propagates.
|
|
341
343
|
try {
|
|
342
344
|
|
|
343
|
-
for await
|
|
345
|
+
for await(const [event] of this.#bus.stream("packet", opts)) {
|
|
344
346
|
|
|
345
347
|
yield event;
|
|
346
348
|
}
|
|
@@ -472,7 +474,8 @@ export class EventStream implements AsyncDisposable {
|
|
|
472
474
|
* which a peer that never answers the close frame would otherwise hold open, and one still in its handshake.
|
|
473
475
|
*
|
|
474
476
|
* The reports then run in one order: the handshake's rejection for a stream that never opened or the rail fault for one that did, the line a fault carries, the
|
|
475
|
-
* close line, `closed` and the closed diagnostic.
|
|
477
|
+
* close line, `closed` and the closed diagnostic. The stream never reconnects, so the last of them is its last emission, and the bus closes after it, carrying the
|
|
478
|
+
* failure the teardown reported, if any, as the cause of its reason.
|
|
476
479
|
*/
|
|
477
480
|
#onClose(teardown: SocketTeardown): void {
|
|
478
481
|
|
|
@@ -488,17 +491,20 @@ export class EventStream implements AsyncDisposable {
|
|
|
488
491
|
this.#controller.abort();
|
|
489
492
|
this.#released = (this.#owned === null) ? Promise.resolve() : releaseOwned(this.#owned);
|
|
490
493
|
|
|
494
|
+
let failure: ProtectError | null;
|
|
495
|
+
|
|
491
496
|
if(this.#live) {
|
|
492
497
|
|
|
493
|
-
|
|
498
|
+
failure = this.#railFault(teardown);
|
|
494
499
|
|
|
495
|
-
if(
|
|
500
|
+
if(failure !== null) {
|
|
496
501
|
|
|
497
|
-
this.#bus.emit("error",
|
|
502
|
+
this.#bus.emit("error", failure);
|
|
498
503
|
}
|
|
499
504
|
} else {
|
|
500
505
|
|
|
501
|
-
this.#
|
|
506
|
+
failure = this.#preOpenFailure(teardown);
|
|
507
|
+
this.#rejectOpen(failure);
|
|
502
508
|
}
|
|
503
509
|
|
|
504
510
|
if((teardown.kind === "fault") && (teardown.line !== null)) {
|
|
@@ -513,6 +519,8 @@ export class EventStream implements AsyncDisposable {
|
|
|
513
519
|
|
|
514
520
|
channels.eventsClosed.publish({ code, reason } satisfies EventsClosedPayload);
|
|
515
521
|
}
|
|
522
|
+
|
|
523
|
+
this.#bus.close(new ProtectAbortedError("The UniFi Protect realtime events stream closed.", { ...((failure !== null) && { cause: failure }) }));
|
|
516
524
|
}
|
|
517
525
|
|
|
518
526
|
/* What a handshake that never completed rejects with. A fault is handed over as itself, so the rejection's type says exactly what went wrong; the caller's own
|
package/src/transport/http.ts
CHANGED
|
@@ -425,6 +425,10 @@ export class Transport implements AsyncDisposable {
|
|
|
425
425
|
#pool: OwnedDispatcher | { readonly connector: null; readonly dispatcher: Dispatcher };
|
|
426
426
|
#throttledSince: number | null = null;
|
|
427
427
|
|
|
428
|
+
// The error a disposed transport answers every later request with, null until disposal, which is the transport's whole terminal state: from then on a send
|
|
429
|
+
// rejects with it before dispatching, and neither the breaker nor reset() does anything.
|
|
430
|
+
#disposed: ProtectAbortedError | null = null;
|
|
431
|
+
|
|
428
432
|
constructor(options: TransportOptions) {
|
|
429
433
|
|
|
430
434
|
this.#clock = options.clock ?? wallClock;
|
|
@@ -454,9 +458,9 @@ export class Transport implements AsyncDisposable {
|
|
|
454
458
|
}
|
|
455
459
|
|
|
456
460
|
/**
|
|
457
|
-
* Send a request and return the {@link ProtectResponse} for any HTTP status.
|
|
458
|
-
* sending a request, composes the caller's signal with the timeout deadline, classifies transport failures into
|
|
459
|
-
* caller cancelled the request, and runs the 401-relogin retry (once) when a hook is wired.
|
|
461
|
+
* Send a request and return the {@link ProtectResponse} for any HTTP status. Refuses a request once the transport is disposed, throttle-gates before dispatching,
|
|
462
|
+
* answers a caller that has already aborted without sending a request, composes the caller's signal with the timeout deadline, classifies transport failures into
|
|
463
|
+
* typed errors, books the breaker outcome unless the caller cancelled the request, and runs the 401-relogin retry (once) when a hook is wired.
|
|
460
464
|
*
|
|
461
465
|
* This is the transport primitive. Callers that want the ergonomic "throw on non-2xx and parse JSON" path use {@link Transport.request}; callers that need raw
|
|
462
466
|
* status, headers, or bytes (the auth handshake, snapshots) use `send` directly.
|
|
@@ -466,13 +470,16 @@ export class Transport implements AsyncDisposable {
|
|
|
466
470
|
*
|
|
467
471
|
* @returns The response.
|
|
468
472
|
*
|
|
469
|
-
* @throws {@link
|
|
470
|
-
* {@link ProtectNetworkError} on transport-level failures; and whatever the relogin hook rejects
|
|
471
|
-
* error that handshake was answered with among them.
|
|
473
|
+
* @throws {@link ProtectAbortedError} once the transport is disposed; {@link ProtectThrottledError} while the breaker is open and cooling;
|
|
474
|
+
* {@link ProtectTimeoutError}, {@link ProtectAbortedError}, or {@link ProtectNetworkError} on transport-level failures; and whatever the relogin hook rejects
|
|
475
|
+
* with, when the handshake of a 401's relogin throws, the status error that handshake was answered with among them.
|
|
472
476
|
*/
|
|
473
477
|
async send(url: string, opts: SendOptions = {}): Promise<ProtectResponse> {
|
|
474
478
|
|
|
475
|
-
//
|
|
479
|
+
// A disposed transport is terminal, so a request sent to it rejects before the breaker or the network ever sees it: it books nothing and reaches no pool.
|
|
480
|
+
this.#throwIfDisposed();
|
|
481
|
+
|
|
482
|
+
// Then the gate: if the breaker is open and still inside its cooldown window, refuse locally without touching the network. Once the cooldown has elapsed we fall
|
|
476
483
|
// through and let this request act as the half-open recovery probe; `book` will close or re-arm the breaker based on its outcome, and a probe its caller cancels
|
|
477
484
|
// books nothing and leaves the breaker half-open. A `probe` request - the ConnectionMonitor's recovery trial, or the handshake of a relogin a 401 on that trial
|
|
478
485
|
// triggers - skips this gate entirely: the monitor's backoff curve is the rate limiter while it is recovering, so its probe dispatches at the monitor's cadence
|
|
@@ -497,6 +504,10 @@ export class Transport implements AsyncDisposable {
|
|
|
497
504
|
|
|
498
505
|
for(;;) {
|
|
499
506
|
|
|
507
|
+
// A disposal can land while a 401's relogin hook is pending, so every attempt reads the terminal state again before it dispatches, and the retry the hook
|
|
508
|
+
// allows rejects with the disposal's error as any later request does. The entry check above answers the first attempt ahead of the breaker gate.
|
|
509
|
+
this.#throwIfDisposed();
|
|
510
|
+
|
|
500
511
|
// A caller that has already aborted is answered before anything is dispatched. No request is issued, so none is published and none is booked: the
|
|
501
512
|
// controller was never asked, and an abort or a deadline that fired before the request began says nothing about it.
|
|
502
513
|
if(opts.signal?.aborted === true) {
|
|
@@ -561,13 +572,14 @@ export class Transport implements AsyncDisposable {
|
|
|
561
572
|
* Rebuild the owned connection pool, dropping every keepalive connection to the controller. Called when the breaker trips so the next attempt starts from a clean
|
|
562
573
|
* pool rather than reusing sockets to a degraded controller. A request in flight, over HTTP/2 or HTTP/1.1, fails as the pool-reset interruption, and a connection
|
|
563
574
|
* attempt still in flight is released along with the keepalive connections, so a request waiting on one fails at once the same way rather than running on to
|
|
564
|
-
* undici's own connect timer. A no-op when the dispatcher was injected - that lifecycle belongs to the injector
|
|
575
|
+
* undici's own connect timer. A no-op when the dispatcher was injected - that lifecycle belongs to the injector - and once the transport is disposed, since a pool
|
|
576
|
+
* built then would have nothing left to release it.
|
|
565
577
|
*/
|
|
566
578
|
reset(): void {
|
|
567
579
|
|
|
568
580
|
const pool = this.#pool;
|
|
569
581
|
|
|
570
|
-
if(pool.connector === null) {
|
|
582
|
+
if((this.#disposed !== null) || (pool.connector === null)) {
|
|
571
583
|
|
|
572
584
|
return;
|
|
573
585
|
}
|
|
@@ -593,10 +605,11 @@ export class Transport implements AsyncDisposable {
|
|
|
593
605
|
}
|
|
594
606
|
|
|
595
607
|
/**
|
|
596
|
-
* Wait for the next emission of a transport event.
|
|
608
|
+
* Wait for the next emission of a transport event. A wait still pending when the transport is disposed rejects with a {@link ProtectAbortedError}, so a wait that
|
|
609
|
+
* is never awaited needs a rejection handler; an abort of the signal rejects it with an `AbortError` whose `cause` is the signal's reason.
|
|
597
610
|
*
|
|
598
611
|
* @param event - The event to await.
|
|
599
|
-
* @param opts - Optional abort signal.
|
|
612
|
+
* @param opts - Optional abort signal that cancels the wait.
|
|
600
613
|
*
|
|
601
614
|
* @returns A promise resolving to the event's argument tuple.
|
|
602
615
|
*/
|
|
@@ -606,7 +619,8 @@ export class Transport implements AsyncDisposable {
|
|
|
606
619
|
}
|
|
607
620
|
|
|
608
621
|
/**
|
|
609
|
-
* Stream every subsequent emission of a transport event until the signal aborts.
|
|
622
|
+
* Stream every subsequent emission of a transport event until the signal aborts or the transport is disposed. The disposal ends the iteration cleanly once every
|
|
623
|
+
* emission made before it has been delivered; an abort rejects it with an `AbortError` whose `cause` is the signal's reason.
|
|
610
624
|
*
|
|
611
625
|
* @param event - The event to stream.
|
|
612
626
|
* @param opts - Stream options, including the abort signal.
|
|
@@ -619,17 +633,34 @@ export class Transport implements AsyncDisposable {
|
|
|
619
633
|
}
|
|
620
634
|
|
|
621
635
|
/**
|
|
622
|
-
* Dispose the transport
|
|
623
|
-
*
|
|
636
|
+
* Dispose the transport for good: every later request is refused, the breaker and {@link Transport.reset} do nothing, the owned pool is destroyed, and every stream
|
|
637
|
+
* and pending wait on the transport's events ends. A connection attempt still in flight is severed before the pool's own teardown is awaited, and an injected
|
|
638
|
+
* dispatcher is left to its injector. Safe to call more than once.
|
|
624
639
|
*/
|
|
625
640
|
async [Symbol.asyncDispose](): Promise<void> {
|
|
626
641
|
|
|
642
|
+
// The transport turns terminal before its pool is released, so a request in flight that fails on the released pool books nothing, which would otherwise trip the
|
|
643
|
+
// breaker and rebuild a pool nothing releases. The bus closes last, once nothing can emit.
|
|
644
|
+
this.#disposed ??= new ProtectAbortedError("The UniFi Protect transport was disposed.");
|
|
645
|
+
|
|
627
646
|
const pool = this.#pool;
|
|
628
647
|
|
|
629
648
|
if(pool.connector !== null) {
|
|
630
649
|
|
|
631
650
|
await releaseOwned(pool);
|
|
632
651
|
}
|
|
652
|
+
|
|
653
|
+
this.#bus.close(this.#disposed);
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
// Throw the disposal's error once the transport is disposed. It is a method rather than an inline test because the compiler narrows the field to null past
|
|
657
|
+
// the first test in `send` and would read a second one as dead, though a disposal can land at any await between them.
|
|
658
|
+
#throwIfDisposed(): void {
|
|
659
|
+
|
|
660
|
+
if(this.#disposed !== null) {
|
|
661
|
+
|
|
662
|
+
throw this.#disposed;
|
|
663
|
+
}
|
|
633
664
|
}
|
|
634
665
|
|
|
635
666
|
// Perform a single HTTP exchange: compose the deadline with the caller's signal, stamp the auth and per-call headers, publish the request diagnostics, buffer the
|
|
@@ -730,9 +761,15 @@ export class Transport implements AsyncDisposable {
|
|
|
730
761
|
}
|
|
731
762
|
|
|
732
763
|
// Book one breaker outcome. The first answer `controllerServing` accepts closes the breaker (and announces recovery only on the closing edge, so `throttleExited`
|
|
733
|
-
// never flaps); a failure either trips the breaker once the threshold is crossed, or re-arms the cooldown if a half-open probe just failed.
|
|
764
|
+
// never flaps); a failure either trips the breaker once the threshold is crossed, or re-arms the cooldown if a half-open probe just failed. A disposed transport
|
|
765
|
+
// books nothing, since a request still in flight at the disposal settles after it, and its outcome says nothing a terminal transport acts on.
|
|
734
766
|
#book(ok: boolean): void {
|
|
735
767
|
|
|
768
|
+
if(this.#disposed !== null) {
|
|
769
|
+
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
|
|
736
773
|
if(ok) {
|
|
737
774
|
|
|
738
775
|
this.#consecutiveFailures = 0;
|
|
@@ -741,7 +778,7 @@ export class Transport implements AsyncDisposable {
|
|
|
741
778
|
|
|
742
779
|
this.#throttledSince = null;
|
|
743
780
|
|
|
744
|
-
this.#log.info("Resumed communication with the UniFi Protect controller
|
|
781
|
+
this.#log.info("Resumed communication with the UniFi Protect controller, and the throttle breaker has closed.");
|
|
745
782
|
|
|
746
783
|
this.#bus.emit("throttleExited");
|
|
747
784
|
|
|
@@ -426,10 +426,11 @@ export class LivestreamSession implements AsyncDisposable {
|
|
|
426
426
|
}
|
|
427
427
|
|
|
428
428
|
/**
|
|
429
|
-
* Wait for the next emission of a session event.
|
|
429
|
+
* Wait for the next emission of a session event. A wait still pending when the session tears down, for any reason, rejects with a {@link ProtectAbortedError}, so a
|
|
430
|
+
* wait that is never awaited needs a rejection handler; an abort of the signal rejects it with an `AbortError` whose `cause` is the signal's reason.
|
|
430
431
|
*
|
|
431
432
|
* @param event - The event to await.
|
|
432
|
-
* @param opts - Optional abort signal.
|
|
433
|
+
* @param opts - Optional abort signal that cancels the wait.
|
|
433
434
|
*
|
|
434
435
|
* @returns A promise resolving to the event's argument tuple.
|
|
435
436
|
*/
|
|
@@ -439,7 +440,8 @@ export class LivestreamSession implements AsyncDisposable {
|
|
|
439
440
|
}
|
|
440
441
|
|
|
441
442
|
/**
|
|
442
|
-
* Stream every subsequent emission of a session event until the signal aborts.
|
|
443
|
+
* Stream every subsequent emission of a session event until the signal aborts or the session tears down, for any reason. The teardown ends the iteration cleanly
|
|
444
|
+
* once every emission made before it has been delivered; an abort rejects it with an `AbortError` whose `cause` is the signal's reason.
|
|
443
445
|
*
|
|
444
446
|
* @param event - The event to stream.
|
|
445
447
|
* @param opts - Stream options, including the abort signal.
|
|
@@ -816,7 +818,8 @@ export class LivestreamSession implements AsyncDisposable {
|
|
|
816
818
|
*
|
|
817
819
|
* The reports then run in one order: the closure's cause recorded, a fault put on the error rail whether or not the socket had opened (the pool acts on a stall
|
|
818
820
|
* alone, which only an open socket raises), the line a fault carries, the close line and `closed`. A peer's close puts nothing on the rail, so the pool recovers
|
|
819
|
-
* from `closed` alone.
|
|
821
|
+
* from `closed` alone. The session never reconnects, so `closed` is its last emission, and the bus closes after it, carrying the closure's cause, if any, as the
|
|
822
|
+
* cause of its reason.
|
|
820
823
|
*/
|
|
821
824
|
#onClose(teardown: SocketTeardown): void {
|
|
822
825
|
|
|
@@ -846,6 +849,7 @@ export class LivestreamSession implements AsyncDisposable {
|
|
|
846
849
|
|
|
847
850
|
this.#log.debug("The UniFi Protect livestream API connection closed.", { code, reason });
|
|
848
851
|
this.#bus.emit("closed", { ...((this.#closeCause !== null) && { cause: this.#closeCause }), code, reason });
|
|
852
|
+
this.#bus.close(new ProtectAbortedError("The UniFi Protect livestream session closed.", { ...((this.#closeCause !== null) && { cause: this.#closeCause }) }));
|
|
849
853
|
}
|
|
850
854
|
|
|
851
855
|
// What the closure records as its cause: the typed abort for the caller's cancel, the fault's own error, and nothing for an explicit close or a peer's close.
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/* Copyright(C) 2019-2026, HJD (https://github.com/hjdhjd). All rights reserved.
|
|
2
|
+
*
|
|
3
|
+
* talkback-session-double.ts: The shipped talkback test doubles - a deterministic write-direction WebSocket a suite drives by hand, and a factory that connects a real
|
|
4
|
+
* TalkbackSession over one, so a consumer's suite exercises the send-only channel without a live controller. The unifi-protect/testing entry publishes each of them.
|
|
5
|
+
*/
|
|
6
|
+
import type { ProtectWritableWebSocket } from "./ws.ts";
|
|
7
|
+
import { TalkbackSession } from "./talkback-session.ts";
|
|
8
|
+
|
|
9
|
+
// The synthetic camera every session a factory connects negotiates for, and the synthetic URL its resolver answers: the `.invalid` top-level domain never resolves,
|
|
10
|
+
// and no session built here dials its URL, because the socket it dials is the double below.
|
|
11
|
+
const TEST_TALKBACK_CAMERA_ID = "talkback-double-camera";
|
|
12
|
+
const TEST_TALKBACK_URL = "wss://controller.invalid/talkback";
|
|
13
|
+
|
|
14
|
+
// The listener-registration options TalkbackSession passes, which are a subset of the standard addEventListener options.
|
|
15
|
+
interface ListenerOptions {
|
|
16
|
+
|
|
17
|
+
once?: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// A registered listener and whether it fires only once. The listener is stored type-erased, and the public addEventListener overloads keep the call sites fully
|
|
21
|
+
// typed.
|
|
22
|
+
interface ListenerEntry {
|
|
23
|
+
|
|
24
|
+
listener: (event: unknown) => void;
|
|
25
|
+
once: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Construction options for {@link TestTalkbackSocket}, and for every socket a {@link TestTalkbackFactory} built with them dials.
|
|
30
|
+
*
|
|
31
|
+
* - `autoOpen` (default `true`) opens the socket on the next microtask, so a session's connect resolves with no driving by hand. A suite that scrutinizes the open
|
|
32
|
+
* handshake itself passes `false` and opens the socket with `emitOpen()`.
|
|
33
|
+
* - `closeFault` (default `false`) makes `close()` throw after it records the request, so a suite can show that a teardown survives a socket whose close faults.
|
|
34
|
+
* - `failsOnClose` (default `false`) makes `close()` on a socket that has not opened fire `error` and then `close` with code 1006 from inside the call, because undici
|
|
35
|
+
* fails a socket still connecting from underneath a close request and reports it synchronously.
|
|
36
|
+
*/
|
|
37
|
+
export interface TestTalkbackSocketOptions {
|
|
38
|
+
|
|
39
|
+
autoOpen?: boolean;
|
|
40
|
+
closeFault?: boolean;
|
|
41
|
+
failsOnClose?: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* A deterministic in-memory WebSocket with the write-direction surface a {@link TalkbackSession} dials: `send`, `bufferedAmount`, and the `open`, `close` and `error`
|
|
46
|
+
* listeners, with no `message` listener and no `binaryType`, because the talkback channel carries nothing inbound. A suite drives the connection with the `emit*`
|
|
47
|
+
* methods and reads what the session did: `sent` records every chunk written, in order, `closeRequested` whether the session asked the socket to close, and
|
|
48
|
+
* {@link TestTalkbackSocket.listenerCount} the listeners still registered. The socket honors `once` and detaches on `removeEventListener` by identity, and nothing
|
|
49
|
+
* else removes a listener, so a teardown that forgets a removal leaves one behind. `bufferedAmount` is writable, so a suite can drive the session's send-buffer
|
|
50
|
+
* safety ceiling.
|
|
51
|
+
*
|
|
52
|
+
* A consumer's suite receives one from each {@link TestTalkbackFactory.connect} call, through {@link TestTalkbackConnectCall.socket}.
|
|
53
|
+
*/
|
|
54
|
+
export class TestTalkbackSocket implements ProtectWritableWebSocket {
|
|
55
|
+
|
|
56
|
+
/** The bytes queued for transmission but not yet flushed. It stays at zero unless a suite sets it to drive the session's send-buffer safety ceiling. */
|
|
57
|
+
bufferedAmount = 0;
|
|
58
|
+
|
|
59
|
+
/** Whether the session has asked the socket to close. */
|
|
60
|
+
closeRequested = false;
|
|
61
|
+
|
|
62
|
+
/** Every chunk the session sent, in order. */
|
|
63
|
+
readonly sent: Uint8Array[] = [];
|
|
64
|
+
|
|
65
|
+
readonly #closeFault: boolean;
|
|
66
|
+
readonly #failsOnClose: boolean;
|
|
67
|
+
readonly #listeners = new Map<string, Set<ListenerEntry>>();
|
|
68
|
+
|
|
69
|
+
// Where the socket is in its lifecycle as the `emit*` methods have driven it, which is what tells `failsOnClose` whether a close lands on a socket still connecting.
|
|
70
|
+
#readyState: "closed" | "connecting" | "open" = "connecting";
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Build a socket double, still connecting.
|
|
74
|
+
*
|
|
75
|
+
* @param options - The {@link TestTalkbackSocketOptions} that shape how the socket opens and closes.
|
|
76
|
+
*/
|
|
77
|
+
constructor(options: TestTalkbackSocketOptions = {}) {
|
|
78
|
+
|
|
79
|
+
this.#closeFault = options.closeFault ?? false;
|
|
80
|
+
this.#failsOnClose = options.failsOnClose ?? false;
|
|
81
|
+
|
|
82
|
+
// Open on the next microtask by default, after the TalkbackSession's connect has synchronously attached its listeners.
|
|
83
|
+
if(options.autoOpen ?? true) {
|
|
84
|
+
|
|
85
|
+
queueMicrotask(() => this.emitOpen());
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Register a listener for the `open`, `close` or `error` event, honoring the `once` option as a WebSocket does. */
|
|
90
|
+
addEventListener(type: "open", listener: () => void, options?: ListenerOptions): void;
|
|
91
|
+
addEventListener(type: "close", listener: (event: { code: number; reason: string }) => void, options?: ListenerOptions): void;
|
|
92
|
+
addEventListener(type: "error", listener: (event: { error?: unknown; message?: string }) => void, options?: ListenerOptions): void;
|
|
93
|
+
addEventListener(type: string, listener: (event: never) => void, options: ListenerOptions = {}): void {
|
|
94
|
+
|
|
95
|
+
const set = this.#setFor(type);
|
|
96
|
+
const entry: ListenerEntry = { listener: listener as (event: unknown) => void, once: options.once ?? false };
|
|
97
|
+
|
|
98
|
+
set.add(entry);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Request the socket close. Records the request; teardown in TalkbackSession flows through its own close path rather than waiting on a close event here. When
|
|
103
|
+
* constructed with `failsOnClose`, a socket that has not opened fires `error` and then `close` 1006 from inside this call, undici's empty error and reason on each.
|
|
104
|
+
* When constructed with `closeFault`, it throws after recording the request.
|
|
105
|
+
*/
|
|
106
|
+
close(): void {
|
|
107
|
+
|
|
108
|
+
this.closeRequested = true;
|
|
109
|
+
|
|
110
|
+
// The socket is closed before it reports, as undici closes it, so a close() re-entered from a listener here asks nothing of it a second time.
|
|
111
|
+
if(this.#failsOnClose && (this.#readyState === "connecting")) {
|
|
112
|
+
|
|
113
|
+
this.#readyState = "closed";
|
|
114
|
+
this.emitError(new TypeError(""));
|
|
115
|
+
this.emitClose(1006, "");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if(this.#closeFault) {
|
|
119
|
+
|
|
120
|
+
throw new Error("The talkback socket double's close() faulted, as its closeFault option asks.");
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The number of listeners still registered, across every event type, for a suite that reads whether a teardown removed everything it added. */
|
|
125
|
+
listenerCount(): number {
|
|
126
|
+
|
|
127
|
+
let count = 0;
|
|
128
|
+
|
|
129
|
+
for(const set of this.#listeners.values()) {
|
|
130
|
+
|
|
131
|
+
count += set.size;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return count;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Detach a listener by the identity of the function that was registered, which is the only handle the caller is given and the only one it hands back. */
|
|
138
|
+
removeEventListener(type: "open", listener: () => void): void;
|
|
139
|
+
removeEventListener(type: "close", listener: (event: { code: number; reason: string }) => void): void;
|
|
140
|
+
removeEventListener(type: "error", listener: (event: { error?: unknown; message?: string }) => void): void;
|
|
141
|
+
removeEventListener(type: string, listener: (event: never) => void): void {
|
|
142
|
+
|
|
143
|
+
const set = this.#listeners.get(type);
|
|
144
|
+
|
|
145
|
+
if(set === undefined) {
|
|
146
|
+
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const registered = listener as (event: unknown) => void;
|
|
151
|
+
|
|
152
|
+
for(const entry of set) {
|
|
153
|
+
|
|
154
|
+
if(entry.listener === registered) {
|
|
155
|
+
|
|
156
|
+
set.delete(entry);
|
|
157
|
+
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Queue a binary frame for transmission. Records it in {@link TestTalkbackSocket.sent} so a suite can assert the bytes and their order. */
|
|
164
|
+
send(data: Uint8Array): void {
|
|
165
|
+
|
|
166
|
+
this.sent.push(data);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Fire the `open` event, as the controller accepting the upgrade does. */
|
|
170
|
+
emitOpen(): void {
|
|
171
|
+
|
|
172
|
+
if(this.#readyState === "connecting") {
|
|
173
|
+
|
|
174
|
+
this.#readyState = "open";
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
this.#dispatch("open", undefined);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Fire a `close` event with the given frame code and reason. */
|
|
181
|
+
emitClose(code = 1000, reason = ""): void {
|
|
182
|
+
|
|
183
|
+
this.#readyState = "closed";
|
|
184
|
+
this.#dispatch("close", { code, reason });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Fire an `error` event carrying an optional underlying cause. */
|
|
188
|
+
emitError(error?: unknown): void {
|
|
189
|
+
|
|
190
|
+
this.#dispatch("error", { error });
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Dispatch an event to every listener registered for the type, removing any that asked to fire only once. We snapshot the set first so a listener that detaches
|
|
194
|
+
// mid-dispatch does not perturb the iteration.
|
|
195
|
+
#dispatch(type: string, event: unknown): void {
|
|
196
|
+
|
|
197
|
+
const set = this.#listeners.get(type);
|
|
198
|
+
|
|
199
|
+
if(set === undefined) {
|
|
200
|
+
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
for(const entry of [...set]) {
|
|
205
|
+
|
|
206
|
+
if(entry.once) {
|
|
207
|
+
|
|
208
|
+
set.delete(entry);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
entry.listener(event);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Return the listener set for the given event type, creating and caching an empty one on first use.
|
|
216
|
+
#setFor(type: string): Set<ListenerEntry> {
|
|
217
|
+
|
|
218
|
+
let set = this.#listeners.get(type);
|
|
219
|
+
|
|
220
|
+
if(set === undefined) {
|
|
221
|
+
|
|
222
|
+
set = new Set();
|
|
223
|
+
this.#listeners.set(type, set);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
return set;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* One {@link TestTalkbackFactory.connect} call, as the factory recorded it.
|
|
232
|
+
*
|
|
233
|
+
* - `signal` is the abort signal the caller passed, or `undefined` when it passed none.
|
|
234
|
+
* - `socket` resolves with the socket the call's session dials, once it dials. The session negotiates its URL before it dials, so the socket does not exist yet when
|
|
235
|
+
* `connect` returns its promise, and an event fired before the dial would reach no listener, as on a real socket. When the connect fails before the dial, `socket`
|
|
236
|
+
* rejects with the connect's own error, and a suite that never reads it meets no unhandled rejection.
|
|
237
|
+
*/
|
|
238
|
+
export interface TestTalkbackConnectCall {
|
|
239
|
+
|
|
240
|
+
readonly signal: AbortSignal | undefined;
|
|
241
|
+
readonly socket: Promise<TestTalkbackSocket>;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* A stand-in for `Camera.talkback` that connects a real {@link TalkbackSession} over a {@link TestTalkbackSocket}, so a consumer's suite drives the session itself - its
|
|
246
|
+
* atomic connect, its send drain and safety ceiling, its teardown and its typed failures - and fakes only the wire beneath it. {@link TestTalkbackFactory.connect} takes
|
|
247
|
+
* `Camera.talkback`'s signature, so a host standing in for a camera answers `talkback(opts)` with `factory.connect(opts)` and passes the call straight through.
|
|
248
|
+
*
|
|
249
|
+
* Each call is recorded in {@link TestTalkbackFactory.connectCalls} with the caller's signal and the socket its session dials, which the suite drives to open, close or
|
|
250
|
+
* fail the connection. The session takes the caller's signal as a camera's does, so aborting it cancels the connect and tears down a live session.
|
|
251
|
+
*
|
|
252
|
+
* Every session the factory connects negotiates for, and publishes on the talkback diagnostics channels under, one synthetic camera id, `talkback-double-camera`,
|
|
253
|
+
* whichever camera the host stands in for.
|
|
254
|
+
*/
|
|
255
|
+
export class TestTalkbackFactory {
|
|
256
|
+
|
|
257
|
+
/** Every connect call, in order, with the caller's signal and the socket its session dials, so a suite can assert the call was made and drive its socket. */
|
|
258
|
+
readonly connectCalls: TestTalkbackConnectCall[] = [];
|
|
259
|
+
|
|
260
|
+
readonly #socketOptions: TestTalkbackSocketOptions;
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Build a factory whose sessions each dial a fresh socket double.
|
|
264
|
+
*
|
|
265
|
+
* @param options - The {@link TestTalkbackSocketOptions} every socket the factory builds is constructed with.
|
|
266
|
+
*/
|
|
267
|
+
constructor(options: TestTalkbackSocketOptions = {}) {
|
|
268
|
+
|
|
269
|
+
this.#socketOptions = options;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Connect a real talkback session over a fresh socket double, as `Camera.talkback` connects one to the controller. The call is recorded before anything is awaited,
|
|
274
|
+
* so `connectCalls` holds it as soon as `connect` returns its promise.
|
|
275
|
+
*
|
|
276
|
+
* @param opts - An optional abort signal that cancels the connect and, once live, tears the session down.
|
|
277
|
+
*
|
|
278
|
+
* @returns A connected talkback session.
|
|
279
|
+
*
|
|
280
|
+
* @throws `ProtectAbortedError` when the caller's signal aborts the connect, and the session's typed failure when its socket errors or closes before it opens.
|
|
281
|
+
*/
|
|
282
|
+
async connect(opts: { signal?: AbortSignal } = {}): Promise<TalkbackSession> {
|
|
283
|
+
|
|
284
|
+
const socket = Promise.withResolvers<TestTalkbackSocket>();
|
|
285
|
+
|
|
286
|
+
// A connect that fails before its session dials rejects the call's socket, which a suite need not read, so the rejection carries a handler of its own and never
|
|
287
|
+
// surfaces as an unhandled one.
|
|
288
|
+
void socket.promise.catch(() => undefined);
|
|
289
|
+
|
|
290
|
+
this.connectCalls.push({ signal: opts.signal, socket: socket.promise });
|
|
291
|
+
|
|
292
|
+
try {
|
|
293
|
+
|
|
294
|
+
return await TalkbackSession.connect({
|
|
295
|
+
|
|
296
|
+
cameraId: TEST_TALKBACK_CAMERA_ID,
|
|
297
|
+
resolveUrl: async (): Promise<string> => TEST_TALKBACK_URL,
|
|
298
|
+
...((opts.signal !== undefined) && { signal: opts.signal }),
|
|
299
|
+
webSocket: (): TestTalkbackSocket => {
|
|
300
|
+
|
|
301
|
+
const dialed = new TestTalkbackSocket(this.#socketOptions);
|
|
302
|
+
|
|
303
|
+
socket.resolve(dialed);
|
|
304
|
+
|
|
305
|
+
return dialed;
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
} catch(error) {
|
|
309
|
+
|
|
310
|
+
// The call's socket rejects with the connect's own error, so a suite awaiting it learns the session never dialed. A session that dialed has already resolved
|
|
311
|
+
// the socket, and this changes nothing.
|
|
312
|
+
socket.reject(error);
|
|
313
|
+
|
|
314
|
+
throw error;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
@@ -75,7 +75,7 @@ const cameraTalkbackHandler: CommandHandler = async (ctx) => {
|
|
|
75
75
|
let bytes = 0;
|
|
76
76
|
const metered = async function *(): AsyncGenerator<Uint8Array> {
|
|
77
77
|
|
|
78
|
-
for await
|
|
78
|
+
for await(const chunk of source) {
|
|
79
79
|
|
|
80
80
|
bytes += (chunk as Uint8Array).length;
|
|
81
81
|
|
|
@@ -209,7 +209,7 @@ function tallyCadence(window: Window, id: string, payload: unknown): void {
|
|
|
209
209
|
*/
|
|
210
210
|
async function consumeRaw(source: AsyncIterable<RawPacket>, window: Window, manifest: SchemaManifest, device: CompiledAxis | undefined): Promise<void> {
|
|
211
211
|
|
|
212
|
-
for await
|
|
212
|
+
for await(const packet of source) {
|
|
213
213
|
|
|
214
214
|
const { action, id, modelKey } = packet.header;
|
|
215
215
|
|
|
@@ -269,7 +269,7 @@ async function consumeRaw(source: AsyncIterable<RawPacket>, window: Window, mani
|
|
|
269
269
|
// one writer between them and a frame is judged against the map as of the moment it arrived.
|
|
270
270
|
async function consumeEvents(source: AsyncIterable<TypedEvent>, window: Window): Promise<void> {
|
|
271
271
|
|
|
272
|
-
for await
|
|
272
|
+
for await(const event of source) {
|
|
273
273
|
|
|
274
274
|
window.occurrencesSeen += 1;
|
|
275
275
|
|