@inlang/sdk 0.26.5 → 0.27.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.
Files changed (60) hide show
  1. package/dist/adapter/solidAdapter.test.js +52 -4
  2. package/dist/api.d.ts +3 -0
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/createMessageLintReportsQuery.d.ts +1 -1
  5. package/dist/createMessageLintReportsQuery.d.ts.map +1 -1
  6. package/dist/createMessageLintReportsQuery.js +30 -22
  7. package/dist/createMessagesQuery.d.ts.map +1 -1
  8. package/dist/createMessagesQuery.js +24 -1
  9. package/dist/createMessagesQuery.test.js +46 -2
  10. package/dist/createNodeishFsWithAbsolutePaths.d.ts +3 -3
  11. package/dist/createNodeishFsWithAbsolutePaths.d.ts.map +1 -1
  12. package/dist/createNodeishFsWithAbsolutePaths.js +9 -1
  13. package/dist/createNodeishFsWithAbsolutePaths.test.js +7 -1
  14. package/dist/createNodeishFsWithWatcher.d.ts +3 -3
  15. package/dist/createNodeishFsWithWatcher.d.ts.map +1 -1
  16. package/dist/createNodeishFsWithWatcher.js +3 -0
  17. package/dist/errors.d.ts +14 -0
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/errors.js +12 -0
  20. package/dist/loadProject.d.ts.map +1 -1
  21. package/dist/loadProject.js +472 -39
  22. package/dist/loadProject.test.js +91 -14
  23. package/dist/messages/variant.test.js +3 -0
  24. package/dist/resolve-modules/plugins/resolvePlugins.test.js +4 -2
  25. package/dist/storage/helper.d.ts +5 -0
  26. package/dist/storage/helper.d.ts.map +1 -0
  27. package/dist/storage/helper.js +35 -0
  28. package/dist/storage/human-id/human-readable-id.d.ts +3 -0
  29. package/dist/storage/human-id/human-readable-id.d.ts.map +1 -0
  30. package/dist/storage/human-id/human-readable-id.js +20 -0
  31. package/dist/storage/human-id/words.d.ts +5 -0
  32. package/dist/storage/human-id/words.d.ts.map +1 -0
  33. package/dist/storage/human-id/words.js +1032 -0
  34. package/dist/storage/human-id/words.test.d.ts +2 -0
  35. package/dist/storage/human-id/words.test.d.ts.map +1 -0
  36. package/dist/storage/human-id/words.test.js +25 -0
  37. package/dist/test-utilities/createMessage.d.ts +1 -0
  38. package/dist/test-utilities/createMessage.d.ts.map +1 -1
  39. package/dist/test-utilities/createMessage.js +1 -0
  40. package/dist/test-utilities/createMessage.test.js +70 -55
  41. package/package.json +12 -8
  42. package/src/adapter/solidAdapter.test.ts +76 -4
  43. package/src/api.ts +4 -0
  44. package/src/createMessageLintReportsQuery.ts +46 -34
  45. package/src/createMessagesQuery.test.ts +54 -2
  46. package/src/createMessagesQuery.ts +30 -1
  47. package/src/createNodeishFsWithAbsolutePaths.test.ts +10 -3
  48. package/src/createNodeishFsWithAbsolutePaths.ts +14 -5
  49. package/src/createNodeishFsWithWatcher.ts +6 -3
  50. package/src/errors.ts +20 -0
  51. package/src/loadProject.test.ts +106 -14
  52. package/src/loadProject.ts +655 -60
  53. package/src/messages/variant.test.ts +3 -0
  54. package/src/resolve-modules/plugins/resolvePlugins.test.ts +4 -2
  55. package/src/storage/helper.ts +48 -0
  56. package/src/storage/human-id/human-readable-id.ts +27 -0
  57. package/src/storage/human-id/words.test.ts +27 -0
  58. package/src/storage/human-id/words.ts +1035 -0
  59. package/src/test-utilities/createMessage.test.ts +72 -54
  60. package/src/test-utilities/createMessage.ts +1 -0
@@ -1,9 +1,8 @@
1
1
  import { resolveModules } from "./resolve-modules/index.js";
2
2
  import { TypeCompiler, ValueErrorType } from "@sinclair/typebox/compiler";
