@sfxcode/mongocamp-server-core 2.1.0 → 2.2.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 CHANGED
@@ -1,8 +1,8 @@
1
1
  # @sfxcode/mongocamp-server-core
2
2
 
3
3
  The MongoCamp REST API (`openapi/docs.yaml`) as a framework-neutral core: `createMongocampServer()` returns a web standard
4
- `fetch(Request): Promise<Response>` handler. It replaces the Scala `mongocamp-server` and is hosted by `apps/server` (Nitro 3,
5
- standalone) or embedded in a Nuxt application.
4
+ `fetch(Request): Promise<Response>` handler. It is hosted by `apps/server` (Nitro 3, standalone) or embedded in a Nuxt
5
+ application.
6
6
 
7
7
  ```ts
8
8
  import { createMongocampServer } from '@sfxcode/mongocamp-server-core'
@@ -17,15 +17,22 @@ await server.close()
17
17
 
18
18
  ## Configuration
19
19
 
20
- The keys are the env variables of the Scala server (`CONNECTION_*`, `AUTH_*`, `CORS_*`, ...). Persistent keys live in
21
- `<AUTH_PREFIX>configuration` and can be changed with `PATCH /system/configurations/{key}`; env and programmatic values win.
20
+ The keys are env variables (`CONNECTION_*`, `AUTH_*`, `CORS_*`, ...). Persistent keys live in `<AUTH_PREFIX>configuration` and can be
21
+ changed with `PATCH /system/configurations/{key}`; env and programmatic values win.
22
22
 
23
- | Plugin of the Scala server | Keys |
23
+ ## Features
24
+
25
+ Optional parts that a host switches on with `server.use(...)`, in Nitro from a plugin on `mongocamp:ready`:
26
+
27
+ | Feature | Content |
24
28
  | --- | --- |
25
- | request logging | `REQUESTLOGGING_ENABLED` — every request is a document of `<AUTH_PREFIX>request_logging` |
26
- | micrometer | `METRICS_ENABLED` — `GET /system/monitoring/{jvm,system,mongodb,events,prometheus}`; `METRICS_MONGODB_*` select the MongoDB metrics, `LOGGING_METRICS_MONGODB_*` write snapshots into `monitoring_*` every `LOGGING_METRICS_MONGODB_STEP` |
29
+ | `requestLogging()` | every request is a document of `<AUTH_PREFIX>request_logging` |
30
+ | `metrics()` | `GET /system/monitoring/{runtime,system,mongodb,events,prometheus}` (404 while off); `METRICS_MONGODB_*` select the MongoDB metrics, `LOGGING_METRICS_MONGODB_*` write snapshots into `monitoring_*` every `LOGGING_METRICS_MONGODB_STEP` |
27
31
 
28
- The category `jvm` holds the numbers of the Node runtime (`nodejs_*`).
32
+ `REQUESTLOGGING_ENABLED` / `METRICS_ENABLED` still switch them on in the core with a deprecation warning (removed in 3.0); `featureSwitches:
33
+ false` turns that off. `apps/server` reads the two settings in its own Nitro plugin.
34
+
35
+ The category `runtime` holds the numbers of the Node runtime (`nodejs_*`).
29
36
 
30
37
  ## Logging
31
38
 
@@ -36,7 +43,17 @@ the event of `evlog/nuxt` when the application uses it.
36
43
 
37
44
  ## Extensions
38
45
 
39
- The dynamic JVM plugins of the Scala server are replaced by three things a host can use.
46
+ In Nitro, extensions are Nitro 3 plugins: `connectHooks(server, nitroApp.hooks)` (done by `apps/server` and the Nuxt module) calls
47
+ `mongocamp:ready` with the started server and forwards every event as a hook `mongocamp:<event>`:
48
+
49
+ ```ts
50
+ export default definePlugin((nitroApp) => {
51
+ nitroApp.hooks.hook('mongocamp:ready', server => server.use(metrics()))
52
+ nitroApp.hooks.hook('mongocamp:document:update', event => audit(event))
53
+ })
54
+ ```
55
+
56
+ Expensive parts of an event are only read for hooks with a listener. Without Nitro, a host uses the server directly:
40
57
 
41
58
  ### Events
42
59
 
package/dist/index.d.mts CHANGED
@@ -21,12 +21,6 @@ declare const ConfigKeys: {
21
21
  readonly ServerInterface: "SERVER_INTERFACE";
22
22
  readonly ServerPort: "SERVER_PORT";
23
23
  readonly AggregationStagesDenied: "AGGREGATION_STAGES_DENIED";
24
- readonly PluginsIgnored: "PLUGINS_IGNORED";
25
- readonly PluginsDirectory: "PLUGINS_DIRECTORY";
26
- readonly PluginsUrls: "PLUGINS_URLS";
27
- readonly PluginsModules: "PLUGINS_MODULES";
28
- readonly PluginsMavenRepositories: "PLUGINS_MAVEN_REPOSITORIES";
29
- readonly HttpClientHeaders: "HTTP_CLIENT_HEADERS";
30
24
  readonly AuthHandler: "AUTH_HANDLER";
31
25
  readonly AuthSecret: "AUTH_SECRET";
32
26
  readonly AuthApiKeyLength: "AUTH_APIKEYLENGTH";
@@ -68,6 +62,7 @@ declare const ConfigKeys: {
68
62
  readonly MetricsMongoDbCommand: "METRICS_MONGODB_COMMAND";
69
63
  readonly MetricsMongoDbConnectionPool: "METRICS_MONGODB_CONNECTIONPOOL";
70
64
  readonly LoggingMetricsStep: "LOGGING_METRICS_MONGODB_STEP";
65
+ readonly LoggingMetricsRuntime: "LOGGING_METRICS_MONGODB_RUNTIME";
71
66
  readonly LoggingMetricsJvm: "LOGGING_METRICS_MONGODB_JVM";
72
67
  readonly LoggingMetricsSystem: "LOGGING_METRICS_MONGODB_SYSTEM";
73
68
  readonly LoggingMetricsMongo: "LOGGING_METRICS_MONGODB_MONGO";
@@ -624,7 +619,8 @@ interface components {
624
619
  read: boolean;
625
620
  write: boolean;
626
621
  administrate: boolean;
627
- grantType: string;
622
+ /** @enum {string} */
623
+ grantType: "COLLECTION" | "BUCKET" | "BUCKET_META";
628
624
  };
629
625
  /** ImportResponse */
630
626
  ImportResponse: {
@@ -803,6 +799,8 @@ interface components {
803
799
  MongoAggregateRequest: {
804
800
  pipeline?: components["schemas"]["PipelineStage"][];
805
801
  allowDiskUse: boolean;
802
+ /** @description 2.1.0: the Lucene filter of the list as first stage, like the query parameter filter (send one of both; no URL limit in the body) */
803
+ filter?: string;
806
804
  };
807
805
  /** MongoCampConfiguration */
808
806
  MongoCampConfiguration: {
@@ -913,6 +911,20 @@ interface components {
913
911
  /** Format: double */
914
912
  percentageOfParent: number;
915
913
  };
914
+ /** ExportRequest */
915
+ ExportRequest: {
916
+ /** @description Lucene filter like on the list of documents, by default all documents */
917
+ filter?: string;
918
+ sort?: string[];
919
+ projection?: string[];
920
+ /** Format: int32 */
921
+ limit?: number;
922
+ };
923
+ /** CountRequest */
924
+ CountRequest: {
925
+ /** @description Lucene filter like on the list of documents, by default all documents */
926
+ filter?: string;
927
+ };
916
928
  /** SearchRequest */
917
929
  SearchRequest: {
918
930
  filter?: string;
@@ -921,17 +933,6 @@ interface components {
921
933
  };
922
934
  /** SettingsResponse */
923
935
  SettingsResponse: {
924
- routesPlugins?: string[];
925
- /**
926
- * @deprecated
927
- * @description Deprecated: plugin system of the Scala server, always [GridFsFileAdapter]
928
- */
929
- filePlugins?: string[];
930
- /**
931
- * @deprecated
932
- * @description Deprecated: plugin system of the Scala server, the value of PLUGINS_IGNORED
933
- */
934
- ignoredPlugins?: string[];
935
936
  configurations: components["schemas"]["Map_Any"];
936
937
  };
937
938
  /** SystemInfo */
@@ -953,8 +954,8 @@ interface components {
953
954
  filename?: string;
954
955
  metadata?: components["schemas"]["Map_Any"];
955
956
  };
956
- /** UpdateRequest */
957
- UpdateRequest: {
957
+ /** UpdateManyRequest */
958
+ UpdateManyRequest: {
958
959
  document: components["schemas"]["Map_Any"];
959
960
  filter: components["schemas"]["Map_Any"];
960
961
  };
@@ -1163,16 +1164,28 @@ type HookMap = {
1163
1164
  };
1164
1165
  /** Sees every published event, also without a listener; it does not count as listener, so no expensive payload is read for it. */
1165
1166
  type EventObserver = (name: EventName, payload: MongocampEvents[EventName]) => void;
1167
+ /**
1168
+ * A hook system of the host that receives the events, e.g. the hooks of a Nitro app (`mongocamp:document:update`). `listens` tells whether
1169
+ * the host has a listener for an event, so that its expensive parts are only read when somebody waits for them.
1170
+ */
1171
+ interface EventTarget {
1172
+ listens: (name: EventName) => boolean;
1173
+ call: (name: EventName, event: MongocampEvent<EventName>) => unknown;
1174
+ }
1166
1175
  declare class EventBus {
1167
1176
  private readonly log;
1168
1177
  readonly hooks: hookable.Hookable<HookMap, hookable.HookKeys<HookMap>>;
1169
1178
  private readonly listeners;
1170
1179
  private readonly observers;
1180
+ private readonly targets;
1171
1181
  constructor(log?: (message: string, error: unknown) => void);
1172
1182
  /** Registers a listener; the returned function removes it. */
1173
1183
  on<N extends EventName>(name: N, listener: EventListener<N>): () => void;
1174
1184
  /** Registers an observer (metrics); the returned function removes it. */
1175
1185
  observe(observer: EventObserver): () => void;
1186
+ /** Sends the events to a hook system of the host (`forwardToNitro`); the returned function stops it. */
1187
+ forward(target: EventTarget): () => void;
1188
+ private targetsFor;
1176
1189
  /** Whether anybody listens, so that an expensive payload (old values of documents) is only read when needed. */
1177
1190
  has(name: EventName): boolean;
1178
1191
  /** Sends an event without waiting for the listeners; a failure of a listener is logged. */
@@ -1283,12 +1296,13 @@ declare class JobScheduler {
1283
1296
 
1284
1297
  /**
1285
1298
  * `mongocamp-plugin-micrometer` on `@prometheus-io/client` (the successor of prom-client): four categories with the endpoints
1286
- * `/system/monitoring/{jvm,system,mongodb,events}` in the `Metric` / `Measurement` shape of the plugin, a Prometheus text endpoint, and
1299
+ * `/system/monitoring/{runtime,system,mongodb,events}` in the `Metric` / `Measurement` shape of the plugin, a Prometheus text endpoint, and
1287
1300
  * snapshots in the collections `monitoring_*` every `LOGGING_METRICS_MONGODB_STEP` (the document shape of micrometer-mongodb).
1288
1301
  *
1289
- * The category `jvm` keeps its name for the clients and holds the numbers of the Node runtime (`nodejs_*`): heap, event loop, gc, handles.
1302
+ * The category `runtime` holds the numbers of the Node runtime (`nodejs_*`): heap, event loop, gc, handles. Until 2.1.0 it was named `jvm`;
1303
+ * `/system/monitoring/jvm` and `LOGGING_METRICS_MONGODB_JVM` stay as deprecated aliases until 3.0.
1290
1304
  */
1291
- type MetricCategory = 'jvm' | 'system' | 'mongodb' | 'events';
1305
+ type MetricCategory = 'runtime' | 'system' | 'mongodb' | 'events';
1292
1306
  interface Measurement {
1293
1307
  statisticType: string;
1294
1308
  value: number;
@@ -1363,10 +1377,21 @@ interface MongocampContext {
1363
1377
  systemInfo: InfoCache<SystemInfo>;
1364
1378
  /** Stops the process (`DELETE /system`); not set when the server is embedded in an application. */
1365
1379
  shutdown?: (force: boolean) => void | Promise<void>;
1366
- /** The names of the route groups (`SettingsResponse.routesPlugins`). */
1367
- routeGroups: string[];
1368
1380
  }
1369
1381
 
1382
+ /**
1383
+ * An optional part of the server that a host switches on with `server.use(...)`, typically from a Nitro plugin on the hook
1384
+ * `mongocamp:ready`. `setup` starts it and answers the function that stops it (called by `server.close()`).
1385
+ */
1386
+ interface MongocampFeature {
1387
+ name: string;
1388
+ setup: (context: MongocampContext) => Promise<() => void | Promise<void>> | (() => void | Promise<void>);
1389
+ }
1390
+ /** Every request as a document of `<AUTH_PREFIX>request_logging`. */
1391
+ declare function requestLogging(): MongocampFeature;
1392
+ /** `/system/monitoring/{runtime,system,mongodb,events,prometheus}` and the snapshots of `LOGGING_METRICS_MONGODB_*`. */
1393
+ declare function metrics(): MongocampFeature;
1394
+
1370
1395
  interface MongocampServerOptions extends DatabaseOptions {
1371
1396
  /** Environment variables, `process.env` when omitted. */
1372
1397
  env?: ConfigSources['env'];
@@ -1381,6 +1406,11 @@ interface MongocampServerOptions extends DatabaseOptions {
1381
1406
  shutdown?: (force: boolean) => void | Promise<void>;
1382
1407
  /** Interval in milliseconds to read configuration changes of other instances, `false` for none. Default one minute. */
1383
1408
  configRefresh?: number | false;
1409
+ /**
1410
+ * Deprecated (removed in 3.0): switches request logging and metrics on from `REQUESTLOGGING_ENABLED` / `METRICS_ENABLED` (default true).
1411
+ * A host that adds them itself with `server.use(requestLogging())` / `server.use(metrics())` passes false.
1412
+ */
1413
+ featureSwitches?: boolean;
1384
1414
  /** The log of the server (start, failed jobs and writes, 5xx errors); `console` when omitted. */
1385
1415
  logger?: MongocampLogger;
1386
1416
  /** Listeners of the events, registered before the start (`server:started`); later ones with `server.events.on(...)`. */
@@ -1422,6 +1452,11 @@ interface MongocampServer {
1422
1452
  * handler again. A Nuxt application registers its handlers this way in a Nitro plugin (`(await useMongocampCore()).registerJobHandler(...)`).
1423
1453
  */
1424
1454
  registerJobHandler: (className: string, handler: JobHandler) => () => void;
1455
+ /**
1456
+ * Switches an optional part on (`requestLogging()`, `metrics()`), typically from a Nitro plugin on `mongocamp:ready`. A feature with the
1457
+ * same name is used once; it is stopped by `close`.
1458
+ */
1459
+ use: (feature: MongocampFeature) => Promise<void>;
1425
1460
  close: () => Promise<void>;
1426
1461
  }
1427
1462
  /** Creates and connects a MongoCamp server. */
@@ -1543,6 +1578,7 @@ type LuceneQuery = {
1543
1578
  type: 'term';
1544
1579
  field: string;
1545
1580
  text: string;
1581
+ quoted?: boolean;
1546
1582
  } | {
1547
1583
  type: 'range';
1548
1584
  field: string;
@@ -1611,5 +1647,32 @@ declare function luceneToFilter(input: string, defaultField: string, options?: C
1611
1647
  */
1612
1648
  declare function filterParameter(input: string | null | undefined, options?: ConvertOptions, parameter?: string): Record<string, unknown>;
1613
1649
 
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 };
1650
+ /**
1651
+ * The events of the server as hooks of a Nitro app (or any `hookable` instance): `mongocamp:document:update`, ... and `mongocamp:ready` with
1652
+ * the server once it is started. An extension of an application is then a plain Nitro plugin:
1653
+ *
1654
+ * export default definePlugin((nitroApp) => {
1655
+ * nitroApp.hooks.hook('mongocamp:ready', server => server.use(metrics()))
1656
+ * nitroApp.hooks.hook('mongocamp:document:delete', event => audit(event))
1657
+ * })
1658
+ */
1659
+ type MongocampHooks = {
1660
+ 'mongocamp:ready': (server: MongocampServer) => void | Promise<void>;
1661
+ } & {
1662
+ [N in EventName as `mongocamp:${N}`]: (event: MongocampEvent<N>) => void | Promise<void>;
1663
+ };
1664
+ /** The part of `hookable` (Nitro's `nitroApp.hooks`) the bridge needs. */
1665
+ interface HookSystem {
1666
+ callHook(name: string, ...args: unknown[]): unknown;
1667
+ }
1668
+ declare const HookPrefix = "mongocamp:";
1669
+ /** Calls `mongocamp:<event>` for every event of the server that has a hook listener; the returned function stops it. */
1670
+ declare function forwardEventsToHooks(server: Pick<MongocampServer, 'events'>, hooks: HookSystem): () => void;
1671
+ /**
1672
+ * Connects a started server with the hooks of its host: forwards the events and calls `mongocamp:ready` (awaited, so features that the
1673
+ * plugins switch on are active before the first request is answered).
1674
+ */
1675
+ declare function connectHooks(server: MongocampServer, hooks: HookSystem): Promise<() => void>;
1676
+
1677
+ export { CleanUpTokenJob, CleanUpTokenJobClass, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, TextMarker, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, decodeAny, documentToJson, filterParameter, forwardEventsToHooks, luceneQueryToFilter, luceneToFilter, metrics, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, requestFields, requestLogging, stringifyJson };
1678
+ export type { ConfigDefinition, ConfigKey, ConfigType, ConvertOptions, ErrorDescription, EventListener, EventName, EventTarget, ExtendedJsonMode, FetchOptions, HookSystem, JobConfig, JobHandler, JobInformation, JobRun, LuceneQuery, MongocampContext, MongocampEvent, MongocampEvents, MongocampFeature, MongocampHooks, MongocampLogger, MongocampRequestFields, MongocampServer, MongocampServerOptions, PaginationInfo, Paging, RequestLog, VersionInfo };
package/dist/index.mjs CHANGED
@@ -679,6 +679,7 @@ function toConfig(document) {
679
679
  }
680
680
 
681
681
  const QuartzCleanUpExpression = "0 0/5 * ? * * *";
682
+ const RemovedPluginSettings = ["PLUGINS_IGNORED", "PLUGINS_URLS", "PLUGINS_DIRECTORY", "PLUGINS_MODULES", "PLUGINS_MAVEN_REPOSITORIES", "HTTP_CLIENT_HEADERS"];
682
683
  async function dropScalaLeftovers(database) {
683
684
  const db = database.db();
684
685
  const quartzPrefix = database.internalCollectionName("jobs_");
@@ -689,7 +690,8 @@ async function dropScalaLeftovers(database) {
689
690
  const tokens = await db.collection(database.internalCollectionName("token_cache")).deleteMany({ token: { $not: /^[0-9a-f]{64}$/ } });
690
691
  const { group, name } = CleanUpTokenJob;
691
692
  const jobs = await db.collection(database.internalCollectionName("jobs")).updateOne({ group, name, cronExpression: QuartzCleanUpExpression }, { $set: { cronExpression: CleanUpTokenJob.cronExpression } });
692
- return { droppedCollections, removedTokenEntries: tokens.deletedCount, rewrittenJobs: jobs.modifiedCount };
693
+ const settings = await db.collection(database.internalCollectionName("configuration")).deleteMany({ key: { $in: RemovedPluginSettings } });
694
+ return { droppedCollections, removedTokenEntries: tokens.deletedCount, rewrittenJobs: jobs.modifiedCount, removedSettings: settings.deletedCount };
693
695
  }
694
696
 
695
697
  const instantPattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|([+-])(\d{2}):(\d{2}))$/;
@@ -748,12 +750,6 @@ const ConfigKeys = {
748
750
  ServerInterface: "SERVER_INTERFACE",
749
751
  ServerPort: "SERVER_PORT",
750
752
  AggregationStagesDenied: "AGGREGATION_STAGES_DENIED",
751
- PluginsIgnored: "PLUGINS_IGNORED",
752
- PluginsDirectory: "PLUGINS_DIRECTORY",
753
- PluginsUrls: "PLUGINS_URLS",
754
- PluginsModules: "PLUGINS_MODULES",
755
- PluginsMavenRepositories: "PLUGINS_MAVEN_REPOSITORIES",
756
- HttpClientHeaders: "HTTP_CLIENT_HEADERS",
757
753
  AuthHandler: "AUTH_HANDLER",
758
754
  AuthSecret: "AUTH_SECRET",
759
755
  AuthApiKeyLength: "AUTH_APIKEYLENGTH",
@@ -800,6 +796,8 @@ const ConfigKeys = {
800
796
  MetricsMongoDbCommand: "METRICS_MONGODB_COMMAND",
801
797
  MetricsMongoDbConnectionPool: "METRICS_MONGODB_CONNECTIONPOOL",
802
798
  LoggingMetricsStep: "LOGGING_METRICS_MONGODB_STEP",
799
+ // 2.1.0: the snapshots of the Node runtime; LOGGING_METRICS_MONGODB_JVM is its deprecated alias (removed in 3.0)
800
+ LoggingMetricsRuntime: "LOGGING_METRICS_MONGODB_RUNTIME",
803
801
  LoggingMetricsJvm: "LOGGING_METRICS_MONGODB_JVM",
804
802
  LoggingMetricsSystem: "LOGGING_METRICS_MONGODB_SYSTEM",
805
803
  LoggingMetricsMongo: "LOGGING_METRICS_MONGODB_MONGO",
@@ -821,12 +819,6 @@ const configDefinitions = [
821
819
  define(K.ServerInterface, "String", "0.0.0.0", restart),
822
820
  define(K.ServerPort, "Long", 8080, restart),
823
821
  define(K.AggregationStagesDenied, "List[String]", ["$function", "$accumulator", "$where", "$out", "$merge", "$currentOp", "$listSessions", "$collStats", "$indexStats"]),
824
- define(K.PluginsIgnored, "List[String]", [], restart),
825
- define(K.PluginsUrls, "List[String]", [], restart),
826
- define(K.PluginsDirectory, "String", "/opt/mongocamp/plugins", restart),
827
- define(K.PluginsModules, "List[String]", [], restart),
828
- define(K.PluginsMavenRepositories, "List[String]", [], restart),
829
- define(K.HttpClientHeaders, "String", "{}"),
830
822
  define(K.AuthHandler, "String", "mongo", restart),
831
823
  // the Scala server registers a random secret (not the `secret_key` of reference.conf); it is persisted, so it survives restarts
832
824
  define(K.AuthSecret, "String", () => randomAlphanumeric$1(32)),
@@ -834,7 +826,8 @@ const configDefinitions = [
834
826
  define(K.AuthCacheDb, "Boolean", true),
835
827
  define(K.AuthExpiringDuration, "Duration", 6 * 36e5),
836
828
  define(K.AuthRefreshGraceDuration, "Duration", 6e4),
837
- define(K.AuthGrantDeniedStatus, "Long", 401),
829
+ // 2.1.0: 403 by default, a user who only lacks a grant keeps the session (401 clears it in the clients); 401 stays configurable
830
+ define(K.AuthGrantDeniedStatus, "Long", 403),
838
831
  define(K.ImportMaxBytes, "Long", 1073741824),
839
832
  define(K.FilterTimeZone, "String", "UTC"),
840
833
  define(K.MigrationDropScalaLeftovers, "Boolean", false, nonPersistent),
@@ -861,6 +854,7 @@ const configDefinitions = [
861
854
  define(K.MetricsMongoDbCommand, "Boolean", false, restart),
862
855
  define(K.MetricsMongoDbConnectionPool, "Boolean", false, restart),
863
856
  define(K.LoggingMetricsStep, "Duration", 60 * 6e4, restart),
857
+ define(K.LoggingMetricsRuntime, "Boolean", false, restart),
864
858
  define(K.LoggingMetricsJvm, "Boolean", false, restart),
865
859
  define(K.LoggingMetricsSystem, "Boolean", false, restart),
866
860
  define(K.LoggingMetricsMongo, "Boolean", false, restart),
@@ -998,7 +992,8 @@ async function verifyNothing(password) {
998
992
  }
999
993
 
1000
994
  const AuthErrors = {
1001
- userNotFound: () => new MongocampError("user does not exists", 404),
995
+ // 2.1.0: names the user (the Scala text had an empty name)
996
+ userNotFound: (userId) => new MongocampError(`user ${userId} does not exist`, 404),
1002
997
  userOrPassword: () => new MongocampError("user or password does not exists", 401),
1003
998
  apiKey: () => new MongocampError("apiKey not valid", 401),
1004
999
  badConfiguration: () => new MongocampError("Authentication method not configured correctly", 501, 5001)
@@ -1006,7 +1001,7 @@ const AuthErrors = {
1006
1001
  async function findUser(holder, userId) {
1007
1002
  const user = await holder.findUserOption(userId);
1008
1003
  if (!user) {
1009
- throw AuthErrors.userNotFound();
1004
+ throw AuthErrors.userNotFound(userId);
1010
1005
  }
1011
1006
  return user;
1012
1007
  }
@@ -1486,7 +1481,7 @@ class AuthService {
1486
1481
  }
1487
1482
  /** The error for a logged in user without the grant for a request; the status is `AUTH_GRANT_DENIED_STATUS` (403) or 401. */
1488
1483
  grantDenied(message) {
1489
- const status = this.config.number(ConfigKeys.AuthGrantDeniedStatus) === 403 ? 403 : 401;
1484
+ const status = this.config.number(ConfigKeys.AuthGrantDeniedStatus) === 401 ? 401 : 403;
1490
1485
  return new MongocampError(message, status, ErrorCodes.unauthorizedUser);
1491
1486
  }
1492
1487
  async requireAdmin(request) {
@@ -1965,6 +1960,7 @@ class EventBus {
1965
1960
  hooks = createHooks();
1966
1961
  listeners = /* @__PURE__ */ new Map();
1967
1962
  observers = /* @__PURE__ */ new Set();
1963
+ targets = /* @__PURE__ */ new Set();
1968
1964
  /** Registers a listener; the returned function removes it. */
1969
1965
  on(name, listener) {
1970
1966
  this.listeners.set(name, (this.listeners.get(name) ?? 0) + 1);
@@ -1985,9 +1981,25 @@ class EventBus {
1985
1981
  this.observers.delete(observer);
1986
1982
  };
1987
1983
  }
1984
+ /** Sends the events to a hook system of the host (`forwardToNitro`); the returned function stops it. */
1985
+ forward(target) {
1986
+ this.targets.add(target);
1987
+ return () => {
1988
+ this.targets.delete(target);
1989
+ };
1990
+ }
1991
+ targetsFor(name) {
1992
+ return [...this.targets].filter((target) => {
1993
+ try {
1994
+ return target.listens(name);
1995
+ } catch {
1996
+ return true;
1997
+ }
1998
+ });
1999
+ }
1988
2000
  /** Whether anybody listens, so that an expensive payload (old values of documents) is only read when needed. */
1989
2001
  has(name) {
1990
- return (this.listeners.get(name) ?? 0) > 0;
2002
+ return (this.listeners.get(name) ?? 0) > 0 || this.targetsFor(name).length > 0;
1991
2003
  }
1992
2004
  /** Sends an event without waiting for the listeners; a failure of a listener is logged. */
1993
2005
  publish(name, payload) {
@@ -1998,10 +2010,21 @@ class EventBus {
1998
2010
  this.log(`an observer failed for event <${name}>`, error);
1999
2011
  }
2000
2012
  }
2001
- if (!this.has(name)) {
2013
+ const targets = this.targetsFor(name);
2014
+ if ((this.listeners.get(name) ?? 0) === 0 && targets.length === 0) {
2002
2015
  return;
2003
2016
  }
2004
2017
  const event = { ...payload, id: randomUUID(), eventDate: /* @__PURE__ */ new Date(), name };
2018
+ for (const target of targets) {
2019
+ try {
2020
+ Promise.resolve(target.call(name, event)).catch((error) => this.log(`a hook failed for event <${name}>`, error));
2021
+ } catch (error) {
2022
+ this.log(`a hook failed for event <${name}>`, error);
2023
+ }
2024
+ }
2025
+ if ((this.listeners.get(name) ?? 0) === 0) {
2026
+ return;
2027
+ }
2005
2028
  try {
2006
2029
  const result = this.hooks.callHook(name, event);
2007
2030
  Promise.resolve(result).catch((error) => this.log(`could not publish event <${name}>`, error));
@@ -2319,6 +2342,16 @@ function optionalBoolean(body, field) {
2319
2342
  }
2320
2343
  return value;
2321
2344
  }
2345
+ function optionalInteger$1(body, field) {
2346
+ const value = body[field];
2347
+ if (value === void 0 || value === null) {
2348
+ return void 0;
2349
+ }
2350
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
2351
+ fail(field);
2352
+ }
2353
+ return value;
2354
+ }
2322
2355
  function stringList(value, field) {
2323
2356
  if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
2324
2357
  fail(field);
@@ -3236,7 +3269,7 @@ function searchMap(query, negated, settings) {
3236
3269
  appendRange(negated, result, query, settings);
3237
3270
  break;
3238
3271
  case "term":
3239
- appendTerm(negated, result, query.field, query.text, settings);
3272
+ appendTerm(negated, result, query.field, query.text, settings, query.quoted === true);
3240
3273
  break;
3241
3274
  case "prefix":
3242
3275
  appendPrefix(negated, result, query.field, query.text, settings.caseInsensitive);
@@ -3284,10 +3317,16 @@ function appendRange(negated, result, query, settings) {
3284
3317
  result[field] = { $exists: !negated };
3285
3318
  return;
3286
3319
  }
3320
+ const nextDay = upper !== null && query.includeUpper ? dayAfter(upper) : void 0;
3321
+ const upperDate = nextDay !== void 0 && convert(upper) instanceof Date ? convert(nextDay) : void 0;
3287
3322
  const rangeSearch = (convert2) => {
3288
3323
  const range = {};
3289
3324
  if (upper !== null) {
3290
- range[query.includeUpper ? "$lte" : "$lt"] = convert2(upper);
3325
+ if (upperDate instanceof Date && convert2(upper) instanceof Date) {
3326
+ range.$lt = upperDate;
3327
+ } else {
3328
+ range[query.includeUpper ? "$lte" : "$lt"] = convert2(upper);
3329
+ }
3291
3330
  }
3292
3331
  if (lower !== null) {
3293
3332
  range[query.includeLower ? "$gte" : "$gt"] = convert2(lower);
@@ -3309,12 +3348,20 @@ function appendRange(negated, result, query, settings) {
3309
3348
  result[field] = inRange;
3310
3349
  }
3311
3350
  }
3312
- function appendTerm(negated, result, field, termText, settings) {
3351
+ function dayAfter(text) {
3352
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
3353
+ if (!match) {
3354
+ return void 0;
3355
+ }
3356
+ const next = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]) + 1));
3357
+ return next.toISOString().slice(0, 10);
3358
+ }
3359
+ function appendTerm(negated, result, field, termText, settings, quoted = false) {
3313
3360
  if (containsWildcard(termText)) {
3314
3361
  appendWildcard(negated, result, field, termText, settings.caseInsensitive);
3315
3362
  return;
3316
3363
  }
3317
- const both = settings.both;
3364
+ const both = settings.both || quoted;
3318
3365
  const text = termText.includes("*") ? unescape(termText) : termText;
3319
3366
  const value = convertTermValue(text, settings.timeZone);
3320
3367
  const operator = negated ? "$ne" : "$eq";
@@ -3329,7 +3376,9 @@ function appendPrefix(negated, result, field, prefix, caseInsensitive) {
3329
3376
  result[field] = { $exists: !negated };
3330
3377
  return;
3331
3378
  }
3332
- Object.assign(result, textOrNumberMatch(negated, field, anchoredRegex(`${literalToRegex(prefix)}(.*?)`, caseInsensitive), prefix));
3379
+ const regex = anchoredRegex(`${literalToRegex(prefix)}(.*?)`, caseInsensitive);
3380
+ Object.assign(result, textOrNumberMatch(negated, field, regex, prefix));
3381
+ addObjectIdText(negated, result, field, prefix, regex);
3333
3382
  }
3334
3383
  function appendWildcard(negated, result, field, text, caseInsensitive) {
3335
3384
  if (text === "*") {
@@ -3337,7 +3386,20 @@ function appendWildcard(negated, result, field, text, caseInsensitive) {
3337
3386
  return;
3338
3387
  }
3339
3388
  const literals = wildcardTokens(text).filter((token) => token.literal || token.char !== "*" && token.char !== "?").map((token) => token.char).join("");
3340
- Object.assign(result, textOrNumberMatch(negated, field, anchoredRegex(wildcardToRegex(text), caseInsensitive), literals));
3389
+ const regex = anchoredRegex(wildcardToRegex(text), caseInsensitive);
3390
+ Object.assign(result, textOrNumberMatch(negated, field, regex, literals));
3391
+ addObjectIdText(negated, result, field, literals, regex);
3392
+ }
3393
+ function addObjectIdText(negated, result, field, literals, regex) {
3394
+ if (field !== "_id" || !/^[\da-f]+$/i.test(literals)) {
3395
+ return;
3396
+ }
3397
+ const objectIdMatch = { $expr: { $and: [{ $eq: [{ $type: "$_id" }, "objectId"] }, { $regexMatch: { input: { $toString: "$_id" }, regex: regex.$regex, options: "i" } }] } };
3398
+ const textFilter = { ...result };
3399
+ for (const key of Object.keys(result)) {
3400
+ Reflect.deleteProperty(result, key);
3401
+ }
3402
+ Object.assign(result, negated ? { $and: [textFilter, { $nor: [objectIdMatch] }] } : { $or: [textFilter, objectIdMatch] });
3341
3403
  }
3342
3404
  function couldBeNumberText(literals) {
3343
3405
  return /^[\d.e+-]*$/i.test(literals) && /\d/.test(literals);
@@ -3884,11 +3946,8 @@ class Parser {
3884
3946
  return { type: "range", field, lower: null, upper: bound, includeLower: true, includeUpper: true };
3885
3947
  }
3886
3948
  }
3887
- if (quoted && text.includes("*")) {
3888
- return { type: "wildcard", field, text: escapeChars(text, "\\?") };
3889
- }
3890
3949
  if (quoted) {
3891
- return { type: "term", field, text };
3950
+ return { type: "term", field, text: text.includes("*") ? escapeChars(text, "\\*?") : text, quoted: true };
3892
3951
  }
3893
3952
  const terms = tokenize(text).map((token) => this.termQuery(field, token.term));
3894
3953
  if (terms.length === 0) {
@@ -4045,7 +4104,7 @@ function registerAdminRoutes(app, context) {
4045
4104
  const userId = pathParam(event, "userId");
4046
4105
  const deleted = await holder.deleteUser(userId);
4047
4106
  if (!deleted) {
4048
- throw AuthErrors.userNotFound();
4107
+ throw AuthErrors.userNotFound(userId);
4049
4108
  }
4050
4109
  await auth.tokens.invalidateUserTokens(userId);
4051
4110
  events.publish("user:delete", { user: admin.user, deletedUser: userId });
@@ -4560,6 +4619,35 @@ function pagedPipeline(pipeline, skip, rows) {
4560
4619
  return [...pipeline, ...skip > 0 ? [{ $skip: skip }] : [], { $limit: rows }];
4561
4620
  }
4562
4621
 
4622
+ const SecretUserFields = ["password"];
4623
+ function secretFieldsOf(database, collection) {
4624
+ const name = parseCollectionName(collection);
4625
+ const defaultDatabase = database.db().databaseName;
4626
+ const inDefault = name.database === void 0 || name.database === defaultDatabase;
4627
+ return inDefault && name.name === database.internalCollectionName("users") ? SecretUserFields : [];
4628
+ }
4629
+ function withoutSecrets(document, fields) {
4630
+ if (fields.length === 0 || !fields.some((field) => field in document)) {
4631
+ return document;
4632
+ }
4633
+ return Object.fromEntries(Object.entries(document).filter(([key]) => !fields.includes(key)));
4634
+ }
4635
+ function referencesSecret(value, fields) {
4636
+ if (fields.length === 0) {
4637
+ return false;
4638
+ }
4639
+ if (typeof value === "string") {
4640
+ return fields.some((field) => value === `$${field}` || value.startsWith(`$${field}.`));
4641
+ }
4642
+ if (Array.isArray(value)) {
4643
+ return value.some((entry) => referencesSecret(entry, fields));
4644
+ }
4645
+ if (value !== null && typeof value === "object") {
4646
+ return Object.values(value).some((entry) => referencesSecret(entry, fields));
4647
+ }
4648
+ return false;
4649
+ }
4650
+
4563
4651
  function readAggregateRequest(body) {
4564
4652
  const object = asObject(body);
4565
4653
  if (!Array.isArray(object.pipeline)) {
@@ -4572,7 +4660,7 @@ function readAggregateRequest(body) {
4572
4660
  }
4573
4661
  return { stage: stage.stage, value: decodeAny(stage.value) };
4574
4662
  });
4575
- return { pipeline, allowDiskUse: optionalBoolean(object, "allowDiskUse") ?? false };
4663
+ return { pipeline, allowDiskUse: optionalBoolean(object, "allowDiskUse") ?? false, filter: optionalString(object, "filter") };
4576
4664
  }
4577
4665
  function registerAggregationRoutes(app, context) {
4578
4666
  const { auth, database, config } = context;
@@ -4584,26 +4672,39 @@ function registerAggregationRoutes(app, context) {
4584
4672
  const mode = parseExtendedJsonMode(params.get("extendedJson")) ?? DefaultExtendedJsonMode;
4585
4673
  const paging = readPaging(params);
4586
4674
  const count = readCountMode(params);
4587
- const matchFilter = filterParameter(params.get("filter"), filterOptions(params, config));
4588
4675
  const request = readAggregateRequest(await readJson(event));
4676
+ const queryFilter = params.get("filter");
4677
+ if (queryFilter !== null && queryFilter.trim() !== "" && request.filter !== void 0 && request.filter.trim() !== "") {
4678
+ throw MongocampError.badRequest("send the filter in the query or in the body, not in both", ErrorCodes.ambiguousFilter);
4679
+ }
4680
+ const matchFilter = request.filter !== void 0 ? bodyFilter(request.filter, filterOptions(params, config)) : filterParameter(queryFilter, filterOptions(params, config));
4589
4681
  checkPipeline(user, collection, request.pipeline, config.list(ConfigKeys.AggregationStagesDenied));
4590
4682
  const prefix = [];
4591
4683
  if (Object.keys(matchFilter).length > 0) {
4592
4684
  checkMatchBefore(request.pipeline);
4593
4685
  prefix.push({ $match: convertFields(matchFilter) });
4594
4686
  }
4687
+ const secrets = secretFieldsOf(database, collection);
4688
+ if (secrets.length > 0) {
4689
+ prefix.unshift({ $unset: [...secrets] });
4690
+ }
4595
4691
  const pipeline = [...prefix, ...toBsonPipeline(request.pipeline)];
4596
4692
  const { documents, info } = await paginatedAggregation(collectionOf(database, collection), pipeline, request.allowDiskUse, paging, count);
4597
- return jsonResponse(documents.map((document) => documentToJson(document, mode)), { headers: paginationHeaders(info) });
4693
+ return jsonResponse(documents.map((document) => withoutSecrets(documentToJson(document, mode), secrets)), { headers: paginationHeaders(info) });
4598
4694
  });
4599
4695
  app.post("/mongodb/collections/:collectionName/distinct/:field", async (event) => {
4600
4696
  const collection = collectionParam(event);
4601
4697
  await auth.requireCollection(event.req, collection, "read");
4602
- const field = `$${pathParam(event, "field")}`;
4698
+ const fieldName = pathParam(event, "field");
4699
+ if (secretFieldsOf(database, collection).some((secret) => fieldName === secret || fieldName.startsWith(`${secret}.`))) {
4700
+ throw MongocampError.badRequest(`the field ${fieldName} of the users collection cannot be read`);
4701
+ }
4702
+ const field = `$${fieldName}`;
4603
4703
  const pipeline = [{ $group: { _id: field, field: { $first: field } } }];
4604
4704
  const params = queryParams(event);
4605
4705
  const { documents, info } = await paginatedAggregation(collectionOf(database, collection), pipeline, true, readPaging(params), readCountMode(params));
4606
- return jsonResponse(documents.map((document) => legacyValue(document.field)), { headers: paginationHeaders(info) });
4706
+ const mode = parseExtendedJsonMode(params.get("extendedJson"));
4707
+ return jsonResponse(documents.map((document) => mode === void 0 || mode === "plain" ? legacyValue(document.field) : documentToJson({ v: document.field }, mode).v), { headers: paginationHeaders(info) });
4607
4708
  });
4608
4709
  }
4609
4710
 
@@ -13454,19 +13555,49 @@ function exportCursor(collection, query) {
13454
13555
  }
13455
13556
  return cursor;
13456
13557
  }
13457
- async function* converted(cursor, mode) {
13558
+ async function* converted(cursor, mode, secrets = []) {
13458
13559
  for await (const document of cursor) {
13459
- yield documentToJson(document, mode);
13560
+ yield withoutSecrets(documentToJson(document, mode), secrets);
13460
13561
  }
13461
13562
  }
13462
- function exportStream(cursor, format, columns, mode) {
13563
+ function endMarker(format, count) {
13564
+ if (format === "ndjson") {
13565
+ return `${stringifyJson({ $end: true, count })}
13566
+ `;
13567
+ }
13568
+ return format === "csv" ? `# end ${count}\r
13569
+ ` : "";
13570
+ }
13571
+ function errorMarker(format, error) {
13572
+ const message = removeInternalNames(error instanceof Error ? error.message : String(error));
13573
+ if (format === "ndjson") {
13574
+ return `${stringifyJson({ $error: message })}
13575
+ `;
13576
+ }
13577
+ return format === "csv" ? `# error ${message.replaceAll(/[\r\n]+/g, " ")}\r
13578
+ ` : "";
13579
+ }
13580
+ function exportStream(cursor, format, columns, options = {}) {
13463
13581
  const encoder = new TextEncoder();
13464
- const pieces = renderExport(format, converted(cursor, mode), columns);
13582
+ let count = 0;
13583
+ async function* counted() {
13584
+ for await (const document of converted(cursor, options.mode, options.secrets)) {
13585
+ count++;
13586
+ yield document;
13587
+ }
13588
+ }
13589
+ const pieces = renderExport(format, counted(), columns);
13465
13590
  return new ReadableStream({
13466
13591
  async pull(controller) {
13467
13592
  try {
13468
13593
  const { value, done } = await pieces.next();
13469
13594
  if (done) {
13595
+ if (options.trailer) {
13596
+ const marker = endMarker(format, count);
13597
+ if (marker) {
13598
+ controller.enqueue(encoder.encode(marker));
13599
+ }
13600
+ }
13470
13601
  controller.close();
13471
13602
  await cursor.close();
13472
13603
  } else {
@@ -13475,7 +13606,15 @@ function exportStream(cursor, format, columns, mode) {
13475
13606
  } catch (error) {
13476
13607
  await cursor.close().catch(() => {
13477
13608
  });
13478
- controller.error(error);
13609
+ if (options.trailer) {
13610
+ const marker = errorMarker(format, error);
13611
+ if (marker) {
13612
+ controller.enqueue(encoder.encode(marker));
13613
+ }
13614
+ controller.close();
13615
+ } else {
13616
+ controller.error(error);
13617
+ }
13479
13618
  }
13480
13619
  },
13481
13620
  async cancel() {
@@ -13659,8 +13798,8 @@ function requireMatched(count) {
13659
13798
  throw MongocampError.notFound("could not find document");
13660
13799
  }
13661
13800
  }
13662
- function pageResponse(page) {
13663
- return jsonResponse(page.items, { headers: paginationHeaders(page.info) });
13801
+ function pageResponse(page, secrets = []) {
13802
+ return jsonResponse(page.items.map((item) => withoutSecrets(item, secrets)), { headers: paginationHeaders(page.info) });
13664
13803
  }
13665
13804
  function extendedJsonMode(params) {
13666
13805
  return parseExtendedJsonMode(params.get("extendedJson")) ?? DefaultExtendedJsonMode;
@@ -13746,7 +13885,7 @@ function registerDocumentRoutes(app, context) {
13746
13885
  sort: sortFromList(params.getAll("sort")),
13747
13886
  projection: projectionFromList(params.getAll("projection"))
13748
13887
  };
13749
- return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), extendedJsonMode(params), readCountMode(params)));
13888
+ return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), extendedJsonMode(params), readCountMode(params)), secretFieldsOf(database, collection));
13750
13889
  });
13751
13890
  app.get(`${base}/count`, async (event) => {
13752
13891
  const collection = collectionParam(event);
@@ -13755,6 +13894,14 @@ function registerDocumentRoutes(app, context) {
13755
13894
  const filter = convertFields(filterParameter(params.get("filter"), filterOptions(params, config)));
13756
13895
  return jsonResponse({ count: await collectionOf(database, collection).countDocuments(filter) });
13757
13896
  });
13897
+ app.post(`${base}/count`, async (event) => {
13898
+ const collection = collectionParam(event);
13899
+ await auth.requireCollection(event.req, collection, "read");
13900
+ const params = queryParams(event);
13901
+ const body = asObject(await readJson(event));
13902
+ const filter = convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config)));
13903
+ return jsonResponse({ count: await collectionOf(database, collection).countDocuments(filter) });
13904
+ });
13758
13905
  app.post(`${base}/search`, async (event) => {
13759
13906
  const collection = collectionParam(event);
13760
13907
  await auth.requireCollection(event.req, collection, "read");
@@ -13766,7 +13913,7 @@ function registerDocumentRoutes(app, context) {
13766
13913
  sort: sortFromList(stringListField(body, "sort")),
13767
13914
  projection: projectionFromList(stringListField(body, "projection"))
13768
13915
  };
13769
- return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), mode, readCountMode(params)));
13916
+ return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), mode, readCountMode(params)), secretFieldsOf(database, collection));
13770
13917
  });
13771
13918
  app.post(base, async (event) => {
13772
13919
  const collection = collectionParam(event);
@@ -13779,7 +13926,10 @@ function registerDocumentRoutes(app, context) {
13779
13926
  sort: mapField(body, "sort", true),
13780
13927
  projection: mapField(body, "projection", true)
13781
13928
  };
13782
- return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), mode, readCountMode(params)));
13929
+ if (referencesSecret(request.projection, secretFieldsOf(database, collection))) {
13930
+ throw MongocampError.badRequest("the projection must not read the password of the users collection");
13931
+ }
13932
+ return pageResponse(await paginatedFind(collectionOf(database, collection), request, readPaging(params), mode, readCountMode(params)), secretFieldsOf(database, collection));
13783
13933
  });
13784
13934
  app.put(base, async (event) => {
13785
13935
  const collection = collectionParam(event);
@@ -13796,7 +13946,7 @@ function registerDocumentRoutes(app, context) {
13796
13946
  if (!document) {
13797
13947
  throw MongocampError.notFound("could not find document");
13798
13948
  }
13799
- return jsonResponse(documentToJson(document, mode));
13949
+ return jsonResponse(withoutSecrets(documentToJson(document, mode), secretFieldsOf(database, collection)));
13800
13950
  });
13801
13951
  app.delete(`${base}/:documentId`, async (event) => {
13802
13952
  const collection = collectionParam(event);
@@ -13827,37 +13977,54 @@ function registerDocumentRoutes(app, context) {
13827
13977
  requireMatched(result.matchedCount);
13828
13978
  return updated(user, collection, updateResponse(result, id), old.slice(0, 1));
13829
13979
  });
13830
- app.get(`${base}/export`, async (event) => {
13831
- const collection = collectionParam(event);
13832
- await auth.requireCollection(event.req, collection, "read");
13833
- const params = queryParams(event);
13980
+ const exportResponse = async (collection, params, request) => {
13834
13981
  const format = parseExportFormat(params.get("format"));
13835
13982
  const mode = parseExtendedJsonMode(params.get("extendedJson")) ?? (format === "csv" ? "plain" : DefaultExtendedJsonMode);
13836
- const limit = intQuery(params, "limit");
13837
- if (limit !== void 0 && limit <= 0) {
13983
+ if (request.limit !== void 0 && request.limit <= 0) {
13838
13984
  throw MongocampError.badRequest("limit has to be greater than 0");
13839
13985
  }
13840
- const projectionFields = params.getAll("projection");
13841
13986
  const query = {
13842
- filter: convertFields(filterParameter(params.get("filter"), filterOptions(params, config))),
13843
- sort: sortFromList(params.getAll("sort")),
13844
- projection: projectionFromList(projectionFields),
13845
- limit
13987
+ filter: convertFields(request.filter),
13988
+ sort: sortFromList(request.sort),
13989
+ projection: projectionFromList(request.projection),
13990
+ limit: request.limit
13846
13991
  };
13847
13992
  const target = collectionOf(database, collection);
13993
+ const secrets = secretFieldsOf(database, collection);
13848
13994
  let columns = [];
13849
13995
  if (format === "csv") {
13850
- columns = projectionFields.length > 0 ? projectionFields : await columnNames(target, ColumnSample);
13851
- if (projectionFields.length === 0 && columns.includes("_id")) {
13996
+ columns = request.projection.length > 0 ? request.projection : await columnNames(target, ColumnSample);
13997
+ if (request.projection.length === 0 && columns.includes("_id")) {
13852
13998
  columns = ["_id", ...columns.filter((column) => column !== "_id")];
13853
13999
  }
14000
+ columns = columns.filter((column) => !secrets.includes(column));
13854
14001
  }
13855
- return new Response(exportStream(exportCursor(target, query), format, columns, mode), {
14002
+ const trailer = booleanQuery(params, "trailer", false);
14003
+ return new Response(exportStream(exportCursor(target, query), format, columns, { mode, secrets, trailer }), {
13856
14004
  headers: {
13857
14005
  "content-type": "text/plain; charset=UTF-8",
13858
14006
  "content-disposition": `attachment; filename="${exportFileName(collection, format)}"`
13859
14007
  }
13860
14008
  });
14009
+ };
14010
+ app.get(`${base}/export`, async (event) => {
14011
+ const collection = collectionParam(event);
14012
+ await auth.requireCollection(event.req, collection, "read");
14013
+ const params = queryParams(event);
14014
+ const filter = filterParameter(params.get("filter"), filterOptions(params, config));
14015
+ return exportResponse(collection, params, { filter, sort: params.getAll("sort"), projection: params.getAll("projection"), limit: intQuery(params, "limit") });
14016
+ });
14017
+ app.post(`${base}/export`, async (event) => {
14018
+ const collection = collectionParam(event);
14019
+ await auth.requireCollection(event.req, collection, "read");
14020
+ const params = queryParams(event);
14021
+ const body = asObject(await readJson(event));
14022
+ return exportResponse(collection, params, {
14023
+ filter: bodyFilter(optionalString(body, "filter"), filterOptions(params, config)),
14024
+ sort: stringListField(body, "sort"),
14025
+ projection: stringListField(body, "projection"),
14026
+ limit: optionalInteger$1(body, "limit")
14027
+ });
13861
14028
  });
13862
14029
  app.post(`${base}/import`, async (event) => {
13863
14030
  const collection = collectionParam(event);
@@ -14343,26 +14510,38 @@ function registerJobRoutes(app, context) {
14343
14510
  }
14344
14511
 
14345
14512
  function registerMonitoringRoutes(app, context) {
14346
- const metrics = context.metrics;
14347
- if (!metrics) {
14348
- return;
14349
- }
14350
- const paths = { jvm: "jvm", system: "system", mongodb: "mongodb", events: "events" };
14513
+ const enabled = () => {
14514
+ if (!context.metrics) {
14515
+ throw MongocampError.notFound("Not Found");
14516
+ }
14517
+ return context.metrics;
14518
+ };
14519
+ const paths = { runtime: "runtime", system: "system", mongodb: "mongodb", events: "events" };
14351
14520
  for (const [path, category] of Object.entries(paths)) {
14352
14521
  app.get(`/system/monitoring/${path}`, async (event) => {
14522
+ const metrics = enabled();
14353
14523
  await context.auth.requireAdmin(event.req);
14354
14524
  return jsonResponse(await metrics.json(category));
14355
14525
  });
14356
14526
  }
14527
+ app.get("/system/monitoring/jvm", async (event) => {
14528
+ const metrics = enabled();
14529
+ await context.auth.requireAdmin(event.req);
14530
+ const response = jsonResponse(await metrics.json("runtime"));
14531
+ response.headers.set("deprecation", "true");
14532
+ response.headers.set("link", '</system/monitoring/runtime>; rel="successor-version"');
14533
+ return response;
14534
+ });
14357
14535
  app.get("/system/monitoring/prometheus", async (event) => {
14536
+ const metrics = enabled();
14358
14537
  await context.auth.requireAdmin(event.req);
14359
14538
  const { text, contentType } = await metrics.prometheus();
14360
14539
  return new Response(text, { headers: { "content-type": contentType } });
14361
14540
  });
14362
14541
  }
14363
14542
 
14364
- const MetricCategories = ["jvm", "system", "mongodb", "events"];
14365
- const MonitoringCollections = { jvm: "monitoring_jvm", system: "monitoring_system", mongodb: "monitoring_mongo_db", events: "monitoring_event" };
14543
+ const MetricCategories = ["runtime", "system", "mongodb", "events"];
14544
+ const MonitoringCollections = { runtime: "monitoring_runtime", system: "monitoring_system", mongodb: "monitoring_mongo_db", events: "monitoring_event" };
14366
14545
  const baseUnitOf = (name) => name.endsWith("_seconds") || name.endsWith("_seconds_total") ? "seconds" : name.endsWith("_bytes") || name.endsWith("_bytes_total") ? "bytes" : "";
14367
14546
  function labelsOf(value, without = []) {
14368
14547
  return Object.fromEntries(Object.entries(value.labels ?? {}).filter(([key]) => !without.includes(key)).map(([key, entry]) => [key, String(entry)]));
@@ -14594,7 +14773,7 @@ class MongocampMetrics {
14594
14773
  }
14595
14774
  async json(category) {
14596
14775
  switch (category) {
14597
- case "jvm":
14776
+ case "runtime":
14598
14777
  return toMetrics((await this.runtime.getMetricsAsJSON()).filter((entry) => entry.name.startsWith("nodejs_")));
14599
14778
  case "system":
14600
14779
  return toMetrics((await this.runtime.getMetricsAsJSON()).filter((entry) => !entry.name.startsWith("nodejs_")));
@@ -14611,8 +14790,7 @@ class MongocampMetrics {
14611
14790
  /** Writes a snapshot of the enabled categories every `LOGGING_METRICS_MONGODB_STEP`. */
14612
14791
  startPersistence() {
14613
14792
  const { config } = this.context;
14614
- const enabled = MetricCategories.filter((category) => config.boolean({
14615
- jvm: ConfigKeys.LoggingMetricsJvm,
14793
+ const enabled = MetricCategories.filter((category) => category === "runtime" ? config.boolean(ConfigKeys.LoggingMetricsRuntime) || config.boolean(ConfigKeys.LoggingMetricsJvm) : config.boolean({
14616
14794
  system: ConfigKeys.LoggingMetricsSystem,
14617
14795
  mongodb: ConfigKeys.LoggingMetricsMongo,
14618
14796
  events: ConfigKeys.LoggingMetricsEvent
@@ -14693,6 +14871,24 @@ async function enableRequestLogging(context) {
14693
14871
  };
14694
14872
  }
14695
14873
 
14874
+ function requestLogging() {
14875
+ return { name: "requestLogging", setup: (context) => enableRequestLogging(context) };
14876
+ }
14877
+ function metrics() {
14878
+ return {
14879
+ name: "metrics",
14880
+ setup: (context) => {
14881
+ const created = new MongocampMetrics(context);
14882
+ context.metrics = created;
14883
+ created.startPersistence();
14884
+ return () => {
14885
+ created.close();
14886
+ context.metrics = void 0;
14887
+ };
14888
+ }
14889
+ };
14890
+ }
14891
+
14696
14892
  function registerInformationRoutes(app, context) {
14697
14893
  app.get("/version", () => jsonResponse({
14698
14894
  name: context.version.name,
@@ -14813,7 +15009,7 @@ async function systemStats(admin) {
14813
15009
  function capabilityLimits(config) {
14814
15010
  return {
14815
15011
  importMaxBytes: config.number(ConfigKeys.ImportMaxBytes),
14816
- grantDeniedStatus: config.number(ConfigKeys.AuthGrantDeniedStatus) === 403 ? 403 : 401
15012
+ grantDeniedStatus: config.number(ConfigKeys.AuthGrantDeniedStatus) === 401 ? 401 : 403
14817
15013
  };
14818
15014
  }
14819
15015
  async function capabilities(config, serverVersion, info) {
@@ -14846,9 +15042,6 @@ function registerConfigurationRoutes(app, context) {
14846
15042
  return [definition.key, SecretKeys.has(definition.key) && value !== null && value !== "" ? SecretMask : value];
14847
15043
  }).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
14848
15044
  return jsonResponse({
14849
- routesPlugins: context.routeGroups,
14850
- filePlugins: ["GridFsFileAdapter"],
14851
- ignoredPlugins: config.list(ConfigKeys.PluginsIgnored),
14852
15045
  configurations: values
14853
15046
  });
14854
15047
  });
@@ -14923,20 +15116,20 @@ const defaultVersion = {
14923
15116
  builtAt: /* @__PURE__ */ new Date()
14924
15117
  };
14925
15118
  const routeGroups = [
14926
- ["InformationRoutes", registerInformationRoutes],
14927
- ["AuthRoutes", registerAuthRoutes],
14928
- ["AdminRoutes", registerAdminRoutes],
14929
- ["ConfigurationRoutes", registerConfigurationRoutes],
14930
- ["SystemRoutes", registerSystemRoutes],
14931
- ["JobRoutes", registerJobRoutes],
14932
- ["MetricsRoutes", registerMonitoringRoutes],
14933
- ["ApiDocsRoutes", registerDocsRoutes],
14934
- ["DatabaseRoutes", registerDatabaseRoutes],
14935
- ["CollectionRoutes", registerCollectionRoutes],
14936
- ["AggregationRoutes", registerAggregationRoutes],
14937
- ["DocumentRoutes", registerDocumentRoutes],
14938
- ["IndexRoutes", registerIndexRoutes],
14939
- ["BucketRoutes", registerBucketRoutes]
15119
+ registerInformationRoutes,
15120
+ registerAuthRoutes,
15121
+ registerAdminRoutes,
15122
+ registerConfigurationRoutes,
15123
+ registerSystemRoutes,
15124
+ registerJobRoutes,
15125
+ registerMonitoringRoutes,
15126
+ registerDocsRoutes,
15127
+ registerDatabaseRoutes,
15128
+ registerCollectionRoutes,
15129
+ registerAggregationRoutes,
15130
+ registerDocumentRoutes,
15131
+ registerIndexRoutes,
15132
+ registerBucketRoutes
14940
15133
  ];
14941
15134
  function createApp(context) {
14942
15135
  const app = new H3({
@@ -14944,7 +15137,7 @@ function createApp(context) {
14944
15137
  silent: true,
14945
15138
  onError: (error) => toErrorResponse(error, errorLogger(context.logger))
14946
15139
  });
14947
- for (const [, register] of routeGroups) {
15140
+ for (const register of routeGroups) {
14948
15141
  register(app, context);
14949
15142
  }
14950
15143
  return app;
@@ -14980,7 +15173,7 @@ async function createMongocampServer(options = {}) {
14980
15173
  await configurations.initialize(options.configRefresh ?? void 0);
14981
15174
  if (config.boolean(ConfigKeys.MigrationDropScalaLeftovers)) {
14982
15175
  const leftovers = await dropScalaLeftovers(database);
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`);
15176
+ logger.info(`[mongocamp] Scala leftovers: dropped ${leftovers.droppedCollections.length} Quartz collections (${leftovers.droppedCollections.join(", ") || "-"}), removed ${leftovers.removedTokenEntries} token entries, rewrote ${leftovers.rewrittenJobs} job expressions, removed ${leftovers.removedSettings} plugin settings`);
14984
15177
  }
