@xdcobra/react-native-grpc 1.0.0 → 1.1.8

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 (96) hide show
  1. package/LICENSE.md +22 -22
  2. package/README.md +284 -114
  3. package/android/build.gradle +127 -127
  4. package/android/gradle.properties +4 -4
  5. package/android/src/main/AndroidManifest.xml +3 -3
  6. package/android/src/main/java/com/reactnativegrpc/GrpcMarshaller.java +27 -27
  7. package/android/src/main/java/com/reactnativegrpc/GrpcModule.java +730 -585
  8. package/android/src/main/java/com/reactnativegrpc/GrpcPackage.java +27 -27
  9. package/android/src/main/java/com/reactnativegrpc/SpkiPinTrustManager.java +101 -101
  10. package/android/src/main/java/com/reactnativegrpc/TrustManagers.java +51 -51
  11. package/ios/Grpc.h +22 -22
  12. package/ios/Grpc.m +625 -439
  13. package/ios/SpkiPinning.h +22 -22
  14. package/ios/SpkiPinning.m +114 -114
  15. package/lib/commonjs/bidi-streaming.js.map +1 -1
  16. package/lib/commonjs/channel.js +84 -0
  17. package/lib/commonjs/channel.js.map +1 -0
  18. package/lib/commonjs/client-streaming.js +3 -3
  19. package/lib/commonjs/client-streaming.js.map +1 -1
  20. package/lib/commonjs/client.js +538 -135
  21. package/lib/commonjs/client.js.map +1 -1
  22. package/lib/commonjs/create-client.js +206 -0
  23. package/lib/commonjs/create-client.js.map +1 -0
  24. package/lib/commonjs/errors.js.map +1 -1
  25. package/lib/commonjs/index.js +32 -1
  26. package/lib/commonjs/index.js.map +1 -1
  27. package/lib/commonjs/interceptors.js +116 -0
  28. package/lib/commonjs/interceptors.js.map +1 -0
  29. package/lib/commonjs/native.js +24 -0
  30. package/lib/commonjs/native.js.map +1 -0
  31. package/lib/commonjs/retry.js +153 -0
  32. package/lib/commonjs/retry.js.map +1 -0
  33. package/lib/commonjs/server-streaming.js.map +1 -1
  34. package/lib/commonjs/status.js +54 -0
  35. package/lib/commonjs/status.js.map +1 -0
  36. package/lib/commonjs/types.js +29 -0
  37. package/lib/commonjs/types.js.map +1 -1
  38. package/lib/commonjs/unary.js.map +1 -1
  39. package/lib/module/bidi-streaming.js.map +1 -1
  40. package/lib/module/channel.js +76 -0
  41. package/lib/module/channel.js.map +1 -0
  42. package/lib/module/client-streaming.js +3 -3
  43. package/lib/module/client-streaming.js.map +1 -1
  44. package/lib/module/client.js +525 -129
  45. package/lib/module/client.js.map +1 -1
  46. package/lib/module/create-client.js +201 -0
  47. package/lib/module/create-client.js.map +1 -0
  48. package/lib/module/errors.js.map +1 -1
  49. package/lib/module/index.js +3 -0
  50. package/lib/module/index.js.map +1 -1
  51. package/lib/module/interceptors.js +104 -0
  52. package/lib/module/interceptors.js.map +1 -0
  53. package/lib/module/native.js +17 -0
  54. package/lib/module/native.js.map +1 -0
  55. package/lib/module/retry.js +141 -0
  56. package/lib/module/retry.js.map +1 -0
  57. package/lib/module/server-streaming.js.map +1 -1
  58. package/lib/module/status.js +46 -0
  59. package/lib/module/status.js.map +1 -0
  60. package/lib/module/types.js +17 -0
  61. package/lib/module/types.js.map +1 -1
  62. package/lib/module/unary.js.map +1 -1
  63. package/lib/typescript/channel.d.ts +27 -0
  64. package/lib/typescript/channel.d.ts.map +1 -0
  65. package/lib/typescript/client.d.ts +56 -49
  66. package/lib/typescript/client.d.ts.map +1 -1
  67. package/lib/typescript/create-client.d.ts +65 -0
  68. package/lib/typescript/create-client.d.ts.map +1 -0
  69. package/lib/typescript/index.d.ts +5 -0
  70. package/lib/typescript/index.d.ts.map +1 -1
  71. package/lib/typescript/interceptors.d.ts +43 -0
  72. package/lib/typescript/interceptors.d.ts.map +1 -0
  73. package/lib/typescript/native.d.ts +53 -0
  74. package/lib/typescript/native.d.ts.map +1 -0
  75. package/lib/typescript/retry.d.ts +56 -0
  76. package/lib/typescript/retry.d.ts.map +1 -0
  77. package/lib/typescript/status.d.ts +24 -0
  78. package/lib/typescript/status.d.ts.map +1 -0
  79. package/lib/typescript/types.d.ts +60 -0
  80. package/lib/typescript/types.d.ts.map +1 -1
  81. package/package.json +209 -169
  82. package/react-native-grpc.podspec +29 -29
  83. package/src/bidi-streaming.ts +78 -78
  84. package/src/channel.ts +110 -0
  85. package/src/client-streaming.ts +106 -106
  86. package/src/client.ts +1046 -521
  87. package/src/create-client.ts +391 -0
  88. package/src/errors.ts +11 -11
  89. package/src/index.ts +28 -11
  90. package/src/interceptors.ts +167 -0
  91. package/src/native.ts +99 -0
  92. package/src/retry.ts +208 -0
  93. package/src/server-streaming.ts +105 -105
  94. package/src/status.ts +50 -0
  95. package/src/types.ts +171 -107
  96. package/src/unary.ts +71 -71
