@sixb/sync-worker 0.1.1 → 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,17 +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";
14
24
  import { getDatasetMergeChangeValidationError } from "@sixb/core/lake-storage";
25
+ import { SYNC_RUN_FAILURE_CODES } from "@sixb/core/storage";
15
26
 
16
27
  // src/normalize.ts
17
28
  function isPlainObject(value) {
@@ -41,30 +52,326 @@ function throwIfAborted(signal) {
41
52
  throw toAbortError(signal);
42
53
  }
43
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
+ }
44
71
  function assertDatasetRow(value, syncId, itemIndex) {
45
72
  if (isPlainObject(value)) {
46
73
  return value;
47
74
  }
48
75
  throw new Error(`[SixbSyncWorker] Sync '${syncId}' returned an invalid row at item ${itemIndex}. Dataset rows must be plain objects.`);
49
76
  }
50
- async function* normalizeReadResult(readResult, syncId) {
77
+ async function* normalizeReadResult(readResult, syncId, signal) {
51
78
  if (isAsyncIterable(readResult)) {
52
- 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
+ }
53
99
  return;
54
100
  }
55
101
  if (isIterable(readResult)) {
56
102
  for (const item of readResult) {
103
+ throwIfAborted(signal);
57
104
  yield item;
58
105
  }
59
106
  return;
60
107
  }
61
108
  if (isPlainObject(readResult)) {
109
+ throwIfAborted(signal);
62
110
  yield readResult;
63
111
  return;
64
112
  }
65
113
  throw new Error(`[SixbSyncWorker] Sync '${syncId}' returned an unsupported read result. Expected a row object, iterable, or async iterable.`);
66
114
  }
67
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
+
68
375
  // src/run-sync-job.ts
69
376
  class SyncRunAlreadyStartedError extends Error {
70
377
  run;
@@ -74,25 +381,35 @@ class SyncRunAlreadyStartedError extends Error {
74
381
  this.run = run;
75
382
  }
76
383
  }
77
- function toSyncRunFailure(error) {
78
- if (error instanceof Error) {
79
- return {
80
- name: error.name,
81
- message: error.message
82
- };
83
- }
84
- return {
85
- message: String(error)
86
- };
87
- }
88
384
  function createBookkeepingError(options) {
89
- 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
+ });
90
394
  }
91
- function requireFinishedAt(runId, finishedAt) {
92
- if (finishedAt) {
93
- return finishedAt;
395
+ function requireFinishedAt(input) {
396
+ if (input.finishedAt) {
397
+ return input.finishedAt;
94
398
  }
95
- 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
+ });
96
413
  }
97
414
  async function verifyFileRef(options) {
98
415
  const blobInfo = await options.blobStorage.stat(options.fileRef.blobId);
@@ -130,92 +447,102 @@ function assertMergeChange(value, syncId, dataset, itemIndex) {
130
447
  }
131
448
  return value;
132
449
  }
133
- async function readSyncValues(options) {
134
- const client = await options.runtime.connector(options.sync.connector);
135
- const readResult = await options.sync.read(client, {
136
- projectId: options.runtime.id,
137
- syncId: options.sync.id,
138
- signal: options.signal,
139
- blobs: options.blobStorage,
140
- logger: options.logger,
141
- checkpoint: options.previousCheckpoint !== undefined ? cloneJsonValue(options.previousCheckpoint) : undefined,
142
- setCheckpoint: options.setCheckpoint
143
- });
144
- return normalizeReadResult(readResult, options.sync.id);
145
- }
146
450
  async function* validatedDatasetRows(options) {
147
451
  let itemIndex = 0;
148
- for await (const value of options.values) {
452
+ for await (const sourceValue of options.values) {
149
453
  throwIfAborted(options.signal);
150
454
  itemIndex += 1;
151
- const row = assertDatasetRow(value, options.syncId, itemIndex);
152
- const validationError = getDatasetRowValidationError(row, options.dataset);
153
- if (validationError) {
154
- throw new Error(`[SixbSyncWorker] Sync '${options.syncId}' returned an invalid row at item ${itemIndex}. ${validationError}`);
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);
155
472
  }
156
- await verifyRowFileRefs({
157
- blobStorage: options.blobStorage,
158
- syncId: options.syncId,
159
- dataset: options.dataset,
160
- row,
161
- itemIndex
162
- });
163
- options.onRead();
164
473
  yield row;
165
474
  }
166
475
  }
