@openinc/parse-server-opendash 4.17.1 → 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.
@@ -0,0 +1 @@
1
+ export { deriveSearchFields, type ChangelogSearchFields, } from "./services/deriveSearchFields.js";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deriveSearchFields = void 0;
4
+ var deriveSearchFields_js_1 = require("./services/deriveSearchFields.js");
5
+ Object.defineProperty(exports, "deriveSearchFields", { enumerable: true, get: function () { return deriveSearchFields_js_1.deriveSearchFields; } });
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The search fields of an `OD3_Changelog` entry, derived from its snapshots.
3
+ *
4
+ * The snapshots (`original` / `value`) are whole `toJSON()` dumps stored as
5
+ * Object fields — Parse can neither say which fields differ between them nor
6
+ * search text inside them. These three columns make an entry findable by what
7
+ * a person actually asks:
8
+ *
9
+ * - "who changed the status?" → `changedFields`
10
+ * - "what happened to equipment X / when was it set to *done*?" → `refs`
11
+ * - "what happened to *Pumpe 3* / ticket 4711?" → `searchText`
12
+ */
13
+ export interface ChangelogSearchFields {
14
+ /**
15
+ * Top-level fields whose value differs between `original` and `value`. A
16
+ * create lists every field it set, a delete every field the object had.
17
+ */
18
+ changedFields: string[];
19
+ /**
20
+ * Every pointer in either snapshot, as `field:objectId` (arrays of pointers
21
+ * contribute one per element). Both snapshots, so an entry that moved a
22
+ * ticket from one machine to another belongs to both machines.
23
+ */
24
+ refs: string[];
25
+ /**
26
+ * The text and number values of both snapshots, lower-cased and
27
+ * whitespace-normalised, for a case-insensitive substring search. One value
28
+ * per line, so a phrase cannot match across two fields.
29
+ */
30
+ searchText: string;
31
+ }
32
+ type Snapshot = Record<string, unknown> | null | undefined;
33
+ /**
34
+ * Derive the search fields of a changelog entry from its snapshots. Pure and
35
+ * deterministic, so the beforeSave hook and the backfill produce the same
36
+ * result for the same entry.
37
+ */
38
+ export declare function deriveSearchFields(original: Snapshot, value: Snapshot): ChangelogSearchFields;
39
+ export {};
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deriveSearchFields = deriveSearchFields;
4
+ const fast_equals_1 = require("fast-equals");
5
+ /** Bookkeeping Parse adds to every object — never a change anyone made. */
6
+ const TECHNICAL_FIELDS = new Set(["objectId", "createdAt", "updatedAt", "ACL"]);
7
+ /** Credentials a `_User` snapshot can carry; they stay out of the search text. */
8
+ const SECRET_FIELDS = new Set(["sessionToken", "authData"]);
9
+ /**
10
+ * Upper bound for `searchText`. Values are joined shortest first, so a long
11
+ * description or an embedded JSON blob is what gets cut — never the name,
12
+ * number or title next to it.
13
+ */
14
+ const MAX_SEARCH_TEXT_LENGTH = 10_000;
15
+ /** Nesting depth followed into JSON fields, for both comparison and text. */
16
+ const MAX_DEPTH = 5;
17
+ /**
18
+ * The objectId of a reference, in either shape it reaches us: wire JSON
19
+ * (`{__type: "Pointer" | "Object"}`, as `toJSON()` wrote it) or a decoded
20
+ * `Parse.Object` (the SDK decodes nested pointers when it reads an Object
21
+ * field). Duck-typed rather than `instanceof`, so a second copy of the SDK does
22
+ * not make every pointer invisible.
23
+ */
24
+ function pointerId(value) {
25
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
26
+ return undefined;
27
+ }
28
+ const v = value;
29
+ if (typeof v.toPointer === "function" && typeof v.id === "string") {
30
+ return v.id;
31
+ }
32
+ if ((v.__type === "Pointer" || v.__type === "Object") &&
33
+ typeof v.objectId === "string") {
34
+ return v.objectId;
35
+ }
36
+ return undefined;
37
+ }
38
+ function isPlainObject(value) {
39
+ if (typeof value !== "object" || value === null)
40
+ return false;
41
+ const proto = Object.getPrototypeOf(value);
42
+ return proto === Object.prototype || proto === null;
43
+ }
44
+ /**
45
+ * A value as it should be compared: references reduced to their identity. An
46
+ * included object's other fields are not part of this record, and two decoded
47
+ * `Parse.Object`s of the same pointer differ in internal counters.
48
+ */
49
+ function comparable(value, depth = 0) {
50
+ const id = pointerId(value);
51
+ if (id !== undefined)
52
+ return { objectId: id };
53
+ if (depth >= MAX_DEPTH)
54
+ return value;
55
+ if (Array.isArray(value)) {
56
+ return value.map((item) => comparable(item, depth + 1));
57
+ }
58
+ if (isPlainObject(value)) {
59
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
60
+ key,
61
+ comparable(item, depth + 1),
62
+ ]));
63
+ }
64
+ return value;
65
+ }
66
+ function isEmpty(value) {
67
+ return value === null || value === undefined;
68
+ }
69
+ function sameValue(before, after) {
70
+ // `null` and absent both mean "not set" — clearing a field that was never
71
+ // set is no change.
72
+ if (isEmpty(before) && isEmpty(after))
73
+ return true;
74
+ return (0, fast_equals_1.deepEqual)(comparable(before), comparable(after));
75
+ }
76
+ function changedFieldsOf(original, value) {
77
+ const keys = new Set([
78
+ ...Object.keys(original ?? {}),
79
+ ...Object.keys(value ?? {}),
80
+ ]);
81
+ return [...keys]
82
+ .filter((key) => !TECHNICAL_FIELDS.has(key))
83
+ .filter((key) => !sameValue(original?.[key], value?.[key]))
84
+ .sort();
85
+ }
86
+ function refsOf(snapshots) {
87
+ const refs = new Set();
88
+ for (const snapshot of snapshots) {
89
+ for (const [key, value] of Object.entries(snapshot ?? {})) {
90
+ if (TECHNICAL_FIELDS.has(key))
91
+ continue;
92
+ for (const item of Array.isArray(value) ? value : [value]) {
93
+ const id = pointerId(item);
94
+ if (id !== undefined)
95
+ refs.add(`${key}:${id}`);
96
+ }
97
+ }
98
+ }
99
+ return [...refs].sort();
100
+ }
101
+ function normalizeText(text) {
102
+ return text.replace(/\s+/g, " ").trim().toLowerCase();
103
+ }
104
+ /** The name of a file, as wire JSON or as a decoded `Parse.File`. */
105
+ function fileNameOf(value) {
106
+ if (value.__type === "File" && typeof value.name === "string") {
107
+ return value.name;
108
+ }
109
+ if (typeof value.name === "function" && typeof value.url === "function") {
110
+ const name = value.name();
111
+ return typeof name === "string" ? name : undefined;
112
+ }
113
+ return undefined;
114
+ }
115
+ function collectText(value, out, depth) {
116
+ if (isEmpty(value) || depth > MAX_DEPTH)
117
+ return;
118
+ if (typeof value === "string") {
119
+ const text = normalizeText(value);
120
+ if (text)
121
+ out.add(text);
122
+ return;
123
+ }
124
+ if (typeof value === "number") {
125
+ if (Number.isFinite(value))
126
+ out.add(String(value));
127
+ return;
128
+ }
129
+ if (Array.isArray(value)) {
130
+ for (const item of value)
131
+ collectText(item, out, depth + 1);
132
+ return;
133
+ }
134
+ if (typeof value !== "object")
135
+ return;
136
+ const v = value;
137
+ const fileName = fileNameOf(v);
138
+ if (fileName) {
139
+ collectText(fileName, out, depth);
140
+ return;
141
+ }
142
+ // References, dates, geo points, … carry ids and coordinates, not words. Their
143
+ // wire form is a plain object too, so it has to be caught by `__type` before
144
+ // the generic walk below would index `className` and `objectId`.
145
+ if (typeof v.__type === "string" || !isPlainObject(v))
146
+ return;
147
+ for (const item of Object.values(v))
148
+ collectText(item, out, depth + 1);
149
+ }
150
+ function searchTextOf(snapshots) {
151
+ const values = new Set();
152
+ for (const snapshot of snapshots) {
153
+ for (const [key, value] of Object.entries(snapshot ?? {})) {
154
+ if (TECHNICAL_FIELDS.has(key) || SECRET_FIELDS.has(key))
155
+ continue;
156
+ collectText(value, values, 1);
157
+ }
158
+ }
159
+ return [...values]
160
+ .sort((a, b) => a.length - b.length)
161
+ .join("\n")
162
+ .slice(0, MAX_SEARCH_TEXT_LENGTH);
163
+ }
164
+ /**
165
+ * Derive the search fields of a changelog entry from its snapshots. Pure and
166
+ * deterministic, so the beforeSave hook and the backfill produce the same
167
+ * result for the same entry.
168
+ */
169
+ function deriveSearchFields(original, value) {
170
+ const snapshots = [original, value];
171
+ return {
172
+ changedFields: changedFieldsOf(original, value),
173
+ refs: refsOf(snapshots),
174
+ searchText: searchTextOf(snapshots),
175
+ };
176
+ }
@@ -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
@@ -7,11 +7,12 @@ exports.init = init;
7
7
  const node_1 = __importDefault(require("parse/node"));
