-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.js
353 lines (334 loc) · 10.3 KB
/
engine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// noinspection JSUnusedGlobalSymbols
/**
* @typedef {import("./pkg/meilisearch")} wasm
* @typedef {wasm.WikiSearchEngine} WikiSearchEngine
*/
/**
* Represents a wiki page with various properties.
*
* @typedef {Object} WikiPage
* @property {number} id - The unique identifier of the wiki page.
* @property {string} path - The path or URL of the wiki page.
* @property {string} hash - The hash value associated with the wiki page.
* @property {string} title - The title of the wiki page.
* @property {string} description - The description of the wiki page.
* @property {boolean} isPrivate - Indicates whether the wiki page is private or not.
* @property {boolean} isPublished - Indicates whether the wiki page is published or not.
* @property {string} content - The content of the wiki page.
* @property {string} contentType - The content type of the wiki page.
* @property {string} createdAt - The date and time when the wiki page was created.
* @property {string} updatedAt - The date and time when the wiki page was last updated.
* @property {string} editorKey - The key associated with the editor of the wiki page.
* @property {string} localeCode - The locale code of the wiki page.
* @property {number} authorId - The unique identifier of the wiki page author.
* @property {number} creatorId - The unique identifier of the wiki page creator.
*/
/**
* @type {wasm}
*/
const wasm = require("./meilisearch.js");
/**
* @type {WikiSearchEngine}
*/
let searchEngine;
/**
* @type {Console}
*/
let logger = WIKI.logger;
/**
*
* @param meilisearchHost
* @param meilisearchApiKey
* @param indexName
* @param timeout
* @returns {Promise<WikiSearchEngine>}
*/
async function getSearchEngine({
meilisearchHost,
meilisearchApiKey,
indexName,
timeout,
}) {
if (!wasm.WikiSearchEngine) {
throw new Error(
`(SEARCH/MEILISEARCH) WikiSearchEngine is not defined. Make sure to add the search engine to your dependencies.`,
);
}
if (!searchEngine) {
logger.info(
`(SEARCH/MEILISEARCH) Configuring search engine with host: ${meilisearchHost}, index: ${indexName}`,
);
searchEngine = await new wasm.WikiSearchEngine(
meilisearchHost || "http://meilisearch:7700",
meilisearchApiKey || "demo",
indexName || "wiki_index",
BigInt(timeout || 5000),
);
}
return searchEngine;
}
function rejectIfIsPrivateAndNotPublished(page, action) {
if (!page.isPublished) {
logger.warn(
`(SEARCH/MEILISEARCH) SKIPPING: Page with path ${page.path} is not published.`,
);
return Promise.resolve();
} else if (page.isPrivate) {
logger.warn(
`(SEARCH/MEILISEARCH) SKIPPING: Page with path ${page.path} is private.`,
);
return Promise.resolve();
} else {
return action(page);
}
}
module.exports = {
/**
* ACTIVATE
*/
async activate() {
logger.info(`(SEARCH/MEILISEARCH) Activating search engine...`);
const engine = await getSearchEngine(this.config);
// log all methods attached to engine
logger.info(`(SEARCH/MEILISEARCH) Engine methods: ${Object.keys(engine)}`);
await engine.activated();
logger.info(`(SEARCH/MEILISEARCH) Search engine activated.`);
},
/**
* DEACTIVATE
*/
async deactivate() {
logger.info(`(SEARCH/MEILISEARCH) Deactivating search engine...`);
// const engine = await getSearchEngine(this.config);
// await engine.deactivated();
logger.info(`(SEARCH/MEILISEARCH) Search engine deactivated.`);
},
/**
* INIT
*/
async init() {
logger.info(`(SEARCH/MEILISEARCH) Initializing search engine...`);
const engine = await getSearchEngine(this.config);
await engine.healthcheck();
logger.info(`(SEARCH/MEILISEARCH) Search engine initialized.`);
},
/**
* @typedef {WikiPage} SearchResultsResponse
* @property {string} locale - This is required mutation from localeCode to locale only for search.
*/
/**
* Represents the response structure for a page search query.
*
* @typedef {Object} PageSearchResponse
* @property {string[]} suggestions - A list of suggested search terms based on the query.
* @property {SearchResultsResponse[]} results - The list of results returned from the search query.
* @property {number} total_hits - The total number of hits (results) found for the query.
*/
/**
* Queries the search engine with the specified query string and options.
*
* This function logs the query process, retrieves search results, and formats
* the results to include locale information. It returns a structured response
* containing the search results and other relevant data.
*
* @async
* @param {string} q - The search query string to be executed.
* @param {Object} opts - Optional parameters for the search query.
* @returns {Promise<PageSearchResponse>} A promise that resolves to a PageSearchResponse object.
*
* @throws {Error} Throws an error if the query fails.
*/
async query(q, opts) {
try {
logger.info(
`(SEARCH/MEILISEARCH) Querying search engine with query: ${q}`,
);
const engine = await getSearchEngine(this.config);
const results = (await engine.query(q)) || [];
logger.info(
`(SEARCH/MEILISEARCH) Query returned ${results.length} results.`,
);
// locale is required for search but nowhere else. So we need to map it to localCode
results.results = (results.results || []).map(
/**
*
* @param {WikiPage} s
* @returns {SearchResultsResponse}
*/
(s) => {
let locale = s.localeCode;
delete s.localeCode;
// Not being found here is expected.
s.locale = locale;
return s;
},
);
return results;
} catch (err) {
logger.warn(
`(SEARCH/MEILISEARCH) Query failed with error: ${err.message}`,
);
throw err;
}
},
/**
* SUGGEST
*
* @param {String} q Query
* @param {Object} opts Additional options
*/
async suggest(q, opts) {
try {
logger.info(`(SEARCH/MEILISEARCH) Fetching suggestions for query: ${q}`);
const engine = await getSearchEngine(this.config);
const suggestions = await engine.suggest(q, opts);
logger.info(`(SEARCH/MEILISEARCH) Suggestions fetched successfully.`);
return suggestions;
} catch (err) {
logger.warn(
`(SEARCH/MEILISEARCH) Suggest failed with error: ${err.message}`,
);
throw err;
}
},
/**
* CREATE
*
* @param {Object} page Page to create
*/
async created(page) {
await rejectIfIsPrivateAndNotPublished(page, async (page) => {
logger.info(
`(SEARCH/MEILISEARCH) Creating search index for page: ${page.path}`,
);
const engine = await getSearchEngine(this.config);
await engine.created(page);
logger.info(
`(SEARCH/MEILISEARCH) Search index created for page: ${page.path}`,
);
});
},
/**
* UPDATE
*
* @param {Object} page Page to update
*/
async updated(page) {
await rejectIfIsPrivateAndNotPublished(page, async (page) => {
logger.info(
`(SEARCH/MEILISEARCH) Updating search index for page: ${page.path}`,
);
const engine = await getSearchEngine(this.config);
await engine.updated(page);
logger.info(
`(SEARCH/MEILISEARCH) Search index updated for page: ${page.path}`,
);
});
},
/**
* DELETE
*
* @param {Object} page Page to delete
*/
async deleted(page) {
await rejectIfIsPrivateAndNotPublished(page, async (page) => {
logger.info(
`(SEARCH/MEILISEARCH) Deleting search index for page: ${page.path}`,
);
const engine = await getSearchEngine(this.config);
await engine.deleted(page);
logger.info(
`(SEARCH/MEILISEARCH) Search index deleted for page: ${page.path}`,
);
});
},
/**
* RENAME
*
* @param {Object} page Page to rename
*/
async renamed(page) {
await rejectIfIsPrivateAndNotPublished(page, async (page) => {
logger.info(
`(SEARCH/MEILISEARCH) Renaming search index for page: ${page.path}`,
);
const engine = await getSearchEngine(this.config);
await engine.updated(page);
logger.info(
`(SEARCH/MEILISEARCH) Search index renamed for page: ${page.destinationPath}`,
);
});
},
/**
* REBUILD INDEX
*/
async rebuild() {
logger.info(`(SEARCH/MEILISEARCH) Rebuilding entire search index...`);
const engine = await getSearchEngine(this.config);
try {
const stream = WIKI.models.knex
.column(
{ id: "hash" },
"path",
{ locale: "localeCode" },
"title",
"description",
"hash",
"isPrivate",
"isPublished",
"content",
"contentType",
"createdAt",
"updatedAt",
"editorKey",
"authorId",
"creatorId",
"localeCode",
{ realId: "id" },
)
.select()
.from("pages")
.where({
isPublished: true,
isPrivate: false,
})
.stream();
// Use a promise to handle the streaming process
const processRow = async (row) => {
row.id = row.realId;
console.log(
`Processing page with ID ${JSON.stringify(row, null, 2)}...`,
);
try {
// Perform delete operation
await engine.deleted(row);
// Perform create operation
await engine.created(row);
console.log(`Page with ID ${row.id} processed successfully.`);
} catch (err) {
console.error(`Error processing page with ID ${row.id}: ${err}`);
}
};
// Listen for data events and process each row
stream.on("data", (row) => {
processRow(row);
});
// Wait for the stream to finish
await new Promise((resolve, reject) => {
stream.on("end", () => {
console.log("All pages processed.");
resolve();
});
stream.on("error", (err) => {
console.error(`Stream error: ${err}`);
reject(err);
});
});
logger.info(`(SEARCH/MEILISEARCH) Search index rebuilt successfully.`);
} catch (err) {
logger.error(
`(SEARCH/MEILISEARCH) Error rebuilding search index: ${err}`,
);
}
},
};