3 * Copyright 2019 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 /// <reference types="bytebuffer" />
21 declare 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";
27 /* The Message interface is copied and slightly modified from @types/protobuf
28 * version 5.0.31, which was distributed under the following license:
30 * This project is licensed under the MIT license.
31 * Copyrights are respective of each contributor listed at the beginning of each definition file.
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:
35 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
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.
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;
45 encode(buffer?: ByteBuffer | boolean, noVerify?: boolean): ByteBuffer;
47 encodeAB(): ArrayBuffer;
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;
58 toRaw(binaryAsBase64?: boolean, longsAsStrings?: boolean): {[key: string]: any};
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.
69 export function loadObject<T = GrpcObject>(value: object, options?: LoadObjectOptions): T;
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.
78 export interface LoadObjectOptions {
80 * Deserialize bytes values as base64 strings instead of Buffers.
81 * Defaults to `false`.
83 binaryAsBase64?: boolean;
86 * Deserialize long values as strings instead of objects.
89 longsAsStrings?: boolean;
92 * Deserialize enum values as strings instead of numbers. Only works with
93 * Protobuf.js 6 values.
96 enumsAsStrings?: boolean;
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
103 * Defaults to `false`
105 deprecatedArgumentOrder?: boolean;
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
113 protobufjsVersion?: 5 | 6 | "detect";
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
125 export interface GrpcObject {
126 [name: string]: GrpcObject | typeof Client | ProtobufMessage;
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
136 export function load<T = GrpcObject>(filename: Filename, format?: "proto" | "json", options?: LoadOptions): T;
139 * Load a gRPC package definition as a gRPC object hierarchy
140 * @param packageDef The package definition object
141 * @return The resulting gRPC object
143 export function loadPackageDefinition(packageDefinition: PackageDefinition): GrpcObject;
148 export type Filename = string | { root: string, file: string };
151 * Options for loading proto file as gRPC object
153 export interface LoadOptions {
155 * Load this file with field names in camel case instead of their original case.
156 * Defaults to `false`.
158 convertFieldsToCamelCase?: boolean;
161 * Deserialize bytes values as base64 strings instead of Buffers.
162 * Defaults to `false`.
164 binaryAsBase64?: boolean;
167 * Deserialize long values as strings instead of objects.
168 * Defaults to `true`.
170 longsAsStrings?: boolean;
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
177 * Defaults to `false`
179 deprecatedArgumentOrder?: boolean;
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.
190 export function setLogger(logger: Console): void;
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
197 export function setLogVerbosity(verbosity: logVerbosity): void;
200 * Server object that stores request handlers and delegates incoming requests to those handlers
202 export class Server {
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
209 * var server = new grpc.Server();
210 * server.addProtoService(protobuf_service_descriptor, service_implementation);
211 * server.bind('address:port', server_credential);
215 constructor(options?: object);
218 * Start the server and begin handling requests
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
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
235 register<RequestType, ResponseType>(
237 handler: handleCall<RequestType, ResponseType>,
238 serialize: serialize<ResponseType>,
239 deserialize: deserialize<RequestType>,
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
250 tryShutdown(callback: () => void): void;
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.
258 forceShutdown(): void;
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.
266 addService<ImplementationType = UntypedServiceImplementation>(
267 service: ServiceDefinition<ImplementationType>,
268 implementation: ImplementationType
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.
278 addProtoService<ImplementationType = UntypedServiceImplementation>(
279 service: ServiceDefinition<ImplementationType>,
280 implementation: ImplementationType
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
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.
292 bind(port: string, creds: ServerCredentials): number;
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.
304 bindAsync(port: string, creds: ServerCredentials, callback: (error: Error | null, port: number) => void): void;
308 * A type that servers as a default for an untyped service.
310 export type UntypedServiceImplementation = { [name: string]: handleCall<any, any> };
313 * An object that completely defines a service.
315 export type ServiceDefinition<ImplementationType> = {
316 readonly [I in keyof ImplementationType]: MethodDefinition<any, any>;
320 * An object that defines a protobuf type
322 export interface ProtobufTypeDefinition {
325 fileDescriptorProtos: Buffer[];
329 * An object that defines a package containing multiple services
331 export type PackageDefinition = {
332 readonly [fullyQualifiedName: string]: ServiceDefinition<any> | ProtobufTypeDefinition;
336 * An object that completely defines a service method signature.
338 export interface MethodDefinition<RequestType, ResponseType> {
340 * The method's URL path
344 * Indicates whether the method accepts a stream of requests
346 requestStream: boolean;
348 * Indicates whether the method returns a stream of responses
350 responseStream: boolean;
352 * Serialization function for request values
354 requestSerialize: serialize<RequestType>;
356 * Serialization function for response values
358 responseSerialize: serialize<ResponseType>;
360 * Deserialization function for request data
362 requestDeserialize: deserialize<RequestType>;
364 * Deserialization function for repsonse data
366 responseDeserialize: deserialize<ResponseType>;
369 type handleCall<RequestType, ResponseType> =
370 handleUnaryCall<RequestType, ResponseType> |
371 handleClientStreamingCall<RequestType, ResponseType> |
372 handleServerStreamingCall<RequestType, ResponseType> |
373 handleBidiStreamingCall<RequestType, ResponseType>;
376 * User-provided method to handle unary requests on a server
378 type handleUnaryCall<RequestType, ResponseType> =
379 (call: ServerUnaryCall<RequestType>, callback: sendUnaryData<ResponseType>) => void;
382 * An EventEmitter. Used for unary calls.
384 export class ServerUnaryCall<RequestType> extends EventEmitter {
386 * Indicates if the call has been cancelled
391 * The request metadata from the client
396 * The request message from the client
398 request: RequestType;
400 private constructor();
403 * Get the endpoint this call/stream is connected to.
404 * @return The URI of the endpoint
409 * Send the initial metadata for a writable stream.
410 * @param responseMetadata Metadata to send
412 sendMetadata(responseMetadata: Metadata): void;
416 * User provided method to handle client streaming methods on the server.
418 type handleClientStreamingCall<RequestType, ResponseType> =
419 (call: ServerReadableStream<RequestType>, callback: sendUnaryData<ResponseType>) => void;
422 * A stream that the server can read from. Used for calls that are streaming
423 * from the client side.
425 export class ServerReadableStream<RequestType> extends Readable {
427 * Indicates if the call has been cancelled
432 * The request metadata from the client
436 private constructor();
439 * Get the endpoint this call/stream is connected to.
440 * @return The URI of the endpoint
445 * Send the initial metadata for a writable stream.
446 * @param responseMetadata Metadata to send
448 sendMetadata(responseMetadata: Metadata): void;
452 * User provided method to handle server streaming methods on the server.
454 type handleServerStreamingCall<RequestType, ResponseType> =
455 (call: ServerWritableStream<RequestType, ResponseType>) => void;
458 * A stream that the server can write to. Used for calls that are streaming
459 * from the server side.
461 export class ServerWritableStream<RequestType, ResponseType=unknown> extends Writable {
463 * Indicates if the call has been cancelled
468 * The request metadata from the client
473 * The request message from the client
475 request: RequestType;
477 private constructor();
480 * Get the endpoint this call/stream is connected to.
481 * @return The URI of the endpoint
486 * Send the initial metadata for a writable stream.
487 * @param responseMetadata Metadata to send
489 sendMetadata(responseMetadata: Metadata): void;
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>;
497 * User provided method to handle bidirectional streaming calls on the server.
499 type handleBidiStreamingCall<RequestType, ResponseType> =
500 (call: ServerDuplexStream<RequestType, ResponseType>) => void;
503 * A stream that the server can read from or write to. Used for calls
504 * with duplex streaming.
506 export class ServerDuplexStream<RequestType, ResponseType> extends Duplex {
508 * Indicates if the call has been cancelled
513 * The request metadata from the client
517 private constructor();
520 * Get the endpoint this call/stream is connected to.
521 * @return The URI of the endpoint
526 * Send the initial metadata for a writable stream.
527 * @param responseMetadata Metadata to send
529 sendMetadata(responseMetadata: Metadata): void;
533 * A deserialization function
534 * @param data The byte sequence to deserialize
535 * @return The data deserialized as a value
537 type deserialize<T> = (data: Buffer) => T;
540 * A serialization function
541 * @param value The value to serialize
542 * @return The value serialized as a byte sequence
544 type serialize<T> = (value: T) => Buffer;
547 * Callback function passed to server handlers that handle methods with
550 type sendUnaryData<ResponseType> =
551 (error: ServiceError | null, value: ResponseType | null, trailer?: Metadata, flags?: number) => void;
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. */
567 * A class for storing metadata. Keys are normalized to lowercase ASCII.
569 export class Metadata {
571 * @param options Boolean options for the beginning of the call.
572 * These options only have any effect when passed at the beginning of
575 constructor(options?: MetadataOptions);
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'.
583 set(key: string, value: MetadataValue): void;
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'.
592 add(key: string, value: MetadataValue): void;
595 * Removes the given key and any associated values. Normalizes the key.
596 * @param key The key whose values should be removed.
598 remove(key: string): void;
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.
605 get(key: string): MetadataValue[];
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.
612 getMap(): { [key: string]: MetadataValue };
615 * Clones the metadata object.
616 * @return The newly cloned object.
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
626 setOptions(options: MetadataOptions): void;
629 export type MetadataValue = string | Buffer;
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.
638 export interface StatusObject {
640 * The error code, a key of `grpc.status`
644 * Human-readable description of the status
648 * Trailing metadata sent with the status, if applicable
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.
658 export interface ServiceError extends Error {
660 * The error code, a key of {@link grpc.status} that is not `grpc.status.OK`
664 * Trailing metadata sent with the status, if applicable
668 * Original status details string
674 * ServerCredentials factories
676 export class ServerCredentials {
678 * Create insecure server credentials
679 * @return The ServerCredentials
681 static createInsecure(): ServerCredentials;
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
692 static createSsl(rootCerts: Buffer | null, keyCertPairs: KeyCertPair[], checkClientCertificate?: boolean): ServerCredentials;
696 * A private key and certificate pair
698 export interface KeyCertPair {
700 * The server's private key
705 * The server's certificate chain
711 * Enum of status codes that gRPC can return
715 * Not an error; returned on success
719 * The operation was cancelled (typically by the caller).
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.
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).
736 INVALID_ARGUMENT = 3,
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.
744 DEADLINE_EXCEEDED = 4,
746 * Some requested entity (e.g., file or directory) was not found.
750 * Some entity that we attempted to create (e.g., file or directory)
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).
762 PERMISSION_DENIED = 7,
764 * Some resource has been exhausted, perhaps a per-user quota, or
765 * perhaps the entire file system is out of space.
767 RESOURCE_EXHAUSTED = 8,
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.
774 * A litmus test that may help a service implementor in deciding
775 * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
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.
790 FAILED_PRECONDITION = 9,
792 * The operation was aborted, typically due to a concurrency issue
793 * like sequencer check failures, transaction aborts, etc.
795 * See litmus test above for deciding between FAILED_PRECONDITION,
796 * ABORTED, and UNAVAILABLE.
800 * Operation was attempted past the valid range. E.g., seeking or
801 * reading past end of file.
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
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
818 * Operation is not implemented or not supported/enabled in this service.
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.
828 * The service is currently unavailable. This is a most likely a
829 * transient condition and may be corrected by retrying with
832 * See litmus test above for deciding between FAILED_PRECONDITION,
833 * ABORTED, and UNAVAILABLE.
837 * Unrecoverable data loss or corruption.
841 * The request does not have valid authentication credentials for the
844 UNAUTHENTICATED = 16,
848 * Propagation flags: these can be bitwise or-ed to form the propagation option
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.
855 export enum propagate {
857 CENSUS_STATS_CONTEXT,
858 CENSUS_TRACING_CONTEXT,
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.
867 export enum callError {
879 NOT_SERVER_COMPLETION_QUEUE,
881 PAYLOAD_TYPE_MISMATCH,
885 * Write flags: these can be bitwise or-ed to form write options that modify
886 * how data is written.
888 export enum writeFlags {
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.
896 * Force compression to be disabled for a particular write
902 * Log verbosity constants. Maps setting names to code numbers.
904 export enum logVerbosity {
911 * Method type constants
913 export enum methodTypes {
922 * A certificate as received by the checkServerIdentity callback.
924 export interface Certificate {
926 * The raw certificate in DER form.
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.
937 export type CheckServerIdentityCallback = (hostname: string, cert: Certificate) => Error | undefined;
940 * Additional peer verification options that can be set when creating
943 export interface VerifyOptions {
945 * If set, this callback will be invoked after the usual hostname verification
946 * has been performed on the peer certificate.
948 checkServerIdentity?: CheckServerIdentityCallback;
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.
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.
965 * For example, to create a client secured with SSL that uses Google
966 * default application credentials to authenticate:
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);
978 export const credentials: {
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
988 createSsl(rootCerts?: Buffer, privateKey?: Buffer, certChain?: Buffer, verifyOptions?: VerifyOptions): ChannelCredentials;
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
998 createFromMetadataGenerator(metadataGenerator: metadataGenerator): CallCredentials;
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
1005 createFromGoogleCredential(googleCredential: GoogleOAuth2Client): CallCredentials;
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
1014 combineChannelCredentials(channelCredential: ChannelCredentials, ...credentials: CallCredentials[]): ChannelCredentials;
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
1021 combineCallCredentials(...credentials: CallCredentials[]): CallCredentials;
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
1028 createInsecure(): ChannelCredentials;
1032 * Metadata generator function.
1034 export type metadataGenerator = (params: { service_url: string }, callback: (error: Error | null, metadata?: Metadata) => void) => void;
1037 * This cannot be constructed directly. Instead, instances of this class should
1038 * be created using the factory functions in `grpc.credentials`
1040 export interface ChannelCredentials {
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
1047 compose(callCredentials: CallCredentials): ChannelCredentials;
1051 * This cannot be constructed directly. Instead, instances of this class should
1052 * be created using the factory functions in `grpc.credentials`
1054 export interface CallCredentials {
1056 * Asynchronously generates a new Metadata object.
1057 * @param options Options used in generating the Metadata object.
1059 generateMetadata(options: object): Promise<Metadata>;
1062 * Creates a new CallCredentials object from properties of both this and
1063 * another CallCredentials object. This object's metadata generator will be
1065 * @param callCredentials The other CallCredentials object.
1067 compose(callCredentials: CallCredentials): CallCredentials;
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`
1075 export interface GoogleOAuth2Client {
1076 getRequestMetadata(optUri: string, metadataCallback: (err: Error, headers: any) => void): void;
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.
1092 export function makeGenericClientConstructor(
1093 methods: ServiceDefinition<any>,
1094 serviceName: string,
1095 classOptions: GenericClientOptions,
1099 * Options for generic client constructor.
1101 export interface GenericClientOptions {
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.
1108 deprecatedArgumentOrder?: boolean;
1112 * Create a client with the given methods
1114 export class Client {
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
1121 constructor(address: string, credentials: ChannelCredentials, options?: object)
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
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
1136 makeUnaryRequest<RequestType, ResponseType>(
1138 serialize: serialize<RequestType>,
1139 deserialize: deserialize<ResponseType>,
1140 argument: RequestType | null,
1141 metadata: Metadata | null,
1142 options: CallOptions | null,
1143 callback: requestCallback<ResponseType>,
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
1157 makeClientStreamRequest<RequestType, ResponseType>(
1159 serialize: serialize<RequestType>,
1160 deserialize: deserialize<ResponseType>,
1161 metadata: Metadata | null,
1162 options: CallOptions | null,
1163 callback: requestCallback<ResponseType>,
1164 ): ClientWritableStream<RequestType>;
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
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
1178 makeServerStreamRequest<RequestType, ResponseType>(
1180 serialize: serialize<RequestType>,
1181 deserialize: deserialize<ResponseType>,
1182 argument: RequestType,
1183 metadata?: Metadata | null,
1184 options?: CallOptions | null,
1185 ): ClientReadableStream<ResponseType>;
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
1198 makeBidiStreamRequest<RequestType, ResponseType>(
1200 serialize: serialize<RequestType>,
1201 deserialize: deserialize<ResponseType>,
1202 metadata?: Metadata | null,
1203 options?: CallOptions | null,
1204 ): ClientDuplexStream<RequestType, ResponseType>;
1207 * Close this client.
1212 * Return the underlying channel object for the specified client
1213 * @return The channel
1215 getChannel(): Channel;
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.
1226 waitForReady(deadline: Deadline, callback: (error: Error | null) => void): void;
1230 * Options that can be set on a call.
1232 export interface CallOptions {
1234 * The deadline for the entire call to complete.
1236 deadline?: Deadline;
1238 * Server hostname to set on the call. Only meaningful if different from
1239 * the server address used to construct the client.
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.
1249 * Indicates which properties of a parent call should propagate to this
1250 * call. Bitwise combination of flags in `grpc.propagate`.
1252 propagate_flags?: number;
1254 * The credentials that should be used to make this particular call.
1256 credentials?: CallCredentials;
1258 * Additional custom call options. These can be used to pass additional
1259 * data per-call to client interceptors
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
1271 export type Deadline = number | Date;
1274 * Any client call type
1278 ClientReadableStream<any> |
1279 ClientWritableStream<any> |
1280 ClientDuplexStream<any, any>;
1283 * An EventEmitter. Used for unary calls.
1285 export class ClientUnaryCall extends EventEmitter {
1286 private constructor();
1289 * Cancel the ongoing call. Results in the call ending with a CANCELLED status,
1290 * unless it has already ended with some other status.
1295 * Get the endpoint this call/stream is connected to.
1296 * @return The URI of the endpoint
1302 * A stream that the client can read from. Used for calls that are streaming
1303 * from the server side.
1305 export class ClientReadableStream<ResponseType> extends Readable {
1306 private constructor();
1309 * Cancel the ongoing call. Results in the call ending with a CANCELLED status,
1310 * unless it has already ended with some other status.
1315 * Get the endpoint this call/stream is connected to.
1316 * @return The URI of the endpoint
1322 * A stream that the client can write to. Used for calls that are streaming from
1325 export class ClientWritableStream<RequestType> extends Writable {
1326 private constructor();
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}
1337 write(message: RequestType, flags?: any&writeFlags, callback?: Function): boolean;
1340 * Cancel the ongoing call. Results in the call ending with a CANCELLED status,
1341 * unless it has already ended with some other status.
1346 * Get the endpoint this call/stream is connected to.
1347 * @return The URI of the endpoint
1353 * A stream that the client can read from or write to. Used for calls with
1356 export class ClientDuplexStream<RequestType, ResponseType> extends Duplex {
1357 private constructor();
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}
1368 write(message: RequestType, flags?: any&writeFlags, callback?: Function): boolean;
1371 * Cancel the ongoing call. Results in the call ending with a CANCELLED status,
1372 * unless it has already ended with some other status.
1377 * Get the endpoint this call/stream is connected to.
1378 * @return The URI of the endpoint
1384 * Client request callback
1385 * @param error The error, if the call failed
1386 * @param value The response value, if the call succeeded
1388 export type requestCallback<ResponseType> =
1389 (error: ServiceError | null, value?: ResponseType) => void;
1392 * Return the underlying channel object for the specified client
1393 * @see grpc.Client#getChannel
1394 * @param client The client
1395 * @return The channel
1397 export function getClientChannel(client: Client): Channel;
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
1409 * @param callback The callback to call when done attempting to connect.
1411 export function waitForClientReady(client: Client, deadline: Deadline, callback: (error: Error | null) => void): void;
1415 * @param clientObj The client to close
1417 export function closeClient(clientObj: Client): void;
1420 * A builder for gRPC status objects
1422 export class StatusBuilder {
1426 * Adds a status code to the builder
1427 * @param code The status code
1429 withCode(code: number): this;
1432 * Adds details to the builder
1433 * @param details A status message
1435 withDetails(details: string): this;
1438 * Adds metadata to the builder
1439 * @param metadata The gRPC status metadata
1441 withMetadata(metadata: Metadata): this;
1444 * Builds the status object
1445 * @return A gRPC status
1447 build(): StatusObject;
1450 export type MetadataListener = (metadata: Metadata, next: Function) => void;
1452 export type MessageListener = (message: any, next: Function) => void;
1454 export type StatusListener = (status: StatusObject, next: Function) => void;
1456 export interface Listener {
1457 onReceiveMetadata?: MetadataListener;
1458 onReceiveMessage?: MessageListener;
1459 onReceiveStatus?: StatusListener;
1463 * A builder for listener interceptors
1465 export class ListenerBuilder {
1469 * Adds onReceiveMetadata method to the builder
1470 * @param onReceiveMetadata A listener method for receiving metadata
1472 withOnReceiveMetadata(onReceiveMetadata: MetadataListener): this;
1475 * Adds onReceiveMessage method to the builder
1476 * @param onReceiveMessage A listener method for receiving message
1478 withOnReceiveMessage(onReceiveMessage: MessageListener): this;
1481 * Adds onReceiveStatus method to the builder
1482 * @param onReceiveStatus A listener method for receiving status
1484 withOnReceiveStatus(onReceiveStatus: StatusListener): this;
1487 * Builds the call listener
1492 export type MetadataRequester = (metadata: Metadata, listener: Listener, next: Function) => void;
1494 export type MessageRequester = (message: any, next: Function) => void;
1496 export type CloseRequester = (next: Function) => void;
1498 export type CancelRequester = (next: Function) => void;
1500 export type GetPeerRequester = (next: Function) => string;
1502 export interface Requester {
1503 start?: MetadataRequester;
1504 sendMessage?: MessageRequester;
1505 halfClose?: CloseRequester;
1506 cancel?: CancelRequester;
1507 getPeer?: GetPeerRequester;
1511 * A builder for the outbound methods of an interceptor
1513 export class RequesterBuilder {
1517 * Add a metadata requester to the builder
1518 * @param start A requester method for handling metadata
1520 withStart(start: MetadataRequester): this;
1523 * Add a message requester to the builder.
1524 * @param sendMessage A requester method for handling
1527 withSendMessage(sendMessage: MessageRequester): this;
1530 * Add a close requester to the builder.
1531 * @param halfClose A requester method for handling client
1534 withHalfClose(halfClose: CloseRequester): this;
1537 * Add a cancel requester to the builder.
1538 * @param cancel A requester method for handling `cancel`
1540 withCancel(cancel: CancelRequester): this;
1543 * Builds the requester's interceptor methods.
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.
1555 export class InterceptingCall {
1557 * @param next_Call The next call in the chain
1558 * @param requester Interceptor methods to handle request
1560 constructor(nextCall: InterceptingCall|null, requester?: Requester);
1563 * Starts a call through the outbound interceptor chain and adds an element to
1564 * the reciprocal inbound listener chain.
1566 start(metadata: Metadata, listener: Listener): void;
1569 * Pass a message through the interceptor chain.
1571 sendMessage(message: any): void;
1574 * Run a close operation through the interceptor chain
1579 * Run a cancel operation through the interceptor chain
1584 * Run a cancelWithStatus operation through the interceptor chain.
1588 cancelWithStatus(status: StatusObject, message: string): void;
1591 * Pass a getPeer call down to the base gRPC call (should not be intercepted)
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.
1602 sendMessageWithContext(context: object, message: any): void;
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
1609 recvMessageWithContext(context: object): void;
1611 export enum connectivityState {
1615 TRANSIENT_FAILURE = 3,
1619 export class Channel {
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
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
1628 constructor(target: string, credentials: ChannelCredentials, options: {[key:string]: string|number});
1630 * Close the channel. This has the same functionality as the existing grpc.Client.prototype.close
1634 * Return the target that this channel connects to
1636 getTarget(): string;
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
1643 getConnectivityState(tryToConnect: boolean): connectivityState;
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
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.
1653 watchConnectivityState(currentState: connectivityState, deadline: Date|number, callback: (error?: Error) => void): void;
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
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.
1667 createCall(method: string, deadline: Date|number, host: string|null, parentCall: Call|null, propagateFlags: number|null): Call;