diff --git a/apps/api/src/database/db.ts b/apps/api/src/database/db.ts index 0d15d6f..2aa8d90 100644 --- a/apps/api/src/database/db.ts +++ b/apps/api/src/database/db.ts @@ -1,7 +1,7 @@ import { CreateTableBuilder, Kysely, PostgresDialect, sql } from 'kysely'; import { type DB } from "./out/db"; import { Pool } from "pg"; -import { env, WORKER_COUNT } from '../util'; +import { env, WORKER_COUNT } from '../util/env'; export const db = new Kysely({ dialect: new PostgresDialect({ diff --git a/apps/api/src/database/migrate.ts b/apps/api/src/database/migrate.ts index 6941c0f..4bfb29c 100644 --- a/apps/api/src/database/migrate.ts +++ b/apps/api/src/database/migrate.ts @@ -3,7 +3,8 @@ import { promises as fs } from 'fs' import { FileMigrationProvider, Migrator, type MigrationResultSet } from 'kysely/migration' import { db } from './db' import { argv } from 'bun' -import { env, log } from '../util' +import { env } from '../util/env'; +import { log } from '../util/log'; type HandlerResult = { message: string; diff --git a/apps/api/src/database/seed.ts b/apps/api/src/database/seed.ts index 2ff759c..87aa440 100644 --- a/apps/api/src/database/seed.ts +++ b/apps/api/src/database/seed.ts @@ -3,10 +3,13 @@ import { } from "@blade-and-brawn/calculator"; import { Value } from "@sinclair/typebox/value"; import { db } from "./db"; -import { DEFAULT_NAME, env, log } from "../util"; +import { env } from "../util/env"; +import { log } from "../util/log"; import standardsConfig from "./seed-data/standards-config.json" with {type: "json"}; import type { AccountRole } from "../services/accounts"; +export const DEFAULT_NAME = "Default"; + Value.Assert(StandardsConfigSchema, standardsConfig); async function seedStandardsDataset(): Promise { diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 01ac074..8ad1682 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -1,5 +1,6 @@ import cluster from 'node:cluster' -import { log, WORKER_COUNT } from "./util"; +import { log } from "./util/log"; +import { WORKER_COUNT } from "./util/env"; if (cluster.isPrimary) { log.info(`Starting ${WORKER_COUNT} worker processes`) diff --git a/apps/api/src/scripts/list-collections.ts b/apps/api/src/scripts/list-collections.ts index 6c2dbdc..17c729e 100644 --- a/apps/api/src/scripts/list-collections.ts +++ b/apps/api/src/scripts/list-collections.ts @@ -1,5 +1,5 @@ import { WebflowClient } from "@blade-and-brawn/commerce"; -import { env } from "../util"; +import { env } from "../util/env"; const webflow = new WebflowClient({ siteId: env.WEBFLOW_SITE_ID, diff --git a/apps/api/src/scripts/register-webhooks.ts b/apps/api/src/scripts/register-webhooks.ts index dda5593..3ff429b 100644 --- a/apps/api/src/scripts/register-webhooks.ts +++ b/apps/api/src/scripts/register-webhooks.ts @@ -1,5 +1,5 @@ import { Printful, PrintfulClient, PrintfulError, Webflow, WebflowClient, WebflowError } from "@blade-and-brawn/commerce"; -import { env } from "../util"; +import { env } from "../util/env"; const DOMAIN = env.NODE_ENV === "development" ? "dev-api.bladeandbrawn.com" : diff --git a/apps/api/src/scripts/seed-test-verification.ts b/apps/api/src/scripts/seed-test-verification.ts index 3d3de5c..15f4f2d 100644 --- a/apps/api/src/scripts/seed-test-verification.ts +++ b/apps/api/src/scripts/seed-test-verification.ts @@ -4,7 +4,8 @@ import { readdir } from "node:fs/promises"; import path from "node:path"; import { parseArgs } from "node:util"; import { db } from "../database/db"; -import { env, log } from "../util"; +import { env } from "../util/env"; +import { log } from "../util/log"; import type { AccountRole } from "../services/accounts"; import { VerificationsService } from "../services/verifications"; diff --git a/apps/api/src/scripts/validate-products.ts b/apps/api/src/scripts/validate-products.ts index 0abe0ce..fc3b6e8 100644 --- a/apps/api/src/scripts/validate-products.ts +++ b/apps/api/src/scripts/validate-products.ts @@ -3,7 +3,7 @@ import { ProductSyncer, WebflowClient, } from "@blade-and-brawn/commerce"; -import { env } from "../util"; +import { env } from "../util/env"; const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); diff --git a/apps/api/src/server.ts b/apps/api/src/server.ts index 59b47f8..2e7364c 100644 --- a/apps/api/src/server.ts +++ b/apps/api/src/server.ts @@ -11,7 +11,11 @@ import { Printful, Webflow, } from "@blade-and-brawn/commerce"; -import { AccountIdSchema, BadGatewayError, BadRequestError, BigIntIdSchema, ConflictError, DEFAULT_NAME, DUMMY_PASSWORD_HASH, env, ForbiddenError, HttpError, log, UnauthorizedError } from "./util"; +import { AccountIdSchema, BigIntIdSchema } from "./util/models"; +import { BadGatewayError, BadRequestError, ConflictError, ForbiddenError, HttpError, UnauthorizedError } from "./util/error"; +import { DUMMY_PASSWORD_HASH } from "./util/crypto"; +import { env } from "./util/env"; +import { log } from "./util/log"; import serverTiming from "@elysia/server-timing"; import jwt from "@elysia/jwt"; import { CommerceService, WOrderStatusSchema } from "./services/commerce"; @@ -37,7 +41,7 @@ const JWT_EXP_SECONDS = 60 * 60 * 24; // keep in sync with JWT_EXP; used for coo // ----------------------- const s = (() => { const Standards = new StandardsService(); - const Calculator = new CalculatorService(DEFAULT_NAME); + const Calculator = new CalculatorService(); const Commerce = new CommerceService(); const Accounts = new AccountsService(Calculator); const Events = new EventsService(); diff --git a/apps/api/src/services/calculator.ts b/apps/api/src/services/calculator.ts index 12ad1e7..60bb3bf 100644 --- a/apps/api/src/services/calculator.ts +++ b/apps/api/src/services/calculator.ts @@ -1,6 +1,6 @@ import { LevelCalculator, Standards, StandardsParamsSchema, StandardsDataSchema, type StandardsConfig, type LevelCalculatorOutput } from "@blade-and-brawn/calculator"; import type { ActivityPerformance, Player } from "@blade-and-brawn/domain"; -import { log } from "../util"; +import { log } from "../util/log"; import { db } from "../database/db"; import { Value } from "@sinclair/typebox/value"; @@ -16,11 +16,13 @@ export class CalculatorUnavailableError extends Error { } export class CalculatorService { + private static readonly DEFAULT_NAME = "Default"; + private calculator: LevelCalculator | null = null; Standards: CalculatorStandardsService; - constructor(private name: string) { - this.Standards = new CalculatorStandardsService(this.name); + constructor() { + this.Standards = new CalculatorStandardsService(CalculatorService.DEFAULT_NAME); // eagerly load this.refresh().catch((err) => log.error({ err }, "failed to load initial standards config")); } diff --git a/apps/api/src/services/commerce.ts b/apps/api/src/services/commerce.ts index 57017ff..3cffb26 100644 --- a/apps/api/src/services/commerce.ts +++ b/apps/api/src/services/commerce.ts @@ -1,5 +1,6 @@ import { PrintfulClient, ProductSyncer, WebflowClient } from "@blade-and-brawn/commerce"; -import { env, log } from "../util"; +import { env } from "../util/env"; +import { log } from "../util/log"; import { db } from "../database/db"; import { defineEventType, EventQueue } from "./event-queue"; import { Type as t } from "@sinclair/typebox"; diff --git a/apps/api/src/services/event-queue.ts b/apps/api/src/services/event-queue.ts index 8c8ac28..897baed 100644 --- a/apps/api/src/services/event-queue.ts +++ b/apps/api/src/services/event-queue.ts @@ -1,6 +1,6 @@ import { type Selectable, type Transaction } from "kysely"; import type { DB } from "../database/out/db"; -import { log } from "../util"; +import { log } from "../util/log"; import { sleep } from "bun"; import { db } from "../database/db"; import { AssertError, Value } from "@sinclair/typebox/value"; diff --git a/apps/api/src/services/events.ts b/apps/api/src/services/events.ts index c0c143e..ffd14d2 100644 --- a/apps/api/src/services/events.ts +++ b/apps/api/src/services/events.ts @@ -3,7 +3,7 @@ import { t } from "elysia"; import { sql, type Selectable, type Transaction } from "kysely"; import type { DB, JsonValue } from "../database/out/db"; import { db } from "../database/db"; -import { log } from "../util"; +import { log } from "../util/log"; import { minToMs } from "@blade-and-brawn/domain"; export const EventStatusSchema = t.Union([ diff --git a/apps/api/src/util/crypto.ts b/apps/api/src/util/crypto.ts new file mode 100644 index 0000000..34fed07 --- /dev/null +++ b/apps/api/src/util/crypto.ts @@ -0,0 +1,4 @@ +import { createHash } from "node:crypto"; + +export const DUMMY_PASSWORD_HASH = await Bun.password.hash("Dummy"); +export const sha256Sum = (s: string) => createHash("sha256").update(s).digest(); diff --git a/apps/api/src/util.ts b/apps/api/src/util/env.ts similarity index 54% rename from apps/api/src/util.ts rename to apps/api/src/util/env.ts index bdf3701..8da39b2 100644 --- a/apps/api/src/util.ts +++ b/apps/api/src/util/env.ts @@ -1,15 +1,5 @@ import cluster from 'node:cluster'; -import { createHash } from 'node:crypto'; -import { pino } from 'pino'; import os from 'node:os' -import { t } from 'elysia'; - -export const log = pino({ - level: Bun.env.LOG_LEVEL ?? "info", - transport: Bun.env.NODE_ENV != "production" - ? { target: "pino-pretty" } - : undefined, -}); export const env = { PRINTFUL_AUTH: requireEnv("PRINTFUL_AUTH"), @@ -39,47 +29,12 @@ export const env = { }; export const WORKER_COUNT = Math.min(os.availableParallelism(), +env.MAX_WORKER_COUNT); -export const DEFAULT_NAME = "Default"; -export const DUMMY_PASSWORD_HASH = await Bun.password.hash("Dummy"); - -export class HttpError extends Error { - constructor(public status: number, message: string) { - super(message); - } - - toResponse() { - return Response.json({ error: this.message }, { status: this.status }); - } -} - -export class BadRequestError extends HttpError { - constructor(message: string) { super(400, message); } -} - -export class UnauthorizedError extends HttpError { - constructor(message: string) { super(401, message); } -} - -export class ForbiddenError extends HttpError { - constructor(message: string) { super(403, message); } -} - -export class ConflictError extends HttpError { - constructor(message: string) { super(409, message); } -} - -export class BadGatewayError extends HttpError { - constructor(message: string) { super(502, message); } -} - -export const BigIntIdSchema = t.String({ pattern: "^\\d+$" }); -export const AccountIdSchema = t.String({ pattern: "^(@.+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$" }); function requireEnv(key: string): string { const val = Bun.env[key]; if (!val) { if (cluster.worker?.id === 1) - log.error({ name: key }, "Missing required environment variable"); + console.error({ name: key }, "Missing required environment variable"); throw new Error(`Missing required environment variable: ${key}`) }; return val; @@ -89,10 +44,8 @@ function optionEnv(key: string, fallback: string = ""): string { const val = Bun.env[key]; if (!val) { if (cluster.worker?.id === 1) - log.warn({ name: key }, `Missing optional environmental variable, falling back to "${fallback}"`) + console.warn({ name: key }, `Missing optional environmental variable, falling back to "${fallback}"`) return fallback }; return val; } - -export const sha256Sum = (s: string) => createHash("sha256").update(s).digest(); diff --git a/apps/api/src/util/error.ts b/apps/api/src/util/error.ts new file mode 100644 index 0000000..77920d1 --- /dev/null +++ b/apps/api/src/util/error.ts @@ -0,0 +1,29 @@ +export class HttpError extends Error { + constructor(public status: number, message: string) { + super(message); + } + + toResponse() { + return Response.json({ error: this.message }, { status: this.status }); + } +} + +export class BadRequestError extends HttpError { + constructor(message: string) { super(400, message); } +} + +export class UnauthorizedError extends HttpError { + constructor(message: string) { super(401, message); } +} + +export class ForbiddenError extends HttpError { + constructor(message: string) { super(403, message); } +} + +export class ConflictError extends HttpError { + constructor(message: string) { super(409, message); } +} + +export class BadGatewayError extends HttpError { + constructor(message: string) { super(502, message); } +} diff --git a/apps/api/src/util/log.ts b/apps/api/src/util/log.ts new file mode 100644 index 0000000..2fafd60 --- /dev/null +++ b/apps/api/src/util/log.ts @@ -0,0 +1,8 @@ +import { pino } from 'pino'; + +export const log = pino({ + level: Bun.env.LOG_LEVEL ?? "info", + transport: Bun.env.NODE_ENV != "production" + ? { target: "pino-pretty" } + : undefined, +}); diff --git a/apps/api/src/util/models.ts b/apps/api/src/util/models.ts new file mode 100644 index 0000000..b481206 --- /dev/null +++ b/apps/api/src/util/models.ts @@ -0,0 +1,4 @@ +import { t } from 'elysia'; + +export const BigIntIdSchema = t.String({ pattern: "^\\d+$" }); +export const AccountIdSchema = t.String({ pattern: "^(@.+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$" }); diff --git a/bun.lock b/bun.lock index edd66b3..2655a22 100644 --- a/bun.lock +++ b/bun.lock @@ -11,6 +11,7 @@ }, "devDependencies": { "@types/bun": "^1.4.2", + "@types/node": "^26.6.4", "@typescript/native": "npm:typescript@7", "typescript": "~6", }, diff --git a/package.json b/package.json index b7315bc..513827f 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ }, "devDependencies": { "@types/bun": "^1.4.2", + "@types/node": "^26.6.4", "@typescript/native": "npm:typescript@7", "typescript": "~6" },