Options
All
  • Public
  • Public/Protected
  • All
Menu

etcd3 Run Tests

etcd3 aims is a high-quality, production-ready client for the Protocol Buffer-based etcdv3 API. It includes:

and is type-safe for TypeScript consumers.

Quickstart

Install via:

npm install --save etcd3

Start building!

const { Etcd3 } = require('etcd3');
const client = new Etcd3();

(async () => {
  await client.put('foo').value('bar');

  const fooValue = await client.get('foo').string();
  console.log('foo was:', fooValue);

  const allFValues = await client.getAll().prefix('f').keys();
  console.log('all our keys starting with "f":', allFValues);

  await client.delete().all();
})();

API Documentation

Our TypeDoc docs are available here.

Our test cases are also readable.

Running tests

$ npm install
$ cd src/test/containers/3.2 && docker-compose up # in a separate shell
$ 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.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Index

Enumerations

Classes

Interfaces

Type aliases

Variables

Functions

Object literals

Type aliases

CallContext

CallContext: { isStream: false; method: "range"; params: IRangeRequest; service: "KV" } | { isStream: false; method: "put"; params: IPutRequest; service: "KV" } | { isStream: false; method: "deleteRange"; params: IDeleteRangeRequest; service: "KV" } | { isStream: false; method: "txn"; params: ITxnRequest; service: "KV" } | { isStream: false; method: "compact"; params: ICompactionRequest; service: "KV" } | { isStream: true; method: "watch"; service: "Watch" } | { isStream: false; method: "leaseGrant"; params: ILeaseGrantRequest; service: "Lease" } | { isStream: false; method: "leaseRevoke"; params: ILeaseRevokeRequest; service: "Lease" } | { isStream: true; method: "leaseKeepAlive"; service: "Lease" } | { isStream: false; method: "leaseTimeToLive"; params: ILeaseTimeToLiveRequest; service: "Lease" } | { isStream: false; method: "leaseLeases"; service: "Lease" } | { isStream: false; method: "memberAdd"; params: IMemberAddRequest; service: "Cluster" } | { isStream: false; method: "memberRemove"; params: IMemberRemoveRequest; service: "Cluster" } | { isStream: false; method: "memberUpdate"; params: IMemberUpdateRequest; service: "Cluster" } | { isStream: false; method: "memberList"; params: IMemberListRequest; service: "Cluster" } | { isStream: false; method: "memberPromote"; params: IMemberPromoteRequest; service: "Cluster" } | { isStream: false; method: "alarm"; params: IAlarmRequest; service: "Maintenance" } | { isStream: false; method: "status"; service: "Maintenance" } | { isStream: false; method: "defragment"; service: "Maintenance" } | { isStream: false; method: "hash"; service: "Maintenance" } | { isStream: false; method: "hashKV"; params: IHashKVRequest; service: "Maintenance" } | { isStream: true; method: "snapshot"; service: "Maintenance" } | { isStream: false; method: "moveLeader"; params: IMoveLeaderRequest; service: "Maintenance" } | { isStream: false; method: "downgrade"; params: IDowngradeRequest; service: "Maintenance" } | { isStream: false; method: "authEnable"; service: "Auth" } | { isStream: false; method: "authDisable"; service: "Auth" } | { isStream: false; method: "authStatus"; service: "Auth" } | { isStream: false; method: "authenticate"; params: IAuthenticateRequest; service: "Auth" } | { isStream: false; method: "userAdd"; params: IAuthUserAddRequest; service: "Auth" } | { isStream: false; method: "userGet"; params: IAuthUserGetRequest; service: "Auth" } | { isStream: false; method: "userList"; service: "Auth" } | { isStream: false; method: "userDelete"; params: IAuthUserDeleteRequest; service: "Auth" } | { isStream: false; method: "userChangePassword"; params: IAuthUserChangePasswordRequest; service: "Auth" } | { isStream: false; method: "userGrantRole"; params: IAuthUserGrantRoleRequest; service: "Auth" } | { isStream: false; method: "userRevokeRole"; params: IAuthUserRevokeRoleRequest; service: "Auth" } | { isStream: false; method: "roleAdd"; params: IAuthRoleAddRequest; service: "Auth" } | { isStream: false; method: "roleGet"; params: IAuthRoleGetRequest; service: "Auth" } | { isStream: false; method: "roleList"; service: "Auth" } | { isStream: false; method: "roleDelete"; params: IAuthRoleDeleteRequest; service: "Auth" } | { isStream: false; method: "roleGrantPermission"; params: IAuthRoleGrantPermissionRequest; service: "Auth" } | { isStream: false; method: "roleRevokePermission"; params: IAuthRoleRevokePermissionRequest; service: "Auth" }

CallOptionsFactory

CallOptionsFactory: CallOptions | ((context: CallContext) => CallOptions)

IErrorCtor

IErrorCtor: {}

Type declaration

IPermissionRequest

IPermissionRequest: { permission: keyof typeof Permission; range: Range } | { key: Buffer | string; permission: keyof typeof Permission }