3
- import { ProjectSettingsFileJSONSyntaxError, ProjectSettingsFileNotFoundError, ProjectSettingsInvalidError, PluginLoadMessagesError, PluginSaveMessagesError, LoadProjectInvalidArgument, } from "./errors.js";
3
+ import { ProjectSettingsFileJSONSyntaxError, ProjectSettingsFileNotFoundError, ProjectSettingsInvalidError, PluginSaveMessagesError, LoadProjectInvalidArgument, PluginLoadMessagesError, } from "./errors.js";
4
4
  import { createRoot, createSignal, createEffect } from "./reactivity/solid.js";
5
5
  import { createMessagesQuery } from "./createMessagesQuery.js";
6
- import { debounce } from "throttle-debounce";
7
6
  import { createMessageLintReportsQuery } from "./createMessageLintReportsQuery.js";
8
7
  import { ProjectSettings, Message } from "./versionedInterfaces.js";
9
8
  import { tryCatch } from "@inlang/result";
@@ -11,11 +10,15 @@ import { migrateIfOutdated } from "@inlang/project-settings/migration";
11
10
  import { createNodeishFsWithAbsolutePaths } from "./createNodeishFsWithAbsolutePaths.js";
12
11
  import { normalizePath } from "@lix-js/fs";
13
12
  import { isAbsolutePath } from "./isAbsolutePath.js";
14
- import { createNodeishFsWithWatcher } from "./createNodeishFsWithWatcher.js";
15
13
  import { maybeMigrateToDirectory } from "./migrations/migrateToDirectory.js";
14
+ import { stringifyMessage as stringifyMessage } from "./storage/helper.js";
15
+ import { humanIdHash } from "./storage/human-id/human-readable-id.js";
16
+ import { createNodeishFsWithWatcher } from "./createNodeishFsWithWatcher.js";
16
17
  import { maybeCreateFirstProjectId } from "./migrations/maybeCreateFirstProjectId.js";
17
18
  import { capture } from "./telemetry/capture.js";
18
19
  import { identifyProject } from "./telemetry/groupIdentify.js";
20
+ import _debug from "debug";
21
+ const debug = _debug("loadProject");
19
22
  const settingsCompiler = TypeCompiler.Compile(ProjectSettings);
20
23
  /**
21
24
  * @param projectPath - Absolute path to the inlang settings file.
@@ -27,6 +30,15 @@ const settingsCompiler = TypeCompiler.Compile(ProjectSettings);
27
30
  */
