@sfxcode/mongocamp-server-core 2.0.0 → 2.1.0
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.
- package/README.md +13 -0
- package/dist/index.d.mts +80 -11
- package/dist/index.mjs +117 -19
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -27,6 +27,13 @@ The keys are the env variables of the Scala server (`CONNECTION_*`, `AUTH_*`, `C
|
|
|
27
27
|
|
|
28
28
|
The category `jvm` holds the numbers of the Node runtime (`nodejs_*`).
|
|
29
29
|
|
|
30
|
+
## Logging
|
|
31
|
+
|
|
32
|
+
`logger` (`{ info, warn, error }`, default `console`) receives the messages of the server. `server.fetch(request, { log, requestId })`
|
|
33
|
+
adds the fields of the server under `mongocamp` to the wide event of the host (anything with `set(fields)`, e.g. evlog's request logger)
|
|
34
|
+
and uses the host's request id for `x-request-id` and the events. `apps/server` does both with `evlog/nitro/v3`; the Nuxt module passes
|
|
35
|
+
the event of `evlog/nuxt` when the application uses it.
|
|
36
|
+
|
|
30
37
|
## Extensions
|
|
31
38
|
|
|
32
39
|
The dynamic JVM plugins of the Scala server are replaced by three things a host can use.
|
|
@@ -62,8 +69,14 @@ await createMongocampServer({
|
|
|
62
69
|
enabled: true, // false: this instance does not run the jobs on their schedule (several instances of one application)
|
|
63
70
|
},
|
|
64
71
|
})
|
|
72
|
+
|
|
73
|
+
// later, e.g. in a Nuxt application through useMongocampCore(): schedules the stored jobs of the class right away
|
|
74
|
+
const remove = server.registerJobHandler('my.app.CleanupJob', async run => cleanup(run.config))
|
|
65
75
|
```
|
|
66
76
|
|
|
77
|
+
`JOBS_ENABLED=false` (environment or `config`, never stored) switches the scheduler of an instance off as well, also for the standalone
|
|
78
|
+
server.
|
|
79
|
+
|
|
67
80
|
### Routes
|
|
68
81
|
|
|
69
82
|
Routes of the host go in front of the core: answer them yourself and give every other request to `server.fetch`. In Nitro 3 a route
|
package/dist/index.d.mts
CHANGED
|
@@ -37,6 +37,7 @@ declare const ConfigKeys: {
|
|
|
37
37
|
readonly ImportMaxBytes: "IMPORT_MAX_BYTES";
|
|
38
38
|
readonly FilterTimeZone: "FILTER_TIME_ZONE";
|
|
39
39
|
readonly MigrationDropScalaLeftovers: "MIGRATION_DROP_SCALA_LEFTOVERS";
|
|
40
|
+
readonly JobsEnabled: "JOBS_ENABLED";
|
|
40
41
|
readonly AuthPrefix: "AUTH_PREFIX";
|
|
41
42
|
readonly AuthBearer: "AUTH_BEARER";
|
|
42
43
|
readonly AuthBasic: "AUTH_BASIC";
|
|
@@ -112,6 +113,24 @@ declare class ConfigStore {
|
|
|
112
113
|
allDefinitions(): ConfigDefinition[];
|
|
113
114
|
}
|
|
114
115
|
|
|
116
|
+
/**
|
|
117
|
+
* The log of the server: `console` by default, any structured logger (evlog, consola, pino) through the option `logger`. The core never
|
|
118
|
+
* depends on a logging library; a host adapts its logger to these three functions.
|
|
119
|
+
*/
|
|
120
|
+
interface MongocampLogger {
|
|
121
|
+
info: (message: string) => void;
|
|
122
|
+
warn: (message: string) => void;
|
|
123
|
+
error: (message: string, error?: unknown) => void;
|
|
124
|
+
}
|
|
125
|
+
declare const consoleLogger: MongocampLogger;
|
|
126
|
+
/**
|
|
127
|
+
* The wide event of one request, e.g. the request logger of evlog (`useLogger(event)`): anything with `set`. The server adds its fields under
|
|
128
|
+
* the key `mongocamp` (`requestFields`), the host emits the event.
|
|
129
|
+
*/
|
|
130
|
+
interface RequestLog {
|
|
131
|
+
set: (fields: Record<string, unknown>) => void;
|
|
132
|
+
}
|
|
133
|
+
|
|
115
134
|
interface DatabaseOptions {
|
|
116
135
|
/** A full MongoDB connection string. Takes precedence over the `CONNECTION_*` configurations. */
|
|
117
136
|
connectionUri?: string;
|
|
@@ -265,7 +284,7 @@ declare class MongoAuthHolder implements AuthHolder {
|
|
|
265
284
|
get users(): Collection;
|
|
266
285
|
get rolesCollection(): Collection;
|
|
267
286
|
/** Creates the indexes and, for an empty user collection, the user `admin` with a random password that is printed once. */
|
|
268
|
-
createIndicesAndInitData(log?: (message: string) => void): Promise<void>;
|
|
287
|
+
createIndicesAndInitData(log?: (message: string) => void, warn?: (message: string) => void): Promise<void>;
|
|
269
288
|
/**
|
|
270
289
|
* Unique index for the api-key lookup, partial on string values (users without a key store `null`). A database in which two users share
|
|
271
290
|
* a key (possible with the Scala server, which had no index) gets a non-unique index instead, so the start never fails on old data.
|
|
@@ -356,8 +375,10 @@ declare class AuthService {
|
|
|
356
375
|
readonly tokens: TokenCache;
|
|
357
376
|
/** Key: SHA-256 of user and password; value: the stored hash that was verified, valid while the user still has it. */
|
|
358
377
|
private readonly basicCache;
|
|
378
|
+
/** The user of a request once it is authenticated, for the fields of its wide event (`userOf`). */
|
|
379
|
+
private readonly requestUsers;
|
|
359
380
|
constructor(database: MongocampDatabase, config: ConfigStore, version: VersionInfo);
|
|
360
|
-
initialize(): Promise<void>;
|
|
381
|
+
initialize(logger?: MongocampLogger): Promise<void>;
|
|
361
382
|
/** The users and roles in the database, for the routes that change them (only with `AUTH_HANDLER=mongo`). */
|
|
362
383
|
get mongoHolder(): MongoAuthHolder | undefined;
|
|
363
384
|
get bearerEnabled(): boolean;
|
|
@@ -368,6 +389,8 @@ declare class AuthService {
|
|
|
368
389
|
authenticateUser(credentials: Credentials): Promise<UserInformation>;
|
|
369
390
|
/** The logged in user of a request with the current roles. */
|
|
370
391
|
authenticate(request: Request): Promise<AuthorizedUser>;
|
|
392
|
+
/** The id of the user a request was authenticated as, `undefined` before (or without) the authentication. */
|
|
393
|
+
userOf(request: Request): string | undefined;
|
|
371
394
|
/** The error for a logged in user without the grant for a request; the status is `AUTH_GRANT_DENIED_STATUS` (403) or 401. */
|
|
372
395
|
grantDenied(message: string): MongocampError;
|
|
373
396
|
requireAdmin(request: Request): Promise<AuthorizedUser>;
|
|
@@ -1228,9 +1251,10 @@ declare class JobScheduler {
|
|
|
1228
1251
|
private readonly events;
|
|
1229
1252
|
private readonly handlers;
|
|
1230
1253
|
private readonly options;
|
|
1254
|
+
private readonly logger;
|
|
1231
1255
|
private readonly entries;
|
|
1232
1256
|
private timer;
|
|
1233
|
-
constructor(database: MongocampDatabase, events: EventBus, handlers: Map<string, JobHandler>, options: SchedulerOptions);
|
|
1257
|
+
constructor(database: MongocampDatabase, events: EventBus, handlers: Map<string, JobHandler>, options: SchedulerOptions, logger?: MongocampLogger);
|
|
1234
1258
|
get collection(): Collection;
|
|
1235
1259
|
initialize(): Promise<void>;
|
|
1236
1260
|
/** Reads the stored jobs and brings the schedules in line: new ones are added, changed ones rescheduled, removed ones stopped. */
|
|
@@ -1239,6 +1263,12 @@ declare class JobScheduler {
|
|
|
1239
1263
|
private run;
|
|
1240
1264
|
private information;
|
|
1241
1265
|
list(): JobInformation[];
|
|
1266
|
+
/**
|
|
1267
|
+
* Adds the handler of a class name at runtime (a host that gets the server after its start, e.g. a Nuxt application through
|
|
1268
|
+
* `useMongocampCore()`). The stored jobs of that class are scheduled now; the returned function removes the handler again and stops them.
|
|
1269
|
+
*/
|
|
1270
|
+
registerHandler(className: string, handler: JobHandler): () => void;
|
|
1271
|
+
private rescheduleClass;
|
|
1242
1272
|
classes(): string[];
|
|
1243
1273
|
/** Checks the class and the expression; an empty name is the simple name of the class (`addJob`). */
|
|
1244
1274
|
private checked;
|
|
@@ -1319,6 +1349,8 @@ interface VersionInfo {
|
|
|
1319
1349
|
/** Everything a route needs. One instance per server. */
|
|
1320
1350
|
interface MongocampContext {
|
|
1321
1351
|
config: ConfigStore;
|
|
1352
|
+
/** The log of the server (option `logger`, `console` by default). */
|
|
1353
|
+
logger: MongocampLogger;
|
|
1322
1354
|
database: MongocampDatabase;
|
|
1323
1355
|
version: VersionInfo;
|
|
1324
1356
|
auth: AuthService;
|
|
@@ -1349,34 +1381,71 @@ interface MongocampServerOptions extends DatabaseOptions {
|
|
|
1349
1381
|
shutdown?: (force: boolean) => void | Promise<void>;
|
|
1350
1382
|
/** Interval in milliseconds to read configuration changes of other instances, `false` for none. Default one minute. */
|
|
1351
1383
|
configRefresh?: number | false;
|
|
1352
|
-
/**
|
|
1353
|
-
|
|
1354
|
-
* need only one that runs them); `handlers` adds job handlers by class name; `refresh` is the interval to read the job changes of other
|
|
1355
|
-
* instances (default one minute, `false` for none).
|
|
1356
|
-
*/
|
|
1384
|
+
/** The log of the server (start, failed jobs and writes, 5xx errors); `console` when omitted. */
|
|
1385
|
+
logger?: MongocampLogger;
|
|
1357
1386
|
/** Listeners of the events, registered before the start (`server:started`); later ones with `server.events.on(...)`. */
|
|
1358
1387
|
on?: {
|
|
1359
1388
|
[N in EventName]?: EventListener<N>;
|
|
1360
1389
|
};
|
|
1390
|
+
/**
|
|
1391
|
+
* The jobs: `false` keeps the scheduler of this instance from running the jobs on their schedule (several instances of an application
|
|
1392
|
+
* need only one that runs them; the configuration `JOBS_ENABLED=false` does the same); `handlers` adds job handlers by class name (later
|
|
1393
|
+
* ones with `server.registerJobHandler(...)`); `refresh` is the interval to read the job changes of other instances (default one minute,
|
|
1394
|
+
* `false` for none).
|
|
1395
|
+
*/
|
|
1361
1396
|
jobs?: boolean | {
|
|
1362
1397
|
enabled?: boolean;
|
|
1363
1398
|
handlers?: Record<string, JobHandler>;
|
|
1364
1399
|
refresh?: number | false;
|
|
1365
1400
|
};
|
|
1366
1401
|
}
|
|
1402
|
+
/** Options of one request. */
|
|
1403
|
+
interface FetchOptions {
|
|
1404
|
+
/**
|
|
1405
|
+
* The wide event of the request in the host (e.g. `useLogger(event)` of evlog): the server adds its fields under `mongocamp` (operation,
|
|
1406
|
+
* user, collection or bucket, rows, error code), the host emits it.
|
|
1407
|
+
*/
|
|
1408
|
+
log?: RequestLog;
|
|
1409
|
+
/** The id of the request in the host (e.g. the one of its wide event), used for `x-request-id` and the events; a new one without. */
|
|
1410
|
+
requestId?: string;
|
|
1411
|
+
}
|
|
1367
1412
|
interface MongocampServer {
|
|
1368
1413
|
/** Web standard handler; paths start at the API root (`/version`, `/auth/login`, ...). */
|
|
1369
|
-
fetch: (request: Request) => Promise<Response>;
|
|
1414
|
+
fetch: (request: Request, options?: FetchOptions) => Promise<Response>;
|
|
1370
1415
|
context: MongocampContext;
|
|
1371
1416
|
/** The registered routes as `METHOD /path/:param`, for checks against the OpenAPI spec. */
|
|
1372
1417
|
routes: () => string[];
|
|
1373
1418
|
/** The events of the server (`hookable`): `server.events.on('document:create', event => ...)`. */
|
|
1374
1419
|
events: EventBus;
|
|
1420
|
+
/**
|
|
1421
|
+
* Adds a job handler after the start: the stored jobs with this `className` are scheduled right away. Returns a function that removes the
|
|
1422
|
+
* handler again. A Nuxt application registers its handlers this way in a Nitro plugin (`(await useMongocampCore()).registerJobHandler(...)`).
|
|
1423
|
+
*/
|
|
1424
|
+
registerJobHandler: (className: string, handler: JobHandler) => () => void;
|
|
1375
1425
|
close: () => Promise<void>;
|
|
1376
1426
|
}
|
|
1377
1427
|
/** Creates and connects a MongoCamp server. */
|
|
1378
1428
|
declare function createMongocampServer(options?: MongocampServerOptions): Promise<MongocampServer>;
|
|
1379
1429
|
|
|
1430
|
+
/** The fields of the server in the wide event of a request (key `mongocamp`). */
|
|
1431
|
+
interface MongocampRequestFields {
|
|
1432
|
+
requestId: string;
|
|
1433
|
+
/** The operationId of the OpenAPI spec (`listDocuments`), `NOT_SET` for an unknown route. */
|
|
1434
|
+
operation: string;
|
|
1435
|
+
controller: string;
|
|
1436
|
+
/** The user the request was authenticated as; missing for public routes and invalid credentials. */
|
|
1437
|
+
user?: string;
|
|
1438
|
+
database?: string;
|
|
1439
|
+
collection?: string;
|
|
1440
|
+
bucket?: string;
|
|
1441
|
+
/** All matching rows of a paged list (`x-pagination-count-rows`). */
|
|
1442
|
+
rows?: number;
|
|
1443
|
+
/** `x-error-code` and `x-error-message` of an error response. */
|
|
1444
|
+
errorCode?: string;
|
|
1445
|
+
errorMessage?: string;
|
|
1446
|
+
}
|
|
1447
|
+
declare function requestFields(request: Request, response: Response, fields: HttpRequestFields, user: string | undefined): MongocampRequestFields;
|
|
1448
|
+
|
|
1380
1449
|
/** Error codes of the API (`mongocamp-library/.../exception/ErrorCodes.scala`), sent in `ErrorDescription.code` and `x-error-code`. */
|
|
1381
1450
|
declare const ErrorCodes: {
|
|
1382
1451
|
/** A request that could not be decoded (body, query or header with an invalid value). */
|
|
@@ -1542,5 +1611,5 @@ declare function luceneToFilter(input: string, defaultField: string, options?: C
|
|
|
1542
1611
|
*/
|
|
1543
1612
|
declare function filterParameter(input: string | null | undefined, options?: ConvertOptions, parameter?: string): Record<string, unknown>;
|
|
1544
1613
|
|
|
1545
|
-
export { CleanUpTokenJob, CleanUpTokenJobClass, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, ErrorCodes, EventBus, FilterDefaultField, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, TextMarker, configDefinitions, convertFields, convertIdValue, createMongocampServer, decodeAny, documentToJson, filterParameter, luceneQueryToFilter, luceneToFilter, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, stringifyJson };
|
|
1546
|
-
export type { ConfigDefinition, ConfigKey, ConfigType, ConvertOptions, ErrorDescription, EventListener, EventName, ExtendedJsonMode, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampContext, MongocampEvent, MongocampEvents, MongocampServer, MongocampServerOptions, PaginationInfo, Paging, VersionInfo };
|
|
1614
|
+
export { CleanUpTokenJob, CleanUpTokenJobClass, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, ErrorCodes, EventBus, FilterDefaultField, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, TextMarker, configDefinitions, consoleLogger, convertFields, convertIdValue, createMongocampServer, decodeAny, documentToJson, filterParameter, luceneQueryToFilter, luceneToFilter, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, requestFields, stringifyJson };
|
|
1615
|
+
export type { ConfigDefinition, ConfigKey, ConfigType, ConvertOptions, ErrorDescription, EventListener, EventName, ExtendedJsonMode, FetchOptions, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampContext, MongocampEvent, MongocampEvents, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, PaginationInfo, Paging, RequestLog, VersionInfo };
|
package/dist/index.mjs
CHANGED
|
@@ -437,6 +437,12 @@ function resolveTarget(source, target, defaultDatabase, systemPrefix) {
|
|
|
437
437
|
return resolved;
|
|
438
438
|
}
|
|
439
439
|
|
|
440
|
+
const consoleLogger = {
|
|
441
|
+
info: (message) => console.info(message),
|
|
442
|
+
warn: (message) => console.warn(message),
|
|
443
|
+
error: (message, error) => error === void 0 ? console.error(message) : console.error(message, error)
|
|
444
|
+
};
|
|
445
|
+
|
|
440
446
|
const DefaultJobGroup = "Default";
|
|
441
447
|
const DefaultJobPriority = 1;
|
|
442
448
|
const CleanUpTokenJobClass = "dev.mongocamp.server.jobs.CleanUpTokenJob";
|
|
@@ -456,11 +462,12 @@ function sameConfig(a, b) {
|
|
|
456
462
|
return a.className === b.className && a.cronExpression === b.cronExpression && a.description === b.description && a.priority === b.priority;
|
|
457
463
|
}
|
|
458
464
|
class JobScheduler {
|
|
459
|
-
constructor(database, events, handlers, options) {
|
|
465
|
+
constructor(database, events, handlers, options, logger = consoleLogger) {
|
|
460
466
|
this.database = database;
|
|
461
467
|
this.events = events;
|
|
462
468
|
this.handlers = handlers;
|
|
463
469
|
this.options = options;
|
|
470
|
+
this.logger = logger;
|
|
464
471
|
}
|
|
465
472
|
entries = /* @__PURE__ */ new Map();
|
|
466
473
|
timer;
|
|
@@ -474,7 +481,7 @@ class JobScheduler {
|
|
|
474
481
|
await this.refresh();
|
|
475
482
|
if (this.options.refresh !== false) {
|
|
476
483
|
this.timer = setInterval(() => {
|
|
477
|
-
this.refresh().catch((error) =>
|
|
484
|
+
this.refresh().catch((error) => this.logger.error("could not read the jobs", error));
|
|
478
485
|
}, this.options.refresh);
|
|
479
486
|
this.timer.unref?.();
|
|
480
487
|
}
|
|
@@ -525,7 +532,7 @@ class JobScheduler {
|
|
|
525
532
|
await handler({ config: entry.config, startedAt, manual });
|
|
526
533
|
} catch (error) {
|
|
527
534
|
failure = error;
|
|
528
|
-
|
|
535
|
+
this.logger.error(`job ${entry.config.name} in group ${entry.config.group} failed`, error);
|
|
529
536
|
}
|
|
530
537
|
this.events.publish("job:executed", {
|
|
531
538
|
jobName: entry.config.name,
|
|
@@ -559,6 +566,27 @@ class JobScheduler {
|
|
|
559
566
|
list() {
|
|
560
567
|
return [...this.entries.values()].sort((a, b) => a.config.group.localeCompare(b.config.group) || a.config.name.localeCompare(b.config.name)).map((entry) => this.information(entry));
|
|
561
568
|
}
|
|
569
|
+
/**
|
|
570
|
+
* Adds the handler of a class name at runtime (a host that gets the server after its start, e.g. a Nuxt application through
|
|
571
|
+
* `useMongocampCore()`). The stored jobs of that class are scheduled now; the returned function removes the handler again and stops them.
|
|
572
|
+
*/
|
|
573
|
+
registerHandler(className, handler) {
|
|
574
|
+
this.handlers.set(className, handler);
|
|
575
|
+
this.rescheduleClass(className);
|
|
576
|
+
return () => {
|
|
577
|
+
if (this.handlers.get(className) === handler) {
|
|
578
|
+
this.handlers.delete(className);
|
|
579
|
+
this.rescheduleClass(className);
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
rescheduleClass(className) {
|
|
584
|
+
for (const entry of [...this.entries.values()]) {
|
|
585
|
+
if (entry.config.className === className) {
|
|
586
|
+
this.schedule(entry.config, entry.lastRun);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
562
590
|
classes() {
|
|
563
591
|
return [...this.handlers.keys()].sort();
|
|
564
592
|
}
|
|
@@ -738,6 +766,8 @@ const ConfigKeys = {
|
|
|
738
766
|
FilterTimeZone: "FILTER_TIME_ZONE",
|
|
739
767
|
// new in 2.0.0: drop what the Scala server left in the database at the start (`system/scala-leftovers.ts`)
|
|
740
768
|
MigrationDropScalaLeftovers: "MIGRATION_DROP_SCALA_LEFTOVERS",
|
|
769
|
+
// new in 2.1.0: whether this instance runs the jobs on their schedule (not persistent: a stored value would switch every instance)
|
|
770
|
+
JobsEnabled: "JOBS_ENABLED",
|
|
741
771
|
AuthPrefix: "AUTH_PREFIX",
|
|
742
772
|
AuthBearer: "AUTH_BEARER",
|
|
743
773
|
AuthBasic: "AUTH_BASIC",
|
|
@@ -808,6 +838,7 @@ const configDefinitions = [
|
|
|
808
838
|
define(K.ImportMaxBytes, "Long", 1073741824),
|
|
809
839
|
define(K.FilterTimeZone, "String", "UTC"),
|
|
810
840
|
define(K.MigrationDropScalaLeftovers, "Boolean", false, nonPersistent),
|
|
841
|
+
define(K.JobsEnabled, "Boolean", true, nonPersistent),
|
|
811
842
|
define(K.AuthBearer, "Boolean", true, restart),
|
|
812
843
|
define(K.AuthBasic, "Boolean", true, restart),
|
|
813
844
|
define(K.AuthToken, "Boolean", true, restart),
|
|
@@ -1017,7 +1048,7 @@ class MongoAuthHolder {
|
|
|
1017
1048
|
return this.database.db().collection(this.database.internalCollectionName("roles"));
|
|
1018
1049
|
}
|
|
1019
1050
|
/** Creates the indexes and, for an empty user collection, the user `admin` with a random password that is printed once. */
|
|
1020
|
-
async createIndicesAndInitData(log = console.
|
|
1051
|
+
async createIndicesAndInitData(log = console.info, warn = console.warn) {
|
|
1021
1052
|
if (await this.users.countDocuments({}, { limit: 1 }) === 0) {
|
|
1022
1053
|
const password = randomAlphanumeric(10);
|
|
1023
1054
|
await this.users.insertOne({ userId: "admin", password: await hashPassword(password), apiKey: null, roles: ["adminRole"] });
|
|
@@ -1035,7 +1066,7 @@ class MongoAuthHolder {
|
|
|
1035
1066
|
}
|
|
1036
1067
|
await this.users.createIndex({ userId: 1 }, { unique: true });
|
|
1037
1068
|
await this.rolesCollection.createIndex({ name: 1 }, { unique: true });
|
|
1038
|
-
await this.createApiKeyIndex();
|
|
1069
|
+
await this.createApiKeyIndex(warn);
|
|
1039
1070
|
}
|
|
1040
1071
|
/**
|
|
1041
1072
|
* Unique index for the api-key lookup, partial on string values (users without a key store `null`). A database in which two users share
|
|
@@ -1395,9 +1426,11 @@ class AuthService {
|
|
|
1395
1426
|
tokens;
|
|
1396
1427
|
/** Key: SHA-256 of user and password; value: the stored hash that was verified, valid while the user still has it. */
|
|
1397
1428
|
basicCache = /* @__PURE__ */ new Map();
|
|
1398
|
-
|
|
1429
|
+
/** The user of a request once it is authenticated, for the fields of its wide event (`userOf`). */
|
|
1430
|
+
requestUsers = /* @__PURE__ */ new WeakMap();
|
|
1431
|
+
async initialize(logger = consoleLogger) {
|
|
1399
1432
|
if (this.holder instanceof MongoAuthHolder) {
|
|
1400
|
-
await this.holder.createIndicesAndInitData();
|
|
1433
|
+
await this.holder.createIndicesAndInitData((message) => logger.info(message), (message) => logger.warn(message));
|
|
1401
1434
|
}
|
|
1402
1435
|
await this.tokens.createIndexes();
|
|
1403
1436
|
}
|
|
@@ -1444,8 +1477,13 @@ class AuthService {
|
|
|
1444
1477
|
/** The logged in user of a request with the current roles. */
|
|
1445
1478
|
async authenticate(request) {
|
|
1446
1479
|
const user = await this.authenticateUser(readCredentials(request));
|
|
1480
|
+
this.requestUsers.set(request, user.userId);
|
|
1447
1481
|
return new AuthorizedUser(user, await this.holder.findRoles(user.roles));
|
|
1448
1482
|
}
|
|
1483
|
+
/** The id of the user a request was authenticated as, `undefined` before (or without) the authentication. */
|
|
1484
|
+
userOf(request) {
|
|
1485
|
+
return this.requestUsers.get(request);
|
|
1486
|
+
}
|
|
1449
1487
|
/** The error for a logged in user without the grant for a request; the status is `AUTH_GRANT_DENIED_STATUS` (403) or 401. */
|
|
1450
1488
|
grantDenied(message) {
|
|
1451
1489
|
const status = this.config.number(ConfigKeys.AuthGrantDeniedStatus) === 403 ? 403 : 401;
|
|
@@ -2032,6 +2070,53 @@ function withCommonHeaders(response, request, config, version, requestId) {
|
|
|
2032
2070
|
}
|
|
2033
2071
|
}
|
|
2034
2072
|
|
|
2073
|
+
const resourcePattern = /^\/mongodb\/(collections|buckets|databases)\/([^/]+)/;
|
|
2074
|
+
function decoded(segment) {
|
|
2075
|
+
try {
|
|
2076
|
+
return decodeURIComponent(segment);
|
|
2077
|
+
} catch {
|
|
2078
|
+
return segment;
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
function requestFields(request, response, fields, user) {
|
|
2082
|
+
const result = { requestId: fields.requestId, operation: fields.methodName, controller: fields.controller };
|
|
2083
|
+
if (user) {
|
|
2084
|
+
result.user = user;
|
|
2085
|
+
}
|
|
2086
|
+
const match = resourcePattern.exec(new URL(request.url).pathname);
|
|
2087
|
+
if (match && match[2] !== "info") {
|
|
2088
|
+
const name = decoded(match[2]);
|
|
2089
|
+
if (match[1] === "collections") {
|
|
2090
|
+
result.collection = name;
|
|
2091
|
+
} else if (match[1] === "buckets") {
|
|
2092
|
+
result.bucket = name;
|
|
2093
|
+
} else if (match[2] !== "infos") {
|
|
2094
|
+
result.database = name;
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
2097
|
+
const rows = Number.parseInt(response.headers.get(PaginationHeaders.countRows) ?? "", 10);
|
|
2098
|
+
if (Number.isFinite(rows)) {
|
|
2099
|
+
result.rows = rows;
|
|
2100
|
+
}
|
|
2101
|
+
if (response.status >= 400) {
|
|
2102
|
+
const code = response.headers.get(ErrorHeaders.code);
|
|
2103
|
+
const message = response.headers.get(ErrorHeaders.message);
|
|
2104
|
+
if (code) {
|
|
2105
|
+
result.errorCode = code;
|
|
2106
|
+
}
|
|
2107
|
+
if (message) {
|
|
2108
|
+
result.errorMessage = message;
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
return result;
|
|
2112
|
+
}
|
|
2113
|
+
function addRequestFields(log, request, response, fields, user) {
|
|
2114
|
+
try {
|
|
2115
|
+
log.set({ mongocamp: requestFields(request, response, fields, user) });
|
|
2116
|
+
} catch {
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2035
2120
|
const operations = [
|
|
2036
2121
|
["POST", "/auth/login", "login", "Auth", "Login User"],
|
|
2037
2122
|
["POST", "/auth/logout", "logout", "Auth", "Logout User"],
|
|
@@ -14537,7 +14622,7 @@ class MongocampMetrics {
|
|
|
14537
14622
|
}
|
|
14538
14623
|
this.timer = setInterval(() => {
|
|
14539
14624
|
for (const category of enabled) {
|
|
14540
|
-
this.persist(category).catch((error) =>
|
|
14625
|
+
this.persist(category).catch((error) => this.context.logger.error(`could not write the metrics ${category}`, error));
|
|
14541
14626
|
}
|
|
14542
14627
|
}, Math.max(config.number(ConfigKeys.LoggingMetricsStep), 100));
|
|
14543
14628
|
this.timer.unref?.();
|
|
@@ -14579,7 +14664,7 @@ function requestLogEntry(fields, date, application, containerName = hostname())
|
|
|
14579
14664
|
};
|
|
14580
14665
|
}
|
|
14581
14666
|
async function enableRequestLogging(context) {
|
|
14582
|
-
const { database, events, version } = context;
|
|
14667
|
+
const { database, events, version, logger } = context;
|
|
14583
14668
|
const collection = database.db().collection(database.internalCollectionName("request_logging"));
|
|
14584
14669
|
await collection.createIndex({ requestId: 1 });
|
|
14585
14670
|
const inserts = /* @__PURE__ */ new Map();
|
|
@@ -14590,7 +14675,7 @@ async function enableRequestLogging(context) {
|
|
|
14590
14675
|
return write;
|
|
14591
14676
|
};
|
|
14592
14677
|
const removeStart = events.on("http:requestStart", (event) => {
|
|
14593
|
-
const insert = track(collection.insertOne(requestLogEntry(event, event.eventDate, version)).catch((error) =>
|
|
14678
|
+
const insert = track(collection.insertOne(requestLogEntry(event, event.eventDate, version)).catch((error) => logger.error("could not log the request", error)));
|
|
14594
14679
|
inserts.set(event.requestId, insert);
|
|
14595
14680
|
});
|
|
14596
14681
|
const removeCompleted = events.on("http:requestCompleted", async (event) => {
|
|
@@ -14857,19 +14942,27 @@ function createApp(context) {
|
|
|
14857
14942
|
const app = new H3({
|
|
14858
14943
|
// errors are answered and logged (5xx) by toErrorResponse
|
|
14859
14944
|
silent: true,
|
|
14860
|
-
onError: (error) => toErrorResponse(error)
|
|
14945
|
+
onError: (error) => toErrorResponse(error, errorLogger(context.logger))
|
|
14861
14946
|
});
|
|
14862
14947
|
for (const [, register] of routeGroups) {
|
|
14863
14948
|
register(app, context);
|
|
14864
14949
|
}
|
|
14865
14950
|
return app;
|
|
14866
14951
|
}
|
|
14952
|
+
function errorLogger(logger) {
|
|
14953
|
+
return (error, status) => {
|
|
14954
|
+
if (status >= 500) {
|
|
14955
|
+
logger.error("[mongocamp]", error);
|
|
14956
|
+
}
|
|
14957
|
+
};
|
|
14958
|
+
}
|
|
14867
14959
|
async function createMongocampServer(options = {}) {
|
|
14868
14960
|
const config = new ConfigStore({ env: options.env, values: options.config });
|
|
14869
14961
|
const database = new MongocampDatabase(config, options);
|
|
14870
14962
|
await database.connect();
|
|
14871
14963
|
const version = { ...defaultVersion, ...options.version };
|
|
14872
|
-
const
|
|
14964
|
+
const logger = options.logger ?? consoleLogger;
|
|
14965
|
+
const events = new EventBus((message, error) => logger.error(message, error));
|
|
14873
14966
|
for (const [name, listener] of Object.entries(options.on ?? {})) {
|
|
14874
14967
|
events.on(name, listener);
|
|
14875
14968
|
}
|
|
@@ -14882,14 +14975,14 @@ async function createMongocampServer(options = {}) {
|
|
|
14882
14975
|
}],
|
|
14883
14976
|
...Object.entries(jobOptions.handlers ?? {})
|
|
14884
14977
|
]);
|
|
14885
|
-
const jobs = new JobScheduler(database, events, handlers, { enabled: jobOptions.enabled ?? true, refresh: jobOptions.refresh ?? 6e4 });
|
|
14978
|
+
const jobs = new JobScheduler(database, events, handlers, { enabled: (jobOptions.enabled ?? true) && config.boolean(ConfigKeys.JobsEnabled), refresh: jobOptions.refresh ?? 6e4 }, logger);
|
|
14886
14979
|
try {
|
|
14887
14980
|
await configurations.initialize(options.configRefresh ?? void 0);
|
|
14888
14981
|
if (config.boolean(ConfigKeys.MigrationDropScalaLeftovers)) {
|
|
14889
14982
|
const leftovers = await dropScalaLeftovers(database);
|
|
14890
|
-
|
|
14983
|
+
logger.info(`[mongocamp] Scala leftovers: dropped ${leftovers.droppedCollections.length} Quartz collections (${leftovers.droppedCollections.join(", ") || "-"}), removed ${leftovers.removedTokenEntries} token entries, rewrote ${leftovers.rewrittenJobs} job expressions`);
|
|
14891
14984
|
}
|
|
14892
|
-
await auth.initialize();
|
|
14985
|
+
await auth.initialize(logger);
|
|
14893
14986
|
await jobs.initialize();
|
|
14894
14987
|
} catch (error) {
|
|
14895
14988
|
jobs.close();
|
|
@@ -14899,6 +14992,7 @@ async function createMongocampServer(options = {}) {
|
|
|
14899
14992
|
}
|
|
14900
14993
|
const context = {
|
|
14901
14994
|
config,
|
|
14995
|
+
logger,
|
|
14902
14996
|
database,
|
|
14903
14997
|
version,
|
|
14904
14998
|
auth,
|
|
@@ -14931,19 +15025,22 @@ async function createMongocampServer(options = {}) {
|
|
|
14931
15025
|
context.routeGroups = routeGroupNames;
|
|
14932
15026
|
const app = createApp(context);
|
|
14933
15027
|
const requestEvents = new RequestEvents(events, auth);
|
|
14934
|
-
const fetch = async (request) => {
|
|
15028
|
+
const fetch = async (request, fetchOptions = {}) => {
|
|
14935
15029
|
if (request.method === "OPTIONS") {
|
|
14936
15030
|
return preflightResponse(request, config);
|
|
14937
15031
|
}
|
|
14938
|
-
const requestId = newRequestId();
|
|
15032
|
+
const requestId = fetchOptions.requestId || newRequestId();
|
|
14939
15033
|
const start = await requestEvents.started(request, requestId);
|
|
14940
15034
|
let response;
|
|
14941
15035
|
try {
|
|
14942
15036
|
response = await app.fetch(request);
|
|
14943
15037
|
} catch (error) {
|
|
14944
|
-
response = toErrorResponse(error);
|
|
15038
|
+
response = toErrorResponse(error, errorLogger(logger));
|
|
14945
15039
|
}
|
|
14946
15040
|
requestEvents.completed(start, response);
|
|
15041
|
+
if (fetchOptions.log) {
|
|
15042
|
+
addRequestFields(fetchOptions.log, request, response, start.fields, auth.userOf(request));
|
|
15043
|
+
}
|
|
14947
15044
|
return withCommonHeaders(response, request, config, context.version, requestId);
|
|
14948
15045
|
};
|
|
14949
15046
|
events.publish("server:started", {});
|
|
@@ -14951,6 +15048,7 @@ async function createMongocampServer(options = {}) {
|
|
|
14951
15048
|
fetch,
|
|
14952
15049
|
context,
|
|
14953
15050
|
events,
|
|
15051
|
+
registerJobHandler: (className, handler) => jobs.registerHandler(className, handler),
|
|
14954
15052
|
routes: () => app["~routes"].filter((route) => route.route && route.method).map((route) => `${route.method} ${route.route}`),
|
|
14955
15053
|
close: async () => {
|
|
14956
15054
|
await Promise.allSettled(cleanups.map((cleanup) => cleanup()));
|
|
@@ -14961,4 +15059,4 @@ async function createMongocampServer(options = {}) {
|
|
|
14961
15059
|
};
|
|
14962
15060
|
}
|
|
14963
15061
|
|
|
14964
|
-
export { CleanUpTokenJob, CleanUpTokenJobClass, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, ErrorCodes, EventBus, FilterDefaultField, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, TextMarker, configDefinitions, convertFields, convertIdValue, createMongocampServer, decodeAny, documentToJson, filterParameter, luceneQueryToFilter, luceneToFilter, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, stringifyJson };
|
|
15062
|
+
export { CleanUpTokenJob, CleanUpTokenJobClass, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, ErrorCodes, EventBus, FilterDefaultField, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, TextMarker, configDefinitions, consoleLogger, convertFields, convertIdValue, createMongocampServer, decodeAny, documentToJson, filterParameter, luceneQueryToFilter, luceneToFilter, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, requestFields, stringifyJson };
|