@stream-io/video-client 1.39.2 → 1.40.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.
@@ -40,9 +40,49 @@ export const withHeaders = (
40
40
  };
41
41
  };
42
42
 
43
+ export const TIMEOUT_SYMBOL = '@@stream-io/timeout';
44
+
45
+ export const withTimeout = (
46
+ timeoutMs: number,
47
+ trace?: Trace,
48
+ ): RpcInterceptor => {
49
+ const scheduleTimeout = (methodName: string) => {
50
+ const controller = new AbortController();
51
+ // aborts with specially crafted error that can be reliably recognized by
52
+ // @protobuf-ts/twirp-transport and our internal retry logic.
53
+ // https://github.com/timostamm/protobuf-ts/blob/657e64e80009e503e94f608fda423fbcbf4fb5a7/packages/twirp-transport/src/twirp-transport.ts#L102-L107
54
+ const timeoutId = setTimeout(() => {
55
+ trace?.(`${methodName}Timeout`, [timeoutMs]);
56
+ const error = new Error(TIMEOUT_SYMBOL);
57
+ error.name = 'AbortError';
58
+ controller.abort(error);
59
+ }, timeoutMs);
60
+ return [controller.signal, () => clearTimeout(timeoutId)] as const;
61
+ };
62
+
63
+ return {
64
+ interceptUnary(
65
+ next: NextUnaryFn,
66
+ method: MethodInfo,
67
+ input: object,
68
+ options: RpcOptions,
69
+ ): UnaryCall {
70
+ // respect external abort signals if provided
71
+ if (options.abort) return next(method, input, options);
72
+
73
+ // set up a custom abort signal for the RPC call
74
+ const [signal, cancel] = scheduleTimeout(method.name);
75
+ const invocation = next(method, input, { ...options, abort: signal });
76
+ invocation.then(cancel, cancel);
77
+
78
+ return invocation;
79
+ },
80
+ };
81
+ };
82
+
43
83
  export const withRequestLogger = (
44
84
  logger: ScopedLogger,
45
- level: LogLevel,
85
+ level: LogLevel = 'trace',
46
86
  ): RpcInterceptor => {
47
87
  return {
48
88
  interceptUnary: (
@@ -78,18 +118,24 @@ export const withRequestTracer = (trace: Trace): RpcInterceptor => {
78
118
  input: object,
79
119
  options: RpcOptions,
80
120
  ): UnaryCall {
81
- const name = method.name as RpcMethodName;
82
- if (exclusions.has(name)) return next(method, input, options);
121
+ const methodName = method.name as RpcMethodName;
122
+ if (exclusions.has(methodName)) return next(method, input, options);
123
+
124
+ const { invocationMeta: { attempt = 0 } = {} } = options;
125
+ const traceName =
126
+ attempt === 0 ? methodName : `${methodName}(${attempt})`;
127
+ trace(traceName, input);
83
128
 
84
- trace(name, input);
85
129
  const unaryCall = next(method, input, options);
86
130
  unaryCall.then(
87
131
  (invocation) => {
88
132
  const response = invocation.response as SfuResponseWithError;
89
- if (response.error) traceError(name, input, response.error);
90
- if (responseInclusions.has(name)) trace(`${name}Response`, response);
133
+ if (response.error) traceError(traceName, input, response.error);
134
+ if (responseInclusions.has(methodName)) {
135
+ trace(`${traceName}Response`, response);
136
+ }
91
137
  },
92
- (error) => traceError(name, input, error),
138
+ (error) => traceError(methodName, input, error),
93
139
  );
94
140
  return unaryCall;
95
141
  },
@@ -7,6 +7,8 @@ import { TwirpErrorCode } from '@protobuf-ts/twirp-transport';
7
7
  import { retryInterval, sleep } from '../coordinator/connection/utils';
8
8
  import { Error as SfuError } from '../gen/video/sfu/models/models';
9
9
  import { videoLoggerSystem } from '../logger';
10
+ import { TIMEOUT_SYMBOL } from './createClient';
11
+ import type { RpcInvocationMeta } from './types';
10
12
 
11
13
  /**
12
14
  * An internal interface which asserts that "retryable" SFU responses
@@ -28,26 +30,30 @@ export interface SfuResponseWithError {
28
30
  *
29
31
  * @param rpc the closure around the RPC call to execute.
30
32
  * @param signal the signal to abort the RPC call and retries loop.
33
+ * @param maxRetries the maximum number of retries to perform. Defaults to `Number.POSITIVE_INFINITY`.
31
34
  */
32
35
  export const retryable = async <
33
36
  I extends object,
34
37
  O extends SfuResponseWithError,
35
38
  >(
36
- rpc: () => UnaryCall<I, O>,
39
+ rpc: (invocationMeta: RpcInvocationMeta) => UnaryCall<I, O>,
37
40
  signal?: AbortSignal,
41
+ maxRetries = Number.POSITIVE_INFINITY,
38
42
  ): Promise<FinishedUnaryCall<I, O>> => {
39
43
  let attempt = 0;
40
44
  let result: FinishedUnaryCall<I, O> | undefined = undefined;
41
45
  do {
42
46
  if (attempt > 0) await sleep(retryInterval(attempt));
43
47
  try {
44
- result = await rpc();
48
+ result = await rpc({ attempt });
45
49
  } catch (err) {
46
50
  const isRequestCancelled =
47
51
  err instanceof RpcError &&
52
+ err.message !== TIMEOUT_SYMBOL &&
48
53
  err.code === TwirpErrorCode[TwirpErrorCode.cancelled];
49
54
  const isAborted = signal?.aborted ?? false;
50
55
  if (isRequestCancelled || isAborted) throw err;
56
+ if (attempt + 1 >= maxRetries) throw err;
51
57
  videoLoggerSystem
52
58
  .getLogger('sfu-client', { tags: ['rpc'] })
53
59
  .debug(`rpc failed (${attempt})`, err);
@@ -0,0 +1,11 @@
1
+ export type RpcInvocationMeta = {
2
+ attempt: number;
3
+ };
4
+
5
+ declare module '@protobuf-ts/runtime-rpc' {
6
+ // instead of casting, we extend the default interface with
7
+ // an additional payload provided by our `retryable` implementation
8
+ interface RpcOptions {
9
+ invocationMeta?: RpcInvocationMeta;
10
+ }
11
+ }