@@ -4,18 +4,16 @@ 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 { combineInterceptors, runOnError, runOnHeaders, runOnMessage, runOnSendMessage, runOnStart, runOnTrailers, toGrpcError } from './interceptors';
8
+ import { nativeGrpc } from './native';
7
9
  import { GrpcServerStreamingCall, ServerOutputStream } from './server-streaming';
10
+ import { computeRetryBackoffMs, delay, normalizeHedgingPolicy, normalizeRetryPolicy, remainingDeadlineSeconds, resolveEffectivePolicy } from './retry';
11
+ import { GrpcStatusCode } from './status';
12
+ import { DEFAULT_CHANNEL_ID } from './types';
8
13
  import { GrpcUnaryCall } from './unary';
9
14
 
10
15
  /* prettier-ignore */
11
16
 
12
- function nativeGrpc() {
13
- const grpc = NativeModules.Grpc;
14
- if (!grpc) {
15
- throw new Error('NativeModules.Grpc is not linked');
16
- }
17
- return grpc;
18
- }
19
17
  const Emitter = new NativeEventEmitter(NativeModules.Grpc);
20
18
  function createDeferred(signal) {
21
19
  let completed = false;
@@ -39,32 +37,45 @@ function createDeferred(signal) {
39
37
  }
40
38
  let idCtr = 1;
41
39
  const deferredMap = {};
40
+ function rejectDeferredCall(deferred, error) {
41
+ var _deferred$headers, _deferred$trailers, _deferred$response, _deferred$data;
42
+ (_deferred$headers = deferred.headers) === null || _deferred$headers === void 0 || _deferred$headers.reject(error);
43
+ (_deferred$trailers = deferred.trailers) === null || _deferred$trailers === void 0 || _deferred$trailers.reject(error);
44
+ (_deferred$response = deferred.response) === null || _deferred$response === void 0 || _deferred$response.reject(error);
45
+ (_deferred$data = deferred.data) === null || _deferred$data === void 0 || _deferred$data.noitfyError(error);
46
+ }
42
47
  function handleGrpcEvent(event) {
43
- var _deferred$headers, _deferred$data, _deferred$response, _deferred$trailers, _deferred$data2, _deferred$headers2, _deferred$trailers2, _deferred$response2, _deferred$data3;
48
+ var _deferred$headers2, _deferred$trailers2, _deferred$data3;
44
49
  const deferred = deferredMap[event.id];
45
50
  if (deferred) {
51
+ const {
52
+ method,
53
+ interceptors
54
+ } = deferred;
46
55
  switch (event.type) {
47
56
  case 'headers':
48
- (_deferred$headers = deferred.headers) === null || _deferred$headers === void 0 || _deferred$headers.resolve(event.payload);
57
+ (_deferred$headers2 = deferred.headers) === null || _deferred$headers2 === void 0 || _deferred$headers2.resolve(runOnHeaders(interceptors, event.payload, method));
49
58
  break;
50
59
  case 'response':
51
- const data = toByteArray(event.payload);
52
- (_deferred$data = deferred.data) === null || _deferred$data === void 0 || _deferred$data.notifyData(data);
53
- (_deferred$response = deferred.response) === null || _deferred$response === void 0 || _deferred$response.resolve(data);
54
- break;
60
+ {
61
+ var _deferred$data2, _deferred$response2;
62
+ const data = runOnMessage(interceptors, toByteArray(event.payload), method);
63
+ (_deferred$data2 = deferred.data) === null || _deferred$data2 === void 0 || _deferred$data2.notifyData(data);
64
+ (_deferred$response2 = deferred.response) === null || _deferred$response2 === void 0 || _deferred$response2.resolve(data);
65
+ break;
66
+ }
55
67
  case 'trailers':
56
- (_deferred$trailers = deferred.trailers) === null || _deferred$trailers === void 0 || _deferred$trailers.resolve(event.payload);
57
- (_deferred$data2 = deferred.data) === null || _deferred$data2 === void 0 || _deferred$data2.notifyComplete();
68
+ (_deferred$trailers2 = deferred.trailers) === null || _deferred$trailers2 === void 0 || _deferred$trailers2.resolve(runOnTrailers(interceptors, event.payload, method));
69
+ (_deferred$data3 = deferred.data) === null || _deferred$data3 === void 0 || _deferred$data3.notifyComplete();
58
70
  delete deferredMap[event.id];
59
71
  break;
60
72
  case 'error':
61
- const error = new GrpcError(event.error, event.code, event.trailers);
62
- (_deferred$headers2 = deferred.headers) === null || _deferred$headers2 === void 0 || _deferred$headers2.reject(error);
63
- (_deferred$trailers2 = deferred.trailers) === null || _deferred$trailers2 === void 0 || _deferred$trailers2.reject(error);
64
- (_deferred$response2 = deferred.response) === null || _deferred$response2 === void 0 || _deferred$response2.reject(error);
65
- (_deferred$data3 = deferred.data) === null || _deferred$data3 === void 0 || _deferred$data3.noitfyError(error);
66
- delete deferredMap[event.id];
67
- break;
73
+ {
74
+ const error = runOnError(interceptors, new GrpcError(event.error, event.code, event.trailers), method);
75
+ rejectDeferredCall(deferred, error);
76
+ delete deferredMap[event.id];
77
+ break;
78
+ }
68
79
  }
69
80
  }
70
81
  }
@@ -80,105 +91,302 @@ function buildRequestObject(data, options) {
80
91
  }
81
92
  return obj;
82
93
  }