28
31
  export async function loadProject(args) {
29
32
  const projectPath = normalizePath(args.projectPath);
33
+ const messageStates = {
34
+ messageDirtyFlags: {},
35
+ messageLoadHash: {},
36
+ isSaving: false,
37
+ currentSaveMessagesViaPlugin: undefined,
38
+ sheduledSaveMessages: undefined,
39
+ isLoading: false,
40
+ sheduledLoadMessagesViaPlugin: undefined,
41
+ };
30
42
  // -- validation --------------------------------------------------------
31
43
  // the only place where throwing is acceptable because the project
32
44
  // won't even be loaded. do not throw anywhere else. otherwise, apps
@@ -100,8 +112,14 @@ export async function loadProject(args) {
100
112
  createEffect(() => (settingsValue = settings())); // workaround to not run effects twice (e.g. settings change + modules change) (I'm sure there exists a solid way of doing this, but I haven't found it yet)
101
113
  // please don't use this as source of truth, use the query instead
102
114
  // needed for granular linting
103
- const [messages, setMessages] = createSignal();
115
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- setMessages is not called directly we use the CRUD operations on the messageQuery to set the messages now
116
+ const [messages, setMessages] = createSignal([]);
117
+ const [loadMessagesViaPluginError, setLoadMessagesViaPluginError] = createSignal();
118
+ const [saveMessagesViaPluginError, setSaveMessagesViaPluginError] = createSignal();
119
+ const messagesQuery = createMessagesQuery(() => messages());
120
+ const messageLockDirPath = projectPath + "/messagelock";
104
121
  createEffect(() => {
122
+ // wait for first effect excution until modules are resolved
105
123
  const _resolvedModules = resolvedModules();
106
124
  if (!_resolvedModules)
107
125
  return;
@@ -109,24 +127,36 @@ export async function loadProject(args) {
109
127
  markInitAsFailed(undefined);
110
128
  return;
111
129
  }
112
- const loadAndSetMessages = async (fs) => {
113
- makeTrulyAsync(_resolvedModules.resolvedPluginApi.loadMessages({
114
- settings: settingsValue,
115
- nodeishFs: fs,
116
- }))
117
- .then((messages) => {
118
- setMessages(messages);
119
- markInitAsComplete();
120
- })
121
- .catch((err) => markInitAsFailed(new PluginLoadMessagesError({ cause: err })));
122
- };
130
+ const _settings = settings();
131
+ if (!_settings)
132
+ return;
133
+ // get plugin finding the plugin that provides loadMessages function
134
+ const loadMessagePlugin = _resolvedModules.plugins.find((plugin) => plugin.loadMessages !== undefined);
135
+ // TODO #1844 this watcher needs to get pruned when we have a change in the configs which will trigger this again
123
136
  const fsWithWatcher = createNodeishFsWithWatcher({
124
137
  nodeishFs: nodeishFs,
138
+ // this message is called whenever a file changes that was read earlier by this filesystem
139
+ // - the plugin loads messages -> reads the file messages.json -> start watching on messages.json -> updateMessages
125
140
  updateMessages: () => {
126
- loadAndSetMessages(nodeishFs);
141
+ // preserving console.logs as comments pending #
142
+ debug("load messages because of a change in the message.json files");
143
+ loadMessagesViaPlugin(fsWithWatcher, messageLockDirPath, messageStates, messagesQuery, settings(), // NOTE we bang here - we don't expect the settings to become null during the livetime of a project
144
+ loadMessagePlugin)
145
+ .catch((e) => setLoadMessagesViaPluginError(new PluginLoadMessagesError({ cause: e })))
146
+ .then(() => {
147
+ if (loadMessagesViaPluginError() !== undefined) {
148
+ setLoadMessagesViaPluginError(undefined);
149
+ }
150
+ });
127
151
  },
128
152
  });
129
- loadAndSetMessages(fsWithWatcher);
153
+ loadMessagesViaPlugin(fsWithWatcher, messageLockDirPath, messageStates, messagesQuery, _settings, loadMessagePlugin)
154
+ .then(() => {
155
+ markInitAsComplete();
156
+ })
157
+ .catch((err) => {
158
+ markInitAsFailed(new PluginLoadMessagesError({ cause: err }));
159
+ });
130
160
  });
131
161
  // -- installed items ----------------------------------------------------
132
162
  const installedMessageLintRules = () => {
@@ -156,33 +186,73 @@ export async function loadProject(args) {
156
186
  // -- app ---------------------------------------------------------------
157
187
  const initializeError = await initialized.catch((error) => error);
158
188
  const abortController = new AbortController();
159
- const hasWatcher = nodeishFs.watch("/", { signal: abortController.signal }) !== undefined;
160
- const messagesQuery = createMessagesQuery(() => messages() || []);
161
- const lintReportsQuery = createMessageLintReportsQuery(messagesQuery, settings, installedMessageLintRules, resolvedModules, hasWatcher);
162
- const debouncedSave = skipFirst(debounce(500, async (newMessages) => {
163
- try {
164
- if (JSON.stringify(newMessages) !== JSON.stringify(messages())) {
165
- await resolvedModules()?.resolvedPluginApi.saveMessages({
166
- settings: settingsValue,
167
- messages: newMessages,
189
+ nodeishFs.watch("/", { signal: abortController.signal }) !== undefined;
190
+ // map of message id => dispose function from createRoot for each message
191
+ const trackedMessages = new Map();
192
+ let initialSetup = true;
193
+ // -- subscribe to all messages and write to files on signal -------------
194
+ createEffect(() => {
195
+ // debug("Outer createEffect")
196
+ const _resolvedModules = resolvedModules();
197
+ if (!_resolvedModules)
198
+ return;
199
+ const currentMessageIds = new Set(messagesQuery.includedMessageIds());
200
+ const deletedTrackedMessages = [...trackedMessages].filter((tracked) => !currentMessageIds.has(tracked[0]));
201
+ const saveMessagesPlugin = _resolvedModules.plugins.find((plugin) => plugin.saveMessages !== undefined);
202
+ const loadMessagesPlugin = _resolvedModules.plugins.find((plugin) => plugin.loadMessages !== undefined);
203
+ for (const messageId of currentMessageIds) {
204
+ if (!trackedMessages.has(messageId)) {
205
+ // we create a new root to be able to cleanup an effect for a message that got deleted
206
+ createRoot((dispose) => {
207
+ createEffect(() => {
208
+ // debug("Inner createEffect", messageId)
209
+ const message = messagesQuery.get({ where: { id: messageId } });
210
+ if (!message) {
211
+ return;
212
+ }
213
+ if (!trackedMessages?.has(messageId)) {
214
+ // initial effect execution - add dispose function
215
+ trackedMessages?.set(messageId, dispose);
216
+ }
217
+ // don't trigger saves or set dirty flags during initial setup
218
+ if (!initialSetup) {
219
+ messageStates.messageDirtyFlags[message.id] = true;
220
+ saveMessagesViaPlugin(fs, messageLockDirPath, messageStates, messagesQuery, settings(), saveMessagesPlugin, loadMessagesPlugin)
221
+ .catch((e) => setSaveMessagesViaPluginError(new PluginSaveMessagesError({ cause: e })))
222
+ .then(() => {
223
+ if (saveMessagesViaPluginError() !== undefined) {
224
+ setSaveMessagesViaPluginError(undefined);
225
+ }
226
+ });
227
+ }
228
+ });
168
229
  });
169
230
  }
170
231
  }
171
- catch (err) {
172
- throw new PluginSaveMessagesError({
173
- cause: err,
174
- });
232
+ for (const deletedMessage of deletedTrackedMessages) {
233
+ const deletedMessageId = deletedMessage[0];
234
+ // call dispose to cleanup the effect
235
+ const messageEffectDisposeFunction = trackedMessages.get(deletedMessageId);
236
+ if (messageEffectDisposeFunction) {
237
+ messageEffectDisposeFunction();
238
+ trackedMessages.delete(deletedMessageId);
239
+ }
240
+ // mark the deleted message as dirty to force a save
241
+ messageStates.messageDirtyFlags[deletedMessageId] = true;
175
242
  }
176
- const abortController = new AbortController();
177
- if (newMessages.length !== 0 &&
178
- JSON.stringify(newMessages) !== JSON.stringify(messages()) &&
179
- nodeishFs.watch("/", { signal: abortController.signal }) !== undefined) {
180
- setMessages(newMessages);
243
+ if (deletedTrackedMessages.length > 0) {
244
+ // we keep track of the latest save within the loadProject call to await it at the end - this is not used in subsequetial upserts
245
+ saveMessagesViaPlugin(nodeishFs, messageLockDirPath, messageStates, messagesQuery, settings(), saveMessagesPlugin, loadMessagesPlugin)
246
+ .catch((e) => setSaveMessagesViaPluginError(new PluginSaveMessagesError({ cause: e })))
247
+ .then(() => {
248
+ if (saveMessagesViaPluginError() !== undefined) {
249
+ setSaveMessagesViaPluginError(undefined);
250
+ }
251
+ });
181
252
  }
182
- }, { atBegin: false }));
183
- createEffect(() => {
184
- debouncedSave(messagesQuery.getAll());
253
+ initialSetup = false;
185
254
  });
255
+ const lintReportsQuery = createMessageLintReportsQuery(messagesQuery, settings, installedMessageLintRules, resolvedModules);
186
256
  /**
187
257
  * Utility to escape reactive tracking and avoid multiple calls to
188
258
  * the capture event.
@@ -221,6 +291,10 @@ export async function loadProject(args) {
221
291
  errors: createSubscribable(() => [
222
292
  ...(initializeError ? [initializeError] : []),
223
293
  ...(resolvedModules() ? resolvedModules().errors : []),
294
+ ...(loadMessagesViaPluginError() ? [loadMessagesViaPluginError()] : []),
295
+ ...(saveMessagesViaPluginError() ? [saveMessagesViaPluginError()] : []),
296
+ // have a query error exposed
297
+ //...(lintErrors() ?? []),
224
298
  ]),
225
299
  settings: createSubscribable(() => settings()),
226
300
  setSettings,
@@ -232,7 +306,6 @@ export async function loadProject(args) {
232
306
  };
233
307
  });
234
308
  }
235
- //const x = {} as InlangProject
236
309
  // ------------------------------------------------------------------------------------------------
237
310
  const loadSettings = async (args) => {
238
311
  const { data: settingsFile, error: settingsFileError } = await tryCatch(async () => await args.nodeishFs.readFile(args.settingsFilePath, { encoding: "utf-8" }));
@@ -319,3 +392,363 @@ export function createSubscribable(signal) {
319
392
  },
320
393
  });
321
394
  }
395
+ // --- serialization of loading / saving messages.
396
+ // 1. A plugin saveMessage call can not be called simultaniously to avoid side effects - its an async function not controlled by us
397
+ // 2. loading and saving must not run in "parallel".
398
+ // - json plugin exports into separate file per language.
399
+ // - saving a message in two different languages would lead to a write in de.json first
400
+ // - This will leads to a load of the messages and since en.json has not been saved yet the english variant in the message would get overritten with the old state again
401
+ /**
402
+ * Messsage that loads messages from a plugin - this method synchronizes with the saveMessage funciton.
403
+ * If a save is in progress loading will wait until saving is done. If another load kicks in during this load it will queue the
404
+ * load and execute it at the end of this load. subsequential loads will not be queued but the same promise will be reused
405
+ *
406
+ * - NOTE: this means that the parameters used to load like settingsValue and loadPlugin might not take into account. this has to be refactored
407
+ * with the loadProject restructuring
408
+ * @param fs
409
+ * @param messagesQuery
410
+ * @param settingsValue
411
+ * @param loadPlugin
412
+ * @returns void - updates the files and messages in of the project in place
413
+ */
414
+ async function loadMessagesViaPlugin(fs, lockDirPath, messageState, messagesQuery, settingsValue, loadPlugin) {
415
+ const experimentalAliases = !!settingsValue.experimental?.aliases;
416
+ // loading is an asynchronous process - check if another load is in progress - queue this call if so
417
+ if (messageState.isLoading) {
418
+ if (!messageState.sheduledLoadMessagesViaPlugin) {
419
+ messageState.sheduledLoadMessagesViaPlugin = createAwaitable();
420
+ }
421
+ // another load will take place right after the current one - its goingt to be idempotent form the current requested one - don't reschedule
422
+ return messageState.sheduledLoadMessagesViaPlugin[0];
423
+ }
424
+ // set loading flag
425
+ messageState.isLoading = true;
426
+ let lockTime = undefined;
427
+ try {
428
+ lockTime = await acquireFileLock(fs, lockDirPath, "loadMessage");
429
+ const loadedMessages = await makeTrulyAsync(loadPlugin.loadMessages({
430
+ settings: settingsValue,
431
+ nodeishFs: fs,
432
+ }));
433
+ for (const loadedMessage of loadedMessages) {
434
+ const loadedMessageClone = structuredClone(loadedMessage);
435
+ const currentMessages = messagesQuery
436
+ .getAll()
437
+ // TODO #1585 here we match using the id to support legacy load message plugins - after we introduced import / export methods we will use importedMessage.alias
438
+ .filter((message) => (experimentalAliases ? message.alias["default"] : message.id) === loadedMessage.id);
439
+ if (currentMessages.length > 1) {
440
+ // NOTE: if we happen to find two messages witht the sam alias we throw for now
441
+ // - this could be the case if one edits the aliase manualy
442
+ throw new Error("more than one message with the same id or alias found ");
443
+ }
444
+ else if (currentMessages.length === 1) {
445
+ // update message in place - leave message id and alias untouched
446
+ loadedMessageClone.alias = {};
447
+ // TODO #1585 we have to map the id of the importedMessage to the alias and fill the id property with the id of the existing message - change when import mesage provides importedMessage.alias
448
+ if (experimentalAliases) {
449
+ loadedMessageClone.alias["default"] = loadedMessageClone.id;
450
+ loadedMessageClone.id = currentMessages[0].id;
451
+ }
452
+ // NOTE stringifyMessage encodes messages independent from key order!
453
+ const importedEnecoded = stringifyMessage(loadedMessageClone);
454
+ // NOTE could use hash instead of the whole object JSON to save memory...
455
+ if (messageState.messageLoadHash[loadedMessageClone.id] === importedEnecoded) {
456
+ debug("skipping upsert!");
457
+ continue;
458
+ }
459
+ // This logic is preventing cycles - could also be handled if update api had a parameter for who triggered update
460
+ // e.g. when FS was updated, we don't need to write back to FS
461
+ // update is synchronous, so update effect will be triggered immediately
462
+ // NOTE: this might trigger a save before we have the chance to delete - but since save is async and waits for the lock acquired by this method - its save to set the flags afterwards
463
+ messagesQuery.update({ where: { id: loadedMessageClone.id }, data: loadedMessageClone });
464
+ // we load a fresh version - lets delete dirty flag that got created by the update
465
+ delete messageState.messageDirtyFlags[loadedMessageClone.id];
466
+ // NOTE could use hash instead of the whole object JSON to save memory...
467
+ messageState.messageLoadHash[loadedMessageClone.id] = importedEnecoded;
468
+ }
469
+ else {
470
+ // message with the given alias does not exist so far
471
+ loadedMessageClone.alias = {};
472
+ // TODO #1585 we have to map the id of the importedMessage to the alias - change when import mesage provides importedMessage.alias
473
+ if (experimentalAliases) {
474
+ loadedMessageClone.alias["default"] = loadedMessageClone.id;
475
+ let currentOffset = 0;
476
+ let messsageId;
477
+ do {
478
+ messsageId = humanIdHash(loadedMessageClone.id, currentOffset);
479
+ if (messagesQuery.get({ where: { id: messsageId } })) {
480
+ currentOffset += 1;
481
+ messsageId = undefined;
482
+ }
483
+ } while (messsageId === undefined);
484
+ // create a humanId based on a hash of the alias
485
+ loadedMessageClone.id = messsageId;
486
+ }
487
+ const importedEnecoded = stringifyMessage(loadedMessageClone);
488
+ // add the message - this will trigger an async file creation in the backgound!
489
+ messagesQuery.create({ data: loadedMessageClone });
490
+ // we load a fresh version - lets delete dirty flag that got created by the create method
491
+ delete messageState.messageDirtyFlags[loadedMessageClone.id];
492
+ messageState.messageLoadHash[loadedMessageClone.id] = importedEnecoded;
493
+ }
494
+ }
495
+ await releaseLock(fs, lockDirPath, "loadMessage", lockTime);
496
+ lockTime = undefined;
497
+ debug("loadMessagesViaPlugin: " + loadedMessages.length + " Messages processed ");
498
+ messageState.isLoading = false;
499
+ }
500
+ finally {
501
+ if (lockTime !== undefined) {
502
+ await releaseLock(fs, lockDirPath, "loadMessage", lockTime);
503
+ }
504
+ messageState.isLoading = false;
505
+ }
506
+ const executingScheduledMessages = messageState.sheduledLoadMessagesViaPlugin;
507
+ if (executingScheduledMessages) {
508
+ // a load has been requested during the load - executed it
509
+ // reset sheduling to except scheduling again
510
+ messageState.sheduledLoadMessagesViaPlugin = undefined;
511
+ // recall load unawaited to allow stack to pop
512
+ loadMessagesViaPlugin(fs, lockDirPath, messageState, messagesQuery, settingsValue, loadPlugin)
513
+ .then(() => {
514
+ // resolve the scheduled load message promise
515
+ executingScheduledMessages[1]();
516
+ })
517
+ .catch((e) => {
518
+ // reject the scheduled load message promise
519
+ executingScheduledMessages[2](e);
520
+ });
521
+ }
522
+ }
523
+ async function saveMessagesViaPlugin(fs, lockDirPath, messageState, messagesQuery, settingsValue, savePlugin, loadPlugin) {
524
+ // queue next save if we have a save ongoing
525
+ if (messageState.isSaving) {
526
+ if (!messageState.sheduledSaveMessages) {
527
+ messageState.sheduledSaveMessages = createAwaitable();
528
+ }
529
+ return messageState.sheduledSaveMessages[0];
530
+ }
531
+ // set isSavingFlag
532
+ messageState.isSaving = true;
533
+ messageState.currentSaveMessagesViaPlugin = (async function () {
534
+ const saveMessageHashes = {};
535
+ // check if we have any dirty message - witho
536
+ if (Object.keys(messageState.messageDirtyFlags).length == 0) {
537
+ // nothing to save :-)
538
+ debug("save was skipped - no messages marked as dirty... build!");
539
+ messageState.isSaving = false;
540
+ return;
541
+ }
542
+ let messageDirtyFlagsBeforeSave;
543
+ let lockTime;
544
+ try {
545
+ lockTime = await acquireFileLock(fs, lockDirPath, "saveMessage");
546
+ // since it may takes some time to acquire the lock we check if the save is required still (loadMessage could have happend in between)
547
+ if (Object.keys(messageState.messageDirtyFlags).length == 0) {
548
+ debug("save was skipped - no messages marked as dirty... releasing lock again");
549
+ messageState.isSaving = false;
550
+ // release lock in finally block
551
+ return;
552
+ }
553
+ const currentMessages = messagesQuery.getAll();
554
+ const messagesToExport = [];
555
+ for (const message of currentMessages) {
556
+ if (messageState.messageDirtyFlags[message.id]) {
557
+ const importedEnecoded = stringifyMessage(message);
558
+ // NOTE: could use hash instead of the whole object JSON to save memory...
559
+ saveMessageHashes[message.id] = importedEnecoded;
560
+ }
561
+ const fixedExportMessage = { ...message };
562
+ // TODO #1585 here we match using the id to support legacy load message plugins - after we introduced import / export methods we will use importedMessage.alias
563
+ if (settingsValue.experimental?.aliases) {
564
+ fixedExportMessage.id = fixedExportMessage.alias["default"] ?? fixedExportMessage.id;
565
+ }
566
+ messagesToExport.push(fixedExportMessage);
567
+ }
568
+ // wa are about to save the messages to the plugin - reset all flags now
569
+ messageDirtyFlagsBeforeSave = { ...messageState.messageDirtyFlags };
570
+ messageState.messageDirtyFlags = {};
571
+ // NOTE: this assumes that the plugin will handle message ordering
572
+ await savePlugin.saveMessages({
573
+ settings: settingsValue,
574
+ messages: messagesToExport,
575
+ nodeishFs: fs,
576
+ });
577
+ for (const [messageId, messageHash] of Object.entries(saveMessageHashes)) {
578
+ messageState.messageLoadHash[messageId] = messageHash;
579
+ }
580
+ if (lockTime !== undefined) {
581
+ await releaseLock(fs, lockDirPath, "saveMessage", lockTime);
582
+ lockTime = undefined;
583
+ }
584
+ // if there is a queued load, allow it to take the lock before we run additional saves.
585
+ if (messageState.sheduledLoadMessagesViaPlugin) {
586
+ debug("saveMessagesViaPlugin calling queued loadMessagesViaPlugin to share lock");
587
+ await loadMessagesViaPlugin(fs, lockDirPath, messageState, messagesQuery, settingsValue, loadPlugin);
588
+ }
589
+ messageState.isSaving = false;
590
+ }
591
+ catch (err) {
592
+ // something went wrong - add dirty flags again
593
+ if (messageDirtyFlagsBeforeSave !== undefined) {
594
+ for (const dirtyMessageId of Object.keys(messageDirtyFlagsBeforeSave)) {
595
+ messageState.messageDirtyFlags[dirtyMessageId] = true;
596
+ }
597
+ }
598
+ if (lockTime !== undefined) {
599
+ await releaseLock(fs, lockDirPath, "saveMessage", lockTime);
600
+ lockTime = undefined;
601
+ }
602
+ messageState.isSaving = false;
603
+ // ok an error
604
+ throw new PluginSaveMessagesError({
605
+ cause: err,
606
+ });
607
+ }
608
+ finally {
609
+ if (lockTime !== undefined) {
610
+ await releaseLock(fs, lockDirPath, "saveMessage", lockTime);
611
+ lockTime = undefined;
612
+ }
613
+ messageState.isSaving = false;
614
+ }
615
+ })();
616
+ await messageState.currentSaveMessagesViaPlugin;
617
+ if (messageState.sheduledSaveMessages) {
618
+ const executingSheduledSaveMessages = messageState.sheduledSaveMessages;
619
+ messageState.sheduledSaveMessages = undefined;
620
+ saveMessagesViaPlugin(fs, lockDirPath, messageState, messagesQuery, settingsValue, savePlugin, loadPlugin)
621
+ .then(() => {
622
+ executingSheduledSaveMessages[1]();
623
+ })
624
+ .catch((e) => {
625
+ executingSheduledSaveMessages[2](e);
626
+ });
627
+ }
628
+ }
629
+ const maxRetries = 5;
630
+ const nProbes = 50;
631
+ const probeInterval = 100;
632
+ async function acquireFileLock(fs, lockDirPath, lockOrigin, tryCount = 0) {
633
+ if (tryCount > maxRetries) {
634
+ throw new Error(lockOrigin + " exceeded maximum Retries (5) to acquire lockfile " + tryCount);
635
+ }
636
+ try {
637
+ debug(lockOrigin + " tries to acquire a lockfile Retry Nr.: " + tryCount);
638
+ await fs.mkdir(lockDirPath);
639
+ const stats = await fs.stat(lockDirPath);
640
+ debug(lockOrigin + " acquired a lockfile Retry Nr.: " + tryCount);
641
+ return stats.mtimeMs;
642
+ }
643
+ catch (error) {
644
+ if (error.code !== "EEXIST") {
645
+ // we only expect the error that the file exists already (locked by other process)
646
+ throw error;
647
+ }
648
+ }
649
+ let currentLockTime;
650
+ try {
651
+ const stats = await fs.stat(lockDirPath);
652
+ currentLockTime = stats.mtimeMs;
653
+ }
654
+ catch (fstatError) {
655
+ if (fstatError.code === "ENOENT") {
656
+ // lock file seems to be gone :) - lets try again
657
+ debug(lockOrigin + " tryCount++ lock file seems to be gone :) - lets try again " + tryCount);
658
+ return acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1);
659
+ }
660
+ throw fstatError;
661
+ }
662
+ debug(lockOrigin +
663
+ " tries to acquire a lockfile - lock currently in use... starting probe phase " +
664
+ tryCount);
665
+ return new Promise((resolve, reject) => {
666
+ let probeCounts = 0;
667
+ const scheduleProbationTimeout = () => {
668
+ setTimeout(async () => {
669
+ probeCounts += 1;
670
+ let lockFileStats = undefined;
671
+ try {
672
+ debug(lockOrigin + " tries to acquire a lockfile - check if the lock is free now " + tryCount);
673
+ // alright lets give it another try
674
+ lockFileStats = await fs.stat(lockDirPath);
675
+ }
676
+ catch (fstatError) {
677
+ if (fstatError.code === "ENOENT") {
678
+ debug(lockOrigin +
679
+ " tryCount++ in Promise - tries to acquire a lockfile - lock file seems to be free now - try to acquire " +
680
+ tryCount);
681
+ const lock = acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1);
682
+ return resolve(lock);
683
+ }
684
+ return reject(fstatError);
685
+ }
686
+ // still the same locker! -
687
+ if (lockFileStats.mtimeMs === currentLockTime) {
688
+ if (probeCounts >= nProbes) {
689
+ // ok maximum lock time ran up (we waitetd nProbes * probeInterval) - we consider the lock to be stale
690
+ debug(lockOrigin +
691
+ " tries to acquire a lockfile - lock not free - but stale lets drop it" +
692
+ tryCount);
693
+ try {
694
+ await fs.rmdir(lockDirPath);
695
+ }
696
+ catch (rmLockError) {
697
+ if (rmLockError.code === "ENOENT") {
698
+ // lock already gone?
699
+ // Option 1: The "stale process" decided to get rid of it
700
+ // Option 2: Another process acquiring the lock and detected a stale one as well
701
+ }
702
+ return reject(rmLockError);
703
+ }
704
+ try {
705
+ debug(lockOrigin +
706
+ " tryCount++ same locker - try to acquire again after removing stale lock " +
707
+ tryCount);
708
+ const lock = await acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1);
709
+ return resolve(lock);
710
+ }
711
+ catch (lockAquireException) {
712
+ return reject(lockAquireException);
713
+ }
714
+ }
715
+ else {
716
+ // lets schedule a new probation
717
+ return scheduleProbationTimeout();
718
+ }
719
+ }
720
+ else {
721
+ try {
722
+ debug(lockOrigin + " tryCount++ different locker - try to acquire again " + tryCount);
723
+ const lock = await acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1);
724
+ return resolve(lock);
725
+ }
726
+ catch (error) {
727
+ return reject(error);
728
+ }
729
+ }
730
+ }, probeInterval);
731
+ };
732
+ scheduleProbationTimeout();
733
+ });
734
+ }
735
+ async function releaseLock(fs, lockDirPath, lockOrigin, lockTime) {
736
+ debug(lockOrigin + " releasing the lock ");
737
+ try {
738
+ const stats = await fs.stat(lockDirPath);
739
+ if (stats.mtimeMs === lockTime) {
740
+ // this can be corrupt as welll since the last getStat and the current a modification could have occured :-/
741
+ await fs.rmdir(lockDirPath);
742
+ }
743
+ }
744
+ catch (statError) {
745
+ debug(lockOrigin + " couldn't release the lock");
746
+ if (statError.code === "ENOENT") {
747
+ // ok seeks like the log was released by someone else
748
+ debug(lockOrigin + " WARNING - the lock was released by a different process");
749
+ return;
750
+ }
751
+ debug(statError);
752
+ throw statError;
753
+ }
754
+ }