|
| 1 | +import type { createDbClient } from "@bunny.net/openapi-client"; |
| 2 | +import type { components } from "@bunny.net/openapi-client/generated/database.d.ts"; |
| 3 | +import { UserError } from "../../core/errors.ts"; |
| 4 | +import { DB_PAGE_SIZE, TOKEN_TTL_MINUTES } from "./constants.ts"; |
| 5 | + |
| 6 | +type DbClient = ReturnType<typeof createDbClient>; |
| 7 | +type Database = components["schemas"]["Database2"]; |
| 8 | +type RegionConfig = components["schemas"]["ListConfigAPIResponse"]; |
| 9 | +type GenerateTokenResponse = |
| 10 | + components["schemas"]["GenerateTokenDatabaseV2Response"]; |
| 11 | +type TokenAuthorization = |
| 12 | + components["schemas"]["GenerateTokenDatabaseV2Payload"]["authorization"]; |
| 13 | +type DBLiveStatus = components["schemas"]["DBLiveStatus"]; |
| 14 | + |
| 15 | +/** Fetch a single database by ID, throwing a UserError if it doesn't exist. */ |
| 16 | +export async function fetchDatabase( |
| 17 | + client: DbClient, |
| 18 | + id: string, |
| 19 | +): Promise<Database> { |
| 20 | + const { data } = await client.GET("/v2/databases/{db_id}", { |
| 21 | + params: { path: { db_id: id } }, |
| 22 | + }); |
| 23 | + if (!data?.db) throw new UserError(`Database ${id} not found.`); |
| 24 | + return data.db; |
| 25 | +} |
| 26 | + |
| 27 | +/** Fetch every database in the account, paginating until exhausted. */ |
| 28 | +export async function fetchAllDatabases(client: DbClient): Promise<Database[]> { |
| 29 | + const all: Database[] = []; |
| 30 | + let page = 1; |
| 31 | + |
| 32 | + while (true) { |
| 33 | + const { data } = await client.GET("/v2/databases", { |
| 34 | + params: { query: { page, per_page: DB_PAGE_SIZE } }, |
| 35 | + }); |
| 36 | + |
| 37 | + all.push(...(data?.databases ?? [])); |
| 38 | + |
| 39 | + if (!data?.page_info?.has_more_items) break; |
| 40 | + page++; |
| 41 | + } |
| 42 | + |
| 43 | + return all; |
| 44 | +} |
| 45 | + |
| 46 | +/** Fetch the global region configuration, throwing if unavailable. */ |
| 47 | +export async function fetchRegionConfig( |
| 48 | + client: DbClient, |
| 49 | +): Promise<RegionConfig> { |
| 50 | + const { data } = await client.GET("/v1/config", { params: {} }); |
| 51 | + if (!data) throw new UserError("Could not fetch region configuration."); |
| 52 | + return data; |
| 53 | +} |
| 54 | + |
| 55 | +/** Fetch a database and the region config in parallel. */ |
| 56 | +export async function fetchDatabaseWithRegions( |
| 57 | + client: DbClient, |
| 58 | + id: string, |
| 59 | +): Promise<{ db: Database; config: RegionConfig }> { |
| 60 | + const [db, config] = await Promise.all([ |
| 61 | + fetchDatabase(client, id), |
| 62 | + fetchRegionConfig(client), |
| 63 | + ]); |
| 64 | + return { db, config }; |
| 65 | +} |
| 66 | + |
| 67 | +/** Build a region id → display name lookup from the region config. */ |
| 68 | +export function regionNameMap(config: RegionConfig): Map<string, string> { |
| 69 | + const map = new Map<string, string>(); |
| 70 | + for (const r of [...config.primary_regions, ...config.replica_regions]) { |
| 71 | + map.set(r.id, r.name); |
| 72 | + } |
| 73 | + return map; |
| 74 | +} |
| 75 | + |
| 76 | +/** Generate an auth token for a database. */ |
| 77 | +export async function generateToken( |
| 78 | + client: DbClient, |
| 79 | + id: string, |
| 80 | + opts: { authorization: TokenAuthorization; expiresAt: string | null }, |
| 81 | +): Promise<GenerateTokenResponse | undefined> { |
| 82 | + const { data } = await client.PUT("/v2/databases/{db_id}/auth/generate", { |
| 83 | + params: { path: { db_id: id } }, |
| 84 | + body: { authorization: opts.authorization, expires_at: opts.expiresAt }, |
| 85 | + }); |
| 86 | + return data; |
| 87 | +} |
| 88 | + |
| 89 | +/** RFC 3339 timestamp `minutes` from now (defaults to the token TTL). */ |
| 90 | +export function tokenExpiryFromNow(minutes = TOKEN_TTL_MINUTES): string { |
| 91 | + return new Date(Date.now() + minutes * 60 * 1000).toISOString(); |
| 92 | +} |
| 93 | + |
| 94 | +/** Fetch live status metrics for the given database IDs. */ |
| 95 | +export async function fetchLiveStatus( |
| 96 | + client: DbClient, |
| 97 | + ids: string[], |
| 98 | +): Promise<Record<string, DBLiveStatus>> { |
| 99 | + const { data } = await client.POST("/v1/live/live_db", { |
| 100 | + body: { db_ids: ids }, |
| 101 | + }); |
| 102 | + return data?.live_metrics ?? {}; |
| 103 | +} |
| 104 | + |
| 105 | +/** "Active" when the database is live, otherwise "Idle". */ |
| 106 | +export function liveStatusLabel(live: DBLiveStatus | undefined): string { |
| 107 | + return live?.state === "Live" ? "Active" : "Idle"; |
| 108 | +} |
| 109 | + |
| 110 | +/** Primary region code from live metadata, or null when not live. */ |
| 111 | +export function liveMainRegion(live: DBLiveStatus | undefined): string | null { |
| 112 | + return live?.state === "Live" ? live.metadata.main : null; |
| 113 | +} |
0 commit comments