@xdcobra/react-native-grpc 1.0.0 → 1.1.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.
Files changed (68) hide show
  1. package/README.md +176 -6
  2. package/android/src/main/java/com/reactnativegrpc/GrpcModule.java +233 -88
  3. package/ios/Grpc.h +1 -1
  4. package/ios/Grpc.m +210 -24
  5. package/lib/commonjs/channel.js +84 -0
  6. package/lib/commonjs/channel.js.map +1 -0
  7. package/lib/commonjs/client.js +531 -128
  8. package/lib/commonjs/client.js.map +1 -1
  9. package/lib/commonjs/create-client.js +206 -0
  10. package/lib/commonjs/create-client.js.map +1 -0
  11. package/lib/commonjs/index.js +32 -1
  12. package/lib/commonjs/index.js.map +1 -1
  13. package/lib/commonjs/interceptors.js +116 -0
  14. package/lib/commonjs/interceptors.js.map +1 -0
  15. package/lib/commonjs/native.js +24 -0
  16. package/lib/commonjs/native.js.map +1 -0
  17. package/lib/commonjs/retry.js +153 -0
  18. package/lib/commonjs/retry.js.map +1 -0
  19. package/lib/commonjs/status.js +54 -0
  20. package/lib/commonjs/status.js.map +1 -0
  21. package/lib/commonjs/types.js +29 -0
  22. package/lib/commonjs/types.js.map +1 -1
  23. package/lib/module/channel.js +76 -0
  24. package/lib/module/channel.js.map +1 -0
  25. package/lib/module/client.js +518 -122
  26. package/lib/module/client.js.map +1 -1
  27. package/lib/module/create-client.js +201 -0
  28. package/lib/module/create-client.js.map +1 -0
  29. package/lib/module/index.js +3 -0
  30. package/lib/module/index.js.map +1 -1
  31. package/lib/module/interceptors.js +104 -0
  32. package/lib/module/interceptors.js.map +1 -0
  33. package/lib/module/native.js +17 -0
  34. package/lib/module/native.js.map +1 -0
  35. package/lib/module/retry.js +141 -0
  36. package/lib/module/retry.js.map +1 -0
  37. package/lib/module/status.js +46 -0
  38. package/lib/module/status.js.map +1 -0
  39. package/lib/module/types.js +17 -0
  40. package/lib/module/types.js.map +1 -1
  41. package/lib/typescript/channel.d.ts +27 -0
  42. package/lib/typescript/channel.d.ts.map +1 -0
  43. package/lib/typescript/client.d.ts +56 -49
  44. package/lib/typescript/client.d.ts.map +1 -1
  45. package/lib/typescript/create-client.d.ts +65 -0
  46. package/lib/typescript/create-client.d.ts.map +1 -0
  47. package/lib/typescript/index.d.ts +5 -0
  48. package/lib/typescript/index.d.ts.map +1 -1
  49. package/lib/typescript/interceptors.d.ts +43 -0
  50. package/lib/typescript/interceptors.d.ts.map +1 -0
  51. package/lib/typescript/native.d.ts +53 -0
  52. package/lib/typescript/native.d.ts.map +1 -0
  53. package/lib/typescript/retry.d.ts +56 -0
  54. package/lib/typescript/retry.d.ts.map +1 -0
  55. package/lib/typescript/status.d.ts +24 -0
  56. package/lib/typescript/status.d.ts.map +1 -0
  57. package/lib/typescript/types.d.ts +60 -0
  58. package/lib/typescript/types.d.ts.map +1 -1
  59. package/package.json +48 -7
  60. package/src/channel.ts +110 -0
  61. package/src/client.ts +725 -200
  62. package/src/create-client.ts +391 -0
  63. package/src/index.ts +17 -0
  64. package/src/interceptors.ts +167 -0
  65. package/src/native.ts +99 -0
  66. package/src/retry.ts +208 -0
  67. package/src/status.ts +50 -0
  68. package/src/types.ts +64 -0
package/src/client.ts CHANGED
@@ -4,72 +4,42 @@ import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
4
4
  import { GrpcBidiStreamingCall } from './bidi-streaming';
5
5
  import { GrpcClientStreamingCall, ServerInputStream } from './client-streaming';
6
6
  import { GrpcError } from './errors';
7
+ import {
8
+ combineInterceptors,
9
+ GrpcInterceptor,
10
+ runOnError,
11
+ runOnHeaders,
12
+ runOnMessage,
13
+ runOnSendMessage,
14
+ runOnStart,
15
+ runOnTrailers,
16
+ toGrpcError,
17
+ } from './interceptors';
18
+ import { GrpcRequestObject, nativeGrpc } from './native';
7
19
  import {
8
20
  GrpcServerStreamingCall,
9
21
  ServerOutputStream,
10
22
  } from './server-streaming';
11
- import { GrpcCallOptions, GrpcMetadata, GrpcTlsOptions } from './types';
23
+ import {
24
+ computeRetryBackoffMs,
25
+ delay,
26
+ EffectiveCallPolicy,
27
+ GrpcHedgingPolicy,
28
+ GrpcRetryPolicy,
29
+ normalizeHedgingPolicy,
30
+ normalizeRetryPolicy,
31
+ remainingDeadlineSeconds,
32
+ resolveEffectivePolicy,
33
+ } from './retry';
34
+ import { GrpcStatusCode } from './status';
35
+ import {
36
+ DEFAULT_CHANNEL_ID,
37
+ GrpcCallOptions,
38
+ GrpcMetadata,
39
+ GrpcTlsOptions,
40
+ } from './types';
12
41
  import { GrpcUnaryCall } from './unary';
