@sixb/sync-worker 0.0.1

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.
@@ -0,0 +1,49 @@
1
+ import type { BlobStorage, ConnectorAdapter, ConnectorClient, ConnectorDefinition, DatasetDefinition, LakeStorage, SyncDefinition } from "@sixb/core";
2
+ import type { LogsRuntime } from "@sixb/core/internal/logging";
3
+ import type { DatasetVersion, DatasetWriteMode } from "@sixb/core/lake-storage";
4
+ import type { SyncRunRecord, SyncRunStorage } from "@sixb/core/storage";
5
+ export interface SyncWorkerContext {
6
+ readonly id: string;
7
+ readonly syncRunsStorage: SyncRunStorage;
8
+ readonly lakeStorage: LakeStorage;
9
+ readonly blobStorage: BlobStorage;
10
+ readonly logs?: LogsRuntime;
11
+ getDatasetById(datasetId: string): DatasetDefinition | null;
12
+ getSyncById(syncId: string): SyncDefinition | null;
13
+ connector<TAdapter extends ConnectorAdapter>(definition: ConnectorDefinition<string, TAdapter>): Promise<ConnectorClient<TAdapter>>;
14
+ }
15
+ export interface SyncJob {
16
+ readonly id: string;
17
+ readonly syncId: string;
18
+ readonly expectedLatestVersionId?: string;
19
+ readonly commitMessage?: string;
20
+ }
21
+ export interface RunSyncJobInput {
22
+ readonly runtime: SyncWorkerContext;
23
+ readonly job: SyncJob;
24
+ readonly signal?: AbortSignal;
25
+ readonly onRunStarted?: SyncRunStartedHandler;
26
+ readonly onRunFailed?: SyncRunFailedHandler;
27
+ }
28
+ export type SyncRunStartedHandler = (run: SyncRunRecord) => Promise<void> | void;
29
+ export type SyncRunFailedHandler = (error: unknown, run: SyncRunRecord) => void;
30
+ interface SyncRunResultBase {
31
+ readonly id: string;
32
+ readonly syncId: string;
33
+ readonly datasetId: string;
34
+ readonly mode: DatasetWriteMode;
35
+ readonly startedAt: Date;
36
+ readonly finishedAt: Date;
37
+ readonly rowsRead: number;
38
+ }
39
+ export type SyncRunResult = SyncRunResultBase & ({
40
+ readonly version: DatasetVersion;
41
+ /** True only when this run created the returned dataset version. */
42
+ readonly versionCreated: boolean;
43
+ } | {
44
+ /** A first empty append has no dataset version yet. */
45
+ readonly version?: undefined;
46
+ readonly versionCreated: false;
47
+ });
48
+ export {};
49
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,iBAAiB,EACjB,WAAW,EACX,cAAc,EACf,MAAM,YAAY,CAAA;AACnB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAA;AAC9D,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAA;AAC/E,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAEvE,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,eAAe,EAAE,cAAc,CAAA;IACxC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAA;IACjC,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAA;IACjC,QAAQ,CAAC,IAAI,CAAC,EAAE,WAAW,CAAA;IAE3B,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,iBAAiB,GAAG,IAAI,CAAA;IAC3D,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,cAAc,GAAG,IAAI,CAAA;IAElD,SAAS,CAAC,QAAQ,SAAS,gBAAgB,EACzC,UAAU,EAAE,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,GAChD,OAAO,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC,CAAA;CACtC;AAED,MAAM,WAAW,OAAO;IACtB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,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type { BlobStorage, ConnectorAdapter, ConnectorClient, ConnectorDefinition, DatasetDefinition, DomainEventLog, LakeStorage, Queues, Storage, SyncDefinition } from "@sixb/core";
2
+ import type { LogsRuntime } from "@sixb/core/internal/logging";
3
+ import type { QueueWorkerFailureDecision } from "@sixb/core/internal/workers";
4
+ import { QueueWorker } from "@sixb/core/internal/workers";
5
+ import type { ClaimedQueueJob, SyncRunRequestedQueueJob } from "@sixb/core/queues";
6
+ export interface SyncWorkerSixb {
7
+ readonly id: string;
8
+ readonly events?: DomainEventLog;
9
+ readonly logs?: LogsRuntime;
10
+ readonly lakeStorage: LakeStorage;
11
+ readonly blobStorage: BlobStorage;
12
+ readonly queues: Queues;
13
+ readonly storage: Storage;
14
+ listSyncs(): readonly SyncDefinition[];
15
+ getSyncById(syncId: string): SyncDefinition | null;
16
+ getDatasetById(datasetId: string): DatasetDefinition | null;
17
+ connector<TAdapter extends ConnectorAdapter>(definition: ConnectorDefinition<string, TAdapter>): Promise<ConnectorClient<TAdapter>>;
18
+ }
19
+ export declare class SyncWorker extends QueueWorker<SyncRunRequestedQueueJob> {
20
+ private readonly context;
21
+ private readonly sixb;
22
+ constructor(sixb: SyncWorkerSixb);
23
+ protected execute(claimed: ClaimedQueueJob<SyncRunRequestedQueueJob>, signal: AbortSignal): Promise<void>;
24
+ protected onExecutionError(claimed: ClaimedQueueJob<SyncRunRequestedQueueJob>, _error: unknown): Promise<QueueWorkerFailureDecision>;
25
+ }
26
+ //# sourceMappingURL=worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,WAAW,EACX,MAAM,EACN,OAAO,EACP,cAAc,EACf,MAAM,YAAY,CAAA;AAEnB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,6BAA6B,CA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d,OAAO,CAAC,0BAA0B,CAAC;CASvC"}
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@sixb/sync-worker",
3
+ "version": "0.0.1",
4
+ "description": "Worker that runs Sixb syncs",
5
+ "keywords": [
6
+ "sixb",
7
+ "bun",
8
+ "worker"
9
+ ],
10
+ "homepage": "https://sixb.ai",
11
+ "bugs": {
12
+ "url": "https://github.com/sixb-ai/sixb/issues"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/sixb-ai/sixb.git",
17
+ "directory": "packages/sync-worker"
18
+ },
19
+ "author": "Sixb contributors",
20
+ "type": "module",
21
+ "main": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "bun": "./src/index.ts",
27
+ "import": "./dist/index.js",
28
+ "default": "./dist/index.js"
29
+ }
30
+ },
31
+ "scripts": {
32
+ "build": "bun ../../scripts/build-package.ts",
33
+ "typecheck": "tsc --noEmit",
34
+ "test": "bun test",
35
+ "prepack": "bun run build"
36
+ },
37
+ "dependencies": {
38
+ "@sixb/core": "0.0.1"
39
+ },
40
+ "devDependencies": {
41
+ "@sixb/lake-local": "0.0.1",
42
+ "@types/bun": "latest",
43
+ "typescript": "^5.7.0"
44
+ },
45
+ "license": "MIT",
46
+ "engines": {
47
+ "bun": ">=1.3.0"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "files": [
53
+ "dist",
54
+ "src",
55
+ "README.md",
56
+ "LICENSE"
57
+ ]
58
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export type { SyncWorkerSixb } from "./worker"
2
+ export { SyncWorker } from "./worker"
@@ -0,0 +1,83 @@
1
+ import type { DatasetRow, SyncReadResult } from "@sixb/core"
2
+
3
+ function isPlainObject(value: unknown): value is DatasetRow {
4
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
5
+ return false
6
+ }
7
+
8
+ const prototype = Object.getPrototypeOf(value)
9
+ return prototype === Object.prototype || prototype === null
10
+ }
11
+
12
+ function isIterable(value: unknown): value is Iterable<unknown> {
13
+ return (
14
+ value !== null &&
15
+ value !== undefined &&
16
+ typeof (value as { [Symbol.iterator]?: unknown })[Symbol.iterator] === "function"
17
+ )
18
+ }
19
+
20
+ function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {
21
+ return (
22
+ value !== null &&
23
+ value !== undefined &&
24
+ typeof (value as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === "function"
25
+ )
26
+ }
27
+
28
+ function toAbortError(signal: AbortSignal): Error {
29
+ if (signal.reason instanceof Error) {
30
+ return signal.reason
31
+ }
32
+
33
+ const message =
34
+ typeof signal.reason === "string" && signal.reason.length > 0
35
+ ? signal.reason
36
+ : "[SixbSyncWorker] Operation was cancelled."
37
+
38
+ const error = new Error(message)
39
+ error.name = "AbortError"
40
+ return error
41
+ }
42
+
43
+ export function throwIfAborted(signal: AbortSignal): void {
44
+ if (signal.aborted) {
45
+ throw toAbortError(signal)
46
+ }
47
+ }
48
+
49
+ export function assertDatasetRow(value: unknown, syncId: string, itemIndex: number): DatasetRow {
50
+ if (isPlainObject(value)) {
51
+ return value
52
+ }
53
+
54
+ throw new Error(
55
+ `[SixbSyncWorker] Sync '${syncId}' returned an invalid row at item ${itemIndex}. Dataset rows must be plain objects.`
56
+ )
57
+ }
58
+
59
+ export async function* normalizeReadResult(
60
+ readResult: SyncReadResult,
61
+ syncId: string
62
+ ): AsyncIterable<unknown> {
63
+ if (isAsyncIterable(readResult)) {
64
+ yield* readResult
65
+ return
66
+ }
67
+
68
+ if (isIterable(readResult)) {
69
+ for (const item of readResult) {
70
+ yield item
71
+ }
72
+ return
73
+ }
74
+
75
+ if (isPlainObject(readResult)) {
76
+ yield readResult
77
+ return
78
+ }
79
+
80
+ throw new Error(
81
+ `[SixbSyncWorker] Sync '${syncId}' returned an unsupported read result. Expected a row object, iterable, or async iterable.`
82
+ )
83
+ }
@@ -0,0 +1,337 @@
1
+ import {
2
+ assertJsonValue,
3
+ type BlobStorage,
4
+ cloneJsonValue,
5
+ type FileRef,
6
+ getDatasetRowValidationError,
7
+ isFileRef,
8
+ type JsonValue,
9
+ } from "@sixb/core"
10
+ import { resolveLogsRuntime } from "@sixb/core/internal/logging"
11
+ import type { DatasetVersion, LakeWriteSession } from "@sixb/core/lake-storage"
12
+ import type { SyncRunFailure, SyncRunRecord } from "@sixb/core/storage"
13
+ import { assertDatasetRow, normalizeReadResult, throwIfAborted } from "./normalize"
14
+ import type { RunSyncJobInput, SyncRunResult } from "./types"
15
+
16
+ export class SyncRunAlreadyStartedError extends Error {
17
+ override readonly name = "SyncRunAlreadyStartedError"
18
+
19
+ constructor(readonly run: SyncRunRecord) {
20
+ super(`[SixbSyncWorker] Sync run '${run.id}' has already started.`)
21
+ }
22
+ }
23
+
24
+ function toSyncRunFailure(error: unknown): SyncRunFailure {
25
+ if (error instanceof Error) {
26
+ return {
27
+ name: error.name,
28
+ message: error.message,
29
+ }
30
+ }
31
+
32
+ return {
33
+ message: String(error),
34
+ }
35
+ }
36
+
37
+ function createBookkeepingError(options: {
38
+ syncId: string
39
+ runId: string
40
+ version: DatasetVersion
41
+ cause: unknown
42
+ }): Error {
43
+ // The lake commit is already durable here, so we surface an explicit repair-needed error.
44
+ return new Error(
45
+ `[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.`,
46
+ { cause: options.cause }
47
+ )
48
+ }
49
+
50
+ function requireFinishedAt(runId: string, finishedAt: Date | undefined): Date {
51
+ if (finishedAt) {
52
+ return finishedAt
53
+ }
54
+
55
+ throw new Error(`[SixbSyncWorker] Sync run '${runId}' finished without a finishedAt timestamp.`)
56
+ }
57
+
58
+ async function verifyFileRef(options: {
59
+ blobStorage: BlobStorage
60
+ syncId: string
61
+ datasetId: string
62
+ columnName: string
63
+ itemIndex: number
64
+ fileRef: FileRef
65
+ }): Promise<void> {
66
+ const blobInfo = await options.blobStorage.stat(options.fileRef.blobId)
67
+ if (!blobInfo) {
68
+ throw new Error(
69
+ `[SixbSyncWorker] Sync '${options.syncId}' returned row ${options.itemIndex} with dataset '${options.datasetId}' column '${options.columnName}' referencing unknown blob '${options.fileRef.blobId}'.`
70
+ )
71
+ }
72
+
73
+ if (blobInfo.digest !== options.fileRef.digest) {
74
+ throw new Error(
75
+ `[SixbSyncWorker] Sync '${options.syncId}' returned row ${options.itemIndex} with dataset '${options.datasetId}' column '${options.columnName}' referencing blob '${options.fileRef.blobId}' with digest '${options.fileRef.digest}', but blob storage has '${blobInfo.digest}'.`
76
+ )
77
+ }
78
+
79
+ if (blobInfo.sizeBytes !== options.fileRef.sizeBytes) {
80
+ throw new Error(
81
+ `[SixbSyncWorker] Sync '${options.syncId}' returned row ${options.itemIndex} with dataset '${options.datasetId}' column '${options.columnName}' referencing blob '${options.fileRef.blobId}' with size ${options.fileRef.sizeBytes}, but blob storage has ${blobInfo.sizeBytes}.`
82
+ )
83
+ }
84
+ }
85
+
86
+ async function verifyRowFileRefs(options: {
87
+ blobStorage: BlobStorage
88
+ syncId: string
89
+ dataset: { id: string; schema: { columns: readonly { name: string; type: string }[] } }
90
+ row: Record<string, unknown>
91
+ itemIndex: number
92
+ }): Promise<void> {
93
+ const fileRefColumns = options.dataset.schema.columns.filter(
94
+ (column) => column.type === "fileRef"
95
+ )
96
+ for (const column of fileRefColumns) {
97
+ const value = options.row[column.name]
98
+ if (!isFileRef(value)) {
99
+ continue
100
+ }
101
+
102
+ await verifyFileRef({
103
+ blobStorage: options.blobStorage,
104
+ syncId: options.syncId,
105
+ datasetId: options.dataset.id,
106
+ columnName: column.name,
107
+ itemIndex: options.itemIndex,
108
+ fileRef: value,
109
+ })
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Run one sync job end to end using a caller-supplied run id.
115
+ *
116
+ * The worker creates the operational sync-run record, streams rows into lake
117
+ * storage, commits one dataset version, and then finalizes the run record with
118
+ * the outcome. It does not own scheduling, retries, or run-id generation.
119
+ */
120
+ export async function runSyncJob(input: RunSyncJobInput): Promise<SyncRunResult> {
121
+ const { runtime, job } = input
122
+ const signal = input.signal ?? new AbortController().signal
123
+ const { syncRunsStorage, lakeStorage, blobStorage } = runtime
124
+
125
+ const sync = runtime.getSyncById(job.syncId)
126
+ if (!sync) {
127
+ throw new Error(`[SixbSyncWorker] Unknown sync '${job.syncId}'.`)
128
+ }
129
+
130
+ const dataset = runtime.getDatasetById(sync.target.dataset.id)
131
+ if (!dataset) {
132
+ throw new Error(
133
+ `[SixbSyncWorker] Sync '${sync.id}' targets unknown dataset '${sync.target.dataset.id}'.`
134
+ )
135
+ }
136
+
137
+ throwIfAborted(signal)
138
+
139
+ let startedRun: SyncRunRecord
140
+ try {
141
+ startedRun = await syncRunsStorage.start({
142
+ projectId: runtime.id,
143
+ id: job.id,
144
+ syncId: sync.id,
145
+ datasetId: dataset.id,
146
+ mode: sync.config.mode,
147
+ expectedLatestVersionId: job.expectedLatestVersionId,
148
+ commitMessage: job.commitMessage,
149
+ })
150
+ } catch (error) {
151
+ const existing = await syncRunsStorage.getById({ projectId: runtime.id, id: job.id })
152
+ if (existing?.syncId === sync.id && existing.datasetId === dataset.id) {
153
+ throw new SyncRunAlreadyStartedError(existing)
154
+ }
155
+ throw error
156
+ }
157
+ await input.onRunStarted?.(startedRun)
158
+
159
+ const logSession = resolveLogsRuntime(runtime.id, runtime.logs).startExecution({
160
+ kind: "sync",
161
+ id: job.id,
162
+ })
163
+ const logger = logSession.logger
164
+ let write: LakeWriteSession | undefined
165
+ let rowsRead = 0
166
+ let committedVersion: DatasetVersion | undefined
167
+
168
+ try {
169
+ throwIfAborted(signal)
170
+ await lakeStorage.createDataset(dataset)
171
+
172
+ const latestSuccessfulRuns = await syncRunsStorage.list({
173
+ projectId: runtime.id,
174
+ syncId: sync.id,
175
+ statuses: ["succeeded"],
176
+ limit: 1,
177
+ order: "desc",
178
+ })
179
+ const previousCheckpoint = latestSuccessfulRuns.runs[0]?.checkpoint
180
+ let nextCheckpoint: JsonValue | undefined =
181
+ previousCheckpoint !== undefined ? cloneJsonValue(previousCheckpoint) : undefined
182
+
183
+ const client = await runtime.connector(sync.connector)
184
+ const readResult = await sync.read(client, {
185
+ projectId: runtime.id,
186
+ syncId: sync.id,
187
+ signal,
188
+ blobs: blobStorage,
189
+ logger,
190
+ checkpoint: previousCheckpoint !== undefined ? cloneJsonValue(previousCheckpoint) : undefined,
191
+ setCheckpoint(next: unknown) {
192
+ assertJsonValue(next, `Sync '${sync.id}' checkpoint`)
193
+ nextCheckpoint = cloneJsonValue(next)
194
+ },
195
+ })
196
+ const rows = normalizeReadResult(readResult, sync.id)
197
+
198
+ throwIfAborted(signal)
199
+
200
+ write = await lakeStorage.beginWrite({
201
+ dataset,
202
+ mode: sync.config.mode,
203
+ producer: {
204
+ kind: "sync",
205
+ id: sync.id,
206
+ runId: job.id,
207
+ },
208
+ })
209
+
210
+ await write.writeRows(
211
+ (async function* () {
212
+ let itemIndex = 0
213
+
214
+ for await (const value of rows) {
215
+ throwIfAborted(signal)
216
+ itemIndex += 1
217
+
218
+ const row = assertDatasetRow(value, sync.id, itemIndex)
219
+ // Validate before handing rows to lake storage so sync failures include
220
+ // the source item index; lake storage still re-validates as the final boundary.
221
+ const validationError = getDatasetRowValidationError(row, dataset)
222
+ if (validationError) {
223
+ throw new Error(
224
+ `[SixbSyncWorker] Sync '${sync.id}' returned an invalid row at item ${itemIndex}. ${validationError}`
225
+ )
226
+ }
227
+
228
+ // Lake storage validates fileRef shape; the worker owns existence checks against blob storage.
229
+ await verifyRowFileRefs({
230
+ blobStorage,
231
+ syncId: sync.id,
232
+ dataset,
233
+ row,
234
+ itemIndex,
235
+ })
236
+
237
+ rowsRead += 1
238
+ yield row
239
+ }
240
+ })()
241
+ )
242
+
243
+ throwIfAborted(signal)
244
+
245
+ if (sync.config.mode === "append" && rowsRead === 0) {
246
+ await write.abort()
247
+ write = undefined
248
+ const version = await lakeStorage.getLatestVersion(dataset.id)
249
+ const finishedRun = await syncRunsStorage.finish({
250
+ projectId: runtime.id,
251
+ id: job.id,
252
+ status: "succeeded",
253
+ rowsRead,
254
+ ...(version
255
+ ? { output: { datasetId: version.datasetId, versionId: version.versionId } }
256
+ : {}),
257
+ checkpoint: nextCheckpoint,
258
+ })
259
+
260
+ return {
261
+ id: job.id,
262
+ syncId: sync.id,
263
+ datasetId: dataset.id,
264
+ mode: sync.config.mode,
265
+ startedAt: startedRun.startedAt,
266
+ finishedAt: requireFinishedAt(job.id, finishedRun.finishedAt),
267
+ rowsRead,
268
+ ...(version ? { version } : {}),
269
+ versionCreated: false,
270
+ }
271
+ }
272
+
273
+ const commit = await write.commit({
274
+ expectedLatestVersionId: job.expectedLatestVersionId,
275
+ commitMessage: job.commitMessage ?? `sync ${sync.id} run ${job.id}`,
276
+ })
277
+ const { outcome, ...version } = commit
278
+ committedVersion = version
279
+ let finishedRun: SyncRunRecord
280
+
281
+ try {
282
+ finishedRun = await syncRunsStorage.finish({
283
+ projectId: runtime.id,
284
+ id: job.id,
285
+ status: "succeeded",
286
+ rowsRead,
287
+ output: {
288
+ datasetId: version.datasetId,
289
+ versionId: version.versionId,
290
+ },
291
+ checkpoint: nextCheckpoint,
292
+ })
293
+ } catch (error) {
294
+ throw createBookkeepingError({
295
+ syncId: sync.id,
296
+ runId: job.id,
297
+ version,
298
+ cause: error,
299
+ })
300
+ }
301
+
302
+ return {
303
+ id: job.id,
304
+ syncId: sync.id,
305
+ datasetId: dataset.id,
306
+ mode: sync.config.mode,
307
+ startedAt: startedRun.startedAt,
308
+ finishedAt: requireFinishedAt(job.id, finishedRun.finishedAt),
309
+ rowsRead,
310
+ version,
311
+ versionCreated: outcome === "created",
312
+ }
313
+ } catch (error) {
314
+ if (!committedVersion) {
315
+ // Before commit succeeds we can still best-effort clean up both the write session and run record.
316
+ await write?.abort().catch(() => {})
317
+
318
+ const status = signal.aborted ? "cancelled" : "failed"
319
+ try {
320
+ const run = await syncRunsStorage.finish({
321
+ projectId: runtime.id,
322
+ id: job.id,
323
+ status,
324
+ rowsRead,
325
+ error: toSyncRunFailure(error),
326
+ })
327
+ if (status === "failed" && run.status === "failed") input.onRunFailed?.(error, run)
328
+ } catch {
329
+ // The run did not transition to the requested terminal status.
330
+ }
331
+ }
332
+
333
+ throw error
334
+ } finally {
335
+ await logSession.flush()
336
+ }
337
+ }
package/src/types.ts ADDED
@@ -0,0 +1,70 @@
1
+ import type {
2
+ BlobStorage,
3
+ ConnectorAdapter,
4
+ ConnectorClient,
5
+ ConnectorDefinition,
6
+ DatasetDefinition,
7
+ LakeStorage,
8
+ SyncDefinition,
9
+ } from "@sixb/core"
10
+ import type { LogsRuntime } from "@sixb/core/internal/logging"
11
+ import type { DatasetVersion, DatasetWriteMode } from "@sixb/core/lake-storage"
12
+ import type { SyncRunRecord, SyncRunStorage } from "@sixb/core/storage"
13
+
14
+ export interface SyncWorkerContext {
15
+ readonly id: string
16
+ readonly syncRunsStorage: SyncRunStorage
17
+ readonly lakeStorage: LakeStorage
18
+ readonly blobStorage: BlobStorage
19
+ readonly logs?: LogsRuntime
20
+
21
+ getDatasetById(datasetId: string): DatasetDefinition | null
22
+ getSyncById(syncId: string): SyncDefinition | null
23
+
24
+ connector<TAdapter extends ConnectorAdapter>(
25
+ definition: ConnectorDefinition<string, TAdapter>
26
+ ): Promise<ConnectorClient<TAdapter>>
27
+ }
28
+
29
+ export interface SyncJob {
30
+ readonly id: string
31
+ readonly syncId: string
32
+ readonly expectedLatestVersionId?: string
33
+ readonly commitMessage?: string
34
+ }
35
+
36
+ export interface RunSyncJobInput {
37
+ readonly runtime: SyncWorkerContext
38
+ readonly job: SyncJob
39
+ readonly signal?: AbortSignal
40
+ readonly onRunStarted?: SyncRunStartedHandler
41
+ readonly onRunFailed?: SyncRunFailedHandler
42
+ }
43
+
44
+ export type SyncRunStartedHandler = (run: SyncRunRecord) => Promise<void> | void
45
+
46
+ export type SyncRunFailedHandler = (error: unknown, run: SyncRunRecord) => void
47
+
48
+ interface SyncRunResultBase {
49
+ readonly id: string
50
+ readonly syncId: string
51
+ readonly datasetId: string
52
+ readonly mode: DatasetWriteMode
53
+ readonly startedAt: Date
54
+ readonly finishedAt: Date
55
+ readonly rowsRead: number
56
+ }
57
+
58
+ export type SyncRunResult = SyncRunResultBase &
59
+ (
60
+ | {
61
+ readonly version: DatasetVersion
62
+ /** True only when this run created the returned dataset version. */
63
+ readonly versionCreated: boolean
64
+ }
65
+ | {
66
+ /** A first empty append has no dataset version yet. */
67
+ readonly version?: undefined
68
+ readonly versionCreated: false
69
+ }
70
+ )