Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fdd8596787 | ||
|
|
6e9ce94d46 | ||
|
|
daaf779562 |
@@ -38,6 +38,3 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
|
||||
# Agents
|
||||
.claude/settings.local.json
|
||||
|
||||
# Local test media for seed scripts
|
||||
apps/api/src/scripts/fixtures
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Local test media for seed scripts
|
||||
src/scripts/test-verification-media
|
||||
@@ -2,18 +2,20 @@ import Elysia, { NotFoundError, t } from "elysia";
|
||||
import { ActivityPerformanceSchema, PlayerSchema } from "@blade-and-brawn/domain";
|
||||
import { authPlugin } from "../plugins/auth";
|
||||
import { s } from "../services";
|
||||
import { BigIntIdSchema } from "../util/models";
|
||||
import { AccountIdSchema, BigIntIdSchema } from "../util/models";
|
||||
|
||||
const AssessmentsController = new Elysia({ prefix: "/assessments" })
|
||||
.use(authPlugin)
|
||||
.guard({ authAdmin: true })
|
||||
.post("/", async ({ body: { player, activityPerformances, id } }) => {
|
||||
return await s.Assessments.create(player, activityPerformances, id);
|
||||
.post("/", async ({ body: { player, activityPerformances, accountId } }) => {
|
||||
const account = await s.Accounts.get(accountId);
|
||||
if (!account) throw new NotFoundError("Account not found");
|
||||
return await s.Assessments.create(player, activityPerformances, account.id);
|
||||
}, {
|
||||
body: t.Object({
|
||||
player: PlayerSchema,
|
||||
activityPerformances: t.Array(ActivityPerformanceSchema),
|
||||
id: t.Optional(t.String()),
|
||||
accountId: AccountIdSchema,
|
||||
})
|
||||
})
|
||||
.put("/:id", async ({ body: { player, activityPerformances }, params: { id } }) => {
|
||||
|
||||
@@ -22,7 +22,7 @@ const AuthController = new Elysia({ prefix: "/auth" })
|
||||
.post("/login", async ({ jwt, body: { password, email }, cookie: { auth } }) => {
|
||||
const account = await s.Accounts.getByEmail(email);
|
||||
const password_match = await Bun.password.verify(password, account?.password_hash ?? DUMMY_PASSWORD_HASH);
|
||||
if (!account || !password_match) throw new UnauthorizedError("Invalid credentials");
|
||||
if (!account?.password_hash || !password_match) throw new UnauthorizedError("Invalid credentials");
|
||||
|
||||
auth.set({
|
||||
value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }),
|
||||
@@ -62,9 +62,11 @@ const AuthController = new Elysia({ prefix: "/auth" })
|
||||
.get("/callback", async ({ query, cookie: { authDiscord, auth }, jwt }) => {
|
||||
if (query.error) throw new BadRequestError(query.error_description ? `${query.error}: ${query.error_description}` : query.error);
|
||||
|
||||
// Validate input
|
||||
if (!query.state) throw new BadRequestError("No Discord OAuth2 state query parameter provided");
|
||||
if (query.state !== authDiscord.value) throw new BadRequestError("Invalid Discord OAuth state");
|
||||
|
||||
// Retrieve access token from discord
|
||||
const tokenRes = await fetch("https://discord.com/api/oauth2/token", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -80,36 +82,38 @@ const AuthController = new Elysia({ prefix: "/auth" })
|
||||
});
|
||||
if (!tokenRes.ok) {
|
||||
const errorBody = await tokenRes.json().catch(() => null);
|
||||
throw new BadGatewayError(errorBody ?? "Discord token exchange failed");
|
||||
throw new BadGatewayError(errorBody ? JSON.stringify(errorBody) : "Discord token exchange failed");
|
||||
}
|
||||
|
||||
const tokenResPayload = await tokenRes.json();
|
||||
Value.Assert(t.Object({ access_token: t.String() }), tokenResPayload);
|
||||
|
||||
// Retrieve user's discord identity
|
||||
const identityRes = await fetch("https://discord.com/api/users/@me", {
|
||||
headers: { "Authorization": `Bearer ${tokenResPayload.access_token}` }
|
||||
});
|
||||
if (!identityRes.ok) {
|
||||
const errorBody = await identityRes.json().catch(() => null);
|
||||
throw new BadGatewayError(errorBody ?? "Failed to fetch Discord identity");
|
||||
throw new BadGatewayError(errorBody ? JSON.stringify(errorBody) : "Failed to fetch Discord identity");
|
||||
}
|
||||
const discordIdentity = await identityRes.json();
|
||||
Value.Assert(t.Object({ id: t.String(), email: t.Optional(t.Nullable(t.String())), username: t.String(), verified: t.Boolean() }), discordIdentity);
|
||||
|
||||
// Get account or create if it dosent exist
|
||||
let account = await s.Accounts.get(`@${discordIdentity.id}`);
|
||||
if (!account) {
|
||||
// only accept VERIFIED emails not already used by another account
|
||||
const email = discordIdentity.verified && discordIdentity.email ? discordIdentity.email : undefined;
|
||||
const emailTaken = email !== undefined && !!(await s.Accounts.getByEmail(email));
|
||||
account = await s.Accounts.create(
|
||||
discordIdentity.id,
|
||||
emailTaken ? undefined : email,
|
||||
discordIdentity.username
|
||||
);
|
||||
}
|
||||
|
||||
const identityResPayload = await identityRes.json();
|
||||
Value.Assert(t.Object({ id: t.String(), email: t.Optional(t.String()), username: t.String() }), identityResPayload);
|
||||
|
||||
// Create the account
|
||||
let accountId = (await s.Accounts.get(`@${identityResPayload.id}`))?.id;
|
||||
if (!accountId) {
|
||||
accountId = (await s.Accounts.create(
|
||||
identityResPayload.id,
|
||||
identityResPayload.email,
|
||||
identityResPayload.username
|
||||
)).id;
|
||||
}
|
||||
|
||||
// Authenticate
|
||||
// Setup and sign auth cookie
|
||||
auth.set({
|
||||
value: await jwt.sign({ role: "user" satisfies AccountRole, sessionId: randomUUIDv7(), accountId, exp: JWT_EXP }),
|
||||
value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }),
|
||||
path: "/",
|
||||
maxAge: JWT_EXP_SECONDS,
|
||||
sameSite: env.NODE_ENV === "production" ? "lax" : "none",
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
import Elysia, { NotFoundError, t } from "elysia";
|
||||
import { StandardsParamsSchema } from "@blade-and-brawn/calculator";
|
||||
import { authPlugin } from "../plugins/auth";
|
||||
import { s } from "../services";
|
||||
import { BigIntIdSchema } from "../util/models";
|
||||
import { ConflictError } from "../util/error";
|
||||
|
||||
const StandardsController = new Elysia({ prefix: "/standards" })
|
||||
.use(authPlugin)
|
||||
@@ -17,18 +18,27 @@ const StandardsController = new Elysia({ prefix: "/standards" })
|
||||
})
|
||||
.group("/:id", (app) => app
|
||||
.get("/", async ({ params: { id } }) => {
|
||||
return await s.Standards.Configs.get(id);
|
||||
const config = await s.Standards.Configs.get(id);
|
||||
if (!config) throw new NotFoundError("Standards config not found");
|
||||
return config;
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
.put("/", async ({ params: { id }, body: { name, datasetId, params: parameters } }) => {
|
||||
await s.Standards.Configs.update(id, name, datasetId, parameters);
|
||||
// Active config is not allowed to be edited
|
||||
const activeConfig = await s.Calculator.Standards.Config.get();
|
||||
if (activeConfig.id === id) throw new ConflictError("Cannot edit the active standards config");
|
||||
|
||||
const updated = await s.Standards.Configs.update(id, name, datasetId, parameters);
|
||||
if (!updated) throw new NotFoundError("Standards config not found");
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema }),
|
||||
body: t.Object({ name: t.String(), datasetId: BigIntIdSchema, params: StandardsParamsSchema })
|
||||
})
|
||||
.delete("/", async ({ params: { id } }) => {
|
||||
await s.Standards.Configs.delete(id);
|
||||
if (await s.Standards.Configs.count() <= 1) throw new ConflictError("Cannot delete the last remaining standards config");
|
||||
const deleted = await s.Standards.Configs.delete(id);
|
||||
if (!deleted) throw new NotFoundError("Standards config not found");
|
||||
}, { params: t.Object({ id: BigIntIdSchema }) })
|
||||
)
|
||||
)
|
||||
@@ -38,12 +48,15 @@ const StandardsController = new Elysia({ prefix: "/standards" })
|
||||
})
|
||||
.group("/:id", (app) => app
|
||||
.get("/", async ({ params: { id } }) => {
|
||||
return await s.Standards.Datasets.get(id);
|
||||
const dataset = await s.Standards.Datasets.get(id);
|
||||
if (!dataset) throw new NotFoundError("Standards dataset not found");
|
||||
return dataset;
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
.patch("/", async ({ params: { id }, body: { name } }) => {
|
||||
await s.Standards.Datasets.update(id, name);
|
||||
const updated = await s.Standards.Datasets.update(id, name);
|
||||
if (!updated) throw new NotFoundError("Standards dataset not found");
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema }),
|
||||
body: t.Object({ name: t.String() })
|
||||
|
||||
BIN
Binary file not shown.
Binary file not shown.
@@ -56,6 +56,9 @@ export const app = new Elysia()
|
||||
switch (code) {
|
||||
case "HttpError":
|
||||
break;
|
||||
case "CalculatorUnavailableError":
|
||||
log.error({ err: error.cause }, error.message);
|
||||
break;
|
||||
case "PrintfulError":
|
||||
case "WebflowError":
|
||||
log.error({ upstreamStatus: error.upstreamStatus, payload: error.payload }, error.message);
|
||||
|
||||
@@ -22,7 +22,7 @@ export class AccountsService {
|
||||
name: name ?? "",
|
||||
email: email ?? null
|
||||
})
|
||||
.returning("id")
|
||||
.returning(["id", "discord_id", "name", "email", "gender", "role"])
|
||||
.executeTakeFirstOrThrow();
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,9 @@ class CalculatorStandardsConfigService {
|
||||
config: null as StandardsConfig | null
|
||||
},
|
||||
isStale: async () => {
|
||||
// Becomes stale only when standards are switched
|
||||
// We currently enforce read-only view of selected calculator's standards config
|
||||
// So only way to update calculator is to make new standards config, edit, then switch
|
||||
const { standards_config_id: selectedConfigId } = await db.selectFrom("calculators")
|
||||
.select("standards_config_id")
|
||||
.where("name", "=", this.name)
|
||||
|
||||
@@ -65,7 +65,7 @@ class ApparelOrdersService {
|
||||
shippingAddress: t.Object({
|
||||
addressee: t.String(),
|
||||
line1: t.String(),
|
||||
line2: t.String(),
|
||||
line2: t.Optional(t.Union([t.String(), t.Null()])),
|
||||
city: t.String(),
|
||||
country: t.String(),
|
||||
postalCode: t.String(),
|
||||
@@ -82,6 +82,12 @@ class ApparelOrdersService {
|
||||
processor: async (payload) => {
|
||||
const wOrder = payload.wOrder;
|
||||
|
||||
// a previous attempt may have created the order before failing
|
||||
if (await this.Printful.Orders.get(`@${wOrder.orderId}`)) {
|
||||
log.info({ wOrderId: wOrder.orderId }, "printful order already exists, skipping creation");
|
||||
return;
|
||||
}
|
||||
|
||||
const stateCode = zipcodesUs.find(
|
||||
wOrder.shippingAddress.postalCode.split("-")[0] ?? "",
|
||||
).stateCode;
|
||||
@@ -95,7 +101,7 @@ class ApparelOrdersService {
|
||||
recipient: {
|
||||
name: wOrder.shippingAddress.addressee,
|
||||
address1: wOrder.shippingAddress.line1,
|
||||
address2: wOrder.shippingAddress.line2,
|
||||
address2: wOrder.shippingAddress.line2 ?? "",
|
||||
city: wOrder.shippingAddress.city,
|
||||
state_code: stateCode,
|
||||
country_code: wOrder.shippingAddress.country,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type Selectable, type Transaction } from "kysely";
|
||||
import { sql, type Selectable, type Transaction } from "kysely";
|
||||
import type { DB } from "../database/out/db";
|
||||
import { log } from "../util/log";
|
||||
import { sleep } from "bun";
|
||||
@@ -29,7 +29,6 @@ type EventQueueCfg = {
|
||||
},
|
||||
};
|
||||
|
||||
class AlreadyClaimedEventError extends Error { }
|
||||
class ConcurrencyLimitReachedError extends Error { }
|
||||
|
||||
export function defineEventType<P extends TSchema, S extends TSchema>(opt: EventTypeOptions<P, S>): EventTypeOptions<P, S> {
|
||||
@@ -46,7 +45,6 @@ function exponentialDelay(initialDelay: number, tries: number, cap: number = Inf
|
||||
}
|
||||
|
||||
export class EventQueue<G extends string, T extends Record<string, EventTypeOptions<any, any>>> {
|
||||
private static readonly DEQUEUE_ALREADY_CLAIMED_SKIP_DELAY_MS = 250;
|
||||
private static readonly DEQUEUE_RETRY_DELAY_MS = secToMs(10);
|
||||
private static readonly DEQUEUE_RETRY_LIMIT = 3;
|
||||
private static readonly RATE_LIMIT_RETRY_LIMIT = 15;
|
||||
@@ -77,15 +75,8 @@ export class EventQueue<G extends string, T extends Record<string, EventTypeOpti
|
||||
consecutiveFailures = 0;
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof AlreadyClaimedEventError) {
|
||||
log.warn("event processing already claimed by another worker, skipping");
|
||||
await sleep(EventQueue.DEQUEUE_ALREADY_CLAIMED_SKIP_DELAY_MS);
|
||||
continue;
|
||||
}
|
||||
if (err instanceof ConcurrencyLimitReachedError) {
|
||||
await sleep(EventQueue.DEQUEUE_RETRY_DELAY_MS);
|
||||
continue;
|
||||
}
|
||||
// Return to the manager loop so it can clean timed out events
|
||||
if (err instanceof ConcurrencyLimitReachedError) break;
|
||||
|
||||
if (++consecutiveFailures <= EventQueue.DEQUEUE_RETRY_LIMIT) {
|
||||
log.warn({ err, consecutiveFailures }, "dequeue failed, retrying")
|
||||
@@ -102,37 +93,29 @@ export class EventQueue<G extends string, T extends Record<string, EventTypeOpti
|
||||
async dequeue() {
|
||||
log.trace("dequeueing");
|
||||
|
||||
const front = await this.front();
|
||||
if (!front) return;
|
||||
// Serialize claims per group so concurrent workers see each other's claims when checking the concurrency limit
|
||||
const front = await db.transaction().execute(async (trx) => {
|
||||
await sql`select pg_advisory_xact_lock(hashtext(${this.group}))`.execute(trx);
|
||||
|
||||
const result = await db.updateTable("events")
|
||||
.set({ started_at: new Date(), heartbeat_at: new Date() })
|
||||
.where("id", "=", front.id)
|
||||
.where("started_at", "is", null)
|
||||
.where((eb) =>
|
||||
eb(
|
||||
eb.selectFrom("events")
|
||||
.select(eb.fn.countAll().as("count"))
|
||||
.where("group", "=", this.group)
|
||||
.where("started_at", "is not", null)
|
||||
.where("ended_at", "is", null),
|
||||
"<",
|
||||
this.cfg.concurrency.limit
|
||||
)
|
||||
)
|
||||
.executeTakeFirstOrThrow();
|
||||
const { count } = await trx.selectFrom("events")
|
||||
.select(trx.fn.countAll().as("count"))
|
||||
.where("group", "=", this.group)
|
||||
.where("started_at", "is not", null)
|
||||
.where("ended_at", "is", null)
|
||||
.executeTakeFirstOrThrow();
|
||||
if (Number(count) >= this.cfg.concurrency.limit) throw new ConcurrencyLimitReachedError();
|
||||
|
||||
// Guard against another worker/machine having already claimed this event and guard against max concurrency
|
||||
if (result.numUpdatedRows === 0n) {
|
||||
const frontFresh = await db.selectFrom("events")
|
||||
.select("started_at")
|
||||
const front = await this.front(trx);
|
||||
if (!front) return;
|
||||
|
||||
await trx.updateTable("events")
|
||||
.set({ started_at: new Date(), heartbeat_at: new Date() })
|
||||
.where("id", "=", front.id)
|
||||
.executeTakeFirst();
|
||||
.execute();
|
||||
|
||||
if (!frontFresh) throw new AlreadyClaimedEventError();
|
||||
if (frontFresh?.started_at) throw new AlreadyClaimedEventError();
|
||||
throw new ConcurrencyLimitReachedError();
|
||||
};
|
||||
return front;
|
||||
});
|
||||
if (!front) return;
|
||||
|
||||
log.trace({ name: front.id }, "dequeuing event");
|
||||
await this.process(front);
|
||||
|
||||
@@ -120,7 +120,7 @@ export class EventsService {
|
||||
|
||||
async resolve(id: string, trx?: Transaction<DB>): Promise<void> {
|
||||
await (trx ?? db).updateTable("events")
|
||||
.set({ state: null, ended_at: new Date(), last_error: null })
|
||||
.set({ state: null, ended_at: new Date(), has_failed: false, last_error: null })
|
||||
.where("id", "=", id)
|
||||
.execute();
|
||||
}
|
||||
@@ -132,6 +132,8 @@ export class EventsService {
|
||||
started_at: null,
|
||||
ended_at: null,
|
||||
has_failed: false,
|
||||
errors: 0,
|
||||
rate_limits: 0,
|
||||
available_at: new Date(),
|
||||
})
|
||||
.where("id", "=", id)
|
||||
|
||||
@@ -31,7 +31,7 @@ class StandardsConfigService {
|
||||
.execute();
|
||||
}
|
||||
|
||||
async get(id: string): Promise<StandardsConfig & { id: string, name: string, datasetId: string }> {
|
||||
async get(id: string): Promise<(StandardsConfig & { id: string, name: string, datasetId: string }) | undefined> {
|
||||
const result = await db.selectFrom("standards_configs")
|
||||
.innerJoin("standards_datasets", "standards_datasets.id", "standards_configs.dataset_id")
|
||||
.select([
|
||||
@@ -42,7 +42,8 @@ class StandardsConfigService {
|
||||
"standards_datasets.data as data",
|
||||
])
|
||||
.where("standards_configs.id", "=", id)
|
||||
.executeTakeFirstOrThrow({ errorConstructor: () => new Error(`No config with id "${id}"`) });
|
||||
.executeTakeFirst();
|
||||
if (!result) return;
|
||||
Value.Assert(StandardsParamsSchema, result.params);
|
||||
Value.Assert(StandardsDataSchema, result.data);
|
||||
return {
|
||||
@@ -54,24 +55,26 @@ class StandardsConfigService {
|
||||
};
|
||||
}
|
||||
|
||||
async update(id: string, name: string, datasetId: string, params: StandardsParams) {
|
||||
async update(id: string, name: string, datasetId: string, params: StandardsParams): Promise<boolean> {
|
||||
const result = await db.updateTable("standards_configs")
|
||||
.set({ name, params, dataset_id: datasetId })
|
||||
.where("id", "=", id)
|
||||
.execute();
|
||||
if (result[0]?.numUpdatedRows === 0n) throw new Error(`No config with id "${id}"`);
|
||||
.executeTakeFirst();
|
||||
return result.numUpdatedRows > 0n;
|
||||
}
|
||||
|
||||
async delete(id: string) {
|
||||
async count(): Promise<number> {
|
||||
const { count } = await db.selectFrom("standards_configs")
|
||||
.select(db.fn.countAll<number>().as("count"))
|
||||
.executeTakeFirstOrThrow();
|
||||
if (Number(count) <= 1) throw new Error("Cannot delete the last remaining standards configuration");
|
||||
return Number(count);
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<boolean> {
|
||||
const result = await db.deleteFrom("standards_configs")
|
||||
.where("id", "=", id)
|
||||
.execute();
|
||||
if (result[0]?.numDeletedRows === 0n) throw new Error(`No config with id "${id}"`);
|
||||
.executeTakeFirst();
|
||||
return result.numDeletedRows > 0n;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,20 +86,21 @@ class StandardsDatasetService {
|
||||
.execute();
|
||||
}
|
||||
|
||||
async get(id: string): Promise<{ id: string, name: string, data: StandardsData }> {
|
||||
async get(id: string): Promise<{ id: string, name: string, data: StandardsData } | undefined> {
|
||||
const result = await db.selectFrom("standards_datasets")
|
||||
.select(["id", "name", "data"])
|
||||
.where("id", "=", id)
|
||||
.executeTakeFirstOrThrow({ errorConstructor: () => new Error(`No dataset with id "${id}"`) });
|
||||
.executeTakeFirst();
|
||||
if (!result) return;
|
||||
Value.Assert(StandardsDataSchema, result.data);
|
||||
return { id: result.id, name: result.name, data: result.data };
|
||||
}
|
||||
|
||||
async update(id: string, name: string) {
|
||||
async update(id: string, name: string): Promise<boolean> {
|
||||
const result = await db.updateTable("standards_datasets")
|
||||
.set({ name })
|
||||
.where("id", "=", id)
|
||||
.execute();
|
||||
if (result[0]?.numUpdatedRows === 0n) throw new Error(`No dataset with id "${id}"`);
|
||||
.executeTakeFirst();
|
||||
return result.numUpdatedRows > 0n;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user