(params: {
conn: DbConn
userId: string
subscription: SubscriptionRow
logger: Logger
now?: Date
})
| 255 | * All operations are serialised under an advisory lock for the user. |
| 256 | */ |
| 257 | export async function ensureActiveBlockGrantCallback(params: { |
| 258 | conn: DbConn |
| 259 | userId: string |
| 260 | subscription: SubscriptionRow |
| 261 | logger: Logger |
| 262 | now?: Date |
| 263 | }): Promise<BlockGrantResult> { |
| 264 | const { conn, userId, subscription, logger, now = new Date() } = params |
| 265 | const subscriptionId = subscription.stripe_subscription_id |
| 266 | |
| 267 | // 1. Check for an existing non-expired block grant (regardless of balance) |
| 268 | const existingGrants = await conn |
| 269 | .select() |
| 270 | .from(schema.creditLedger) |
| 271 | .where( |
| 272 | and( |
| 273 | eq(schema.creditLedger.user_id, userId), |
| 274 | eq(schema.creditLedger.type, 'subscription'), |
| 275 | gt(schema.creditLedger.expires_at, now), |
| 276 | ), |
| 277 | ) |
| 278 | .orderBy(desc(schema.creditLedger.expires_at)) |
| 279 | .limit(1) |
| 280 | |
| 281 | if (existingGrants.length > 0) { |
| 282 | const g = existingGrants[0] |
| 283 | |
| 284 | // Block exists with credits remaining - return it |
| 285 | if (g.balance > 0) { |
| 286 | return { |
| 287 | grantId: g.operation_id, |
| 288 | credits: g.balance, |
| 289 | expiresAt: g.expires_at!, |
| 290 | isNew: false, |
| 291 | } satisfies BlockGrant |
| 292 | } |
| 293 | |
| 294 | // Block exists but is exhausted - don't create a new one until it expires |
| 295 | return { |
| 296 | error: 'block_exhausted', |
| 297 | blockUsed: g.principal, |
| 298 | blockLimit: g.principal, |
| 299 | resetsAt: g.expires_at!, |
| 300 | } satisfies BlockExhaustedError |
| 301 | } |
| 302 | |
| 303 | // 2. Resolve limits |
| 304 | const limits = await getSubscriptionLimits({ |
| 305 | userId, |
| 306 | logger, |
| 307 | conn, |
| 308 | tier: subscription.tier, |
| 309 | }) |
| 310 | |
| 311 | // 3. Check weekly limit before creating a new block |
| 312 | const weekly = await getWeeklyUsage({ |
| 313 | userId, |
| 314 | billingPeriodStart: subscription.billing_period_start, |
no test coverage detected