Enqueue product sync delete event

This commit is contained in:
Dominic Ferrando
2026-07-12 05:44:09 -04:00
parent 4c2acfaede
commit f4638ef028
4 changed files with 34 additions and 16 deletions
+6 -1
View File
@@ -253,7 +253,12 @@ export const app = new Elysia()
log.info({ externalId: payload.data.sync_product.external_id, wProductId }, "printful webhook: product deleted"); log.info({ externalId: payload.data.sync_product.external_id, wProductId }, "printful webhook: product deleted");
if (!wProductId) throw new NotFoundError("Missing webflow product ID"); if (!wProductId) throw new NotFoundError("Missing webflow product ID");
await s.Commerce.Webflow.Products.remove(wProductId); await s.Commerce.ProductSync.Queue.enqueue({
type: "product_sync_delete",
source: "printful",
payload: { wProductId }
});
break; break;
} }
case Printful.Webhook.Event.PackageShipped: { case Printful.Webhook.Event.PackageShipped: {
+18 -5
View File
@@ -7,6 +7,7 @@ import type { Static } from "@sinclair/typebox";
import { Value } from "@sinclair/typebox/value"; import { Value } from "@sinclair/typebox/value";
import { sql } from "kysely"; import { sql } from "kysely";
// product_sync_update
const ProductSyncUpdatePayloadSchema = t.Object({ const ProductSyncUpdatePayloadSchema = t.Object({
session: t.Object({ session: t.Object({
name: t.String(), name: t.String(),
@@ -19,7 +20,6 @@ const ProductSyncUpdatePayloadSchema = t.Object({
) )
}); });
type ProductSyncUpdatePayload = Static<typeof ProductSyncUpdatePayloadSchema>; type ProductSyncUpdatePayload = Static<typeof ProductSyncUpdatePayloadSchema>;
const ProductSyncUpdateStateSchema = t.Union([ const ProductSyncUpdateStateSchema = t.Union([
t.Object({ t.Object({
pProductIds: t.Optional(t.Array(t.Number())) pProductIds: t.Optional(t.Array(t.Number()))
@@ -28,9 +28,15 @@ const ProductSyncUpdateStateSchema = t.Union([
]); ]);
type ProductSyncUpdateState = Static<typeof ProductSyncUpdateStateSchema>; type ProductSyncUpdateState = Static<typeof ProductSyncUpdateStateSchema>;
// product_sync_delete
const ProductSyncDeletePayloadSchema = t.Object({ wProductId: t.String() });
type ProductSyncDeletePayload = Static<typeof ProductSyncDeletePayloadSchema>;
const ProductSyncDeleteStateSchema = t.Union([t.Object({}), t.Null()]);
type ProductSyncDeleteState = Static<typeof ProductSyncDeleteStateSchema>;
export type ProductSyncEvents = { export type ProductSyncEvents = {
product_sync_update: EventSpec<ProductSyncUpdatePayload, ProductSyncUpdateState> product_sync_update: EventSpec<ProductSyncUpdatePayload, ProductSyncUpdateState>;
// TODO: product_sync_delete, once its schema/processor are written product_sync_delete: EventSpec<ProductSyncDeletePayload, ProductSyncDeleteState>;
}; };
export class CommerceService { export class CommerceService {
@@ -62,17 +68,23 @@ class ProductSyncService {
retry: { limit: 3, delayMs: 10000 }, retry: { limit: 3, delayMs: 10000 },
concurrency: { limit: 1, timeoutMs: 600000 } concurrency: { limit: 1, timeoutMs: 600000 }
}, },
types: { events: {
"product_sync_update": { "product_sync_update": {
schemas: { payload: ProductSyncUpdatePayloadSchema, state: ProductSyncUpdateStateSchema }, schemas: { payload: ProductSyncUpdatePayloadSchema, state: ProductSyncUpdateStateSchema },
processor: async (id, payload, setState) => { processor: async (id, payload, setState) => {
await this.ProductSyncer.syncApparel({ await this.ProductSyncer.sync({
filter: payload.filter, filter: payload.filter,
beforeStep: async (pProductIds: number[]) => { beforeStep: async (pProductIds: number[]) => {
await setState({ pProductIds }); await setState({ pProductIds });
} }
}); });
} }
},
"product_sync_delete": {
schemas: { payload: ProductSyncDeletePayloadSchema, state: ProductSyncDeleteStateSchema },
processor: async (id, payload, setState) => {
await this.Webflow.Products.remove(payload.wProductId);
}
} }
} }
}); });
@@ -82,6 +94,7 @@ class ProductSyncService {
const latestSync = await db.selectFrom("events") const latestSync = await db.selectFrom("events")
.select(["started_at", "ended_at", "has_failed", "state"]) .select(["started_at", "ended_at", "has_failed", "state"])
.where("group", "=", ProductSyncService.EVENT_GROUP) .where("group", "=", ProductSyncService.EVENT_GROUP)
.where("type", "=", "product_sync_update")
.where(sql<string>`payload->'session'->>'id'`, "=", sessionId) .where(sql<string>`payload->'session'->>'id'`, "=", sessionId)
.orderBy(sql`(started_at is not null and ended_at is null)`, "desc") .orderBy(sql`(started_at is not null and ended_at is null)`, "desc")
.orderBy("created_at", "desc") .orderBy("created_at", "desc")
+9 -9
View File
@@ -6,17 +6,17 @@ import { db } from "../database/db";
import { Value } from "@sinclair/typebox/value"; import { Value } from "@sinclair/typebox/value";
import type { TSchema } from "@sinclair/typebox"; import type { TSchema } from "@sinclair/typebox";
export type EventSpec<P extends JsonValue = JsonValue, S extends JsonValue = JsonValue> = { export type EventSpec<P extends JsonValue, S extends JsonValue> = {
payload: P, payload: P,
state: S state: S
} }
export type EventSource = "portal" | "printful" | "webflow"; export type EventSource = "portal" | "printful" | "webflow";
type EventProcessor<S extends EventSpec> = type EventProcessor<S extends EventSpec<JsonValue, JsonValue>> =
(id: string, payload: S["payload"], setState: (state: S["state"]) => Promise<void>) => Promise<void>; (id: string, payload: S["payload"], setState: (state: S["state"]) => Promise<void>) => Promise<void>;
type EventStatus = "pending" | "processing" | "failed" | "fulfilled"; type EventStatus = "pending" | "processing" | "failed" | "fulfilled";
type EventTypeOptions<S extends EventSpec> = { type EventTypeOptions<S extends EventSpec<JsonValue, JsonValue>> = {
schemas: { schemas: {
payload: TSchema & { static: S["payload"] }, payload: TSchema & { static: S["payload"] },
state: TSchema & { static: S["state"] }, state: TSchema & { static: S["state"] },
@@ -24,7 +24,7 @@ type EventTypeOptions<S extends EventSpec> = {
processor: EventProcessor<S>, processor: EventProcessor<S>,
}; };
type EventQueueOptions<G extends string, M extends Record<string, EventSpec>> = { type EventQueueOptions<G extends string, M extends Record<string, EventSpec<JsonValue, JsonValue>>> = {
group: G, group: G,
cfg: { cfg: {
retry: { retry: {
@@ -36,12 +36,12 @@ type EventQueueOptions<G extends string, M extends Record<string, EventSpec>> =
timeoutMs: number, timeoutMs: number,
}, },
}, },
types: { events: {
[T in keyof M]: EventTypeOptions<M[T]> [T in keyof M]: EventTypeOptions<M[T]>
}, },
} }
type EnqueueOptions<M extends Record<string, EventSpec>, T extends keyof M & string> = { type EnqueueOptions<M extends Record<string, EventSpec<JsonValue, JsonValue>>, T extends keyof M & string> = {
source: EventSource, source: EventSource,
type: T, type: T,
payload: M[T]["payload"] payload: M[T]["payload"]
@@ -50,7 +50,7 @@ type EnqueueOptions<M extends Record<string, EventSpec>, T extends keyof M & str
class AlreadyClaimedEventError extends Error { } class AlreadyClaimedEventError extends Error { }
class ConcurrencyLimitReachedError extends Error { } class ConcurrencyLimitReachedError extends Error { }
export class EventQueue<G extends string, M extends Record<string, EventSpec>> { export class EventQueue<G extends string, M extends Record<string, EventSpec<JsonValue, JsonValue>>> {
private _lastCleanDate: Date = new Date(0); private _lastCleanDate: Date = new Date(0);
readonly cfg: EventQueueOptions<G, M>["cfg"]; readonly cfg: EventQueueOptions<G, M>["cfg"];
readonly group: G; readonly group: G;
@@ -201,8 +201,8 @@ export class EventQueue<G extends string, M extends Record<string, EventSpec>> {
private async handleEvent(id: string, type: string, payload: JsonValue) { private async handleEvent(id: string, type: string, payload: JsonValue) {
log.info({ id, payload }, "handling event"); log.info({ id, payload }, "handling event");
if (!(type in this.opt.types)) throw new Error(`Unknown event type: ${type}`); if (!(type in this.opt.events)) throw new Error(`Unknown event type: ${type}`);
const cfg = this.opt.types[type as keyof M]; const cfg = this.opt.events[type as keyof M];
try { try {
Value.Assert(cfg.schemas.payload, payload); Value.Assert(cfg.schemas.payload, payload);
await cfg.processor(id, payload, async (state) => { await cfg.processor(id, payload, async (state) => {
+1 -1
View File
@@ -37,7 +37,7 @@ export class ProductSyncer {
this.log = (log ?? pino({ level: "silent" })).child({ component: "ProductSyncer" }); this.log = (log ?? pino({ level: "silent" })).child({ component: "ProductSyncer" });
} }
async syncApparel(opt: ProductSyncerOptions = {}) { async sync(opt: ProductSyncerOptions = {}) {
const startDate = new Date(); const startDate = new Date();
await opt.beforeStart?.(startDate); await opt.beforeStart?.(startDate);