@observertc/observer-js 1.0.0-b276103.0 → 1.0.0-beta.10
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 +972 -383
- package/dist/index.d.mts +2952 -0
- package/dist/index.d.ts +2952 -0
- package/dist/index.js +4040 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +3970 -0
- package/dist/index.mjs.map +1 -0
- package/llms-full.txt +1536 -0
- package/package.json +32 -16
- package/.eslintrc.json +0 -143
- package/.prettierignore +0 -5
- package/.prettierrc +0 -7
- package/jest.config.js +0 -9
- package/lib/ObservedCall.d.ts +0 -70
- package/lib/ObservedCall.d.ts.map +0 -1
- package/lib/ObservedCall.js +0 -196
- package/lib/ObservedCallEventMonitor.d.ts +0 -107
- package/lib/ObservedCallEventMonitor.d.ts.map +0 -1
- package/lib/ObservedCallEventMonitor.js +0 -321
- package/lib/ObservedCallSummary.d.ts +0 -18
- package/lib/ObservedCallSummary.d.ts.map +0 -1
- package/lib/ObservedCallSummary.js +0 -2
- package/lib/ObservedCertificate.d.ts +0 -19
- package/lib/ObservedCertificate.d.ts.map +0 -1
- package/lib/ObservedCertificate.js +0 -38
- package/lib/ObservedClient.d.ts +0 -115
- package/lib/ObservedClient.d.ts.map +0 -1
- package/lib/ObservedClient.js +0 -714
- package/lib/ObservedClientEventMonitor.d.ts +0 -91
- package/lib/ObservedClientEventMonitor.d.ts.map +0 -1
- package/lib/ObservedClientEventMonitor.js +0 -254
- package/lib/ObservedClientSummary.d.ts +0 -23
- package/lib/ObservedClientSummary.d.ts.map +0 -1
- package/lib/ObservedClientSummary.js +0 -2
- package/lib/ObservedCodec.d.ts +0 -22
- package/lib/ObservedCodec.d.ts.map +0 -1
- package/lib/ObservedCodec.js +0 -45
- package/lib/ObservedDataChannel.d.ts +0 -30
- package/lib/ObservedDataChannel.d.ts.map +0 -1
- package/lib/ObservedDataChannel.js +0 -75
- package/lib/ObservedIceCandidate.d.ts +0 -29
- package/lib/ObservedIceCandidate.d.ts.map +0 -1
- package/lib/ObservedIceCandidate.js +0 -59
- package/lib/ObservedIceCandidatePair.d.ts +0 -45
- package/lib/ObservedIceCandidatePair.d.ts.map +0 -1
- package/lib/ObservedIceCandidatePair.js +0 -127
- package/lib/ObservedIceTransport.d.ts +0 -36
- package/lib/ObservedIceTransport.d.ts.map +0 -1
- package/lib/ObservedIceTransport.js +0 -93
- package/lib/ObservedInboundRtp.d.ts +0 -92
- package/lib/ObservedInboundRtp.d.ts.map +0 -1
- package/lib/ObservedInboundRtp.js +0 -193
- package/lib/ObservedInboundTrack.d.ts +0 -34
- package/lib/ObservedInboundTrack.d.ts.map +0 -1
- package/lib/ObservedInboundTrack.js +0 -92
- package/lib/ObservedMediaPlayout.d.ts +0 -22
- package/lib/ObservedMediaPlayout.d.ts.map +0 -1
- package/lib/ObservedMediaPlayout.js +0 -42
- package/lib/ObservedMediaSource.d.ts +0 -28
- package/lib/ObservedMediaSource.d.ts.map +0 -1
- package/lib/ObservedMediaSource.js +0 -55
- package/lib/ObservedOutboundRtp.d.ts +0 -62
- package/lib/ObservedOutboundRtp.d.ts.map +0 -1
- package/lib/ObservedOutboundRtp.js +0 -144
- package/lib/ObservedOutboundTrack.d.ts +0 -34
- package/lib/ObservedOutboundTrack.d.ts.map +0 -1
- package/lib/ObservedOutboundTrack.js +0 -65
- package/lib/ObservedPeerConnection.d.ts +0 -207
- package/lib/ObservedPeerConnection.d.ts.map +0 -1
- package/lib/ObservedPeerConnection.js +0 -788
- package/lib/ObservedPeerConnectionTransport.d.ts +0 -17
- package/lib/ObservedPeerConnectionTransport.d.ts.map +0 -1
- package/lib/ObservedPeerConnectionTransport.js +0 -34
- package/lib/ObservedRemoteInboundRtp.d.ts +0 -30
- package/lib/ObservedRemoteInboundRtp.d.ts.map +0 -1
- package/lib/ObservedRemoteInboundRtp.js +0 -60
- package/lib/ObservedRemoteOutboundRtp.d.ts +0 -30
- package/lib/ObservedRemoteOutboundRtp.d.ts.map +0 -1
- package/lib/ObservedRemoteOutboundRtp.js +0 -60
- package/lib/ObservedTURN.d.ts +0 -31
- package/lib/ObservedTURN.d.ts.map +0 -1
- package/lib/ObservedTURN.js +0 -58
- package/lib/ObservedTurnServer.d.ts +0 -25
- package/lib/ObservedTurnServer.d.ts.map +0 -1
- package/lib/ObservedTurnServer.js +0 -59
- package/lib/Observer.d.ts +0 -62
- package/lib/Observer.d.ts.map +0 -1
- package/lib/Observer.js +0 -160
- package/lib/ObserverEventMonitor.d.ts +0 -141
- package/lib/ObserverEventMonitor.d.ts.map +0 -1
- package/lib/ObserverEventMonitor.js +0 -440
- package/lib/ObserverSummary.d.ts +0 -13
- package/lib/ObserverSummary.d.ts.map +0 -1
- package/lib/ObserverSummary.js +0 -2
- package/lib/Reports.d.ts +0 -85
- package/lib/Reports.d.ts.map +0 -1
- package/lib/Reports.js +0 -2
- package/lib/common/Middleware.d.ts +0 -17
- package/lib/common/Middleware.d.ts.map +0 -1
- package/lib/common/Middleware.js +0 -60
- package/lib/common/SingleExecutor.d.ts +0 -3
- package/lib/common/SingleExecutor.d.ts.map +0 -1
- package/lib/common/SingleExecutor.js +0 -31
- package/lib/common/logger.d.ts +0 -17
- package/lib/common/logger.d.ts.map +0 -1
- package/lib/common/logger.js +0 -50
- package/lib/common/types.d.ts +0 -3
- package/lib/common/types.d.ts.map +0 -1
- package/lib/common/types.js +0 -3
- package/lib/common/utils.d.ts +0 -11
- package/lib/common/utils.d.ts.map +0 -1
- package/lib/common/utils.js +0 -63
- package/lib/detectors/Detector.d.ts +0 -5
- package/lib/detectors/Detector.d.ts.map +0 -1
- package/lib/detectors/Detector.js +0 -3
- package/lib/detectors/Detectors.d.ts +0 -11
- package/lib/detectors/Detectors.d.ts.map +0 -1
- package/lib/detectors/Detectors.js +0 -34
- package/lib/index.d.ts +0 -29
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js +0 -49
- package/lib/mediasoup/ObservedMediaRouter.d.ts +0 -10
- package/lib/mediasoup/ObservedMediaRouter.d.ts.map +0 -1
- package/lib/mediasoup/ObservedMediaRouter.js +0 -6
- package/lib/monitors/TurnUsageMonitor.d.ts +0 -1
- package/lib/monitors/TurnUsageMonitor.d.ts.map +0 -1
- package/lib/monitors/TurnUsageMonitor.js +0 -146
- package/lib/schema/ClientEventTypes.d.ts +0 -228
- package/lib/schema/ClientEventTypes.d.ts.map +0 -1
- package/lib/schema/ClientEventTypes.js +0 -41
- package/lib/schema/ClientMetaTypes.d.ts +0 -34
- package/lib/schema/ClientMetaTypes.d.ts.map +0 -1
- package/lib/schema/ClientMetaTypes.js +0 -16
- package/lib/schema/ClientSample.d.ts +0 -1333
- package/lib/schema/ClientSample.d.ts.map +0 -1
- package/lib/schema/ClientSample.js +0 -4
- package/lib/scores/CalculatedScore.d.ts +0 -6
- package/lib/scores/CalculatedScore.d.ts.map +0 -1
- package/lib/scores/CalculatedScore.js +0 -2
- package/lib/scores/DefaultCallScoreCalculator.d.ts +0 -7
- package/lib/scores/DefaultCallScoreCalculator.d.ts.map +0 -1
- package/lib/scores/DefaultCallScoreCalculator.js +0 -21
- package/lib/scores/ScoreCalculator.d.ts +0 -4
- package/lib/scores/ScoreCalculator.d.ts.map +0 -1
- package/lib/scores/ScoreCalculator.js +0 -2
- package/lib/updaters/CallUpdater.d.ts +0 -5
- package/lib/updaters/CallUpdater.d.ts.map +0 -1
- package/lib/updaters/CallUpdater.js +0 -2
- package/lib/updaters/ObserverUpdater.d.ts +0 -5
- package/lib/updaters/ObserverUpdater.d.ts.map +0 -1
- package/lib/updaters/ObserverUpdater.js +0 -2
- package/lib/updaters/OnAllCallObserverUpdater.d.ts +0 -15
- package/lib/updaters/OnAllCallObserverUpdater.d.ts.map +0 -1
- package/lib/updaters/OnAllCallObserverUpdater.js +0 -50
- package/lib/updaters/OnAllClientCallUpdater.d.ts +0 -15
- package/lib/updaters/OnAllClientCallUpdater.d.ts.map +0 -1
- package/lib/updaters/OnAllClientCallUpdater.js +0 -53
- package/lib/updaters/OnAnyCallObserverUpdater.d.ts +0 -12
- package/lib/updaters/OnAnyCallObserverUpdater.d.ts.map +0 -1
- package/lib/updaters/OnAnyCallObserverUpdater.js +0 -37
- package/lib/updaters/OnAnyClientCallUpdater.d.ts +0 -12
- package/lib/updaters/OnAnyClientCallUpdater.d.ts.map +0 -1
- package/lib/updaters/OnAnyClientCallUpdater.js +0 -36
- package/lib/updaters/OnIntervalUpdater.d.ts +0 -10
- package/lib/updaters/OnIntervalUpdater.d.ts.map +0 -1
- package/lib/updaters/OnIntervalUpdater.js +0 -17
- package/lib/updaters/Updater.d.ts +0 -6
- package/lib/updaters/Updater.d.ts.map +0 -1
- package/lib/updaters/Updater.js +0 -2
- package/lib/utils/MediasoupRemoteTrackResolver.d.ts +0 -25
- package/lib/utils/MediasoupRemoteTrackResolver.d.ts.map +0 -1
- package/lib/utils/MediasoupRemoteTrackResolver.js +0 -110
- package/lib/utils/RemoteTrackResolver.d.ts +0 -7
- package/lib/utils/RemoteTrackResolver.d.ts.map +0 -1
- package/lib/utils/RemoteTrackResolver.js +0 -2
- package/src/ObservedCall.ts +0 -308
- package/src/ObservedCallEventMonitor.ts +0 -402
- package/src/ObservedCallSummary.ts +0 -22
- package/src/ObservedCertificate.ts +0 -43
- package/src/ObservedClient.ts +0 -883
- package/src/ObservedClientEventMonitor.ts +0 -309
- package/src/ObservedClientSummary.ts +0 -24
- package/src/ObservedCodec.ts +0 -49
- package/src/ObservedDataChannel.ts +0 -85
- package/src/ObservedIceCandidate.ts +0 -64
- package/src/ObservedIceCandidatePair.ts +0 -134
- package/src/ObservedIceTransport.ts +0 -99
- package/src/ObservedInboundRtp.ts +0 -205
- package/src/ObservedInboundTrack.ts +0 -105
- package/src/ObservedMediaPlayout.ts +0 -49
- package/src/ObservedMediaSource.ts +0 -60
- package/src/ObservedOutboundRtp.ts +0 -156
- package/src/ObservedOutboundTrack.ts +0 -82
- package/src/ObservedPeerConnection.ts +0 -1104
- package/src/ObservedPeerConnectionTransport.ts +0 -38
- package/src/ObservedRemoteInboundRtp.ts +0 -64
- package/src/ObservedRemoteOutboundRtp.ts +0 -65
- package/src/ObservedTURN.ts +0 -86
- package/src/ObservedTurnServer.ts +0 -72
- package/src/Observer.ts +0 -248
- package/src/ObserverEventMonitor.ts +0 -561
- package/src/ObserverSummary.ts +0 -15
- package/src/Reports.ts +0 -87
- package/src/common/Middleware.ts +0 -84
- package/src/common/SingleExecutor.ts +0 -36
- package/src/common/logger.ts +0 -82
- package/src/common/types.ts +0 -4
- package/src/common/utils.ts +0 -69
- package/src/detectors/Detector.ts +0 -6
- package/src/detectors/Detectors.ts +0 -38
- package/src/index.ts +0 -32
- package/src/mediasoup/ObservedMediaRouter.ts +0 -10
- package/src/monitors/TurnUsageMonitor.ts +0 -187
- package/src/schema/ClientEventTypes.ts +0 -280
- package/src/schema/ClientMetaTypes.ts +0 -41
- package/src/schema/ClientSample.ts +0 -1682
- package/src/scores/CalculatedScore.ts +0 -6
- package/src/scores/DefaultCallScoreCalculator.ts +0 -23
- package/src/scores/ScoreCalculator.ts +0 -3
- package/src/updaters/CallUpdater.ts +0 -5
- package/src/updaters/ObserverUpdater.ts +0 -5
- package/src/updaters/OnAllCallObserverUpdater.ts +0 -59
- package/src/updaters/OnAllClientCallUpdater.ts +0 -61
- package/src/updaters/OnAnyCallObserverUpdater.ts +0 -41
- package/src/updaters/OnAnyClientCallUpdater.ts +0 -39
- package/src/updaters/OnIntervalUpdater.ts +0 -19
- package/src/updaters/Updater.ts +0 -5
- package/src/utils/MediasoupRemoteTrackResolver.ts +0 -155
- package/src/utils/RemoteTrackResolver.ts +0 -12
- package/tsconfig.json +0 -19
- package/tslint.json +0 -6
package/llms-full.txt
ADDED
|
@@ -0,0 +1,1536 @@
|
|
|
1
|
+
# observer-js (@observertc/observer-js) — full documentation
|
|
2
|
+
|
|
3
|
+
> Single-file export of the project's documentation for one-shot LLM ingestion.
|
|
4
|
+
> Concatenates: README.md, docs/logging.md, CHANGELOG.md. Generated from source —
|
|
5
|
+
> the canonical, always-current copies live in the repository; see llms.txt for the link index.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# ============================================================================
|
|
10
|
+
# README.md
|
|
11
|
+
# ============================================================================
|
|
12
|
+
|
|
13
|
+
# ObserverTC — `@observertc/observer-js`
|
|
14
|
+
|
|
15
|
+
[](https://www.npmjs.com/package/@observertc/observer-js)
|
|
16
|
+
[](https://github.com/observertc/observer-js/blob/main/LICENSE)
|
|
17
|
+
|
|
18
|
+
> **In one line:** feed it WebRTC `getStats()` snapshots, and get back a live, queryable model of
|
|
19
|
+
> every call plus a single typed event stream to react to.
|
|
20
|
+
|
|
21
|
+
`observer-js` is a **server-side Node.js library for monitoring WebRTC sessions**. A WebRTC
|
|
22
|
+
application (typically an SFU or a signaling/stats backend) feeds it `ClientSample` objects —
|
|
23
|
+
periodic snapshots of each participant's `RTCPeerConnection.getStats()` output plus
|
|
24
|
+
application events — and `observer-js` maintains a live, in-memory model of every call,
|
|
25
|
+
participant, peer connection, and media stream, derives per-interval and cumulative metrics,
|
|
26
|
+
and emits a single, unified stream of typed events the application can react to.
|
|
27
|
+
|
|
28
|
+
**What you can do with it:**
|
|
29
|
+
|
|
30
|
+
- **Monitor calls live** — a queryable in-memory tree of every call, client, peer connection,
|
|
31
|
+
track, codec, ICE candidate and data channel, each holding current **and** cumulative metrics.
|
|
32
|
+
- **React on one event bus** — subscribe once on the `Observer`; every payload carries its full
|
|
33
|
+
ancestry (`call → client → peer connection → stat`), so you never walk the tree to subscribe.
|
|
34
|
+
- **Get derived metrics for free** — counter-reset-safe per-tick deltas, bitrates, jitter, RTT,
|
|
35
|
+
fraction-lost, remote-RTP (RTCP) correlation, and TURN/TCP usage from the selected candidate pair.
|
|
36
|
+
- **Correlate across an SFU** — link a publisher's outbound track to every subscriber's inbound
|
|
37
|
+
track (`RemoteTrackResolver`), and observe mediasoup routers/transports/producers/consumers
|
|
38
|
+
on the server side.
|
|
39
|
+
- **Detect server-only problems** — cross-client `Detector`s raise `call-issue`s for conditions no
|
|
40
|
+
single client can see (e.g. everyone in a call degrading at once).
|
|
41
|
+
- **Persist every sample** — per-client sinks (JSONL file, in-memory, or your own) for archival,
|
|
42
|
+
streaming, and offline replay.
|
|
43
|
+
- **Drop it in safely** — warn-don't-throw, a pluggable logger, dual **ESM + CommonJS**, and **no**
|
|
44
|
+
media-stack dependency in the core.
|
|
45
|
+
|
|
46
|
+
> **Status:** `1.0.0-beta`. The API described here is current and intended to be implemented
|
|
47
|
+
> against directly. This document is written to be self-sufficient: an engineer (or an AI
|
|
48
|
+
> agent) should be able to integrate the library, or develop it further, from this file alone.
|
|
49
|
+
> A companion doc, [`docs/logging.md`](./docs/logging.md), covers logging integration in depth.
|
|
50
|
+
|
|
51
|
+
> **Packaging:** server-side, **Node.js ≥ 22**, shipped as a **dual ESM + CommonJS** build — so it
|
|
52
|
+
> works whether your project uses `import` (ESM) or `require()` (CommonJS). Everything — including
|
|
53
|
+
> the built-in file sink — is exported from the single `@observertc/observer-js` entry.
|
|
54
|
+
|
|
55
|
+
> **For AI agents:** [`llms.txt`](./llms.txt) is a curated map of these docs (with a one-file
|
|
56
|
+
> [`llms-full.txt`](./llms-full.txt) export for one-shot ingestion); [`AGENTS.md`](./AGENTS.md)
|
|
57
|
+
> covers build/test commands and conventions for working **in** this repository. `llms-full.txt`
|
|
58
|
+
> ships in the npm package (so it's available wherever the library is installed); `llms.txt` and
|
|
59
|
+
> `AGENTS.md` live in the repo (and `llms.txt` belongs at the root of the docs site).
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## Table of contents
|
|
64
|
+
|
|
65
|
+
1. [Installation](#installation)
|
|
66
|
+
2. [Quick start](#quick-start)
|
|
67
|
+
3. [Data flow](#data-flow)
|
|
68
|
+
4. [Entity hierarchy](#entity-hierarchy)
|
|
69
|
+
5. [Ingestion: `accept()`, context & lifecycle](#ingestion-accept-context--lifecycle)
|
|
70
|
+
6. [Update policies](#update-policies)
|
|
71
|
+
7. [The event bus](#the-event-bus) ← the core of the API
|
|
72
|
+
8. [API reference](#api-reference)
|
|
73
|
+
9. [Schema types (`ClientSample`)](#schema-types-clientsample)
|
|
74
|
+
10. [Detectors (server-side extension point)](#detectors-server-side-extension-point)
|
|
75
|
+
11. [Remote track resolution (mediasoup / SFU)](#remote-track-resolution-mediasoup--sfu)
|
|
76
|
+
12. [Mediasoup router observation](#mediasoup-router-observation)
|
|
77
|
+
13. [Sinks (per-client sample persistence)](#sinks-per-client-sample-persistence)
|
|
78
|
+
14. [Logging](#logging)
|
|
79
|
+
15. [Error-handling philosophy](#error-handling-philosophy)
|
|
80
|
+
16. [Development & extension guide](#development--extension-guide)
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## Installation
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
npm install @observertc/observer-js
|
|
88
|
+
# or
|
|
89
|
+
yarn add @observertc/observer-js
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
**Server-side, Node.js ≥ 22, dual ESM + CommonJS.** The package ships both module formats, so it
|
|
93
|
+
works the same whether your project is ESM or CommonJS — your import line is unchanged either way:
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { Observer, ClientSample, createJsonlFileSinkFactory } from '@observertc/observer-js';
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
In an ESM project this resolves to the `.mjs` build; in a CommonJS project (where TypeScript
|
|
100
|
+
compiles your `import` down to `require()`) it resolves to the `.js` build. Everything is exported
|
|
101
|
+
from the single `@observertc/observer-js` entry. Written in TypeScript; ships type declarations for
|
|
102
|
+
both formats (`dist/index.d.ts` for `require`, `dist/index.d.mts` for `import`). Runtime
|
|
103
|
+
dependencies: `@bufbuild/protobuf`, `events`, `uuid`. The library does **not** bundle a logger or
|
|
104
|
+
any transport — see [Logging](#logging).
|
|
105
|
+
|
|
106
|
+
`ClientSample` and friends are re-exported from this package, and are also published as the
|
|
107
|
+
shared schema in [`@observertc/schemas`](https://github.com/observertc/schemas); samples
|
|
108
|
+
produced on the client (e.g. by `@observertc/client-monitor-js`) conform to the same shape.
|
|
109
|
+
|
|
110
|
+
---
|
|
111
|
+
|
|
112
|
+
## Quick start
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import { Observer, ClientSample } from '@observertc/observer-js';
|
|
116
|
+
|
|
117
|
+
// 1. Create an observer.
|
|
118
|
+
const observer = new Observer({
|
|
119
|
+
// when the observer aggregates call/client metrics:
|
|
120
|
+
updatePolicy: 'update-when-all-call-updated',
|
|
121
|
+
// default policy applied to calls created automatically by accept():
|
|
122
|
+
defaultCallUpdatePolicy: 'update-on-any-client-updated',
|
|
123
|
+
// optional auto-teardown:
|
|
124
|
+
closeCallIfEmptyForMs: 20_000,
|
|
125
|
+
closeClientIfIdleForMs: 60_000,
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
// 2. Subscribe on the single bus. Every payload is an object with the ancestry.
|
|
129
|
+
observer.on('call-added', ({ observedCall }) => {
|
|
130
|
+
console.log('new call', observedCall.callId);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
observer.on('client-issue', ({ observedClient, issue }) => {
|
|
134
|
+
console.warn(`[${observedClient.clientId}] ${issue.type}`, issue.payload);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
observer.on('peer-connection-updated', ({ observedClient, observedPeerConnection }) => {
|
|
138
|
+
console.log(observedClient.clientId, 'RTT(ms):', observedPeerConnection.currentRttInMs);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
observer.on('sample-rejected', ({ reason, sample }) => {
|
|
142
|
+
console.warn('dropped a sample:', reason);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
// 3. Feed samples. `context` (optional) is transient per-accept data, carried to the
|
|
146
|
+
// `*-updated` events this accept triggers (never written to appData).
|
|
147
|
+
function onClientStats(sample: ClientSample) {
|
|
148
|
+
observer.accept(sample, { studioVersion: '1.2.3' });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// 4. Tear down.
|
|
152
|
+
process.on('SIGINT', () => observer.close());
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## Data flow
|
|
158
|
+
|
|
159
|
+
```
|
|
160
|
+
client getStats() ──► ClientSample ──► observer.accept(sample, ctx?)
|
|
161
|
+
│
|
|
162
|
+
┌────────────────────────────────┘
|
|
163
|
+
▼
|
|
164
|
+
get-or-create ObservedCall ──► get-or-create ObservedClient ──► client.accept(sample, ctx)
|
|
165
|
+
│
|
|
166
|
+
per peerConnections[] in the sample
|
|
167
|
+
▼
|
|
168
|
+
get-or-create ObservedPeerConnection
|
|
169
|
+
.accept(pcSample, ctx) updates all sub-stats,
|
|
170
|
+
derives deltas/bitrates/RTT, correlates remote RTP
|
|
171
|
+
│
|
|
172
|
+
metrics roll up: PeerConnection → Client → Call → Observer
|
|
173
|
+
│
|
|
174
|
+
events emitted on the Observer bus ──► your handlers
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
- A sample **must** have `callId` and `clientId` (the library sets them, or the app does). If
|
|
178
|
+
either is missing, the sample is dropped and `sample-rejected` is emitted.
|
|
179
|
+
- Sub-entities that stop appearing in samples are garbage-collected via a "visited"
|
|
180
|
+
mark-and-sweep on each `ObservedPeerConnection.accept()`, emitting the corresponding
|
|
181
|
+
`*-removed` events.
|
|
182
|
+
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
## Entity hierarchy
|
|
186
|
+
|
|
187
|
+
| Class | Created by | Keyed on its parent as | Holds |
|
|
188
|
+
|-------|-----------|------------------------|-------|
|
|
189
|
+
| `Observer` | `new Observer(config?)` | — (root) | `observedCalls: Map<string, ObservedCall>`, global counters, the event bus |
|
|
190
|
+
| `ObservedCall` | `observer.createObservedCall(settings)` / lazily by `accept` | `observedCalls` | `observedClients: Map<string, ObservedClient>`, call-wide metrics, `detectors`, `scoreCalculator` |
|
|
191
|
+
| `ObservedClient` | `call.createObservedClient(settings)` / lazily | `observedClients` | `observedPeerConnections: Map<string, ObservedPeerConnection>`, per-client metrics |
|
|
192
|
+
| `ObservedPeerConnection` | lazily, from `sample.peerConnections[]` | `observedPeerConnections` | the 15 sub-stat maps below, transport/RTT/bitrate metrics |
|
|
193
|
+
| Sub-stats | lazily, from the `PeerConnectionSample` | maps on the PC | individual WebRTC stat objects |
|
|
194
|
+
|
|
195
|
+
`ObservedPeerConnection` sub-stat maps (all `public readonly`):
|
|
196
|
+
|
|
197
|
+
```
|
|
198
|
+
observedCertificates, observedCodecs, observedDataChannels,
|
|
199
|
+
observedIceCandidates, observedIceCandidatesPair, observedIceTransports,
|
|
200
|
+
observedInboundRtps, observedInboundTracks, observedMediaPlayouts,
|
|
201
|
+
observedMediaSources, observedOutboundRtps, observedOutboundTracks,
|
|
202
|
+
observedPeerConnectionTransports, observedRemoteInboundRtps, observedRemoteOutboundRtps
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Each sub-stat class (`ObservedInboundRtp`, `ObservedOutboundRtp`, `ObservedInboundTrack`,
|
|
206
|
+
`ObservedOutboundTrack`, `ObservedDataChannel`, `ObservedIceCandidate`,
|
|
207
|
+
`ObservedIceCandidatePair`, `ObservedIceTransport`, `ObservedCertificate`, `ObservedCodec`,
|
|
208
|
+
`ObservedMediaSource`, `ObservedMediaPlayout`, `ObservedPeerConnectionTransport`,
|
|
209
|
+
`ObservedRemoteInboundRtp`, `ObservedRemoteOutboundRtp`) mirrors the corresponding stat
|
|
210
|
+
fields from the schema plus derived fields (deltas, bitrates).
|
|
211
|
+
|
|
212
|
+
---
|
|
213
|
+
|
|
214
|
+
## Ingestion: `accept()`, context & lifecycle
|
|
215
|
+
|
|
216
|
+
### `observer.accept(sample, context?)`
|
|
217
|
+
|
|
218
|
+
The single entry point. It:
|
|
219
|
+
|
|
220
|
+
1. drops + emits `sample-rejected` if the observer is closed;
|
|
221
|
+
2. runs the sample through the **global accept-middleware chain** (see below);
|
|
222
|
+
3. (chain terminal) drops + emits `sample-rejected` if `callId`/`clientId` is missing;
|
|
223
|
+
4. gets or lazily creates the `ObservedCall` and `ObservedClient` (their `appData` comes from the
|
|
224
|
+
configured factories, never from `context`);
|
|
225
|
+
5. delegates to `client.accept(sample, context)`, which fans out to each
|
|
226
|
+
`ObservedPeerConnection.accept(pcSample, context)`.
|
|
227
|
+
|
|
228
|
+
### Accept middlewares (global pre-dispatch hook)
|
|
229
|
+
|
|
230
|
+
`observer.addAcceptMiddleware(...)` registers middlewares run on **every** sample inside
|
|
231
|
+
`accept()`, in order, **before** the sample is dispatched to any call or client. Each middleware
|
|
232
|
+
gets a `{ sample, context }` payload; it can inspect or mutate the sample (set/normalize
|
|
233
|
+
`callId`/`clientId`, enrich, redact) or the context, then call `next(payload)` to continue.
|
|
234
|
+
**Not calling `next` drops the sample** — nothing is created and no event fires. A throwing
|
|
235
|
+
middleware is caught and warns (the sample is dropped), never crashing `accept()`.
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
import { Observer, AcceptMiddleware } from '@observertc/observer-js';
|
|
239
|
+
|
|
240
|
+
const observer = new Observer();
|
|
241
|
+
|
|
242
|
+
// derive callId/clientId from the app's own attachment, before dispatch
|
|
243
|
+
const route: AcceptMiddleware = ({ sample }, next) => {
|
|
244
|
+
sample.callId ??= sample.attachments?.roomId as string;
|
|
245
|
+
sample.clientId ??= sample.attachments?.peerId as string;
|
|
246
|
+
next({ sample });
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
// drop samples from a blocklisted client (never dispatched)
|
|
250
|
+
const filter: AcceptMiddleware = (payload, next) => {
|
|
251
|
+
if (blocked.has(payload.sample.clientId)) return; // no next() => dropped
|
|
252
|
+
next(payload);
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
observer.addAcceptMiddleware(route, filter);
|
|
256
|
+
// observer.removeAcceptMiddleware(route);
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
This is a lightweight global injection point, distinct from the larger (not-yet-built)
|
|
260
|
+
`ClientSampleProcessor` pipeline in the roadmap. When no middleware is registered, `accept()`
|
|
261
|
+
dispatches directly with no overhead.
|
|
262
|
+
|
|
263
|
+
### `context` (the `AcceptContext`)
|
|
264
|
+
|
|
265
|
+
```ts
|
|
266
|
+
type AcceptContext = Record<string, unknown>;
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
A single, optional, free-form object threaded down the whole accept chain
|
|
270
|
+
(`Observer → Client → PeerConnection`). It is **transient request-scoped data** — temporary or
|
|
271
|
+
contextual information the application wants available while an update is processed.
|
|
272
|
+
|
|
273
|
+
`context` is **never written to `appData`** and is **not stored** on any entity. The two are
|
|
274
|
+
deliberately distinct:
|
|
275
|
+
|
|
276
|
+
- **`appData`** — application-assigned extra info that identifies/decorates an entity, fixed at
|
|
277
|
+
creation (via `settings.appData` or the `createCallAppData` / `createClientAppData` factories),
|
|
278
|
+
or assigned by the app on the `*-added` events. The library never changes it.
|
|
279
|
+
- **`context`** — passed per `accept()`, may differ on every call, and is carried straight
|
|
280
|
+
through to the `*-updated` events that the `accept()` triggers, then discarded.
|
|
281
|
+
|
|
282
|
+
`client-updated` and `peer-connection-updated` carry the exact context of that sample;
|
|
283
|
+
`call-updated` carries the context of the client `accept()` that drove the call update (absent
|
|
284
|
+
for interval- or teardown-driven call updates). When no context is given, the field is absent.
|
|
285
|
+
|
|
286
|
+
### Get-or-create helpers
|
|
287
|
+
|
|
288
|
+
If you want to create/configure entities yourself before/without samples:
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
const call = observer.getOrCreateObservedCall({ callId, appData }); // ObservedCall | undefined
|
|
292
|
+
const client = call?.getOrCreateObservedClient({ clientId, appData }); // ObservedClient | undefined
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
These return `undefined` (and warn) when the parent is closed; `createObservedCall`/
|
|
296
|
+
`createObservedClient` return the **existing** instance (and warn) if the id already exists.
|
|
297
|
+
|
|
298
|
+
### Automatic teardown
|
|
299
|
+
|
|
300
|
+
- `closeClientIfIdleForMs` — a client with no sample for this long auto-closes.
|
|
301
|
+
- `closeCallIfEmptyForMs` — a call with zero clients for this long auto-closes.
|
|
302
|
+
- Closing cascades down (call → clients → peer connections → sub-stats), unsubscribing
|
|
303
|
+
listeners and emitting the `*-closed` / `*-removed` events.
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
## Update policies
|
|
308
|
+
|
|
309
|
+
"Update" means *recompute aggregated metrics and emit the `*-updated` event* at that level.
|
|
310
|
+
Both the observer and each call have a configurable trigger. Updates are **event-driven** — there
|
|
311
|
+
is no built-in timer. An app that wants a fixed cadence can call `observer.update()` /
|
|
312
|
+
`call.update()` from its own `setInterval`. With `'none'`, **nothing auto-updates** — the level
|
|
313
|
+
updates only when the application calls the public `update()` itself.
|
|
314
|
+
|
|
315
|
+
**Observer-level** (`ObserverConfig.updatePolicy`, default `update-when-all-call-updated`):
|
|
316
|
+
|
|
317
|
+
| Policy | Triggers `observer.update()` when… |
|
|
318
|
+
|--------|-------------------------------------|
|
|
319
|
+
| `update-on-any-call-updated` | any call updates |
|
|
320
|
+
| `update-when-all-call-updated` | every call has updated since the last observer update |
|
|
321
|
+
| `none` | never automatically — only when the app calls `observer.update()` |
|
|
322
|
+
|
|
323
|
+
**Call-level** (`ObservedCallSettings.updatePolicy`, defaulted from
|
|
324
|
+
`ObserverConfig.defaultCallUpdatePolicy`):
|
|
325
|
+
|
|
326
|
+
| Policy | Triggers `call.update()` when… |
|
|
327
|
+
|--------|--------------------------------|
|
|
328
|
+
| `update-on-any-client-updated` | any client in the call updates |
|
|
329
|
+
| `update-when-all-client-updated` | every client has updated since the last call update |
|
|
330
|
+
| `none` | never automatically — only when the app calls `call.update()` |
|
|
331
|
+
|
|
332
|
+
---
|
|
333
|
+
|
|
334
|
+
## The event bus
|
|
335
|
+
|
|
336
|
+
This is the primary API. **Subscribe on the `Observer` instance** — it is the single emitter
|
|
337
|
+
for the entire hierarchy. The `ObservedCall` / `ObservedClient` / `ObservedPeerConnection`
|
|
338
|
+
objects are themselves `EventEmitter`s too, but those local events are reserved for internal
|
|
339
|
+
lifecycle/teardown wiring (see [Local lifecycle events](#local-lifecycle-events)); application
|
|
340
|
+
code should use the Observer bus.
|
|
341
|
+
|
|
342
|
+
### Payload shape: ancestry + subject
|
|
343
|
+
|
|
344
|
+
Every Observer event delivers exactly **one argument: a payload object**. The payload always
|
|
345
|
+
contains the ancestry from the observer down to the entity that raised it, plus any event-
|
|
346
|
+
specific subject:
|
|
347
|
+
|
|
348
|
+
```ts
|
|
349
|
+
type ObserverEventBase = { observer: Observer };
|
|
350
|
+
type ObservedCallScope = ObserverEventBase & { observedCall: ObservedCall };
|
|
351
|
+
type ObservedClientScope = ObservedCallScope & { observedClient: ObservedClient };
|
|
352
|
+
type ObservedPeerConnectionScope = ObservedClientScope & { observedPeerConnection: ObservedPeerConnection };
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
So a peer-connection-level event hands you the observer, call, client, **and** peer connection:
|
|
356
|
+
|
|
357
|
+
```ts
|
|
358
|
+
observer.on('inbound-rtp-added', ({ observer, observedCall, observedClient, observedPeerConnection, observedInboundRtp }) => {
|
|
359
|
+
// all five are present and correctly typed
|
|
360
|
+
});
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
`observer.on/off/once/emit` are fully typed against the event map — the handler argument is
|
|
364
|
+
inferred per event name.
|
|
365
|
+
|
|
366
|
+
### Event catalogue
|
|
367
|
+
|
|
368
|
+
All payloads include the ancestry for their level (above). The **Extra** column lists the
|
|
369
|
+
additional field(s) on top of that scope.
|
|
370
|
+
|
|
371
|
+
#### Observer level — scope `{ observer }`
|
|
372
|
+
|
|
373
|
+
| Event | Extra payload | Fires when |
|
|
374
|
+
|-------|---------------|-----------|
|
|
375
|
+
| `observer-updated` | — | `observer.update()` ran (per the observer update policy) |
|
|
376
|
+
| `observer-closed` | — | `observer.close()` |
|
|
377
|
+
| `sample-rejected` | `{ reason: 'observer-closed' \| 'missing-callId' \| 'missing-clientId', sample: ClientSample }` | a sample was dropped by `accept()` |
|
|
378
|
+
|
|
379
|
+
#### Mediasoup level — scope `{ observer, observedMediasoupRouter }`
|
|
380
|
+
|
|
381
|
+
| Event | Extra | Fires when |
|
|
382
|
+
|-------|-------|-----------|
|
|
383
|
+
| `mediasoup-router-added` | — | `observer.createObservedMediasoupRouter(...)` registered a router |
|
|
384
|
+
| `mediasoup-router-matched-with-peer-connection` | `{ observedCall, observedClient, observedPeerConnection }` | a newly added peer connection's id matched one of the router's WebRTC transport ids. |
|
|
385
|
+
| `mediasoup-router-removed` | — | the underlying mediasoup router closed (its `router.observer` `close` fired) |
|
|
386
|
+
|
|
387
|
+
See [Mediasoup router observation](#mediasoup-router-observation) for the full design and examples.
|
|
388
|
+
|
|
389
|
+
#### Call level — scope `{ observer, observedCall }`
|
|
390
|
+
|
|
391
|
+
| Event | Extra | Fires when |
|
|
392
|
+
|-------|-------|-----------|
|
|
393
|
+
| `call-added` | — | a call is created |
|
|
394
|
+
| `call-updated` | `{ context?: AcceptContext }` | `call.update()` ran |
|
|
395
|
+
| `call-closed` | — | the call closed |
|
|
396
|
+
| `call-empty` | — | last client left the call |
|
|
397
|
+
| `call-not-empty` | — | first client joined a previously-empty call |
|
|
398
|
+
| `call-issue` | `{ issue: ClientIssue }` | `call.addIssue(...)` (server-side detector finding) |
|
|
399
|
+
|
|
400
|
+
#### Client level — scope `{ observer, observedCall, observedClient }`
|
|
401
|
+
|
|
402
|
+
| Event | Extra | Fires when |
|
|
403
|
+
|-------|-------|-----------|
|
|
404
|
+
| `client-added` | — | a client is created |
|
|
405
|
+
| `client-sink-created` | `{ sink: ClientSampleSink }` | a per-client sink was created (only when `createClientSink` returns one); fires right after `client-added` |
|
|
406
|
+
| `client-updated` | `{ sample: ClientSample, elapsedTimeInMs: number, context?: AcceptContext }` | the client processed a sample |
|
|
407
|
+
| `client-closed` | — | the client closed |
|
|
408
|
+
| `client-joined` | — | first `CLIENT_JOINED` event seen |
|
|
409
|
+
| `client-left` | — | `CLIENT_LEFT` seen (or inferred on close) |
|
|
410
|
+
| `client-rejoined` | `{ timestamp: number }` | a later `CLIENT_JOINED` after an earlier join |
|
|
411
|
+
| `client-issue` | `{ issue: ClientIssue }` | a client-reported issue arrived, or `client.addIssue(...)` |
|
|
412
|
+
| `client-metadata` | `{ metaData: ClientMetaData }` | a client meta item arrived |
|
|
413
|
+
| `client-extension-stats` | `{ extensionStats: ExtensionStat }` | an app-defined extension stat arrived |
|
|
414
|
+
| `client-event` | `{ event: ClientEvent }` | any client event was processed |
|
|
415
|
+
|
|
416
|
+
#### Peer-connection level — scope `{ observer, observedCall, observedClient, observedPeerConnection }`
|
|
417
|
+
|
|
418
|
+
| Event | Extra | Notes |
|
|
419
|
+
|-------|-------|-------|
|
|
420
|
+
| `peer-connection-added` / `peer-connection-closed` | — | lifecycle of the PC |
|
|
421
|
+
| `peer-connection-updated` | `{ context?: AcceptContext }` | the PC processed a sample |
|
|
422
|
+
| `ice-connection-state-changed` / `ice-gathering-state-changed` / `connection-state-changed` | `{ state: string }` | driven by client events |
|
|
423
|
+
| `selected-candidate-pair-changed` | — | *declared; not currently emitted* |
|
|
424
|
+
| `inbound-track-added` / `-updated` / `-removed` / `-muted` / `-unmuted` | `{ observedInboundTrack }` | |
|
|
425
|
+
| `outbound-track-added` / `-updated` / `-removed` / `-muted` / `-unmuted` | `{ observedOutboundTrack }` | |
|
|
426
|
+
| `inbound-rtp-added` / `-updated` / `-removed` | `{ observedInboundRtp }` | `-updated` fires every tick |
|
|
427
|
+
| `outbound-rtp-added` / `-updated` / `-removed` | `{ observedOutboundRtp }` | `-updated` fires every tick |
|
|
428
|
+
| `remote-inbound-rtp-added` / `-updated` / `-removed` | `{ observedRemoteInboundRtp }` | |
|
|
429
|
+
| `remote-outbound-rtp-added` / `-updated` / `-removed` | `{ observedRemoteOutboundRtp }` | |
|
|
430
|
+
| `data-channel-added` / `-updated` / `-removed` | `{ observedDataChannel }` | |
|
|
431
|
+
| `ice-candidate-added` / `-updated` / `-removed` | `{ observedIceCandidate }` | |
|
|
432
|
+
| `ice-candidate-pair-added` / `-updated` / `-removed` | `{ observedIceCandidatePair }` | |
|
|
433
|
+
| `ice-transport-added` / `-updated` / `-removed` | `{ observedIceTransport }` | |
|
|
434
|
+
| `codec-added` / `-updated` / `-removed` | `{ observedCodec }` | |
|
|
435
|
+
| `media-source-added` / `-updated` / `-removed` | `{ observedMediaSource }` | |
|
|
436
|
+
| `media-playout-added` / `-updated` / `-removed` | `{ observedMediaPlayout }` | |
|
|
437
|
+
| `peer-connection-transport-added` / `-updated` / `-removed` | `{ observedPeerConnectionTransport }` | |
|
|
438
|
+
| `certificate-added` / `-updated` / `-removed` | `{ observedCertificate }` | |
|
|
439
|
+
|
|
440
|
+
> **Volume note.** The `*-updated` sub-stat events fire on every peer-connection `accept()`
|
|
441
|
+
> (i.e. per sample, per stream). For high-throughput servers, subscribe only to what you need,
|
|
442
|
+
> or read fields off the entities on `client-updated` / `call-updated` instead.
|
|
443
|
+
|
|
444
|
+
### Local lifecycle events
|
|
445
|
+
|
|
446
|
+
These remain on the individual entities (not the bus), for teardown/coordination. You can
|
|
447
|
+
listen to them, but prefer the bus equivalents above for application logic.
|
|
448
|
+
|
|
449
|
+
| Entity | Local events |
|
|
450
|
+
|--------|--------------|
|
|
451
|
+
| `ObservedCall` | `update`, `newclient`, `empty`, `not-empty`, `close` |
|
|
452
|
+
| `ObservedClient` | `update` (`sample`, `elapsedTimeInMs`), `close`, `joined`, `left` |
|
|
453
|
+
| `ObservedPeerConnection` | `removed-inbound-track`, `removed-outbound-track`, `close` |
|
|
454
|
+
|
|
455
|
+
---
|
|
456
|
+
|
|
457
|
+
## API reference
|
|
458
|
+
|
|
459
|
+
### `Observer`
|
|
460
|
+
|
|
461
|
+
```ts
|
|
462
|
+
new Observer<AppData>(config?: ObserverConfig<AppData>)
|
|
463
|
+
|
|
464
|
+
type ObserverConfig<AppData = Record<string, unknown>> = {
|
|
465
|
+
updatePolicy?: 'update-on-any-call-updated' | 'update-when-all-call-updated' | 'none';
|
|
466
|
+
defaultCallUpdatePolicy?: ObservedCallSettings['updatePolicy'];
|
|
467
|
+
appData?: AppData;
|
|
468
|
+
closeClientIfIdleForMs?: number;
|
|
469
|
+
closeCallIfEmptyForMs?: number;
|
|
470
|
+
// appData factories — run when an entity is created without explicit appData
|
|
471
|
+
// (incl. lazily by accept()). appData is application-owned; accept `context` never touches it.
|
|
472
|
+
createCallAppData?: (p: { callId: string; observer: Observer }) => Record<string, unknown>;
|
|
473
|
+
createClientAppData?: (p: { clientId: string; observedCall: ObservedCall }) => Record<string, unknown>;
|
|
474
|
+
// sink factory — produces a per-client sink that receives every accepted sample (see Sinks).
|
|
475
|
+
createClientSink?: (p: { clientId: string; observedCall: ObservedCall }) => ClientSampleSink | undefined;
|
|
476
|
+
// track-resolver factory — produces a call's RemoteTrackResolver (see Remote track resolution).
|
|
477
|
+
createTrackResolver?: (observedCall: ObservedCall) => RemoteTrackResolver | undefined;
|
|
478
|
+
};
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
**appData factories.** Instead of pre-creating a call/client (or assigning on `call-added` /
|
|
482
|
+
`client-added`) just to enrich its `appData`, register a factory once. It runs in the entity's
|
|
483
|
+
constructor whenever it's created without an explicit `settings.appData` — including the lazy
|
|
484
|
+
creation inside `accept()`. The `client` factory receives the already-created parent
|
|
485
|
+
`observedCall`, so it can derive fields from it. `appData` is application-owned and is never
|
|
486
|
+
modified by the `accept()` context.
|
|
487
|
+
|
|
488
|
+
```ts
|
|
489
|
+
const observer = new Observer({
|
|
490
|
+
createCallAppData: ({ callId }) => ({ callId, startedAt: Date.now(), region: 'eu' }),
|
|
491
|
+
createClientAppData: ({ clientId, observedCall }) => ({ clientId, region: observedCall.appData.region }),
|
|
492
|
+
});
|
|
493
|
+
```
|
|
494
|
+
|
|
495
|
+
Key members:
|
|
496
|
+
|
|
497
|
+
- `accept(sample: ClientSample, context?: AcceptContext): void`
|
|
498
|
+
- `addAcceptMiddleware(...mw: AcceptMiddleware[]): this` / `removeAcceptMiddleware(...mw): this` — global pre-dispatch sample hooks (see [Accept middlewares](#accept-middlewares-global-pre-dispatch-hook))
|
|
499
|
+
- `getObservedCall<T>(callId): ObservedCall<T> | undefined`
|
|
500
|
+
- `createObservedCall<T>(settings): ObservedCall<T> | undefined`
|
|
501
|
+
- `getOrCreateObservedCall<T>(settings): ObservedCall<T> | undefined`
|
|
502
|
+
- `update(): void` — force an aggregation/`observer-updated` tick
|
|
503
|
+
- `close(): void`
|
|
504
|
+
- `readonly observedCalls: Map<string, ObservedCall>`
|
|
505
|
+
- `readonly observedTURN: ObservedTURN`
|
|
506
|
+
- `get appData()`, `get numberOfCalls()`
|
|
507
|
+
- counters: `numberOfClients`, `numberOfClientsUsingTurn`, `numberOfInboundRtpStreams`,
|
|
508
|
+
`numberOfOutboundRtpStreams`, `numberOfDataChannels`, `numberOfPeerConnections`,
|
|
509
|
+
`totalAddedCall`, `totalRemovedCall`, `closed`
|
|
510
|
+
- `on/off/once/emit` typed against the [event map](#event-catalogue)
|
|
511
|
+
|
|
512
|
+
### `ObservedCall`
|
|
513
|
+
|
|
514
|
+
```ts
|
|
515
|
+
type ObservedCallSettings<AppData = Record<string, unknown>> = {
|
|
516
|
+
updatePolicy?: 'update-on-any-client-updated' | 'update-when-all-client-updated' | 'none';
|
|
517
|
+
callId: string;
|
|
518
|
+
appData?: AppData;
|
|
519
|
+
closeCallIfEmptyForMs?: number;
|
|
520
|
+
};
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
Key members:
|
|
524
|
+
|
|
525
|
+
- `readonly callId: string`, `appData: AppData`
|
|
526
|
+
- `readonly observedClients: Map<string, ObservedClient>`, `get numberOfClients()`
|
|
527
|
+
- `getObservedClient<T>(clientId)`, `createObservedClient<T>(settings)`, `getOrCreateObservedClient<T>(settings)` (all `… | undefined`)
|
|
528
|
+
- `addIssue(issue: ClientIssue): void` — raise a **call-level** issue → emits `call-issue`
|
|
529
|
+
- `readonly detectors: Detectors` — server-side detector registry (empty by default; see [Detectors](#detectors-server-side-extension-point))
|
|
530
|
+
- `scoreCalculator: ScoreCalculator`, `get score()`, `readonly calculatedScore`
|
|
531
|
+
- `remoteTrackResolver?: RemoteTrackResolver` — set from `ObserverConfig.createTrackResolver` at call creation (see [Remote track resolution](#remote-track-resolution-mediasoup--sfu))
|
|
532
|
+
- aggregates: `numberOfIssues`, `numberOfPeerConnections`, `numberOfInboundRtpStreams`,
|
|
533
|
+
`numberOfOutboundRtpStreams`, `numberOfDataChannels`, `maxNumberOfClients`,
|
|
534
|
+
`clientsUsedTurn: Set<string>`, `startedAt?`, `endedAt?`, `closedAt?`, `closed`
|
|
535
|
+
- `update()`, `close()`
|
|
536
|
+
|
|
537
|
+
### `ObservedClient`
|
|
538
|
+
|
|
539
|
+
```ts
|
|
540
|
+
type ObservedClientSettings<AppData = Record<string, unknown>> = {
|
|
541
|
+
clientId: string;
|
|
542
|
+
appData?: AppData;
|
|
543
|
+
closeClientIfIdleForMs?: number;
|
|
544
|
+
};
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
Key members:
|
|
548
|
+
|
|
549
|
+
- `readonly clientId: string`, `appData: AppData`, `readonly call: ObservedCall`
|
|
550
|
+
- `readonly observedPeerConnections: Map<string, ObservedPeerConnection>`
|
|
551
|
+
- `readonly sink?: ClientSampleSink` — the per-client sink (see [Sinks](#sinks-per-client-sample-persistence)), if `createClientSink` is configured; listen on it for `close`/`error`
|
|
552
|
+
- **Injection API** (queue app data to be merged into the next sample processing):
|
|
553
|
+
`injectEvent(ClientEvent)`, `injectIssue(ClientIssue)`, `injectMetaData(ClientMetaData)`,
|
|
554
|
+
`injectExtensionStat(ExtensionStat)`, `injectAttachment(key, value)`
|
|
555
|
+
- **Direct add API** (process immediately): `addIssue(ClientIssue)`, `addMetadata(ClientMetaData)`,
|
|
556
|
+
`addExtensionStats(ExtensionStat)`
|
|
557
|
+
- Metrics (current/derived): `currentAvgRttInMs?`, `currentMinRttInMs?`, `currentMaxRttInMs?`,
|
|
558
|
+
`receivingAudioBitrate`, `receivingVideoBitrate`, `sendingAudioBitrate`, `sendingVideoBitrate`,
|
|
559
|
+
`usingTURN`, `usingTCP`, `availableIncomingBitrate`, `availableOutgoingBitrate`
|
|
560
|
+
- Counts: `numberOfInboundRtpStreams`, `numberOfOutboundRtpStreams`, `numberOfInbundTracks`,
|
|
561
|
+
`numberOfOutboundTracks`, `numberOfDataChannels`, `numberOfPeerConnections`
|
|
562
|
+
- Per-tick deltas: `deltaReceivedAudioBytes`, `deltaSentAudioBytes`, … (see source for the full set)
|
|
563
|
+
- Lifecycle: `joinedAt?`, `leftAt?`, `closedAt?`, `closed`, `get score()`
|
|
564
|
+
- Metadata: `browser?`, `engine?`, `platform?`, `operationSystem?`, `mediaDevices`, `mediaConstraints`
|
|
565
|
+
- `accept(sample, context?)`, `close()`
|
|
566
|
+
|
|
567
|
+
### `ObservedPeerConnection`
|
|
568
|
+
|
|
569
|
+
Key members:
|
|
570
|
+
|
|
571
|
+
- `readonly peerConnectionId: string`, `readonly client: ObservedClient`, `appData?`
|
|
572
|
+
- The 15 `observed*` sub-stat `Map`s (listed [above](#entity-hierarchy)), plus array getters:
|
|
573
|
+
`codecs`, `inboundRtps`, `outboundRtps`, `remoteInboundRtps`, `remoteOutboundRtps`,
|
|
574
|
+
`mediaSources`, `mediaPlayouts`, `dataChannels`, `peerConnectionTransports`, `iceTransports`,
|
|
575
|
+
`iceCandidates`, `iceCandidatePairs`, `certificates`, `selectedIceCandidatePairs`,
|
|
576
|
+
`selectedIceCandiadtePairForTurn`
|
|
577
|
+
- State: `connectionState?`, `iceConnectionState?`, `iceGatheringState?`, `usingTURN`, `usingTCP`
|
|
578
|
+
- Metrics: `currentRttInMs?`, `currentJitter?`, `availableIncomingBitrate`,
|
|
579
|
+
`availableOutgoingBitrate`, sending/receiving bitrates, packet rates, and `total*` / `delta*`
|
|
580
|
+
byte/packet counters
|
|
581
|
+
- `accept(pcSample, context?)`, `close()`, `get score()`
|
|
582
|
+
|
|
583
|
+
**Remote-RTP correlation (derived).** During `accept()`, receiver/sender reports are linked
|
|
584
|
+
to the local streams by `remoteId` (fallback SSRC) and surfaced as fields:
|
|
585
|
+
|
|
586
|
+
- on `ObservedOutboundRtp`: `remoteRttInMs?`, `remoteFractionLost?`, `remoteJitter?`, `remotePacketsLost?`
|
|
587
|
+
- on `ObservedInboundRtp`: `remoteRttInMs?`, `remoteBytesSent?`, `remotePacketsSent?`, `remoteTimestamp?`
|
|
588
|
+
|
|
589
|
+
These are reset each tick and only set when the matching remote report is present.
|
|
590
|
+
|
|
591
|
+
---
|
|
592
|
+
|
|
593
|
+
## Schema types (`ClientSample`)
|
|
594
|
+
|
|
595
|
+
The shape of an accepted sample (re-exported from this package; identical to
|
|
596
|
+
`@observertc/schemas`). Only the top level is shown — each stat object mirrors the standard
|
|
597
|
+
WebRTC `getStats()` dictionaries plus a few extensions.
|
|
598
|
+
|
|
599
|
+
```ts
|
|
600
|
+
type ClientSample = {
|
|
601
|
+
timestamp: number; // client wall-clock (ms epoch)
|
|
602
|
+
callId?: string; // set by you or the library
|
|
603
|
+
clientId?: string; // set by you or the library
|
|
604
|
+
score?: number; // optional client-computed score (0..5)
|
|
605
|
+
attachments?: Record<string, unknown>;
|
|
606
|
+
peerConnections?: PeerConnectionSample[];
|
|
607
|
+
clientEvents?: ClientEvent[];
|
|
608
|
+
clientIssues?: ClientIssue[];
|
|
609
|
+
clientMetaItems?: ClientMetaData[];
|
|
610
|
+
extensionStats?: ExtensionStat[];
|
|
611
|
+
};
|
|
612
|
+
|
|
613
|
+
type PeerConnectionSample = {
|
|
614
|
+
peerConnectionId: string;
|
|
615
|
+
attachments?: Record<string, unknown>; // e.g. { direction: 'send'|'recv', producerId, consumerId, label }
|
|
616
|
+
score?: number;
|
|
617
|
+
inboundTracks?; outboundTracks?;
|
|
618
|
+
codecs?;
|
|
619
|
+
inboundRtps?; remoteInboundRtps?;
|
|
620
|
+
outboundRtps?; remoteOutboundRtps?;
|
|
621
|
+
mediaSources?; mediaPlayouts?;
|
|
622
|
+
peerConnectionTransports?; dataChannels?;
|
|
623
|
+
iceTransports?; iceCandidates?; iceCandidatePairs?;
|
|
624
|
+
certificates?;
|
|
625
|
+
};
|
|
626
|
+
|
|
627
|
+
type ClientEvent = { type: string; payload?: string; timestamp?: number; /* +ids */ };
|
|
628
|
+
type ClientIssue = { type: string; payload?: string; timestamp?: number }; // also used for call-issue
|
|
629
|
+
type ClientMetaData = { type: string; payload?: string; timestamp?: number; /* +ids */ };
|
|
630
|
+
type ExtensionStat = { type: string; payload?: string };
|
|
631
|
+
```
|
|
632
|
+
|
|
633
|
+
`payload` fields are JSON strings; the library parses the ones it understands.
|
|
634
|
+
|
|
635
|
+
**`ClientEventTypes`** (enum of known `event.type` values): `CLIENT_JOINED`, `CLIENT_LEFT`,
|
|
636
|
+
`PEER_CONNECTION_OPENED/CLOSED/STATE_CHANGED`, `MEDIA_TRACK_ADDED/REMOVED/MUTED/UNMUTED/RESUMED`,
|
|
637
|
+
`ICE_GATHERING_STATE_CHANGED`, `ICE_CONNECTION_STATE_CHANGED`, `DATA_CHANNEL_OPEN/CLOSED/ERROR`,
|
|
638
|
+
`NEGOTIATION_NEEDED`, `SIGNALING_STATE_CHANGE`, `ICE_CANDIDATE`, `ICE_CANDIDATE_ERROR`, and the
|
|
639
|
+
mediasoup set `PRODUCER_*` / `CONSUMER_*` / `DATA_PRODUCER_*` / `DATA_CONSUMER_*`.
|
|
640
|
+
|
|
641
|
+
**`ClientMetaTypes`** (enum of known meta `type` values): `MEDIA_CONSTRAINT`, `MEDIA_DEVICE`,
|
|
642
|
+
`MEDIA_DEVICES_SUPPORTED_CONSTRAINTS`, `USER_MEDIA_ERROR`, `LOCAL_SDP`, `OPERATION_SYSTEM`,
|
|
643
|
+
`ENGINE`, `PLATFORM`, `BROWSER`.
|
|
644
|
+
|
|
645
|
+
### Worked example: a real `ClientSample`
|
|
646
|
+
|
|
647
|
+
Two consecutive samples from one participant ("Guest" in room `qq0iwfnd`) of an
|
|
648
|
+
edumeet/mediasoup call show what actually flows through `accept()`: a rich **join snapshot**,
|
|
649
|
+
then lean **steady-state ticks**.
|
|
650
|
+
|
|
651
|
+
**Sample 1 — the join snapshot.** Carries the one-off lifecycle `clientEvents` and device
|
|
652
|
+
`clientMetaItems` alongside the first stats. (Abbreviated; ids and times are from the real log.)
|
|
653
|
+
|
|
654
|
+
```jsonc
|
|
655
|
+
{
|
|
656
|
+
"timestamp": 1780572332518,
|
|
657
|
+
"callId": "d3dbf2f5-79be-4cb8-9d43-fb404f07ef27",
|
|
658
|
+
"clientId": "c926983c-4468-4046-ae8c-a9cabe1a1868",
|
|
659
|
+
"score": 0, // no quality measured yet on the join tick
|
|
660
|
+
"attachments": { "displayName": "Guest", "roomId": "qq0iwfnd", "actualSessionId": "d3dbf2f5-…" },
|
|
661
|
+
|
|
662
|
+
"clientEvents": [ // chronological lifecycle (12 in the real sample)
|
|
663
|
+
{ "type": "CLIENT_JOINED", "timestamp": 1780572324515 },
|
|
664
|
+
{ "type": "PEER_CONNECTION_OPENED", "timestamp": 1780572326790 }, // pc=b81c8d9d (media)
|
|
665
|
+
{ "type": "ICE_GATHERING_STATE_CHANGED", "timestamp": 1780572326811 }, // → gathering
|
|
666
|
+
{ "type": "PEER_CONNECTION_STATE_CHANGED", "timestamp": 1780572326812 }, // → connecting
|
|
667
|
+
{ "type": "PRODUCER_ADDED", "timestamp": 1780572326821 }, // producer=1abdaf82 (audio)
|
|
668
|
+
{ "type": "MEDIA_TRACK_ADDED", "timestamp": 1780572326821 }, // track=36ae42df (audio)
|
|
669
|
+
{ "type": "PEER_CONNECTION_STATE_CHANGED", "timestamp": 1780572326827 }, // → connected
|
|
670
|
+
{ "type": "PRODUCER_ADDED", "timestamp": 1780572326837 }, // producer=ba06a35b (video)
|
|
671
|
+
{ "type": "DATA_PRODUCER_CREATED", "timestamp": 1780572326853 }
|
|
672
|
+
],
|
|
673
|
+
|
|
674
|
+
"clientMetaItems": [ // environment & devices, one-off (10 in the real sample)
|
|
675
|
+
{ "type": "USER_AGENT_DATA", "payload": "{…Chrome 148 / macOS…}" },
|
|
676
|
+
{ "type": "MEDIA_DEVICE", "payload": "{…\"BRIO 4K Stream Edition\"…}" }
|
|
677
|
+
// …mic / camera / speaker devices…
|
|
678
|
+
],
|
|
679
|
+
|
|
680
|
+
"peerConnections": [
|
|
681
|
+
{
|
|
682
|
+
"peerConnectionId": "b81c8d9d-…", // the media PC — Guest publishes to the SFU
|
|
683
|
+
"outboundRtps": [ /* audio + video */ ],
|
|
684
|
+
"outboundTracks": [ /* mic + camera: label, settings, capabilities */ ],
|
|
685
|
+
"remoteInboundRtps": [ /* RTCP feedback from the SFU */ ],
|
|
686
|
+
"codecs": [ /* … */ ], "iceTransports": [ /* … */ ],
|
|
687
|
+
"iceCandidatePairs": [ /* … */ ], "dataChannels": [ /* … */ ]
|
|
688
|
+
},
|
|
689
|
+
{ "peerConnectionId": "8635acb7-…", "peerConnectionTransports": [ /* … */ ] } // signaling-only PC
|
|
690
|
+
]
|
|
691
|
+
}
|
|
692
|
+
```
|
|
693
|
+
|
|
694
|
+
What `accept()` does with it, in order — each step emits on the bus with full ancestry:
|
|
695
|
+
|
|
696
|
+
1. lazily creates the `ObservedCall` → **`call-added`**;
|
|
697
|
+
2. creates the `ObservedClient` → **`client-added`**, then **`client-joined`** (from `CLIENT_JOINED`);
|
|
698
|
+
3. creates an `ObservedPeerConnection` per entry → **`peer-connection-added`** (×2 here);
|
|
699
|
+
4. creates an `ObservedOutboundTrack` per track → **`outbound-track-added`**, plus the matching
|
|
700
|
+
**`outbound-rtp-added`**;
|
|
701
|
+
5. replays the device list as **`client-metadata`** events and the lifecycle items as
|
|
702
|
+
**`client-event`**; and finally **`client-updated`** for the whole tick.
|
|
703
|
+
|
|
704
|
+
`attachments.roomId` lands on `observedClient.attachments` (read it on `client-updated`, **not** at
|
|
705
|
+
creation — see [Ingestion](#ingestion-accept-context--lifecycle)).
|
|
706
|
+
|
|
707
|
+
**Sample 2 — a steady-state tick** (~8 s later): same `callId` / `clientId`, **no** new
|
|
708
|
+
`clientEvents` or `clientMetaItems`, just refreshed `peerConnections` stats. Each PC now scores `5`
|
|
709
|
+
and the aggregate client `score` is `4.74` — a healthy call. This is the shape of nearly every
|
|
710
|
+
sample: each tick refreshes metrics and fires the `*-updated` events, while the heavy join
|
|
711
|
+
snapshot happens only once.
|
|
712
|
+
|
|
713
|
+
---
|
|
714
|
+
|
|
715
|
+
## Detectors (server-side extension point)
|
|
716
|
+
|
|
717
|
+
`observer-js` deliberately ships **no built-in detectors**. Per-client signals — packet loss,
|
|
718
|
+
jitter, RTT, freezes, etc. — are already detectable on the client and arrive on samples as
|
|
719
|
+
`clientIssues` (surfaced via `client-issue`). Server-side detection should focus on what only
|
|
720
|
+
the server can see by **correlating data across the clients of a call**.
|
|
721
|
+
|
|
722
|
+
The hook lives on **`ObservedCall`**:
|
|
723
|
+
|
|
724
|
+
```ts
|
|
725
|
+
import { Observer, Detector } from '@observertc/observer-js';
|
|
726
|
+
|
|
727
|
+
class MyCrossClientDetector implements Detector {
|
|
728
|
+
readonly name = 'my-detector';
|
|
729
|
+
constructor(private readonly call /* : ObservedCall */) {}
|
|
730
|
+
update() { // called on every call.update()
|
|
731
|
+
// …inspect this.call.observedClients across participants…
|
|
732
|
+
if (/* condition only visible server-side */ false) {
|
|
733
|
+
this.call.addIssue({ type: this.name, payload: JSON.stringify({ /* … */ }), timestamp: Date.now() });
|
|
734
|
+
// → emitted on the bus as 'call-issue'
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
const observer = new Observer();
|
|
740
|
+
observer.on('call-added', ({ observedCall }) => {
|
|
741
|
+
observedCall.detectors.add(new MyCrossClientDetector(observedCall));
|
|
742
|
+
});
|
|
743
|
+
observer.on('call-issue', ({ observedCall, issue }) => { /* react */ });
|
|
744
|
+
```
|
|
745
|
+
|
|
746
|
+
`Detector` interface and the registry:
|
|
747
|
+
|
|
748
|
+
```ts
|
|
749
|
+
interface Detector { readonly name: string; update(): void; }
|
|
750
|
+
|
|
751
|
+
class Detectors {
|
|
752
|
+
add(d: Detector): void;
|
|
753
|
+
remove(d: Detector): void;
|
|
754
|
+
clear(): void;
|
|
755
|
+
update(): void; // called by ObservedCall.update(); guards each detector in try/catch
|
|
756
|
+
get listOfNames(): string[];
|
|
757
|
+
}
|
|
758
|
+
```
|
|
759
|
+
|
|
760
|
+
---
|
|
761
|
+
|
|
762
|
+
## Remote track resolution (mediasoup / SFU)
|
|
763
|
+
|
|
764
|
+
In an SFU, one participant's **outbound** track is delivered to other participants as **inbound**
|
|
765
|
+
tracks (one **publisher** → many **subscribers**). Correlation is **opt-in** per observer: set
|
|
766
|
+
`ObserverConfig.createTrackResolver`, a factory invoked when each call is created that returns the
|
|
767
|
+
call's `RemoteTrackResolver` (or `undefined` for none).
|
|
768
|
+
|
|
769
|
+
`RemoteTrackResolver` is a generic, strategy-driven class. It subscribes to the bus (filtered to
|
|
770
|
+
its call) and links tracks by **publisher id** — the link key — maintaining the links directly on
|
|
771
|
+
the tracks: `inboundTrack.remoteOutboundTrack` and `outboundTrack.remoteInboundTracks: Set`.
|
|
772
|
+
|
|
773
|
+
```ts
|
|
774
|
+
import { Observer, createDefaultMediasoupRemoteTrackResolverFactory } from '@observertc/observer-js';
|
|
775
|
+
|
|
776
|
+
const observer = new Observer({
|
|
777
|
+
createTrackResolver: createDefaultMediasoupRemoteTrackResolverFactory(),
|
|
778
|
+
});
|
|
779
|
+
|
|
780
|
+
// later, given tracks (links are kept up to date as tracks come and go):
|
|
781
|
+
const source = inboundTrack.remoteOutboundTrack; // the publishing ObservedOutboundTrack
|
|
782
|
+
const receivers = [ ...outboundTrack.remoteInboundTracks ]; // the subscribing ObservedInboundTrack[]
|
|
783
|
+
```
|
|
784
|
+
|
|
785
|
+
Two built-in factories ship: `createDefaultMediasoupRemoteTrackResolverFactory()` (publisher =
|
|
786
|
+
`attachments.producerId`, subscriber = `attachments.consumerId`) and
|
|
787
|
+
`createP2pRemoteTrackResolverFactory()` (matches by RTP **SSRC**, preserved end-to-end in p2p).
|
|
788
|
+
|
|
789
|
+
For any other topology, build a `RemoteTrackResolver` with your own key resolvers — the publisher
|
|
790
|
+
id is just whatever links a subscribed track to the published one:
|
|
791
|
+
|
|
792
|
+
```ts
|
|
793
|
+
import { Observer, RemoteTrackResolver } from '@observertc/observer-js';
|
|
794
|
+
|
|
795
|
+
const observer = new Observer({
|
|
796
|
+
createTrackResolver: (observedCall) => new RemoteTrackResolver(observedCall, {
|
|
797
|
+
resolveOutboundTrackPublisherId: (out) => out.attachments?.mediaId as string | undefined,
|
|
798
|
+
resolveInboundTrackPublisherId: (inb) => inb.attachments?.mediaId as string | undefined,
|
|
799
|
+
resolveInboundTrackSubscriberId: (inb) => inb.attachments?.subId as string | undefined, // optional
|
|
800
|
+
}),
|
|
801
|
+
});
|
|
802
|
+
```
|
|
803
|
+
|
|
804
|
+
For the mediasoup factory, the application puts `producerId` / `consumerId` (and optionally
|
|
805
|
+
`direction`, `label`) into the track `attachments`.
|
|
806
|
+
|
|
807
|
+
---
|
|
808
|
+
|
|
809
|
+
## Mediasoup router observation
|
|
810
|
+
|
|
811
|
+
Everything above is built from the **client-reported** `ClientSample`. When you run a
|
|
812
|
+
[mediasoup](https://mediasoup.org) SFU you also have the **server's own** ground truth — its
|
|
813
|
+
routers, transports, producers, consumers and data channels, with exact lifetimes and state
|
|
814
|
+
transitions. `ObservedMediasoupRouter` captures that server-side view into a
|
|
815
|
+
**`MediasoupRouterSample`**, completely independent of the client sample pipeline.
|
|
816
|
+
|
|
817
|
+
### The concept
|
|
818
|
+
|
|
819
|
+
You hand the observer a live mediasoup `Router`; it attaches to mediasoup's own `observer` API and,
|
|
820
|
+
from then on, **passively records** the router's topology and lifecycle — with no polling and no
|
|
821
|
+
changes to your media code:
|
|
822
|
+
|
|
823
|
+
- new transports (`webrtc` / `plain` / `pipe` / `direct`), their selected `tuple`, and ICE state
|
|
824
|
+
transitions;
|
|
825
|
+
- producers (codec, SSRCs/RIDs, `pause`/`resume`) and consumers (`pause`/`resume`,
|
|
826
|
+
`producerPaused`/`producerResumed`);
|
|
827
|
+
- data producers and data consumers;
|
|
828
|
+
- `createdAt` / `closedAt` for every entity above.
|
|
829
|
+
|
|
830
|
+
All of it accumulates on `observedMediasoupRouter.sample` (a `MediasoupRouterSample` — see
|
|
831
|
+
[`src/schema/MediasoupRouter.ts`](./src/schema/MediasoupRouter.ts)). This is a *Sample*, not a
|
|
832
|
+
*Report*: it mirrors the naming of `ClientSample` and is yours to snapshot, persist, or correlate.
|
|
833
|
+
|
|
834
|
+
### Matching peer connections — by **event**, not by storage
|
|
835
|
+
|
|
836
|
+
The observer correlates the SFU side with the client side **at the peer-connection level**: a
|
|
837
|
+
mediasoup WebRTC transport and a client's `RTCPeerConnection` share the same id, so whenever an
|
|
838
|
+
observed peer connection's id matches one of the router's WebRTC transport ids, that's a match.
|
|
839
|
+
|
|
840
|
+
**The observer does not store the router (or its sample) on any entity.** Instead, for **every**
|
|
841
|
+
matching peer connection it emits **`mediasoup-router-matched-with-peer-connection`** and steps
|
|
842
|
+
back — *your application* decides what the pairing means. The payload carries the full peer-connection
|
|
843
|
+
ancestry, so you get the router **and** the matched `observedPeerConnection`, `observedClient` and
|
|
844
|
+
`observedCall` in one place. Stamp the `routerId` into the peer connection's / client's `appData`,
|
|
845
|
+
build your own index, attach the server sample to the call in your database — whatever fits.
|
|
846
|
+
|
|
847
|
+
How it works: as peer connections are observed (`peer-connection-added`), the observer checks whether
|
|
848
|
+
the peer connection's id is one of the router's WebRTC transport ids. On a hit it emits — **once per
|
|
849
|
+
matching peer connection** (de-duplicated by peer-connection id) — and keeps watching, so a router
|
|
850
|
+
that serves many participants emits one match per participant's transport. The internal listener is
|
|
851
|
+
removed automatically when the router closes or the observer closes.
|
|
852
|
+
|
|
853
|
+
When the underlying mediasoup router closes, its `close` propagates to `ObservedMediasoupRouter`,
|
|
854
|
+
which emits **`mediasoup-router-removed`**. That is your cue to do whatever cleanup or persistence
|
|
855
|
+
you want with the now-final `sample` — again, the observer itself keeps nothing.
|
|
856
|
+
|
|
857
|
+
### Options — `observer.createObservedMediasoupRouter(settings)`
|
|
858
|
+
|
|
859
|
+
| Field | Type | Required | Meaning |
|
|
860
|
+
|-------|------|----------|---------|
|
|
861
|
+
| `router` | `mediasoup.types.Router` | yes | the live router to observe; the observer attaches to `router.observer` |
|
|
862
|
+
| `routerId` | `string` | yes | your id for the router (the sample also carries `router.id`) |
|
|
863
|
+
| `appData` | `Record<string, unknown>` | no | application-owned bag on the `ObservedMediasoupRouter` |
|
|
864
|
+
| `attachments` | `Record<string, unknown>` | no | free-form data copied onto `sample.attachments` |
|
|
865
|
+
|
|
866
|
+
Peer-connection matching is automatic — there is nothing to opt into. Returns the
|
|
867
|
+
`ObservedMediasoupRouter`, or `undefined` if the observer is closed (a router with the same id
|
|
868
|
+
returns the existing instance — both warn).
|
|
869
|
+
|
|
870
|
+
Useful members on the returned object: `.sample` (the `MediasoupRouterSample`), `.appData`,
|
|
871
|
+
`.attachments` (getter over `sample.attachments`), `.webrtcTransportIds: Set<string>`, `.id`,
|
|
872
|
+
`.close()`.
|
|
873
|
+
|
|
874
|
+
### Example
|
|
875
|
+
|
|
876
|
+
```ts
|
|
877
|
+
import { Observer } from '@observertc/observer-js';
|
|
878
|
+
import type { ObservedMediasoupRouterScope, ObservedPeerConnectionScope } from '@observertc/observer-js';
|
|
879
|
+
|
|
880
|
+
const observer = new Observer();
|
|
881
|
+
|
|
882
|
+
// 1) Feed client samples as usual so the observer knows about calls, clients & peer connections.
|
|
883
|
+
// (e.g. transport-layer: observer.accept(clientSample, context))
|
|
884
|
+
|
|
885
|
+
// 2) Observe the SFU side. The observer auto-matches peer connections to this router's transports.
|
|
886
|
+
const router = /* your mediasoup router */ undefined as any;
|
|
887
|
+
const observedRouter = observer.createObservedMediasoupRouter({ router, routerId: router.id });
|
|
888
|
+
|
|
889
|
+
// 3) Every peer connection whose id matches one of the router's WebRTC transport ids fires this —
|
|
890
|
+
// WE decide what to do with each pairing. The payload carries the full ancestry.
|
|
891
|
+
observer.on('mediasoup-router-matched-with-peer-connection',
|
|
892
|
+
({ observedMediasoupRouter, observedCall, observedClient, observedPeerConnection }:
|
|
893
|
+
ObservedMediasoupRouterScope & ObservedPeerConnectionScope) => {
|
|
894
|
+
// e.g. remember which router serves this peer connection / client…
|
|
895
|
+
(observedPeerConnection.appData ??= {}).routerId = observedMediasoupRouter.id;
|
|
896
|
+
// …or index the server sample by call in your own store:
|
|
897
|
+
myStore.linkRouterToCall(observedCall.callId, observedMediasoupRouter.sample);
|
|
898
|
+
},
|
|
899
|
+
);
|
|
900
|
+
|
|
901
|
+
// 4) The router closed — WE decide what to persist/forward with the final sample.
|
|
902
|
+
observer.on('mediasoup-router-removed', ({ observedMediasoupRouter }: ObservedMediasoupRouterScope) => {
|
|
903
|
+
myStore.saveRouterSample(observedMediasoupRouter.sample);
|
|
904
|
+
});
|
|
905
|
+
|
|
906
|
+
// (optional) react to the router being registered at all:
|
|
907
|
+
observer.on('mediasoup-router-added', ({ observedMediasoupRouter }) => {
|
|
908
|
+
console.log('observing router', observedMediasoupRouter.id);
|
|
909
|
+
});
|
|
910
|
+
```
|
|
911
|
+
|
|
912
|
+
### Why event-driven instead of storing on the call
|
|
913
|
+
|
|
914
|
+
- **Loose coupling.** The call model stays about client telemetry; the SFU view lives on its own
|
|
915
|
+
object and is associated only if and how *you* choose.
|
|
916
|
+
- **You own the association.** One router serves many peer connections (across clients and calls),
|
|
917
|
+
and the right place to keep that mapping is application-specific — so the observer hands you each
|
|
918
|
+
peer-connection match and the final sample, and gets out of the way.
|
|
919
|
+
- **No silent accumulation.** Nothing is appended to `ObservedCall`, so there is no hidden growth or
|
|
920
|
+
lifetime you have to reason about; the router sample lives exactly as long as you keep a reference.
|
|
921
|
+
|
|
922
|
+
---
|
|
923
|
+
|
|
924
|
+
## Sinks (per-client sample persistence)
|
|
925
|
+
|
|
926
|
+
A **sink** receives the samples a client accepts — for archival, streaming, or later offline
|
|
927
|
+
replay. Each `ObservedClient` gets its **own** sink, produced by the
|
|
928
|
+
`ObserverConfig.createClientSink` factory when the client is created (return `undefined` for no
|
|
929
|
+
sink). The client pushes every accepted sample to its sink, and `end()`s it on close.
|
|
930
|
+
|
|
931
|
+
### The `ClientSampleSink` base class
|
|
932
|
+
|
|
933
|
+
`ClientSampleSink` is an **abstract base class** (a typed `EventEmitter`). You create a sink by
|
|
934
|
+
**subclassing it** and implementing `write` and `end`. It is **object-mode**: `write` receives
|
|
935
|
+
the `ClientSample` *object*, so each sink decides how (or whether) to serialize it — JSON line,
|
|
936
|
+
protobuf, a remote POST body, an in-memory push, etc.
|
|
937
|
+
|
|
938
|
+
```ts
|
|
939
|
+
import { ClientSampleSink, ClientSample } from '@observertc/observer-js';
|
|
940
|
+
|
|
941
|
+
abstract class ClientSampleSink /* extends EventEmitter */ {
|
|
942
|
+
abstract write(sample: ClientSample): boolean; // accept one sample; `false` = backpressure
|
|
943
|
+
abstract end(): void; // flush; emit `close` when the destination is ready
|
|
944
|
+
|
|
945
|
+
// typed events (inherited): the listener signature is inferred from the event name
|
|
946
|
+
on(event: 'close' | 'finish' | 'drain', listener: () => void): this;
|
|
947
|
+
on(event: 'error', listener: (err: Error) => void): this;
|
|
948
|
+
// ...and the matching `once` / `off` / `emit`
|
|
949
|
+
}
|
|
950
|
+
```
|
|
951
|
+
|
|
952
|
+
| Event | Meaning |
|
|
953
|
+
|-------|---------|
|
|
954
|
+
| `close` | the destination is fully written and closed (e.g. a file flushed and its fd closed) — "ready" |
|
|
955
|
+
| `error` | the destination failed |
|
|
956
|
+
| `finish` | `end()` was processed and queued data flushed (before `close`) |
|
|
957
|
+
| `drain` | the buffer drained after backpressure; safe to write more |
|
|
958
|
+
|
|
959
|
+
The library calls `write(sample)` **synchronously** per accepted sample (it is not awaited),
|
|
960
|
+
`end()`s the sink when the client closes, and attaches an `error` listener so a failing sink
|
|
961
|
+
can't crash the process (it also catches throws from `write`/`end`). The application — which
|
|
962
|
+
created the sink — listens for `close` (destination ready) and `error`. Because `write` isn't
|
|
963
|
+
awaited in the `accept()` hot path, **backpressure and batching are the sink's concern**.
|
|
964
|
+
|
|
965
|
+
### Built-in sinks
|
|
966
|
+
|
|
967
|
+
```ts
|
|
968
|
+
import { Observer, createJsonlFileSinkFactory } from '@observertc/observer-js';
|
|
969
|
+
|
|
970
|
+
const observer = new Observer({
|
|
971
|
+
// one ./stats/<callId>__<clientId>.jsonl per client
|
|
972
|
+
createClientSink: createJsonlFileSinkFactory({ directory: './stats' }),
|
|
973
|
+
});
|
|
974
|
+
|
|
975
|
+
// React when a sink is created for a client:
|
|
976
|
+
observer.on('client-sink-created', ({ observedClient, sink }) => {
|
|
977
|
+
sink.on('close', () => {
|
|
978
|
+
// the file is fully flushed and its fd closed — ready to upload, move, etc.
|
|
979
|
+
});
|
|
980
|
+
});
|
|
981
|
+
```
|
|
982
|
+
|
|
983
|
+
| Export | Signature | Notes |
|
|
984
|
+
|--------|-----------|-------|
|
|
985
|
+
| `createJsonlFileSinkFactory` | `({ directory, flags?, getFileName?, serializeSample? }) => ClientSampleSinkFactory` | per-client JSONL files; path defaults to `${callId}__${clientId}.jsonl` under `directory` (which **must exist**) |
|
|
986
|
+
| `createJsonlFileSink` | `({ path, flags?, serializeSample? }) => ClientSampleSink` | a single JSONL file; wraps `fs.WriteStream` and re-emits its `close`/`finish`/`drain`/`error` |
|
|
987
|
+
| `JsonlFileSink` | `class extends ClientSampleSink` | the underlying class; exposes `readonly path` so a `close` handler knows which file is ready |
|
|
988
|
+
| `createInMemorySink` / `InMemorySink` | `(samples?: ClientSample[]) => InMemorySink` | collects the accepted **sample objects** into `.samples: ClientSample[]`; emits `close` on `end()` |
|
|
989
|
+
|
|
990
|
+
`serializeSample?: (sample: ClientSample) => string` overrides the default `JSON.stringify` for
|
|
991
|
+
the JSONL sinks (e.g. to redact or reshape before writing).
|
|
992
|
+
|
|
993
|
+
### Reading sink-specific info (e.g. the file path)
|
|
994
|
+
|
|
995
|
+
The bus hands you the sink as the base `ClientSampleSink`. To read information specific to a sink
|
|
996
|
+
type — for a file sink, where it was written — **narrow with `instanceof`** and read the sink's
|
|
997
|
+
public fields. `JsonlFileSink` exposes `path`:
|
|
998
|
+
|
|
999
|
+
```ts
|
|
1000
|
+
import { JsonlFileSink } from '@observertc/observer-js';
|
|
1001
|
+
|
|
1002
|
+
observer.on('client-sink-created', ({ observedClient, sink }) => {
|
|
1003
|
+
if (sink instanceof JsonlFileSink) {
|
|
1004
|
+
const { path } = sink; // the file this client's samples go to
|
|
1005
|
+
sink.once('close', () => uploadFile(path)); // close = flushed & fd closed → ready
|
|
1006
|
+
}
|
|
1007
|
+
});
|
|
1008
|
+
```
|
|
1009
|
+
|
|
1010
|
+
The general pattern: each concrete sink exposes whatever it wants as `public readonly` fields, and
|
|
1011
|
+
consumers narrow (`instanceof YourSink`) to read them. Your own sinks do the same.
|
|
1012
|
+
|
|
1013
|
+
### Writing your own sink
|
|
1014
|
+
|
|
1015
|
+
Subclass `ClientSampleSink` and emit the lifecycle events yourself — for any non-file
|
|
1016
|
+
destination (a remote endpoint, a message queue, an object store, …):
|
|
1017
|
+
|
|
1018
|
+
```ts
|
|
1019
|
+
import { ClientSampleSink, ClientSample, ClientSampleSinkFactory } from '@observertc/observer-js';
|
|
1020
|
+
|
|
1021
|
+
class HttpSink extends ClientSampleSink {
|
|
1022
|
+
private buffer: ClientSample[] = [];
|
|
1023
|
+
constructor(private readonly url: string) { super(); }
|
|
1024
|
+
|
|
1025
|
+
write(sample: ClientSample): boolean {
|
|
1026
|
+
this.buffer.push(sample); // batch; decide your own backpressure
|
|
1027
|
+
return true;
|
|
1028
|
+
}
|
|
1029
|
+
end(): void {
|
|
1030
|
+
fetch(this.url, { method: 'POST', body: JSON.stringify(this.buffer) })
|
|
1031
|
+
.then(() => this.emit('close')) // signal "destination ready"
|
|
1032
|
+
.catch((err) => this.emit('error', err));
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
const createClientSink: ClientSampleSinkFactory = ({ clientId, observedCall }) =>
|
|
1037
|
+
new HttpSink(`https://stats.example.com/${observedCall.callId}/${clientId}`);
|
|
1038
|
+
|
|
1039
|
+
const observer = new Observer({ createClientSink });
|
|
1040
|
+
```
|
|
1041
|
+
|
|
1042
|
+
`observedClient.sink?` exposes the created sink; the `client-sink-created` event delivers it on
|
|
1043
|
+
the bus with full ancestry. `ClientSampleSinkFactory` is
|
|
1044
|
+
`(p: { clientId: string; observedCall: ObservedCall }) => ClientSampleSink | undefined`.
|
|
1045
|
+
|
|
1046
|
+
## Logging
|
|
1047
|
+
|
|
1048
|
+
`observer-js` logs through a single, swappable sink. Out of the box it writes `debug` and
|
|
1049
|
+
above to `console` (verbose — install your own sink for production). Funnel everything into your
|
|
1050
|
+
logger:
|
|
1051
|
+
|
|
1052
|
+
```ts
|
|
1053
|
+
import { setObserverLogger, type ObserverLogger } from '@observertc/observer-js';
|
|
1054
|
+
|
|
1055
|
+
setObserverLogger({
|
|
1056
|
+
trace: (m, ...a) => myLogger.trace(`[${m}]`, ...a),
|
|
1057
|
+
debug: (m, ...a) => myLogger.debug(`[${m}]`, ...a),
|
|
1058
|
+
info: (m, ...a) => myLogger.info(`[${m}]`, ...a),
|
|
1059
|
+
warn: (m, ...a) => myLogger.warn(`[${m}]`, ...a),
|
|
1060
|
+
error: (m, ...a) => myLogger.error(`[${m}]`, ...a),
|
|
1061
|
+
});
|
|
1062
|
+
```
|
|
1063
|
+
|
|
1064
|
+
`createLogger(moduleName)` is also exported for your own modules. See
|
|
1065
|
+
**[`docs/logging.md`](./docs/logging.md)** for pino / winston / console recipes, level
|
|
1066
|
+
filtering, per-module routing, and full silencing.
|
|
1067
|
+
|
|
1068
|
+
---
|
|
1069
|
+
|
|
1070
|
+
## Error-handling philosophy
|
|
1071
|
+
|
|
1072
|
+
The library **warns and degrades; it does not throw** on operational problems:
|
|
1073
|
+
|
|
1074
|
+
- `createObservedCall` / `createObservedClient` on a closed parent → warn + return `undefined`.
|
|
1075
|
+
- Duplicate id → warn + return the **existing** instance.
|
|
1076
|
+
- `accept()` on a closed client → warn + no-op.
|
|
1077
|
+
- Sample missing `callId`/`clientId`, or observer closed → `sample-rejected` event.
|
|
1078
|
+
- A throwing accept-middleware → warn + drop that sample (never crashes `accept()`).
|
|
1079
|
+
|
|
1080
|
+
Therefore `create*` and `getOrCreate*` return `T | undefined`; **guard the result.** The
|
|
1081
|
+
`Middleware` utility's internal invariants (e.g. calling `next()` twice) throw, but those throws
|
|
1082
|
+
are caught by `accept()` and surfaced as a warning.
|
|
1083
|
+
|
|
1084
|
+
---
|
|
1085
|
+
|
|
1086
|
+
## Development & extension guide
|
|
1087
|
+
|
|
1088
|
+
```bash
|
|
1089
|
+
yarn install
|
|
1090
|
+
yarn build # tsup → dist/ (dual ESM .mjs + CJS .js, single entry, .d.ts/.d.mts + sourcemaps)
|
|
1091
|
+
yarn lint # eslint -c .eslintrc.json "src/**/*.ts"
|
|
1092
|
+
yarn typecheck # tsc --noEmit
|
|
1093
|
+
yarn test # jest
|
|
1094
|
+
```
|
|
1095
|
+
|
|
1096
|
+
The build is driven by [`tsup`](https://tsup.egoist.dev) (config in `tsup.config.ts`): a single
|
|
1097
|
+
entry (`src/index.ts`), dual ESM + CommonJS output to `dist/` (`index.mjs` / `index.js`) with
|
|
1098
|
+
`.d.mts` / `.d.ts` types and sourcemaps, targeting Node 20. CI (`.github/workflows/ci.yml`) runs
|
|
1099
|
+
lint + typecheck + **build** + test on every push/PR.
|
|
1100
|
+
|
|
1101
|
+
**Project layout** (`src/`): `Observer.ts`, `ObservedCall.ts`, `ObservedClient.ts`,
|
|
1102
|
+
`ObservedPeerConnection.ts`, the `Observed*` sub-stat classes, `ObserverEvents.ts` (the typed
|
|
1103
|
+
event map + scope types), `detectors/` (`Detector`, `Detectors`), `scores/`, `updaters/`
|
|
1104
|
+
(update-policy strategies), `utils/` (remote-track resolvers), `common/` (`logger`, `utils`,
|
|
1105
|
+
`Middleware`), `schema/` (sample/event/meta types), and `sinks/` (the `ClientSampleSink` base +
|
|
1106
|
+
`JsonlFileSink` / `InMemorySink`, re-exported from the package root).
|
|
1107
|
+
|
|
1108
|
+
**Conventions to follow when developing further:**
|
|
1109
|
+
|
|
1110
|
+
- *Single event bus.* New consumer-facing events go in `ObserverEvents.ts` with an object
|
|
1111
|
+
payload `[<Scope> & { …subject }]`, and are emitted via the component's
|
|
1112
|
+
`_notify(type, { ...this.eventScope, …subject })`. Each component has a precomputed
|
|
1113
|
+
`eventScope` field and a thin `_notify` wrapper around the right emitter. Keep purely internal
|
|
1114
|
+
coordination as **local** EventEmitter events (and remember to `off` them on close).
|
|
1115
|
+
- *Warn, don't throw* on operational/edge conditions; return `undefined` where a value can't be produced.
|
|
1116
|
+
- *Counter-reset-safe deltas.* When computing a delta from a cumulative counter, never emit a
|
|
1117
|
+
negative value (guard `curr >= prev`), to survive counter resets / SSRC reuse.
|
|
1118
|
+
- *Explicit accumulation.* The per-sample metric accumulation in `accept()` is intentionally
|
|
1119
|
+
explicit and not abstracted — match that style.
|
|
1120
|
+
- *Detectors are server-side.* Add cross-client detectors on `ObservedCall.detectors`; don't
|
|
1121
|
+
re-implement client-detectable signals.
|
|
1122
|
+
|
|
1123
|
+
**Recipes:**
|
|
1124
|
+
|
|
1125
|
+
- *Add an event:* add the key + payload to `ObserverEvents`; in the owning component call
|
|
1126
|
+
`this._notify('my-event', { ...this.eventScope, subject })`.
|
|
1127
|
+
- *Add a per-stream metric:* add the field to the relevant `Observed*Rtp`/track class, populate
|
|
1128
|
+
it in its `update()` (reset at the top of `update()` if it's per-tick), and read it from a
|
|
1129
|
+
`*-updated` handler.
|
|
1130
|
+
- *Add a detector:* implement `Detector`, register it on `call-added` via
|
|
1131
|
+
`observedCall.detectors.add(...)`, surface findings with `observedCall.addIssue(...)`.
|
|
1132
|
+
|
|
1133
|
+
---
|
|
1134
|
+
|
|
1135
|
+
## License
|
|
1136
|
+
|
|
1137
|
+
Apache-2.0. Part of the [ObserverTC](https://github.com/observertc) ecosystem.
|
|
1138
|
+
|
|
1139
|
+
---
|
|
1140
|
+
|
|
1141
|
+
# ============================================================================
|
|
1142
|
+
# docs/logging.md
|
|
1143
|
+
# ============================================================================
|
|
1144
|
+
|
|
1145
|
+
# Logging in `@observertc/observer-js`
|
|
1146
|
+
|
|
1147
|
+
`observer-js` writes diagnostic logs from its internal modules (the `Observer`, each
|
|
1148
|
+
`Observed*` entity, the updaters, etc.). All of that output is routed through a single,
|
|
1149
|
+
swappable sink so that the host application stays in full control of *where* logs go,
|
|
1150
|
+
*what level* is kept, and *how* they are formatted. This document explains the model and
|
|
1151
|
+
gives copy-paste recipes for funneling the logs into `pino`, `winston`, plain `console`,
|
|
1152
|
+
or nothing at all.
|
|
1153
|
+
|
|
1154
|
+
## TL;DR
|
|
1155
|
+
|
|
1156
|
+
```ts
|
|
1157
|
+
import { setObserverLogger } from '@observertc/observer-js';
|
|
1158
|
+
|
|
1159
|
+
// Funnel every observer-js log line into your own logger.
|
|
1160
|
+
setObserverLogger({
|
|
1161
|
+
trace: (module, ...args) => myLogger.trace(`[${module}]`, ...args),
|
|
1162
|
+
debug: (module, ...args) => myLogger.debug(`[${module}]`, ...args),
|
|
1163
|
+
info: (module, ...args) => myLogger.info(`[${module}]`, ...args),
|
|
1164
|
+
warn: (module, ...args) => myLogger.warn(`[${module}]`, ...args),
|
|
1165
|
+
error: (module, ...args) => myLogger.error(`[${module}]`, ...args),
|
|
1166
|
+
});
|
|
1167
|
+
```
|
|
1168
|
+
|
|
1169
|
+
That's the whole integration surface. The rest of this document is detail.
|
|
1170
|
+
|
|
1171
|
+
## The model
|
|
1172
|
+
|
|
1173
|
+
There are two interfaces and two functions, all exported from the package root:
|
|
1174
|
+
|
|
1175
|
+
```ts
|
|
1176
|
+
import {
|
|
1177
|
+
createLogger, // (moduleName: string) => Logger
|
|
1178
|
+
setObserverLogger, // (logger: ObserverLogger) => void
|
|
1179
|
+
type Logger,
|
|
1180
|
+
type ObserverLogger,
|
|
1181
|
+
} from '@observertc/observer-js';
|
|
1182
|
+
```
|
|
1183
|
+
|
|
1184
|
+
- **`Logger`** — what each internal module holds. Five level methods, each variadic:
|
|
1185
|
+
`trace`, `debug`, `info`, `warn`, `error`, all `(...args: any[]) => void`.
|
|
1186
|
+
- **`ObserverLogger`** — the single *sink* every `Logger` forwards to. Same five levels,
|
|
1187
|
+
but each receives the originating **module name** as the first argument:
|
|
1188
|
+
`(module: string, ...args: any[]) => void`.
|
|
1189
|
+
|
|
1190
|
+
Internally, each file does:
|
|
1191
|
+
|
|
1192
|
+
```ts
|
|
1193
|
+
const logger = createLogger('ObservedPeerConnection');
|
|
1194
|
+
// ...
|
|
1195
|
+
logger.warn('Received sample without callId. %o', sample);
|
|
1196
|
+
```
|
|
1197
|
+
|
|
1198
|
+
`createLogger(moduleName)` returns a `Logger` whose every call forwards to the process-wide
|
|
1199
|
+
`ObserverLogger`, injecting `moduleName`. So the line above ultimately calls:
|
|
1200
|
+
|
|
1201
|
+
```ts
|
|
1202
|
+
observerLogger.warn('ObservedPeerConnection', 'Received sample without callId. %o', sample);
|
|
1203
|
+
```
|
|
1204
|
+
|
|
1205
|
+
`setObserverLogger(...)` replaces that process-wide sink. One call reroutes **all** logging
|
|
1206
|
+
from **every** `Observer` instance in the process.
|
|
1207
|
+
|
|
1208
|
+
```
|
|
1209
|
+
ObservedCall ─┐
|
|
1210
|
+
ObservedClient ┤ createLogger('<module>') ──► the single ObserverLogger ──► your logger
|
|
1211
|
+
Observer ──────┘ (per module) (set via setObserverLogger)
|
|
1212
|
+
```
|
|
1213
|
+
|
|
1214
|
+
## Default behavior (important)
|
|
1215
|
+
|
|
1216
|
+
If you never call `setObserverLogger`, the built-in sink writes to `console`:
|
|
1217
|
+
|
|
1218
|
+
| Level | Default destination |
|
|
1219
|
+
|-------|---------------------|
|
|
1220
|
+
| `trace` | dropped (no-op) |
|
|
1221
|
+
| `debug` | `console.log` |
|
|
1222
|
+
| `info` | `console.info` |
|
|
1223
|
+
| `warn` | `console.warn` |
|
|
1224
|
+
| `error` | `console.error` |
|
|
1225
|
+
|
|
1226
|
+
…each prefixed with `"[LEVEL] <module>"`. This means **the default is fairly verbose
|
|
1227
|
+
(`debug` and up go to the console).** For anything beyond local experimentation you should
|
|
1228
|
+
install your own sink with an appropriate level — see below.
|
|
1229
|
+
|
|
1230
|
+
## Message format
|
|
1231
|
+
|
|
1232
|
+
Internal log calls use Node/`console`-style printf placeholders (`%s`, `%o`, `%d`, `%j`)
|
|
1233
|
+
followed by the substitution values, and sometimes a trailing object:
|
|
1234
|
+
|
|
1235
|
+
```ts
|
|
1236
|
+
logger.warn('Observed Call with id %s already exists; returning the existing instance', callId);
|
|
1237
|
+
logger.warn('Received sample without clientId %o', sample);
|
|
1238
|
+
```
|
|
1239
|
+
|
|
1240
|
+
Your `ObserverLogger` receives these as `(module, formatString, ...values)`. A logger that
|
|
1241
|
+
understands printf placeholders (`console`, `pino`) can pass them straight through; for
|
|
1242
|
+
others, format them yourself with `util.format` (recipe below).
|
|
1243
|
+
|
|
1244
|
+
## When can I call `setObserverLogger`?
|
|
1245
|
+
|
|
1246
|
+
Any time. The sink is read on every log call, not captured at import, so a later
|
|
1247
|
+
`setObserverLogger(...)` immediately affects all subsequent logs. There is no ordering
|
|
1248
|
+
requirement relative to constructing an `Observer`. Note it is **global/process-wide**:
|
|
1249
|
+
the last call wins and applies to all `Observer` instances.
|
|
1250
|
+
|
|
1251
|
+
---
|
|
1252
|
+
|
|
1253
|
+
## Recipes
|
|
1254
|
+
|
|
1255
|
+
### 1. Silence everything
|
|
1256
|
+
|
|
1257
|
+
```ts
|
|
1258
|
+
import { setObserverLogger } from '@observertc/observer-js';
|
|
1259
|
+
|
|
1260
|
+
const noop = () => undefined;
|
|
1261
|
+
setObserverLogger({ trace: noop, debug: noop, info: noop, warn: noop, error: noop });
|
|
1262
|
+
```
|
|
1263
|
+
|
|
1264
|
+
### 2. Console, but only `warn` and above
|
|
1265
|
+
|
|
1266
|
+
```ts
|
|
1267
|
+
import { setObserverLogger } from '@observertc/observer-js';
|
|
1268
|
+
|
|
1269
|
+
setObserverLogger({
|
|
1270
|
+
trace: () => undefined,
|
|
1271
|
+
debug: () => undefined,
|
|
1272
|
+
info: () => undefined,
|
|
1273
|
+
warn: (module, ...args) => console.warn(`[WARN] ${module}`, ...args),
|
|
1274
|
+
error: (module, ...args) => console.error(`[ERROR] ${module}`, ...args),
|
|
1275
|
+
});
|
|
1276
|
+
```
|
|
1277
|
+
|
|
1278
|
+
### 3. pino (recommended for servers)
|
|
1279
|
+
|
|
1280
|
+
`observer-js` does not depend on `pino` — you bring your own. pino understands printf
|
|
1281
|
+
placeholders, and passing `{ module }` as the merging object keeps the module name as a
|
|
1282
|
+
structured field (so you can filter by it later).
|
|
1283
|
+
|
|
1284
|
+
```ts
|
|
1285
|
+
import pino from 'pino';
|
|
1286
|
+
import { setObserverLogger, type ObserverLogger } from '@observertc/observer-js';
|
|
1287
|
+
|
|
1288
|
+
const root = pino({ level: 'warn', name: 'observer-js' });
|
|
1289
|
+
|
|
1290
|
+
const adapter: ObserverLogger = {
|
|
1291
|
+
trace: (module, ...args) => root.trace({ module }, ...args),
|
|
1292
|
+
debug: (module, ...args) => root.debug({ module }, ...args),
|
|
1293
|
+
info: (module, ...args) => root.info({ module }, ...args),
|
|
1294
|
+
warn: (module, ...args) => root.warn({ module }, ...args),
|
|
1295
|
+
error: (module, ...args) => root.error({ module }, ...args),
|
|
1296
|
+
};
|
|
1297
|
+
|
|
1298
|
+
setObserverLogger(adapter);
|
|
1299
|
+
```
|
|
1300
|
+
|
|
1301
|
+
Level filtering is handled by pino (`level: 'warn'` above), so the dropped levels cost
|
|
1302
|
+
almost nothing. If you prefer a dedicated child logger per module:
|
|
1303
|
+
|
|
1304
|
+
```ts
|
|
1305
|
+
const children = new Map<string, pino.Logger>();
|
|
1306
|
+
const child = (module: string) =>
|
|
1307
|
+
children.get(module) ?? children.set(module, root.child({ module })).get(module)!;
|
|
1308
|
+
|
|
1309
|
+
const adapter: ObserverLogger = {
|
|
1310
|
+
trace: (m, ...a) => child(m).trace(...a),
|
|
1311
|
+
debug: (m, ...a) => child(m).debug(...a),
|
|
1312
|
+
info: (m, ...a) => child(m).info(...a),
|
|
1313
|
+
warn: (m, ...a) => child(m).warn(...a),
|
|
1314
|
+
error: (m, ...a) => child(m).error(...a),
|
|
1315
|
+
};
|
|
1316
|
+
setObserverLogger(adapter);
|
|
1317
|
+
```
|
|
1318
|
+
|
|
1319
|
+
### 4. winston
|
|
1320
|
+
|
|
1321
|
+
winston's level methods don't do printf substitution the same way, so format the message
|
|
1322
|
+
with `util.format` first:
|
|
1323
|
+
|
|
1324
|
+
```ts
|
|
1325
|
+
import { format } from 'node:util';
|
|
1326
|
+
import { createLogger as createWinston, transports, format as wformat } from 'winston';
|
|
1327
|
+
import { setObserverLogger, type ObserverLogger } from '@observertc/observer-js';
|
|
1328
|
+
|
|
1329
|
+
const w = createWinston({
|
|
1330
|
+
level: 'warn',
|
|
1331
|
+
transports: [new transports.Console()],
|
|
1332
|
+
format: wformat.json(),
|
|
1333
|
+
});
|
|
1334
|
+
|
|
1335
|
+
const adapter: ObserverLogger = {
|
|
1336
|
+
trace: (module, ...args) => w.silly(format(...args), { module }),
|
|
1337
|
+
debug: (module, ...args) => w.debug(format(...args), { module }),
|
|
1338
|
+
info: (module, ...args) => w.info(format(...args), { module }),
|
|
1339
|
+
warn: (module, ...args) => w.warn(format(...args), { module }),
|
|
1340
|
+
error: (module, ...args) => w.error(format(...args), { module }),
|
|
1341
|
+
};
|
|
1342
|
+
|
|
1343
|
+
setObserverLogger(adapter);
|
|
1344
|
+
```
|
|
1345
|
+
|
|
1346
|
+
### 5. Generic / any logger (`util.format`)
|
|
1347
|
+
|
|
1348
|
+
The most portable adapter — works with any logger that takes a single string:
|
|
1349
|
+
|
|
1350
|
+
```ts
|
|
1351
|
+
import { format } from 'node:util';
|
|
1352
|
+
import { setObserverLogger, type ObserverLogger } from '@observertc/observer-js';
|
|
1353
|
+
|
|
1354
|
+
const toLine = (module: string, args: unknown[]) => `[${module}] ${format(...args)}`;
|
|
1355
|
+
|
|
1356
|
+
const adapter: ObserverLogger = {
|
|
1357
|
+
trace: (module, ...args) => myLogger.trace(toLine(module, args)),
|
|
1358
|
+
debug: (module, ...args) => myLogger.debug(toLine(module, args)),
|
|
1359
|
+
info: (module, ...args) => myLogger.info(toLine(module, args)),
|
|
1360
|
+
warn: (module, ...args) => myLogger.warn(toLine(module, args)),
|
|
1361
|
+
error: (module, ...args) => myLogger.error(toLine(module, args)),
|
|
1362
|
+
};
|
|
1363
|
+
|
|
1364
|
+
setObserverLogger(adapter);
|
|
1365
|
+
```
|
|
1366
|
+
|
|
1367
|
+
### 6. Filter or re-route specific modules
|
|
1368
|
+
|
|
1369
|
+
Because the sink receives the module name, you can route or drop per module:
|
|
1370
|
+
|
|
1371
|
+
```ts
|
|
1372
|
+
const NOISY = new Set(['ObservedPeerConnection']);
|
|
1373
|
+
|
|
1374
|
+
setObserverLogger({
|
|
1375
|
+
trace: () => undefined,
|
|
1376
|
+
debug: (module, ...args) => { if (!NOISY.has(module)) root.debug({ module }, ...args); },
|
|
1377
|
+
info: (module, ...args) => root.info({ module }, ...args),
|
|
1378
|
+
warn: (module, ...args) => root.warn({ module }, ...args),
|
|
1379
|
+
error: (module, ...args) => root.error({ module }, ...args),
|
|
1380
|
+
});
|
|
1381
|
+
```
|
|
1382
|
+
|
|
1383
|
+
## Reusing the funnel for your own modules
|
|
1384
|
+
|
|
1385
|
+
`createLogger` is exported, so your application code can emit through the same sink and
|
|
1386
|
+
inherit whatever routing/level you configured with `setObserverLogger`:
|
|
1387
|
+
|
|
1388
|
+
```ts
|
|
1389
|
+
import { createLogger } from '@observertc/observer-js';
|
|
1390
|
+
|
|
1391
|
+
const logger = createLogger('my-app:ingest');
|
|
1392
|
+
logger.info('accepted %d samples in %dms', count, elapsedMs);
|
|
1393
|
+
```
|
|
1394
|
+
|
|
1395
|
+
## Notes & caveats
|
|
1396
|
+
|
|
1397
|
+
- **Global, not per-instance.** `setObserverLogger` sets one process-wide sink shared by
|
|
1398
|
+
every `Observer`. There is currently no per-`Observer` logger override.
|
|
1399
|
+
- **Level filtering belongs in your logger.** `observer-js` always calls the sink for
|
|
1400
|
+
`debug`/`info`/`warn`/`error` (and `trace`, though the default drops it); decide what to
|
|
1401
|
+
keep inside your `ObserverLogger` (or, with pino/winston, via their `level`).
|
|
1402
|
+
- **No bundled transport.** `observer-js` never imports `pino`, `winston`, or any logging
|
|
1403
|
+
library — you wire in whichever you already use.
|
|
1404
|
+
- **`trace`** is intended for very high-frequency, per-sample diagnostics; keep it dropped
|
|
1405
|
+
in production.
|
|
1406
|
+
|
|
1407
|
+
## Type reference
|
|
1408
|
+
|
|
1409
|
+
```ts
|
|
1410
|
+
interface Logger {
|
|
1411
|
+
trace(...args: any[]): void;
|
|
1412
|
+
debug(...args: any[]): void;
|
|
1413
|
+
info(...args: any[]): void;
|
|
1414
|
+
warn(...args: any[]): void;
|
|
1415
|
+
error(...args: any[]): void;
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
interface ObserverLogger {
|
|
1419
|
+
trace(module: string, ...args: any[]): void;
|
|
1420
|
+
debug(module: string, ...args: any[]): void;
|
|
1421
|
+
info(module: string, ...args: any[]): void;
|
|
1422
|
+
warn(module: string, ...args: any[]): void;
|
|
1423
|
+
error(module: string, ...args: any[]): void;
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
function createLogger(moduleName: string): Logger;
|
|
1427
|
+
function setObserverLogger(logger: ObserverLogger): void;
|
|
1428
|
+
```
|
|
1429
|
+
|
|
1430
|
+
---
|
|
1431
|
+
|
|
1432
|
+
# ============================================================================
|
|
1433
|
+
# CHANGELOG.md
|
|
1434
|
+
# ============================================================================
|
|
1435
|
+
|
|
1436
|
+
# Changelog
|
|
1437
|
+
|
|
1438
|
+
## 1.0.0
|
|
1439
|
+
|
|
1440
|
+
First stable release of `@observertc/observer-js` — a server-side Node.js library that turns a
|
|
1441
|
+
stream of WebRTC `ClientSample`s into a live, queryable model of every call, with a single typed
|
|
1442
|
+
event bus and pluggable extension points. This entry states the full set of features and concepts
|
|
1443
|
+
the 1.0.0 API provides.
|
|
1444
|
+
|
|
1445
|
+
### Core model
|
|
1446
|
+
|
|
1447
|
+
- **Entity hierarchy.** `Observer → ObservedCall → ObservedClient → ObservedPeerConnection →`
|
|
1448
|
+
sub-stats (inbound/outbound RTP, remote inbound/outbound RTP, inbound/outbound tracks, codecs,
|
|
1449
|
+
data channels, ICE transports/candidates/candidate-pairs, certificates, media sources, media
|
|
1450
|
+
playouts, peer-connection transports). Every node holds current + cumulative metrics and is
|
|
1451
|
+
reachable by id through `Map`s on its parent.
|
|
1452
|
+
- **One ingestion method.** `observer.accept(sample, context?)` is the only way data gets in.
|
|
1453
|
+
Calls, clients and peer connections are **created lazily** the first time their id appears.
|
|
1454
|
+
- **Single event bus.** Everything worth subscribing to is emitted on the **`Observer`** itself,
|
|
1455
|
+
with a payload object that carries the full ancestry (observer → call → client → peer connection)
|
|
1456
|
+
down to the subject. `on`/`off`/`once`/`emit` are fully typed against the event map. Local
|
|
1457
|
+
EventEmitter lifecycle events remain on each component for internal teardown wiring.
|
|
1458
|
+
- **Pull or react.** Read fields off the entities at any time, and/or subscribe to events.
|
|
1459
|
+
|
|
1460
|
+
### Ingestion & configuration
|
|
1461
|
+
|
|
1462
|
+
- **`accept(sample, context?)`** with a transient, free-form `AcceptContext` that is threaded down
|
|
1463
|
+
the accept chain and carried to the `*-updated` events of that pass — and **never** written to
|
|
1464
|
+
`appData`.
|
|
1465
|
+
- **`appData` vs `context`.** `appData` is application-owned, fixed at entity creation (via
|
|
1466
|
+
`settings.appData` or the `createCallAppData` / `createClientAppData` factories) and never mutated
|
|
1467
|
+
by the library; `context` is per-accept and ephemeral.
|
|
1468
|
+
- **Accept middlewares.** `observer.acceptMiddlewares` — a global, pre-dispatch chain run on every
|
|
1469
|
+
sample before it reaches any call/client (inspect, mutate/normalize ids, enrich).
|
|
1470
|
+
- **Event-driven update policies.** Observer and call aggregation triggers are
|
|
1471
|
+
`update-on-any-…-updated` / `update-when-all-…-updated` / `none`. There are **no internal timers**;
|
|
1472
|
+
with `none` (or to drive a fixed cadence) the app calls the public `observer.update()` /
|
|
1473
|
+
`call.update()` itself.
|
|
1474
|
+
- **Automatic teardown.** Optional `closeClientIfIdleForMs` and `closeCallIfEmptyForMs`; closing
|
|
1475
|
+
cascades down the tree and emits the matching `*-closed` / `*-removed` events.
|
|
1476
|
+
|
|
1477
|
+
### Derived metrics
|
|
1478
|
+
|
|
1479
|
+
- **Counter-reset-safe deltas.** Per-tick deltas never go negative across counter resets / SSRC
|
|
1480
|
+
reuse (guarded `curr >= prev`).
|
|
1481
|
+
- **Per-stream metrics**: bitrates, packet/byte deltas, jitter, fraction-lost, RTT, etc.
|
|
1482
|
+
- **Remote-RTP correlation.** Receiver/sender RTCP reports are linked to the local stream by
|
|
1483
|
+
`remoteId`/SSRC and surfaced as `remote*` fields (e.g. `remoteRttInMs`, `remoteFractionLost` on
|
|
1484
|
+
outbound; `remoteRttInMs`, `remoteBytesSent` on inbound).
|
|
1485
|
+
- **TURN/TCP usage** derived from the selected ICE candidate pair (`usingTURN` / `usingTCP`), with a
|
|
1486
|
+
call-level `ObservedTURN` view.
|
|
1487
|
+
|
|
1488
|
+
### Optional track correlation
|
|
1489
|
+
|
|
1490
|
+
- **`RemoteTrackResolver`** — a generic, strategy-driven resolver that links a published (outbound)
|
|
1491
|
+
track to the subscribed (inbound) tracks carrying it (**one publisher → many subscribers**) by a
|
|
1492
|
+
**publisher id** (the link key). Links are maintained directly on the tracks
|
|
1493
|
+
(`inboundTrack.remoteOutboundTrack`, `outboundTrack.remoteInboundTracks`).
|
|
1494
|
+
- **Opt-in via `ObserverConfig.createTrackResolver`**, invoked per call. Built-in factories:
|
|
1495
|
+
`createDefaultMediasoupRemoteTrackResolverFactory()` (producerId/consumerId attachments) and
|
|
1496
|
+
`createP2pRemoteTrackResolverFactory()` (RTP SSRC). Custom topologies supply their own
|
|
1497
|
+
publisher/subscriber id resolvers.
|
|
1498
|
+
|
|
1499
|
+
### Per-client sample sinks
|
|
1500
|
+
|
|
1501
|
+
- **`ClientSampleSink`** — an object-mode, `EventEmitter`-based base class (`write(sample)`,
|
|
1502
|
+
`end()`, typed `close`/`error`/`finish`/`drain` events). One sink per `ObservedClient`, produced
|
|
1503
|
+
by `ObserverConfig.createClientSink`; the `client-sink-created` event delivers it on the bus.
|
|
1504
|
+
- **Built-ins:** `JsonlFileSink` (+ `createJsonlFileSink` / `createJsonlFileSinkFactory`, exposing
|
|
1505
|
+
`path` and a custom `serializeSample`) and the env-agnostic `InMemorySink`.
|
|
1506
|
+
|
|
1507
|
+
### Detectors & call-level issues
|
|
1508
|
+
|
|
1509
|
+
- **`Detectors`** — a server-side extension-point registry on `ObservedCall` (ships empty; runs each
|
|
1510
|
+
registered detector on `call.update()`, isolating throws). `call.addIssue(...)` raises a
|
|
1511
|
+
call-level issue surfaced on the bus as `call-issue`; client-reported issues surface as
|
|
1512
|
+
`client-issue`.
|
|
1513
|
+
|
|
1514
|
+
### Logging
|
|
1515
|
+
|
|
1516
|
+
- **Pluggable logger** — a single swappable sink (`setObserverLogger`, `createLogger`) with a
|
|
1517
|
+
documented funnel for pino/winston/console (`docs/logging.md`).
|
|
1518
|
+
|
|
1519
|
+
### Error-handling philosophy
|
|
1520
|
+
|
|
1521
|
+
- **Warn, don't throw** on operational/edge conditions. `create*` / `getOrCreate*` return
|
|
1522
|
+
`T | undefined` (closed parent → `undefined` + warn; duplicate id → existing instance + warn).
|
|
1523
|
+
Missing `callId`/`clientId` or a closed observer → a `sample-rejected` event.
|
|
1524
|
+
|
|
1525
|
+
### Packaging & tooling
|
|
1526
|
+
|
|
1527
|
+
- **Server-side, Node.js ≥ 22.** Shipped as a **dual ESM + CommonJS** build (single entry) via
|
|
1528
|
+
`tsup`, with `.d.ts`/`.d.mts` types and sourcemaps; works with both `import` and `require()`.
|
|
1529
|
+
- **CI gate** (lint + typecheck + build + tested with a **coverage threshold**) and **npm Trusted
|
|
1530
|
+
Publishing (OIDC) with provenance**.
|
|
1531
|
+
|
|
1532
|
+
### Documentation
|
|
1533
|
+
|
|
1534
|
+
- A self-sufficient `README.md`; `docs/logging.md`; and design docs for the roadmap, track
|
|
1535
|
+
correlation & detectors, the call-level-detector analysis, and the (deferred) report-generation
|
|
1536
|
+
approach.
|