Implement sync service queue

This commit is contained in:
Dominic Ferrando
2026-07-03 14:07:47 -04:00
parent fc9cd6f1ae
commit 437300831f
4 changed files with 99 additions and 37 deletions
+6 -3
View File
@@ -3,7 +3,7 @@ import { db } from "./db";
import { log } from "../util"; import { log } from "../util";
// ===================== // =====================
// SYNC RUNS // PRODUCT SYNCS
// ===================== // =====================
{ {
log.info({ name: "product_syncs" }, "Creating table"); log.info({ name: "product_syncs" }, "Creating table");
@@ -11,8 +11,11 @@ import { log } from "../util";
await db.schema.createTable("product_syncs") await db.schema.createTable("product_syncs")
.$call(addDefaultColumns) .$call(addDefaultColumns)
.addColumn("printful_product_id_filter", sql`integer[]`) .addColumn("printful_product_id_filter", sql`integer[]`)
.addColumn("syncing_printful_product_ids", sql`integer[]`, (cb) => cb.notNull()) .addColumn("syncing_printful_product_ids", sql`integer[]`, (cb) => cb
.addColumn("started_at", "timestamptz", (cb) => cb.unique()) .notNull()
.defaultTo(sql`'{}'::integer[]`)
)
.addColumn("started_at", "timestamptz")
.addColumn("ended_at", "timestamptz") .addColumn("ended_at", "timestamptz")
.addColumn("has_failed", "boolean", (cb) => cb.notNull().defaultTo(false)) .addColumn("has_failed", "boolean", (cb) => cb.notNull().defaultTo(false))
.execute() .execute()
+8 -11
View File
@@ -144,21 +144,18 @@ export const app = new Elysia()
app app
// Sync status // Sync status
.get("/", async ({ }) => { .get("/", async ({ }) => {
const activeRun = await syncService.getActiveRun(); const activeSync = await syncService.getActiveSync();
if (!activeRun) throw new NotFoundError("No sync in progress"); if (!activeSync) throw new NotFoundError("No sync in progress");
return { return {
startDate: activeRun.started_at, startDate: activeSync.started_at,
syncingPrintfulProductIds: activeRun.syncing_printful_product_ids syncingPrintfulProductIds: activeSync.syncing_printful_product_ids
} }
}) })
// Run sync // Run sync
.post("/:printfulProductId?", async ({ params: { printfulProductId } }) => { .post("/:printfulProductId?", async ({ params: { printfulProductId } }) => {
log.debug({ printfulProductId }); const printfulProductIds = printfulProductId ? [printfulProductId] : null;
await syncService.start({ log.debug({ printfulProductIds });
printfulProductIds: printfulProductId ? await syncService.sync({ filter: { printfulProductIds } });
[printfulProductId] :
undefined
});
}, { params: t.Object({ printfulProductId: t.Optional(t.Numeric()) }) }), }, { params: t.Object({ printfulProductId: t.Optional(t.Numeric()) }) }),
) )
.get("/:printfulProductId", async ({ params }) => { .get("/:printfulProductId", async ({ params }) => {
@@ -185,7 +182,7 @@ export const app = new Elysia()
case Printful.Webhook.Event.ProductUpdated: { case Printful.Webhook.Event.ProductUpdated: {
const printfulProduct = payload.data.sync_product; const printfulProduct = payload.data.sync_product;
log.info({ productId: printfulProduct.id }, "printful webhook: product updated"); log.info({ productId: printfulProduct.id }, "printful webhook: product updated");
await syncService.start({ printfulProductIds: [printfulProduct.id] }); await syncService.sync({ filter: { printfulProductIds: [printfulProduct.id] } });
break; break;
} }
case Printful.Webhook.Event.ProductDeleted: { case Printful.Webhook.Event.ProductDeleted: {
+77 -14
View File
@@ -1,29 +1,72 @@
import { PrintfulClient, ProductSyncer, WebflowClient, type SyncOptions } from "@blade-and-brawn/commerce"; import { PrintfulClient, ProductSyncer, WebflowClient, type ProductSyncerOptions } from "@blade-and-brawn/commerce";
import { log } from "../util"; import { log } from "../util";
import { db } from "../database/db"; import { db } from "../database/db";
import { DatabaseError } from "pg";
class SyncQueue {
async enqueue(item: SyncServiceOptions) {
const values = { printful_product_id_filter: item.filter?.printfulProductIds };
if (item.id) {
await db.updateTable("product_syncs")
.set(values)
.where("id", "=", item.id)
.execute();
}
else {
await db.insertInto("product_syncs")
.values(values)
.execute();
}
}
async front() {
return await db.selectFrom("product_syncs")
.selectAll()
.where("started_at", "is", null)
.orderBy("created_at", "asc")
.limit(1)
.executeTakeFirst();
}
}
type SyncServiceOptions = {
id?: string | null,
filter: ProductSyncerOptions["filter"]
}
export class SyncService { export class SyncService {
readonly productSyncer: ProductSyncer private readonly productSyncer: ProductSyncer;
private queue: SyncQueue;
constructor(printful: PrintfulClient, webflow: WebflowClient) { constructor(printful: PrintfulClient, webflow: WebflowClient) {
this.productSyncer = new ProductSyncer(printful, webflow, log); this.productSyncer = new ProductSyncer(printful, webflow, log);
this.queue = new SyncQueue();
} }
async start(filter: SyncOptions["filter"]) { async sync(opt: SyncServiceOptions) {
let id: string | null = null; let id = opt.id ?? null;
try { try {
log.info("starting sync run");
await this.productSyncer.sync({ await this.productSyncer.sync({
filter, filter: opt.filter,
onStart: async (startDate) => { onStart: async (startDate) => {
const result = await db.insertInto("product_syncs") const values = {
.values({
started_at: startDate, started_at: startDate,
printful_product_id_filter: filter?.printfulProductIds, printful_product_id_filter: opt.filter?.printfulProductIds ?? null,
syncing_printful_product_ids: [] };
}) if (id) {
await db.updateTable("product_syncs")
.set(values)
.where("id", "=", id)
.execute();
}
else {
const result = await db.insertInto("product_syncs")
.values(values)
.returning("id") .returning("id")
.executeTakeFirstOrThrow(); .executeTakeFirstOrThrow();
id = result.id; id = result.id;
}
}, },
onStep: async (printfulProductIds: number[]) => { onStep: async (printfulProductIds: number[]) => {
if (!id) throw new Error("Expected sync run ID"); if (!id) throw new Error("Expected sync run ID");
@@ -35,14 +78,29 @@ export class SyncService {
onCompletion: async (completionDate, duration) => { onCompletion: async (completionDate, duration) => {
if (!id) throw new Error("Expected sync run ID"); if (!id) throw new Error("Expected sync run ID");
await db.updateTable("product_syncs") await db.updateTable("product_syncs")
.set({ syncing_printful_product_ids: [], ended_at: completionDate, }) .set({ syncing_printful_product_ids: [], ended_at: completionDate })
.where("id", "=", id) .where("id", "=", id)
.execute(); .execute();
// Sync next item in queue
const nextSync = await this.queue.front();
if (nextSync) {
await this.sync({
id: nextSync.id,
filter: { printfulProductIds: nextSync.printful_product_id_filter }
});
}
} }
}); });
} }
catch (err) { catch (err) {
if (id) { const isActiveSyncConflict = err instanceof DatabaseError && err.code === "23505" && (await this.getActiveSync());
if (isActiveSyncConflict) {
log.info("sync already active, enqueuing next sync");
await this.queue.enqueue(opt);
return;
}
else if (id) {
await db.updateTable("product_syncs") await db.updateTable("product_syncs")
.set({ syncing_printful_product_ids: [], ended_at: new Date(), has_failed: true }) .set({ syncing_printful_product_ids: [], ended_at: new Date(), has_failed: true })
.where("id", "=", id) .where("id", "=", id)
@@ -52,7 +110,12 @@ export class SyncService {
} }
} }
async getActiveRun() { async getActiveSync() {
return await db.selectFrom("product_syncs").selectAll().where("ended_at", "is", null).executeTakeFirst(); return await db.selectFrom("product_syncs")
.selectAll()
.where("started_at", "is not", null)
.where("ended_at", "is", null)
.limit(1)
.executeTakeFirst();
} }
} }
+4 -5
View File
@@ -17,9 +17,9 @@ type MetaPrintfulProduct = {
entries: ProductEntry[]; entries: ProductEntry[];
}; };
export type SyncOptions = { export type ProductSyncerOptions = {
filter?: { filter?: {
printfulProductIds?: number[]; printfulProductIds: number[] | null;
}, },
onStart?: (startDate: Date) => Promise<void> onStart?: (startDate: Date) => Promise<void>
onCompletion?: (completionDate: Date, duration: number) => Promise<void> onCompletion?: (completionDate: Date, duration: number) => Promise<void>
@@ -37,8 +37,7 @@ export class ProductSyncer {
this.log = (log ?? pino({ level: "silent" })).child({ component: "ProductSyncer" }); this.log = (log ?? pino({ level: "silent" })).child({ component: "ProductSyncer" });
} }
async sync(opt: SyncOptions = {}) { async sync(opt: ProductSyncerOptions = {}) {
this.log.info("starting sync run");
const startDate = new Date(); const startDate = new Date();
await opt.onStart?.(startDate); await opt.onStart?.(startDate);
@@ -256,7 +255,7 @@ export class ProductSyncer {
async generateMetaPrintfulProducts( async generateMetaPrintfulProducts(
allWebflowProducts: Webflow.Products.ProductAndSkus[], allWebflowProducts: Webflow.Products.ProductAndSkus[],
allPrintfulProducts: Printful.Products.SyncProduct[], allPrintfulProducts: Printful.Products.SyncProduct[],
opt: SyncOptions, opt: ProductSyncerOptions,
) { ) {
const metaNameFilter = opt.filter?.printfulProductIds const metaNameFilter = opt.filter?.printfulProductIds
?.map((id) => allPrintfulProducts.find((p) => p.id === id)) ?.map((id) => allPrintfulProducts.find((p) => p.id === id))