167
476
  async function* validatedMergeChanges(options) {
168
477
  let itemIndex = 0;
169
- for await (const value of options.values) {
478
+ for await (const sourceValue of options.values) {
170
479
  throwIfAborted(options.signal);
171
480
  itemIndex += 1;
172
- const mergeChange = assertMergeChange(value, options.syncId, options.dataset, itemIndex);
173
- if (mergeChange.kind === "upsert") {
174
- await verifyRowFileRefs({
175
- blobStorage: options.blobStorage,
176
- syncId: options.syncId,
177
- dataset: options.dataset,
178
- row: mergeChange.row,
179
- itemIndex
180
- });
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);
181
496
  }
182
- options.onRead();
183
497
  yield mergeChange;
184
498
  }
185
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
+ }
186
517
  async function runSyncJob(input) {
187
- 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
+ };
188
525
  const signal = input.signal ?? new AbortController().signal;
189
- const { syncRunsStorage, lakeStorage, blobStorage } = runtime;
190
- const sync = runtime.getSyncById(job.syncId);
191
- if (!sync) {
192
- throw new Error(`[SixbSyncWorker] Unknown sync '${job.syncId}'.`);
193
- }
194
- const dataset = runtime.getDatasetById(sync.target.dataset.id);
195
- if (!dataset) {
196
- 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}'.`);
197
529
  }
198
530
  throwIfAborted(signal);
199
531
  let startedRun;
