合并 master 到 Pingora 网关分支
保留 Pingora 网关发布与巡检能力 合入外部生成 worker 与 controller 运维链路 对齐 SpacetimeDB 2.5.0 依赖锁定 更新项目共享记忆与生产运维文档
This commit is contained in:
@@ -1,229 +1,151 @@
|
||||
---
|
||||
name: spacetimedb-cli
|
||||
description: SpacetimeDB CLI reference for initializing projects, building modules, publishing databases, querying data, and managing servers
|
||||
triggers:
|
||||
- spacetime init
|
||||
- spacetime build
|
||||
- spacetime publish
|
||||
- spacetime dev
|
||||
- spacetime sql
|
||||
- spacetime call
|
||||
- spacetime logs
|
||||
- spacetime server
|
||||
- spacetime login
|
||||
- spacetime generate
|
||||
- how do I use the CLI
|
||||
- CLI command
|
||||
description: SpacetimeDB 2.5 CLI reference for Genarrative. Use for spacetime build, publish, generate, call, sql, logs, server management, local dev, explicit server targeting, version checks, and remote runtime verification.
|
||||
---
|
||||
|
||||
# SpacetimeDB CLI
|
||||
|
||||
Use this skill when the user needs help with the `spacetime` CLI tool - initializing projects, building modules, publishing databases, querying data, managing servers, or troubleshooting CLI issues.
|
||||
Use this skill when working with the `spacetime` CLI in Genarrative. Prefer repository scripts when they exist, and keep every operation pinned to an explicit target server or local process.
|
||||
|
||||
## Quick Reference
|
||||
## Genarrative Rules
|
||||
|
||||
### Project Initialization & Development
|
||||
- Do not rely on the default SpacetimeDB cloud target. Pass `--server` or `--server-url` explicitly in scripts, docs, smoke tests, and manual troubleshooting.
|
||||
- Do not introduce `maincloud` / `MAINCLOUD` commands, env vars, or docs. Treat old references as historical residue.
|
||||
- Do not use `spacetime --root-dir` in manual commands or docs. Use project scripts, `--data-dir`, explicit `--server`, or the configured running service.
|
||||
- For repository version upgrades, update `server-rs/Cargo.toml` exact pins, regenerate bindings, and verify the actual CLI/runtime version. Do not treat a local CLI reinstall as a repo upgrade.
|
||||
- For host upgrades, verify the running service binary, not just shell PATH: `systemctl show ... MainPID` -> `/proc/$pid/exe --version` -> `/v1/ping`.
|
||||
|
||||
## Core Commands
|
||||
|
||||
```bash
|
||||
# Initialize new project
|
||||
spacetime init my-project --lang rust|csharp|typescript|cpp
|
||||
spacetime init my-project --template <template-id>
|
||||
|
||||
# Build module
|
||||
spacetime build # release build
|
||||
spacetime build --debug # faster iteration, slower runtime
|
||||
spacetime build
|
||||
spacetime build --debug
|
||||
|
||||
# Dev mode (auto-rebuild, auto-publish, generates bindings)
|
||||
spacetime dev
|
||||
spacetime dev --client-lang typescript --module-bindings-path ./client/src/module_bindings
|
||||
# Publish to an explicit server
|
||||
spacetime publish my-database --server http://127.0.0.1:3101 --yes=migrate,break-clients
|
||||
|
||||
# Generate client bindings
|
||||
# Destructive publish only when explicitly intended
|
||||
spacetime publish my-database --server http://127.0.0.1:3101 --delete-data=always --yes=delete-data,migrate
|
||||
|
||||
# Delete data only for breaking schema conflicts
|
||||
spacetime publish my-database --server http://127.0.0.1:3101 --delete-data=on-conflict --yes=migrate
|
||||
|
||||
# Generate bindings
|
||||
spacetime generate --lang typescript|csharp|rust|unrealcpp --out-dir ./bindings --module-path ./server
|
||||
```
|
||||
|
||||
### Publishing & Deployment
|
||||
## Genarrative Local Workflow
|
||||
|
||||
```bash
|
||||
# Publish to an explicit server
|
||||
spacetime publish my-database --server http://127.0.0.1:3101 --yes
|
||||
# Prefer project wrappers
|
||||
npm run dev:spacetime
|
||||
npm run dev:api-server
|
||||
npm run spacetime:generate
|
||||
|
||||
# Publish to local server
|
||||
spacetime publish my-database --server local --yes
|
||||
# Query local database
|
||||
spacetime sql my-db --server http://127.0.0.1:3101 "SELECT * FROM players"
|
||||
|
||||
# Clear database and republish
|
||||
spacetime publish my-database --clear-database --yes
|
||||
# Logs
|
||||
spacetime logs my-db --server http://127.0.0.1:3101 -f
|
||||
```
|
||||
|
||||
### Database Interaction
|
||||
## Database Interaction
|
||||
|
||||
```bash
|
||||
# SQL queries
|
||||
spacetime sql my-database "SELECT * FROM users"
|
||||
spacetime sql my-database --interactive # REPL mode
|
||||
# SQL / describe
|
||||
spacetime sql my-db --server http://127.0.0.1:3101 "SELECT * FROM users"
|
||||
spacetime describe my-db --server http://127.0.0.1:3101 --json
|
||||
spacetime describe my-db table users --server http://127.0.0.1:3101 --json
|
||||
|
||||
# Call reducers
|
||||
spacetime call my-database my_reducer '{"arg1": "value", "arg2": 123}'
|
||||
# Reducer/procedure calls. Arguments are positional JSON values.
|
||||
spacetime call --server http://127.0.0.1:3101 my-db my_reducer '"value"' '123'
|
||||
|
||||
# Subscribe to changes
|
||||
spacetime subscribe my-database "SELECT * FROM users" --num-updates 10
|
||||
# 2.5 accepts hex strings for Identity arguments without full JSON tuple syntax.
|
||||
spacetime call --server http://127.0.0.1:3101 my-db reducer_needing_identity 0xabc123...
|
||||
|
||||
# View logs
|
||||
spacetime logs my-database -f # follow logs
|
||||
spacetime logs my-database -n 100 # up to 100 log lines
|
||||
|
||||
# Describe schema
|
||||
spacetime describe my-database --json
|
||||
spacetime describe my-database table users --json
|
||||
spacetime describe my-database reducer my_reducer --json
|
||||
# Subscribe from CLI
|
||||
spacetime subscribe my-db "SELECT * FROM users" --num-updates 10 --server http://127.0.0.1:3101
|
||||
```
|
||||
|
||||
### Database Management
|
||||
## Server & Auth
|
||||
|
||||
```bash
|
||||
# List databases
|
||||
spacetime list
|
||||
|
||||
# Delete database
|
||||
spacetime delete my-database
|
||||
|
||||
# Rename database
|
||||
spacetime rename <database-identity> --to new-name
|
||||
```
|
||||
|
||||
### Server Management
|
||||
|
||||
```bash
|
||||
# List configured servers
|
||||
spacetime server list
|
||||
|
||||
# Add server
|
||||
spacetime server add local --url http://localhost:3000 --default
|
||||
spacetime server add myserver --url https://my-spacetime.example.com
|
||||
spacetime server add genarrative-dev --url http://127.0.0.1:3101
|
||||
spacetime server ping genarrative-dev
|
||||
|
||||
# Set default server
|
||||
spacetime server set-default local
|
||||
|
||||
# Test connectivity
|
||||
spacetime server ping local
|
||||
|
||||
# Start local instance
|
||||
spacetime start
|
||||
|
||||
# Clear local data
|
||||
spacetime server clear
|
||||
```
|
||||
|
||||
### Authentication
|
||||
|
||||
```bash
|
||||
# Login (opens browser)
|
||||
spacetime login
|
||||
|
||||
# Login with token
|
||||
spacetime login --token <token>
|
||||
|
||||
# Show login status
|
||||
spacetime login show
|
||||
|
||||
# Logout
|
||||
spacetime logout
|
||||
```
|
||||
|
||||
## Default Servers
|
||||
|
||||
| Name | URL | Description |
|
||||
|------|-----|-------------|
|
||||
| `local` | `http://127.0.0.1:3000` | Local development server |
|
||||
| `dev` | `http://127.0.0.1:3101` | Genarrative local development server |
|
||||
|
||||
## Common Workflows
|
||||
|
||||
### New Project Setup
|
||||
## Version & Runtime Verification
|
||||
|
||||
```bash
|
||||
# 1. Login
|
||||
spacetime login
|
||||
# CLI resolution can be misleading; compare all candidates when diagnosing.
|
||||
type -a spacetime
|
||||
spacetime --version
|
||||
spacetime version list
|
||||
|
||||
# 2. Create project
|
||||
spacetime init my-game --lang rust
|
||||
cd my-game
|
||||
|
||||
# 3. Start dev mode (auto-rebuilds and publishes)
|
||||
spacetime dev
|
||||
# Verify a systemd service binary actually changed.
|
||||
pid="$(systemctl show spacetimedb.service -p MainPID --value)"
|
||||
readlink -f "/proc/${pid}/exe"
|
||||
"/proc/${pid}/exe" --version
|
||||
curl -fsS http://127.0.0.1:3101/v1/ping
|
||||
```
|
||||
|
||||
### Local Development
|
||||
## Flags
|
||||
|
||||
```bash
|
||||
# Start local server (in separate terminal)
|
||||
spacetime start
|
||||
|
||||
# Publish to local
|
||||
spacetime publish my-db --server local --clear-database --yes
|
||||
|
||||
# Query local database
|
||||
spacetime sql my-db --server local "SELECT * FROM players"
|
||||
```
|
||||
|
||||
### Generate Client Bindings
|
||||
|
||||
```bash
|
||||
# After building module
|
||||
spacetime build
|
||||
spacetime generate --lang typescript --out-dir ./client/src/bindings --module-path .
|
||||
|
||||
# Or use dev mode which auto-generates
|
||||
spacetime dev --client-lang typescript --module-bindings-path ./client/src/bindings
|
||||
```
|
||||
|
||||
## Common Flags
|
||||
|
||||
| Flag | Short | Description |
|
||||
|------|-------|-------------|
|
||||
| `--server` | `-s` | Target server (nickname, hostname, or URL) |
|
||||
| `--yes` | `-y` | Non-interactive mode (skip confirmations) |
|
||||
| `--anonymous` | | Use anonymous identity |
|
||||
| `--module-path` | `-p` | Path to module project |
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--server`, `-s` | Target server nickname, host, or URL |
|
||||
| `--yes`, `-y` | Non-interactive prompt skipping; in 2.5 prefer scoped values |
|
||||
| `--delete-data`, `-c` | Publish data policy: `always`, `on-conflict`, or `never` |
|
||||
| `--module-path`, `-p` | Module project path |
|
||||
| `--bin-path`, `-b` | Publish/generate from compiled wasm |
|
||||
| `--no-config` | Ignore `spacetime.json` |
|
||||
| `--env` | Select config file layering environment |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Not logged in"
|
||||
### Not Logged In
|
||||
|
||||
```bash
|
||||
spacetime login
|
||||
# Or use --anonymous for public operations
|
||||
```
|
||||
|
||||
### "Server not responding"
|
||||
### Server Not Responding
|
||||
|
||||
```bash
|
||||
spacetime server ping <server>
|
||||
# For local: ensure spacetime start is running
|
||||
curl -fsS http://127.0.0.1:3101/v1/ping
|
||||
```
|
||||
|
||||
### "Schema conflict"
|
||||
For local Genarrative work, start SpacetimeDB first with `npm run dev:spacetime`, then start `npm run dev:api-server`.
|
||||
|
||||
### Schema Conflict
|
||||
|
||||
```bash
|
||||
# Clear data and republish
|
||||
spacetime publish my-db --clear-database --yes
|
||||
# Clear data and republish only when conflict
|
||||
spacetime publish my-db --clear-database=on-conflict --yes
|
||||
spacetime publish my-db --server http://127.0.0.1:3101 --delete-data=on-conflict --yes=migrate
|
||||
```
|
||||
|
||||
### "Build failed"
|
||||
Use `--delete-data=always` only with explicit approval.
|
||||
|
||||
### Version Mismatch
|
||||
|
||||
```bash
|
||||
# Check Rust/C# toolchain
|
||||
rustup show
|
||||
# For Rust modules, ensure wasm32-unknown-unknown target
|
||||
rustup target add wasm32-unknown-unknown
|
||||
rg -n 'spacetimedb' server-rs/Cargo.toml
|
||||
spacetime --version
|
||||
spacetime version list
|
||||
pid="$(systemctl show spacetimedb.service -p MainPID --value)"
|
||||
"/proc/${pid}/exe" --version
|
||||
```
|
||||
|
||||
## Module Languages
|
||||
|
||||
**Server-side (modules):** Rust, C#, TypeScript, C++
|
||||
**Client SDKs:** TypeScript, C#, Rust, Python, Unreal Engine
|
||||
**CLI `generate` targets:** TypeScript, C#, Rust, Unreal C++
|
||||
|
||||
## Notes
|
||||
|
||||
- Many commands are marked UNSTABLE and may change
|
||||
- Genarrative scripts should pass `--server` or `--server-url` explicitly instead of relying on the CLI default
|
||||
- Use `--yes` flag in scripts to avoid interactive prompts
|
||||
- Dev mode watches files and auto-rebuilds on changes
|
||||
- Procedure calls are stable in 2.5; module HTTP handlers/webhooks, unstable view features, and RLS remain behind unstable gates per release notes.
|
||||
- 2.5 fixes `publish --delete-data` config fallback so `spacetime.json` can provide the database name.
|
||||
- Genarrative scripts should pass `--server` or `--server-url` explicitly instead of relying on CLI defaults.
|
||||
|
||||
@@ -1,345 +1,105 @@
|
||||
---
|
||||
name: spacetimedb-concepts
|
||||
description: Understand SpacetimeDB architecture and core concepts. Use when learning SpacetimeDB or making architectural decisions.
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: clockworklabs
|
||||
version: "2.0"
|
||||
description: Understand SpacetimeDB 2.5 architecture, reducer/procedure/table/view semantics, schema evolution, subscriptions, identity, and Genarrative-specific backend boundaries. Use when designing or reviewing SpacetimeDB-backed features.
|
||||
---
|
||||
|
||||
# SpacetimeDB Core Concepts
|
||||
|
||||
SpacetimeDB is a relational database that is also a server. It lets you upload application logic directly into the database via WebAssembly modules, eliminating the traditional web/game server layer entirely.
|
||||
SpacetimeDB is a relational database that also executes application logic in uploaded modules. In Genarrative, it is the data and transaction layer behind `server-rs + Axum + SpacetimeDB`, not a replacement for the `api-server` BFF or external platform adapters.
|
||||
|
||||
---
|
||||
## Genarrative Boundaries
|
||||
|
||||
## Critical Rules (Read First)
|
||||
- Domain rules live in `module-*`.
|
||||
- SpacetimeDB tables, reducers, procedures, migrations, row mappers, and read models live in `spacetime-module`.
|
||||
- Backend access goes through `spacetime-client` facades.
|
||||
- HTTP/SSE/BFF and external orchestration stay in `api-server`.
|
||||
- External side effects stay in `platform-*`.
|
||||
- Frontend renders backend truth and must not bypass BFF/projections to invent formal business state.
|
||||
|
||||
These five rules prevent the most common SpacetimeDB mistakes:
|
||||
## Critical Rules
|
||||
|
||||
1. **Reducers are transactional** — they do not return data to callers. Use subscriptions to read data.
|
||||
2. **Reducers must be deterministic** — no filesystem, network, timers, or random. All state must come from tables.
|
||||
3. **Read data via tables/subscriptions** — not reducer return values. Clients get data through subscribed queries.
|
||||
4. **Auto-increment IDs are not sequential** — gaps are normal, do not use for ordering. Use timestamps or explicit sequence columns.
|
||||
5. **`ctx.sender()` is the authenticated principal** — never trust identity passed as arguments. Always use `ctx.sender()` for authorization.
|
||||
|
||||
---
|
||||
|
||||
## Feature Implementation Checklist
|
||||
|
||||
When implementing a feature that spans backend and client:
|
||||
|
||||
1. **Backend:** Define table(s) to store the data
|
||||
2. **Backend:** Define reducer(s) to mutate the data
|
||||
3. **Client:** Subscribe to the table(s)
|
||||
4. **Client:** Call the reducer(s) from UI — **do not skip this step**
|
||||
5. **Client:** Render the data from the table(s)
|
||||
|
||||
**Common mistake:** Building backend tables/reducers but forgetting to wire up the client to call them.
|
||||
|
||||
---
|
||||
|
||||
## Debugging Checklist
|
||||
|
||||
When things are not working:
|
||||
|
||||
1. Is SpacetimeDB server running? (`spacetime start`)
|
||||
2. Is the module published? (`spacetime publish`)
|
||||
3. Are client bindings generated? (`spacetime generate`)
|
||||
4. Check server logs for errors (`spacetime logs <db-name>`)
|
||||
5. **Is the reducer actually being called from the client?**
|
||||
|
||||
---
|
||||
|
||||
## CLI Commands
|
||||
|
||||
```bash
|
||||
spacetime start
|
||||
spacetime publish <db-name> --module-path <module-path>
|
||||
spacetime publish <db-name> --clear-database -y --module-path <module-path>
|
||||
spacetime generate --lang <lang> --out-dir <out> --module-path <module-path>
|
||||
spacetime logs <db-name>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## What SpacetimeDB Is
|
||||
|
||||
SpacetimeDB combines a database and application server into a single deployable unit. Clients connect directly to the database and execute application logic inside it. The system is optimized for real-time applications requiring maximum speed and minimum latency.
|
||||
|
||||
Key characteristics:
|
||||
|
||||
- **In-memory execution**: Application state is served from memory for very low-latency access
|
||||
- **Persistent storage**: Data is automatically persisted to a write-ahead log (WAL) for durability
|
||||
- **Real-time synchronization**: Changes are automatically pushed to subscribed clients
|
||||
- **Single deployment**: No separate servers, containers, or infrastructure to manage
|
||||
|
||||
## The Five Zen Principles
|
||||
|
||||
1. **Everything is a Table**: Your entire application state lives in tables. No separate cache layer, no Redis, no in-memory state to synchronize.
|
||||
2. **Everything is Persistent**: SpacetimeDB persists state by default (for example via WAL-backed durability).
|
||||
3. **Everything is Real-Time**: Clients are replicas of server state. Subscribe to data and it flows automatically.
|
||||
4. **Everything is Transactional**: Every reducer runs atomically. Either all changes succeed or all roll back.
|
||||
5. **Everything is Programmable**: Modules are real code (Rust, C#, TypeScript) running inside the database.
|
||||
1. **Reducers are transactional**: they do not return data to callers. Read through subscriptions, read models, views, or BFF endpoints.
|
||||
2. **Reducers are deterministic**: no filesystem, network, wall-clock, or external RNG. Use `ctx.timestamp`, `ctx.rng()` / `ctx.random()`, and tables.
|
||||
3. **Procedures are stable in 2.5**: they can use explicit transactions and outgoing HTTP via `ctx.http`.
|
||||
4. **Identity comes from context**: use `ctx.sender()` or language equivalent for authorization. Never trust identity passed as an argument.
|
||||
5. **Auto-increment IDs are not ordering guarantees**: gaps are normal. Use timestamps or explicit sequence columns for ordering.
|
||||
6. **Schema changes need migration discipline**: existing Genarrative table fields must be appended with defaults; update migration code, table catalog, generated bindings, and run `npm run check:spacetime-schema`.
|
||||
|
||||
## Tables
|
||||
|
||||
Tables store all data in SpacetimeDB. They use the relational model and support SQL queries for subscriptions.
|
||||
|
||||
### Defining Tables
|
||||
|
||||
Tables are defined using language-specific attributes. In 2.0, use `accessor` (not `name`) for the API name:
|
||||
|
||||
**Rust:**
|
||||
```rust
|
||||
#[spacetimedb::table(accessor = player, public)]
|
||||
pub struct Player {
|
||||
#[primary_key]
|
||||
#[auto_inc]
|
||||
id: u32,
|
||||
#[index(btree)]
|
||||
name: String,
|
||||
#[unique]
|
||||
email: String,
|
||||
}
|
||||
```
|
||||
|
||||
**C#:**
|
||||
```csharp
|
||||
[SpacetimeDB.Table(Accessor = "Player", Public = true)]
|
||||
public partial struct Player
|
||||
{
|
||||
[SpacetimeDB.PrimaryKey]
|
||||
[SpacetimeDB.AutoInc]
|
||||
public uint Id;
|
||||
[SpacetimeDB.Index.BTree]
|
||||
public string Name;
|
||||
[SpacetimeDB.Unique]
|
||||
public string Email;
|
||||
}
|
||||
```
|
||||
|
||||
**TypeScript:**
|
||||
```typescript
|
||||
const players = table(
|
||||
{ name: 'players', public: true },
|
||||
{
|
||||
id: t.u32().primaryKey().autoInc(),
|
||||
name: t.string().index('btree'),
|
||||
email: t.string().unique(),
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### Table Visibility
|
||||
|
||||
- **Private tables** (default): Only accessible by reducers and the database owner
|
||||
- **Public tables**: Exposed for client read access through subscriptions. Writes still require reducers.
|
||||
|
||||
### Table Design Principles
|
||||
|
||||
Organize data by access pattern, not by entity:
|
||||
|
||||
**Decomposed approach (recommended):**
|
||||
```
|
||||
Player PlayerState PlayerStats
|
||||
id <-- player_id player_id
|
||||
name position_x total_kills
|
||||
position_y total_deaths
|
||||
velocity_x play_time
|
||||
```
|
||||
|
||||
Benefits: reduced bandwidth, cache efficiency, schema evolution, semantic clarity.
|
||||
- Private tables are the default; only reducers/procedures and database owners can access them.
|
||||
- Public tables are exposed to clients through subscriptions. Writes still go through reducers/procedures.
|
||||
- Organize data by access pattern when bandwidth or update frequency differs.
|
||||
- Existing persistent tables in Genarrative are conservative: no rename, delete, reorder, or type changes without a user-approved migration plan.
|
||||
|
||||
## Reducers
|
||||
|
||||
Reducers are transactional functions that modify database state. They are the primary client-invoked mutation path; procedures can also mutate tables by running explicit transactions.
|
||||
Reducers are deterministic transactional functions. They are the primary client-invoked mutation path.
|
||||
|
||||
### Key Properties
|
||||
- No global mutable state.
|
||||
- No filesystem, network, timers, or non-deterministic RNG.
|
||||
- Return `Result<(), String>` for expected sender-visible errors.
|
||||
- Use `ctx.sender()` for authorization.
|
||||
- Store persistent state in tables.
|
||||
|
||||
- **Transactional**: Run in isolated database transactions
|
||||
- **Atomic**: Either all changes succeed or all roll back
|
||||
- **Isolated**: Cannot interact with the outside world (no network, no filesystem)
|
||||
- **Callable**: Clients invoke reducers as remote procedure calls
|
||||
## Procedures
|
||||
|
||||
### Critical Reducer Rules
|
||||
Procedures are stable in 2.5. They can be scheduled, can open explicit transactions with `with_tx` / `try_with_tx`, and can use outgoing HTTP (`ctx.http`).
|
||||
|
||||
1. **No global state**: Relying on static variables is undefined behavior
|
||||
2. **No side effects**: Reducers cannot make network requests or access files
|
||||
3. **Store state in tables**: All persistent state must be in tables
|
||||
4. **No return data**: Reducers do not return data to callers — use subscriptions
|
||||
5. **Must be deterministic**: No random, no timers, no external I/O
|
||||
Genarrative default: keep external provider protocols in `platform-*` and orchestration in `api-server` unless a task explicitly moves a workflow into a module procedure.
|
||||
|
||||
### Defining Reducers
|
||||
Module HTTP handlers/webhooks, unstable view features, and RLS `client_visibility_filter` remain gated behind unstable according to the 2.5 release notes.
|
||||
|
||||
**Rust:**
|
||||
```rust
|
||||
#[spacetimedb::reducer]
|
||||
pub fn create_user(ctx: &ReducerContext, name: String, email: String) -> Result<(), String> {
|
||||
if name.is_empty() {
|
||||
return Err("Name cannot be empty".to_string());
|
||||
}
|
||||
ctx.db.user().insert(User { id: 0, name, email });
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
## Views
|
||||
|
||||
**C#:**
|
||||
```csharp
|
||||
[SpacetimeDB.Reducer]
|
||||
public static void CreateUser(ReducerContext ctx, string name, string email)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name))
|
||||
throw new ArgumentException("Name cannot be empty");
|
||||
ctx.Db.User.Insert(new User { Id = 0, Name = name, Email = email });
|
||||
}
|
||||
```
|
||||
Views expose computed read-only data. In 2.4.1 Rust and TypeScript gained primary key support for procedural views; in 2.5 C# gained the same. Clients can receive `OnUpdate` events when subscribed to such views with primary keys. Ensure the view never returns duplicate primary keys, because that can fail view refresh and roll back the triggering transaction.
|
||||
|
||||
### ReducerContext
|
||||
## Event Tables
|
||||
|
||||
Every reducer receives a `ReducerContext` providing:
|
||||
- **Database**: `ctx.db` (Rust field, TS property) / `ctx.Db` (C# property)
|
||||
- **Sender**: `ctx.sender()` (Rust method) / `ctx.Sender` (C# property) / `ctx.sender` (TS property)
|
||||
- **Connection ID**: `ctx.connection_id()` (Rust method) / `ctx.ConnectionId` (C# property) / `ctx.connectionId` (TS property)
|
||||
- **Timestamp**: `ctx.timestamp` (Rust field, TS property) / `ctx.Timestamp` (C# property)
|
||||
Event tables broadcast reducer/procedure-specific facts to subscribers and must be subscribed explicitly. They are excluded from `subscribe_to_all_tables()`.
|
||||
|
||||
## Event Tables (2.0)
|
||||
2.5 adds broader layout-altering automigrations for event tables, including column removal, reordering, and type changes that regular tables reject. This relaxed migration behavior is for event-only tables, not persistent tables.
|
||||
|
||||
Event tables are the preferred way to broadcast reducer-specific data to clients.
|
||||
Event-table primary keys and constraints are transaction-scoped. They can reject duplicate event rows within one transaction, but event rows are not retained in client cache, so clients observe event tables through insert callbacks only. Do not design Genarrative event tables around `OnUpdate` / `on_update` / `onUpdate`; use a persistent table or a primary-keyed procedural view when update callbacks are required.
|
||||
|
||||
```rust
|
||||
#[table(accessor = damage_event, public, event)]
|
||||
pub struct DamageEvent {
|
||||
pub target: Identity,
|
||||
pub amount: u32,
|
||||
}
|
||||
|
||||
#[reducer]
|
||||
fn deal_damage(ctx: &ReducerContext, target: Identity, amount: u32) {
|
||||
ctx.db.damage_event().insert(DamageEvent { target, amount });
|
||||
}
|
||||
```
|
||||
|
||||
Clients subscribe to event tables and use `on_insert` callbacks. Event tables must be subscribed explicitly and are excluded from `subscribe_to_all_tables()`.
|
||||
Official 2.4.1/2.5 release notes document primary-key-backed update callbacks for procedural views, not event tables.
|
||||
|
||||
## Subscriptions
|
||||
|
||||
Subscriptions replicate database rows to clients in real-time.
|
||||
1. Subscribe to SQL queries or generated table/query builders.
|
||||
2. Receive initial matching rows.
|
||||
3. Receive updates when subscribed rows change.
|
||||
4. Render from subscribed data, not reducer return values.
|
||||
|
||||
### How Subscriptions Work
|
||||
Best practices:
|
||||
|
||||
1. **Subscribe**: Register SQL queries describing needed data
|
||||
2. **Receive initial data**: All matching rows are sent immediately
|
||||
3. **Receive updates**: Real-time updates when subscribed rows change
|
||||
4. **React to changes**: Use callbacks (`onInsert`, `onDelete`, `onUpdate`)
|
||||
- Group subscriptions by lifetime.
|
||||
- Subscribe to new data before unsubscribing old data during transitions.
|
||||
- Avoid overlapping queries that duplicate row delivery.
|
||||
- Use indexes for subscribed filters.
|
||||
|
||||
### Subscription Best Practices
|
||||
## 2.2.0 to 2.5.0 Delta
|
||||
|
||||
1. **Group subscriptions by lifetime**: Keep always-needed data separate from temporary subscriptions
|
||||
2. **Subscribe before unsubscribing**: When updating subscriptions, subscribe to new data first
|
||||
3. **Avoid overlapping queries**: Distinct queries returning overlapping data cause redundant processing
|
||||
4. **Use indexes**: Queries on indexed columns are efficient; full table scans are expensive
|
||||
Genarrative introduced SpacetimeDB around 2.2.0. Important changes since then:
|
||||
|
||||
## Modules
|
||||
- **2.2.0**: v3 WebSocket transport and TS SDK default, safer production operations (`lock`/`unlock`, safer `delete`, better `publish --yes`), TS React `useProcedure`, table clearing APIs, empty-table drop automigration, primary-key migration fixes, bytes-key B-tree support, durability hardening.
|
||||
- **2.3.0**: first-party Godot SDK, more WebSocket pipelining/batching, HTTP/2 backend support, Vue `useProcedure`, Unity 6 WebGL support, commitlog compression/throughput improvements, Rust `DbContext` generics, `ReducerContext::identity` deprecated in favor of `database_identity`, connection lifecycle and unsubscribe fixes.
|
||||
- **2.4.0**: unstable module HTTP handlers/webhooks, faster synchronous WASM reducer runtime, commitlog resume truncation fix for silent data loss risk, better commitlog decode context, V8 heap metrics for procedure workers, JS execution-time billing regression reverted.
|
||||
- **2.4.1**: Rust and TypeScript procedural views can declare primary keys, enabling `OnUpdate` events for subscribed views; fixed index schema from ST tables.
|
||||
- **2.5.0**: procedures are stable, C# procedural views gain primary keys, event tables allow broader layout-altering automigrations, BTreeSet storage makes row insertion deterministic and avoids accidentally quadratic bulk insert behavior, `wasm_memory_bytes` billing metric semantics changed, template version constraints unified, `publish --delete-data` config fallback fixed, CLI `call` accepts hex Identity arguments.
|
||||
|
||||
Modules are WebAssembly bundles containing application logic that runs inside the database.
|
||||
## Debugging Checklist
|
||||
|
||||
### Module Components
|
||||
|
||||
- **Tables**: Define the data schema
|
||||
- **Reducers**: Define callable functions that modify state
|
||||
- **Views**: Define read-only computed queries
|
||||
- **Event Tables**: Broadcast reducer-specific data to clients (2.0)
|
||||
- **Procedures**: (Beta) Functions that can have side effects (HTTP requests)
|
||||
|
||||
### Module Languages
|
||||
|
||||
Server-side modules can be written in: Rust, C#, TypeScript (beta)
|
||||
|
||||
### Module Lifecycle
|
||||
|
||||
1. **Write**: Define tables and reducers in your chosen language
|
||||
2. **Compile**: Build to WebAssembly using the SpacetimeDB CLI
|
||||
3. **Publish**: Upload to a SpacetimeDB host with `spacetime publish`
|
||||
4. **Hot-swap**: Republish to update code without disconnecting clients
|
||||
|
||||
## Identity
|
||||
|
||||
Identity is SpacetimeDB's authentication system based on OpenID Connect (OIDC).
|
||||
|
||||
- **Identity**: A long-lived, globally unique identifier for a user.
|
||||
- **ConnectionId**: Identifies a specific client connection.
|
||||
|
||||
```rust
|
||||
#[spacetimedb::reducer]
|
||||
pub fn do_something(ctx: &ReducerContext) {
|
||||
let caller_identity = ctx.sender(); // Who is calling?
|
||||
// NEVER trust identity passed as a reducer argument
|
||||
}
|
||||
```
|
||||
|
||||
### Authentication Providers
|
||||
|
||||
SpacetimeDB works with many OIDC providers, including SpacetimeAuth (built-in), Auth0, Clerk, Keycloak, Google, and GitHub.
|
||||
|
||||
## When to Use SpacetimeDB
|
||||
|
||||
### Ideal Use Cases
|
||||
|
||||
- **Real-time games**: MMOs, multiplayer games, turn-based games
|
||||
- **Collaborative applications**: Document editing, whiteboards, design tools
|
||||
- **Chat and messaging**: Real-time communication with presence
|
||||
- **Live dashboards**: Streaming analytics and monitoring
|
||||
|
||||
### Key Decision Factors
|
||||
|
||||
Choose SpacetimeDB when you need:
|
||||
- Sub-10ms latency for reads and writes
|
||||
- Automatic real-time synchronization
|
||||
- Transactional guarantees for all operations
|
||||
- Simplified architecture (no separate cache, queue, or server)
|
||||
|
||||
### Less Suitable For
|
||||
|
||||
- **Batch analytics**: Optimized for OLTP, not OLAP
|
||||
- **Large blob storage**: Better suited for structured relational data
|
||||
- **Stateless APIs**: Traditional REST APIs do not need real-time sync
|
||||
|
||||
## Common Patterns
|
||||
|
||||
**Authentication check in reducer:**
|
||||
```rust
|
||||
#[spacetimedb::reducer]
|
||||
fn admin_action(ctx: &ReducerContext) -> Result<(), String> {
|
||||
let admin = ctx.db.admin().identity().find(&ctx.sender())
|
||||
.ok_or("Not an admin")?;
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
**Scheduled reducer:**
|
||||
```rust
|
||||
#[spacetimedb::table(accessor = reminder, scheduled(send_reminder))]
|
||||
pub struct Reminder {
|
||||
#[primary_key]
|
||||
#[auto_inc]
|
||||
id: u64,
|
||||
scheduled_at: ScheduleAt,
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[spacetimedb::reducer]
|
||||
fn send_reminder(ctx: &ReducerContext, reminder: Reminder) {
|
||||
log::info!("Reminder: {}", reminder.message);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
1. Is the Genarrative SpacetimeDB server running? Use `npm run dev:spacetime` locally or host-local `systemctl`.
|
||||
2. Is the module published to the same server the API uses?
|
||||
3. Are generated bindings current? Use `npm run spacetime:generate`.
|
||||
4. Is `api-server` using the same database and token?
|
||||
5. Is the reducer/procedure actually called?
|
||||
6. Did `/healthz` / `/readyz` pass while business SpacetimeDB calls still timeout? Inspect API logs and public route behavior.
|
||||
|
||||
## Editing Behavior
|
||||
|
||||
When modifying SpacetimeDB code:
|
||||
|
||||
- Make the smallest change necessary
|
||||
- Do NOT touch unrelated files, configs, or dependencies
|
||||
- Do NOT invent new SpacetimeDB APIs — use only what exists in docs or this repo
|
||||
- Make the smallest change necessary.
|
||||
- Do not invent SpacetimeDB APIs; verify against current docs, generated bindings, or source.
|
||||
- For Genarrative schema edits, update migration code, table catalog/docs, generated bindings, and relevant tests.
|
||||
- After schema edits, run `npm run spacetime:generate` and `npm run check:spacetime-schema`.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,489 +0,0 @@
|
||||
---
|
||||
name: spacetimedb-typescript
|
||||
description: Build TypeScript clients for SpacetimeDB. Use when connecting to SpacetimeDB from web apps, Node.js, Deno, Bun, or other JavaScript runtimes.
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: clockworklabs
|
||||
version: "2.0"
|
||||
---
|
||||
|
||||
# SpacetimeDB TypeScript SDK
|
||||
|
||||
Build real-time TypeScript clients that connect directly to SpacetimeDB modules. The SDK provides type-safe database access, automatic synchronization, and reactive updates for web apps, Node.js, Deno, Bun, and other JavaScript runtimes.
|
||||
|
||||
---
|
||||
|
||||
## HALLUCINATED APIs — DO NOT USE
|
||||
|
||||
**These APIs DO NOT EXIST. LLMs frequently hallucinate them.**
|
||||
|
||||
```typescript
|
||||
// WRONG PACKAGE — does not exist
|
||||
import { SpacetimeDBClient } from "@clockworklabs/spacetimedb-sdk";
|
||||
|
||||
// WRONG — these methods don't exist
|
||||
SpacetimeDBClient.connect(...);
|
||||
SpacetimeDBClient.call("reducer_name", [...]);
|
||||
connection.call("reducer_name", [arg1, arg2]);
|
||||
|
||||
// WRONG — positional reducer arguments
|
||||
conn.reducers.doSomething("value"); // WRONG!
|
||||
|
||||
// WRONG — old 1.0 patterns
|
||||
spacetimedb.reducer('reducer_name', params, fn); // Use export const name = spacetimedb.reducer(params, fn)
|
||||
schema(myTable); // Use schema({ myTable })
|
||||
schema(t1, t2, t3); // Use schema({ t1, t2, t3 })
|
||||
scheduled: 'run_cleanup' // Use scheduled: () => run_cleanup
|
||||
.withModuleName('db') // Use .withDatabaseName('db') (2.0)
|
||||
setReducerFlags.x('NoSuccessNotify') // Removed in 2.0
|
||||
```
|
||||
|
||||
### CORRECT PATTERNS:
|
||||
|
||||
```typescript
|
||||
// CORRECT IMPORTS
|
||||
import { DbConnection, tables } from './module_bindings'; // Generated!
|
||||
import { SpacetimeDBProvider, useTable } from 'spacetimedb/react';
|
||||
import { Identity } from 'spacetimedb';
|
||||
|
||||
// CORRECT REDUCER CALLS — object syntax, not positional!
|
||||
conn.reducers.doSomething({ value: 'test' });
|
||||
conn.reducers.updateItem({ itemId: 1n, newValue: 42 });
|
||||
|
||||
// CORRECT DATA ACCESS — useTable returns [rows, isReady]
|
||||
const [items, isReady] = useTable(tables.item);
|
||||
```
|
||||
|
||||
### DO NOT:
|
||||
- **Invent hooks** like `useItems()`, `useData()` — use `useTable(tables.tableName)`
|
||||
- **Import from fake packages** — only `spacetimedb`, `spacetimedb/react`, `./module_bindings`
|
||||
|
||||
---
|
||||
|
||||
## Common Mistakes Table
|
||||
|
||||
### Server-side errors
|
||||
|
||||
| Wrong | Right | Error |
|
||||
|-------|-------|-------|
|
||||
| Missing `package.json` | Create `package.json` | "could not detect language" |
|
||||
| Missing `tsconfig.json` | Create `tsconfig.json` | "TsconfigNotFound" |
|
||||
| Entrypoint not at `src/index.ts` | Use `src/index.ts` | Module won't bundle |
|
||||
| `indexes` in COLUMNS (2nd arg) | `indexes` in OPTIONS (1st arg) of `table()` | "reading 'tag'" error |
|
||||
| Index without `algorithm` | `algorithm: 'btree'` | "reading 'tag'" error |
|
||||
| `filter({ ownerId })` | `filter(ownerId)` | "does not exist in type 'Range'" |
|
||||
| `.filter()` on unique column | `.find()` on unique column | TypeError |
|
||||
| `insert({ ...without id })` | `insert({ id: 0n, ... })` | "Property 'id' is missing" |
|
||||
| `const id = table.insert(...)` | `const row = table.insert(...)` | `.insert()` returns ROW, not ID |
|
||||
| `.unique()` + explicit index | Just use `.unique()` | "name is used for multiple entities" |
|
||||
| Import spacetimedb from index.ts | Import from schema.ts | "Cannot access before initialization" |
|
||||
| Incorrect multi-column `.filter()` range shape | Match index prefix/tuple shape | Empty results or range/type errors |
|
||||
| `.iter()` in views | Use index lookups only | Views can't scan tables |
|
||||
| `ctx.db` in procedures | `ctx.withTx(tx => tx.db...)` | Procedures need explicit transactions |
|
||||
|
||||
### Client-side errors
|
||||
|
||||
| Wrong | Right | Error |
|
||||
|-------|-------|-------|
|
||||
| Inline `connectionBuilder` | `useMemo(() => ..., [])` | Reconnects every render |
|
||||
| `const rows = useTable(table)` | `const [rows, isReady] = useTable(table)` | Tuple destructuring |
|
||||
| Optimistic UI updates | Let subscriptions drive state | Desync issues |
|
||||
| `<SpacetimeDBProvider builder={...}>` | `connectionBuilder={...}` | Wrong prop name |
|
||||
|
||||
---
|
||||
|
||||
## Hard Requirements
|
||||
|
||||
1. **`schema({ table })`** — use a single tables object; optional module settings are allowed as a second argument
|
||||
2. **Reducer/procedure names from exports** — `export const name = spacetimedb.reducer(params, fn)`; never `reducer('name', ...)`
|
||||
3. **Reducer calls use object syntax** — `{ param: 'value' }` not positional args
|
||||
4. **Import `DbConnection` from `./module_bindings`** — not from `spacetimedb`
|
||||
5. **DO NOT edit generated bindings** — regenerate with `spacetime generate`
|
||||
6. **Indexes go in OPTIONS (1st arg)** — not in COLUMNS (2nd arg) of `table()`
|
||||
7. **Use BigInt for u64/i64 fields** — `0n`, `1n`, not `0`, `1`
|
||||
8. **Reducers are transactional** — they do not return data
|
||||
9. **Reducers must be deterministic** — no filesystem, network, timers, random
|
||||
10. **Views should use index lookups** — `.iter()` causes severe performance issues
|
||||
11. **Procedures need `ctx.withTx()`** — `ctx.db` doesn't exist in procedures
|
||||
12. **Sum type values** — use `{ tag: 'variant', value: payload }` not `{ variant: payload }`
|
||||
13. **Use `.withDatabaseName()`** — not `.withModuleName()` (2.0)
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install spacetimedb
|
||||
```
|
||||
|
||||
For Node.js environments without native fetch/WebSocket support, install `undici`.
|
||||
|
||||
## Generating Type Bindings
|
||||
|
||||
```bash
|
||||
spacetime generate --lang typescript --out-dir ./src/module_bindings --module-path ./server
|
||||
```
|
||||
|
||||
## Client Connection
|
||||
|
||||
```typescript
|
||||
import { DbConnection } from './module_bindings';
|
||||
|
||||
const connection = DbConnection.builder()
|
||||
.withUri('ws://localhost:3000')
|
||||
.withDatabaseName('my_database')
|
||||
.withToken(localStorage.getItem('spacetimedb_token') ?? undefined)
|
||||
.onConnect((conn, identity, token) => {
|
||||
// identity: your unique Identity for this database
|
||||
console.log('Connected as:', identity.toHexString());
|
||||
|
||||
// Save token for reconnection (preserves identity across sessions)
|
||||
localStorage.setItem('spacetimedb_token', token);
|
||||
|
||||
conn.subscriptionBuilder()
|
||||
.onApplied(() => console.log('Cache ready'))
|
||||
.subscribe('SELECT * FROM player');
|
||||
})
|
||||
.onDisconnect((ctx) => console.log('Disconnected'))
|
||||
.onConnectError((ctx, error) => console.error('Connection failed:', error))
|
||||
.build();
|
||||
```
|
||||
|
||||
## Subscribing to Tables
|
||||
|
||||
```typescript
|
||||
// Basic subscription
|
||||
connection.subscriptionBuilder()
|
||||
.onApplied((ctx) => console.log('Cache ready'))
|
||||
.subscribe('SELECT * FROM player');
|
||||
|
||||
// Multiple queries
|
||||
connection.subscriptionBuilder()
|
||||
.subscribe(['SELECT * FROM player', 'SELECT * FROM game_state']);
|
||||
|
||||
// Subscribe to all tables (development only — cannot mix with Subscribe)
|
||||
connection.subscriptionBuilder().subscribeToAllTables();
|
||||
|
||||
// Subscription handle for later unsubscribe
|
||||
const handle = connection.subscriptionBuilder()
|
||||
.onApplied(() => console.log('Subscribed'))
|
||||
.subscribe('SELECT * FROM player');
|
||||
|
||||
handle.unsubscribeThen(() => console.log('Unsubscribed'));
|
||||
```
|
||||
|
||||
## Accessing Table Data
|
||||
|
||||
```typescript
|
||||
for (const player of connection.db.player.iter()) { console.log(player.name); }
|
||||
const players = Array.from(connection.db.player.iter());
|
||||
const count = connection.db.player.count();
|
||||
const player = connection.db.player.id.find(42n);
|
||||
```
|
||||
|
||||
## Table Event Callbacks
|
||||
|
||||
```typescript
|
||||
connection.db.player.onInsert((ctx, player) => console.log('New:', player.name));
|
||||
connection.db.player.onDelete((ctx, player) => console.log('Left:', player.name));
|
||||
connection.db.player.onUpdate((ctx, old, new_) => console.log(`${old.score} -> ${new_.score}`));
|
||||
```
|
||||
|
||||
## Calling Reducers
|
||||
|
||||
**CRITICAL: Use object syntax, not positional arguments.**
|
||||
|
||||
```typescript
|
||||
connection.reducers.createPlayer({ name: 'Alice', location: { x: 0, y: 0 } });
|
||||
```
|
||||
|
||||
### Snake_case to camelCase conversion
|
||||
- Server: `export const do_something = spacetimedb.reducer(...)`
|
||||
- Client: `conn.reducers.doSomething({ ... })`
|
||||
|
||||
---
|
||||
|
||||
## Identity and Authentication
|
||||
|
||||
- `identity` and `token` are provided in the `onConnect` callback (see Client Connection above)
|
||||
- `identity.toHexString()` for display or logging
|
||||
- Omit `.withToken()` for anonymous connection — server assigns a new identity
|
||||
- Pass a stale/invalid token: server issues a new identity and token in `onConnect`
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
Connection-level errors (`.onConnectError`, `.onDisconnect`) are shown in the Client Connection example above.
|
||||
|
||||
```typescript
|
||||
// Subscription error
|
||||
connection.subscriptionBuilder()
|
||||
.onApplied(() => console.log('Subscribed'))
|
||||
.onError((ctx) => console.error('Subscription error:', ctx.event))
|
||||
.subscribe('SELECT * FROM player');
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Server-Side Module Development
|
||||
|
||||
### Table Definition
|
||||
|
||||
```typescript
|
||||
import { schema, table, t } from 'spacetimedb/server';
|
||||
|
||||
export const Task = table({
|
||||
name: 'task',
|
||||
public: true,
|
||||
indexes: [{ name: 'task_owner_id', algorithm: 'btree', columns: ['ownerId'] }]
|
||||
}, {
|
||||
id: t.u64().primaryKey().autoInc(),
|
||||
ownerId: t.identity(),
|
||||
title: t.string(),
|
||||
createdAt: t.timestamp(),
|
||||
});
|
||||
```
|
||||
|
||||
### Column types
|
||||
|
||||
```typescript
|
||||
t.identity() // User identity
|
||||
t.u64() // Unsigned 64-bit integer (use for IDs)
|
||||
t.string() // Text
|
||||
t.bool() // Boolean
|
||||
t.timestamp() // Timestamp
|
||||
t.scheduleAt() // For scheduled tables only
|
||||
t.object('Name', {}) // Product types (nested objects)
|
||||
t.enum('Name', {}) // Sum types (tagged unions)
|
||||
t.string().optional() // Nullable
|
||||
```
|
||||
|
||||
> BigInt syntax: All `u64`/`i64` fields use `0n`, `1n`, not `0`, `1`.
|
||||
|
||||
### Schema export
|
||||
|
||||
```typescript
|
||||
const spacetimedb = schema({ Task, Player });
|
||||
export default spacetimedb;
|
||||
```
|
||||
|
||||
### Reducer Definition (2.0)
|
||||
|
||||
**Name comes from the export — NOT from a string argument.**
|
||||
|
||||
```typescript
|
||||
import spacetimedb from './schema';
|
||||
import { t, SenderError } from 'spacetimedb/server';
|
||||
|
||||
export const create_task = spacetimedb.reducer(
|
||||
{ title: t.string() },
|
||||
(ctx, { title }) => {
|
||||
if (!title) throw new SenderError('title required');
|
||||
ctx.db.task.insert({ id: 0n, ownerId: ctx.sender, title, createdAt: ctx.timestamp });
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### Update Pattern
|
||||
|
||||
```typescript
|
||||
const existing = ctx.db.task.id.find(taskId);
|
||||
if (!existing) throw new SenderError('Task not found');
|
||||
ctx.db.task.id.update({ ...existing, title: newTitle, updatedAt: ctx.timestamp });
|
||||
```
|
||||
|
||||
### Lifecycle Hooks
|
||||
|
||||
```typescript
|
||||
spacetimedb.clientConnected((ctx) => { /* ctx.sender is the connecting identity */ });
|
||||
spacetimedb.clientDisconnected((ctx) => { /* clean up */ });
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Event Tables (2.0)
|
||||
|
||||
Reducer callbacks are removed in 2.0. Use event tables + `onInsert` instead.
|
||||
|
||||
```typescript
|
||||
export const DamageEvent = table(
|
||||
{ name: 'damage_event', public: true, event: true },
|
||||
{ target: t.identity(), amount: t.u32() }
|
||||
);
|
||||
|
||||
export const deal_damage = spacetimedb.reducer(
|
||||
{ target: t.identity(), amount: t.u32() },
|
||||
(ctx, { target, amount }) => {
|
||||
ctx.db.damageEvent.insert({ target, amount });
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
Client subscribes and uses `onInsert`:
|
||||
```typescript
|
||||
conn.db.damageEvent.onInsert((ctx, evt) => {
|
||||
playDamageAnimation(evt.target, evt.amount);
|
||||
});
|
||||
```
|
||||
|
||||
Event tables must be subscribed explicitly — they are excluded from `subscribeToAllTables()`.
|
||||
|
||||
---
|
||||
|
||||
## Views
|
||||
|
||||
### ViewContext vs AnonymousViewContext
|
||||
|
||||
```typescript
|
||||
// ViewContext — has ctx.sender, result varies per user
|
||||
spacetimedb.view({ name: 'my_items', public: true }, t.array(Item.rowType), (ctx) => {
|
||||
return [...ctx.db.item.by_owner.filter(ctx.sender)];
|
||||
});
|
||||
|
||||
// AnonymousViewContext — no ctx.sender, same result for everyone (better perf)
|
||||
spacetimedb.anonymousView({ name: 'leaderboard', public: true }, t.array(Player.rowType), (ctx) => {
|
||||
return ctx.from.player.where(p => p.score.gt(1000));
|
||||
});
|
||||
```
|
||||
|
||||
Views can only use index lookups — `.iter()` is NOT allowed.
|
||||
|
||||
---
|
||||
|
||||
## Scheduled Tables
|
||||
|
||||
```typescript
|
||||
export const CleanupJob = table({
|
||||
name: 'cleanup_job',
|
||||
scheduled: () => run_cleanup // function returning the exported reducer
|
||||
}, {
|
||||
scheduledId: t.u64().primaryKey().autoInc(),
|
||||
scheduledAt: t.scheduleAt(),
|
||||
targetId: t.u64(),
|
||||
});
|
||||
|
||||
export const run_cleanup = spacetimedb.reducer(
|
||||
{ arg: CleanupJob.rowType },
|
||||
(ctx, { arg }) => { /* arg.scheduledId, arg.targetId available */ }
|
||||
);
|
||||
|
||||
// Schedule a job
|
||||
import { ScheduleAt } from 'spacetimedb';
|
||||
ctx.db.cleanupJob.insert({
|
||||
scheduledId: 0n,
|
||||
scheduledAt: ScheduleAt.time(ctx.timestamp.microsSinceUnixEpoch + 60_000_000n),
|
||||
targetId: someId
|
||||
});
|
||||
```
|
||||
|
||||
### ScheduleAt on Client
|
||||
|
||||
```typescript
|
||||
// ScheduleAt is a tagged union on the client
|
||||
// { tag: 'Time', value: Timestamp } or { tag: 'Interval', value: TimeDuration }
|
||||
const schedule = row.scheduledAt;
|
||||
if (schedule.tag === 'Time') {
|
||||
const date = new Date(Number(schedule.value.microsSinceUnixEpoch / 1000n));
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Timestamps
|
||||
|
||||
### Server-side
|
||||
```typescript
|
||||
ctx.db.item.insert({ id: 0n, createdAt: ctx.timestamp });
|
||||
const future = ctx.timestamp.microsSinceUnixEpoch + 300_000_000n;
|
||||
```
|
||||
|
||||
### Client-side
|
||||
```typescript
|
||||
// Timestamps are objects with BigInt, not numbers
|
||||
const date = new Date(Number(row.createdAt.microsSinceUnixEpoch / 1000n));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Procedures (Beta)
|
||||
|
||||
```typescript
|
||||
export const fetch_data = spacetimedb.procedure(
|
||||
{ url: t.string() }, t.string(),
|
||||
(ctx, { url }) => {
|
||||
const response = ctx.http.fetch(url);
|
||||
ctx.withTx(tx => { tx.db.myTable.insert({ id: 0n, content: response.text() }); });
|
||||
return response.text();
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
Procedures don't have `ctx.db` — use `ctx.withTx(tx => tx.db...)`.
|
||||
|
||||
---
|
||||
|
||||
## React Integration
|
||||
|
||||
```tsx
|
||||
import { useMemo } from 'react';
|
||||
import { SpacetimeDBProvider, useTable } from 'spacetimedb/react';
|
||||
import { DbConnection, tables } from './module_bindings';
|
||||
|
||||
function Root() {
|
||||
const connectionBuilder = useMemo(() =>
|
||||
DbConnection.builder()
|
||||
.withUri('ws://localhost:3000')
|
||||
.withDatabaseName('my_game')
|
||||
.withToken(localStorage.getItem('auth_token') || undefined)
|
||||
.onConnect((conn, identity, token) => {
|
||||
localStorage.setItem('auth_token', token);
|
||||
conn.subscriptionBuilder().subscribe(tables.player);
|
||||
}),
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<SpacetimeDBProvider connectionBuilder={connectionBuilder}>
|
||||
<App />
|
||||
</SpacetimeDBProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function PlayerList() {
|
||||
const [players, isReady] = useTable(tables.player);
|
||||
if (!isReady) return <div>Loading...</div>;
|
||||
return <ul>{players.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Project Structure
|
||||
|
||||
### Server (`backend/spacetimedb/`)
|
||||
```
|
||||
src/schema.ts -> Tables, export spacetimedb
|
||||
src/index.ts -> Reducers, lifecycle, import schema
|
||||
package.json -> { "type": "module", "dependencies": { "spacetimedb": "^2.0.0" } }
|
||||
tsconfig.json -> Standard config
|
||||
```
|
||||
|
||||
### Client (`client/`)
|
||||
```
|
||||
src/module_bindings/ -> Generated (spacetime generate)
|
||||
src/main.tsx -> Provider, connection setup
|
||||
src/App.tsx -> UI components
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
spacetime start
|
||||
spacetime publish <module-name> --module-path <backend-dir>
|
||||
spacetime publish <module-name> --clear-database -y --module-path <backend-dir>
|
||||
spacetime generate --lang typescript --out-dir <client>/src/module_bindings --module-path <backend-dir>
|
||||
spacetime logs <module-name>
|
||||
```
|
||||
@@ -1,292 +0,0 @@
|
||||
---
|
||||
name: spacetimedb-unity
|
||||
description: Integrate SpacetimeDB with Unity game projects. Use when building Unity clients with MonoBehaviour lifecycle, FrameTick, and PlayerPrefs token persistence.
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: clockworklabs
|
||||
version: "2.0"
|
||||
tested_with: "SpacetimeDB 2.0, Unity 2022.3+"
|
||||
---
|
||||
|
||||
# SpacetimeDB Unity Integration
|
||||
|
||||
This skill covers Unity-specific patterns for connecting to SpacetimeDB. For server-side module development and general C# SDK usage, see the `spacetimedb-csharp` skill.
|
||||
|
||||
---
|
||||
|
||||
## HALLUCINATED APIs — DO NOT USE
|
||||
|
||||
```csharp
|
||||
// WRONG — these do not exist in Unity SDK
|
||||
SpacetimeDBClient.instance.Connect(...); // Use DbConnection.Builder()
|
||||
SpacetimeDBClient.instance.Subscribe(...); // Use conn.SubscriptionBuilder()
|
||||
NetworkManager.RegisterReducer(...); // SpacetimeDB is not a Unity networking plugin
|
||||
|
||||
// WRONG — old 1.0 patterns
|
||||
.WithModuleName("my-db") // Use .WithDatabaseName() (2.0)
|
||||
ScheduleAt.Time(futureTime) // Use new ScheduleAt.Time(futureTime)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
| Wrong | Right | Error |
|
||||
|-------|-------|-------|
|
||||
| Not calling `FrameTick()` | `conn?.FrameTick()` in `Update()` | No callbacks fire |
|
||||
| Accessing `conn.Db` from background thread | Copy data in callback, use on main thread | Data races / crashes |
|
||||
| Forgetting `DontDestroyOnLoad` | Add to manager `Awake()` | Connection lost on scene load |
|
||||
| Connecting in `Update()` | Connect in `Start()` or on user action | Reconnects every frame |
|
||||
| Not saving auth token | `PlayerPrefs.SetString(...)` in `OnConnect` | New identity every session |
|
||||
| Missing generated bindings | Run `spacetime generate --lang csharp` | Compile errors |
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
Add via Unity Package Manager using the git URL:
|
||||
|
||||
```
|
||||
https://github.com/clockworklabs/com.clockworklabs.spacetimedbsdk.git
|
||||
```
|
||||
|
||||
**Window > Package Manager > + > Add package from git URL**
|
||||
|
||||
---
|
||||
|
||||
## Generate Module Bindings
|
||||
|
||||
```bash
|
||||
spacetime generate --lang csharp --out-dir Assets/SpacetimeDB/module_bindings --module-path PATH_TO_MODULE
|
||||
```
|
||||
|
||||
Place generated files in your Assets folder so Unity compiles them.
|
||||
|
||||
---
|
||||
|
||||
## SpacetimeManager Singleton
|
||||
|
||||
The core pattern for Unity integration. This MonoBehaviour manages the connection lifecycle.
|
||||
|
||||
```csharp
|
||||
using UnityEngine;
|
||||
using SpacetimeDB;
|
||||
using SpacetimeDB.Types;
|
||||
|
||||
public class SpacetimeManager : MonoBehaviour
|
||||
{
|
||||
private const string TOKEN_KEY = "SpacetimeAuthToken";
|
||||
private const string SERVER_URI = "http://localhost:3000";
|
||||
private const string DATABASE_NAME = "my-game";
|
||||
|
||||
public static SpacetimeManager Instance { get; private set; }
|
||||
public DbConnection Connection { get; private set; }
|
||||
public Identity LocalIdentity { get; private set; }
|
||||
|
||||
void Awake()
|
||||
{
|
||||
if (Instance != null && Instance != this) { Destroy(gameObject); return; }
|
||||
Instance = this;
|
||||
DontDestroyOnLoad(gameObject);
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
string savedToken = PlayerPrefs.GetString(TOKEN_KEY, null);
|
||||
|
||||
Connection = DbConnection.Builder()
|
||||
.WithUri(SERVER_URI)
|
||||
.WithDatabaseName(DATABASE_NAME)
|
||||
.WithToken(savedToken)
|
||||
.OnConnect(OnConnected)
|
||||
.OnConnectError(err => Debug.LogError($"Connection failed: {err}"))
|
||||
.OnDisconnect((conn, err) => {
|
||||
if (err != null) Debug.LogError($"Disconnected: {err}");
|
||||
})
|
||||
.Build();
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
Connection?.FrameTick();
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
Connection?.Disconnect();
|
||||
}
|
||||
|
||||
private void OnConnected(DbConnection conn, Identity identity, string authToken)
|
||||
{
|
||||
LocalIdentity = identity;
|
||||
PlayerPrefs.SetString(TOKEN_KEY, authToken);
|
||||
PlayerPrefs.Save();
|
||||
|
||||
Debug.Log($"Connected as: {identity}");
|
||||
|
||||
conn.SubscriptionBuilder()
|
||||
.OnApplied(OnSubscriptionApplied)
|
||||
.SubscribeToAllTables();
|
||||
}
|
||||
|
||||
private void OnSubscriptionApplied(SubscriptionEventContext ctx)
|
||||
{
|
||||
Debug.Log("Subscription applied — game state loaded");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## FrameTick — Critical
|
||||
|
||||
**`FrameTick()` must be called every frame in `Update()`.** The SDK queues all network messages and only processes them when you call `FrameTick()`. Without it:
|
||||
- No callbacks fire (OnInsert, OnUpdate, OnDelete, reducer callbacks)
|
||||
- The client appears frozen
|
||||
|
||||
```csharp
|
||||
void Update()
|
||||
{
|
||||
Connection?.FrameTick();
|
||||
}
|
||||
```
|
||||
|
||||
**Thread safety**: `FrameTick()` processes messages on the calling thread (the main thread in Unity). Do NOT call it from a background thread. Do NOT access `conn.Db` from background threads.
|
||||
|
||||
---
|
||||
|
||||
## Subscribing to Tables
|
||||
|
||||
Subscribe in the `OnConnected` callback:
|
||||
|
||||
```csharp
|
||||
private void OnConnected(DbConnection conn, Identity identity, string authToken)
|
||||
{
|
||||
// ...save token...
|
||||
|
||||
// Development: subscribe to all
|
||||
conn.SubscriptionBuilder()
|
||||
.OnApplied(OnSubscriptionApplied)
|
||||
.SubscribeToAllTables();
|
||||
|
||||
// Production: subscribe to specific tables
|
||||
conn.SubscriptionBuilder()
|
||||
.OnApplied(OnSubscriptionApplied)
|
||||
.Subscribe(new[] {
|
||||
"SELECT * FROM player",
|
||||
"SELECT * FROM game_state"
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Row Callbacks for Game State
|
||||
|
||||
Register callbacks to update Unity GameObjects when table data changes.
|
||||
|
||||
```csharp
|
||||
void RegisterCallbacks()
|
||||
{
|
||||
Connection.Db.Player.OnInsert += (EventContext ctx, Player player) => {
|
||||
SpawnPlayerObject(player);
|
||||
};
|
||||
|
||||
Connection.Db.Player.OnDelete += (EventContext ctx, Player player) => {
|
||||
DestroyPlayerObject(player.Id);
|
||||
};
|
||||
|
||||
Connection.Db.Player.OnUpdate += (EventContext ctx, Player oldPlayer, Player newPlayer) => {
|
||||
UpdatePlayerObject(newPlayer);
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Register these in `OnSubscriptionApplied` (after initial data is loaded) or in `Start()` before connecting.
|
||||
|
||||
---
|
||||
|
||||
## Calling Reducers from UI
|
||||
|
||||
```csharp
|
||||
public class GameUI : MonoBehaviour
|
||||
{
|
||||
public void OnMoveButtonClicked(Vector2 direction)
|
||||
{
|
||||
SpacetimeManager.Instance.Connection.Reducers.MovePlayer(direction.x, direction.y);
|
||||
}
|
||||
|
||||
public void OnSendChat(string message)
|
||||
{
|
||||
SpacetimeManager.Instance.Connection.Reducers.SendMessage(message);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Reducer Callbacks
|
||||
|
||||
```csharp
|
||||
SpacetimeManager.Instance.Connection.Reducers.OnSendMessage += (ReducerEventContext ctx, string text) => {
|
||||
if (ctx.Event.Status is Status.Committed)
|
||||
Debug.Log($"Message sent: {text}");
|
||||
else if (ctx.Event.Status is Status.Failed(var reason))
|
||||
Debug.LogError($"Send failed: {reason}");
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Reading the Client Cache
|
||||
|
||||
```csharp
|
||||
// Find by primary key
|
||||
if (Connection.Db.Player.Id.Find(playerId) is Player player)
|
||||
{
|
||||
Debug.Log($"Player: {player.Name}");
|
||||
}
|
||||
|
||||
// Iterate all
|
||||
foreach (var p in Connection.Db.Player.Iter())
|
||||
{
|
||||
Debug.Log(p.Name);
|
||||
}
|
||||
|
||||
// Filter by index
|
||||
foreach (var p in Connection.Db.Player.Level.Filter(5))
|
||||
{
|
||||
Debug.Log($"Level 5: {p.Name}");
|
||||
}
|
||||
|
||||
// Count
|
||||
int total = Connection.Db.Player.Count;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Unity-Specific Considerations
|
||||
|
||||
### Main Thread Only
|
||||
All SpacetimeDB SDK calls (`FrameTick`, `conn.Db` access, reducer calls) must happen on the main thread. If you need to pass data to a background thread, copy it first in the callback.
|
||||
|
||||
### Scene Loading
|
||||
Use `DontDestroyOnLoad(gameObject)` on the SpacetimeManager to prevent the connection from being destroyed during scene transitions. Without it, the connection drops every time you load a new scene.
|
||||
|
||||
### IL2CPP / AOT
|
||||
The SpacetimeDB SDK uses code generation. If you encounter issues with IL2CPP builds:
|
||||
- Ensure generated bindings are up to date
|
||||
- Check that `link.xml` preserves SpacetimeDB types if you use assembly stripping
|
||||
|
||||
### Token Persistence
|
||||
Token save/load via `PlayerPrefs` is demonstrated in the SpacetimeManager singleton above. If the token is stale or invalid, the server issues a new identity and token in the `OnConnect` callback.
|
||||
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
spacetime start
|
||||
spacetime publish <module-name> --module-path <backend-dir>
|
||||
spacetime publish <module-name> --clear-database -y --module-path <backend-dir>
|
||||
spacetime generate --lang csharp --out-dir Assets/SpacetimeDB/module_bindings --module-path <backend-dir>
|
||||
spacetime logs <module-name>
|
||||
```
|
||||
@@ -22,6 +22,7 @@ tmp
|
||||
.env.secrets.*
|
||||
spacetime.local.json
|
||||
deploy/container/api-server.env
|
||||
deploy/container/worker-smoke
|
||||
|
||||
server-rs/target
|
||||
server-rs/target-*
|
||||
|
||||
@@ -37,11 +37,14 @@ temp*build*/
|
||||
/.app/
|
||||
/target/
|
||||
/logs
|
||||
/.codegraph/
|
||||
/server-rs/crates/*/logs/
|
||||
.worktrees/
|
||||
.rag/
|
||||
.env.secrets.local
|
||||
spacetime.local.json
|
||||
deploy/container/api-server.env
|
||||
deploy/container/worker-smoke/
|
||||
|
||||
# Local load-test data extracted from private migration files
|
||||
scripts/loadtest/data/*.local.json
|
||||
|
||||
+7
-33
@@ -1,30 +1,21 @@
|
||||
# Genarrative 团队 Hermes 共享记忆
|
||||
# Genarrative Hermes 工具目录
|
||||
|
||||
本目录用于在仓库内共享团队级 Hermes 上下文,供 3 名开发人员在各自本地 Hermes 中读取、更新和同步。
|
||||
本目录只保留 Hermes 专用的仓库级工具资源,例如 Hermes skills、plugins 和启用说明。项目知识本体、长期记忆、计划和 TODO 不再放在 `.hermes/`,统一迁移到 `docs/project-memory/`。
|
||||
|
||||
## 使用原则
|
||||
|
||||
- `.hermes/` 中只保存可以进入 Git 的团队共享内容。
|
||||
- `.hermes/` 中只保存 Hermes 工具运行或加载所需内容。
|
||||
- 项目长期知识、架构约定、排障经验、协作规则、计划和 TODO 统一放在 `docs/project-memory/`。
|
||||
- 不提交个人配置、API Key、会话转录、模型密钥、本地路径密钥等敏感内容。
|
||||
- 个人 Hermes 的 `~/.hermes/config.yaml`、`~/.hermes/.env`、`~/.hermes/sessions/` 不应复制到本仓库。
|
||||
- 开发前先阅读本目录下与任务相关的记忆文件;开发后如产生稳定知识,更新对应文档。
|
||||
- 后续新增的 Markdown 文档文件名必须以分类标签开头,格式为 `【标签名】中文标题-日期.md`,便于团队跨目录检索。
|
||||
- 若本目录内容与 `docs/` 或代码事实冲突,以当前代码和最新 `docs/` 为准,并同步修正过期记忆。
|
||||
- 阶段性计划、一次性 TODO 和已关闭实验不再长期沉淀为仓库文档;仍有效内容应合并进 `docs/` 当前融合文档或 `.hermes/shared-memory/`。
|
||||
- 若 `.hermes/` 中的工具说明与代码或 `docs/` 冲突,以当前代码和最新 `docs/` 为准。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```text
|
||||
.hermes/
|
||||
├─ README.md # 本说明
|
||||
├─ shared-memory/
|
||||
│ ├─ project-overview.md # 项目概览与当前技术路线
|
||||
│ ├─ team-conventions.md # 团队协作约定
|
||||
│ ├─ development-workflow.md # 开发、测试、提交流程
|
||||
│ ├─ document-map.md # README / AGENTS / docs 阅读索引
|
||||
│ ├─ decision-log.md # 长期决策记录
|
||||
│ ├─ pitfalls.md # 踩坑与排障记录
|
||||
│ └─ handoff-template.md # 任务交接模板
|
||||
├─ README.md # Hermes 工具目录说明
|
||||
├─ skills/ # 仓库级 Hermes skills
|
||||
└─ plugins/ # 仓库级 Hermes plugins(需显式启用项目 plugin)
|
||||
```
|
||||
@@ -71,22 +62,5 @@ HERMES_ENABLE_PROJECT_PLUGINS=1 HERMES_PLUGINS_DEBUG=1 hermes chat -q "请读取
|
||||
在本仓库中开始复杂任务时,可以先对 Hermes 说:
|
||||
|
||||
```text
|
||||
请先读取 AGENTS.md 以及 .hermes/shared-memory/ 下与本任务相关的团队共享记忆,再开始分析。若任务完成后产生稳定项目知识,请更新 .hermes/shared-memory/ 对应文件。
|
||||
请先读取 AGENTS.md 以及 docs/project-memory/shared-memory/ 下与本任务相关的团队共享记忆,再开始分析。若任务完成后产生稳定项目知识,请更新 docs/project-memory/shared-memory/ 对应文件。
|
||||
```
|
||||
|
||||
## 需要沉淀到这里的内容
|
||||
|
||||
- 长期有效的架构约定
|
||||
- 反复会用到的本地开发/测试流程
|
||||
- 已确认的接口契约或模块边界
|
||||
- 重要技术决策及原因
|
||||
- 踩坑、排障方式、验证命令
|
||||
- 团队协作规则和任务交接规范
|
||||
|
||||
## 不应沉淀到这里的内容
|
||||
|
||||
- API Key、Token、Cookie、私有密钥
|
||||
- 个人账号、个人本地绝对路径、个人隐私信息
|
||||
- 大段临时聊天记录
|
||||
- 尚未确认的一次性猜测
|
||||
- 构建产物、日志、缓存、数据库 dump
|
||||
|
||||
@@ -284,7 +284,7 @@ fn anonymous_user_cannot_publish_generated_draft() {
|
||||
| 正式产品验收 / PRD 场景 | 当前 `docs/` 融合文档,必要时新增 `docs/【产品验收】<功能名>BDD场景-YYYY-MM-DD.md` | 产品、测试、开发都需要长期参考的验收标准、用户故事、功能边界。 |
|
||||
| 技术/API/领域行为场景 | 当前 `docs/` 融合文档,必要时新增 `docs/【技术验收】<功能名>BDD场景-YYYY-MM-DD.md` | 后端 API、领域规则、状态机、SpacetimeDB reducer/table、SSE/异步任务、埋点副作用。 |
|
||||
| 自动化 Gherkin feature 文件 | `tests/features/*.feature` 或 `e2e/features/*.feature` | 项目已接入 Cucumber/Playwright BDD 等 Gherkin runner 时。未接入前不要随意新建测试 runner 目录。 |
|
||||
| 稳定流程或团队经验 | `.hermes/shared-memory/` 或 `.hermes/skills/` | 不是某个功能验收,而是长期可复用的团队流程、坑点、执行规范。 |
|
||||
| 稳定流程或团队经验 | `docs/project-memory/shared-memory/` 或 `.hermes/skills/` | 不是某个功能验收,而是长期可复用的团队流程、坑点、执行规范。 |
|
||||
|
||||
默认规则:
|
||||
|
||||
@@ -311,7 +311,7 @@ e2e/features/invite-code.feature
|
||||
- 实施计划:当前任务上下文或 `.tmp/<task-name>.md`
|
||||
- 产品/验收文档:当前 `docs/` 融合文档,必要时新增 `docs/【产品验收】中文标题-YYYY-MM-DD.md`
|
||||
- 技术设计:当前 `docs/` 融合文档,必要时新增 `docs/【技术方案】中文标题-YYYY-MM-DD.md`
|
||||
- 共享经验或稳定流程:`.hermes/shared-memory/` 或 `.hermes/skills/`
|
||||
- 共享经验或稳定流程:`docs/project-memory/shared-memory/` 或 `.hermes/skills/`
|
||||
|
||||
BDD 文档建议包含:
|
||||
|
||||
@@ -389,4 +389,4 @@ npm run test -- --run <相关测试文件>
|
||||
```
|
||||
|
||||
- [ ] 若涉及后端 Rust/API,按相关 DDD/SpacetimeDB 文档运行对应 cargo/npm/API smoke 验证。
|
||||
- [ ] 若产生长期有效经验,已同步到 `.hermes/shared-memory/` 或合适的仓库级 skill。
|
||||
- [ ] 若产生长期有效经验,已同步到 `docs/project-memory/shared-memory/` 或合适的仓库级 skill。
|
||||
|
||||
@@ -21,7 +21,7 @@ metadata:
|
||||
- 处理 `3000`、`3101`、`3102`、`8082` 等端口被占用导致本地开发栈启动失败。
|
||||
- 排查 Vite 代理仍指向旧 api-server 端口、前端打开了旧 dev server、后台代理错配。
|
||||
- 调整 SpacetimeDB standalone、publish、Rust `api-server`、主站 Vite、后台 Vite 的启动顺序。
|
||||
- 修改本地联调文档或 `.hermes/shared-memory/pitfalls.md` 中的 dev 启动口径。
|
||||
- 修改本地联调文档或 `docs/project-memory/shared-memory/pitfalls.md` 中的 dev 启动口径。
|
||||
|
||||
## 当前端口职责
|
||||
|
||||
@@ -75,7 +75,7 @@ Linux 多用户并发开发时,`GENARRATIVE_DEV_PORT_RANGE` 或 `--port-range`
|
||||
- `scripts/dev.mjs`
|
||||
- `scripts/dev-utils.mjs`
|
||||
- `docs/technical/RUST_LOCAL_AND_REMOTE_DEPLOYMENT_SCRIPTS_2026-04-22.md`
|
||||
- `.hermes/shared-memory/pitfalls.md`
|
||||
- `docs/project-memory/shared-memory/pitfalls.md`
|
||||
2. 优先改公共端口工具,不要把端口探测逻辑复制到多个脚本。
|
||||
3. 修改 `scripts/dev.mjs` 时确认变量顺序:先解析参数和端口,再构造 `SPACETIME_SERVER` / `RUST_SERVER_TARGET`,最后启动对应 service。
|
||||
4. 修改 watch 时保持模块边界:SpacetimeDB 只监听 `spacetime-module` 且改动后重新 publish,不重启 standalone 宿主;api-server 排除 `spacetime-module`;web/admin-web 源码变化交给 Vite 自身 HMR,外层调度器不要再监听前端目录重启 Vite。
|
||||
@@ -124,5 +124,5 @@ node scripts/dev-stack-port-utils.mjs resolve-dev-stack spacetime:127.0.0.1:0 ap
|
||||
- [ ] `npm run dev` 的 SpacetimeDB、publish、api-server、主站 Vite、后台 Vite 都使用实际端口。
|
||||
- [ ] `npm run dev:web` 在主站端口不可用时能切换到可用端口。
|
||||
- [ ] 文档同步更新 `docs/technical/RUST_LOCAL_AND_REMOTE_DEPLOYMENT_SCRIPTS_2026-04-22.md`。
|
||||
- [ ] 长期踩坑同步更新 `.hermes/shared-memory/pitfalls.md`。
|
||||
- [ ] 长期踩坑同步更新 `docs/project-memory/shared-memory/pitfalls.md`。
|
||||
- [ ] 修改中文文件后运行 `npm run check:encoding`。
|
||||
|
||||
@@ -47,13 +47,13 @@ description: 在 Genarrative 新增、开放或重构玩法创作工具时,按
|
||||
先读:
|
||||
|
||||
- `AGENTS.md`
|
||||
- `.hermes/shared-memory/`
|
||||
- `docs/project-memory/shared-memory/`
|
||||
- `CONTEXT.md`
|
||||
- `docs/README.md`
|
||||
- `docs/【玩法创作】平台入口与玩法链路-2026-05-15.md`
|
||||
- 相关玩法 PRD 或设计文档
|
||||
|
||||
如果文档不能精确指导字段、契约、资产槽位、生成流程和恢复语义,先补文档再编码。新增长期约定时同步 `.hermes/shared-memory/`。
|
||||
如果文档不能精确指导字段、契约、资产槽位、生成流程和恢复语义,先补文档再编码。新增长期约定时同步 `docs/project-memory/shared-memory/`。
|
||||
|
||||
### 2. 定玩法边界
|
||||
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@
|
||||
11. 接 `api-server`:
|
||||
- `src/runtime_profile.rs`:Query params / parser / handler / response builder。
|
||||
- `src/app.rs`:挂路由,例如 profile 或 admin analytics endpoint;选择路径前确认产品定位。
|
||||
12. 最后更新当前 `docs/` 文档和必要的 `.hermes/shared-memory/` 摘要,并确认 diff 不只是生成物。
|
||||
12. 最后更新当前 `docs/` 文档和必要的 `docs/project-memory/shared-memory/` 摘要,并确认 diff 不只是生成物。
|
||||
|
||||
## 验证命令示例
|
||||
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
# AGENTS.md
|
||||
|
||||
## 团队 Hermes 共享记忆
|
||||
- 本仓库的团队级 Hermes 共享内容位于 [`.hermes/`](.hermes/),用于在 3 名开发人员各自本地 Hermes 之间同步长期项目记忆。
|
||||
## 项目共享记忆
|
||||
- 本仓库的团队级项目记忆位于 [`docs/project-memory/`](docs/project-memory/),用于在 3 名开发人员和各自本地 Agent 之间同步长期项目知识。
|
||||
- [`.hermes/`](.hermes/) 只保存 Hermes 专用的仓库级工具资源,例如 skills、plugins 和启用说明,不作为项目知识库。
|
||||
- 开始复杂开发任务前,除阅读本文件外,还应优先读取:
|
||||
- [`.hermes/README.md`](.hermes/README.md)
|
||||
- [`.hermes/shared-memory/project-overview.md`](.hermes/shared-memory/project-overview.md)
|
||||
- [`.hermes/shared-memory/team-conventions.md`](.hermes/shared-memory/team-conventions.md)
|
||||
- [`.hermes/shared-memory/development-workflow.md`](.hermes/shared-memory/development-workflow.md)
|
||||
- 与任务相关的 [`.hermes/shared-memory/decision-log.md`](.hermes/shared-memory/decision-log.md) 和 [`.hermes/shared-memory/pitfalls.md`](.hermes/shared-memory/pitfalls.md)
|
||||
- 如果本次任务产生长期有效的架构约定、接口变化、排障经验、开发流程或协作规则,应同步更新 `.hermes/shared-memory/` 中对应文件。
|
||||
- 仓库 `.hermes/` 只保存可进入 Git 的团队共享内容;禁止提交个人 `~/.hermes` 配置、`.env`、API Key、Token、会话记录、认证文件和本地私密路径。
|
||||
- 若 `.hermes/shared-memory/` 与当前代码或 `docs/` 最新文档冲突,以代码和最新 `docs/` 为准,并同步修正过期共享记忆。
|
||||
- [`docs/project-memory/README.md`](docs/project-memory/README.md)
|
||||
- [`docs/project-memory/shared-memory/project-overview.md`](docs/project-memory/shared-memory/project-overview.md)
|
||||
- [`docs/project-memory/shared-memory/team-conventions.md`](docs/project-memory/shared-memory/team-conventions.md)
|
||||
- [`docs/project-memory/shared-memory/development-workflow.md`](docs/project-memory/shared-memory/development-workflow.md)
|
||||
- 与任务相关的 [`docs/project-memory/shared-memory/decision-log.md`](docs/project-memory/shared-memory/decision-log.md) 和 [`docs/project-memory/shared-memory/pitfalls.md`](docs/project-memory/shared-memory/pitfalls.md)
|
||||
- 如果本次任务产生长期有效的架构约定、接口变化、排障经验、开发流程或协作规则,应同步更新 `docs/project-memory/shared-memory/` 中对应文件。
|
||||
- 禁止提交个人 `~/.hermes` 配置、`.env`、API Key、Token、会话记录、认证文件和本地私密路径。
|
||||
- 若 `docs/project-memory/shared-memory/` 与当前代码或 `docs/` 最新文档冲突,以代码和最新 `docs/` 为准,并同步修正过期共享记忆。
|
||||
|
||||
## Agent 本地 RAG
|
||||
- 本仓库提供面向 Agent 的本地文档 RAG,入口位于 [`scripts/rag/`](scripts/rag/);RAG 主要用于 Agent 检索项目上下文,不替代人工阅读 `AGENTS.md`、`docs/README.md` 和 `docs/project-memory/`。
|
||||
- 开始复杂任务、跨模块任务或不确定文档入口时,Agent 可先用 `npm run rag:search -- --query "问题或关键词" --limit 8 --max-chars 12000` 取候选上下文;需要刷新索引时运行 `npm run rag:index`。
|
||||
- RAG 输出只作为候选上下文。涉及精确代码或文档修改时,仍需打开对应源文件核对;来源冲突时,以当前代码和最新 `docs/` 为准。
|
||||
- 默认不安装 RAG 运行时依赖,也不把 LanceDB、Transformers.js 或本地 embedding 模型写入根 `package.json`。需要启用时,Agent 必须先询问用户是否安装,并在确认后只安装到 gitignored 的 `.rag/runtime/`;详细命令见 [`scripts/rag/README.md`](scripts/rag/README.md)。
|
||||
|
||||
## Agent skills
|
||||
|
||||
@@ -67,11 +75,10 @@ Single-context layout: read root `CONTEXT.md` when present. Current architecture
|
||||
- [$spacetimedb-cli](.codex\\skills\\spacetimedb-cli\\SKILL.md)
|
||||
- [$spacetimedb-rust](.codex\\skills\\spacetimedb-rust\\SKILL.md)
|
||||
- [$spacetimedb-concepts](.codex\\skills\\spacetimedb-concepts\\SKILL.md)
|
||||
- [$spacetimedb-typescript](.codex\\skills\\spacetimedb-typescript\\SKILL.md)
|
||||
- 涉及 `spacetime` CLI、发布、绑定生成、本地联调时,按 `spacetimedb-cli` 执行。
|
||||
- 涉及 `npm run dev` / `npm run dev:rust` / `npm run dev:web` 的端口探测、端口漂移、SpacetimeDB publish server、api-server 环境变量、Vite 代理目标或后台 dev 端口时,按 [`.hermes/skills/genarrative-dev-stack-port-routing/SKILL.md`](.hermes/skills/genarrative-dev-stack-port-routing/SKILL.md) 执行。
|
||||
- 涉及 `crates/spacetime-module` 的表、reducer、view、Rust API 使用时,按 `spacetimedb-rust` 与 `spacetimedb-concepts` 执行。
|
||||
- 涉及前端或 Node 侧的 SpacetimeDB TypeScript SDK、订阅、绑定使用时,按 `spacetimedb-typescript` 与 `spacetimedb-concepts` 执行。
|
||||
- 涉及前端或 Node 侧的 SpacetimeDB 订阅、绑定使用时,按当前生成绑定、项目代码和官方文档核对;本仓库不再维护单独 TypeScript / C# / Unity SpacetimeDB skill。
|
||||
- 若仓库内旧实现或旧文档与这些 skill 冲突,先修正文档和方案,再继续编码。
|
||||
- 修改后端代码后,必须使用 `npm run api-server` 自动重新运行后端,并执行相应自动测试;不要再使用旧的后端重启命令。
|
||||
- 数据库表结构更改后,需要对齐migration.rs
|
||||
|
||||
@@ -9,12 +9,14 @@ Docker Compose
|
||||
├─ spacetimedb :3101,独立数据卷,供 api-server 连接
|
||||
├─ nginx :80 -> api-server:8082,负责静态站点、/admin/、/api/ 反代、upstream timing log、连接限制
|
||||
├─ api-server :8082,Linux release 构建,连接 compose 内 SpacetimeDB
|
||||
├─ external-generation-worker,独立 worker 进程,消费 external_generation_job 队列
|
||||
├─ otelcol :4317/4318,debug exporter,接收 traces / metrics / logs
|
||||
└─ k6 profile=loadtest 时临时启动,在 compose 网络内压 nginx
|
||||
```
|
||||
|
||||
当前容器模拟参数按 `genarrative-release` 服务器采样值收口为 2 vCPU / 2 GiB RAM / 4096 soft nofile / 768 worker_connections,并已在 compose 里落实到 `spacetimedb cpus=1.0 mem_limit=896m`、`api-server cpus=2.0 mem_limit=1g`、`nginx cpus=0.5 mem_limit=128m`、`otelcol cpus=0.25 mem_limit=128m`、`k6 cpus=1.0 mem_limit=512m`。SpacetimeDB 同时设置 `--page_pool_max_size=402653184`,给 reducer、订阅与运行时保留更多非 page pool 内存。
|
||||
当前容器模拟参数按 `genarrative-release` 服务器采样值收口为 2 vCPU / 2 GiB RAM / 4096 soft nofile / 768 worker_connections,并已在 compose 里落实到 `spacetimedb cpus=1.0 mem_limit=896m`、`api-server cpus=2.0 mem_limit=1g`、`external-generation-worker cpus=2.0 mem_limit=1g`、`nginx cpus=0.5 mem_limit=128m`、`otelcol cpus=0.25 mem_limit=128m`、`k6 cpus=1.0 mem_limit=512m`。SpacetimeDB 同时设置 `--page_pool_max_size=402653184`,给 reducer、订阅与运行时保留更多非 page pool 内存。
|
||||
容器 `api-server` 默认 `GENARRATIVE_API_WORKER_THREADS=4`,用于让 Tokio 在 2 vCPU 配额内有更多 I/O 调度 worker;该值不会突破 compose 里的 `cpus=2.0` CPU 上限。
|
||||
容器默认 `GENARRATIVE_EXTERNAL_GENERATION_MODE=queue`,用于验证 `api-server -> external_generation_job -> external-generation-worker` 链路;如只想本地同步排查 provider/OSS/SpacetimeDB 写回,可在本机 env 临时改为 `inline`,但该模式不会覆盖 worker 动态扩缩容验证。
|
||||
Collector 镜像使用 `otel/opentelemetry-collector-contrib:0.151.0`。
|
||||
生产服务器若启用 Collector,则由 `deploy/systemd/otelcol-contrib.service` 和 `deploy/otelcol/genarrative-debug.yaml` 托管,不走容器镜像。
|
||||
|
||||
@@ -55,7 +57,7 @@ Linux Docker Engine 若要从宿主机 CLI 连到容器内服务,直接用 `ht
|
||||
|
||||
## 构建工具链
|
||||
|
||||
`api-server` 容器镜像只构建 Linux release API 二进制,不构建 `spacetime-module`。当前 `api-server -> spacetime-client -> spacetimedb-sdk 2.4.1` 依赖链要求 Rust 1.93,因此 `deploy/container/api-server.Dockerfile` 的 Rust builder 固定为 `rust:1.93-bookworm`。如果本机 Docker Hub 拉取失败,可以先在本机准备同名本地 builder 镜像,但不要把临时 bootstrap 容器或私有 registry 凭据写入仓库。
|
||||
`api-server` 容器镜像只构建 Linux release API 二进制,不构建 `spacetime-module`。当前 `api-server -> spacetime-client -> spacetimedb-sdk 2.4.1` 依赖链要求 Rust 1.93,因此 `deploy/container/api-server.Dockerfile` 的 Rust builder 固定为 `rust:1.93-bookworm`。镜像构建阶段会同时复制 `public/`,用于满足 API 二进制里 `include_bytes!` 引用的内置素材;不要把 `public/generated-*` 放入镜像上下文。如果本机 Docker Hub 拉取失败,可以先在本机准备同名本地 builder 镜像,但不要把临时 bootstrap 容器或私有 registry 凭据写入仓库。
|
||||
|
||||
## 启动与验证
|
||||
|
||||
@@ -74,6 +76,7 @@ curl -sS http://127.0.0.1:18080/api/runtime/puzzle/gallery
|
||||
```bash
|
||||
npm run container:logs -- nginx
|
||||
npm run container:logs -- api-server
|
||||
npm run container:logs -- external-generation-worker
|
||||
npm run container:logs -- otelcol
|
||||
```
|
||||
|
||||
@@ -85,6 +88,73 @@ npm run container:config -- --print
|
||||
|
||||
如果 `deploy/container/api-server.env` 已写入真实 token,不要把完整展开结果贴到公开渠道。
|
||||
|
||||
动态扩缩容外部生成 worker 时,只调整 `external-generation-worker` service:
|
||||
|
||||
```bash
|
||||
npm run container:up -- --scale external-generation-worker=3 external-generation-worker
|
||||
npm run container:up -- --scale external-generation-worker=1 external-generation-worker
|
||||
```
|
||||
|
||||
动态扩缩容验证必须保持 `GENARRATIVE_EXTERNAL_GENERATION_MODE=queue`;`inline` 模式下生成请求由 `api-server` 同步执行,不会被这些 worker 实例消费。
|
||||
|
||||
### 外部生成 Worker 隔离 Smoke
|
||||
|
||||
如果只想在本机隔离验证 worker 模式,不复用 `deploy/container/api-server.env`,使用专用脚本:
|
||||
|
||||
```bash
|
||||
npm run container:worker-smoke -- smoke
|
||||
```
|
||||
|
||||
该脚本会生成 gitignored 的 `deploy/container/worker-smoke/api-server.env` 与端口 state,使用独立 compose project、独立 SpacetimeDB 数据卷和独立 host 端口,完成 `build -> up-spacetime -> publish -> up -> enqueue -> api-update -> enqueue`。测试 job 使用 `worker_smoke_unsupported` 类型,不访问真实 VectorEngine、LLM 或 OSS;预期结果是 worker 领取队列任务后按“不支持的任务类型”执行失败分支,从而验证队列 claim、lease、失败回写路径和 API / worker 进程隔离。`external_generation_job` 是 private table,脚本通过 worker 日志里的 job_id 和 unsupported 记录确认消费,不通过 CLI SQL 绕过权限。`smoke` 默认只启动 `api-server` 与 `external-generation-worker`,避免无关前端 / Nginx 镜像构建;需要同时验证 Nginx 时可分步执行 `up --with-nginx`。
|
||||
|
||||
分步排查时可执行:
|
||||
|
||||
```bash
|
||||
npm run container:worker-smoke -- init --force
|
||||
npm run container:worker-smoke -- build
|
||||
npm run container:worker-smoke -- up-spacetime
|
||||
npm run container:worker-smoke -- publish
|
||||
npm run container:worker-smoke -- up
|
||||
npm run container:worker-smoke -- enqueue before-update
|
||||
npm run container:worker-smoke -- api-update
|
||||
npm run container:worker-smoke -- enqueue after-update
|
||||
npm run container:worker-smoke -- status
|
||||
```
|
||||
|
||||
如果隔离端口或库数据需要重置:
|
||||
|
||||
```bash
|
||||
npm run container:worker-smoke -- smoke --force
|
||||
```
|
||||
|
||||
`container:worker-smoke` 默认会把本机 `spacetime` 2.4.1 CLI 打成轻量 SpacetimeDB 镜像,避免首次 smoke 必须拉取官方大镜像;普通 `npm run container:*` 压测仍默认使用 `clockworklabs/spacetime:v2.4.1`。如果 Docker build 阶段在容器内拉取 crates.io 依赖不稳定,可让容器内 Cargo 复用本机 Cargo 缓存构建当前二进制,再打入临时 smoke 镜像。该模式默认使用 `rust:1.93-bookworm` 作为 builder、Debian bookworm smoke runtime 承载构建产物;需要换 builder 镜像时设置 `GENARRATIVE_WORKER_SMOKE_CARGO_IMAGE`,需要换运行时基础镜像时设置 `GENARRATIVE_WORKER_SMOKE_LOCAL_BASE_IMAGE`:
|
||||
|
||||
```bash
|
||||
npm run container:worker-smoke -- smoke --local-binary
|
||||
```
|
||||
|
||||
`api-update` 只会 `--force-recreate api-server`,并校验 `external-generation-worker` 容器 ID 不变;如要同时重建 API 镜像,使用:
|
||||
|
||||
```bash
|
||||
npm run container:worker-smoke -- api-update --build
|
||||
```
|
||||
|
||||
验证 worker 动态扩缩容:
|
||||
|
||||
```bash
|
||||
npm run container:worker-smoke -- scale 3
|
||||
npm run container:worker-smoke -- ps
|
||||
npm run container:worker-smoke -- enqueue scaled-workers
|
||||
npm run container:worker-smoke -- scale 1
|
||||
```
|
||||
|
||||
查看或清理隔离环境:
|
||||
|
||||
```bash
|
||||
npm run container:worker-smoke -- logs external-generation-worker
|
||||
npm run container:worker-smoke -- down -v
|
||||
```
|
||||
|
||||
停止:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -2,6 +2,7 @@ FROM rust:1.93-bookworm AS rust-builder
|
||||
WORKDIR /workspace
|
||||
|
||||
COPY server-rs ./server-rs
|
||||
COPY public ./public
|
||||
RUN cargo build --release -p api-server --manifest-path server-rs/Cargo.toml && \
|
||||
cp server-rs/target/release/api-server /tmp/api-server
|
||||
|
||||
|
||||
@@ -8,6 +8,14 @@ GENARRATIVE_API_PORT=8082
|
||||
GENARRATIVE_API_LOG=info,tower_http=info
|
||||
GENARRATIVE_API_LISTEN_BACKLOG=1024
|
||||
GENARRATIVE_API_WORKER_THREADS=4
|
||||
# 容器 smoke 可临时设 all;压测或预发按 api / external-generation-worker 拆进程。
|
||||
GENARRATIVE_PROCESS_ROLE=api
|
||||
# 默认 queue 进入 external_generation_job;本地/小流量同步排查可显式设 inline。
|
||||
GENARRATIVE_EXTERNAL_GENERATION_MODE=queue
|
||||
GENARRATIVE_EXTERNAL_GENERATION_WORKER_ID=
|
||||
GENARRATIVE_EXTERNAL_GENERATION_WORKER_CONCURRENCY=2
|
||||
GENARRATIVE_EXTERNAL_GENERATION_WORKER_POLL_INTERVAL_MS=2000
|
||||
GENARRATIVE_EXTERNAL_GENERATION_WORKER_LEASE_SECONDS=3600
|
||||
GENARRATIVE_API_MAX_CONCURRENT_REQUESTS=512
|
||||
GENARRATIVE_API_GALLERY_MAX_CONCURRENT_REQUESTS=320
|
||||
GENARRATIVE_API_DETAIL_MAX_CONCURRENT_REQUESTS=64
|
||||
|
||||
@@ -2,7 +2,7 @@ name: genarrative-container-loadtest
|
||||
|
||||
services:
|
||||
spacetimedb:
|
||||
image: clockworklabs/spacetime:v2.4.1
|
||||
image: ${GENARRATIVE_CONTAINER_SPACETIME_IMAGE:-clockworklabs/spacetime:v2.4.1}
|
||||
user: root
|
||||
command:
|
||||
[
|
||||
@@ -44,7 +44,7 @@ services:
|
||||
cpus: "2.0"
|
||||
mem_limit: 1g
|
||||
env_file:
|
||||
- ./api-server.env
|
||||
- ${GENARRATIVE_CONTAINER_API_ENV_FILE:-./api-server.env}
|
||||
environment:
|
||||
GENARRATIVE_API_HOST: 0.0.0.0
|
||||
GENARRATIVE_API_PORT: 8082
|
||||
@@ -69,6 +69,32 @@ services:
|
||||
retries: 12
|
||||
start_period: 20s
|
||||
|
||||
external-generation-worker:
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: deploy/container/api-server.Dockerfile
|
||||
target: api-runtime
|
||||
cpus: "2.0"
|
||||
mem_limit: 1g
|
||||
env_file:
|
||||
- ${GENARRATIVE_CONTAINER_API_ENV_FILE:-./api-server.env}
|
||||
environment:
|
||||
GENARRATIVE_PROCESS_ROLE: external-generation-worker
|
||||
GENARRATIVE_TRACKING_OUTBOX_DIR: /var/lib/genarrative/tracking-outbox-worker
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://otelcol:4318
|
||||
OTEL_SERVICE_NAME: genarrative-external-generation-worker
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
ulimits:
|
||||
nofile:
|
||||
soft: 4096
|
||||
hard: 4096
|
||||
depends_on:
|
||||
spacetimedb:
|
||||
condition: service_healthy
|
||||
otelcol:
|
||||
condition: service_started
|
||||
|
||||
nginx:
|
||||
build:
|
||||
context: ../..
|
||||
|
||||
Vendored
+8
@@ -7,6 +7,14 @@ GENARRATIVE_API_PORT=8082
|
||||
GENARRATIVE_API_LOG=info,tower_http=info
|
||||
GENARRATIVE_API_LISTEN_BACKLOG=1024
|
||||
GENARRATIVE_API_WORKER_THREADS=4
|
||||
# api 只监听 HTTP;外部生成 worker 用独立进程设置为 external-generation-worker 后横向扩缩。
|
||||
GENARRATIVE_PROCESS_ROLE=api
|
||||
# 默认 queue 进入 external_generation_job;本地/小流量同步排查可显式设 inline。
|
||||
GENARRATIVE_EXTERNAL_GENERATION_MODE=queue
|
||||
GENARRATIVE_EXTERNAL_GENERATION_WORKER_ID=
|
||||
GENARRATIVE_EXTERNAL_GENERATION_WORKER_CONCURRENCY=2
|
||||
GENARRATIVE_EXTERNAL_GENERATION_WORKER_POLL_INTERVAL_MS=2000
|
||||
GENARRATIVE_EXTERNAL_GENERATION_WORKER_LEASE_SECONDS=3600
|
||||
GENARRATIVE_API_MAX_CONCURRENT_REQUESTS=512
|
||||
GENARRATIVE_API_GALLERY_MAX_CONCURRENT_REQUESTS=320
|
||||
GENARRATIVE_API_DETAIL_MAX_CONCURRENT_REQUESTS=64
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# 复制到 /etc/genarrative/external-generation-controller.env 后按机器容量调整。
|
||||
# controller 只管理 systemd worker 实例;SpacetimeDB、外部 provider 密钥继续复用 api-server.env。
|
||||
# systemd unit 会强制设置 GENARRATIVE_PROCESS_ROLE=external-generation-controller。
|
||||
|
||||
GENARRATIVE_EXTERNAL_GENERATION_CONTROLLER_MIN_WORKERS=1
|
||||
GENARRATIVE_EXTERNAL_GENERATION_CONTROLLER_MAX_WORKERS=8
|
||||
GENARRATIVE_EXTERNAL_GENERATION_CONTROLLER_TARGET_JOBS_PER_WORKER=2
|
||||
GENARRATIVE_EXTERNAL_GENERATION_CONTROLLER_POLL_INTERVAL_MS=10000
|
||||
GENARRATIVE_EXTERNAL_GENERATION_CONTROLLER_SCALE_DOWN_IDLE_ROUNDS=6
|
||||
GENARRATIVE_EXTERNAL_GENERATION_CONTROLLER_SERVICE_TEMPLATE=genarrative-external-generation-worker@{}.service
|
||||
GENARRATIVE_EXTERNAL_GENERATION_CONTROLLER_DRY_RUN=false
|
||||
GENARRATIVE_API_LOG=info,tower_http=info
|
||||
OTEL_SERVICE_NAME=genarrative-external-generation-controller
|
||||
@@ -0,0 +1,11 @@
|
||||
# 复制到 /etc/genarrative/external-generation-worker.env 后按机器容量调整。
|
||||
# 该文件只覆盖 worker 专属参数;SpacetimeDB、外部 provider 密钥继续复用 api-server.env。
|
||||
# systemd 模板会强制设置 GENARRATIVE_PROCESS_ROLE=external-generation-worker
|
||||
# 和 GENARRATIVE_EXTERNAL_GENERATION_WORKER_ID=%H-%i,避免多实例 ID 冲突。
|
||||
|
||||
GENARRATIVE_EXTERNAL_GENERATION_WORKER_CONCURRENCY=2
|
||||
GENARRATIVE_EXTERNAL_GENERATION_WORKER_POLL_INTERVAL_MS=2000
|
||||
# 单次 lease 会由 worker 自动续租;该值覆盖心跳抖动窗口即可。
|
||||
GENARRATIVE_EXTERNAL_GENERATION_WORKER_LEASE_SECONDS=3600
|
||||
GENARRATIVE_API_LOG=info,tower_http=info
|
||||
OTEL_SERVICE_NAME=genarrative-external-generation-worker
|
||||
@@ -0,0 +1,28 @@
|
||||
[Unit]
|
||||
Description=Genarrative External Generation Worker Controller
|
||||
After=network-online.target spacetimedb.service
|
||||
Wants=network-online.target
|
||||
Requires=spacetimedb.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=/opt/genarrative/current
|
||||
EnvironmentFile=/etc/genarrative/api-server.env
|
||||
EnvironmentFile=-/etc/genarrative/external-generation-controller.env
|
||||
Environment="LD_LIBRARY_PATH=/opt/genarrative/openssl-3.2.0/lib64:/opt/genarrative/openssl-3.2.0/lib"
|
||||
ExecStart=/usr/bin/env GENARRATIVE_PROCESS_ROLE=external-generation-controller GENARRATIVE_TRACKING_OUTBOX_DIR=/var/lib/genarrative/tracking-outbox/controller OTEL_SERVICE_NAME=genarrative-external-generation-controller /opt/genarrative/current/api-server
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
KillSignal=SIGINT
|
||||
TimeoutStopSec=120
|
||||
LimitNOFILE=65535
|
||||
TasksMax=512
|
||||
|
||||
# controller 需要调用 systemctl 管理 worker@N 实例,因此不降为 genarrative 用户。
|
||||
# 它只复用 api-server 发布包和 SpacetimeDB 配置,不直接执行外部生成任务。
|
||||
PrivateTmp=true
|
||||
ProtectSystem=full
|
||||
ReadWritePaths=/opt/genarrative /var/lib/genarrative
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,30 @@
|
||||
[Unit]
|
||||
Description=Genarrative External Generation Worker %i
|
||||
After=network-online.target spacetimedb.service
|
||||
Wants=network-online.target
|
||||
Requires=spacetimedb.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=genarrative
|
||||
Group=genarrative
|
||||
WorkingDirectory=/opt/genarrative/current
|
||||
EnvironmentFile=/etc/genarrative/api-server.env
|
||||
EnvironmentFile=-/etc/genarrative/external-generation-worker.env
|
||||
Environment="LD_LIBRARY_PATH=/opt/genarrative/openssl-3.2.0/lib64:/opt/genarrative/openssl-3.2.0/lib"
|
||||
ExecStart=/usr/bin/env GENARRATIVE_PROCESS_ROLE=external-generation-worker GENARRATIVE_EXTERNAL_GENERATION_WORKER_ID=%H-%i GENARRATIVE_TRACKING_OUTBOX_DIR=/var/lib/genarrative/tracking-outbox/%H-%i OTEL_SERVICE_NAME=genarrative-external-generation-worker /opt/genarrative/current/api-server
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
KillSignal=SIGINT
|
||||
TimeoutStopSec=7200
|
||||
LimitNOFILE=65535
|
||||
TasksMax=2048
|
||||
|
||||
# worker 复用 api-server 发布目录;外部生成审计与临时运行态只写服务端私有目录。
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=full
|
||||
ReadWritePaths=/opt/genarrative /var/lib/genarrative
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -21,6 +21,8 @@
|
||||
|
||||
微信小程序虚拟支付接入、`wechat_mp_virtual` 渠道、`wx.requestVirtualPayment` 承接页和后端签名配置见 [【技术方案】微信虚拟支付接入-2026-05-26.md](./%E3%80%90%E6%8A%80%E6%9C%AF%E6%96%B9%E6%A1%88%E3%80%91%E5%BE%AE%E4%BF%A1%E8%99%9A%E6%8B%9F%E6%94%AF%E4%BB%98%E6%8E%A5%E5%85%A5-2026-05-26.md)。
|
||||
|
||||
本地通过 SSH alias 管理多台服务器、查看硬件 / systemd / HTTP 健康状态并执行受控服务启停的 egui 桌面工具见 [【开发运维】本地SSH服务器管理面板技术方案-2026-06-11.md](./technical/【开发运维】本地SSH服务器管理面板技术方案-2026-06-11.md)。
|
||||
|
||||
生产部署切换到 systemd + Nginx + SpacetimeDB 自托管的总方案见 [PRODUCTION_DEPLOYMENT_PLAN_2026-05-02.md](./technical/PRODUCTION_DEPLOYMENT_PLAN_2026-05-02.md),该文档也是当前生产 Jenkinsfile 的唯一入口。Pingora 只作为独立二进制影子网关试点时,边界、路由口径与替换前验收见 [【开发运维】Pingora独立网关试点-2026-06-11.md](./technical/【开发运维】Pingora独立网关试点-2026-06-11.md)。SpacetimeDB 表结构变更、自动迁移边界和保留旧数据的分阶段迁移流程见 [SPACETIMEDB_SCHEMA_CHANGE_CONSTRAINTS.md](./technical/SPACETIMEDB_SCHEMA_CHANGE_CONSTRAINTS.md);private 表迁移 JSON 导入导出、HTTP 413 分片导入和旧数据库迁移流水线经验见 [SPACETIMEDB_JSON_STRING_MIGRATION_PROCEDURE_2026-04-27.md](./technical/SPACETIMEDB_JSON_STRING_MIGRATION_PROCEDURE_2026-04-27.md) 与 [JENKINS_SPACETIMEDB_DATABASE_MIGRATION_PIPELINES_2026-04-29.md](./technical/JENKINS_SPACETIMEDB_DATABASE_MIGRATION_PIPELINES_2026-04-29.md);后台管理独立前端工程技术方案见 [ADMIN_WEB_CONSOLE_TECHNICAL_SOLUTION_2026-04-30.md](./technical/ADMIN_WEB_CONSOLE_TECHNICAL_SOLUTION_2026-04-30.md)。
|
||||
|
||||
SpacetimeDB 表结构变更、自动迁移边界和保留旧数据的分阶段迁移流程见 [SPACETIMEDB_SCHEMA_CHANGE_CONSTRAINTS.md](./technical/SPACETIMEDB_SCHEMA_CHANGE_CONSTRAINTS.md)。
|
||||
@@ -83,6 +85,8 @@ RPG Agent 结果页发布门禁展示和预览来源 label 收口到 `src/compon
|
||||
|
||||
平台入口错误 / 完成弹窗的文案归一、来源格式、候选择一、dismiss key 与任务完成文案收口到 `src/components/platform-entry/platformDialogStateModel.ts`,规则见 [【前端架构】PlatformDialogStateModel收口计划-2026-06-03.md](./technical/【前端架构】PlatformDialogStateModel收口计划-2026-06-03.md)。
|
||||
|
||||
平台 UI Kit 的提示 / 确认弹窗收口到 `src/components/common/UnifiedConfirmDialog.tsx`,复制反馈收口到 `src/components/common/useCopyFeedback.ts`、`src/components/common/CopyFeedbackButton.tsx`、`src/components/common/CopyCodeButton.tsx` 与 `src/components/common/CopyFeedbackMessage.tsx`,基础状态提示收口到 `src/components/common/PlatformStatusMessage.tsx`,运行态短错误 / 成功 / 反馈 toast 收口到 `src/components/common/PlatformRuntimeStatusToast.tsx`,平台空态 / 轻量加载态收口到 `src/components/common/PlatformEmptyState.tsx`,平台动作按钮收口到 `src/components/common/PlatformActionButton.tsx`,平台白底子面板 / 小型列表卡片收口到 `src/components/common/PlatformSubpanel.tsx`,平台输入框 / 文本域收口到 `src/components/common/PlatformTextField.tsx`,平台字段标题收口到 `src/components/common/PlatformFieldLabel.tsx`,平台媒体预览框收口到 `src/components/common/PlatformMediaFrame.tsx`,平台胶囊状态标签收口到 `src/components/common/PlatformPillBadge.tsx`,平台图片全屏预览收口到 `src/components/common/PlatformImagePreviewModal.tsx`,平台 / 个人中心弹窗关闭按钮收口到 `src/components/common/PlatformModalCloseButton.tsx`,底层继续复用 `UnifiedModal`;普通提示、确认 / 取消、危险确认、复制状态机、短代码复制 chip、复制按钮表现、白底 / 个人中心 / 认证入口 token 状态条、运行态状态 toast、无操作空态、主动作按钮、白底子面板、白底交互列表卡片、普通输入字段、字段标题、图片源 / fallback / 固定比例媒体预览、全屏黑底图片查看、单个状态 / 标签 chip 和圆形关闭按钮优先使用公共 Module,规则见 [【前端架构】PlatformUiKit弹窗组件收口计划-2026-06-08.md](./technical/【前端架构】PlatformUiKit弹窗组件收口计划-2026-06-08.md)。
|
||||
|
||||
平台入口受保护数据失效后的 stage 去留判定,以及缺失草稿 / 作品 / run 时的阶段回退,收口到 `src/components/platform-entry/platformSelectionStageModel.ts`,壳层只执行缓存清空、布尔事实汇总和必要跳转,规则见 [【前端架构】PlatformSelectionStageModel收口计划-2026-06-04.md](./technical/【前端架构】PlatformSelectionStageModel收口计划-2026-06-04.md)。
|
||||
|
||||
小游戏 runtime client 的路径编码、JSON 请求、runtime guest auth 与 retry 选项收口到 `src/services/runtimeRequest.ts`,Match3D、SquareHole、Big Fish、Bark Battle、Puzzle 公开 / 推荐运行态请求、Jump Hop / Wooden Fish 正式 run 请求和 Visual Novel 局部 JSON runtime 请求已先迁移,规则见 [【前端架构】RuntimeClientFamily收口计划-2026-06-03.md](./technical/%E3%80%90%E5%89%8D%E7%AB%AF%E6%9E%B6%E6%9E%84%E3%80%91RuntimeClientFamily%E6%94%B6%E5%8F%A3%E8%AE%A1%E5%88%92-2026-06-03.md)。
|
||||
|
||||
@@ -9,5 +9,5 @@
|
||||
## 维护规则
|
||||
|
||||
- 计划文档只记录可执行阶段、负责人切分、验收门禁和当前状态。
|
||||
- 已经稳定为长期约定的内容,应同步沉淀到 `docs/【玩法创作】平台入口与玩法链路-2026-05-15.md` 或 `.hermes/shared-memory/`。
|
||||
- 已经稳定为长期约定的内容,应同步沉淀到 `docs/【玩法创作】平台入口与玩法链路-2026-05-15.md` 或 `docs/project-memory/shared-memory/`。
|
||||
- 若代码事实与计划冲突,以代码和当前融合文档为准,并回写更新本目录。
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user