-
Notifications
You must be signed in to change notification settings - Fork 4
/
PolykeyClient.ts
370 lines (352 loc) · 10.7 KB
/
PolykeyClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import type {
JSONRPCRequest,
JSONRPCResponse,
MiddlewareFactory,
} from '@matrixai/rpc';
import type { PromiseCancellable } from '@matrixai/async-cancellable';
import type { ContextTimed, ContextTimedInput } from '@matrixai/contexts';
import type { DeepPartial, FileSystem } from './types';
import type {
ClientRPCRequestParams,
ClientRPCResponseResult,
OverrideRPClientType,
} from './client/types';
import type { NodeId } from './ids/types';
import path from 'path';
import Logger from '@matrixai/logger';
import {
CreateDestroyStartStop,
ready,
} from '@matrixai/async-init/dist/CreateDestroyStartStop';
import { timedCancellable, context } from '@matrixai/contexts/dist/decorators';
import { WebSocketClient, events as webSocketEvents } from '@matrixai/ws';
import { RPCClient, middleware as rpcMiddleware } from '@matrixai/rpc';
import { Session } from './sessions';
import * as ids from './ids';
import * as utils from './utils';
import * as errors from './errors';
import * as events from './events';
import * as networkUtils from './network/utils';
import * as validationErrors from './validation/errors';
import * as clientUtils from './client/utils';
import * as clientMiddleware from './client/middleware';
import clientClientManifest from './client/callers';
import config from './config';
/**
* Optional configuration for`PolykeyClient`.
*/
type PolykeyClientOptions = {
nodePath: string;
keepAliveTimeoutTime: number;
keepAliveIntervalTime: number;
rpcCallTimeoutTime: number;
rpcParserBufferSize: number;
rpcMiddlewareFactory?: MiddlewareFactory<
JSONRPCRequest<ClientRPCRequestParams>,
JSONRPCRequest<ClientRPCRequestParams>,
JSONRPCResponse<ClientRPCResponseResult>,
JSONRPCResponse<ClientRPCResponseResult>
>;
};
interface PolykeyClient extends CreateDestroyStartStop {}
@CreateDestroyStartStop(
new errors.ErrorPolykeyClientRunning(),
new errors.ErrorPolykeyClientDestroyed(),
{
eventStart: events.EventPolykeyClientStart,
eventStarted: events.EventPolykeyClientStarted,
eventStop: events.EventPolykeyClientStop,
eventStopped: events.EventPolykeyClientStopped,
eventDestroy: events.EventPolykeyClientDestroy,
eventDestroyed: events.EventPolykeyClientDestroyed,
},
)
class PolykeyClient {
/**
* Creates a Polykey Client.
*
* @param opts
* @param opts.nodeId
* @param opts.host
* @param opts.port
* @param ctx
*/
public static createPolykeyClient(
opts: {
nodeId: string | NodeId;
host: string;
port: number;
options?: DeepPartial<PolykeyClientOptions>;
fresh?: boolean;
fs?: FileSystem;
logger?: Logger;
},
ctx?: Partial<ContextTimedInput>,
): PromiseCancellable<PolykeyClient>;
@timedCancellable(
true,
config.defaultsSystem.clientConnectTimeoutTime,
errors.ErrorPolykeyClientCreateTimeout,
)
public static async createPolykeyClient(
{
// Required parameters
nodeId,
host,
port,
// Options
options = {},
fresh = false,
// Optional dependencies
fs = require('fs'),
logger = new Logger(this.name),
}: {
nodeId: string | NodeId;
host: string;
port: number;
options?: DeepPartial<PolykeyClientOptions>;
fresh?: boolean;
fs?: FileSystem;
logger?: Logger;
},
@context ctx: ContextTimed,
): Promise<PolykeyClient> {
logger.info(`Creating ${this.name}`);
const optionsDefaulted = utils.mergeObjects(options, {
nodePath: config.defaultsUser.nodePath,
connectTimeoutTime: config.defaultsSystem.clientConnectTimeoutTime,
keepAliveTimeoutTime: config.defaultsSystem.clientKeepAliveTimeoutTime,
keepAliveIntervalTime: config.defaultsSystem.clientKeepAliveIntervalTime,
callTimeoutTime: config.defaultsSystem.rpcCallTimeoutTime,
parserBufferSize: config.defaultsSystem.rpcParserBufferSize,
}) as PolykeyClientOptions;
if (optionsDefaulted.nodePath == null) {
throw new errors.ErrorUtilsNodePath();
}
await utils.mkdirExists(fs, optionsDefaulted.nodePath);
const sessionTokenPath = path.join(
optionsDefaulted.nodePath,
config.paths.tokenBase,
);
const session = await Session.createSession({
sessionTokenPath,
logger: logger.getChild(Session.name),
fresh,
});
const pkClient = new this({
nodePath: optionsDefaulted.nodePath,
session,
fs,
logger,
});
await pkClient.start(
{
nodeId,
host,
port,
options: {
keepAliveTimeoutTime: optionsDefaulted.keepAliveTimeoutTime,
keepAliveIntervalTime: optionsDefaulted.keepAliveIntervalTime,
rpcCallTimeoutTime: optionsDefaulted.rpcCallTimeoutTime,
rpcParserBufferSize: optionsDefaulted.rpcParserBufferSize,
},
fresh,
},
ctx,
);
logger.info(`Created ${this.name}`);
return pkClient;
}
public readonly nodePath: string;
public readonly session: Session;
protected fs: FileSystem;
protected logger: Logger;
protected _nodeId: NodeId;
protected _webSocketClient: WebSocketClient;
protected _rpcClient: OverrideRPClientType<
RPCClient<typeof clientClientManifest>
>;
protected handleEventWebSocketClientDestroyed = async () => {
await this.stop({ force: true });
};
constructor({
nodePath,
session,
fs,
logger,
}: {
nodePath: string;
session: Session;
fs: FileSystem;
logger: Logger;
}) {
this.logger = logger;
this.nodePath = nodePath;
this.session = session;
this.fs = fs;
}
@ready(new errors.ErrorPolykeyClientNotRunning())
public get nodeId() {
return this._nodeId;
}
@ready(new errors.ErrorPolykeyClientNotRunning())
public get webSocketClient() {
return this._webSocketClient;
}
@ready(new errors.ErrorPolykeyClientNotRunning())
public get rpcClient() {
return this._rpcClient;
}
@ready(new errors.ErrorPolykeyClientNotRunning())
public get host() {
return this._webSocketClient.connection.remoteHost;
}
@ready(new errors.ErrorPolykeyClientNotRunning())
public get port() {
return this._webSocketClient.connection.remotePort;
}
@ready(new errors.ErrorPolykeyClientNotRunning())
public get localHost() {
return this._webSocketClient.connection.localHost;
}
@ready(new errors.ErrorPolykeyClientNotRunning())
public get localPort() {
return this._webSocketClient.connection.localPort;
}
public start(
opts: {
nodeId: string | NodeId;
host: string;
port: number;
options?: DeepPartial<{
keepAliveTimeoutTime: number;
keepAliveIntervalTime: number;
rpcCallTimeoutTime: number;
rpcParserBufferSize: number;
}>;
fresh?: boolean;
},
ctx?: Partial<ContextTimedInput>,
): PromiseCancellable<void>;
@timedCancellable(
true,
config.defaultsSystem.clientConnectTimeoutTime,
errors.ErrorPolykeyClientCreateTimeout,
)
public async start(
{
nodeId,
host,
port,
options = {},
fresh = false,
}: {
nodeId: string | NodeId;
host: string;
port: number;
options?: DeepPartial<{
keepAliveTimeoutTime: number;
keepAliveIntervalTime: number;
rpcCallTimeoutTime: number;
rpcParserBufferSize: number;
}>;
fresh?: boolean;
},
@context ctx: ContextTimed,
): Promise<void> {
this.logger.info(`Starting ${this.constructor.name}`);
const optionsDefaulted = utils.mergeObjects(options, {
keepAliveTimeoutTime: config.defaultsSystem.clientKeepAliveTimeoutTime,
keepAliveIntervalTime: config.defaultsSystem.clientKeepAliveIntervalTime,
rpcCallTimeoutTime: config.defaultsSystem.rpcCallTimeoutTime,
rpcParserBufferSize: config.defaultsSystem.rpcParserBufferSize,
});
let nodeId_: NodeId;
if (typeof nodeId === 'string') {
try {
nodeId_ = ids.parseNodeId(nodeId);
} catch (e) {
if (e instanceof validationErrors.ErrorParse) {
throw new errors.ErrorPolykeyClientNodeIdInvalid(
'Encoded node ID must be a multibase base32hex encoded public-key',
{
cause: e,
data: { nodeId },
},
);
}
throw e;
}
} else {
nodeId_ = nodeId;
}
await this.session.start({ fresh });
const webSocketClient = await WebSocketClient.createWebSocketClient(
{
host,
port,
config: {
verifyPeer: true,
verifyCallback: async (certs) => {
await clientUtils.verifyServerCertificateChain([nodeId_], certs);
},
keepAliveTimeoutTime: optionsDefaulted.keepAliveTimeoutTime,
keepAliveIntervalTime: optionsDefaulted.keepAliveIntervalTime,
},
logger: this.logger.getChild(WebSocketClient.name),
},
ctx,
);
webSocketClient.addEventListener(
webSocketEvents.EventWebSocketClientDestroyed.name,
this.handleEventWebSocketClientDestroyed,
);
const rpcClient = new RPCClient({
manifest: clientClientManifest,
streamFactory: () => webSocketClient.connection.newStream(),
middlewareFactory: rpcMiddleware.defaultClientMiddlewareWrapper(
clientMiddleware.middlewareClient(
this.session,
optionsDefaulted.rpcMiddlewareFactory,
),
optionsDefaulted.rpcParserBufferSize,
),
toError: networkUtils.toError,
timeoutTime: optionsDefaulted.rpcCallTimeoutTime,
logger: this.logger.getChild(RPCClient.name),
});
this._nodeId = nodeId_;
this._webSocketClient = webSocketClient;
this._rpcClient = rpcClient as typeof this._rpcClient;
this.logger.info(`Started ${this.constructor.name}`);
}
/**
* Stops Polykey Client
*
* Stopping can force destruction of the websocket client.
* Prefer not forcing for a graceful stop.
* Stopping the session does not destroy the session state.
*/
public async stop({ force = false }: { force?: boolean } = {}) {
this.logger.info(`Stopping ${this.constructor.name}`);
this._webSocketClient.removeEventListener(
webSocketEvents.EventWebSocketClientDestroyed.name,
this.handleEventWebSocketClientDestroyed,
);
await this._webSocketClient.destroy({ force });
await this.session.stop();
this.logger.info(`Stopped ${this.constructor.name}`);
}
/**
* Destroys Polykey Client
*
* This will destroy the session state.
*/
public async destroy() {
this.logger.info(`Destroying ${this.constructor.name}`);
await this.session.destroy();
this.logger.info(`Destroyed ${this.constructor.name}`);
}
}
export default PolykeyClient;
export type { PolykeyClientOptions };