| 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 | // Set once the owner has been emailed about the disable, so every API instance's sweep emails them once. |
| 36 | disabledNotifiedAt: timestamp({ |
| 37 | createdAt: timestamp({ |
| 38 | updatedAt: timestamp({ |
| 39 | .notNull() |
| 40 | .defaultNow() |
| 41 | .$onUpdateFn(() => |
| 42 | }, |
| 43 | (t) => |
| 44 | // enforce this endpoint has only 1 owner. Either a repo or an org |
| 45 | check( |
| 46 | "webhook_endpoint_owner", |
| 47 | sql`num_nonnulls(repository_id, organization_id) = 1`, |
| 48 | ), |
| 49 | index("webhook_endpoint_repository_idx"). |
| 50 | index("webhook_endpoint_organization_idx"). |
| 51 | ], |
| 52 | ); |
| 53 | |
| 54 | export const deliveryJobStatus = |
| 55 | "pending", |
| 56 | "succeeded", |
| 57 | "dead", |
| 58 | ]); |
| 59 | |
| 60 | export const deliveryJobKind = |
| 61 | "email", |
| 62 | "webhook", |
| 63 | ]); |
| 64 | |
| 65 | export const deliveryJob = |
| 66 | "delivery_job", |
| 67 | { |
| 68 | id: uuid().primaryKey |
| 69 | kind: deliveryJobKind().notNull |
| 70 | idempotencyKey: text().unique |
| 71 | payload: jsonb().notNull |
| 72 | endpointId: text().references |
| 73 | onDelete: "cascade", |
| 74 | }), |
| 75 | status: deliveryJobStatus().notNull |
| 76 | attempts: integer().notNull |
| 77 | nextAttemptAt: timestamp({ |
| 78 | lockedUntil: timestamp({ |
| 79 | claimToken: uuid().notNull |
| 80 | lastError: text(), |
| 81 | createdAt: timestamp({ |
| 82 | updatedAt: timestamp({ |
| 83 | .notNull() |
| 84 | .defaultNow() |
| 85 | .$onUpdateFn(() => |
| 86 | }, |
| 87 | (t) => |
| 88 | index("delivery_job_pending_idx") |
| 89 | .on(t.nextAttemptAt |
| 90 | .where(sql`${ |
| 91 | ], |
| 92 | ); |
| 93 | |
| 94 | export const deliveryAttempt = |
| 95 | "delivery_attempt", |
| 96 | { |
| 97 | id: uuid().primaryKey |
| 98 | jobId: uuid() |
| 99 | .references(() => |
| 100 | .notNull(), |
| 101 | startedAt: timestamp({ |
| 102 | durationMs: integer().notNull |
| 103 | statusCode: integer(), |
| 104 | error: text(), |
| 105 | requestHeaders: jsonb().notNull |
| 106 | responseBody: text(), |
| 107 | }, |
| 108 | (t) => |
| 109 | ); |