Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 39x 39x 39x 1x 1x 1x 39x 39x 1x 1x 1x 16x 16x 16x 16x 1x 5x 5x 5x 1x 1x 1x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 19x 19x 19x 19x 4x 3x 3x 18x 19x 3x 3x 2x 2x 1x 1x 1x 1x 3x 15x 19x 3x 3x 12x 12x 12x 12x 12x 12x 12x 5x 5x 5x 5x 5x 5x 5x 19x 7x 6x 6x 6x 1x 1x 19x 12x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 6x 6x 6x 6x 1x 1x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 6x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x | import { RestError } from "@azure/data-tables";
import { MONTHLY_ANALYSES, type Tier, type UsageEntity } from "../models/user";
import { ensureTable } from "./tablesService";
/**
* Usage metering (contracts/metering.md, data-model.md `Usage`): one entity
* per user per UTC month, incremented BEFORE the OpenAI call so exhaustion
* never costs a token (fail closed). Optimistic concurrency via real ETags
* only — never `If-Match: *`, never an unconditional write — so N parallel
* requests at the cap yield exactly one winner (SC-002).
*/
const TABLE = "Usage";
/** Bounded retry budget for both the create-race and the 412 update loop. */
const MAX_RETRIES = 4;
export class MeteringUnavailableError extends Error {
constructor(message = "Couldn't verify your usage allowance. Please try again.") {
super(message);
this.name = "MeteringUnavailableError";
}
}
export interface UsageResult {
count: number;
limit: number;
resetsAt: string;
tier: Tier;
}
export interface CheckAndIncrementResult extends UsageResult {
allowed: boolean;
}
function pad2(n: number): string {
return String(n).padStart(2, "0");
}
/** `"usage-" + YYYY-MM` for the given (default: current) UTC month. */
export function usageRowKey(date: Date = new Date()): string {
return `usage-${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}`;
}
/** First instant of the next UTC month (FR-008) — no reset write ever happens. */
export function resetsAt(date: Date = new Date()): string {
return new Date(
Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1, 0, 0, 0, 0)
).toISOString();
}
function isNotFound(err: unknown): boolean {
return err instanceof RestError && err.statusCode === 404;
}
function isConflict(err: unknown): boolean {
return err instanceof RestError && err.statusCode === 409;
}
function isPreconditionFailed(err: unknown): boolean {
return err instanceof RestError && err.statusCode === 412;
}
/**
* Check-and-increment algorithm (contracts/metering.md, normative). `limit`
* is always recomputed from the current `tier` — mid-month upgrades unblock
* immediately (FR-019); the stored `limit` column is refreshed but never the
* enforcement input.
*/
export async function checkAndIncrement(
sub: string,
tier: Tier
): Promise<CheckAndIncrementResult> {
const limit = MONTHLY_ANALYSES[tier];
const rowKey = usageRowKey();
const reset = resetsAt();
const client = await ensureTable(TABLE);
let createRetries = 0;
let updateRetries = 0;
for (;;) {
let existing: (UsageEntity & { etag?: string }) | null;
try {
existing = await client.getEntity<UsageEntity>(sub, rowKey);
} catch (err) {
if (!isNotFound(err)) throw new MeteringUnavailableError();
existing = null;
}
if (!existing) {
try {
await client.createEntity({ partitionKey: sub, rowKey, count: 1, limit });
return { allowed: true, count: 1, limit, resetsAt: reset, tier };
} catch (err) {
if (isConflict(err) && createRetries < MAX_RETRIES) {
createRetries++;
continue;
}
throw new MeteringUnavailableError();
}
}
if (existing.count >= limit) {
return { allowed: false, count: existing.count, limit, resetsAt: reset, tier };
}
try {
await client.updateEntity(
{ partitionKey: sub, rowKey, count: existing.count + 1, limit },
"Replace",
{ etag: existing.etag }
);
return {
allowed: true,
count: existing.count + 1,
limit,
resetsAt: reset,
tier,
};
} catch (err) {
if (isPreconditionFailed(err) && updateRetries < MAX_RETRIES) {
updateRetries++;
continue;
}
throw new MeteringUnavailableError();
}
}
}
/**
* Best-effort conditional decrement on a system-caused analysis failure
* (FR-007): same ETag discipline, floor at 0, max 2 attempts. Never throws —
* a lost refund over-counts by one and is accepted (contracts/metering.md).
*/
export async function refundOnSystemFailure(sub: string, tier: Tier): Promise<void> {
const limit = MONTHLY_ANALYSES[tier];
const rowKey = usageRowKey();
const client = await ensureTable(TABLE);
for (let attempt = 0; attempt < 2; attempt++) {
let existing: (UsageEntity & { etag?: string }) | null;
try {
existing = await client.getEntity<UsageEntity>(sub, rowKey);
} catch {
return;
}
if (existing.count <= 0) return;
try {
await client.updateEntity(
{
partitionKey: sub,
rowKey,
count: Math.max(0, existing.count - 1),
limit,
},
"Replace",
{ etag: existing.etag }
);
return;
} catch {
// Retry once on conflict; otherwise give up silently (best-effort).
}
}
}
/** Read-only usage view for GET /api/account — never increments. */
export async function peekUsage(sub: string, tier: Tier): Promise<UsageResult> {
const limit = MONTHLY_ANALYSES[tier];
const rowKey = usageRowKey();
const reset = resetsAt();
const client = await ensureTable(TABLE);
try {
const existing = await client.getEntity<UsageEntity>(sub, rowKey);
return { count: existing.count, limit, resetsAt: reset, tier };
} catch (err) {
if (isNotFound(err)) return { count: 0, limit, resetsAt: reset, tier };
throw new MeteringUnavailableError();
}
}
|