200
532
  try {
201
533
  startedRun = await syncRunsStorage.start({
202
534
  projectId: runtime.id,
203
- id: job.id,
204
- syncId: sync.id,
205
- datasetId: dataset.id,
206
- mode: sync.config.mode,
207
- expectedLatestVersionId: job.expectedLatestVersionId,
208
- commitMessage: job.commitMessage
535
+ id: job.id
209
536
  });
210
537
  } catch (error) {
211
538
  const existing = await syncRunsStorage.getById({ projectId: runtime.id, id: job.id });
212
- if (existing?.syncId === sync.id && existing.datasetId === dataset.id) {
539
+ if (existing?.syncId === run.syncId && existing.executionId === run.executionId) {
213
540
  throw new SyncRunAlreadyStartedError(existing);
214
541
  }
215
542
  throw error;
216
543
  }
217
544
  await input.onRunStarted?.(startedRun);
218
- const logSession = resolveLogsRuntime(runtime.id, runtime.logs).startExecution({
545
+ const logSession = resolveLoggingService(runtime.id, runtime.logging).startExecution({
219
546
  kind: "sync",
220
547
  id: job.id
221
548
  });
@@ -224,6 +551,17 @@ async function runSyncJob(input) {
224
551
  let rowsRead = 0;
225
552
  let committedVersion;
226
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
+ }
227
565
  throwIfAborted(signal);
228
566
  await lakeStorage.createDataset(dataset);
229
567
  const latestSuccessfulRuns = await syncRunsStorage.list({
@@ -234,7 +572,7 @@ async function runSyncJob(input) {
234
572
  order: "desc"
235
573
  });
236
574
  const previousCheckpoint = latestSuccessfulRuns.runs[0]?.checkpoint;
237
- let nextCheckpoint = previousCheckpoint !== undefined ? cloneJsonValue(previousCheckpoint) : undefined;
575
+ let nextCheckpoint = previousCheckpoint !== undefined ? cloneJsonValue3(previousCheckpoint) : undefined;
238
576
  const producer = {
239
577
  kind: "sync",
240
578
  id: sync.id,
@@ -243,13 +581,14 @@ async function runSyncJob(input) {
243
581
  const readValues = () => readSyncValues({
244
582
  runtime,
245
583
  sync,
584
+ runId: job.id,
585
+ datasetId: dataset.id,
246
586
  signal,
247
587
  blobStorage,
248
588
  logger,
249
589
  previousCheckpoint,
250
590
  setCheckpoint(next) {
251
- assertJsonValue(next, `Sync '${sync.id}' checkpoint`);
252
- nextCheckpoint = cloneJsonValue(next);
591
+ nextCheckpoint = next === undefined ? undefined : cloneJsonValue3(next);
253
592
  }
254
593
  });
255
594
  const onRead = () => {
@@ -271,6 +610,7 @@ async function runSyncJob(input) {
271
610
  signal,
272
611
  blobStorage,
273
612
  syncId: sync.id,
613
+ runId: job.id,
274
614
  dataset,
275
615
  onRead
276
616
  }));
@@ -295,6 +635,7 @@ async function runSyncJob(input) {
295
635
  signal,
296
636
  blobStorage,
297
637
  syncId: sync.id,
638
+ runId: job.id,
298
639
  dataset,
299
640
  onRead
300
641
  }));
@@ -312,13 +653,19 @@ async function runSyncJob(input) {
312
653
  ...version3 ? { output: { datasetId: version3.datasetId, versionId: version3.versionId } } : {},
313
654
  checkpoint: nextCheckpoint
314
655
  });
656
+ const finishedAt2 = requireFinishedAt({
657
+ syncId: sync.id,
658
+ runId: job.id,
659
+ finishedAt: finishedRun2.finishedAt
660
+ });
661
+ await notifyRunFinished(input.onRunFinished, finishedRun2);
315
662
  return {
316
663
  id: job.id,
317
664
  syncId: sync.id,
318
665
  datasetId: dataset.id,
319
666
  mode: sync.config.mode,
320
- startedAt: startedRun.startedAt,
321
- finishedAt: requireFinishedAt(job.id, finishedRun2.finishedAt),
667
+ startedAt: requireStartedAt(job.id, startedRun.startedAt),
668
+ finishedAt: finishedAt2,
322
669
  rowsRead,
323
670
  ...version3 ? { version: version3 } : {},
324
671
  versionCreated: false
@@ -335,7 +682,7 @@ async function runSyncJob(input) {
335
682
  const { outcome, version } = commitResult;
336
683
  if (outcome === "created") {
337
684
  if (!version) {
338
- throw new Error(`[SixbSyncWorker] Sync '${sync.id}' created no dataset version.`);
685
+ throw createSixbError3("internal.unexpected", `[SixbSyncWorker] Sync '${sync.id}' created no dataset version.`, { details: { syncId: sync.id, runId: job.id, datasetId: dataset.id } });
339
686
  }
340
687
  committedVersion = version;
341
688
  }
@@ -360,13 +707,19 @@ async function runSyncJob(input) {
360
707
  }
361
708
  throw error;
362
709
  }
710
+ const finishedAt = requireFinishedAt({
711
+ syncId: sync.id,
712
+ runId: job.id,
713
+ finishedAt: finishedRun.finishedAt
714
+ });
715
+ await notifyRunFinished(input.onRunFinished, finishedRun, committedVersion);
363
716
  const result = {
364
717
  id: job.id,
365
718
  syncId: sync.id,
366
719
  datasetId: dataset.id,
367
720
  mode: sync.config.mode,
368
- startedAt: startedRun.startedAt,
369
- finishedAt: requireFinishedAt(job.id, finishedRun.finishedAt),
721
+ startedAt: requireStartedAt(job.id, startedRun.startedAt),
722
+ finishedAt,
370
723
  rowsRead
371
724
  };
372
725
  return version ? { ...result, version, versionCreated: outcome === "created" } : { ...result, versionCreated: false };
@@ -375,15 +728,27 @@ async function runSyncJob(input) {
375
728
  await abortWrite?.().catch(() => {});
376
729
  const status = signal.aborted ? "cancelled" : "failed";
377
730
  try {
378
- 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({
379
742
  projectId: runtime.id,
380
743
  id: job.id,
381
744
  status,
382
745
  rowsRead,
383
- error: toSyncRunFailure(error)
746
+ error: failure
384
747
  });
385
- if (status === "failed" && run.status === "failed")
386
- input.onRunFailed?.(error, run);
748
+ await notifyRunFinished(input.onRunFinished, failedRun);
749
+ if (status === "failed" && failedRun.status === "failed") {
750
+ input.onRunFailed?.(error, failedRun, failure);
751
+ }
387
752
  } catch {}
388
753
  }
389
754
  throw error;
@@ -391,50 +756,76 @@ async function runSyncJob(input) {
391
756
  await logSession.flush();
392
757
  }
393
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
+ }
394
771
 
395
772
  // src/worker.ts
396
773
  var SOURCE = "SixbSyncWorker";
397
774
 
398
775
  class SyncWorker extends QueueWorker {
399
- context;
400
- sixb;
401
- constructor(sixb) {
402
- if (sixb.listSyncs().length === 0) {
776
+ host;
777
+ constructor(host) {
778
+ if (host.definitions.syncs.list().length === 0) {
403
779
  throw new Error("[SixbSyncWorker] No sync definitions are registered.");
404
780
  }
405
781
  super({
406
- projectId: sixb.id,
407
- queue: sixb.queues.syncRuns,
408
- 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}`
409
786
  });
410
- this.context = buildSyncContext(sixb);
411
- this.sixb = sixb;
787
+ assertSyncStorage(host);
788
+ this.host = host;
412
789
  }
413
790
  async execute(claimed, signal) {
414
791
  const { job } = claimed;
415
- const syncJob = {
416
- id: job.payload.runId ?? `${job.id}:attempt:${job.attempt}`,
417
- syncId: job.payload.syncId,
418
- expectedLatestVersionId: job.payload.expectedLatestVersionId,
419
- commitMessage: job.payload.commitMessage
420
- };
421
- 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);
422
812
  try {
423
- result = await runSyncJob({
424
- runtime: this.context,
425
- job: syncJob,
813
+ await runSyncJob({
814
+ runtime: context,
815
+ run,
426
816
  signal,
427
- onRunStarted: (run) => emitSyncRunStarted(this.sixb, run),
428
- onRunFailed: (error, run) => {
429
- reportRunFailure(this.sixb, error, {
430
- projectId: this.sixb.id,
431
- 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,
432
822
  attempt: job.attempt,
823
+ runKind: "sync",
433
824
  run: {
434
- kind: "sync",
435
- runId: run.id,
436
- syncId: run.syncId
437
- }
825
+ runId: run2.id,
826
+ syncId: run2.syncId
827
+ },
828
+ failure
438
829
  });
439
830
  }
440
831
  });
@@ -443,19 +834,20 @@ class SyncWorker extends QueueWorker {
443
834
  return;
444
835
  throw error;
445
836
  }
446
- await emitSyncSucceededEvents(this.sixb, syncJob, result);
447
837
  }
448
838
  async onExecutionError(claimed, _error) {
449
- const { job } = claimed;
450
- await emitSyncRunFinished(this.sixb, {
451
- id: job.payload.runId ?? `${job.id}:attempt:${job.attempt}`,
452
- syncId: job.payload.syncId
839
+ const run = await this.host.storage.syncRuns?.getById({
840
+ projectId: this.host.id,
841
+ id: claimed.job.payload.runId
453
842
  });
454
- return { kind: "fail" };
843
+ return run?.status === "failed" && run.error ? { kind: "fail", failure: run.error } : { kind: "fail" };
455
844
  }
456
845
  }
457
- async function emitSyncRunStarted(sixb, run) {
458
- 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({
459
851
  events: [
460
852
  {
461
853
  type: "sync.run.started",
@@ -465,23 +857,24 @@ async function emitSyncRunStarted(sixb, run) {
465
857
  startedAt: run.startedAt.toISOString()
466
858
  }
467
859
  }
468
- ]
860
+ ],
861
+ correlationId
469
862
  }, { source: SOURCE });
470
863
  }
471
- async function emitSyncSucceededEvents(sixb, job, result) {
472
- await sixb.events?.emit({
864
+ async function emitSyncRunFinishedEvents(host, run, correlationId, createdVersion) {
865
+ await host.events?.emit({
473
866
  events: [
474
- ...result.versionCreated ? [
867
+ ...createdVersion ? [
475
868
  {
476
869
  type: "dataset.version.committed",
477
870
  payload: {
478
- datasetId: result.datasetId,
479
- versionId: result.version.versionId,
480
- createdAt: result.version.createdAt.toISOString(),
871
+ datasetId: createdVersion.datasetId,
872
+ versionId: createdVersion.versionId,
873
+ createdAt: createdVersion.createdAt.toISOString(),
481
874
  producer: {
482
875
  kind: "sync",
483
- id: job.syncId,
484
- runId: job.id
876
+ id: run.syncId,
877
+ runId: run.id
485
878
  }
486
879
  }
487
880
  }
@@ -489,49 +882,44 @@ async function emitSyncSucceededEvents(sixb, job, result) {
489
882
  {
490
883
  type: "sync.run.finished",
491
884
  payload: {
492
- syncId: job.syncId,
493
- runId: job.id,
494
- status: "succeeded",
495
- datasetId: result.datasetId,
496
- ...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 } : {}
497
891
  }
498
892
  }
499
- ]
893
+ ],
894
+ correlationId
500
895
  }, { source: SOURCE });
501
896
  }
502
- async function emitSyncRunFinished(sixb, job) {
503
- await sixb.events?.emit({
504
- events: [
505
- {
506
- type: "sync.run.finished",
507
- payload: {
508
- syncId: job.syncId,
509
- runId: job.id,
510
- status: "failed"
511
- }
512
- }
513
- ]
514
- }, { 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;
902
+ }
903
+ function assertSyncStorage(host) {
904
+ if (!host.storage.syncRuns) {
905
+ throw new Error("[SixbSyncWorker] Sync workers require storage.syncRuns support.");
906
+ }
515
907
  }
516
- function buildSyncContext(sixb) {
517
- const syncRunsStorage = sixb.storage.syncRuns;
908
+ function buildSyncContext(host, sixb) {
909
+ const syncRunsStorage = host.storage.syncRuns;
518
910
  if (!syncRunsStorage) {
519
911
  throw new Error("[SixbSyncWorker] Sync workers require storage.syncRuns support.");
520
912
  }
521
913
  return {
522
- id: sixb.id,
914
+ id: host.id,
523
915
  syncRunsStorage,
524
- lakeStorage: sixb.lakeStorage,
525
- blobStorage: sixb.blobStorage,
526
- logs: sixb.logs,
527
- getSyncById(syncId) {
528
- return sixb.getSyncById(syncId);
529
- },
530
- getDatasetById(datasetId) {
531
- return sixb.getDatasetById(datasetId);
532
- },
533
- connector(definition) {
534
- 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)
535
923
  }
536
924
  };
537
925
  }
@@ -539,4 +927,4 @@ export {
539
927
  SyncWorker
540
928
  };
541
929
 
542
- //# debugId=3B01117F7588DCC564756E2164756E21
930
+ //# debugId=2BE58ED5203AC1D364756E2164756E21