@zlink-systems/framework-locations-etcd 0.0.0-stage → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +93 -0
- package/README.en.md +66 -0
- package/README.ko.md +116 -0
- package/dist/.tsbuildinfo +1 -0
- package/dist/admin.d.ts +2 -0
- package/dist/admin.js +143 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +5 -0
- package/dist/internal/admin-engine.d.ts +36 -0
- package/dist/internal/admin-engine.js +171 -0
- package/dist/internal/client.d.ts +61 -0
- package/dist/internal/client.js +182 -0
- package/dist/internal/cursor.d.ts +18 -0
- package/dist/internal/cursor.js +67 -0
- package/dist/internal/encoding.d.ts +29 -0
- package/dist/internal/encoding.js +119 -0
- package/dist/internal/input.d.ts +6 -0
- package/dist/internal/input.js +81 -0
- package/dist/internal/options.d.ts +4 -0
- package/dist/internal/options.js +65 -0
- package/dist/location-store.d.ts +20 -0
- package/dist/location-store.js +285 -0
- package/dist/options.d.ts +19 -0
- package/dist/options.js +2 -0
- package/dist/proto/README.ko.md +39 -0
- package/dist/proto/v3.6.16/etcd/api/authpb/auth.proto +44 -0
- package/dist/proto/v3.6.16/etcd/api/etcdserverpb/rpc.proto +1436 -0
- package/dist/proto/v3.6.16/etcd/api/mvccpb/kv.proto +51 -0
- package/dist/proto/v3.6.16/etcd/api/versionpb/version.proto +30 -0
- package/dist/proto/v3.6.16/gogoproto/gogo.proto +144 -0
- package/dist/proto/v3.6.16/google/api/annotations.proto +31 -0
- package/dist/proto/v3.6.16/google/api/http.proto +379 -0
- package/dist/proto/v3.6.16/licenses/etcd-LICENSE +202 -0
- package/dist/proto/v3.6.16/licenses/gogo-protobuf-LICENSE +35 -0
- package/dist/proto/v3.6.16/licenses/googleapis-LICENSE +201 -0
- package/dist/proto/v3.6.16/licenses/grpc-gateway-LICENSE +27 -0
- package/dist/proto/v3.6.16/protoc-gen-openapiv2/options/annotations.proto +51 -0
- package/dist/proto/v3.6.16/protoc-gen-openapiv2/options/openapiv2.proto +762 -0
- package/package.json +24 -4
- package/README.md +0 -3
package/dist/admin.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.main = main;
|
|
5
|
+
// Install CLI signal handlers before loading the gRPC dependency graph.
|
|
6
|
+
function watchTermination() {
|
|
7
|
+
const stop = new AbortController();
|
|
8
|
+
const onSignal = () => stop.abort();
|
|
9
|
+
process.on('SIGINT', onSignal);
|
|
10
|
+
process.on('SIGTERM', onSignal);
|
|
11
|
+
return {
|
|
12
|
+
stop,
|
|
13
|
+
close: () => {
|
|
14
|
+
process.removeListener('SIGINT', onSignal);
|
|
15
|
+
process.removeListener('SIGTERM', onSignal);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
const entryTermination = require.main === module ? watchTermination() : undefined;
|
|
20
|
+
const node_fs_1 = require("node:fs");
|
|
21
|
+
const node_path_1 = require("node:path");
|
|
22
|
+
const client_1 = require("./internal/client");
|
|
23
|
+
const admin_engine_1 = require("./internal/admin-engine");
|
|
24
|
+
const options_1 = require("./internal/options");
|
|
25
|
+
const CLEANUP_INTERVAL_MS = 60_000;
|
|
26
|
+
const ERROR_WAIT_MS = 1000;
|
|
27
|
+
function readConfig(file) {
|
|
28
|
+
const config = JSON.parse((0, node_fs_1.readFileSync)(file, 'utf8'));
|
|
29
|
+
const read = (name) => (0, node_fs_1.readFileSync)((0, node_path_1.resolve)((0, node_path_1.dirname)(file), name), 'utf8');
|
|
30
|
+
const tls = config.tls;
|
|
31
|
+
if (tls === null || (tls !== undefined && (typeof tls !== 'object' || Array.isArray(tls))))
|
|
32
|
+
throw new TypeError('Invalid TLS configuration');
|
|
33
|
+
const identity = tls?.clientIdentity;
|
|
34
|
+
if (identity === null)
|
|
35
|
+
throw new TypeError('Invalid client identity');
|
|
36
|
+
const options = {
|
|
37
|
+
endpoints: config.endpoints,
|
|
38
|
+
namespace: config.namespace,
|
|
39
|
+
operationTimeoutMs: config.operationTimeoutMs,
|
|
40
|
+
tls: tls === undefined
|
|
41
|
+
? undefined
|
|
42
|
+
: {
|
|
43
|
+
trustedCaPem: tls.trustedCaPemFile === undefined ? undefined : read(tls.trustedCaPemFile),
|
|
44
|
+
clientIdentity: identity === undefined
|
|
45
|
+
? undefined
|
|
46
|
+
: {
|
|
47
|
+
certificatePem: read(identity.certificatePemFile),
|
|
48
|
+
keyPem: read(identity.keyPemFile)
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
credentials: config.credentials === undefined
|
|
52
|
+
? undefined
|
|
53
|
+
: {
|
|
54
|
+
user: config.credentials.user,
|
|
55
|
+
password: read(config.credentials.passwordFile)
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
(0, options_1.validateOptions)(options);
|
|
59
|
+
return options;
|
|
60
|
+
}
|
|
61
|
+
function report(error) {
|
|
62
|
+
if (error instanceof admin_engine_1.MissingClockError)
|
|
63
|
+
process.stderr.write('Store clock key is missing\n');
|
|
64
|
+
else if (error instanceof client_1.EtcdCallError)
|
|
65
|
+
process.stderr.write(`etcd ${error.kind} (gRPC ${error.code})\n`);
|
|
66
|
+
else
|
|
67
|
+
process.stderr.write('Store maintenance failed\n');
|
|
68
|
+
}
|
|
69
|
+
async function run(store, stop) {
|
|
70
|
+
let result = 0;
|
|
71
|
+
const stopped = () => stop.signal.aborted;
|
|
72
|
+
const engine = new admin_engine_1.ClockEngine(store);
|
|
73
|
+
const loop = async (action, interval) => {
|
|
74
|
+
while (!stop.signal.aborted) {
|
|
75
|
+
try {
|
|
76
|
+
await action();
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
if (stopped())
|
|
80
|
+
return;
|
|
81
|
+
report(error);
|
|
82
|
+
if (error instanceof admin_engine_1.MissingClockError) {
|
|
83
|
+
result = 3;
|
|
84
|
+
stop.abort();
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
await admin_engine_1.systemTime.sleep(ERROR_WAIT_MS, stop.signal);
|
|
88
|
+
}
|
|
89
|
+
if (interval > 0)
|
|
90
|
+
await admin_engine_1.systemTime.sleep(interval, stop.signal);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
await Promise.all([
|
|
94
|
+
loop(() => engine.step(stop.signal), 0),
|
|
95
|
+
loop(() => store.cleanup(stop.signal), CLEANUP_INTERVAL_MS)
|
|
96
|
+
]);
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
async function main(args = process.argv.slice(2)) {
|
|
100
|
+
const termination = entryTermination ?? watchTermination();
|
|
101
|
+
try {
|
|
102
|
+
let options;
|
|
103
|
+
const command = args[0];
|
|
104
|
+
try {
|
|
105
|
+
if (args.length !== 3 ||
|
|
106
|
+
!['init', 'run', 'cleanup'].includes(command) ||
|
|
107
|
+
args[1] !== '--config')
|
|
108
|
+
throw new TypeError('Invalid arguments');
|
|
109
|
+
options = readConfig((0, node_path_1.resolve)(args[2]));
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
process.stderr.write('Invalid command or configuration\n');
|
|
113
|
+
return 1;
|
|
114
|
+
}
|
|
115
|
+
if (command === 'run' && termination.stop.signal.aborted)
|
|
116
|
+
return 0;
|
|
117
|
+
let client;
|
|
118
|
+
try {
|
|
119
|
+
client = new client_1.EtcdClient(options);
|
|
120
|
+
const store = new admin_engine_1.EtcdAdminStore(client);
|
|
121
|
+
if (command === 'init')
|
|
122
|
+
return (await store.init()) ? 0 : 2;
|
|
123
|
+
if (command === 'run')
|
|
124
|
+
return await run(store, termination.stop);
|
|
125
|
+
await store.cleanup();
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
report(error);
|
|
130
|
+
return error instanceof admin_engine_1.MissingClockError ? 3 : 4;
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
client?.close();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
termination.close();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (require.main === module)
|
|
141
|
+
void main().then((code) => {
|
|
142
|
+
process.exitCode = code;
|
|
143
|
+
});
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ZLinkEtcdLocationStore = void 0;
|
|
4
|
+
var location_store_1 = require("./location-store");
|
|
5
|
+
Object.defineProperty(exports, "ZLinkEtcdLocationStore", { enumerable: true, get: function () { return location_store_1.ZLinkEtcdLocationStore; } });
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { EtcdClient, Operation } from './client';
|
|
2
|
+
export declare class MissingClockError extends Error {
|
|
3
|
+
constructor();
|
|
4
|
+
}
|
|
5
|
+
export interface ClockSample {
|
|
6
|
+
value: bigint;
|
|
7
|
+
revision: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ClockStore {
|
|
10
|
+
operation?(signal?: AbortSignal): Operation;
|
|
11
|
+
readClock(operation?: Operation): Promise<ClockSample>;
|
|
12
|
+
compareClock(revision: string, value: bigint, operation?: Operation): Promise<boolean>;
|
|
13
|
+
}
|
|
14
|
+
export interface EngineTime {
|
|
15
|
+
monotonicMs(): bigint;
|
|
16
|
+
wallMs(): bigint;
|
|
17
|
+
sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
export declare const systemTime: EngineTime;
|
|
20
|
+
export declare class ClockEngine {
|
|
21
|
+
private readonly store;
|
|
22
|
+
private readonly time;
|
|
23
|
+
private sample;
|
|
24
|
+
constructor(store: ClockStore, time?: EngineTime);
|
|
25
|
+
step(signal?: AbortSignal): Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
export declare class EtcdAdminStore implements ClockStore {
|
|
28
|
+
private readonly client;
|
|
29
|
+
private readonly key;
|
|
30
|
+
constructor(client: EtcdClient);
|
|
31
|
+
operation(signal?: AbortSignal): Operation;
|
|
32
|
+
readClock(operation?: Operation): Promise<ClockSample>;
|
|
33
|
+
compareClock(revision: string, value: bigint, operation?: Operation): Promise<boolean>;
|
|
34
|
+
init(wallMs?: bigint): Promise<boolean>;
|
|
35
|
+
cleanup(signal?: AbortSignal): Promise<void>;
|
|
36
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.EtcdAdminStore = exports.ClockEngine = exports.systemTime = exports.MissingClockError = void 0;
|
|
4
|
+
const encoding_1 = require("./encoding");
|
|
5
|
+
const CLOCK_CHECK_INTERVAL_MS = 1000;
|
|
6
|
+
function stopped(signal) {
|
|
7
|
+
return signal?.aborted ?? false;
|
|
8
|
+
}
|
|
9
|
+
class MissingClockError extends Error {
|
|
10
|
+
constructor() {
|
|
11
|
+
super('Store clock key is missing');
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
exports.MissingClockError = MissingClockError;
|
|
15
|
+
exports.systemTime = {
|
|
16
|
+
monotonicMs: () => process.hrtime.bigint() / 1000000n,
|
|
17
|
+
wallMs: () => BigInt(Date.now()),
|
|
18
|
+
sleep: (ms, signal) => new Promise((resolve) => {
|
|
19
|
+
if (stopped(signal)) {
|
|
20
|
+
resolve();
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const finish = () => {
|
|
24
|
+
clearTimeout(timer);
|
|
25
|
+
signal?.removeEventListener('abort', finish);
|
|
26
|
+
resolve();
|
|
27
|
+
};
|
|
28
|
+
const timer = setTimeout(finish, ms);
|
|
29
|
+
signal?.addEventListener('abort', finish, { once: true });
|
|
30
|
+
})
|
|
31
|
+
};
|
|
32
|
+
class ClockEngine {
|
|
33
|
+
store;
|
|
34
|
+
time;
|
|
35
|
+
sample;
|
|
36
|
+
constructor(store, time = exports.systemTime) {
|
|
37
|
+
this.store = store;
|
|
38
|
+
this.time = time;
|
|
39
|
+
}
|
|
40
|
+
async step(signal) {
|
|
41
|
+
if (stopped(signal))
|
|
42
|
+
return;
|
|
43
|
+
try {
|
|
44
|
+
if (this.sample === undefined) {
|
|
45
|
+
const clock = await this.store.readClock(this.store.operation?.(signal));
|
|
46
|
+
this.sample = { clock, at: this.time.monotonicMs() };
|
|
47
|
+
}
|
|
48
|
+
const previous = this.sample;
|
|
49
|
+
if (stopped(signal))
|
|
50
|
+
return;
|
|
51
|
+
await this.time.sleep(CLOCK_CHECK_INTERVAL_MS, signal);
|
|
52
|
+
if (stopped(signal))
|
|
53
|
+
return;
|
|
54
|
+
// The one-second wait is not part of any operation: the confirming read and the write get their own deadline.
|
|
55
|
+
const operation = this.store.operation?.(signal);
|
|
56
|
+
const next = await this.store.readClock(operation);
|
|
57
|
+
const receivedAt = this.time.monotonicMs();
|
|
58
|
+
if (next.revision !== previous.clock.revision) {
|
|
59
|
+
this.sample = { clock: next, at: receivedAt };
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (stopped(signal))
|
|
63
|
+
return;
|
|
64
|
+
const elapsed = this.time.monotonicMs() - previous.at;
|
|
65
|
+
let increment = elapsed < 1000n ? elapsed : 1000n;
|
|
66
|
+
const wall = this.time.wallMs();
|
|
67
|
+
if (wall > previous.clock.value + increment) {
|
|
68
|
+
const correction = wall - previous.clock.value;
|
|
69
|
+
increment = increment + 10n < correction ? increment + 10n : correction;
|
|
70
|
+
}
|
|
71
|
+
await this.store.compareClock(previous.clock.revision, previous.clock.value + increment, operation);
|
|
72
|
+
this.sample = undefined;
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
this.sample = undefined;
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
exports.ClockEngine = ClockEngine;
|
|
81
|
+
class EtcdAdminStore {
|
|
82
|
+
client;
|
|
83
|
+
key;
|
|
84
|
+
constructor(client) {
|
|
85
|
+
this.client = client;
|
|
86
|
+
this.key = (0, encoding_1.keys)(client.options.namespace);
|
|
87
|
+
}
|
|
88
|
+
operation(signal) {
|
|
89
|
+
return this.client.operation(signal);
|
|
90
|
+
}
|
|
91
|
+
async readClock(operation = this.operation()) {
|
|
92
|
+
const response = await this.client.rpc('KV', 'range', { key: this.key.clock }, operation);
|
|
93
|
+
const value = response.kvs.at(0);
|
|
94
|
+
if (value === undefined)
|
|
95
|
+
throw new MissingClockError();
|
|
96
|
+
return { value: (0, encoding_1.decodeClock)(value.value), revision: value.mod_revision };
|
|
97
|
+
}
|
|
98
|
+
async compareClock(revision, value, operation = this.operation()) {
|
|
99
|
+
const response = await this.client.rpc('KV', 'txn', {
|
|
100
|
+
compare: [{ key: this.key.clock, target: 'MOD', result: 'EQUAL', mod_revision: revision }],
|
|
101
|
+
success: [{ request_put: { key: this.key.clock, value: (0, encoding_1.encodeClock)(value) } }]
|
|
102
|
+
}, operation);
|
|
103
|
+
return response.succeeded;
|
|
104
|
+
}
|
|
105
|
+
async init(wallMs = exports.systemTime.wallMs()) {
|
|
106
|
+
const response = await this.client.rpc('KV', 'txn', {
|
|
107
|
+
compare: [
|
|
108
|
+
{
|
|
109
|
+
key: this.key.namespacePrefix,
|
|
110
|
+
range_end: (0, encoding_1.prefixEnd)(this.key.namespacePrefix),
|
|
111
|
+
target: 'VERSION',
|
|
112
|
+
result: 'EQUAL',
|
|
113
|
+
version: '0'
|
|
114
|
+
}
|
|
115
|
+
],
|
|
116
|
+
success: [{ request_put: { key: this.key.clock, value: (0, encoding_1.encodeClock)(wallMs) } }]
|
|
117
|
+
}, this.operation());
|
|
118
|
+
return response.succeeded;
|
|
119
|
+
}
|
|
120
|
+
async cleanup(signal) {
|
|
121
|
+
if (stopped(signal))
|
|
122
|
+
return;
|
|
123
|
+
const clock = await this.readClock(this.operation(signal));
|
|
124
|
+
let start = this.key.metadataPrefix;
|
|
125
|
+
const end = (0, encoding_1.prefixEnd)(start);
|
|
126
|
+
while (!stopped(signal)) {
|
|
127
|
+
const page = await this.client.rpc('KV', 'range', {
|
|
128
|
+
key: start,
|
|
129
|
+
range_end: end,
|
|
130
|
+
limit: '1000',
|
|
131
|
+
sort_order: 'ASCEND',
|
|
132
|
+
sort_target: 'KEY'
|
|
133
|
+
}, this.operation(signal));
|
|
134
|
+
for (const record of page.kvs) {
|
|
135
|
+
if (stopped(signal))
|
|
136
|
+
return;
|
|
137
|
+
let metadata;
|
|
138
|
+
try {
|
|
139
|
+
metadata = (0, encoding_1.decodeMetadata)(record.value);
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
if (!(error instanceof encoding_1.StoreFormatError))
|
|
143
|
+
throw error;
|
|
144
|
+
process.stderr.write('corrupt metadata skipped\n');
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (metadata.hasExpiry && metadata.expiresAtMs <= clock.value) {
|
|
148
|
+
const frameworkKey = record.key.subarray(this.key.metadataPrefix.length);
|
|
149
|
+
await this.client.rpc('KV', 'txn', {
|
|
150
|
+
compare: [
|
|
151
|
+
{
|
|
152
|
+
key: record.key,
|
|
153
|
+
target: 'MOD',
|
|
154
|
+
result: 'EQUAL',
|
|
155
|
+
mod_revision: record.mod_revision
|
|
156
|
+
}
|
|
157
|
+
],
|
|
158
|
+
success: [
|
|
159
|
+
{ request_delete_range: { key: record.key } },
|
|
160
|
+
{ request_delete_range: { key: this.key.payload(frameworkKey) } }
|
|
161
|
+
]
|
|
162
|
+
}, this.operation(signal));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (!page.more || page.kvs.length === 0)
|
|
166
|
+
return;
|
|
167
|
+
start = Buffer.concat([page.kvs[page.kvs.length - 1].key, Buffer.from([0])]);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
exports.EtcdAdminStore = EtcdAdminStore;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import * as grpc from '@grpc/grpc-js';
|
|
2
|
+
import * as loader from '@grpc/proto-loader';
|
|
3
|
+
import { EtcdOptions } from './options';
|
|
4
|
+
export type ErrorKind = 'compaction' | 'nospace' | 'auth' | 'storeFailure';
|
|
5
|
+
export declare class EtcdCallError extends Error {
|
|
6
|
+
readonly kind: ErrorKind;
|
|
7
|
+
readonly code: number;
|
|
8
|
+
readonly description: string;
|
|
9
|
+
readonly endpoint: string;
|
|
10
|
+
constructor(kind: ErrorKind, code: number, description: string, endpoint: string);
|
|
11
|
+
}
|
|
12
|
+
export declare function classifyError(code: number, description: string): ErrorKind;
|
|
13
|
+
export declare const CHANNEL_OPTIONS: grpc.ChannelOptions;
|
|
14
|
+
export declare function protoDefinition(): loader.PackageDefinition;
|
|
15
|
+
export interface Operation {
|
|
16
|
+
readonly deadline: Date;
|
|
17
|
+
readonly signal?: AbortSignal;
|
|
18
|
+
/** An abort also cancels the RPC already sent; otherwise it only stops new RPCs (§4.4). */
|
|
19
|
+
readonly cancelsSent?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface KeyValue {
|
|
22
|
+
key: Buffer;
|
|
23
|
+
value: Buffer;
|
|
24
|
+
mod_revision: string;
|
|
25
|
+
create_revision: string;
|
|
26
|
+
version: string;
|
|
27
|
+
}
|
|
28
|
+
export interface RangeResponse {
|
|
29
|
+
kvs: KeyValue[];
|
|
30
|
+
more: boolean;
|
|
31
|
+
header: {
|
|
32
|
+
revision: string;
|
|
33
|
+
cluster_id: string;
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
export interface TxnResponse {
|
|
37
|
+
succeeded: boolean;
|
|
38
|
+
header: {
|
|
39
|
+
revision: string;
|
|
40
|
+
cluster_id: string;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
export interface ReadTxnResponse extends TxnResponse {
|
|
44
|
+
responses: {
|
|
45
|
+
response_range: RangeResponse;
|
|
46
|
+
}[];
|
|
47
|
+
}
|
|
48
|
+
export declare class EtcdClient {
|
|
49
|
+
readonly options: EtcdOptions;
|
|
50
|
+
private readonly channels;
|
|
51
|
+
private readonly clients;
|
|
52
|
+
private readonly services;
|
|
53
|
+
private endpoint;
|
|
54
|
+
private token;
|
|
55
|
+
constructor(options: EtcdOptions);
|
|
56
|
+
operation(signal?: AbortSignal, cancelsSent?: boolean): Operation;
|
|
57
|
+
private authenticate;
|
|
58
|
+
rpc<T = RangeResponse>(service: 'KV' | 'Auth', method: string, request: object, operation: Operation): Promise<T>;
|
|
59
|
+
private invoke;
|
|
60
|
+
close(): void;
|
|
61
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.EtcdClient = exports.CHANNEL_OPTIONS = exports.EtcdCallError = void 0;
|
|
37
|
+
exports.classifyError = classifyError;
|
|
38
|
+
exports.protoDefinition = protoDefinition;
|
|
39
|
+
const grpc = __importStar(require("@grpc/grpc-js"));
|
|
40
|
+
const loader = __importStar(require("@grpc/proto-loader"));
|
|
41
|
+
const node_fs_1 = require("node:fs");
|
|
42
|
+
const node_path_1 = require("node:path");
|
|
43
|
+
const node_tls_1 = require("node:tls");
|
|
44
|
+
const options_1 = require("./options");
|
|
45
|
+
class EtcdCallError extends Error {
|
|
46
|
+
kind;
|
|
47
|
+
code;
|
|
48
|
+
description;
|
|
49
|
+
endpoint;
|
|
50
|
+
constructor(kind, code, description, endpoint) {
|
|
51
|
+
super(`etcd ${kind} (gRPC ${code})`);
|
|
52
|
+
this.kind = kind;
|
|
53
|
+
this.code = code;
|
|
54
|
+
this.description = description;
|
|
55
|
+
this.endpoint = endpoint;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
exports.EtcdCallError = EtcdCallError;
|
|
59
|
+
function classifyError(code, description) {
|
|
60
|
+
if (code === grpc.status.OUT_OF_RANGE &&
|
|
61
|
+
description.includes('required revision has been compacted'))
|
|
62
|
+
return 'compaction';
|
|
63
|
+
if (code === grpc.status.RESOURCE_EXHAUSTED && description.includes('database space exceeded'))
|
|
64
|
+
return 'nospace';
|
|
65
|
+
if ((code === grpc.status.UNAUTHENTICATED && description.includes('invalid auth token')) ||
|
|
66
|
+
(code === grpc.status.INVALID_ARGUMENT && description.includes('revision of auth store is old')))
|
|
67
|
+
return 'auth';
|
|
68
|
+
return 'storeFailure';
|
|
69
|
+
}
|
|
70
|
+
exports.CHANNEL_OPTIONS = {
|
|
71
|
+
'grpc.enable_retries': 0,
|
|
72
|
+
'grpc.service_config_disable_resolution': 1,
|
|
73
|
+
'grpc.max_send_message_length': 16 * 1024 * 1024,
|
|
74
|
+
'grpc.max_receive_message_length': 8 * 1024 * 1024
|
|
75
|
+
};
|
|
76
|
+
function protoDefinition() {
|
|
77
|
+
const packed = (0, node_path_1.resolve)(__dirname, '../proto/v3.6.16');
|
|
78
|
+
const root = (0, node_fs_1.existsSync)(packed)
|
|
79
|
+
? packed
|
|
80
|
+
: (0, node_path_1.resolve)(__dirname, '../../../../../../runtime/protocol/etcd/v3.6.16');
|
|
81
|
+
return loader.loadSync((0, node_path_1.resolve)(root, 'etcd/api/etcdserverpb/rpc.proto'), {
|
|
82
|
+
keepCase: true,
|
|
83
|
+
longs: String,
|
|
84
|
+
bytes: Buffer,
|
|
85
|
+
defaults: true,
|
|
86
|
+
includeDirs: [root]
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
class EtcdClient {
|
|
90
|
+
options;
|
|
91
|
+
channels;
|
|
92
|
+
clients;
|
|
93
|
+
services;
|
|
94
|
+
endpoint = 0;
|
|
95
|
+
token;
|
|
96
|
+
constructor(options) {
|
|
97
|
+
this.options = options;
|
|
98
|
+
const endpoints = (0, options_1.validateOptions)(options);
|
|
99
|
+
this.services = grpc.loadPackageDefinition(protoDefinition()).etcdserverpb;
|
|
100
|
+
const tls = options.tls;
|
|
101
|
+
const identity = tls?.clientIdentity;
|
|
102
|
+
const credentials = endpoints[0].protocol === 'https:'
|
|
103
|
+
? grpc.credentials.createSsl(Buffer.from(tls?.trustedCaPem ?? (0, node_tls_1.getCACertificates)('system').join('\n')), identity === undefined ? undefined : Buffer.from(identity.keyPem), identity === undefined ? undefined : Buffer.from(identity.certificatePem))
|
|
104
|
+
: grpc.credentials.createInsecure();
|
|
105
|
+
this.channels = endpoints.map((endpoint) => new grpc.Channel(`${endpoint.hostname}:${endpoint.port === '' ? (endpoint.protocol === 'https:' ? '443' : '80') : endpoint.port}`, credentials, exports.CHANNEL_OPTIONS));
|
|
106
|
+
this.clients = this.channels.map((channel) => ({
|
|
107
|
+
KV: new this.services.KV('', credentials, { channelOverride: channel }),
|
|
108
|
+
Auth: new this.services.Auth('', credentials, { channelOverride: channel })
|
|
109
|
+
}));
|
|
110
|
+
}
|
|
111
|
+
operation(signal, cancelsSent = false) {
|
|
112
|
+
return {
|
|
113
|
+
deadline: new Date(Date.now() + (this.options.operationTimeoutMs ?? options_1.DEFAULT_OPERATION_TIMEOUT_MS)),
|
|
114
|
+
signal,
|
|
115
|
+
cancelsSent
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
async authenticate(operation) {
|
|
119
|
+
const credentials = this.options.credentials;
|
|
120
|
+
if (credentials === undefined)
|
|
121
|
+
return;
|
|
122
|
+
const response = await this.invoke('Auth', 'authenticate', { name: credentials.user, password: credentials.password }, operation, false);
|
|
123
|
+
this.token = response.token;
|
|
124
|
+
}
|
|
125
|
+
async rpc(service, method, request, operation) {
|
|
126
|
+
if (this.options.credentials !== undefined && this.token === undefined)
|
|
127
|
+
await this.authenticate(operation);
|
|
128
|
+
try {
|
|
129
|
+
return await this.invoke(service, method, request, operation, true);
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
if (!(error instanceof EtcdCallError) ||
|
|
133
|
+
error.kind !== 'auth' ||
|
|
134
|
+
this.options.credentials === undefined)
|
|
135
|
+
throw error;
|
|
136
|
+
await this.authenticate(operation);
|
|
137
|
+
return this.invoke(service, method, request, operation, true);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
invoke(service, method, request, operation, authenticated) {
|
|
141
|
+
if (operation.signal?.aborted === true)
|
|
142
|
+
return Promise.reject(new Error('Store operation stopped'));
|
|
143
|
+
const index = this.endpoint;
|
|
144
|
+
const descriptor = Object.entries(this.services[service].service).find(([name]) => name.toLowerCase() === method.toLowerCase())?.[1];
|
|
145
|
+
if (descriptor === undefined)
|
|
146
|
+
return Promise.reject(new TypeError('Unknown RPC'));
|
|
147
|
+
const metadata = new grpc.Metadata();
|
|
148
|
+
if (authenticated && this.token !== undefined)
|
|
149
|
+
metadata.set('token', this.token);
|
|
150
|
+
return new Promise((accept, reject) => {
|
|
151
|
+
const cancel = () => call.cancel();
|
|
152
|
+
const call = this.clients[index][service].makeUnaryRequest(descriptor.path, descriptor.requestSerialize, descriptor.responseDeserialize, request, metadata, { deadline: operation.deadline }, (error, response) => {
|
|
153
|
+
operation.signal?.removeEventListener('abort', cancel);
|
|
154
|
+
if (operation.signal?.aborted === true) {
|
|
155
|
+
reject(new Error('Store operation stopped'));
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (error !== null) {
|
|
159
|
+
if ((error.code === grpc.status.UNAVAILABLE ||
|
|
160
|
+
error.code === grpc.status.DEADLINE_EXCEEDED) &&
|
|
161
|
+
this.endpoint === index)
|
|
162
|
+
this.endpoint = (index + 1) % this.channels.length;
|
|
163
|
+
reject(new EtcdCallError(classifyError(error.code, error.details), error.code, error.details, this.options.endpoints[index]));
|
|
164
|
+
}
|
|
165
|
+
else if (response === undefined)
|
|
166
|
+
reject(new Error('Missing RPC response'));
|
|
167
|
+
else
|
|
168
|
+
accept(response);
|
|
169
|
+
});
|
|
170
|
+
if (operation.cancelsSent === true) {
|
|
171
|
+
operation.signal?.addEventListener('abort', cancel, { once: true });
|
|
172
|
+
if (operation.signal?.aborted === true)
|
|
173
|
+
cancel();
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
close() {
|
|
178
|
+
for (const channel of this.channels)
|
|
179
|
+
channel.close();
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
exports.EtcdClient = EtcdClient;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare const monotonicMs: () => bigint;
|
|
2
|
+
export interface Snapshot {
|
|
3
|
+
cluster: string;
|
|
4
|
+
revision: string;
|
|
5
|
+
clock: bigint;
|
|
6
|
+
started: bigint;
|
|
7
|
+
last: Buffer;
|
|
8
|
+
}
|
|
9
|
+
/** Binary fields keep the longest UTF-8 prefix/key cursor below the SPI bound. */
|
|
10
|
+
export declare class ScanCursor {
|
|
11
|
+
private readonly namespace;
|
|
12
|
+
private readonly now;
|
|
13
|
+
private readonly instance;
|
|
14
|
+
constructor(namespace: string, now?: () => bigint);
|
|
15
|
+
encode(snapshot: Snapshot, prefix: string): string;
|
|
16
|
+
decode(value: string, prefix: string): Snapshot | undefined;
|
|
17
|
+
valid(snapshot: Snapshot): boolean;
|
|
18
|
+
}
|