83
- export class GrpcClient {
84
- constructor() {
85
- Emitter.addListener('grpc-call', handleGrpcEvent);
94
+ export function normalizeTlsOptions(options = {}) {
95
+ const rootCertsPem = options.rootCertsPem ?? null;
96
+ const certificateChainPem = options.certificateChainPem ?? null;
97
+ const privateKeyPem = options.privateKeyPem ?? null;
98
+ const hostNameOverride = options.hostNameOverride ?? null;
99
+ const spkiSha256Pins = options.spkiSha256Pins && options.spkiSha256Pins.length > 0 ? options.spkiSha256Pins : null;
100
+ const hasCert = !!certificateChainPem;
101
+ const hasKey = !!privateKeyPem;
102
+ if (hasCert !== hasKey) {
103
+ throw new Error('mTLS requires both certificateChainPem and privateKeyPem');
86
104
  }
87
- destroy() {
88
- Emitter.removeAllListeners('grpc-call');
105
+ return {
106
+ rootCertsPem,
107
+ certificateChainPem,
108
+ privateKeyPem,
109
+ hostNameOverride,
110
+ spkiSha256Pins
111
+ };
112
+ }
113
+
114
+ /**
115
+ * Shared RPC surface bound to a native channel id.
116
+ * Used by the singleton {@link GrpcClient} and by {@link GrpcChannel}.
117
+ */
118
+ export class GrpcCallApi {
119
+ channelDeadlineSeconds = 120;
120
+ channelRetry = null;
121
+ channelHedging = null;
122
+ constructor(channelId, channelInterceptors = [], channelDeadlineSeconds = 120, channelRetry = null, channelHedging = null) {
123
+ this.channelId = channelId;
124
+ this.channelInterceptors = [...channelInterceptors];
125
+ this.channelDeadlineSeconds = channelDeadlineSeconds;
126
+ this.channelRetry = channelRetry;
127
+ this.channelHedging = channelHedging;
89
128
  }
90
- getHost() {
91
- return nativeGrpc().getHost();
129
+ resolveInterceptors(options) {
130
+ return combineInterceptors(this.channelInterceptors, options === null || options === void 0 ? void 0 : options.interceptors);
92
131
  }
93
- setHost(host) {
94
- nativeGrpc().setHost(host);
132
+ resolvePolicy(options) {
133
+ return resolveEffectivePolicy(this.channelRetry, this.channelHedging, options === null || options === void 0 ? void 0 : options.retry, options === null || options === void 0 ? void 0 : options.hedging);
95
134
  }
96
- getInsecure() {
97
- return nativeGrpc().getIsInsecure();
98
- }
99
- setInsecure(insecure) {
100
- nativeGrpc().setInsecure(insecure);
101
- }
102
- /**
103
- * Replace channel TLS options (custom CA, mTLS, hostname override).
104
- * Each call replaces the previous config; omitted fields are cleared.
105
- * Apply before `initGrpcChannel()`. Ignored while insecure/plaintext.
106
- */
107
- setTlsOptions(options = {}) {
108
- const rootCertsPem = options.rootCertsPem ?? null;
109
- const certificateChainPem = options.certificateChainPem ?? null;
110
- const privateKeyPem = options.privateKeyPem ?? null;
111
- const hostNameOverride = options.hostNameOverride ?? null;
112
- const spkiSha256Pins = options.spkiSha256Pins && options.spkiSha256Pins.length > 0 ? options.spkiSha256Pins : null;
113
- const hasCert = !!certificateChainPem;
114
- const hasKey = !!privateKeyPem;
115
- if (hasCert !== hasKey) {
116
- throw new Error('mTLS requires both certificateChainPem and privateKeyPem');
135
+ resolveDeadlineBudgetSeconds(options) {
136
+ if ((options === null || options === void 0 ? void 0 : options.deadlineSeconds) !== undefined) {
137
+ return options.deadlineSeconds;
117
138
  }
118
- nativeGrpc().setTlsOptions({
119
- rootCertsPem,
120
- certificateChainPem,
121
- privateKeyPem,
122
- hostNameOverride,
123
- spkiSha256Pins
124
- });
125
- }
126
- setCompression(enable, compressorName) {
127
- nativeGrpc().setCompression(enable, compressorName);
128
- }
129
- setResponseSizeLimit(limitInBytes) {
130
- nativeGrpc().setResponseSizeLimit(limitInBytes);
131
- }
132
- /** Global per-call deadline in seconds (Android/iOS). Default 120. Overridable per RPC via options. */
133
- setCallDeadlineSeconds(seconds) {
134
- nativeGrpc().setCallDeadlineSeconds(seconds);
135
- }
136
- initGrpcChannel() {
137
- nativeGrpc().initGrpcChannel();
138
- }
139
- setKeepAlive(enable, keepAliveTime, keepAliveTimeOut) {
140
- nativeGrpc().setKeepAlive(enable, keepAliveTime, keepAliveTimeOut);
139
+ return this.channelDeadlineSeconds;
141
140
  }
142
- resetConnection(message) {
143
- if (!this.isAndroid()) return;
144
- nativeGrpc().resetConnection(message);
145
- }
146
- setUiLogEnabled(enable) {
147
- if (!this.isAndroid()) return;
148
- nativeGrpc().setUiLogEnabled(enable);
149
- }
150
- onConnectionStateChange() {
151
- if (!this.isAndroid()) return;
152
- nativeGrpc().onConnectionStateChange();
141
+ async runUnaryAttempt(method, data, requestHeaders, options, interceptors, parentSignal, attemptIds) {
142
+ if (parentSignal.aborted) {
143
+ throw new GrpcError('aborted', GrpcStatusCode.CANCELLED);
144
+ }
145
+ const id = getId();
146
+ attemptIds.add(id);
147
+ const attemptAbort = new AbortController();
148
+ const onParentAbort = () => attemptAbort.abort();
149
+ parentSignal.addEventListener('abort', onParentAbort);
150
+ const response = createDeferred(attemptAbort.signal);
151
+ const headers = createDeferred(attemptAbort.signal);
152
+ const trailers = createDeferred(attemptAbort.signal);
153
+ deferredMap[id] = {
154
+ response,
155
+ headers,
156
+ trailers,
157
+ method,
158
+ interceptors
159
+ };
160
+ try {
161
+ let start = await runOnStart(interceptors, {
162
+ method,
163
+ headers: {
164
+ ...requestHeaders
165
+ },
166
+ options: {
167
+ ...(options || {})
168
+ },
169
+ request: data
170
+ });
171
+ const callOptions = {
172
+ ...start.options
173
+ };
174
+ delete callOptions.interceptors;
175
+ delete callOptions.retry;
176
+ delete callOptions.hedging;
177
+ start = {
178
+ ...start,
179
+ options: callOptions
180
+ };
181
+ const requestBytes = await runOnSendMessage(interceptors, start.request ?? data, start.method);
182
+ const obj = buildRequestObject(requestBytes, start.options);
183
+ await nativeGrpc().unaryCall(id, start.method, obj, start.headers, this.channelId);
184
+ const [hdrs, body, trl] = await Promise.all([headers.promise, response.promise, trailers.promise]);
185
+ return {
186
+ headers: hdrs,
187
+ response: body,
188
+ trailers: trl
189
+ };
190
+ } catch (reason) {
191
+ if (attemptAbort.signal.aborted || parentSignal.aborted) {
192
+ throw new GrpcError('aborted', GrpcStatusCode.CANCELLED);
193
+ }
194
+ throw toGrpcError(reason);
195
+ } finally {
196
+ parentSignal.removeEventListener('abort', onParentAbort);
197
+ attemptIds.delete(id);
198
+ if (attemptAbort.signal.aborted) {
199
+ nativeGrpc().cancelGrpcCall(id);
200
+ }
201
+ }
153
202
  }
154
- enterIdle() {
155
- if (!this.isAndroid()) return;
156
- nativeGrpc().enterIdle();
203
+ async runUnaryWithPolicy(method, data, requestHeaders, options, interceptors, parentSignal, policy, deadlineBudgetSeconds) {
204
+ const startedAt = Date.now();
205
+ const attemptIds = new Set();
206
+ const withRemainingDeadline = () => {
207
+ const next = {
208
+ ...(options || {})
209
+ };
210
+ delete next.interceptors;
211
+ delete next.retry;
212
+ delete next.hedging;
213
+ if (policy.kind === 'none') {
214
+ if ((options === null || options === void 0 ? void 0 : options.deadlineSeconds) === undefined) {
215
+ delete next.deadlineSeconds;
216
+ }
217
+ return next;
218
+ }
219
+ const remaining = remainingDeadlineSeconds(deadlineBudgetSeconds, startedAt);
220
+ if (remaining !== undefined) {
221
+ next.deadlineSeconds = remaining;
222
+ }
223
+ return next;
224
+ };
225
+ const cancelAllAttempts = () => {
226
+ for (const id of [...attemptIds]) {
227
+ nativeGrpc().cancelGrpcCall(id);
228
+ }
229
+ };
230
+ const onAbort = () => cancelAllAttempts();
231
+ parentSignal.addEventListener('abort', onAbort);
232
+ try {
233
+ if (policy.kind === 'none') {
234
+ return await this.runUnaryAttempt(method, data, requestHeaders, withRemainingDeadline(), interceptors, parentSignal, attemptIds);
235
+ }
236
+ if (policy.kind === 'retry') {
237
+ let lastError;
238
+ for (let attempt = 1; attempt <= policy.policy.maxAttempts; attempt++) {
239
+ if (parentSignal.aborted) {
240
+ throw new GrpcError('aborted', GrpcStatusCode.CANCELLED);
241
+ }
242
+ const remaining = remainingDeadlineSeconds(deadlineBudgetSeconds, startedAt);
243
+ if (deadlineBudgetSeconds !== undefined && deadlineBudgetSeconds > 0 && remaining !== undefined && remaining <= 0) {
244
+ throw new GrpcError('DEADLINE_EXCEEDED', GrpcStatusCode.DEADLINE_EXCEEDED);
245
+ }
246
+ try {
247
+ return await this.runUnaryAttempt(method, data, requestHeaders, withRemainingDeadline(), interceptors, parentSignal, attemptIds);
248
+ } catch (reason) {
249
+ const error = toGrpcError(reason);
250
+ lastError = error;
251
+ if (error.code === GrpcStatusCode.CANCELLED || parentSignal.aborted) {
252
+ throw error;
253
+ }
254
+ const retryable = error.code !== undefined && policy.policy.retryableStatusCodes.has(error.code);
255
+ if (!retryable || attempt >= policy.policy.maxAttempts) {
256
+ throw error;
257
+ }
258
+ const backoffMs = computeRetryBackoffMs(policy.policy, attempt);
259
+ await delay(backoffMs, parentSignal);
260
+ }
261
+ }
262
+ throw lastError ?? new GrpcError('UNAVAILABLE', GrpcStatusCode.UNAVAILABLE);
263
+ }
264
+
265
+ // hedging
266
+
267
+ return await new Promise((resolve, reject) => {
268
+ let settled = false;
269
+ let started = 0;
270
+ let finished = 0;
271
+ const timers = [];
272
+ const inFlight = new Map();
273
+ const finishSuccess = value => {
274
+ if (settled) {
275
+ return;
276
+ }
277
+ settled = true;
278
+ timers.forEach(clearTimeout);
279
+ cancelAllAttempts();
280
+ resolve(value);
281
+ };
282
+ const finishError = error => {
283
+ if (settled) {
284
+ return;
285
+ }
286
+ settled = true;
287
+ timers.forEach(clearTimeout);
288
+ cancelAllAttempts();
289
+ reject(error);
290
+ };
291
+ const launch = () => {
292
+ if (settled || parentSignal.aborted) {
293
+ return;
294
+ }
295
+ const remaining = remainingDeadlineSeconds(deadlineBudgetSeconds, startedAt);
296
+ if (deadlineBudgetSeconds !== undefined && deadlineBudgetSeconds > 0 && remaining !== undefined && remaining <= 0) {
297
+ finishError(new GrpcError('DEADLINE_EXCEEDED', GrpcStatusCode.DEADLINE_EXCEEDED));
298
+ return;
299
+ }
300
+ started += 1;
301
+ const launchIndex = started;
302
+ const p = this.runUnaryAttempt(method, data, requestHeaders, withRemainingDeadline(), interceptors, parentSignal, attemptIds).then(value => ({
303
+ ok: true,
304
+ value
305
+ }), reason => ({
306
+ ok: false,
307
+ error: toGrpcError(reason)
308
+ })).then(outcome => {
309
+ inFlight.delete(launchIndex);
310
+ finished += 1;
311
+ if (settled) {
312
+ return outcome;
313
+ }
314
+ if (outcome.ok) {
315
+ finishSuccess(outcome.value);
316
+ return outcome;
317
+ }
318
+ const {
319
+ error
320
+ } = outcome;
321
+ if (error.code === GrpcStatusCode.CANCELLED || parentSignal.aborted) {
322
+ if (finished >= started && inFlight.size === 0) {
323
+ finishError(error);
324
+ }
325
+ return outcome;
326
+ }
327
+ const nonFatal = error.code !== undefined && policy.policy.nonFatalStatusCodes.has(error.code);
328
+ if (!nonFatal) {
329
+ finishError(error);
330
+ return outcome;
331
+ }
332
+ if (finished >= policy.policy.maxAttempts || started >= policy.policy.maxAttempts && inFlight.size === 0) {
333
+ finishError(error);
334
+ }
335
+ return outcome;
336
+ });
337
+ inFlight.set(launchIndex, p);
338
+ };
339
+ launch();
340
+ for (let i = 2; i <= policy.policy.maxAttempts; i++) {
341
+ const delayMs = policy.policy.hedgingDelayMs * (i - 1);
342
+ if (delayMs <= 0) {
343
+ launch();
344
+ } else {
345
+ timers.push(setTimeout(launch, delayMs));
346
+ }
347
+ }
348
+ parentSignal.addEventListener('abort', () => {
349
+ finishError(new GrpcError('aborted', GrpcStatusCode.CANCELLED));
350
+ });
351
+ });
352
+ } finally {
353
+ parentSignal.removeEventListener('abort', onAbort);
354
+ }
157
355
  }
158
356
  unaryCall(method, data, requestHeaders, options) {
159
- const obj = buildRequestObject(data, options);
160
- const id = getId();
161
357
  const abort = new AbortController();
162
- abort.signal.addEventListener('abort', () => {
163
- nativeGrpc().cancelGrpcCall(id);
164
- });
358
+ const interceptors = this.resolveInterceptors(options);
359
+ const policy = this.resolvePolicy(options);
360
+ const deadlineBudgetSeconds = this.resolveDeadlineBudgetSeconds(options);
165
361
  const response = createDeferred(abort.signal);
166
362
  const headers = createDeferred(abort.signal);
167
363
  const trailers = createDeferred(abort.signal);
168
- deferredMap[id] = {
169
- response,
170
- headers,
171
- trailers
172
- };
173
- nativeGrpc().unaryCall(id, method, obj, requestHeaders || {});
174
364
  const call = new GrpcUnaryCall(method, data, requestHeaders || {}, headers.promise, response.promise, trailers.promise, abort);
175
365
  call.then(result => result, () => abort.abort());
366
+ Promise.resolve().then(async () => {
367
+ const result = await this.runUnaryWithPolicy(method, data, requestHeaders || {}, options, interceptors, abort.signal, policy, deadlineBudgetSeconds);
368
+ headers.resolve(result.headers);
369
+ response.resolve(result.response);
370
+ trailers.resolve(result.trailers);
371
+ }).catch(reason => {
372
+ if (abort.signal.aborted) {
373
+ const error = new GrpcError('aborted', GrpcStatusCode.CANCELLED);
374
+ headers.reject(error);
375
+ response.reject(error);
376
+ trailers.reject(error);
377
+ return;
378
+ }
379
+ const error = runOnError(interceptors, toGrpcError(reason), method);
380
+ headers.reject(error);
381
+ response.reject(error);
382
+ trailers.reject(error);
383
+ });
176
384
  return call;
177
385
  }
178
386
  serverStreamCall(method, data, requestHeaders, options) {
179
- const obj = buildRequestObject(data, options);
180
387
  const id = getId();
181
388
  const abort = new AbortController();
389
+ const interceptors = this.resolveInterceptors(options);
182
390
  abort.signal.addEventListener('abort', () => {
183
391
  nativeGrpc().cancelGrpcCall(id);
184
392
  });
@@ -188,22 +396,62 @@ export class GrpcClient {
188
396
  deferredMap[id] = {
189
397
  headers,
190
398
  trailers,
191
- data: stream
399
+ data: stream,
400
+ method,
401
+ interceptors
192
402
  };
193
- nativeGrpc().serverStreamingCall(id, method, obj, requestHeaders || {});
194
403
  const call = new GrpcServerStreamingCall(method, data, requestHeaders || {}, headers.promise, stream, trailers.promise, abort);
195
404
  call.then(result => result, () => abort.abort());
405
+ Promise.resolve().then(async () => {
406
+ let start = await runOnStart(interceptors, {
407
+ method,
408
+ headers: {
409
+ ...(requestHeaders || {})
410
+ },
411
+ options: {
412
+ ...(options || {})
413
+ },
414
+ request: data
415
+ });
416
+ const callOptions = {
417
+ ...start.options
418
+ };
419
+ delete callOptions.interceptors;
420
+ start = {
421
+ ...start,
422
+ options: callOptions
423
+ };
424
+ const requestBytes = await runOnSendMessage(interceptors, start.request ?? data, start.method);
425
+ const obj = buildRequestObject(requestBytes, start.options);
426
+ await nativeGrpc().serverStreamingCall(id, start.method, obj, start.headers, this.channelId);
427
+ }).catch(reason => {
428
+ const deferred = deferredMap[id];
429
+ if (!deferred) {
430
+ return;
431
+ }
432
+ const error = runOnError(interceptors, toGrpcError(reason), method);
433
+ rejectDeferredCall(deferred, error);
434
+ delete deferredMap[id];
435
+ });
196
436
  return call;
197
437
  }
198
438
 
199
- /**
200
- * Client-streaming RPC: many request messages, one response.
201
- * Native call starts on the first `requests.send(...)`.
439
+ /**
440
+ * Client-streaming RPC: many request messages, one response.
441
+ * Native call starts on the first `requests.send(...)`.
202
442
  */
203
443
  clientStreamCall(method, requestHeaders, options) {
204
444
  const id = getId();
205
445
  const abort = new AbortController();
206
- const headersMeta = requestHeaders || {};
446
+ const interceptors = this.resolveInterceptors(options);
447
+ let headersMeta = {
448
+ ...(requestHeaders || {})
449
+ };
450
+ let callOptions = {
451
+ ...(options || {})
452
+ };
453
+ const channelId = this.channelId;
454
+ let started = false;
207
455
  abort.signal.addEventListener('abort', () => {
208
456
  nativeGrpc().cancelGrpcCall(id);
209
457
  });
@@ -213,26 +461,62 @@ export class GrpcClient {
213
461
  deferredMap[id] = {
214
462
  response,
215
463
  headers,
216
- trailers
464
+ trailers,
465
+ method,
466
+ interceptors
217
467
  };
218
- const requests = new ServerInputStream((data, isFirst) => {
219
- const obj = buildRequestObject(data, isFirst ? options : undefined);
220
- return nativeGrpc().clientStreamingCall(id, method, obj, isFirst ? headersMeta : {});
468
+ const requests = new ServerInputStream(async (data, isFirst) => {
469
+ try {
470
+ let message = await runOnSendMessage(interceptors, data, method);
471
+ if (isFirst || !started) {
472
+ const start = await runOnStart(interceptors, {
473
+ method,
474
+ headers: headersMeta,
475
+ options: callOptions,
476
+ request: message
477
+ });
478
+ headersMeta = start.headers;
479
+ callOptions = {
480
+ ...start.options
481
+ };
482
+ delete callOptions.interceptors;
483
+ message = start.request ?? message;
484
+ started = true;
485
+ }
486
+ const obj = buildRequestObject(message, isFirst ? callOptions : undefined);
487
+ return nativeGrpc().clientStreamingCall(id, method, obj, isFirst ? headersMeta : {}, channelId);
488
+ } catch (reason) {
489
+ const deferred = deferredMap[id];
490
+ if (deferred) {
491
+ const error = runOnError(interceptors, toGrpcError(reason), method);
492
+ rejectDeferredCall(deferred, error);
493
+ delete deferredMap[id];
494
+ }
495
+ throw toGrpcError(reason);
496
+ }
221
497
  }, () => nativeGrpc().finishClientStreaming(id));
222
498
  const call = new GrpcClientStreamingCall(method, headersMeta, requests, headers.promise, response.promise, trailers.promise, abort);
223
499
  call.then(result => result, () => abort.abort());
224
500
  return call;
225
501
  }
226
502
 
227
- /**
228
- * Bidirectional streaming RPC: interleaved request and response messages.
229
- * Native call starts on the first `requests.send(...)`.
230
- * Registers only the `data` stream (plus headers/trailers) — no unary `response`.
503
+ /**
504
+ * Bidirectional streaming RPC: interleaved request and response messages.
505
+ * Native call starts on the first `requests.send(...)`.
506
+ * Registers only the `data` stream (plus headers/trailers) — no unary `response`.
231
507
  */
232
508
  bidiStreamCall(method, requestHeaders, options) {
233
509
  const id = getId();
234
510
  const abort = new AbortController();
235
- const headersMeta = requestHeaders || {};
511
+ const interceptors = this.resolveInterceptors(options);
512
+ let headersMeta = {
513
+ ...(requestHeaders || {})
514
+ };
515
+ let callOptions = {
516
+ ...(options || {})
517
+ };
518
+ const channelId = this.channelId;
519
+ let started = false;
236
520
  abort.signal.addEventListener('abort', () => {
237
521
  nativeGrpc().cancelGrpcCall(id);
238
522
  });
@@ -242,27 +526,139 @@ export class GrpcClient {
242
526
  deferredMap[id] = {
243
527
  headers,
244
528
  trailers,
245
- data: stream
529
+ data: stream,
530
+ method,
531
+ interceptors
246
532
  };
247
- const requests = new ServerInputStream((data, isFirst) => {
248
- const obj = buildRequestObject(data, isFirst ? options : undefined);
249
- return nativeGrpc().bidiStreamingCall(id, method, obj, isFirst ? headersMeta : {});
533
+ const requests = new ServerInputStream(async (data, isFirst) => {
534
+ try {
535
+ let message = await runOnSendMessage(interceptors, data, method);
536
+ if (isFirst || !started) {
537
+ const start = await runOnStart(interceptors, {
538
+ method,
539
+ headers: headersMeta,
540
+ options: callOptions,
541
+ request: message
542
+ });
543
+ headersMeta = start.headers;
544
+ callOptions = {
545
+ ...start.options
546
+ };
547
+ delete callOptions.interceptors;
548
+ message = start.request ?? message;
549
+ started = true;
550
+ }
551
+ const obj = buildRequestObject(message, isFirst ? callOptions : undefined);
552
+ return nativeGrpc().bidiStreamingCall(id, method, obj, isFirst ? headersMeta : {}, channelId);
553
+ } catch (reason) {
554
+ const deferred = deferredMap[id];
555
+ if (deferred) {
556
+ const error = runOnError(interceptors, toGrpcError(reason), method);
557
+ rejectDeferredCall(deferred, error);
558
+ delete deferredMap[id];
559
+ }
560
+ throw toGrpcError(reason);
561
+ }
250
562
  }, () => nativeGrpc().finishClientStreaming(id));
251
563
  const call = new GrpcBidiStreamingCall(method, headersMeta, requests, headers.promise, stream, trailers.promise, abort);
252
564
  call.then(result => result, () => abort.abort());
253
565
  return call;
254
566
  }
567
+ }
568
+ export class GrpcClient extends GrpcCallApi {
569
+ constructor() {
570
+ super(DEFAULT_CHANNEL_ID, [], 120, null, null);
571
+ Emitter.addListener('grpc-call', handleGrpcEvent);
572
+ }
573
+ destroy() {
574
+ Emitter.removeAllListeners('grpc-call');
575
+ }
576
+ /**
577
+ * Replace default-channel interceptors (same replace semantics as `setTlsOptions`).
578
+ * Prefer `createChannel({ interceptors })` for multi-host apps.
579
+ */
580
+ setInterceptors(interceptors = []) {
581
+ this.channelInterceptors = [...interceptors];
582
+ }
583
+ /**
584
+ * Replace unary retry policy on the default channel.
585
+ * Clears any hedging policy (mutually exclusive). Pass `null` to disable.
586
+ */
587
+ setRetryPolicy(policy) {
588
+ if (policy) {
589
+ normalizeRetryPolicy(policy);
590
+ }
591
+ this.channelRetry = policy;
592
+ this.channelHedging = null;
593
+ }
594
+ /**
595
+ * Replace unary hedging policy on the default channel.
596
+ * Clears any retry policy (mutually exclusive). Pass `null` to disable.
597
+ */
598
+ setHedgingPolicy(policy) {
599
+ if (policy) {
600
+ normalizeHedgingPolicy(policy);
601
+ }
602
+ this.channelHedging = policy;
603
+ this.channelRetry = null;
604
+ }
605
+ getHost() {
606
+ return nativeGrpc().getHost();
607
+ }
608
+ setHost(host) {
609
+ nativeGrpc().setHost(host);
610
+ }
611
+ getInsecure() {
612
+ return nativeGrpc().getIsInsecure();
613
+ }
614
+ setInsecure(insecure) {
615
+ nativeGrpc().setInsecure(insecure);
616
+ }
617
+ /**
618
+ * Replace channel TLS options (custom CA, mTLS, hostname override).
619
+ * Each call replaces the previous config; omitted fields are cleared.
620
+ * Apply before `initGrpcChannel()`. Ignored while insecure/plaintext.
621
+ * For multi-host apps prefer {@link createChannel} with `tls` in config.
622
+ */
623
+ setTlsOptions(options = {}) {
624
+ nativeGrpc().setTlsOptions(normalizeTlsOptions(options));
625
+ }
626
+ setCompression(enable, compressorName) {
627
+ nativeGrpc().setCompression(enable, compressorName);
628
+ }
629
+ setResponseSizeLimit(limitInBytes) {
630
+ nativeGrpc().setResponseSizeLimit(limitInBytes);
631
+ }
632
+ /** Global per-call deadline in seconds (Android/iOS). Default 120. Overridable per RPC via options. */
633
+ setCallDeadlineSeconds(seconds) {
634
+ this.channelDeadlineSeconds = Math.max(0, seconds);
635
+ nativeGrpc().setCallDeadlineSeconds(seconds);
636
+ }
637
+ initGrpcChannel() {
638
+ nativeGrpc().initGrpcChannel();
639
+ }
640
+ setKeepAlive(enable, keepAliveTime, keepAliveTimeOut) {
641
+ nativeGrpc().setKeepAlive(enable, keepAliveTime, keepAliveTimeOut);
642
+ }
643
+ resetConnection(message) {
644
+ if (!this.isAndroid()) return;
645
+ nativeGrpc().resetConnection(message);
646
+ }
647
+ setUiLogEnabled(enable) {
648
+ if (!this.isAndroid()) return;
649
+ nativeGrpc().setUiLogEnabled(enable);
650
+ }
651
+ onConnectionStateChange() {
652
+ if (!this.isAndroid()) return;
653
+ nativeGrpc().onConnectionStateChange();
654
+ }
655
+ enterIdle() {
656
+ if (!this.isAndroid()) return;
657
+ nativeGrpc().enterIdle();
658
+ }
255
659
  isAndroid() {
256
660
  return Platform.OS === 'android';
257
661
  }
258
662
  }
259
-
260
- /** Lazy binding to NativeModules.Grpc (works with Jest mocks / late link). */
261
- export const Grpc = new Proxy({}, {
262
- get(_target, prop) {
263
- const native = nativeGrpc();
264
- const value = native[prop];
265
- return typeof value === 'function' ? value.bind(native) : value;
266
- }
267
- });
663
+ export { Grpc } from './native';
268
664
  //# sourceMappingURL=client.js.map