Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
ALTER TABLE "coderouter_accounts"
ADD COLUMN "usage" jsonb,
ADD COLUMN "usage_error" text,
ADD COLUMN "usage_fetched_at" timestamp with time zone,
ADD COLUMN "usage_refresh_claimed_at" timestamp with time zone;
10 changes: 10 additions & 0 deletions web/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1210,6 +1210,16 @@ export const coderouterAccounts = pgTable(
cooldownUntil: timestamp("cooldown_until", { withTimezone: true }),
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
lastFailureCode: text("last_failure_code"),
/**
* Last provider quota read for `cr` status. Display data: routing uses
* `cooldown_until`. Served while fresh so status does not call the
* provider once per account per request.
*/
usage: jsonb("usage").$type<unknown>(),
usageError: text("usage_error"),
usageFetchedAt: timestamp("usage_fetched_at", { withTimezone: true }),
/** One web instance refreshes a stale reading at a time. */
usageRefreshClaimedAt: timestamp("usage_refresh_claimed_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
Expand Down
74 changes: 73 additions & 1 deletion web/services/coderouter/repository.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { grantVmImportedAccount } from "./vmAccountImport";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { and, eq, gt, isNotNull, isNull, lt, lte, or, sql } from "drizzle-orm";
import { and, eq, gt, inArray, isNotNull, isNull, lt, lte, or, sql } from "drizzle-orm";
import { cloudDb } from "../../db/client";
import { runWithCloudDbQuerySignal } from "../../db/queryScope";
import {
Expand Down Expand Up @@ -642,6 +642,78 @@ export async function listCoderouterTeamIds(): Promise<readonly string[]> {
.then((rows) => rows.map((row) => row.teamId));
}

export type StoredAccountUsage = {
readonly usage: unknown;
readonly usageError: string | null;
readonly fetchedAt: Date;
};

/** The last quota reading per account, for accounts that have one. */
export async function storedAccountUsage(
teamId: string,
): Promise<ReadonlyMap<string, StoredAccountUsage>> {
const rows = await cloudDb()
.select({
id: coderouterAccounts.id,
usage: coderouterAccounts.usage,
usageError: coderouterAccounts.usageError,
fetchedAt: coderouterAccounts.usageFetchedAt,
})
.from(coderouterAccounts)
.where(and(eq(coderouterAccounts.teamId, teamId), isNotNull(coderouterAccounts.usageFetchedAt)));
return new Map(rows.flatMap((row) => row.fetchedAt
? [[row.id, { usage: row.usage ?? null, usageError: row.usageError, fetchedAt: row.fetchedAt }] as const]
: []));
}

/**
* Claims the stale readings this instance will refresh. An account whose
* refresh another instance claimed after `claimedBefore` is skipped, so
* concurrent status views issue one provider read per account.
*/
export async function claimAccountUsageRefresh(
teamId: string,
accountIds: readonly string[],
now: Date,
claimedBefore: Date,
): Promise<readonly string[]> {
if (accountIds.length === 0) return [];
const rows = await cloudDb()
.update(coderouterAccounts)
.set({ usageRefreshClaimedAt: now })
.where(and(
eq(coderouterAccounts.teamId, teamId),
inArray(coderouterAccounts.id, [...accountIds]),
or(
isNull(coderouterAccounts.usageRefreshClaimedAt),
lt(coderouterAccounts.usageRefreshClaimedAt, claimedBefore),
),
))
.returning({ id: coderouterAccounts.id });
return rows.map((row) => row.id);
}

/** Records a quota reading. An older reading never replaces a newer one. */
export async function storeAccountUsage(
teamId: string,
accountId: string,
reading: { readonly usage: unknown } | { readonly usageError: string },
fetchedAt: Date,
): Promise<void> {
await cloudDb()
.update(coderouterAccounts)
.set({
usage: "usage" in reading ? reading.usage : null,
usageError: "usageError" in reading ? reading.usageError : null,
usageFetchedAt: fetchedAt,
})
.where(and(
eq(coderouterAccounts.teamId, teamId),
eq(coderouterAccounts.id, accountId),
or(isNull(coderouterAccounts.usageFetchedAt), lt(coderouterAccounts.usageFetchedAt, fetchedAt)),
));
}

export async function listEncryptedCredentials(
teamId: string,
): Promise<readonly EncryptedCredential[]> {
Expand Down
Loading
Loading