8
8
  const AMQPBusConnection_js_1 = require("../features/openware/services/AMQPBusConnection.js");
9
9
  const index_js_1 = require("../features/schema/index.js");
10
- const index_js_2 = require("../features/config/index.js");
11
- const index_js_3 = require("../types/index.js");
10
+ const index_js_2 = require("../features/changelog/index.js");
11
+ const index_js_3 = require("../features/config/index.js");
12
+ const index_js_4 = require("../types/index.js");
12
13
  async function init() {
13
14
  const schema = await node_1.default.Schema.all();
14
- const config = index_js_2.ConfigInstance.getInstance();
15
+ const config = index_js_3.ConfigInstance.getInstance();
15
16
  console.log(`ChangeLog publishing enabled: ${config.getBoolean("CHANGELOG_PUBLISH_ENABLE")}`);
16
17
  const blacklistedClasses = [
17
18
  "_Session",
@@ -22,9 +23,21 @@ async function init() {
22
23
  .filter((c) => c.length > 0),
23
24
  ];
24
25
  console.log(`ChangeLog blacklisted classes: ${blacklistedClasses.join(", ") || "None"}`);
25
- (0, index_js_1.beforeSaveHook)(index_js_3.Changelog.className, async (request) => {
26
- const { object, user } = request;
26
+ (0, index_js_1.beforeSaveHook)(index_js_4.Changelog.className, async (request) => {
27
+ const { object, user, original } = request;
27
28
  await (0, index_js_1.defaultHandler)(request);
29
+ // Re-derived on every save, so they always match the snapshots and cannot
30
+ // be set by hand. See features/changelog/services/deriveSearchFields.ts.
31
+ const search = (0, index_js_2.deriveSearchFields)(object.get("original"), object.get("value"));
32
+ object.set("changedFields", search.changedFields);
33
+ object.set("refs", search.refs);
34
+ object.set("searchText", search.searchText);
35
+ // The ACL is settled when the entry is written. A later save — the search
36
+ // backfill, an admin edit — must not re-derive it: entries from before the
37
+ // mirroring below were locked to od-admin, and re-mirroring would quietly
38
+ // widen who can read them.
39
+ if (original)
40
+ return;
28
41
  // Mirror the ACL of the changed object instead of locking the changelog to
29
42
  // the od-admin role: whoever can see the underlying object can see its
30
43
  // history. The object snapshot lives in `value` for create/update and in
@@ -62,8 +75,12 @@ async function init() {
62
75
  console.log(`Establishing Connection to ${url} for ChangeLog publishing...`);
63
76
  await connection.connect();
64
77
  console.log(`Connected to AMQPBus at ${url} for ChangeLog publishing.`);
65
- (0, index_js_1.afterSaveHook)(index_js_3.Changelog.className, async (request) => {
66
- const { object: changelog } = request;
78
+ (0, index_js_1.afterSaveHook)(index_js_4.Changelog.className, async (request) => {
79
+ const { object: changelog, original } = request;
80
+ // Only a new entry reports a change. Saving an existing one again (the
81
+ // search backfill) would otherwise replay the whole history on the bus.
82
+ if (original)
83
+ return;
67
84
  const msg = JSON.stringify(changelog.toJSON());
68
85
  const topic = `${params.topicPrefix && params.topicPrefix.length > 0
69
86
  ? params.topicPrefix + "."
@@ -78,8 +95,8 @@ async function init() {
78
95
  }
79
96
  schema.forEach((classSchema) => {
80
97
  if (!classSchema.className ||
81
- classSchema.className === index_js_3.Changelog.className ||
82
- classSchema.className === index_js_3.Permission.className) {
98
+ classSchema.className === index_js_4.Changelog.className ||
99
+ classSchema.className === index_js_4.Permission.className) {
83
100
  console.log(`Skipping ChangeLog hook for class ${classSchema.className}`);
84
101
  return;
85
102
  }
@@ -103,7 +120,7 @@ async function init() {
103
120
  console.log(`Skipping ChangeLog entry for class ${classSchema.className} and object ${object.id} due to ${context?.skipChangelog ? "context flag" : "blacklisted class"}.`);
104
121
  return;
105
122
  }
106
- const changelog = new index_js_3.Changelog();
123
+ const changelog = new index_js_4.Changelog();
107
124
  changelog.set("nameOfClass", classSchema.className);
108
125
  changelog.set("changedObject", object.id);
109
126
  changelog.set("operation", "delete");
@@ -131,7 +148,7 @@ async function init() {
131
148
  console.log(`Skipping ChangeLog entry for class ${classSchema.className} and object ${object.id} due to ${context.skipChangelog ? "context flag" : "blacklisted class"}.`);
132
149
  return;
133
150
  }
134
- const changelog = new index_js_3.Changelog();
151
+ const changelog = new index_js_4.Changelog();
135
152
  changelog.set("nameOfClass", classSchema.className);
136
153
  changelog.set("changedObject", object.id);
137
154
  changelog.set("operation", original ? "update" : "create");
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,112 @@
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
+ const fast_equals_1 = require("fast-equals");
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const index_js_1 = require("../features/changelog/index.js");
9
+ const index_js_2 = require("../types/index.js");
10
+ /**
11
+ * One-off backfill for the search fields of `OD3_Changelog` (`changedFields`,
12
+ * `refs`, `searchText`).
13
+ *
14
+ * From here on `beforeSave(OD3_Changelog)` derives them for every new entry,
15
+ * but everything already in the database predates that — and so does every
16
+ * entry the v1 migration writes, because migration mode registers no
17
+ * beforeSave at all. Until this ran, those entries are invisible to the search
18
+ * and the field filter (`references` sources still find them client-side).
19
+ *
20
+ * PARSE_URL=… PARSE_APP_ID=… PARSE_MASTER_KEY=… \
21
+ * node dist/scripts/backfill-changelog-search.js [--dry-run]
22
+ *
23
+ * Safe to re-run: an entry is only saved when its stored fields differ from
24
+ * what its snapshots derive to — which also makes this the way to bring old
25
+ * entries up to date after the derivation changed. The save itself leaves the
26
+ * entry's ACL alone and publishes nothing; both only happen for new entries.
27
+ */
28
+ const BATCH_SIZE = 500;
29
+ function requireEnv(name) {
30
+ const value = process.env[name];
31
+ if (!value) {
32
+ console.error(`Missing required environment variable ${name}.`);
33
+ process.exit(1);
34
+ }
35
+ return value;
36
+ }
37
+ /**
38
+ * Iterate the changelog in `(createdAt, objectId)` order, page by page. The
39
+ * objectId breaks ties: entries can share a timestamp (the migration writes
40
+ * reconstructed history with historical ones), and a cursor on `createdAt`
41
+ * alone would skip whatever shares the last timestamp of a page.
42
+ */
43
+ async function* pages() {
44
+ let cursor;
45
+ for (;;) {
46
+ let query = new node_1.default.Query(index_js_2.Changelog);
47
+ if (cursor) {
48
+ query = node_1.default.Query.or(new node_1.default.Query(index_js_2.Changelog).greaterThan("createdAt", cursor.createdAt), new node_1.default.Query(index_js_2.Changelog)
49
+ .equalTo("createdAt", cursor.createdAt)
50
+ .greaterThan("objectId", cursor.id));
51
+ }
52
+ const results = await query
53
+ .ascending("createdAt")
54
+ .addAscending("objectId")
55
+ .limit(BATCH_SIZE)
56
+ .find({ useMasterKey: true });
57
+ if (results.length === 0)
58
+ return;
59
+ yield results;
60
+ // Fetched rows always carry both; the SDK types them optional for unsaved ones.
61
+ const last = results[results.length - 1];
62
+ cursor = { createdAt: last.createdAt, id: last.id };
63
+ if (results.length < BATCH_SIZE)
64
+ return;
65
+ }
66
+ }
67
+ async function main() {
68
+ const dryRun = process.argv.includes("--dry-run");
69
+ node_1.default.initialize(requireEnv("PARSE_APP_ID"), undefined, requireEnv("PARSE_MASTER_KEY"));
70
+ node_1.default.serverURL =
71
+ process.env.PARSE_URL ?? "http://localhost:1337/parse";
72
+ let scanned = 0;
73
+ let updated = 0;
74
+ let failed = 0;
75
+ for await (const page of pages()) {
76
+ const stale = [];
77
+ for (const entry of page) {
78
+ scanned++;
79
+ const fields = (0, index_js_1.deriveSearchFields)(entry.original, entry.value);
80
+ const current = {
81
+ changedFields: entry.changedFields,
82
+ refs: entry.refs,
83
+ searchText: entry.searchText,
84
+ };
85
+ if ((0, fast_equals_1.deepEqual)(current, fields))
86
+ continue;
87
+ entry.changedFields = fields.changedFields;
88
+ entry.refs = fields.refs;
89
+ entry.searchText = fields.searchText;
90
+ stale.push(entry);
91
+ }
92
+ if (!dryRun && stale.length > 0) {
93
+ try {
94
+ await node_1.default.Object.saveAll(stale, { useMasterKey: true });
95
+ }
96
+ catch (error) {
97
+ failed += stale.length;
98
+ console.error(`Saving ${stale.length} entries failed (${stale[0].id} … ${stale[stale.length - 1].id}):`, error?.message ?? error);
99
+ continue;
100
+ }
101
+ }
102
+ updated += stale.length;
103
+ console.log(`${dryRun ? "[dry run] " : ""}${scanned} scanned, ${updated} ${dryRun ? "to update" : "updated"}`);
104
+ }
105
+ console.log(`${dryRun ? "[dry run] " : ""}done: ${scanned} scanned, ${updated} ${dryRun ? "to update" : "updated"}, ${failed} failed`);
106
+ if (failed > 0)
107
+ process.exit(1);
108
+ }
109
+ main().catch((error) => {
110
+ console.error(error);
111
+ process.exit(1);
112
+ });
@@ -6,12 +6,15 @@ export interface ChangelogAttributes {
6
6
  createdAt: Date;
7
7
  updatedAt: Date;
8
8
  actingUser?: _User | undefined;
9
+ changedFields?: any[] | undefined;
9
10
  changedObject: string;
10
11
  context?: any | undefined;
11
12
  masterkey: boolean;
12
13
  nameOfClass: string;
13
14
  operation: string;
14
15
  original?: any | undefined;
16
+ refs?: any[] | undefined;
17
+ searchText?: string | undefined;
15
18
  value?: any | undefined;
16
19
  }
17
20
  export declare class Changelog extends Parse.Object<ChangelogAttributes> {
@@ -19,6 +22,8 @@ export declare class Changelog extends Parse.Object<ChangelogAttributes> {
19
22
  constructor(data?: Partial<ChangelogAttributes>);
20
23
  get actingUser(): _User | undefined;
21
24
  set actingUser(value: _User | undefined);
25
+ get changedFields(): any[] | undefined;
26
+ set changedFields(value: any[] | undefined);
22
27
  get changedObject(): string;
23
28
  set changedObject(value: string);
24
29
  get context(): any | undefined;
@@ -31,6 +36,10 @@ export declare class Changelog extends Parse.Object<ChangelogAttributes> {
31
36
  set operation(value: string);
32
37
  get original(): any | undefined;
33
38
  set original(value: any | undefined);
39
+ get refs(): any[] | undefined;
40
+ set refs(value: any[] | undefined);
41
+ get searchText(): string | undefined;
42
+ set searchText(value: string | undefined);
34
43
  get value(): any | undefined;
35
44
  set value(value: any | undefined);
36
45
  }
@@ -16,6 +16,12 @@ class Changelog extends node_1.default.Object {
16
16
  set actingUser(value) {
17
17
  super.set("actingUser", value);
18
18
  }
19
+ get changedFields() {
20
+ return super.get("changedFields");
21
+ }
22
+ set changedFields(value) {
23
+ super.set("changedFields", value);
24
+ }
19
25
  get changedObject() {
20
26
  return super.get("changedObject");
21
27
  }
@@ -52,6 +58,18 @@ class Changelog extends node_1.default.Object {
52
58
  set original(value) {
53
59
  super.set("original", value);
54
60
  }
61
+ get refs() {
62
+ return super.get("refs");
63
+ }
64
+ set refs(value) {
65
+ super.set("refs", value);
66
+ }
67
+ get searchText() {
68
+ return super.get("searchText");
69
+ }
70
+ set searchText(value) {
71
+ super.set("searchText", value);
72
+ }
55
73
  get value() {
56
74
  return super.get("value");
57
75
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openinc/parse-server-opendash",
3
- "version": "4.17.1",
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": [
@@ -66,6 +66,7 @@
66
66
  "migrate": "node dist/scripts/migration/run.js",
67
67
  "migrate:verify": "node dist/scripts/migration/verify.js",
68
68
  "backfill:meta-contexts": "node dist/scripts/backfill-meta-contexts.js",
69
+ "backfill:changelog-search": "node dist/scripts/backfill-changelog-search.js",
69
70
  "seed:v1": "node dist/scripts/seed-v1-testdata.js"
70
71
  },
71
72
  "dependencies": {
@@ -5,6 +5,10 @@
5
5
  "targetClass": "_User",
6
6
  "required": false
7
7
  },
8
+ "changedFields": {
9
+ "type": "Array",
10
+ "required": false
11
+ },
8
12
  "changedObject": {
9
13
  "type": "String",
10
14
  "required": true
@@ -30,6 +34,14 @@
30
34
  "type": "Object",
31
35
  "required": false
32
36
  },
37
+ "refs": {
38
+ "type": "Array",
39
+ "required": false
40
+ },
41
+ "searchText": {
42
+ "type": "String",
43
+ "required": false
44
+ },
33
45
  "value": {
34
46
  "type": "Object",
35
47
  "required": false