@inlang/sdk 0.26.5 → 0.28.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 +5 -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 +474 -39
  22. package/dist/loadProject.test.js +93 -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 +16 -7
  42. package/src/adapter/solidAdapter.test.ts +76 -4
  43. package/src/api.ts +6 -0
  44. package/src/createMessageLintReportsQuery.ts +47 -35
  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 +108 -14
  52. package/src/loadProject.ts +657 -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 ----------------------------------------------------
@@ -204,6 +281,7 @@ export async function loadProject(args: {
204
281
  "Unknown module. You stumbled on a bug in inlang's source code. Please open an issue.",
205
282
  // default to warning, see https://github.com/opral/monorepo/issues/1254
206
283
  level: settingsValue["messageLintRuleLevels"]?.[rule.id] ?? "warning",
284
+ settingsSchema: rule.settingsSchema,
207
285
  } satisfies InstalledMessageLintRule)
208
286
  ) satisfies Array<InstalledMessageLintRule>
209
287
  }
@@ -217,6 +295,7 @@ export async function loadProject(args: {
217
295
  module:
218
296
  resolvedModules()?.meta.find((m) => m.id.includes(plugin.id))?.module ??
219
297
  "Unknown module. You stumbled on a bug in inlang's source code. Please open an issue.",
298
+ settingsSchema: plugin.settingsSchema,
220
299
  })) satisfies Array<InstalledPlugin>
221
300
  }
222
301
 
