Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(pg): pool ending state check

Sidwebworksfafe7a681da6
diff --git a/packages/database/supabase/functions/lib/postgres/index.ts b/packages/database/supabase/functions/lib/postgres/index.ts
index cbf7fed1b5..401c0884e9 100644
--- a/packages/database/supabase/functions/lib/postgres/index.ts
+++ b/packages/database/supabase/functions/lib/postgres/index.ts
@@ -41,7 +41,11 @@ const poolCache = new Map<number, Pool>();
export function getPostgresConnectionPool(connections: number): Pool {
const cached = poolCache.get(connections);
- if (cached) return cached;
+ // An ended pool can never serve connections again ("Cannot use a pool after
+ // calling end on the pool") — evict it so callers get a live pool instead of
+ // a permanently broken process. `ending` is node-postgres only; on Deno it's
+ // undefined and the cached pool is always reused.
+ if (cached && !(cached as { ending?: boolean }).ending) return cached;
const pool = createPostgresConnectionPool(connections);
poolCache.set(connections, pool);
@@ -66,10 +70,22 @@ function createPostgresConnectionPool(connections: number): Pool {
const connectionPoolerUrl = url.includes("supabase.co")
? url.replace("5432", "6543")
: url;
- return new Pool({
+ const pool = new Pool({
connectionString: connectionPoolerUrl,
max: connections,
+ // Fail fast instead of queueing forever when the DB/pooler is
+ // unreachable or the pool is saturated.
+ connectionTimeoutMillis: 10_000,
+ // Rotate connections so direct (non-Supavisor) connections can't rot
+ // through NAT/firewall idle limits.
+ maxLifetimeSeconds: 1800,
});
+ // pg-pool purges the broken client before emitting 'error'; the listener
+ // exists because an unlistened EventEmitter 'error' crashes the process.
+ pool.on("error", (err) => {
+ console.error("postgres pool: idle client error", err);
+ });
+ return pool;
}
default:
diff --git a/packages/jobs/src/inngest/functions/events/sync.ts b/packages/jobs/src/inngest/functions/events/sync.ts
index c34a934d9a..125aedc77d 100644
--- a/packages/jobs/src/inngest/functions/events/sync.ts
+++ b/packages/jobs/src/inngest/functions/events/sync.ts
@@ -74,152 +74,144 @@ export const syncFunction = inngest.createFunction(
const kysely = getPostgresClient(pool, PostgresDriver);
const client = getCarbonServiceRole();
- try {
- for (const [key, records] of Object.entries(byCompanyProvider)) {
- const [companyId, provider] = key.split(":");
-
- if (!companyId || companyId === "undefined" || !provider) {
- for (const r of records) {
- results.skipped.push({
- recordId: r.event.recordId,
- reason: "Missing companyId or provider"
- });
- }
- continue;
+ for (const [key, records] of Object.entries(byCompanyProvider)) {
+ const [companyId, provider] = key.split(":");
+
+ if (!companyId || companyId === "undefined" || !provider) {
+ for (const r of records) {
+ results.skipped.push({
+ recordId: r.event.recordId,
+ reason: "Missing companyId or provider"
+ });
}
+ continue;
+ }
- // Process each company-provider group as a step for checkpointing
- type GroupResults = {
- success: BatchSyncResult[];
- failed: { recordId: string; error: string }[];
- skipped: { recordId: string; reason: string }[];
- };
-
- const groupResult = (await step.run(
- `sync-${companyId}-${provider}`,
- async () => {
- const groupResults: GroupResults = {
- success: [],
- failed: [],
- skipped: []
- };
-
- try {
- // Get integration and provider instance
- const integration = await getAccountingIntegration(
- client,
- companyId,
- provider as ProviderID
- );
+ // Process each company-provider group as a step for checkpointing
+ type GroupResults = {
+ success: BatchSyncResult[];
+ failed: { recordId: string; error: string }[];
+ skipped: { recordId: string; reason: string }[];
+ };
+
+ const groupResult = (await step.run(
+ `sync-${companyId}-${provider}`,
+ async () => {
+ const groupResults: GroupResults = {
+ success: [],
+ failed: [],
+ skipped: []
+ };
+
+ try {
+ // Get integration and provider instance
+ const integration = await getAccountingIntegration(
+ client,
+ companyId,
+ provider as ProviderID
+ );
+
+ const providerInstance = getProviderIntegration(
+ client,
+ companyId,
+ provider as ProviderID,
+ integration.metadata
+ );
+
+ // Group by entity type
+ const byEntityType = groupBy(records, (r) => {
+ const entityType = getEntityTypeFromTable(r.event.table);
+ return entityType ?? "unknown";
+ });
- const providerInstance = getProviderIntegration(
- client,
- companyId,
- provider as ProviderID,
- integration.metadata
+ for (const [entityType, entityRecords] of Object.entries(
+ byEntityType
+ )) {
+ if (entityType === "unknown") {
+ for (const r of entityRecords) {
+ groupResults.skipped.push({
+ recordId: r.event.recordId,
+ reason: `Table '${r.event.table}' has no entity mapping`
+ });
+ }
+ continue;
+ }
+
+ // Separate by operation
+ const inserts = entityRecords.filter(
+ (r) => r.event.operation === "INSERT"
+ );
+ const updates = entityRecords.filter(
+ (r) => r.event.operation === "UPDATE"
+ );
+ const deletes = entityRecords.filter(
+ (r) => r.event.operation === "DELETE"
);
- // Group by entity type
- const byEntityType = groupBy(records, (r) => {
- const entityType = getEntityTypeFromTable(r.event.table);
- return entityType ?? "unknown";
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId,
+ provider: providerInstance,
+ config: providerInstance.getSyncConfig(
+ entityType as AccountingEntityType
+ ),
+ entityType: entityType as AccountingEntityType
});
- for (const [entityType, entityRecords] of Object.entries(
- byEntityType
- )) {
- if (entityType === "unknown") {
- for (const r of entityRecords) {
- groupResults.skipped.push({
- recordId: r.event.recordId,
- reason: `Table '${r.event.table}' has no entity mapping`
- });
- }
- continue;
- }
+ // Process INSERTs and UPDATEs (push to accounting)
+ const toSync = [...inserts, ...updates];
+ if (toSync.length > 0) {
+ const entityIds = pluckUnique(toSync, (r) => r.event.recordId);
- // Separate by operation
- const inserts = entityRecords.filter(
- (r) => r.event.operation === "INSERT"
- );
- const updates = entityRecords.filter(
- (r) => r.event.operation === "UPDATE"
+ console.log(
+ `Pushing ${entityIds.length} ${entityType} entities to accounting`
);
- const deletes = entityRecords.filter(
- (r) => r.event.operation === "DELETE"
- );
-
- const syncer = SyncFactory.getSyncer({
- database: kysely,
- companyId,
- provider: providerInstance,
- config: providerInstance.getSyncConfig(
- entityType as AccountingEntityType
- ),
- entityType: entityType as AccountingEntityType
- });
- // Process INSERTs and UPDATEs (push to accounting)
- const toSync = [...inserts, ...updates];
- if (toSync.length > 0) {
- const entityIds = pluckUnique(
- toSync,
- (r) => r.event.recordId
- );
-
- console.log(
- `Pushing ${entityIds.length} ${entityType} entities to accounting`
- );
-
- // Handle rate limiting with retry
- let result: BatchSyncResult;
- try {
- result = await syncer.pushBatchToAccounting(entityIds);
- } catch (error) {
- if (error instanceof RatelimitError) {
- const { retryAfterSeconds } = error.rateLimitInfo;
- console.warn(
- `[RATE LIMIT] Hit rate limit, will retry after ${retryAfterSeconds}s`
- );
- // Let inngest handle the retry by throwing
- throw error;
- }
+ // Handle rate limiting with retry
+ let result: BatchSyncResult;
+ try {
+ result = await syncer.pushBatchToAccounting(entityIds);
+ } catch (error) {
+ if (error instanceof RatelimitError) {
+ const { retryAfterSeconds } = error.rateLimitInfo;
+ console.warn(
+ `[RATE LIMIT] Hit rate limit, will retry after ${retryAfterSeconds}s`
+ );
+ // Let inngest handle the retry by throwing
throw error;
}
-
- console.log("Sync result:", { entityType, result });
- groupResults.success.push(result);
+ throw error;
}
- // Handle DELETEs (log for now, not yet implemented in syncers)
- for (const del of deletes) {
- groupResults.skipped.push({
- recordId: del.event.recordId,
- reason: "DELETE operations not yet implemented"
- });
- }
+ console.log("Sync result:", { entityType, result });
+ groupResults.success.push(result);
}
- } catch (error) {
- console.error(`Failed to process sync for ${key}:`, error);
- for (const r of records) {
- groupResults.failed.push({
- recordId: r.event.recordId,
- error:
- error instanceof Error ? error.message : "Unknown error"
+
+ // Handle DELETEs (log for now, not yet implemented in syncers)
+ for (const del of deletes) {
+ groupResults.skipped.push({
+ recordId: del.event.recordId,
+ reason: "DELETE operations not yet implemented"
});
}
}
-
- return groupResults;
+ } catch (error) {
+ console.error(`Failed to process sync for ${key}:`, error);
+ for (const r of records) {
+ groupResults.failed.push({
+ recordId: r.event.recordId,
+ error: error instanceof Error ? error.message : "Unknown error"
+ });
+ }
}
- )) as GroupResults;
- results.success.push(...groupResult.success);
- results.failed.push(...groupResult.failed);
- results.skipped.push(...groupResult.skipped);
- }
- } finally {
- await pool.end();
+ return groupResults;
+ }
+ )) as GroupResults;
+
+ results.success.push(...groupResult.success);
+ results.failed.push(...groupResult.failed);
+ results.skipped.push(...groupResult.skipped);
}
console.log("Sync function completed", {
diff --git a/packages/jobs/src/inngest/functions/integrations/accounting-backfill.ts b/packages/jobs/src/inngest/functions/integrations/accounting-backfill.ts
index 3eae9f2cf8..0fc4fb9e57 100644
--- a/packages/jobs/src/inngest/functions/integrations/accounting-backfill.ts
+++ b/packages/jobs/src/inngest/functions/integrations/accounting-backfill.ts
@@ -203,115 +203,111 @@ export const accountingBackfillFunction = inngest.createFunction(
const pool = getPostgresConnectionPool(5);
const kysely = getPostgresClient(pool, PostgresDriver);
- try {
- console.info(`[PULL] Fetching contacts page ${currentPage}`);
- const response = await withRateLimitRetry(
- () =>
- pullProvider.listContacts({
- page: currentPage,
- summaryOnly: true
- }),
- `listContacts page ${currentPage}`,
- step
- );
-
- console.info(`[PULL] Contacts page ${currentPage} response`, {
- count: response.contacts.length,
- hasMore: response.hasMore,
- contacts: response.contacts.map((c) => ({
- id: c.ContactID,
- name: c.Name,
- isCustomer: c.IsCustomer,
- isSupplier: c.IsSupplier
- }))
- });
+ console.info(`[PULL] Fetching contacts page ${currentPage}`);
+ const response = await withRateLimitRetry(
+ () =>
+ pullProvider.listContacts({
+ page: currentPage,
+ summaryOnly: true
+ }),
+ `listContacts page ${currentPage}`,
+ step
+ );
- if (response.contacts.length === 0) {
- return {
- hasMore: false,
- pulled: { customers: 0, vendors: 0 }
- };
- }
+ console.info(`[PULL] Contacts page ${currentPage} response`, {
+ count: response.contacts.length,
+ hasMore: response.hasMore,
+ contacts: response.contacts.map((c) => ({
+ id: c.ContactID,
+ name: c.Name,
+ isCustomer: c.IsCustomer,
+ isSupplier: c.IsSupplier
+ }))
+ });
+
+ if (response.contacts.length === 0) {
+ return {
+ hasMore: false,
+ pulled: { customers: 0, vendors: 0 }
+ };
+ }
- let customersPulled = 0;
- let vendorsPulled = 0;
-
- // Pull customers
- if (pullCustomers) {
- const customers = response.contacts.filter((c) => c.IsCustomer);
- if (customers.length > 0) {
- const syncer = SyncFactory.getSyncer({
- database: kysely,
- companyId: payload.companyId,
- provider: pullProvider,
- config: pullProvider.getSyncConfig("customer"),
- entityType: "customer"
- });
- const ids = customers.map((c) => c.ContactID);
- const syncResult = await withRateLimitRetry(
- () => syncer.pullBatchFromAccounting(ids),
- `pullBatchFromAccounting customers page ${currentPage}`,
- step
- );
- customersPulled = syncResult.successCount;
- console.info(
- `[PULL] Page ${currentPage}: pulled ${customersPulled} customers`,
- {
- results: syncResult.results.map((r) => ({
- status: r.status,
- action: r.action,
- localId: r.localId,
- remoteId: r.remoteId,
- error: r.error
- }))
- }
- );
- }
+ let customersPulled = 0;
+ let vendorsPulled = 0;
+
+ // Pull customers
+ if (pullCustomers) {
+ const customers = response.contacts.filter((c) => c.IsCustomer);
+ if (customers.length > 0) {
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId: payload.companyId,
+ provider: pullProvider,
+ config: pullProvider.getSyncConfig("customer"),
+ entityType: "customer"
+ });
+ const ids = customers.map((c) => c.ContactID);
+ const syncResult = await withRateLimitRetry(
+ () => syncer.pullBatchFromAccounting(ids),
+ `pullBatchFromAccounting customers page ${currentPage}`,
+ step
+ );
+ customersPulled = syncResult.successCount;
+ console.info(
+ `[PULL] Page ${currentPage}: pulled ${customersPulled} customers`,
+ {
+ results: syncResult.results.map((r) => ({
+ status: r.status,
+ action: r.action,
+ localId: r.localId,
+ remoteId: r.remoteId,
+ error: r.error
+ }))
+ }
+ );
}
+ }
- // Pull vendors
- if (pullVendors) {
- const vendors = response.contacts.filter((c) => c.IsSupplier);
- if (vendors.length > 0) {
- const syncer = SyncFactory.getSyncer({
- database: kysely,
- companyId: payload.companyId,
- provider: pullProvider,
- config: pullProvider.getSyncConfig("vendor"),
- entityType: "vendor"
- });
- const ids = vendors.map((c) => c.ContactID);
- const syncResult = await withRateLimitRetry(
- () => syncer.pullBatchFromAccounting(ids),
- `pullBatchFromAccounting vendors page ${currentPage}`,
- step
- );
- vendorsPulled = syncResult.successCount;
- console.info(
- `[PULL] Page ${currentPage}: pulled ${vendorsPulled} vendors`,
- {
- results: syncResult.results.map((r) => ({
- status: r.status,
- action: r.action,
- localId: r.localId,
- remoteId: r.remoteId,
- error: r.error
- }))
- }
- );
- }
+ // Pull vendors
+ if (pullVendors) {
+ const vendors = response.contacts.filter((c) => c.IsSupplier);
+ if (vendors.length > 0) {
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId: payload.companyId,
+ provider: pullProvider,
+ config: pullProvider.getSyncConfig("vendor"),
+ entityType: "vendor"
+ });
+ const ids = vendors.map((c) => c.ContactID);
+ const syncResult = await withRateLimitRetry(
+ () => syncer.pullBatchFromAccounting(ids),
+ `pullBatchFromAccounting vendors page ${currentPage}`,
+ step
+ );
+ vendorsPulled = syncResult.successCount;
+ console.info(
+ `[PULL] Page ${currentPage}: pulled ${vendorsPulled} vendors`,
+ {
+ results: syncResult.results.map((r) => ({
+ status: r.status,
+ action: r.action,
+ localId: r.localId,
+ remoteId: r.remoteId,
+ error: r.error
+ }))
+ }
+ );
}
-
- return {
- hasMore: response.hasMore,
- pulled: {
- customers: customersPulled,
- vendors: vendorsPulled
- }
- };
- } finally {
- await pool.end();
}
+
+ return {
+ hasMore: response.hasMore,
+ pulled: {
+ customers: customersPulled,
+ vendors: vendorsPulled
+ }
+ };
}
);
@@ -368,62 +364,58 @@ export const accountingBackfillFunction = inngest.createFunction(
const pool = getPostgresConnectionPool(5);
const kysely = getPostgresClient(pool, PostgresDriver);
- try {
- console.info(`[PULL] Fetching items page ${currentPage}`);
- const response = await withRateLimitRetry(
- () => pullProvider.listItems({ page: currentPage }),
- `listItems page ${currentPage}`,
- step
- );
-
- console.info(`[PULL] Items page ${currentPage} response`, {
- count: response.items.length,
- hasMore: response.hasMore,
- items: response.items.map((i) => ({
- id: i.ItemID,
- code: i.Code,
- name: i.Name
- }))
- });
+ console.info(`[PULL] Fetching items page ${currentPage}`);
+ const response = await withRateLimitRetry(
+ () => pullProvider.listItems({ page: currentPage }),
+ `listItems page ${currentPage}`,
+ step
+ );
- if (response.items.length === 0) {
- return { hasMore: false, pulled: { items: 0 } };
- }
+ console.info(`[PULL] Items page ${currentPage} response`, {
+ count: response.items.length,
+ hasMore: response.hasMore,
+ items: response.items.map((i) => ({
+ id: i.ItemID,
+ code: i.Code,
+ name: i.Name
+ }))
+ });
+
+ if (response.items.length === 0) {
+ return { hasMore: false, pulled: { items: 0 } };
+ }
- const syncer = SyncFactory.getSyncer({
- database: kysely,
- companyId: payload.companyId,
- provider: pullProvider,
- config: pullProvider.getSyncConfig("item"),
- entityType: "item"
- });
- const ids = response.items.map((item) => item.ItemID);
- const syncResult = await withRateLimitRetry(
- () => syncer.pullBatchFromAccounting(ids),
- `pullBatchFromAccounting items page ${currentPage}`,
- step
- );
-
- console.info(
- `[PULL] Page ${currentPage}: pulled ${syncResult.successCount} items`,
- {
- results: syncResult.results.map((r) => ({
- status: r.status,
- action: r.action,
- localId: r.localId,
- remoteId: r.remoteId,
- error: r.error
- }))
- }
- );
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId: payload.companyId,
+ provider: pullProvider,
+ config: pullProvider.getSyncConfig("item"),
+ entityType: "item"
+ });
+ const ids = response.items.map((item) => item.ItemID);
+ const syncResult = await withRateLimitRetry(
+ () => syncer.pullBatchFromAccounting(ids),
+ `pullBatchFromAccounting items page ${currentPage}`,
+ step
+ );
- return {
- hasMore: response.hasMore,
- pulled: { items: syncResult.successCount }
- };
- } finally {
- await pool.end();
- }
+ console.info(
+ `[PULL] Page ${currentPage}: pulled ${syncResult.successCount} items`,
+ {
+ results: syncResult.results.map((r) => ({
+ status: r.status,
+ action: r.action,
+ localId: r.localId,
+ remoteId: r.remoteId,
+ error: r.error
+ }))
+ }
+ );
+
+ return {
+ hasMore: response.hasMore,
+ pulled: { items: syncResult.successCount }
+ };
}
);
@@ -479,61 +471,57 @@ export const accountingBackfillFunction = inngest.createFunction(
const pool = getPostgresConnectionPool(5);
const kysely = getPostgresClient(pool, PostgresDriver);
- try {
- const mappingService = createMappingService(
- kysely,
- payload.companyId
- );
-
- const unsyncedIds = await mappingService.getUnsyncedEntityIds(
- "customer",
- "customer",
- pushProvider.id,
- payload.batchSize
- );
-
- if (unsyncedIds.length === 0) {
- return {
- successCount: 0,
- hasMore: false
- };
- }
+ const mappingService = createMappingService(
+ kysely,
+ payload.companyId
+ );
- const syncer = SyncFactory.getSyncer({
- database: kysely,
- companyId: payload.companyId,
- provider: pushProvider,
- config: pushProvider.getSyncConfig("customer"),
- entityType: "customer"
- });
-
- const syncResult = await withRateLimitRetry(
- () => syncer.pushBatchToAccounting(unsyncedIds),
- `pushBatchToAccounting customers`,
- step
- );
-
- console.info(
- `[PUSH] Pushed ${syncResult.successCount}/${unsyncedIds.length} customer entities`,
- {
- entityIds: unsyncedIds,
- results: syncResult.results.map((r) => ({
- status: r.status,
- action: r.action,
- localId: r.localId,
- remoteId: r.remoteId,
- error: r.error
- }))
- }
- );
+ const unsyncedIds = await mappingService.getUnsyncedEntityIds(
+ "customer",
+ "customer",
+ pushProvider.id,
+ payload.batchSize
+ );
+ if (unsyncedIds.length === 0) {
return {
- successCount: syncResult.successCount,
- hasMore: unsyncedIds.length >= payload.batchSize
+ successCount: 0,
+ hasMore: false
};
- } finally {
- await pool.end();
}
+
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId: payload.companyId,
+ provider: pushProvider,
+ config: pushProvider.getSyncConfig("customer"),
+ entityType: "customer"
+ });
+
+ const syncResult = await withRateLimitRetry(
+ () => syncer.pushBatchToAccounting(unsyncedIds),
+ `pushBatchToAccounting customers`,
+ step
+ );
+
+ console.info(
+ `[PUSH] Pushed ${syncResult.successCount}/${unsyncedIds.length} customer entities`,
+ {
+ entityIds: unsyncedIds,
+ results: syncResult.results.map((r) => ({
+ status: r.status,
+ action: r.action,
+ localId: r.localId,
+ remoteId: r.remoteId,
+ error: r.error
+ }))
+ }
+ );
+
+ return {
+ successCount: syncResult.successCount,
+ hasMore: unsyncedIds.length >= payload.batchSize
+ };
}
);
@@ -585,61 +573,57 @@ export const accountingBackfillFunction = inngest.createFunction(
const pool = getPostgresConnectionPool(5);
const kysely = getPostgresClient(pool, PostgresDriver);
- try {
- const mappingService = createMappingService(
- kysely,
- payload.companyId
- );
-
- const unsyncedIds = await mappingService.getUnsyncedEntityIds(
- "vendor",
- "supplier",
- pushProvider.id,
- payload.batchSize
- );
-
- if (unsyncedIds.length === 0) {
- return {
- successCount: 0,
- hasMore: false
- };
- }
+ const mappingService = createMappingService(
+ kysely,
+ payload.companyId
+ );
- const syncer = SyncFactory.getSyncer({
- database: kysely,
- companyId: payload.companyId,
- provider: pushProvider,
- config: pushProvider.getSyncConfig("vendor"),
- entityType: "vendor"
- });
-
- const syncResult = await withRateLimitRetry(
- () => syncer.pushBatchToAccounting(unsyncedIds),
- `pushBatchToAccounting vendors`,
- step
- );
-
- console.info(
- `[PUSH] Pushed ${syncResult.successCount}/${unsyncedIds.length} vendor entities`,
- {
- entityIds: unsyncedIds,
- results: syncResult.results.map((r) => ({
- status: r.status,
- action: r.action,
- localId: r.localId,
- remoteId: r.remoteId,
- error: r.error
- }))
- }
- );
+ const unsyncedIds = await mappingService.getUnsyncedEntityIds(
+ "vendor",
+ "supplier",
+ pushProvider.id,
+ payload.batchSize
+ );
+ if (unsyncedIds.length === 0) {
return {
- successCount: syncResult.successCount,
- hasMore: unsyncedIds.length >= payload.batchSize
+ successCount: 0,
+ hasMore: false
};
- } finally {
- await pool.end();
}
+
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId: payload.companyId,
+ provider: pushProvider,
+ config: pushProvider.getSyncConfig("vendor"),
+ entityType: "vendor"
+ });
+
+ const syncResult = await withRateLimitRetry(
+ () => syncer.pushBatchToAccounting(unsyncedIds),
+ `pushBatchToAccounting vendors`,
+ step
+ );
+
+ console.info(
+ `[PUSH] Pushed ${syncResult.successCount}/${unsyncedIds.length} vendor entities`,
+ {
+ entityIds: unsyncedIds,
+ results: syncResult.results.map((r) => ({
+ status: r.status,
+ action: r.action,
+ localId: r.localId,
+ remoteId: r.remoteId,
+ error: r.error
+ }))
+ }
+ );
+
+ return {
+ successCount: syncResult.successCount,
+ hasMore: unsyncedIds.length >= payload.batchSize
+ };
}
);
@@ -690,61 +674,57 @@ export const accountingBackfillFunction = inngest.createFunction(
const pool = getPostgresConnectionPool(5);
const kysely = getPostgresClient(pool, PostgresDriver);
- try {
- const mappingService = createMappingService(
- kysely,
- payload.companyId
- );
-
- const unsyncedIds = await mappingService.getUnsyncedEntityIds(
- "item",
- "item",
- pushProvider.id,
- payload.batchSize
- );
-
- if (unsyncedIds.length === 0) {
- return {
- successCount: 0,
- hasMore: false
- };
- }
+ const mappingService = createMappingService(
+ kysely,
+ payload.companyId
+ );
- const syncer = SyncFactory.getSyncer({
- database: kysely,
- companyId: payload.companyId,
- provider: pushProvider,
- config: pushProvider.getSyncConfig("item"),
- entityType: "item"
- });
-
- const syncResult = await withRateLimitRetry(
- () => syncer.pushBatchToAccounting(unsyncedIds),
- `pushBatchToAccounting items`,
- step
- );
-
- console.info(
- `[PUSH] Pushed ${syncResult.successCount}/${unsyncedIds.length} item entities`,
- {
- entityIds: unsyncedIds,
- results: syncResult.results.map((r) => ({
- status: r.status,
- action: r.action,
- localId: r.localId,
- remoteId: r.remoteId,
- error: r.error
- }))
- }
- );
+ const unsyncedIds = await mappingService.getUnsyncedEntityIds(
+ "item",
+ "item",
+ pushProvider.id,
+ payload.batchSize
+ );
+ if (unsyncedIds.length === 0) {
return {
- successCount: syncResult.successCount,
- hasMore: unsyncedIds.length >= payload.batchSize
+ successCount: 0,
+ hasMore: false
};
- } finally {
- await pool.end();
}
+
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId: payload.companyId,
+ provider: pushProvider,
+ config: pushProvider.getSyncConfig("item"),
+ entityType: "item"
+ });
+
+ const syncResult = await withRateLimitRetry(
+ () => syncer.pushBatchToAccounting(unsyncedIds),
+ `pushBatchToAccounting items`,
+ step
+ );
+
+ console.info(
+ `[PUSH] Pushed ${syncResult.successCount}/${unsyncedIds.length} item entities`,
+ {
+ entityIds: unsyncedIds,
+ results: syncResult.results.map((r) => ({
+ status: r.status,
+ action: r.action,
+ localId: r.localId,
+ remoteId: r.remoteId,
+ error: r.error
+ }))
+ }
+ );
+
+ return {
+ successCount: syncResult.successCount,
+ hasMore: unsyncedIds.length >= payload.batchSize
+ };
}
);
diff --git a/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts b/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts
index 8e48e9d4c9..0ca3bca779 100644
--- a/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts
+++ b/packages/jobs/src/inngest/functions/integrations/sync-external-accounting.ts
@@ -185,8 +185,6 @@ export const syncExternalAccountingFunction = inngest.createFunction(
}
} catch (error) {
console.error("Sync task failed:", error);
- } finally {
- await pool.end();
}
return results;