@sixb/sync-worker 0.1.0 → 0.1.2

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.
package/dist/index.js CHANGED
@@ -1,16 +1,28 @@
1
1
  // @bun
2
2
  // src/worker.ts
3
3
  import { reportRunFailure } from "@sixb/core/internal/error-reporting";
4
+ import {
5
+ bindDurablePrimitiveExecution
6
+ } from "@sixb/core/internal/primitive-execution";
7
+ import { resolveSyncConnectorSources } from "@sixb/core/internal/syncs";
4
8
  import { QueueWorker } from "@sixb/core/internal/workers";
9
+ import { SYNC_RUN_FAILURE_CODES as SYNC_RUN_FAILURE_CODES2 } from "@sixb/core/storage";
5
10
 
6
11
  // src/run-sync-job.ts
7
12
  import {
8
- assertJsonValue,
9
- cloneJsonValue,
13
+ cloneJsonValue as cloneJsonValue3,
10
14
  getDatasetRowValidationError,
11
15
  isFileRef
12
16
  } from "@sixb/core";
13
- import { resolveLogsRuntime } from "@sixb/core/internal/logging";
17
+ import {
18
+ captureSixbFailure,
19
+ createSixbError as createSixbError3,
20
+ isSixbError,
21
+ summarizeErrorMessage as summarizeErrorMessage2
22
+ } from "@sixb/core/internal/errors";
23
+ import { resolveLoggingService } from "@sixb/core/internal/logging";
24
+ import { getDatasetMergeChangeValidationError } from "@sixb/core/lake-storage";
25
+ import { SYNC_RUN_FAILURE_CODES } from "@sixb/core/storage";
14
26
 
15
27
  // src/normalize.ts
16
28
  function isPlainObject(value) {
@@ -40,30 +52,326 @@ function throwIfAborted(signal) {
40
52
  throw toAbortError(signal);
41
53
  }
42
54
  }
55
+ async function runAbortable(signal, run) {
56
+ throwIfAborted(signal);
57
+ let rejectAborted;
58
+ const aborted = new Promise((_resolve, reject) => {
59
+ rejectAborted = reject;
60
+ });
61
+ const onAbort = () => rejectAborted?.(toAbortError(signal));
62
+ signal.addEventListener("abort", onAbort, { once: true });
63
+ const operation = Promise.resolve().then(run);
64
+ operation.catch(() => {});
65
+ try {
66
+ return await Promise.race([operation, aborted]);
67
+ } finally {
68
+ signal.removeEventListener("abort", onAbort);
69
+ }
70
+ }
43
71
  function assertDatasetRow(value, syncId, itemIndex) {
44
72
  if (isPlainObject(value)) {
45
73
  return value;
46
74
  }
47
75
  throw new Error(`[SixbSyncWorker] Sync '${syncId}' returned an invalid row at item ${itemIndex}. Dataset rows must be plain objects.`);
48
76
  }