@@ -225,50 +304,114 @@ export async function loadProject(args: {
225
304
  const initializeError: Error | undefined = await initialized.catch((error) => error)
226
305
 
227
306
  const abortController = new AbortController()
228
- const hasWatcher = nodeishFs.watch("/", { signal: abortController.signal }) !== undefined
307
+ nodeishFs.watch("/", { signal: abortController.signal }) !== undefined
308
+
309
+ // map of message id => dispose function from createRoot for each message
310
+ const trackedMessages: Map<string, () => void> = new Map()
311
+ let initialSetup = true
312
+ // -- subscribe to all messages and write to files on signal -------------
313
+ createEffect(() => {
314
+ // debug("Outer createEffect")
315
+
316
+ const _resolvedModules = resolvedModules()
317
+ if (!_resolvedModules) return
318
+
319
+ const currentMessageIds = new Set(messagesQuery.includedMessageIds())
320
+ const deletedTrackedMessages = [...trackedMessages].filter(
321
+ (tracked) => !currentMessageIds.has(tracked[0])
322
+ )
323
+
324
+ const saveMessagesPlugin = _resolvedModules.plugins.find(
325
+ (plugin) => plugin.saveMessages !== undefined
326
+ )
327
+ const loadMessagesPlugin = _resolvedModules.plugins.find(
328
+ (plugin) => plugin.loadMessages !== undefined
329
+ )
330
+
331
+ for (const messageId of currentMessageIds) {
332
+ if (!trackedMessages!.has(messageId!)) {
333
+ // we create a new root to be able to cleanup an effect for a message that got deleted
334
+ createRoot((dispose) => {
335
+ createEffect(() => {
336
+ // debug("Inner createEffect", messageId)
337
+
338
+ const message = messagesQuery.get({ where: { id: messageId } })!
339
+ if (!message) {
340
+ return
341
+ }
342
+ if (!trackedMessages?.has(messageId)) {
343
+ // initial effect execution - add dispose function
344
+ trackedMessages?.set(messageId, dispose)
345
+ }
346
+
347
+ // don't trigger saves or set dirty flags during initial setup
348
+ if (!initialSetup) {
349
+ messageStates.messageDirtyFlags[message.id] = true
350
+ saveMessagesViaPlugin(
351
+ fs,
352
+ messageLockDirPath,
353
+ messageStates,
354
+ messagesQuery,
355
+ settings()!,
356
+ saveMessagesPlugin,
357
+ loadMessagesPlugin
358
+ )
359
+ .catch((e) =>
360
+ setSaveMessagesViaPluginError(new PluginSaveMessagesError({ cause: e }))
361
+ )
362
+ .then(() => {
363
+ if (saveMessagesViaPluginError() !== undefined) {
364
+ setSaveMessagesViaPluginError(undefined)
365
+ }
366
+ })
367
+ }
368
+ })
369
+ })
370
+ }
371
+ }
372
+
373
+ for (const deletedMessage of deletedTrackedMessages) {
374
+ const deletedMessageId = deletedMessage[0]
375
+
376
+ // call dispose to cleanup the effect
377
+ const messageEffectDisposeFunction = trackedMessages.get(deletedMessageId)
378
+ if (messageEffectDisposeFunction) {
379
+ messageEffectDisposeFunction()
380
+ trackedMessages.delete(deletedMessageId)
381
+ }
382
+ // mark the deleted message as dirty to force a save
383
+ messageStates.messageDirtyFlags[deletedMessageId] = true
384
+ }
385
+
386
+ if (deletedTrackedMessages.length > 0) {
387
+ // we keep track of the latest save within the loadProject call to await it at the end - this is not used in subsequetial upserts
388
+ saveMessagesViaPlugin(
389
+ nodeishFs,
390
+ messageLockDirPath,
391
+ messageStates,
392
+ messagesQuery,
393
+ settings()!,
394
+ saveMessagesPlugin,
395
+ loadMessagesPlugin
396
+ )
397
+ .catch((e) => setSaveMessagesViaPluginError(new PluginSaveMessagesError({ cause: e })))
398
+ .then(() => {
399
+ if (saveMessagesViaPluginError() !== undefined) {
400
+ setSaveMessagesViaPluginError(undefined)
401
+ }
402
+ })
403
+ }
404
+
405
+ initialSetup = false
406
+ })
229
407
 
230
- const messagesQuery = createMessagesQuery(() => messages() || [])
231
408
  const lintReportsQuery = createMessageLintReportsQuery(
232
409
  messagesQuery,
233
410
  settings as () => ProjectSettings,
234
411
  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
- )
412
+ resolvedModules
266
413
  )
267
414
 
268
- createEffect(() => {
269
- debouncedSave(messagesQuery.getAll())
270
- })
271
-
272
415
  /**
273
416
  * Utility to escape reactive tracking and avoid multiple calls to
274
417
  * the capture event.
@@ -309,6 +452,10 @@ export async function loadProject(args: {
309
452
  errors: createSubscribable(() => [
310
453
  ...(initializeError ? [initializeError] : []),
311
454
  ...(resolvedModules() ? resolvedModules()!.errors : []),
455
+ ...(loadMessagesViaPluginError() ? [loadMessagesViaPluginError()!] : []),
456
+ ...(saveMessagesViaPluginError() ? [saveMessagesViaPluginError()!] : []),
457
+ // have a query error exposed
458
+ //...(lintErrors() ?? []),
312
459
  ]),
313
460
  settings: createSubscribable(() => settings() as ProjectSettings),
314
461
  setSettings,
@@ -321,8 +468,6 @@ export async function loadProject(args: {
321
468
  })
322
469
  }
323
470
 
324
- //const x = {} as InlangProject
325
-
326
471
  // ------------------------------------------------------------------------------------------------
327
472
 
328
473
  const loadSettings = async (args: {
@@ -448,3 +593,455 @@ export function createSubscribable<T>(signal: () => T): Subscribable<T> {
448
593
  },
449
594
  })
450
595
  }
596
+
597
+ // --- serialization of loading / saving messages.
598
+ // 1. A plugin saveMessage call can not be called simultaniously to avoid side effects - its an async function not controlled by us
599
+ // 2. loading and saving must not run in "parallel".
600
+ // - json plugin exports into separate file per language.
601
+ // - saving a message in two different languages would lead to a write in de.json first
602
+ // - 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
603
+
604
+ /**
605
+ * Messsage that loads messages from a plugin - this method synchronizes with the saveMessage funciton.
606
+ * 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
607
+ * load and execute it at the end of this load. subsequential loads will not be queued but the same promise will be reused
608
+ *
609
+ * - NOTE: this means that the parameters used to load like settingsValue and loadPlugin might not take into account. this has to be refactored
610
+ * with the loadProject restructuring
611
+ * @param fs
612
+ * @param messagesQuery
613
+ * @param settingsValue
614
+ * @param loadPlugin
615
+ * @returns void - updates the files and messages in of the project in place
616
+ */
617
+ async function loadMessagesViaPlugin(
618
+ fs: NodeishFilesystem,
619
+ lockDirPath: string,
620
+ messageState: MessageState,
621
+ messagesQuery: InlangProject["query"]["messages"],
622
+ settingsValue: ProjectSettings,
623
+ loadPlugin: any
624
+ ) {
625
+ const experimentalAliases = !!settingsValue.experimental?.aliases
626
+
627
+ // loading is an asynchronous process - check if another load is in progress - queue this call if so
628
+ if (messageState.isLoading) {
629
+ if (!messageState.sheduledLoadMessagesViaPlugin) {
630
+ messageState.sheduledLoadMessagesViaPlugin = createAwaitable()
631
+ }
632
+ // another load will take place right after the current one - its goingt to be idempotent form the current requested one - don't reschedule
633
+ return messageState.sheduledLoadMessagesViaPlugin[0]
634
+ }
635
+
636
+ // set loading flag
637
+ messageState.isLoading = true
638
+ let lockTime: number | undefined = undefined
639
+
640
+ try {
641
+ lockTime = await acquireFileLock(fs as NodeishFilesystem, lockDirPath, "loadMessage")
642
+ const loadedMessages = await makeTrulyAsync(
643
+ loadPlugin.loadMessages({
644
+ settings: settingsValue,
645
+ nodeishFs: fs,
646
+ })
647
+ )
648
+
649
+ for (const loadedMessage of loadedMessages) {
650
+ const loadedMessageClone = structuredClone(loadedMessage)
651
+
652
+ const currentMessages = messagesQuery
653
+ .getAll()
654
+ // 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
655
+ .filter(
656
+ (message: any) =>
657
+ (experimentalAliases ? message.alias["default"] : message.id) === loadedMessage.id
658
+ )
659
+
660
+ if (currentMessages.length > 1) {
661
+ // NOTE: if we happen to find two messages witht the sam alias we throw for now
662
+ // - this could be the case if one edits the aliase manualy
663
+ throw new Error("more than one message with the same id or alias found ")
664
+ } else if (currentMessages.length === 1) {
665
+ // update message in place - leave message id and alias untouched
666
+ loadedMessageClone.alias = {} as any
667
+
668
+ // 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
669
+ if (experimentalAliases) {
670
+ loadedMessageClone.alias["default"] = loadedMessageClone.id
671
+ loadedMessageClone.id = currentMessages[0]!.id
672
+ }
673
+
674
+ // NOTE stringifyMessage encodes messages independent from key order!
675
+ const importedEnecoded = stringifyMessage(loadedMessageClone)
676
+
677
+ // NOTE could use hash instead of the whole object JSON to save memory...
678
+ if (messageState.messageLoadHash[loadedMessageClone.id] === importedEnecoded) {
679
+ debug("skipping upsert!")
680
+ continue
681
+ }
682
+
683
+ // This logic is preventing cycles - could also be handled if update api had a parameter for who triggered update
684
+ // e.g. when FS was updated, we don't need to write back to FS
685
+ // update is synchronous, so update effect will be triggered immediately
686
+ // 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
687
+ messagesQuery.update({ where: { id: loadedMessageClone.id }, data: loadedMessageClone })
688
+ // we load a fresh version - lets delete dirty flag that got created by the update
689
+ delete messageState.messageDirtyFlags[loadedMessageClone.id]
690
+ // NOTE could use hash instead of the whole object JSON to save memory...
691
+ messageState.messageLoadHash[loadedMessageClone.id] = importedEnecoded
692
+ } else {
693
+ // message with the given alias does not exist so far
694
+ loadedMessageClone.alias = {} as any
695
+ // TODO #1585 we have to map the id of the importedMessage to the alias - change when import mesage provides importedMessage.alias
696
+ if (experimentalAliases) {
697
+ loadedMessageClone.alias["default"] = loadedMessageClone.id
698
+
699
+ let currentOffset = 0
700
+ let messsageId: string | undefined
701
+ do {
702
+ messsageId = humanIdHash(loadedMessageClone.id, currentOffset)
703
+ if (messagesQuery.get({ where: { id: messsageId } })) {
704
+ currentOffset += 1
705
+ messsageId = undefined
706
+ }
707
+ } while (messsageId === undefined)
708
+
709
+ // create a humanId based on a hash of the alias
710
+ loadedMessageClone.id = messsageId
711
+ }
712
+
713
+ const importedEnecoded = stringifyMessage(loadedMessageClone)
714
+
715
+ // add the message - this will trigger an async file creation in the backgound!
716
+ messagesQuery.create({ data: loadedMessageClone })
717
+ // we load a fresh version - lets delete dirty flag that got created by the create method
718
+ delete messageState.messageDirtyFlags[loadedMessageClone.id]
719
+ messageState.messageLoadHash[loadedMessageClone.id] = importedEnecoded
720
+ }
721
+ }
722
+ await releaseLock(fs as NodeishFilesystem, lockDirPath, "loadMessage", lockTime)
723
+ lockTime = undefined
724
+
725
+ debug("loadMessagesViaPlugin: " + loadedMessages.length + " Messages processed ")
726
+
727
+ messageState.isLoading = false
728
+ } finally {
729
+ if (lockTime !== undefined) {
730
+ await releaseLock(fs as NodeishFilesystem, lockDirPath, "loadMessage", lockTime)
731
+ }
732
+ messageState.isLoading = false
733
+ }
734
+
735
+ const executingScheduledMessages = messageState.sheduledLoadMessagesViaPlugin
736
+ if (executingScheduledMessages) {
737
+ // a load has been requested during the load - executed it
738
+
739
+ // reset sheduling to except scheduling again
740
+ messageState.sheduledLoadMessagesViaPlugin = undefined
741
+
742
+ // recall load unawaited to allow stack to pop
743
+ loadMessagesViaPlugin(fs, lockDirPath, messageState, messagesQuery, settingsValue, loadPlugin)
744
+ .then(() => {
745
+ // resolve the scheduled load message promise
746
+ executingScheduledMessages[1]()
747
+ })
748
+ .catch((e: Error) => {
749
+ // reject the scheduled load message promise
750
+ executingScheduledMessages[2](e)
751
+ })
752
+ }
753
+ }
754
+
755
+ async function saveMessagesViaPlugin(
756
+ fs: NodeishFilesystem,
757
+ lockDirPath: string,
758
+ messageState: MessageState,
759
+ messagesQuery: InlangProject["query"]["messages"],
760
+ settingsValue: ProjectSettings,
761
+ savePlugin: any,
762
+ loadPlugin: any
763
+ ): Promise<void> {
764
+ // queue next save if we have a save ongoing
765
+ if (messageState.isSaving) {
766
+ if (!messageState.sheduledSaveMessages) {
767
+ messageState.sheduledSaveMessages = createAwaitable()
768
+ }
769
+
770
+ return messageState.sheduledSaveMessages[0]
771
+ }
772
+
773
+ // set isSavingFlag
774
+ messageState.isSaving = true
775
+
776
+ messageState.currentSaveMessagesViaPlugin = (async function () {
777
+ const saveMessageHashes = {} as { [messageId: string]: string }
778
+
779
+ // check if we have any dirty message - witho
780
+ if (Object.keys(messageState.messageDirtyFlags).length == 0) {
781
+ // nothing to save :-)
782
+ debug("save was skipped - no messages marked as dirty... build!")
783
+ messageState.isSaving = false
784
+ return
785
+ }
786
+
787
+ let messageDirtyFlagsBeforeSave: typeof messageState.messageDirtyFlags | undefined
788
+ let lockTime: number | undefined
789
+ try {
790
+ lockTime = await acquireFileLock(fs as NodeishFilesystem, lockDirPath, "saveMessage")
791
+
792
+ // since it may takes some time to acquire the lock we check if the save is required still (loadMessage could have happend in between)
793
+ if (Object.keys(messageState.messageDirtyFlags).length == 0) {
794
+ debug("save was skipped - no messages marked as dirty... releasing lock again")
795
+ messageState.isSaving = false
796
+ // release lock in finally block
797
+ return
798
+ }
799
+
800
+ const currentMessages = messagesQuery.getAll()
801
+
802
+ const messagesToExport: Message[] = []
803
+ for (const message of currentMessages) {
804
+ if (messageState.messageDirtyFlags[message.id]) {
805
+ const importedEnecoded = stringifyMessage(message)
806
+ // NOTE: could use hash instead of the whole object JSON to save memory...
807
+ saveMessageHashes[message.id] = importedEnecoded
808
+ }
809
+
810
+ const fixedExportMessage = { ...message }
811
+ // 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
812
+ if (settingsValue.experimental?.aliases) {
813
+ fixedExportMessage.id = fixedExportMessage.alias["default"] ?? fixedExportMessage.id
814
+ }
815
+
816
+ messagesToExport.push(fixedExportMessage)
817
+ }
818
+
819
+ // wa are about to save the messages to the plugin - reset all flags now
820
+ messageDirtyFlagsBeforeSave = { ...messageState.messageDirtyFlags }
821
+ messageState.messageDirtyFlags = {}
822
+
823
+ // NOTE: this assumes that the plugin will handle message ordering
824
+ await savePlugin.saveMessages({
825
+ settings: settingsValue,
826
+ messages: messagesToExport,
827
+ nodeishFs: fs,
828
+ })
829
+
830
+ for (const [messageId, messageHash] of Object.entries(saveMessageHashes)) {
831
+ messageState.messageLoadHash[messageId] = messageHash
832
+ }
833
+
834
+ if (lockTime !== undefined) {
835
+ await releaseLock(fs as NodeishFilesystem, lockDirPath, "saveMessage", lockTime)
836
+ lockTime = undefined
837
+ }
838
+
839
+ // if there is a queued load, allow it to take the lock before we run additional saves.
840
+ if (messageState.sheduledLoadMessagesViaPlugin) {
841
+ debug("saveMessagesViaPlugin calling queued loadMessagesViaPlugin to share lock")
842
+ await loadMessagesViaPlugin(
843
+ fs,
844
+ lockDirPath,
845
+ messageState,
846
+ messagesQuery,
847
+ settingsValue,
848
+ loadPlugin
849
+ )
850
+ }
851
+
852
+ messageState.isSaving = false
853
+ } catch (err) {
854
+ // something went wrong - add dirty flags again
855
+ if (messageDirtyFlagsBeforeSave !== undefined) {
856
+ for (const dirtyMessageId of Object.keys(messageDirtyFlagsBeforeSave)) {
857
+ messageState.messageDirtyFlags[dirtyMessageId] = true
858
+ }
859
+ }
860
+
861
+ if (lockTime !== undefined) {
862
+ await releaseLock(fs as NodeishFilesystem, lockDirPath, "saveMessage", lockTime)
863
+ lockTime = undefined
864
+ }
865
+ messageState.isSaving = false
866
+
867
+ // ok an error
868
+ throw new PluginSaveMessagesError({
869
+ cause: err,
870
+ })
871
+ } finally {
872
+ if (lockTime !== undefined) {
873
+ await releaseLock(fs as NodeishFilesystem, lockDirPath, "saveMessage", lockTime)
874
+ lockTime = undefined
875
+ }
876
+ messageState.isSaving = false
877
+ }
878
+ })()
879
+
880
+ await messageState.currentSaveMessagesViaPlugin
881
+
882
+ if (messageState.sheduledSaveMessages) {
883
+ const executingSheduledSaveMessages = messageState.sheduledSaveMessages
884
+ messageState.sheduledSaveMessages = undefined
885
+
886
+ saveMessagesViaPlugin(
887
+ fs,
888
+ lockDirPath,
889
+ messageState,
890
+ messagesQuery,
891
+ settingsValue,
892
+ savePlugin,
893
+ loadPlugin
894
+ )
895
+ .then(() => {
896
+ executingSheduledSaveMessages[1]()
897
+ })
898
+ .catch((e: Error) => {
899
+ executingSheduledSaveMessages[2](e)
900
+ })
901
+ }
902
+ }
903
+
904
+ const maxRetries = 5
905
+ const nProbes = 50
906
+ const probeInterval = 100
907
+ async function acquireFileLock(
908
+ fs: NodeishFilesystem,
909
+ lockDirPath: string,
910
+ lockOrigin: string,
911
+ tryCount: number = 0
912
+ ): Promise<number> {
913
+ if (tryCount > maxRetries) {
914
+ throw new Error(lockOrigin + " exceeded maximum Retries (5) to acquire lockfile " + tryCount)
915
+ }
916
+
917
+ try {
918
+ debug(lockOrigin + " tries to acquire a lockfile Retry Nr.: " + tryCount)
919
+ await fs.mkdir(lockDirPath)
920
+ const stats = await fs.stat(lockDirPath)
921
+ debug(lockOrigin + " acquired a lockfile Retry Nr.: " + tryCount)
922
+ return stats.mtimeMs
923
+ } catch (error: any) {
924
+ if (error.code !== "EEXIST") {
925
+ // we only expect the error that the file exists already (locked by other process)
926
+ throw error
927
+ }
928
+ }
929
+
930
+ let currentLockTime: number
931
+
932
+ try {
933
+ const stats = await fs.stat(lockDirPath)
934
+ currentLockTime = stats.mtimeMs
935
+ } catch (fstatError: any) {
936
+ if (fstatError.code === "ENOENT") {
937
+ // lock file seems to be gone :) - lets try again
938
+ debug(lockOrigin + " tryCount++ lock file seems to be gone :) - lets try again " + tryCount)
939
+ return acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1)
940
+ }
941
+ throw fstatError
942
+ }
943
+ debug(
944
+ lockOrigin +
945
+ " tries to acquire a lockfile - lock currently in use... starting probe phase " +
946
+ tryCount
947
+ )
948
+
949
+ return new Promise((resolve, reject) => {
950
+ let probeCounts = 0
951
+ const scheduleProbationTimeout = () => {
952
+ setTimeout(async () => {
953
+ probeCounts += 1
954
+ let lockFileStats: undefined | NodeishStats = undefined
955
+ try {
956
+ debug(
957
+ lockOrigin + " tries to acquire a lockfile - check if the lock is free now " + tryCount
958
+ )
959
+
960
+ // alright lets give it another try
961
+ lockFileStats = await fs.stat(lockDirPath)
962
+ } catch (fstatError: any) {
963
+ if (fstatError.code === "ENOENT") {
964
+ debug(
965
+ lockOrigin +
966
+ " tryCount++ in Promise - tries to acquire a lockfile - lock file seems to be free now - try to acquire " +
967
+ tryCount
968
+ )
969
+ const lock = acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1)
970
+ return resolve(lock)
971
+ }
972
+ return reject(fstatError)
973
+ }
974
+
975
+ // still the same locker! -
976
+ if (lockFileStats.mtimeMs === currentLockTime) {
977
+ if (probeCounts >= nProbes) {
978
+ // ok maximum lock time ran up (we waitetd nProbes * probeInterval) - we consider the lock to be stale
979
+ debug(
980
+ lockOrigin +
981
+ " tries to acquire a lockfile - lock not free - but stale lets drop it" +
982
+ tryCount
983
+ )
984
+ try {
985
+ await fs.rmdir(lockDirPath)
986
+ } catch (rmLockError: any) {
987
+ if (rmLockError.code === "ENOENT") {
988
+ // lock already gone?
989
+ // Option 1: The "stale process" decided to get rid of it
990
+ // Option 2: Another process acquiring the lock and detected a stale one as well
991
+ }
992
+ return reject(rmLockError)
993
+ }
994
+ try {
995
+ debug(
996
+ lockOrigin +
997
+ " tryCount++ same locker - try to acquire again after removing stale lock " +
998
+ tryCount
999
+ )
1000
+ const lock = await acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1)
1001
+ return resolve(lock)
1002
+ } catch (lockAquireException) {
1003
+ return reject(lockAquireException)
1004
+ }
1005
+ } else {
1006
+ // lets schedule a new probation
1007
+ return scheduleProbationTimeout()
1008
+ }
1009
+ } else {
1010
+ try {
1011
+ debug(lockOrigin + " tryCount++ different locker - try to acquire again " + tryCount)
1012
+ const lock = await acquireFileLock(fs, lockDirPath, lockOrigin, tryCount + 1)
1013
+ return resolve(lock)
1014
+ } catch (error) {
1015
+ return reject(error)
1016
+ }
1017
+ }
1018
+ }, probeInterval)
1019
+ }
1020
+ scheduleProbationTimeout()
1021
+ })
1022
+ }
1023
+
1024
+ async function releaseLock(
1025
+ fs: NodeishFilesystem,
1026
+ lockDirPath: string,
1027
+ lockOrigin: string,
1028
+ lockTime: number
1029
+ ) {
1030
+ debug(lockOrigin + " releasing the lock ")
1031
+ try {
1032
+ const stats = await fs.stat(lockDirPath)
1033
+ if (stats.mtimeMs === lockTime) {
1034
+ // this can be corrupt as welll since the last getStat and the current a modification could have occured :-/
1035
+ await fs.rmdir(lockDirPath)
1036
+ }
1037
+ } catch (statError: any) {
1038
+ debug(lockOrigin + " couldn't release the lock")
1039
+ if (statError.code === "ENOENT") {
1040
+ // ok seeks like the log was released by someone else
1041
+ debug(lockOrigin + " WARNING - the lock was released by a different process")
1042
+ return
1043
+ }
1044
+ debug(statError)
1045
+ throw statError
1046
+ }
1047
+ }