@open-mercato/core 0.7.1-develop.7183.1.db9678eeb8 → 0.7.1-develop.7185.1.0f280ef1f1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { hash, compare } from "bcryptjs";
3
3
  import { ApiKey } from "../data/entities.js";
4
- import { createKmsService } from "@open-mercato/shared/lib/encryption/kms";
5
- import { encryptWithAesGcm, decryptWithAesGcm } from "@open-mercato/shared/lib/encryption/aes";
4
+ import { createKmsService, resolveEncryptionMode } from "@open-mercato/shared/lib/encryption/kms";
5
+ import { encryptWithAesGcm, decryptWithAesGcm, looksLikeEncryptedPayload } from "@open-mercato/shared/lib/encryption/aes";
6
6
  import { getSharedApiKeyAuthCache } from "@open-mercato/shared/lib/auth/apiKeyAuthCache";
7
7
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
8
8
  import { createLogger } from "@open-mercato/shared/lib/logger";
@@ -11,7 +11,15 @@ const BCRYPT_COST = 10;
11
11
  async function encryptSessionSecret(secret, tenantId) {
12
12
  if (!tenantId) return null;
13
13
  const kms = createKmsService();
14
- if (!kms.isHealthy()) return null;
14
+ const mode = resolveEncryptionMode(kms);
15
+ if (mode === "disabled") return secret;
16
+ if (mode === "unavailable") {
17
+ logger.warn(
18
+ "Tenant data encryption is enabled but no DEK is reachable; session secret not stored. MCP session-token auth will fail until the KMS recovers.",
19
+ { tenantId }
20
+ );
21
+ return null;
22
+ }
15
23
  const dek = await kms.getTenantDek(tenantId);
16
24
  if (!dek) {
17
25
  const created = await kms.createTenantDek(tenantId);
@@ -22,13 +30,21 @@ async function encryptSessionSecret(secret, tenantId) {
22
30
  const encrypted = encryptWithAesGcm(secret, dek.key);
23
31
  return encrypted.value;
24
32
  }
25
- async function decryptSessionSecret(encrypted, tenantId) {
26
- if (!tenantId || !encrypted) return null;
33
+ async function decryptSessionSecret(stored, tenantId) {
34
+ if (!tenantId || !stored) return null;
27
35
  const kms = createKmsService();
28
- if (!kms.isHealthy()) return null;
36
+ const mode = resolveEncryptionMode(kms);
37
+ if (mode === "disabled") {
38
+ return looksLikeEncryptedPayload(stored) ? null : stored;
39
+ }
40
+ if (mode === "unavailable") {
41
+ logger.warn("Tenant data encryption is enabled but no DEK is reachable; cannot recover session secret", { tenantId });
42
+ return null;
43
+ }
44
+ if (!looksLikeEncryptedPayload(stored)) return stored;
29
45
  const dek = await kms.getTenantDek(tenantId);
30
46
  if (!dek) return null;
31
- return decryptWithAesGcm(encrypted, dek.key);
47
+ return decryptWithAesGcm(stored, dek.key);
32
48
  }
33
49
  function generateApiKeySecret() {
34
50
  const short = randomBytes(4).toString("hex");
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/api_keys/services/apiKeyService.ts"],
4
- "sourcesContent": ["import { randomBytes } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { hash, compare } from 'bcryptjs'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { Role } from '@open-mercato/core/modules/auth/data/entities'\nimport { ApiKey } from '../data/entities'\nimport { createKmsService } from '@open-mercato/shared/lib/encryption/kms'\nimport { encryptWithAesGcm, decryptWithAesGcm } from '@open-mercato/shared/lib/encryption/aes'\nimport { getSharedApiKeyAuthCache } from '@open-mercato/shared/lib/auth/apiKeyAuthCache'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('api_keys').child({ component: 'api-key-service' })\n\nconst BCRYPT_COST = 10\n\n// =============================================================================\n// Session Secret Encryption Helpers\n// =============================================================================\n\n/**\n * Encrypt an API key secret for storage.\n * Uses tenant-specific DEK if available, otherwise returns null.\n */\nasync function encryptSessionSecret(\n secret: string,\n tenantId: string | null\n): Promise<string | null> {\n if (!tenantId) return null\n\n const kms = createKmsService()\n if (!kms.isHealthy()) return null\n\n const dek = await kms.getTenantDek(tenantId)\n if (!dek) {\n // Try to create a DEK if one doesn't exist\n const created = await kms.createTenantDek(tenantId)\n if (!created) return null\n const encrypted = encryptWithAesGcm(secret, created.key)\n return encrypted.value\n }\n\n const encrypted = encryptWithAesGcm(secret, dek.key)\n return encrypted.value\n}\n\n/**\n * Decrypt an API key secret from storage.\n * Returns null if decryption fails or no DEK available.\n */\nasync function decryptSessionSecret(\n encrypted: string,\n tenantId: string | null\n): Promise<string | null> {\n if (!tenantId || !encrypted) return null\n\n const kms = createKmsService()\n if (!kms.isHealthy()) return null\n\n const dek = await kms.getTenantDek(tenantId)\n if (!dek) return null\n\n return decryptWithAesGcm(encrypted, dek.key)\n}\n\nexport type CreateApiKeyInput = {\n name: string\n description?: string | null\n tenantId?: string | null\n organizationId?: string | null\n roles?: string[]\n expiresAt?: Date | null\n createdBy?: string | null\n}\n\nexport type ApiKeyWithSecret = {\n record: ApiKey\n secret: string\n}\n\nexport function generateApiKeySecret(): { secret: string; prefix: string } {\n const short = randomBytes(4).toString('hex')\n const body = randomBytes(24).toString('hex')\n const secret = `omk_${short}.${body}`\n const prefix = secret.slice(0, 12)\n return { secret, prefix }\n}\n\nexport async function hashApiKey(secret: string): Promise<string> {\n return hash(secret, BCRYPT_COST)\n}\n\nexport async function verifyApiKey(secret: string, keyHash: string): Promise<boolean> {\n return compare(secret, keyHash)\n}\n\nexport async function createApiKey(\n em: EntityManager,\n input: CreateApiKeyInput,\n opts: { rbac?: RbacService } = {},\n): Promise<ApiKeyWithSecret> {\n const { secret, prefix } = generateApiKeySecret()\n const keyHash = await hashApiKey(secret)\n const record = em.create(ApiKey, {\n name: input.name,\n description: input.description ?? null,\n tenantId: input.tenantId ?? null,\n organizationId: input.organizationId ?? null,\n keyHash,\n keyPrefix: prefix,\n rolesJson: Array.isArray(input.roles) ? input.roles : [],\n createdBy: input.createdBy ?? null,\n expiresAt: input.expiresAt ?? null,\n createdAt: new Date(),\n })\n await em.persist(record).flush()\n if (opts.rbac) {\n await opts.rbac.invalidateUserCache(`api_key:${record.id}`)\n }\n return { record, secret }\n}\n\nexport async function deleteApiKey(\n em: EntityManager,\n id: string,\n opts: { rbac?: RbacService } = {},\n): Promise<void> {\n const record = await em.findOne(ApiKey, { id })\n if (!record) return\n record.deletedAt = new Date()\n await em.persist(record).flush()\n getSharedApiKeyAuthCache().invalidateByKeyId(record.id)\n if (opts.rbac) {\n await opts.rbac.invalidateUserCache(`api_key:${record.id}`)\n }\n}\n\nexport async function findApiKeyBySecret(em: EntityManager, secret: string): Promise<ApiKey | null> {\n if (!secret) return null\n // Extract prefix from the secret for fast candidate lookup\n const prefix = secret.slice(0, 12)\n // Find candidates by prefix (fast index lookup). Invariant: the unique keyPrefix\n // constraint plus the deletedAt: null filter keep this to at most one live row, so\n // the bcrypt loop below stays bounded. Do not widen the prefix space or relax either\n // filter without re-evaluating that cost (see #3812).\n const candidates = await em.find(ApiKey, { keyPrefix: prefix, deletedAt: null })\n // Verify each candidate with bcrypt until we find a match\n for (const candidate of candidates) {\n if (candidate.expiresAt && candidate.expiresAt.getTime() < Date.now()) continue\n const isValid = await verifyApiKey(secret, candidate.keyHash)\n if (isValid) return candidate\n }\n return null\n}\n\n// =============================================================================\n// Session-scoped API Keys (for AI Chat ephemeral authorization)\n// =============================================================================\n\nexport type CreateSessionApiKeyInput = {\n sessionToken: string\n userId: string\n userRoles: string[]\n tenantId?: string | null\n organizationId?: string | null\n ttlMinutes?: number\n}\n\n/**\n * Generate a unique session token for ephemeral API keys.\n * Format: sess_{32 hex chars}\n */\nexport function generateSessionToken(): string {\n return `sess_${randomBytes(16).toString('hex')}`\n}\n\n/**\n * Create an ephemeral API key scoped to a chat session.\n * The key inherits the user's roles and expires after ttlMinutes (default 30).\n * The API key secret is encrypted and stored so it can be recovered for API calls.\n */\nexport async function createSessionApiKey(\n em: EntityManager,\n input: CreateSessionApiKeyInput\n): Promise<{ keyId: string; secret: string; sessionToken: string }> {\n const { secret, prefix } = generateApiKeySecret()\n const ttl = input.ttlMinutes ?? 30\n const expiresAt = new Date(Date.now() + ttl * 60 * 1000)\n const keyHash = await hashApiKey(secret)\n\n // Encrypt the secret for later retrieval (used by MCP server for API calls)\n const encryptedSecret = await encryptSessionSecret(secret, input.tenantId ?? null)\n\n const record = em.create(ApiKey, {\n name: `__session_${input.sessionToken}__`,\n description: 'Ephemeral session API key for AI chat',\n tenantId: input.tenantId ?? null,\n organizationId: input.organizationId ?? null,\n keyHash,\n keyPrefix: prefix,\n rolesJson: input.userRoles,\n createdBy: input.userId,\n sessionToken: input.sessionToken,\n sessionUserId: input.userId,\n sessionSecretEncrypted: encryptedSecret,\n expiresAt,\n createdAt: new Date(),\n })\n\n await em.persist(record).flush()\n\n return {\n keyId: record.id,\n secret,\n sessionToken: input.sessionToken,\n }\n}\n\n/**\n * Find an API key by its session token.\n * Returns null if not found, expired, or deleted.\n */\nexport async function findApiKeyBySessionToken(\n em: EntityManager,\n sessionToken: string\n): Promise<ApiKey | null> {\n if (!sessionToken) return null\n\n const record = await em.findOne(ApiKey, {\n sessionToken,\n deletedAt: null,\n })\n\n if (!record) return null\n if (record.expiresAt && record.expiresAt.getTime() < Date.now()) return null\n\n return record\n}\n\n/**\n * Bind an OpenCode session id to the api_key row that owns this chat session.\n *\n * Called by the chat dispatcher the first time we see the `done` event for a\n * freshly minted session token. From that point on,\n * `findApiKeyByOpencodeSessionId(em, opencodeSessionId)` returns the same row,\n * which the ai-assistant runtime uses to assert ownership on every resume.\n *\n * Throws when the session token has been deleted/expired, and when the api_key\n * row is already bound to a DIFFERENT OpenCode session (defensive: this should\n * never happen in practice because each chat mints a new session token, but we\n * fail closed instead of silently overwriting).\n *\n * Idempotent when the row is already bound to the same OpenCode session id.\n */\nexport async function bindOpencodeSessionToApiKey(\n em: EntityManager,\n sessionToken: string,\n opencodeSessionId: string\n): Promise<void> {\n if (!sessionToken) throw new Error('Session token not found or expired')\n if (!opencodeSessionId) throw new Error('OpenCode session id is required')\n\n const row = await findApiKeyBySessionToken(em, sessionToken)\n if (!row) throw new Error('Session token not found or expired')\n\n if (row.opencodeSessionId === opencodeSessionId) return\n if (row.opencodeSessionId && row.opencodeSessionId !== opencodeSessionId) {\n throw new Error('Session token already bound to a different OpenCode session')\n }\n\n row.opencodeSessionId = opencodeSessionId\n await em.persist(row).flush()\n}\n\n/**\n * Find an api_key row by its bound OpenCode session id.\n *\n * Returns null if no active row matches, or if the matched row is expired\n * (same contract as `findApiKeyBySessionToken`). Uses\n * `findOneWithDecryption` so encrypted-at-rest fields on the row are decrypted\n * before the ai-assistant runtime inspects `sessionUserId` / `tenantId` /\n * `organizationId` for the ownership check.\n */\nexport async function findApiKeyByOpencodeSessionId(\n em: EntityManager,\n opencodeSessionId: string\n): Promise<ApiKey | null> {\n if (!opencodeSessionId) return null\n\n const record = await findOneWithDecryption(\n em,\n ApiKey,\n { opencodeSessionId, deletedAt: null } as any,\n )\n\n if (!record) return null\n if (record.expiresAt && record.expiresAt.getTime() < Date.now()) return null\n\n return record\n}\n\n/**\n * Find a session API key with its decrypted secret.\n * Returns null if not found, expired, deleted, or decryption fails.\n * This is used by the MCP server to recover the API key secret for making\n * authenticated API calls on behalf of the user.\n */\nexport async function findSessionApiKeyWithSecret(\n em: EntityManager,\n sessionToken: string\n): Promise<{ key: ApiKey; secret: string } | null> {\n const record = await findApiKeyBySessionToken(em, sessionToken)\n if (!record) return null\n\n // If no encrypted secret stored, cannot recover\n if (!record.sessionSecretEncrypted) {\n logger.warn('Session key has no encrypted secret', { apiKeyId: record.id })\n return null\n }\n\n // Decrypt the secret\n const secret = await decryptSessionSecret(record.sessionSecretEncrypted, record.tenantId ?? null)\n if (!secret) {\n logger.warn('Failed to decrypt session secret', { apiKeyId: record.id })\n return null\n }\n\n return { key: record, secret }\n}\n\n/**\n * Delete an ephemeral API key by its session token.\n */\nexport async function deleteSessionApiKey(\n em: EntityManager,\n sessionToken: string\n): Promise<void> {\n const record = await em.findOne(ApiKey, { sessionToken, deletedAt: null })\n if (!record) return\n\n record.deletedAt = new Date()\n await em.persist(record).flush()\n getSharedApiKeyAuthCache().invalidateByKeyId(record.id)\n}\n\n/**\n * Execute a function with a one-time API key\n *\n * Creates a temporary API key, executes the function, and deletes the key.\n * Perfect for workflow activities that need authenticated access without\n * storing long-lived credentials.\n *\n * @param em - Entity manager\n * @param input - API key configuration\n * @param fn - Function to execute with the API key secret\n * @returns Result of the function\n */\nconst ONETIME_KEY_MAX_TTL_MS = 5 * 60 * 1000\n\nexport async function withOnetimeApiKey<T>(\n em: EntityManager,\n input: CreateApiKeyInput,\n fn: (secret: string) => Promise<T>\n): Promise<T> {\n const maxExpiresAt = new Date(Date.now() + ONETIME_KEY_MAX_TTL_MS)\n const safeExpiresAt = input.expiresAt && input.expiresAt < maxExpiresAt\n ? input.expiresAt\n : maxExpiresAt\n\n const { record, secret } = await createApiKey(em, {\n ...input,\n name: input.name || '__onetime__',\n description: input.description || 'One-time API key',\n expiresAt: safeExpiresAt,\n })\n\n try {\n const result = await fn(secret)\n return result\n } finally {\n try {\n record.deletedAt = new Date()\n await em.persist(record).flush()\n getSharedApiKeyAuthCache().invalidateByKeyId(record.id)\n } catch (error) {\n logger.error('Failed to soft-delete one-time API key', { err: error })\n }\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,mBAAmB;AAE5B,SAAS,MAAM,eAAe;AAG9B,SAAS,cAAc;AACvB,SAAS,wBAAwB;AACjC,SAAS,mBAAmB,yBAAyB;AACrD,SAAS,gCAAgC;AACzC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,UAAU,EAAE,MAAM,EAAE,WAAW,kBAAkB,CAAC;AAE9E,MAAM,cAAc;AAUpB,eAAe,qBACb,QACA,UACwB;AACxB,MAAI,CAAC,SAAU,QAAO;AAEtB,QAAM,MAAM,iBAAiB;AAC7B,MAAI,CAAC,IAAI,UAAU,EAAG,QAAO;AAE7B,QAAM,MAAM,MAAM,IAAI,aAAa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AAI,KAAK,KAAK,IAAI,IAAI,sBAAsB;AACjE,QAAM,gBAAgB,MAAM,aAAa,MAAM,YAAY,eACvD,MAAM,YACN;AAEJ,QAAM,EAAE,QAAQ,OAAO,IAAI,MAAM,aAAa,IAAI;AAAA,IAChD,GAAG;AAAA,IACH,MAAM,MAAM,QAAQ;AAAA,IACpB,aAAa,MAAM,eAAe;AAAA,IAClC,WAAW;AAAA,EACb,CAAC;AAED,MAAI;AACF,UAAM,SAAS,MAAM,GAAG,MAAM;AAC9B,WAAO;AAAA,EACT,UAAE;AACA,QAAI;AACF,aAAO,YAAY,oBAAI,KAAK;AAC5B,YAAM,GAAG,QAAQ,MAAM,EAAE,MAAM;AAC/B,+BAAyB,EAAE,kBAAkB,OAAO,EAAE;AAAA,IACxD,SAAS,OAAO;AACd,aAAO,MAAM,0CAA0C,EAAE,KAAK,MAAM,CAAC;AAAA,IACvE;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { randomBytes } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { hash, compare } from 'bcryptjs'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { Role } from '@open-mercato/core/modules/auth/data/entities'\nimport { ApiKey } from '../data/entities'\nimport { createKmsService, resolveEncryptionMode } from '@open-mercato/shared/lib/encryption/kms'\nimport { encryptWithAesGcm, decryptWithAesGcm, looksLikeEncryptedPayload } from '@open-mercato/shared/lib/encryption/aes'\nimport { getSharedApiKeyAuthCache } from '@open-mercato/shared/lib/auth/apiKeyAuthCache'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('api_keys').child({ component: 'api-key-service' })\n\nconst BCRYPT_COST = 10\n\n// =============================================================================\n// Session Secret Encryption Helpers\n// =============================================================================\n\n/**\n * Seal an ephemeral session API key secret for storage in `session_secret_encrypted`.\n *\n * Returns null when the secret cannot be stored at all, which costs the caller MCP session-token\n * auth (the secret is unrecoverable and `findSessionApiKeyWithSecret` gives up).\n *\n * Under `TENANT_DATA_ENCRYPTION=no` the secret is stored as-is. That is the same bargain the rest\n * of the system already strikes in that mode -- emails, integration credentials and the search\n * index all sit in plaintext -- and it is what keeps the AI chat working when an operator opts\n * out. A DEK that is merely unreachable is a different situation and still yields null: writing a\n * secret in the clear because Vault happens to be down is not a downgrade anyone asked for.\n */\nasync function encryptSessionSecret(\n secret: string,\n tenantId: string | null\n): Promise<string | null> {\n if (!tenantId) return null\n\n const kms = createKmsService()\n const mode = resolveEncryptionMode(kms)\n if (mode === 'disabled') return secret\n if (mode === 'unavailable') {\n logger.warn(\n 'Tenant data encryption is enabled but no DEK is reachable; session secret not stored. '\n + 'MCP session-token auth will fail until the KMS recovers.',\n { tenantId },\n )\n return null\n }\n\n const dek = await kms.getTenantDek(tenantId)\n if (!dek) {\n // Try to create a DEK if one doesn't exist\n const created = await kms.createTenantDek(tenantId)\n if (!created) return null\n const encrypted = encryptWithAesGcm(secret, created.key)\n return encrypted.value\n }\n\n const encrypted = encryptWithAesGcm(secret, dek.key)\n return encrypted.value\n}\n\n/**\n * Recover a session API key secret written by {@link encryptSessionSecret}.\n * Returns null if it cannot be recovered.\n */\nasync function decryptSessionSecret(\n stored: string,\n tenantId: string | null\n): Promise<string | null> {\n if (!tenantId || !stored) return null\n\n const kms = createKmsService()\n const mode = resolveEncryptionMode(kms)\n if (mode === 'disabled') {\n // Written in the clear by the branch above -- unless it predates the toggle being flipped, in\n // which case it is a sealed envelope no key can open and null is the honest answer.\n return looksLikeEncryptedPayload(stored) ? null : stored\n }\n if (mode === 'unavailable') {\n logger.warn('Tenant data encryption is enabled but no DEK is reachable; cannot recover session secret', { tenantId })\n return null\n }\n\n // Mirror of the `disabled` branch: a secret written in the clear while the toggle was off is\n // still recoverable after it is switched back on. Without this `decryptWithAesGcm` reads the\n // plaintext as a malformed envelope and returns null, so the flip would silently break every\n // live session rather than only the ones sealed under the old setting.\n if (!looksLikeEncryptedPayload(stored)) return stored\n\n const dek = await kms.getTenantDek(tenantId)\n if (!dek) return null\n\n return decryptWithAesGcm(stored, dek.key)\n}\n\nexport type CreateApiKeyInput = {\n name: string\n description?: string | null\n tenantId?: string | null\n organizationId?: string | null\n roles?: string[]\n expiresAt?: Date | null\n createdBy?: string | null\n}\n\nexport type ApiKeyWithSecret = {\n record: ApiKey\n secret: string\n}\n\nexport function generateApiKeySecret(): { secret: string; prefix: string } {\n const short = randomBytes(4).toString('hex')\n const body = randomBytes(24).toString('hex')\n const secret = `omk_${short}.${body}`\n const prefix = secret.slice(0, 12)\n return { secret, prefix }\n}\n\nexport async function hashApiKey(secret: string): Promise<string> {\n return hash(secret, BCRYPT_COST)\n}\n\nexport async function verifyApiKey(secret: string, keyHash: string): Promise<boolean> {\n return compare(secret, keyHash)\n}\n\nexport async function createApiKey(\n em: EntityManager,\n input: CreateApiKeyInput,\n opts: { rbac?: RbacService } = {},\n): Promise<ApiKeyWithSecret> {\n const { secret, prefix } = generateApiKeySecret()\n const keyHash = await hashApiKey(secret)\n const record = em.create(ApiKey, {\n name: input.name,\n description: input.description ?? null,\n tenantId: input.tenantId ?? null,\n organizationId: input.organizationId ?? null,\n keyHash,\n keyPrefix: prefix,\n rolesJson: Array.isArray(input.roles) ? input.roles : [],\n createdBy: input.createdBy ?? null,\n expiresAt: input.expiresAt ?? null,\n createdAt: new Date(),\n })\n await em.persist(record).flush()\n if (opts.rbac) {\n await opts.rbac.invalidateUserCache(`api_key:${record.id}`)\n }\n return { record, secret }\n}\n\nexport async function deleteApiKey(\n em: EntityManager,\n id: string,\n opts: { rbac?: RbacService } = {},\n): Promise<void> {\n const record = await em.findOne(ApiKey, { id })\n if (!record) return\n record.deletedAt = new Date()\n await em.persist(record).flush()\n getSharedApiKeyAuthCache().invalidateByKeyId(record.id)\n if (opts.rbac) {\n await opts.rbac.invalidateUserCache(`api_key:${record.id}`)\n }\n}\n\nexport async function findApiKeyBySecret(em: EntityManager, secret: string): Promise<ApiKey | null> {\n if (!secret) return null\n // Extract prefix from the secret for fast candidate lookup\n const prefix = secret.slice(0, 12)\n // Find candidates by prefix (fast index lookup). Invariant: the unique keyPrefix\n // constraint plus the deletedAt: null filter keep this to at most one live row, so\n // the bcrypt loop below stays bounded. Do not widen the prefix space or relax either\n // filter without re-evaluating that cost (see #3812).\n const candidates = await em.find(ApiKey, { keyPrefix: prefix, deletedAt: null })\n // Verify each candidate with bcrypt until we find a match\n for (const candidate of candidates) {\n if (candidate.expiresAt && candidate.expiresAt.getTime() < Date.now()) continue\n const isValid = await verifyApiKey(secret, candidate.keyHash)\n if (isValid) return candidate\n }\n return null\n}\n\n// =============================================================================\n// Session-scoped API Keys (for AI Chat ephemeral authorization)\n// =============================================================================\n\nexport type CreateSessionApiKeyInput = {\n sessionToken: string\n userId: string\n userRoles: string[]\n tenantId?: string | null\n organizationId?: string | null\n ttlMinutes?: number\n}\n\n/**\n * Generate a unique session token for ephemeral API keys.\n * Format: sess_{32 hex chars}\n */\nexport function generateSessionToken(): string {\n return `sess_${randomBytes(16).toString('hex')}`\n}\n\n/**\n * Create an ephemeral API key scoped to a chat session.\n * The key inherits the user's roles and expires after ttlMinutes (default 30).\n * The API key secret is encrypted and stored so it can be recovered for API calls.\n */\nexport async function createSessionApiKey(\n em: EntityManager,\n input: CreateSessionApiKeyInput\n): Promise<{ keyId: string; secret: string; sessionToken: string }> {\n const { secret, prefix } = generateApiKeySecret()\n const ttl = input.ttlMinutes ?? 30\n const expiresAt = new Date(Date.now() + ttl * 60 * 1000)\n const keyHash = await hashApiKey(secret)\n\n // Encrypt the secret for later retrieval (used by MCP server for API calls)\n const encryptedSecret = await encryptSessionSecret(secret, input.tenantId ?? null)\n\n const record = em.create(ApiKey, {\n name: `__session_${input.sessionToken}__`,\n description: 'Ephemeral session API key for AI chat',\n tenantId: input.tenantId ?? null,\n organizationId: input.organizationId ?? null,\n keyHash,\n keyPrefix: prefix,\n rolesJson: input.userRoles,\n createdBy: input.userId,\n sessionToken: input.sessionToken,\n sessionUserId: input.userId,\n sessionSecretEncrypted: encryptedSecret,\n expiresAt,\n createdAt: new Date(),\n })\n\n await em.persist(record).flush()\n\n return {\n keyId: record.id,\n secret,\n sessionToken: input.sessionToken,\n }\n}\n\n/**\n * Find an API key by its session token.\n * Returns null if not found, expired, or deleted.\n */\nexport async function findApiKeyBySessionToken(\n em: EntityManager,\n sessionToken: string\n): Promise<ApiKey | null> {\n if (!sessionToken) return null\n\n const record = await em.findOne(ApiKey, {\n sessionToken,\n deletedAt: null,\n })\n\n if (!record) return null\n if (record.expiresAt && record.expiresAt.getTime() < Date.now()) return null\n\n return record\n}\n\n/**\n * Bind an OpenCode session id to the api_key row that owns this chat session.\n *\n * Called by the chat dispatcher the first time we see the `done` event for a\n * freshly minted session token. From that point on,\n * `findApiKeyByOpencodeSessionId(em, opencodeSessionId)` returns the same row,\n * which the ai-assistant runtime uses to assert ownership on every resume.\n *\n * Throws when the session token has been deleted/expired, and when the api_key\n * row is already bound to a DIFFERENT OpenCode session (defensive: this should\n * never happen in practice because each chat mints a new session token, but we\n * fail closed instead of silently overwriting).\n *\n * Idempotent when the row is already bound to the same OpenCode session id.\n */\nexport async function bindOpencodeSessionToApiKey(\n em: EntityManager,\n sessionToken: string,\n opencodeSessionId: string\n): Promise<void> {\n if (!sessionToken) throw new Error('Session token not found or expired')\n if (!opencodeSessionId) throw new Error('OpenCode session id is required')\n\n const row = await findApiKeyBySessionToken(em, sessionToken)\n if (!row) throw new Error('Session token not found or expired')\n\n if (row.opencodeSessionId === opencodeSessionId) return\n if (row.opencodeSessionId && row.opencodeSessionId !== opencodeSessionId) {\n throw new Error('Session token already bound to a different OpenCode session')\n }\n\n row.opencodeSessionId = opencodeSessionId\n await em.persist(row).flush()\n}\n\n/**\n * Find an api_key row by its bound OpenCode session id.\n *\n * Returns null if no active row matches, or if the matched row is expired\n * (same contract as `findApiKeyBySessionToken`). Uses\n * `findOneWithDecryption` so encrypted-at-rest fields on the row are decrypted\n * before the ai-assistant runtime inspects `sessionUserId` / `tenantId` /\n * `organizationId` for the ownership check.\n */\nexport async function findApiKeyByOpencodeSessionId(\n em: EntityManager,\n opencodeSessionId: string\n): Promise<ApiKey | null> {\n if (!opencodeSessionId) return null\n\n const record = await findOneWithDecryption(\n em,\n ApiKey,\n { opencodeSessionId, deletedAt: null } as any,\n )\n\n if (!record) return null\n if (record.expiresAt && record.expiresAt.getTime() < Date.now()) return null\n\n return record\n}\n\n/**\n * Find a session API key with its decrypted secret.\n * Returns null if not found, expired, deleted, or decryption fails.\n * This is used by the MCP server to recover the API key secret for making\n * authenticated API calls on behalf of the user.\n */\nexport async function findSessionApiKeyWithSecret(\n em: EntityManager,\n sessionToken: string\n): Promise<{ key: ApiKey; secret: string } | null> {\n const record = await findApiKeyBySessionToken(em, sessionToken)\n if (!record) return null\n\n // If no encrypted secret stored, cannot recover\n if (!record.sessionSecretEncrypted) {\n logger.warn('Session key has no encrypted secret', { apiKeyId: record.id })\n return null\n }\n\n // Decrypt the secret\n const secret = await decryptSessionSecret(record.sessionSecretEncrypted, record.tenantId ?? null)\n if (!secret) {\n logger.warn('Failed to decrypt session secret', { apiKeyId: record.id })\n return null\n }\n\n return { key: record, secret }\n}\n\n/**\n * Delete an ephemeral API key by its session token.\n */\nexport async function deleteSessionApiKey(\n em: EntityManager,\n sessionToken: string\n): Promise<void> {\n const record = await em.findOne(ApiKey, { sessionToken, deletedAt: null })\n if (!record) return\n\n record.deletedAt = new Date()\n await em.persist(record).flush()\n getSharedApiKeyAuthCache().invalidateByKeyId(record.id)\n}\n\n/**\n * Execute a function with a one-time API key\n *\n * Creates a temporary API key, executes the function, and deletes the key.\n * Perfect for workflow activities that need authenticated access without\n * storing long-lived credentials.\n *\n * @param em - Entity manager\n * @param input - API key configuration\n * @param fn - Function to execute with the API key secret\n * @returns Result of the function\n */\nconst ONETIME_KEY_MAX_TTL_MS = 5 * 60 * 1000\n\nexport async function withOnetimeApiKey<T>(\n em: EntityManager,\n input: CreateApiKeyInput,\n fn: (secret: string) => Promise<T>\n): Promise<T> {\n const maxExpiresAt = new Date(Date.now() + ONETIME_KEY_MAX_TTL_MS)\n const safeExpiresAt = input.expiresAt && input.expiresAt < maxExpiresAt\n ? input.expiresAt\n : maxExpiresAt\n\n const { record, secret } = await createApiKey(em, {\n ...input,\n name: input.name || '__onetime__',\n description: input.description || 'One-time API key',\n expiresAt: safeExpiresAt,\n })\n\n try {\n const result = await fn(secret)\n return result\n } finally {\n try {\n record.deletedAt = new Date()\n await em.persist(record).flush()\n getSharedApiKeyAuthCache().invalidateByKeyId(record.id)\n } catch (error) {\n logger.error('Failed to soft-delete one-time API key', { err: error })\n }\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,mBAAmB;AAE5B,SAAS,MAAM,eAAe;AAG9B,SAAS,cAAc;AACvB,SAAS,kBAAkB,6BAA6B;AACxD,SAAS,mBAAmB,mBAAmB,iCAAiC;AAChF,SAAS,gCAAgC;AACzC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,UAAU,EAAE,MAAM,EAAE,WAAW,kBAAkB,CAAC;AAE9E,MAAM,cAAc;AAkBpB,eAAe,qBACb,QACA,UACwB;AACxB,MAAI,CAAC,SAAU,QAAO;AAEtB,QAAM,MAAM,iBAAiB;AAC7B,QAAM,OAAO,sBAAsB,GAAG;AACtC,MAAI,SAAS,WAAY,QAAO;AAChC,MAAI,SAAS,eAAe;AAC1B,WAAO;AAAA,MACL;AAAA,MAEA,EAAE,SAAS;AAAA,IACb;AACA,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,MAAM,IAAI,aAAa,QAAQ;AAC3C,MAAI,CAAC,KAAK;AAER,UAAM,UAAU,MAAM,IAAI,gBAAgB,QAAQ;AAClD,QAAI,CAAC,QAAS,QAAO;AACrB,UAAMA,aAAY,kBAAkB,QAAQ,QAAQ,GAAG;AACvD,WAAOA,WAAU;AAAA,EACnB;AAEA,QAAM,YAAY,kBAAkB,QAAQ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K,IAAI,IAAI,sBAAsB;AACjE,QAAM,gBAAgB,MAAM,aAAa,MAAM,YAAY,eACvD,MAAM,YACN;AAEJ,QAAM,EAAE,QAAQ,OAAO,IAAI,MAAM,aAAa,IAAI;AAAA,IAChD,GAAG;AAAA,IACH,MAAM,MAAM,QAAQ;AAAA,IACpB,aAAa,MAAM,eAAe;AAAA,IAClC,WAAW;AAAA,EACb,CAAC;AAED,MAAI;AACF,UAAM,SAAS,MAAM,GAAG,MAAM;AAC9B,WAAO;AAAA,EACT,UAAE;AACA,QAAI;AACF,aAAO,YAAY,oBAAI,KAAK;AAC5B,YAAM,GAAG,QAAQ,MAAM,EAAE,MAAM;AAC/B,+BAAyB,EAAE,kBAAkB,OAAO,EAAE;AAAA,IACxD,SAAS,OAAO;AACd,aAAO,MAAM,0CAA0C,EAAE,KAAK,MAAM,CAAC;AAAA,IACvE;AAAA,EACF;AACF;",
6
6
  "names": ["encrypted"]
7
7
  }
@@ -6,9 +6,38 @@ import { SyncRunOwnershipConflictError } from "./sync-run-service.js";
6
6
  import { forEachBatch } from "./batch-stream.js";
7
7
  import { createLogger } from "@open-mercato/shared/lib/logger";
8
8
  import {
9
- captureTelemetryTrace
9
+ captureTelemetryTrace,
10
+ getTelemetryRuntime
10
11
  } from "@open-mercato/shared/lib/telemetry/runtime";
12
+ import { groupableCode } from "@open-mercato/shared/lib/telemetry/error-code";
11
13
  const logger = createLogger("data_sync").child({ component: "sync-engine" });
14
+ class SyncRunPartialFailureError extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = "SyncRunPartialFailureError";
18
+ }
19
+ }
20
+ const RUN_FAILED_CODE = "data_sync.run_failed";
21
+ function runEventAttributes(run, scope) {
22
+ return {
23
+ "data_sync.run_id": run.id,
24
+ "data_sync.integration_id": run.integrationId,
25
+ "data_sync.entity_type": run.entityType,
26
+ "data_sync.direction": run.direction,
27
+ "om.tenant_id": scope.tenantId,
28
+ "om.organization_id": scope.organizationId
29
+ };
30
+ }
31
+ function itemErrorCode(data, fallback) {
32
+ return groupableCode(data.errorCode, fallback);
33
+ }
34
+ function reportSyncError(error, code, attributes) {
35
+ try {
36
+ getTelemetryRuntime()?.reportError(error, { module: "data_sync", code, attributes });
37
+ } catch (telemetryError) {
38
+ logger.warn("Failed to report a data sync error to telemetry", { code, err: telemetryError });
39
+ }
40
+ }
12
41
  function runSpanAttributes(run, providerKey, scope) {
13
42
  return {
14
43
  "data_sync.run_id": run.id,
@@ -146,13 +175,25 @@ function createSyncEngine(deps) {
146
175
  }
147
176
  async function refreshCoverageSnapshots(entityTypes, scope) {
148
177
  if (!entityTypes || entityTypes.length === 0) return;
149
- await Promise.allSettled(
150
- Array.from(new Set(entityTypes.filter((value) => typeof value === "string" && value.trim().length > 0))).map((entityType) => refreshCoverageSnapshot(deps.em, {
178
+ const types = Array.from(
179
+ new Set(entityTypes.filter((value) => typeof value === "string" && value.trim().length > 0))
180
+ );
181
+ const outcomes = await Promise.allSettled(
182
+ types.map((entityType) => refreshCoverageSnapshot(deps.em, {
151
183
  entityType,
152
184
  tenantId: scope.tenantId,
153
185
  organizationId: scope.organizationId
154
186
  }))
155
187
  );
188
+ outcomes.forEach((outcome, index) => {
189
+ if (outcome.status !== "rejected") return;
190
+ logger.warn("Coverage snapshot refresh failed", { entityType: types[index], err: outcome.reason });
191
+ reportSyncError(outcome.reason, "data_sync.coverage_refresh_failed", {
192
+ entityType: types[index],
193
+ "om.tenant_id": scope.tenantId,
194
+ "om.organization_id": scope.organizationId
195
+ });
196
+ });
156
197
  }
157
198
  async function logImportItemFailures(runId, integrationId, items, scope) {
158
199
  const failedItems = items.filter((item) => item.action === "failed");
@@ -172,6 +213,7 @@ function createSyncEngine(deps) {
172
213
  runId,
173
214
  level: "error",
174
215
  message,
216
+ code: itemErrorCode(item.data, "data_sync.item_failed"),
175
217
  payload: item.data
176
218
  },
177
219
  scope
@@ -190,6 +232,7 @@ function createSyncEngine(deps) {
190
232
  runId,
191
233
  level: "error",
192
234
  message,
235
+ code: "data_sync.export_item_failed",
193
236
  payload: { kind: "export-item-failure", summary: result.error }
194
237
  },
195
238
  scope
@@ -342,13 +385,30 @@ function createSyncEngine(deps) {
342
385
  });
343
386
  }
344
387
  if (status === "completed") {
388
+ if (run.failedCount > 0) {
389
+ reportSyncError(
390
+ new SyncRunPartialFailureError(`Sync run completed with ${run.failedCount} failed item(s)`),
391
+ "data_sync.run_partial_failure",
392
+ {
393
+ ...runEventAttributes(run, scope),
394
+ "data_sync.failed_count": run.failedCount,
395
+ "data_sync.created_count": run.createdCount,
396
+ "data_sync.updated_count": run.updatedCount,
397
+ "data_sync.skipped_count": run.skippedCount
398
+ }
399
+ );
400
+ }
345
401
  await emitDataSyncEvent("data_sync.run.completed", {
346
402
  runId,
347
403
  integrationId: run.integrationId,
348
404
  entityType: run.entityType,
349
405
  direction: run.direction,
350
406
  tenantId: scope.tenantId,
351
- organizationId: scope.organizationId
407
+ organizationId: scope.organizationId,
408
+ createdCount: run.createdCount,
409
+ updatedCount: run.updatedCount,
410
+ skippedCount: run.skippedCount,
411
+ failedCount: run.failedCount
352
412
  });
353
413
  return;
354
414
  }
@@ -556,7 +616,8 @@ function createSyncEngine(deps) {
556
616
  integrationId: run.integrationId,
557
617
  runId: run.id,
558
618
  level: "error",
559
- message
619
+ message,
620
+ code: RUN_FAILED_CODE
560
621
  },
561
622
  scope
562
623
  );
@@ -748,7 +809,8 @@ function createSyncEngine(deps) {
748
809
  integrationId: run.integrationId,
749
810
  runId: run.id,
750
811
  level: "error",
751
- message
812
+ message,
813
+ code: RUN_FAILED_CODE
752
814
  },
753
815
  scope
754
816
  );
@@ -764,6 +826,7 @@ function createSyncEngine(deps) {
764
826
  };
765
827
  }
766
828
  export {
829
+ SyncRunPartialFailureError,
767
830
  createSyncEngine
768
831
  };
769
832
  //# sourceMappingURL=sync-engine.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/data_sync/lib/sync-engine.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CredentialsService } from '../../integrations/lib/credentials-service'\nimport type { IntegrationLogService } from '../../integrations/lib/log-service'\nimport type { IntegrationStateService } from '../../integrations/lib/state-service'\nimport type { ProgressService } from '../../progress/lib/progressService'\nimport { STALE_JOB_TIMEOUT_SECONDS } from '../../progress/lib/progressService'\nimport { refreshCoverageSnapshot } from '../../query_index/lib/coverage'\nimport { emitDataSyncEvent } from '../events'\nimport type { DataSyncAdapter, DataMapping, ExportBatch, ImportBatch, RunParameterValue } from './adapter'\nimport { getDataSyncAdapter, resolveProviderKey } from './adapter-registry'\nimport type { SyncRunService } from './sync-run-service'\nimport { SyncRunOwnershipConflictError } from './sync-run-service'\nimport { forEachBatch } from './batch-stream'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport {\n captureTelemetryTrace,\n type TelemetrySpanAttributes,\n} from '@open-mercato/shared/lib/telemetry/runtime'\nimport type { SyncRun } from '../data/entities'\n\nconst logger = createLogger('data_sync').child({ component: 'sync-engine' })\n\ntype RunParameters = Record<string, RunParameterValue>\n\ntype SyncScope = {\n organizationId: string\n tenantId: string\n userId?: string | null\n}\n\ntype EngineDeps = {\n em: EntityManager\n syncRunService: SyncRunService\n integrationCredentialsService: CredentialsService\n integrationLogService: IntegrationLogService\n integrationStateService?: IntegrationStateService\n progressService: ProgressService\n}\n\n/** Repeated on every batch span so a rooted batch trace identifies its run on its own. */\nfunction runSpanAttributes(run: SyncRun, providerKey: string, scope: SyncScope): TelemetrySpanAttributes {\n return {\n 'data_sync.run_id': run.id,\n 'data_sync.integration_id': run.integrationId,\n 'data_sync.provider_key': providerKey,\n 'data_sync.entity_type': run.entityType,\n 'data_sync.direction': run.direction,\n 'om.tenant_id': scope.tenantId,\n 'om.organization_id': scope.organizationId,\n }\n}\n\nfunction applyImportCounters(batch: ImportBatch): Pick<Required<SyncCounterDelta>, 'createdCount' | 'updatedCount' | 'skippedCount' | 'failedCount'> {\n let createdCount = 0\n let updatedCount = 0\n let skippedCount = 0\n let failedCount = 0\n\n for (const item of batch.items) {\n if (item.action === 'create') createdCount += 1\n else if (item.action === 'update') updatedCount += 1\n else if (item.action === 'failed') failedCount += 1\n else skippedCount += 1\n }\n\n return { createdCount, updatedCount, skippedCount, failedCount }\n}\n\ntype SyncCounterDelta = {\n createdCount?: number\n updatedCount?: number\n skippedCount?: number\n failedCount?: number\n processedCount: number\n}\n\nfunction applyExportCounters(batch: ExportBatch): SyncCounterDelta {\n let failedCount = 0\n let skippedCount = 0\n let updatedCount = 0\n\n for (const result of batch.results) {\n if (result.status === 'error') failedCount += 1\n else if (result.status === 'skipped') skippedCount += 1\n else updatedCount += 1\n }\n\n return {\n failedCount,\n skippedCount,\n updatedCount,\n processedCount: batch.results.length,\n }\n}\n\n// Adapter batches can legitimately outlast the stale-job sweep window (slow upstream\n// APIs), so the engine must heartbeat while a batch is still being produced. The same\n// tick also polls cancellation, so a cancel lands within one interval instead of waiting\n// out the batch \u2014 sharing this timer rather than adding a second one that would double\n// the per-interval round-trips for the whole life of a run.\nconst HEARTBEAT_TICK_MS = (STALE_JOB_TIMEOUT_SECONDS * 1000) / 4\n\n// Runs `tick` on an interval only while the source iterator is pending, so heartbeats\n// stop the moment the producer dies and genuinely stale jobs still get swept. The outer\n// finally closes the adapter generator on early exits (cancellation, ownership conflict).\n// Our own abort, as opposed to a failure that merely coincided with one. Adapters are told to\n// return rather than throw, but `signal.throwIfAborted()` and an aborted `fetch` both surface as\n// this, and either is a cancellation rather than a fault.\n//\n// Matched structurally on `name` rather than with `instanceof Error`, because those two throw a\n// `DOMException`, and whether that inherits from `Error` depends on the runtime \u2014 it does under\n// bare Node 24 and does NOT under the jest environment this is tested in. An `instanceof` test\n// therefore passes or fails on where the code runs, which is not something cancellation should\n// depend on.\nfunction isAbortError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'AbortError'\n}\n\nasync function* withHeartbeat<T>(source: AsyncIterable<T>, tick: () => void, intervalMs: number): AsyncGenerator<T, void, undefined> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n while (true) {\n const timer = setInterval(tick, intervalMs)\n let result: IteratorResult<T>\n try {\n result = await iterator.next()\n } finally {\n clearInterval(timer)\n }\n if (result.done) return\n yield result.value\n }\n } finally {\n await iterator.return?.()\n }\n}\n\nexport function createSyncEngine(deps: EngineDeps) {\n const { syncRunService, integrationCredentialsService, integrationLogService, integrationStateService, progressService } = deps\n\n async function resolveMapping(adapter: DataSyncAdapter, entityType: string, scope: SyncScope): Promise<DataMapping> {\n return adapter.getMapping({\n entityType,\n scope: { organizationId: scope.organizationId, tenantId: scope.tenantId },\n })\n }\n\n async function updateProgress(progressJobId: string | null | undefined, processedCount: number, totalCount: number | null, scope: SyncScope): Promise<void> {\n if (!progressJobId) return\n\n await progressService.updateProgress(\n progressJobId,\n {\n processedCount,\n totalCount: totalCount ?? undefined,\n },\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n )\n }\n\n // On redelivery the progress counter must resume where the last delivery left off the\n // same way committedBatches does \u2014 updateProgress writes absolute counts, so starting at\n // zero would regress the visible count. The progress job's own processedCount is the only\n // persisted value already in the engine's unit: `batch.processedCount ?? items.length`,\n // i.e. source records. The run's created/updated/skipped/failed counters count emitted\n // items, which adapters may explode several-per-source-record (Akeneo yields a product\n // plus its variants), so seeding from them would overshoot the total and pin the bar.\n async function seedProcessedCount(progressJobId: string | null | undefined, scope: SyncScope): Promise<number> {\n if (!progressJobId) return 0\n const job = await progressService.getJob(progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n return job?.processedCount ?? 0\n }\n\n function makeHeartbeatTick(progressJobId: string | null | undefined, scope: SyncScope): () => void {\n const touchJobHeartbeat = progressService.touchJobHeartbeat?.bind(progressService)\n if (!progressJobId || !touchJobHeartbeat) return () => {}\n let inFlight = false\n return () => {\n if (inFlight) return\n inFlight = true\n touchJobHeartbeat(progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n .catch((error) => {\n logger.warn('Progress heartbeat failed', {\n progressJobId,\n error: error instanceof Error ? error.message : String(error),\n })\n })\n .finally(() => {\n inFlight = false\n })\n }\n }\n\n // Rides the heartbeat timer, which is the only thing that runs while the adapter is still\n // producing a batch \u2014 the engine's own cancellation check sits in the batch handler and is\n // reached only after a yield. Swallows its own errors because it runs on a timer, where an\n // unhandled rejection is fatal, and stops polling once it has aborted.\n function makeCancellationTick(progressJobId: string | null | undefined, scope: SyncScope, controller: AbortController): () => void {\n if (!progressJobId) return () => {}\n let inFlight = false\n return () => {\n if (inFlight || controller.signal.aborted) return\n inFlight = true\n progressService.isCancellationRequested(progressJobId, scope.tenantId, scope.organizationId)\n .then((cancelled) => {\n if (cancelled) controller.abort()\n })\n .catch((error) => {\n logger.warn('Cancellation poll failed', {\n progressJobId,\n error: error instanceof Error ? error.message : String(error),\n })\n })\n .finally(() => {\n inFlight = false\n })\n }\n }\n\n async function refreshCoverageSnapshots(entityTypes: string[] | undefined, scope: SyncScope): Promise<void> {\n if (!entityTypes || entityTypes.length === 0) return\n\n await Promise.allSettled(\n Array.from(new Set(entityTypes.filter((value) => typeof value === 'string' && value.trim().length > 0)))\n .map((entityType) => refreshCoverageSnapshot(deps.em, {\n entityType,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })),\n )\n }\n\n async function logImportItemFailures(\n runId: string,\n integrationId: string,\n items: ImportBatch['items'],\n scope: SyncScope,\n ): Promise<void> {\n const failedItems = items.filter((item) => item.action === 'failed')\n for (const item of failedItems) {\n const errorMessage = typeof item.data.errorMessage === 'string' && item.data.errorMessage.trim().length > 0\n ? item.data.errorMessage.trim()\n : 'Import item failed'\n const sourceProductUuid = typeof item.data.sourceProductUuid === 'string' && item.data.sourceProductUuid.trim().length > 0\n ? item.data.sourceProductUuid.trim()\n : null\n const sourceIdentifier = typeof item.data.sourceIdentifier === 'string' && item.data.sourceIdentifier.trim().length > 0\n ? item.data.sourceIdentifier.trim()\n : null\n const message = [\n `Failed to import item ${item.externalId}`,\n sourceProductUuid ? `(uuid: ${sourceProductUuid})` : null,\n sourceIdentifier ? `(identifier: ${sourceIdentifier})` : null,\n `: ${errorMessage}`,\n ].filter((part) => part !== null).join(' ')\n\n await integrationLogService.write(\n {\n integrationId,\n runId,\n level: 'error',\n message,\n payload: item.data,\n },\n scope,\n )\n }\n }\n\n async function logExportItemFailures(\n runId: string,\n integrationId: string,\n results: ExportBatch['results'],\n scope: SyncScope,\n ): Promise<void> {\n const failedResults = results.filter((result) => result.status === 'error' && result.error)\n for (const result of failedResults) {\n const label = result.externalId ? `${result.externalId} (id: ${result.localId})` : result.localId\n const errorMessage = result.error!.split('\\n')[0]\n const message = `Failed to export item ${label}: ${errorMessage}`\n\n await integrationLogService.write(\n {\n integrationId,\n runId,\n level: 'error',\n message,\n payload: { kind: 'export-item-failure', summary: result.error },\n },\n scope,\n )\n }\n }\n\n async function writeOperationalLog(params: {\n integrationId: string\n runId: string\n level: 'info' | 'warn' | 'error'\n message: string\n scope: SyncScope\n enabled: boolean\n payload?: Record<string, unknown>\n }): Promise<void> {\n if (!params.enabled) return\n\n await integrationLogService.write(\n {\n integrationId: params.integrationId,\n runId: params.runId,\n level: params.level,\n message: params.message,\n payload: params.payload,\n },\n params.scope,\n )\n }\n\n async function updateOperationalState(params: {\n integrationId: string\n status: 'healthy' | 'degraded' | 'unhealthy'\n scope: SyncScope\n enabled: boolean\n }): Promise<void> {\n if (!params.enabled || !integrationStateService) return\n\n await integrationStateService.upsert(\n params.integrationId,\n {\n lastHealthStatus: params.status,\n lastHealthCheckedAt: new Date(),\n },\n params.scope,\n )\n }\n\n async function finalizeRun(\n runId: string,\n status: 'completed' | 'failed' | 'cancelled',\n scope: SyncScope,\n error?: string,\n operationalTelemetry = false,\n ): Promise<void> {\n const existingRun = await syncRunService.getRun(runId, scope)\n const alreadyFinalizedWithSameStatus = existingRun?.status === status\n && (status === 'completed' || status === 'failed' || status === 'cancelled')\n\n const run = await syncRunService.markStatus(runId, status, scope, error)\n if (!run) return\n\n if (alreadyFinalizedWithSameStatus) {\n return\n }\n\n if (run.status !== status) {\n // `markStatus` refuses a terminal -> different-terminal transition and\n // returns the row unchanged, so the run is already finished under another\n // delivery of this job. Everything below \u2014 the progress job, the\n // operational log and the lifecycle event \u2014 would describe the wrong\n // outcome, and `data_sync.run.failed` is dispatched to tenant webhooks.\n // A displaced worker stays silent instead.\n logger.warn('Skipping finalization of a sync run another worker already finalized', {\n runId,\n requestedStatus: status,\n actualStatus: run.status,\n })\n return\n }\n\n if (run.progressJobId) {\n if (status === 'completed') {\n await progressService.completeJob(\n run.progressJobId,\n {\n resultSummary: {\n createdCount: run.createdCount,\n updatedCount: run.updatedCount,\n skippedCount: run.skippedCount,\n failedCount: run.failedCount,\n batchesCompleted: run.batchesCompleted,\n },\n },\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n )\n } else if (status === 'failed') {\n await progressService.failJob(\n run.progressJobId,\n {\n errorMessage: error ?? 'Sync run failed',\n },\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n )\n } else if (status === 'cancelled') {\n await progressService.markCancelled(\n run.progressJobId,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n )\n }\n }\n\n if (status === 'completed') {\n await updateOperationalState({\n integrationId: run.integrationId,\n status: 'healthy',\n scope,\n enabled: operationalTelemetry,\n })\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'info',\n message: 'Sync run completed',\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'completed',\n summary: `Sync completed with ${run.createdCount} created, ${run.updatedCount} updated, ${run.failedCount} failed.`,\n createdCount: run.createdCount,\n updatedCount: run.updatedCount,\n skippedCount: run.skippedCount,\n failedCount: run.failedCount,\n batchesCompleted: run.batchesCompleted,\n },\n })\n } else if (status === 'cancelled') {\n await updateOperationalState({\n integrationId: run.integrationId,\n status: 'degraded',\n scope,\n enabled: operationalTelemetry,\n })\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'warn',\n message: 'Sync run cancelled',\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'cancelled',\n summary: 'The sync run was cancelled before completion.',\n },\n })\n } else {\n await updateOperationalState({\n integrationId: run.integrationId,\n status: 'unhealthy',\n scope,\n enabled: operationalTelemetry,\n })\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'error',\n message: error ?? 'Sync run failed',\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'failed',\n summary: error ?? 'The sync run failed.',\n },\n })\n }\n\n if (status === 'completed') {\n await emitDataSyncEvent('data_sync.run.completed', {\n runId,\n integrationId: run.integrationId,\n entityType: run.entityType,\n direction: run.direction,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n return\n }\n\n if (status === 'cancelled') {\n await emitDataSyncEvent('data_sync.run.cancelled', {\n runId,\n integrationId: run.integrationId,\n entityType: run.entityType,\n direction: run.direction,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n return\n }\n\n await emitDataSyncEvent('data_sync.run.failed', {\n runId,\n integrationId: run.integrationId,\n entityType: run.entityType,\n direction: run.direction,\n error: error ?? null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n }\n\n return {\n async runImport(runId: string, batchSize: number, scope: SyncScope): Promise<void> {\n const run = await syncRunService.getRun(runId, scope)\n if (!run) {\n logger.warn('Skipping stale import job for missing run', { runId })\n return\n }\n if (run.status === 'cancelled') {\n if (run.progressJobId) {\n await progressService.markCancelled(run.progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n }\n return\n }\n\n const providerKey = resolveProviderKey(run.integrationId)\n const adapter = getDataSyncAdapter(providerKey)\n if (!adapter?.streamImport) {\n throw new Error(`No import adapter registered for provider ${providerKey}`)\n }\n const operationalTelemetry = adapter.operationalTelemetry === true\n const persistSharedCursor = adapter.persistsSharedCursor?.(run.entityType) ?? true\n\n const credentials = await integrationCredentialsService.resolve(run.integrationId, scope)\n if (!credentials) {\n throw new Error(`Integration ${run.integrationId} is missing credentials`)\n }\n\n // A run already `running` means a stalled job was redelivered, so this is\n // a resume rather than a first start. Consumers see one `started` event per\n // delivery either way; the flag is what lets them tell the two apart.\n const resumed = run.status === 'running'\n const activeRun = await syncRunService.markStatus(run.id, 'running', scope)\n if (!activeRun || activeRun.status !== 'running') {\n return\n }\n await emitDataSyncEvent('data_sync.run.started', {\n runId: run.id,\n integrationId: run.integrationId,\n entityType: run.entityType,\n direction: run.direction,\n resumed,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n await updateOperationalState({\n integrationId: run.integrationId,\n status: 'degraded',\n scope,\n enabled: operationalTelemetry,\n })\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'info',\n message: 'Sync run started',\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'running',\n summary: `Import run started for ${run.entityType}.`,\n entityType: run.entityType,\n direction: run.direction,\n },\n })\n\n if (run.progressJobId) {\n await progressService.startJob(run.progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n }\n\n const mapping = await resolveMapping(adapter, run.entityType, scope)\n let processedCount = await seedProcessedCount(run.progressJobId, scope)\n let totalCount: number | null = null\n let committedBatches = activeRun.batchesCompleted ?? 0\n // Whether the last committed batch said the source was exhausted. Distinguishes a stream that\n // drained from one the adapter stopped early \u2014 see the post-stream finalize below.\n let streamReportedDone = false\n // Captured while the triggering job's span is still the active one, so\n // every rooted batch trace can link back to it.\n const runTrace = captureTelemetryTrace()\n const spanAttributes = runSpanAttributes(run, providerKey, scope)\n // Declared outside the try because both the catch and the completion path below read it.\n const cancellation = new AbortController()\n const heartbeat = makeHeartbeatTick(run.progressJobId, scope)\n const pollCancellation = makeCancellationTick(run.progressJobId, scope, cancellation)\n\n try {\n const streamResult = await forEachBatch(\n withHeartbeat(\n adapter.streamImport({\n entityType: run.entityType,\n cursor: run.cursor ?? undefined,\n batchSize,\n credentials,\n mapping,\n scope: { organizationId: scope.organizationId, tenantId: scope.tenantId },\n runId: run.id,\n parameters: (run.parameters ?? {}) as RunParameters,\n signal: cancellation.signal,\n }),\n // `finally` so a synchronous throw from the heartbeat cannot also stop cancellation\n // from being observed for the rest of the run.\n () => { try { heartbeat() } finally { pollCancellation() } },\n HEARTBEAT_TICK_MS,\n ),\n {\n spanName: 'data_sync.import.batch',\n drainSpanName: 'data_sync.import.drain',\n attributes: spanAttributes,\n linkTo: runTrace,\n },\n async (batch, span) => {\n span.setAttributes({\n 'data_sync.batch_index': batch.batchIndex,\n 'data_sync.batch_size': batch.items.length,\n })\n\n if (cancellation.signal.aborted || (run.progressJobId && await progressService.isCancellationRequested(run.progressJobId, scope.tenantId, scope.organizationId))) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return 'stop'\n }\n\n const delta = applyImportCounters(batch)\n const processedBatchCount = batch.processedCount ?? batch.items.length\n processedCount += processedBatchCount\n totalCount = batch.totalEstimate ?? totalCount\n\n span.setAttributes({\n 'data_sync.processed_count': processedBatchCount,\n 'data_sync.created_count': delta.createdCount,\n 'data_sync.updated_count': delta.updatedCount,\n 'data_sync.skipped_count': delta.skippedCount,\n 'data_sync.failed_count': delta.failedCount,\n })\n\n await syncRunService.commitBatchProgress(\n run.id,\n {\n ...delta,\n batchesCompleted: 1,\n },\n batch.cursor,\n scope,\n { expectedBatchesCompleted: committedBatches, persistSharedCursor },\n )\n committedBatches += 1\n streamReportedDone = batch.hasMore === false\n\n await updateProgress(run.progressJobId, processedCount, totalCount, scope)\n await refreshCoverageSnapshots(batch.refreshCoverageEntityTypes, scope)\n await logImportItemFailures(run.id, run.integrationId, batch.items, scope)\n\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'info',\n message: batch.message?.trim().length\n ? batch.message.trim()\n : `Processed import batch ${batch.batchIndex}`,\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'running',\n summary: `Processed ${processedCount}${totalCount ? ` of ${totalCount}` : ''} rows so far.`,\n processedCount,\n batchSize: batch.items.length,\n processedBatchCount,\n cursor: batch.cursor,\n },\n })\n\n return 'continue'\n },\n )\n if (streamResult === 'stopped') return\n } catch (error) {\n if (error instanceof SyncRunOwnershipConflictError) {\n logger.warn('Yielding import run to a concurrent worker that already advanced it', {\n runId: run.id,\n expectedBatchesCompleted: error.expectedBatchesCompleted,\n })\n return\n }\n // An adapter that honours the signal may reject instead of returning, so our own abort is\n // a cancellation rather than a fault \u2014 and must not leave an `error` entry in the\n // integration log for a run the operator cancelled on purpose. Anything else that merely\n // coincided with the cancel \u2014 a rejecting commit, an upstream 500 \u2014 is a genuine failure\n // and keeps its log entry, its message, its `failed` status and its failed event.\n if (cancellation.signal.aborted && isAbortError(error)) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return\n }\n const message = error instanceof Error ? error.message : 'Sync import failed'\n await integrationLogService.write(\n {\n integrationId: run.integrationId,\n runId: run.id,\n level: 'error',\n message,\n },\n scope,\n )\n await finalizeRun(run.id, 'failed', scope, message, operationalTelemetry)\n return\n }\n\n // An adapter that honours the signal stops mid-batch and returns WITHOUT yielding, so the\n // batch handler \u2014 which owns the only other `cancelled` transition \u2014 never runs and the\n // stream reports `completed`.\n //\n // `streamReportedDone` keeps that from swallowing a run that genuinely finished: an adapter\n // that ignores the signal and drains after reporting `hasMore: false` delivered everything it\n // had, even when the cancel landed during the final read. Calling that cancelled would tell\n // the operator a complete sync was partial and leave a finished run resumable.\n if (cancellation.signal.aborted && !streamReportedDone) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return\n }\n\n await finalizeRun(run.id, 'completed', scope, undefined, operationalTelemetry)\n },\n\n async runExport(runId: string, batchSize: number, scope: SyncScope): Promise<void> {\n const run = await syncRunService.getRun(runId, scope)\n if (!run) {\n logger.warn('Skipping stale export job for missing run', { runId })\n return\n }\n if (run.status === 'cancelled') {\n if (run.progressJobId) {\n await progressService.markCancelled(run.progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n }\n return\n }\n\n const providerKey = resolveProviderKey(run.integrationId)\n const adapter = getDataSyncAdapter(providerKey)\n if (!adapter?.streamExport) {\n throw new Error(`No export adapter registered for provider ${providerKey}`)\n }\n const operationalTelemetry = adapter.operationalTelemetry === true\n const persistSharedCursor = adapter.persistsSharedCursor?.(run.entityType) ?? true\n\n const credentials = await integrationCredentialsService.resolve(run.integrationId, scope)\n if (!credentials) {\n throw new Error(`Integration ${run.integrationId} is missing credentials`)\n }\n\n // A run already `running` means a stalled job was redelivered, so this is\n // a resume rather than a first start. Consumers see one `started` event per\n // delivery either way; the flag is what lets them tell the two apart.\n const resumed = run.status === 'running'\n const activeRun = await syncRunService.markStatus(run.id, 'running', scope)\n if (!activeRun || activeRun.status !== 'running') {\n return\n }\n await emitDataSyncEvent('data_sync.run.started', {\n runId: run.id,\n integrationId: run.integrationId,\n entityType: run.entityType,\n direction: run.direction,\n resumed,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n await updateOperationalState({\n integrationId: run.integrationId,\n status: 'degraded',\n scope,\n enabled: operationalTelemetry,\n })\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'info',\n message: 'Sync run started',\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'running',\n summary: `Export run started for ${run.entityType}.`,\n entityType: run.entityType,\n direction: run.direction,\n },\n })\n\n if (run.progressJobId) {\n await progressService.startJob(run.progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n }\n\n const mapping = await resolveMapping(adapter, run.entityType, scope)\n let processedCount = await seedProcessedCount(run.progressJobId, scope)\n let committedBatches = activeRun.batchesCompleted ?? 0\n // Whether the last committed batch said the source was exhausted. Distinguishes a stream that\n // drained from one the adapter stopped early \u2014 see the post-stream finalize below.\n let streamReportedDone = false\n // Captured while the triggering job's span is still the active one, so\n // every rooted batch trace can link back to it.\n const runTrace = captureTelemetryTrace()\n const spanAttributes = runSpanAttributes(run, providerKey, scope)\n // Declared outside the try because both the catch and the completion path below read it.\n const cancellation = new AbortController()\n const heartbeat = makeHeartbeatTick(run.progressJobId, scope)\n const pollCancellation = makeCancellationTick(run.progressJobId, scope, cancellation)\n\n try {\n const streamResult = await forEachBatch(\n withHeartbeat(\n adapter.streamExport({\n entityType: run.entityType,\n cursor: run.cursor ?? undefined,\n batchSize,\n credentials,\n mapping,\n scope: { organizationId: scope.organizationId, tenantId: scope.tenantId },\n runId: run.id,\n parameters: (run.parameters ?? {}) as RunParameters,\n signal: cancellation.signal,\n }),\n // `finally` so a synchronous throw from the heartbeat cannot also stop cancellation\n // from being observed for the rest of the run.\n () => { try { heartbeat() } finally { pollCancellation() } },\n HEARTBEAT_TICK_MS,\n ),\n {\n spanName: 'data_sync.export.batch',\n drainSpanName: 'data_sync.export.drain',\n attributes: spanAttributes,\n linkTo: runTrace,\n },\n async (batch, span) => {\n span.setAttributes({\n 'data_sync.batch_index': batch.batchIndex,\n 'data_sync.batch_size': batch.results.length,\n })\n\n if (cancellation.signal.aborted || (run.progressJobId && await progressService.isCancellationRequested(run.progressJobId, scope.tenantId, scope.organizationId))) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return 'stop'\n }\n\n const delta = applyExportCounters(batch)\n processedCount += delta.processedCount\n\n span.setAttributes({\n 'data_sync.processed_count': delta.processedCount,\n 'data_sync.updated_count': delta.updatedCount,\n 'data_sync.skipped_count': delta.skippedCount,\n 'data_sync.failed_count': delta.failedCount,\n })\n\n await syncRunService.commitBatchProgress(\n run.id,\n {\n createdCount: 0,\n updatedCount: delta.updatedCount,\n skippedCount: delta.skippedCount,\n failedCount: delta.failedCount,\n batchesCompleted: 1,\n },\n batch.cursor,\n scope,\n { expectedBatchesCompleted: committedBatches, persistSharedCursor },\n )\n committedBatches += 1\n streamReportedDone = batch.hasMore === false\n await updateProgress(run.progressJobId, processedCount, null, scope)\n await logExportItemFailures(run.id, run.integrationId, batch.results, scope)\n\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'info',\n message: `Processed export batch ${batch.batchIndex}`,\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'running',\n summary: `Processed ${processedCount} export items so far.`,\n processedCount,\n batchSize: batch.results.length,\n cursor: batch.cursor,\n },\n })\n\n return 'continue'\n },\n )\n if (streamResult === 'stopped') return\n } catch (error) {\n if (error instanceof SyncRunOwnershipConflictError) {\n logger.warn('Yielding export run to a concurrent worker that already advanced it', {\n runId: run.id,\n expectedBatchesCompleted: error.expectedBatchesCompleted,\n })\n return\n }\n // An adapter that honours the signal may reject instead of returning, so our own abort is\n // a cancellation rather than a fault \u2014 and must not leave an `error` entry in the\n // integration log for a run the operator cancelled on purpose. Anything else that merely\n // coincided with the cancel \u2014 a rejecting commit, an upstream 500 \u2014 is a genuine failure\n // and keeps its log entry, its message, its `failed` status and its failed event.\n if (cancellation.signal.aborted && isAbortError(error)) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return\n }\n const message = error instanceof Error ? error.message : 'Sync export failed'\n await integrationLogService.write(\n {\n integrationId: run.integrationId,\n runId: run.id,\n level: 'error',\n message,\n },\n scope,\n )\n await finalizeRun(run.id, 'failed', scope, message, operationalTelemetry)\n return\n }\n\n // An adapter that honours the signal stops mid-batch and returns WITHOUT yielding, so the\n // batch handler \u2014 which owns the only other `cancelled` transition \u2014 never runs and the\n // stream reports `completed`.\n //\n // `streamReportedDone` keeps that from swallowing a run that genuinely finished: an adapter\n // that ignores the signal and drains after reporting `hasMore: false` delivered everything it\n // had, even when the cancel landed during the final read. Calling that cancelled would tell\n // the operator a complete sync was partial and leave a finished run resumable.\n if (cancellation.signal.aborted && !streamReportedDone) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return\n }\n\n await finalizeRun(run.id, 'completed', scope, undefined, operationalTelemetry)\n },\n }\n}\n\nexport type SyncEngine = ReturnType<typeof createSyncEngine>\n"],
5
- "mappings": "AAKA,SAAS,iCAAiC;AAC1C,SAAS,+BAA+B;AACxC,SAAS,yBAAyB;AAElC,SAAS,oBAAoB,0BAA0B;AAEvD,SAAS,qCAAqC;AAC9C,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,OAEK;AAGP,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,cAAc,CAAC;AAoB3E,SAAS,kBAAkB,KAAc,aAAqB,OAA2C;AACvG,SAAO;AAAA,IACL,oBAAoB,IAAI;AAAA,IACxB,4BAA4B,IAAI;AAAA,IAChC,0BAA0B;AAAA,IAC1B,yBAAyB,IAAI;AAAA,IAC7B,uBAAuB,IAAI;AAAA,IAC3B,gBAAgB,MAAM;AAAA,IACtB,sBAAsB,MAAM;AAAA,EAC9B;AACF;AAEA,SAAS,oBAAoB,OAAwH;AACnJ,MAAI,eAAe;AACnB,MAAI,eAAe;AACnB,MAAI,eAAe;AACnB,MAAI,cAAc;AAElB,aAAW,QAAQ,MAAM,OAAO;AAC9B,QAAI,KAAK,WAAW,SAAU,iBAAgB;AAAA,aACrC,KAAK,WAAW,SAAU,iBAAgB;AAAA,aAC1C,KAAK,WAAW,SAAU,gBAAe;AAAA,QAC7C,iBAAgB;AAAA,EACvB;AAEA,SAAO,EAAE,cAAc,cAAc,cAAc,YAAY;AACjE;AAUA,SAAS,oBAAoB,OAAsC;AACjE,MAAI,cAAc;AAClB,MAAI,eAAe;AACnB,MAAI,eAAe;AAEnB,aAAW,UAAU,MAAM,SAAS;AAClC,QAAI,OAAO,WAAW,QAAS,gBAA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xE;AAAA,MACF;AAUA,UAAI,aAAa,OAAO,WAAW,CAAC,oBAAoB;AACtD,cAAM,YAAY,IAAI,IAAI,aAAa,OAAO,QAAW,oBAAoB;AAC7E;AAAA,MACF;AAEA,YAAM,YAAY,IAAI,IAAI,aAAa,OAAO,QAAW,oBAAoB;AAAA,IAC/E;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CredentialsService } from '../../integrations/lib/credentials-service'\nimport type { IntegrationLogService } from '../../integrations/lib/log-service'\nimport type { IntegrationStateService } from '../../integrations/lib/state-service'\nimport type { ProgressService } from '../../progress/lib/progressService'\nimport { STALE_JOB_TIMEOUT_SECONDS } from '../../progress/lib/progressService'\nimport { refreshCoverageSnapshot } from '../../query_index/lib/coverage'\nimport { emitDataSyncEvent } from '../events'\nimport type { DataSyncAdapter, DataMapping, ExportBatch, ImportBatch, RunParameterValue } from './adapter'\nimport { getDataSyncAdapter, resolveProviderKey } from './adapter-registry'\nimport type { SyncRunService } from './sync-run-service'\nimport { SyncRunOwnershipConflictError } from './sync-run-service'\nimport { forEachBatch } from './batch-stream'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport {\n captureTelemetryTrace,\n getTelemetryRuntime,\n type TelemetrySpanAttributes,\n} from '@open-mercato/shared/lib/telemetry/runtime'\nimport { groupableCode } from '@open-mercato/shared/lib/telemetry/error-code'\nimport type { SyncRun } from '../data/entities'\n\nconst logger = createLogger('data_sync').child({ component: 'sync-engine' })\n\n/**\n * A run that finished with failed items. Raised so a partial success is one\n * reported error with a count, at the granularity an operator acts on \u2014 a\n * different fact from any single item's failure, which the per-item error rows\n * report on their own.\n */\nexport class SyncRunPartialFailureError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SyncRunPartialFailureError'\n }\n}\n\n/**\n * The fingerprint for a run that ended in a fault.\n *\n * One code for now. PR #5450's `classifySyncError` splits faults into transient\n * and terminal; when it lands, this is the single place that becomes\n * `data_sync.run_transient` / `data_sync.run_terminal`.\n */\nconst RUN_FAILED_CODE = 'data_sync.run_failed'\n\n/** Run identity for a reported error, mirroring `runSpanAttributes` minus the provider key. */\nfunction runEventAttributes(run: SyncRun, scope: SyncScope): TelemetrySpanAttributes {\n return {\n 'data_sync.run_id': run.id,\n 'data_sync.integration_id': run.integrationId,\n 'data_sync.entity_type': run.entityType,\n 'data_sync.direction': run.direction,\n 'om.tenant_id': scope.tenantId,\n 'om.organization_id': scope.organizationId,\n }\n}\n\n/**\n * The failure fingerprint for a dead-lettered item.\n *\n * An adapter that classifies its own failures sets `errorCode` on the item's data\n * (a stable `module.reason` token, never an interpolated string); anything that is\n * not that shape falls back rather than being trusted, and the fallback is a real\n * code rather than `unknown`, so grouping works even for an adapter that supplies\n * nothing.\n */\nfunction itemErrorCode(data: Record<string, unknown>, fallback: string): string {\n return groupableCode(data.errorCode, fallback)\n}\n\n/**\n * Report a `data_sync` failure that is otherwise only recorded (a dropped\n * promise, a run's own summary). Wrapped: observability may never decide the fate\n * of a batch that is already committed.\n */\nfunction reportSyncError(\n error: unknown,\n code: string,\n attributes: TelemetrySpanAttributes,\n): void {\n try {\n getTelemetryRuntime()?.reportError(error, { module: 'data_sync', code, attributes })\n } catch (telemetryError) {\n logger.warn('Failed to report a data sync error to telemetry', { code, err: telemetryError as Error })\n }\n}\n\ntype RunParameters = Record<string, RunParameterValue>\n\ntype SyncScope = {\n organizationId: string\n tenantId: string\n userId?: string | null\n}\n\ntype EngineDeps = {\n em: EntityManager\n syncRunService: SyncRunService\n integrationCredentialsService: CredentialsService\n integrationLogService: IntegrationLogService\n integrationStateService?: IntegrationStateService\n progressService: ProgressService\n}\n\n/** Repeated on every batch span so a rooted batch trace identifies its run on its own. */\nfunction runSpanAttributes(run: SyncRun, providerKey: string, scope: SyncScope): TelemetrySpanAttributes {\n return {\n 'data_sync.run_id': run.id,\n 'data_sync.integration_id': run.integrationId,\n 'data_sync.provider_key': providerKey,\n 'data_sync.entity_type': run.entityType,\n 'data_sync.direction': run.direction,\n 'om.tenant_id': scope.tenantId,\n 'om.organization_id': scope.organizationId,\n }\n}\n\nfunction applyImportCounters(batch: ImportBatch): Pick<Required<SyncCounterDelta>, 'createdCount' | 'updatedCount' | 'skippedCount' | 'failedCount'> {\n let createdCount = 0\n let updatedCount = 0\n let skippedCount = 0\n let failedCount = 0\n\n for (const item of batch.items) {\n if (item.action === 'create') createdCount += 1\n else if (item.action === 'update') updatedCount += 1\n else if (item.action === 'failed') failedCount += 1\n else skippedCount += 1\n }\n\n return { createdCount, updatedCount, skippedCount, failedCount }\n}\n\ntype SyncCounterDelta = {\n createdCount?: number\n updatedCount?: number\n skippedCount?: number\n failedCount?: number\n processedCount: number\n}\n\nfunction applyExportCounters(batch: ExportBatch): SyncCounterDelta {\n let failedCount = 0\n let skippedCount = 0\n let updatedCount = 0\n\n for (const result of batch.results) {\n if (result.status === 'error') failedCount += 1\n else if (result.status === 'skipped') skippedCount += 1\n else updatedCount += 1\n }\n\n return {\n failedCount,\n skippedCount,\n updatedCount,\n processedCount: batch.results.length,\n }\n}\n\n// Adapter batches can legitimately outlast the stale-job sweep window (slow upstream\n// APIs), so the engine must heartbeat while a batch is still being produced. The same\n// tick also polls cancellation, so a cancel lands within one interval instead of waiting\n// out the batch \u2014 sharing this timer rather than adding a second one that would double\n// the per-interval round-trips for the whole life of a run.\nconst HEARTBEAT_TICK_MS = (STALE_JOB_TIMEOUT_SECONDS * 1000) / 4\n\n// Runs `tick` on an interval only while the source iterator is pending, so heartbeats\n// stop the moment the producer dies and genuinely stale jobs still get swept. The outer\n// finally closes the adapter generator on early exits (cancellation, ownership conflict).\n// Our own abort, as opposed to a failure that merely coincided with one. Adapters are told to\n// return rather than throw, but `signal.throwIfAborted()` and an aborted `fetch` both surface as\n// this, and either is a cancellation rather than a fault.\n//\n// Matched structurally on `name` rather than with `instanceof Error`, because those two throw a\n// `DOMException`, and whether that inherits from `Error` depends on the runtime \u2014 it does under\n// bare Node 24 and does NOT under the jest environment this is tested in. An `instanceof` test\n// therefore passes or fails on where the code runs, which is not something cancellation should\n// depend on.\nfunction isAbortError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'AbortError'\n}\n\nasync function* withHeartbeat<T>(source: AsyncIterable<T>, tick: () => void, intervalMs: number): AsyncGenerator<T, void, undefined> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n while (true) {\n const timer = setInterval(tick, intervalMs)\n let result: IteratorResult<T>\n try {\n result = await iterator.next()\n } finally {\n clearInterval(timer)\n }\n if (result.done) return\n yield result.value\n }\n } finally {\n await iterator.return?.()\n }\n}\n\nexport function createSyncEngine(deps: EngineDeps) {\n const { syncRunService, integrationCredentialsService, integrationLogService, integrationStateService, progressService } = deps\n\n async function resolveMapping(adapter: DataSyncAdapter, entityType: string, scope: SyncScope): Promise<DataMapping> {\n return adapter.getMapping({\n entityType,\n scope: { organizationId: scope.organizationId, tenantId: scope.tenantId },\n })\n }\n\n async function updateProgress(progressJobId: string | null | undefined, processedCount: number, totalCount: number | null, scope: SyncScope): Promise<void> {\n if (!progressJobId) return\n\n await progressService.updateProgress(\n progressJobId,\n {\n processedCount,\n totalCount: totalCount ?? undefined,\n },\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n )\n }\n\n // On redelivery the progress counter must resume where the last delivery left off the\n // same way committedBatches does \u2014 updateProgress writes absolute counts, so starting at\n // zero would regress the visible count. The progress job's own processedCount is the only\n // persisted value already in the engine's unit: `batch.processedCount ?? items.length`,\n // i.e. source records. The run's created/updated/skipped/failed counters count emitted\n // items, which adapters may explode several-per-source-record (Akeneo yields a product\n // plus its variants), so seeding from them would overshoot the total and pin the bar.\n async function seedProcessedCount(progressJobId: string | null | undefined, scope: SyncScope): Promise<number> {\n if (!progressJobId) return 0\n const job = await progressService.getJob(progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n return job?.processedCount ?? 0\n }\n\n function makeHeartbeatTick(progressJobId: string | null | undefined, scope: SyncScope): () => void {\n const touchJobHeartbeat = progressService.touchJobHeartbeat?.bind(progressService)\n if (!progressJobId || !touchJobHeartbeat) return () => {}\n let inFlight = false\n return () => {\n if (inFlight) return\n inFlight = true\n touchJobHeartbeat(progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n .catch((error) => {\n logger.warn('Progress heartbeat failed', {\n progressJobId,\n error: error instanceof Error ? error.message : String(error),\n })\n })\n .finally(() => {\n inFlight = false\n })\n }\n }\n\n // Rides the heartbeat timer, which is the only thing that runs while the adapter is still\n // producing a batch \u2014 the engine's own cancellation check sits in the batch handler and is\n // reached only after a yield. Swallows its own errors because it runs on a timer, where an\n // unhandled rejection is fatal, and stops polling once it has aborted.\n function makeCancellationTick(progressJobId: string | null | undefined, scope: SyncScope, controller: AbortController): () => void {\n if (!progressJobId) return () => {}\n let inFlight = false\n return () => {\n if (inFlight || controller.signal.aborted) return\n inFlight = true\n progressService.isCancellationRequested(progressJobId, scope.tenantId, scope.organizationId)\n .then((cancelled) => {\n if (cancelled) controller.abort()\n })\n .catch((error) => {\n logger.warn('Cancellation poll failed', {\n progressJobId,\n error: error instanceof Error ? error.message : String(error),\n })\n })\n .finally(() => {\n inFlight = false\n })\n }\n }\n\n async function refreshCoverageSnapshots(entityTypes: string[] | undefined, scope: SyncScope): Promise<void> {\n if (!entityTypes || entityTypes.length === 0) return\n\n const types = Array.from(\n new Set(entityTypes.filter((value) => typeof value === 'string' && value.trim().length > 0)),\n )\n const outcomes = await Promise.allSettled(\n types.map((entityType) => refreshCoverageSnapshot(deps.em, {\n entityType,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })),\n )\n // `allSettled` keeps a failed refresh from failing a committed batch, which is\n // right \u2014 but on its own it also discards the reason entirely, leaving no row,\n // no log and no signal. Reporting is the whole difference between degrading and\n // going silent.\n outcomes.forEach((outcome, index) => {\n if (outcome.status !== 'rejected') return\n logger.warn('Coverage snapshot refresh failed', { entityType: types[index], err: outcome.reason as Error })\n reportSyncError(outcome.reason, 'data_sync.coverage_refresh_failed', {\n entityType: types[index],\n 'om.tenant_id': scope.tenantId,\n 'om.organization_id': scope.organizationId,\n })\n })\n }\n\n async function logImportItemFailures(\n runId: string,\n integrationId: string,\n items: ImportBatch['items'],\n scope: SyncScope,\n ): Promise<void> {\n const failedItems = items.filter((item) => item.action === 'failed')\n for (const item of failedItems) {\n const errorMessage = typeof item.data.errorMessage === 'string' && item.data.errorMessage.trim().length > 0\n ? item.data.errorMessage.trim()\n : 'Import item failed'\n const sourceProductUuid = typeof item.data.sourceProductUuid === 'string' && item.data.sourceProductUuid.trim().length > 0\n ? item.data.sourceProductUuid.trim()\n : null\n const sourceIdentifier = typeof item.data.sourceIdentifier === 'string' && item.data.sourceIdentifier.trim().length > 0\n ? item.data.sourceIdentifier.trim()\n : null\n const message = [\n `Failed to import item ${item.externalId}`,\n sourceProductUuid ? `(uuid: ${sourceProductUuid})` : null,\n sourceIdentifier ? `(identifier: ${sourceIdentifier})` : null,\n `: ${errorMessage}`,\n ].filter((part) => part !== null).join(' ')\n\n await integrationLogService.write(\n {\n integrationId,\n runId,\n level: 'error',\n message,\n code: itemErrorCode(item.data, 'data_sync.item_failed'),\n payload: item.data,\n },\n scope,\n )\n }\n }\n\n async function logExportItemFailures(\n runId: string,\n integrationId: string,\n results: ExportBatch['results'],\n scope: SyncScope,\n ): Promise<void> {\n const failedResults = results.filter((result) => result.status === 'error' && result.error)\n for (const result of failedResults) {\n const label = result.externalId ? `${result.externalId} (id: ${result.localId})` : result.localId\n const errorMessage = result.error!.split('\\n')[0]\n const message = `Failed to export item ${label}: ${errorMessage}`\n\n await integrationLogService.write(\n {\n integrationId,\n runId,\n level: 'error',\n message,\n code: 'data_sync.export_item_failed',\n payload: { kind: 'export-item-failure', summary: result.error },\n },\n scope,\n )\n }\n }\n\n /**\n * The adapter-gated operational log. Deliberately carries no `code`: these rows\n * are run status records, and every fault they narrate was already written \u2014 and\n * therefore already reported \u2014 by a direct `level: 'error'` write that owns the\n * fingerprint. A code here would double-report every fault for adapters that\n * have `operationalTelemetry` on.\n */\n async function writeOperationalLog(params: {\n integrationId: string\n runId: string\n level: 'info' | 'warn' | 'error'\n message: string\n scope: SyncScope\n enabled: boolean\n payload?: Record<string, unknown>\n }): Promise<void> {\n if (!params.enabled) return\n\n await integrationLogService.write(\n {\n integrationId: params.integrationId,\n runId: params.runId,\n level: params.level,\n message: params.message,\n payload: params.payload,\n },\n params.scope,\n )\n }\n\n async function updateOperationalState(params: {\n integrationId: string\n status: 'healthy' | 'degraded' | 'unhealthy'\n scope: SyncScope\n enabled: boolean\n }): Promise<void> {\n if (!params.enabled || !integrationStateService) return\n\n await integrationStateService.upsert(\n params.integrationId,\n {\n lastHealthStatus: params.status,\n lastHealthCheckedAt: new Date(),\n },\n params.scope,\n )\n }\n\n async function finalizeRun(\n runId: string,\n status: 'completed' | 'failed' | 'cancelled',\n scope: SyncScope,\n error?: string,\n operationalTelemetry = false,\n ): Promise<void> {\n const existingRun = await syncRunService.getRun(runId, scope)\n const alreadyFinalizedWithSameStatus = existingRun?.status === status\n && (status === 'completed' || status === 'failed' || status === 'cancelled')\n\n const run = await syncRunService.markStatus(runId, status, scope, error)\n if (!run) return\n\n if (alreadyFinalizedWithSameStatus) {\n return\n }\n\n if (run.status !== status) {\n // `markStatus` refuses a terminal -> different-terminal transition and\n // returns the row unchanged, so the run is already finished under another\n // delivery of this job. Everything below \u2014 the progress job, the\n // operational log and the lifecycle event \u2014 would describe the wrong\n // outcome, and `data_sync.run.failed` is dispatched to tenant webhooks.\n // A displaced worker stays silent instead.\n logger.warn('Skipping finalization of a sync run another worker already finalized', {\n runId,\n requestedStatus: status,\n actualStatus: run.status,\n })\n return\n }\n\n if (run.progressJobId) {\n if (status === 'completed') {\n await progressService.completeJob(\n run.progressJobId,\n {\n resultSummary: {\n createdCount: run.createdCount,\n updatedCount: run.updatedCount,\n skippedCount: run.skippedCount,\n failedCount: run.failedCount,\n batchesCompleted: run.batchesCompleted,\n },\n },\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n )\n } else if (status === 'failed') {\n await progressService.failJob(\n run.progressJobId,\n {\n errorMessage: error ?? 'Sync run failed',\n },\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n )\n } else if (status === 'cancelled') {\n await progressService.markCancelled(\n run.progressJobId,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n )\n }\n }\n\n if (status === 'completed') {\n await updateOperationalState({\n integrationId: run.integrationId,\n status: 'healthy',\n scope,\n enabled: operationalTelemetry,\n })\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'info',\n message: 'Sync run completed',\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'completed',\n summary: `Sync completed with ${run.createdCount} created, ${run.updatedCount} updated, ${run.failedCount} failed.`,\n createdCount: run.createdCount,\n updatedCount: run.updatedCount,\n skippedCount: run.skippedCount,\n failedCount: run.failedCount,\n batchesCompleted: run.batchesCompleted,\n },\n })\n } else if (status === 'cancelled') {\n await updateOperationalState({\n integrationId: run.integrationId,\n status: 'degraded',\n scope,\n enabled: operationalTelemetry,\n })\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'warn',\n message: 'Sync run cancelled',\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'cancelled',\n summary: 'The sync run was cancelled before completion.',\n },\n })\n } else {\n await updateOperationalState({\n integrationId: run.integrationId,\n status: 'unhealthy',\n scope,\n enabled: operationalTelemetry,\n })\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'error',\n message: error ?? 'Sync run failed',\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'failed',\n summary: error ?? 'The sync run failed.',\n },\n })\n }\n\n if (status === 'completed') {\n // A run that finished with failures is a partial success, and the operator\n // finds out here or not at all: the per-item rows carry the reasons but no\n // count, and this is the only place that knows the run is over. Reported\n // outside `writeOperationalLog` on purpose \u2014 that path is gated on an adapter\n // opt-in, and an adapter flag may decide how chatty the operational log is,\n // never whether a failure is observable.\n if (run.failedCount > 0) {\n reportSyncError(\n new SyncRunPartialFailureError(`Sync run completed with ${run.failedCount} failed item(s)`),\n 'data_sync.run_partial_failure',\n {\n ...runEventAttributes(run, scope),\n 'data_sync.failed_count': run.failedCount,\n 'data_sync.created_count': run.createdCount,\n 'data_sync.updated_count': run.updatedCount,\n 'data_sync.skipped_count': run.skippedCount,\n },\n )\n }\n await emitDataSyncEvent('data_sync.run.completed', {\n runId,\n integrationId: run.integrationId,\n entityType: run.entityType,\n direction: run.direction,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n createdCount: run.createdCount,\n updatedCount: run.updatedCount,\n skippedCount: run.skippedCount,\n failedCount: run.failedCount,\n })\n return\n }\n\n if (status === 'cancelled') {\n await emitDataSyncEvent('data_sync.run.cancelled', {\n runId,\n integrationId: run.integrationId,\n entityType: run.entityType,\n direction: run.direction,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n return\n }\n\n await emitDataSyncEvent('data_sync.run.failed', {\n runId,\n integrationId: run.integrationId,\n entityType: run.entityType,\n direction: run.direction,\n error: error ?? null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n }\n\n return {\n async runImport(runId: string, batchSize: number, scope: SyncScope): Promise<void> {\n const run = await syncRunService.getRun(runId, scope)\n if (!run) {\n logger.warn('Skipping stale import job for missing run', { runId })\n return\n }\n if (run.status === 'cancelled') {\n if (run.progressJobId) {\n await progressService.markCancelled(run.progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n }\n return\n }\n\n const providerKey = resolveProviderKey(run.integrationId)\n const adapter = getDataSyncAdapter(providerKey)\n if (!adapter?.streamImport) {\n throw new Error(`No import adapter registered for provider ${providerKey}`)\n }\n const operationalTelemetry = adapter.operationalTelemetry === true\n const persistSharedCursor = adapter.persistsSharedCursor?.(run.entityType) ?? true\n\n const credentials = await integrationCredentialsService.resolve(run.integrationId, scope)\n if (!credentials) {\n throw new Error(`Integration ${run.integrationId} is missing credentials`)\n }\n\n // A run already `running` means a stalled job was redelivered, so this is\n // a resume rather than a first start. Consumers see one `started` event per\n // delivery either way; the flag is what lets them tell the two apart.\n const resumed = run.status === 'running'\n const activeRun = await syncRunService.markStatus(run.id, 'running', scope)\n if (!activeRun || activeRun.status !== 'running') {\n return\n }\n await emitDataSyncEvent('data_sync.run.started', {\n runId: run.id,\n integrationId: run.integrationId,\n entityType: run.entityType,\n direction: run.direction,\n resumed,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n await updateOperationalState({\n integrationId: run.integrationId,\n status: 'degraded',\n scope,\n enabled: operationalTelemetry,\n })\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'info',\n message: 'Sync run started',\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'running',\n summary: `Import run started for ${run.entityType}.`,\n entityType: run.entityType,\n direction: run.direction,\n },\n })\n\n if (run.progressJobId) {\n await progressService.startJob(run.progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n }\n\n const mapping = await resolveMapping(adapter, run.entityType, scope)\n let processedCount = await seedProcessedCount(run.progressJobId, scope)\n let totalCount: number | null = null\n let committedBatches = activeRun.batchesCompleted ?? 0\n // Whether the last committed batch said the source was exhausted. Distinguishes a stream that\n // drained from one the adapter stopped early \u2014 see the post-stream finalize below.\n let streamReportedDone = false\n // Captured while the triggering job's span is still the active one, so\n // every rooted batch trace can link back to it.\n const runTrace = captureTelemetryTrace()\n const spanAttributes = runSpanAttributes(run, providerKey, scope)\n // Declared outside the try because both the catch and the completion path below read it.\n const cancellation = new AbortController()\n const heartbeat = makeHeartbeatTick(run.progressJobId, scope)\n const pollCancellation = makeCancellationTick(run.progressJobId, scope, cancellation)\n\n try {\n const streamResult = await forEachBatch(\n withHeartbeat(\n adapter.streamImport({\n entityType: run.entityType,\n cursor: run.cursor ?? undefined,\n batchSize,\n credentials,\n mapping,\n scope: { organizationId: scope.organizationId, tenantId: scope.tenantId },\n runId: run.id,\n parameters: (run.parameters ?? {}) as RunParameters,\n signal: cancellation.signal,\n }),\n // `finally` so a synchronous throw from the heartbeat cannot also stop cancellation\n // from being observed for the rest of the run.\n () => { try { heartbeat() } finally { pollCancellation() } },\n HEARTBEAT_TICK_MS,\n ),\n {\n spanName: 'data_sync.import.batch',\n drainSpanName: 'data_sync.import.drain',\n attributes: spanAttributes,\n linkTo: runTrace,\n },\n async (batch, span) => {\n span.setAttributes({\n 'data_sync.batch_index': batch.batchIndex,\n 'data_sync.batch_size': batch.items.length,\n })\n\n if (cancellation.signal.aborted || (run.progressJobId && await progressService.isCancellationRequested(run.progressJobId, scope.tenantId, scope.organizationId))) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return 'stop'\n }\n\n const delta = applyImportCounters(batch)\n const processedBatchCount = batch.processedCount ?? batch.items.length\n processedCount += processedBatchCount\n totalCount = batch.totalEstimate ?? totalCount\n\n span.setAttributes({\n 'data_sync.processed_count': processedBatchCount,\n 'data_sync.created_count': delta.createdCount,\n 'data_sync.updated_count': delta.updatedCount,\n 'data_sync.skipped_count': delta.skippedCount,\n 'data_sync.failed_count': delta.failedCount,\n })\n\n await syncRunService.commitBatchProgress(\n run.id,\n {\n ...delta,\n batchesCompleted: 1,\n },\n batch.cursor,\n scope,\n { expectedBatchesCompleted: committedBatches, persistSharedCursor },\n )\n committedBatches += 1\n streamReportedDone = batch.hasMore === false\n\n await updateProgress(run.progressJobId, processedCount, totalCount, scope)\n await refreshCoverageSnapshots(batch.refreshCoverageEntityTypes, scope)\n await logImportItemFailures(run.id, run.integrationId, batch.items, scope)\n\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'info',\n message: batch.message?.trim().length\n ? batch.message.trim()\n : `Processed import batch ${batch.batchIndex}`,\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'running',\n summary: `Processed ${processedCount}${totalCount ? ` of ${totalCount}` : ''} rows so far.`,\n processedCount,\n batchSize: batch.items.length,\n processedBatchCount,\n cursor: batch.cursor,\n },\n })\n\n return 'continue'\n },\n )\n if (streamResult === 'stopped') return\n } catch (error) {\n if (error instanceof SyncRunOwnershipConflictError) {\n logger.warn('Yielding import run to a concurrent worker that already advanced it', {\n runId: run.id,\n expectedBatchesCompleted: error.expectedBatchesCompleted,\n })\n return\n }\n // An adapter that honours the signal may reject instead of returning, so our own abort is\n // a cancellation rather than a fault \u2014 and must not leave an `error` entry in the\n // integration log for a run the operator cancelled on purpose. Anything else that merely\n // coincided with the cancel \u2014 a rejecting commit, an upstream 500 \u2014 is a genuine failure\n // and keeps its log entry, its message, its `failed` status and its failed event.\n if (cancellation.signal.aborted && isAbortError(error)) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return\n }\n const message = error instanceof Error ? error.message : 'Sync import failed'\n await integrationLogService.write(\n {\n integrationId: run.integrationId,\n runId: run.id,\n level: 'error',\n message,\n code: RUN_FAILED_CODE,\n },\n scope,\n )\n await finalizeRun(run.id, 'failed', scope, message, operationalTelemetry)\n return\n }\n\n // An adapter that honours the signal stops mid-batch and returns WITHOUT yielding, so the\n // batch handler \u2014 which owns the only other `cancelled` transition \u2014 never runs and the\n // stream reports `completed`.\n //\n // `streamReportedDone` keeps that from swallowing a run that genuinely finished: an adapter\n // that ignores the signal and drains after reporting `hasMore: false` delivered everything it\n // had, even when the cancel landed during the final read. Calling that cancelled would tell\n // the operator a complete sync was partial and leave a finished run resumable.\n if (cancellation.signal.aborted && !streamReportedDone) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return\n }\n\n await finalizeRun(run.id, 'completed', scope, undefined, operationalTelemetry)\n },\n\n async runExport(runId: string, batchSize: number, scope: SyncScope): Promise<void> {\n const run = await syncRunService.getRun(runId, scope)\n if (!run) {\n logger.warn('Skipping stale export job for missing run', { runId })\n return\n }\n if (run.status === 'cancelled') {\n if (run.progressJobId) {\n await progressService.markCancelled(run.progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n }\n return\n }\n\n const providerKey = resolveProviderKey(run.integrationId)\n const adapter = getDataSyncAdapter(providerKey)\n if (!adapter?.streamExport) {\n throw new Error(`No export adapter registered for provider ${providerKey}`)\n }\n const operationalTelemetry = adapter.operationalTelemetry === true\n const persistSharedCursor = adapter.persistsSharedCursor?.(run.entityType) ?? true\n\n const credentials = await integrationCredentialsService.resolve(run.integrationId, scope)\n if (!credentials) {\n throw new Error(`Integration ${run.integrationId} is missing credentials`)\n }\n\n // A run already `running` means a stalled job was redelivered, so this is\n // a resume rather than a first start. Consumers see one `started` event per\n // delivery either way; the flag is what lets them tell the two apart.\n const resumed = run.status === 'running'\n const activeRun = await syncRunService.markStatus(run.id, 'running', scope)\n if (!activeRun || activeRun.status !== 'running') {\n return\n }\n await emitDataSyncEvent('data_sync.run.started', {\n runId: run.id,\n integrationId: run.integrationId,\n entityType: run.entityType,\n direction: run.direction,\n resumed,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n await updateOperationalState({\n integrationId: run.integrationId,\n status: 'degraded',\n scope,\n enabled: operationalTelemetry,\n })\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'info',\n message: 'Sync run started',\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'running',\n summary: `Export run started for ${run.entityType}.`,\n entityType: run.entityType,\n direction: run.direction,\n },\n })\n\n if (run.progressJobId) {\n await progressService.startJob(run.progressJobId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n })\n }\n\n const mapping = await resolveMapping(adapter, run.entityType, scope)\n let processedCount = await seedProcessedCount(run.progressJobId, scope)\n let committedBatches = activeRun.batchesCompleted ?? 0\n // Whether the last committed batch said the source was exhausted. Distinguishes a stream that\n // drained from one the adapter stopped early \u2014 see the post-stream finalize below.\n let streamReportedDone = false\n // Captured while the triggering job's span is still the active one, so\n // every rooted batch trace can link back to it.\n const runTrace = captureTelemetryTrace()\n const spanAttributes = runSpanAttributes(run, providerKey, scope)\n // Declared outside the try because both the catch and the completion path below read it.\n const cancellation = new AbortController()\n const heartbeat = makeHeartbeatTick(run.progressJobId, scope)\n const pollCancellation = makeCancellationTick(run.progressJobId, scope, cancellation)\n\n try {\n const streamResult = await forEachBatch(\n withHeartbeat(\n adapter.streamExport({\n entityType: run.entityType,\n cursor: run.cursor ?? undefined,\n batchSize,\n credentials,\n mapping,\n scope: { organizationId: scope.organizationId, tenantId: scope.tenantId },\n runId: run.id,\n parameters: (run.parameters ?? {}) as RunParameters,\n signal: cancellation.signal,\n }),\n // `finally` so a synchronous throw from the heartbeat cannot also stop cancellation\n // from being observed for the rest of the run.\n () => { try { heartbeat() } finally { pollCancellation() } },\n HEARTBEAT_TICK_MS,\n ),\n {\n spanName: 'data_sync.export.batch',\n drainSpanName: 'data_sync.export.drain',\n attributes: spanAttributes,\n linkTo: runTrace,\n },\n async (batch, span) => {\n span.setAttributes({\n 'data_sync.batch_index': batch.batchIndex,\n 'data_sync.batch_size': batch.results.length,\n })\n\n if (cancellation.signal.aborted || (run.progressJobId && await progressService.isCancellationRequested(run.progressJobId, scope.tenantId, scope.organizationId))) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return 'stop'\n }\n\n const delta = applyExportCounters(batch)\n processedCount += delta.processedCount\n\n span.setAttributes({\n 'data_sync.processed_count': delta.processedCount,\n 'data_sync.updated_count': delta.updatedCount,\n 'data_sync.skipped_count': delta.skippedCount,\n 'data_sync.failed_count': delta.failedCount,\n })\n\n await syncRunService.commitBatchProgress(\n run.id,\n {\n createdCount: 0,\n updatedCount: delta.updatedCount,\n skippedCount: delta.skippedCount,\n failedCount: delta.failedCount,\n batchesCompleted: 1,\n },\n batch.cursor,\n scope,\n { expectedBatchesCompleted: committedBatches, persistSharedCursor },\n )\n committedBatches += 1\n streamReportedDone = batch.hasMore === false\n await updateProgress(run.progressJobId, processedCount, null, scope)\n await logExportItemFailures(run.id, run.integrationId, batch.results, scope)\n\n await writeOperationalLog({\n integrationId: run.integrationId,\n runId: run.id,\n level: 'info',\n message: `Processed export batch ${batch.batchIndex}`,\n scope,\n enabled: operationalTelemetry,\n payload: {\n operationalStatus: 'running',\n summary: `Processed ${processedCount} export items so far.`,\n processedCount,\n batchSize: batch.results.length,\n cursor: batch.cursor,\n },\n })\n\n return 'continue'\n },\n )\n if (streamResult === 'stopped') return\n } catch (error) {\n if (error instanceof SyncRunOwnershipConflictError) {\n logger.warn('Yielding export run to a concurrent worker that already advanced it', {\n runId: run.id,\n expectedBatchesCompleted: error.expectedBatchesCompleted,\n })\n return\n }\n // An adapter that honours the signal may reject instead of returning, so our own abort is\n // a cancellation rather than a fault \u2014 and must not leave an `error` entry in the\n // integration log for a run the operator cancelled on purpose. Anything else that merely\n // coincided with the cancel \u2014 a rejecting commit, an upstream 500 \u2014 is a genuine failure\n // and keeps its log entry, its message, its `failed` status and its failed event.\n if (cancellation.signal.aborted && isAbortError(error)) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return\n }\n const message = error instanceof Error ? error.message : 'Sync export failed'\n await integrationLogService.write(\n {\n integrationId: run.integrationId,\n runId: run.id,\n level: 'error',\n message,\n code: RUN_FAILED_CODE,\n },\n scope,\n )\n await finalizeRun(run.id, 'failed', scope, message, operationalTelemetry)\n return\n }\n\n // An adapter that honours the signal stops mid-batch and returns WITHOUT yielding, so the\n // batch handler \u2014 which owns the only other `cancelled` transition \u2014 never runs and the\n // stream reports `completed`.\n //\n // `streamReportedDone` keeps that from swallowing a run that genuinely finished: an adapter\n // that ignores the signal and drains after reporting `hasMore: false` delivered everything it\n // had, even when the cancel landed during the final read. Calling that cancelled would tell\n // the operator a complete sync was partial and leave a finished run resumable.\n if (cancellation.signal.aborted && !streamReportedDone) {\n await finalizeRun(run.id, 'cancelled', scope, undefined, operationalTelemetry)\n return\n }\n\n await finalizeRun(run.id, 'completed', scope, undefined, operationalTelemetry)\n },\n }\n}\n\nexport type SyncEngine = ReturnType<typeof createSyncEngine>\n"],
5
+ "mappings": "AAKA,SAAS,iCAAiC;AAC1C,SAAS,+BAA+B;AACxC,SAAS,yBAAyB;AAElC,SAAS,oBAAoB,0BAA0B;AAEvD,SAAS,qCAAqC;AAC9C,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,qBAAqB;AAG9B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,cAAc,CAAC;AAQpE,MAAM,mCAAmC,MAAM;AAAA,EACpD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AASA,MAAM,kBAAkB;AAGxB,SAAS,mBAAmB,KAAc,OAA2C;AACnF,SAAO;AAAA,IACL,oBAAoB,IAAI;AAAA,IACxB,4BAA4B,IAAI;AAAA,IAChC,yBAAyB,IAAI;AAAA,IAC7B,uBAAuB,IAAI;AAAA,IAC3B,gBAAgB,MAAM;AAAA,IACtB,sBAAsB,MAAM;AAAA,EAC9B;AACF;AAWA,SAAS,cAAc,MAA+B,UAA0B;AAC9E,SAAO,cAAc,KAAK,WAAW,QAAQ;AAC/C;AAOA,SAAS,gBACP,OACA,MACA,YACM;AACN,MAAI;AACF,wBAAoB,GAAG,YAAY,OAAO,EAAE,QAAQ,aAAa,MAAM,WAAW,CAAC;AAAA,EACrF,SAAS,gBAAgB;AACvB,WAAO,KAAK,mDAAmD,EAAE,MAAM,KAAK,eAAwB,CAAC;AAAA,EACvG;AACF;AAoBA,SAAS,kBAAkB,KAAc,aAAqB,OAA2C;AACvG,S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