14985
15178
  await auth.initialize(logger);
14986
15179
  await jobs.initialize();
@@ -15000,19 +15193,25 @@ async function createMongocampServer(options = {}) {
15000
15193
  events,
15001
15194
  jobs,
15002
15195
  systemInfo: buildInfoCache(database.db()),
15003
- shutdown: options.shutdown,
15004
- routeGroups: routeGroups.map(([name]) => name)
15196
+ shutdown: options.shutdown
15005
15197
  };
15006
15198
  const cleanups = [];
15007
- try {
15008
- if (config.boolean(ConfigKeys.RequestLoggingEnabled)) {
15009
- cleanups.push(await enableRequestLogging(context));
15199
+ const used = /* @__PURE__ */ new Set();
15200
+ const use = async (feature) => {
15201
+ if (used.has(feature.name)) {
15202
+ return;
15010
15203
  }
15011
- if (config.boolean(ConfigKeys.MetricsEnabled)) {
15012
- const metrics = new MongocampMetrics(context);
15013
- context.metrics = metrics;
15014
- metrics.startPersistence();
15015
- cleanups.push(() => metrics.close());
15204
+ used.add(feature.name);
15205
+ cleanups.push(await feature.setup(context));
15206
+ };
15207
+ try {
15208
+ if (options.featureSwitches !== false) {
15209
+ for (const [key, feature] of [[ConfigKeys.RequestLoggingEnabled, requestLogging()], [ConfigKeys.MetricsEnabled, metrics()]]) {
15210
+ if (config.boolean(key)) {
15211
+ logger.warn(`[mongocamp] ${key} is deprecated for embedding hosts (removed in 3.0): add the feature with server.use(${feature.name}()), e.g. in a Nitro plugin on mongocamp:ready`);
15212
+ await use(feature);
15213
+ }
15214
+ }
15016
15215
  }
15017
15216
  } catch (error) {
15018
15217
  await Promise.allSettled(cleanups.map((cleanup) => cleanup()));
@@ -15021,8 +15220,6 @@ async function createMongocampServer(options = {}) {
15021
15220
  await database.close();
15022
15221
  throw error;
15023
15222
  }
15024
- const routeGroupNames = routeGroups.filter(([name]) => name !== "MetricsRoutes" || context.metrics).map(([name]) => name);
15025
- context.routeGroups = routeGroupNames;
15026
15223
  const app = createApp(context);
15027
15224
  const requestEvents = new RequestEvents(events, auth);
15028
15225
  const fetch = async (request, fetchOptions = {}) => {
@@ -15049,6 +15246,7 @@ async function createMongocampServer(options = {}) {
15049
15246
  context,
15050
15247
  events,
15051
15248
  registerJobHandler: (className, handler) => jobs.registerHandler(className, handler),
15249
+ use,
15052
15250
  routes: () => app["~routes"].filter((route) => route.route && route.method).map((route) => `${route.method} ${route.route}`),
15053
15251
  close: async () => {
15054
15252
  await Promise.allSettled(cleanups.map((cleanup) => cleanup()));
@@ -15059,4 +15257,21 @@ async function createMongocampServer(options = {}) {
15059
15257
  };
15060
15258
  }
15061
15259
 
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 };
15260
+ const HookPrefix = "mongocamp:";
15261
+ function listens(hooks, name) {
15262
+ const table = hooks._hooks;
15263
+ return table === void 0 || (table[name]?.length ?? 0) > 0;
15264
+ }
15265
+ function forwardEventsToHooks(server, hooks) {
15266
+ return server.events.forward({
15267
+ listens: (name) => listens(hooks, `${HookPrefix}${name}`),
15268
+ call: (name, event) => hooks.callHook(`${HookPrefix}${name}`, event)
15269
+ });
15270
+ }
15271
+ async function connectHooks(server, hooks) {
15272
+ const stop = forwardEventsToHooks(server, hooks);
15273
+ await hooks.callHook(`${HookPrefix}ready`, server);
15274
+ return stop;
15275
+ }
15276
+
15277
+ export { CleanUpTokenJob, CleanUpTokenJobClass, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, JobScheduler, LuceneQueryError, MongocampError, PaginationHeaders, TextMarker, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, decodeAny, documentToJson, filterParameter, forwardEventsToHooks, luceneQueryToFilter, luceneToFilter, metrics, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, requestFields, requestLogging, stringifyJson };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sfxcode/mongocamp-server-core",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {