@sixb/sync-worker 0.1.1 → 0.1.3

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.
@@ -1,5 +1,4 @@
1
1
  import {
2
- assertJsonValue,
3
2
  type BlobStorage,
4
3
  cloneJsonValue,
5
4
  type DatasetDefinition,
@@ -8,15 +7,20 @@ import {
8
7
  getDatasetRowValidationError,
9
8
  isFileRef,
10
9
  type JsonValue,
11
- type Logger,
12
10
  type MergeChange,
13
- type SyncDefinition,
14
11
  } from "@sixb/core"
15
- import { resolveLogsRuntime } from "@sixb/core/internal/logging"
12
+ import {
13
+ captureSixbFailure,
14
+ createSixbError,
15
+ isSixbError,
16
+ summarizeErrorMessage,
17
+ } from "@sixb/core/internal/errors"
18
+ import { resolveLoggingService } from "@sixb/core/internal/logging"
16
19
  import { type DatasetVersion, getDatasetMergeChangeValidationError } from "@sixb/core/lake-storage"
17
- import type { SyncRunFailure, SyncRunRecord } from "@sixb/core/storage"
18
- import { assertDatasetRow, normalizeReadResult, throwIfAborted } from "./normalize"
19
- import type { RunSyncJobInput, SyncRunResult, SyncWorkerContext } from "./types"
20
+ import { SYNC_RUN_FAILURE_CODES, type SyncRunRecord } from "@sixb/core/storage"
21
+ import { assertDatasetRow, throwIfAborted } from "./normalize"
22
+ import { readSyncValues, type SyncSourceValue } from "./source-read"
23
+ import type { RunSyncJobInput, SyncRunFinishedHandler, SyncRunResult } from "./types"
20
24
 
21
25
  export class SyncRunAlreadyStartedError extends Error {
22
26
  override readonly name = "SyncRunAlreadyStartedError"
@@ -26,19 +30,6 @@ export class SyncRunAlreadyStartedError extends Error {
26
30
  }
27
31
  }
28
32
 
29
- function toSyncRunFailure(error: unknown): SyncRunFailure {
30
- if (error instanceof Error) {
31
- return {
32
- name: error.name,
33
- message: error.message,
34
- }
35
- }
36
-
37
- return {
38
- message: String(error),
39
- }
40
- }
41
-
42
33
  function createBookkeepingError(options: {
43
34
  syncId: string
44
35
  runId: string
@@ -46,18 +37,64 @@ function createBookkeepingError(options: {
46
37
  cause: unknown
47
38
  }): Error {
48
39
  // The lake commit is already durable here, so we surface an explicit repair-needed error.
49
- return new Error(
40
+ return createSixbError(
41
+ "internal.unexpected",
50
42
  `[SixbSyncWorker] Sync '${options.syncId}' committed dataset version '${options.version.versionId}', but failed to finalize sync run '${options.runId}'. The dataset commit may already have succeeded and the sync run record may need repair.`,
51
- { cause: options.cause }
43
+ {
44
+ cause: options.cause,
45
+ details: {
46
+ syncId: options.syncId,
47
+ runId: options.runId,
48
+ datasetId: options.version.datasetId,
49
+ versionId: options.version.versionId,
50
+ },
51
+ }
52
52
  )
53
53
  }
54
54
 
55
- function requireFinishedAt(runId: string, finishedAt: Date | undefined): Date {
56
- if (finishedAt) {
57
- return finishedAt
55
+ function requireFinishedAt(input: {
56
+ readonly syncId: string
57
+ readonly runId: string
58
+ readonly finishedAt: Date | undefined
59
+ }): Date {
60
+ if (input.finishedAt) {
61
+ return input.finishedAt
58
62
  }
59
63
 
60
- throw new Error(`[SixbSyncWorker] Sync run '${runId}' finished without a finishedAt timestamp.`)
64
+ throw createSixbError(
65
+ "internal.unexpected",
66
+ `[SixbSyncWorker] Sync run '${input.runId}' finished without a finishedAt timestamp.`,
67
+ { details: { syncId: input.syncId, runId: input.runId } }
68
+ )
69
+ }
70
+
71
+ function translateSyncExecutionError(
72
+ error: unknown,
73
+ input: {
74
+ readonly syncId: string
75
+ readonly runId: string
76
+ readonly datasetId: string
77
+ }
78
+ ): unknown {
79
+ if (
80
+ isSixbError(error) &&
81
+ (error.code === "internal.unexpected" || error.code === "sync.execution_failed")
82
+ ) {
83
+ return error
84
+ }
85
+
86
+ return createSixbError(
87
+ "sync.execution_failed",
88
+ summarizeErrorMessage(error, "Sync execution failed."),
89
+ {
90
+ cause: error,
91
+ details: {
92
+ syncId: input.syncId,
93
+ runId: input.runId,
94
+ datasetId: input.datasetId,
95
+ },
96
+ }
97
+ )
61
98
  }
62
99
 
63
100
  async function verifyFileRef(options: {
@@ -130,121 +167,131 @@ function assertMergeChange(
130
167
  return value as MergeChange<DatasetRow, DatasetRow>
131
168
  }
132
169
 
133
- async function readSyncValues(options: {
134
- runtime: SyncWorkerContext
135
- sync: SyncDefinition
136
- signal: AbortSignal
137
- blobStorage: BlobStorage
138
- logger: Logger
139
- previousCheckpoint: JsonValue | undefined
140
- setCheckpoint(next: unknown): void
141
- }): Promise<AsyncIterable<unknown>> {
142
- const client = await options.runtime.connector(options.sync.connector)
143
- const readResult = await options.sync.read(client, {
144
- projectId: options.runtime.id,
145
- syncId: options.sync.id,
146
- signal: options.signal,
147
- blobs: options.blobStorage,
148
- logger: options.logger,
149
- checkpoint:
150
- options.previousCheckpoint !== undefined
151
- ? cloneJsonValue(options.previousCheckpoint)
152
- : undefined,
153
- setCheckpoint: options.setCheckpoint,
154
- })
155
- return normalizeReadResult(readResult, options.sync.id)
156
- }
157
-
158
170
  async function* validatedDatasetRows(options: {
159
- values: AsyncIterable<unknown>
171
+ values: AsyncIterable<SyncSourceValue>
160
172
  signal: AbortSignal
161
173
  blobStorage: BlobStorage
162
174
  syncId: string
175
+ runId: string
163
176
  dataset: DatasetDefinition
164
177
  onRead(): void
165
178
  }): AsyncIterable<DatasetRow> {
166
179
  let itemIndex = 0
167
- for await (const value of options.values) {
180
+ for await (const sourceValue of options.values) {
168
181
  throwIfAborted(options.signal)
169
182
  itemIndex += 1
170
183
 
171
- const row = assertDatasetRow(value, options.syncId, itemIndex)
172
- // Validate before handing rows to lake storage so sync failures include
173
- // the source item index; lake storage still re-validates as the final boundary.
174
- const validationError = getDatasetRowValidationError(row, options.dataset)
175
- if (validationError) {
176
- throw new Error(
177
- `[SixbSyncWorker] Sync '${options.syncId}' returned an invalid row at item ${itemIndex}. ${validationError}`
178
- )
179
- }
180
-
181
- // Lake storage validates fileRef shape; the worker owns existence checks against blob storage.
182
- await verifyRowFileRefs({
183
- blobStorage: options.blobStorage,
184
- syncId: options.syncId,
185
- dataset: options.dataset,
186
- row,
187
- itemIndex,
188
- })
184
+ let row: DatasetRow
185
+ try {
186
+ row = assertDatasetRow(sourceValue.value, options.syncId, itemIndex)
187
+ // Validate before handing rows to lake storage so sync failures include
188
+ // the source item index; lake storage still re-validates as the final boundary.
189
+ const validationError = getDatasetRowValidationError(row, options.dataset)
190
+ if (validationError) {
191
+ throw new Error(
192
+ `[SixbSyncWorker] Sync '${options.syncId}' returned an invalid row at item ${itemIndex}. ${validationError}`
193
+ )
194
+ }
189
195
 
190
- options.onRead()
196
+ // Lake storage validates fileRef shape; the worker owns existence checks against blob storage.
197
+ await verifyRowFileRefs({
198
+ blobStorage: options.blobStorage,
199
+ syncId: options.syncId,
200
+ dataset: options.dataset,
201
+ row,
202
+ itemIndex,
203
+ })
204
+ options.onRead()
205
+ } catch (error) {
206
+ throw sourceValidationError(error, sourceValue, options, itemIndex)
207
+ }
191
208
  yield row
192
209
  }
193
210
  }
194
211
 
195
212
  async function* validatedMergeChanges(options: {
196
- values: AsyncIterable<unknown>
213
+ values: AsyncIterable<SyncSourceValue>
197
214
  signal: AbortSignal
198
215
  blobStorage: BlobStorage
199
216
  syncId: string
217
+ runId: string
200
218
  dataset: DatasetDefinition
201
219
  onRead(): void
202
220
  }): AsyncIterable<MergeChange<DatasetRow, DatasetRow>> {
203
221
  let itemIndex = 0
204
- for await (const value of options.values) {
222
+ for await (const sourceValue of options.values) {
205
223
  throwIfAborted(options.signal)
206
224
  itemIndex += 1
207
- const mergeChange = assertMergeChange(value, options.syncId, options.dataset, itemIndex)
208
- if (mergeChange.kind === "upsert") {
209
- await verifyRowFileRefs({
210
- blobStorage: options.blobStorage,
211
- syncId: options.syncId,
212
- dataset: options.dataset,
213
- row: mergeChange.row,
214
- itemIndex,
215
- })
225
+ let mergeChange: MergeChange<DatasetRow, DatasetRow>
226
+ try {
227
+ mergeChange = assertMergeChange(sourceValue.value, options.syncId, options.dataset, itemIndex)
228
+ if (mergeChange.kind === "upsert") {
229
+ await verifyRowFileRefs({
230
+ blobStorage: options.blobStorage,
231
+ syncId: options.syncId,
232
+ dataset: options.dataset,
233
+ row: mergeChange.row,
234
+ itemIndex,
235
+ })
236
+ }
237
+ options.onRead()
238
+ } catch (error) {
239
+ throw sourceValidationError(error, sourceValue, options, itemIndex)
216
240
  }
217
- options.onRead()
218
241
  yield mergeChange
219
242
  }
220
243
  }
221
244
 
245
+ function sourceValidationError(
246
+ error: unknown,
247
+ sourceValue: SyncSourceValue,
248
+ options: { readonly syncId: string; readonly runId: string; readonly dataset: DatasetDefinition },
249
+ itemIndex: number
250
+ ): unknown {
251
+ const connection = sourceValue.connection
252
+ if (!connection) return error
253
+ const code =
254
+ isSixbError(error) && error.code === "internal.unexpected"
255
+ ? "internal.unexpected"
256
+ : "sync.execution_failed"
257
+ return createSixbError(code, summarizeErrorMessage(error, "Sync source validation failed."), {
258
+ cause: error,
259
+ details: {
260
+ syncId: options.syncId,
261
+ runId: options.runId,
262
+ datasetId: options.dataset.id,
263
+ itemIndex,
264
+ connectionId: connection.id,
265
+ accountId: connection.account.id,
266
+ },
267
+ })
268
+ }
269
+
222
270
  interface SyncCommitResult {
223
271
  readonly outcome: "created" | "unchanged"
224
272
  readonly version?: DatasetVersion
225
273
  }
226
274
 
227
275
  /**
228
- * Run one sync job end to end using a caller-supplied run id.
276
+ * Run one already-persisted Sync run end to end.
229
277
  *
230
- * The worker creates the operational sync-run record, streams source values into lake storage,
231
- * commits or reuses a dataset version when one exists, and then finalizes the run record. It does
232
- * not own scheduling, retries, or run-id generation.
278
+ * Dispatch owns identity and queueing. The worker only transitions the durable run from queued to
279
+ * running, streams source values, and records its terminal outcome.
233
280
  */
234
281
  export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult> {
235
- const { runtime, job } = input
236
- const signal = input.signal ?? new AbortController().signal
237
- const { syncRunsStorage, lakeStorage, blobStorage } = runtime
238
-
239
- const sync = runtime.getSyncById(job.syncId)
240
- if (!sync) {
241
- throw new Error(`[SixbSyncWorker] Unknown sync '${job.syncId}'.`)
282
+ const { runtime, run } = input
283
+ const job = {
284
+ id: run.id,
285
+ syncId: run.syncId,
286
+ expectedLatestVersionId: run.expectedLatestVersionId,
287
+ commitMessage: run.commitMessage,
242
288
  }
289
+ const signal = input.signal ?? new AbortController().signal
290
+ const { syncRunsStorage, lakeStorage, blobs: blobStorage } = runtime
243
291
 
244
- const dataset = runtime.getDatasetById(sync.target.dataset.id)
245
- if (!dataset) {
292
+ if (run.projectId !== runtime.id) {
246
293
  throw new Error(
247
- `[SixbSyncWorker] Sync '${sync.id}' targets unknown dataset '${sync.target.dataset.id}'.`
294
+ `[SixbSyncWorker] Sync run '${run.id}' belongs to project '${run.projectId}', not '${runtime.id}'.`
248
295
  )
249
296
  }
250
297
 
@@ -255,22 +302,17 @@ export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult>
255
302
  startedRun = await syncRunsStorage.start({
256
303
  projectId: runtime.id,
257
304
  id: job.id,
258
- syncId: sync.id,
259
- datasetId: dataset.id,
260
- mode: sync.config.mode,
261
- expectedLatestVersionId: job.expectedLatestVersionId,
262
- commitMessage: job.commitMessage,
263
305
  })
264
306
  } catch (error) {
265
307
  const existing = await syncRunsStorage.getById({ projectId: runtime.id, id: job.id })
266
- if (existing?.syncId === sync.id && existing.datasetId === dataset.id) {
308
+ if (existing?.syncId === run.syncId && existing.executionId === run.executionId) {
267
309
  throw new SyncRunAlreadyStartedError(existing)
268
310
  }
269
311
  throw error
270
312
  }
271
313
  await input.onRunStarted?.(startedRun)
272
314
 
273
- const logSession = resolveLogsRuntime(runtime.id, runtime.logs).startExecution({
315
+ const logSession = resolveLoggingService(runtime.id, runtime.logging).startExecution({
274
316
  kind: "sync",
275
317
  id: job.id,
276
318
  })
@@ -280,6 +322,23 @@ export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult>
280
322
  let committedVersion: DatasetVersion | undefined
281
323
 
282
324
  try {
325
+ const sync = runtime.syncs.getById(run.syncId)
326
+ if (!sync) {
327
+ throw new Error(`[SixbSyncWorker] Unknown sync '${run.syncId}'.`)
328
+ }
329
+ if (sync.target.dataset.id !== run.datasetId || sync.config.mode !== run.mode) {
330
+ throw new Error(
331
+ `[SixbSyncWorker] Sync run '${run.id}' no longer matches Sync '${sync.id}' configuration.`
332
+ )
333
+ }
334
+
335
+ const dataset = runtime.datasets.getById(run.datasetId)
336
+ if (!dataset) {
337
+ throw new Error(
338
+ `[SixbSyncWorker] Sync '${sync.id}' targets unknown dataset '${run.datasetId}'.`
339
+ )
340
+ }
341
+
283
342
  throwIfAborted(signal)
284
343
  await lakeStorage.createDataset(dataset)
285
344
 
@@ -303,13 +362,14 @@ export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult>
303
362
  readSyncValues({
304
363
  runtime,
305
364
  sync,
365
+ runId: job.id,
366
+ datasetId: dataset.id,
306
367
  signal,
307
368
  blobStorage,
308
369
  logger,
309
370
  previousCheckpoint,
310
371
  setCheckpoint(next) {
311
- assertJsonValue(next, `Sync '${sync.id}' checkpoint`)
312
- nextCheckpoint = cloneJsonValue(next)
372
+ nextCheckpoint = next === undefined ? undefined : cloneJsonValue(next)
313
373
  },
314
374
  })
315
375
  const onRead = () => {
@@ -334,6 +394,7 @@ export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult>
334
394
  signal,
335
395
  blobStorage,
336
396
  syncId: sync.id,
397
+ runId: job.id,
337
398
  dataset,
338
399
  onRead,
339
400
  })
@@ -362,6 +423,7 @@ export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult>
362
423
  signal,
363
424
  blobStorage,
364
425
  syncId: sync.id,
426
+ runId: job.id,
365
427
  dataset,
366
428
  onRead,
367
429
  })
@@ -383,14 +445,20 @@ export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult>
383
445
  : {}),
384
446
  checkpoint: nextCheckpoint,
385
447
  })
448
+ const finishedAt = requireFinishedAt({
449
+ syncId: sync.id,
450
+ runId: job.id,
451
+ finishedAt: finishedRun.finishedAt,
452
+ })
453
+ await notifyRunFinished(input.onRunFinished, finishedRun)
386
454
 
387
455
  return {
388
456
  id: job.id,
389
457
  syncId: sync.id,
390
458
  datasetId: dataset.id,
391
459
  mode: sync.config.mode,
392
- startedAt: startedRun.startedAt,
393
- finishedAt: requireFinishedAt(job.id, finishedRun.finishedAt),
460
+ startedAt: requireStartedAt(job.id, startedRun.startedAt),
461
+ finishedAt,
394
462
  rowsRead,
395
463
  ...(version ? { version } : {}),
396
464
  versionCreated: false,
@@ -409,7 +477,11 @@ export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult>
409
477
  const { outcome, version } = commitResult
410
478
  if (outcome === "created") {
411
479
  if (!version) {
412
- throw new Error(`[SixbSyncWorker] Sync '${sync.id}' created no dataset version.`)
480
+ throw createSixbError(
481
+ "internal.unexpected",
482
+ `[SixbSyncWorker] Sync '${sync.id}' created no dataset version.`,
483
+ { details: { syncId: sync.id, runId: job.id, datasetId: dataset.id } }
484
+ )
413
485
  }
414
486
  committedVersion = version
415
487
  }
@@ -438,13 +510,19 @@ export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult>
438
510
  throw error
439
511
  }
440
512
 
513
+ const finishedAt = requireFinishedAt({
514
+ syncId: sync.id,
515
+ runId: job.id,
516
+ finishedAt: finishedRun.finishedAt,
517
+ })
518
+ await notifyRunFinished(input.onRunFinished, finishedRun, committedVersion)
441
519
  const result = {
442
520
  id: job.id,
443
521
  syncId: sync.id,
444
522
  datasetId: dataset.id,
445
523
  mode: sync.config.mode,
446
- startedAt: startedRun.startedAt,
447
- finishedAt: requireFinishedAt(job.id, finishedRun.finishedAt),
524
+ startedAt: requireStartedAt(job.id, startedRun.startedAt),
525
+ finishedAt,
448
526
  rowsRead,
449
527
  }
450
528
  return version
@@ -457,14 +535,30 @@ export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult>
457
535
 
458
536
  const status = signal.aborted ? "cancelled" : "failed"
459
537
  try {
460
- const run = await syncRunsStorage.finish({
538
+ const failureError =
539
+ status === "failed"
540
+ ? translateSyncExecutionError(error, {
541
+ syncId: run.syncId,
542
+ runId: job.id,
543
+ datasetId: run.datasetId,
544
+ })
545
+ : error
546
+ const failure = captureSixbFailure(failureError, {
547
+ allowedCodes: SYNC_RUN_FAILURE_CODES,
548
+ defaultCode: status === "cancelled" ? "runtime.cancelled" : "internal.unexpected",
549
+ details: { syncId: run.syncId, runId: job.id, datasetId: run.datasetId },
550
+ })
551
+ const failedRun = await syncRunsStorage.finish({
461
552
  projectId: runtime.id,
462
553
  id: job.id,
463
554
  status,
464
555
  rowsRead,
465
- error: toSyncRunFailure(error),
556
+ error: failure,
466
557
  })
467
- if (status === "failed" && run.status === "failed") input.onRunFailed?.(error, run)
558
+ await notifyRunFinished(input.onRunFinished, failedRun)
559
+ if (status === "failed" && failedRun.status === "failed") {
560
+ input.onRunFailed?.(error, failedRun, failure)
561
+ }
468
562
  } catch {
469
563
  // The run did not transition to the requested terminal status.
470
564
  }
@@ -475,3 +569,26 @@ export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult>
475
569
  await logSession.flush()
476
570
  }
477
571
  }
572
+
573
+ async function notifyRunFinished(
574
+ handler: SyncRunFinishedHandler | undefined,
575
+ run: SyncRunRecord,
576
+ createdVersion?: DatasetVersion
577
+ ): Promise<void> {
578
+ try {
579
+ await handler?.(run, createdVersion)
580
+ } catch (error) {
581
+ // The built-in event log reports lost batches itself. Anything reaching here is a broken
582
+ // invariant in a custom lifecycle handler and must not change an already durable outcome.
583
+ console.error("[SixbSyncWorker] Sync run lifecycle handler failed:", error)
584
+ }
585
+ }
586
+
587
+ function requireStartedAt(runId: string, startedAt: Date | undefined): Date {
588
+ if (startedAt) return startedAt
589
+ throw createSixbError(
590
+ "internal.unexpected",
591
+ `[SixbSyncWorker] Sync run '${runId}' started without a startedAt timestamp.`,
592
+ { details: { runId } }
593
+ )
594
+ }