@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.
@@ -0,0 +1,200 @@
1
+ import {
2
+ assertJsonValue,
3
+ cloneJsonValue,
4
+ isJsonValue,
5
+ type JsonValue,
6
+ type SyncConnectorConnection,
7
+ } from "@sixb/core"
8
+ import { createSixbError } from "@sixb/core/internal/errors"
9
+
10
+ const SYNC_CHECKPOINT_KIND = "sync_checkpoint"
11
+ const SYNC_CHECKPOINT_VERSION = 1
12
+
13
+ type SyncCheckpointStrategy = "single" | "connections"
14
+
15
+ interface ConnectionCheckpointEntry {
16
+ readonly connectionId: string
17
+ readonly accountId: string
18
+ readonly checkpoint?: JsonValue
19
+ }
20
+
21
+ export interface SyncCheckpointCodec {
22
+ read(value: JsonValue | undefined): JsonValue | undefined
23
+ serialize(value: JsonValue): JsonValue
24
+ }
25
+
26
+ /** Bind opaque handler checkpoints to the framework source contract stored beside the run. */
27
+ export function createSyncCheckpointCodec(options: {
28
+ readonly syncId: string
29
+ readonly connectorId: string
30
+ readonly strategy: SyncCheckpointStrategy
31
+ }): SyncCheckpointCodec {
32
+ return {
33
+ read(value) {
34
+ if (value === undefined) return undefined
35
+ if (!isSyncCheckpoint(value)) {
36
+ // Static Sync checkpoints predate the framework envelope. Preserve them in place and
37
+ // migrate the next successful run; managed fan-out has no compatible legacy raw format.
38
+ if (options.strategy === "single") return cloneJsonValue(value)
39
+ throw incompatibleCheckpoint(options, "format")
40
+ }
41
+ if (value.version !== SYNC_CHECKPOINT_VERSION) {
42
+ throw incompatibleCheckpoint(options, "version")
43
+ }
44
+ if (value.connectorId !== options.connectorId) {
45
+ throw incompatibleCheckpoint(options, "connector")
46
+ }
47
+ if (value.strategy !== options.strategy) {
48
+ throw incompatibleCheckpoint(options, "strategy")
49
+ }
50
+ if (!("value" in value) || !isJsonValue(value.value)) {
51
+ throw invalidFrameworkCheckpoint(options.syncId)
52
+ }
53
+ return cloneJsonValue(value.value)
54
+ },
55
+ serialize(value) {
56
+ const envelope: unknown = {
57
+ kind: SYNC_CHECKPOINT_KIND,
58
+ version: SYNC_CHECKPOINT_VERSION,
59
+ connectorId: options.connectorId,
60
+ strategy: options.strategy,
61
+ value: cloneJsonValue(value),
62
+ }
63
+ assertJsonValue(envelope, "Sync checkpoint envelope")
64
+ return envelope
65
+ },
66
+ }
67
+ }
68
+
69
+ /** Per-connection cursor state carried inside a framework-managed checkpoint envelope. */
70
+ export class ConnectionCheckpoints {
71
+ private readonly entries: Map<string, ConnectionCheckpointEntry>
72
+
73
+ private constructor(entries: Map<string, ConnectionCheckpointEntry>) {
74
+ this.entries = entries
75
+ }
76
+
77
+ static from(syncId: string, value: JsonValue | undefined): ConnectionCheckpoints {
78
+ if (value === undefined) return new ConnectionCheckpoints(new Map())
79
+ if (!isConnectionCheckpoint(value)) throw invalidConnectionCheckpoint(syncId)
80
+
81
+ const entries = new Map<string, ConnectionCheckpointEntry>()
82
+ for (const candidate of value.entries) {
83
+ if (
84
+ !isRecord(candidate) ||
85
+ typeof candidate.connectionId !== "string" ||
86
+ !candidate.connectionId.trim() ||
87
+ typeof candidate.accountId !== "string" ||
88
+ !candidate.accountId.trim() ||
89
+ entries.has(candidate.connectionId)
90
+ ) {
91
+ throw invalidConnectionCheckpoint(syncId)
92
+ }
93
+ if ("checkpoint" in candidate && !isJsonValue(candidate.checkpoint)) {
94
+ throw invalidConnectionCheckpoint(syncId)
95
+ }
96
+ entries.set(candidate.connectionId, {
97
+ connectionId: candidate.connectionId,
98
+ accountId: candidate.accountId,
99
+ ...(candidate.checkpoint === undefined
100
+ ? {}
101
+ : { checkpoint: cloneJsonValue(candidate.checkpoint as JsonValue) }),
102
+ })
103
+ }
104
+ return new ConnectionCheckpoints(entries)
105
+ }
106
+
107
+ reconcile(connections: readonly SyncConnectorConnection[]): void {
108
+ for (const connection of connections) {
109
+ const existing = this.entries.get(connection.id)
110
+ if (existing && existing.accountId !== connection.account.id) {
111
+ this.entries.delete(connection.id)
112
+ }
113
+ }
114
+ }
115
+
116
+ get(connection: SyncConnectorConnection): JsonValue | undefined {
117
+ const entry = this.entries.get(connection.id)
118
+ if (entry?.accountId !== connection.account.id || entry.checkpoint === undefined) {
119
+ return undefined
120
+ }
121
+ return cloneJsonValue(entry.checkpoint)
122
+ }
123
+
124
+ set(connection: SyncConnectorConnection, checkpoint: JsonValue): void {
125
+ this.entries.set(connection.id, {
126
+ connectionId: connection.id,
127
+ accountId: connection.account.id,
128
+ checkpoint: cloneJsonValue(checkpoint),
129
+ })
130
+ }
131
+
132
+ serialize(): JsonValue {
133
+ const value: unknown = {
134
+ entries: [...this.entries.values()]
135
+ .sort((left, right) => left.connectionId.localeCompare(right.connectionId))
136
+ .map((entry) => ({
137
+ connectionId: entry.connectionId,
138
+ accountId: entry.accountId,
139
+ ...(entry.checkpoint === undefined
140
+ ? {}
141
+ : { checkpoint: cloneJsonValue(entry.checkpoint) }),
142
+ })),
143
+ }
144
+ assertJsonValue(value, "Managed connector Sync checkpoint")
145
+ return value
146
+ }
147
+ }
148
+
149
+ function incompatibleCheckpoint(
150
+ options: { readonly syncId: string; readonly connectorId: string },
151
+ reason: "format" | "version" | "connector" | "strategy"
152
+ ): Error {
153
+ return createSixbError(
154
+ "sync.execution_failed",
155
+ `[SixbSyncWorker] Sync '${options.syncId}' has a checkpoint incompatible with connector '${options.connectorId}'. Use a new Sync id to reset its ingestion state.`,
156
+ {
157
+ details: {
158
+ syncId: options.syncId,
159
+ connectorId: options.connectorId,
160
+ reason: `checkpoint_${reason}`,
161
+ },
162
+ }
163
+ )
164
+ }
165
+
166
+ function invalidFrameworkCheckpoint(syncId: string): Error {
167
+ return createSixbError(
168
+ "internal.unexpected",
169
+ `[SixbSyncWorker] Sync '${syncId}' has an invalid checkpoint envelope.`,
170
+ { details: { syncId } }
171
+ )
172
+ }
173
+
174
+ function invalidConnectionCheckpoint(syncId: string): Error {
175
+ return createSixbError(
176
+ "internal.unexpected",
177
+ `[SixbSyncWorker] Sync '${syncId}' has an invalid managed connector checkpoint.`,
178
+ { details: { syncId } }
179
+ )
180
+ }
181
+
182
+ function isSyncCheckpoint(value: JsonValue): value is JsonValue & {
183
+ readonly kind: typeof SYNC_CHECKPOINT_KIND
184
+ readonly version?: JsonValue
185
+ readonly connectorId?: JsonValue
186
+ readonly strategy?: JsonValue
187
+ readonly value?: JsonValue
188
+ } {
189
+ return isRecord(value) && value.kind === SYNC_CHECKPOINT_KIND
190
+ }
191
+
192
+ function isConnectionCheckpoint(value: JsonValue): value is JsonValue & {
193
+ readonly entries: JsonValue[]
194
+ } {
195
+ return isRecord(value) && Array.isArray(value.entries)
196
+ }
197
+
198
+ function isRecord(value: unknown): value is Record<string, unknown> {
199
+ return typeof value === "object" && value !== null && !Array.isArray(value)
200
+ }
package/src/index.ts CHANGED
@@ -1,2 +1,2 @@
1
- export type { SyncWorkerSixb } from "./worker"
1
+ export type { SyncWorkerHost } from "./worker"
2
2
  export { SyncWorker } from "./worker"
