@zlink-systems/framework-locations-etcd 0.0.0-stage → 0.33.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 +26 -0
- package/README.ko.md +80 -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
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ScanCursor = exports.monotonicMs = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const encoding_1 = require("./encoding");
|
|
6
|
+
const monotonicMs = () => process.hrtime.bigint() / 1000000n;
|
|
7
|
+
exports.monotonicMs = monotonicMs;
|
|
8
|
+
/** Binary fields keep the longest UTF-8 prefix/key cursor below the SPI bound. */
|
|
9
|
+
class ScanCursor {
|
|
10
|
+
namespace;
|
|
11
|
+
now;
|
|
12
|
+
instance = (0, node_crypto_1.randomBytes)(16);
|
|
13
|
+
constructor(namespace, now = exports.monotonicMs) {
|
|
14
|
+
this.namespace = namespace;
|
|
15
|
+
this.now = now;
|
|
16
|
+
}
|
|
17
|
+
encode(snapshot, prefix) {
|
|
18
|
+
const fields = [Buffer.from(this.namespace), Buffer.from(prefix), snapshot.last];
|
|
19
|
+
const header = Buffer.alloc(54);
|
|
20
|
+
header[0] = 1;
|
|
21
|
+
this.instance.copy(header, 1);
|
|
22
|
+
header.writeBigUInt64BE(BigInt(snapshot.cluster), 17);
|
|
23
|
+
header.writeBigUInt64BE(BigInt(snapshot.revision), 25);
|
|
24
|
+
header.writeBigUInt64BE(snapshot.clock, 33);
|
|
25
|
+
header.writeBigUInt64BE(snapshot.started, 41);
|
|
26
|
+
header[49] = fields[0].length;
|
|
27
|
+
header.writeUInt16BE(fields[1].length, 50);
|
|
28
|
+
header.writeUInt16BE(fields[2].length, 52);
|
|
29
|
+
return Buffer.concat([header, ...fields]).toString('base64url');
|
|
30
|
+
}
|
|
31
|
+
decode(value, prefix) {
|
|
32
|
+
if (!/^[A-Za-z0-9_-]+$/.test(value))
|
|
33
|
+
return undefined;
|
|
34
|
+
const bytes = Buffer.from(value, 'base64url');
|
|
35
|
+
if (bytes.length < 54 ||
|
|
36
|
+
bytes.toString('base64url') !== value ||
|
|
37
|
+
bytes[0] !== 1 ||
|
|
38
|
+
!bytes.subarray(1, 17).equals(this.instance))
|
|
39
|
+
return undefined;
|
|
40
|
+
const namespaceEnd = 54 + bytes[49];
|
|
41
|
+
const prefixEnd = namespaceEnd + bytes.readUInt16BE(50);
|
|
42
|
+
if (bytes.length !== prefixEnd + bytes.readUInt16BE(52) ||
|
|
43
|
+
!bytes.subarray(54, namespaceEnd).equals(Buffer.from(this.namespace)) ||
|
|
44
|
+
!bytes.subarray(namespaceEnd, prefixEnd).equals(Buffer.from(prefix)))
|
|
45
|
+
return undefined;
|
|
46
|
+
const snapshot = {
|
|
47
|
+
cluster: bytes.readBigUInt64BE(17).toString(),
|
|
48
|
+
revision: bytes.readBigUInt64BE(25).toString(),
|
|
49
|
+
clock: bytes.readBigUInt64BE(33),
|
|
50
|
+
started: bytes.readBigUInt64BE(41),
|
|
51
|
+
last: bytes.subarray(prefixEnd)
|
|
52
|
+
};
|
|
53
|
+
if (snapshot.clock > encoding_1.MAX_TIME_MS ||
|
|
54
|
+
snapshot.revision === '0' ||
|
|
55
|
+
BigInt(snapshot.revision) > 0x7fffffffffffffffn ||
|
|
56
|
+
snapshot.last.length > 1024 ||
|
|
57
|
+
!snapshot.last.subarray(0, Buffer.byteLength(prefix)).equals(Buffer.from(prefix)) ||
|
|
58
|
+
!this.valid(snapshot))
|
|
59
|
+
return undefined;
|
|
60
|
+
return snapshot;
|
|
61
|
+
}
|
|
62
|
+
valid(snapshot) {
|
|
63
|
+
const elapsed = this.now() - snapshot.started;
|
|
64
|
+
return elapsed >= 0n && elapsed < 300000n;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
exports.ScanCursor = ScanCursor;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export declare const MAX_TIME_MS = 9223372036854n;
|
|
2
|
+
export declare class StoreFormatError extends Error {
|
|
3
|
+
constructor();
|
|
4
|
+
}
|
|
5
|
+
export declare function validateNamespace(namespace: string): void;
|
|
6
|
+
export declare function keys(namespace: string): {
|
|
7
|
+
namespacePrefix: Buffer<ArrayBuffer>;
|
|
8
|
+
metadataPrefix: Buffer<ArrayBuffer>;
|
|
9
|
+
payloadPrefix: Buffer<ArrayBuffer>;
|
|
10
|
+
clock: Buffer<ArrayBuffer>;
|
|
11
|
+
metadata: (key: Uint8Array) => Buffer<ArrayBuffer>;
|
|
12
|
+
payload: (key: Uint8Array) => Buffer<ArrayBuffer>;
|
|
13
|
+
};
|
|
14
|
+
export declare function prefixEnd(prefix: Buffer): Buffer;
|
|
15
|
+
export declare function encodeClock(value: bigint): Buffer;
|
|
16
|
+
export declare function decodeClock(bytes: Buffer): bigint;
|
|
17
|
+
export interface Metadata {
|
|
18
|
+
hasExpiry: boolean;
|
|
19
|
+
expiresAtMs: bigint;
|
|
20
|
+
payloadLength: number;
|
|
21
|
+
}
|
|
22
|
+
export declare function encodeMetadata(value: Metadata): Buffer;
|
|
23
|
+
export declare function decodeMetadata(bytes: Buffer): Metadata;
|
|
24
|
+
export declare function validateRecord(metadata: Buffer | null, payload: Buffer | null, metadataRevision: string, payloadRevision: string): Metadata | null;
|
|
25
|
+
export declare function encodeVersion(clusterId: string, revision: string): string;
|
|
26
|
+
export declare function decodeVersion(value: string): {
|
|
27
|
+
clusterId: string;
|
|
28
|
+
revision: string;
|
|
29
|
+
} | null;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.StoreFormatError = exports.MAX_TIME_MS = void 0;
|
|
4
|
+
exports.validateNamespace = validateNamespace;
|
|
5
|
+
exports.keys = keys;
|
|
6
|
+
exports.prefixEnd = prefixEnd;
|
|
7
|
+
exports.encodeClock = encodeClock;
|
|
8
|
+
exports.decodeClock = decodeClock;
|
|
9
|
+
exports.encodeMetadata = encodeMetadata;
|
|
10
|
+
exports.decodeMetadata = decodeMetadata;
|
|
11
|
+
exports.validateRecord = validateRecord;
|
|
12
|
+
exports.encodeVersion = encodeVersion;
|
|
13
|
+
exports.decodeVersion = decodeVersion;
|
|
14
|
+
exports.MAX_TIME_MS = 9223372036854n;
|
|
15
|
+
const MAX_PAYLOAD_BYTES = 1_048_576;
|
|
16
|
+
const MAX_REVISION = 9223372036854775807n;
|
|
17
|
+
class StoreFormatError extends Error {
|
|
18
|
+
constructor() {
|
|
19
|
+
super('Invalid etcd Store encoding');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
exports.StoreFormatError = StoreFormatError;
|
|
23
|
+
function validateNamespace(namespace) {
|
|
24
|
+
if (typeof namespace !== 'string' || namespace.includes('\0'))
|
|
25
|
+
throw new TypeError('Invalid namespace');
|
|
26
|
+
const length = Buffer.byteLength(namespace, 'utf8');
|
|
27
|
+
if (length < 1 || length > 64)
|
|
28
|
+
throw new RangeError('Namespace must contain 1..64 UTF-8 bytes');
|
|
29
|
+
}
|
|
30
|
+
function keys(namespace) {
|
|
31
|
+
validateNamespace(namespace);
|
|
32
|
+
const namespacePrefix = Buffer.from(`${namespace}\0`);
|
|
33
|
+
const metadataPrefix = Buffer.concat([namespacePrefix, Buffer.from('m\0')]);
|
|
34
|
+
const payloadPrefix = Buffer.concat([namespacePrefix, Buffer.from('p\0')]);
|
|
35
|
+
return {
|
|
36
|
+
namespacePrefix,
|
|
37
|
+
metadataPrefix,
|
|
38
|
+
payloadPrefix,
|
|
39
|
+
clock: Buffer.concat([namespacePrefix, Buffer.from('c')]),
|
|
40
|
+
metadata: (key) => Buffer.concat([metadataPrefix, key]),
|
|
41
|
+
payload: (key) => Buffer.concat([payloadPrefix, key])
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function prefixEnd(prefix) {
|
|
45
|
+
const end = Buffer.from(prefix);
|
|
46
|
+
for (let i = end.length - 1; i >= 0; i--) {
|
|
47
|
+
if (end[i] < 255) {
|
|
48
|
+
end[i]++;
|
|
49
|
+
return end.subarray(0, i + 1);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return Buffer.from([0]);
|
|
53
|
+
}
|
|
54
|
+
function encodeClock(value) {
|
|
55
|
+
if (value < 0n || value > exports.MAX_TIME_MS)
|
|
56
|
+
throw new RangeError('Store time exceeds its encoding range');
|
|
57
|
+
const bytes = Buffer.alloc(8);
|
|
58
|
+
bytes.writeBigUInt64BE(value);
|
|
59
|
+
return bytes;
|
|
60
|
+
}
|
|
61
|
+
function decodeClock(bytes) {
|
|
62
|
+
if (bytes.length !== 8)
|
|
63
|
+
throw new StoreFormatError();
|
|
64
|
+
const value = bytes.readBigUInt64BE();
|
|
65
|
+
if (value > exports.MAX_TIME_MS)
|
|
66
|
+
throw new StoreFormatError();
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
function encodeMetadata(value) {
|
|
70
|
+
if (!Number.isInteger(value.payloadLength) ||
|
|
71
|
+
value.payloadLength < 0 ||
|
|
72
|
+
value.payloadLength > MAX_PAYLOAD_BYTES ||
|
|
73
|
+
(!value.hasExpiry && value.expiresAtMs !== 0n))
|
|
74
|
+
throw new RangeError('Invalid metadata');
|
|
75
|
+
const bytes = Buffer.alloc(14);
|
|
76
|
+
bytes[0] = 1;
|
|
77
|
+
bytes[1] = value.hasExpiry ? 1 : 0;
|
|
78
|
+
encodeClock(value.expiresAtMs).copy(bytes, 2);
|
|
79
|
+
bytes.writeUInt32BE(value.payloadLength, 10);
|
|
80
|
+
return bytes;
|
|
81
|
+
}
|
|
82
|
+
function decodeMetadata(bytes) {
|
|
83
|
+
if (bytes.length !== 14 || bytes[0] !== 1 || bytes[1] > 1)
|
|
84
|
+
throw new StoreFormatError();
|
|
85
|
+
const value = {
|
|
86
|
+
hasExpiry: bytes[1] === 1,
|
|
87
|
+
expiresAtMs: decodeClock(bytes.subarray(2, 10)),
|
|
88
|
+
payloadLength: bytes.readUInt32BE(10)
|
|
89
|
+
};
|
|
90
|
+
if ((!value.hasExpiry && value.expiresAtMs !== 0n) || value.payloadLength > MAX_PAYLOAD_BYTES)
|
|
91
|
+
throw new StoreFormatError();
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
function validateRecord(metadata, payload, metadataRevision, payloadRevision) {
|
|
95
|
+
if (metadata === null && payload === null)
|
|
96
|
+
return null;
|
|
97
|
+
if (metadata === null || payload === null || metadataRevision !== payloadRevision)
|
|
98
|
+
throw new StoreFormatError();
|
|
99
|
+
const value = decodeMetadata(metadata);
|
|
100
|
+
if (value.payloadLength !== payload.length)
|
|
101
|
+
throw new StoreFormatError();
|
|
102
|
+
return value;
|
|
103
|
+
}
|
|
104
|
+
function encodeVersion(clusterId, revision) {
|
|
105
|
+
const cluster = BigInt(clusterId);
|
|
106
|
+
if (cluster < 0n ||
|
|
107
|
+
cluster > 0xffffffffffffffffn ||
|
|
108
|
+
!/^[1-9][0-9]*$/.test(revision) ||
|
|
109
|
+
BigInt(revision).toString() !== revision ||
|
|
110
|
+
BigInt(revision) > MAX_REVISION)
|
|
111
|
+
throw new RangeError('Invalid version');
|
|
112
|
+
return `e1:${cluster.toString(16).padStart(16, '0')}:${revision}`;
|
|
113
|
+
}
|
|
114
|
+
function decodeVersion(value) {
|
|
115
|
+
const match = /^e1:([0-9a-f]{16}):([1-9][0-9]*)$/.exec(value);
|
|
116
|
+
if (match === null || match[0] !== value || BigInt(match[2]) > MAX_REVISION)
|
|
117
|
+
return null;
|
|
118
|
+
return { clusterId: BigInt(`0x${match[1]}`).toString(), revision: match[2] };
|
|
119
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { ZLinkStoreKey, ZLinkStoreWriteRequest, ZLinkStoreScanRequest } from '@zlink-systems/framework';
|
|
2
|
+
export declare const bounds: Record<"ZLINK_PROVIDER_MAX_KEY_BYTES" | "ZLINK_PROVIDER_MAX_VALUE_BYTES" | "ZLINK_PROVIDER_MAX_VERSION_BYTES" | "ZLINK_PROVIDER_MAX_WRITE_KEYS" | "ZLINK_PROVIDER_MAX_WRITE_BYTES" | "ZLINK_PROVIDER_MAX_SCAN_CURSOR_BYTES" | "ZLINK_PROVIDER_MAX_PAGE_SIZE" | "ZLINK_PROVIDER_MAX_ENCODED_PAGE_BYTES", number>;
|
|
3
|
+
export declare function text(value: string, minimum: number, maximum: number): string;
|
|
4
|
+
export declare function key(value: ZLinkStoreKey): Buffer;
|
|
5
|
+
export declare function validateWrite(request: ZLinkStoreWriteRequest): void;
|
|
6
|
+
export declare function validateScan(request: ZLinkStoreScanRequest): void;
|