@nestia/benchmark 12.0.0-rc.2 → 12.0.0-rc.4

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.
@@ -1,465 +1,465 @@
1
- import { IConnection } from "@nestia/fetcher";
2
- import fs from "fs";
3
- import { Driver, WorkerConnector, WorkerServer } from "tgrid";
4
- import { HashMap, hash, sleep_for } from "tstl";
5
-
6
- import { IBenchmarkEvent } from "./IBenchmarkEvent";
7
- import { DynamicBenchmarkReporter } from "./internal/DynamicBenchmarkReporter";
8
- import { IBenchmarkMaster } from "./internal/IBenchmarkMaster";
9
- import { IBenchmarkServant } from "./internal/IBenchmarkServant";
10
-
11
- /**
12
- * Dynamic benchmark executor running prefixed functions.
13
- *
14
- * `DynamicBenchmarker` is composed with two programs,
15
- * {@link DynamicBenchmarker.master} and
16
- * {@link DynamicBenchmarker.servant servants}. The master program creates
17
- * multiple servant programs, and the servant programs execute the prefixed
18
- * functions in parallel. When the pre-congirued count of requests are all
19
- * completed, the master program collects the results and returns them.
20
- *
21
- * Therefore, when you want to benchmark the performance of a backend server,
22
- * you have to make two programs; one for calling the
23
- * {@link DynamicBenchmarker.master} function, and the other for calling the
24
- * {@link DynamicBenchmarker.servant} function. Also, never forget to write the
25
- * path of the servant program to the
26
- * {@link DynamicBenchmarker.IMasterProps.servant} property.
27
- *
28
- * Also, you when you complete the benchmark execution through the
29
- * {@link DynamicBenchmarker.master} and {@link DynamicBenchmarker.servant}
30
- * functions, you can convert the result to markdown content by using the
31
- * {@link DynamicBenchmarker.markdown} function.
32
- *
33
- * Additionally, if you hope to see some utilization cases, see the below
34
- * example tagged links.
35
- *
36
- * @author Jeongho Nam - https://github.com/samchon
37
- * @example
38
- * https://github.com/samchon/nestia-start/blob/master/test/benchmaark/index.ts
39
- *
40
- * @example
41
- * https://github.com/samchon/backend/blob/master/test/benchmark/index.ts
42
- */
43
- export namespace DynamicBenchmarker {
44
- /** Properties of the master program. */
45
- export interface IMasterProps {
46
- /** Total count of the requests. */
47
- count: number;
48
-
49
- /**
50
- * Number of threads.
51
- *
52
- * The number of threads to be executed as parallel servant.
53
- */
54
- threads: number;
55
-
56
- /**
57
- * Number of simultaneous requests.
58
- *
59
- * The number of requests to be executed simultaneously.
60
- *
61
- * This property value would be divided by the {@link threads} in the
62
- * servants.
63
- */
64
- simultaneous: number;
65
-
66
- /**
67
- * Path of the servant program.
68
- *
69
- * The path of the servant program executing the
70
- * {@link DynamicBenchmarker.servant} function.
71
- */
72
- servant: string;
73
-
74
- /**
75
- * Filter function.
76
- *
77
- * The filter function is called with the file name (basename) of each
78
- * benchmark function module, not with the function name. When it returns
79
- * `false`, the file would never be imported in the servant, so that every
80
- * function defined in the file would never be executed either.
81
- *
82
- * @param file File name (basename) of the benchmark functions
83
- * @returns Whether to execute the function or not.
84
- */
85
- filter?: (file: string) => boolean;
86
-
87
- /**
88
- * Progress callback function.
89
- *
90
- * @param complete The number of completed requests.
91
- */
92
- progress?: (complete: number) => void;
93
-
94
- /**
95
- * Get memory usage.
96
- *
97
- * Get the memory usage of the master program.
98
- *
99
- * Specify this property only when your backend server is running on a
100
- * different process, so that need to measure the memory usage of the
101
- * backend server from other process.
102
- */
103
- memory?: () => Promise<NodeJS.MemoryUsage>;
104
-
105
- /**
106
- * Standard I/O option.
107
- *
108
- * The standard I/O option for the servant programs.
109
- */
110
- stdio?: undefined | "overlapped" | "pipe" | "ignore" | "inherit";
111
- }
112
-
113
- /** Properties of the servant program. */
114
- export interface IServantProps<Parameters extends any[]> {
115
- /**
116
- * Default connection.
117
- *
118
- * Default connection to be used in the servant.
119
- */
120
- connection: IConnection;
121
-
122
- /** Location of the benchmark functions. */
123
- location: string;
124
-
125
- /**
126
- * Extension of the benchmark function files to load, without the leading
127
- * dot.
128
- *
129
- * The servant reads {@link location} and imports every file ending with this
130
- * extension. Set it to match how the feature files are actually run: `"js"`
131
- * when they are built JavaScript, or `"ts"` when they are executed from
132
- * TypeScript source (for example under `ttsx`).
133
- *
134
- * @default "js"
135
- */
136
- extension?: string;
137
-
138
- /**
139
- * Prefix of the benchmark functions.
140
- *
141
- * Every prefixed function will be executed in the servant.
142
- *
143
- * In other words, if a function name doesn't start with the prefix, then it
144
- * would never be executed. Also, when a file name (basename) does not start
145
- * with the prefix, the file would never be imported either, so that every
146
- * function defined in the file would never be executed.
147
- */
148
- prefix: string;
149
-
150
- /**
151
- * Get parameters of a function.
152
- *
153
- * When composing the parameters, never forget to copy the
154
- * {@link IConnection.logger} property of default connection to the returning
155
- * parameters.
156
- *
157
- * @param connection Default connection instance
158
- * @param name Function name
159
- */
160
- parameters: (connection: IConnection, name: string) => Parameters;
161
- }
162
-
163
- /** Benchmark report. */
164
- export interface IReport {
165
- count: number;
166
- threads: number;
167
- simultaneous: number;
168
- started_at: string;
169
- completed_at: string;
170
- statistics: IReport.IStatistics;
171
- endpoints: Array<IReport.IEndpoint & IReport.IStatistics>;
172
- memories: IReport.IMemory[];
173
- }
174
- export namespace IReport {
175
- export interface IEndpoint {
176
- method: string;
177
- path: string;
178
- }
179
- export interface IStatistics {
180
- count: number;
181
- success: number;
182
- mean: number | null;
183
- stdev: number | null;
184
- minimum: number | null;
185
- maximum: number | null;
186
- }
187
- export interface IMemory {
188
- time: string;
189
- usage: NodeJS.MemoryUsage;
190
- }
191
- }
192
-
193
- /**
194
- * Master program.
195
- *
196
- * Creates a master program that executing the servant programs in parallel.
197
- *
198
- * Note that, {@link IMasterProps.servant} property must be the path of the
199
- * servant program executing the {@link servant} function.
200
- *
201
- * @param props Properties of the master program
202
- * @returns Benchmark report
203
- */
204
- export const master = async (props: IMasterProps): Promise<IReport> => {
205
- const completes: number[] = new Array(props.threads).fill(0);
206
- const servants: WorkerConnector<
207
- null,
208
- IBenchmarkMaster,
209
- IBenchmarkServant
210
- >[] = await Promise.all(
211
- new Array(props.threads).fill(null).map(async (_, i) => {
212
- const connector: WorkerConnector<
213
- null,
214
- IBenchmarkMaster,
215
- IBenchmarkServant
216
- > = new WorkerConnector(
217
- null,
218
- {
219
- filter: props.filter ?? (() => true),
220
- progress: (current) => {
221
- completes[i] = current;
222
- if (props.progress)
223
- props.progress(completes.reduce((a, b) => a + b, 0));
224
- },
225
- },
226
- "process",
227
- );
228
- await connector.connect(props.servant, { stdio: props.stdio });
229
- return connector;
230
- }),
231
- );
232
-
233
- const started_at: Date = new Date();
234
- const memories: IReport.IMemory[] = [];
235
- let completed_at: Date | null = null;
236
-
237
- (async () => {
238
- const getter = props.memory ?? (async () => process.memoryUsage());
239
- while (completed_at === null) {
240
- await sleep_for(1_000);
241
- memories.push({
242
- usage: await getter(),
243
- time: new Date().toISOString(),
244
- });
245
- }
246
- })().catch(() => {});
247
-
248
- const events: IBenchmarkEvent[] = (
249
- await Promise.all(
250
- servants.map((connector) =>
251
- connector.getDriver().execute({
252
- count: Math.ceil(props.count / props.threads),
253
- simultaneous: Math.ceil(props.simultaneous / props.threads),
254
- }),
255
- ),
256
- )
257
- ).flat();
258
-
259
- completed_at = new Date();
260
- await Promise.all(servants.map((connector) => connector.close()));
261
- if (props.progress) props.progress(props.count);
262
-
263
- const endpoints: HashMap<IReport.IEndpoint, IBenchmarkEvent[]> =
264
- new HashMap(
265
- (key) => hash(key.method, key.path),
266
- (x, y) => x.method === y.method && x.path === y.path,
267
- );
268
- for (const e of events)
269
- endpoints
270
- .take(
271
- {
272
- method: e.metadata.method,
273
- path: e.metadata.template ?? e.metadata.path,
274
- },
275
- () => [],
276
- )
277
- .push(e);
278
- return {
279
- count: props.count,
280
- threads: props.threads,
281
- simultaneous: props.simultaneous,
282
- statistics: statistics(events),
283
- endpoints: [...endpoints].map((it) => ({
284
- ...statistics(it.second),
285
- ...it.first,
286
- })),
287
- started_at: started_at.toISOString(),
288
- completed_at: completed_at.toISOString(),
289
- memories,
290
- };
291
- };
292
-
293
- /**
294
- * Create a servant program.
295
- *
296
- * Creates a servant program executing the prefixed functions in parallel.
297
- *
298
- * @param props Properties of the servant program
299
- * @returns Servant program as a worker server
300
- */
301
- export const servant = async <Parameters extends any[]>(
302
- props: IServantProps<Parameters>,
303
- ): Promise<WorkerServer<null, IBenchmarkServant, IBenchmarkMaster>> => {
304
- const server: WorkerServer<null, IBenchmarkServant, IBenchmarkMaster> =
305
- new WorkerServer();
306
- await server.open({
307
- execute: execute({
308
- driver: server.getDriver(),
309
- props,
310
- }),
311
- });
312
- return server;
313
- };
314
-
315
- /**
316
- * Convert the benchmark report to markdown content.
317
- *
318
- * @param report Benchmark report
319
- * @returns Markdown content
320
- */
321
- export const markdown = (report: DynamicBenchmarker.IReport): string =>
322
- DynamicBenchmarkReporter.markdown(report);
323
-
324
- const execute =
325
- <Parameters extends any[]>(ctx: {
326
- driver: Driver<IBenchmarkMaster>;
327
- props: IServantProps<Parameters>;
328
- }) =>
329
- async (mass: {
330
- count: number;
331
- simultaneous: number;
332
- }): Promise<IBenchmarkEvent[]> => {
333
- const functions: IFunction<Parameters>[] = [];
334
- await iterate({
335
- collection: functions,
336
- driver: ctx.driver,
337
- props: ctx.props,
338
- })(ctx.props.location);
339
-
340
- const entireEvents: IBenchmarkEvent[] = [];
341
- await Promise.all(
342
- new Array(mass.simultaneous)
343
- .fill(null)
344
- .map(() => 1)
345
- .map(async () => {
346
- while (entireEvents.length < mass.count) {
347
- const localEvents: IBenchmarkEvent[] = [];
348
- const func: IFunction<Parameters> =
349
- functions[Math.floor(Math.random() * functions.length)]!;
350
- const connection: IConnection = {
351
- ...ctx.props.connection,
352
- logger: async (fe): Promise<void> => {
353
- const be: IBenchmarkEvent = {
354
- metadata: fe.route,
355
- status: fe.status,
356
- started_at: fe.started_at.toISOString(),
357
- respond_at: fe.respond_at?.toISOString() ?? null,
358
- completed_at: fe.completed_at.toISOString(),
359
- success: true,
360
- };
361
- localEvents.push(be);
362
- entireEvents.push(be);
363
- },
364
- };
365
- try {
366
- await func.value(...ctx.props.parameters(connection, func.key));
367
- } catch (exp) {
368
- for (const e of localEvents)
369
- e.success = e.status === 200 || e.status === 201;
370
- }
371
- if (localEvents.length !== 0)
372
- ctx.driver.progress(entireEvents.length).catch(() => {});
373
- }
374
- }),
375
- );
376
- await ctx.driver.progress(entireEvents.length);
377
- return entireEvents;
378
- };
379
- }
380
-
381
- interface IFunction<Parameters extends any[]> {
382
- key: string;
383
- value: (...args: Parameters) => Promise<void>;
384
- }
385
-
386
- const iterate =
387
- <Parameters extends any[]>(ctx: {
388
- collection: IFunction<Parameters>[];
389
- driver: Driver<IBenchmarkMaster>;
390
- props: DynamicBenchmarker.IServantProps<Parameters>;
391
- }) =>
392
- async (path: string): Promise<void> => {
393
- const directory: string[] = await fs.promises.readdir(path);
394
- for (const file of directory) {
395
- const location: string = `${path}/${file}`;
396
- const stat: fs.Stats = await fs.promises.stat(location);
397
- if (stat.isDirectory() === true) await iterate(ctx)(location);
398
- // Load feature files whose extension matches `props.extension`. This is
399
- // configurable instead of inferred from the servant's own module
400
- // extension, because the benchmark library may be built (`.js`) while the
401
- // feature files it drives are run from source (`.ts`, e.g. under `ttsx`);
402
- // inferring would look for `.js` features that do not exist, load
403
- // nothing, and spin forever.
404
- else if (
405
- file.endsWith(`.${ctx.props.extension ?? "js"}`) &&
406
- file.endsWith(".d.ts") === false
407
- ) {
408
- // GATE BY FILE NAME (PREFIX & FILTER), SO THAT EXCLUDED FILES ARE
409
- // NEVER IMPORTED.
410
- if (file.startsWith(ctx.props.prefix) === false) continue;
411
- if ((await ctx.driver.filter(file)) === false) continue;
412
- const modulo = await import(location);
413
- for (const [key, value] of Object.entries(modulo)) {
414
- if (typeof value !== "function") continue;
415
- else if (key.startsWith(ctx.props.prefix) === false) continue;
416
- ctx.collection.push({
417
- key,
418
- value: value as (...args: Parameters) => Promise<any>,
419
- });
420
- }
421
- }
422
- }
423
- };
424
-
425
- const statistics = (
426
- events: IBenchmarkEvent[],
427
- ): DynamicBenchmarker.IReport.IStatistics => {
428
- const successes: IBenchmarkEvent[] = events.filter((event) => event.success);
429
- return {
430
- count: events.length,
431
- success: successes.length,
432
- ...average(events),
433
- };
434
- };
435
-
436
- const average = (
437
- events: IBenchmarkEvent[],
438
- ): Pick<
439
- DynamicBenchmarker.IReport.IStatistics,
440
- "mean" | "stdev" | "minimum" | "maximum"
441
- > => {
442
- if (events.length === 0)
443
- return {
444
- mean: null,
445
- stdev: null,
446
- minimum: null,
447
- maximum: null,
448
- };
449
- let mean: number = 0;
450
- let stdev: number = 0;
451
- let minimum: number = Number.MAX_SAFE_INTEGER;
452
- let maximum: number = Number.MIN_SAFE_INTEGER;
453
- for (const event of events) {
454
- const elapsed: number =
455
- new Date(event.completed_at).getTime() -
456
- new Date(event.started_at).getTime();
457
- mean += elapsed;
458
- stdev += elapsed * elapsed;
459
- minimum = Math.min(minimum, elapsed);
460
- maximum = Math.max(maximum, elapsed);
461
- }
462
- mean /= events.length;
463
- stdev = Math.sqrt(stdev / events.length - mean * mean);
464
- return { mean, stdev, minimum, maximum };
465
- };
1
+ import { IConnection } from "@nestia/fetcher";
2
+ import fs from "fs";
3
+ import { Driver, WorkerConnector, WorkerServer } from "tgrid";
4
+ import { HashMap, hash, sleep_for } from "tstl";
5
+
6
+ import { IBenchmarkEvent } from "./IBenchmarkEvent";
7
+ import { DynamicBenchmarkReporter } from "./internal/DynamicBenchmarkReporter";
8
+ import { IBenchmarkMaster } from "./internal/IBenchmarkMaster";
9
+ import { IBenchmarkServant } from "./internal/IBenchmarkServant";
10
+
11
+ /**
12
+ * Dynamic benchmark executor running prefixed functions.
13
+ *
14
+ * `DynamicBenchmarker` is composed with two programs,
15
+ * {@link DynamicBenchmarker.master} and
16
+ * {@link DynamicBenchmarker.servant servants}. The master program creates
17
+ * multiple servant programs, and the servant programs execute the prefixed
18
+ * functions in parallel. When the pre-congirued count of requests are all
19
+ * completed, the master program collects the results and returns them.
20
+ *
21
+ * Therefore, when you want to benchmark the performance of a backend server,
22
+ * you have to make two programs; one for calling the
23
+ * {@link DynamicBenchmarker.master} function, and the other for calling the
24
+ * {@link DynamicBenchmarker.servant} function. Also, never forget to write the
25
+ * path of the servant program to the
26
+ * {@link DynamicBenchmarker.IMasterProps.servant} property.
27
+ *
28
+ * Also, you when you complete the benchmark execution through the
29
+ * {@link DynamicBenchmarker.master} and {@link DynamicBenchmarker.servant}
30
+ * functions, you can convert the result to markdown content by using the
31
+ * {@link DynamicBenchmarker.markdown} function.
32
+ *
33
+ * Additionally, if you hope to see some utilization cases, see the below
34
+ * example tagged links.
35
+ *
36
+ * @author Jeongho Nam - https://github.com/samchon
37
+ * @example
38
+ * https://github.com/samchon/nestia-start/blob/master/test/benchmaark/index.ts
39
+ *
40
+ * @example
41
+ * https://github.com/samchon/backend/blob/master/test/benchmark/index.ts
42
+ */
43
+ export namespace DynamicBenchmarker {
44
+ /** Properties of the master program. */
45
+ export interface IMasterProps {
46
+ /** Total count of the requests. */
47
+ count: number;
48
+
49
+ /**
50
+ * Number of threads.
51
+ *
52
+ * The number of threads to be executed as parallel servant.
53
+ */
54
+ threads: number;
55
+
56
+ /**
57
+ * Number of simultaneous requests.
58
+ *
59
+ * The number of requests to be executed simultaneously.
60
+ *
61
+ * This property value would be divided by the {@link threads} in the
62
+ * servants.
63
+ */
64
+ simultaneous: number;
65
+
66
+ /**
67
+ * Path of the servant program.
68
+ *
69
+ * The path of the servant program executing the
70
+ * {@link DynamicBenchmarker.servant} function.
71
+ */
72
+ servant: string;
73
+
74
+ /**
75
+ * Filter function.
76
+ *
77
+ * The filter function is called with the file name (basename) of each
78
+ * benchmark function module, not with the function name. When it returns
79
+ * `false`, the file would never be imported in the servant, so that every
80
+ * function defined in the file would never be executed either.
81
+ *
82
+ * @param file File name (basename) of the benchmark functions
83
+ * @returns Whether to execute the function or not.
84
+ */
85
+ filter?: (file: string) => boolean;
86
+
87
+ /**
88
+ * Progress callback function.
89
+ *
90
+ * @param complete The number of completed requests.
91
+ */
92
+ progress?: (complete: number) => void;
93
+
94
+ /**
95
+ * Get memory usage.
96
+ *
97
+ * Get the memory usage of the master program.
98
+ *
99
+ * Specify this property only when your backend server is running on a
100
+ * different process, so that need to measure the memory usage of the
101
+ * backend server from other process.
102
+ */
103
+ memory?: () => Promise<NodeJS.MemoryUsage>;
104
+
105
+ /**
106
+ * Standard I/O option.
107
+ *
108
+ * The standard I/O option for the servant programs.
109
+ */
110
+ stdio?: undefined | "overlapped" | "pipe" | "ignore" | "inherit";
111
+ }
112
+
113
+ /** Properties of the servant program. */
114
+ export interface IServantProps<Parameters extends any[]> {
115
+ /**
116
+ * Default connection.
117
+ *
118
+ * Default connection to be used in the servant.
119
+ */
120
+ connection: IConnection;
121
+
122
+ /** Location of the benchmark functions. */
123
+ location: string;
124
+
125
+ /**
126
+ * Extension of the benchmark function files to load, without the leading
127
+ * dot.
128
+ *
129
+ * The servant reads {@link location} and imports every file ending with this
130
+ * extension. Set it to match how the feature files are actually run: `"js"`
131
+ * when they are built JavaScript, or `"ts"` when they are executed from
132
+ * TypeScript source (for example under `ttsx`).
133
+ *
134
+ * @default "js"
135
+ */
136
+ extension?: string;
137
+
138
+ /**
139
+ * Prefix of the benchmark functions.
140
+ *
141
+ * Every prefixed function will be executed in the servant.
142
+ *
143
+ * In other words, if a function name doesn't start with the prefix, then it
144
+ * would never be executed. Also, when a file name (basename) does not start
145
+ * with the prefix, the file would never be imported either, so that every
146
+ * function defined in the file would never be executed.
147
+ */
148
+ prefix: string;
149
+
150
+ /**
151
+ * Get parameters of a function.
152
+ *
153
+ * When composing the parameters, never forget to copy the
154
+ * {@link IConnection.logger} property of default connection to the returning
155
+ * parameters.
156
+ *
157
+ * @param connection Default connection instance
158
+ * @param name Function name
159
+ */
160
+ parameters: (connection: IConnection, name: string) => Parameters;
161
+ }
162
+
163
+ /** Benchmark report. */
164
+ export interface IReport {
165
+ count: number;
166
+ threads: number;
167
+ simultaneous: number;
168
+ started_at: string;
169
+ completed_at: string;
170
+ statistics: IReport.IStatistics;
171
+ endpoints: Array<IReport.IEndpoint & IReport.IStatistics>;
172
+ memories: IReport.IMemory[];
173
+ }
174
+ export namespace IReport {
175
+ export interface IEndpoint {
176
+ method: string;
177
+ path: string;
178
+ }
179
+ export interface IStatistics {
180
+ count: number;
181
+ success: number;
182
+ mean: number | null;
183
+ stdev: number | null;
184
+ minimum: number | null;
185
+ maximum: number | null;
186
+ }
187
+ export interface IMemory {
188
+ time: string;
189
+ usage: NodeJS.MemoryUsage;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Master program.
195
+ *
196
+ * Creates a master program that executing the servant programs in parallel.
197
+ *
198
+ * Note that, {@link IMasterProps.servant} property must be the path of the
199
+ * servant program executing the {@link servant} function.
200
+ *
201
+ * @param props Properties of the master program
202
+ * @returns Benchmark report
203
+ */
204
+ export const master = async (props: IMasterProps): Promise<IReport> => {
205
+ const completes: number[] = new Array(props.threads).fill(0);
206
+ const servants: WorkerConnector<
207
+ null,
208
+ IBenchmarkMaster,
209
+ IBenchmarkServant
210
+ >[] = await Promise.all(
211
+ new Array(props.threads).fill(null).map(async (_, i) => {
212
+ const connector: WorkerConnector<
213
+ null,
214
+ IBenchmarkMaster,
215
+ IBenchmarkServant
216
+ > = new WorkerConnector(
217
+ null,
218
+ {
219
+ filter: props.filter ?? (() => true),
220
+ progress: (current) => {
221
+ completes[i] = current;
222
+ if (props.progress)
223
+ props.progress(completes.reduce((a, b) => a + b, 0));
224
+ },
225
+ },
226
+ "process",
227
+ );
228
+ await connector.connect(props.servant, { stdio: props.stdio });
229
+ return connector;
230
+ }),
231
+ );
232
+
233
+ const started_at: Date = new Date();
234
+ const memories: IReport.IMemory[] = [];
235
+ let completed_at: Date | null = null;
236
+
237
+ (async () => {
238
+ const getter = props.memory ?? (async () => process.memoryUsage());
239
+ while (completed_at === null) {
240
+ await sleep_for(1_000);
241
+ memories.push({
242
+ usage: await getter(),
243
+ time: new Date().toISOString(),
244
+ });
245
+ }
246
+ })().catch(() => {});
247
+
248
+ const events: IBenchmarkEvent[] = (
249
+ await Promise.all(
250
+ servants.map((connector) =>
251
+ connector.getDriver().execute({
252
+ count: Math.ceil(props.count / props.threads),
253
+ simultaneous: Math.ceil(props.simultaneous / props.threads),
254
+ }),
255
+ ),
256
+ )
257
+ ).flat();
258
+
259
+ completed_at = new Date();
260
+ await Promise.all(servants.map((connector) => connector.close()));
261
+ if (props.progress) props.progress(props.count);
262
+
263
+ const endpoints: HashMap<IReport.IEndpoint, IBenchmarkEvent[]> =
264
+ new HashMap(
265
+ (key) => hash(key.method, key.path),
266
+ (x, y) => x.method === y.method && x.path === y.path,
267
+ );
268
+ for (const e of events)
269
+ endpoints
270
+ .take(
271
+ {
272
+ method: e.metadata.method,
273
+ path: e.metadata.template ?? e.metadata.path,
274
+ },
275
+ () => [],
276
+ )
277
+ .push(e);
278
+ return {
279
+ count: props.count,
280
+ threads: props.threads,
281
+ simultaneous: props.simultaneous,
282
+ statistics: statistics(events),
283
+ endpoints: [...endpoints].map((it) => ({
284
+ ...statistics(it.second),
285
+ ...it.first,
286
+ })),
287
+ started_at: started_at.toISOString(),
288
+ completed_at: completed_at.toISOString(),
289
+ memories,
290
+ };
291
+ };
292
+
293
+ /**
294
+ * Create a servant program.
295
+ *
296
+ * Creates a servant program executing the prefixed functions in parallel.
297
+ *
298
+ * @param props Properties of the servant program
299
+ * @returns Servant program as a worker server
300
+ */
301
+ export const servant = async <Parameters extends any[]>(
302
+ props: IServantProps<Parameters>,
303
+ ): Promise<WorkerServer<null, IBenchmarkServant, IBenchmarkMaster>> => {
304
+ const server: WorkerServer<null, IBenchmarkServant, IBenchmarkMaster> =
305
+ new WorkerServer();
306
+ await server.open({
307
+ execute: execute({
308
+ driver: server.getDriver(),
309
+ props,
310
+ }),
311
+ });
312
+ return server;
313
+ };
314
+
315
+ /**
316
+ * Convert the benchmark report to markdown content.
317
+ *
318
+ * @param report Benchmark report
319
+ * @returns Markdown content
320
+ */
321
+ export const markdown = (report: DynamicBenchmarker.IReport): string =>
322
+ DynamicBenchmarkReporter.markdown(report);
323
+
324
+ const execute =
325
+ <Parameters extends any[]>(ctx: {
326
+ driver: Driver<IBenchmarkMaster>;
327
+ props: IServantProps<Parameters>;
328
+ }) =>
329
+ async (mass: {
330
+ count: number;
331
+ simultaneous: number;
332
+ }): Promise<IBenchmarkEvent[]> => {
333
+ const functions: IFunction<Parameters>[] = [];
334
+ await iterate({
335
+ collection: functions,
336
+ driver: ctx.driver,
337
+ props: ctx.props,
338
+ })(ctx.props.location);
339
+
340
+ const entireEvents: IBenchmarkEvent[] = [];
341
+ await Promise.all(
342
+ new Array(mass.simultaneous)
343
+ .fill(null)
344
+ .map(() => 1)
345
+ .map(async () => {
346
+ while (entireEvents.length < mass.count) {
347
+ const localEvents: IBenchmarkEvent[] = [];
348
+ const func: IFunction<Parameters> =
349
+ functions[Math.floor(Math.random() * functions.length)]!;
350
+ const connection: IConnection = {
351
+ ...ctx.props.connection,
352
+ logger: async (fe): Promise<void> => {
353
+ const be: IBenchmarkEvent = {
354
+ metadata: fe.route,
355
+ status: fe.status,
356
+ started_at: fe.started_at.toISOString(),
357
+ respond_at: fe.respond_at?.toISOString() ?? null,
358
+ completed_at: fe.completed_at.toISOString(),
359
+ success: true,
360
+ };
361
+ localEvents.push(be);
362
+ entireEvents.push(be);
363
+ },
364
+ };
365
+ try {
366
+ await func.value(...ctx.props.parameters(connection, func.key));
367
+ } catch (exp) {
368
+ for (const e of localEvents)
369
+ e.success = e.status === 200 || e.status === 201;
370
+ }
371
+ if (localEvents.length !== 0)
372
+ ctx.driver.progress(entireEvents.length).catch(() => {});
373
+ }
374
+ }),
375
+ );
376
+ await ctx.driver.progress(entireEvents.length);
377
+ return entireEvents;
378
+ };
379
+ }
380
+
381
+ interface IFunction<Parameters extends any[]> {
382
+ key: string;
383
+ value: (...args: Parameters) => Promise<void>;
384
+ }
385
+
386
+ const iterate =
387
+ <Parameters extends any[]>(ctx: {
388
+ collection: IFunction<Parameters>[];
389
+ driver: Driver<IBenchmarkMaster>;
390
+ props: DynamicBenchmarker.IServantProps<Parameters>;
391
+ }) =>
392
+ async (path: string): Promise<void> => {
393
+ const directory: string[] = await fs.promises.readdir(path);
394
+ for (const file of directory) {
395
+ const location: string = `${path}/${file}`;
396
+ const stat: fs.Stats = await fs.promises.stat(location);
397
+ if (stat.isDirectory() === true) await iterate(ctx)(location);
398
+ // Load feature files whose extension matches `props.extension`. This is
399
+ // configurable instead of inferred from the servant's own module
400
+ // extension, because the benchmark library may be built (`.js`) while the
401
+ // feature files it drives are run from source (`.ts`, e.g. under `ttsx`);
402
+ // inferring would look for `.js` features that do not exist, load
403
+ // nothing, and spin forever.
404
+ else if (
405
+ file.endsWith(`.${ctx.props.extension ?? "js"}`) &&
406
+ file.endsWith(".d.ts") === false
407
+ ) {
408
+ // GATE BY FILE NAME (PREFIX & FILTER), SO THAT EXCLUDED FILES ARE
409
+ // NEVER IMPORTED.
410
+ if (file.startsWith(ctx.props.prefix) === false) continue;
411
+ if ((await ctx.driver.filter(file)) === false) continue;
412
+ const modulo = await import(location);
413
+ for (const [key, value] of Object.entries(modulo)) {
414
+ if (typeof value !== "function") continue;
415
+ else if (key.startsWith(ctx.props.prefix) === false) continue;
416
+ ctx.collection.push({
417
+ key,
418
+ value: value as (...args: Parameters) => Promise<any>,
419
+ });
420
+ }
421
+ }
422
+ }
423
+ };
424
+
425
+ const statistics = (
426
+ events: IBenchmarkEvent[],
427
+ ): DynamicBenchmarker.IReport.IStatistics => {
428
+ const successes: IBenchmarkEvent[] = events.filter((event) => event.success);
429
+ return {
430
+ count: events.length,
431
+ success: successes.length,
432
+ ...average(events),
433
+ };
434
+ };
435
+
436
+ const average = (
437
+ events: IBenchmarkEvent[],
438
+ ): Pick<
439
+ DynamicBenchmarker.IReport.IStatistics,
440
+ "mean" | "stdev" | "minimum" | "maximum"
441
+ > => {
442
+ if (events.length === 0)
443
+ return {
444
+ mean: null,
445
+ stdev: null,
446
+ minimum: null,
447
+ maximum: null,
448
+ };
449
+ let mean: number = 0;
450
+ let stdev: number = 0;
451
+ let minimum: number = Number.MAX_SAFE_INTEGER;
452
+ let maximum: number = Number.MIN_SAFE_INTEGER;
453
+ for (const event of events) {
454
+ const elapsed: number =
455
+ new Date(event.completed_at).getTime() -
456
+ new Date(event.started_at).getTime();
457
+ mean += elapsed;
458
+ stdev += elapsed * elapsed;
459
+ minimum = Math.min(minimum, elapsed);
460
+ maximum = Math.max(maximum, elapsed);
461
+ }
462
+ mean /= events.length;
463
+ stdev = Math.sqrt(stdev / events.length - mean * mean);
464
+ return { mean, stdev, minimum, maximum };
465
+ };