49
- async function* normalizeReadResult(readResult, syncId) {
77
+ async function* normalizeReadResult(readResult, syncId, signal) {
50
78
  if (isAsyncIterable(readResult)) {
51
- yield* readResult;
79
+ const iterator = readResult[Symbol.asyncIterator]();
80
+ let completed = false;
81
+ try {
82
+ while (true) {
83
+ const next = await runAbortable(signal, () => iterator.next());
84
+ if (next.done) {
85
+ completed = true;
86
+ return;
87
+ }
88
+ yield next.value;
89
+ }
90
+ } finally {
91
+ if (!completed && iterator.return) {
92
+ const closing = Promise.resolve().then(() => iterator.return?.());
93
+ if (signal.aborted)
94
+ closing.catch(() => {});
95
+ else
96
+ await closing;
97
+ }
98
+ }
52
99
  return;
53
100
  }
54
101
  if (isIterable(readResult)) {
55
102
  for (const item of readResult) {
103
+ throwIfAborted(signal);
56
104
  yield item;
57
105
  }
58
106
  return;
59
107
  }
60
108
  if (isPlainObject(readResult)) {
109
+ throwIfAborted(signal);
61
110
  yield readResult;
62
111
  return;
63
112
  }
64
113
  throw new Error(`[SixbSyncWorker] Sync '${syncId}' returned an unsupported read result. Expected a row object, iterable, or async iterable.`);
65
114
  }
66
115
 
116
+ // src/source-read.ts
117
+ import {
118
+ assertJsonValue as assertJsonValue2,
119
+ cloneJsonValue as cloneJsonValue2
120
+ } from "@sixb/core";
121
+ import { isOAuthConnectorDefinition } from "@sixb/core/internal/connector-connections";
122
+ import { createSixbError as createSixbError2, summarizeErrorMessage } from "@sixb/core/internal/errors";
123
+
124
+ // src/checkpoints.ts
125
+ import {
126
+ assertJsonValue,
127
+ cloneJsonValue,
128
+ isJsonValue
129
+ } from "@sixb/core";
130
+ import { createSixbError } from "@sixb/core/internal/errors";
131
+ var SYNC_CHECKPOINT_KIND = "sync_checkpoint";
132
+ var SYNC_CHECKPOINT_VERSION = 1;
133
+ function createSyncCheckpointCodec(options) {
134
+ return {
135
+ read(value) {
136
+ if (value === undefined)
137
+ return;
138
+ if (!isSyncCheckpoint(value)) {
139
+ if (options.strategy === "single")
140
+ return cloneJsonValue(value);
141
+ throw incompatibleCheckpoint(options, "format");
142
+ }
143
+ if (value.version !== SYNC_CHECKPOINT_VERSION) {
144
+ throw incompatibleCheckpoint(options, "version");
145
+ }
146
+ if (value.connectorId !== options.connectorId) {
147
+ throw incompatibleCheckpoint(options, "connector");
148
+ }
149
+ if (value.strategy !== options.strategy) {
150
+ throw incompatibleCheckpoint(options, "strategy");
151
+ }
152
+ if (!("value" in value) || !isJsonValue(value.value)) {
153
+ throw invalidFrameworkCheckpoint(options.syncId);
154
+ }
155
+ return cloneJsonValue(value.value);
156
+ },
157
+ serialize(value) {
158
+ const envelope = {
159
+ kind: SYNC_CHECKPOINT_KIND,
160
+ version: SYNC_CHECKPOINT_VERSION,
161
+ connectorId: options.connectorId,
162
+ strategy: options.strategy,
163
+ value: cloneJsonValue(value)
164
+ };
165
+ assertJsonValue(envelope, "Sync checkpoint envelope");
166
+ return envelope;
167
+ }
168
+ };
169
+ }
170
+
171
+ class ConnectionCheckpoints {
172
+ entries;
173
+ constructor(entries) {
174
+ this.entries = entries;
175
+ }
176
+ static from(syncId, value) {
177
+ if (value === undefined)
178
+ return new ConnectionCheckpoints(new Map);
179
+ if (!isConnectionCheckpoint(value))
180
+ throw invalidConnectionCheckpoint(syncId);
181
+ const entries = new Map;
182
+ for (const candidate of value.entries) {
183
+ if (!isRecord(candidate) || typeof candidate.connectionId !== "string" || !candidate.connectionId.trim() || typeof candidate.accountId !== "string" || !candidate.accountId.trim() || entries.has(candidate.connectionId)) {
184
+ throw invalidConnectionCheckpoint(syncId);
185
+ }
186
+ if ("checkpoint" in candidate && !isJsonValue(candidate.checkpoint)) {
187
+ throw invalidConnectionCheckpoint(syncId);
188
+ }
189
+ entries.set(candidate.connectionId, {
190
+ connectionId: candidate.connectionId,
191
+ accountId: candidate.accountId,
192
+ ...candidate.checkpoint === undefined ? {} : { checkpoint: cloneJsonValue(candidate.checkpoint) }
193
+ });
194
+ }
195
+ return new ConnectionCheckpoints(entries);
196
+ }
197
+ reconcile(connections) {
198
+ for (const connection of connections) {
199
+ const existing = this.entries.get(connection.id);
200
+ if (existing && existing.accountId !== connection.account.id) {
201
+ this.entries.delete(connection.id);
202
+ }
203
+ }
204
+ }
205
+ get(connection) {
206
+ const entry = this.entries.get(connection.id);
207
+ if (entry?.accountId !== connection.account.id || entry.checkpoint === undefined) {
208
+ return;
209
+ }
210
+ return cloneJsonValue(entry.checkpoint);
211
+ }
212
+ set(connection, checkpoint) {
213
+ this.entries.set(connection.id, {
214
+ connectionId: connection.id,
215
+ accountId: connection.account.id,
216
+ checkpoint: cloneJsonValue(checkpoint)
217
+ });
218
+ }
219
+ serialize() {
220
+ const value = {
221
+ entries: [...this.entries.values()].sort((left, right) => left.connectionId.localeCompare(right.connectionId)).map((entry) => ({
222
+ connectionId: entry.connectionId,
223
+ accountId: entry.accountId,
224
+ ...entry.checkpoint === undefined ? {} : { checkpoint: cloneJsonValue(entry.checkpoint) }
225
+ }))
226
+ };
227
+ assertJsonValue(value, "Managed connector Sync checkpoint");
228
+ return value;
229
+ }
230
+ }
231
+ function incompatibleCheckpoint(options, reason) {
232
+ return createSixbError("sync.execution_failed", `[SixbSyncWorker] Sync '${options.syncId}' has a checkpoint incompatible with connector '${options.connectorId}'. Use a new Sync id to reset its ingestion state.`, {
233
+ details: {
234
+ syncId: options.syncId,
235
+ connectorId: options.connectorId,
236
+ reason: `checkpoint_${reason}`
237
+ }
238
+ });
239
+ }
240
+ function invalidFrameworkCheckpoint(syncId) {
241
+ return createSixbError("internal.unexpected", `[SixbSyncWorker] Sync '${syncId}' has an invalid checkpoint envelope.`, { details: { syncId } });
242
+ }
243
+ function invalidConnectionCheckpoint(syncId) {
244
+ return createSixbError("internal.unexpected", `[SixbSyncWorker] Sync '${syncId}' has an invalid managed connector checkpoint.`, { details: { syncId } });
245
+ }
246
+ function isSyncCheckpoint(value) {
247
+ return isRecord(value) && value.kind === SYNC_CHECKPOINT_KIND;
248
+ }
249
+ function isConnectionCheckpoint(value) {
250
+ return isRecord(value) && Array.isArray(value.entries);
251
+ }
252
+ function isRecord(value) {
253
+ return typeof value === "object" && value !== null && !Array.isArray(value);
254
+ }
255
+
256
+ // src/source-read.ts
257
+ async function readSyncValues(options) {
258
+ const sources = await options.runtime.connectorSources.list(options.sync.connector);
259
+ if (!isOAuthConnectorDefinition(options.sync.connector)) {
260
+ if (sources.length !== 1 || sources[0]?.connection !== undefined) {
261
+ throw sourceInvariant(options.sync.id, "Static connectors must resolve exactly one source.");
262
+ }
263
+ const checkpointCodec2 = createSyncCheckpointCodec({
264
+ syncId: options.sync.id,
265
+ connectorId: options.sync.connector.id,
266
+ strategy: "single"
267
+ });
268
+ return readStaticSource(options, sources[0], checkpointCodec2);
269
+ }
270
+ const connectionIds = new Set;
271
+ const managedSources = sources.map((source) => {
272
+ if (!source.connection) {
273
+ throw sourceInvariant(options.sync.id, "OAuth connector sources must include connection metadata.");
274
+ }
275
+ const connection = source.connection;
276
+ if (connection.connectorId !== options.sync.connector.id) {
277
+ throw sourceInvariant(options.sync.id, `Connection '${connection.id}' belongs to connector '${connection.connectorId}', not '${options.sync.connector.id}'.`);
278
+ }
279
+ if (connectionIds.has(connection.id)) {
280
+ throw sourceInvariant(options.sync.id, `Connection '${connection.id}' was resolved twice.`);
281
+ }
282
+ connectionIds.add(connection.id);
283
+ return {
284
+ connection,
285
+ connect: (signal) => source.connect(signal)
286
+ };
287
+ });
288
+ managedSources.sort((left, right) => left.connection.id.localeCompare(right.connection.id));
289
+ const checkpointCodec = createSyncCheckpointCodec({
290
+ syncId: options.sync.id,
291
+ connectorId: options.sync.connector.id,
292
+ strategy: "connections"
293
+ });
294
+ const checkpoints = ConnectionCheckpoints.from(options.sync.id, checkpointCodec.read(options.previousCheckpoint));
295
+ checkpoints.reconcile(managedSources.map((source) => source.connection));
296
+ const storeCheckpoint = () => options.setCheckpoint(checkpointCodec.serialize(checkpoints.serialize()));
297
+ storeCheckpoint();
298
+ return readManagedSources(options, managedSources, checkpoints, storeCheckpoint);
299
+ }
300
+ async function readStaticSource(options, source, checkpointCodec) {
301
+ const previousCheckpoint = checkpointCodec.read(options.previousCheckpoint);
302
+ if (previousCheckpoint !== undefined) {
303
+ options.setCheckpoint(checkpointCodec.serialize(previousCheckpoint));
304
+ }
305
+ const client = await runAbortable(options.signal, () => source.connect(options.signal));
306
+ throwIfAborted(options.signal);
307
+ const readResult = await runAbortable(options.signal, () => options.sync.read(client, {
308
+ projectId: options.runtime.id,
309
+ syncId: options.sync.id,
310
+ signal: options.signal,
311
+ blobs: options.blobStorage,
312
+ logger: options.logger,
313
+ checkpoint: previousCheckpoint === undefined ? undefined : cloneJsonValue2(previousCheckpoint),
314
+ setCheckpoint(next) {
315
+ assertJsonValue2(next, `Sync '${options.sync.id}' checkpoint`);
316
+ options.setCheckpoint(checkpointCodec.serialize(cloneJsonValue2(next)));
317
+ }
318
+ }));
319
+ return sourceValues(normalizeReadResult(readResult, options.sync.id, options.signal));
320
+ }
321
+ async function* readManagedSources(options, sources, checkpoints, storeCheckpoint) {
322
+ for (const source of sources) {
323
+ yield* readManagedSource(options, source, checkpoints, storeCheckpoint);
324
+ }
325
+ }
326
+ async function* readManagedSource(options, source, checkpoints, storeCheckpoint) {
327
+ const { connection } = source;
328
+ try {
329
+ throwIfAborted(options.signal);
330
+ const client = await runAbortable(options.signal, () => source.connect(options.signal));
331
+ throwIfAborted(options.signal);
332
+ const previous = checkpoints.get(connection);
333
+ const readResult = await runAbortable(options.signal, () => options.sync.read(client, {
334
+ projectId: options.runtime.id,
335
+ syncId: options.sync.id,
336
+ signal: options.signal,
337
+ blobs: options.blobStorage,
338
+ logger: options.logger,
339
+ connection,
340
+ checkpoint: previous === undefined ? undefined : cloneJsonValue2(previous),
341
+ setCheckpoint(next) {
342
+ assertJsonValue2(next, `Sync '${options.sync.id}' connection '${connection.id}' checkpoint`);
343
+ checkpoints.set(connection, cloneJsonValue2(next));
344
+ storeCheckpoint();
345
+ }
346
+ }));
347
+ for await (const value of normalizeReadResult(readResult, options.sync.id, options.signal)) {
348
+ yield { value, connection };
349
+ }
350
+ } catch (error) {
351
+ if (options.signal.aborted)
352
+ throw error;
353
+ throw createSixbError2("sync.execution_failed", summarizeErrorMessage(error, "Managed connector Sync source failed."), {
354
+ cause: error,
355
+ details: {
356
+ syncId: options.sync.id,
357
+ runId: options.runId,
358
+ datasetId: options.datasetId,
359
+ connectionId: connection.id,
360
+ accountId: connection.account.id
361
+ }
362
+ });
363
+ }
364
+ }
365
+ function sourceInvariant(syncId, message) {
366
+ return createSixbError2("internal.unexpected", `[SixbSyncWorker] ${message}`, {
367
+ details: { syncId }
368
+ });
369
+ }
370
+ async function* sourceValues(values) {
371
+ for await (const value of values)
372
+ yield { value };
373
+ }
374
+
67
375
  // src/run-sync-job.ts
68
376
  class SyncRunAlreadyStartedError extends Error {
69
377
  run;
@@ -73,25 +381,35 @@ class SyncRunAlreadyStartedError extends Error {
73
381
  this.run = run;
74
382
  }
75
383
  }
76
- function toSyncRunFailure(error) {
77
- if (error instanceof Error) {
78
- return {
79
- name: error.name,
80
- message: error.message
81
- };
82
- }
83
- return {
84
- message: String(error)
85
- };
86
- }
87
384
  function createBookkeepingError(options) {
88
- return new Error(`[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.`, { cause: options.cause });
385
+ return createSixbError3("internal.unexpected", `[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.`, {
386
+ cause: options.cause,
387
+ details: {
388
+ syncId: options.syncId,
389
+ runId: options.runId,
390
+ datasetId: options.version.datasetId,
391
+ versionId: options.version.versionId
392
+ }
393
+ });
89
394
  }
90
- function requireFinishedAt(runId, finishedAt) {
91
- if (finishedAt) {
92
- return finishedAt;
395
+ function requireFinishedAt(input) {
396
+ if (input.finishedAt) {
397
+ return input.finishedAt;
93
398
  }
94
- throw new Error(`[SixbSyncWorker] Sync run '${runId}' finished without a finishedAt timestamp.`);
399
+ throw createSixbError3("internal.unexpected", `[SixbSyncWorker] Sync run '${input.runId}' finished without a finishedAt timestamp.`, { details: { syncId: input.syncId, runId: input.runId } });
400
+ }
401
+ function translateSyncExecutionError(error, input) {
402
+ if (isSixbError(error) && (error.code === "internal.unexpected" || error.code === "sync.execution_failed")) {
403
+ return error;
404
+ }
405
+ return createSixbError3("sync.execution_failed", summarizeErrorMessage2(error, "Sync execution failed."), {
406
+ cause: error,
407
+ details: {
408
+ syncId: input.syncId,
409
+ runId: input.runId,
410
+ datasetId: input.datasetId
411
+ }
412
+ });
95
413
  }
96
414
  async function verifyFileRef(options) {
97
415
  const blobInfo = await options.blobStorage.stat(options.fileRef.blobId);
@@ -122,47 +440,128 @@ async function verifyRowFileRefs(options) {
122
440
  });
123
441
  }
124
442
  }
443
+ function assertMergeChange(value, syncId, dataset, itemIndex) {
444
+ const validationError = getDatasetMergeChangeValidationError(value, dataset);
445
+ if (validationError) {
446
+ throw new Error(`[SixbSyncWorker] Sync '${syncId}' returned an invalid merge change at item ${itemIndex}. ${validationError}`);
447
+ }
448
+ return value;
449
+ }
450
+ async function* validatedDatasetRows(options) {
451
+ let itemIndex = 0;
452
+ for await (const sourceValue of options.values) {
453
+ throwIfAborted(options.signal);
454
+ itemIndex += 1;
455
+ let row;
456
+ try {
457
+ row = assertDatasetRow(sourceValue.value, options.syncId, itemIndex);
458
+ const validationError = getDatasetRowValidationError(row, options.dataset);
459
+ if (validationError) {
460
+ throw new Error(`[SixbSyncWorker] Sync '${options.syncId}' returned an invalid row at item ${itemIndex}. ${validationError}`);
461
+ }
462
+ await verifyRowFileRefs({
463
+ blobStorage: options.blobStorage,
464
+ syncId: options.syncId,
465
+ dataset: options.dataset,
466
+ row,
467
+ itemIndex
468
+ });
469
+ options.onRead();
470
+ } catch (error) {
471
+ throw sourceValidationError(error, sourceValue, options, itemIndex);
472
+ }
473
+ yield row;
474
+ }
475
+ }
476
+ async function* validatedMergeChanges(options) {
477
+ let itemIndex = 0;
478
+ for await (const sourceValue of options.values) {
479
+ throwIfAborted(options.signal);
480
+ itemIndex += 1;
481
+ let mergeChange;
482
+ try {
483
+ mergeChange = assertMergeChange(sourceValue.value, options.syncId, options.dataset, itemIndex);
484
+ if (mergeChange.kind === "upsert") {
485
+ await verifyRowFileRefs({
486
+ blobStorage: options.blobStorage,
487
+ syncId: options.syncId,
488
+ dataset: options.dataset,
489
+ row: mergeChange.row,
490
+ itemIndex
491
+ });
492
+ }
493
+ options.onRead();
494
+ } catch (error) {
495
+ throw sourceValidationError(error, sourceValue, options, itemIndex);
496
+ }
497
+ yield mergeChange;
498
+ }
499
+ }
500
+ function sourceValidationError(error, sourceValue, options, itemIndex) {
501
+ const connection = sourceValue.connection;
502
+ if (!connection)
503
+ return error;
504
+ const code = isSixbError(error) && error.code === "internal.unexpected" ? "internal.unexpected" : "sync.execution_failed";
505
+ return createSixbError3(code, summarizeErrorMessage2(error, "Sync source validation failed."), {
506
+ cause: error,
507
+ details: {
508
+ syncId: options.syncId,
509
+ runId: options.runId,
510
+ datasetId: options.dataset.id,
511
+ itemIndex,
512
+ connectionId: connection.id,
513
+ accountId: connection.account.id
514
+ }
515
+ });
516
+ }
125
517
  async function runSyncJob(input) {
126
- const { runtime, job } = input;
518
+ const { runtime, run } = input;
519
+ const job = {
520
+ id: run.id,
521
+ syncId: run.syncId,
522
+ expectedLatestVersionId: run.expectedLatestVersionId,
523
+ commitMessage: run.commitMessage
524
+ };
127
525
  const signal = input.signal ?? new AbortController().signal;
128
- const { syncRunsStorage, lakeStorage, blobStorage } = runtime;
129
- const sync = runtime.getSyncById(job.syncId);
130
- if (!sync) {
131
- throw new Error(`[SixbSyncWorker] Unknown sync '${job.syncId}'.`);
132
- }
133
- const dataset = runtime.getDatasetById(sync.target.dataset.id);
134
- if (!dataset) {
135
- throw new Error(`[SixbSyncWorker] Sync '${sync.id}' targets unknown dataset '${sync.target.dataset.id}'.`);
526
+ const { syncRunsStorage, lakeStorage, blobs: blobStorage } = runtime;
527
+ if (run.projectId !== runtime.id) {
528
+ throw new Error(`[SixbSyncWorker] Sync run '${run.id}' belongs to project '${run.projectId}', not '${runtime.id}'.`);
136
529
  }
137
530
  throwIfAborted(signal);
138
531
  let startedRun;
139
532
  try {
140
533
  startedRun = await syncRunsStorage.start({
141
534
  projectId: runtime.id,
142
- id: job.id,
143
- syncId: sync.id,
144
- datasetId: dataset.id,
145
- mode: sync.config.mode,
146
- expectedLatestVersionId: job.expectedLatestVersionId,
147
- commitMessage: job.commitMessage
535
+ id: job.id
148
536
  });
149
537
  } catch (error) {
150
538
  const existing = await syncRunsStorage.getById({ projectId: runtime.id, id: job.id });
151
- if (existing?.syncId === sync.id && existing.datasetId === dataset.id) {
539
+ if (existing?.syncId === run.syncId && existing.executionId === run.executionId) {
152
540
  throw new SyncRunAlreadyStartedError(existing);
153
541
  }
154
542
  throw error;
155
543
  }
156
544
  await input.onRunStarted?.(startedRun);
157
- const logSession = resolveLogsRuntime(runtime.id, runtime.logs).startExecution({
545
+ const logSession = resolveLoggingService(runtime.id, runtime.logging).startExecution({
158
546
  kind: "sync",
159
547
  id: job.id
160
548
  });
161
549
  const logger = logSession.logger;
162
- let write;
550
+ let abortWrite;
163
551
  let rowsRead = 0;
164
552
  let committedVersion;
165
553
  try {
554
+ const sync = runtime.syncs.getById(run.syncId);
555
+ if (!sync) {
556
+ throw new Error(`[SixbSyncWorker] Unknown sync '${run.syncId}'.`);
557
+ }
558
+ if (sync.target.dataset.id !== run.datasetId || sync.config.mode !== run.mode) {
559
+ throw new Error(`[SixbSyncWorker] Sync run '${run.id}' no longer matches Sync '${sync.id}' configuration.`);
560
+ }
561
+ const dataset = runtime.datasets.getById(run.datasetId);
562
+ if (!dataset) {
563
+ throw new Error(`[SixbSyncWorker] Sync '${sync.id}' targets unknown dataset '${run.datasetId}'.`);
564
+ }
166
565
  throwIfAborted(signal);
167
566
  await lakeStorage.createDataset(dataset);
168
567
  const latestSuccessfulRuns = await syncRunsStorage.list({
@@ -173,83 +572,120 @@ async function runSyncJob(input) {
173
572
  order: "desc"
174
573
  });
175
574
  const previousCheckpoint = latestSuccessfulRuns.runs[0]?.checkpoint;
176
- let nextCheckpoint = previousCheckpoint !== undefined ? cloneJsonValue(previousCheckpoint) : undefined;
177
- const client = await runtime.connector(sync.connector);
178
- const readResult = await sync.read(client, {
179
- projectId: runtime.id,
180
- syncId: sync.id,
575
+ let nextCheckpoint = previousCheckpoint !== undefined ? cloneJsonValue3(previousCheckpoint) : undefined;
576
+ const producer = {
577
+ kind: "sync",
578
+ id: sync.id,
579
+ runId: job.id
580
+ };
581
+ const readValues = () => readSyncValues({
582
+ runtime,
583
+ sync,
584
+ runId: job.id,
585
+ datasetId: dataset.id,
181
586
  signal,
182
- blobs: blobStorage,
587
+ blobStorage,
183
588
  logger,
184
- checkpoint: previousCheckpoint !== undefined ? cloneJsonValue(previousCheckpoint) : undefined,
589
+ previousCheckpoint,
185
590
  setCheckpoint(next) {
186
- assertJsonValue(next, `Sync '${sync.id}' checkpoint`);
187
- nextCheckpoint = cloneJsonValue(next);
591
+ nextCheckpoint = next === undefined ? undefined : cloneJsonValue3(next);
188
592
  }
189
593
  });
190
- const rows = normalizeReadResult(readResult, sync.id);
191
- throwIfAborted(signal);
192
- write = await lakeStorage.beginWrite({
193
- dataset,
194
- mode: sync.config.mode,
195
- producer: {
196
- kind: "sync",
197
- id: sync.id,
198
- runId: job.id
199
- }
200
- });
201
- await write.writeRows(async function* () {
202
- let itemIndex = 0;
203
- for await (const value of rows) {
204
- throwIfAborted(signal);
205
- itemIndex += 1;
206
- const row = assertDatasetRow(value, sync.id, itemIndex);
207
- const validationError = getDatasetRowValidationError(row, dataset);
208
- if (validationError) {
209
- throw new Error(`[SixbSyncWorker] Sync '${sync.id}' returned an invalid row at item ${itemIndex}. ${validationError}`);
210
- }
211
- await verifyRowFileRefs({
212
- blobStorage,
213
- syncId: sync.id,
214
- dataset,
215
- row,
216
- itemIndex
217
- });
218
- rowsRead += 1;
219
- yield row;
220
- }
221
- }());
222
- throwIfAborted(signal);
223
- if (sync.config.mode === "append" && rowsRead === 0) {
224
- await write.abort();
225
- write = undefined;
226
- const version2 = await lakeStorage.getLatestVersion(dataset.id);
227
- const finishedRun2 = await syncRunsStorage.finish({
228
- projectId: runtime.id,
229
- id: job.id,
230
- status: "succeeded",
231
- rowsRead,
232
- ...version2 ? { output: { datasetId: version2.datasetId, versionId: version2.versionId } } : {},
233
- checkpoint: nextCheckpoint
594
+ const onRead = () => {
595
+ rowsRead += 1;
596
+ };
597
+ const commitMessage = job.commitMessage ?? `sync ${sync.id} run ${job.id}`;
598
+ let commitResult;
599
+ if (sync.config.mode === "merge") {
600
+ const mergeWrite = await lakeStorage.beginMerge({
601
+ dataset,
602
+ expectedLatestVersionId: job.expectedLatestVersionId,
603
+ producer
234
604
  });
235
- return {
236
- id: job.id,
605
+ abortWrite = () => mergeWrite.abort();
606
+ const values = await readValues();
607
+ throwIfAborted(signal);
608
+ await mergeWrite.writeChanges(validatedMergeChanges({
609
+ values,
610
+ signal,
611
+ blobStorage,
237
612
  syncId: sync.id,
238
- datasetId: dataset.id,
239
- mode: sync.config.mode,
240
- startedAt: startedRun.startedAt,
241
- finishedAt: requireFinishedAt(job.id, finishedRun2.finishedAt),
242
- rowsRead,
243
- ...version2 ? { version: version2 } : {},
244
- versionCreated: false
613
+ runId: job.id,
614
+ dataset,
615
+ onRead
616
+ }));
617
+ throwIfAborted(signal);
618
+ const commit = await mergeWrite.commit({ commitMessage });
619
+ abortWrite = undefined;
620
+ commitResult = {
621
+ outcome: commit.outcome,
622
+ ...commit.version ? { version: commit.version } : {}
245
623
  };
624
+ } else {
625
+ const values = await readValues();
626
+ throwIfAborted(signal);
627
+ const rowWrite = await lakeStorage.beginWrite({
628
+ dataset,
629
+ mode: sync.config.mode,
630
+ producer
631
+ });
632
+ abortWrite = () => rowWrite.abort();
633
+ await rowWrite.writeRows(validatedDatasetRows({
634
+ values,
635
+ signal,
636
+ blobStorage,
637
+ syncId: sync.id,
638
+ runId: job.id,
639
+ dataset,
640
+ onRead
641
+ }));
642
+ throwIfAborted(signal);
643
+ if (rowsRead === 0) {
644
+ const version3 = await lakeStorage.getLatestVersion(dataset.id);
645
+ if (sync.config.mode === "append" || !version3) {
646
+ await rowWrite.abort();
647
+ abortWrite = undefined;
648
+ const finishedRun2 = await syncRunsStorage.finish({
649
+ projectId: runtime.id,
650
+ id: job.id,
651
+ status: "succeeded",
652
+ rowsRead,
653
+ ...version3 ? { output: { datasetId: version3.datasetId, versionId: version3.versionId } } : {},
654
+ checkpoint: nextCheckpoint
655
+ });
656
+ const finishedAt2 = requireFinishedAt({
657
+ syncId: sync.id,
658
+ runId: job.id,
659
+ finishedAt: finishedRun2.finishedAt
660
+ });
661
+ await notifyRunFinished(input.onRunFinished, finishedRun2);
662
+ return {
663
+ id: job.id,
664
+ syncId: sync.id,
665
+ datasetId: dataset.id,
666
+ mode: sync.config.mode,
667
+ startedAt: requireStartedAt(job.id, startedRun.startedAt),
668
+ finishedAt: finishedAt2,
669
+ rowsRead,
670
+ ...version3 ? { version: version3 } : {},
671
+ versionCreated: false
672
+ };
673
+ }
674
+ }
675
+ const { outcome: outcome2, ...version2 } = await rowWrite.commit({
676
+ expectedLatestVersionId: job.expectedLatestVersionId,
677
+ commitMessage
678
+ });
679
+ abortWrite = undefined;
680
+ commitResult = { outcome: outcome2, version: version2 };
681
+ }
682
+ const { outcome, version } = commitResult;
683
+ if (outcome === "created") {
684
+ if (!version) {
685
+ throw createSixbError3("internal.unexpected", `[SixbSyncWorker] Sync '${sync.id}' created no dataset version.`, { details: { syncId: sync.id, runId: job.id, datasetId: dataset.id } });
686
+ }
687
+ committedVersion = version;
246
688
  }
247
- const commit = await write.commit({
248
- expectedLatestVersionId: job.expectedLatestVersionId,
249
- commitMessage: job.commitMessage ?? `sync ${sync.id} run ${job.id}`
250
- });
251
- const { outcome, ...version } = commit;
252
- committedVersion = version;
253
689
  let finishedRun;
254
690
  try {
255
691
  finishedRun = await syncRunsStorage.finish({
@@ -257,45 +693,62 @@ async function runSyncJob(input) {
257
693
  id: job.id,
258
694
  status: "succeeded",
259
695
  rowsRead,
260
- output: {
261
- datasetId: version.datasetId,
262
- versionId: version.versionId
263
- },
696
+ ...version ? { output: { datasetId: version.datasetId, versionId: version.versionId } } : {},
264
697
  checkpoint: nextCheckpoint
265
698
  });
266
699
  } catch (error) {
267
- throw createBookkeepingError({
268
- syncId: sync.id,
269
- runId: job.id,
270
- version,
271
- cause: error
272
- });
700
+ if (committedVersion) {
701
+ throw createBookkeepingError({
702
+ syncId: sync.id,
703
+ runId: job.id,
704
+ version: committedVersion,
705
+ cause: error
706
+ });
707
+ }
708
+ throw error;
273
709
  }
274
- return {
710
+ const finishedAt = requireFinishedAt({
711
+ syncId: sync.id,
712
+ runId: job.id,
713
+ finishedAt: finishedRun.finishedAt
714
+ });
715
+ await notifyRunFinished(input.onRunFinished, finishedRun, committedVersion);
716
+ const result = {
275
717
  id: job.id,
276
718
  syncId: sync.id,
277
719
  datasetId: dataset.id,
278
720
  mode: sync.config.mode,
279
- startedAt: startedRun.startedAt,
280
- finishedAt: requireFinishedAt(job.id, finishedRun.finishedAt),
281
- rowsRead,
282
- version,
283
- versionCreated: outcome === "created"
721
+ startedAt: requireStartedAt(job.id, startedRun.startedAt),
722
+ finishedAt,
723
+ rowsRead
284
724
  };
725
+ return version ? { ...result, version, versionCreated: outcome === "created" } : { ...result, versionCreated: false };
285
726
  } catch (error) {
286
727
  if (!committedVersion) {
287
- await write?.abort().catch(() => {});
728
+ await abortWrite?.().catch(() => {});
288
729
  const status = signal.aborted ? "cancelled" : "failed";
289
730
  try {
290
- const run = await syncRunsStorage.finish({
731
+ const failureError = status === "failed" ? translateSyncExecutionError(error, {
732
+ syncId: run.syncId,
733
+ runId: job.id,
734
+ datasetId: run.datasetId
735
+ }) : error;
736
+ const failure = captureSixbFailure(failureError, {
737
+ allowedCodes: SYNC_RUN_FAILURE_CODES,
738
+ defaultCode: status === "cancelled" ? "runtime.cancelled" : "internal.unexpected",
739
+ details: { syncId: run.syncId, runId: job.id, datasetId: run.datasetId }
740
+ });
741
+ const failedRun = await syncRunsStorage.finish({
291
742
  projectId: runtime.id,
292
743
  id: job.id,
293
744
  status,
294
745
  rowsRead,
295
- error: toSyncRunFailure(error)
746
+ error: failure
296
747
  });
297
- if (status === "failed" && run.status === "failed")
298
- input.onRunFailed?.(error, run);
748
+ await notifyRunFinished(input.onRunFinished, failedRun);
749
+ if (status === "failed" && failedRun.status === "failed") {
750
+ input.onRunFailed?.(error, failedRun, failure);
751
+ }
299
752
  } catch {}
300
753
  }
301
754
  throw error;
@@ -303,50 +756,76 @@ async function runSyncJob(input) {
303
756
  await logSession.flush();
304
757
  }
305
758
  }
759
+ async function notifyRunFinished(handler, run, createdVersion) {
760
+ try {
761
+ await handler?.(run, createdVersion);
762
+ } catch (error) {
763
+ console.error("[SixbSyncWorker] Sync run lifecycle handler failed:", error);
764
+ }
765
+ }
766
+ function requireStartedAt(runId, startedAt) {
767
+ if (startedAt)
768
+ return startedAt;
769
+ throw createSixbError3("internal.unexpected", `[SixbSyncWorker] Sync run '${runId}' started without a startedAt timestamp.`, { details: { runId } });
770
+ }
306
771
 
307
772
  // src/worker.ts
308
773
  var SOURCE = "SixbSyncWorker";
309
774
 
310
775
  class SyncWorker extends QueueWorker {
311
- context;
312
- sixb;
313
- constructor(sixb) {
314
- if (sixb.listSyncs().length === 0) {
776
+ host;
777
+ constructor(host) {
778
+ if (host.definitions.syncs.list().length === 0) {
315
779
  throw new Error("[SixbSyncWorker] No sync definitions are registered.");
316
780
  }
317
781
  super({
318
- projectId: sixb.id,
319
- queue: sixb.queues.syncRuns,
320
- workerId: `sync-worker-${sixb.id}`
782
+ projectId: host.id,
783
+ queue: host.queues.syncRuns,
784
+ failureCodes: SYNC_RUN_FAILURE_CODES2,
785
+ workerId: `sync-worker-${host.id}`
321
786
  });
322
- this.context = buildSyncContext(sixb);
323
- this.sixb = sixb;
787
+ assertSyncStorage(host);
788
+ this.host = host;
324
789
  }
325
790
  async execute(claimed, signal) {
326
791
  const { job } = claimed;
327
- const syncJob = {
328
- id: job.payload.runId ?? `${job.id}:attempt:${job.attempt}`,
329
- syncId: job.payload.syncId,
330
- expectedLatestVersionId: job.payload.expectedLatestVersionId,
331
- commitMessage: job.payload.commitMessage
332
- };
333
- let result;
792
+ const syncRuns = this.host.storage.syncRuns;
793
+ if (!syncRuns) {
794
+ throw new Error("[SixbSyncWorker] Sync workers require storage.syncRuns support.");
795
+ }
796
+ const run = await syncRuns.getById({ projectId: this.host.id, id: job.payload.runId });
797
+ if (!run) {
798
+ throw new Error(`[SixbSyncWorker] Sync run '${job.payload.runId}' was not found.`);
799
+ }
800
+ const durableExecution = await this.host.storage.executions.getById({
801
+ projectId: this.host.id,
802
+ id: run.executionId
803
+ });
804
+ if (!durableExecution) {
805
+ throw new Error(`[SixbSyncWorker] Sync run '${run.id}' references missing execution '${run.executionId}'.`);
806
+ }
807
+ const execution = bindDurablePrimitiveExecution(this.host, {
808
+ execution: durableExecution,
809
+ primitive: { kind: "sync", id: run.syncId, runId: run.id }
810
+ });
811
+ const context = buildSyncContext(this.host, execution.sixb);
334
812
  try {
335
- result = await runSyncJob({
336
- runtime: this.context,
337
- job: syncJob,
813
+ await runSyncJob({
814
+ runtime: context,
815
+ run,
338
816
  signal,
339
- onRunStarted: (run) => emitSyncRunStarted(this.sixb, run),
340
- onRunFailed: (error, run) => {
341
- reportRunFailure(this.sixb, error, {
342
- projectId: this.sixb.id,
343
- occurredAt: run.finishedAt,
817
+ onRunStarted: (started) => emitSyncRunStarted(this.host, started, durableExecution.correlationId),
818
+ onRunFinished: (finished, createdVersion) => emitSyncRunFinishedEvents(this.host, finished, durableExecution.correlationId, createdVersion),
819
+ onRunFailed: (error, run2, failure) => {
820
+ reportRunFailure(this.host, error, {
821
+ projectId: this.host.id,
344
822
  attempt: job.attempt,
823
+ runKind: "sync",
345
824
  run: {
346
- kind: "sync",
347
- runId: run.id,
348
- syncId: run.syncId
349
- }
825
+ runId: run2.id,
826
+ syncId: run2.syncId
827
+ },
828
+ failure
350
829
  });
351
830
  }
352
831
  });
@@ -355,19 +834,20 @@ class SyncWorker extends QueueWorker {
355
834
  return;
356
835
  throw error;
357
836
  }
358
- await emitSyncSucceededEvents(this.sixb, syncJob, result);
359
837
  }
360
838
  async onExecutionError(claimed, _error) {
361
- const { job } = claimed;
362
- await emitSyncRunFinished(this.sixb, {
363
- id: job.payload.runId ?? `${job.id}:attempt:${job.attempt}`,
364
- syncId: job.payload.syncId
839
+ const run = await this.host.storage.syncRuns?.getById({
840
+ projectId: this.host.id,
841
+ id: claimed.job.payload.runId
365
842
  });
366
- return { kind: "fail" };
843
+ return run?.status === "failed" && run.error ? { kind: "fail", failure: run.error } : { kind: "fail" };
367
844
  }
368
845
  }
369
- async function emitSyncRunStarted(sixb, run) {
370
- await sixb.events?.emit({
846
+ async function emitSyncRunStarted(host, run, correlationId) {
847
+ if (!run.startedAt) {
848
+ throw new Error(`[SixbSyncWorker] Sync run '${run.id}' started without a timestamp.`);
849
+ }
850
+ await host.events?.emit({
371
851
  events: [
372
852
  {
373
853
  type: "sync.run.started",
@@ -377,23 +857,24 @@ async function emitSyncRunStarted(sixb, run) {
377
857
  startedAt: run.startedAt.toISOString()
378
858
  }
379
859
  }
380
- ]
860
+ ],
861
+ correlationId
381
862
  }, { source: SOURCE });
382
863
  }
383
- async function emitSyncSucceededEvents(sixb, job, result) {
384
- await sixb.events?.emit({
864
+ async function emitSyncRunFinishedEvents(host, run, correlationId, createdVersion) {
865
+ await host.events?.emit({
385
866
  events: [
386
- ...result.versionCreated ? [
867
+ ...createdVersion ? [
387
868
  {
388
869
  type: "dataset.version.committed",
389
870
  payload: {
390
- datasetId: result.datasetId,
391
- versionId: result.version.versionId,
392
- createdAt: result.version.createdAt.toISOString(),
871
+ datasetId: createdVersion.datasetId,
872
+ versionId: createdVersion.versionId,
873
+ createdAt: createdVersion.createdAt.toISOString(),
393
874
  producer: {
394
875
  kind: "sync",
395
- id: job.syncId,
396
- runId: job.id
876
+ id: run.syncId,
877
+ runId: run.id
397
878
  }
398
879
  }
399
880
  }
@@ -401,49 +882,44 @@ async function emitSyncSucceededEvents(sixb, job, result) {
401
882
  {
402
883
  type: "sync.run.finished",
403
884
  payload: {
404
- syncId: job.syncId,
405
- runId: job.id,
406
- status: "succeeded",
407
- datasetId: result.datasetId,
408
- ...result.version ? { versionId: result.version.versionId } : {}
885
+ syncId: run.syncId,
886
+ runId: run.id,
887
+ status: requireTerminalStatus(run.status, `Sync run '${run.id}'`),
888
+ datasetId: run.datasetId,
889
+ ...run.output ? { versionId: run.output.versionId } : {},
890
+ ...run.error ? { error: run.error } : {}
409
891
  }
410
892
  }
411
- ]
893
+ ],
894
+ correlationId
412
895
  }, { source: SOURCE });
413
896
  }
414
- async function emitSyncRunFinished(sixb, job) {
415
- await sixb.events?.emit({
416
- events: [
417
- {
418
- type: "sync.run.finished",
419
- payload: {
420
- syncId: job.syncId,
421
- runId: job.id,
422
- status: "failed"
423
- }
424
- }
425
- ]
426
- }, { source: SOURCE });
897
+ function requireTerminalStatus(status, context) {
898
+ if (status === "queued" || status === "running") {
899
+ throw new Error(`[SixbSyncWorker] ${context} is not terminal.`);
900
+ }
901
+ return status;
427
902
  }
428
- function buildSyncContext(sixb) {
429
- const syncRunsStorage = sixb.storage.syncRuns;
903
+ function assertSyncStorage(host) {
904
+ if (!host.storage.syncRuns) {
905
+ throw new Error("[SixbSyncWorker] Sync workers require storage.syncRuns support.");
906
+ }
907
+ }
908
+ function buildSyncContext(host, sixb) {
909
+ const syncRunsStorage = host.storage.syncRuns;
430
910
  if (!syncRunsStorage) {
431
911
  throw new Error("[SixbSyncWorker] Sync workers require storage.syncRuns support.");
432
912
  }
433
913
  return {
434
- id: sixb.id,
914
+ id: host.id,
435
915
  syncRunsStorage,
436
- lakeStorage: sixb.lakeStorage,
437
- blobStorage: sixb.blobStorage,
438
- logs: sixb.logs,
439
- getSyncById(syncId) {
440
- return sixb.getSyncById(syncId);
441
- },
442
- getDatasetById(datasetId) {
443
- return sixb.getDatasetById(datasetId);
444
- },
445
- connector(definition) {
446
- return sixb.connector(definition);
916
+ lakeStorage: host.lakeStorage,
917
+ blobs: sixb.blobs,
918
+ logging: host.logging,
919
+ syncs: host.definitions.syncs,
920
+ datasets: host.definitions.datasets,
921
+ connectorSources: {
922
+ list: (definition) => resolveSyncConnectorSources(sixb.connector, definition)
447
923
  }
448
924
  };
449
925
  }
@@ -451,4 +927,4 @@ export {
451
927
  SyncWorker
452
928
  };
453
929
 
454
- //# debugId=33375B9F4568F6E364756E2164756E21
930
+ //# debugId=2BE58ED5203AC1D364756E2164756E21