13
42
 
14
- type GrpcRequestObject = {
15
- data: string;
16
- /** Optional per-call override; native falls back to global default when omitted. */
17
- deadlineSeconds?: number;
18
- };
19
-
20
- type GrpcType = {
21
- getHost: () => Promise<string>;
22
- getIsInsecure: () => Promise<boolean>;
23
- setHost(host: string): void;
24
- setInsecure(insecure: boolean): void;
25
- setTlsOptions(options: {
26
- rootCertsPem: string | null;
27
- certificateChainPem: string | null;
28
- privateKeyPem: string | null;
29
- hostNameOverride: string | null;
30
- spkiSha256Pins: string[] | null;
31
- }): void;
32
- setCompression(enable: boolean, compressorName: string): void;
33
- setResponseSizeLimit(limitInBytes: number): void;
34
- setCallDeadlineSeconds(seconds: number): void;
35
- initGrpcChannel(): void;
36
- unaryCall(
37
- id: number,
38
- path: string,
39
- obj: GrpcRequestObject,
40
- requestHeaders?: GrpcMetadata
41
- ): Promise<void>;
42
- serverStreamingCall(
43
- id: number,
44
- path: string,
45
- obj: GrpcRequestObject,
46
- requestHeaders?: GrpcMetadata
47
- ): Promise<void>;
48
- cancelGrpcCall: (id: number) => Promise<boolean>;
49
- clientStreamingCall(
50
- id: number,
51
- path: string,
52
- obj: GrpcRequestObject,
53
- requestHeaders?: GrpcMetadata
54
- ): Promise<void>;
55
- bidiStreamingCall(
56
- id: number,
57
- path: string,
58
- obj: GrpcRequestObject,
59
- requestHeaders?: GrpcMetadata
60
- ): Promise<void>;
61
- finishClientStreaming(id: number): Promise<void>;
62
- resetConnection(message: string): void;
63
- setKeepAlive(
64
- enable: boolean,
65
- keepAliveTime: number,
66
- keepAliveTimeOut: number
67
- ): void;
68
- onConnectionStateChange(): void;
69
- setUiLogEnabled(enable: boolean): void;
70
- enterIdle(): void;
71
- };
72
-
73
43
  type GrpcEventType = 'response' | 'error' | 'headers' | 'trailers';
74
44
 
75
45
  /* prettier-ignore */
@@ -98,14 +68,6 @@ type GrpcEvent = {
98
68
  type: GrpcEventType;
99
69
  } & GrpcEventPayload;
100
70
 
101
- function nativeGrpc(): GrpcType {
102
- const grpc = (NativeModules as { Grpc: GrpcType }).Grpc;
103
- if (!grpc) {
104
- throw new Error('NativeModules.Grpc is not linked');
105
- }
106
- return grpc;
107
- }
108
-
109
71
  const Emitter = new NativeEventEmitter(NativeModules.Grpc);
110
72
 
