-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconfig.ts
More file actions
142 lines (132 loc) · 4.76 KB
/
config.ts
File metadata and controls
142 lines (132 loc) · 4.76 KB
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
import { Modules } from "./Modules.ts";
import { Tenant } from "./tenant.ts";
import * as log from "std/log/mod.ts";
import { ConsoleHandler, RotatingFileHandler } from "std/log/mod.ts";
import { Validate, validator } from "https://cdn.skypack.dev/@exodus/schemasafe?dts";
import * as path from "std/path/mod.ts";
import { LogRecord } from "std/log/logger.ts";
import { Authoriser } from "./auth/Authoriser.ts";
import { schemaIChordServiceConfig } from "rs-core/IServiceConfig.ts";
import { Message } from "rs-core/Message.ts";
import { stripUndefined } from "rs-core/utility/schema.ts";
export interface Infra {
adapterSource: string; // cannot be site relative
}
export interface IServerConfig {
tenancy: "single" | "multi";
mainDomain: string,
domainMap: { [domain: string]: string };
infra: { [ name: string ]: Infra };
configStore: string;
stateStore: string;
incomingAlwaysHttps?: boolean;
setServerCors(msg: Message): Message;
}
const LOG_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
const formatter = (rec: LogRecord) => {
let severity = 'DEBUG';
switch (rec.levelName) {
case "NOTSET":
severity = "TRACE";
break;
case "INFO":
severity = "INFO ";
break;
case "WARN":
severity = "WARN ";
break;
case "ERROR":
severity = "ERROR";
break;
case "CRITICAL":
severity = "FATAL";
break;
}
let [ tenant, service, username, traceId, spanId, eventTimestamp ] = rec.args;
if (!tenant) tenant = 'global';
if (!service) service = '?'; else service = (service as string).replace(/ /g, '_');
if (!username) username = '?';
if (!traceId) traceId = 'x'.repeat(32);
if (!spanId) spanId = 'x'.repeat(16);
const timestamp = typeof eventTimestamp === "string" && LOG_TIMESTAMP_PATTERN.test(eventTimestamp)
? eventTimestamp
: rec.datetime.toISOString();
return `${severity} ${timestamp} ${traceId} ${spanId} ${tenant} ${service} ${username} ${rec.msg}`;
}
export type LogLevel = "NOTSET" | "DEBUG" | "INFO" | "WARN" | "ERROR" | "CRITICAL";
// we allow for extra schema properties like 'editor' to direct UI
const defaultValidator = (schema: any) => {
const v = validator(schema, { includeErrors: true, allErrors: true, allowUnusedKeywords: true });
const v2 = ((data: any) => {
const newData = stripUndefined(data);
return v(newData);
}) as unknown as Validate;
v2.toModule = v.toModule;
v2.toJSON = v.toJSON;
return v2;
};
export class RequestAbortActions {
actions: Record<string, (() => void)[]> = {};
add(id: string, action: () => void) {
if (this.actions[id] === undefined) {
this.actions[id] = [ action ];
} else {
this.actions[id].push(action);
}
}
abort(id: string) {
if (this.actions[id]) this.actions[id].forEach(action => action());
}
clear(id: string) {
if (id) delete this.actions[id];
}
}
export const config = {
server: {} as IServerConfig,
modules: new Modules(defaultValidator),
tenants: {} as { [ name: string ]: Tenant },
logger: log.getLogger(),
// path.resolves resolves relative to dir of current source file, which is repo root
fixRelativeToRoot: (pathUrl: string) => pathUrl.startsWith('.') ? path.resolve(pathUrl) : pathUrl,
defaultValidator,
jwtExpiryMins: 30,
getParam: (key: string) => Deno.env.get(key),
authoriser: new Authoriser(),
validateChordService: defaultValidator(schemaIChordServiceConfig),
validateChord: defaultValidator({
type: "object",
properties: {
id: { type: "string" },
newServices: {
type: "array",
items: {
schemaIChordServiceConfig
}
}
}
}),
requestExternal: null as null | ((msg: Message) => Promise<Message>),
canonicaliseUrl: (url: string, tenant?: string, primaryDomain?: string) =>
url.startsWith('/') ? "https://" + (primaryDomain || config.tenants[tenant || ''].primaryDomain) + url : url,
requestAbortActions: new RequestAbortActions()
}
export const setupLogging = async (level: LogLevel) => {
await log.setup({
handlers: {
console: new ConsoleHandler(level, { formatter }),
file: new RotatingFileHandler(level, {
maxBytes: 512 * 1024,
maxBackupCount: 5,
filename: './main.log',
formatter
})
},
loggers: {
default: {
level,
handlers: [ 'console', 'file' ]
}
}
});
config.logger = log.getLogger();
}