UNPKG

58.1 kBTypeScriptView Raw
1
2/*
3 * Copyright 2019 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19/// <reference types="bytebuffer" />
20
21declare module "grpc" {
22 // add imports here, inside the "grpc" module, to keep it as an ambient module
23 import { EventEmitter } from "events";
24 import { Duplex, Readable, Writable } from "stream";
25 import { SecureContext } from "tls";
26
27 /* The Message interface is copied and slightly modified from @types/protobuf
28 * version 5.0.31, which was distributed under the following license:
29 *
30 * This project is licensed under the MIT license.
31 * Copyrights are respective of each contributor listed at the beginning of each definition file.
32 *
33 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
34 *
35 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
36 *
37 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38 */
39 export interface ProtobufMessage {
40 $add(key: string, value: any, noAssert?: boolean): ProtobufMessage;
41 $get<T>(key: string): T;
42 $set(key: string | {[key: string]: any}, value?: any | boolean, noAssert?: boolean): void;
43 add(key: string, value: any, noAssert?: boolean): ProtobufMessage;
44 calculate(): number;
45 encode(buffer?: ByteBuffer | boolean, noVerify?: boolean): ByteBuffer;
46 encode64(): string;
47 encodeAB(): ArrayBuffer;
48 encodeNB(): Buffer;
49 encodeHex(): string;
50 encodeJSON(): string;
51 encodeDelimited(buffer?: ByteBuffer | boolean, noVerify?: boolean): ByteBuffer;
52 get<T>(key: string, noAssert?: boolean): T;
53 set(key: string | {[key: string]: any}, value?: any | boolean, noAssert?: boolean): void;
54 toArrayBuffer(): ArrayBuffer;
55 toBase64(): string;
56 toBuffer(): Buffer;
57 toHex(): string;
58 toRaw(binaryAsBase64?: boolean, longsAsStrings?: boolean): {[key: string]: any};
59 toString(): string;
60 [field: string]: any;
61 }
62
63 /**
64 * Load a ProtoBuf.js object as a gRPC object.
65 * @param value The ProtoBuf.js reflection object to load
66 * @param options Options to apply to the loaded file
67 * @return The resulting gRPC object.
68 */
69 export function loadObject<T = GrpcObject>(value: object, options?: LoadObjectOptions): T;
70
71 /**
72 * Options for loading proto object as gRPC object
73 * @param {(number|string)=} [options.protobufjsVersion='detect'] 5 and 6
74 * respectively indicate that an object from the corresponding version of
75 * Protobuf.js is provided in the value argument. If the option is 'detect',
76 * gRPC will guess what the version is based on the structure of the value.
77 */
78 export interface LoadObjectOptions {
79 /**
80 * Deserialize bytes values as base64 strings instead of Buffers.
81 * Defaults to `false`.
82 */
83 binaryAsBase64?: boolean;
84
85 /**
86 * Deserialize long values as strings instead of objects.
87 * Defaults to `true`.
88 */
89 longsAsStrings?: boolean;
90
91 /**
92 * Deserialize enum values as strings instead of numbers. Only works with
93 * Protobuf.js 6 values.
94 * Defaults to `true`.
95 */
96 enumsAsStrings?: boolean;
97
98 /**
99 * use the beta method argument order for client methods, with optional
100 * arguments after the callback. This option is only a temporary stopgap
101 * measure to smooth an API breakage. It is deprecated, and new code
102 * should not use it.
103 * Defaults to `false`
104 */
105 deprecatedArgumentOrder?: boolean;
106
107 /**
108 * 5 and 6 respectively indicate that an object from the corresponding
109 * version of Protobuf.js is provided in the value argument. If the option
110 * is 'detect', gRPC wll guess what the version is based on the structure
111 * of the value.
112 */
113 protobufjsVersion?: 5 | 6 | "detect";
114 }
115
116 /**
117 * Map from `.proto` file.
118 * - Namespaces become maps from the names of their direct members to those member objects
119 * - Service definitions become client constructors for clients for that service. They also
120 * have a service member that can be used for constructing servers.
121 * - Message definitions become Message constructors like those that ProtoBuf.js would create
122 * - Enum definitions become Enum objects like those that ProtoBuf.js would create
123 * - Anything else becomes the relevant reflection object that ProtoBuf.js would create
124 */
125 export interface GrpcObject {
126 [name: string]: GrpcObject | typeof Client | ProtobufMessage;
127 }
128
129 /**
130 * Load a gRPC object from a .proto file.
131 * @param filename The file to load
132 * @param format The file format to expect. Defaults to 'proto'
133 * @param options Options to apply to the loaded file
134 * @return The resulting gRPC object
135 */
136 export function load<T = GrpcObject>(filename: Filename, format?: "proto" | "json", options?: LoadOptions): T;
137
138 /**
139 * Load a gRPC package definition as a gRPC object hierarchy
140 * @param packageDef The package definition object
141 * @return The resulting gRPC object
142 */
143 export function loadPackageDefinition(packageDefinition: PackageDefinition): GrpcObject;
144
145 /**
146 * A filename
147 */
148 export type Filename = string | { root: string, file: string };
149
150 /**
151 * Options for loading proto file as gRPC object
152 */
153 export interface LoadOptions {
154 /**
155 * Load this file with field names in camel case instead of their original case.
156 * Defaults to `false`.
157 */
158 convertFieldsToCamelCase?: boolean;
159
160 /**
161 * Deserialize bytes values as base64 strings instead of Buffers.
162 * Defaults to `false`.
163 */
164 binaryAsBase64?: boolean;
165
166 /**
167 * Deserialize long values as strings instead of objects.
168 * Defaults to `true`.
169 */
170 longsAsStrings?: boolean;
171
172 /**
173 * Use the beta method argument order for client methods, with optional
174 * arguments after the callback. This option is only a temporary stopgap
175 * measure to smooth an API breakage. It is deprecated, and new code
176 * should not use it.
177 * Defaults to `false`
178 */
179 deprecatedArgumentOrder?: boolean;
180 }
181
182 /**
183 * Sets the logger function for the gRPC module. For debugging purposes, the C
184 * core will log synchronously directly to stdout unless this function is
185 * called. Note: the output format here is intended to be informational, and
186 * is not guaranteed to stay the same in the future.
187 * Logs will be directed to logger.error.
188 * @param logger A Console-like object.
189 */
190 export function setLogger(logger: Console): void;
191
192 /**
193 * Sets the logger verbosity for gRPC module logging. The options are members
194 * of the grpc.logVerbosity map.
195 * @param verbosity The minimum severity to log
196 */
197 export function setLogVerbosity(verbosity: logVerbosity): void;
198
199 /**
200 * Server object that stores request handlers and delegates incoming requests to those handlers
201 */
202 export class Server {
203 /**
204 * Constructs a server object that stores request handlers and delegates
205 * incoming requests to those handlers
206 * @param options Options that should be passed to the internal server
207 * implementation
208 * ```
209 * var server = new grpc.Server();
210 * server.addProtoService(protobuf_service_descriptor, service_implementation);
211 * server.bind('address:port', server_credential);
212 * server.start();
213 * ```
214 */
215 constructor(options?: object);
216
217 /**
218 * Start the server and begin handling requests
219 */
220 start(): void;
221
222 /**
223 * Registers a handler to handle the named method. Fails if there already is
224 * a handler for the given method. Returns true on success
225 * @param name The name of the method that the provided function should
226 * handle/respond to.
227 * @param handler Function that takes a stream of
228 * request values and returns a stream of response values
229 * @param serialize Serialization function for responses
230 * @param deserialize Deserialization function for requests
231 * @param type The streaming type of method that this handles
232 * @return True if the handler was set. False if a handler was already
233 * set for that name.
234 */
235 register<RequestType, ResponseType>(
236 name: string,
237 handler: handleCall<RequestType, ResponseType>,
238 serialize: serialize<ResponseType>,
239 deserialize: deserialize<RequestType>,
240 type: string
241 ): boolean;
242
243 /**
244 * Gracefully shuts down the server. The server will stop receiving new calls,
245 * and any pending calls will complete. The callback will be called when all
246 * pending calls have completed and the server is fully shut down. This method
247 * is idempotent with itself and forceShutdown.
248 * @param {function()} callback The shutdown complete callback
249 */
250 tryShutdown(callback: () => void): void;
251
252 /**
253 * Forcibly shuts down the server. The server will stop receiving new calls
254 * and cancel all pending calls. When it returns, the server has shut down.
255 * This method is idempotent with itself and tryShutdown, and it will trigger
256 * any outstanding tryShutdown callbacks.
257 */
258 forceShutdown(): void;
259
260 /**
261 * Add a service to the server, with a corresponding implementation.
262 * @param service The service descriptor
263 * @param implementation Map of method names to method implementation
264 * for the provided service.
265 */
266 addService<ImplementationType = UntypedServiceImplementation>(
267 service: ServiceDefinition<ImplementationType>,
268 implementation: ImplementationType
269 ): void;
270
271 /**
272 * Add a proto service to the server, with a corresponding implementation
273 * @deprecated Use `Server#addService` instead
274 * @param service The proto service descriptor
275 * @param implementation Map of method names to method implementation
276 * for the provided service.
277 */
278 addProtoService<ImplementationType = UntypedServiceImplementation>(
279 service: ServiceDefinition<ImplementationType>,
280 implementation: ImplementationType
281 ): void;
282
283 /**
284 * Binds the server to the given port, with SSL disabled if creds is an
285 * insecure credentials object
286 * @param port The port that the server should bind on, in the format
287 * "address:port"
288 * @param creds Server credential object to be used for SSL. Pass an
289 * insecure credentials object for an insecure port.
290 * @return The bound port number or 0 if the operation failed.
291 */
292 bind(port: string, creds: ServerCredentials): number;
293
294 /**
295 * Binds the server to the given port, with SSL disabled if creds is an
296 * insecure credentials object. Provides the result asynchronously.
297 * @param port The port that the server should bind on, in the format "address:port"
298 * @param creds Server credential object to be used for
299 * SSL. Pass an insecure credentials object for an insecure port.
300 * @param callback Called with the result of attempting to bind a port
301 * - error: If non-null, indicates that binding the port failed.
302 * - port: The bound port number. If binding the port fails, this will be negative to match the output of bind.
303 */
304 bindAsync(port: string, creds: ServerCredentials, callback: (error: Error | null, port: number) => void): void;
305 }
306
307 /**
308 * A type that servers as a default for an untyped service.
309 */
310 export type UntypedServiceImplementation = { [name: string]: handleCall<any, any> };
311
312 /**
313 * An object that completely defines a service.
314 */
315 export type ServiceDefinition<ImplementationType = UntypedServiceImplementation> = {
316 readonly [I in keyof ImplementationType]: MethodDefinition<any, any>;
317 }
318
319 /**
320 * An object that defines a protobuf type
321 */
322 export interface ProtobufTypeDefinition {
323 format: string;
324 type: object;
325 fileDescriptorProtos: Buffer[];
326 }
327
328 /**
329 * An object that defines a package containing multiple services
330 */
331 export type PackageDefinition = {
332 readonly [fullyQualifiedName: string]: ServiceDefinition<any> | ProtobufTypeDefinition;
333 }
334
335 /**
336 * An object that completely defines a service method signature.
337 */
338 export interface MethodDefinition<RequestType, ResponseType> {
339 /**
340 * The method's URL path
341 */
342 path: string;
343 /**
344 * Indicates whether the method accepts a stream of requests
345 */
346 requestStream: boolean;
347 /**
348 * Indicates whether the method returns a stream of responses
349 */
350 responseStream: boolean;
351 /**
352 * Serialization function for request values
353 */
354 requestSerialize: serialize<RequestType>;
355 /**
356 * Serialization function for response values
357 */
358 responseSerialize: serialize<ResponseType>;
359 /**
360 * Deserialization function for request data
361 */
362 requestDeserialize: deserialize<RequestType>;
363 /**
364 * Deserialization function for repsonse data
365 */
366 responseDeserialize: deserialize<ResponseType>;
367 }
368
369 type handleCall<RequestType, ResponseType> =
370 handleUnaryCall<RequestType, ResponseType> |
371 handleClientStreamingCall<RequestType, ResponseType> |
372 handleServerStreamingCall<RequestType, ResponseType> |
373 handleBidiStreamingCall<RequestType, ResponseType>;
374
375 /**
376 * User-provided method to handle unary requests on a server
377 */
378 type handleUnaryCall<RequestType, ResponseType> =
379 (call: ServerUnaryCall<RequestType>, callback: sendUnaryData<ResponseType>) => void;
380
381 /**
382 * An EventEmitter. Used for unary calls.
383 */
384 export class ServerUnaryCall<RequestType> extends EventEmitter {
385 /**
386 * Indicates if the call has been cancelled
387 */
388 cancelled: boolean;
389
390 /**
391 * The request metadata from the client
392 */
393 metadata: Metadata;
394
395 /**
396 * The request message from the client
397 */
398 request: RequestType;
399
400 private constructor();
401
402 /**
403 * Get the endpoint this call/stream is connected to.
404 * @return The URI of the endpoint
405 */
406 getPeer(): string;
407
408 /**
409 * Send the initial metadata for a writable stream.
410 * @param responseMetadata Metadata to send
411 */
412 sendMetadata(responseMetadata: Metadata): void;
413 }
414
415 /**
416 * User provided method to handle client streaming methods on the server.
417 */
418 type handleClientStreamingCall<RequestType, ResponseType> =
419 (call: ServerReadableStream<RequestType>, callback: sendUnaryData<ResponseType>) => void;
420
421 /**
422 * A stream that the server can read from. Used for calls that are streaming
423 * from the client side.
424 */
425 export class ServerReadableStream<RequestType> extends Readable {
426 /**
427 * Indicates if the call has been cancelled
428 */
429 cancelled: boolean;
430
431 /**
432 * The request metadata from the client
433 */
434 metadata: Metadata;
435
436 private constructor();
437
438 /**
439 * Get the endpoint this call/stream is connected to.
440 * @return The URI of the endpoint
441 */
442 getPeer(): string;
443
444 /**
445 * Send the initial metadata for a writable stream.
446 * @param responseMetadata Metadata to send
447 */
448 sendMetadata(responseMetadata: Metadata): void;
449 }
450
451 /**
452 * User provided method to handle server streaming methods on the server.
453 */
454 type handleServerStreamingCall<RequestType, ResponseType> =
455 (call: ServerWritableStream<RequestType, ResponseType>) => void;
456
457 /**
458 * A stream that the server can write to. Used for calls that are streaming
459 * from the server side.
460 */
461 export class ServerWritableStream<RequestType, ResponseType=unknown> extends Writable {
462 /**
463 * Indicates if the call has been cancelled
464 */
465 cancelled: boolean;
466
467 /**
468 * The request metadata from the client
469 */
470 metadata: Metadata;
471
472 /**
473 * The request message from the client
474 */
475 request: RequestType;
476
477 private constructor();
478
479 /**
480 * Get the endpoint this call/stream is connected to.
481 * @return The URI of the endpoint
482 */
483 getPeer(): string;
484
485 /**
486 * Send the initial metadata for a writable stream.
487 * @param responseMetadata Metadata to send
488 */
489 sendMetadata(responseMetadata: Metadata): void;
490 }
491
492 /* This typo existed in previous versions of this file, so we provide this
493 * type alias for backwards compatibility. */
494 export type ServerWriteableStream<RequestType, ResponseType=unknown> = ServerWritableStream<RequestType, ResponseType>;
495
496 /**
497 * User provided method to handle bidirectional streaming calls on the server.
498 */
499 type handleBidiStreamingCall<RequestType, ResponseType> =
500 (call: ServerDuplexStream<RequestType, ResponseType>) => void;
501
502 /**
503 * A stream that the server can read from or write to. Used for calls
504 * with duplex streaming.
505 */
506 export class ServerDuplexStream<RequestType, ResponseType> extends Duplex {
507 /**
508 * Indicates if the call has been cancelled
509 */
510 cancelled: boolean;
511
512 /**
513 * The request metadata from the client
514 */
515 metadata: Metadata;
516
517 private constructor();
518
519 /**
520 * Get the endpoint this call/stream is connected to.
521 * @return The URI of the endpoint
522 */
523 getPeer(): string;
524
525 /**
526 * Send the initial metadata for a writable stream.
527 * @param responseMetadata Metadata to send
528 */
529 sendMetadata(responseMetadata: Metadata): void;
530 }
531
532 /**
533 * A deserialization function
534 * @param data The byte sequence to deserialize
535 * @return The data deserialized as a value
536 */
537 type deserialize<T> = (data: Buffer) => T;
538
539 /**
540 * A serialization function
541 * @param value The value to serialize
542 * @return The value serialized as a byte sequence
543 */
544 type serialize<T> = (value: T) => Buffer;
545
546 /**
547 * Callback function passed to server handlers that handle methods with
548 * unary responses.
549 */
550 type sendUnaryData<ResponseType> =
551 (error: ServiceError | null, value: ResponseType | null, trailer?: Metadata, flags?: number) => void;
552
553 interface MetadataOptions {
554 /* Signal that the request is idempotent. Defaults to false */
555 idempotentRequest?: boolean;
556 /* Signal that the call should not return UNAVAILABLE before it has
557 * started. Defaults to true. */
558 waitForReady?: boolean;
559 /* Signal that the call is cacheable. GRPC is free to use GET verb.
560 * Defaults to false */
561 cacheableRequest?: boolean;
562 /* Signal that the initial metadata should be corked. Defaults to false. */
563 corked?: boolean;
564 }
565
566 /**
567 * A class for storing metadata. Keys are normalized to lowercase ASCII.
568 */
569 export class Metadata {
570 /**
571 * @param options Boolean options for the beginning of the call.
572 * These options only have any effect when passed at the beginning of
573 * a client request.
574 */
575 constructor(options?: MetadataOptions);
576 /**
577 * Sets the given value for the given key by replacing any other values
578 * associated with that key. Normalizes the key.
579 * @param key The key to whose value should be set.
580 * @param value The value to set. Must be a buffer if and only
581 * if the normalized key ends with '-bin'.
582 */
583 set(key: string, value: MetadataValue): void;
584
585 /**
586 * Adds the given value for the given key by appending to a list of previous
587 * values associated with that key. Normalizes the key.
588 * @param key The key for which a new value should be appended.
589 * @param value The value to add. Must be a buffer if and only
590 * if the normalized key ends with '-bin'.
591 */
592 add(key: string, value: MetadataValue): void;
593
594 /**
595 * Removes the given key and any associated values. Normalizes the key.
596 * @param key The key whose values should be removed.
597 */
598 remove(key: string): void;
599
600 /**
601 * Gets a list of all values associated with the key. Normalizes the key.
602 * @param key The key whose value should be retrieved.
603 * @return A list of values associated with the given key.
604 */
605 get(key: string): MetadataValue[];
606
607 /**
608 * Gets a plain object mapping each key to the first value associated with it.
609 * This reflects the most common way that people will want to see metadata.
610 * @return A key/value mapping of the metadata.
611 */
612 getMap(): { [key: string]: MetadataValue };
613
614 /**
615 * Clones the metadata object.
616 * @return The newly cloned object.
617 */
618 clone(): Metadata;
619
620 /**
621 * Set options on the metadata object
622 * @param options Boolean options for the beginning of the call.
623 * These options only have any effect when passed at the beginning of
624 * a client request.
625 */
626 setOptions(options: MetadataOptions): void;
627 }
628
629 export type MetadataValue = string | Buffer;
630
631 /**
632 * Represents the status of a completed request. If `code` is
633 * `grpc.status.OK`, then the request has completed successfully.
634 * Otherwise, the request has failed, `details` will contain a description of
635 * the error. Either way, `metadata` contains the trailing response metadata
636 * sent by the server when it finishes processing the call.
637 */
638 export interface StatusObject {
639 /**
640 * The error code, a key of `grpc.status`
641 */
642 code: status;
643 /**
644 * Human-readable description of the status
645 */
646 details: string;
647 /**
648 * Trailing metadata sent with the status, if applicable
649 */
650 metadata: Metadata;
651 }
652
653 /**
654 * Describes how a request has failed. The member `message` will be the same as
655 * `details` in `StatusObject`, and `code` and `metadata` are the
656 * same as in that object.
657 */
658 export interface ServiceError extends Error {
659 /**
660 * The error code, a key of {@link grpc.status} that is not `grpc.status.OK`
661 */
662 code?: status;
663 /**
664 * Trailing metadata sent with the status, if applicable
665 */
666 metadata?: Metadata;
667 /**
668 * Original status details string
669 */
670 details?: string;
671 }
672
673 /**
674 * ServerCredentials factories
675 */
676 export class ServerCredentials {
677 /**
678 * Create insecure server credentials
679 * @return The ServerCredentials
680 */
681 static createInsecure(): ServerCredentials;
682 /**
683 * Create SSL server credentials
684 * @param rootCerts Root CA certificates for validating client certificates
685 * @param keyCertPairs A list of private key and certificate chain pairs to
686 * be used for authenticating the server
687 * @param checkClientCertificate Indicates that the server should request
688 * and verify the client's certificates.
689 * Defaults to `false`.
690 * @return The ServerCredentials
691 */
692 static createSsl(rootCerts: Buffer | null, keyCertPairs: KeyCertPair[], checkClientCertificate?: boolean): ServerCredentials;
693 }
694
695 /**
696 * A private key and certificate pair
697 */
698 export interface KeyCertPair {
699 /**
700 * The server's private key
701 */
702 private_key: Buffer;
703
704 /**
705 * The server's certificate chain
706 */
707 cert_chain: Buffer;
708 }
709
710 /**
711 * Enum of status codes that gRPC can return
712 */
713 export enum status {
714 /**
715 * Not an error; returned on success
716 */
717 OK = 0,
718 /**
719 * The operation was cancelled (typically by the caller).
720 */
721 CANCELLED = 1,
722 /**
723 * Unknown error. An example of where this error may be returned is
724 * if a status value received from another address space belongs to
725 * an error-space that is not known in this address space. Also
726 * errors raised by APIs that do not return enough error information
727 * may be converted to this error.
728 */
729 UNKNOWN = 2,
730 /**
731 * Client specified an invalid argument. Note that this differs
732 * from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments
733 * that are problematic regardless of the state of the system
734 * (e.g., a malformed file name).
735 */
736 INVALID_ARGUMENT = 3,
737 /**
738 * Deadline expired before operation could complete. For operations
739 * that change the state of the system, this error may be returned
740 * even if the operation has completed successfully. For example, a
741 * successful response from a server could have been delayed long
742 * enough for the deadline to expire.
743 */
744 DEADLINE_EXCEEDED = 4,
745 /**
746 * Some requested entity (e.g., file or directory) was not found.
747 */
748 NOT_FOUND = 5,
749 /**
750 * Some entity that we attempted to create (e.g., file or directory)
751 * already exists.
752 */
753 ALREADY_EXISTS = 6,
754 /**
755 * The caller does not have permission to execute the specified
756 * operation. PERMISSION_DENIED must not be used for rejections
757 * caused by exhausting some resource (use RESOURCE_EXHAUSTED
758 * instead for those errors). PERMISSION_DENIED must not be
759 * used if the caller can not be identified (use UNAUTHENTICATED
760 * instead for those errors).
761 */
762 PERMISSION_DENIED = 7,
763 /**
764 * Some resource has been exhausted, perhaps a per-user quota, or
765 * perhaps the entire file system is out of space.
766 */
767 RESOURCE_EXHAUSTED = 8,
768 /**
769 * Operation was rejected because the system is not in a state
770 * required for the operation's execution. For example, directory
771 * to be deleted may be non-empty, an rmdir operation is applied to
772 * a non-directory, etc.
773 *
774 * A litmus test that may help a service implementor in deciding
775 * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
776 *
777 * - Use UNAVAILABLE if the client can retry just the failing call.
778 * - Use ABORTED if the client should retry at a higher-level
779 * (e.g., restarting a read-modify-write sequence).
780 * - Use FAILED_PRECONDITION if the client should not retry until
781 * the system state has been explicitly fixed. E.g., if an "rmdir"
782 * fails because the directory is non-empty, FAILED_PRECONDITION
783 * should be returned since the client should not retry unless
784 * they have first fixed up the directory by deleting files from it.
785 * - Use FAILED_PRECONDITION if the client performs conditional
786 * REST Get/Update/Delete on a resource and the resource on the
787 * server does not match the condition. E.g., conflicting
788 * read-modify-write on the same resource.
789 */
790 FAILED_PRECONDITION = 9,
791 /**
792 * The operation was aborted, typically due to a concurrency issue
793 * like sequencer check failures, transaction aborts, etc.
794 *
795 * See litmus test above for deciding between FAILED_PRECONDITION,
796 * ABORTED, and UNAVAILABLE.
797 */
798 ABORTED = 10,
799 /**
800 * Operation was attempted past the valid range. E.g., seeking or
801 * reading past end of file.
802 *
803 * Unlike INVALID_ARGUMENT, this error indicates a problem that may
804 * be fixed if the system state changes. For example, a 32-bit file
805 * system will generate INVALID_ARGUMENT if asked to read at an
806 * offset that is not in the range [0,2^32-1], but it will generate
807 * OUT_OF_RANGE if asked to read from an offset past the current
808 * file size.
809 *
810 * There is a fair bit of overlap between FAILED_PRECONDITION and
811 * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific
812 * error) when it applies so that callers who are iterating through
813 * a space can easily look for an OUT_OF_RANGE error to detect when
814 * they are done.
815 */
816 OUT_OF_RANGE = 11,
817 /**
818 * Operation is not implemented or not supported/enabled in this service.
819 */
820 UNIMPLEMENTED = 12,
821 /**
822 * Internal errors. Means some invariants expected by underlying
823 * system has been broken. If you see one of these errors,
824 * something is very broken.
825 */
826 INTERNAL = 13,
827 /**
828 * The service is currently unavailable. This is a most likely a
829 * transient condition and may be corrected by retrying with
830 * a backoff.
831 *
832 * See litmus test above for deciding between FAILED_PRECONDITION,
833 * ABORTED, and UNAVAILABLE.
834 */
835 UNAVAILABLE = 14,
836 /**
837 * Unrecoverable data loss or corruption.
838 */
839 DATA_LOSS = 15,
840 /**
841 * The request does not have valid authentication credentials for the
842 * operation.
843 */
844 UNAUTHENTICATED = 16,
845 }
846
847 /**
848 * Propagation flags: these can be bitwise or-ed to form the propagation option
849 * for calls.
850 *
851 * Users are encouraged to write propagation masks as deltas from the default.
852 * i.e. write `grpc.propagate.DEFAULTS & ~grpc.propagate.DEADLINE` to disable
853 * deadline propagation.
854 */
855 export enum propagate {
856 DEADLINE,
857 CENSUS_STATS_CONTEXT,
858 CENSUS_TRACING_CONTEXT,
859 CANCELLATION,
860 DEFAULTS,
861 }
862
863 /**
864 * Call error constants. Call errors almost always indicate bugs in the gRPC
865 * library, and these error codes are mainly useful for finding those bugs.
866 */
867 export enum callError {
868 OK,
869 ERROR,
870 NOT_ON_SERVER,
871 NOT_ON_CLIENT,
872 ALREADY_INVOKED,
873 NOT_INVOKED,
874 ALREADY_FINISHED,
875 TOO_MANY_OPERATIONS,
876 INVALID_FLAGS,
877 INVALID_METADATA,
878 INVALID_MESSAGE,
879 NOT_SERVER_COMPLETION_QUEUE,
880 BATCH_TOO_BIG,
881 PAYLOAD_TYPE_MISMATCH,
882 }
883
884 /**
885 * Write flags: these can be bitwise or-ed to form write options that modify
886 * how data is written.
887 */
888 export enum writeFlags {
889 /**
890 * Hint that the write may be buffered and need not go out on the wire
891 * immediately. GRPC is free to buffer the message until the next non-buffered
892 * write, or until writes_done, but it need not buffer completely or at all.
893 */
894 BUFFER_HINT = 1,
895 /**
896 * Force compression to be disabled for a particular write
897 */
898 NO_COMPRESS,
899 }
900
901 /**
902 * Log verbosity constants. Maps setting names to code numbers.
903 */
904 export enum logVerbosity {
905 DEBUG,
906 INFO,
907 ERROR,
908 }
909
910 /**
911 * Method type constants
912 */
913 export enum methodTypes {
914 UNARY,
915 CLIENT_STREAMING,
916 SERVER_STREAMING,
917 BIDI_STREAMING,
918 }
919
920
921 /**
922 * A certificate as received by the checkServerIdentity callback.
923 */
924 export interface Certificate {
925 /**
926 * The raw certificate in DER form.
927 */
928 raw: Buffer;
929 }
930
931 /**
932 * A callback that will receive the expected hostname and presented peer
933 * certificate as parameters. The callback should return an error to
934 * indicate that the presented certificate is considered invalid and
935 * otherwise returned undefined.
936 */
937 export type CheckServerIdentityCallback = (hostname: string, cert: Certificate) => Error | undefined;
938
939 /**
940 * Additional peer verification options that can be set when creating
941 * SSL credentials.
942 */
943 export interface VerifyOptions {
944 /**
945 * If set, this callback will be invoked after the usual hostname verification
946 * has been performed on the peer certificate.
947 */
948 checkServerIdentity?: CheckServerIdentityCallback;
949 }
950
951 /**
952 * Credentials module
953 *
954 * This module contains factory methods for two different credential types:
955 * CallCredentials and ChannelCredentials. ChannelCredentials are things like
956 * SSL credentials that can be used to secure a connection, and are used to
957 * construct a Client object. CallCredentials generally modify metadata, so they
958 * can be attached to an individual method call.
959 *
960 * CallCredentials can be composed with other CallCredentials to create
961 * CallCredentials. ChannelCredentials can be composed with CallCredentials
962 * to create ChannelCredentials. No combined credential can have more than
963 * one ChannelCredentials.
964 *
965 * For example, to create a client secured with SSL that uses Google
966 * default application credentials to authenticate:
967 *
968 * ```
969 * var channel_creds = credentials.createSsl(root_certs);
970 * (new GoogleAuth()).getApplicationDefault(function(err, credential) {
971 * var call_creds = credentials.createFromGoogleCredential(credential);
972 * var combined_creds = credentials.combineChannelCredentials(
973 * channel_creds, call_creds);
974 * var client = new Client(address, combined_creds);
975 * });
976 * ```
977 */
978 export const credentials: {
979 /**
980 * Create an SSL Credentials object. If using a client-side certificate, both
981 * the second and third arguments must be passed.
982 * @param rootCerts The root certificate data
983 * @param privateKey The client certificate private key, if applicable
984 * @param certChain The client certificate cert chain, if applicable
985 * @param verifyOptions Additional peer verification options, if desired
986 * @return The SSL Credentials object
987 */
988 createSsl(rootCerts?: Buffer, privateKey?: Buffer, certChain?: Buffer, verifyOptions?: VerifyOptions): ChannelCredentials;
989
990 /**
991 * Create a gRPC credentials object from a metadata generation function. This
992 * function gets the service URL and a callback as parameters. The error
993 * passed to the callback can optionally have a 'code' value attached to it,
994 * which corresponds to a status code that this library uses.
995 * @param metadataGenerator The function that generates metadata
996 * @return The credentials object
997 */
998 createFromMetadataGenerator(metadataGenerator: metadataGenerator): CallCredentials;
999
1000 /**
1001 * Create a gRPC credential from a Google credential object.
1002 * @param googleCredential The Google credential object to use
1003 * @return The resulting credentials object
1004 */
1005 createFromGoogleCredential(googleCredential: GoogleOAuth2Client): CallCredentials;
1006
1007 /**
1008 * Combine a ChannelCredentials with any number of CallCredentials into a single
1009 * ChannelCredentials object.
1010 * @param channelCredential The ChannelCredentials to start with
1011 * @param credentials The CallCredentials to compose
1012 * @return A credentials object that combines all of the input credentials
1013 */
1014 combineChannelCredentials(channelCredential: ChannelCredentials, ...credentials: CallCredentials[]): ChannelCredentials;
1015
1016 /**
1017 * Combine any number of CallCredentials into a single CallCredentials object
1018 * @param credentials The CallCredentials to compose
1019 * @return A credentials object that combines all of the input credentials
1020 */
1021 combineCallCredentials(...credentials: CallCredentials[]): CallCredentials;
1022
1023 /**
1024 * Create an insecure credentials object. This is used to create a channel that
1025 * does not use SSL. This cannot be composed with anything.
1026 * @return The insecure credentials object
1027 */
1028 createInsecure(): ChannelCredentials;
1029 };
1030
1031 /**
1032 * Metadata generator function.
1033 */
1034 export type metadataGenerator = (params: { service_url: string }, callback: (error: Error | null, metadata?: Metadata) => void) => void;
1035
1036 /**
1037 * This cannot be constructed directly. Instead, instances of this class should
1038 * be created using the factory functions in `grpc.credentials`
1039 */
1040 export interface ChannelCredentials {
1041 /**
1042 * Returns a copy of this object with the included set of per-call credentials
1043 * expanded to include callCredentials.
1044 * @param callCredentials A CallCredentials object to associate with this
1045 * instance.
1046 */
1047 compose(callCredentials: CallCredentials): ChannelCredentials;
1048 }
1049
1050 /**
1051 * This cannot be constructed directly. Instead, instances of this class should
1052 * be created using the factory functions in `grpc.credentials`
1053 */
1054 export interface CallCredentials {
1055 /**
1056 * Asynchronously generates a new Metadata object.
1057 * @param options Options used in generating the Metadata object.
1058 */
1059 generateMetadata(options: object): Promise<Metadata>;
1060
1061 /**
1062 * Creates a new CallCredentials object from properties of both this and
1063 * another CallCredentials object. This object's metadata generator will be
1064 * called first.
1065 * @param callCredentials The other CallCredentials object.
1066 */
1067 compose(callCredentials: CallCredentials): CallCredentials;
1068 }
1069
1070 /**
1071 * This is the required interface from the OAuth2Client object
1072 * from https://github.com/google/google-auth-library-nodejs lib.
1073 * The definition is copied from `ts/lib/auth/oauth2client.ts`
1074 */
1075 export interface GoogleOAuth2Client {
1076 getRequestMetadata(optUri: string, metadataCallback: (err: Error, headers: any) => void): void;
1077 }
1078
1079 /**
1080 * Creates a constructor for a client with the given methods, as specified in
1081 * the methods argument. The resulting class will have an instance method for
1082 * each method in the service, which is a partial application of one of the
1083 * `grpc.Client` request methods, depending on `requestSerialize`
1084 * and `responseSerialize`, with the `method`, `serialize`, and `deserialize`
1085 * arguments predefined.
1086 * @param methods An object mapping method names to method attributes
1087 * @param serviceName The fully qualified name of the service
1088 * @param classOptions An options object.
1089 * @return New client constructor, which is a subclass of `grpc.Client`, and
1090 * has the same arguments as that constructor.
1091 */
1092 export function makeGenericClientConstructor(
1093 methods: ServiceDefinition<any>,
1094 serviceName: string,
1095 classOptions: GenericClientOptions,
1096 ): typeof Client;
1097
1098 /**
1099 * Options for generic client constructor.
1100 */
1101 export interface GenericClientOptions {
1102 /**
1103 * Indicates that the old argument order should be used for methods, with
1104 * optional arguments at the end instead of the callback at the end. This
1105 * option is only a temporary stopgap measure to smooth an API breakage.
1106 * It is deprecated, and new code should not use it.
1107 */
1108 deprecatedArgumentOrder?: boolean;
1109 }
1110
1111 /**
1112 * Create a client with the given methods
1113 */
1114 export class Client {
1115 /**
1116 * A generic gRPC client. Primarily useful as a base class for generated clients
1117 * @param address Server address to connect to
1118 * @param credentials Credentials to use to connect to the server
1119 * @param options Options to apply to channel creation
1120 */
1121 constructor(address: string, credentials: ChannelCredentials, options?: object)
1122
1123 /**
1124 * Make a unary request to the given method, using the given serialize
1125 * and deserialize functions, with the given argument.
1126 * @param method The name of the method to request
1127 * @param serialize The serialization function for inputs
1128 * @param deserialize The deserialization function for outputs
1129 * @param argument The argument to the call. Should be serializable with
1130 * serialize
1131 * @param metadata Metadata to add to the call
1132 * @param options Options map
1133 * @param callback The callback to for when the response is received
1134 * @return An event emitter for stream related events
1135 */
1136 makeUnaryRequest<RequestType, ResponseType>(
1137 method: string,
1138 serialize: serialize<RequestType>,
1139 deserialize: deserialize<ResponseType>,
1140 argument: RequestType | null,
1141 metadata: Metadata | null,
1142 options: CallOptions | null,
1143 callback: requestCallback<ResponseType>,
1144 ): ClientUnaryCall;
1145
1146 /**
1147 * Make a client stream request to the given method, using the given serialize
1148 * and deserialize functions, with the given argument.
1149 * @param method The name of the method to request
1150 * @param serialize The serialization function for inputs
1151 * @param deserialize The deserialization function for outputs
1152 * @param metadata Array of metadata key/value pairs to add to the call
1153 * @param options Options map
1154 * @param callback The callback to for when the response is received
1155 * @return An event emitter for stream related events
1156 */
1157 makeClientStreamRequest<RequestType, ResponseType>(
1158 method: string,
1159 serialize: serialize<RequestType>,
1160 deserialize: deserialize<ResponseType>,
1161 metadata: Metadata | null,
1162 options: CallOptions | null,
1163 callback: requestCallback<ResponseType>,
1164 ): ClientWritableStream<RequestType>;
1165
1166 /**
1167 * Make a server stream request to the given method, with the given serialize
1168 * and deserialize function, using the given argument
1169 * @param method The name of the method to request
1170 * @param serialize The serialization function for inputs
1171 * @param deserialize The deserialization function for outputs
1172 * @param argument The argument to the call. Should be serializable with
1173 * serialize
1174 * @param metadata Array of metadata key/value pairs to add to the call
1175 * @param options Options map
1176 * @return An event emitter for stream related events
1177 */
1178 makeServerStreamRequest<RequestType, ResponseType>(
1179 method: string,
1180 serialize: serialize<RequestType>,
1181 deserialize: deserialize<ResponseType>,
1182 argument: RequestType,
1183 metadata?: Metadata | null,
1184 options?: CallOptions | null,
1185 ): ClientReadableStream<ResponseType>;
1186
1187 /**
1188 * Make a bidirectional stream request with this method on the given channel.
1189 * @param method The name of the method to request
1190 * @param serialize The serialization function for inputs
1191 * @param deserialize The deserialization
1192 * function for outputs
1193 * @param metadata Array of metadata key/value
1194 * pairs to add to the call
1195 * @param options Options map
1196 * @return An event emitter for stream related events
1197 */
1198 makeBidiStreamRequest<RequestType, ResponseType>(
1199 method: string,
1200 serialize: serialize<RequestType>,
1201 deserialize: deserialize<ResponseType>,
1202 metadata?: Metadata | null,
1203 options?: CallOptions | null,
1204 ): ClientDuplexStream<RequestType, ResponseType>;
1205
1206 /**
1207 * Close this client.
1208 */
1209 close(): void;
1210
1211 /**
1212 * Return the underlying channel object for the specified client
1213 * @return The channel
1214 */
1215 getChannel(): Channel;
1216
1217 /**
1218 * Wait for the client to be ready. The callback will be called when the
1219 * client has successfully connected to the server, and it will be called
1220 * with an error if the attempt to connect to the server has unrecoverablly
1221 * failed or if the deadline expires. This function will make the channel
1222 * start connecting if it has not already done so.
1223 * @param deadline When to stop waiting for a connection.
1224 * @param callback The callback to call when done attempting to connect.
1225 */
1226 waitForReady(deadline: Deadline, callback: (error: Error | null) => void): void;
1227 }
1228
1229 /**
1230 * Options that can be set on a call.
1231 */
1232 export interface CallOptions {
1233 /**
1234 * The deadline for the entire call to complete.
1235 */
1236 deadline?: Deadline;
1237 /**
1238 * Server hostname to set on the call. Only meaningful if different from
1239 * the server address used to construct the client.
1240 */
1241 host?: string;
1242 /**
1243 * Parent call. Used in servers when making a call as part of the process
1244 * of handling a call. Used to propagate some information automatically,
1245 * as specified by propagate_flags.
1246 */
1247 parent?: Call;
1248 /**
1249 * Indicates which properties of a parent call should propagate to this
1250 * call. Bitwise combination of flags in `grpc.propagate`.
1251 */
1252 propagate_flags?: number;
1253 /**
1254 * The credentials that should be used to make this particular call.
1255 */
1256 credentials?: CallCredentials;
1257 /**
1258 * Additional custom call options. These can be used to pass additional
1259 * data per-call to client interceptors
1260 */
1261 [key: string]: any;
1262 }
1263
1264 /**
1265 * The deadline of an operation. If it is a date, the deadline is reached at
1266 * the date and time specified. If it is a finite number, it is treated as
1267 * a number of milliseconds since the Unix Epoch. If it is Infinity, the
1268 * deadline will never be reached. If it is -Infinity, the deadline has already
1269 * passed.
1270 */
1271 export type Deadline = number | Date;
1272
1273 /**
1274 * Any client call type
1275 */
1276 type Call =
1277 ClientUnaryCall |
1278 ClientReadableStream<any> |
1279 ClientWritableStream<any> |
1280 ClientDuplexStream<any, any>;
1281
1282 /**
1283 * An EventEmitter. Used for unary calls.
1284 */
1285 export class ClientUnaryCall extends EventEmitter {
1286 private constructor();
1287
1288 /**
1289 * Cancel the ongoing call. Results in the call ending with a CANCELLED status,
1290 * unless it has already ended with some other status.
1291 */
1292 cancel(): void;
1293
1294 /**
1295 * Get the endpoint this call/stream is connected to.
1296 * @return The URI of the endpoint
1297 */
1298 getPeer(): string;
1299 }
1300
1301 /**
1302 * A stream that the client can read from. Used for calls that are streaming
1303 * from the server side.
1304 */
1305 export class ClientReadableStream<ResponseType> extends Readable {
1306 private constructor();
1307
1308 /**
1309 * Cancel the ongoing call. Results in the call ending with a CANCELLED status,
1310 * unless it has already ended with some other status.
1311 */
1312 cancel(): void;
1313
1314 /**
1315 * Get the endpoint this call/stream is connected to.
1316 * @return The URI of the endpoint
1317 */
1318 getPeer(): string;
1319 }
1320
1321 /**
1322 * A stream that the client can write to. Used for calls that are streaming from
1323 * the client side.
1324 */
1325 export class ClientWritableStream<RequestType> extends Writable {
1326 private constructor();
1327
1328 /**
1329 * Write a message to the request stream. If serializing the argument fails,
1330 * the call will be cancelled and the stream will end with an error.
1331 * @param message The message to write. Must be a valid argument to the
1332 * serialize function of the corresponding method
1333 * @param flags Flags to modify how the message is written
1334 * @param callback Callback for when this chunk of data is flushed
1335 * @return As defined for [Writable]{@link external:Writable}
1336 */
1337 write(message: RequestType, flags?: any&writeFlags, callback?: Function): boolean;
1338
1339 /**
1340 * Cancel the ongoing call. Results in the call ending with a CANCELLED status,
1341 * unless it has already ended with some other status.
1342 */
1343 cancel(): void;
1344
1345 /**
1346 * Get the endpoint this call/stream is connected to.
1347 * @return The URI of the endpoint
1348 */
1349 getPeer(): string;
1350 }
1351
1352 /**
1353 * A stream that the client can read from or write to. Used for calls with
1354 * duplex streaming.
1355 */
1356 export class ClientDuplexStream<RequestType, ResponseType> extends Duplex {
1357 private constructor();
1358
1359 /**
1360 * Write a message to the request stream. If serializing the argument fails,
1361 * the call will be cancelled and the stream will end with an error.
1362 * @param message The message to write. Must be a valid argument to the
1363 * serialize function of the corresponding method
1364 * @param flags Flags to modify how the message is written
1365 * @param callback Callback for when this chunk of data is flushed
1366 * @return As defined for [Writable]{@link external:Writable}
1367 */
1368 write(message: RequestType, flags?: any&writeFlags, callback?: Function): boolean;
1369
1370 /**
1371 * Cancel the ongoing call. Results in the call ending with a CANCELLED status,
1372 * unless it has already ended with some other status.
1373 */
1374 cancel(): void;
1375
1376 /**
1377 * Get the endpoint this call/stream is connected to.
1378 * @return The URI of the endpoint
1379 */
1380 getPeer(): string;
1381 }
1382
1383 /**
1384 * Client request callback
1385 * @param error The error, if the call failed
1386 * @param value The response value, if the call succeeded
1387 */
1388 export type requestCallback<ResponseType> =
1389 (error: ServiceError | null, value?: ResponseType) => void;
1390
1391 /**
1392 * Return the underlying channel object for the specified client
1393 * @see grpc.Client#getChannel
1394 * @param client The client
1395 * @return The channel
1396 */
1397 export function getClientChannel(client: Client): Channel;
1398
1399 /**
1400 * Wait for the client to be ready. The callback will be called when the
1401 * client has successfully connected to the server, and it will be called
1402 * with an error if the attempt to connect to the server has unrecoverably
1403 * failed or if the deadline expires. This function will make the channel
1404 * start connecting if it has not already done so.
1405 * @see grpc.Client#waitForReady
1406 * @param client The client to wait on
1407 * @param deadline When to stop waiting for a connection. Pass Infinity to
1408 * wait forever.
1409 * @param callback The callback to call when done attempting to connect.
1410 */
1411 export function waitForClientReady(client: Client, deadline: Deadline, callback: (error: Error | null) => void): void;
1412
1413 /**
1414 * Close client.
1415 * @param clientObj The client to close
1416 */
1417 export function closeClient(clientObj: Client): void;
1418
1419 /**
1420 * A builder for gRPC status objects
1421 */
1422 export class StatusBuilder {
1423 constructor()
1424
1425 /**
1426 * Adds a status code to the builder
1427 * @param code The status code
1428 */
1429 withCode(code: number): this;
1430
1431 /**
1432 * Adds details to the builder
1433 * @param details A status message
1434 */
1435 withDetails(details: string): this;
1436
1437 /**
1438 * Adds metadata to the builder
1439 * @param metadata The gRPC status metadata
1440 */
1441 withMetadata(metadata: Metadata): this;
1442
1443 /**
1444 * Builds the status object
1445 * @return A gRPC status
1446 */
1447 build(): StatusObject;
1448 }
1449
1450 export type MetadataListener = (metadata: Metadata, next: Function) => void;
1451
1452 export type MessageListener = (message: any, next: Function) => void;
1453
1454 export type StatusListener = (status: StatusObject, next: Function) => void;
1455
1456 export interface Listener {
1457 onReceiveMetadata?: MetadataListener;
1458 onReceiveMessage?: MessageListener;
1459 onReceiveStatus?: StatusListener;
1460 }
1461
1462 /**
1463 * A builder for listener interceptors
1464 */
1465 export class ListenerBuilder {
1466 constructor();
1467
1468 /**
1469 * Adds onReceiveMetadata method to the builder
1470 * @param onReceiveMetadata A listener method for receiving metadata
1471 */
1472 withOnReceiveMetadata(onReceiveMetadata: MetadataListener): this;
1473
1474 /**
1475 * Adds onReceiveMessage method to the builder
1476 * @param onReceiveMessage A listener method for receiving message
1477 */
1478 withOnReceiveMessage(onReceiveMessage: MessageListener): this;
1479
1480 /**
1481 * Adds onReceiveStatus method to the builder
1482 * @param onReceiveStatus A listener method for receiving status
1483 */
1484 withOnReceiveStatus(onReceiveStatus: StatusListener): this;
1485
1486 /**
1487 * Builds the call listener
1488 */
1489 build(): Listener;
1490 }
1491
1492 export type MetadataRequester = (metadata: Metadata, listener: Listener, next: Function) => void;
1493
1494 export type MessageRequester = (message: any, next: Function) => void;
1495
1496 export type CloseRequester = (next: Function) => void;
1497
1498 export type CancelRequester = (next: Function) => void;
1499
1500 export type GetPeerRequester = (next: Function) => string;
1501
1502 export interface Requester {
1503 start?: MetadataRequester;
1504 sendMessage?: MessageRequester;
1505 halfClose?: CloseRequester;
1506 cancel?: CancelRequester;
1507 getPeer?: GetPeerRequester;
1508 }
1509
1510 /**
1511 * A builder for the outbound methods of an interceptor
1512 */
1513 export class RequesterBuilder {
1514 constructor();
1515
1516 /**
1517 * Add a metadata requester to the builder
1518 * @param start A requester method for handling metadata
1519 */
1520 withStart(start: MetadataRequester): this;
1521
1522 /**
1523 * Add a message requester to the builder.
1524 * @param sendMessage A requester method for handling
1525 * messages.
1526 */
1527 withSendMessage(sendMessage: MessageRequester): this;
1528
1529 /**
1530 * Add a close requester to the builder.
1531 * @param halfClose A requester method for handling client
1532 * close.
1533 */
1534 withHalfClose(halfClose: CloseRequester): this;
1535
1536 /**
1537 * Add a cancel requester to the builder.
1538 * @param cancel A requester method for handling `cancel`
1539 */
1540 withCancel(cancel: CancelRequester): this;
1541
1542 /**
1543 * Builds the requester's interceptor methods.
1544 */
1545 build(): Requester;
1546 }
1547
1548 /**
1549 * A chainable gRPC call proxy which will delegate to an optional requester
1550 * object. By default, interceptor methods will chain to nextCall. If a
1551 * requester is provided which implements an interceptor method, that
1552 * requester method will be executed as part of the chain.
1553 * operations.
1554 */
1555 export class InterceptingCall {
1556 /**
1557 * @param next_Call The next call in the chain
1558 * @param requester Interceptor methods to handle request
1559 */
1560 constructor(nextCall: InterceptingCall|null, requester?: Requester);
1561
1562 /**
1563 * Starts a call through the outbound interceptor chain and adds an element to
1564 * the reciprocal inbound listener chain.
1565 */
1566 start(metadata: Metadata, listener: Listener): void;
1567
1568 /**
1569 * Pass a message through the interceptor chain.
1570 */
1571 sendMessage(message: any): void;
1572
1573 /**
1574 * Run a close operation through the interceptor chain
1575 */
1576 halfClose(): void;
1577
1578 /**
1579 * Run a cancel operation through the interceptor chain
1580 */
1581 cancel(): void;
1582
1583 /**
1584 * Run a cancelWithStatus operation through the interceptor chain.
1585 * @param status
1586 * @param message
1587 */
1588 cancelWithStatus(status: StatusObject, message: string): void;
1589
1590 /**
1591 * Pass a getPeer call down to the base gRPC call (should not be intercepted)
1592 */
1593 getPeer(): object;
1594
1595 /**
1596 * For streaming calls, we need to transparently pass the stream's context
1597 * through the interceptor chain. Passes the context between InterceptingCalls
1598 * but hides it from any requester implementations.
1599 * @param context Carries objects needed for streaming operations.
1600 * @param message The message to send.
1601 */
1602 sendMessageWithContext(context: object, message: any): void;
1603
1604 /**
1605 * For receiving streaming messages, we need to seed the base interceptor with
1606 * the streaming context to create a RECV_MESSAGE batch.
1607 * @param context Carries objects needed for streaming operations
1608 */
1609 recvMessageWithContext(context: object): void;
1610 }
1611 export enum connectivityState {
1612 IDLE = 0,
1613 CONNECTING = 1,
1614 READY = 2,
1615 TRANSIENT_FAILURE = 3,
1616 SHUTDOWN = 4
1617 }
1618
1619 export class Channel {
1620 /**
1621 * This constructor API is almost identical to the Client constructor,
1622 * except that some of the options for the Client constructor are not valid
1623 * here.
1624 * @param target The address of the server to connect to
1625 * @param credentials Channel credentials to use when connecting
1626 * @param options A map of channel options that will be passed to the core
1627 */
1628 constructor(target: string, credentials: ChannelCredentials, options: {[key:string]: string|number});
1629 /**
1630 * Close the channel. This has the same functionality as the existing grpc.Client.prototype.close
1631 */
1632 close(): void;
1633 /**
1634 * Return the target that this channel connects to
1635 */
1636 getTarget(): string;
1637 /**
1638 * Get the channel's current connectivity state.
1639 * @param tryToConnect If true, the channel will start connecting if it is
1640 * idle. Otherwise, idle channels will only start connecting when a
1641 * call starts.
1642 */
1643 getConnectivityState(tryToConnect: boolean): connectivityState;
1644 /**
1645 * Watch for connectivity state changes.
1646 * @param currentState The state to watch for transitions from. This should
1647 * always be populated by calling getConnectivityState immediately
1648 * before.
1649 * @param deadline A deadline for waiting for a state change
1650 * @param callback Called with no error when a state change, or with an
1651 * error if the deadline passes without a state change.
1652 */
1653 watchConnectivityState(currentState: connectivityState, deadline: Date|number, callback: (error?: Error) => void): void;
1654 /**
1655 * Create a call object. Call is an opaque type that is used by the Client
1656 * and Server classes. This function is called by the gRPC library when
1657 * starting a request. Implementers should return an instance of Call that
1658 * is returned from calling createCall on an instance of the provided
1659 * Channel class.
1660 * @param method The full method string to request.
1661 * @param deadline The call deadline
1662 * @param host A host string override for making the request
1663 * @param parentCall A server call to propagate some information from
1664 * @param propagateFlags A bitwise combination of elements of grpc.propagate
1665 * that indicates what information to propagate from parentCall.
1666 */
1667 createCall(method: string, deadline: Date|number, host: string|null, parentCall: Call|null, propagateFlags: number|null): Call;
1668 }
1669}