fix(typescript): don't define custom types for grpc

This commit is contained in:
Mark Dietzer 2019-12-04 11:00:04 -08:00 коммит произвёл GitHub
Родитель af1242283f 2a398f1463
Коммит 0ffcec9676
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
7 изменённых файлов: 35 добавлений и 300 удалений

8
docker-compose.yml Normal file
Просмотреть файл

@ -0,0 +1,8 @@
version: '3.6'
services:
etcd:
build:
context: .
ports:
- 2379:2379
- 2380:2380

Просмотреть файл

@ -30,6 +30,15 @@ Our [TypeDoc docs are available here](https://mixer.github.io/etcd3/classes/inde
Our [test cases](https://github.com/mixer/etcd3/blob/master/test/) are also quite readable.
### Running tests
```sh
$ npm install
$ docker-compose up
$ npm test
$ docker-compose down
```
### Contributing
Running tests for this module requires running an etcd3 server locally. The tests try to use the default port initially, and you can configure this by setting the `ETCD_ADDR` environment variable, like `export ETCD_ADDR=localhost:12345`.# Contributing

Просмотреть файл

@ -3,6 +3,7 @@ import * as grpc from 'grpc';
import { ExponentialBackoff } from './backoff/exponential';
import { castGrpcError, EtcdInvalidAuthTokenError, GRPCGenericError } from './errors';
import { ChannelOptions } from './grpcTypes';
import { IOptions } from './options';
import { ICallable, Services } from './rpc';
import { SharedPool } from './shared-pool';
@ -16,6 +17,7 @@ const packageDefinition = loadSync(`${__dirname}/../proto/rpc.proto`, {
oneofs: true,
});
const services = grpc.loadPackageDefinition(packageDefinition);
const etcdserverpb = services.etcdserverpb as { [service: string]: typeof grpc.Client };
export const defaultBackoffStrategy = new ExponentialBackoff({
initial: 300,
@ -120,7 +122,7 @@ class Authenticator {
credentials: grpc.ChannelCredentials,
): Promise<string> {
return runServiceCall(
new services.etcdserverpb.Auth(address, credentials),
new etcdserverpb.Auth(address, credentials),
new grpc.Metadata(),
undefined,
'authenticate',
@ -141,7 +143,7 @@ export class Host {
constructor(
host: string,
private readonly channelCredentials: grpc.ChannelCredentials,
private readonly channelOptions?: grpc.ChannelOptions,
private readonly channelOptions?: ChannelOptions,
) {
this.host = removeProtocolPrefix(host);
}
@ -155,7 +157,7 @@ export class Host {
return service;
}
const newService = new services.etcdserverpb[name](
const newService = new etcdserverpb[name](
this.host,
this.channelCredentials,
this.channelOptions,

Просмотреть файл

@ -1,302 +1,9 @@
/* tslint:disable */
import { PackageDefinition } from '@grpc/proto-loader';
import { Duplex, Readable, Writable } from 'stream';
export class ChannelCredentials {
private constructor();
}
export class CallCredentials {
private constructor();
}
export class Service {
private constructor();
}
/**
* The deadline of an operation. If it is a date, the deadline is reached at
* the date and time specified. If it is a finite number, it is treated as
* a number of milliseconds since the Unix Epoch. If it is Infinity, the
* deadline will never be reached. If it is -Infinity, the deadline has already
* passed.
*/
export type Deadline = number | Date;
/**
* Options that can be set on a call.
*/
export interface CallOptions {
/**
* The deadline for the entire call to complete.
*/
deadline?: Deadline;
/**
* Server hostname to set on the call. Only meaningful if different from
* the server address used to construct the client.
*/
host?: string;
/**
* Indicates which properties of a parent call should propagate to this
* call. Bitwise combination of flags in `grpc.propagate`.
*/
propagate_flags: number;
/**
* The credentials that should be used to make this particular call.
*/
credentials: CallCredentials;
}
/**
* Describes some generic GRPC call or service function. This is super generic,
* you'll probably want to override or cast these based on your specific typing.
*/
export type grpcCall =
// Simple GRPC call, one request and one response.
| ((args: object, callback: (err: Error | null, result: any) => void) => void)
// A readable stream call, where a request is made with one set of args.
| ((args: object) => Readable)
// A writeable stream call, where the client can write many data points
// to the stream and await a single response from the server.
| ((callback: (err: Error | null, result: any) => void) => Writable)
// A duplex stream, where both the client and server send asynchronous calls.
| (() => Duplex);
/**
* Describes a handle to a GRPC client, returned from load(). Note that other
* methods will be defined on the client per the protobuf definitions, but
* these cannot be typed here.
*/
export class Client {
/**
* Creates a new instance of the client.
*/
constructor(address: string, credentials: ChannelCredentials, options?: ChannelOptions);
/**
* The Service associated with the client, used for creating GRPC servers.
*/
service: Service;
}
export class Server {
/**
* Add a proto service to the server, with a corresponding implementation.
*/
addService(service: Service, implementations: { [method: string]: grpcCall }): void;
/**
* Binds the server to the given port, with SSL enabled if credentials are given.
*/
bind(port: string, credentials: ChannelCredentials): void;
/**
* Forcibly shuts down the server. The server will stop receiving new calls
* and cancel all pending calls. When it returns, the server has shut down.
* This method is idempotent with itself and tryShutdown, and it will trigger
* any outstanding tryShutdown callbacks.
*/
forceShutdown(): void;
/**
* Start the server and begin handling requests.
*/
start(): void;
/**
* Gracefully shuts down the server. The server will stop receiving new
* calls, and any pending calls will complete. The callback will be called
* when all pending calls have completed and the server is fully shut down.
* This method is idempotent with itself and forceShutdown.
*/
tryShutdown(callback: () => void): void;
}
export interface LoadOptions {
/**
* Load this file with field names in camel case instead of their
* original case. Defaults to false.
*/
convertFieldsToCamelCase?: boolean;
/**
* Deserialize bytes values as base64 strings instead of Buffers.
* Defaults to false.
*/
binaryAsBase64?: boolean;
/**
* Deserialize long values as strings instead of objects. Defaults to true.
*/
longsAsStrings?: boolean;
/**
* Deserialize enum values as strings instead of numbers. Defaults to true.
*/
enumsAsStrings?: boolean;
/**
* Use the beta method argument order for client methods, with optional
* arguments after the callback. Defaults to false. This option is only a
* temporary stopgap measure to smooth an API breakage. It is deprecated,
* and new code should not use it.
*/
deprecatedArgumentOrder?: boolean;
}
/**
* Load a gRPC object from a .proto file.
*/
export function load(
filename: string,
format?: 'proto' | 'json',
options?: LoadOptions,
): { [namespace: string]: { [service: string]: typeof Client } };
/**
* Load a gRPC package definition as a gRPC object hierarchy
* @param packageDef The package definition object
* @return The resulting gRPC object
*/
export function loadPackageDefinition(
packageDefinition: PackageDefinition,
): { [namespace: string]: { [service: string]: typeof Client } };
/**
* Tears down a GRPC client.
*/
export function closeClient(client: Client): void;
/**
* Runs the callback after the connection is established.
*/
export function waitForClientRead(
client: Client,
deadline: Date | Number,
callback: (err: Error | null) => void,
): void;
/**
* Class for storing metadata. Keys are normalized to lowercase ASCII.
*/
export class Metadata {
/**
* Adds the given value for the given key. Normalizes the key.
*/
add(key: string, value: string | Buffer): void;
/**
* Sets the given value for the given key, replacing any other values
* associated with that key. Normalizes the key.
*/
set(key: string, value: string | Buffer): void;
/**
* Sets the given value for the given key, replacing any other values
* associated with that key. Normalizes the key.
*/
remove(key: string): void;
/**
* Clone the metadata object.
*/
clone(): Metadata;
/**
* Gets a list of all values associated with the key. Normalizes the key.
*/
get(key: string): (string | Buffer)[];
/**
* Get a map of each key to a single associated value. This reflects
* the most common way that people will want to see metadata.
*/
getMap(): { [key: string]: string | Buffer };
}
export namespace credentials {
/**
* Create an insecure credentials object. This is used to create a channel
* that does not use SSL. This cannot be composed with anything.
*/
export function createInsecure(): CallCredentials;
/**
* Create an SSL Credentials object. If using a client-side certificate, both
* the second and third arguments must be passed.
*/
export function createSsl(
rootCerts?: Buffer,
privateKey?: Buffer,
certChain?: Buffer,
): CallCredentials;
/**
* Combine any number of CallCredentials into a single CallCredentials object.
*/
export function combineCallCredentials(...credentials: CallCredentials[]): CallCredentials;
/**
* Combine a ChannelCredentials with any number of CallCredentials into a
* single ChannelCredentials object.
*/
export function combineChannelCredentials(
channelCredential: ChannelCredentials,
...callCredentials: CallCredentials[]
): ChannelCredentials;
/**
* Create a gRPC credential from a Google credential object.
* todo(connor4312): type
*/
export function createFromGoogleCredential(googleCredential: any): CallCredentials;
/**
* IMetadataGenerator can be passed into createFromMetadataGenerator.
*/
export interface IMetadataGenerator {
(
target: { service_url: string },
callback: (error: Error | null, metadata?: Metadata) => void,
): void;
}
/**
* Create a gRPC credential from a Google credential object.
* todo(connor4312): type
*/
export function createFromMetadataGenerator(generator: IMetadataGenerator): CallCredentials;
}
export const status: Readonly<{
OK: 0;
CANCELLED: 1;
UNKNOWN: 2;
INVALID_ARGUMENT: 3;
DEADLINE_EXCEEDED: 4;
NOT_FOUND: 5;
ALREADY_EXISTS: 6;
PERMISSION_DENIED: 7;
RESOURCE_EXHAUSTED: 8;
FAILED_PRECONDITION: 9;
ABORTED: 10;
OUT_OF_RANGE: 11;
UNIMPLEMENTED: 12;
INTERNAL: 13;
UNAVAILABLE: 14;
DATA_LOSS: 15;
UNAUTHENTICATED: 16;
}>;
export interface StatusMessage {
code: number;
details: string;
metadata: Metadata;
}
import * as grpc from 'grpc';
/**
* ChannelOptions may be passed into the Client to configure GRPC internals.
*/
// tslint:disable-next-line: interface-name
export interface ChannelOptions {
/**
* If non-zero, allow the use of SO_REUSEPORT if it's available (default 1)
@ -628,3 +335,10 @@ export interface ChannelOptions {
*/
'grpc.ssl_target_name_override'?: string;
}
// tslint:disable-next-line: interface-name
export interface StatusMessage {
code: number;
details: string;
metadata: grpc.Metadata;
}

Просмотреть файл

@ -14,6 +14,7 @@ export * from './options';
export * from './range';
export * from './rpc';
export * from './stm';
export * from './grpcTypes';
export { WatchBuilder, Watcher } from './watch';
/**

Просмотреть файл

@ -1,4 +1,4 @@
import { ChannelOptions } from 'grpc';
import { ChannelOptions } from './grpcTypes';
import { IBackoffStrategy } from './backoff/backoff';

Просмотреть файл

@ -2,6 +2,7 @@
// tslint:disable
import * as grpc from 'grpc';
import { StatusMessage } from './grpcTypes';
export interface ICallable<T> {
exec(
@ -21,7 +22,7 @@ export interface ICallable<T> {
export interface IResponseStream<T> {
on(event: 'data', fn: (item: T) => void): this;
on(event: 'end', fn: () => void): this;
on(event: 'status', fn: (status: grpc.StatusMessage) => void): this;
on(event: 'status', fn: (status: StatusMessage) => void): this;
on(event: 'error', fn: (err: Error) => void): this;
}