effect-cloudflare-webrtc 0.0.0-stage → 0.0.0
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 +439 -2
- package/dist/AudioSink-BybkMP2y.d.ts +54 -0
- package/dist/Readable-CJPSx6Uq.js +65 -0
- package/dist/Readable-CJPSx6Uq.js.map +1 -0
- package/dist/Realtime-B5OIHlLR.d.ts +129 -0
- package/dist/Realtime-B6TjV8su.js +195 -0
- package/dist/Realtime-B6TjV8su.js.map +1 -0
- package/dist/RealtimeClient-Bl0Tun5r.js +2488 -0
- package/dist/RealtimeClient-Bl0Tun5r.js.map +1 -0
- package/dist/RealtimeClient-ESFO5vfF.d.ts +412 -0
- package/dist/RealtimeClient-K7oKgsB9.d.ts +1000 -0
- package/dist/chunk-pbuEa-1d.js +13 -0
- package/dist/client/index.d.ts +275 -0
- package/dist/client/index.js +493 -0
- package/dist/client/index.js.map +1 -0
- package/dist/effect/client/index.d.ts +434 -0
- package/dist/effect/client/index.js +2 -0
- package/dist/effect/server/index.d.ts +2 -0
- package/dist/effect/server/index.js +2 -0
- package/dist/react/index.d.ts +44 -0
- package/dist/react/index.js +107 -0
- package/dist/react/index.js.map +1 -0
- package/dist/server/index.d.ts +23 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/package.json +92 -4
|
@@ -0,0 +1,2488 @@
|
|
|
1
|
+
import * as Effect from "effect/Effect";
|
|
2
|
+
import * as Exit from "effect/Exit";
|
|
3
|
+
import * as Layer from "effect/Layer";
|
|
4
|
+
import * as Stream from "effect/Stream";
|
|
5
|
+
import * as SubscriptionRef from "effect/SubscriptionRef";
|
|
6
|
+
import * as Schema from "effect/Schema";
|
|
7
|
+
import * as Context from "effect/Context";
|
|
8
|
+
import * as Fiber from "effect/Fiber";
|
|
9
|
+
import * as Option from "effect/Option";
|
|
10
|
+
import * as Scheduler from "effect/Scheduler";
|
|
11
|
+
import * as Clock from "effect/Clock";
|
|
12
|
+
import * as Deferred from "effect/Deferred";
|
|
13
|
+
import * as PubSub from "effect/PubSub";
|
|
14
|
+
import * as Duration from "effect/Duration";
|
|
15
|
+
import * as Queue from "effect/Queue";
|
|
16
|
+
import * as Cause from "effect/Cause";
|
|
17
|
+
import * as Schedule from "effect/Schedule";
|
|
18
|
+
import * as Equal from "effect/Equal";
|
|
19
|
+
import * as Ref from "effect/Ref";
|
|
20
|
+
import * as Semaphore from "effect/Semaphore";
|
|
21
|
+
import * as FetchHttpClient from "effect/http/FetchHttpClient";
|
|
22
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
23
|
+
import * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
24
|
+
import * as Data from "effect/Data";
|
|
25
|
+
import * as Hash from "effect/Hash";
|
|
26
|
+
import * as RcMap from "effect/RcMap";
|
|
27
|
+
import * as RcRef from "effect/RcRef";
|
|
28
|
+
import * as Pull from "effect/Pull";
|
|
29
|
+
import * as Request from "effect/Request";
|
|
30
|
+
import * as RequestResolver from "effect/RequestResolver";
|
|
31
|
+
//#region src/effect/client/Errors.ts
|
|
32
|
+
/** The request got no response. The outcome on the server is not known. */
|
|
33
|
+
var ApiTransportError = class extends Schema.TaggedError()("ApiTransportError", {
|
|
34
|
+
endpoint: Schema.String,
|
|
35
|
+
cause: Schema.Unknown
|
|
36
|
+
}) {};
|
|
37
|
+
/**
|
|
38
|
+
* The server sent a response that is an error: a status that is not 2xx, or
|
|
39
|
+
* an `errorCode` in the body.
|
|
40
|
+
*/
|
|
41
|
+
var ApiResponseError = class extends Schema.TaggedError()("ApiResponseError", {
|
|
42
|
+
endpoint: Schema.String,
|
|
43
|
+
status: Schema.Number,
|
|
44
|
+
errorCode: Schema.optional(Schema.String),
|
|
45
|
+
errorDescription: Schema.optional(Schema.String)
|
|
46
|
+
}) {};
|
|
47
|
+
/**
|
|
48
|
+
* The server sent a successful response, but its body is not the expected
|
|
49
|
+
* JSON. The outcome on the server is not known.
|
|
50
|
+
*/
|
|
51
|
+
var ApiInvalidResponse = class extends Schema.TaggedError()("ApiInvalidResponse", {
|
|
52
|
+
endpoint: Schema.String,
|
|
53
|
+
status: Schema.Number,
|
|
54
|
+
message: Schema.String
|
|
55
|
+
}) {};
|
|
56
|
+
/**
|
|
57
|
+
* The request was redirected. With `redirect: "manual"` the browser reports
|
|
58
|
+
* status `0`. An expired Cloudflare Access session causes this.
|
|
59
|
+
*/
|
|
60
|
+
var ApiAuthRedirect = class extends Schema.TaggedError()("ApiAuthRedirect", { endpoint: Schema.String }) {};
|
|
61
|
+
const PeerConnectionFailedReason = Schema.Literals([
|
|
62
|
+
"connection-failed",
|
|
63
|
+
"connection-closed",
|
|
64
|
+
"ice-failed",
|
|
65
|
+
"ice-closed",
|
|
66
|
+
"ice-disconnected-timeout"
|
|
67
|
+
]);
|
|
68
|
+
/** The peer connection is not usable any more. */
|
|
69
|
+
var PeerConnectionFailed = class extends Schema.TaggedError()("PeerConnectionFailed", { reason: PeerConnectionFailedReason }) {};
|
|
70
|
+
/**
|
|
71
|
+
* A negotiation step did not complete, and the state of the session on the
|
|
72
|
+
* SFU is not known. The request is not repeated. The session is replaced.
|
|
73
|
+
*/
|
|
74
|
+
var NegotiationOutcomeUnknown = class extends Schema.TaggedError()("NegotiationOutcomeUnknown", {
|
|
75
|
+
step: Schema.String,
|
|
76
|
+
cause: Schema.Unknown
|
|
77
|
+
}) {};
|
|
78
|
+
/**
|
|
79
|
+
* The session failed, and its retry policy ended. A push or a pull that waits
|
|
80
|
+
* for a session cannot continue.
|
|
81
|
+
*/
|
|
82
|
+
var SessionFailed = class extends Schema.TaggedError()("SessionFailed", { error: Schema.Union([
|
|
83
|
+
ApiTransportError,
|
|
84
|
+
ApiResponseError,
|
|
85
|
+
ApiInvalidResponse,
|
|
86
|
+
ApiAuthRedirect,
|
|
87
|
+
PeerConnectionFailed,
|
|
88
|
+
NegotiationOutcomeUnknown
|
|
89
|
+
]) }) {};
|
|
90
|
+
/** One track of a request was refused by the SFU. */
|
|
91
|
+
var TrackError = class extends Schema.TaggedError()("TrackError", {
|
|
92
|
+
trackName: Schema.optional(Schema.String),
|
|
93
|
+
mid: Schema.optional(Schema.String),
|
|
94
|
+
errorCode: Schema.String,
|
|
95
|
+
errorDescription: Schema.optional(Schema.String)
|
|
96
|
+
}) {};
|
|
97
|
+
/** The SFU answered, but the peer connection has no transceiver for the track. */
|
|
98
|
+
var TransceiverNotFound = class extends Schema.TaggedError()("TransceiverNotFound", {
|
|
99
|
+
trackName: Schema.optional(Schema.String),
|
|
100
|
+
mid: Schema.optional(Schema.String)
|
|
101
|
+
}) {};
|
|
102
|
+
/** A browser call on a sender rejected (`replaceTrack`, `setParameters`). */
|
|
103
|
+
var SenderError = class extends Schema.TaggedError()("SenderError", {
|
|
104
|
+
operation: Schema.Literals(["replaceTrack", "setParameters"]),
|
|
105
|
+
cause: Schema.Unknown
|
|
106
|
+
}) {};
|
|
107
|
+
/** A browser call for devices or media rejected. */
|
|
108
|
+
var MediaAccessError = class extends Schema.TaggedError()("MediaAccessError", {
|
|
109
|
+
operation: Schema.Literals([
|
|
110
|
+
"enumerateDevices",
|
|
111
|
+
"getUserMedia",
|
|
112
|
+
"getDisplayMedia"
|
|
113
|
+
]),
|
|
114
|
+
/** The `name` of the browser error, for example "NotAllowedError". */
|
|
115
|
+
errorName: Schema.String,
|
|
116
|
+
message: Schema.String,
|
|
117
|
+
cause: Schema.Unknown
|
|
118
|
+
}) {};
|
|
119
|
+
/** No device of the list gave a healthy track. */
|
|
120
|
+
var DevicesExhausted = class extends Schema.TaggedError()("DevicesExhausted", { kind: Schema.Literals(["audioinput", "videoinput"]) }) {};
|
|
121
|
+
/** A transformation of a content track failed. */
|
|
122
|
+
var TransformFailed = class extends Schema.TaggedError()("TransformFailed", { cause: Schema.Unknown }) {};
|
|
123
|
+
/** The audio output device was not selected. */
|
|
124
|
+
var SinkError = class extends Schema.TaggedError()("SinkError", {
|
|
125
|
+
reason: Schema.Literals(["not-supported", "rejected"]),
|
|
126
|
+
cause: Schema.optional(Schema.Unknown)
|
|
127
|
+
}) {};
|
|
128
|
+
//#endregion
|
|
129
|
+
//#region src/effect/client/internal/identical.ts
|
|
130
|
+
/**
|
|
131
|
+
* The same value or the same object. `Stream.changes` compares by structure,
|
|
132
|
+
* which reads each property of the object. That is slow for a browser
|
|
133
|
+
* object such as a `MediaStreamTrack`, and it does not end for some.
|
|
134
|
+
*/
|
|
135
|
+
const identical = (a, b) => Object.is(a, b) || Option.isOption(a) && Option.isOption(b) && (Option.isSome(a) ? Option.isSome(b) && Object.is(a.value, b.value) : Option.isNone(b));
|
|
136
|
+
//#endregion
|
|
137
|
+
//#region src/effect/client/MediaDevices.ts
|
|
138
|
+
const sameDevice = (a, b) => a.deviceId === b.deviceId && a.groupId === b.groupId && a.kind === b.kind && a.label === b.label;
|
|
139
|
+
/** The two lists have the same devices in the same sequence. */
|
|
140
|
+
const sameDeviceList = (a, b) => a.length === b.length && a.every((device, index) => {
|
|
141
|
+
const other = b[index];
|
|
142
|
+
return other !== void 0 && sameDevice(device, other);
|
|
143
|
+
});
|
|
144
|
+
const stopTracks = (stream) => Effect.sync(() => {
|
|
145
|
+
for (const track of stream.getTracks()) track.stop();
|
|
146
|
+
});
|
|
147
|
+
/**
|
|
148
|
+
* The tracks of the media stream are stopped when the scope closes. An
|
|
149
|
+
* interruption does not wait for the browser: if the media stream arrives
|
|
150
|
+
* after the interruption, its tracks are stopped then. This prevents a
|
|
151
|
+
* device that stays on with no user.
|
|
152
|
+
*/
|
|
153
|
+
const acquireMediaStream = (request) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
154
|
+
const fiber = yield* Effect.forkDetach(request);
|
|
155
|
+
const stream = yield* restore(Fiber.join(fiber)).pipe(Effect.onInterrupt(() => Fiber.await(fiber).pipe(Effect.flatMap((exit) => Exit.isSuccess(exit) ? stopTracks(exit.value) : Effect.void), Effect.forkDetach)));
|
|
156
|
+
yield* Effect.addFinalizer(() => stopTracks(stream));
|
|
157
|
+
return stream;
|
|
158
|
+
}));
|
|
159
|
+
/** Devices, permissions, and media capture. Tests replace this service. */
|
|
160
|
+
var MediaDevices = class MediaDevices extends Context.Service()("effect-cloudflare-webrtc/MediaDevices") {
|
|
161
|
+
static layerBackend = (backend) => Layer.effect(MediaDevices, make$6(backend));
|
|
162
|
+
/** Uses `navigator.mediaDevices` and `navigator.permissions`. */
|
|
163
|
+
static layerBrowser = Layer.effect(MediaDevices, Effect.suspend(() => make$6(browserBackend)));
|
|
164
|
+
};
|
|
165
|
+
const make$6 = (backend) => Effect.gen(function* () {
|
|
166
|
+
const permissionState = (name) => Stream.unwrap(backend.permissionStatus(name).pipe(Effect.map((status) => Stream.fromEventListener(status, "change").pipe(Stream.map(() => status.state), Stream.prepend([status.state]))), Effect.catch(() => Effect.succeed(Stream.make("unknown"))))).pipe(Stream.changesWith(identical));
|
|
167
|
+
const permissionChanges = (name) => permissionState(name).pipe(Stream.drop(1));
|
|
168
|
+
const devices = yield* Stream.mergeAll([
|
|
169
|
+
Stream.make(void 0),
|
|
170
|
+
backend.deviceChanges,
|
|
171
|
+
permissionChanges("camera"),
|
|
172
|
+
permissionChanges("microphone")
|
|
173
|
+
], { concurrency: "unbounded" }).pipe(Stream.mapEffect(() => backend.enumerateDevices.pipe(Effect.map(Option.some), Effect.catch((error) => Effect.logWarning("The device list was not read", error).pipe(Effect.as(Option.none()))))), Stream.filter(Option.isSome), Stream.map((list) => list.value), Stream.changesWith(sameDeviceList), Stream.share({
|
|
174
|
+
capacity: 16,
|
|
175
|
+
replay: 1
|
|
176
|
+
}));
|
|
177
|
+
return MediaDevices.of({
|
|
178
|
+
devices,
|
|
179
|
+
enumerateDevices: backend.enumerateDevices,
|
|
180
|
+
permissionState,
|
|
181
|
+
getUserMedia: (constraints) => acquireMediaStream(backend.getUserMedia(constraints)),
|
|
182
|
+
getDisplayMedia: (options) => acquireMediaStream(backend.getDisplayMedia(options)),
|
|
183
|
+
pageVisible: Stream.map(backend.pageVisible, () => void 0)
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
/** The device list of the `MediaDevices` service. */
|
|
187
|
+
const devices = Stream.unwrap(Effect.gen(function* () {
|
|
188
|
+
return (yield* MediaDevices).devices;
|
|
189
|
+
}));
|
|
190
|
+
const toMediaAccessError = (operation) => (cause) => new MediaAccessError({
|
|
191
|
+
operation,
|
|
192
|
+
errorName: cause instanceof Error ? cause.name : "UnknownError",
|
|
193
|
+
message: cause instanceof Error ? cause.message : String(cause),
|
|
194
|
+
cause
|
|
195
|
+
});
|
|
196
|
+
const browserBackend = {
|
|
197
|
+
enumerateDevices: Effect.tryPromise({
|
|
198
|
+
try: () => navigator.mediaDevices.enumerateDevices(),
|
|
199
|
+
catch: toMediaAccessError("enumerateDevices")
|
|
200
|
+
}),
|
|
201
|
+
deviceChanges: Stream.suspend(() => Stream.fromEventListener(navigator.mediaDevices, "devicechange")),
|
|
202
|
+
permissionStatus: (name) => Effect.tryPromise(() => navigator.permissions.query({ name })),
|
|
203
|
+
getUserMedia: (constraints) => Effect.tryPromise({
|
|
204
|
+
try: () => navigator.mediaDevices.getUserMedia(constraints),
|
|
205
|
+
catch: toMediaAccessError("getUserMedia")
|
|
206
|
+
}),
|
|
207
|
+
getDisplayMedia: (options) => Effect.tryPromise({
|
|
208
|
+
try: () => navigator.mediaDevices.getDisplayMedia(options),
|
|
209
|
+
catch: toMediaAccessError("getDisplayMedia")
|
|
210
|
+
}),
|
|
211
|
+
pageVisible: Stream.suspend(() => Stream.fromEventListener(document, "visibilitychange").pipe(Stream.filter(() => document.visibilityState === "visible")))
|
|
212
|
+
};
|
|
213
|
+
//#endregion
|
|
214
|
+
//#region src/effect/client/Subscribable.ts
|
|
215
|
+
/**
|
|
216
|
+
* The current value, then the changes. A slow consumer gets the newest value
|
|
217
|
+
* when it is ready, and not the values that it did not keep up with.
|
|
218
|
+
*/
|
|
219
|
+
const latestChanges = (ref) => SubscriptionRef.changes(ref).pipe(Stream.buffer({
|
|
220
|
+
capacity: 1,
|
|
221
|
+
strategy: "sliding"
|
|
222
|
+
}));
|
|
223
|
+
const fromSubscriptionRef = (ref) => ({
|
|
224
|
+
get: SubscriptionRef.get(ref),
|
|
225
|
+
changes: latestChanges(ref)
|
|
226
|
+
});
|
|
227
|
+
const map = (self, f) => ({
|
|
228
|
+
get: Effect.map(self.get, f),
|
|
229
|
+
changes: Stream.map(self.changes, f)
|
|
230
|
+
});
|
|
231
|
+
//#endregion
|
|
232
|
+
//#region src/effect/client/internal/scheduler.ts
|
|
233
|
+
const microtaskScheduler = new Scheduler.MixedScheduler("sync");
|
|
234
|
+
/** Runs the effect, and the fibers that it forks, on microtasks. */
|
|
235
|
+
const withMicrotaskScheduler = (effect) => Effect.provideService(effect, Scheduler.Scheduler, microtaskScheduler);
|
|
236
|
+
//#endregion
|
|
237
|
+
//#region src/effect/client/AudioSink.ts
|
|
238
|
+
/**
|
|
239
|
+
* Plays all attached audio tracks in one `<audio>` element. Closing the
|
|
240
|
+
* scope removes all tracks from the element.
|
|
241
|
+
*/
|
|
242
|
+
const make$5 = (options) => Effect.gen(function* () {
|
|
243
|
+
const media = yield* MediaDevices;
|
|
244
|
+
const element = options.audioElement;
|
|
245
|
+
const mediaStream = new MediaStream();
|
|
246
|
+
let released = false;
|
|
247
|
+
const isPlaying = yield* SubscriptionRef.make(false);
|
|
248
|
+
const devices = yield* SubscriptionRef.make([]);
|
|
249
|
+
const selectSink = (sinkId) => Effect.suspend(() => element.setSinkId === void 0 ? Effect.fail(new SinkError({ reason: "not-supported" })) : Effect.tryPromise({
|
|
250
|
+
try: () => element.setSinkId?.(sinkId) ?? Promise.resolve(),
|
|
251
|
+
catch: (cause) => new SinkError({
|
|
252
|
+
reason: "rejected",
|
|
253
|
+
cause
|
|
254
|
+
})
|
|
255
|
+
}));
|
|
256
|
+
const background = (effect) => effect.pipe(withMicrotaskScheduler, Effect.forkScoped);
|
|
257
|
+
yield* background(media.devices.pipe(Stream.map((list) => list.filter((device) => device.kind === "audiooutput")), Stream.changesWith(sameDeviceList), Stream.runForEach((list) => SubscriptionRef.set(devices, list))));
|
|
258
|
+
const listen = (type, handler) => Effect.acquireRelease(Effect.sync(() => {
|
|
259
|
+
const listener = () => {
|
|
260
|
+
Effect.runFork(handler);
|
|
261
|
+
};
|
|
262
|
+
element.addEventListener(type, listener);
|
|
263
|
+
return listener;
|
|
264
|
+
}), (listener) => Effect.sync(() => element.removeEventListener(type, listener)));
|
|
265
|
+
yield* listen("canplay", Effect.tryPromise(() => element.play()).pipe(Effect.catch(() => SubscriptionRef.set(isPlaying, false))));
|
|
266
|
+
yield* listen("playing", SubscriptionRef.set(isPlaying, true));
|
|
267
|
+
yield* listen("pause", SubscriptionRef.set(isPlaying, false));
|
|
268
|
+
const refresh = Effect.sync(() => {
|
|
269
|
+
if (!released) element.srcObject = mediaStream;
|
|
270
|
+
});
|
|
271
|
+
yield* Effect.acquireRelease(refresh, () => Effect.sync(() => {
|
|
272
|
+
released = true;
|
|
273
|
+
for (const track of mediaStream.getTracks()) mediaStream.removeTrack(track);
|
|
274
|
+
element.srcObject = null;
|
|
275
|
+
}));
|
|
276
|
+
if (options.sinkId !== void 0 && element.setSinkId !== void 0) yield* selectSink(options.sinkId).pipe(Effect.catch((error) => Effect.logWarning("The audio output device was not selected", error)));
|
|
277
|
+
return {
|
|
278
|
+
attach: (track) => Effect.gen(function* () {
|
|
279
|
+
let current;
|
|
280
|
+
const replace = (next) => Effect.suspend(() => {
|
|
281
|
+
if (released) return Effect.void;
|
|
282
|
+
if (current !== void 0) mediaStream.removeTrack(current);
|
|
283
|
+
if (next !== void 0) mediaStream.addTrack(next);
|
|
284
|
+
current = next;
|
|
285
|
+
return refresh;
|
|
286
|
+
});
|
|
287
|
+
yield* Effect.addFinalizer(() => replace(void 0));
|
|
288
|
+
yield* background(track.pipe(Stream.runForEach(replace), Effect.catch((error) => Effect.logWarning("An attached track stream failed", error))));
|
|
289
|
+
}),
|
|
290
|
+
isSinkIdSupported: element.setSinkId !== void 0,
|
|
291
|
+
setSinkId: selectSink,
|
|
292
|
+
availableDevices: fromSubscriptionRef(devices),
|
|
293
|
+
isPlaying: fromSubscriptionRef(isPlaying)
|
|
294
|
+
};
|
|
295
|
+
});
|
|
296
|
+
const AudioSink = { make: make$5 };
|
|
297
|
+
//#endregion
|
|
298
|
+
//#region src/effect/client/internal/devicePriority.ts
|
|
299
|
+
function resolveDevice(devices, ref) {
|
|
300
|
+
const exact = ref.deviceId && devices.find((d) => d.kind === ref.kind && d.deviceId === ref.deviceId);
|
|
301
|
+
if (exact) return exact;
|
|
302
|
+
if (!ref.label) return void 0;
|
|
303
|
+
const matches = devices.filter((d) => d.kind === ref.kind && d.label === ref.label);
|
|
304
|
+
return matches.length === 1 ? matches[0] : void 0;
|
|
305
|
+
}
|
|
306
|
+
function rankDevices(devices, choices, failures, automatic) {
|
|
307
|
+
const selected = choices.map((ref) => resolveDevice(devices, ref));
|
|
308
|
+
const failed = new Set(failures.map((ref) => resolveDevice(devices, ref)));
|
|
309
|
+
const fallback = automatic && resolveDevice(devices, automatic);
|
|
310
|
+
return devices.map((device) => {
|
|
311
|
+
const index = selected.indexOf(device);
|
|
312
|
+
const label = device.label.toLowerCase();
|
|
313
|
+
const unlikely = label.includes("virtual") || label.includes("iphone microphone");
|
|
314
|
+
if (failed.has(device)) return {
|
|
315
|
+
device,
|
|
316
|
+
rank: choices.length + (unlikely ? 3 : 2),
|
|
317
|
+
reason: "recent-failure"
|
|
318
|
+
};
|
|
319
|
+
if (index >= 0) return {
|
|
320
|
+
device,
|
|
321
|
+
rank: index,
|
|
322
|
+
reason: index === 0 ? "preferred" : "previously-selected"
|
|
323
|
+
};
|
|
324
|
+
if (device === fallback) return {
|
|
325
|
+
device,
|
|
326
|
+
rank: choices.length,
|
|
327
|
+
reason: "local-fallback"
|
|
328
|
+
};
|
|
329
|
+
return {
|
|
330
|
+
device,
|
|
331
|
+
rank: choices.length + (unlikely ? 3 : 1),
|
|
332
|
+
reason: unlikely ? "unlikely" : "default"
|
|
333
|
+
};
|
|
334
|
+
}).sort((a, b) => a.rank - b.rank);
|
|
335
|
+
}
|
|
336
|
+
//#endregion
|
|
337
|
+
//#region src/effect/client/DevicePreferences.ts
|
|
338
|
+
const minute = 6e4;
|
|
339
|
+
const day = 1440 * minute;
|
|
340
|
+
const kinds = [
|
|
341
|
+
"audioinput",
|
|
342
|
+
"audiooutput",
|
|
343
|
+
"videoinput"
|
|
344
|
+
];
|
|
345
|
+
const preferredKey = (kind) => `effect-cloudflare-webrtc:${kind}-preferred-device`;
|
|
346
|
+
const deprioritizedKey = (kind) => `effect-cloudflare-webrtc:${kind}-deprioritized-devices`;
|
|
347
|
+
const isKind = (value) => kinds.some((kind) => kind === value);
|
|
348
|
+
function toReference(value) {
|
|
349
|
+
if (typeof value === "object" && value !== null && "kind" in value && "label" in value && isKind(value.kind) && typeof value.label === "string") return {
|
|
350
|
+
kind: value.kind,
|
|
351
|
+
label: value.label,
|
|
352
|
+
..."deviceId" in value && typeof value.deviceId === "string" && value.deviceId ? { deviceId: value.deviceId } : {}
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
function readJson(storage, key) {
|
|
356
|
+
try {
|
|
357
|
+
const item = storage.getItem(key);
|
|
358
|
+
return item === null ? void 0 : JSON.parse(item);
|
|
359
|
+
} catch {
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
function read(storage, kind) {
|
|
364
|
+
const list = readJson(storage, deprioritizedKey(kind));
|
|
365
|
+
const saved = readJson(storage, preferredKey(kind));
|
|
366
|
+
return {
|
|
367
|
+
choices: [saved, ...typeof saved === "object" && saved && "history" in saved && Array.isArray(saved.history) ? saved.history : []].map(toReference).filter((r) => r?.kind === kind && !!r.label),
|
|
368
|
+
deprioritized: Array.isArray(list) ? list.flatMap((item) => {
|
|
369
|
+
const ref = toReference(item);
|
|
370
|
+
if (ref?.kind !== kind || !Number.isFinite(item.retryAt) || !Number.isSafeInteger(item.failures) || item.failures < 1) return [];
|
|
371
|
+
return [{
|
|
372
|
+
...ref,
|
|
373
|
+
retryAt: Number(item.retryAt),
|
|
374
|
+
failures: Number(item.failures)
|
|
375
|
+
}];
|
|
376
|
+
}) : []
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
const readAll = (storage) => ({
|
|
380
|
+
audioinput: read(storage, "audioinput"),
|
|
381
|
+
audiooutput: read(storage, "audiooutput"),
|
|
382
|
+
videoinput: read(storage, "videoinput")
|
|
383
|
+
});
|
|
384
|
+
function write(storage, kind, value) {
|
|
385
|
+
try {
|
|
386
|
+
const [first, ...history] = value.choices;
|
|
387
|
+
if (first) storage.setItem(preferredKey(kind), JSON.stringify({
|
|
388
|
+
...first,
|
|
389
|
+
history
|
|
390
|
+
}));
|
|
391
|
+
storage.setItem(deprioritizedKey(kind), JSON.stringify(value.deprioritized));
|
|
392
|
+
storage.notify();
|
|
393
|
+
} catch {}
|
|
394
|
+
}
|
|
395
|
+
const sameReference = (a, b) => a?.kind === b?.kind && a?.label === b?.label && a?.deviceId === b?.deviceId;
|
|
396
|
+
const sameFailures = (a, b) => a.length === b.length && a.every((f, i) => sameReference(f, b[i]) && f.retryAt === b[i]?.retryAt && f.failures === b[i]?.failures);
|
|
397
|
+
const sameRanking = (a, b) => a.choices.length === b.choices.length && a.choices.every((r, i) => sameReference(r, b.choices[i])) && sameFailures(a.deprioritized, b.deprioritized);
|
|
398
|
+
const samePreferences = (a, b) => kinds.every((kind) => sameRanking(a[kind], b[kind]));
|
|
399
|
+
const reference = (device) => ({
|
|
400
|
+
kind: device.kind,
|
|
401
|
+
label: device.label,
|
|
402
|
+
...device.deviceId ? { deviceId: device.deviceId } : {}
|
|
403
|
+
});
|
|
404
|
+
/** The preferred device and the deprioritized devices of the user. */
|
|
405
|
+
var DevicePreferences = class DevicePreferences extends Context.Service()("effect-cloudflare-webrtc/DevicePreferences") {
|
|
406
|
+
static layerStorage = (storage) => Layer.effect(DevicePreferences, make$4(storage));
|
|
407
|
+
/** The preferences are lost when the page closes. */
|
|
408
|
+
static layerMemory = Layer.effect(DevicePreferences, Effect.suspend(() => make$4(memoryStorage())));
|
|
409
|
+
/**
|
|
410
|
+
* Keeps the preferences in `localStorage`, and follows the changes of
|
|
411
|
+
* other tabs. If `localStorage` is not available, the preferences stay in
|
|
412
|
+
* memory.
|
|
413
|
+
*/
|
|
414
|
+
static layerLocalStorage = Layer.effect(DevicePreferences, Effect.suspend(() => make$4(browserStorage)));
|
|
415
|
+
};
|
|
416
|
+
const make$4 = (storage) => Effect.gen(function* () {
|
|
417
|
+
const state = yield* SubscriptionRef.make(readAll(storage));
|
|
418
|
+
yield* storage.changes.pipe(Stream.runForEach(() => SubscriptionRef.update(state, (current) => {
|
|
419
|
+
const next = readAll(storage);
|
|
420
|
+
return samePreferences(current, next) ? current : next;
|
|
421
|
+
})), Effect.forkScoped);
|
|
422
|
+
const update = (kind, f) => SubscriptionRef.update(state, (current) => {
|
|
423
|
+
const next = f(current[kind]);
|
|
424
|
+
write(storage, kind, next);
|
|
425
|
+
return {
|
|
426
|
+
...current,
|
|
427
|
+
[kind]: next
|
|
428
|
+
};
|
|
429
|
+
});
|
|
430
|
+
const change = (action) => (device, available) => {
|
|
431
|
+
if (!device.label) return Effect.void;
|
|
432
|
+
const ref = reference(device);
|
|
433
|
+
const matches = (item) => item.deviceId && item.deviceId === ref.deviceId || (available !== void 0 || !item.deviceId) && resolveDevice(available ?? [device], item)?.deviceId === device.deviceId;
|
|
434
|
+
return Effect.flatMap(Clock.currentTimeMillis, (now) => update(device.kind, (value) => {
|
|
435
|
+
const previous = value.deprioritized.find(matches);
|
|
436
|
+
const deprioritized = value.deprioritized.filter((item) => !matches(item) && item.retryAt + day > now);
|
|
437
|
+
if (action === "fail") {
|
|
438
|
+
const failures = (previous && previous.retryAt + day > now ? previous.failures : 0) + 1;
|
|
439
|
+
deprioritized.push({
|
|
440
|
+
...ref,
|
|
441
|
+
failures,
|
|
442
|
+
retryAt: now + Math.min(day, minute * 2 ** (failures - 1))
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
return {
|
|
446
|
+
choices: action === "select" ? [ref, ...value.choices.filter((item) => !matches(item))] : value.choices,
|
|
447
|
+
deprioritized
|
|
448
|
+
};
|
|
449
|
+
}));
|
|
450
|
+
};
|
|
451
|
+
return DevicePreferences.of({
|
|
452
|
+
ranking: (kind) => ({
|
|
453
|
+
get: Effect.map(SubscriptionRef.get(state), (all) => all[kind]),
|
|
454
|
+
changes: SubscriptionRef.changes(state).pipe(Stream.map((all) => all[kind]), Stream.changesWith(sameRanking))
|
|
455
|
+
}),
|
|
456
|
+
preferred: (kind) => ({
|
|
457
|
+
get: Effect.map(SubscriptionRef.get(state), (all) => all[kind].choices[0]),
|
|
458
|
+
changes: SubscriptionRef.changes(state).pipe(Stream.map((all) => all[kind].choices[0]), Stream.changesWith(sameReference))
|
|
459
|
+
}),
|
|
460
|
+
deprioritized: (kind) => ({
|
|
461
|
+
get: Effect.map(SubscriptionRef.get(state), (all) => all[kind].deprioritized),
|
|
462
|
+
changes: SubscriptionRef.changes(state).pipe(Stream.map((all) => all[kind].deprioritized), Stream.changesWith(sameFailures))
|
|
463
|
+
}),
|
|
464
|
+
setPreferred: change("select"),
|
|
465
|
+
deprioritize: change("fail"),
|
|
466
|
+
recovered: change("recover")
|
|
467
|
+
});
|
|
468
|
+
});
|
|
469
|
+
const memoryStorage = () => {
|
|
470
|
+
const items = /* @__PURE__ */ new Map();
|
|
471
|
+
return {
|
|
472
|
+
getItem: (key) => items.get(key) ?? null,
|
|
473
|
+
setItem: (key, value) => {
|
|
474
|
+
items.set(key, value);
|
|
475
|
+
},
|
|
476
|
+
changes: Stream.never,
|
|
477
|
+
notify: () => {}
|
|
478
|
+
};
|
|
479
|
+
};
|
|
480
|
+
const browserStorage = {
|
|
481
|
+
getItem: (key) => localStorage.getItem(key),
|
|
482
|
+
setItem: (key, value) => localStorage.setItem(key, value),
|
|
483
|
+
changes: Stream.suspend(() => Stream.fromEventListener(window, "storage")),
|
|
484
|
+
notify: () => window.dispatchEvent(new Event("storage"))
|
|
485
|
+
};
|
|
486
|
+
//#endregion
|
|
487
|
+
//#region src/effect/client/TrackSource.ts
|
|
488
|
+
const initialTrackModel = (options) => ({
|
|
489
|
+
shouldBroadcast: options.broadcasting ?? false,
|
|
490
|
+
broadcastConsumers: 0,
|
|
491
|
+
monitorConsumers: 0,
|
|
492
|
+
transforms: options.transforms ?? [],
|
|
493
|
+
content: Option.none(),
|
|
494
|
+
fallback: Option.none()
|
|
495
|
+
});
|
|
496
|
+
const disabled = (source) => ({
|
|
497
|
+
enabled: false,
|
|
498
|
+
tracks: source.tracks.map((track) => ({
|
|
499
|
+
...track,
|
|
500
|
+
shouldBroadcast: false
|
|
501
|
+
}))
|
|
502
|
+
});
|
|
503
|
+
const hasContent = (isEnabled, current) => isEnabled && current.shouldBroadcast && Option.isSome(current.content);
|
|
504
|
+
/** The content track is in the broadcast track, and it has a consumer. */
|
|
505
|
+
const isBroadcastingNow = (isEnabled, current) => hasContent(isEnabled, current) && current.broadcastConsumers > 0;
|
|
506
|
+
/**
|
|
507
|
+
* `TrackSource.make` on a state that more than one broadcast track can
|
|
508
|
+
* share. The screen share uses this for its two tracks.
|
|
509
|
+
*/
|
|
510
|
+
const makeTrackSource = (options, state, index) => Effect.gen(function* () {
|
|
511
|
+
const retain = options.keepSourceAlive ?? false;
|
|
512
|
+
const errors = yield* PubSub.unbounded();
|
|
513
|
+
const trackOf = (source) => source.tracks[index] ?? initialTrackModel({});
|
|
514
|
+
const updateSource = (f) => SubscriptionRef.update(state, (current) => {
|
|
515
|
+
const [enabled, track] = f(current.enabled, trackOf(current));
|
|
516
|
+
return {
|
|
517
|
+
enabled,
|
|
518
|
+
tracks: current.tracks.map((item, i) => i === index ? track : item)
|
|
519
|
+
};
|
|
520
|
+
});
|
|
521
|
+
const update = (f) => updateSource((enabled, current) => [enabled, f(current)]);
|
|
522
|
+
const derive = (f) => SubscriptionRef.changes(state).pipe(Stream.map((current) => f(current.enabled, trackOf(current))), Stream.changesWith(identical));
|
|
523
|
+
const subscribable = (f) => ({
|
|
524
|
+
get: Effect.map(SubscriptionRef.get(state), (current) => f(current.enabled, trackOf(current))),
|
|
525
|
+
changes: derive(f)
|
|
526
|
+
});
|
|
527
|
+
const enable = updateSource((_, current) => [true, current]);
|
|
528
|
+
const stopBroadcasting = update((current) => ({
|
|
529
|
+
...current,
|
|
530
|
+
shouldBroadcast: false
|
|
531
|
+
}));
|
|
532
|
+
const disable = SubscriptionRef.update(state, options.explicit ? (current) => ({
|
|
533
|
+
...current,
|
|
534
|
+
enabled: false
|
|
535
|
+
}) : disabled);
|
|
536
|
+
const startBroadcasting = updateSource((enabled, current) => [options.explicit ? enabled : true, {
|
|
537
|
+
...current,
|
|
538
|
+
shouldBroadcast: true
|
|
539
|
+
}]);
|
|
540
|
+
const contentWanted = (isEnabled, current) => isEnabled && (options.explicit !== void 0 || current.monitorConsumers > 0 || current.broadcastConsumers > 0 && (current.shouldBroadcast || retain));
|
|
541
|
+
const fallbackWanted = (isEnabled, current) => current.broadcastConsumers > 0 || current.monitorConsumers > 0 && !isEnabled;
|
|
542
|
+
const sourceFailed = (error) => PubSub.publish(errors, error).pipe(Effect.andThen(disable), Effect.andThen(options.explicit?.failed(error) ?? Effect.void), Effect.uninterruptible);
|
|
543
|
+
/** Runs the content source, and applies the transforms to it. */
|
|
544
|
+
const runContent = Effect.gen(function* () {
|
|
545
|
+
const raw = yield* SubscriptionRef.make(Option.none());
|
|
546
|
+
yield* Stream.zipLatest(SubscriptionRef.changes(raw).pipe(Stream.filter(Option.isSome), Stream.map((track) => track.value)), derive((_, current) => current.transforms)).pipe(Stream.switchMap(([track, transforms]) => Stream.fromEffect(Effect.gen(function* () {
|
|
547
|
+
let transformed = track;
|
|
548
|
+
for (const transform of transforms) transformed = yield* transform(transformed).pipe(Effect.mapError((cause) => new TransformFailed({ cause })));
|
|
549
|
+
yield* update((current) => ({
|
|
550
|
+
...current,
|
|
551
|
+
content: Option.some(transformed)
|
|
552
|
+
}));
|
|
553
|
+
yield* options.explicit?.ready ?? Effect.void;
|
|
554
|
+
return yield* Effect.never;
|
|
555
|
+
}).pipe(Effect.scoped, Effect.catch(sourceFailed)))), Stream.runDrain, Effect.forkScoped);
|
|
556
|
+
yield* options.contentTrack.pipe(Stream.runForEach((track) => SubscriptionRef.set(raw, Option.some(track))));
|
|
557
|
+
}).pipe(Effect.scoped, Effect.andThen(disable), Effect.catch(sourceFailed), Effect.ensuring(update((current) => ({
|
|
558
|
+
...current,
|
|
559
|
+
content: Option.none()
|
|
560
|
+
}))));
|
|
561
|
+
const runFallback = options.fallbackTrack.pipe(Stream.runForEach((track) => update((current) => ({
|
|
562
|
+
...current,
|
|
563
|
+
fallback: Option.some(track)
|
|
564
|
+
}))), Effect.ensuring(update((current) => ({
|
|
565
|
+
...current,
|
|
566
|
+
fallback: Option.none()
|
|
567
|
+
}))));
|
|
568
|
+
const runWhile = (wanted, effect) => derive(wanted).pipe(Stream.switchMap((isWanted) => isWanted ? Stream.fromEffect(effect) : Stream.empty), Stream.runDrain, withMicrotaskScheduler, Effect.forkScoped);
|
|
569
|
+
yield* runWhile(contentWanted, runContent);
|
|
570
|
+
yield* runWhile(fallbackWanted, runFallback);
|
|
571
|
+
const output = (consumers, select) => Stream.unwrap(Effect.acquireRelease(update((current) => ({
|
|
572
|
+
...current,
|
|
573
|
+
[consumers]: current[consumers] + 1
|
|
574
|
+
})), () => update((current) => ({
|
|
575
|
+
...current,
|
|
576
|
+
[consumers]: current[consumers] - 1
|
|
577
|
+
}))).pipe(Effect.as(derive(select).pipe(Stream.filter(Option.isSome), Stream.map((track) => track.value), Stream.changesWith(identical)))));
|
|
578
|
+
return {
|
|
579
|
+
broadcastTrack: output("broadcastConsumers", (isEnabled, current) => hasContent(isEnabled, current) ? current.content : current.fallback),
|
|
580
|
+
localMonitorTrack: output("monitorConsumers", (isEnabled, current) => isEnabled ? current.content : current.fallback),
|
|
581
|
+
isEnabled: subscribable((isEnabled) => isEnabled),
|
|
582
|
+
isBroadcasting: subscribable(isBroadcastingNow),
|
|
583
|
+
enable,
|
|
584
|
+
disable,
|
|
585
|
+
toggleEnabled: SubscriptionRef.update(state, (current) => current.enabled ? disabled(current) : {
|
|
586
|
+
...current,
|
|
587
|
+
enabled: true
|
|
588
|
+
}),
|
|
589
|
+
startBroadcasting,
|
|
590
|
+
stopBroadcasting,
|
|
591
|
+
toggleBroadcasting: updateSource((isEnabled, current) => current.shouldBroadcast ? [isEnabled, {
|
|
592
|
+
...current,
|
|
593
|
+
shouldBroadcast: false
|
|
594
|
+
}] : [options.explicit ? isEnabled : true, {
|
|
595
|
+
...current,
|
|
596
|
+
shouldBroadcast: true
|
|
597
|
+
}]),
|
|
598
|
+
errors: Stream.fromPubSub(errors),
|
|
599
|
+
addTransform: (transform) => Effect.acquireRelease(update((current) => ({
|
|
600
|
+
...current,
|
|
601
|
+
transforms: [...current.transforms, transform]
|
|
602
|
+
})), () => update((current) => ({
|
|
603
|
+
...current,
|
|
604
|
+
transforms: current.transforms.filter((item) => item !== transform)
|
|
605
|
+
})))
|
|
606
|
+
};
|
|
607
|
+
});
|
|
608
|
+
/**
|
|
609
|
+
* A track for `RealtimeClient.push` that changes between a content track and a
|
|
610
|
+
* fallback track. The change uses `replaceTrack`, so there is no new
|
|
611
|
+
* negotiation and other parties do not pull again.
|
|
612
|
+
*/
|
|
613
|
+
const make$3 = (options) => Effect.flatMap(SubscriptionRef.make({
|
|
614
|
+
enabled: options.enabled ?? true,
|
|
615
|
+
tracks: [initialTrackModel(options)]
|
|
616
|
+
}), (state) => makeTrackSource(options, state, 0));
|
|
617
|
+
const TrackSource = { make: make$3 };
|
|
618
|
+
//#endregion
|
|
619
|
+
//#region src/effect/client/FallbackTracks.ts
|
|
620
|
+
/**
|
|
621
|
+
* One instance for the page. It is made for the first consumer and closed
|
|
622
|
+
* when the last consumer goes away.
|
|
623
|
+
*/
|
|
624
|
+
function sharedForPage(make) {
|
|
625
|
+
let consumers = 0;
|
|
626
|
+
let current;
|
|
627
|
+
return Stream.unwrap(Effect.acquireRelease(Effect.sync(() => {
|
|
628
|
+
consumers++;
|
|
629
|
+
current ??= make();
|
|
630
|
+
return current.value;
|
|
631
|
+
}), () => Effect.sync(() => {
|
|
632
|
+
consumers--;
|
|
633
|
+
if (consumers === 0) {
|
|
634
|
+
current?.close();
|
|
635
|
+
current = void 0;
|
|
636
|
+
}
|
|
637
|
+
})).pipe(Effect.map((value) => Stream.concat(Stream.make(value), Stream.never))));
|
|
638
|
+
}
|
|
639
|
+
const userGestureEvents = [
|
|
640
|
+
"click",
|
|
641
|
+
"contextmenu",
|
|
642
|
+
"auxclick",
|
|
643
|
+
"dblclick",
|
|
644
|
+
"mousedown",
|
|
645
|
+
"mouseup",
|
|
646
|
+
"pointerup",
|
|
647
|
+
"touchend",
|
|
648
|
+
"keydown",
|
|
649
|
+
"keyup"
|
|
650
|
+
];
|
|
651
|
+
let audioContextStartedBefore = false;
|
|
652
|
+
/**
|
|
653
|
+
* An audio track that cannot be heard. It sends a small quantity of data,
|
|
654
|
+
* which lets a push complete while the microphone is muted.
|
|
655
|
+
*/
|
|
656
|
+
const inaudibleAudioTrack = sharedForPage(() => {
|
|
657
|
+
const audioContext = new AudioContext();
|
|
658
|
+
const oscillator = audioContext.createOscillator();
|
|
659
|
+
oscillator.type = "triangle";
|
|
660
|
+
oscillator.frequency.setValueAtTime(20, audioContext.currentTime);
|
|
661
|
+
const gain = audioContext.createGain();
|
|
662
|
+
gain.gain.setValueAtTime(0, audioContext.currentTime);
|
|
663
|
+
oscillator.connect(gain);
|
|
664
|
+
const destination = audioContext.createMediaStreamDestination();
|
|
665
|
+
gain.connect(destination);
|
|
666
|
+
const [track] = destination.stream.getAudioTracks();
|
|
667
|
+
if (track === void 0) throw new Error("The audio context gave no audio track");
|
|
668
|
+
let oscillatorStarted = false;
|
|
669
|
+
const removeGestureListeners = () => {
|
|
670
|
+
for (const gesture of userGestureEvents) document.removeEventListener(gesture, resume, { capture: true });
|
|
671
|
+
};
|
|
672
|
+
const resume = () => {
|
|
673
|
+
audioContext.resume().then(removeGestureListeners, () => {});
|
|
674
|
+
};
|
|
675
|
+
const onStateChange = () => {
|
|
676
|
+
const state = audioContext.state;
|
|
677
|
+
if (state === "running") {
|
|
678
|
+
audioContextStartedBefore = true;
|
|
679
|
+
if (!oscillatorStarted) {
|
|
680
|
+
oscillator.start();
|
|
681
|
+
oscillatorStarted = true;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
if (state === "suspended" || state === "interrupted") resume();
|
|
685
|
+
};
|
|
686
|
+
audioContext.addEventListener("statechange", onStateChange);
|
|
687
|
+
if (audioContextStartedBefore) resume();
|
|
688
|
+
else for (const gesture of userGestureEvents) document.addEventListener(gesture, resume, { capture: true });
|
|
689
|
+
return {
|
|
690
|
+
value: track,
|
|
691
|
+
close: () => {
|
|
692
|
+
track.stop();
|
|
693
|
+
audioContext.removeEventListener("statechange", onStateChange);
|
|
694
|
+
removeGestureListeners();
|
|
695
|
+
audioContext.close().catch(() => {});
|
|
696
|
+
}
|
|
697
|
+
};
|
|
698
|
+
});
|
|
699
|
+
/**
|
|
700
|
+
* A black video track of 1280x720. The canvas is drawn again each second,
|
|
701
|
+
* because a frame is sent only when the canvas changes.
|
|
702
|
+
*/
|
|
703
|
+
const blackVideoTrack = sharedForPage(() => {
|
|
704
|
+
const canvas = document.createElement("canvas");
|
|
705
|
+
canvas.width = 1280;
|
|
706
|
+
canvas.height = 720;
|
|
707
|
+
const context = canvas.getContext("2d");
|
|
708
|
+
const draw = () => {
|
|
709
|
+
if (context === null) return;
|
|
710
|
+
context.fillStyle = "black";
|
|
711
|
+
context.fillRect(0, 0, canvas.width, canvas.height);
|
|
712
|
+
};
|
|
713
|
+
draw();
|
|
714
|
+
const interval = setInterval(draw, 1e3);
|
|
715
|
+
const [track] = canvas.captureStream().getVideoTracks();
|
|
716
|
+
if (track === void 0) {
|
|
717
|
+
clearInterval(interval);
|
|
718
|
+
throw new Error("The canvas gave no video track");
|
|
719
|
+
}
|
|
720
|
+
return {
|
|
721
|
+
value: track,
|
|
722
|
+
close: () => {
|
|
723
|
+
track.stop();
|
|
724
|
+
clearInterval(interval);
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
});
|
|
728
|
+
//#endregion
|
|
729
|
+
//#region src/effect/client/ResilientTrack.ts
|
|
730
|
+
/** A track is healthy when it is live and not muted. */
|
|
731
|
+
const trackIsHealthy = (track) => !track.muted && track.readyState === "live";
|
|
732
|
+
const listChangeDelay = Duration.millis(50);
|
|
733
|
+
const reacquisitionResetMillis = 1e4;
|
|
734
|
+
const maxReacquisitions = 3;
|
|
735
|
+
/**
|
|
736
|
+
* A track from the first device of the list that gives a healthy track.
|
|
737
|
+
*
|
|
738
|
+
* - A device that is not found, is in use, or gives a track that is not
|
|
739
|
+
* healthy is skipped.
|
|
740
|
+
* - When the track ends, the next device is tried.
|
|
741
|
+
* - When the track becomes muted, or is not healthy when the page becomes
|
|
742
|
+
* visible, the same device is acquired again. After three reacquisitions
|
|
743
|
+
* in a row, the device is treated as failed.
|
|
744
|
+
* - When the list changes and its first device is not the active device,
|
|
745
|
+
* the devices are tried again from the top.
|
|
746
|
+
*
|
|
747
|
+
* The stream fails with `DevicesExhausted` when no device is left, and with
|
|
748
|
+
* `MediaAccessError` for all other browser errors, for example
|
|
749
|
+
* `NotAllowedError`.
|
|
750
|
+
*
|
|
751
|
+
* The stream is not shared. Each run acquires a device.
|
|
752
|
+
*/
|
|
753
|
+
const resilientTrack = (options) => Stream.callback((queue) => Effect.gen(function* () {
|
|
754
|
+
const media = yield* MediaDevices;
|
|
755
|
+
const { kind, constraints = {} } = options;
|
|
756
|
+
const priority = yield* SubscriptionRef.make(Option.none());
|
|
757
|
+
yield* (options.devicePriority ?? media.devices).pipe(Stream.map((list) => list.filter((device) => device.kind === kind)), Stream.changesWith(sameDeviceList), Stream.runForEach((list) => SubscriptionRef.set(priority, Option.some(list))), Effect.forkScoped);
|
|
758
|
+
const lists = SubscriptionRef.changes(priority).pipe(Stream.filter(Option.isSome), Stream.map((list) => list.value));
|
|
759
|
+
const currentList = Stream.runHead(lists).pipe(Effect.map(Option.getOrElse(() => [])));
|
|
760
|
+
const request = (device) => {
|
|
761
|
+
const track = {
|
|
762
|
+
...constraints,
|
|
763
|
+
...device.deviceId === "" ? {} : { deviceId: { exact: device.deviceId } },
|
|
764
|
+
...device.groupId === "" ? {} : { groupId: { exact: device.groupId } }
|
|
765
|
+
};
|
|
766
|
+
return kind === "videoinput" ? { video: track } : { audio: track };
|
|
767
|
+
};
|
|
768
|
+
/** The device that the browser used for a request with no device. */
|
|
769
|
+
const reportSelection = (track) => Effect.gen(function* () {
|
|
770
|
+
const report = options.onUnconstrainedDeviceSelection;
|
|
771
|
+
if (report === void 0) return;
|
|
772
|
+
const settings = track.getSettings();
|
|
773
|
+
const selected = (yield* media.enumerateDevices.pipe(Effect.catch(() => Effect.succeed([])))).find((device) => device.kind === kind && device.deviceId !== "" && device.deviceId === settings.deviceId && (settings.groupId === void 0 || device.groupId === settings.groupId));
|
|
774
|
+
if (selected !== void 0) yield* report(selected);
|
|
775
|
+
});
|
|
776
|
+
const attempt = (device, usedList) => Effect.gen(function* () {
|
|
777
|
+
if (options.priorityReason) yield* Effect.annotateCurrentSpan("device.priority.reason", yield* options.priorityReason(device));
|
|
778
|
+
yield* Effect.logDebug(`Requesting the device "${device.label}"`);
|
|
779
|
+
const capture = media.getUserMedia(request(device)).pipe(Effect.map(Option.some), Effect.catchIf((error) => error.errorName === "NotFoundError" || error.errorName === "NotReadableError", () => Effect.succeed(Option.none())));
|
|
780
|
+
const changed = lists.pipe(Stream.filter((list) => list[0]?.deviceId !== usedList[0]?.deviceId), Stream.runHead, Effect.as("restart"));
|
|
781
|
+
const stream = yield* device.deviceId === "" ? capture : Effect.raceFirst(capture, changed);
|
|
782
|
+
if (stream === "restart") return {
|
|
783
|
+
outcome: "restart",
|
|
784
|
+
usedMillis: 0
|
|
785
|
+
};
|
|
786
|
+
if (Option.isNone(stream)) {
|
|
787
|
+
yield* Effect.logDebug(`The device "${device.label}" is not available`);
|
|
788
|
+
return {
|
|
789
|
+
outcome: "next",
|
|
790
|
+
usedMillis: 0
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
yield* Effect.logDebug(`The device "${device.label}" gave a track`);
|
|
794
|
+
const [track] = kind === "videoinput" ? stream.value.getVideoTracks() : stream.value.getAudioTracks();
|
|
795
|
+
if (track === void 0) return {
|
|
796
|
+
outcome: "next",
|
|
797
|
+
usedMillis: 0
|
|
798
|
+
};
|
|
799
|
+
if (!trackIsHealthy(track)) {
|
|
800
|
+
yield* Effect.logDebug(`The track of the device "${device.label}" is not healthy`);
|
|
801
|
+
if (options.onDeviceFailure !== void 0) yield* options.onDeviceFailure(device);
|
|
802
|
+
return {
|
|
803
|
+
outcome: "next",
|
|
804
|
+
usedMillis: 0
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
if (device.deviceId === "" && device.groupId === "") yield* reportSelection(track);
|
|
808
|
+
const trackEvents = yield* Queue.unbounded();
|
|
809
|
+
const listen = (type, outcome) => Effect.acquireRelease(Effect.sync(() => {
|
|
810
|
+
const listener = () => {
|
|
811
|
+
Queue.offerUnsafe(trackEvents, outcome);
|
|
812
|
+
};
|
|
813
|
+
track.addEventListener(type, listener);
|
|
814
|
+
return listener;
|
|
815
|
+
}), (listener) => Effect.sync(() => track.removeEventListener(type, listener)));
|
|
816
|
+
yield* listen("ended", "next");
|
|
817
|
+
yield* listen("mute", "again");
|
|
818
|
+
yield* Queue.offer(queue, track);
|
|
819
|
+
if (options.onStableDevice) {
|
|
820
|
+
const stable = options.onStableDevice;
|
|
821
|
+
yield* Effect.sleep("1 minute").pipe(Effect.andThen(Effect.suspend(() => trackIsHealthy(track) ? stable(device) : Effect.void)), Effect.forkScoped);
|
|
822
|
+
}
|
|
823
|
+
const startedAt = yield* Clock.currentTimeMillis;
|
|
824
|
+
const activeDeviceId = track.getSettings().deviceId ?? device.deviceId;
|
|
825
|
+
const notHealthy = media.pageVisible.pipe(Stream.filter(() => !trackIsHealthy(track)), Stream.map(() => "again"));
|
|
826
|
+
const listChanged = lists.pipe(Stream.debounce(listChangeDelay), Stream.filter((list) => !sameDeviceList(list, usedList) && !(list[0]?.deviceId === activeDeviceId && trackIsHealthy(track))), Stream.map(() => "restart"));
|
|
827
|
+
const outcome = yield* Stream.mergeAll([
|
|
828
|
+
Stream.fromQueue(trackEvents),
|
|
829
|
+
notHealthy,
|
|
830
|
+
listChanged
|
|
831
|
+
], { concurrency: "unbounded" }).pipe(Stream.runHead);
|
|
832
|
+
const endedAt = yield* Clock.currentTimeMillis;
|
|
833
|
+
return {
|
|
834
|
+
outcome: Option.getOrElse(outcome, () => "next"),
|
|
835
|
+
usedMillis: endedAt - startedAt
|
|
836
|
+
};
|
|
837
|
+
}).pipe(Effect.annotateLogs({
|
|
838
|
+
kind,
|
|
839
|
+
deviceId: device.deviceId
|
|
840
|
+
}), Effect.scoped, Effect.withSpan("realtime.acquire", { attributes: {
|
|
841
|
+
kind,
|
|
842
|
+
deviceId: device.deviceId
|
|
843
|
+
} }));
|
|
844
|
+
let tried = [];
|
|
845
|
+
while (true) {
|
|
846
|
+
const list = yield* currentList;
|
|
847
|
+
const device = list.find((candidate) => !tried.some((item) => sameDevice(item, candidate)));
|
|
848
|
+
if (device === void 0) return yield* new DevicesExhausted({ kind });
|
|
849
|
+
let result = yield* attempt(device, list);
|
|
850
|
+
let againCount = 0;
|
|
851
|
+
while (result.outcome === "again") {
|
|
852
|
+
if (result.usedMillis >= reacquisitionResetMillis) againCount = 0;
|
|
853
|
+
againCount += 1;
|
|
854
|
+
if (againCount >= maxReacquisitions) {
|
|
855
|
+
yield* Effect.logDebug(`The device "${device.label}" mutes again and again`);
|
|
856
|
+
if (options.onDeviceFailure !== void 0) yield* options.onDeviceFailure(device);
|
|
857
|
+
result = {
|
|
858
|
+
outcome: "next",
|
|
859
|
+
usedMillis: 0
|
|
860
|
+
};
|
|
861
|
+
break;
|
|
862
|
+
}
|
|
863
|
+
result = yield* attempt(device, list);
|
|
864
|
+
}
|
|
865
|
+
tried = result.outcome === "restart" ? [] : [...tried, device];
|
|
866
|
+
}
|
|
867
|
+
}));
|
|
868
|
+
//#endregion
|
|
869
|
+
//#region src/effect/client/DeviceSource.ts
|
|
870
|
+
const devicesOf = (state) => Option.getOrElse(state.devices, () => []);
|
|
871
|
+
const ranked = (state) => rankDevices(devicesOf(state), state.ranking.choices, state.ranking.deprioritized.filter((f) => f.retryAt > state.acquiredAt), state.automatic);
|
|
872
|
+
const priority = (state) => ranked(state).map((item) => item.device);
|
|
873
|
+
const makeDevice = (defaults) => (options = {}, initial) => Effect.gen(function* () {
|
|
874
|
+
const { kind } = defaults;
|
|
875
|
+
const media = yield* MediaDevices;
|
|
876
|
+
const preferences = yield* DevicePreferences;
|
|
877
|
+
const state = yield* SubscriptionRef.make({
|
|
878
|
+
devices: Option.none(),
|
|
879
|
+
ranking: yield* preferences.ranking(kind).get,
|
|
880
|
+
acquiredAt: yield* Clock.currentTimeMillis,
|
|
881
|
+
activeDeviceId: Option.none(),
|
|
882
|
+
permission: "unknown"
|
|
883
|
+
});
|
|
884
|
+
const failures = yield* PubSub.unbounded();
|
|
885
|
+
const follow = (stream, set) => stream.pipe(Stream.runForEach((value) => SubscriptionRef.update(state, (current) => set(current, value))), withMicrotaskScheduler, Effect.forkScoped);
|
|
886
|
+
yield* follow(media.devices.pipe(Stream.map((list) => list.filter((device) => device.kind === kind)), Stream.changesWith(sameDeviceList)), (current, devices) => ({
|
|
887
|
+
...current,
|
|
888
|
+
devices: Option.some(devices)
|
|
889
|
+
}));
|
|
890
|
+
yield* follow(preferences.ranking(kind).changes, (current, ranking) => ({
|
|
891
|
+
...current,
|
|
892
|
+
ranking
|
|
893
|
+
}));
|
|
894
|
+
yield* follow(media.permissionState(defaults.permission), (current, permission) => ({
|
|
895
|
+
...current,
|
|
896
|
+
permission
|
|
897
|
+
}));
|
|
898
|
+
const derived = (f) => ({
|
|
899
|
+
get: Effect.map(SubscriptionRef.get(state), f),
|
|
900
|
+
changes: SubscriptionRef.changes(state).pipe(Stream.map(f), Stream.changesWith(identical))
|
|
901
|
+
});
|
|
902
|
+
const setActiveDeviceId = (activeDeviceId) => SubscriptionRef.update(state, (current) => ({
|
|
903
|
+
...current,
|
|
904
|
+
automatic: Option.isNone(activeDeviceId) ? devicesOf(current).find((d) => d.deviceId === Option.getOrUndefined(current.activeDeviceId)) ?? current.automatic : current.automatic,
|
|
905
|
+
activeDeviceId
|
|
906
|
+
}));
|
|
907
|
+
const contentTrack = resilientTrack({
|
|
908
|
+
kind,
|
|
909
|
+
constraints: options.constraints,
|
|
910
|
+
devicePriority: SubscriptionRef.changes(state).pipe(Stream.filter((current) => Option.isSome(current.devices)), Stream.map(priority), Stream.changesWith(sameDeviceList)),
|
|
911
|
+
priorityReason: (device) => Effect.map(SubscriptionRef.get(state), (current) => ranked(current).find((item) => item.device.deviceId === device.deviceId)?.reason ?? "unknown"),
|
|
912
|
+
onDeviceFailure: (device) => Effect.flatMap(SubscriptionRef.get(state), (current) => preferences.deprioritize(device, devicesOf(current))).pipe(Effect.andThen(PubSub.publish(failures, device))),
|
|
913
|
+
onStableDevice: (device) => Effect.flatMap(SubscriptionRef.get(state), (current) => {
|
|
914
|
+
const devices = devicesOf(current);
|
|
915
|
+
return current.ranking.deprioritized.some((f) => resolveDevice(devices, f)?.deviceId === device.deviceId) ? preferences.recovered(device, devices) : Effect.void;
|
|
916
|
+
}),
|
|
917
|
+
onUnconstrainedDeviceSelection: (automatic) => SubscriptionRef.update(state, (current) => ({
|
|
918
|
+
...current,
|
|
919
|
+
automatic
|
|
920
|
+
}))
|
|
921
|
+
}).pipe(Stream.tap((track) => setActiveDeviceId(Option.fromNullishOr(track.getSettings().deviceId))), Stream.ensuring(setActiveDeviceId(Option.none())), Stream.provideService(MediaDevices, {
|
|
922
|
+
...media,
|
|
923
|
+
getUserMedia: (constraints) => Effect.suspend(() => {
|
|
924
|
+
const first = initial?.(constraints);
|
|
925
|
+
if (!first) return media.getUserMedia(constraints);
|
|
926
|
+
return Effect.flatMap(first, (stream) => {
|
|
927
|
+
return Effect.acquireRelease(Effect.sync(() => {
|
|
928
|
+
const track = (kind === "audioinput" ? stream.getAudioTracks() : stream.getVideoTracks())[0];
|
|
929
|
+
if (!track) return new MediaStream();
|
|
930
|
+
const single = new MediaStream([track]);
|
|
931
|
+
stream.removeTrack(track);
|
|
932
|
+
return single;
|
|
933
|
+
}), (single) => Effect.sync(() => single.getTracks().forEach((track) => track.stop())));
|
|
934
|
+
});
|
|
935
|
+
})
|
|
936
|
+
}));
|
|
937
|
+
let pending;
|
|
938
|
+
yield* Effect.addFinalizer(() => pending ? Deferred.interrupt(pending) : Effect.void);
|
|
939
|
+
const model = yield* SubscriptionRef.make({
|
|
940
|
+
enabled: false,
|
|
941
|
+
tracks: [initialTrackModel(options)]
|
|
942
|
+
});
|
|
943
|
+
const broadcast = yield* makeTrackSource({
|
|
944
|
+
contentTrack,
|
|
945
|
+
fallbackTrack: options.fallbackTrack ?? defaults.fallbackTrack,
|
|
946
|
+
explicit: {
|
|
947
|
+
ready: Effect.suspend(() => pending ? Deferred.succeed(pending, void 0).pipe(Effect.asVoid) : Effect.void),
|
|
948
|
+
failed: (error) => Effect.suspend(() => {
|
|
949
|
+
const waiter = pending;
|
|
950
|
+
pending = void 0;
|
|
951
|
+
return waiter ? Deferred.fail(waiter, error).pipe(Effect.asVoid) : Effect.void;
|
|
952
|
+
})
|
|
953
|
+
}
|
|
954
|
+
}, model, 0);
|
|
955
|
+
const captureState = (ready) => {
|
|
956
|
+
const read = (state) => state.enabled && Option.isSome(state.tracks[0]?.content ?? Option.none()) === ready;
|
|
957
|
+
return {
|
|
958
|
+
get: Effect.map(SubscriptionRef.get(model), read),
|
|
959
|
+
changes: SubscriptionRef.changes(model).pipe(Stream.map(read), Stream.changesWith(identical))
|
|
960
|
+
};
|
|
961
|
+
};
|
|
962
|
+
const acquire = Effect.suspend(() => {
|
|
963
|
+
if (pending) return Deferred.await(pending);
|
|
964
|
+
const waiter = pending = Deferred.makeUnsafe();
|
|
965
|
+
return Effect.flatMap(Clock.currentTimeMillis, (acquiredAt) => SubscriptionRef.update(state, (current) => Option.isSome(current.activeDeviceId) ? current : {
|
|
966
|
+
...current,
|
|
967
|
+
acquiredAt
|
|
968
|
+
})).pipe(Effect.andThen(broadcast.enable), Effect.andThen(Deferred.await(waiter)));
|
|
969
|
+
});
|
|
970
|
+
const startBroadcasting = Effect.andThen(broadcast.startBroadcasting, acquire);
|
|
971
|
+
const toggleBroadcasting = Effect.flatMap(SubscriptionRef.get(model), (current) => current.enabled && current.tracks[0]?.shouldBroadcast ? broadcast.stopBroadcasting : startBroadcasting);
|
|
972
|
+
return {
|
|
973
|
+
broadcastTrack: broadcast.broadcastTrack,
|
|
974
|
+
localMonitorTrack: broadcast.localMonitorTrack,
|
|
975
|
+
isBroadcasting: broadcast.isBroadcasting,
|
|
976
|
+
startBroadcasting,
|
|
977
|
+
stopBroadcasting: broadcast.stopBroadcasting,
|
|
978
|
+
toggleBroadcasting,
|
|
979
|
+
errors: broadcast.errors,
|
|
980
|
+
addTransform: broadcast.addTransform,
|
|
981
|
+
isAcquired: captureState(true),
|
|
982
|
+
isAcquiring: captureState(false),
|
|
983
|
+
acquire,
|
|
984
|
+
release: Effect.suspend(() => {
|
|
985
|
+
const waiter = pending;
|
|
986
|
+
pending = void 0;
|
|
987
|
+
return broadcast.disable.pipe(Effect.andThen(waiter ? Deferred.interrupt(waiter) : Effect.void), Effect.asVoid);
|
|
988
|
+
}),
|
|
989
|
+
permissionState: derived((current) => current.permission),
|
|
990
|
+
availableDevices: {
|
|
991
|
+
get: Effect.map(SubscriptionRef.get(state), (current) => Option.getOrElse(current.devices, () => [])),
|
|
992
|
+
changes: SubscriptionRef.changes(state).pipe(Stream.map((current) => Option.getOrElse(current.devices, () => [])), Stream.changesWith(sameDeviceList))
|
|
993
|
+
},
|
|
994
|
+
activeDevice: derived((current) => {
|
|
995
|
+
const list = priority(current);
|
|
996
|
+
const activeId = Option.getOrUndefined(current.activeDeviceId);
|
|
997
|
+
return list.find((device) => device.deviceId === activeId) ?? list[0];
|
|
998
|
+
}),
|
|
999
|
+
setPreferredDevice: (device) => Effect.flatMap(SubscriptionRef.get(state), (current) => preferences.setPreferred(device, devicesOf(current))),
|
|
1000
|
+
deviceFailures: Stream.fromPubSub(failures)
|
|
1001
|
+
};
|
|
1002
|
+
});
|
|
1003
|
+
const makeMicrophone = makeDevice({
|
|
1004
|
+
kind: "audioinput",
|
|
1005
|
+
permission: "microphone",
|
|
1006
|
+
fallbackTrack: inaudibleAudioTrack
|
|
1007
|
+
});
|
|
1008
|
+
const makeCamera = makeDevice({
|
|
1009
|
+
kind: "videoinput",
|
|
1010
|
+
permission: "camera",
|
|
1011
|
+
fallbackTrack: blackVideoTrack
|
|
1012
|
+
});
|
|
1013
|
+
const MicrophoneSource = { make: (options) => makeMicrophone(options) };
|
|
1014
|
+
const CameraSource = { make: (options) => makeCamera(options) };
|
|
1015
|
+
const jointRequest = () => {
|
|
1016
|
+
const audio = Deferred.makeUnsafe();
|
|
1017
|
+
const video = Deferred.makeUnsafe();
|
|
1018
|
+
const result = Deferred.makeUnsafe();
|
|
1019
|
+
const request = (slot) => (constraints) => Effect.andThen(Deferred.succeed(slot, constraints), Deferred.await(result));
|
|
1020
|
+
return {
|
|
1021
|
+
audio: request(audio),
|
|
1022
|
+
video: request(video),
|
|
1023
|
+
capture: Effect.gen(function* () {
|
|
1024
|
+
const stream = yield* (yield* MediaDevices).getUserMedia({
|
|
1025
|
+
...yield* Deferred.await(audio),
|
|
1026
|
+
...yield* Deferred.await(video)
|
|
1027
|
+
});
|
|
1028
|
+
yield* Deferred.succeed(result, stream);
|
|
1029
|
+
})
|
|
1030
|
+
};
|
|
1031
|
+
};
|
|
1032
|
+
/** Acquire both idle devices in one request or control either device independently. */
|
|
1033
|
+
const MediaSources = { make: (options = {}) => Effect.gen(function* () {
|
|
1034
|
+
const devices = yield* MediaDevices;
|
|
1035
|
+
let audio;
|
|
1036
|
+
let video;
|
|
1037
|
+
const microphone = yield* makeMicrophone(options.microphone, (c) => {
|
|
1038
|
+
const request = audio;
|
|
1039
|
+
audio = void 0;
|
|
1040
|
+
return request?.(c);
|
|
1041
|
+
});
|
|
1042
|
+
const camera = yield* makeCamera(options.camera, (c) => {
|
|
1043
|
+
const request = video;
|
|
1044
|
+
video = void 0;
|
|
1045
|
+
return request?.(c);
|
|
1046
|
+
});
|
|
1047
|
+
const release = Effect.andThen(microphone.release, camera.release);
|
|
1048
|
+
const acquireBoth = Effect.scoped(Effect.gen(function* () {
|
|
1049
|
+
if ((yield* microphone.isAcquiring.get) || (yield* camera.isAcquiring.get) || (yield* microphone.isAcquired.get) || (yield* camera.isAcquired.get)) {
|
|
1050
|
+
yield* microphone.acquire;
|
|
1051
|
+
yield* camera.acquire;
|
|
1052
|
+
return;
|
|
1053
|
+
}
|
|
1054
|
+
const joint = jointRequest();
|
|
1055
|
+
audio = joint.audio;
|
|
1056
|
+
video = joint.video;
|
|
1057
|
+
yield* Effect.all([
|
|
1058
|
+
microphone.acquire,
|
|
1059
|
+
camera.acquire,
|
|
1060
|
+
joint.capture.pipe(Effect.provideService(MediaDevices, devices))
|
|
1061
|
+
], {
|
|
1062
|
+
concurrency: "unbounded",
|
|
1063
|
+
discard: true
|
|
1064
|
+
}).pipe(Effect.onExit((exit) => {
|
|
1065
|
+
audio = video = void 0;
|
|
1066
|
+
return exit._tag === "Failure" ? release : Effect.void;
|
|
1067
|
+
}));
|
|
1068
|
+
}));
|
|
1069
|
+
let running;
|
|
1070
|
+
return {
|
|
1071
|
+
microphone,
|
|
1072
|
+
camera,
|
|
1073
|
+
acquire: Effect.suspend(() => {
|
|
1074
|
+
if (running) return Deferred.await(running);
|
|
1075
|
+
const waiter = running = Deferred.makeUnsafe();
|
|
1076
|
+
return acquireBoth.pipe(Effect.onExit((exit) => {
|
|
1077
|
+
running = void 0;
|
|
1078
|
+
return Deferred.done(waiter, exit);
|
|
1079
|
+
}));
|
|
1080
|
+
}),
|
|
1081
|
+
release
|
|
1082
|
+
};
|
|
1083
|
+
}) };
|
|
1084
|
+
//#endregion
|
|
1085
|
+
//#region src/effect/client/ScreenShareSource.ts
|
|
1086
|
+
const trackOptions = (option) => typeof option === "object" ? option : {};
|
|
1087
|
+
const constraintsOf = (option) => option === false ? void 0 : trackOptions(option).constraints ?? {};
|
|
1088
|
+
const screenTrack = (track) => ({
|
|
1089
|
+
broadcastTrack: track.broadcastTrack,
|
|
1090
|
+
localMonitorTrack: track.localMonitorTrack,
|
|
1091
|
+
isBroadcasting: track.isBroadcasting,
|
|
1092
|
+
startBroadcasting: track.startBroadcasting,
|
|
1093
|
+
stopBroadcasting: track.stopBroadcasting,
|
|
1094
|
+
toggleBroadcasting: track.toggleBroadcasting,
|
|
1095
|
+
errors: track.errors,
|
|
1096
|
+
addTransform: track.addTransform
|
|
1097
|
+
});
|
|
1098
|
+
/**
|
|
1099
|
+
* A screen share: an audio and a video broadcast track from one browser
|
|
1100
|
+
* request. The browser prompt shows when the source is enabled and a track
|
|
1101
|
+
* needs its content.
|
|
1102
|
+
*/
|
|
1103
|
+
const make$2 = (options = {}) => Effect.gen(function* () {
|
|
1104
|
+
const media = yield* MediaDevices;
|
|
1105
|
+
const fallbackAudio = options.fallbackTracks?.audio ?? inaudibleAudioTrack;
|
|
1106
|
+
const fallbackVideo = options.fallbackTracks?.video ?? blackVideoTrack;
|
|
1107
|
+
/**
|
|
1108
|
+
* One request for the two tracks. It ends when one of its tracks ends,
|
|
1109
|
+
* and when the user cancels the prompt.
|
|
1110
|
+
*/
|
|
1111
|
+
const capture = yield* Stream.unwrap(Effect.gen(function* () {
|
|
1112
|
+
const stream = yield* media.getDisplayMedia({
|
|
1113
|
+
audio: constraintsOf(options.audio),
|
|
1114
|
+
video: constraintsOf(options.video)
|
|
1115
|
+
});
|
|
1116
|
+
const ended = yield* Deferred.make();
|
|
1117
|
+
yield* Effect.forEach(stream.getTracks(), (track) => Effect.acquireRelease(Effect.sync(() => {
|
|
1118
|
+
const listener = () => Deferred.doneUnsafe(ended, Effect.void);
|
|
1119
|
+
track.addEventListener("ended", listener);
|
|
1120
|
+
return listener;
|
|
1121
|
+
}), (listener) => Effect.sync(() => track.removeEventListener("ended", listener))));
|
|
1122
|
+
return Stream.concat(Stream.make(stream), Stream.drain(Stream.fromEffect(Deferred.await(ended))));
|
|
1123
|
+
})).pipe(Stream.catchIf((error) => error.errorName === "NotAllowedError", () => Stream.empty), Stream.share({
|
|
1124
|
+
capacity: 4,
|
|
1125
|
+
replay: 1
|
|
1126
|
+
}));
|
|
1127
|
+
const state = yield* SubscriptionRef.make({
|
|
1128
|
+
enabled: options.enabled ?? false,
|
|
1129
|
+
tracks: [initialTrackModel(trackOptions(options.audio)), initialTrackModel(trackOptions(options.video))]
|
|
1130
|
+
});
|
|
1131
|
+
const audio = yield* makeTrackSource({
|
|
1132
|
+
contentTrack: capture.pipe(Stream.switchMap((stream) => {
|
|
1133
|
+
const [track] = stream.getAudioTracks();
|
|
1134
|
+
return track === void 0 ? fallbackAudio.pipe(Stream.interruptWhen(Stream.runDrain(capture))) : Stream.make(track);
|
|
1135
|
+
})),
|
|
1136
|
+
fallbackTrack: fallbackAudio,
|
|
1137
|
+
keepSourceAlive: options.keepSourceAlive
|
|
1138
|
+
}, state, 0);
|
|
1139
|
+
const video = yield* makeTrackSource({
|
|
1140
|
+
contentTrack: capture.pipe(Stream.flatMap((stream) => Stream.fromIterable(stream.getVideoTracks().slice(0, 1)))),
|
|
1141
|
+
fallbackTrack: fallbackVideo,
|
|
1142
|
+
keepSourceAlive: options.keepSourceAlive
|
|
1143
|
+
}, state, 1);
|
|
1144
|
+
const derived = (f) => ({
|
|
1145
|
+
get: Effect.map(SubscriptionRef.get(state), f),
|
|
1146
|
+
changes: SubscriptionRef.changes(state).pipe(Stream.map(f), Stream.changesWith(identical))
|
|
1147
|
+
});
|
|
1148
|
+
const setBroadcasting = (source, shouldBroadcast) => ({
|
|
1149
|
+
enabled: shouldBroadcast ? true : source.enabled,
|
|
1150
|
+
tracks: source.tracks.map((track) => ({
|
|
1151
|
+
...track,
|
|
1152
|
+
shouldBroadcast
|
|
1153
|
+
}))
|
|
1154
|
+
});
|
|
1155
|
+
return {
|
|
1156
|
+
audio: screenTrack(audio),
|
|
1157
|
+
video: screenTrack(video),
|
|
1158
|
+
isEnabled: audio.isEnabled,
|
|
1159
|
+
isBroadcasting: derived((source) => source.tracks.some((track) => isBroadcastingNow(source.enabled, track))),
|
|
1160
|
+
enable: audio.enable,
|
|
1161
|
+
disable: audio.disable,
|
|
1162
|
+
toggleEnabled: audio.toggleEnabled,
|
|
1163
|
+
startBroadcasting: SubscriptionRef.update(state, (source) => setBroadcasting(source, true)),
|
|
1164
|
+
stopBroadcasting: SubscriptionRef.update(state, (source) => setBroadcasting(source, false)),
|
|
1165
|
+
toggleBroadcasting: SubscriptionRef.update(state, (source) => setBroadcasting(source, !source.tracks.some((track) => track.shouldBroadcast)))
|
|
1166
|
+
};
|
|
1167
|
+
});
|
|
1168
|
+
const ScreenShareSource = { make: make$2 };
|
|
1169
|
+
//#endregion
|
|
1170
|
+
//#region src/effect/client/ConnectionStats.ts
|
|
1171
|
+
const defaultStatsInterval = Duration.seconds(2);
|
|
1172
|
+
const Kind = Schema.Literals(["audio", "video"]);
|
|
1173
|
+
const OptionalNumber = Schema.optional(Schema.Number);
|
|
1174
|
+
const OutboundRtp = Schema.Struct({
|
|
1175
|
+
type: Schema.Literal("outbound-rtp"),
|
|
1176
|
+
id: Schema.String,
|
|
1177
|
+
timestamp: Schema.Number,
|
|
1178
|
+
kind: Kind,
|
|
1179
|
+
rid: Schema.optional(Schema.String),
|
|
1180
|
+
bytesSent: Schema.Number,
|
|
1181
|
+
packetsSent: Schema.Number,
|
|
1182
|
+
framesPerSecond: OptionalNumber,
|
|
1183
|
+
qualityLimitationReason: Schema.optional(Schema.Literals([
|
|
1184
|
+
"none",
|
|
1185
|
+
"cpu",
|
|
1186
|
+
"bandwidth",
|
|
1187
|
+
"other"
|
|
1188
|
+
]))
|
|
1189
|
+
});
|
|
1190
|
+
const RemoteInboundRtp = Schema.Struct({
|
|
1191
|
+
type: Schema.Literal("remote-inbound-rtp"),
|
|
1192
|
+
id: Schema.String,
|
|
1193
|
+
localId: Schema.String,
|
|
1194
|
+
packetsLost: Schema.Number,
|
|
1195
|
+
fractionLost: OptionalNumber,
|
|
1196
|
+
jitter: OptionalNumber,
|
|
1197
|
+
roundTripTime: OptionalNumber
|
|
1198
|
+
});
|
|
1199
|
+
const InboundRtp = Schema.Struct({
|
|
1200
|
+
type: Schema.Literal("inbound-rtp"),
|
|
1201
|
+
id: Schema.String,
|
|
1202
|
+
timestamp: Schema.Number,
|
|
1203
|
+
kind: Kind,
|
|
1204
|
+
bytesReceived: Schema.Number,
|
|
1205
|
+
packetsReceived: Schema.Number,
|
|
1206
|
+
packetsLost: Schema.Number,
|
|
1207
|
+
jitter: OptionalNumber,
|
|
1208
|
+
framesPerSecond: OptionalNumber,
|
|
1209
|
+
freezeCount: OptionalNumber,
|
|
1210
|
+
concealedSamples: OptionalNumber,
|
|
1211
|
+
totalSamplesReceived: OptionalNumber
|
|
1212
|
+
});
|
|
1213
|
+
const Transport = Schema.Struct({
|
|
1214
|
+
type: Schema.Literal("transport"),
|
|
1215
|
+
selectedCandidatePairId: Schema.optional(Schema.String)
|
|
1216
|
+
});
|
|
1217
|
+
const CandidatePair = Schema.Struct({
|
|
1218
|
+
type: Schema.Literal("candidate-pair"),
|
|
1219
|
+
id: Schema.String,
|
|
1220
|
+
state: Schema.optional(Schema.String),
|
|
1221
|
+
nominated: Schema.optional(Schema.Boolean),
|
|
1222
|
+
selected: Schema.optional(Schema.Boolean),
|
|
1223
|
+
currentRoundTripTime: OptionalNumber,
|
|
1224
|
+
availableOutgoingBitrate: OptionalNumber,
|
|
1225
|
+
availableIncomingBitrate: OptionalNumber
|
|
1226
|
+
});
|
|
1227
|
+
const KnownStat = Schema.Union([
|
|
1228
|
+
OutboundRtp,
|
|
1229
|
+
RemoteInboundRtp,
|
|
1230
|
+
InboundRtp,
|
|
1231
|
+
Transport,
|
|
1232
|
+
CandidatePair
|
|
1233
|
+
]);
|
|
1234
|
+
const decodeStat = Schema.decodeUnknownOption(KnownStat);
|
|
1235
|
+
const knownStats = (report) => {
|
|
1236
|
+
const stats = [];
|
|
1237
|
+
report.forEach((value) => {
|
|
1238
|
+
const stat = decodeStat(value);
|
|
1239
|
+
if (Option.isSome(stat)) stats.push(stat.value);
|
|
1240
|
+
});
|
|
1241
|
+
return stats;
|
|
1242
|
+
};
|
|
1243
|
+
const millis = (seconds) => seconds === void 0 ? null : seconds * 1e3;
|
|
1244
|
+
const selectedPair = (stats) => {
|
|
1245
|
+
const pairs = stats.filter((stat) => stat.type === "candidate-pair");
|
|
1246
|
+
const selectedId = stats.find((stat) => stat.type === "transport")?.selectedCandidatePairId;
|
|
1247
|
+
return pairs.find((pair) => pair.id === selectedId) ?? pairs.find((pair) => pair.selected === true) ?? pairs.find((pair) => pair.nominated === true && pair.state === "succeeded");
|
|
1248
|
+
};
|
|
1249
|
+
const transportOf = (stats) => {
|
|
1250
|
+
const pair = selectedPair(stats);
|
|
1251
|
+
return pair === void 0 ? null : {
|
|
1252
|
+
roundTripTimeMillis: millis(pair.currentRoundTripTime),
|
|
1253
|
+
availableOutgoingBitrate: pair.availableOutgoingBitrate ?? null,
|
|
1254
|
+
availableIncomingBitrate: pair.availableIncomingBitrate ?? null
|
|
1255
|
+
};
|
|
1256
|
+
};
|
|
1257
|
+
/**
|
|
1258
|
+
* Reads the statistics of the session and of each target. It fails when
|
|
1259
|
+
* the browser rejects a call.
|
|
1260
|
+
*/
|
|
1261
|
+
const takeSample = (peerConnection, targets) => Effect.gen(function* () {
|
|
1262
|
+
const read = (load) => Effect.tryPromise({
|
|
1263
|
+
try: load,
|
|
1264
|
+
catch: (cause) => cause
|
|
1265
|
+
}).pipe(Effect.map(knownStats));
|
|
1266
|
+
const [session, ...perTarget] = yield* Effect.all([read(() => peerConnection.getStats()), ...targets.map((target) => read(() => target.direction === "send" ? target.transceiver.sender.getStats() : target.transceiver.receiver.getStats()))], { concurrency: "unbounded" });
|
|
1267
|
+
const sent = [];
|
|
1268
|
+
const received = [];
|
|
1269
|
+
targets.forEach((target, index) => {
|
|
1270
|
+
const stats = perTarget[index] ?? [];
|
|
1271
|
+
if (target.direction === "send") sent.push({
|
|
1272
|
+
trackName: target.trackName,
|
|
1273
|
+
outbound: stats.filter((stat) => stat.type === "outbound-rtp"),
|
|
1274
|
+
remote: stats.filter((stat) => stat.type === "remote-inbound-rtp")
|
|
1275
|
+
});
|
|
1276
|
+
else received.push({
|
|
1277
|
+
metadata: target.metadata,
|
|
1278
|
+
inbound: stats.filter((stat) => stat.type === "inbound-rtp")
|
|
1279
|
+
});
|
|
1280
|
+
});
|
|
1281
|
+
return {
|
|
1282
|
+
transport: transportOf(session ?? []),
|
|
1283
|
+
sent,
|
|
1284
|
+
received
|
|
1285
|
+
};
|
|
1286
|
+
});
|
|
1287
|
+
/** A counter can go down, for example `packetsLost` after duplicates. */
|
|
1288
|
+
const increase = (current, previous) => Math.max(0, current - previous);
|
|
1289
|
+
const bitrate = (bytes, previousBytes, timestamp, previousTimestamp) => timestamp > previousTimestamp ? increase(bytes, previousBytes) * 8 * 1e3 / (timestamp - previousTimestamp) : 0;
|
|
1290
|
+
const optionalIncrease = (current, previous) => current === void 0 || previous === void 0 ? null : increase(current, previous);
|
|
1291
|
+
const sentStream = (outbound, previous, remote, previousRemote) => ({
|
|
1292
|
+
rid: outbound.rid ?? null,
|
|
1293
|
+
bitrate: bitrate(outbound.bytesSent, previous.bytesSent, outbound.timestamp, previous.timestamp),
|
|
1294
|
+
packetsSent: increase(outbound.packetsSent, previous.packetsSent),
|
|
1295
|
+
framesPerSecond: outbound.framesPerSecond ?? null,
|
|
1296
|
+
qualityLimitationReason: outbound.qualityLimitationReason ?? null,
|
|
1297
|
+
remote: remote === void 0 ? null : {
|
|
1298
|
+
packetsLost: increase(remote.packetsLost, previousRemote?.packetsLost ?? 0),
|
|
1299
|
+
fractionLost: remote.fractionLost ?? null,
|
|
1300
|
+
jitterMillis: millis(remote.jitter),
|
|
1301
|
+
roundTripTimeMillis: millis(remote.roundTripTime)
|
|
1302
|
+
}
|
|
1303
|
+
});
|
|
1304
|
+
const receivedTrack = (metadata, inbound, previous) => {
|
|
1305
|
+
const concealed = optionalIncrease(inbound.concealedSamples, previous.concealedSamples);
|
|
1306
|
+
const samples = optionalIncrease(inbound.totalSamplesReceived, previous.totalSamplesReceived);
|
|
1307
|
+
return {
|
|
1308
|
+
metadata,
|
|
1309
|
+
kind: inbound.kind,
|
|
1310
|
+
bitrate: bitrate(inbound.bytesReceived, previous.bytesReceived, inbound.timestamp, previous.timestamp),
|
|
1311
|
+
packetsReceived: increase(inbound.packetsReceived, previous.packetsReceived),
|
|
1312
|
+
packetsLost: increase(inbound.packetsLost, previous.packetsLost),
|
|
1313
|
+
jitterMillis: millis(inbound.jitter),
|
|
1314
|
+
framesPerSecond: inbound.framesPerSecond ?? null,
|
|
1315
|
+
freezeCount: optionalIncrease(inbound.freezeCount, previous.freezeCount),
|
|
1316
|
+
concealedFraction: concealed === null || samples === null || samples === 0 ? null : Math.min(1, concealed / samples)
|
|
1317
|
+
};
|
|
1318
|
+
};
|
|
1319
|
+
const byId = (stats) => new Map(stats.map((stat) => [stat.id, stat]));
|
|
1320
|
+
/**
|
|
1321
|
+
* The difference between two samples of a session. An RTP stream that is
|
|
1322
|
+
* not in the previous sample is left out.
|
|
1323
|
+
*/
|
|
1324
|
+
const compareSamples = (sessionId, previous, current) => {
|
|
1325
|
+
const previousOutbound = byId(previous.sent.flatMap((t) => t.outbound));
|
|
1326
|
+
const previousRemote = byId(previous.sent.flatMap((t) => t.remote));
|
|
1327
|
+
const previousInbound = byId(previous.received.flatMap((t) => t.inbound));
|
|
1328
|
+
const sent = current.sent.flatMap((track) => {
|
|
1329
|
+
const streams = track.outbound.flatMap((outbound) => {
|
|
1330
|
+
const before = previousOutbound.get(outbound.id);
|
|
1331
|
+
if (before === void 0) return [];
|
|
1332
|
+
const remote = track.remote.find((r) => r.localId === outbound.id);
|
|
1333
|
+
return [sentStream(outbound, before, remote, remote === void 0 ? void 0 : previousRemote.get(remote.id))];
|
|
1334
|
+
});
|
|
1335
|
+
const kind = track.outbound[0]?.kind;
|
|
1336
|
+
return kind === void 0 || streams.length === 0 ? [] : [{
|
|
1337
|
+
trackName: track.trackName,
|
|
1338
|
+
kind,
|
|
1339
|
+
streams
|
|
1340
|
+
}];
|
|
1341
|
+
});
|
|
1342
|
+
const received = current.received.flatMap((track) => track.inbound.flatMap((inbound) => {
|
|
1343
|
+
const before = previousInbound.get(inbound.id);
|
|
1344
|
+
return before === void 0 ? [] : [receivedTrack(track.metadata, inbound, before)];
|
|
1345
|
+
}));
|
|
1346
|
+
return {
|
|
1347
|
+
sessionId,
|
|
1348
|
+
transport: current.transport,
|
|
1349
|
+
sent,
|
|
1350
|
+
received
|
|
1351
|
+
};
|
|
1352
|
+
};
|
|
1353
|
+
/**
|
|
1354
|
+
* Samples one session at each interval. The first sample is the base of the
|
|
1355
|
+
* second, so the first value comes after one interval. A sample that the
|
|
1356
|
+
* browser cannot give is skipped.
|
|
1357
|
+
*/
|
|
1358
|
+
const sampleSession = (session, targets, options = {}) => Stream.tick(options.interval ?? defaultStatsInterval).pipe(Stream.mapAccumEffect(() => Option.none(), (previous) => targets.pipe(Effect.flatMap((current) => takeSample(session.peerConnection, current)), Effect.map((sample) => [Option.some(sample), Option.isSome(previous) ? [compareSamples(session.sessionId, previous.value, sample)] : []]), Effect.catch(() => Effect.succeed([previous, []])))));
|
|
1359
|
+
//#endregion
|
|
1360
|
+
//#region src/effect/client/Config.ts
|
|
1361
|
+
const maxRetryDelay = Duration.seconds(10);
|
|
1362
|
+
const defaultRetrySchedule = Schedule.exponential("250 millis", 2).pipe(Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.min(duration, maxRetryDelay))));
|
|
1363
|
+
const duration = (input, fallback) => input === void 0 ? fallback : Duration.fromInputUnsafe(input);
|
|
1364
|
+
function resolveConfig(config = {}) {
|
|
1365
|
+
const { headers } = config;
|
|
1366
|
+
return {
|
|
1367
|
+
prefix: config.prefix ?? "/realtime",
|
|
1368
|
+
apiExtraParams: new URLSearchParams(config.apiExtraParams),
|
|
1369
|
+
headers: headers === void 0 ? () => ({}) : typeof headers === "function" ? headers : () => headers,
|
|
1370
|
+
iceServers: config.iceServers,
|
|
1371
|
+
maxApiHistory: config.maxApiHistory === void 0 || Number.isNaN(config.maxApiHistory) ? 100 : Math.max(1, Math.floor(config.maxApiHistory)),
|
|
1372
|
+
tracePropagation: config.tracePropagation ?? true,
|
|
1373
|
+
sessionRetry: config.sessionRetry ?? defaultRetrySchedule,
|
|
1374
|
+
trackRetry: config.trackRetry ?? defaultRetrySchedule,
|
|
1375
|
+
iceDisconnectedTimeout: duration(config.iceDisconnectedTimeout, Duration.seconds(7)),
|
|
1376
|
+
negotiationTimeout: duration(config.negotiationTimeout, Duration.seconds(5)),
|
|
1377
|
+
pullTimeout: duration(config.pullTimeout, Duration.seconds(15)),
|
|
1378
|
+
maxBatchSize: Math.min(64, Math.max(1, config.maxBatchSize ?? 32)),
|
|
1379
|
+
sessionIdleTimeout: duration(config.sessionIdleTimeout, Duration.seconds(5)),
|
|
1380
|
+
sessionStableAfter: duration(config.sessionStableAfter, Duration.seconds(10))
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
//#endregion
|
|
1384
|
+
//#region src/effect/client/PeerConnections.ts
|
|
1385
|
+
/** Makes peer connections. Tests replace this service with a fake. */
|
|
1386
|
+
var PeerConnections = class PeerConnections extends Context.Service()("effect-cloudflare-webrtc/PeerConnections") {
|
|
1387
|
+
/** Uses the `RTCPeerConnection` of the browser. */
|
|
1388
|
+
static layerBrowser = Layer.succeed(PeerConnections, PeerConnections.of({ make: (configuration) => Effect.acquireRelease(Effect.sync(() => new RTCPeerConnection(configuration)), (peerConnection) => Effect.sync(() => peerConnection.close())) }));
|
|
1389
|
+
};
|
|
1390
|
+
//#endregion
|
|
1391
|
+
//#region src/effect/client/internal/schemas.ts
|
|
1392
|
+
const SessionDescription = Schema.Struct({
|
|
1393
|
+
type: Schema.Literals(["offer", "answer"]),
|
|
1394
|
+
sdp: Schema.String
|
|
1395
|
+
});
|
|
1396
|
+
const ErrorBody = Schema.Struct({
|
|
1397
|
+
errorCode: Schema.optional(Schema.String),
|
|
1398
|
+
errorDescription: Schema.optional(Schema.String)
|
|
1399
|
+
});
|
|
1400
|
+
const NewSessionResponse = Schema.Struct({
|
|
1401
|
+
sessionId: Schema.String,
|
|
1402
|
+
/** Added by `routeRealtimeRequest` when the session lock is on. */
|
|
1403
|
+
sessionToken: Schema.optional(Schema.String)
|
|
1404
|
+
});
|
|
1405
|
+
const IceServersResponse = Schema.Struct({ iceServers: Schema.Array(Schema.Struct({
|
|
1406
|
+
urls: Schema.Union([Schema.String, Schema.Array(Schema.String)]),
|
|
1407
|
+
username: Schema.optional(Schema.String),
|
|
1408
|
+
credential: Schema.optional(Schema.String)
|
|
1409
|
+
})) });
|
|
1410
|
+
const TrackResult = Schema.Struct({
|
|
1411
|
+
trackName: Schema.optional(Schema.String),
|
|
1412
|
+
sessionId: Schema.optional(Schema.String),
|
|
1413
|
+
mid: Schema.optional(Schema.NullOr(Schema.String)),
|
|
1414
|
+
errorCode: Schema.optional(Schema.String),
|
|
1415
|
+
errorDescription: Schema.optional(Schema.String)
|
|
1416
|
+
});
|
|
1417
|
+
const TracksResponse = Schema.Struct({
|
|
1418
|
+
requiresImmediateRenegotiation: Schema.optional(Schema.Boolean),
|
|
1419
|
+
sessionDescription: Schema.optional(SessionDescription),
|
|
1420
|
+
tracks: Schema.optional(Schema.Array(TrackResult))
|
|
1421
|
+
});
|
|
1422
|
+
const EmptyResponse = Schema.Struct({});
|
|
1423
|
+
//#endregion
|
|
1424
|
+
//#region src/effect/client/RealtimeApi.ts
|
|
1425
|
+
/** The header that carries the session token to `routeRealtimeRequest`. */
|
|
1426
|
+
const sessionTokenHeader = "x-realtime-session-token";
|
|
1427
|
+
/**
|
|
1428
|
+
* Typed requests to the server route (`routeRealtimeRequest`), which
|
|
1429
|
+
* forwards them to the Realtime SFU API.
|
|
1430
|
+
*/
|
|
1431
|
+
var RealtimeApi = class RealtimeApi extends Context.Service()("effect-cloudflare-webrtc/RealtimeApi") {
|
|
1432
|
+
/** Needs an `HttpClient`. Use `redirect: "manual"` in a browser. */
|
|
1433
|
+
static layer = (config) => Layer.effect(RealtimeApi, make$1(config));
|
|
1434
|
+
};
|
|
1435
|
+
const decodeErrorBody = Schema.decodeUnknownOption(ErrorBody);
|
|
1436
|
+
const pullTrackBody = (track) => ({
|
|
1437
|
+
location: "remote",
|
|
1438
|
+
sessionId: track.sessionId,
|
|
1439
|
+
trackName: track.trackName,
|
|
1440
|
+
...track.preferredRid === void 0 || track.preferredRid === "" ? {} : { simulcast: { preferredRid: track.preferredRid } }
|
|
1441
|
+
});
|
|
1442
|
+
const make$1 = (config) => Effect.gen(function* () {
|
|
1443
|
+
const resolved = resolveConfig(config);
|
|
1444
|
+
const client = yield* HttpClient.HttpClient;
|
|
1445
|
+
const history = yield* Ref.make([]);
|
|
1446
|
+
const events = yield* PubSub.unbounded();
|
|
1447
|
+
const record = (entry) => Ref.update(history, (entries) => [...entries, entry].slice(-resolved.maxApiHistory)).pipe(Effect.andThen(PubSub.publish(events, entry)));
|
|
1448
|
+
const url = (path) => {
|
|
1449
|
+
const query = resolved.apiExtraParams.toString();
|
|
1450
|
+
return `${resolved.prefix}${path}${query === "" ? "" : `?${query}`}`;
|
|
1451
|
+
};
|
|
1452
|
+
const request = (method, path, schema, options = {}) => Effect.gen(function* () {
|
|
1453
|
+
const endpoint = url(path);
|
|
1454
|
+
yield* record({
|
|
1455
|
+
type: "request",
|
|
1456
|
+
method,
|
|
1457
|
+
endpoint,
|
|
1458
|
+
body: options.body
|
|
1459
|
+
});
|
|
1460
|
+
const headers = new Headers(resolved.headers());
|
|
1461
|
+
if (options.session?.token !== void 0) headers.set(sessionTokenHeader, options.session.token);
|
|
1462
|
+
const base = HttpClientRequest.make(method)(endpoint).pipe(HttpClientRequest.setHeaders(Object.fromEntries(headers.entries())));
|
|
1463
|
+
const httpRequest = options.body === void 0 ? base : HttpClientRequest.bodyJsonUnsafe(base, options.body);
|
|
1464
|
+
const { status, body } = yield* Effect.gen(function* () {
|
|
1465
|
+
const response = yield* client.execute(httpRequest).pipe(Effect.provideService(HttpClient.TracerPropagationEnabled, resolved.tracePropagation));
|
|
1466
|
+
const body = yield* response.json.pipe(Effect.option);
|
|
1467
|
+
return {
|
|
1468
|
+
status: response.status,
|
|
1469
|
+
body
|
|
1470
|
+
};
|
|
1471
|
+
}).pipe(Effect.timeoutOrElse({
|
|
1472
|
+
duration: options.timeout ?? resolved.negotiationTimeout,
|
|
1473
|
+
orElse: () => Effect.fail(new ApiTransportError({
|
|
1474
|
+
endpoint,
|
|
1475
|
+
cause: "The request timed out"
|
|
1476
|
+
}))
|
|
1477
|
+
}), Effect.mapError((error) => error._tag === "ApiTransportError" ? error : new ApiTransportError({
|
|
1478
|
+
endpoint,
|
|
1479
|
+
cause: error
|
|
1480
|
+
})));
|
|
1481
|
+
yield* record({
|
|
1482
|
+
type: "response",
|
|
1483
|
+
endpoint,
|
|
1484
|
+
status,
|
|
1485
|
+
body: Option.getOrUndefined(body)
|
|
1486
|
+
});
|
|
1487
|
+
if (status === 0) return yield* new ApiAuthRedirect({ endpoint });
|
|
1488
|
+
const errorBody = Option.flatMap(body, decodeErrorBody);
|
|
1489
|
+
const errorCode = Option.getOrUndefined(Option.flatMapNullishOr(errorBody, (b) => b.errorCode));
|
|
1490
|
+
if (status < 200 || status >= 300 || errorCode !== void 0) return yield* new ApiResponseError({
|
|
1491
|
+
endpoint,
|
|
1492
|
+
status,
|
|
1493
|
+
errorCode,
|
|
1494
|
+
errorDescription: Option.getOrUndefined(Option.flatMapNullishOr(errorBody, (b) => b.errorDescription))
|
|
1495
|
+
});
|
|
1496
|
+
if (Option.isNone(body)) return yield* new ApiInvalidResponse({
|
|
1497
|
+
endpoint,
|
|
1498
|
+
status,
|
|
1499
|
+
message: "The response body is not JSON"
|
|
1500
|
+
});
|
|
1501
|
+
return yield* Schema.decodeUnknownEffect(schema)(body.value).pipe(Effect.mapError((error) => new ApiInvalidResponse({
|
|
1502
|
+
endpoint,
|
|
1503
|
+
status,
|
|
1504
|
+
message: error.message
|
|
1505
|
+
})));
|
|
1506
|
+
});
|
|
1507
|
+
const sessionPath = (session, path) => `/sessions/${session.sessionId}${path}`;
|
|
1508
|
+
return RealtimeApi.of({
|
|
1509
|
+
newSession: request("POST", "/sessions/new", NewSessionResponse).pipe(Effect.map(({ sessionId, sessionToken }) => ({
|
|
1510
|
+
sessionId,
|
|
1511
|
+
token: sessionToken
|
|
1512
|
+
}))),
|
|
1513
|
+
iceServers: request("GET", "/generate-ice-servers", IceServersResponse).pipe(Effect.map(({ iceServers }) => iceServers.map((server) => ({
|
|
1514
|
+
...server,
|
|
1515
|
+
urls: typeof server.urls === "string" ? server.urls : [...server.urls]
|
|
1516
|
+
})))),
|
|
1517
|
+
pushTracks: (session, offer, tracks) => request("POST", sessionPath(session, "/tracks/new"), TracksResponse, {
|
|
1518
|
+
session,
|
|
1519
|
+
body: {
|
|
1520
|
+
sessionDescription: {
|
|
1521
|
+
type: "offer",
|
|
1522
|
+
sdp: offer
|
|
1523
|
+
},
|
|
1524
|
+
tracks: tracks.map(({ trackName, mid }) => ({
|
|
1525
|
+
location: "local",
|
|
1526
|
+
trackName,
|
|
1527
|
+
mid
|
|
1528
|
+
}))
|
|
1529
|
+
}
|
|
1530
|
+
}),
|
|
1531
|
+
pullTracks: (session, tracks) => request("POST", sessionPath(session, "/tracks/new"), TracksResponse, {
|
|
1532
|
+
session,
|
|
1533
|
+
body: { tracks: tracks.map(pullTrackBody) },
|
|
1534
|
+
timeout: resolved.pullTimeout
|
|
1535
|
+
}),
|
|
1536
|
+
renegotiate: (session, answer) => request("PUT", sessionPath(session, "/renegotiate"), EmptyResponse, {
|
|
1537
|
+
session,
|
|
1538
|
+
body: { sessionDescription: {
|
|
1539
|
+
type: "answer",
|
|
1540
|
+
sdp: answer
|
|
1541
|
+
} }
|
|
1542
|
+
}).pipe(Effect.asVoid),
|
|
1543
|
+
updateTracks: (session, tracks) => request("PUT", sessionPath(session, "/tracks/update"), TracksResponse, {
|
|
1544
|
+
session,
|
|
1545
|
+
body: { tracks: tracks.map((track) => ({
|
|
1546
|
+
...pullTrackBody(track),
|
|
1547
|
+
mid: track.mid,
|
|
1548
|
+
simulcast: { preferredRid: track.preferredRid ?? "" }
|
|
1549
|
+
})) }
|
|
1550
|
+
}),
|
|
1551
|
+
closeTracks: (session, offer, mids) => request("PUT", sessionPath(session, "/tracks/close"), TracksResponse, {
|
|
1552
|
+
session,
|
|
1553
|
+
body: offer === void 0 ? {
|
|
1554
|
+
tracks: mids.map((mid) => ({ mid })),
|
|
1555
|
+
force: true
|
|
1556
|
+
} : {
|
|
1557
|
+
sessionDescription: {
|
|
1558
|
+
type: "offer",
|
|
1559
|
+
sdp: offer
|
|
1560
|
+
},
|
|
1561
|
+
tracks: mids.map((mid) => ({ mid })),
|
|
1562
|
+
force: false
|
|
1563
|
+
}
|
|
1564
|
+
}),
|
|
1565
|
+
history: Ref.get(history),
|
|
1566
|
+
events: Stream.fromPubSub(events)
|
|
1567
|
+
});
|
|
1568
|
+
});
|
|
1569
|
+
//#endregion
|
|
1570
|
+
//#region src/effect/client/TrackMetadata.ts
|
|
1571
|
+
/**
|
|
1572
|
+
* What one party sends to a different party, so that it can pull the track.
|
|
1573
|
+
* Use `Schema.decodeUnknownEffect(TrackMetadata)` to validate metadata that
|
|
1574
|
+
* comes from the network.
|
|
1575
|
+
*/
|
|
1576
|
+
const TrackMetadata = Schema.Struct({
|
|
1577
|
+
sessionId: Schema.String,
|
|
1578
|
+
trackName: Schema.String,
|
|
1579
|
+
location: Schema.Literal("remote")
|
|
1580
|
+
});
|
|
1581
|
+
const trackMetadataEquals = (a, b) => a.sessionId === b.sessionId && a.trackName === b.trackName;
|
|
1582
|
+
//#endregion
|
|
1583
|
+
//#region src/effect/client/internal/errorAction.ts
|
|
1584
|
+
const actionByErrorCode = new Map(Object.entries({
|
|
1585
|
+
unauthorized: "Fail",
|
|
1586
|
+
not_found: "Fail",
|
|
1587
|
+
decoding_error: "Fail",
|
|
1588
|
+
invalid_params: "Fail",
|
|
1589
|
+
payload_too_large: "Fail",
|
|
1590
|
+
update_track_error: "Fail",
|
|
1591
|
+
not_found_track_error: "Retry",
|
|
1592
|
+
empty_track_error: "Retry",
|
|
1593
|
+
retryable_transient_error: "Retry",
|
|
1594
|
+
temporarily_unavailable_error: "Retry",
|
|
1595
|
+
transport_unavailable_error: "Retry",
|
|
1596
|
+
backend_error: "Retry",
|
|
1597
|
+
internal_error: "Retry",
|
|
1598
|
+
invalid_session_description: "ReplaceSession",
|
|
1599
|
+
realtime_session_token_invalid: "ReplaceSession"
|
|
1600
|
+
}));
|
|
1601
|
+
function actionForCode(errorCode, status) {
|
|
1602
|
+
if (errorCode === "session_error") return status === 425 ? "Retry" : "ReplaceSession";
|
|
1603
|
+
return actionByErrorCode.get(errorCode) ?? "Retry";
|
|
1604
|
+
}
|
|
1605
|
+
function errorAction(error) {
|
|
1606
|
+
switch (error._tag) {
|
|
1607
|
+
case "ApiTransportError":
|
|
1608
|
+
case "ApiInvalidResponse":
|
|
1609
|
+
case "ApiAuthRedirect": return "Retry";
|
|
1610
|
+
case "ApiResponseError":
|
|
1611
|
+
if (error.errorCode !== void 0) return actionForCode(error.errorCode, error.status);
|
|
1612
|
+
if (error.status === 401 || error.status === 403) return "Fail";
|
|
1613
|
+
if (error.status === 410) return "ReplaceSession";
|
|
1614
|
+
return "Retry";
|
|
1615
|
+
case "TrackError": return actionForCode(error.errorCode, 200);
|
|
1616
|
+
case "NegotiationOutcomeUnknown":
|
|
1617
|
+
case "PeerConnectionFailed":
|
|
1618
|
+
case "TransceiverNotFound": return "ReplaceSession";
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
//#endregion
|
|
1622
|
+
//#region src/effect/client/internal/Negotiator.ts
|
|
1623
|
+
var PushRequest = class extends Request.TaggedClass("PushRequest") {};
|
|
1624
|
+
var PullRequest = class extends Request.TaggedClass("PullRequest") {};
|
|
1625
|
+
var CloseRequest = class extends Request.TaggedClass("CloseRequest") {};
|
|
1626
|
+
const batchDelay = "1 millis";
|
|
1627
|
+
const closeRetries = 5;
|
|
1628
|
+
const pushExchangeRetries = 3;
|
|
1629
|
+
const trackError = (result, errorCode) => new TrackError({
|
|
1630
|
+
trackName: result.trackName,
|
|
1631
|
+
mid: result.mid ?? void 0,
|
|
1632
|
+
errorCode,
|
|
1633
|
+
errorDescription: result.errorDescription
|
|
1634
|
+
});
|
|
1635
|
+
/** A close response in which each failed track is already closed. */
|
|
1636
|
+
const onlyClosedTracks = (response) => response.tracks !== void 0 && response.tracks.some((track) => track.errorCode === "close_track_error") && response.tracks.every((track) => track.errorCode === void 0 || track.errorCode === "close_track_error");
|
|
1637
|
+
const isCloseTrackError = (error) => error._tag === "ApiResponseError" && error.errorCode === "close_track_error";
|
|
1638
|
+
/**
|
|
1639
|
+
* Makes a request that the caller can interrupt. The work continues after the
|
|
1640
|
+
* interruption, so that a track that the SFU gives late is closed. The
|
|
1641
|
+
* resolver leaves out a request whose caller stopped waiting before the batch
|
|
1642
|
+
* was sent.
|
|
1643
|
+
*/
|
|
1644
|
+
const acquireRequest = (request, close) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
1645
|
+
const abandoned = Deferred.makeUnsafe();
|
|
1646
|
+
const fiber = yield* Effect.forkDetach(request(abandoned));
|
|
1647
|
+
const result = yield* restore(Fiber.join(fiber)).pipe(Effect.onInterrupt(() => Deferred.succeed(abandoned, void 0).pipe(Effect.andThen(Fiber.await(fiber).pipe(Effect.flatMap((exit) => Exit.isSuccess(exit) ? close(exit.value.mid) : Effect.void), Effect.forkDetach)))));
|
|
1648
|
+
yield* Effect.addFinalizer(() => close(result.mid));
|
|
1649
|
+
return result;
|
|
1650
|
+
}));
|
|
1651
|
+
const makeNegotiator = (options) => Effect.gen(function* () {
|
|
1652
|
+
const { api, auth, config, fail, peerConnection, transceivers } = options;
|
|
1653
|
+
const queue = yield* Semaphore.make(1);
|
|
1654
|
+
const unknown = (step) => (cause) => new NegotiationOutcomeUnknown({
|
|
1655
|
+
step,
|
|
1656
|
+
cause
|
|
1657
|
+
});
|
|
1658
|
+
/** A browser SDP call. A rejection or a timeout leaves the state unknown. */
|
|
1659
|
+
const sdp = (step, call) => Effect.tryPromise({
|
|
1660
|
+
try: call,
|
|
1661
|
+
catch: unknown(step)
|
|
1662
|
+
}).pipe(Effect.timeoutOrElse({
|
|
1663
|
+
duration: config.negotiationTimeout,
|
|
1664
|
+
orElse: () => Effect.fail(unknown(step)(`The ${step} call did not end`))
|
|
1665
|
+
}));
|
|
1666
|
+
/** An API call that is part of an exchange. No response: state unknown. */
|
|
1667
|
+
const exchangeRequest = (step) => (request) => Effect.mapError(request, (error) => error._tag === "ApiTransportError" || error._tag === "ApiInvalidResponse" ? unknown(step)(error) : error);
|
|
1668
|
+
const waitForStableSignalingState = Effect.callback((resume) => {
|
|
1669
|
+
const check = () => {
|
|
1670
|
+
if (peerConnection.signalingState === "stable") resume(Effect.void);
|
|
1671
|
+
};
|
|
1672
|
+
peerConnection.addEventListener("signalingstatechange", check);
|
|
1673
|
+
check();
|
|
1674
|
+
return Effect.sync(() => peerConnection.removeEventListener("signalingstatechange", check));
|
|
1675
|
+
}).pipe(Effect.timeoutOrElse({
|
|
1676
|
+
duration: config.negotiationTimeout,
|
|
1677
|
+
orElse: () => Effect.fail(unknown("signalingState")("The signaling state did not become stable"))
|
|
1678
|
+
}));
|
|
1679
|
+
/**
|
|
1680
|
+
* After an exchange failed: replaces the session if its state is not
|
|
1681
|
+
* known. If not, removes the local offer, so that the next exchange can
|
|
1682
|
+
* start from a stable state.
|
|
1683
|
+
*/
|
|
1684
|
+
const recover = (error) => Effect.gen(function* () {
|
|
1685
|
+
if (errorAction(error) === "ReplaceSession") return yield* fail(error);
|
|
1686
|
+
if (peerConnection.signalingState === "have-local-offer") yield* sdp("rollback", () => peerConnection.setLocalDescription({ type: "rollback" })).pipe(Effect.catch(fail));
|
|
1687
|
+
});
|
|
1688
|
+
const publish = (direction, transceiver) => PubSub.publish(transceivers, {
|
|
1689
|
+
direction,
|
|
1690
|
+
sessionId: auth.sessionId,
|
|
1691
|
+
transceiver
|
|
1692
|
+
});
|
|
1693
|
+
const answerOf = (step, response) => response.sessionDescription === void 0 ? Effect.fail(unknown(step)("The response has no session description")) : Effect.succeed(response.sessionDescription);
|
|
1694
|
+
const pushResolver = RequestResolver.make((entries) => queue.withPermit(Effect.gen(function* () {
|
|
1695
|
+
yield* Effect.annotateCurrentSpan({ sessionId: auth.sessionId });
|
|
1696
|
+
const live = [];
|
|
1697
|
+
for (const entry of entries) if (Deferred.isDoneUnsafe(entry.request.abandoned)) entry.completeUnsafe(Exit.interrupt());
|
|
1698
|
+
else live.push(entry);
|
|
1699
|
+
if (live.length === 0) return;
|
|
1700
|
+
const only = live.length === 1 ? live[0] : void 0;
|
|
1701
|
+
if (only !== void 0) yield* Effect.annotateCurrentSpan({ trackName: only.request.input.trackName });
|
|
1702
|
+
if (peerConnection.signalingState === "closed") {
|
|
1703
|
+
const error = unknown("tracks/new")("The peer connection is closed");
|
|
1704
|
+
for (const entry of live) entry.completeUnsafe(Exit.fail(error));
|
|
1705
|
+
return;
|
|
1706
|
+
}
|
|
1707
|
+
const added = live.map((entry) => ({
|
|
1708
|
+
entry,
|
|
1709
|
+
transceiver: peerConnection.addTransceiver(entry.request.input.track, {
|
|
1710
|
+
direction: "sendonly",
|
|
1711
|
+
sendEncodings: [...entry.request.input.sendEncodings]
|
|
1712
|
+
})
|
|
1713
|
+
}));
|
|
1714
|
+
const exchange = Effect.gen(function* () {
|
|
1715
|
+
const offer = yield* sdp("createOffer", () => peerConnection.createOffer());
|
|
1716
|
+
yield* sdp("setLocalDescription", () => peerConnection.setLocalDescription(offer));
|
|
1717
|
+
const response = yield* api.pushTracks(auth, offer.sdp ?? "", added.map(({ entry, transceiver }) => ({
|
|
1718
|
+
trackName: entry.request.input.trackName,
|
|
1719
|
+
mid: transceiver.mid ?? ""
|
|
1720
|
+
}))).pipe(exchangeRequest("tracks/new"));
|
|
1721
|
+
const answer = yield* answerOf("tracks/new", response);
|
|
1722
|
+
yield* sdp("setRemoteDescription", () => peerConnection.setRemoteDescription(answer));
|
|
1723
|
+
yield* waitForStableSignalingState;
|
|
1724
|
+
return response;
|
|
1725
|
+
});
|
|
1726
|
+
const response = yield* Effect.gen(function* () {
|
|
1727
|
+
const retryDelay = yield* Schedule.toStepWithSleep(config.trackRetry);
|
|
1728
|
+
let attempt = 0;
|
|
1729
|
+
while (true) {
|
|
1730
|
+
const result = yield* Effect.result(exchange);
|
|
1731
|
+
if (result._tag === "Success") return result.success;
|
|
1732
|
+
const error = result.failure;
|
|
1733
|
+
if (errorAction(error) === "ReplaceSession") {
|
|
1734
|
+
yield* recover(error);
|
|
1735
|
+
for (const { entry } of added) entry.completeUnsafe(Exit.fail(error));
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
yield* recover(error);
|
|
1739
|
+
if (errorAction(error) === "Fail") {
|
|
1740
|
+
for (const { entry } of added) entry.completeUnsafe(Exit.fail(error));
|
|
1741
|
+
yield* fail(unknown("tracks/new")(error));
|
|
1742
|
+
return;
|
|
1743
|
+
}
|
|
1744
|
+
if (attempt >= pushExchangeRetries || peerConnection.signalingState !== "stable") {
|
|
1745
|
+
const replace = unknown("tracks/new")(error);
|
|
1746
|
+
for (const { entry } of added) entry.completeUnsafe(Exit.fail(replace));
|
|
1747
|
+
yield* fail(replace);
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
attempt += 1;
|
|
1751
|
+
yield* Effect.forEach(added, ({ entry }) => entry.request.input.onRetry(error, attempt), { discard: true });
|
|
1752
|
+
if (!(yield* Pull.matchEffect(retryDelay(error), {
|
|
1753
|
+
onSuccess: () => Effect.succeed(true),
|
|
1754
|
+
onFailure: (cause) => Effect.die(cause),
|
|
1755
|
+
onDone: () => Effect.succeed(false)
|
|
1756
|
+
}))) {
|
|
1757
|
+
for (const { entry } of added) entry.completeUnsafe(Exit.fail(error));
|
|
1758
|
+
yield* fail(unknown("tracks/new")(error));
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
});
|
|
1763
|
+
if (response === void 0) return;
|
|
1764
|
+
let sessionError;
|
|
1765
|
+
for (const { entry, transceiver } of added) {
|
|
1766
|
+
const { mid } = transceiver;
|
|
1767
|
+
const trackResult = response.tracks?.find((t) => t.mid === mid);
|
|
1768
|
+
if (mid === null || trackResult === void 0 || trackResult.errorCode !== void 0) {
|
|
1769
|
+
transceiver.stop();
|
|
1770
|
+
const error = trackError(trackResult ?? { trackName: entry.request.input.trackName }, trackResult?.errorCode ?? "missing_result");
|
|
1771
|
+
if (sessionError === void 0 && errorAction(error) === "ReplaceSession") sessionError = error;
|
|
1772
|
+
entry.completeUnsafe(Exit.fail(error));
|
|
1773
|
+
continue;
|
|
1774
|
+
}
|
|
1775
|
+
yield* publish("send", transceiver);
|
|
1776
|
+
entry.completeUnsafe(Exit.succeed({
|
|
1777
|
+
transceiver,
|
|
1778
|
+
mid
|
|
1779
|
+
}));
|
|
1780
|
+
}
|
|
1781
|
+
if (sessionError !== void 0) yield* fail(unknown("tracks/new")(sessionError));
|
|
1782
|
+
}).pipe(Effect.annotateLogs({ sessionId: auth.sessionId }), Effect.withSpan("realtime.negotiate")))).pipe(RequestResolver.batchN(config.maxBatchSize), RequestResolver.setDelay(batchDelay));
|
|
1783
|
+
const pullResolver = RequestResolver.make((entries) => queue.withPermit(Effect.gen(function* () {
|
|
1784
|
+
yield* Effect.annotateCurrentSpan({ sessionId: auth.sessionId });
|
|
1785
|
+
const live = [];
|
|
1786
|
+
for (const entry of entries) if (Deferred.isDoneUnsafe(entry.request.abandoned)) entry.completeUnsafe(Exit.interrupt());
|
|
1787
|
+
else live.push(entry);
|
|
1788
|
+
if (live.length === 0) return;
|
|
1789
|
+
const only = live.length === 1 ? live[0] : void 0;
|
|
1790
|
+
if (only !== void 0) yield* Effect.annotateCurrentSpan({ trackName: only.request.input.trackName });
|
|
1791
|
+
if (peerConnection.signalingState === "closed") {
|
|
1792
|
+
const error = unknown("tracks/new")("The peer connection is closed");
|
|
1793
|
+
for (const entry of live) entry.completeUnsafe(Exit.fail(error));
|
|
1794
|
+
return;
|
|
1795
|
+
}
|
|
1796
|
+
const exchange = Effect.gen(function* () {
|
|
1797
|
+
const response = yield* api.pullTracks(auth, live.map((entry) => entry.request.input)).pipe(exchangeRequest("tracks/new"));
|
|
1798
|
+
if (response.requiresImmediateRenegotiation === true && response.sessionDescription !== void 0) {
|
|
1799
|
+
const offer = response.sessionDescription;
|
|
1800
|
+
yield* sdp("setRemoteDescription", () => peerConnection.setRemoteDescription(offer));
|
|
1801
|
+
const answer = yield* sdp("createAnswer", () => peerConnection.createAnswer());
|
|
1802
|
+
yield* sdp("setLocalDescription", () => peerConnection.setLocalDescription(answer));
|
|
1803
|
+
yield* api.renegotiate(auth, answer.sdp ?? "").pipe(Effect.mapError(unknown("renegotiate")));
|
|
1804
|
+
yield* waitForStableSignalingState;
|
|
1805
|
+
}
|
|
1806
|
+
return response;
|
|
1807
|
+
});
|
|
1808
|
+
const result = yield* Effect.result(exchange);
|
|
1809
|
+
if (result._tag === "Failure") {
|
|
1810
|
+
for (const entry of live) entry.completeUnsafe(Exit.fail(result.failure));
|
|
1811
|
+
yield* recover(result.failure);
|
|
1812
|
+
return;
|
|
1813
|
+
}
|
|
1814
|
+
let sessionError;
|
|
1815
|
+
for (const entry of live) {
|
|
1816
|
+
const { sessionId, trackName } = entry.request.input;
|
|
1817
|
+
const trackResult = result.success.tracks?.find((t) => t.trackName === trackName && t.sessionId === sessionId);
|
|
1818
|
+
if (trackResult === void 0 || trackResult.errorCode !== void 0) {
|
|
1819
|
+
const error = trackError(trackResult ?? {
|
|
1820
|
+
trackName,
|
|
1821
|
+
sessionId
|
|
1822
|
+
}, trackResult?.errorCode ?? "missing_result");
|
|
1823
|
+
if (sessionError === void 0 && errorAction(error) === "ReplaceSession") sessionError = error;
|
|
1824
|
+
entry.completeUnsafe(Exit.fail(error));
|
|
1825
|
+
continue;
|
|
1826
|
+
}
|
|
1827
|
+
const { mid } = trackResult;
|
|
1828
|
+
const transceiver = peerConnection.getTransceivers().find((t) => t.mid !== null && t.mid === mid);
|
|
1829
|
+
if (transceiver === void 0 || typeof mid !== "string") {
|
|
1830
|
+
const error = new TransceiverNotFound({
|
|
1831
|
+
trackName,
|
|
1832
|
+
mid: mid ?? void 0
|
|
1833
|
+
});
|
|
1834
|
+
sessionError ??= error;
|
|
1835
|
+
entry.completeUnsafe(Exit.fail(error));
|
|
1836
|
+
continue;
|
|
1837
|
+
}
|
|
1838
|
+
yield* publish("receive", transceiver);
|
|
1839
|
+
entry.completeUnsafe(Exit.succeed({
|
|
1840
|
+
transceiver,
|
|
1841
|
+
mid,
|
|
1842
|
+
track: transceiver.receiver.track
|
|
1843
|
+
}));
|
|
1844
|
+
}
|
|
1845
|
+
if (sessionError !== void 0) yield* fail(unknown("tracks/new")(sessionError));
|
|
1846
|
+
}).pipe(Effect.annotateLogs({ sessionId: auth.sessionId }), Effect.withSpan("realtime.negotiate")))).pipe(RequestResolver.batchN(config.maxBatchSize), RequestResolver.setDelay(batchDelay));
|
|
1847
|
+
const closeResolver = RequestResolver.make((entries) => queue.withPermit(Effect.gen(function* () {
|
|
1848
|
+
yield* Effect.annotateCurrentSpan({ sessionId: auth.sessionId });
|
|
1849
|
+
const only = entries.length === 1 ? entries[0] : void 0;
|
|
1850
|
+
if (only !== void 0) yield* Effect.annotateCurrentSpan({ mid: only.request.mid });
|
|
1851
|
+
const complete = (exit) => {
|
|
1852
|
+
for (const entry of entries) entry.completeUnsafe(exit);
|
|
1853
|
+
};
|
|
1854
|
+
if (peerConnection.signalingState === "closed") return complete(Exit.void);
|
|
1855
|
+
const mids = entries.map((entry) => entry.request.mid);
|
|
1856
|
+
const transceivers = peerConnection.getTransceivers();
|
|
1857
|
+
const closing = transceivers.filter((transceiver) => transceiver.mid !== null && mids.includes(transceiver.mid));
|
|
1858
|
+
const parked = transceivers.some((transceiver) => transceiver.direction !== "stopped" && !closing.includes(transceiver)) ? void 0 : closing[0];
|
|
1859
|
+
for (const transceiver of closing) if (transceiver === parked) {
|
|
1860
|
+
transceiver.direction = "inactive";
|
|
1861
|
+
yield* sdp("replaceTrack", () => transceiver.sender.replaceTrack(null)).pipe(Effect.catch(() => Effect.void));
|
|
1862
|
+
} else transceiver.stop();
|
|
1863
|
+
const exchange = Effect.gen(function* () {
|
|
1864
|
+
if (parked !== void 0) {
|
|
1865
|
+
yield* api.closeTracks(auth, void 0, mids).pipe(exchangeRequest("tracks/close"));
|
|
1866
|
+
return;
|
|
1867
|
+
}
|
|
1868
|
+
const offer = yield* sdp("createOffer", () => peerConnection.createOffer());
|
|
1869
|
+
yield* sdp("setLocalDescription", () => peerConnection.setLocalDescription(offer));
|
|
1870
|
+
const response = yield* api.closeTracks(auth, offer.sdp ?? "", mids).pipe(exchangeRequest("tracks/close"));
|
|
1871
|
+
if (response.sessionDescription === void 0 && onlyClosedTracks(response)) {
|
|
1872
|
+
if (peerConnection.signalingState === "have-local-offer") yield* sdp("rollback", () => peerConnection.setLocalDescription({ type: "rollback" })).pipe(Effect.catch(fail));
|
|
1873
|
+
return;
|
|
1874
|
+
}
|
|
1875
|
+
const answer = yield* answerOf("tracks/close", response);
|
|
1876
|
+
yield* sdp("setRemoteDescription", () => peerConnection.setRemoteDescription(answer));
|
|
1877
|
+
yield* waitForStableSignalingState;
|
|
1878
|
+
});
|
|
1879
|
+
const result = yield* Effect.result(exchange);
|
|
1880
|
+
if (result._tag === "Failure") {
|
|
1881
|
+
yield* recover(result.failure);
|
|
1882
|
+
return complete(Exit.fail(result.failure));
|
|
1883
|
+
}
|
|
1884
|
+
complete(Exit.void);
|
|
1885
|
+
}).pipe(Effect.annotateLogs({ sessionId: auth.sessionId }), Effect.withSpan("realtime.negotiate")))).pipe(RequestResolver.batchN(config.maxBatchSize), RequestResolver.setDelay(batchDelay));
|
|
1886
|
+
const close = (mid) => Effect.request(new CloseRequest({ mid }), closeResolver).pipe(Effect.retry({
|
|
1887
|
+
schedule: config.trackRetry,
|
|
1888
|
+
times: closeRetries,
|
|
1889
|
+
while: (error) => errorAction(error) === "Retry" && !isCloseTrackError(error)
|
|
1890
|
+
}), Effect.catch((error) => isCloseTrackError(error) ? Effect.logDebug("The SFU says that the track is closed", error) : Effect.logWarning("A track was not closed on the SFU", error)), Effect.annotateLogs({
|
|
1891
|
+
sessionId: auth.sessionId,
|
|
1892
|
+
mid
|
|
1893
|
+
}), Effect.forkIn(options.scope), Effect.asVoid);
|
|
1894
|
+
return {
|
|
1895
|
+
push: (input) => acquireRequest((abandoned) => Effect.request(new PushRequest({
|
|
1896
|
+
input,
|
|
1897
|
+
abandoned
|
|
1898
|
+
}), pushResolver), close),
|
|
1899
|
+
pull: (input) => acquireRequest((abandoned) => Effect.request(new PullRequest({
|
|
1900
|
+
input,
|
|
1901
|
+
abandoned
|
|
1902
|
+
}), pullResolver), close),
|
|
1903
|
+
close,
|
|
1904
|
+
update: (track) => queue.withPermit(Effect.gen(function* () {
|
|
1905
|
+
yield* Effect.annotateCurrentSpan({
|
|
1906
|
+
sessionId: auth.sessionId,
|
|
1907
|
+
trackName: track.trackName,
|
|
1908
|
+
mid: track.mid
|
|
1909
|
+
});
|
|
1910
|
+
const failed = (yield* api.updateTracks(auth, [track])).tracks?.find((t) => t.errorCode !== void 0);
|
|
1911
|
+
if (failed?.errorCode !== void 0) return yield* trackError(failed, failed.errorCode);
|
|
1912
|
+
}).pipe(Effect.annotateLogs({ sessionId: auth.sessionId }), Effect.withSpan("realtime.negotiate")))
|
|
1913
|
+
};
|
|
1914
|
+
});
|
|
1915
|
+
//#endregion
|
|
1916
|
+
//#region src/effect/client/internal/Session.ts
|
|
1917
|
+
var StableEnd = class extends Data.TaggedError("StableEnd") {};
|
|
1918
|
+
var UnstableEnd = class extends Data.TaggedError("UnstableEnd") {};
|
|
1919
|
+
var PermanentFailure = class extends Data.TaggedError("PermanentFailure") {};
|
|
1920
|
+
/**
|
|
1921
|
+
* The key of a shared pull. Two pulls of the same track have the same key, so
|
|
1922
|
+
* the request of the first one is used for both.
|
|
1923
|
+
*/
|
|
1924
|
+
var PullKey = class PullKey {
|
|
1925
|
+
constructor(input) {
|
|
1926
|
+
this.input = input;
|
|
1927
|
+
}
|
|
1928
|
+
[Equal.symbol](that) {
|
|
1929
|
+
return that instanceof PullKey && that.input.sessionId === this.input.sessionId && that.input.trackName === this.input.trackName;
|
|
1930
|
+
}
|
|
1931
|
+
[Hash.symbol]() {
|
|
1932
|
+
return Hash.string(`${this.input.sessionId}\n${this.input.trackName}`);
|
|
1933
|
+
}
|
|
1934
|
+
};
|
|
1935
|
+
const makeSessionManager = (config) => Effect.gen(function* () {
|
|
1936
|
+
const api = yield* RealtimeApi;
|
|
1937
|
+
const peerConnections = yield* PeerConnections;
|
|
1938
|
+
const state = yield* SubscriptionRef.make({ _tag: "Idle" });
|
|
1939
|
+
const transceivers = yield* PubSub.unbounded();
|
|
1940
|
+
const failedAttempts = yield* Ref.make(0);
|
|
1941
|
+
let currentSessionId;
|
|
1942
|
+
const setState = (next) => SubscriptionRef.set(state, next);
|
|
1943
|
+
/** The end of an attempt that failed before the session was open. */
|
|
1944
|
+
const creationEnd = (error) => Effect.fail(errorAction(error) === "Fail" ? new PermanentFailure({ error }) : new UnstableEnd({ error }));
|
|
1945
|
+
/** Runs one session. It ends only with a failure. */
|
|
1946
|
+
const oneSession = Effect.gen(function* () {
|
|
1947
|
+
currentSessionId = void 0;
|
|
1948
|
+
const [auth, iceServers] = yield* Effect.all([api.newSession, config.iceServers === void 0 ? api.iceServers : Effect.succeed(config.iceServers)], { concurrency: "unbounded" });
|
|
1949
|
+
currentSessionId = auth.sessionId;
|
|
1950
|
+
yield* Effect.annotateLogsScoped({ sessionId: auth.sessionId });
|
|
1951
|
+
yield* Effect.annotateCurrentSpan({ sessionId: auth.sessionId });
|
|
1952
|
+
const scope = yield* Effect.scope;
|
|
1953
|
+
const peerConnection = yield* peerConnections.make({
|
|
1954
|
+
iceServers: [...iceServers],
|
|
1955
|
+
bundlePolicy: "max-bundle"
|
|
1956
|
+
});
|
|
1957
|
+
const failed = yield* Deferred.make();
|
|
1958
|
+
const fail = (error) => Effect.asVoid(Deferred.fail(failed, error));
|
|
1959
|
+
const negotiator = yield* makeNegotiator({
|
|
1960
|
+
api,
|
|
1961
|
+
auth,
|
|
1962
|
+
config,
|
|
1963
|
+
fail,
|
|
1964
|
+
peerConnection,
|
|
1965
|
+
scope,
|
|
1966
|
+
transceivers
|
|
1967
|
+
});
|
|
1968
|
+
const pulls = yield* RcMap.make({ lookup: (key) => Effect.gen(function* () {
|
|
1969
|
+
const result = yield* negotiator.pull(key.input);
|
|
1970
|
+
let applied = key.input.preferredRid ?? "";
|
|
1971
|
+
let retired = false;
|
|
1972
|
+
yield* Effect.addFinalizer(() => Effect.sync(() => {
|
|
1973
|
+
retired = true;
|
|
1974
|
+
}));
|
|
1975
|
+
const updates = yield* Semaphore.make(1);
|
|
1976
|
+
const syncRid = (desired, force) => updates.withPermit(Effect.gen(function* () {
|
|
1977
|
+
if (retired || Deferred.isDoneUnsafe(failed) || peerConnection.signalingState === "closed") return;
|
|
1978
|
+
const preferredRid = (yield* desired) ?? "";
|
|
1979
|
+
if (!force && preferredRid === applied) return;
|
|
1980
|
+
applied = void 0;
|
|
1981
|
+
yield* negotiator.update({
|
|
1982
|
+
...key.input,
|
|
1983
|
+
mid: result.mid,
|
|
1984
|
+
preferredRid
|
|
1985
|
+
});
|
|
1986
|
+
applied = preferredRid;
|
|
1987
|
+
}));
|
|
1988
|
+
return {
|
|
1989
|
+
...result,
|
|
1990
|
+
syncRid
|
|
1991
|
+
};
|
|
1992
|
+
}) });
|
|
1993
|
+
const session = {
|
|
1994
|
+
auth,
|
|
1995
|
+
peerConnection,
|
|
1996
|
+
fail,
|
|
1997
|
+
negotiator,
|
|
1998
|
+
pull: (input) => RcMap.get(pulls, new PullKey(input)).pipe(Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) && Deferred.isDoneUnsafe(failed) ? Effect.never : Effect.failCause(cause)))
|
|
1999
|
+
};
|
|
2000
|
+
const events = yield* Queue.unbounded();
|
|
2001
|
+
const listen = (type, event) => Effect.acquireRelease(Effect.sync(() => {
|
|
2002
|
+
const listener = () => {
|
|
2003
|
+
Queue.offerUnsafe(events, event);
|
|
2004
|
+
};
|
|
2005
|
+
peerConnection.addEventListener(type, listener);
|
|
2006
|
+
return listener;
|
|
2007
|
+
}), (listener) => Effect.sync(() => peerConnection.removeEventListener(type, listener)));
|
|
2008
|
+
yield* listen("connectionstatechange", "connection");
|
|
2009
|
+
yield* listen("iceconnectionstatechange", "ice");
|
|
2010
|
+
const stable = yield* Ref.make(false);
|
|
2011
|
+
let stableTimer;
|
|
2012
|
+
const failWith = (reason) => fail(new PeerConnectionFailed({ reason }));
|
|
2013
|
+
const onConnectionState = Effect.gen(function* () {
|
|
2014
|
+
const { connectionState } = peerConnection;
|
|
2015
|
+
yield* setState({
|
|
2016
|
+
_tag: "Open",
|
|
2017
|
+
session,
|
|
2018
|
+
connectionState
|
|
2019
|
+
});
|
|
2020
|
+
if (stableTimer !== void 0) {
|
|
2021
|
+
yield* Fiber.interrupt(stableTimer);
|
|
2022
|
+
stableTimer = void 0;
|
|
2023
|
+
}
|
|
2024
|
+
if (connectionState === "connected") stableTimer = yield* Effect.sleep(config.sessionStableAfter).pipe(Effect.andThen(Ref.set(stable, true)), Effect.forkScoped);
|
|
2025
|
+
if (connectionState === "failed") yield* failWith("connection-failed");
|
|
2026
|
+
if (connectionState === "closed") yield* failWith("connection-closed");
|
|
2027
|
+
});
|
|
2028
|
+
let disconnectedTimer;
|
|
2029
|
+
const onIceConnectionState = Effect.gen(function* () {
|
|
2030
|
+
if (disconnectedTimer !== void 0) {
|
|
2031
|
+
yield* Fiber.interrupt(disconnectedTimer);
|
|
2032
|
+
disconnectedTimer = void 0;
|
|
2033
|
+
}
|
|
2034
|
+
const { iceConnectionState } = peerConnection;
|
|
2035
|
+
if (iceConnectionState === "failed") yield* failWith("ice-failed");
|
|
2036
|
+
if (iceConnectionState === "closed") yield* failWith("ice-closed");
|
|
2037
|
+
if (iceConnectionState === "disconnected") disconnectedTimer = yield* Effect.sleep(config.iceDisconnectedTimeout).pipe(Effect.andThen(failWith("ice-disconnected-timeout")), Effect.forkScoped);
|
|
2038
|
+
});
|
|
2039
|
+
yield* Queue.take(events).pipe(Effect.flatMap((event) => event === "connection" ? onConnectionState : onIceConnectionState), Effect.forever, Effect.forkScoped);
|
|
2040
|
+
yield* setState({
|
|
2041
|
+
_tag: "Open",
|
|
2042
|
+
session,
|
|
2043
|
+
connectionState: peerConnection.connectionState
|
|
2044
|
+
});
|
|
2045
|
+
yield* Effect.logInfo("The session is open");
|
|
2046
|
+
return yield* Deferred.await(failed).pipe(Effect.catch((error) => Ref.get(stable).pipe(Effect.flatMap((wasStable) => Effect.fail(wasStable ? new StableEnd({ error }) : new UnstableEnd({ error }))))));
|
|
2047
|
+
}).pipe(Effect.catchTags({
|
|
2048
|
+
ApiTransportError: creationEnd,
|
|
2049
|
+
ApiResponseError: creationEnd,
|
|
2050
|
+
ApiInvalidResponse: creationEnd,
|
|
2051
|
+
ApiAuthRedirect: creationEnd
|
|
2052
|
+
}), Effect.scoped, Effect.withSpan("realtime.session"));
|
|
2053
|
+
const supervise = Effect.gen(function* () {
|
|
2054
|
+
if ((yield* Ref.get(failedAttempts)) === 0) yield* setState({
|
|
2055
|
+
_tag: "Connecting",
|
|
2056
|
+
attempt: 1
|
|
2057
|
+
});
|
|
2058
|
+
return yield* oneSession;
|
|
2059
|
+
}).pipe(Effect.tapError((ended) => Effect.gen(function* () {
|
|
2060
|
+
const attempts = ended._tag === "StableEnd" ? 1 : yield* Ref.updateAndGet(failedAttempts, (n) => n + 1);
|
|
2061
|
+
yield* Ref.set(failedAttempts, attempts);
|
|
2062
|
+
yield* Effect.logWarning(`The session ended: ${ended.error._tag}${"step" in ended.error ? ` at ${ended.error.step}: ${String(ended.error.cause)}` : ""}`, ended.error).pipe(Effect.annotateLogs(currentSessionId === void 0 ? {} : { sessionId: currentSessionId }));
|
|
2063
|
+
yield* setState(ended._tag === "PermanentFailure" ? {
|
|
2064
|
+
_tag: "Failed",
|
|
2065
|
+
error: ended.error
|
|
2066
|
+
} : {
|
|
2067
|
+
_tag: "Reconnecting",
|
|
2068
|
+
error: ended.error,
|
|
2069
|
+
attempt: attempts
|
|
2070
|
+
});
|
|
2071
|
+
}))).pipe(Effect.retry({
|
|
2072
|
+
schedule: config.sessionRetry,
|
|
2073
|
+
while: (ended) => ended._tag === "UnstableEnd"
|
|
2074
|
+
}), Effect.catchTag("StableEnd", () => Effect.void), Effect.forever, Effect.catchTag("UnstableEnd", ({ error }) => setState({
|
|
2075
|
+
_tag: "Failed",
|
|
2076
|
+
error
|
|
2077
|
+
})), Effect.catchTag("PermanentFailure", () => Effect.void), Effect.andThen(Effect.never));
|
|
2078
|
+
const running = yield* RcRef.make({
|
|
2079
|
+
acquire: Effect.gen(function* () {
|
|
2080
|
+
yield* Ref.set(failedAttempts, 0);
|
|
2081
|
+
yield* Effect.addFinalizer(() => setState({ _tag: "Idle" }));
|
|
2082
|
+
yield* Effect.forkScoped(withMicrotaskScheduler(supervise));
|
|
2083
|
+
}),
|
|
2084
|
+
idleTimeToLive: config.sessionIdleTimeout
|
|
2085
|
+
});
|
|
2086
|
+
return {
|
|
2087
|
+
state,
|
|
2088
|
+
transceivers,
|
|
2089
|
+
use: RcRef.get(running)
|
|
2090
|
+
};
|
|
2091
|
+
});
|
|
2092
|
+
//#endregion
|
|
2093
|
+
//#region src/effect/client/RealtimeClient.ts
|
|
2094
|
+
/** Pushes local tracks to the Realtime SFU and pulls remote tracks from it. */
|
|
2095
|
+
var RealtimeClient = class RealtimeClient extends Context.Service()("effect-cloudflare-webrtc/RealtimeClient") {
|
|
2096
|
+
/** Needs `RealtimeApi` and `PeerConnections`. */
|
|
2097
|
+
static layer = (config) => Layer.effect(RealtimeClient, make(config));
|
|
2098
|
+
/**
|
|
2099
|
+
* All defaults for a browser: `fetch`, `RTCPeerConnection`, the devices
|
|
2100
|
+
* of the browser, and device preferences in `localStorage`.
|
|
2101
|
+
*/
|
|
2102
|
+
static layerBrowser = (config) => Layer.mergeAll(RealtimeClient.layer(config).pipe(Layer.provide(PeerConnections.layerBrowser), Layer.provide(RealtimeApi.layer(config)), Layer.provide(FetchHttpClient.layer), Layer.provide(Layer.succeed(FetchHttpClient.RequestInit, browserRequestInit(config?.credentials)))), MediaDevices.layerBrowser, DevicePreferences.layerLocalStorage);
|
|
2103
|
+
};
|
|
2104
|
+
/**
|
|
2105
|
+
* The `fetch` options of the browser layer. A redirect is not followed, so
|
|
2106
|
+
* that an expired login (for example Cloudflare Access) gives a response with
|
|
2107
|
+
* status `0`, which becomes `ApiAuthRedirect`.
|
|
2108
|
+
*/
|
|
2109
|
+
const browserRequestInit = (credentials = "same-origin") => ({
|
|
2110
|
+
redirect: "manual",
|
|
2111
|
+
credentials
|
|
2112
|
+
});
|
|
2113
|
+
const publicSessionState = (state) => state._tag === "Open" ? {
|
|
2114
|
+
_tag: "Open",
|
|
2115
|
+
sessionId: state.session.auth.sessionId,
|
|
2116
|
+
peerConnection: state.session.peerConnection,
|
|
2117
|
+
connectionState: state.connectionState
|
|
2118
|
+
} : state;
|
|
2119
|
+
/**
|
|
2120
|
+
* The poll interval of `waitForSentData` grows to this maximum. PUSH-06 says
|
|
2121
|
+
* that the metadata is given within 100 ms after the track starts to send
|
|
2122
|
+
* data.
|
|
2123
|
+
*/
|
|
2124
|
+
const maxDataPollIntervalMillis = 100;
|
|
2125
|
+
function hasSentData(report) {
|
|
2126
|
+
let sent = false;
|
|
2127
|
+
report.forEach((stat) => {
|
|
2128
|
+
if (typeof stat === "object" && stat !== null && "type" in stat && stat.type === "outbound-rtp" && "bytesSent" in stat && typeof stat.bytesSent === "number" && stat.bytesSent > 0) sent = true;
|
|
2129
|
+
});
|
|
2130
|
+
return sent;
|
|
2131
|
+
}
|
|
2132
|
+
const make = (config) => Effect.gen(function* () {
|
|
2133
|
+
const resolved = resolveConfig(config);
|
|
2134
|
+
const api = yield* RealtimeApi;
|
|
2135
|
+
const manager = yield* makeSessionManager(resolved);
|
|
2136
|
+
/**
|
|
2137
|
+
* The preferred RID of each pulled track, shared by the pulls of the
|
|
2138
|
+
* track. The value is removed when the last pull of the track closes.
|
|
2139
|
+
*/
|
|
2140
|
+
const sharedRids = yield* Ref.make(/* @__PURE__ */ new Map());
|
|
2141
|
+
const ridKey = (target) => `${target.sessionId}\n${target.trackName}`;
|
|
2142
|
+
/** Uses the value of the track, or sets it when the track is new. */
|
|
2143
|
+
const acquireRid = (key, initial) => Ref.modify(sharedRids, (map) => {
|
|
2144
|
+
const existing = map.get(key);
|
|
2145
|
+
const next = new Map(map);
|
|
2146
|
+
if (existing === void 0) {
|
|
2147
|
+
next.set(key, {
|
|
2148
|
+
rid: initial,
|
|
2149
|
+
pulls: 1
|
|
2150
|
+
});
|
|
2151
|
+
return [initial, next];
|
|
2152
|
+
}
|
|
2153
|
+
next.set(key, {
|
|
2154
|
+
rid: existing.rid,
|
|
2155
|
+
pulls: existing.pulls + 1
|
|
2156
|
+
});
|
|
2157
|
+
return [existing.rid, next];
|
|
2158
|
+
});
|
|
2159
|
+
const releaseRid = (key) => Ref.update(sharedRids, (map) => {
|
|
2160
|
+
const existing = map.get(key);
|
|
2161
|
+
if (existing === void 0) return map;
|
|
2162
|
+
const next = new Map(map);
|
|
2163
|
+
if (existing.pulls <= 1) next.delete(key);
|
|
2164
|
+
else next.set(key, {
|
|
2165
|
+
rid: existing.rid,
|
|
2166
|
+
pulls: existing.pulls - 1
|
|
2167
|
+
});
|
|
2168
|
+
return next;
|
|
2169
|
+
});
|
|
2170
|
+
const statsTargets = yield* Ref.make(/* @__PURE__ */ new Set());
|
|
2171
|
+
/** Adds the target to the statistics while the scope is open. */
|
|
2172
|
+
const registerStats = (peerConnection, target) => {
|
|
2173
|
+
const registration = {
|
|
2174
|
+
peerConnection,
|
|
2175
|
+
target
|
|
2176
|
+
};
|
|
2177
|
+
return Effect.acquireRelease(Ref.update(statsTargets, (set) => new Set(set).add(registration)), () => Ref.update(statsTargets, (set) => {
|
|
2178
|
+
const next = new Set(set);
|
|
2179
|
+
next.delete(registration);
|
|
2180
|
+
return next;
|
|
2181
|
+
}));
|
|
2182
|
+
};
|
|
2183
|
+
/** The targets of a session. Two pulls of a track share a transceiver. */
|
|
2184
|
+
const targetsOf = (peerConnection) => Ref.get(statsTargets).pipe(Effect.map((set) => {
|
|
2185
|
+
const byTransceiver = /* @__PURE__ */ new Map();
|
|
2186
|
+
for (const registration of set) {
|
|
2187
|
+
if (registration.peerConnection !== peerConnection) continue;
|
|
2188
|
+
byTransceiver.set(registration.target.transceiver, registration.target);
|
|
2189
|
+
}
|
|
2190
|
+
return [...byTransceiver.values()];
|
|
2191
|
+
}));
|
|
2192
|
+
const readRid = (key) => Ref.get(sharedRids).pipe(Effect.map((map) => map.get(key)?.rid));
|
|
2193
|
+
const writeRid = (key, rid) => Ref.update(sharedRids, (map) => {
|
|
2194
|
+
const existing = map.get(key);
|
|
2195
|
+
if (existing === void 0) return map;
|
|
2196
|
+
const next = new Map(map);
|
|
2197
|
+
next.set(key, {
|
|
2198
|
+
rid,
|
|
2199
|
+
pulls: existing.pulls
|
|
2200
|
+
});
|
|
2201
|
+
return next;
|
|
2202
|
+
});
|
|
2203
|
+
/**
|
|
2204
|
+
* The session for the pushes and pulls. It changes only when the session
|
|
2205
|
+
* changes, or when the session fails for good.
|
|
2206
|
+
*/
|
|
2207
|
+
const openSession = latestChanges(manager.state).pipe(Stream.map((state) => state._tag === "Open" ? {
|
|
2208
|
+
_tag: "Open",
|
|
2209
|
+
session: state.session
|
|
2210
|
+
} : state._tag === "Failed" ? {
|
|
2211
|
+
_tag: "Failed",
|
|
2212
|
+
error: state.error
|
|
2213
|
+
} : { _tag: "NoSession" }), Stream.changesWith((a, b) => a._tag === "Open" ? b._tag === "Open" && a.session === b.session : a._tag === b._tag));
|
|
2214
|
+
/**
|
|
2215
|
+
* The transceiver sends data. Metadata is given to other parties only
|
|
2216
|
+
* after this, so that they can pull the track immediately.
|
|
2217
|
+
*/
|
|
2218
|
+
const waitForSentData = (transceiver) => Effect.gen(function* () {
|
|
2219
|
+
let delay = 1;
|
|
2220
|
+
while (true) {
|
|
2221
|
+
if (yield* Effect.tryPromise(() => transceiver.sender.getStats()).pipe(Effect.map(hasSentData), Effect.catch(() => Effect.succeed(false)))) return;
|
|
2222
|
+
yield* Effect.sleep(Duration.millis(delay));
|
|
2223
|
+
delay = Math.min(delay * 1.1, maxDataPollIntervalMillis);
|
|
2224
|
+
}
|
|
2225
|
+
});
|
|
2226
|
+
const push = (source, options = {}) => Effect.gen(function* () {
|
|
2227
|
+
yield* manager.use;
|
|
2228
|
+
const trackName = options.trackName ?? crypto.randomUUID();
|
|
2229
|
+
const state = yield* SubscriptionRef.make({ _tag: "WaitingForTrack" });
|
|
2230
|
+
const latestTrack = yield* SubscriptionRef.make(Option.none());
|
|
2231
|
+
const encodings = yield* Ref.make(options.sendEncodings ?? []);
|
|
2232
|
+
const encodingsLock = yield* Semaphore.make(1);
|
|
2233
|
+
const published = yield* Ref.make(Option.none());
|
|
2234
|
+
const attempts = yield* Ref.make(0);
|
|
2235
|
+
const setState = (next) => SubscriptionRef.set(state, next);
|
|
2236
|
+
const tracks = latestChanges(latestTrack).pipe(Stream.filter(Option.isSome), Stream.map((track) => track.value));
|
|
2237
|
+
const replaceTrack = (transceiver, track) => transceiver.sender.track === track ? Effect.void : Effect.tryPromise({
|
|
2238
|
+
try: () => transceiver.sender.replaceTrack(track),
|
|
2239
|
+
catch: (cause) => new SenderError({
|
|
2240
|
+
operation: "replaceTrack",
|
|
2241
|
+
cause
|
|
2242
|
+
})
|
|
2243
|
+
}).pipe(Effect.catch((error) => Effect.logWarning("The track was not replaced", error)));
|
|
2244
|
+
const applyEncodings = (transceiver, next) => Effect.tryPromise({
|
|
2245
|
+
try: () => transceiver.sender.setParameters({
|
|
2246
|
+
...transceiver.sender.getParameters(),
|
|
2247
|
+
encodings: [...next]
|
|
2248
|
+
}),
|
|
2249
|
+
catch: (cause) => new SenderError({
|
|
2250
|
+
operation: "setParameters",
|
|
2251
|
+
cause
|
|
2252
|
+
})
|
|
2253
|
+
});
|
|
2254
|
+
const publishOnce = (session, first) => Effect.gen(function* () {
|
|
2255
|
+
yield* Effect.annotateCurrentSpan({
|
|
2256
|
+
sessionId: session.auth.sessionId,
|
|
2257
|
+
trackName
|
|
2258
|
+
});
|
|
2259
|
+
yield* setState({ _tag: "Negotiating" });
|
|
2260
|
+
const current = yield* SubscriptionRef.get(latestTrack);
|
|
2261
|
+
const sentEncodings = yield* Ref.get(encodings);
|
|
2262
|
+
const { transceiver, mid } = yield* session.negotiator.push({
|
|
2263
|
+
trackName,
|
|
2264
|
+
track: Option.getOrElse(current, () => first),
|
|
2265
|
+
sendEncodings: sentEncodings,
|
|
2266
|
+
onRetry: (error, attempt) => Ref.set(attempts, attempt).pipe(Effect.andThen(setState({
|
|
2267
|
+
_tag: "Retrying",
|
|
2268
|
+
error,
|
|
2269
|
+
attempt
|
|
2270
|
+
})), Effect.andThen(Effect.logInfo("The push is tried again", error).pipe(Effect.annotateLogs({ trackName }))))
|
|
2271
|
+
});
|
|
2272
|
+
yield* Effect.annotateCurrentSpan({ mid });
|
|
2273
|
+
yield* registerStats(session.peerConnection, {
|
|
2274
|
+
direction: "send",
|
|
2275
|
+
transceiver,
|
|
2276
|
+
trackName
|
|
2277
|
+
});
|
|
2278
|
+
yield* encodingsLock.withPermit(Effect.gen(function* () {
|
|
2279
|
+
yield* Effect.acquireRelease(Ref.set(published, Option.some(transceiver)), () => Ref.set(published, Option.none()));
|
|
2280
|
+
const newest = yield* Ref.get(encodings);
|
|
2281
|
+
if (!Equal.equals(newest, sentEncodings)) yield* applyEncodings(transceiver, newest).pipe(Effect.catch((error) => Effect.logWarning("The encodings were not applied", error).pipe(Effect.annotateLogs({ trackName }))));
|
|
2282
|
+
}));
|
|
2283
|
+
yield* tracks.pipe(Stream.runForEach((track) => replaceTrack(transceiver, track)), Effect.forkScoped);
|
|
2284
|
+
yield* setState({
|
|
2285
|
+
_tag: "WaitingForData",
|
|
2286
|
+
transceiver
|
|
2287
|
+
});
|
|
2288
|
+
yield* waitForSentData(transceiver);
|
|
2289
|
+
yield* Ref.set(attempts, 0);
|
|
2290
|
+
yield* setState({
|
|
2291
|
+
_tag: "Published",
|
|
2292
|
+
transceiver,
|
|
2293
|
+
metadata: {
|
|
2294
|
+
sessionId: session.auth.sessionId,
|
|
2295
|
+
trackName,
|
|
2296
|
+
location: "remote"
|
|
2297
|
+
}
|
|
2298
|
+
});
|
|
2299
|
+
return yield* Effect.never;
|
|
2300
|
+
}).pipe(Effect.annotateLogs({
|
|
2301
|
+
sessionId: session.auth.sessionId,
|
|
2302
|
+
trackName
|
|
2303
|
+
}), Effect.scoped, Effect.withSpan("realtime.push"));
|
|
2304
|
+
const publishOn = (session) => Effect.gen(function* () {
|
|
2305
|
+
yield* Ref.set(attempts, 0);
|
|
2306
|
+
const first = yield* Stream.runHead(tracks);
|
|
2307
|
+
if (Option.isNone(first)) return false;
|
|
2308
|
+
return yield* publishOnce(session, first.value).pipe(Effect.tapError((error) => error._tag === "TrackError" && errorAction(error) === "Retry" ? Ref.updateAndGet(attempts, (n) => n + 1).pipe(Effect.flatMap((attempt) => setState({
|
|
2309
|
+
_tag: "Retrying",
|
|
2310
|
+
error,
|
|
2311
|
+
attempt
|
|
2312
|
+
}).pipe(Effect.andThen(Effect.logInfo("The push is tried again", error).pipe(Effect.annotateLogs({
|
|
2313
|
+
sessionId: session.auth.sessionId,
|
|
2314
|
+
trackName
|
|
2315
|
+
})))))) : Effect.void), Effect.retry({
|
|
2316
|
+
schedule: resolved.trackRetry,
|
|
2317
|
+
while: (error) => error._tag === "TrackError" && errorAction(error) === "Retry"
|
|
2318
|
+
}), Effect.catch((error) => errorAction(error) === "ReplaceSession" ? setState({ _tag: "WaitingForSession" }).pipe(Effect.as(false)) : setState({
|
|
2319
|
+
_tag: "Failed",
|
|
2320
|
+
error
|
|
2321
|
+
}).pipe(Effect.as(true))));
|
|
2322
|
+
});
|
|
2323
|
+
/** The state of a push that waits for a session, as its track changes. */
|
|
2324
|
+
const waiting = SubscriptionRef.changes(latestTrack).pipe(Stream.map((track) => Option.isSome(track) ? { _tag: "WaitingForSession" } : { _tag: "WaitingForTrack" }), Stream.changesWith((a, b) => a._tag === b._tag), Stream.mapEffect((next) => setState(next).pipe(Effect.as(false))));
|
|
2325
|
+
const publisher = yield* openSession.pipe(Stream.switchMap((slot) => slot._tag === "Open" ? Stream.fromEffect(publishOn(slot.session)) : slot._tag === "Failed" ? Stream.fromEffect(setState({
|
|
2326
|
+
_tag: "Failed",
|
|
2327
|
+
error: new SessionFailed({ error: slot.error })
|
|
2328
|
+
}).pipe(Effect.as(true))) : waiting), Stream.takeUntil((stopped) => stopped), Stream.runDrain, withMicrotaskScheduler, Effect.forkScoped);
|
|
2329
|
+
yield* source.pipe(Stream.runForEach((track) => SubscriptionRef.set(latestTrack, Option.some(track))), Effect.catch((error) => Fiber.interrupt(publisher).pipe(Effect.andThen(setState({
|
|
2330
|
+
_tag: "Failed",
|
|
2331
|
+
error
|
|
2332
|
+
})))), withMicrotaskScheduler, Effect.forkScoped);
|
|
2333
|
+
return {
|
|
2334
|
+
trackName,
|
|
2335
|
+
state: fromSubscriptionRef(state),
|
|
2336
|
+
metadata: latestChanges(state).pipe(Stream.filter((s) => s._tag === "Published"), Stream.map((s) => s.metadata)),
|
|
2337
|
+
setSendEncodings: (next) => encodingsLock.withPermit(Effect.gen(function* () {
|
|
2338
|
+
yield* Ref.set(encodings, next);
|
|
2339
|
+
const transceiver = yield* Ref.get(published);
|
|
2340
|
+
if (Option.isNone(transceiver)) return;
|
|
2341
|
+
yield* applyEncodings(transceiver.value, next);
|
|
2342
|
+
}))
|
|
2343
|
+
};
|
|
2344
|
+
});
|
|
2345
|
+
const pull = (metadata, options = {}) => Effect.gen(function* () {
|
|
2346
|
+
yield* manager.use;
|
|
2347
|
+
const state = yield* SubscriptionRef.make({ _tag: "WaitingForMetadata" });
|
|
2348
|
+
const latestMetadata = yield* SubscriptionRef.make(Option.none());
|
|
2349
|
+
const pendingRid = yield* Ref.make(options.preferredRid);
|
|
2350
|
+
const currentRidKey = yield* Ref.make(Option.none());
|
|
2351
|
+
const ridLock = yield* Semaphore.make(1);
|
|
2352
|
+
const updateLive = yield* Ref.make(Effect.void);
|
|
2353
|
+
const attempts = yield* Ref.make(0);
|
|
2354
|
+
const setState = (next) => SubscriptionRef.set(state, next);
|
|
2355
|
+
/**
|
|
2356
|
+
* Uses the RID of the target. It sets the RID when this pull is the
|
|
2357
|
+
* first one of the track.
|
|
2358
|
+
*/
|
|
2359
|
+
const useRid = (target) => Effect.gen(function* () {
|
|
2360
|
+
const key = ridKey(target);
|
|
2361
|
+
const current = yield* Ref.get(currentRidKey);
|
|
2362
|
+
if (Option.isSome(current) && current.value === key) return;
|
|
2363
|
+
yield* acquireRid(key, yield* Ref.get(pendingRid));
|
|
2364
|
+
yield* Ref.set(currentRidKey, Option.some(key));
|
|
2365
|
+
if (Option.isSome(current)) yield* releaseRid(current.value);
|
|
2366
|
+
});
|
|
2367
|
+
yield* Effect.addFinalizer(() => Ref.get(currentRidKey).pipe(Effect.flatMap((current) => Option.isSome(current) ? releaseRid(current.value) : Effect.void)));
|
|
2368
|
+
const pullOnce = (session, target) => Effect.gen(function* () {
|
|
2369
|
+
yield* Effect.annotateCurrentSpan({
|
|
2370
|
+
sessionId: target.sessionId,
|
|
2371
|
+
trackName: target.trackName
|
|
2372
|
+
});
|
|
2373
|
+
yield* setState({
|
|
2374
|
+
_tag: "Negotiating",
|
|
2375
|
+
metadata: target
|
|
2376
|
+
});
|
|
2377
|
+
yield* ridLock.withPermit(useRid(target));
|
|
2378
|
+
const key = ridKey(target);
|
|
2379
|
+
const requestedRid = yield* readRid(key);
|
|
2380
|
+
const { mid, track, transceiver, syncRid } = yield* session.pull({
|
|
2381
|
+
sessionId: target.sessionId,
|
|
2382
|
+
trackName: target.trackName,
|
|
2383
|
+
preferredRid: requestedRid
|
|
2384
|
+
});
|
|
2385
|
+
yield* Effect.annotateCurrentSpan({ mid });
|
|
2386
|
+
yield* registerStats(session.peerConnection, {
|
|
2387
|
+
direction: "receive",
|
|
2388
|
+
transceiver,
|
|
2389
|
+
metadata: target
|
|
2390
|
+
});
|
|
2391
|
+
yield* ridLock.withPermit(Effect.gen(function* () {
|
|
2392
|
+
const desired = readRid(key);
|
|
2393
|
+
yield* Effect.acquireRelease(Ref.set(updateLive, syncRid(desired, true)), () => Ref.set(updateLive, Effect.void));
|
|
2394
|
+
yield* syncRid(desired, false).pipe(Effect.catch((error) => Effect.logWarning("The simulcast layer was not applied", error).pipe(Effect.annotateLogs({ trackName: target.trackName }))));
|
|
2395
|
+
}));
|
|
2396
|
+
yield* Ref.set(attempts, 0);
|
|
2397
|
+
yield* setState({
|
|
2398
|
+
_tag: "Live",
|
|
2399
|
+
metadata: target,
|
|
2400
|
+
track,
|
|
2401
|
+
transceiver
|
|
2402
|
+
});
|
|
2403
|
+
return yield* Effect.never;
|
|
2404
|
+
}).pipe(Effect.annotateLogs({
|
|
2405
|
+
sessionId: target.sessionId,
|
|
2406
|
+
trackName: target.trackName
|
|
2407
|
+
}), Effect.scoped, Effect.withSpan("realtime.pull"));
|
|
2408
|
+
const pullOn = (session, target) => Effect.gen(function* () {
|
|
2409
|
+
yield* Ref.set(attempts, 0);
|
|
2410
|
+
return yield* pullOnce(session, target).pipe(Effect.tapError((error) => errorAction(error) === "Retry" ? Ref.updateAndGet(attempts, (n) => n + 1).pipe(Effect.flatMap((attempt) => setState({
|
|
2411
|
+
_tag: "Retrying",
|
|
2412
|
+
metadata: target,
|
|
2413
|
+
error,
|
|
2414
|
+
attempt
|
|
2415
|
+
}).pipe(Effect.andThen(Effect.logInfo("The pull is tried again", error).pipe(Effect.annotateLogs({
|
|
2416
|
+
sessionId: target.sessionId,
|
|
2417
|
+
trackName: target.trackName
|
|
2418
|
+
})))))) : Effect.void), Effect.retry({
|
|
2419
|
+
schedule: resolved.trackRetry,
|
|
2420
|
+
while: (error) => errorAction(error) === "Retry"
|
|
2421
|
+
}), Effect.catch((error) => errorAction(error) === "ReplaceSession" ? setState({
|
|
2422
|
+
_tag: "WaitingForSession",
|
|
2423
|
+
metadata: target
|
|
2424
|
+
}).pipe(Effect.as(false)) : setState({
|
|
2425
|
+
_tag: "Failed",
|
|
2426
|
+
error
|
|
2427
|
+
}).pipe(Effect.as(true))));
|
|
2428
|
+
});
|
|
2429
|
+
const targets = latestChanges(latestMetadata).pipe(Stream.changesWith((a, b) => Option.isNone(a) || Option.isNone(b) ? a._tag === b._tag : trackMetadataEquals(a.value, b.value)));
|
|
2430
|
+
const puller = yield* Stream.zipLatest(openSession, targets).pipe(Stream.switchMap(([slot, target]) => slot._tag === "Failed" ? Stream.fromEffect(setState({
|
|
2431
|
+
_tag: "Failed",
|
|
2432
|
+
error: new SessionFailed({ error: slot.error })
|
|
2433
|
+
}).pipe(Effect.as(true))) : slot._tag === "Open" && Option.isSome(target) ? Stream.fromEffect(pullOn(slot.session, target.value)) : Stream.fromEffect(Option.isSome(target) ? setState({
|
|
2434
|
+
_tag: "WaitingForSession",
|
|
2435
|
+
metadata: target.value
|
|
2436
|
+
}).pipe(Effect.as(false)) : Effect.succeed(false))), Stream.takeUntil((stopped) => stopped), Stream.runDrain, withMicrotaskScheduler, Effect.forkScoped);
|
|
2437
|
+
yield* (Stream.isStream(metadata) ? metadata : Stream.succeed(metadata)).pipe(Stream.runForEach((target) => SubscriptionRef.set(latestMetadata, Option.some(target))), Effect.catch((error) => Fiber.interrupt(puller).pipe(Effect.andThen(setState({
|
|
2438
|
+
_tag: "Failed",
|
|
2439
|
+
error
|
|
2440
|
+
})))), withMicrotaskScheduler, Effect.forkScoped);
|
|
2441
|
+
return {
|
|
2442
|
+
state: fromSubscriptionRef(state),
|
|
2443
|
+
track: latestChanges(state).pipe(Stream.filter((s) => s._tag === "Live"), Stream.map((s) => s.track)),
|
|
2444
|
+
setPreferredRid: (rid) => ridLock.withPermit(Effect.gen(function* () {
|
|
2445
|
+
yield* Ref.set(pendingRid, rid);
|
|
2446
|
+
const key = yield* Ref.get(currentRidKey);
|
|
2447
|
+
if (Option.isSome(key)) yield* writeRid(key.value, rid);
|
|
2448
|
+
return yield* Ref.get(updateLive);
|
|
2449
|
+
})).pipe(Effect.flatten)
|
|
2450
|
+
};
|
|
2451
|
+
});
|
|
2452
|
+
return RealtimeClient.of({
|
|
2453
|
+
sessionState: map(fromSubscriptionRef(manager.state), publicSessionState),
|
|
2454
|
+
push,
|
|
2455
|
+
pull,
|
|
2456
|
+
transceivers: Stream.fromPubSub(manager.transceivers),
|
|
2457
|
+
stats: (options) => openSession.pipe(Stream.switchMap((slot) => slot._tag === "Open" ? sampleSession({
|
|
2458
|
+
sessionId: slot.session.auth.sessionId,
|
|
2459
|
+
peerConnection: slot.session.peerConnection
|
|
2460
|
+
}, targetsOf(slot.session.peerConnection), options) : Stream.empty)),
|
|
2461
|
+
history: api.history,
|
|
2462
|
+
apiEvents: api.events
|
|
2463
|
+
});
|
|
2464
|
+
});
|
|
2465
|
+
/**
|
|
2466
|
+
* Pushes a track while the stream runs, and gives the metadata each time
|
|
2467
|
+
* the track is published. Ending the stream closes the track. The stream
|
|
2468
|
+
* fails when the push has the `Failed` state.
|
|
2469
|
+
*
|
|
2470
|
+
* The stream is not shared. Each run is one more push.
|
|
2471
|
+
*/
|
|
2472
|
+
const pushStream = (source, options) => Stream.unwrap(Effect.gen(function* () {
|
|
2473
|
+
return (yield* (yield* RealtimeClient).push(source, options)).state.changes.pipe(Stream.flatMap((state) => state._tag === "Published" ? Stream.succeed(state.metadata) : state._tag === "Failed" ? Stream.fail(state.error) : Stream.empty));
|
|
2474
|
+
}));
|
|
2475
|
+
/**
|
|
2476
|
+
* Pulls a track while the stream runs, and gives each new track. Ending the
|
|
2477
|
+
* stream closes the track. The stream fails when the pull has the `Failed`
|
|
2478
|
+
* state.
|
|
2479
|
+
*
|
|
2480
|
+
* The stream is not shared. Each run is one more pull.
|
|
2481
|
+
*/
|
|
2482
|
+
const pullStream = (metadata, options) => Stream.unwrap(Effect.gen(function* () {
|
|
2483
|
+
return (yield* (yield* RealtimeClient).pull(metadata, options)).state.changes.pipe(Stream.flatMap((state) => state._tag === "Live" ? Stream.succeed(state.track) : state._tag === "Failed" ? Stream.fail(state.error) : Stream.empty));
|
|
2484
|
+
}));
|
|
2485
|
+
//#endregion
|
|
2486
|
+
export { PeerConnectionFailed as A, ApiAuthRedirect as C, DevicesExhausted as D, ApiTransportError as E, TransceiverNotFound as F, TransformFailed as I, SessionFailed as M, SinkError as N, MediaAccessError as O, TrackError as P, devices as S, ApiResponseError as T, TrackSource as _, RealtimeApi as a, microtaskScheduler as b, defaultRetrySchedule as c, MediaSources as d, MicrophoneSource as f, inaudibleAudioTrack as g, blackVideoTrack as h, TrackMetadata as i, SenderError as j, NegotiationOutcomeUnknown as k, ScreenShareSource as l, trackIsHealthy as m, pullStream as n, sessionTokenHeader as o, resilientTrack as p, pushStream as r, PeerConnections as s, RealtimeClient as t, CameraSource as u, DevicePreferences as v, ApiInvalidResponse as w, MediaDevices as x, AudioSink as y };
|
|
2487
|
+
|
|
2488
|
+
//# sourceMappingURL=RealtimeClient-Bl0Tun5r.js.map
|