IPermission can be used to grant a certain role in etcd access to a certain key range, or prefix.

Rangable

Rangable: Range | string | Buffer | { end: string | Buffer; start: string | Buffer } | { prefix: string | Buffer }

WriteOp

WriteOp: { op: Write; req: IPutRequest } | { key: Buffer; op: DeleteKey; req: IDeleteRangeRequest } | { op: DeleteRange; range: Range; req: IDeleteRangeRequest }

Variables

Const RecoverableError

RecoverableError: unique symbol = Symbol('RecoverableError')

Symbol present on transient errors which will be resolved through default fault handling.

Const ResignedCampaign

ResignedCampaign: unique symbol = Symbol('ResignedCampaign')

Const UnsetCurrent

UnsetCurrent: unique symbol = Symbol('unset')

Const emptyBuffer

emptyBuffer: Buffer = Buffer.from([])

Const emptyKey

emptyKey: Buffer = Buffer.from([])

Const etcdserverpb

etcdserverpb: {} = services.etcdserverpb as { [service: string]: typeof grpc.Client }

Type declaration

  • [service: string]: typeof Client

Const grpcCodeToError

grpcCodeToError: Map<number, IErrorCtor> = new Map<number, IErrorCtor>([[1, GRPCCancelledError],[2, GRPCUnknownError],[3, GRPCInvalidArgumentError],[4, GRPCDeadlineExceededError],[5, GRPCNotFoundError],[6, GRPCAlreadyExistsError],[7, EtcdPermissionDeniedError],[8, GRPCResourceExhastedError],[9, GRPCFailedPreconditionError],[10, GRPCAbortedError],[11, GRPCOutOfRangeError],[12, GRPCNotImplementedError],[13, GRPCInternalError],[14, GRPCUnavailableError],[15, GRPCDataLossError],[16, GRPCUnauthenticatedError],])

Const grpcMessageToError

grpcMessageToError: Map<string, IErrorCtor> = new Map<string, IErrorCtor>([['etcdserver: role name already exists', EtcdRoleExistsError],['etcdserver: user name already exists', EtcdUserExistsError],['etcdserver: role is not granted to the user', EtcdRoleNotGrantedError],['etcdserver: role name not found', EtcdRoleNotFoundError],['etcdserver: user name not found', EtcdUserNotFoundError],['etcdserver: authentication failed, invalid user ID or password', EtcdAuthenticationFailedError],['etcdserver: permission denied', EtcdPermissionDeniedError],['etcdserver: invalid auth token', EtcdInvalidAuthTokenError],['etcdserver: requested lease not found', EtcdLeaseInvalidError],])

Mapping of GRPC error messages to typed error. GRPC errors are untyped by default and sourced from within a mess of C code.

Const packageDefinition

packageDefinition: PackageDefinition = loadSync(`${__dirname}/../proto/rpc.proto`, {keepCase: true,longs: String,enums: String,defaults: true,oneofs: true,})

Const secureProtocolPrefix

secureProtocolPrefix: "https:" = "https:"

Const services

services: GrpcObject = grpc.loadPackageDefinition(packageDefinition)

Const zeroKey

zeroKey: Buffer = Buffer.from([0])

Functions

assertWithin

  • assertWithin<T>(map: T, value: keyof T, thing: string): void
  • assertWithin throws a helpful error message if the value provided isn't a key in the given map.

    Type parameters

    • T

    Parameters

    • map: T
    • value: keyof T
    • thing: string

    Returns void

castGrpcError

  • castGrpcError<T>(err: T): Error
  • Tries to convert GRPC's generic, untyped errors to typed errors we can consume. Yes, this method is abhorrent.

    Type parameters

    Parameters

    • err: T

    Returns Error

castGrpcErrorMessage

  • castGrpcErrorMessage(message: string): Error
  • Tries to convert an Etcd error string to an etcd error.

    Parameters

    • message: string

    Returns Error

compare

  • compare(a: Buffer, b: Buffer): number
  • Parameters

    • a: Buffer
    • b: Buffer

    Returns number

debounce

  • debounce(duration: number, fn: () => void): wrapper
  • A trailing-edge debounce function.

    Parameters

    • duration: number
    • fn: () => void
        • (): void
        • Returns void

    Returns wrapper

Const defaultCircuitBreaker

  • defaultCircuitBreaker(): CircuitBreakerPolicy

delay

  • delay(duration: number): Promise<void>
  • Returns a promise that resolves after a certain amount of time.

    Parameters

    • duration: number

    Returns Promise<void>

endRangeForPrefix

  • endRangeForPrefix(prefix: Buffer): Buffer
  • Returns the range_end value for a query for the provided prefix.

    Parameters

    • prefix: Buffer

    Returns Buffer

forOwn

  • forOwn<T>(obj: T, iterator: <K>(value: T[K], key: K) => void): void
  • Implementation of lodash forOwn, with stronger typings and no dependency ;)

    Type parameters

    • T

    Parameters

    • obj: T
    • iterator: <K>(value: T[K], key: K) => void
        • <K>(value: T[K], key: K): void
        • Type parameters

          • K: keyof T

          Parameters

          • value: T[K]
          • key: K

          Returns void

    Returns void

