@openinc/parse-server-opendash 4.18.0 → 4.19.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.
@@ -1,2 +1 @@
1
1
  export { deriveSearchFields, type ChangelogSearchFields, } from "./services/deriveSearchFields.js";
2
- export { ensureChangelogIndexes } from "./services/ensureChangelogIndexes.js";
@@ -1,7 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ensureChangelogIndexes = exports.deriveSearchFields = void 0;
3
+ exports.deriveSearchFields = void 0;
4
4
  var deriveSearchFields_js_1 = require("./services/deriveSearchFields.js");
5
5
  Object.defineProperty(exports, "deriveSearchFields", { enumerable: true, get: function () { return deriveSearchFields_js_1.deriveSearchFields; } });
6
- var ensureChangelogIndexes_js_1 = require("./services/ensureChangelogIndexes.js");
7
- Object.defineProperty(exports, "ensureChangelogIndexes", { enumerable: true, get: function () { return ensureChangelogIndexes_js_1.ensureChangelogIndexes; } });
@@ -0,0 +1,22 @@
1
+ /** The indexes of one class: index name → fields. */
2
+ export interface ClassIndexes {
3
+ className: string;
4
+ indexes: Record<string, string[]>;
5
+ }
6
+ /**
7
+ * Indexes created on startup by `ensureIndexes()`, next to those of every
8
+ * relation's join table. Only add one for a query that runs often on a class
9
+ * that grows — every index costs on each write, and a class of a few hundred
10
+ * rows is scanned faster than an index pays off.
11
+ *
12
+ * Names start with `od_` and list the fields; they only have to be unique
13
+ * within the class. An index gets a new name whenever its fields change:
14
+ * Mongo refuses to redefine an index under an existing name. Removing an
15
+ * entry does not drop the index — do that by hand.
16
+ *
17
+ * `deleted` is never leading: the server-side soft-delete filter is `$ne`
18
+ * (see `hideSoftDeleted()`), which hardly narrows anything. A pointer to a
19
+ * tenant-owned row (status, equipment, schedule, …) needs no `tenant` next to
20
+ * it — the pointer already is tenant-specific.
21
+ */
22
+ export declare const INDEXES: ClassIndexes[];
@@ -0,0 +1,188 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.INDEXES = void 0;
4
+ const index_js_1 = require("../../types/index.js");
5
+ /**
6
+ * Declares indexes of `type`, by name. Field names are checked against the
7
+ * generated class, so renaming a field breaks the build instead of leaving an
8
+ * index on a column nobody writes. A pointer is indexed by its name — the
9
+ * adapter turns it into `_p_<field>`, `createdAt` into `_created_at`.
10
+ *
11
+ * Parse's own classes have no generated class, only a type: pass their fixed
12
+ * name and the attributes type, `defineIndexes<_SessionAttributes>("_Session", …)`.
13
+ *
14
+ * Fields in index order: equality filters first, then the field the query
15
+ * sorts or ranges on. A query on a prefix of an index (`a` of `[a, b]`) uses
16
+ * it too, so `[a]` next to `[a, b]` is redundant.
17
+ */
18
+ function defineIndexes(type, indexes) {
19
+ const className = typeof type === "string" ? type : type.className;
20
+ return { className, indexes };
21
+ }
22
+ /**
23
+ * Indexes created on startup by `ensureIndexes()`, next to those of every
24
+ * relation's join table. Only add one for a query that runs often on a class
25
+ * that grows — every index costs on each write, and a class of a few hundred
26
+ * rows is scanned faster than an index pays off.
27
+ *
28
+ * Names start with `od_` and list the fields; they only have to be unique
29
+ * within the class. An index gets a new name whenever its fields change:
30
+ * Mongo refuses to redefine an index under an existing name. Removing an
31
+ * entry does not drop the index — do that by hand.
32
+ *
33
+ * `deleted` is never leading: the server-side soft-delete filter is `$ne`
34
+ * (see `hideSoftDeleted()`), which hardly narrows anything. A pointer to a
35
+ * tenant-owned row (status, equipment, schedule, …) needs no `tenant` next to
36
+ * it — the pointer already is tenant-specific.
37
+ */
38
+ exports.INDEXES = [
39
+ // Parse resolves the session token of every request (cached for a few
40
+ // seconds) and creates no index for it.
41
+ defineIndexes("_Session", {
42
+ od_sessionToken: ["sessionToken"],
43
+ }),
44
+ // --- Core ---
45
+ // Every changelog query sorts newest first, so each filter is paired with
46
+ // `createdAt` — Mongo then walks the index backwards and stops at the page
47
+ // size instead of sorting every match in memory. `searchText` gets none: a
48
+ // substring regex cannot use one, it is evaluated on the rows the other
49
+ // filters (class, date range) narrowed down.
50
+ defineIndexes(index_js_1.Changelog, {
51
+ od_changelog_created: ["createdAt"],
52
+ od_changelog_class_created: ["nameOfClass", "createdAt"],
53
+ od_changelog_object_created: ["changedObject", "createdAt"],
54
+ od_changelog_user_created: ["actingUser", "createdAt"],
55
+ od_changelog_fields_created: ["changedFields", "createdAt"],
56
+ od_changelog_refs_created: ["refs", "createdAt"],
57
+ }),
58
+ // `hasPermission()` on nearly every guarded write.
59
+ defineIndexes(index_js_1.Permission, {
60
+ od_key_tenant: ["key", "tenant"],
61
+ }),
62
+ // Ticket watcher rules, notification icons, alarm secrets.
63
+ defineIndexes(index_js_1.Config, {
64
+ od_key_tenant: ["key", "tenant"],
65
+ }),
66
+ // Every get/set of the frontend's user storage.
67
+ defineIndexes(index_js_1.UserData, {
68
+ od_user_key: ["user", "key"],
69
+ }),
70
+ // Notification drawer and unread badge.
71
+ defineIndexes(index_js_1.Notification, {
72
+ od_user_read_createdAt: ["user", "read", "createdAt"],
73
+ }),
74
+ // Open chats poll every 5 s.
75
+ defineIndexes(index_js_1.Chat_Message, {
76
+ od_context_createdAt: ["context", "createdAt"],
77
+ }),
78
+ defineIndexes(index_js_1.Assets, {
79
+ od_context_createdAt: ["context", "createdAt"],
80
+ }),
81
+ // Point lookups — saved views, meta panels, the sync's batch lookup
82
+ // (`entryObjectId $in`), cleanup on delete (without `context`) — and the
83
+ // meta search, which sorts by last change.
84
+ defineIndexes(index_js_1.Meta_Entry, {
85
+ od_entryObjectId_entryClassName_context: [
86
+ "entryObjectId",
87
+ "entryClassName",
88
+ "context",
89
+ ],
90
+ od_context_updatedAt: ["context", "updatedAt"],
91
+ }),
92
+ // Insert-only and never pruned; error banners poll it by type.
93
+ defineIndexes(index_js_1.Log, {
94
+ od_type_createdAt: ["type", "createdAt"],
95
+ }),
96
+ defineIndexes(index_js_1.Core_Token, {
97
+ od_key: ["key"],
98
+ }),
99
+ // The mail log only grows; the contact notification's dedupe looks at a
100
+ // time window of it.
101
+ defineIndexes(index_js_1.Core_Email, {
102
+ od_createdAt: ["createdAt"],
103
+ }),
104
+ // Source sync resolves sources by tag, partly without a tenant.
105
+ defineIndexes(index_js_1.Source, {
106
+ od_tag_tenant: ["tag", "tenant"],
107
+ }),
108
+ // --- open.SERVICE ---
109
+ // The ticket dashboard filters by tenant and sorts by due date by default;
110
+ // its columns and KPIs (one query and count each, on every load) filter by
111
+ // status, equipment (also the header picker), project, priority, assignee,
112
+ // creator and tag. Tickets are written at human pace, so many indexes cost
113
+ // little here.
114
+ defineIndexes(index_js_1.Service_Ticket, {
115
+ od_tenant_deleted_dueDate: ["tenant", "deleted", "dueDate"],
116
+ od_status_dueDate: ["status", "dueDate"],
117
+ od_equipment_dueDate: ["equipment", "dueDate"],
118
+ od_project_dueDate: ["project", "dueDate"],
119
+ od_tenant_priority: ["tenant", "priority"],
120
+ od_assignedUsers: ["assignedUsers"],
121
+ od_createdBy: ["createdBy"],
122
+ od_tags: ["tags"],
123
+ // Tickets of a schedule or alarm, and the alarm webhook's dedupe.
124
+ od_origin_createdAt: ["origin", "createdAt"],
125
+ }),
126
+ // The header equipment picker on every /service route; alarm machine
127
+ // resolution; tag re-parenting.
128
+ defineIndexes(index_js_1.Service_Equipment, {
129
+ od_tenant_deleted_label: ["tenant", "deleted", "label"],
130
+ od_sourceTags: ["sourceTags"],
131
+ od_tags: ["tags"],
132
+ }),
133
+ // The alarm webhook's dedupe.
134
+ defineIndexes(index_js_1.Service_Schedule, {
135
+ od_origin_createdAt: ["origin", "createdAt"],
136
+ }),
137
+ // A plan's history; the overview's look-back over all plans.
138
+ defineIndexes(index_js_1.Service_Schedule_Execution, {
139
+ od_schedule_createdAt: ["schedule", "createdAt"],
140
+ od_tenant_createdAt: ["tenant", "createdAt"],
141
+ }),
142
+ // Materialised by the scheduler every few minutes, per plan.
143
+ defineIndexes(index_js_1.Service_Occurrence, {
144
+ od_schedule_date: ["schedule", "date"],
145
+ }),
146
+ // --- BDE ---
147
+ // The fastest-growing BDE class. Bookings of a work order (QA origin, cards,
148
+ // own bookings) and the active bookings of a machine (every terminal load).
149
+ defineIndexes(index_js_1.BDE_WorkTime, {
150
+ od_workOrder_end: ["workOrder", "end"],
151
+ od_source_end: ["source", "end"],
152
+ }),
153
+ // Lookup by number per QA order and material scan; the ABAS sync's newest
154
+ // work orders of a tenant.
155
+ defineIndexes(index_js_1.BDE_WorkOrder, {
156
+ od_workOrderNr: ["workOrderNr"],
157
+ od_tenant_updatedAt: ["tenant", "updatedAt"],
158
+ }),
159
+ defineIndexes(index_js_1.BDE_Article, {
160
+ od_articleNumber: ["articleNumber"],
161
+ }),
162
+ // --- MES ---
163
+ // A cron job reads the last day's orders every minute.
164
+ defineIndexes(index_js_1.MES_Order, {
165
+ od_start: ["start"],
166
+ }),
167
+ // --- open.SERVICE v1 ---
168
+ // The v1 ticket list loads each ticket's newest row of every side table —
169
+ // about a dozen lookups per ticket and page — and every v1 save reads them
170
+ // too. A ticket has few rows each, so `ticket` alone narrows enough.
171
+ defineIndexes(index_js_1.Maintenance_Downtime, { od_ticket: ["ticket"] }),
172
+ defineIndexes(index_js_1.Maintenance_Duedate, { od_ticket: ["ticket"] }),
173
+ defineIndexes(index_js_1.Maintenance_Frequency, { od_ticket: ["ticket"] }),
174
+ defineIndexes(index_js_1.Maintenance_Priority, { od_ticket: ["ticket"] }),
175
+ defineIndexes(index_js_1.Maintenance_Restriction, { od_ticket: ["ticket"] }),
176
+ defineIndexes(index_js_1.Maintenance_Ticket_Issuecategory, { od_ticket: ["ticket"] }),
177
+ defineIndexes(index_js_1.Maintenance_Ticket_Kanban_State, { od_ticket: ["ticket"] }),
178
+ defineIndexes(index_js_1.Maintenance_Ticket_Kanban_State_Current, {
179
+ od_ticket: ["ticket"],
180
+ }),
181
+ defineIndexes(index_js_1.Maintenance_Ticket_Material, { od_ticket: ["ticket"] }),
182
+ defineIndexes(index_js_1.Maintenance_Ticket_Project, { od_ticket: ["ticket"] }),
183
+ defineIndexes(index_js_1.Maintenance_Ticket_Source, { od_ticket: ["ticket"] }),
184
+ defineIndexes(index_js_1.Maintenance_Ticket_Title, { od_ticket: ["ticket"] }),
185
+ defineIndexes(index_js_1.Maintenance_Message, {
186
+ od_referencedObjectId: ["referencedObjectId"],
187
+ }),
188
+ ];
@@ -0,0 +1,30 @@
1
+ /** A class schema as `Parse.Schema.all()` returns it. */
2
+ interface ClassSchema {
3
+ className: string;
4
+ fields: Record<string, {
5
+ type?: string;
6
+ }>;
7
+ }
8
+ /**
9
+ * Create the indexes declared in `../indexes.ts`, and those of every
10
+ * relation's join table, that are missing.
11
+ *
12
+ * Not through the class schema: the schema tool has no `indexes` support, and
13
+ * Parse's schema API hands index keys to Mongo untranslated — an index on
14
+ * `createdAt` would index a field that does not exist (Mongo stores it as
15
+ * `_created_at`, a pointer as `_p_<field>`). The adapter's `ensureIndex` does
16
+ * that translation.
17
+ *
18
+ * Idempotent: Mongo ignores a `createIndex` for an index that already exists
19
+ * with the same keys and name. Changing the fields of an existing index under
20
+ * the same name fails (and is logged) — give it a new name instead, and drop
21
+ * the old one by hand. Indexes are never dropped here.
22
+ *
23
+ * Classes missing from `schemas` are skipped: their feature is disabled on this
24
+ * server (see `featuremap.json`), so the schema upload did not create them.
25
+ *
26
+ * Building an index on a large collection takes a while, so the caller should
27
+ * not wait for it. Never throws.
28
+ */
29
+ export declare function ensureIndexes(schemas: ClassSchema[]): Promise<void>;
30
+ export {};
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ensureIndexes = ensureIndexes;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const indexes_js_1 = require("../indexes.js");
9
+ const LOG_PREFIX = "[@openinc/parse-server-opendash]";
10
+ /**
11
+ * Indexes of a relation's join table `_Join:<field>:<class>`, for which Parse
12
+ * creates none. Reading a relation (`relation.query()`) looks rows up by
13
+ * `owningId`, a query on the relation field (`equalTo("users", user)` — how
14
+ * Parse resolves a user's roles on every request) by `relatedId`, and
15
+ * `relation.add` upserts on both.
16
+ */
17
+ const JOIN_INDEXES = {
18
+ od_join_owning: ["owningId", "relatedId"],
19
+ od_join_related: ["relatedId", "owningId"],
20
+ };
21
+ const JOIN_FIELDS = {
22
+ owningId: { type: "String" },
23
+ relatedId: { type: "String" },
24
+ };
25
+ /**
26
+ * The storage adapter of the running Parse Server, or `undefined` when it is
27
+ * out of reach — a second copy of `parse-server` (whose config cache is empty)
28
+ * or an adapter without `ensureIndex`.
29
+ */
30
+ function storageAdapter() {
31
+ try {
32
+ const Config = require("parse-server/lib/Config");
33
+ const adapter = Config.get(node_1.default.applicationId)?.database?.adapter;
34
+ return typeof adapter?.ensureIndex === "function" ? adapter : undefined;
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ /**
41
+ * Why `fields` cannot be indexed on `schema`, or `undefined` if they can.
42
+ *
43
+ * A field missing from the schema would give an index Mongo happily builds on
44
+ * a column nobody writes. Two array fields in one index are worse: Mongo
45
+ * builds it, then refuses every save of a row that has both arrays set
46
+ * ("cannot index parallel arrays").
47
+ */
48
+ function invalidReason(schema, fields) {
49
+ const missing = fields.filter((field) => !schema.fields[field]);
50
+ if (missing.length > 0) {
51
+ return `unknown field(s) ${missing.join(", ")}`;
52
+ }
53
+ const arrays = fields.filter((field) => schema.fields[field].type === "Array");
54
+ if (arrays.length > 1) {
55
+ return `more than one array field (${arrays.join(", ")})`;
56
+ }
57
+ return undefined;
58
+ }
59
+ /**
60
+ * The join tables of `schemas`' relation fields that exist. One that does not
61
+ * has never been written to, so there is nothing to speed up yet — creating
62
+ * its index would only create an empty collection. It gets its index on the
63
+ * first start after a relation was added.
64
+ */
65
+ async function existingJoinTables(adapter, schemas) {
66
+ if (typeof adapter.classExists !== "function")
67
+ return [];
68
+ const tables = schemas.flatMap(({ className, fields }) => Object.entries(fields)
69
+ .filter(([, field]) => field.type === "Relation")
70
+ .map(([name]) => `_Join:${name}:${className}`));
71
+ const exists = await Promise.all(tables.map((table) => adapter.classExists(table).catch(() => false)));
72
+ return tables.filter((_, i) => exists[i]);
73
+ }
74
+ /**
75
+ * Create the indexes declared in `../indexes.ts`, and those of every
76
+ * relation's join table, that are missing.
77
+ *
78
+ * Not through the class schema: the schema tool has no `indexes` support, and
79
+ * Parse's schema API hands index keys to Mongo untranslated — an index on
80
+ * `createdAt` would index a field that does not exist (Mongo stores it as
81
+ * `_created_at`, a pointer as `_p_<field>`). The adapter's `ensureIndex` does
82
+ * that translation.
83
+ *
84
+ * Idempotent: Mongo ignores a `createIndex` for an index that already exists
85
+ * with the same keys and name. Changing the fields of an existing index under
86
+ * the same name fails (and is logged) — give it a new name instead, and drop
87
+ * the old one by hand. Indexes are never dropped here.
88
+ *
89
+ * Classes missing from `schemas` are skipped: their feature is disabled on this
90
+ * server (see `featuremap.json`), so the schema upload did not create them.
91
+ *
92
+ * Building an index on a large collection takes a while, so the caller should
93
+ * not wait for it. Never throws.
94
+ */
95
+ async function ensureIndexes(schemas) {
96
+ const adapter = storageAdapter();
97
+ if (!adapter) {
98
+ console.warn(`${LOG_PREFIX} Cannot reach the storage adapter — indexes are not ensured.`);
99
+ return;
100
+ }
101
+ const schemaByClass = new Map(schemas.map((s) => [s.className, s]));
102
+ const failed = [];
103
+ let ensured = 0;
104
+ const ensure = async (schema, name, fields) => {
105
+ const reason = invalidReason(schema, fields);
106
+ if (reason) {
107
+ console.warn(`${LOG_PREFIX} Skipping index ${name} on ${schema.className}: ${reason}`);
108
+ failed.push(`${schema.className}.${name}`);
109
+ return;
110
+ }
111
+ try {
112
+ // `ensureIndex` strips `_rperm`/`_wperm` from the schema's fields in
113
+ // place, hence the copy. Not sparse (the adapter's default): Mongo will
114
+ // not use a sparse index to sort, nor for `doesNotExist`, as either has
115
+ // to see the rows that lack the field.
116
+ await adapter.ensureIndex(schema.className, { className: schema.className, fields: { ...schema.fields } }, fields, name, false, { sparse: false });
117
+ ensured++;
118
+ }
119
+ catch (error) {
120
+ console.warn(`${LOG_PREFIX} Could not ensure index ${name} on ${schema.className}:`, error?.message ?? error);
121
+ failed.push(`${schema.className}.${name}`);
122
+ }
123
+ };
124
+ try {
125
+ for (const { className, indexes } of indexes_js_1.INDEXES) {
126
+ const schema = schemaByClass.get(className);
127
+ if (!schema)
128
+ continue;
129
+ for (const [name, fields] of Object.entries(indexes)) {
130
+ await ensure(schema, name, fields);
131
+ }
132
+ }
133
+ for (const table of await existingJoinTables(adapter, schemas)) {
134
+ for (const [name, fields] of Object.entries(JOIN_INDEXES)) {
135
+ await ensure({ className: table, fields: JOIN_FIELDS }, name, fields);
136
+ }
137
+ }
138
+ }
139
+ catch (error) {
140
+ console.warn(`${LOG_PREFIX} Ensuring indexes stopped:`, error);
141
+ }
142
+ console.log(`${LOG_PREFIX} Indexes ensured: ${ensured}` +
143
+ (failed.length > 0 ? `, failed: ${failed.join(", ")}` : ""));
144
+ }
@@ -10,6 +10,7 @@ const path_1 = require("path");
10
10
  const index_js_1 = require("../../config/index.js");
11
11
  const SchemaClass_js_1 = require("../classes/SchemaClass.js");
12
12
  const isClassEnabled_js_1 = require("../helper/isClassEnabled.js");
13
+ const ensureIndexes_js_1 = require("./ensureIndexes.js");
13
14
  const PREFIX = "OD3_";
14
15
  const LOG_PREFIX = "[@openinc/parse-server-opendash]";
15
16
  const schemaHandler = SchemaClass_js_1.SchemaClass.getInstance();
@@ -30,13 +31,12 @@ async function initSchema() {
30
31
  console.error(error);
31
32
  process.exit(1);
32
33
  }
34
+ let schemas;
33
35
  // Unlike the upload above, which sends its own master key header, this goes
34
36
  // through the Parse SDK and relies on Parse Server having initialized it.
35
37
  try {
36
- schemaHandler.setSchema(Object.fromEntries((await node_1.default.Schema.all()).map((schema) => [
37
- schema.className,
38
- schema,
39
- ])));
38
+ schemas = await node_1.default.Schema.all();
39
+ schemaHandler.setSchema(Object.fromEntries(schemas.map((schema) => [schema.className, schema])));
40
40
  }
41
41
  catch (error) {
42
42
  console.error(`${LOG_PREFIX} Error while loading schema via Parse SDK`);
@@ -44,6 +44,9 @@ async function initSchema() {
44
44
  console.error(error);
45
45
  process.exit(1);
46
46
  }
47
+ // Index building on a large collection takes a while; the server does not
48
+ // have to wait for it.
49
+ void (0, ensureIndexes_js_1.ensureIndexes)(schemas);
47
50
  }
48
51
  /**
49
52
  * Logs which Parse SDK this package talks to. If it is not the instance Parse
@@ -23,9 +23,6 @@ async function init() {
23
23
  .filter((c) => c.length > 0),
24
24
  ];
25
25
  console.log(`ChangeLog blacklisted classes: ${blacklistedClasses.join(", ") || "None"}`);
26
- // Index building on a large collection takes a while; the server does not
27
- // have to wait for it.
28
- void (0, index_js_2.ensureChangelogIndexes)(schema.find((s) => s.className === index_js_4.Changelog.className));
29
26
  (0, index_js_1.beforeSaveHook)(index_js_4.Changelog.className, async (request) => {
30
27
  const { object, user, original } = request;
31
28
  await (0, index_js_1.defaultHandler)(request);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openinc/parse-server-opendash",
3
- "version": "4.18.0",
3
+ "version": "4.19.0",
4
4
  "description": "Parse Server Cloud Code for open.INC Stack.",
5
5
  "packageManager": "pnpm@12.8.1",
6
6
  "keywords": [
@@ -1,17 +0,0 @@
1
- /**
2
- * Create the changelog indexes if they are missing.
3
- *
4
- * Not through the class schema: the schema tool has no `indexes` support, and
5
- * Parse's schema API hands index keys to Mongo untranslated — an index on
6
- * `createdAt` would index a field that does not exist (Mongo stores it as
7
- * `_created_at`, a pointer as `_p_<field>`). The adapter's `ensureIndex` does
8
- * that translation.
9
- *
10
- * Idempotent: Mongo ignores a `createIndex` for an index that already exists
11
- * with the same keys and name. Building them on a large collection takes a
12
- * while, so the caller should not wait for it.
13
- */
14
- export declare function ensureChangelogIndexes(schema: {
15
- className: string;
16
- fields: Record<string, unknown>;
17
- } | undefined): Promise<void>;
@@ -1,78 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.ensureChangelogIndexes = ensureChangelogIndexes;
7
- const node_1 = __importDefault(require("parse/node"));
8
- const index_js_1 = require("../../../types/index.js");
9
- const LOG_PREFIX = "[@openinc/parse-server-opendash]";
10
- /**
11
- * Indexes of `OD3_Changelog`, by name. Every changelog query sorts newest
12
- * first, so each filter is paired with `createdAt` — Mongo then walks the index
13
- * backwards and stops at the page size instead of sorting every match in
14
- * memory. `searchText` gets none: a substring regex cannot use one, it is
15
- * evaluated on the rows the other filters (class, date range) narrowed down.
16
- */
17
- const INDEXES = {
18
- od_changelog_created: ["createdAt"],
19
- od_changelog_class_created: ["nameOfClass", "createdAt"],
20
- od_changelog_object_created: ["changedObject", "createdAt"],
21
- od_changelog_user_created: ["actingUser", "createdAt"],
22
- od_changelog_fields_created: ["changedFields", "createdAt"],
23
- od_changelog_refs_created: ["refs", "createdAt"],
24
- };
25
- /**
26
- * The storage adapter of the running Parse Server, or `undefined` when it is
27
- * out of reach — a second copy of `parse-server` (whose config cache is empty)
28
- * or an adapter without `ensureIndex`.
29
- */
30
- function storageAdapter() {
31
- try {
32
- const Config = require("parse-server/lib/Config");
33
- const adapter = Config.get(node_1.default.applicationId)?.database?.adapter;
34
- return typeof adapter?.ensureIndex === "function" ? adapter : undefined;
35
- }
36
- catch {
37
- return undefined;
38
- }
39
- }
40
- /**
41
- * Create the changelog indexes if they are missing.
42
- *
43
- * Not through the class schema: the schema tool has no `indexes` support, and
44
- * Parse's schema API hands index keys to Mongo untranslated — an index on
45
- * `createdAt` would index a field that does not exist (Mongo stores it as
46
- * `_created_at`, a pointer as `_p_<field>`). The adapter's `ensureIndex` does
47
- * that translation.
48
- *
49
- * Idempotent: Mongo ignores a `createIndex` for an index that already exists
50
- * with the same keys and name. Building them on a large collection takes a
51
- * while, so the caller should not wait for it.
52
- */
53
- async function ensureChangelogIndexes(schema) {
54
- const adapter = storageAdapter();
55
- if (!adapter || !schema) {
56
- console.warn(`${LOG_PREFIX} Cannot reach the storage adapter — ${index_js_1.Changelog.className} ` +
57
- `indexes are not ensured. Create them by hand: ` +
58
- Object.values(INDEXES)
59
- .map((fields) => `{ ${fields.join(", ")} }`)
60
- .join(", "));
61
- return;
62
- }
63
- const ensured = [];
64
- for (const [name, fields] of Object.entries(INDEXES)) {
65
- try {
66
- // `ensureIndex` strips `_rperm`/`_wperm` from the schema's fields in
67
- // place, hence the copy. Not sparse: Mongo would refuse a sparse index
68
- // for a sort over all entries, the admin table's default view.
69
- await adapter.ensureIndex(index_js_1.Changelog.className, { className: schema.className, fields: { ...schema.fields } }, fields, name, false, { sparse: false });
70
- ensured.push(name);
71
- }
72
- catch (error) {
73
- console.warn(`${LOG_PREFIX} Could not ensure index ${name} on ${index_js_1.Changelog.className}:`, error?.message ?? error);
74
- }
75
- }
76
- console.log(`${LOG_PREFIX} ${index_js_1.Changelog.className} indexes ensured: ` +
77
- (ensured.join(", ") || "none"));
78
- }