package/src/normalize.ts CHANGED
@@ -46,6 +46,28 @@ export function throwIfAborted(signal: AbortSignal): void {
46
46
  }
47
47
  }
48
48
 
49
+ /** Stop awaiting user/provider work when the queue delivery is cancelled or loses its lease. */
50
+ export async function runAbortable<T>(
51
+ signal: AbortSignal,
52
+ run: () => PromiseLike<T> | T
53
+ ): Promise<T> {
54
+ throwIfAborted(signal)
55
+ let rejectAborted: ((error: Error) => void) | undefined
56
+ const aborted = new Promise<never>((_resolve, reject) => {
57
+ rejectAborted = reject
58
+ })
59
+ const onAbort = () => rejectAborted?.(toAbortError(signal))
60
+ signal.addEventListener("abort", onAbort, { once: true })
61
+
62
+ const operation = Promise.resolve().then(run)
63
+ operation.catch(() => {})
64
+ try {
65
+ return await Promise.race([operation, aborted])
66
+ } finally {
67
+ signal.removeEventListener("abort", onAbort)
68
+ }
69
+ }
70
+
49
71
  export function assertDatasetRow(value: unknown, syncId: string, itemIndex: number): DatasetRow {
50
72
  if (isPlainObject(value)) {
51
73
  return value
@@ -58,21 +80,41 @@ export function assertDatasetRow(value: unknown, syncId: string, itemIndex: numb
58
80
 
59
81
  export async function* normalizeReadResult(
60
82
  readResult: SyncReadResult,
61
- syncId: string
83
+ syncId: string,
84
+ signal: AbortSignal
62
85
  ): AsyncIterable<unknown> {
63
86
  if (isAsyncIterable(readResult)) {
64
- yield* readResult
87
+ const iterator = readResult[Symbol.asyncIterator]()
88
+ let completed = false
89
+ try {
90
+ while (true) {
91
+ const next = await runAbortable(signal, () => iterator.next())
92
+ if (next.done) {
93
+ completed = true
94
+ return
95
+ }
96
+ yield next.value
97
+ }
98
+ } finally {
99
+ if (!completed && iterator.return) {
100
+ const closing = Promise.resolve().then(() => iterator.return?.())
101
+ if (signal.aborted) closing.catch(() => {})
102
+ else await closing
103
+ }
104
+ }
65
105
  return
66
106
  }
67
107
 
68
108
  if (isIterable(readResult)) {
69
109
  for (const item of readResult) {
110
+ throwIfAborted(signal)
70
111
  yield item
71
112
  }
72
113
  return
73
114
  }
74
115
 
75
116
  if (isPlainObject(readResult)) {
117
+ throwIfAborted(signal)
76
118
  yield readResult
77
119
  return
78
120
  }