« get me outta code hell

search.js « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/search.js
blob: c853c3be95203197f3dc465804f8ea2ecabb1d5a (plain)
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
'use strict';

import {createHash} from 'node:crypto';
import {mkdir, writeFile} from 'node:fs/promises';
import * as path from 'node:path';

import {compress} from 'compress-json';
import FlexSearch from 'flexsearch';
import {pack} from 'msgpackr';

import {logWarn} from '#cli';
import {makeSearchIndex} from '#search-shape';
import searchSpec from '#search-select';
import {stitchArrays} from '#sugar';
import {checkIfImagePathHasCachedThumbnails, getThumbnailEqualOrSmaller}
  from '#thumbs';

// TODO: This function basically mirrors bind-utilities.js, which isn't
// exactly robust, but... binding might need some more thought across the
// codebase in *general.*
function bindSearchUtilities({
  checkIfImagePathHasCachedThumbnails,
  getThumbnailEqualOrSmaller,
  thumbsCache,
  urls,
}) {
  const bound = {
    urls,
  };

  bound.checkIfImagePathHasCachedThumbnails =
    (imagePath) =>
      checkIfImagePathHasCachedThumbnails(imagePath, thumbsCache);

  bound.getThumbnailEqualOrSmaller =
    (preferred, imagePath) =>
      getThumbnailEqualOrSmaller(preferred, imagePath, thumbsCache);

  return bound;
}

function populateSearchIndex(index, descriptor, opts) {
  const {wikiData} = opts;
  const bound = bindSearchUtilities(opts);

  for (const thing of descriptor.select(wikiData)) {
    const reference = thing.constructor.getReference(thing);

    let processed;
    try {
      processed = descriptor.process(thing, bound);
    } catch (caughtError) {
      throw new Error(
        `Failed to process searchable thing ${reference}`,
        {cause: caughtError});
    }

    index.add({reference, ...processed});
  }
}

async function serializeIndex(index) {
  const results = {};

  await index.export((key, data) => {
    if (data === undefined) {
      return;
    }

    if (typeof data !== 'string') {
      logWarn`Got something besides a string from index.export(), skipping:`;
      console.warn(key, data);
      return;
    }

    results[key] = JSON.parse(data);
  });

  return results;
}

export async function writeSearchData({
  thumbsCache,
  urls,
  wikiCachePath,
  wikiData,
}) {
  if (!wikiCachePath) {
    throw new Error(`Expected wikiCachePath to write into`);
  }

  // Basic flow is:
  // 1. Define schema for type
  // 2. Add documents to index
  // 3. Save index to exportable json

  const keys =
    Object.keys(searchSpec);

  const descriptors =
    Object.values(searchSpec);

  const indexes =
    descriptors
      .map(descriptor =>
        makeSearchIndex(descriptor, {FlexSearch}));

  stitchArrays({
    index: indexes,
    descriptor: descriptors,
  }).forEach(({index, descriptor}) =>
      populateSearchIndex(index, descriptor, {
        checkIfImagePathHasCachedThumbnails,
        getThumbnailEqualOrSmaller,
        thumbsCache,
        urls,
        wikiData,
      }));

  const serializedIndexes =
    await Promise.all(indexes.map(serializeIndex));

  const packedIndexes =
    serializedIndexes
      .map(data => compress(data))
      .map(data => pack(data));

  const outputDirectory =
    path.join(wikiCachePath, 'search');

  const mainIndexFile =
    path.join(outputDirectory, 'index.json');

  const mainIndexJSON =
    JSON.stringify(
      Object.fromEntries(
        stitchArrays({
          key: keys,
          buffer: packedIndexes,
        }).map(({key, buffer}) => {
          const md5 = createHash('md5');
          md5.write(buffer);

          const value = {
            md5: md5.digest('hex'),
          };

          return [key, value];
        })));


  await mkdir(outputDirectory, {recursive: true});

  await Promise.all(
    stitchArrays({
      key: keys,
      buffer: packedIndexes,
    }).map(({key, buffer}) =>
        writeFile(
          path.join(outputDirectory, key + '.json.msgpack'),
          buffer)));

  await writeFile(mainIndexFile, mainIndexJSON);
}