« get me outta code hell

content-cache.js « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/content-cache.js
blob: 795860d6f5a68c29dbe750b6ddc4334330dd5d72 (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
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
import {getArgsForRelationsAndData} from './content-function.js';
import {quickLoadAllFromYAML} from './data/yaml.js';
import {compareArrays} from './util/sugar.js';

export class TupleMap {
  #store = [undefined, new WeakMap(), new Map()];

  #lifetime(value) {
    if (
      typeof value === 'object' && value !== null ||
      typeof value === 'function'
    ) {
      return 'weak';
    } else {
      return 'strong';
    }
  }

  #getSubstoreShallow(value, store) {
    const map = store[this.#lifetime(value) === 'weak' ? 1 : 2];
    if (map.has(value)) {
      return map.get(value);
    } else {
      const substore = [undefined, new WeakMap(), new Map()];
      map.set(value, substore);
      return substore;
    }
  }

  #getSubstoreDeep(tuple, store = this.#store) {
    if (tuple.length === 0) {
      return store;
    } else {
      const [first, ...rest] = tuple;
      return this.#getSubstoreDeep(rest, this.#getSubstoreShallow(first, store));
    }
  }

  get(tuple) {
    const store = this.#getSubstoreDeep(tuple);
    return store[0];
  }

  set(tuple, value) {
    const store = this.#getSubstoreDeep(tuple);
    store[0] = value;
    return value;
  }
}

export default class ContentCache {
  #contentFunctions = {};
  #extraDependencies = {};

  #contentDependenciesTree = {};
  #desiredContentFunctionCalls = [];

  #cachedRelationsLayouts = new TupleMap();
  #cachedRelationsSlots = new TupleMap();

  #relationIdentifier = Symbol();

  wikiData = {};

  constructor() {}

  desireContentFunction(functionName, args, levelOfDesire) {
    this.#desiredContentFunctionCalls.push({functionName, args, levelOfDesire});
  }

  #getPotentiallyDirectlyDependantContentFunctions(functionName) {
    const direct =
      Object.entries(this.#contentDependenciesTree)
        .filter(([name, dependencies]) => dependencies.has(functionName))
        .map(([name]) => name);

    return new Set(direct);
  }

  #getPotentiallyDependantContentFunctions(functionName) {
    const direct = this.#getPotentiallyDirectlyDependantContentFunctions(functionName);
    const indirect =
      Array.from(direct)
        .flatMap(name => Array.from(this.#getPotentiallyDirectlyDependantContentFunctions(name)));

    return new Set([...direct, ...indirect]);
  }

  #prepareRelations(functionName, args) {
    const tuple = [functionName, ...args];
    if (
      this.#cachedRelationsLayouts.get(tuple) &&
      this.#cachedRelationsSlots.get(tuple)
    ) {
      return;
    }

    const contentFunction = this.#contentFunctions[functionName];
    const argsForRelations =
      getArgsForRelationsAndData(contentFunction, this.wikiData, ...args);

    const listedDependencies = new Set(contentFunction.contentDependencies);

    // Note: "slots" here is a completely separate concept from HTML template
    // slots, which are handled completely within the content function. Here,
    // relation slots are just references to a position within the relations
    // layout that are referred to by a symbol - when the relation is ready,
    // its result will be "slotted" into the layout.
    const relationSlots = {};

    const relationSymbolMessage = (() => {
      let num = 1;
      return name => `#${num++} ${name}`;
    })();

    const relationFunction = (name, ...args) => {
      if (!listedDependencies.has(name)) {
        throw new Error(`Called relation('${name}') but ${functionName} doesn't list that dependency`);
      }

      const relationSymbol = Symbol(relationSymbolMessage(name));
      relationSlots[relationSymbol] = {name, args};
      return {[this.#relationIdentifier]: relationSymbol};
    };

    const relationsLayout =
      contentFunction.relations(relationFunction, ...argsForRelations);

    this.#cachedRelationsLayouts.set([functionName, ...args], relationsLayout);
    this.#cachedRelationsSlots.set([functionName, ...args], relationSlots);
  }

  getRelationsLayout(functionName, args) {
    this.#prepareRelations(functionName, args);
    return this.#cachedRelationsLayouts.get([functionName, ...args]);
  }

  getRelationsSlots(functionName, args) {
    this.#prepareRelations(functionName, args);
    return this.#cachedRelationsSlots.get([functionName, ...args]);
  }

  scoreContentFunctionDesirability(scoreFunctionName, scoreArgs) {
    const potentiallyDependantNames = this.#getPotentiallyDependantContentFunctions(scoreFunctionName);

    let score = 0;

    const recursive = (namesAndArgs, levelOfDesire) => {
      for (const {name, args} of namesAndArgs) {
        if (name === scoreFunctionName) {
          if (compareArrays(args, scoreArgs)) {
            score += levelOfDesire;
          }
        } else if (!potentiallyDependantNames.has(name)) {
          continue;
        }
        const slots = this.getRelationsSlots(name, args);
        const symbols = Object.getOwnPropertySymbols(slots);
        recursive(symbols.map(symbol => slots[symbol]), levelOfDesire);
      }
    };

    for (const {functionName: name, args, levelOfDesire} of this.#desiredContentFunctionCalls) {
      recursive([{name, args}], levelOfDesire);
    }

    return score;
  }

  /*
  evaluateContentFunction(functionName, args) {
  }
  */

  updateContentDependency(functionName, contentFunction) {
    this.#contentFunctions[functionName] =
      contentFunction;

    this.#contentDependenciesTree[functionName] =
      contentFunction.contentDependencies;
  }

  updateExtraDependency(dependencyName, value) {
    this.#extraDependencies[dependencyName] = value;
  }

  connectContentDependenciesWatcher(watcher) {
    watcher.on('update', functionName => {
      this.updateContentDependency(
        functionName,
        watcher.contentDependencies[functionName]);
    });
  }
}

(async function() {
  const {watchContentDependencies} = await import('./content/dependencies/index.js');
  const contentDependenciesWatcher = await watchContentDependencies();

  const cache = new ContentCache();
  cache.connectContentDependenciesWatcher(contentDependenciesWatcher);

  await new Promise(resolve => contentDependenciesWatcher.once('ready', resolve));

  cache.wikiData = await quickLoadAllFromYAML(process.env.HSMUSIC_DATA);

  for (const album of cache.wikiData.albumData) {
    cache.desireContentFunction('generateAlbumInfoPage', [album], 10000);
    cache.desireContentFunction('generateAlbumGalleryPage', [album], 10000);
    for (const track of album.tracks) {
      cache.desireContentFunction('generateTrackInfoPage', [track], 1);
    }
  }

  for (const album of cache.wikiData.albumData) {
    console.log(album, cache.scoreContentFunctionDesirability('linkAlbum', [album]));
  }
  // console.log(cache.scoreContentFunctionDesirability('linkAlbum', [cache.wikiData.albumData[0]]));
  // console.log(cache.scoreContentFunctionDesirability('linkAlbum', [cache.wikiData.albumData[1]]));
  // console.log(cache.scoreContentFunctionDesirability('linkAlbum', [cache.wikiData.albumData[2]]));
})().catch(err => console.error(err));