@inlang/sdk 0.26.4 → 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
@@ -11,29 +11,57 @@ import {
11
11
  ProjectSettingsFileJSONSyntaxError,
12
12
  ProjectSettingsFileNotFoundError,
13
13
  ProjectSettingsInvalidError,
14
- PluginLoadMessagesError,
15
14
  PluginSaveMessagesError,
16
15
  LoadProjectInvalidArgument,
16
+ PluginLoadMessagesError,
17
17
  } from "./errors.js"
18
18
  import { createRoot, createSignal, createEffect } from "./reactivity/solid.js"
19
19
  import { createMessagesQuery } from "./createMessagesQuery.js"
20
- import { debounce } from "throttle-debounce"
21
20
  import { createMessageLintReportsQuery } from "./createMessageLintReportsQuery.js"
22
21
  import { ProjectSettings, Message, type NodeishFilesystemSubset } from "./versionedInterfaces.js"
23
22
  import { tryCatch, type Result } from "@inlang/result"
24
23
  import { migrateIfOutdated } from "@inlang/project-settings/migration"
25
24
  import { createNodeishFsWithAbsolutePaths } from "./createNodeishFsWithAbsolutePaths.js"
26
- import { normalizePath } from "@lix-js/fs"
25
+ import { normalizePath, type NodeishFilesystem } from "@lix-js/fs"
27
26
  import { isAbsolutePath } from "./isAbsolutePath.js"
28
- import { createNodeishFsWithWatcher } from "./createNodeishFsWithWatcher.js"
29
27
  import { maybeMigrateToDirectory } from "./migrations/migrateToDirectory.js"
30
- import { maybeCreateFirstProjectId } from "./migrations/maybeCreateFirstProjectId.js"
28
+
29
+ import { stringifyMessage as stringifyMessage } from "./storage/helper.js"
30
+
31
+ import { humanIdHash } from "./storage/human-id/human-readable-id.js"
32
+
31
33
  import type { Repository } from "@lix-js/client"
34
+ import { createNodeishFsWithWatcher } from "./createNodeishFsWithWatcher.js"
35
+
36
+ import { maybeCreateFirstProjectId } from "./migrations/maybeCreateFirstProjectId.js"
37
+
32
38
  import { capture } from "./telemetry/capture.js"
33
39
  import { identifyProject } from "./telemetry/groupIdentify.js"
40
+ import type { NodeishStats } from "../../../../lix/source-code/fs/dist/NodeishFilesystemApi.js"
41
+
42
+ import _debug from "debug"
43
+ const debug = _debug("loadProject")
34
44
 
35
45
  const settingsCompiler = TypeCompiler.Compile(ProjectSettings)
36
46
 
