-
Notifications
You must be signed in to change notification settings - Fork 2
/
toctl.ts
334 lines (313 loc) · 10.2 KB
/
toctl.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
import {
colors,
docopt,
govnSvcHealth as gsh,
govnSvcVersion as gsv,
oakHelpers as oakH,
path,
} from "./deps.ts";
import * as server from "./server.ts";
import * as tm from "./template-module.ts";
// deno-lint-ignore require-await
export async function determineVersion(importMetaURL: string): Promise<string> {
return gsv.determineVersionFromRepoTag(
importMetaURL,
{ repoIdentity: "gov-suite/governed-text-template" },
);
}
const toctlVersion = await determineVersion(import.meta.url);
const docoptSpec = `
Template Orchestration Controller ${toctlVersion}.
Usage:
toctl server [--port=<port>] [--module=<module-spec>]... [--default-module=<module-url>] [--default-tmpl-id=<template-identity>] [--allow-arbitrary-modules] [--module-spec-delim=<delimiter>] [--verbose]
toctl transform json [--default-module=<module-url>] [--default-tmpl-id=<template-identity>] [--allow-arbitrary-modules]
toctl validate config --module=<module-spec>... [--verbose] [--module-spec-delim=<delimiter>] [--default-module=<module-url>] [--default-tmpl-id=<template-identity>]
toctl -h | --help
toctl --version
Options:
-h --help Show this screen
<module-spec> A pre-defined module template (with an optional name like --module="./x.ts,x")
<module-url> A module template URL
<delimiter> The character(s) used to separate pre-defined template module name and URL (default ",")
--version Show version
--verbose Be explicit about what's going on
`;
export function buildTransformJsonInputOptions(
chc: CommandHandlerContext,
): tm.TransformJsonInputOptions {
const { "--allow-arbitrary-modules": allowArbitraryModules } = chc.cliOptions;
const templateModules = chc.templateModules();
return {
allowArbitraryModule: (templateUrl) => {
return allowArbitraryModules ? true : false;
},
defaultTemplateModuleURL: (): string => {
return chc.defaultTemplateModule() || `./template-module-debug.ts`;
},
defaultTemplateIdentity: (): string | undefined => {
return chc.defaultTemplateIdentity();
},
onArbitraryModuleNotAllowed: (templateUrl: string): string => {
return `Server was not started with --allow-arbitrary-modules, can only use pre-defined modules (not ${templateUrl})`;
},
namedTemplateModuleURL: (name: string): string | undefined => {
return templateModules ? templateModules[name] : undefined;
},
};
}
export async function httpServiceHandler(
chc: CommandHandlerContext,
): Promise<true | void> {
const { "server": isServer } = chc.cliOptions;
if (isServer) {
console.log(`Template Orchestration server started`);
const templateModules = chc.templateModules();
if (templateModules) {
chc.validateTemplateModules(templateModules);
}
const app = server.httpServer({
port: chc.httpServicePort(),
router: server.httpServiceRouter(
{
templateModules: () => {
return templateModules;
},
...buildTransformJsonInputOptions(chc),
},
),
});
// TODO: add https://github.com/marcopacini/ts-prometheus based /metrics route
// TODO: add https://github.com/singhcool/deno-swagger-doc based OpenAPI generator
oakH.registerHealthRoute(app, {
serviceVersion: () => {
return toctlVersion;
},
endpoint: async () => {
const hs = gsh.healthyService({
version: "1",
releaseID: toctlVersion,
...(templateModules
? await chc.templateModulesHealthStatus(templateModules)
: { details: {} }),
});
return gsh.healthStatusEndpoint(hs);
},
});
await app.listen({ port: chc.httpServicePort() });
return true;
}
}
export async function transformStdInJsonHandler(
chc: CommandHandlerContext,
): Promise<true | void> {
const { "transform": transform, "json": json } = chc.cliOptions;
if (transform && json) {
const input = Deno.readAllSync(Deno.stdin);
if (!input || input.length > 0) {
console.log(
await tm.transformJsonInput(input, buildTransformJsonInputOptions(chc)),
);
} else {
console.error("No JSON provided in STDIN");
}
return true;
}
}
// deno-lint-ignore require-await
export async function validateConfigHandler(
chc: CommandHandlerContext,
): Promise<true | void> {
const { "validate": validate, "config": config } = chc.cliOptions;
if (validate && config) {
const templateModules = chc.templateModules();
if (!templateModules) {
console.error("No --module entries defined.");
return true;
}
if (chc.isVerbose && templateModules) {
console.log("Pre-defined template modules:");
console.dir(templateModules);
}
chc.validateTemplateModules(templateModules);
return true;
}
}
export interface CommandHandler<T extends CommandHandlerContext> {
(ctx: T): Promise<true | void>;
}
export class CommandHandlerContext implements CommandHandlerContext {
readonly defaultHttpServicePort = 8179;
readonly isVerbose: boolean;
constructor(
readonly calledFromMetaURL: string,
readonly calledFromMain: boolean,
readonly cliOptions: docopt.DocOptions,
) {
const { "--verbose": verbose } = this.cliOptions;
this.isVerbose = verbose ? true : false;
}
httpServicePort(): number {
const { "--port": portSpec } = this.cliOptions;
const port = typeof portSpec === "number"
? portSpec
: (typeof portSpec === "string" ? Number.parseInt(portSpec)
: this.defaultHttpServicePort);
if (isNaN(port)) {
console.error(
`Invalid --port supplied (${portSpec}), defaulting to ${this.defaultHttpServicePort}.`,
);
return this.defaultHttpServicePort;
}
return port;
}
templateModules(): Record<string, string> | undefined {
const {
"--module": templateModuleSpecs,
"--module-spec-delim": moduleSpecDelim,
} = this.cliOptions;
if (Array.isArray(templateModuleSpecs)) {
const result: Record<string, string> = {};
const delim = typeof moduleSpecDelim === "string" ? moduleSpecDelim : ",";
for (const module of templateModuleSpecs) {
const [url, name] = module.split(delim);
result[name && name.length > 0 ? name : path.basename(url, "")] = url;
}
return result;
}
return undefined;
}
defaultTemplateModule(): string | undefined {
const { "--default-module": defaultModuleURL } = this.cliOptions;
return typeof defaultModuleURL === "string" ? defaultModuleURL : undefined;
}
defaultTemplateIdentity(): string | undefined {
const { "--default-tmpl-id": defaultTemplateId } = this.cliOptions;
return typeof defaultTemplateId === "string"
? defaultTemplateId
: undefined;
}
async templateModulesHealthStatus(
templateModules: Record<string, string>,
): Promise<gsh.ServiceHealthComponents> {
const result: gsh.ServiceHealthComponents = {
details: {},
};
const addStatus = (
tmplName: string,
tmplUrl: string,
diagnostic?: string,
): void => {
const component: Omit<gsh.HealthyServiceHealthComponentStatus, "status"> =
{
componentId: tmplName,
componentType: "component",
time: new Date(),
links: { templateURL: tmplUrl },
};
if (diagnostic) {
result.details[`template:${tmplName}`] = [
gsh.unhealthyComponent("fail", {
...component,
output: diagnostic,
}),
];
} else {
result.details[`template:${tmplName}`] = [
gsh.healthyComponent(component),
];
}
};
for (const entry of Object.entries(templateModules)) {
const [name, url] = entry;
const [_, diagnostic] = await tm.importTemplateModuleHandlers({
srcURL: url,
});
addStatus(name, url, diagnostic);
}
const defaultTmplUrl = this.defaultTemplateModule();
if (defaultTmplUrl) {
const [_, diagnostic] = await tm.importTemplateModuleHandlers({
srcURL: defaultTmplUrl,
});
addStatus("DEFAULT", defaultTmplUrl, diagnostic);
}
return result;
}
async validateTemplateModules(
templateModules: Record<string, string>,
): Promise<void> {
const health = await this.templateModulesHealthStatus(templateModules);
for (const entry of Object.entries(health.details)) {
const [name, componentStates] = entry;
if (Array.isArray(componentStates)) {
for (const state of componentStates) {
if (gsh.isServiceHealthDiagnosable(state)) {
console.error(
`${colors.yellow(state.componentId)}: ${
colors.brightWhite(state.links["templateURL"])
} ${colors.red(state.output)}`,
);
} else if (this.isVerbose) {
console.log(
`${colors.yellow(state.componentId)}: ${
colors.brightWhite(state.links["templateURL"])
} ${colors.green("OK")}`,
);
}
}
}
}
}
}
// deno-lint-ignore require-await
export async function versionHandler(
ctx: CommandHandlerContext,
): Promise<true | void> {
const { "--version": version } = ctx.cliOptions;
if (version) {
console.log(toctlVersion);
return true;
}
}
export const commonHandlers = [versionHandler];
export async function CLI<
T extends CommandHandlerContext = CommandHandlerContext,
>(
docoptSpec: string,
handlers: CommandHandler<T>[],
prepareContext: (options: docopt.DocOptions) => T,
): Promise<void> {
try {
const options = docopt.default(docoptSpec);
const context = prepareContext(options);
let handled: true | void;
for (const handler of handlers) {
handled = await handler(context);
if (handled) break;
}
if (!handled) {
console.error("Unable to handle validly parsed docoptSpec:");
console.dir(options);
}
} catch (e) {
console.error(e.message);
}
}
if (import.meta.main) {
CLI(
docoptSpec,
[
httpServiceHandler,
transformStdInJsonHandler,
validateConfigHandler,
...commonHandlers,
],
(options: docopt.DocOptions): CommandHandlerContext => {
return new CommandHandlerContext(
import.meta.url,
import.meta.main,
options,
);
},
);
}