| 69 | function databaseConstraint(error: unknown): string | null { |
| 70 | let current: unknown = error; |
| 71 | for (let depth = 0; depth < 5 && current && typeof current === 'object'; depth++) { |
| 72 | if ('constraint' in current && typeof current.constraint === 'string') { |
| 73 | return current.constraint; |
| 74 | } |
| 75 | current = 'cause' in current ? current.cause : null; |
| 76 | } |
| 77 | return null; |
| 78 | } |
| 79 | |
| 80 | // Credential validation calls the live provider API per key. Bound the fan-out so |
| 81 | // large inventory uploads finish within the request budget without overwhelming |
| 82 | // the upstream provider with one unbounded burst of requests. |
| 83 | const INVENTORY_VALIDATION_CONCURRENCY = 10; |
| 84 | const BYTEPLUS_INVENTORY_VALIDATION_CONCURRENCY = 2; |
| 85 | |
| 86 | type CancellationReason = |
| 87 | | 'user_canceled' |
| 88 | | 'insufficient_credits' |
| 89 | | 'account_deleted' |
| 90 | | 'administrative_termination'; |
| 91 | |
| 92 | type SubscriptionOutcome = { |
| 93 | subscriptionId: string; |
| 94 | charged: boolean; |
| 95 | }; |
| 96 | |
| 97 | export type CodingPlanUsageAssignmentContext = |
| 98 | | { providerId: 'minimax'; apiKey: string } |
| 99 | | { providerId: 'byteplus-coding'; seatId: string }; |
| 100 | |
| 101 | export async function getAssignedCodingPlanUsageContext(input: { |
| 102 | inventoryId: string; |
| 103 | userId: string; |
| 104 | planId: string; |
| 105 | providerId: string; |
| 106 | }): Promise<CodingPlanUsageAssignmentContext | null> { |
| 107 | const [assignment] = await db |
| 108 | .select({ |
| 109 | planId: coding_plan_key_inventory.plan_id, |
| 110 | providerId: coding_plan_key_inventory.provider_id, |
| 111 | status: coding_plan_key_inventory.status, |
| 112 | assignedToUserId: coding_plan_key_inventory.assigned_to_user_id, |
| 113 | encryptedApiKey: coding_plan_key_inventory.encrypted_api_key, |
| 114 | upstreamUsageId: coding_plan_key_inventory.upstream_usage_id, |
| 115 | }) |
| 116 | .from(coding_plan_key_inventory) |
| 117 | .where(eq(coding_plan_key_inventory.id, input.inventoryId)) |
| 118 | .limit(1); |
| 119 | if ( |
| 120 | !assignment || |
| 121 | assignment.status !== 'assigned' || |
| 122 | assignment.assignedToUserId !== input.userId || |
| 123 | assignment.planId !== input.planId || |
| 124 | assignment.providerId !== input.providerId |
| 125 | ) { |
| 126 | return null; |
| 127 | } |
| 128 | |