111
73
  type Deferred<T> = {
@@ -119,6 +81,8 @@ type DeferredCalls = {
119
81
  response?: Deferred<Uint8Array>;
120
82
  trailers?: Deferred<GrpcMetadata>;
121
83
  data?: ServerOutputStream;
84
+ method: string;
85
+ interceptors: GrpcInterceptor[];
122
86
  };
123
87
 
124
88
  type DeferredCallMap = {
@@ -156,36 +120,55 @@ let idCtr = 1;
156
120
 
157
121
  const deferredMap: DeferredCallMap = {};
158
122
 
123
+ function rejectDeferredCall(deferred: DeferredCalls, error: GrpcError) {
124
+ deferred.headers?.reject(error);
125
+ deferred.trailers?.reject(error);
126
+ deferred.response?.reject(error);
127
+ deferred.data?.noitfyError(error);
128
+ }
129
+
159
130
  function handleGrpcEvent(event: GrpcEvent) {
160
131
  const deferred = deferredMap[event.id];
161
132
 
162
133
  if (deferred) {
134
+ const { method, interceptors } = deferred;
163
135
  switch (event.type) {
164
136
  case 'headers':
165
- deferred.headers?.resolve(event.payload);
137
+ deferred.headers?.resolve(
138
+ runOnHeaders(interceptors, event.payload, method)
139
+ );
166
140
  break;
167
- case 'response':
168
- const data = toByteArray(event.payload);
141
+ case 'response': {
142
+ const data = runOnMessage(
143
+ interceptors,
144
+ toByteArray(event.payload),
145
+ method
146
+ );
169
147
 
170
148
  deferred.data?.notifyData(data);
171
149
  deferred.response?.resolve(data);
172
150
  break;
151
+ }
173
152
  case 'trailers':
174
- deferred.trailers?.resolve(event.payload);
153
+ deferred.trailers?.resolve(
154
+ runOnTrailers(interceptors, event.payload, method)
155
+ );
175
156
  deferred.data?.notifyComplete();
176
157
 
177
158
  delete deferredMap[event.id];
178
159
  break;
179
- case 'error':
180
- const error = new GrpcError(event.error, event.code, event.trailers);
160
+ case 'error': {
161
+ const error = runOnError(
162
+ interceptors,
163
+ new GrpcError(event.error, event.code, event.trailers),
164
+ method
165
+ );
181
166
 
182
- deferred.headers?.reject(error);
183
- deferred.trailers?.reject(error);
184
- deferred.response?.reject(error);
185
- deferred.data?.noitfyError(error);
167
+ rejectDeferredCall(deferred, error);
186
168
 
187
169
  delete deferredMap[event.id];
188
170
  break;
171
+ }
189
172
  }
190
173
  }
191
174
  }
@@ -207,96 +190,419 @@ function buildRequestObject(
207
190
  return obj;
208
191
  }
209
192
 
210
- export class GrpcClient {
211
- constructor() {
212
- Emitter.addListener('grpc-call', handleGrpcEvent);
213
- }
214
- destroy() {
215
- Emitter.removeAllListeners('grpc-call');
193
+ export function normalizeTlsOptions(options: GrpcTlsOptions = {}): {
194
+ rootCertsPem: string | null;
195
+ certificateChainPem: string | null;
196
+ privateKeyPem: string | null;
197
+ hostNameOverride: string | null;
198
+ spkiSha256Pins: string[] | null;
199
+ } {
200
+ const rootCertsPem = options.rootCertsPem ?? null;
201
+ const certificateChainPem = options.certificateChainPem ?? null;
202
+ const privateKeyPem = options.privateKeyPem ?? null;
203
+ const hostNameOverride = options.hostNameOverride ?? null;
204
+ const spkiSha256Pins =
205
+ options.spkiSha256Pins && options.spkiSha256Pins.length > 0
206
+ ? options.spkiSha256Pins
207
+ : null;
208
+
209
+ const hasCert = !!certificateChainPem;
210
+ const hasKey = !!privateKeyPem;
211
+ if (hasCert !== hasKey) {
212
+ throw new Error('mTLS requires both certificateChainPem and privateKeyPem');
216
213
  }
217
- getHost(): Promise<string> {
218
- return nativeGrpc().getHost();
214
+
215
+ return {
216
+ rootCertsPem,
217
+ certificateChainPem,
218
+ privateKeyPem,
219
+ hostNameOverride,
220
+ spkiSha256Pins,
221
+ };
222
+ }
223
+
224
+ /**
225
+ * Shared RPC surface bound to a native channel id.
226
+ * Used by the singleton {@link GrpcClient} and by {@link GrpcChannel}.
227
+ */
228
+ export class GrpcCallApi {
229
+ protected channelInterceptors: GrpcInterceptor[];
230
+ protected channelDeadlineSeconds = 120;
231
+ protected channelRetry: GrpcRetryPolicy | null = null;
232
+ protected channelHedging: GrpcHedgingPolicy | null = null;
233
+
234
+ constructor(
235
+ protected readonly channelId: string,
236
+ channelInterceptors: readonly GrpcInterceptor[] = [],
237
+ channelDeadlineSeconds = 120,
238
+ channelRetry: GrpcRetryPolicy | null = null,
239
+ channelHedging: GrpcHedgingPolicy | null = null
240
+ ) {
241
+ this.channelInterceptors = [...channelInterceptors];
242
+ this.channelDeadlineSeconds = channelDeadlineSeconds;
243
+ this.channelRetry = channelRetry;
244
+ this.channelHedging = channelHedging;
219
245
  }
220
- setHost(host: string): void {
221
- nativeGrpc().setHost(host);
246
+
247
+ protected resolveInterceptors(options?: GrpcCallOptions): GrpcInterceptor[] {
248
+ return combineInterceptors(this.channelInterceptors, options?.interceptors);
222
249
  }
223
- getInsecure(): Promise<boolean> {
224
- return nativeGrpc().getIsInsecure();
250
+
251
+ protected resolvePolicy(options?: GrpcCallOptions): EffectiveCallPolicy {
252
+ return resolveEffectivePolicy(
253
+ this.channelRetry,
254
+ this.channelHedging,
255
+ options?.retry,
256
+ options?.hedging
257
+ );
225
258
  }
226
- setInsecure(insecure: boolean): void {
227
- nativeGrpc().setInsecure(insecure);
259
+
260
+ protected resolveDeadlineBudgetSeconds(
261
+ options?: GrpcCallOptions
262
+ ): number | undefined {
263
+ if (options?.deadlineSeconds !== undefined) {
264
+ return options.deadlineSeconds;
265
+ }
266
+ return this.channelDeadlineSeconds;
228
267
  }
229
- /**
230
- * Replace channel TLS options (custom CA, mTLS, hostname override).
231
- * Each call replaces the previous config; omitted fields are cleared.
232
- * Apply before `initGrpcChannel()`. Ignored while insecure/plaintext.
233
- */
234
- setTlsOptions(options: GrpcTlsOptions = {}): void {
235
- const rootCertsPem = options.rootCertsPem ?? null;
236
- const certificateChainPem = options.certificateChainPem ?? null;
237
- const privateKeyPem = options.privateKeyPem ?? null;
238
- const hostNameOverride = options.hostNameOverride ?? null;
239
- const spkiSha256Pins =
240
- options.spkiSha256Pins && options.spkiSha256Pins.length > 0
241
- ? options.spkiSha256Pins
242
- : null;
243
-
244
- const hasCert = !!certificateChainPem;
245
- const hasKey = !!privateKeyPem;
246
- if (hasCert !== hasKey) {
247
- throw new Error(
248
- 'mTLS requires both certificateChainPem and privateKeyPem'
249
- );
268
+
269
+ private async runUnaryAttempt(
270
+ method: string,
271
+ data: Uint8Array,
272
+ requestHeaders: GrpcMetadata,
273
+ options: GrpcCallOptions | undefined,
274
+ interceptors: GrpcInterceptor[],
275
+ parentSignal: AbortSignal,
276
+ attemptIds: Set<number>
277
+ ): Promise<{
278
+ headers: GrpcMetadata;
279
+ response: Uint8Array;
280
+ trailers: GrpcMetadata;
281
+ }> {
282
+ if (parentSignal.aborted) {
283
+ throw new GrpcError('aborted', GrpcStatusCode.CANCELLED);
250
284
  }
251
285
 
252
- nativeGrpc().setTlsOptions({
253
- rootCertsPem,
254
- certificateChainPem,
255
- privateKeyPem,
256
- hostNameOverride,
257
- spkiSha256Pins,
258
- });
259
- }
260
- setCompression(enable: boolean, compressorName: string): void {
261
- nativeGrpc().setCompression(enable, compressorName);
262
- }
263
- setResponseSizeLimit(limitInBytes: number): void {
264
- nativeGrpc().setResponseSizeLimit(limitInBytes);
265
- }
266
- /** Global per-call deadline in seconds (Android/iOS). Default 120. Overridable per RPC via options. */
267
- setCallDeadlineSeconds(seconds: number): void {
268
- nativeGrpc().setCallDeadlineSeconds(seconds);
269
- }
286
+ const id = getId();
287
+ attemptIds.add(id);
288
+ const attemptAbort = new AbortController();
289
+ const onParentAbort = () => attemptAbort.abort();
290
+ parentSignal.addEventListener('abort', onParentAbort);
270
291
 
271
- initGrpcChannel() {
272
- nativeGrpc().initGrpcChannel();
273
- }
292
+ const response = createDeferred<Uint8Array>(attemptAbort.signal);
293
+ const headers = createDeferred<GrpcMetadata>(attemptAbort.signal);
294
+ const trailers = createDeferred<GrpcMetadata>(attemptAbort.signal);
274
295
 
275
- setKeepAlive(
276
- enable: boolean,
277
- keepAliveTime: number,
278
- keepAliveTimeOut: number
279
- ): void {
280
- nativeGrpc().setKeepAlive(enable, keepAliveTime, keepAliveTimeOut);
281
- }
296
+ deferredMap[id] = {
297
+ response,
298
+ headers,
299
+ trailers,
300
+ method,
301
+ interceptors,
302
+ };
282
303
 
283
- resetConnection(message: string): void {
284
- if (!this.isAndroid()) return;
285
- nativeGrpc().resetConnection(message);
286
- }
287
- setUiLogEnabled(enable: boolean): void {
288
- if (!this.isAndroid()) return;
289
- nativeGrpc().setUiLogEnabled(enable);
290
- }
304
+ try {
305
+ let start = await runOnStart(interceptors, {
306
+ method,
307
+ headers: { ...requestHeaders },
308
+ options: { ...(options || {}) },
309
+ request: data,
310
+ });
311
+ const callOptions = { ...start.options };
312
+ delete callOptions.interceptors;
313
+ delete callOptions.retry;
314
+ delete callOptions.hedging;
315
+ start = {
316
+ ...start,
317
+ options: callOptions,
318
+ };
319
+ const requestBytes = await runOnSendMessage(
320
+ interceptors,
321
+ start.request ?? data,
322
+ start.method
323
+ );
324
+ const obj = buildRequestObject(requestBytes, start.options);
325
+ await nativeGrpc().unaryCall(
326
+ id,
327
+ start.method,
328
+ obj,
329
+ start.headers,
330
+ this.channelId
331
+ );
291
332
 
292
- onConnectionStateChange(): void {
293
- if (!this.isAndroid()) return;
294
- nativeGrpc().onConnectionStateChange();
333
+ const [hdrs, body, trl] = await Promise.all([
334
+ headers.promise,
335
+ response.promise,
336
+ trailers.promise,
337
+ ]);
338
+ return { headers: hdrs, response: body, trailers: trl };
339
+ } catch (reason) {
340
+ if (attemptAbort.signal.aborted || parentSignal.aborted) {
341
+ throw new GrpcError('aborted', GrpcStatusCode.CANCELLED);
342
+ }
343
+ throw toGrpcError(reason);
344
+ } finally {
345
+ parentSignal.removeEventListener('abort', onParentAbort);
346
+ attemptIds.delete(id);
347
+ if (attemptAbort.signal.aborted) {
348
+ nativeGrpc().cancelGrpcCall(id);
349
+ }
350
+ }
295
351
  }
296
352
 
297
- enterIdle(): void {
298
- if (!this.isAndroid()) return;
299
- nativeGrpc().enterIdle();
353
+ private async runUnaryWithPolicy(
354
+ method: string,
355
+ data: Uint8Array,
356
+ requestHeaders: GrpcMetadata,
357
+ options: GrpcCallOptions | undefined,
358
+ interceptors: GrpcInterceptor[],
359
+ parentSignal: AbortSignal,
360
+ policy: EffectiveCallPolicy,
361
+ deadlineBudgetSeconds: number | undefined
362
+ ): Promise<{
363
+ headers: GrpcMetadata;
364
+ response: Uint8Array;
365
+ trailers: GrpcMetadata;
366
+ }> {
367
+ const startedAt = Date.now();
368
+ const attemptIds = new Set<number>();
369
+
370
+ const withRemainingDeadline = (): GrpcCallOptions => {
371
+ const next: GrpcCallOptions = { ...(options || {}) };
372
+ delete next.interceptors;
373
+ delete next.retry;
374
+ delete next.hedging;
375
+ if (policy.kind === 'none') {
376
+ if (options?.deadlineSeconds === undefined) {
377
+ delete next.deadlineSeconds;
378
+ }
379
+ return next;
380
+ }
381
+ const remaining = remainingDeadlineSeconds(
382
+ deadlineBudgetSeconds,
383
+ startedAt
384
+ );
385
+ if (remaining !== undefined) {
386
+ next.deadlineSeconds = remaining;
387
+ }
388
+ return next;
389
+ };
390
+
391
+ const cancelAllAttempts = () => {
392
+ for (const id of [...attemptIds]) {
393
+ nativeGrpc().cancelGrpcCall(id);
394
+ }
395
+ };
396
+ const onAbort = () => cancelAllAttempts();
397
+ parentSignal.addEventListener('abort', onAbort);
398
+
399
+ try {
400
+ if (policy.kind === 'none') {
401
+ return await this.runUnaryAttempt(
402
+ method,
403
+ data,
404
+ requestHeaders,
405
+ withRemainingDeadline(),
406
+ interceptors,
407
+ parentSignal,
408
+ attemptIds
409
+ );
410
+ }
411
+
412
+ if (policy.kind === 'retry') {
413
+ let lastError: GrpcError | undefined;
414
+ for (let attempt = 1; attempt <= policy.policy.maxAttempts; attempt++) {
415
+ if (parentSignal.aborted) {
416
+ throw new GrpcError('aborted', GrpcStatusCode.CANCELLED);
417
+ }
418
+ const remaining = remainingDeadlineSeconds(
419
+ deadlineBudgetSeconds,
420
+ startedAt
421
+ );
422
+ if (
423
+ deadlineBudgetSeconds !== undefined &&
424
+ deadlineBudgetSeconds > 0 &&
425
+ remaining !== undefined &&
426
+ remaining <= 0
427
+ ) {
428
+ throw new GrpcError(
429
+ 'DEADLINE_EXCEEDED',
430
+ GrpcStatusCode.DEADLINE_EXCEEDED
431
+ );
432
+ }
433
+ try {
434
+ return await this.runUnaryAttempt(
435
+ method,
436
+ data,
437
+ requestHeaders,
438
+ withRemainingDeadline(),
439
+ interceptors,
440
+ parentSignal,
441
+ attemptIds
442
+ );
443
+ } catch (reason) {
444
+ const error = toGrpcError(reason);
445
+ lastError = error;
446
+ if (
447
+ error.code === GrpcStatusCode.CANCELLED ||
448
+ parentSignal.aborted
449
+ ) {
450
+ throw error;
451
+ }
452
+ const retryable =
453
+ error.code !== undefined &&
454
+ policy.policy.retryableStatusCodes.has(error.code);
455
+ if (!retryable || attempt >= policy.policy.maxAttempts) {
456
+ throw error;
457
+ }
458
+ const backoffMs = computeRetryBackoffMs(policy.policy, attempt);
459
+ await delay(backoffMs, parentSignal as any);
460
+ }
461
+ }
462
+ throw (
463
+ lastError ?? new GrpcError('UNAVAILABLE', GrpcStatusCode.UNAVAILABLE)
464
+ );
465
+ }
466
+
467
+ // hedging
468
+ type AttemptOutcome =
469
+ | {
470
+ ok: true;
471
+ value: {
472
+ headers: GrpcMetadata;
473
+ response: Uint8Array;
474
+ trailers: GrpcMetadata;
475
+ };
476
+ }
477
+ | { ok: false; error: GrpcError };
478
+
479
+ return await new Promise((resolve, reject) => {
480
+ let settled = false;
481
+ let started = 0;
482
+ let finished = 0;
483
+ const timers: ReturnType<typeof setTimeout>[] = [];
484
+ const inFlight = new Map<number, Promise<AttemptOutcome>>();
485
+
486
+ const finishSuccess = (value: {
487
+ headers: GrpcMetadata;
488
+ response: Uint8Array;
489
+ trailers: GrpcMetadata;
490
+ }) => {
491
+ if (settled) {
492
+ return;
493
+ }
494
+ settled = true;
495
+ timers.forEach(clearTimeout);
496
+ cancelAllAttempts();
497
+ resolve(value);
498
+ };
499
+
500
+ const finishError = (error: GrpcError) => {
501
+ if (settled) {
502
+ return;
503
+ }
504
+ settled = true;
505
+ timers.forEach(clearTimeout);
506
+ cancelAllAttempts();
507
+ reject(error);
508
+ };
509
+
510
+ const launch = () => {
511
+ if (settled || parentSignal.aborted) {
512
+ return;
513
+ }
514
+ const remaining = remainingDeadlineSeconds(
515
+ deadlineBudgetSeconds,
516
+ startedAt
517
+ );
518
+ if (
519
+ deadlineBudgetSeconds !== undefined &&
520
+ deadlineBudgetSeconds > 0 &&
521
+ remaining !== undefined &&
522
+ remaining <= 0
523
+ ) {
524
+ finishError(
525
+ new GrpcError(
526
+ 'DEADLINE_EXCEEDED',
527
+ GrpcStatusCode.DEADLINE_EXCEEDED
528
+ )
529
+ );
530
+ return;
531
+ }
532
+
533
+ started += 1;
534
+ const launchIndex = started;
535
+ const p = this.runUnaryAttempt(
536
+ method,
537
+ data,
538
+ requestHeaders,
539
+ withRemainingDeadline(),
540
+ interceptors,
541
+ parentSignal,
542
+ attemptIds
543
+ )
544
+ .then(
545
+ (value): AttemptOutcome => ({ ok: true, value }),
546
+ (reason): AttemptOutcome => ({
547
+ ok: false,
548
+ error: toGrpcError(reason),
549
+ })
550
+ )
551
+ .then((outcome) => {
552
+ inFlight.delete(launchIndex);
553
+ finished += 1;
554
+ if (settled) {
555
+ return outcome;
556
+ }
557
+ if (outcome.ok) {
558
+ finishSuccess(outcome.value);
559
+ return outcome;
560
+ }
561
+ const { error } = outcome;
562
+ if (
563
+ error.code === GrpcStatusCode.CANCELLED ||
564
+ parentSignal.aborted
565
+ ) {
566
+ if (finished >= started && inFlight.size === 0) {
567
+ finishError(error);
568
+ }
569
+ return outcome;
570
+ }
571
+ const nonFatal =
572
+ error.code !== undefined &&
573
+ policy.policy.nonFatalStatusCodes.has(error.code);
574
+ if (!nonFatal) {
575
+ finishError(error);
576
+ return outcome;
577
+ }
578
+ if (
579
+ finished >= policy.policy.maxAttempts ||
580
+ (started >= policy.policy.maxAttempts && inFlight.size === 0)
581
+ ) {
582
+ finishError(error);
583
+ }
584
+ return outcome;
585
+ });
586
+ inFlight.set(launchIndex, p);
587
+ };
588
+
589
+ launch();
590
+ for (let i = 2; i <= policy.policy.maxAttempts; i++) {
591
+ const delayMs = policy.policy.hedgingDelayMs * (i - 1);
592
+ if (delayMs <= 0) {
593
+ launch();
594
+ } else {
595
+ timers.push(setTimeout(launch, delayMs));
596
+ }
597
+ }
598
+
599
+ parentSignal.addEventListener('abort', () => {
600
+ finishError(new GrpcError('aborted', GrpcStatusCode.CANCELLED));
601
+ });
602
+ });
603
+ } finally {
604
+ parentSignal.removeEventListener('abort', onAbort);
605
+ }
300
606
  }
301
607
 
302
608
  unaryCall(
@@ -305,27 +611,15 @@ export class GrpcClient {
305
611
  requestHeaders?: GrpcMetadata,
306
612
  options?: GrpcCallOptions
307
613
  ): GrpcUnaryCall {
308
- const obj = buildRequestObject(data, options);
309
-
310
- const id = getId();
311
614
  const abort = new AbortController();
312
-
313
- abort.signal.addEventListener('abort', () => {
314
- nativeGrpc().cancelGrpcCall(id);
315
- });
615
+ const interceptors = this.resolveInterceptors(options);
616
+ const policy = this.resolvePolicy(options);
617
+ const deadlineBudgetSeconds = this.resolveDeadlineBudgetSeconds(options);
316
618
 
317
619
  const response = createDeferred<Uint8Array>(abort.signal);
318
620
  const headers = createDeferred<GrpcMetadata>(abort.signal);
319
621
  const trailers = createDeferred<GrpcMetadata>(abort.signal);
320
622
 
321
- deferredMap[id] = {
322
- response,
323
- headers,
324
- trailers,
325
- };
326
-
327
- nativeGrpc().unaryCall(id, method, obj, requestHeaders || {});
328
-
329
623
  const call = new GrpcUnaryCall(
330
624
  method,
331
625
  data,
@@ -341,18 +635,48 @@ export class GrpcClient {
341
635
  () => abort.abort()
342
636
  );
343
637
 
638
+ Promise.resolve()
639
+ .then(async () => {
640
+ const result = await this.runUnaryWithPolicy(
641
+ method,
642
+ data,
643
+ requestHeaders || {},
644
+ options,
645
+ interceptors,
646
+ abort.signal,
647
+ policy,
648
+ deadlineBudgetSeconds
649
+ );
650
+ headers.resolve(result.headers);
651
+ response.resolve(result.response);
652
+ trailers.resolve(result.trailers);
653
+ })
654
+ .catch((reason) => {
655
+ if (abort.signal.aborted) {
656
+ const error = new GrpcError('aborted', GrpcStatusCode.CANCELLED);
657
+ headers.reject(error);
658
+ response.reject(error);
659
+ trailers.reject(error);
660
+ return;
661
+ }
662
+ const error = runOnError(interceptors, toGrpcError(reason), method);
663
+ headers.reject(error);
664
+ response.reject(error);
665
+ trailers.reject(error);
666
+ });
667
+
344
668
  return call;
345
669
  }
670
+
346
671
  serverStreamCall(
347
672
  method: string,
348
673
  data: Uint8Array,
349
674
  requestHeaders?: GrpcMetadata,
350
675
  options?: GrpcCallOptions
351
676
  ): GrpcServerStreamingCall {
352
- const obj = buildRequestObject(data, options);
353
-
354
677
  const id = getId();
355
678
  const abort = new AbortController();
679
+ const interceptors = this.resolveInterceptors(options);
356
680
 
357
681
  abort.signal.addEventListener('abort', () => {
358
682
  nativeGrpc().cancelGrpcCall(id);
@@ -367,10 +691,10 @@ export class GrpcClient {
367
691
  headers,
368
692
  trailers,
369
693
  data: stream,
694
+ method,
695
+ interceptors,
370
696
  };
371
697
 
372
- nativeGrpc().serverStreamingCall(id, method, obj, requestHeaders || {});
373
-
374
698
  const call = new GrpcServerStreamingCall(
375
699
  method,
376
700
  data,
@@ -386,6 +710,44 @@ export class GrpcClient {
386
710
  () => abort.abort()
387
711
  );
388
712
 
713
+ Promise.resolve()
714
+ .then(async () => {
715
+ let start = await runOnStart(interceptors, {
716
+ method,
717
+ headers: { ...(requestHeaders || {}) },
718
+ options: { ...(options || {}) },
719
+ request: data,
720
+ });
721
+ const callOptions = { ...start.options };
722
+ delete callOptions.interceptors;
723
+ start = {
724
+ ...start,
725
+ options: callOptions,
726
+ };
727
+ const requestBytes = await runOnSendMessage(
728
+ interceptors,
729
+ start.request ?? data,
730
+ start.method
731
+ );
732
+ const obj = buildRequestObject(requestBytes, start.options);
733
+ await nativeGrpc().serverStreamingCall(
734
+ id,
735
+ start.method,
736
+ obj,
737
+ start.headers,
738
+ this.channelId
739
+ );
740
+ })
741
+ .catch((reason) => {
742
+ const deferred = deferredMap[id];
743
+ if (!deferred) {
744
+ return;
745
+ }
746
+ const error = runOnError(interceptors, toGrpcError(reason), method);
747
+ rejectDeferredCall(deferred, error);
748
+ delete deferredMap[id];
749
+ });
750
+
389
751
  return call;
390
752
  }
391
753
 
@@ -400,7 +762,11 @@ export class GrpcClient {
400
762
  ): GrpcClientStreamingCall {
401
763
  const id = getId();
402
764
  const abort = new AbortController();
403
- const headersMeta = requestHeaders || {};
765
+ const interceptors = this.resolveInterceptors(options);
766
+ let headersMeta = { ...(requestHeaders || {}) };
767
+ let callOptions: GrpcCallOptions = { ...(options || {}) };
768
+ const channelId = this.channelId;
769
+ let started = false;
404
770
 
405
771
  abort.signal.addEventListener('abort', () => {
406
772
  nativeGrpc().cancelGrpcCall(id);
@@ -414,17 +780,47 @@ export class GrpcClient {
414
780
  response,
415
781
  headers,
416
782
  trailers,
783
+ method,
784
+ interceptors,
417
785
  };
418
786
 
419
787
  const requests = new ServerInputStream(
420
- (data, isFirst) => {
421
- const obj = buildRequestObject(data, isFirst ? options : undefined);
422
- return nativeGrpc().clientStreamingCall(
423
- id,
424
- method,
425
- obj,
426
- isFirst ? headersMeta : {}
427
- );
788
+ async (data, isFirst) => {
789
+ try {
790
+ let message = await runOnSendMessage(interceptors, data, method);
791
+ if (isFirst || !started) {
792
+ const start = await runOnStart(interceptors, {
793
+ method,
794
+ headers: headersMeta,
795
+ options: callOptions,
796
+ request: message,
797
+ });
798
+ headersMeta = start.headers;
799
+ callOptions = { ...start.options };
800
+ delete callOptions.interceptors;
801
+ message = start.request ?? message;
802
+ started = true;
803
+ }
804
+ const obj = buildRequestObject(
805
+ message,
806
+ isFirst ? callOptions : undefined
807
+ );
808
+ return nativeGrpc().clientStreamingCall(
809
+ id,
810
+ method,
811
+ obj,
812
+ isFirst ? headersMeta : {},
813
+ channelId
814
+ );
815
+ } catch (reason) {
816
+ const deferred = deferredMap[id];
817
+ if (deferred) {
818
+ const error = runOnError(interceptors, toGrpcError(reason), method);
819
+ rejectDeferredCall(deferred, error);
820
+ delete deferredMap[id];
821
+ }
822
+ throw toGrpcError(reason);
823
+ }
428
824
  },
429
825
  () => nativeGrpc().finishClientStreaming(id)
430
826
  );
@@ -459,7 +855,11 @@ export class GrpcClient {
459
855
  ): GrpcBidiStreamingCall {
460
856
  const id = getId();
461
857
  const abort = new AbortController();
462
- const headersMeta = requestHeaders || {};
858
+ const interceptors = this.resolveInterceptors(options);
859
+ let headersMeta = { ...(requestHeaders || {}) };
860
+ let callOptions: GrpcCallOptions = { ...(options || {}) };
861
+ const channelId = this.channelId;
862
+ let started = false;
463
863
 
464
864
  abort.signal.addEventListener('abort', () => {
465
865
  nativeGrpc().cancelGrpcCall(id);
@@ -473,17 +873,47 @@ export class GrpcClient {
473
873
  headers,
474
874
  trailers,
475
875
  data: stream,
876
+ method,
877
+ interceptors,
476
878
  };
477
879
 
478
880
  const requests = new ServerInputStream(
479
- (data, isFirst) => {
480
- const obj = buildRequestObject(data, isFirst ? options : undefined);
481
- return nativeGrpc().bidiStreamingCall(
482
- id,
483
- method,
484
- obj,
485
- isFirst ? headersMeta : {}
486
- );
881
+ async (data, isFirst) => {
882
+ try {
883
+ let message = await runOnSendMessage(interceptors, data, method);
884
+ if (isFirst || !started) {
885
+ const start = await runOnStart(interceptors, {
886
+ method,
887
+ headers: headersMeta,
888
+ options: callOptions,
889
+ request: message,
890
+ });
891
+ headersMeta = start.headers;
892
+ callOptions = { ...start.options };
893
+ delete callOptions.interceptors;
894
+ message = start.request ?? message;
895
+ started = true;
896
+ }
897
+ const obj = buildRequestObject(
898
+ message,
899
+ isFirst ? callOptions : undefined
900
+ );
901
+ return nativeGrpc().bidiStreamingCall(
902
+ id,
903
+ method,
904
+ obj,
905
+ isFirst ? headersMeta : {},
906
+ channelId
907
+ );
908
+ } catch (reason) {
909
+ const deferred = deferredMap[id];
910
+ if (deferred) {
911
+ const error = runOnError(interceptors, toGrpcError(reason), method);
912
+ rejectDeferredCall(deferred, error);
913
+ delete deferredMap[id];
914
+ }
915
+ throw toGrpcError(reason);
916
+ }
487
917
  },
488
918
  () => nativeGrpc().finishClientStreaming(id)
489
919
  );
@@ -505,17 +935,112 @@ export class GrpcClient {
505
935
 
506
936
  return call;
507
937
  }
938
+ }
939
+
940
+ export class GrpcClient extends GrpcCallApi {
941
+ constructor() {
942
+ super(DEFAULT_CHANNEL_ID, [], 120, null, null);
943
+ Emitter.addListener('grpc-call', handleGrpcEvent);
944
+ }
945
+ destroy() {
946
+ Emitter.removeAllListeners('grpc-call');
947
+ }
948
+ /**
949
+ * Replace default-channel interceptors (same replace semantics as `setTlsOptions`).
950
+ * Prefer `createChannel({ interceptors })` for multi-host apps.
951
+ */
952
+ setInterceptors(interceptors: GrpcInterceptor[] = []): void {
953
+ this.channelInterceptors = [...interceptors];
954
+ }
955
+ /**
956
+ * Replace unary retry policy on the default channel.
957
+ * Clears any hedging policy (mutually exclusive). Pass `null` to disable.
958
+ */
959
+ setRetryPolicy(policy: GrpcRetryPolicy | null): void {
960
+ if (policy) {
961
+ normalizeRetryPolicy(policy);
962
+ }
963
+ this.channelRetry = policy;
964
+ this.channelHedging = null;
965
+ }
966
+ /**
967
+ * Replace unary hedging policy on the default channel.
968
+ * Clears any retry policy (mutually exclusive). Pass `null` to disable.
969
+ */
970
+ setHedgingPolicy(policy: GrpcHedgingPolicy | null): void {
971
+ if (policy) {
972
+ normalizeHedgingPolicy(policy);
973
+ }
974
+ this.channelHedging = policy;
975
+ this.channelRetry = null;
976
+ }
977
+ getHost(): Promise<string> {
978
+ return nativeGrpc().getHost();
979
+ }
980
+ setHost(host: string): void {
981
+ nativeGrpc().setHost(host);
982
+ }
983
+ getInsecure(): Promise<boolean> {
984
+ return nativeGrpc().getIsInsecure();
985
+ }
986
+ setInsecure(insecure: boolean): void {
987
+ nativeGrpc().setInsecure(insecure);
988
+ }
989
+ /**
990
+ * Replace channel TLS options (custom CA, mTLS, hostname override).
991
+ * Each call replaces the previous config; omitted fields are cleared.
992
+ * Apply before `initGrpcChannel()`. Ignored while insecure/plaintext.
993
+ * For multi-host apps prefer {@link createChannel} with `tls` in config.
994
+ */
995
+ setTlsOptions(options: GrpcTlsOptions = {}): void {
996
+ nativeGrpc().setTlsOptions(normalizeTlsOptions(options));
997
+ }
998
+ setCompression(enable: boolean, compressorName: string): void {
999
+ nativeGrpc().setCompression(enable, compressorName);
1000
+ }
1001
+ setResponseSizeLimit(limitInBytes: number): void {
1002
+ nativeGrpc().setResponseSizeLimit(limitInBytes);
1003
+ }
1004
+ /** Global per-call deadline in seconds (Android/iOS). Default 120. Overridable per RPC via options. */
1005
+ setCallDeadlineSeconds(seconds: number): void {
1006
+ this.channelDeadlineSeconds = Math.max(0, seconds);
1007
+ nativeGrpc().setCallDeadlineSeconds(seconds);
1008
+ }
1009
+
1010
+ initGrpcChannel() {
1011
+ nativeGrpc().initGrpcChannel();
1012
+ }
1013
+
1014
+ setKeepAlive(
1015
+ enable: boolean,
1016
+ keepAliveTime: number,
1017
+ keepAliveTimeOut: number
1018
+ ): void {
1019
+ nativeGrpc().setKeepAlive(enable, keepAliveTime, keepAliveTimeOut);
1020
+ }
1021
+
1022
+ resetConnection(message: string): void {
1023
+ if (!this.isAndroid()) return;
1024
+ nativeGrpc().resetConnection(message);
1025
+ }
1026
+ setUiLogEnabled(enable: boolean): void {
1027
+ if (!this.isAndroid()) return;
1028
+ nativeGrpc().setUiLogEnabled(enable);
1029
+ }
1030
+
1031
+ onConnectionStateChange(): void {
1032
+ if (!this.isAndroid()) return;
1033
+ nativeGrpc().onConnectionStateChange();
1034
+ }
1035
+
1036
+ enterIdle(): void {
1037
+ if (!this.isAndroid()) return;
1038
+ nativeGrpc().enterIdle();
1039
+ }
508
1040
 
509
1041
  private isAndroid(): Boolean {
510
1042
  return Platform.OS === 'android';
511
1043
  }
512
1044
  }
513
1045
 
514
- /** Lazy binding to NativeModules.Grpc (works with Jest mocks / late link). */
515
- export const Grpc: GrpcType = new Proxy({} as GrpcType, {
516
- get(_target, prop) {
517
- const native = nativeGrpc();
518
- const value = (native as any)[prop as string];
519
- return typeof value === 'function' ? value.bind(native) : value;
520
- },
521
- });
1046
+ export { Grpc } from './native';