| 1 | import { createId } from "@paralleldrive/cuid2"; |
| 2 | import { |
| 3 | boolean, |
| 4 | jsonb, |
| 5 | pgEnum, |
| 6 | pgTable, |
| 7 | text, |
| 8 | timestamp, |
| 9 | integer, |
| 10 | index, |
| 11 | check, |
| 12 | uuid, |
| 13 | } from "drizzle-orm/pg-core"; |
| 14 | import { repository } |
| 15 | import { organization } |
| 16 | import { sql } |
| 17 | |
| 18 | export const webhookEndpoint = |
| 19 | "webhook_endpoint", |
| 20 | { |
| 21 | id: text() |
| 22 | .primaryKey() |
| 23 | .$defaultFn(() => |
| 24 | repositoryId: text().references |
| 25 | onDelete: "cascade", |
| 26 | }), |
| 27 | organizationId: text().references |
| 28 | onDelete: "cascade", |
| 29 | }), |
| 30 | url: text().notNull |
| 31 | secret: text().notNull |
| 32 | events: text().array |
| 33 | active: boolean().default |
| 34 | disabledReason: text(), |
| 35 | createdAt: timestamp({ |
| 36 | updatedAt: timestamp({ |
| 37 | .notNull() |
| 38 | .defaultNow() |
| 39 | .$onUpdateFn(() => |
| 40 | }, |
| 41 | (t) => |
| 42 | // enforce this endpoint has only 1 owner. Either a repo or an org |
| 43 | check( |
| 44 | "webhook_endpoint_owner", |
| 45 | sql`num_nonnulls(repository_id, organization_id) = 1`, |
| 46 | ), |
| 47 | index("webhook_endpoint_repository_idx"). |
| 48 | index("webhook_endpoint_organization_idx"). |
| 49 | ], |
| 50 | ); |
| 51 | |
| 52 | export const deliveryJobStatus = |
| 53 | "pending", |
| 54 | "succeeded", |
| 55 | "dead", |
| 56 | ]); |
| 57 | |
| 58 | export const deliveryJobKind = |
| 59 | "email", |
| 60 | "webhook", |
| 61 | ]); |
| 62 | |
| 63 | export const deliveryJob = |
| 64 | "delivery_job", |
| 65 | { |
| 66 | id: uuid().primaryKey |
| 67 | kind: deliveryJobKind().notNull |
| 68 | idempotencyKey: text().unique |
| 69 | payload: jsonb().notNull |
| 70 | endpointId: text().references |
| 71 | onDelete: "cascade", |
| 72 | }), |
| 73 | status: deliveryJobStatus().notNull |
| 74 | attempts: integer().notNull |
| 75 | nextAttemptAt: timestamp({ |
| 76 | lockedUntil: timestamp({ |
| 77 | claimToken: uuid().notNull |
| 78 | lastError: text(), |
| 79 | createdAt: timestamp({ |
| 80 | updatedAt: timestamp({ |
| 81 | .notNull() |
| 82 | .defaultNow() |
| 83 | .$onUpdateFn(() => |
| 84 | }, |
| 85 | (t) => |
| 86 | index("delivery_job_pending_idx") |
| 87 | .on(t.nextAttemptAt |
| 88 | .where(sql`${ |
| 89 | ], |
| 90 | ); |
| 91 | |
| 92 | export const deliveryAttempt = |
| 93 | "delivery_attempt", |
| 94 | { |
| 95 | id: uuid().primaryKey |
| 96 | jobId: uuid() |
| 97 | .references(() => |
| 98 | .notNull(), |
| 99 | startedAt: timestamp({ |
| 100 | durationMs: integer().notNull |
| 101 | statusCode: integer(), |
| 102 | error: text(), |
| 103 | requestHeaders: jsonb().notNull |
| 104 | responseBody: text(), |
| 105 | }, |
| 106 | (t) => |
| 107 | ); |