Const getDeferred

  • getDeferred<T>(): { promise: Promise<T>; reject: (error: unknown) => void; resolve: (value: T) => void }
  • Type parameters

    • T

    Returns { promise: Promise<T>; reject: (error: unknown) => void; resolve: (value: T) => void }

    • promise: Promise<T>
    • reject: (error: unknown) => void
        • (error: unknown): void
        • Parameters

          • error: unknown

          Returns void

    • resolve: (value: T) => void
        • (value: T): void
        • Parameters

          • value: T

          Returns void

getMatchingGrpcError

  • getMatchingGrpcError(message: string): IErrorCtor | undefined

getRange

Const isRecoverableError

  • isRecoverableError(error: Error): boolean
  • Returns whether the error is a network or server error that should trigger fault-handling policies.

    Parameters

    Returns boolean

keyValueToResponse

  • keyValueToResponse(key: string | Buffer, value?: Buffer): IRangeResponse
  • Converts the key/value pair to a partial response that contains it. The response will not contain header or revision information.

    Parameters

    • key: string | Buffer
    • Optional value: Buffer

    Returns IRangeResponse

leaseExpired

minBy

  • minBy<T>(items: T[], prop: (x: T) => number): T[]
  • Returns items with the smallest value as picked by the prop function.

    Type parameters

    • T

    Parameters

    • items: T[]
    • prop: (x: T) => number
        • (x: T): number
        • Parameters

          • x: T

          Returns number

    Returns T[]

onceEvent

  • onceEvent(emitter: EventEmitter, ...events: string[]): Promise<any>
  • onceEvent returns a promise that resolves once any of the listed events fire on the emitter.

    Parameters

    • emitter: EventEmitter
    • Rest ...events: string[]

    Returns Promise<any>

rangableIsPrefix

  • rangableIsPrefix(r: Rangable): r is { prefix: string | Buffer }

removeProtocolPrefix

  • removeProtocolPrefix(name: string): string
  • Strips the https?:// from the start of the connection string.

    Parameters

    • name: string

    Returns string

Const resolveCallOptions

  • resolveCallOptions(callOptions: CallOptions | undefined, defaultOptions: undefined | CallOptionsFactory, context: CallContext): CallOptions | undefined
  • Applies the defaultOptions or defaultOptions factory to the given call-specific options.

    Parameters

    Returns CallOptions | undefined

rewriteErrorName

  • rewriteErrorName(str: string, ctor: {}): string

runServiceCall

  • runServiceCall(client: Client, metadata: Metadata, options: CallOptions | undefined, method: string, payload: unknown): Promise<any>
  • Executes a grpc service calls, casting the error (if any) and wrapping into a Promise.

    Parameters

    • client: Client
    • metadata: Metadata
    • options: CallOptions | undefined
    • method: string
    • payload: unknown

    Returns Promise<any>

sample

  • sample<T>(items: T[]): T
  • Returns a random element from the list of items.

    Type parameters

    • T

    Parameters

    • items: T[]

    Returns T

throwIfError

  • throwIfError<T>(value: T | Error): T

toBuffer

  • toBuffer(input: string | Buffer | number): Buffer
  • Converts the input to a buffer, if it is not already.

    Parameters

    • input: string | Buffer | number

    Returns Buffer

waitForDelete

  • waitForDelete(namespace: Namespace, key: Buffer, rev: string): Promise<void>

waitForDeletes

  • waitForDeletes(namespace: Namespace, keys: Buffer[]): Promise<void>
  • Returns a function that resolves when all of the given keys are deleted.

    Parameters

    Returns Promise<void>

Object literals

Const Services

Services: object

Auth

Auth: AuthClient = AuthClient

Cluster

Cluster: ClusterClient = ClusterClient

KV

KV: KVClient = KVClient

Lease

Lease: LeaseClient = LeaseClient

Maintenance

Maintenance: MaintenanceClient = MaintenanceClient

Watch

Watch: WatchClient = WatchClient

Const comparator

comparator: object

Comparators can be passed to various operations in the ComparatorBuilder.

!=

!=: CompareResult = RPC.CompareResult.NotEqual

!==

!==: CompareResult = RPC.CompareResult.NotEqual

<

<: CompareResult = RPC.CompareResult.Less

==

==: CompareResult = RPC.CompareResult.Equal

===

===: CompareResult = RPC.CompareResult.Equal

>

>: CompareResult = RPC.CompareResult.Greater

Const compareTarget

compareTarget: object

compareTarget are the types of things that can be compared against.

Create

Create: "create_revision" = "create_revision"

Lease

Lease: "lease" = "lease"

Mod

Mod: "mod_revision" = "mod_revision"

Value

Value: "value" = "value"

Version

Version: "version" = "version"

Const operationNames

operationNames: object

delete

delete: FilterType = RPC.FilterType.Noput

put

put: FilterType = RPC.FilterType.Nodelete

Legend

  • Constructor
  • Method
  • Inherited method

Generated using TypeDoc