|
| 1 | +import path from "path"; |
| 2 | +import { EOL } from "os"; |
| 3 | + |
| 4 | +import * as Benchmark from "benchmark"; |
| 5 | +import { v4 as uuidv4 } from "uuid"; |
| 6 | +import type { AuthorizeOptions as SocketIoJwtOptions } from "@thream/socketio-jwt"; |
| 7 | +import type { Params as ExpressJwtOptions } from "express-jwt"; |
| 8 | +import { SignJWT, exportSPKI, generateKeyPair } from "jose"; |
| 9 | +import { RuntimeError } from "run-time-error-cjs"; |
| 10 | +import * as grpc from "@grpc/grpc-js"; |
| 11 | +import fse from "fs-extra"; |
| 12 | + |
| 13 | +import { LogLevelDesc } from "@hyperledger/cactus-common"; |
| 14 | + |
| 15 | +import { IJoseFittingJwtParams } from "@hyperledger/cactus-common"; |
| 16 | +import { PluginRegistry } from "@hyperledger/cactus-core"; |
| 17 | +import { Constants } from "@hyperledger/cactus-core-api"; |
| 18 | + |
| 19 | +import { |
| 20 | + ApiServer, |
| 21 | + ApiServerApiClient, |
| 22 | + ApiServerApiClientConfiguration, |
| 23 | + AuthorizationProtocol, |
| 24 | + ConfigService, |
| 25 | + IAuthorizationConfig, |
| 26 | +} from "../../../main/typescript/public-api"; |
| 27 | + |
| 28 | +import { default_service, empty } from "../../../main/typescript/public-api"; |
| 29 | + |
| 30 | +const LOG_TAG = |
| 31 | + "[packages/cactus-cmd-api-server/src/test/typescript/benchmark/run-cmd-api-server-benchmark.ts]"; |
| 32 | + |
| 33 | +const createTestInfrastructure = async (opts: { |
| 34 | + readonly logLevel: LogLevelDesc; |
| 35 | +}): Promise<{ |
| 36 | + readonly httpApi: ApiServerApiClient; |
| 37 | + readonly grpcCredentials: grpc.ChannelCredentials; |
| 38 | + readonly grpcHost: string; |
| 39 | + readonly apiServer: ApiServer; |
| 40 | +}> => { |
| 41 | + const logLevel = opts.logLevel || "DEBUG"; |
| 42 | + |
| 43 | + const jwtKeyPair = await generateKeyPair("RS256", { modulusLength: 4096 }); |
| 44 | + const jwtPublicKey = await exportSPKI(jwtKeyPair.publicKey); |
| 45 | + const expressJwtOptions: ExpressJwtOptions & IJoseFittingJwtParams = { |
| 46 | + algorithms: ["RS256"], |
| 47 | + secret: jwtPublicKey, |
| 48 | + audience: uuidv4(), |
| 49 | + issuer: uuidv4(), |
| 50 | + }; |
| 51 | + const socketIoJwtOptions: SocketIoJwtOptions = { |
| 52 | + secret: jwtPublicKey, |
| 53 | + algorithms: ["RS256"], |
| 54 | + }; |
| 55 | + |
| 56 | + const authorizationConfig: IAuthorizationConfig = { |
| 57 | + unprotectedEndpointExemptions: [], |
| 58 | + expressJwtOptions, |
| 59 | + socketIoJwtOptions, |
| 60 | + socketIoPath: Constants.SocketIoConnectionPathV1, |
| 61 | + }; |
| 62 | + |
| 63 | + const pluginsPath = path.join( |
| 64 | + __dirname, |
| 65 | + "../../../../../../", // walk back up to the project root |
| 66 | + "packages/cactus-cmd-api-server/src/test/typescript/benchmark/run-cmd-api-server-benchmark/", // the dir path from the root |
| 67 | + uuidv4(), // then a random directory to ensure proper isolation |
| 68 | + ); |
| 69 | + const pluginManagerOptionsJson = JSON.stringify({ pluginsPath }); |
| 70 | + |
| 71 | + const pluginRegistry = new PluginRegistry({ logLevel }); |
| 72 | + |
| 73 | + const configService = new ConfigService(); |
| 74 | + |
| 75 | + const apiSrvOpts = await configService.newExampleConfig(); |
| 76 | + apiSrvOpts.logLevel = logLevel; |
| 77 | + apiSrvOpts.pluginManagerOptionsJson = pluginManagerOptionsJson; |
| 78 | + apiSrvOpts.authorizationProtocol = AuthorizationProtocol.JSON_WEB_TOKEN; |
| 79 | + apiSrvOpts.authorizationConfigJson = authorizationConfig; |
| 80 | + apiSrvOpts.configFile = ""; |
| 81 | + apiSrvOpts.apiCorsDomainCsv = "*"; |
| 82 | + apiSrvOpts.apiPort = 0; |
| 83 | + apiSrvOpts.cockpitPort = 0; |
| 84 | + apiSrvOpts.grpcPort = 0; |
| 85 | + apiSrvOpts.apiTlsEnabled = false; |
| 86 | + apiSrvOpts.grpcMtlsEnabled = false; |
| 87 | + apiSrvOpts.plugins = []; |
| 88 | + |
| 89 | + const config = await configService.newExampleConfigConvict(apiSrvOpts); |
| 90 | + |
| 91 | + const apiServer = new ApiServer({ |
| 92 | + config: config.getProperties(), |
| 93 | + pluginRegistry, |
| 94 | + }); |
| 95 | + |
| 96 | + apiServer.initPluginRegistry({ pluginRegistry }); |
| 97 | + const startResponsePromise = apiServer.start(); |
| 98 | + |
| 99 | + const { addressInfoApi, addressInfoGrpc } = await startResponsePromise; |
| 100 | + const protocol = apiSrvOpts.apiTlsEnabled ? "https" : "http"; |
| 101 | + const { address, port } = addressInfoApi; |
| 102 | + const apiHost = `${protocol}://${address}:${port}`; |
| 103 | + |
| 104 | + const grpcHost = `${addressInfoGrpc.address}:${addressInfoGrpc.port}`; |
| 105 | + |
| 106 | + const jwtPayload = { name: "Peter", location: "Albertirsa" }; |
| 107 | + const validJwt = await new SignJWT(jwtPayload) |
| 108 | + .setProtectedHeader({ alg: "RS256" }) |
| 109 | + .setIssuer(expressJwtOptions.issuer) |
| 110 | + .setAudience(expressJwtOptions.audience) |
| 111 | + .sign(jwtKeyPair.privateKey); |
| 112 | + |
| 113 | + const validBearerToken = `Bearer ${validJwt}`; |
| 114 | + |
| 115 | + const apiClient = new ApiServerApiClient( |
| 116 | + new ApiServerApiClientConfiguration({ |
| 117 | + basePath: apiHost, |
| 118 | + baseOptions: { headers: { Authorization: validBearerToken } }, |
| 119 | + logLevel, |
| 120 | + }), |
| 121 | + ); |
| 122 | + |
| 123 | + const grpcCredentials = grpc.credentials.createInsecure(); |
| 124 | + |
| 125 | + return { |
| 126 | + grpcCredentials, |
| 127 | + httpApi: apiClient, |
| 128 | + grpcHost, |
| 129 | + apiServer, |
| 130 | + }; |
| 131 | +}; |
| 132 | + |
| 133 | +const main = async (opts: { readonly argv: Readonly<Array<string>> }) => { |
| 134 | + const logLevel: LogLevelDesc = "WARN"; |
| 135 | + |
| 136 | + const gitRootPath = path.join( |
| 137 | + __dirname, |
| 138 | + "../../../../../../", // walk back up to the project root |
| 139 | + ); |
| 140 | + |
| 141 | + console.log("%s gitRootPath=%s", LOG_TAG, gitRootPath); |
| 142 | + |
| 143 | + const DEFAULT_OUTPUT_FILE_RELATIVE_PATH = |
| 144 | + ".tmp/benchmark-results/cmd-api-server/run-cmd-api-server-benchmark.ts.log"; |
| 145 | + |
| 146 | + const relativeOutputFilePath = |
| 147 | + opts.argv[2] === undefined |
| 148 | + ? DEFAULT_OUTPUT_FILE_RELATIVE_PATH |
| 149 | + : opts.argv[2]; |
| 150 | + |
| 151 | + console.log( |
| 152 | + "%s DEFAULT_OUTPUT_FILE_RELATIVE_PATH=%s", |
| 153 | + LOG_TAG, |
| 154 | + DEFAULT_OUTPUT_FILE_RELATIVE_PATH, |
| 155 | + ); |
| 156 | + |
| 157 | + console.log("%s opts.argv[2]=%s", LOG_TAG, opts.argv[2]); |
| 158 | + |
| 159 | + console.log("%s relativeOutputFilePath=%s", LOG_TAG, relativeOutputFilePath); |
| 160 | + |
| 161 | + const absoluteOutputFilePath = path.join(gitRootPath, relativeOutputFilePath); |
| 162 | + |
| 163 | + console.log("%s absoluteOutputFilePath=%s", LOG_TAG, absoluteOutputFilePath); |
| 164 | + |
| 165 | + const absoluteOutputDirPath = path.dirname(absoluteOutputFilePath); |
| 166 | + console.log("%s absoluteOutputDirPath=%s", LOG_TAG, absoluteOutputDirPath); |
| 167 | + |
| 168 | + await fse.mkdirp(absoluteOutputDirPath); |
| 169 | + console.log("%s mkdir -p OK: %s", LOG_TAG, absoluteOutputDirPath); |
| 170 | + |
| 171 | + const { apiServer, httpApi, grpcHost, grpcCredentials } = |
| 172 | + await createTestInfrastructure({ logLevel }); |
| 173 | + |
| 174 | + const minSamples = 100; |
| 175 | + const suite = new Benchmark.Suite({}); |
| 176 | + |
| 177 | + const cycles: string[] = []; |
| 178 | + |
| 179 | + await new Promise((resolve, reject) => { |
| 180 | + suite |
| 181 | + .add("cmd-api-server_HTTP_GET_getOpenApiSpecV1", { |
| 182 | + defer: true, |
| 183 | + minSamples, |
| 184 | + fn: async function (deferred: Benchmark.Deferred) { |
| 185 | + await httpApi.getOpenApiSpecV1(); |
| 186 | + deferred.resolve(); |
| 187 | + }, |
| 188 | + }) |
| 189 | + .add("cmd-api-server_gRPC_GetOpenApiSpecV1", { |
| 190 | + defer: true, |
| 191 | + minSamples, |
| 192 | + fn: async function (deferred: Benchmark.Deferred) { |
| 193 | + const grpcClient = |
| 194 | + new default_service.org.hyperledger.cactus.cmd_api_server.DefaultServiceClient( |
| 195 | + grpcHost, |
| 196 | + grpcCredentials, |
| 197 | + ); |
| 198 | + |
| 199 | + await new Promise<default_service.org.hyperledger.cactus.cmd_api_server.GetOpenApiSpecV1Response>( |
| 200 | + (resolve, reject) => { |
| 201 | + const req = new empty.google.protobuf.Empty(); |
| 202 | + grpcClient.GetOpenApiSpecV1(req, (err3, value) => { |
| 203 | + if (err3) { |
| 204 | + reject(err3); |
| 205 | + } else if (value) { |
| 206 | + resolve(value); |
| 207 | + } else { |
| 208 | + reject( |
| 209 | + new RuntimeError("Response object received is falsy."), |
| 210 | + ); |
| 211 | + } |
| 212 | + }); |
| 213 | + }, |
| 214 | + ); |
| 215 | + |
| 216 | + grpcClient.close(); |
| 217 | + deferred.resolve(); |
| 218 | + }, |
| 219 | + }) |
| 220 | + .on("cycle", (event: { target: unknown }) => { |
| 221 | + // Output benchmark result by converting benchmark result to string |
| 222 | + // Example line on stdout: |
| 223 | + // cmd-api-server_HTTP_GET_getOpenApiSpecV1 x 1,020 ops/sec ±2.25% (177 runs sampled) |
| 224 | + const cycle = String(event.target); |
| 225 | + console.log("%s Benchmark.js CYCLE: %s", LOG_TAG, cycle); |
| 226 | + cycles.push(cycle); |
| 227 | + }) |
| 228 | + .on("complete", function () { |
| 229 | + console.log("%s Benchmark.js COMPLETE.", LOG_TAG); |
| 230 | + resolve(suite); |
| 231 | + }) |
| 232 | + .on("error", (ex: unknown) => { |
| 233 | + console.log("%s Benchmark.js ERROR: %o", LOG_TAG, ex); |
| 234 | + reject(ex); |
| 235 | + }) |
| 236 | + .run(); |
| 237 | + }); |
| 238 | + |
| 239 | + const data = cycles.join(EOL); |
| 240 | + console.log("%s Writing results...", LOG_TAG); |
| 241 | + await fse.writeFile(absoluteOutputFilePath, data, { encoding: "utf-8" }); |
| 242 | + console.log("%s Wrote results to %s", LOG_TAG, absoluteOutputFilePath); |
| 243 | + |
| 244 | + await apiServer.shutdown(); |
| 245 | + console.log("%s Shut down API server OK", LOG_TAG); |
| 246 | +}; |
| 247 | + |
| 248 | +main({ argv: process.argv }).catch((ex: unknown) => { |
| 249 | + console.error("%s process crashed with:", LOG_TAG, ex); |
| 250 | + process.exit(1); |
| 251 | +}); |
0 commit comments