(params: {
operationId: string
reason: string
logger: Logger
})
| 354 | * @returns true if the grant was found and revoked, false otherwise |
| 355 | */ |
| 356 | export async function revokeGrantByOperationId(params: { |
| 357 | operationId: string |
| 358 | reason: string |
| 359 | logger: Logger |
| 360 | }): Promise<boolean> { |
| 361 | const { operationId, reason, logger } = params |
| 362 | |
| 363 | // First, look up the grant to get the user_id for the advisory lock |
| 364 | const grant = await db.query.creditLedger.findFirst({ |
| 365 | where: eq(schema.creditLedger.operation_id, operationId), |
| 366 | }) |
| 367 | |
| 368 | if (!grant) { |
| 369 | logger.warn({ operationId }, 'Attempted to revoke non-existent grant') |
| 370 | return false |
| 371 | } |
| 372 | |
| 373 | // Determine lock key based on whether this is a user or org grant |
| 374 | const lockKey = grant.org_id ? `org:${grant.org_id}` : `user:${grant.user_id}` |
| 375 | |
| 376 | const { result } = await withAdvisoryLockTransaction({ |
| 377 | callback: async (tx) => { |
| 378 | // Re-fetch within transaction to get current state |
| 379 | const currentGrant = await tx.query.creditLedger.findFirst({ |
| 380 | where: eq(schema.creditLedger.operation_id, operationId), |
| 381 | }) |
| 382 | |
| 383 | if (!currentGrant) { |
| 384 | logger.warn( |
| 385 | { operationId }, |
| 386 | 'Grant no longer exists after acquiring lock', |
| 387 | ) |
| 388 | return false |
| 389 | } |
| 390 | |
| 391 | if (currentGrant.balance < 0) { |
| 392 | logger.warn( |
| 393 | { operationId, currentBalance: currentGrant.balance }, |
| 394 | 'Cannot revoke grant with negative balance - user has already spent these credits', |
| 395 | ) |
| 396 | return false |
| 397 | } |
| 398 | |
| 399 | await tx |
| 400 | .update(schema.creditLedger) |
| 401 | .set({ |
| 402 | principal: 0, |
| 403 | balance: 0, |
| 404 | description: `${currentGrant.description} (Revoked: ${reason})`, |
| 405 | }) |
| 406 | .where(eq(schema.creditLedger.operation_id, operationId)) |
| 407 | |
| 408 | logger.info( |
| 409 | { |
| 410 | operationId, |
| 411 | userId: currentGrant.user_id, |
| 412 | orgId: currentGrant.org_id, |
| 413 | revokedAmount: currentGrant.balance, |
no test coverage detected