47
+ type MessageState = {
48
+ messageDirtyFlags: {
49
+ [messageId: string]: boolean
50
+ }
51
+ messageLoadHash: {
52
+ [messageId: string]: string
53
+ }
54
+ isSaving: boolean
55
+ currentSaveMessagesViaPlugin: Promise<void> | undefined
56
+ sheduledSaveMessages:
57
+ | [awaitable: Promise<void>, resolve: () => void, reject: (e: unknown) => void]
58
+ | undefined
59
+ isLoading: boolean
60
+ sheduledLoadMessagesViaPlugin:
61
+ | [awaitable: Promise<void>, resolve: () => void, reject: (e: unknown) => void]
62
+ | undefined
63
+ }
64
+
37
65
  /**
38
66
  * @param projectPath - Absolute path to the inlang settings file.
39
67
  * @param repo - An instance of a lix repo as returned by `openRepository`.
@@ -50,6 +78,16 @@ export async function loadProject(args: {
50
78
  }): Promise<InlangProject> {
51
79
  const projectPath = normalizePath(args.projectPath)
52
80
 
81
+ const messageStates = {
82
+ messageDirtyFlags: {},
83
+ messageLoadHash: {},
84
+ isSaving: false,
85
+ currentSaveMessagesViaPlugin: undefined,
86
+ sheduledSaveMessages: undefined,
87
+ isLoading: false,
88
+ sheduledLoadMessagesViaPlugin: undefined,
89
+ } as MessageState
90
+
53
91
  // -- validation --------------------------------------------------------
54
92
  // the only place where throwing is acceptable because the project
55
93
  // won't even be loaded. do not throw anywhere else. otherwise, apps
@@ -154,9 +192,23 @@ export async function loadProject(args: {
154
192
 
155
193
  // please don't use this as source of truth, use the query instead
156
194
  // needed for granular linting
157
- const [messages, setMessages] = createSignal<Message[]>()
195
+ // 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
196
+ const [messages, setMessages] = createSignal<Message[]>([])
197
+
198
+ const [loadMessagesViaPluginError, setLoadMessagesViaPluginError] = createSignal<
199
+ Error | undefined
200
+ >()
201
+
202
+ const [saveMessagesViaPluginError, setSaveMessagesViaPluginError] = createSignal<
203
+ Error | undefined
204
+ >()
205
+
206
+ const messagesQuery = createMessagesQuery(() => messages())
207
+
208
+ const messageLockDirPath = projectPath + "/messagelock"
158
209
 
159
210
  createEffect(() => {
211
+ // wait for first effect excution until modules are resolved
160
212
  const _resolvedModules = resolvedModules()
161
213
  if (!_resolvedModules) return
162
214
 
@@ -165,28 +217,53 @@ export async function loadProject(args: {
165
217
  return
166
218
  }
167
219
 
168
- const loadAndSetMessages = async (fs: NodeishFilesystemSubset) => {
169
- makeTrulyAsync(
170
- _resolvedModules.resolvedPluginApi.loadMessages({
171
- settings: settingsValue,
172
- nodeishFs: fs,
173
- })
174
- )
175
- .then((messages) => {
176
- setMessages(messages)
177
- markInitAsComplete()
178
- })
179
- .catch((err) => markInitAsFailed(new PluginLoadMessagesError({ cause: err })))
180
- }
220
+ const _settings = settings()
221
+ if (!_settings) return
181
222
 
223
+ // get plugin finding the plugin that provides loadMessages function
224
+ const loadMessagePlugin = _resolvedModules.plugins.find(
225
+ (plugin) => plugin.loadMessages !== undefined
226
+ )
227
+
228
+ // TODO #1844 this watcher needs to get pruned when we have a change in the configs which will trigger this again
182
229
  const fsWithWatcher = createNodeishFsWithWatcher({
183
230
  nodeishFs: nodeishFs,
231
+ // this message is called whenever a file changes that was read earlier by this filesystem
232
+ // - the plugin loads messages -> reads the file messages.json -> start watching on messages.json -> updateMessages
184
233
  updateMessages: () => {
185
- loadAndSetMessages(nodeishFs)
234
+ // preserving console.logs as comments pending #
235
+ debug("load messages because of a change in the message.json files")
236
+ loadMessagesViaPlugin(
237
+ fsWithWatcher,
238
+ messageLockDirPath,
239
+ messageStates,
240
+ messagesQuery,
241
+ settings()!, // NOTE we bang here - we don't expect the settings to become null during the livetime of a project
242
+ loadMessagePlugin
243
+ )
244
+ .catch((e) => setLoadMessagesViaPluginError(new PluginLoadMessagesError({ cause: e })))
245
+ .then(() => {
246
+ if (loadMessagesViaPluginError() !== undefined) {
247
+ setLoadMessagesViaPluginError(undefined)
248
+ }
249
+ })
186
250
  },
187
251
  })
188
252
 
189
- loadAndSetMessages(fsWithWatcher)
253
+ loadMessagesViaPlugin(
254
+ fsWithWatcher,
255
+ messageLockDirPath,
256
+ messageStates,
257
+ messagesQuery,
258
+ _settings,
259
+ loadMessagePlugin
260
+ )
261
+ .then(() => {
262
+ markInitAsComplete()
263
+ })
264
+ .catch((err) => {
265
+ markInitAsFailed(new PluginLoadMessagesError({ cause: err }))
266
+ })
190
267
  })
191
268
 
192
269
  // -- installed items ----------------------------------------------------
@@ -225,50 +302,114 @@ export async function loadProject(args: {
225
302
  const initializeError: Error | undefined = await initialized.catch((error) => error)
226
303
 
227
304
  const abortController = new AbortController()
228
- const hasWatcher = nodeishFs.watch("/", { signal: abortController.signal }) !== undefined
305
+ nodeishFs.watch("/", { signal: abortController.signal }) !== undefined
306
+
307
+ // map of message id => dispose function from createRoot for each message
308
+ const trackedMessages: Map<string, () => void> = new Map()
309
+ let initialSetup = true
310
+ // -- subscribe to all messages and write to files on signal -------------
311
+ createEffect(() => {
312
+ // debug("Outer createEffect")
313
+
314
+ const _resolvedModules = resolvedModules()
315
+ if (!_resolvedModules) return
316
+
317
+ const currentMessageIds = new Set(messagesQuery.includedMessageIds())
318
+ const deletedTrackedMessages = [...trackedMessages].filter(
319
+ (tracked) => !currentMessageIds.has(tracked[0])
320
+ )
321
+
322
+ const saveMessagesPlugin = _resolvedModules.plugins.find(
323
+ (plugin) => plugin.saveMessages !== undefined
324
+ )
325
+ const loadMessagesPlugin = _resolvedModules.plugins.find(
326
+ (plugin) => plugin.loadMessages !== undefined
327
+ )
328
+
329
+ for (const messageId of currentMessageIds) {
330
+ if (!trackedMessages!.has(messageId!)) {
331
+ // we create a new root to be able to cleanup an effect for a message that got deleted
332
+ createRoot((dispose) => {
333
+ createEffect(() => {
334
+ // debug("Inner createEffect", messageId)
335
+
336
+ const message = messagesQuery.get({ where: { id: messageId } })!
337
+ if (!message) {
338
+ return
339
+ }
340
+ if (!trackedMessages?.has(messageId)) {
341
+ // initial effect execution - add dispose function
342
+ trackedMessages?.set(messageId, dispose)
343
+ }
344
+
345
+ // don't trigger saves or set dirty flags during initial setup
346
+ if (!initialSetup) {
347
+ messageStates.messageDirtyFlags[message.id] = true
348
+ saveMessagesViaPlugin(
349
+ fs,
350
+ messageLockDirPath,
351
+ messageStates,
352
+ messagesQuery,
353
+ settings()!,
354
+ saveMessagesPlugin,
355
+ loadMessagesPlugin
356
+ )
357
+ .catch((e) =>
358
+ setSaveMessagesViaPluginError(new PluginSaveMessagesError({ cause: e }))
359
+ )
360
+ .then(() => {
361
+ if (saveMessagesViaPluginError() !== undefined) {
362
+ setSaveMessagesViaPluginError(undefined)
363
+ }
364
+ })
365
+ }
366
+ })
367
+ })
368
+ }
369
+ }
370
+
371
+ for (const deletedMessage of deletedTrackedMessages) {
372
+ const deletedMessageId = deletedMessage[0]
373
+
374
+ // call dispose to cleanup the effect
375
+ const messageEffectDisposeFunction = trackedMessages.get(deletedMessageId)
376
+ if (messageEffectDisposeFunction) {
377
+ messageEffectDisposeFunction()
378
+ trackedMessages.delete(deletedMessageId)
379
+ }
380
+ // mark the deleted message as dirty to force a save
381
+ messageStates.messageDirtyFlags[deletedMessageId] = true
382
+ }
383
+
384
+ if (deletedTrackedMessages.length > 0) {
385
+ // we keep track of the latest save within the loadProject call to await it at the end - this is not used in subsequetial upserts
386
+ saveMessagesViaPlugin(
387
+ nodeishFs,
388
+ messageLockDirPath,
389
+ messageStates,
390
+ messagesQuery,
391
+ settings()!,
392
+ saveMessagesPlugin,
393
+ loadMessagesPlugin
394
+ )
395
+ .catch((e) => setSaveMessagesViaPluginError(new PluginSaveMessagesError({ cause: e })))
396
+ .then(() => {
397
+ if (saveMessagesViaPluginError() !== undefined) {
398
+ setSaveMessagesViaPluginError(undefined)
399
+ }
400
+ })
401
+ }
402
+
403
+ initialSetup = false
404
+ })
229
405
 
230
- const messagesQuery = createMessagesQuery(() => messages() || [])
231
406
  const lintReportsQuery = createMessageLintReportsQuery(
232
407
  messagesQuery,
233
408
  settings as () => ProjectSettings,
234
409
  installedMessageLintRules,
235
- resolvedModules,
236
- hasWatcher
237
- )
238
-
239
- const debouncedSave = skipFirst(
240
- debounce(
241
- 500,
242
- async (newMessages) => {
243
- try {
244
- if (JSON.stringify(newMessages) !== JSON.stringify(messages())) {
245
- await resolvedModules()?.resolvedPluginApi.saveMessages({
246
- settings: settingsValue,
247
- messages: newMessages,
248
- })
249
- }
250
- } catch (err) {
251
- throw new PluginSaveMessagesError({
252
- cause: err,
253
- })
254
- }
255
- const abortController = new AbortController()
256
- if (
257
- newMessages.length !== 0 &&
258
- JSON.stringify(newMessages) !== JSON.stringify(messages()) &&
259
- nodeishFs.watch("/", { signal: abortController.signal }) !== undefined
260
- ) {
261
- setMessages(newMessages)
262
- }
263
- },
264
- { atBegin: false }
265
- )
410
+ resolvedModules
266
411
  )
267
412
 
268
- createEffect(() => {
269
- debouncedSave(messagesQuery.getAll())
270
- })
271
-
272
413
  /**
273
414
  * Utility to escape reactive tracking and avoid multiple calls to
274
415
  * the capture event.
@@ -309,6 +450,10 @@ export async function loadProject(args: {
309
450
  errors: createSubscribable(() => [
310
451
  ...(initializeError ? [initializeError] : []),
311
452
  ...(resolvedModules() ? resolvedModules()!.errors : []),
453
+ ...(loadMessagesViaPluginError() ? [loadMessagesViaPluginError()!] : []),
454
+ ...(saveMessagesViaPluginError() ? [saveMessagesViaPluginError()!] : []),
455
+ // have a query error exposed
456
+ //...(lintErrors() ?? []),
312
457
  ]),
313
458
  settings: createSubscribable(() => settings() as ProjectSettings),
314
459
  setSettings,
@@ -321,8 +466,6 @@ export async function loadProject(args: {
321
466
  })
322
467
  }
323
468
 
324
- //const x = {} as InlangProject
325
-
326
469
  // ------------------------------------------------------------------------------------------------
327
470
 
328
471
  const loadSettings = async (args: {
@@ -448,3 +591,455 @@ export function createSubscribable<T>(signal: () => T): Subscribable<T> {
448
591
  },
449
592
  })
450
593
  }
594
+
595
+ // --- serialization of loading / saving messages.
596
+ // 1. A plugin saveMessage call can not be called simultaniously to avoid side effects - its an async function not controlled by us
597
+ // 2. loading and saving must not run in "parallel".
598
+ // - json plugin exports into separate file per language.
599
+ // - saving a message in two different languages would lead to a write in de.json first
600
+ // - 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
601
+
602
+ /**
603
+ * Messsage that loads messages from a plugin - this method synchronizes with the saveMessage funciton.
604
+ * 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
605
+ * load and execute it at the end of this load. subsequential loads will not be queued but the same promise will be reused
606
+ *
607
+ * - NOTE: this means that the parameters used to load like settingsValue and loadPlugin might not take into account. this has to be refactored
608
+ * with the loadProject restructuring
609
+ * @param fs
610
+ * @param messagesQuery
611
+ * @param settingsValue
612
+ * @param loadPlugin
613
+ * @returns void - updates the files and messages in of the project in place
614
+ */
615
+ async function loadMessagesViaPlugin(
616
+ fs: NodeishFilesystem,
617
+ lockDirPath: string,
618
+ messageState: MessageState,
619
+ messagesQuery: InlangProject["query"]["messages"],
620
+ settingsValue: ProjectSettings,
621
+ loadPlugin: any
622
+ ) {
623
+ const experimentalAliases = !!settingsValue.experimental?.aliases
624
+
625
+ // loading is an asynchronous process - check if another load is in progress - queue this call if so
626
+ if (messageState.isLoading) {
627
+ if (!messageState.sheduledLoadMessagesViaPlugin) {
628
+ messageState.sheduledLoadMessagesViaPlugin = createAwaitable()
629
+ }
630
+ // another load will take place right after the current one - its goingt to be idempotent form the current requested one - don't reschedule
631
+ return messageState.sheduledLoadMessagesViaPlugin[0]
632
+ }
633
+
634
+ // set loading flag
635
+ messageState.isLoading = true
636
+ let lockTime: number | undefined = undefined
637
+
638
+ try {
639
+ lockTime = await acquireFileLock(fs as NodeishFilesystem, lockDirPath, "loadMessage")
640
+ const loadedMessages = await makeTrulyAsync(
641
+ loadPlugin.loadMessages({
642
+ settings: settingsValue,
643
+ nodeishFs: fs,
644
+ })
645
+ )
646
+
647
+ for (const loadedMessage of loadedMessages) {
648
+ const loadedMessageClone = structuredClone(loadedMessage)
649
+
650
+ const currentMessages = messagesQuery
651
+ .getAll()
652
+ // 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
653
+ .filter(
654
+ (message: any) =>
655
+ (experimentalAliases ? message.alias["default"] : message.id) === loadedMessage.id
656
+ )
657
+
658
+ if (currentMessages.length > 1) {
659
+ // NOTE: if we happen to find two messages witht the sam alias we throw for now
660
+ // - this could be the case if one edits the aliase manualy
661
+ throw new Error("more than one message with the same id or alias found ")
662
+ } else if (currentMessages.length === 1) {
663
+ // update message in place - leave message id and alias untouched
664
+ loadedMessageClone.alias = {} as any
665
+
666
+ // 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
667
+ if (experimentalAliases) {
668
+ loadedMessageClone.alias["default"] = loadedMessageClone.id
669
+ loadedMessageClone.id = currentMessages[0]!.id
670
+ }
671
+
672
+ // NOTE stringifyMessage encodes messages independent from key order!
673
+ const importedEnecoded = stringifyMessage(loadedMessageClone)
674
+
675
+ // NOTE could use hash instead of the whole object JSON to save memory...
676
+ if (messageState.messageLoadHash[loadedMessageClone.id] === importedEnecoded) {
677
+ debug("skipping upsert!")
678
+ continue
679
+ }
680
+
681
+ // This logic is preventing cycles - could also be handled if update api had a parameter for who triggered update
682
+ // e.g. when FS was updated, we don't need to write back to FS
683
+ // update is synchronous, so update effect will be triggered immediately
684
+ // 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
685
+ messagesQuery.update({ where: { id: loadedMessageClone.id }, data: loadedMessageClone })
686
+ // we load a fresh version - lets delete dirty flag that got created by the update
687
+ delete messageState.messageDirtyFlags[loadedMessageClone.id]
688
+ // NOTE could use hash instead of the whole object JSON to save memory...
689
+ messageState.messageLoadHash[loadedMessageClone.id] = importedEnecoded
690
+ } else {
691
+ // message with the given alias does not exist so far
692
+ loadedMessageClone.alias = {} as any
693
+ // TODO #1585 we have to map the id of the importedMessage to the alias - change when import mesage provides importedMessage.alias
694
+ if (experimentalAliases) {
695
+ loadedMessageClone.alias["default"] = loadedMessageClone.id
696
+
697
+ let currentOffset = 0
698
+ let messsageId: string | undefined
699
+ do {
700
+ messsageId = humanIdHash(loadedMessageClone.id, currentOffset)
701
+ if (messagesQuery.get({ where: { id: messsageId } })) {
702
+ currentOffset += 1
703
+ messsageId = undefined
704
+ }
705
+ } while (messsageId === undefined)
706
+
707
+ // create a humanId based on a hash of the alias
708
+ loadedMessageClone.id = messsageId
709
+ }
710
+
711
+ const importedEnecoded = stringifyMessage(loadedMessageClone)
712
+
713
+ // add the message - this will trigger an async file creation in the backgound!
714
+ messagesQuery.create({ data: loadedMessageClone })
715
+ // we load a fresh version - lets delete dirty flag that got created by the create method
716
+ delete messageState.messageDirtyFlags[loadedMessageClone.id]
717
+ messageState.messageLoadHash[loadedMessageClone.id] = importedEnecoded
718
+ }
719
+ }
720
+ await releaseLock(fs as NodeishFilesystem, lockDirPath, "loadMessage", lockTime)
721
+ lockTime = undefined
722
+
723
+ debug("loadMessagesViaPlugin: " + loadedMessages.length + " Messages processed ")
724
+
725
+ messageState.isLoading = false
726
+ } finally {
727
+ if (lockTime !== undefined) {
728
+ await releaseLock(fs as NodeishFilesystem, lockDirPath, "loadMessage", lockTime)
729
+ }
730
+ messageState.isLoading = false
731
+ }
732
+
733
+ const executingScheduledMessages = messageState.sheduledLoadMessagesViaPlugin
734
+ if (executingScheduledMessages) {
735
+ // a load has been requested during the load - executed it
736
+
737
+ // reset sheduling to except scheduling again
738
+ messageState.sheduledLoadMessagesViaPlugin = undefined
739
+
740
+ // recall load unawaited to allow stack to pop
741
+ loadMessagesViaPlugin(fs, lockDirPath, messageState, messagesQuery, settingsValue, loadPlugin)
742
+ .then(() => {
743
+ // resolve the scheduled load message promise
744
+ executingScheduledMessages[1]()
745
+ })
746
+ .catch((e: Error) => {
747
+ // reject the scheduled load message promise
748
+ executingScheduledMessages[2](e)
749
+ })
750
+ }
751
+ }
752
+
753
+ async function saveMessagesViaPlugin(
754
+ fs: NodeishFilesystem,
755
+ lockDirPath: string,
756
+ messageState: MessageState,
757
+ messagesQuery: InlangProject["query"]["messages"],
758
+ settingsValue: ProjectSettings,
759
+ savePlugin: any,
760
+ loadPlugin: any
761
+ ): Promise<void> {
762
+ // queue next save if we have a save ongoing
763
+ if (messageState.isSaving) {
764
+ if (!messageState.sheduledSaveMessages) {
765
+ messageState.sheduledSaveMessages = createAwaitable()
766
+ }
767
+
768
+ return messageState.sheduledSaveMessages[0]
769
+ }
770
+
771
+ // set isSavingFlag
772
+ messageState.isSaving = true
773
+
774
+ messageState.currentSaveMessagesViaPlugin = (async function () {
775
+ const saveMessageHashes = {} as { [messageId: string]: string }
776
+
777
+ // check if we have any dirty message - witho
778
+ if (Object.keys(messageState.messageDirtyFlags).length == 0) {
779
+ // nothing to save :-)
780
+ debug("save was skipped - no messages marked as dirty... build!")
781
+ messageState.isSaving = false
782
+ return
783
+ }
784
+
785
+ let messageDirtyFlagsBeforeSave: typeof messageState.messageDirtyFlags | undefined
786
+ let lockTime: number | undefined
787
+ try {
788
+ lockTime = await acquireFileLock(fs as NodeishFilesystem, lockDirPath, "saveMessage")
789
+
790
+ // since it may takes some time to acquire the lock we check if the save is required still (loadMessage could have happend in between)
791
+ if (Object.keys(messageState.messageDirtyFlags).length == 0) {
792
+ debug("save was skipped - no messages marked as dirty... releasing lock again")
793
+ messageState.isSaving = false
794
+ // release lock in finally block
795
+ return
796
+ }
797
+
798
+ const currentMessages = messagesQuery.getAll()
799
+
800
+ const messagesToExport: Message[] = []
801
+ for (const message of currentMessages) {
802
+ if (messageState.messageDirtyFlags[message.id]) {
803
+ const importedEnecoded = stringifyMessage(message)
804
+ // NOTE: could use hash instead of the whole object JSON to save memory...
805
+ saveMessageHashes[message.id] = importedEnecoded
806
+ }
807
+
808
+ const fixedExportMessage = { ...message }
809
+ // 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
810
+ if (settingsValue.experimental?.aliases) {
811
+ fixedExportMessage.id = fixedExportMessage.alias["default"] ?? fixedExportMessage.id
812
+ }
813
+
814
+ messagesToExport.push(fixedExportMessage)
815
+ }
816
+
817
+ // wa are about to save the messages to the plugin - reset all flags now
818
+ messageDirtyFlagsBeforeSave = { ...messageState.messageDirtyFlags }
819
+ messageState.messageDirtyFlags = {}
820
+
821
+ // NOTE: this assumes that the plugin will handle message ordering
822
+ await savePlugin.saveMessages({
823
+ settings: settingsValue,
824
+ messages: messagesToExport,
825
+ nodeishFs: fs,
826
+ })
827
+
828
+ for (const [messageId, messageHash] of Object.entries(saveMessageHashes)) {
829
+ messageState.messageLoadHash[messageId] = messageHash
830
+ }
831
+
832
+ if (lockTime !== undefined) {
833
+ await releaseLock(fs as NodeishFilesystem, lockDirPath, "saveMessage", lockTime)
834
+ lockTime = undefined
835
+ }
836
+
837
+ // if there is a queued load, allow it to take the lock before we run additional saves.
838
+ if (messageState.sheduledLoadMessagesViaPlugin) {
839
+ debug("saveMessagesViaPlugin calling queued loadMessagesViaPlugin to share lock")
840
+ await loadMessagesViaPlugin(
841
+ fs,
842
+ lockDirPath,
843
+ messageState,
844
+ messagesQuery,
845
+ settingsValue,
846
+ loadPlugin
847
+ )
848
+ }
849
+
850
+ messageState.isSaving = false
851
+ } catch (err) {
852
+ // something went wrong - add dirty flags again
853
+ if (messageDirtyFlagsBeforeSave !== undefined) {
854
+ for (const dirtyMessageId of Object.keys(messageDirtyFlagsBeforeSave)) {
855
+ messageState.messageDirtyFlags[dirtyMessageId] = true
856
+ }
857
+ }
858
+
859
+ if (lockTime !== undefined) {
860
+ await releaseLock(fs as NodeishFilesystem, lockDirPath, "saveMessage", lockTime)
861
+ lockTime = undefined
862
+ }
863
+ messageState.isSaving = false
864
+
865
+ // ok an error
866
+ throw new PluginSaveMessagesError({
867
+ cause: err,
868
+ })
869
+ } finally {
870
+ if (lockTime !== undefined) {
871
+ await releaseLock(fs as NodeishFilesystem, lockDirPath, "saveMessage", lockTime)
872
+ lockTime = undefined
873
+ }
874
+ messageState.isSaving = false
875
+ }
876
+ })()
877
+
878
+ await messageState.currentSaveMessagesViaPlugin
879
+
880
+ if (messageState.sheduledSaveMessages) {
881
+ const executingSheduledSaveMessages = messageState.sheduledSaveMessages
882
+ messageState.sheduledSaveMessages = undefined
883
+
884
+ saveMessagesViaPlugin(
885
+ fs,
886
+ lockDirPath,
887
+ messageState,
888
+ messagesQuery,
889
+ settingsValue,
890
+ savePlugin,
891
+ loadPlugin
892
+ )
893
+ .then(() => {
894
+ executingSheduledSaveMessages[1]()
895
+ })
896
+ .catch((e: Error) => {
897
+ executingSheduledSaveMessages[2](e)
898
+ })
899
+ }
900
+ }
901
+
902
+ const maxRetries = 5
903
+ const nProbes = 50
904
+ const probeInterval = 100
905
+ async function acquireFileLock(
906
+ fs: NodeishFilesystem,
907
+ lockDirPath: string,
908
+ lockOrigin: string,
909
+ tryCount: number = 0
910
+ ): Promise<number> {
911
+ if (tryCount > maxRetries) {
912
+ throw new Error(lockOrigin + " exceeded maximum Retries (5) to acquire lockfile " + tryCount)
913
+ }
914
+
915
+ try {
916
+ debug(lockOrigin + " tries to acquire a lockfile Retry Nr.: " + tryCount)
917
+ await fs.mkdir(lockDirPath)
918
+ const stats = await fs.stat(lockDirPath)
919
+ debug(lockOrigin + " acquired a lockfile Retry Nr.: " + tryCount)
920
+ return stats.mtimeMs
921
+ } catch (error: any) {
922
+ if (error.code !== "EEXIST") {
923
+ // we only expect the error that the file exists already (locked by other process)
924
+ throw error
925
+ }
926
+ }
927
+
928
+ let currentLockTime: number
929
+
930
+ try {
931
+ const stats = await fs.stat(lockDirPath)
932
+ currentLockTime = stats.mtimeMs
933
+ } catch (fstatError: any) {
934
+ if (fstatError.code === "ENOENT") {
935
+ // lock file seems to be gone :) - lets try again
936
+ debug(lockOrigin + " tryCount++ lock file seems to be gone :) - lets try again " + tryCount)
937
+ return acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1)
938
+ }
939
+ throw fstatError
940
+ }
941
+ debug(
942
+ lockOrigin +
943
+ " tries to acquire a lockfile - lock currently in use... starting probe phase " +
944
+ tryCount
945
+ )
946
+
947
+ return new Promise((resolve, reject) => {
948
+ let probeCounts = 0
949
+ const scheduleProbationTimeout = () => {
950
+ setTimeout(async () => {
951
+ probeCounts += 1
952
+ let lockFileStats: undefined | NodeishStats = undefined
953
+ try {
954
+ debug(
955
+ lockOrigin + " tries to acquire a lockfile - check if the lock is free now " + tryCount
956
+ )
957
+
958
+ // alright lets give it another try
959
+ lockFileStats = await fs.stat(lockDirPath)
960
+ } catch (fstatError: any) {
961
+ if (fstatError.code === "ENOENT") {
962
+ debug(
963
+ lockOrigin +
964
+ " tryCount++ in Promise - tries to acquire a lockfile - lock file seems to be free now - try to acquire " +
965
+ tryCount
966
+ )
967
+ const lock = acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1)
968
+ return resolve(lock)
969
+ }
970
+ return reject(fstatError)
971
+ }
972
+
973
+ // still the same locker! -
974
+ if (lockFileStats.mtimeMs === currentLockTime) {
975
+ if (probeCounts >= nProbes) {
976
+ // ok maximum lock time ran up (we waitetd nProbes * probeInterval) - we consider the lock to be stale
977
+ debug(
978
+ lockOrigin +
979
+ " tries to acquire a lockfile - lock not free - but stale lets drop it" +
980
+ tryCount
981
+ )
982
+ try {
983
+ await fs.rmdir(lockDirPath)
984
+ } catch (rmLockError: any) {
985
+ if (rmLockError.code === "ENOENT") {
986
+ // lock already gone?
987
+ // Option 1: The "stale process" decided to get rid of it
988
+ // Option 2: Another process acquiring the lock and detected a stale one as well
989
+ }
990
+ return reject(rmLockError)
991
+ }
992
+ try {
993
+ debug(
994
+ lockOrigin +
995
+ " tryCount++ same locker - try to acquire again after removing stale lock " +
996
+ tryCount
997
+ )
998
+ const lock = await acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1)
999
+ return resolve(lock)
1000
+ } catch (lockAquireException) {
1001
+ return reject(lockAquireException)
1002
+ }
1003
+ } else {
1004
+ // lets schedule a new probation
1005
+ return scheduleProbationTimeout()
1006
+ }
1007
+ } else {
1008
+ try {
1009
+ debug(lockOrigin + " tryCount++ different locker - try to acquire again " + tryCount)
1010
+ const lock = await acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1)
1011
+ return resolve(lock)
1012
+ } catch (error) {
1013
+ return reject(error)
1014
+ }
1015
+ }
1016
+ }, probeInterval)
1017
+ }
1018
+ scheduleProbationTimeout()
1019
+ })
1020
+ }
1021
+
1022
+ async function releaseLock(
1023
+ fs: NodeishFilesystem,
1024
+ lockDirPath: string,
1025
+ lockOrigin: string,
1026
+ lockTime: number
1027
+ ) {
1028
+ debug(lockOrigin + " releasing the lock ")
1029
+ try {
1030
+ const stats = await fs.stat(lockDirPath)
1031
+ if (stats.mtimeMs === lockTime) {
1032
+ // this can be corrupt as welll since the last getStat and the current a modification could have occured :-/
1033
+ await fs.rmdir(lockDirPath)
1034
+ }
1035
+ } catch (statError: any) {
1036
+ debug(lockOrigin + " couldn't release the lock")
1037
+ if (statError.code === "ENOENT") {
1038
+ // ok seeks like the log was released by someone else
1039
+ debug(lockOrigin + " WARNING - the lock was released by a different process")
1040
+ return
1041
+ }
1042
+ debug(statError)
1043
+ throw statError
1044
+ }
1045
+ }