docs: 更新 MySQL 展示系统说明

This commit is contained in:
2026-05-11 20:51:43 +08:00
parent ddd077eb37
commit 6f627fe776
2 changed files with 147 additions and 285 deletions
+67 -201
View File
@@ -1,232 +1,98 @@
# AGENTS.md
Compact, repo-specific notes for AI agents. Generic language/framework knowledge is omitted — only things that will bite you if you don't know. Pair this with `README.md` (user-facing quick-start + add-a-feature checklist + deploy flow).
Repo-specific notes for AI agents.
## Stack & runtime
## Stack
- **Bun-only** (`mise.toml` pins `bun = 1.3.13`). Never invoke `npm`/`npx`/`node`/`yarn`/`pnpm`. Use `bun run <script>` (bare `bun <script>` can collide with Bun built-in subcommands).
- **Prefer Bun-native APIs over external packages and `node:*` polyfills.** UUIDv7 in app code → `Bun.randomUUIDv7()` (not the `uuid` package); DB primary keys are a separate matter — those go through PG18's `uuidv7()`, see "Drizzle" section. SHA-256 → `Bun.CryptoHasher.hash('sha256', s, 'hex')` (not `node:crypto.createHash`); short sleeps → `Bun.sleep(ms)` (not raw `setTimeout` with promise wrapping); file I/O in build scripts → `Bun.file` / `Bun.write` are fine. The runtime is Bun, the deployment target is Bun, the test runner is Bun — there is no "portability" concern that would justify dragging in npm packages or Node compat shims for things Bun ships natively.
- TanStack Start (React 19 SSR, file-routed) + Vite 8 + Nitro (nightly, preset `bun`). Dev server defaults to Vite's port (3000); not pinned, override via `vite dev --port <n>` if you need to.
- **PostgreSQL 18+ only** (`compose.yaml` pins `postgres:18-alpine`). The starter relies on PG18's built-in `uuidv7()` function for primary-key generation — see "Drizzle" section. Do not soften this to support older PG; if you need PG <18 compatibility, fork and reintroduce app-side UUIDv7 (e.g. `Bun.randomUUIDv7()` or the `uuid` package) yourself.
- **Drizzle ORM `0.45.2` (0.x, NOT 1.0 beta)** — see "Drizzle" section, this matters a lot.
- ORPC (contract-first), TanStack Query v5, Tailwind v4.
- **Logging via [LogTape](https://logtape.org/)** (zero-dep, runtime-agnostic) — see "Logging" section. `console.*` is forbidden in business code.
- Bun-only (`mise.toml` pins `bun = 1.3.13`). Do not use `npm` / `npx` / `node` / `yarn` / `pnpm`.
- TanStack Start + React 19 SSR + Vite + Nitro `bun` preset.
- ORPC contract-first API, TanStack Query v5, Tailwind v4.
- Business data source is the customer's existing **MySQL** database. This app is read-only display software.
- There is no PostgreSQL, Drizzle schema, embedded migration flow, or local DB mutation path in this project now.
- `scripts/seed.ts` is the only local development helper allowed to create/truncate/insert sample data. The app runtime must stay read-only.
## Scripts
```bash
bun run dev # bunx --bun vite dev (localhost:3000)
bun run build # bunx --bun vite build → .output/
bun run compile # bun scripts/compile.ts → out/server-<target> (standalone CLI binary)
bun run cli <cmd> # bun src/bin.ts <cmd> — run a CLI subcommand in source (dev)
bun run typecheck # tsc --noEmit
bun run test # bun test — runs all *.test.ts files (colocated with source)
bun run fix # biome check --write (lint + format + organize imports)
bun run db:push # dev only — push schema to DB, no migration file
bun run db:generate # drizzle-kit generate && scripts/embed-migrations.ts (regenerates migrations.gen.ts)
bun run db:embed # scripts/embed-migrations.ts only — regenerate migrations.gen.ts from ./drizzle/
bun run db:migrate # apply migrations via drizzle-kit (local dev convenience; prod uses ./server migrate)
bun run db:studio # Drizzle Studio
bun run dev
bun run build
bun run compile
bun run seed
bun run typecheck
bun run test
bun run fix
```
Cross-compile targets live under `compile:{linux,darwin,windows}[:arch]`. `scripts/compile.ts` accepts `--target bun-<os>-<arch>`; default derives from host.
Before shipping: `bun run fix && bun run typecheck && bun run test && bun run build`.
Before committing: `bun run fix && bun run typecheck && bun run test`. No CI, no pre-commit hooks, no lint-staged — so these are on you.
## MySQL Source
## Drizzle (v0.x — critical)
Environment variable:
**Why it matters:** the project was on 1.0 beta and was rolled back. Online docs default to 1.0 beta APIs that do NOT exist here. If typecheck complains, you are probably importing a 1.0 beta API.
- Driver: `drizzle-orm/postgres-js`. Do NOT use `drizzle-orm/bun-sql`.
- `drizzle()` is called with `{ connection, schema }` where `schema = import * as schema from '@/server/db/schema'`. There is **no `relations.ts`** and **no `defineRelations`** in 0.x.
- Zod generators live in the separate `drizzle-zod` package (`^0.8.3`). Import from `drizzle-zod`, **not** `drizzle-orm/zod` (that subpath only exists in 1.0 beta).
- Relational queries use **RQB v1 callback syntax**:
```ts
db.query.todoTable.findMany({
orderBy: (t, { desc }) => desc(t.createdAt),
})
```
Do NOT use the v2 object form (`orderBy: { createdAt: 'desc' }`, `where: { id }`) — it won't type-check.
- To add relations later: declare per-table with `relations()` from `drizzle-orm` and export them from the same file as the table; they get picked up automatically because `index.ts` does `drizzle({ schema })` via `import *`.
- Every table must spread `...generatedFields` from `src/server/db/fields.ts` (`id uuid PRIMARY KEY DEFAULT uuidv7() NOT NULL` — **Postgres-side generation**, requires PG18+; `createdAt`, `updatedAt` with `$onUpdateFn`). The DB is the single source of UUIDv7 truth: monotonic per cluster, uses DB clock, no app-side round-trip. **Do not reintroduce `$defaultFn(() => Bun.randomUUIDv7())`** — the SQL default is what the migration emits and what `drizzle-zod` reads as "optional in insert schema". `generatedFieldKeys` is hand-written and uses `satisfies Record<keyof typeof generatedFields, true>` so any field-key drift fails typecheck; it feeds `createInsertSchema(...).omit(...)` / `createUpdateSchema(...).omit(...)`.
- `src/server/db/index.ts` exports a module-level `const db = drizzle(...)` — not a lazy singleton. On Bun this is a long-lived process, so top-level side effects are fine and requested. Don't reintroduce `getDB/closeDB` ceremony; the Nitro shutdown plugin calls `db.$client.end()` directly. (Cloudflare Workers would need per-request init — we don't support that deployment target.)
- `drizzle.config.ts` runs outside Vite — `@/*` path aliases do NOT resolve there. It currently does `import { env } from './src/env'` (relative). Preserve that.
- **Migrations are embedded in the binary, not read from disk.** `bun run db:generate` chains `drizzle-kit generate && bun scripts/embed-migrations.ts`, which regenerates `src/server/db/migrations.gen.ts` (committed, AUTO-GENERATED header) by `import sql_<idx> from '#drizzle/<tag>.sql' with { type: 'text' }`. `src/cli/migrate.ts` reads `embeddedMigrations`, **validates SHA-256 hash of every already-applied migration against the embedded SQL** (rejects schema drift if anyone edited an applied migration), then applies pending entries via `db.execute(sql\`...\`)` + `db.transaction(...)` against the `drizzle.__drizzle_migrations` book-keeping table — public APIs only, no `db.dialect`/`db.session` (those are `@internal`). Each migration is split on `--> statement-breakpoint`; empty fragments are trimmed and skipped. Dev helpers `db:push` / `drizzle-kit migrate` still read `./drizzle/`.
## CLI & single-binary deploy
`bun run compile` produces a single executable that dispatches subcommands via [citty](https://github.com/unjs/citty). Entry is `src/bin.ts`; subcommands live in `src/cli/`.
```
./server [serve] # default — start the HTTP server
./server migrate # apply embedded migrations
./server --help
```bash
DATABASE_URL=mysql://user:password@host:3306/database
```
**Nitro side-effect pitfall (important).** Under the `bun` preset, `.output/server/index.mjs` has a top-level `serve(...)` call — merely importing it starts the HTTP server. `src/bin.ts` therefore must not eager-import any subcommand module, and `src/cli/serve.ts` reaches `.output/server/index.mjs` through the `src/cli/_serve-nitro.mjs` bridge (with `_serve-nitro.d.mts` for types, since `.output/` doesn't exist at typecheck time). Citty's `subCommands: { x: () => import('...') }` lazy-loader is what keeps `--help` and `migrate` from booting the server.
Customer table: `ls_battery_info`.
**Citty eager-loads subcommand modules for `--help`** to read each subcommand's `meta`. So every `src/cli/*.ts` module body must be side-effect-free: do NOT static-import `@/env`, `@/server/db/*`, or anything that reads env at module-load time. Use `await import('@/env')` inside `run()`. Otherwise `./server --help` (or any subcommand's help) will fail with env validation errors before printing.
| Column | Type | Meaning |
| --- | --- | --- |
| `id` | `int(11)` auto increment | primary key |
| `user_id` | `int(11)` | user ID |
| `mac` | `varchar(50)` | device MAC |
| `dev_model` | `varchar(20)` | device model |
| `dev_name` | `varchar(50)` | device name |
| `is_low_power` | `varchar(10)` | `true` / `false` |
| `power_status` | `tinyint(4)` | `0` not charging, `1` charging, `2` full |
| `power` | `tinyint(4)` | current battery `0~100` |
| `create_time` | `datetime` | created time |
| `remark` | `varchar(500)` | nullable remark |
Add a subcommand: drop a file in `src/cli/` that default-exports `defineCommand({...})`, then register it in `src/bin.ts`'s `subCommands` with a `() => import(...)` thunk. Keep top-level imports limited to `citty` + Node built-ins; pull env / db / etc. via `await import(...)` inside `run()`.
Rules:
**Deploy flow is always migrate-then-serve.** Migrations are embedded in the binary (see "Drizzle" section), so the binary is the only artifact — no `./drizzle/` directory at runtime. Dockerfile copies just `./server`. `compose.yaml` models the pattern with a one-shot `migrate` service that `app` `depends_on: service_completed_successfully`. On k8s, run `./server migrate` as an initContainer or a Helm `pre-upgrade` Job; run `./server` (= `./server serve`) as the main container.
- Only run `SELECT` queries against this table. Do not insert, update, delete, migrate, or create tables.
- Do not add mock/fallback rows. If MySQL is unavailable, surface the error.
- `is_low_power` is stored as a string and normalized to boolean in `src/domain/battery.ts`.
- `power_status` is normalized to `0 | 1 | 2`.
- Without `mac`, battery list queries return the latest record per `mac`.
- With `mac`, battery list queries return history ordered by `create_time DESC, id DESC`, limited to 500 rows.
## Compile flags
`scripts/compile.ts` builds with `--minify --bytecode --sourcemap=inline`:
- **`bytecode`** — pre-compiles JS to bytecode and embeds it in the binary; ~2x startup on app-sized binaries (Bun docs benchmark). Requires `--compile`; top-level `await` must live inside `async` functions (it already does in this repo).
- **`minify`** — shrinks the binary and the bytecode it derives from.
- **`sourcemap: 'inline'`** — embeds the source map in the binary so error stack traces stay decodable. Bun also writes a residual `out/bin.js.map` next to the output; `scripts/compile.ts` removes it so the binary is the only artifact.
## ORPC
Contract → Router → Handler → Client, all type-safe from a single contract.
- `os` is built in `src/server/api/server.ts` via `implement(contract).$context<BaseContext>()`. **Always import `os` from `@/server/api/server`**, never from `@orpc/server` directly. `ORPCError`, `onError`, `ValidationError` come from `@orpc/server`.
- Contracts (`src/server/api/contracts/*.contract.ts`) generate Zod from Drizzle tables via `drizzle-zod`:
```ts
const insertSchema = createInsertSchema(todoTable).omit(generatedFieldKeys)
```
Barrel-aggregated in `contracts/index.ts` as `export const contract = { todo }`.
- Routers (`src/server/api/routers/*.router.ts`) import `db` directly from `@/server/db` in their handlers. There is **no `middlewares/` directory** by default — `db` doesn't need one (module-level const). When you actually need per-request context (auth, tenant, rate-limit), create `src/server/api/middlewares/<name>.middleware.ts` with `os.middleware(...)` and extend `BaseContext` in `context.ts`.
- **Interceptors are attached at the handler level, not in `server.ts` and not on `os`.** Both `src/routes/api/rpc.$.ts` (`RPCHandler`) and `src/routes/api/$.ts` (`OpenAPIHandler`) register `[onError(logError)]` (server) and `[onError(handleValidationError)]` (client). The validation interceptor rewrites `BAD_REQUEST + ValidationError` into `INPUT_VALIDATION_FAILED` (422) and output validation errors into `OUTPUT_VALIDATION_FAILED`. `logError` resolves a `getLogger(['api'])` LogTape category — never `console.*` directly. See "Logging" section.
- OpenAPI/Scalar: docs at `/api/docs`, spec at `/api/spec.json` (handler prefix `/api`, plugin paths `/docs` and `/spec.json`).
- **SSR isomorphism** (`src/client/orpc.ts`): `createIsomorphicFn().server(createRouterClient(...)).client(new RPCLink(...))`. Server branch reads `getRequestHeaders()` for context; client branch POSTs to `${origin}/api/rpc`.
- **Mutation invalidation is colocated at the call site** via `mutationOptions({ onSuccess })`, not in `src/client/orpc.ts`. `orpc` in `src/client/orpc.ts` is a plain `createTanstackQueryUtils(client)` — no `experimental_defaults`. Per-feature query helpers live in `src/client/queries/<feature>.ts` (e.g. `useInvalidateTodos`); routes/components compose those hooks rather than holding query keys inline. See `src/client/queries/todo.ts` + `src/routes/index.tsx` for the canonical shape.
- SSR prefetch in route loaders: `await context.queryClient.ensureQueryData(orpc.todo.list.queryOptions())`. Components use `useSuspenseQuery(orpc.feature.list.queryOptions())`.
## Code style (Biome)
- 2-space, LF, single quotes, **semicolons as-needed** (omitted unless required), 120-col, arrow parens always, `useArrowFunction: "error"` (covers function *expressions* only). Also `noReactPropAssignments: "error"`.
- Lint domains enabled (Biome 2.4): `types: "all"` (catches `noFloatingPromises`, `noMisusedPromises`, `useAwaitThenable`, `noUnnecessaryConditions` — TS-aware async/promise traps), `drizzle: "recommended"`, `react: "recommended"`. `noImportCycles` is on under `suspicious`.
- **Route components use `function Foo()` declarations**, placed below the `Route` config so the file reads top-down (route on top, component below). This is the official TanStack Router/Start pattern and relies on hoisting — `const Foo = () => {}` would TDZ-error when referenced from `createFileRoute({ component: Foo })` above it. Inline arrows are fine for trivial leaf components (e.g. plain redirect routes). Non-route components (UI primitives in `src/components/`) use `const Foo = () => {}`.
- Imports are auto-organized into two groups (external, then `@/*`), each alphabetical, with `import type` interleaved (NOT a separate group). `bun run fix` handles this; don't hand-sort.
- Files: utils `kebab-case.ts`, components `PascalCase.tsx`.
- `routeTree.gen.ts` is generated — ignored by Biome, never edit.
## Testing
`bun test` runs all `*.test.ts` files. Tests are colocated next to the source they exercise (e.g. `src/server/api/contracts/todo.contract.test.ts`). Use `import { describe, expect, test } from 'bun:test'`. The `@/*` alias resolves in tests via tsconfig paths. No Vitest, no Jest, no separate test config — keep it that way unless you need a browser/JSDOM environment.
## Endpoints
- `/` — Todos UI (file route).
- `/health` — bare `GET` returning `ok` (200, `text/plain`). Liveness only — no DB check, so it stays green even when Postgres is down. Add a separate `/ready` if you ever need readiness.
- `/api/rpc` — ORPC RPC handler (POST).
- `/api/*` — ORPC OpenAPI handler. Docs at `/api/docs`, spec at `/api/spec.json`.
## TypeScript
Strict mode, plus `noUncheckedIndexedAccess`, `verbatimModuleSyntax`, `erasableSyntaxOnly`, `noImplicitOverride`. No `as any` / `@ts-ignore` / `@ts-expect-error`.
Path alias: `@/* → src/*`. For files outside `src/` use `@/../<file>` (example in the codebase: `src/routes/api/$.ts` imports `name, version` from `@/../package.json`).
## Env
`src/env.ts` via `@t3-oss/env-core`. Server: `DATABASE_URL` (required, `z.url()`), `LOG_LEVEL` (`trace|debug|info|warning|error|fatal`, default `info`), `LOG_FORMAT` (`pretty|json`, default = TTY ? `pretty` : `json`), `LOG_DB` (`stringbool`, default `false` — flips on Drizzle SQL query logging). `client: {}` is empty by default — any client-side env must be `VITE_`-prefixed. Never commit `.env`.
## Logging
All server-side logging goes through `src/server/logger.ts`, a thin wrapper over [LogTape](https://logtape.org/). The module configures LogTape on import (via `configureSync`, no top-level await — works under `--bytecode`) and re-exports `getLogger`.
```ts
import { getLogger } from '@/server/logger'
const logger = getLogger(['feature', 'subsystem'])
logger.info('Created todo {id}', { id })
logger.error('DB write failed', { error })
```
- Categories are hierarchical arrays — they show up as dot-paths in JSON output (`"logger":"feature.subsystem"`) and let you filter by prefix when shipping logs.
- The `{name}` placeholders are for **primitive** values you want rendered inline (numbers, short strings, IDs). For objects, errors, and anything multi-field, omit the placeholder and just pass the value in properties — `logger.error('Auth failed', { error, userId })` keeps the message clean while properties stay structured. Never string-concatenate or template-literal — that defeats structured logging.
- Format is `pretty` (icons + ANSI) on TTY, `json` (one-line JSON) when piped — perfect for Loki/Datadog/CloudWatch ingestion. Override with `LOG_FORMAT`.
- Drizzle SQL queries are logged at `info` under category `['db']` when `LOG_DB=true`, via `@logtape/drizzle-orm`'s `DrizzleLogger` adapter (constructed in `src/server/db/index.ts`). The `info` level is intentional: flipping `LOG_DB=true` alone is enough — no need to also lower `LOG_LEVEL`.
- `src/server/api/interceptors.ts` calls `getLogger(['api']).error(...)` from `logError`. CLI subcommands lazy-import the logger inside `run()` — they are still required to be side-effect-free at module top (citty eager-loads for `--help`).
- Bun-specific: `process.env.NODE_ENV` is **inlined at build time** by `bun build --minify` — do NOT branch on it for logger config (use `process.stdout.isTTY` or `LOG_FORMAT` instead). pino is unusable here because its worker-thread transports crash inside the `/$bunfs/` virtual filesystem of compiled binaries; LogTape has zero workers and zero dynamic require, so it ships cleanly into the single binary.
## Docker / deploy
- Multi-stage: `oven/bun:1.3.13` builds and runs `bun scripts/compile.ts`, then `gcr.io/distroless/cc-debian13:nonroot` runs the single `./server` binary. The `cc` (glibc) distroless variant is required because Bun's compiled binary links glibc.
- `compose.yaml`: one-shot `migrate` service runs `./server migrate` with `restart: "no"`, then `app` starts (`depends_on: migrate: service_completed_successfully`). `DATABASE_URL=postgres://postgres:postgres@db:5432/postgres` for both.
- Distroless has no shell, so any init-then-serve pattern must use exec-form `command: [...]`, not `sh -c`.
## Layout (non-obvious parts only)
## Layout
```
src/
├── bin.ts # citty entry — keep imports minimal (see "CLI" section)
├── client/
│ ├── orpc.ts # isomorphic ORPC client + TanStack Query utils (no global invalidation defaults)
│ └── queries/ # per-feature query hooks: keys, options, `useInvalidate<Feature>` helpers
├── cli/ # CLI subcommands (loaded lazily by src/bin.ts via citty)
│ ├── serve.ts # `./server serve` — imports the Nitro bridge on demand
│ ├── migrate.ts # `./server migrate` — applies embedded migrations via public `db.execute(sql)` + `db.transaction()`
│ ├── _serve-nitro.mjs # bridge: `import('#server')` (subpath import → .output/server/index.mjs)
│ └── _serve-nitro.d.mts # types for the bridge (build output has no .d.ts)
├── routes/
│ ├── __root.tsx # root route + RootDocument shell
│ ├── index.tsx # Todos UI
── health.ts # GET /health → "ok" (no DB)
│ └── api/
│ ├── $.ts # OpenAPI + Scalar; interceptors registered here
│ └── rpc.$.ts # RPC; interceptors registered here
│ ├── index.tsx # SoH dashboard
│ ├── batteries.tsx # battery monitor page
── api/ # ORPC handlers
├── server/
│ ├── logger.ts # LogTape `configureSync` + `getLogger` re-export — the only log entrypoint
── api/
│ │ ├── server.ts # the ONLY place to build `os`
│ │ ├── context.ts # BaseContext (add per-request fields when you add middlewares)
│ │ ├── interceptors.ts # logError (→ logger), handleValidationError
│ │ ├── types.ts # Router{Client,Inputs,Outputs} derived from Contract
│ │ ├── contracts/ # Zod schemas from Drizzle tables (barrel: contract); colocated *.test.ts
│ │ └── routers/ # os.* handlers (barrel: router) — import db directly
│ ├── db/
│ │ ├── index.ts # module-level `export const db = drizzle({...})`
│ │ ├── fields.ts # generatedFields (id/createdAt/updatedAt) + generatedFieldKeys
│ │ ├── migrations.gen.ts # AUTO-GENERATED by `bun run db:embed`; embeds ./drizzle/*.sql via `with { type: 'text' }`
│ │ ├── sql.d.ts # ambient `declare module '*.sql'` — load-bearing for `with { type: 'text' }` imports in migrations.gen.ts
│ │ └── schema/ # pgTable definitions; also put `relations()` here when adding
│ └── plugins/
│ └── shutdown.ts # SIGINT/SIGTERM → db.$client.end() with 500ms delay (prod only)
├── components/ # non-route UI primitives (PascalCase, arrow const)
├── env.ts # t3-oss env validation
├── router.tsx # QueryClient + setupRouterSsrQueryIntegration
├── styles.css # Tailwind v4 entry
└── routeTree.gen.ts # auto-generated, do not edit
scripts/
├── compile.ts # `bun build --compile` driver; resolves --target; sets minify/bytecode/sourcemap
└── embed-migrations.ts # codegen: scans ./drizzle/meta/_journal.json → src/server/db/migrations.gen.ts
drizzle/ # SQL migrations (source of truth for `db:generate`; not shipped in binary)
│ ├── api/ # contracts / routers / interceptors
── battery/mysql.ts
├── domain/battery.ts
├── client/orpc.ts
└── styles.css
```
Nitro plugins are wired in `vite.config.ts` (`nitro({ plugins: [...] })`), not via a Nitro config file.
## ORPC
## Don'ts (specific, non-obvious)
- Contracts live in `src/server/api/contracts/`.
- Routers live in `src/server/api/routers/`.
- Use `os` from `@/server/api/server`.
- Current business API:
- `battery.dashboard`
- `battery.batteries`
- **Don't run `bun run db:generate` (or `drizzle-kit generate`) as an AI agent.** Migration generation is reserved for the human. Make schema changes in `src/server/db/schema/*` + `src/server/db/fields.ts`, push the code changes, and stop — the human will run `bun run db:generate` and commit the resulting `drizzle/*.sql` + `src/server/db/migrations.gen.ts` themselves. (`bun run db:embed` is also off-limits because it's the codegen tail of `db:generate`.)
- Don't edit `routeTree.gen.ts` or `src/server/db/migrations.gen.ts`.
- Don't eager-import anything from `.output/` in `src/bin.ts` or any module it statically imports — it starts the HTTP server as a side effect. Subcommands must be lazy via citty's `() => import(...)` thunks.
- Don't re-add an auto-migrate Nitro plugin. Migrations are an explicit deploy step via `./server migrate`.
- Don't reach into `db.dialect`/`db.session` from `migrate.ts` — they're `@internal`. The current implementation uses public `db.execute(sql)` + `db.transaction(...)` against the documented `drizzle.__drizzle_migrations` schema.
- Don't add `./drizzle/` back to the runtime image — migrations are embedded into the binary.
- Don't reintroduce `getDB/closeDB` or any "lazy DB init" pattern — that's a Cloudflare Workers shape; we deploy on Bun processes.
- Don't import `os` from `@orpc/server` in middleware/routers — always `@/server/api/server`.
- Don't import from `drizzle-orm/zod` (1.0 beta only). Use `drizzle-zod`.
- Don't use RQB v2 object syntax, `defineRelations`, or pass `relations` to `drizzle()`. All are 1.0 beta.
- Don't use `drizzle-orm/bun-sql`.
- Don't use `@/*` aliases in `drizzle.config.ts`.
- Don't commit `.env`.
## CLI And Deploy
## Room-to-grow rules (discipline for the first real feature)
- `src/bin.ts` must keep static imports minimal. Nitro's bun preset starts the server as a side effect when `.output/server/index.mjs` is imported.
- `serve` is lazy-loaded via citty.
- `bun run compile` produces `out/server-<target>`.
- Runtime artifact is a single binary plus `DATABASE_URL` configuration.
These keep the starter from setting bad precedents as it grows. Append, don't restructure.
## Code Style
1. Per-feature client query code — keys, options, `useInvalidate<Feature>` helpers — lives in `src/client/queries/<feature>.ts`. Routes/components compose these hooks; they don't hold query keys inline.
2. Mutation invalidation stays explicit at the mutation call site (`mutationOptions({ onSuccess })`) or in a feature query helper. Do not reintroduce global `experimental_defaults` or any implicit cache policy.
3. Client state defaults to route/component local state. Create a store (zustand or equivalent) only when state is shared across routes or needs persistence.
4. Middlewares (`src/server/api/middlewares/<name>.middleware.ts`) derive request-scoped context or gate access. They do NOT orchestrate business flow, hold side effects, or replace handlers/services.
5. Interceptors (`src/server/api/interceptors.ts`) do cross-cutting error logging, transport normalization, and validation rewrites. They do NOT read business data.
6. One file per Drizzle table. Relations live in the same file and are exported as `<entity>Relations`. No global `relations.ts`.
7. One router file per feature (`routers/<feature>.router.ts`). Only introduce `routers/<domain>/index.ts` when a domain grows past ~5 router files or needs shared domain helpers.
8. All server-side logging goes through `getLogger([...])` from `@/server/logger`. Use a hierarchical category (`['api']`, `['db']`, `['cli', 'migrate']`, etc.) — these become dot-paths in JSON output and let you filter by prefix. Use the `{name}` placeholder + properties form, not string interpolation. `console.*` is forbidden in business code.
9. CLI subcommand modules keep top-level imports to `citty` + Node built-ins. Env, db, and server code are `await import(...)`-ed inside `run()` (see `src/bin.ts` comment for why).
10. Every new business feature ships with at least one `bun test` covering a contract schema, a pure helper, or a router behavior.
- 2-space indentation, LF, single quotes, semicolons as-needed, 120-column line width.
- Route components use `function Foo()` declarations below route config.
- No `console.*` in business code; use `getLogger([...])` from `@/server/logger` if logging is needed.
- No `as any`, `@ts-ignore`, or `@ts-expect-error`.
- Do not edit `src/routeTree.gen.ts` manually.
+80 -84
View File
@@ -1,112 +1,108 @@
# fullstack-starter
# battery-soh
一个**单二进制**的全栈应用 starter——`bun run compile` 出来的 `./server` 文件就是你要部署的全部产物,自带 HTTP 服务、SSR、API、嵌入式 SQL 迁移,运行时不依赖 Node、不依赖源码、不依赖外部 migration 目录
一个基于 **Bun + TanStack Start + ORPC** 的电池健康展示系统。应用会被打包成单个二进制文件,前端页面、SSR 服务和 ORPC API 一起发布;业务数据只读接入甲方现有 MySQL 表 `ls_battery_info`,本项目不写入、不迁移、不修改甲方数据库
技术栈:Bun · TanStack Start (React 19 SSR) · ORPC(契约优先 API)· Drizzle ORM · PostgreSQL 18+ · Tailwind v4 · Biome。
## 数据源
## 为什么用这个
甲方提供的只读表结构:
- **部署最简**:发布只拷一个二进制文件。先 `./server migrate``./server`,完事。
- **契约优先**:在 `*.contract.ts` 用 Zod 定义一次,前端、后端、OpenAPI 文档自动同步。
- **类型严格**TypeScript strict,杜绝 `any` / `@ts-ignore` / `as any` 等类型逃逸。
- **开箱可跑**:路径别名、文件路由、ORPC 接线、Tailwind、热重载、错误页全部预接好。
| 字段名 | 数据类型 | 说明 |
| --- | --- | --- |
| `id` | `int(11)` 自增 | 主键 ID |
| `user_id` | `int(11)` | 用户 ID |
| `mac` | `varchar(50)` | 设备 MAC |
| `dev_model` | `varchar(20)` | 设备型号 |
| `dev_name` | `varchar(50)` | 设备名称 |
| `is_low_power` | `varchar(10)` | 是否低电量:`true` / `false` |
| `power_status` | `tinyint(4)` | `0` 未充电,`1` 正在充电,`2` 充电完成 |
| `power` | `tinyint(4)` | 当前电量 `0~100` |
| `create_time` | `datetime` | 创建时间 |
| `remark` | `varchar(500)` | 备注,可空 |
环境变量:
```bash
DATABASE_URL=mysql://user:password@host:3306/database
```
## 快速开始
> **需要 PostgreSQL 18+**——schema 用 PG 原生的 `uuidv7()` 生成主键(`compose.yaml` 已锁 `postgres:18-alpine`)。要兼容更老的 PG,把 `src/server/db/fields.ts` 里的 `default(sql\`uuidv7()\`)` 换成 `$defaultFn(() => Bun.randomUUIDv7())`,再跑 `bun run db:generate`。
```bash
cp .env.example .env # 把里面的 DATABASE_URL 改成你的 Postgres
cp .env.example .env
bun install
bun run db:push # 开发期:把 schema 直接同步到 DB(不写 migration 文件)
bun run dev # http://localhost:3000
bun run dev
```
打开浏览器
- `http://localhost:3000/` — Todo 示例页
- `http://localhost:3000/api/docs` — Scalar 渲染的 API 文档
## 目录结构(你需要关心的部分)
```
src/
├── routes/ # 文件路由:页面 + API 端点
├── server/
│ ├── api/
│ │ ├── contracts/ # Zod 契约(client / server 共享)
│ │ └── routers/ # 业务实现
│ └── db/ # Drizzle schema + 嵌入式 migrations
├── client/ # 前端 hooks、ORPC 客户端
└── components/ # UI 组件
```
## 加一个功能(以 `post` 为例)
每一步都很短,按顺序填即可:
1. **建表**`src/server/db/schema/post.ts` 定义 `postTable`,记得展开 `...generatedFields`(自动注入 `id` / `createdAt` / `updatedAt`)。
2. **导出表**:在 `src/server/db/schema/index.ts``export * from './post'`
3. **写契约**`src/server/api/contracts/post.contract.ts``drizzle-zod` 从表派生 Zod schema。
4. **挂契约**:在 `src/server/api/contracts/index.ts``post` 加进 `contract` 对象。
5. **写实现**`src/server/api/routers/post.router.ts` 实现 `os.post.*.handler(...)`
6. **挂路由**:在 `src/server/api/routers/index.ts``post` 加进 `router` 对象。
7. **写前端 hook**`src/client/queries/post.ts` 导出 `useInvalidatePosts` 等失效辅助。
8. **写页面**`src/routes/<page>.tsx``useSuspenseQuery` 读、`mutate` 写;mutation 的 `onSuccess` 调用第 7 步的 helper。
9. **生成 migration**`bun run db:generate` 把 SQL 写到 `./drizzle/` 并嵌入二进制。
完工。`bun run dev` 已自动热重载。
## 部署
**永远先 migrate 再 serve**。Migration 已嵌入二进制;部署只发一个 `./server` 文件。
```bash
./server migrate # 应用嵌入式 migration(用 $DATABASE_URL
./server # 启动 HTTP 服务(默认子命令)
./server --help # 列出所有子命令
```
仓库自带 `compose.yaml`(一次性 `migrate` 服务先跑完,再启动 `app`):
如果甲方暂时没有提供数据库连接,可以用 Docker Compose 启动本地 MySQL 并填充示例数据
```bash
docker compose up --build
```
Kubernetes 上:把 `./server migrate` 放进 initContainer 或 Helm `pre-upgrade` Job,主容器跑 `./server`
Compose 会启动三个服务:
## 脚本一览
- `db`:本地 MySQL 8.4
- `seed`:执行 `bun run seed`,用 Drizzle MySQL schema + `drizzle-seed` 重置本地 `ls_battery_info` 并写入示例数据
- `app`:使用同一个 `DATABASE_URL` 启动单二进制应用
也可以手动 seed 本地库:
```bash
DATABASE_URL=mysql://battery:battery@localhost:3306/battery_soh bun run seed
```
`seed` 是本地开发/验收脚本,会建表并重置示例数据;应用运行时仍然只执行 `SELECT`,不会写入数据库。
打开浏览器:
- `http://localhost:3000/`SoH 预测与风险洞察看板
- `http://localhost:3000/batteries`:设备电池实时状态
- `http://localhost:3000/api/docs`Scalar 渲染的 ORPC OpenAPI 文档
## 架构
```
src/
├── routes/ # TanStack Start 文件路由:页面 + API 端点
├── server/
│ ├── api/ # ORPC contract / router
│ └── battery/mysql.ts # 甲方 MySQL 只读查询
├── domain/battery.ts # 电池领域类型、归一化、展示聚合
├── client/orpc.ts # isomorphic ORPC client
└── styles.css # Tailwind v4 entry
```
接口保持模板里的 ORPC 模式:
- `battery.dashboard`:读取每个 `mac` 的最新记录并生成看板聚合数据
- `battery.batteries`:无 `mac` 时返回每台设备最新记录;带 `mac` 时返回该设备历史记录,按 `create_time desc` 限制 500 条
所有业务查询都是 `SELECT`,没有 mutation,也没有 mock/fallback 数据。
## 部署
```bash
bun run build
bun run compile
./out/server-<target>
```
Docker 镜像会在构建阶段产出单个 `./server` 二进制,运行阶段只需要配置 `DATABASE_URL`
## 脚本
| 命令 | 作用 |
| --- | --- |
| `bun run dev` | Vite 开发服务器(默认端口 3000 |
| `bun run build` | 构建到 `.output/``bun run compile` 会用到) |
| `bun run dev` | Vite 开发服务器 |
| `bun run build` | 构建到 `.output/` |
| `bun run compile` | 生成单二进制 `out/server-<target>` |
| `bun run seed` | 为本地 MySQL 创建甲方表并填充示例数据 |
| `bun run typecheck` | TypeScript 类型检查 |
| `bun run test` | 运行所有 `*.test.ts` |
| `bun run fix` | Biome 格式化 + lint + 整理 imports |
| `bun run db:push` | 开发期:直接同步 schema 到 DB(不写 migration 文件) |
| `bun run db:generate` | 写 SQL migration 到 `./drizzle/` 并嵌入二进制 |
| `bun run db:embed` | 仅重生 `migrations.gen.ts`(手改了 `./drizzle/*.sql` 后用) |
| `bun run db:migrate` | 通过 drizzle-kit 在本地应用 migration(开发便利) |
| `bun run db:studio` | Drizzle Studio(可视化 DB |
跨平台编译:`bun run compile:{linux,darwin,windows}[:arch]`
## 端点
| 路径 | 用途 |
| --- | --- |
| `/` | Todo 示例 UI |
| `/health` | 存活探针(不查 DB,纯文本 `ok` |
| `/api/rpc` | ORPC RPC 端点(client 直连) |
| `/api/docs` | Scalar 渲染的 API 文档 |
| `/api/spec.json` | OpenAPI spec |
## 提交前
## 验证
```bash
bun run fix && bun run typecheck && bun run test
bun run fix && bun run typecheck && bun run test && bun run build
```
没有 CI、没有 pre-commit hook——上面三条由你自觉跑。