diff --git a/README.md b/README.md index e905a7adf47..79e539112de 100644 --- a/README.md +++ b/README.md @@ -272,6 +272,8 @@ Full documentation is available at **[spacetimedb.com/docs](https://spacetimedb. SpacetimeDB is licensed under the [Business Source License 1.1 (BSL)](LICENSE.txt). It converts to the AGPL v3.0 with a linking exception after a few years. The linking exception means you are **not** required to open-source your own code if you use SpacetimeDB. You only need to contribute back changes to SpacetimeDB itself. +The [Rust client SDK](sdks/rust/LICENSE) and the [TypeScript client SDK and module library](crates/bindings-typescript/LICENSE.txt) are licensed under [Apache 2.0](licenses/apache2.txt), rather than the server's BSL. Check each component's license file for its terms. + **Why did we choose this license?** We chose to license SpacetimeDB under the MariaDB Business Source License for 4 years because we can't compete with AWS while also building our products for them. diff --git a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md index 430ffe98582..94eeac92eda 100644 --- a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md @@ -58,10 +58,12 @@ For TypeScript client bindings, `spacetime generate --lang typescript --import-e ### Client and Module Bindings -`spacetime generate --bindings client` (default) generates bindings for clients connecting to a database. `--bindings module` generates receiver bindings used inside a **sending database module** to call reducers in another **receiving database** through asynchronous IDC. Rust and TypeScript module bindings are supported; C#/C++ module bindings are not implemented yet. `unrealcpp` is client-only; `cpp` is accepted only in module mode. +`spacetime generate --bindings client` (default) generates bindings for clients connecting to a database. `--bindings module` generates receiver bindings used inside a **sending database module** to call reducers in another **receiving database** through asynchronous IDC. Rust, TypeScript, and C# module bindings are supported; C++ module bindings are not implemented yet. `unrealcpp` is client-only; `cpp` is accepted only in module mode. In `spacetime.json`, each sending database's non-inherited `dependencies` array requires its own `module-path` and dependency `name` plus receiving-module `module-path` or `database`. A `database` reference resolves another target's local source/build settings in the same config; it does not fetch a running database's schema. A direct receiving module source takes precedence. Dependencies do not themselves publish receiving databases or inherit the sending module's build settings. `generate ` processes both its regular `generate` entries (client bindings by default) and `dependencies` (module bindings automatically); no `--bindings` flag or second `generate` entry is needed for a dependency. For dependencies, module binding language defaults to the sending module's language and Rust/TypeScript output defaults to `/src/remote_bindings`. Explicit config `out-dir` is config-relative. A regular `generate` entry can select `"bindings": "module"`, but does not use dependency language or output defaults. The CLI `--bindings` override is allowed only when a single generation entry is selected. +C# dependency output defaults to `/remote_bindings/`, with namespace `RemoteBindings.`. Set `namespace` on that dependency to override it. Direct `--bindings module --lang csharp` generation without a dependency name defaults to `RemoteBindings`; client bindings still default to `SpacetimeDB.Types`. `--namespace` overrides the C# namespace. In a module-bindings namespace, later segments cannot be `System`, `SpacetimeDB`, or the first segment: for example, `RemoteBindings.System` is rejected. + `dev` generates only root dependencies before building the sending module, and watches their source paths. Child targets are available for source lookup, not recursive dependency generation. `--skip-generate` skips receiver/client generation and receiver-only watching; `--skip-publish` does not. See https://spacetimedb.com/docs/cli-reference/spacetime-json#receiver-dependencies for examples. ### C# Build Modes @@ -75,12 +77,16 @@ Use `spacetime init --lang csharp --dotnet-version 10 my-project` to select Do not make the project permanently WASM-only to fix a managed build: keep LLVM package references and WASM settings conditional on the RID. Let dotnet restore -when changing build modes. Managed builds alone do not enable C# module unit tests. +when changing build modes. Managed builds alone do not enable C# module unit tests: +use a separate .NET 10 test project with the matching `SpacetimeDB.Testing` +package and a supported native platform, as described in the C# server skill. .NET 8 retains WASM/JIT by default and requires `--native-aot` to select NativeAOT where supported. The CLI manages `SPACETIMEDB_WASM_AOT` and its legacy alias `EXPERIMENTAL_WASM_AOT`; users do not need to set either for .NET 10. +New databases receive a server-allocated identity; a supplied identity can update an existing database, not create one. Only the registered name owner can recreate a deleted database whose name remains registered. + ### Publishing & Deployment ```bash @@ -180,6 +186,10 @@ spacetime server clear ### Authentication +Log in with `spacetime login` before publishing, including to local servers. Without a saved login, the browser-login prompt defaults to yes; declining it shows a server-issued identity warning and a second prompt that defaults to no. A server-issued identity works only on its issuing server, owns databases published with it, and cannot be recovered if its token is lost. A later `spacetime login` replaces that saved token. + +`--yes` / `--yes=skip-login` and closed stdin can still create a server-issued identity for compatibility; they do not authenticate you with spacetimedb.com. Do not use them to bypass login setup for unattended publishing. Alert the user before intentionally creating a server-issued identity. + ```bash # Login (opens browser) spacetime login diff --git a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md index db3852e4264..d191c9731f4 100644 --- a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md @@ -36,8 +36,9 @@ This describes Spacetime 2.x. The API changed substantially from 1.x, so older a - **Access control.** Tables are private by default. Views expose exactly the rows and columns each client should see, including per-caller views filtered by the caller's identity. ([Access permissions](https://spacetimedb.com/docs/tables/access-permissions/)) - **Auth.** Spacetime works with any OIDC provider, such as Auth0, Clerk, Better Auth, or Firebase Auth. SpacetimeAuth is a first-party provider with magic links, social logins, and user and role management. ([Authentication](https://spacetimedb.com/docs/core-concepts/authentication/)) - **Scheduled work.** Schedule tables run reducers or procedures at a specific time or on a repeating interval. In TypeScript, the Cron module adds calendar schedules with time zones. ([Schedule tables](https://spacetimedb.com/docs/tables/schedule-tables/), [Cron module](https://spacetimedb.com/modules/cron)) +- **Payments.** The TypeScript Stripe module supplies Checkout, billing portal, subscription, and signed-webhook helpers. The host application authenticates users and controls ownership and prices. Fulfill purchases from verified webhook payment state, not the browser redirect. ([Stripe module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts)) - **Ephemeral events.** Event tables broadcast rows to subscribers without storing them, for things like typing indicators. ([Event tables](https://spacetimedb.com/docs/tables/event-tables/)) -- **Files.** Files can be stored as bytes in table columns, or a procedure can store large files in S3 or a similar service and keep a reference in a table. In TypeScript, the Files module handles uploads, listing and download routes. ([File storage](https://spacetimedb.com/docs/tables/file-storage/), [Files module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts)) +- **Files.** Files can be stored as bytes in table columns, or a procedure can store large files in S3 or a similar service and keep a reference in a table. In TypeScript, the Files module handles database-backed uploads, listing and download routes; the S3 module keeps bytes in a private bucket and tracks ownership and upload state in the database. ([File storage](https://spacetimedb.com/docs/tables/file-storage/), [Files module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts), [S3 module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts)) - **SQL and tools.** Spacetime speaks the PostgreSQL wire protocol, so PostgreSQL drivers, `psql`, and GUI clients can connect. ([PostgreSQL wire protocol](https://spacetimedb.com/docs/how-to/pg-wire/)) - **Dashboard.** On Maincloud, each database's dashboard on spacetimedb.com lets you browse, filter, edit, delete, and export table rows, call reducers, and view logs and metrics. ([Maincloud dashboard](https://spacetimedb.com/docs/how-to/deploy/maincloud/#viewing-your-database-on-the-web-dashboard)) - **Schema changes.** Compatible changes, such as adding tables or columns with defaults, migrate automatically when you republish, and incremental migrations handle the rest. ([Automatic migrations](https://spacetimedb.com/docs/databases/automatic-migrations/)) @@ -79,6 +80,10 @@ For questions about older articles, benchmarks, or past reviews, see [Common mis 4. Check server logs for errors (`spacetime logs `) 5. Is the reducer actually being called from the client? +A per-call CPU-budget abort in a reducer or view produces an error-level database log containing `reached the maximum CPU usage allowed per call`, with the function name and elapsed duration, on servers containing that logging change. Check it as the database owner with `spacetime logs --level error `; this message does not by itself mean the account balance is empty. ([Logging](https://spacetimedb.com/docs/how-to/logging/#diagnosing-cpu-budget-aborts)) + +For self-hosted server version changes, stop the service and back up the data directory. The updated `metadata.toml` startup check requires the same edition and, within one major version, a running minor at least as new as recorded; it ignores patch differences and minor/patch prerelease suffixes. A running `X.0.0-*` major prerelease requires an identical recorded version, except that the 1.x-data-to-2.x-server exception is checked first. The restriction is on the running version, not on a previously recorded major prerelease. The recorded version never decreases. Do not edit generated metadata to bypass the check or treat passing it as a blanket rollback guarantee. ([Version compatibility](https://spacetimedb.com/docs/how-to/deploy/self-hosting/#data-directory-version-compatibility)) + --- ## Tables @@ -134,6 +139,10 @@ Server-side modules can be written in: Rust, C#, TypeScript, C++ Lifecycle: Write → Compile → Publish (`spacetime publish`) → Hot-swap (republish without disconnecting clients) +Scheduled functions are private, but the database owner can still call them directly. To restrict a callback to scheduler execution, compare the sender with the database identity; see the server skills for language-specific syntax. + +Outbound HTTP requests from procedures default to a 30-second timeout when none is specified; the host clamps requested timeouts to a maximum of 180 seconds. See [procedure HTTP requests](https://spacetimedb.com/docs/functions/procedures#http-requests) and the language-specific server skills for request syntax. + ## HTTP Handlers A module can expose its own HTTP API. Each handler takes a request and returns a response, and one router per module binds handlers to a method and path. Requests reach them under `/v1/database//route`, so a `/say-hello` route is served at `/v1/database/my-db/route/say-hello`. @@ -144,6 +153,12 @@ A module can expose its own HTTP API. Each handler takes a request and returns a Use HTTP handlers for webhooks and for clients that can't use a SpacetimeDB SDK. See the language-specific server skills for syntax. +## Table Storage Policies + +Tables default to keeping pages and blobs resident in memory. A cache policy can permit eviction to local disk (`required_on_disk`) or any configured tier (`no_requirement`), including remote object storage. It does not configure a backend or force eviction; actual eviction depends on server tiers and memory budgets. Any indexes on tables with non-default policies must be B-trees. The standalone server currently uses an unlimited resident-memory budget. Change a policy by republishing without deleting data; moving back to the in-memory policy requires enough memory to load and retain the table. See https://spacetimedb.com/docs/tables/storage-and-cache-policies and the language-specific table options. + +Recovery temporarily suspends the storage engine's resident-memory hard limit, then re-enables it and attempts eviction before serving transactions. Required-in-memory data can leave usage above budget, so later operations can still fail for lack of memory. This does not bypass process or physical memory limits. See [storage recovery](https://spacetimedb.com/docs/tables/storage-and-cache-policies/#residency-durability-and-performance). + ## Reusable Modules and Configuration TypeScript and C# support same-language submodule composition. A namespace has a language accessor and a canonical database name; SQL, CLI calls, and HTTP calls use the canonical name. Changing the canonical namespace drops its tables and their data, so pin it when renaming an accessor. TypeScript supports nested submodules; C# composition requires 2.13+ with .NET 10/C# 14, and nested or repeated C# mounts require 2.14+. See the respective server skills for registration and helper-context rules. @@ -154,13 +169,17 @@ Database environment values are read-only strings, including secrets, supplied a Views can accept arguments in 2.13+ (Rust, TypeScript, C#), queried as `SELECT * FROM view_name(42)`. Use explicit queries instead of subscribe-all on that connection; subscribe-all skips these views. See server skills for definition restrictions and client skills for query/cache rules. -Rust and TypeScript provide in-memory module unit-test harnesses in 2.12+: run native `cargo test` or Vitest with the module-test plugin. These use the real datastore but do not simulate clients, subscriptions, RLS enforcement, lifecycle events, or timer execution. Test those host behaviors against a running database. +Rust and TypeScript provide in-memory module unit-test harnesses in 2.12+: run native `cargo test` or Vitest with the module-test plugin. C# also provides a managed .NET 10 harness via the separate `SpacetimeDB.Testing` package; see the C# server skill for platform and package requirements. These use the real datastore but do not simulate clients, subscriptions, RLS enforcement, lifecycle events, or timer execution. Test those host behaviors against a running database. ## Inter-Database Communication Reducers can't make network requests, but a reducer can call a reducer in another database on the same server through an **outbox table** (async IDC). The reducer inserts a row, and after its transaction commits, the row is delivered as a reducer call to the target database exactly once, in order with other calls through the same outbox to the same database. The sending reducer doesn't wait, and the two databases don't commit together: the receiving reducer runs later in its own transaction and can fail. An optional `on_result` reducer in the sending database receives the result, so it can undo or record the work. -Use it to split an application into databases that scale and deploy independently, such as a lobby that sends players to separate game world databases. Only Rust and TypeScript modules can declare outbox tables. See the language-specific server skills for syntax. +Deliveries can be pipelined. Receiving calls and `on_result` callbacks each retain stream order, but a later receiving call need not wait for an earlier callback in the sending database. Do not use callbacks as barriers for subsequent receiving calls. + +Outbox rows are insert-only for module code. The host removes them after delivery and the optional result callback; do not update or delete pending rows yourself. + +Use it to split an application into databases that scale and deploy independently, such as a lobby that sends players to separate game world databases. Rust, TypeScript, and C# modules can declare outbox tables. See the language-specific server skills for syntax. ## Identity diff --git a/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md index 4ab3ca89ee5..c3d51a28dfc 100644 --- a/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md @@ -17,10 +17,14 @@ metadata: Module unit tests use a sibling .NET 10 test project with an ordinary module `ProjectReference` and the separate `SpacetimeDB.Testing` NuGet package, at exactly -the module's Runtime version. Run with `dotnet test`; no server or Rust compiler +the module's Runtime version, from a release publishing both packages. Native +libraries support Linux x64/ARM64 (glibc 2.35+) and Windows x64, not macOS. +Run with `dotnet test`; no server or Rust compiler is required. Keep Testing out of module dependencies and test sources outside the module directory. Use `using var test = ModuleTestContext.Create(typeof(Module).Assembly)` -and `test.WithReducerTx(TestAuth.Internal(), ctx => Module.Reducer(ctx))`. +and, for the module below, +`test.WithReducerTx(TestAuth.Internal(), ctx => Module.AddRecord(ctx, 1))` +with `using SpacetimeDB.Testing;` in the test project. Callbacks are synchronous; one fixture supports one execution flow, while separate fixtures may run in parallel. The chat-console-cs template includes tests for .NET 10 only. See `/how-to/unit-testing` for setup and release availability. @@ -57,6 +61,8 @@ spacetime build # CLI selects WASM automatically assemblies. .NET 10 composition uses generated assembly descriptors, not the dependency's standalone WASM exports; no special root/library build flag is needed. +Table attributes also accept `CachePolicy = TableCachePolicy.RequiredInMemory` (default), `TableCachePolicy.RequiredOnDisk`, or `TableCachePolicy.NoRequirement`. See the concepts skill for storage semantics and index restrictions. + ## Module Structure Reducers are static methods in a `static partial class`; tables are `public partial struct`s. This reference keeps everything in one `public static partial class Module`, which needs only `using SpacetimeDB;`: @@ -137,7 +143,7 @@ The complete set of column attributes: [PrimaryKey] // primary key [AutoInc] // auto-increment (use 0 as placeholder on insert) [Unique] // unique constraint; indexes the column, enables .Find() -[SpacetimeDB.Index.BTree] // btree index (enables .Filter() on this column) +[SpacetimeDB.Index.BTree] // non-unique btree index enables .Filter() [Default(true)] // migration-safe default for a newly appended field ``` @@ -161,6 +167,8 @@ public partial struct Membership { public ulong GroupId; public Identity UserId; Prefer a multi-column index over filtering by one column and looping. +A declared single-column B-tree index on a `[Unique]` or `[PrimaryKey]` column is that column's unique index, not a second non-unique index. Its declared `Accessor` is the only accessor and supports `Find`/`Update`/`Delete`, not `Filter`. For example, declaring `Accessor = "ById"` on the `Id` primary-key column changes calls from `.Id.Find(id)` to `.ById.Find(id)`. Remove the redundant index attribute to retain the column-named accessor. Do not change an unconstrained column's `Filter` calls to `Find`. + ## Reducers ```csharp @@ -206,7 +214,7 @@ public static void ClientConnected(ReducerContext ctx) { ... } public static void ClientDisconnected(ReducerContext ctx) { ... } ``` -Reducer and procedure method names must not start with `On`, `on`, or `__`; the code generator rejects them (STDB0010), so name lifecycle reducers `ClientConnected`, not `OnConnect`. +Ordinary reducer and procedure method names must not start with `On`, `on`, or `__`; the code generator rejects them (STDB0010), so name lifecycle reducers `ClientConnected`, not `OnConnect`. A reducer marked `[OnResult]` may start with `On` or `on`, but not `__`. `ctx.ConnectionId` is `ConnectionId?`, including in connection lifecycle reducers. Check or unwrap it before storing it in a non-nullable column or passing it to an index accessor. @@ -303,6 +311,16 @@ The marker is any accessible type in the dependency assembly. Root code uses `ct In 2.14+, any module can mount its own dependencies, and the same assembly can be mounted more than once with independent tables at each path; 2.13 allows only root mounts, once per assembly. Cross-language composition is unsupported. Named dependencies cannot declare lifecycle reducers, nonempty environments, or RLS filters. Define RLS in the root with canonical qualified table names. Named-submodule routes are ignored; root handlers may delegate to library helpers. Dependencies in `public` can contribute lifecycle reducers (subject to uniqueness), environment declarations, and routes. +## Inter-Database Communication + +Generate C# receiver bindings with `spacetime generate --bindings module --lang csharp`, or use the sending module's `dependencies` in `spacetime.json` (see the CLI skill). For a dependency named `game_world`, the default namespace is `RemoteBindings.GameWorld`; import it as `using Gw = RemoteBindings.GameWorld;`. This is independent-database messaging, not assembly composition. + +For a receiver reducer `admit_player(name: string)`, `[Outbox(typeof(Gw.Reducers.AdmitPlayer), Accessor = "AdmitPlayerOutbox")]` on an empty `public partial struct AdmitPlayerOutbox` generates `MsgId`, `Target` (a `Gw.Identity`), and `Name`. Insert through `ctx.Db.AdmitPlayerOutbox.Insert(...)` inside a reducer, with `MsgId = 0` for automatic allocation. Use the generated receiver identity type, not an unwrapped `SpacetimeDB.Identity`. + +Alternatively, declare `[Table(Accessor = "AdmitPlayerOutbox", Outbox = typeof(Gw.Reducers.AdmitPlayer))]` with a `ulong` `[PrimaryKey, AutoInc]` field, exactly one `[Target]` field of type `Gw.Identity`, and matching parameter fields. Field names map to receiver parameters in snake_case; `[Param("name")]` maps a differently named field to the canonical `name` parameter. Additional fields are local callback metadata. Use the manual form if receiver parameters collide with shorthand's `msg_id` or `target`. Outboxes must be in the root assembly, not a referenced library; they cannot also be event or scheduled tables. + +Apply both `[Reducer]` and `[OnResult(typeof(AdmitPlayerOutbox))]` to a `public static void` method with parameters `(ReducerContext ctx, AdmitPlayerOutbox row, Result result)`. Match errors as `Result.ErrR(var error)`. If a row type has several outboxes, select one with `Table = "AccessorName"` on `[OnResult]`; `[Target]` and `[Param]` also accept `Table`. The callback is private: only the host, database owner, and team collaborators can run it, not ordinary clients. See the concepts skill for delivery/transaction guarantees and `/databases/inter-database-communication` for the complete receiver, sender, and callback example. + ## Environment Variables ```csharp @@ -432,6 +450,8 @@ public enum Status { Online, Away, Offline } public partial struct Point { public float X; public float Y; } ``` +`[SpacetimeDB.Type(Name = "game_world.Point")]` overrides a custom type's canonical schema name without renaming the C# type. The runtime accepts `.` or `::` between scope segments. C# receiver bindings use dependency-scoped type names to keep types from different receivers distinct; preserve their generated `Type(Name = ...)` attributes rather than editing generated files. + Tagged enums (discriminated unions): a `partial record` with empty body and no constructor parameters. Payloads are `[Type] partial struct`s: ```csharp diff --git a/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md index c2e69876968..ff8114750e8 100644 --- a/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md @@ -42,7 +42,7 @@ pub struct Entity { } ``` -Options: `accessor = snake_case` (required), `public`, `scheduled(reducer_fn)`, `index(...)` +Options: `accessor = snake_case` (required), `public`, `scheduled(reducer_fn)`, `index(...)`, `cache_policy = required_in_memory | required_on_disk | no_requirement` (default: `required_in_memory`; see the concepts skill for storage semantics). `ctx.db` accessors use the `accessor` name (snake_case). @@ -292,7 +292,7 @@ Construct a connection ID from a numeric representation with `ConnectionId::from A reducer calls a reducer in another database by inserting a row into an outbox table. The call is sent only if the transaction commits, runs exactly once, and runs in order with other calls through the same outbox to the same database. The sending reducer doesn't wait for it. Both databases must be on the same server. -Generate receiver bindings by listing the receiving module under `dependencies` in the sending database's `spacetime.json`, then running `spacetime generate `. Rust bindings are written to `src/remote_bindings/`. +Generate receiver bindings by listing the receiving module under `dependencies` in the sending database's `spacetime.json`, then running `spacetime generate `. Rust bindings are written to `src/remote_bindings/`, with `mod.rs` roots. Regenerate older bindings and remove obsolete `lib.rs` path overrides. With `game_world` imported as a module identifier, `spacetimedb::outbox!(game_world::admit_player);` generates `AdmitPlayerOutbox` with `msg_id`, `target`, and the reducer argument columns. Optional `accessor = custom_outbox` and `name = "custom_outbox"` override table names. Use a manual table (below) for extra columns, reducer arguments named `msg_id` or `target`, or multiple outboxes for the same reducer. ```json { diff --git a/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md index a232086ad3a..914adaea413 100644 --- a/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md @@ -17,6 +17,8 @@ Generated bindings convert snake_case names to camelCase, including row fields: The examples below use bundler-style extensionless imports. For NodeNext or direct-TypeScript execution, choose the matching binding import extension and use explicit file imports in your application; see https://spacetimedb.com/docs/clients/typescript#import-extensions. +`withUri` takes the server base URI, not a subscription endpoint. It preserves a path prefix: `wss://example.com/stdb` (or `/stdb/`) uses `/stdb/v1/database//subscribe` and the HTTPS token-exchange endpoint `/stdb/v1/identity/websocket-token`. A reverse proxy must forward both endpoints, stripping its prefix when forwarding to a root-mounted server. + ## React: main.tsx ```typescript @@ -164,6 +166,8 @@ conn.subscriptionBuilder().subscribe('SELECT * FROM by_id(42)'); Use explicit queries for every table on that connection, not subscribe-all, which skips views with arguments. Only `SELECT * FROM view_name(literal_args)` is supported. All argument values share one cache table; unsubscribe from obsolete arguments to avoid combining their rows. Validate/encode dynamic values as SQL literals rather than concatenating untrusted input. In React, raw SQL subscriptions need explicit lifetime management and cleanup; `useTable` does not supply an argument-bearing view builder. +A server message that cannot be decoded or applied ends the connection without automatic retry: errors go to `onConnectError` before establishment or `onDisconnect` afterwards. Synchronous exceptions thrown by user callbacks are logged without preventing other callbacks from running. TypeScript SDKs containing the row-boundary decoding fix (#6091) can read rows with appended table columns using older generated bindings; removing, reordering, or changing existing column types is not. Regenerate bindings to access added columns. + ## Automatic Reconnect and Token Refresh The React provider's connection manager enables automatic reconnect; the explicit `.withAutomaticReconnect()` above also shows the setting to use for direct connections. Without it, a direct connection does not recover automatically. For direct connections, initial failures are not retried. After an established connection drops, retries use exponential backoff and jitter from `minDelayMs` (default 1 s) up to `maxDelayMs` (default 30 s), until `disconnect()` or a terminal failure. Tune these with `.withAutomaticReconnect({ minDelayMs, maxDelayMs })`; values below the 500 ms and 1 s floors are raised with a warning, so that retrying clients cannot overwhelm the database. While mounted, the React provider also preserves its separate connection-manager retries: it builds a replacement connection after an initial or terminal failure that the core connection will not retry. It respects an explicit `disconnect()`. diff --git a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md index d3348b5a04d..18f2987af7d 100644 --- a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md @@ -13,6 +13,10 @@ metadata: # SpacetimeDB TypeScript SDK Reference +## Runtime Memory + +V8's module memory limit includes `ArrayBuffer` allocations (and typed-array backing buffers), not just ordinary JavaScript objects. Limit peak buffer allocations and copies. This is separate from the storage engine's resident-memory budget; changing table cache policies does not increase the V8 limit. + ## Module Structure Tables are built with `table()`, bound with `schema()`, and exported as default. Reducers and lifecycle hooks are `export const`: @@ -72,7 +76,7 @@ const entity = table( ); ``` -Options: `name` (snake_case, recommended), `public: true`, `event: true`, `indexes: [...]` +Options: `name` (snake_case, recommended), `public: true`, `event: true`, `indexes: [...]`, `cachePolicy: 'required_in_memory' | 'required_on_disk' | 'no_requirement'` (default: `required_in_memory`; see the concepts skill for storage semantics). `ctx.db` accessors are the keys passed to `schema({...})`, verbatim: `schema({ scoreRecord })` -> `ctx.db.scoreRecord`. Keep TypeScript identifiers and accessors camelCase. Use explicit `name: 'snake_case'` strings when you need a canonical database name that differs from the TypeScript identifier. @@ -279,8 +283,18 @@ export default spacetimedb; `myAuth` is the accessor (`ctx.db.myAuth.`); `auth_data` is the canonical namespace used in SQL and wire names. Without an explicit `name`, the root's case policy derives it (`myAuth` → `my_auth` by default). Pin `name` when renaming an accessor: changing the canonical namespace drops its tables and their data. The library keeps its own flat `ctx.db` accessors. To call a library function directly, pass `ctx.as.myAuth`; inside `withTx`, use `tx.as.myAuth`. Nested TypeScript submodules are supported. Lifecycle reducers and nonempty environment declarations belong in the root. Submodule routers are ignored; register delegated handlers on the root router. Composition is not cross-language. +Inside a submodule view, `ctx.from` also uses the library's local schema keys. For `schema({ sessions })` where the table declares `name: 'auth_sessions'`, return `ctx.from.sessions`, not `ctx.from.auth_sessions` or a consumer namespace prefix. Mount qualification is automatic, including explicitly named tables. Raw SQL uses the full canonical path; never mix an accessor namespace with a canonical table name. See the [submodule view example](https://spacetimedb.com/docs/modules#accessor-and-canonical-namespace-names). + Official reusable libraries include `@spacetimedb/cron`, `@spacetimedb/retry`, `@spacetimedb/rate-limit`, and `@spacetimedb/crypto`. Their registration shapes differ: `@spacetimedb/rate-limit/submodule` is mountable, cron/retry expose factories, and crypto exports helpers. Consult the chosen package's README/exports rather than assuming every package root is a mountable module. +Additional mountable packages include `@spacetimedb/auth/submodule` (application-managed sign-in and sessions, distinct from hosted SpacetimeAuth), `@spacetimedb/agents/submodule` (conversations/model calls), and `@spacetimedb/files/submodule` (database-backed files). Auth and Agents require root initialization via `install(ctx.as.auth)` / `install(ctx.as.agents)`. Auth HTTP handlers must be delegated from the root router; configure its signing key first. Agents hosts must authenticate callers, derive owners from trusted state, and enforce quotas before paid model calls. Files helpers accept `ctx.as.files` from reducers or `tx.as.files` inside `withTx`. These libraries require SDK/CLI/server 2.12+. Follow the [package integration guides](https://spacetimedb.com/docs/modules#reusable-typescript-packages) for exact exports and initialization rather than assuming all packages share an `install` API. + +For large external files, `@spacetimedb/s3/submodule` supplies the private state tables; `@spacetimedb/s3` supplies `client` and `s3Tick`. Declare AWS credentials on the root environment, construct a client with `client(options)`, call its `initialize(tx)` method during initialization, and schedule its `reconcile(ctx, credentials)` method in a procedure. Derive owners on the server. The [S3 guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts) specifies bucket constraints and reconciliation behavior; restoring an old database can remove newer S3 objects under its dedicated prefix. + +For server-side PostHog analytics, mount `@spacetimedb/posthog/submodule` in the root schema, then call `posthog.install(ctx.as.posthog)` from the root init reducer. After the host reducer's authorization and state change, call `posthog.enqueueEventInTx(ctx.as.posthog, args)` to queue an event in that same transaction; it does not make a network request. Use `tx.as.posthog` inside a procedure's `withTx`, not the procedure context. An administrator must configure the provider before scheduled delivery can send events. See the [package integration guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-posthog-ts#integrate-into-an-application) for its exact schema, imports, arguments, and delivery semantics. + +For Stripe billing, mount `@spacetimedb/stripe/submodule`, call `stripe.install(ctx.as.stripe)` from the root init reducer, and configure credentials as an administrator. Register a root HTTP handler that calls `stripe.handleStripeWebhook(ctx, req, { stripe: tx => tx.as.stripe })`; the selector receives the host transaction. Call network helpers such as `stripe.createUserCheckoutSession(ctx.as.stripe, args)` from a procedure, outside `withTx`. Derive `userId`, catalog prices, and return URLs from trusted application context; helpers do not authenticate callers. An optional synchronous `onEvent(tx, event)` callback writes fulfillment records in the same transaction as the webhook state; validate event fields and deduplicate by business-object ID, not only event ID. See the [exact integration schema and fulfillment rules](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts#integrate-into-an-application). + ## Environment Variables ```typescript @@ -494,7 +508,7 @@ Handlers are synchronous: return `SyncResponse` directly rather than marking the ## Module Unit Tests -Use `spacetimedb` 2.12+ and Node.js 22+ in the **module** project, not the client. Set `"type": "module"` in `package.json` and install the test runner with `npm install --save-dev vitest@^3.2.4`. Configure the host-import replacement: +Use `spacetimedb` 2.12+ and a supported Node.js release (22.23.4+, 24.22.1+, or 26.12.1+ on those release lines) in the **module** project, not the client. Set `"type": "module"` in `package.json` and install the test runner with `npm install --save-dev vitest@^3.2.4`. Configure the host-import replacement: ```typescript // vitest.config.ts @@ -522,4 +536,4 @@ it('inserts a record', () => { }); ``` -Run `npx vitest run`. Create a fresh harness per test. `withReducerTx` commits on normal return and rolls back/rethrows on exceptions; do not catch a failure inside the transaction if rollback is expected. Callbacks must be synchronous. Use `TestAuth.fromJwtPayload(JSON.stringify({ iss: 'test', sub: 'alice' }), connectionId)` for client authorization tests; internal auth represents the database, not a client or the publisher. The harness exposes `clock`, `rng`, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or scheduling; invoke lifecycle/scheduled reducers explicitly and retain live integration tests for those host behaviors. +Run `npx vitest run`. Create a fresh harness per test. `withReducerTx` commits on normal return and rolls back/rethrows on exceptions; do not catch a failure inside the transaction if rollback is expected. Callbacks must be synchronous. Use `TestAuth.fromJwtPayload(JSON.stringify({ iss: 'test', sub: 'alice' }), connectionId)` for client authorization tests; internal auth represents the database, not a client or the publisher. The harness exposes `clock`, `rng`, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or scheduling; invoke lifecycle/scheduled reducers explicitly and retain live integration tests for those host behaviors. It does not currently supply namespaced `ctx.as` / `tx.as` helper contexts for mounted submodules; test those integrations against a running database. diff --git a/codex-plugin/plugins/spacetimedb/skills/unreal/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/unreal/SKILL.md index b30759ca5e2..144dfaef4b4 100644 --- a/codex-plugin/plugins/spacetimedb/skills/unreal/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/unreal/SKILL.md @@ -153,7 +153,7 @@ void AGameManager::EndPlay(const EEndPlayReason::Type EndPlayReason) void AGameManager::Tick(float DeltaTime) { - if (Conn && Conn->IsActive()) + if (Conn) // Keep ticking during automatic recovery, too. { Conn->FrameTick(); } @@ -222,6 +222,18 @@ Save the `Token` for future reconnection. The `Identity` is the user's persisten --- +## Automatic Reconnect and Token Refresh + +Automatic reconnect is opt-in: add `->WithAutomaticReconnect()` to the builder. Regenerate bindings to get the reconnect methods. Initial connection failures are not retried; after an established connection drops, retries continue with exponential backoff and jitter. Configure `FAutomaticReconnectOptions.MinDelaySeconds` (default 1) and `MaxDelaySeconds` (default 30) with `->WithAutomaticReconnectOptions(Options)`; the effective floors are 0.5 and 1 second. `Disconnect()` cancels recovery. Keep `FrameTick()` running even when `IsActive()` is false; `IsReconnecting()` reports recovery in progress. + +`OnConnect` runs once. `OnAutomaticReconnect` takes the same `FOnConnectDelegate` and runs after recovery, before subscription replay; use it to save the new token. Register subscriptions and row callbacks once, not on every recovery or `OnApplied`: subscriptions replay atomically, their `OnApplied` callbacks run again, and unchanged rows do not fire row callbacks. Cached rows remain readable but stale until reconciliation. + +Existing disconnect/error delegates keep their signatures. `OnDisconnectWithReconnect` and `OnConnectErrorWithReconnect` additionally receive `bWillReconnect`, `NextReconnectAttempt`, and `NextReconnectDelaySeconds`. Do not create a replacement connection while a retry is pending. Calls are never replayed: interrupted calls may have executed and report `UnknownResult`; calls during recovery report `Disconnected`. + +For expiring credentials, use `WithToken` for the initial token and `WithTokenProvider` for recovery. Its `FTokenProviderDelegate` receives `UReconnectTokenRequest*`; complete it asynchronously with `Request->Complete(NewToken, FString())` or an empty token and an error. Tokens must retain the original identity. Provider failures retry; rejection of a fresh token is terminal. The server must support session replacement and batch subscriptions. See https://spacetimedb.com/docs/clients/unreal#method-withautomaticreconnect. + +--- + ## Subscribing to Tables After connecting, subscribe to receive table data: @@ -304,7 +316,7 @@ UFUNCTION() void OnUserUpdate(const FEventContext& Context, const FUserType& OldRow, const FUserType& NewRow); ``` -Register callbacks before connecting or in `HandleSubscriptionApplied`. +Register row callbacks once before subscribing, for example in `HandleConnect`. Do not register them in `HandleSubscriptionApplied`: it runs again after automatic subscription replay. --- diff --git a/docs/README.md b/docs/README.md index a0f10412614..4d34cee9fba 100644 --- a/docs/README.md +++ b/docs/README.md @@ -51,12 +51,18 @@ For more information on how to use Docusaurus, see the #### Installation -1. Make sure you have [Node.js](https://nodejs.org/) installed - (version 22 or higher is recommended). -2. Clone the repository and navigate to the `docs` directory. -3. Install the dependencies: `pnpm install` -4. Run the development server: `pnpm dev`, which will start a local server and open a browser window. - All changes you make to the markdown files will be reflected live in the browser. +1. Install [Node.js](https://nodejs.org/) matching the repository's engines: + `^22.23.4 || ^24.22.1 || >=26.12.1`, and pnpm 10.16.0 (the version pinned in the root `package.json`). +2. Clone the repository and navigate to its root, `SpacetimeDB/`. +3. Install the docs dependencies using the root workspace lockfile: + `pnpm --filter docs... install --frozen-lockfile`. +4. Run `pnpm --filter docs dev`, which starts a local server and opens a browser window. + Markdown edits appear live in the browser. +5. Before opening a PR, run `pnpm --filter docs typecheck` and `pnpm --filter docs build`. + +Repository JavaScript packages use pnpm. Do not create or commit `package-lock.json`; +`cargo ci lockfile-policy` rejects npm lockfiles. This policy applies to this +repository, not to applications consuming the published SDK. ### Cutting Docs Versions diff --git a/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md b/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md index d3a640b537f..875cc5a16e6 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md +++ b/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md @@ -43,7 +43,11 @@ Before publishing, authenticate with SpacetimeDB: spacetime login ``` -This opens a browser window for authentication. Once complete, your credentials are saved locally. +This opens a browser window for authentication. Once complete, your credentials are saved locally. This login also works with local servers. + +If no login is saved, the CLI offers browser login by default. Declining it shows a warning and asks you to confirm creating a server-issued identity; pressing Enter at this second prompt cancels. A server-issued identity works only on that server, and databases you publish belong to it. Running `spacetime login` later replaces its saved token, and a lost server-issued token cannot be recovered. + +For compatibility, `--yes` (including `--yes=skip-login`) or closed standard input can still create a server-issued identity when no login is saved. These are not substitutes for authentication: log in before running unattended publishes. ### Publishing a New Database @@ -61,6 +65,8 @@ This command: 4. Runs the `init` lifecycle reducer (if defined) 5. Starts accepting client connections +New databases receive a server-allocated identity; you cannot create one at an identity you supply. An existing database can be updated by name or identity. If a deleted database name is still registered, only its name owner can recreate it. + After publishing, SpacetimeDB outputs your database identity. **Save this identity** - you'll need it for administrative tasks. ### Updating an Existing Database diff --git a/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md b/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md index 2b57c79b65a..d844f9f6efd 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md +++ b/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md @@ -25,6 +25,10 @@ The following changes are always allowed and will not break existing clients: - **Adding new reducers.** - **Removing `Unique` constraints.** +:::note Older bindings and newer SDKs +TypeScript and C# SDKs containing the [row-boundary decoding fix](https://github.com/clockworklabs/SpacetimeDB/pull/6091) can read rows with appended columns using bindings generated from the older schema: they skip the trailing fields they do not know. Older SDK versions may fail to decode those rows; keeping old bindings is not the same as keeping an old SDK. Regenerate bindings to access the new fields. Removing, reordering, or changing the types of existing columns is not covered by this compatibility. +::: + ## Changing a table's cache policy To change which storage tiers an existing table can use, update its [cache policy](../../00300-tables/00700-storage-and-cache-policies.md) in your module and republish. For a database named `my-database` on Maincloud, use: diff --git a/docs/docs/00200-core-concepts/00100-databases/00600-modules.md b/docs/docs/00200-core-concepts/00100-databases/00600-modules.md index df21debca74..d298dd2291a 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00600-modules.md +++ b/docs/docs/00200-core-concepts/00100-databases/00600-modules.md @@ -14,6 +14,19 @@ Modules let you package reusable database logic as a library that any consumer c Submodules are supported in TypeScript and C# (.NET 10 only). Cross-language composition is not supported. ::: +## Reusable TypeScript Packages + +Official packages provide reusable application features. Follow each package's integration guide: not every package root is a mountable submodule. + +- [Auth](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-auth-ts) provides application-managed password and OAuth sign-in, sessions, and connection bindings. Mount `@spacetimedb/auth/submodule`, initialize it from the root, and configure its signing key and root HTTP routes. This is a library inside your application, not the hosted SpacetimeAuth service. +- [Agents](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-agents-ts) stores conversations and runs model calls with application tools. Mount `@spacetimedb/agents/submodule` and initialize it from the root. The host must authenticate callers, derive conversation ownership from trusted state, and enforce quotas before paid model calls. +- [Files](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts) stores file contents in database tables and supplies upload, listing, and download helpers. Mount `@spacetimedb/files/submodule`; pass its helper context from a reducer or a procedure transaction. +- [S3](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts) stores file contents in a private S3 bucket while keeping ownership and upload state in SpacetimeDB. Its guide covers bucket permissions, root environment declarations for credentials, initialization, and a scheduled reconciliation procedure. Derive file ownership on the server, never from a client-supplied owner. +- [PostHog](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-posthog-ts) queues analytics events transactionally for scheduled delivery. Mount `@spacetimedb/posthog/submodule`, initialize it from the root, and configure the provider before sending events. +- [Stripe](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts) supplies Checkout, customer billing portal, subscription, and signed-webhook helpers. Mount `@spacetimedb/stripe/submodule`, initialize it from the root, configure its credentials as an administrator, and delegate its webhook handler from the root router. Host procedures must authenticate users and derive ownership, prices, and return URLs from trusted state. Fulfill purchases from verified webhook payment state, not a browser redirect; see the package's [fulfillment guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts#checkout-fulfillment). + +These packages require SpacetimeDB SDK, CLI, and server 2.12 or later. Their tables are private; expose only authorized data through your application's views and operations. Perform network I/O in procedures or HTTP handlers, not inside transactions. + ## Writing a Submodule A submodule is a regular SpacetimeDB module. The same module can be published independently or included by another module; no special root/library build role is required. @@ -157,6 +170,27 @@ const spacetimedb = schema({ }); ``` +Inside a TypeScript submodule view, `ctx.from` uses the library's local schema keys, just like `ctx.db`, even when a table has an explicit canonical `name`. For example, the library can export: + +```typescript +import { schema, table, t } from 'spacetimedb/server'; + +const sessions = table( + { name: 'auth_sessions', public: true }, + { id: t.u64().primaryKey().autoInc() }, +); +const authSchema = schema({ sessions }); +export default authSchema; + +export const allSessions = authSchema.anonymousView( + { public: true }, + t.array(sessions.rowType), + ctx => ctx.from.sessions, +); +``` + +Mount the full library namespace under `myAuth` as above. The view still uses `ctx.from.sessions`, not `ctx.from.auth_sessions` or a consumer namespace prefix. The query builder qualifies the table for the mount automatically. When writing raw SQL, use the complete canonical path instead; do not combine an accessor namespace with a canonical table name. + :::warning Changing a canonical namespace re-creates its tables The canonical namespace is part of every table's identity. Publishing a module whose namespace canonicalizes differently than before, for example after renaming the key from `myauth` to `myAuth` without a `name`, is a migration that removes the tables under the old namespace and creates empty ones under the new namespace. To rename the key without touching the tables, pin the canonical name with `name`: changing only the key while keeping the same `name` only updates the accessor aliases. ::: diff --git a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md index 89ca320de6e..955b9e146e3 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md +++ b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md @@ -26,7 +26,7 @@ By contrast, Spacetime async IDC provides a set of important guarantees that red - **Atomic with the sending transaction** An outbox row is part of the transaction that inserts it. If the transaction commits, SpacetimeDB sends the call. If it rolls back, nothing is sent. - **Exactly once semantics** Spacetime retries delivery until the receiving database answers, and the receiving database discards duplicates, so the receiving reducer runs once for each row. This invariant is maintained across crashes and server restarts, without any additional work from the module developer. -- **In order** Calls through one outbox table to one database run in the order their rows were inserted. Calls through different outbox tables, or to different databases, are not ordered relative to each other. +- **In order** Calls through one outbox table to one database run in the order their rows were inserted. Calls through different outbox tables, or to different databases, are not ordered relative to each other. Deliveries may be pipelined, but receiving calls and `on_result` callbacks retain stream order. A later receiving call can run before an earlier call's `on_result`; do not use that callback as a barrier for later receiving calls. - **Durable first** Spacetime sends a call only after the transaction that inserted it is durable, so the receiving database never acts on a call from a transaction that the sending database could lose in a crash. - **Non-blocking** The sending reducer finishes as soon as its transaction commits. The receiving database doesn't need to be available at the time of the call. The call will be made once the receiving database is available. - **Authenticated** In the receiving reducer, `ctx.sender` is the sending database's identity. Spacetime authenticates all async IDC calls, so one database can't pose as another. @@ -64,7 +64,7 @@ In the `game_world` module, write `admit_player` as an ordinary reducer. It may // game_world/src/index.ts import { schema, table, t, SenderError } from 'spacetimedb/server'; -const MAX_PLAYERS = 2n; +const maxPlayers = 2n; const player = table({ public: true }, { name: t.string().primaryKey() }); @@ -74,7 +74,7 @@ export default spacetimedb; export const admitPlayer = spacetimedb.reducer( { name: t.string() }, (ctx, { name }) => { - if (ctx.db.player.count() >= MAX_PLAYERS) { + if (ctx.db.player.count() >= maxPlayers) { throw new SenderError('The world is full'); } ctx.db.player.insert({ name }); @@ -578,7 +578,9 @@ spacetimedb::outbox!(game_world::admit_player); ctx.db.admit_player_outbox().insert(AdmitPlayerOutbox { msg_id: 0, target: world, name }); ``` -Pass `accessor = ...` or `name = "..."` to name the table differently. It can't declare an outbox for a reducer with a parameter named `msg_id` or `target`, or a second outbox for the same reducer. For those, use `#[table]` to manually declare an outbox table, and give the message ID and target columns other names. +For the `admit_player(name: String)` reducer above, this creates `AdmitPlayerOutbox` with `msg_id: u64`, `target: game_world::Identity`, and `name: String`, accessed through `ctx.db.admit_player_outbox()`. Insert `msg_id: 0` to allocate the message ID. Optional `accessor = custom_outbox` and `name = "custom_outbox"` arguments override the accessor and canonical table name. The receiver must be in scope as a module identifier. If its arguments include `msg_id` or `target`, or you need multiple outboxes for the same reducer or extra columns, declare the table manually instead. + +Rust receiver bindings now use `mod.rs` as their root. Regenerate older bindings and remove any obsolete `#[path = "remote_bindings/game_world/lib.rs"]` override; the normal `mod remote_bindings;` declaration works with the generated directory structure. diff --git a/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md b/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md index 093b5a93890..459a62e1286 100644 --- a/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md +++ b/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md @@ -15,6 +15,10 @@ However, procedures don't automatically run in database transactions, and must manually open and commit a transaction in order to read from or modify the database state. For this reason, prefer defining reducers rather than procedures unless you need to use one of the special procedure operators. +:::note Database shutdown +Pausing or suspending a database interrupts in-flight procedure HTTP requests and sleeps, and prevents procedures from starting further transactions during shutdown. Transactions committed earlier in the procedure are not rolled back with the interrupted work. Handle failure at the caller; do not assume a procedure finishes after the database stops. +::: + ## Defining Procedures diff --git a/docs/docs/00200-core-concepts/00300-tables.md b/docs/docs/00200-core-concepts/00300-tables.md index 4fab362f6d2..f1d855c128d 100644 --- a/docs/docs/00200-core-concepts/00300-tables.md +++ b/docs/docs/00200-core-concepts/00300-tables.md @@ -328,6 +328,12 @@ Use idiomatic naming conventions for each language: These conventions align with each language's standard style guides and make your code feel natural within its ecosystem. +## Storage Policy + +A table's cache policy controls which storage tiers its pages and blobs may use. It does not change transaction guarantees, durability, or table visibility. Tables default to keeping their data resident in memory. + +See [Table Storage and Cache Policies](./00300-tables/00700-storage-and-cache-policies.md) for policy values, cross-language examples, index restrictions, and migration requirements. + ## Table Visibility Tables can be **private** (default) or **public**: diff --git a/docs/docs/00200-core-concepts/00300-tables/00210-file-storage.md b/docs/docs/00200-core-concepts/00300-tables/00210-file-storage.md index af12f0aa18f..8daf7546028 100644 --- a/docs/docs/00200-core-concepts/00300-tables/00210-file-storage.md +++ b/docs/docs/00200-core-concepts/00300-tables/00210-file-storage.md @@ -10,6 +10,14 @@ import { CppModuleVersionNotice } from "@site/src/components/CppModuleVersionNot SpacetimeDB can store binary data directly in table columns, making it suitable for files, images, and other blobs that need to participate in transactions and subscriptions. +## Reusable File Packages (TypeScript) + +Use [Files](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts) for database-backed uploads, listing, and download routes. Its limits are package-specific: files are at most 4 MB, with a default total quota of 100 MB per owner. + +Use [S3](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts) when file bytes should go directly between the browser and a private S3 bucket. SpacetimeDB stores ownership and upload state; a scheduled reconciliation procedure completes interrupted uploads and deletes. Follow its bucket and initialization requirements, derive ownership on the server, and never expose AWS credentials to clients. Use a dedicated bucket prefix: reconciliation removes objects the database does not know about, so restoring an older database backup can delete newer files under that prefix. + +These packages require SDK, CLI, and server 2.12 or later. Their limits and delivery behavior are separate from the general inline-storage examples below. + ## Storing Binary Data Inline Store binary data using `Vec` (Rust), `List` (C#), `std::vector` (C++), or `t.array(t.u8())` (TypeScript). This approach keeps data within the database, ensuring it participates in transactions and real-time updates. diff --git a/docs/docs/00200-core-concepts/00300-tables/00300-indexes.md b/docs/docs/00200-core-concepts/00300-tables/00300-indexes.md index d192a722cad..415c3840e6c 100644 --- a/docs/docs/00200-core-concepts/00300-tables/00300-indexes.md +++ b/docs/docs/00200-core-concepts/00300-tables/00300-indexes.md @@ -151,6 +151,8 @@ const user = table( Never use bare `Index` — it conflicts with `System.Index`. Always write `SpacetimeDB.Index.BTree`. For table-level indexes, use `Columns = new[] { nameof(Col) }` or `new[] { "Col1", "Col2" }`, not collection expressions like `[nameof(X)]`. ::: +A single-column `[SpacetimeDB.Index.BTree]` on a `[Unique]` or `[PrimaryKey]` column is now that column's **unique index**, not an additional non-unique index. Only the declared index accessor remains, with `Find`, `Update`, and `Delete`, not `Filter`. For example, if you declare `Accessor = "ById"` for the `Id` primary key below, use `ctx.Db.User.ById.Find(id)`, not `ctx.Db.User.Id.Find(id)` or `ctx.Db.User.ById.Filter(id)`. When updating an existing module, adjust those calls or remove the redundant index declaration to keep the column-named accessor. Indexes on non-unique columns, such as `Name` and `Age` below, still support `Filter`. + ```csharp [SpacetimeDB.Table(Accessor = "User", Public = true)] public partial struct User diff --git a/docs/docs/00200-core-concepts/00300-tables/00500-schedule-tables.md b/docs/docs/00200-core-concepts/00300-tables/00500-schedule-tables.md index 1b22efce2c4..a9efe480ca8 100644 --- a/docs/docs/00200-core-concepts/00300-tables/00500-schedule-tables.md +++ b/docs/docs/00200-core-concepts/00300-tables/00500-schedule-tables.md @@ -419,6 +419,10 @@ SpacetimeDB passes the schedule row to the scheduled reducer or procedure as an - Scheduled reducers delete the row after execution, so the row is visible in the schedule table while the reducer runs. - Interval schedules are never deleted automatically. Only one-shot schedules are removed after they run. +### Who Can Call Scheduled Functions + +Scheduled reducers and procedures are private: ordinary clients cannot call them, but the database owner can invoke them directly. If a callback must reject even owner-initiated calls, check that its sender is the database identity (`ctx.sender.isEqual(ctx.databaseIdentity)` in TypeScript, `ctx.sender() == ctx.database_identity()` in Rust, or `ctx.Sender == ctx.DatabaseIdentity` in C#). + ## Use Cases - **Reminders and notifications** - Schedule messages to be sent at specific times diff --git a/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md b/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md index fbdd7b89cbe..67ce9dc7326 100644 --- a/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md +++ b/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md @@ -12,12 +12,16 @@ SpacetimeDB uses tiered storage to keep frequently accessed data in memory while | Allowed storage tiers | TypeScript / Rust value | C# value | Behavior | |-----------------------|-------------------------|----------|----------| -| Memory only (default) | `required_in_memory` | `RequiredInMemory` | Load all the table's pages and blobs into memory at start up. | +| Memory only (default) | `required_in_memory` | `RequiredInMemory` | Load all the table's pages and blobs into memory at start up. | | Memory and local disk | `required_on_disk` | `RequiredOnDisk` | Allow colder data to page out of memory to local disk. Hot data can remain in memory. | | Any available tier | `no_requirement` | `NoRequirement` | Allow memory, local disk, and object storage where the deployment enables it. | Omitting the setting selects the in-memory policy. SpacetimeDB moves eligible data out of memory as it needs room and loads it again when accessed. See [Resident memory limits](../../00250-how-to/00100-deploy/00100-maincloud.md#resident-memory-limits) for how this works on Maincloud. +Any indexes on tables with `required_on_disk` or `no_requirement` must be **B-trees**. Hash and direct indexes are not supported on those tables. If you change an existing table's policy, check its indexes before republishing. + +The standalone server currently uses an unlimited resident-memory budget, so choosing a policy alone does not make a local database evict data. Eviction depends on the server's configured storage tiers and memory budget; a cache policy does not configure a backend or force eviction. + ## Declare the Policy in Your Module These examples define a table that can page to local disk and a table that can page to any available tier. @@ -105,9 +109,11 @@ pub struct ArchivedHistory { ## Residency, Durability, and Performance -Cache policies control where data can reside while the database is running. They do not affect durability. For example, when a database restarts, SpacetimeDB recovers data even for tables configured to reside fully in memory. +Cache policies control where data can reside while the database is running. They do not affect durability. For example, when a database restarts, SpacetimeDB recovers data even for tables configured to reside fully in memory. + +During database recovery, the storage engine temporarily suspends enforcement of the resident-memory hard limit while reconstructing committed data, rebuilding state, and running startup migrations. It then re-enables the limit and attempts to trim eligible data before serving transactions. Required-in-memory data can keep usage above the configured limit; recovery is not a guarantee that subsequent operations have enough memory to succeed. This storage-engine budget is not a process or machine memory limit: recovery still needs enough physical memory to complete. -The policy applies to table pages and large values stored as blobs. A blob shared by multiple tables stays in memory if at least one of their policies requires it. +The policy applies to table pages and large values stored as blobs. A blob shared by multiple tables stays in memory if at least one of their policies requires it. Accessing cold data may require storage reads, increasing latency. Use indexed lookups to limit the pages an operation touches, and reserve the in-memory policy for data that needs consistently fast access. Large scans can bring substantial amounts of cold data into the cache. See [Performance Best Practices](./00600-performance.md). diff --git a/docs/docs/00200-core-concepts/00600-clients/00500-rust-reference.md b/docs/docs/00200-core-concepts/00600-clients/00500-rust-reference.md index 462b79d3565..2df3d0af7bb 100644 --- a/docs/docs/00200-core-concepts/00600-clients/00500-rust-reference.md +++ b/docs/docs/00200-core-concepts/00600-clients/00500-rust-reference.md @@ -326,6 +326,8 @@ trait DbContext { Gracefully close the `DbConnection`. Returns an `Err` if the connection is already disconnected. +The close request is queued, so keep advancing the connection (for example, with `run_threaded`, `run_async`, or `frame_tick`) until shutdown is processed. Once an established connection ends, its `on_disconnect` callback runs even if another mutation was queued after the close request. Do not queue new reducer or procedure calls after requesting shutdown; they cannot be sent after the connection closes. + ### Subscribe to queries | Name | Description | diff --git a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md index ecc993e4eed..419c97b2a2e 100644 --- a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md +++ b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md @@ -152,6 +152,8 @@ class DbConnectionBuilder { Configure the URI of the SpacetimeDB instance or cluster which hosts the remote database. +The SDK preserves a path prefix, with or without a trailing slash. For example, `wss://example.com/stdb` connects to `/stdb/v1/database//subscribe` and exchanges authentication tokens at `https://example.com/stdb/v1/identity/websocket-token`. Configure your reverse proxy to forward both endpoints to SpacetimeDB, stripping the `/stdb` prefix if the server is mounted at `/`. Supply only the server base URI, not the database subscription endpoint. + #### Method `withDatabaseName` ```typescript @@ -244,6 +246,8 @@ class DbConnectionBuilder { Called when an established connection is lost, or when the application calls [`disconnect`](#method-disconnect). With automatic reconnection enabled, the trailing parameters describe the next attempt and delay in milliseconds. Both are `undefined` when no retry is scheduled. An explicit `disconnect()` also passes `undefined` for `error`, including when called between reconnect attempts. +If a server message cannot be decoded or applied, the SDK ends the connection without retrying, even when automatic reconnect is enabled. The error reaches `onConnectError` before the first successful handshake, or `onDisconnect` afterwards. Synchronous exceptions thrown by user callbacks are logged and do not prevent other callbacks from running. + #### Method `withToken` ```typescript diff --git a/docs/docs/00250-how-to/00050-troubleshooting.md b/docs/docs/00250-how-to/00050-troubleshooting.md index 0c75b96741d..99d2540f2be 100644 --- a/docs/docs/00250-how-to/00050-troubleshooting.md +++ b/docs/docs/00250-how-to/00050-troubleshooting.md @@ -65,6 +65,10 @@ If you see `Database resident memory budget exceeded`, the operation couldn't ge 2. **Allow a table to use more storage tiers.** Change its [cache policy](../00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md) to `RequiredOnDisk` to allow paging to local disk, or to `NoRequirement` to allow paging to any available tier. Follow the [migration steps](../00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md#changing-a-tables-cache-policy) to republish while keeping existing rows. SpacetimeDB can then evict eligible data as it needs room. 3. **Contact Maincloud support if recovery operations also hit the limit.** Include your database identity, the operation that failed, and the full error message. +## TypeScript module memory limit exceeded + +`Javascript module exceeded memory limit` refers to the TypeScript module's V8 runtime, not the database's resident storage budget. `ArrayBuffer` allocations, including typed-array backing buffers, count toward the V8 memory limit as well as ordinary JavaScript objects. Reduce peak allocations: process large inputs in smaller batches and avoid retaining or copying entire buffers unnecessarily. Allowing tables to page to disk does not increase the V8 limit. + ## In Modules ### Identity seen by reducers never changes diff --git a/docs/docs/00250-how-to/00100-deploy/00200-self-hosting.md b/docs/docs/00250-how-to/00100-deploy/00200-self-hosting.md index 51a59001f6d..b171c08b838 100644 --- a/docs/docs/00250-how-to/00100-deploy/00200-self-hosting.md +++ b/docs/docs/00250-how-to/00100-deploy/00200-self-hosting.md @@ -251,6 +251,19 @@ Finally, restart the service: sudo systemctl start spacetimedb ``` +### Data-directory version compatibility + +Before changing server versions, stop the service and back up its data directory. The server checks the generated `metadata.toml` before opening existing data; do not edit this file to bypass a compatibility error. + +For server builds containing the [updated metadata check](https://github.com/clockworklabs/SpacetimeDB/pull/6666): + +- The server edition must match the recorded edition. +- Within the same major version, the running minor version must be at least the recorded minor version. Patch downgrades and minor/patch prerelease suffixes are allowed by this check; for example, recorded `2.16.2` accepts running `2.16.0-rc1`. +- A running major prerelease (`X.0.0-*`) requires the identical recorded version. For example, recorded `3.0.0` rejects running `3.0.0-rc1`. This restriction is on the **running** version: recorded `3.0.0-rc1` accepts running `3.0.0` under the same-major rule. +- The explicit exception allowing a 2.x server to open 1.x data is checked before the major-prerelease restriction. Other cross-major changes are rejected. + +After a successful check, the recorded version only increases; opening data with a lower patch version does not lower it. Passing this startup check is not a general rollback guarantee for every storage format or release. Check the target release's migration and rollback requirements before switching binaries. + ## Step 7: Troubleshooting ### SpacetimeDB Service Fails to Start diff --git a/docs/docs/00250-how-to/00300-logging.md b/docs/docs/00250-how-to/00300-logging.md index 864c31f465d..419c23c00e4 100644 --- a/docs/docs/00250-how-to/00300-logging.md +++ b/docs/docs/00250-how-to/00300-logging.md @@ -183,13 +183,16 @@ spacetime logs --level error # Show warnings and errors spacetime logs --level warn - -# Show logs from a specific time range -spacetime logs --since "2023-01-01 00:00:00" ``` For all log viewing options, see the [`spacetime logs` CLI reference](../00300-resources/00100-cli-reference/00100-cli-reference.md#spacetime-logs). +## Diagnosing CPU-Budget Aborts + +When a reducer or view exhausts its per-call CPU budget, the host writes an error-level database log entry containing `aborted after : reached the maximum CPU usage allowed per call`, with the function name attached. `` represents the measured execution duration, not a fixed time limit. This diagnostic is available in server builds containing the [CPU-budget logging change](https://github.com/clockworklabs/SpacetimeDB/pull/6612); older servers may not emit it. + +Read these entries as the database owner with `spacetime logs --level error `. The entry reports per-call CPU-budget exhaustion, not necessarily an empty account balance. Inspect the function's work and queries, especially large scans or loops. + ## Best Practices ### Log Levels diff --git a/docs/docs/00250-how-to/00900-unit-testing.md b/docs/docs/00250-how-to/00900-unit-testing.md index 84842ab2536..e2f487179a8 100644 --- a/docs/docs/00250-how-to/00900-unit-testing.md +++ b/docs/docs/00250-how-to/00900-unit-testing.md @@ -62,6 +62,8 @@ export default defineConfig({ The plugin also configures the installed `spacetimedb` package to pass through Vitest's transforms. The package includes the test datastore's WebAssembly runtime; you do not need to compile it yourself. +The TypeScript harness does not currently supply namespaced `ctx.as` / `tx.as` helper contexts for mounted submodules. Test integrations that use those contexts against a running database. + ### Define the module For a standalone example, put this in `src/index.ts`. In an existing module, keep your own schema and reducers instead. @@ -325,6 +327,8 @@ The rest of this guide shows fragments rather than whole files. Code marked `// Use .NET 10 and a separate test project referencing `SpacetimeDB.Testing`, at exactly the same version as your module's `SpacetimeDB.Runtime` package. These examples use xUnit. No server, Rust compiler, or WASI workload is needed. +The testing package includes native datastore libraries for Linux x64/ARM64 (glibc 2.35 or later) and Windows x64. macOS is not supported; run C# module tests in a supported Linux environment or Windows. Use a release that publishes matching Testing and Runtime packages. + Keep tests in a sibling project, outside the module directory, so the module's default compile glob does not include test code: ```text diff --git a/modules/spacetime-posthog-ts/README.md b/modules/spacetime-posthog-ts/README.md index 12f6af165e5..74a52317540 100644 --- a/modules/spacetime-posthog-ts/README.md +++ b/modules/spacetime-posthog-ts/README.md @@ -93,7 +93,7 @@ spacetime call --server http://127.0.0.1:3000 spacetime-posthog set_posthog_conf Verify: ```bash -spacetime call --server http://127.0.0.1:3000 spacetime-posthog get_posthog_config_status '{}' +spacetime call --server http://127.0.0.1:3000 spacetime-posthog get_posthog_config_status ``` ## Public views diff --git a/modules/spacetime-posthog-ts/example/README.md b/modules/spacetime-posthog-ts/example/README.md index 61becd41d1c..4a9a834b43c 100644 --- a/modules/spacetime-posthog-ts/example/README.md +++ b/modules/spacetime-posthog-ts/example/README.md @@ -5,8 +5,8 @@ send the café's activity to your analytics project. ## Run it locally -Requires Node.js 20+, pnpm 10, and the SpacetimeDB CLI and server built from -this checkout. +Requires a recent version of Node.js 22, 24, or 26 or later, pnpm 10, and the +SpacetimeDB CLI and server built from this checkout. Start SpacetimeDB in a separate terminal: diff --git a/modules/spacetime-stripe-ts/README.md b/modules/spacetime-stripe-ts/README.md index fe76f8545de..4c6db9106a9 100644 --- a/modules/spacetime-stripe-ts/README.md +++ b/modules/spacetime-stripe-ts/README.md @@ -30,9 +30,18 @@ an administrator with `stripe.set_stripe_config`. See the arguments in with Stripe and select the [events listed below](#webhook-events-handled). ```ts -import { Router, SenderError, schema, t } from 'spacetimedb/server'; +import { Router, SenderError, schema, table, t } from 'spacetimedb/server'; import * as stripe from '@spacetimedb/stripe/submodule'; +const storeProduct = table( + { name: 'store_product' }, + { + productId: t.string().primaryKey(), + active: t.bool(), + stripePriceId: t.option(t.string()), + } +); + const spacetimedb = schema({ stripe, storeProduct }); export default spacetimedb; @@ -48,10 +57,13 @@ export const router = spacetimedb.httpRouter( ); ``` -The submodule's procedures are admin-only. Signed-in users reach Stripe through -host procedures that call the host helpers with `ctx.as.stripe`. The host -procedure resolves the user from `ctx.sender`, -takes prices from a server-owned catalog, and fixes the return URLs: +The submodule's billing and query procedures are admin-only. Application users +reach Stripe through host procedures that call the host helpers with +`ctx.as.stripe`. These helpers do not authenticate the caller. The example below +keys customers by the caller's SpacetimeDB identity and accepts any connected +identity; add your application's account authorization and rate limits before +exposing checkout publicly. The host procedure resolves the user from +`ctx.sender`, takes prices from a server-owned catalog, and fixes the return URLs: ```ts const APP_ORIGIN = 'https://store.example.com'; @@ -116,7 +128,7 @@ For `t.option(...)` CLI arguments, use `null` for no value and Verify: ```bash -spacetime call --server http://127.0.0.1:3000 stripe-ts get_stripe_config_status '{}' +spacetime call --server http://127.0.0.1:3000 stripe-ts get_stripe_config_status ``` ## Private tables diff --git a/modules/spacetime-stripe-ts/example/README.md b/modules/spacetime-stripe-ts/example/README.md index 871e017f3c8..191be6ec034 100644 --- a/modules/spacetime-stripe-ts/example/README.md +++ b/modules/spacetime-stripe-ts/example/README.md @@ -5,8 +5,9 @@ with Stripe test payments. ## Run it locally -Requires Node.js 20+, pnpm 10, and the SpacetimeDB CLI and server built from -this checkout. +Requires a supported Node.js release (22.23.4+, 24.22.1+, or 26.12.1+ on +those release lines), pnpm 10.16+, and the SpacetimeDB CLI and server built +from this checkout. Start SpacetimeDB in a separate terminal: diff --git a/skills/cli/SKILL.md b/skills/cli/SKILL.md index 430ffe98582..94eeac92eda 100644 --- a/skills/cli/SKILL.md +++ b/skills/cli/SKILL.md @@ -58,10 +58,12 @@ For TypeScript client bindings, `spacetime generate --lang typescript --import-e ### Client and Module Bindings -`spacetime generate --bindings client` (default) generates bindings for clients connecting to a database. `--bindings module` generates receiver bindings used inside a **sending database module** to call reducers in another **receiving database** through asynchronous IDC. Rust and TypeScript module bindings are supported; C#/C++ module bindings are not implemented yet. `unrealcpp` is client-only; `cpp` is accepted only in module mode. +`spacetime generate --bindings client` (default) generates bindings for clients connecting to a database. `--bindings module` generates receiver bindings used inside a **sending database module** to call reducers in another **receiving database** through asynchronous IDC. Rust, TypeScript, and C# module bindings are supported; C++ module bindings are not implemented yet. `unrealcpp` is client-only; `cpp` is accepted only in module mode. In `spacetime.json`, each sending database's non-inherited `dependencies` array requires its own `module-path` and dependency `name` plus receiving-module `module-path` or `database`. A `database` reference resolves another target's local source/build settings in the same config; it does not fetch a running database's schema. A direct receiving module source takes precedence. Dependencies do not themselves publish receiving databases or inherit the sending module's build settings. `generate ` processes both its regular `generate` entries (client bindings by default) and `dependencies` (module bindings automatically); no `--bindings` flag or second `generate` entry is needed for a dependency. For dependencies, module binding language defaults to the sending module's language and Rust/TypeScript output defaults to `/src/remote_bindings`. Explicit config `out-dir` is config-relative. A regular `generate` entry can select `"bindings": "module"`, but does not use dependency language or output defaults. The CLI `--bindings` override is allowed only when a single generation entry is selected. +C# dependency output defaults to `/remote_bindings/`, with namespace `RemoteBindings.`. Set `namespace` on that dependency to override it. Direct `--bindings module --lang csharp` generation without a dependency name defaults to `RemoteBindings`; client bindings still default to `SpacetimeDB.Types`. `--namespace` overrides the C# namespace. In a module-bindings namespace, later segments cannot be `System`, `SpacetimeDB`, or the first segment: for example, `RemoteBindings.System` is rejected. + `dev` generates only root dependencies before building the sending module, and watches their source paths. Child targets are available for source lookup, not recursive dependency generation. `--skip-generate` skips receiver/client generation and receiver-only watching; `--skip-publish` does not. See https://spacetimedb.com/docs/cli-reference/spacetime-json#receiver-dependencies for examples. ### C# Build Modes @@ -75,12 +77,16 @@ Use `spacetime init --lang csharp --dotnet-version 10 my-project` to select Do not make the project permanently WASM-only to fix a managed build: keep LLVM package references and WASM settings conditional on the RID. Let dotnet restore -when changing build modes. Managed builds alone do not enable C# module unit tests. +when changing build modes. Managed builds alone do not enable C# module unit tests: +use a separate .NET 10 test project with the matching `SpacetimeDB.Testing` +package and a supported native platform, as described in the C# server skill. .NET 8 retains WASM/JIT by default and requires `--native-aot` to select NativeAOT where supported. The CLI manages `SPACETIMEDB_WASM_AOT` and its legacy alias `EXPERIMENTAL_WASM_AOT`; users do not need to set either for .NET 10. +New databases receive a server-allocated identity; a supplied identity can update an existing database, not create one. Only the registered name owner can recreate a deleted database whose name remains registered. + ### Publishing & Deployment ```bash @@ -180,6 +186,10 @@ spacetime server clear ### Authentication +Log in with `spacetime login` before publishing, including to local servers. Without a saved login, the browser-login prompt defaults to yes; declining it shows a server-issued identity warning and a second prompt that defaults to no. A server-issued identity works only on its issuing server, owns databases published with it, and cannot be recovered if its token is lost. A later `spacetime login` replaces that saved token. + +`--yes` / `--yes=skip-login` and closed stdin can still create a server-issued identity for compatibility; they do not authenticate you with spacetimedb.com. Do not use them to bypass login setup for unattended publishing. Alert the user before intentionally creating a server-issued identity. + ```bash # Login (opens browser) spacetime login diff --git a/skills/concepts/SKILL.md b/skills/concepts/SKILL.md index db3852e4264..d191c9731f4 100644 --- a/skills/concepts/SKILL.md +++ b/skills/concepts/SKILL.md @@ -36,8 +36,9 @@ This describes Spacetime 2.x. The API changed substantially from 1.x, so older a - **Access control.** Tables are private by default. Views expose exactly the rows and columns each client should see, including per-caller views filtered by the caller's identity. ([Access permissions](https://spacetimedb.com/docs/tables/access-permissions/)) - **Auth.** Spacetime works with any OIDC provider, such as Auth0, Clerk, Better Auth, or Firebase Auth. SpacetimeAuth is a first-party provider with magic links, social logins, and user and role management. ([Authentication](https://spacetimedb.com/docs/core-concepts/authentication/)) - **Scheduled work.** Schedule tables run reducers or procedures at a specific time or on a repeating interval. In TypeScript, the Cron module adds calendar schedules with time zones. ([Schedule tables](https://spacetimedb.com/docs/tables/schedule-tables/), [Cron module](https://spacetimedb.com/modules/cron)) +- **Payments.** The TypeScript Stripe module supplies Checkout, billing portal, subscription, and signed-webhook helpers. The host application authenticates users and controls ownership and prices. Fulfill purchases from verified webhook payment state, not the browser redirect. ([Stripe module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts)) - **Ephemeral events.** Event tables broadcast rows to subscribers without storing them, for things like typing indicators. ([Event tables](https://spacetimedb.com/docs/tables/event-tables/)) -- **Files.** Files can be stored as bytes in table columns, or a procedure can store large files in S3 or a similar service and keep a reference in a table. In TypeScript, the Files module handles uploads, listing and download routes. ([File storage](https://spacetimedb.com/docs/tables/file-storage/), [Files module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts)) +- **Files.** Files can be stored as bytes in table columns, or a procedure can store large files in S3 or a similar service and keep a reference in a table. In TypeScript, the Files module handles database-backed uploads, listing and download routes; the S3 module keeps bytes in a private bucket and tracks ownership and upload state in the database. ([File storage](https://spacetimedb.com/docs/tables/file-storage/), [Files module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts), [S3 module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts)) - **SQL and tools.** Spacetime speaks the PostgreSQL wire protocol, so PostgreSQL drivers, `psql`, and GUI clients can connect. ([PostgreSQL wire protocol](https://spacetimedb.com/docs/how-to/pg-wire/)) - **Dashboard.** On Maincloud, each database's dashboard on spacetimedb.com lets you browse, filter, edit, delete, and export table rows, call reducers, and view logs and metrics. ([Maincloud dashboard](https://spacetimedb.com/docs/how-to/deploy/maincloud/#viewing-your-database-on-the-web-dashboard)) - **Schema changes.** Compatible changes, such as adding tables or columns with defaults, migrate automatically when you republish, and incremental migrations handle the rest. ([Automatic migrations](https://spacetimedb.com/docs/databases/automatic-migrations/)) @@ -79,6 +80,10 @@ For questions about older articles, benchmarks, or past reviews, see [Common mis 4. Check server logs for errors (`spacetime logs `) 5. Is the reducer actually being called from the client? +A per-call CPU-budget abort in a reducer or view produces an error-level database log containing `reached the maximum CPU usage allowed per call`, with the function name and elapsed duration, on servers containing that logging change. Check it as the database owner with `spacetime logs --level error `; this message does not by itself mean the account balance is empty. ([Logging](https://spacetimedb.com/docs/how-to/logging/#diagnosing-cpu-budget-aborts)) + +For self-hosted server version changes, stop the service and back up the data directory. The updated `metadata.toml` startup check requires the same edition and, within one major version, a running minor at least as new as recorded; it ignores patch differences and minor/patch prerelease suffixes. A running `X.0.0-*` major prerelease requires an identical recorded version, except that the 1.x-data-to-2.x-server exception is checked first. The restriction is on the running version, not on a previously recorded major prerelease. The recorded version never decreases. Do not edit generated metadata to bypass the check or treat passing it as a blanket rollback guarantee. ([Version compatibility](https://spacetimedb.com/docs/how-to/deploy/self-hosting/#data-directory-version-compatibility)) + --- ## Tables @@ -134,6 +139,10 @@ Server-side modules can be written in: Rust, C#, TypeScript, C++ Lifecycle: Write → Compile → Publish (`spacetime publish`) → Hot-swap (republish without disconnecting clients) +Scheduled functions are private, but the database owner can still call them directly. To restrict a callback to scheduler execution, compare the sender with the database identity; see the server skills for language-specific syntax. + +Outbound HTTP requests from procedures default to a 30-second timeout when none is specified; the host clamps requested timeouts to a maximum of 180 seconds. See [procedure HTTP requests](https://spacetimedb.com/docs/functions/procedures#http-requests) and the language-specific server skills for request syntax. + ## HTTP Handlers A module can expose its own HTTP API. Each handler takes a request and returns a response, and one router per module binds handlers to a method and path. Requests reach them under `/v1/database//route`, so a `/say-hello` route is served at `/v1/database/my-db/route/say-hello`. @@ -144,6 +153,12 @@ A module can expose its own HTTP API. Each handler takes a request and returns a Use HTTP handlers for webhooks and for clients that can't use a SpacetimeDB SDK. See the language-specific server skills for syntax. +## Table Storage Policies + +Tables default to keeping pages and blobs resident in memory. A cache policy can permit eviction to local disk (`required_on_disk`) or any configured tier (`no_requirement`), including remote object storage. It does not configure a backend or force eviction; actual eviction depends on server tiers and memory budgets. Any indexes on tables with non-default policies must be B-trees. The standalone server currently uses an unlimited resident-memory budget. Change a policy by republishing without deleting data; moving back to the in-memory policy requires enough memory to load and retain the table. See https://spacetimedb.com/docs/tables/storage-and-cache-policies and the language-specific table options. + +Recovery temporarily suspends the storage engine's resident-memory hard limit, then re-enables it and attempts eviction before serving transactions. Required-in-memory data can leave usage above budget, so later operations can still fail for lack of memory. This does not bypass process or physical memory limits. See [storage recovery](https://spacetimedb.com/docs/tables/storage-and-cache-policies/#residency-durability-and-performance). + ## Reusable Modules and Configuration TypeScript and C# support same-language submodule composition. A namespace has a language accessor and a canonical database name; SQL, CLI calls, and HTTP calls use the canonical name. Changing the canonical namespace drops its tables and their data, so pin it when renaming an accessor. TypeScript supports nested submodules; C# composition requires 2.13+ with .NET 10/C# 14, and nested or repeated C# mounts require 2.14+. See the respective server skills for registration and helper-context rules. @@ -154,13 +169,17 @@ Database environment values are read-only strings, including secrets, supplied a Views can accept arguments in 2.13+ (Rust, TypeScript, C#), queried as `SELECT * FROM view_name(42)`. Use explicit queries instead of subscribe-all on that connection; subscribe-all skips these views. See server skills for definition restrictions and client skills for query/cache rules. -Rust and TypeScript provide in-memory module unit-test harnesses in 2.12+: run native `cargo test` or Vitest with the module-test plugin. These use the real datastore but do not simulate clients, subscriptions, RLS enforcement, lifecycle events, or timer execution. Test those host behaviors against a running database. +Rust and TypeScript provide in-memory module unit-test harnesses in 2.12+: run native `cargo test` or Vitest with the module-test plugin. C# also provides a managed .NET 10 harness via the separate `SpacetimeDB.Testing` package; see the C# server skill for platform and package requirements. These use the real datastore but do not simulate clients, subscriptions, RLS enforcement, lifecycle events, or timer execution. Test those host behaviors against a running database. ## Inter-Database Communication Reducers can't make network requests, but a reducer can call a reducer in another database on the same server through an **outbox table** (async IDC). The reducer inserts a row, and after its transaction commits, the row is delivered as a reducer call to the target database exactly once, in order with other calls through the same outbox to the same database. The sending reducer doesn't wait, and the two databases don't commit together: the receiving reducer runs later in its own transaction and can fail. An optional `on_result` reducer in the sending database receives the result, so it can undo or record the work. -Use it to split an application into databases that scale and deploy independently, such as a lobby that sends players to separate game world databases. Only Rust and TypeScript modules can declare outbox tables. See the language-specific server skills for syntax. +Deliveries can be pipelined. Receiving calls and `on_result` callbacks each retain stream order, but a later receiving call need not wait for an earlier callback in the sending database. Do not use callbacks as barriers for subsequent receiving calls. + +Outbox rows are insert-only for module code. The host removes them after delivery and the optional result callback; do not update or delete pending rows yourself. + +Use it to split an application into databases that scale and deploy independently, such as a lobby that sends players to separate game world databases. Rust, TypeScript, and C# modules can declare outbox tables. See the language-specific server skills for syntax. ## Identity diff --git a/skills/csharp-server/SKILL.md b/skills/csharp-server/SKILL.md index 4ab3ca89ee5..c3d51a28dfc 100644 --- a/skills/csharp-server/SKILL.md +++ b/skills/csharp-server/SKILL.md @@ -17,10 +17,14 @@ metadata: Module unit tests use a sibling .NET 10 test project with an ordinary module `ProjectReference` and the separate `SpacetimeDB.Testing` NuGet package, at exactly -the module's Runtime version. Run with `dotnet test`; no server or Rust compiler +the module's Runtime version, from a release publishing both packages. Native +libraries support Linux x64/ARM64 (glibc 2.35+) and Windows x64, not macOS. +Run with `dotnet test`; no server or Rust compiler is required. Keep Testing out of module dependencies and test sources outside the module directory. Use `using var test = ModuleTestContext.Create(typeof(Module).Assembly)` -and `test.WithReducerTx(TestAuth.Internal(), ctx => Module.Reducer(ctx))`. +and, for the module below, +`test.WithReducerTx(TestAuth.Internal(), ctx => Module.AddRecord(ctx, 1))` +with `using SpacetimeDB.Testing;` in the test project. Callbacks are synchronous; one fixture supports one execution flow, while separate fixtures may run in parallel. The chat-console-cs template includes tests for .NET 10 only. See `/how-to/unit-testing` for setup and release availability. @@ -57,6 +61,8 @@ spacetime build # CLI selects WASM automatically assemblies. .NET 10 composition uses generated assembly descriptors, not the dependency's standalone WASM exports; no special root/library build flag is needed. +Table attributes also accept `CachePolicy = TableCachePolicy.RequiredInMemory` (default), `TableCachePolicy.RequiredOnDisk`, or `TableCachePolicy.NoRequirement`. See the concepts skill for storage semantics and index restrictions. + ## Module Structure Reducers are static methods in a `static partial class`; tables are `public partial struct`s. This reference keeps everything in one `public static partial class Module`, which needs only `using SpacetimeDB;`: @@ -137,7 +143,7 @@ The complete set of column attributes: [PrimaryKey] // primary key [AutoInc] // auto-increment (use 0 as placeholder on insert) [Unique] // unique constraint; indexes the column, enables .Find() -[SpacetimeDB.Index.BTree] // btree index (enables .Filter() on this column) +[SpacetimeDB.Index.BTree] // non-unique btree index enables .Filter() [Default(true)] // migration-safe default for a newly appended field ``` @@ -161,6 +167,8 @@ public partial struct Membership { public ulong GroupId; public Identity UserId; Prefer a multi-column index over filtering by one column and looping. +A declared single-column B-tree index on a `[Unique]` or `[PrimaryKey]` column is that column's unique index, not a second non-unique index. Its declared `Accessor` is the only accessor and supports `Find`/`Update`/`Delete`, not `Filter`. For example, declaring `Accessor = "ById"` on the `Id` primary-key column changes calls from `.Id.Find(id)` to `.ById.Find(id)`. Remove the redundant index attribute to retain the column-named accessor. Do not change an unconstrained column's `Filter` calls to `Find`. + ## Reducers ```csharp @@ -206,7 +214,7 @@ public static void ClientConnected(ReducerContext ctx) { ... } public static void ClientDisconnected(ReducerContext ctx) { ... } ``` -Reducer and procedure method names must not start with `On`, `on`, or `__`; the code generator rejects them (STDB0010), so name lifecycle reducers `ClientConnected`, not `OnConnect`. +Ordinary reducer and procedure method names must not start with `On`, `on`, or `__`; the code generator rejects them (STDB0010), so name lifecycle reducers `ClientConnected`, not `OnConnect`. A reducer marked `[OnResult]` may start with `On` or `on`, but not `__`. `ctx.ConnectionId` is `ConnectionId?`, including in connection lifecycle reducers. Check or unwrap it before storing it in a non-nullable column or passing it to an index accessor. @@ -303,6 +311,16 @@ The marker is any accessible type in the dependency assembly. Root code uses `ct In 2.14+, any module can mount its own dependencies, and the same assembly can be mounted more than once with independent tables at each path; 2.13 allows only root mounts, once per assembly. Cross-language composition is unsupported. Named dependencies cannot declare lifecycle reducers, nonempty environments, or RLS filters. Define RLS in the root with canonical qualified table names. Named-submodule routes are ignored; root handlers may delegate to library helpers. Dependencies in `public` can contribute lifecycle reducers (subject to uniqueness), environment declarations, and routes. +## Inter-Database Communication + +Generate C# receiver bindings with `spacetime generate --bindings module --lang csharp`, or use the sending module's `dependencies` in `spacetime.json` (see the CLI skill). For a dependency named `game_world`, the default namespace is `RemoteBindings.GameWorld`; import it as `using Gw = RemoteBindings.GameWorld;`. This is independent-database messaging, not assembly composition. + +For a receiver reducer `admit_player(name: string)`, `[Outbox(typeof(Gw.Reducers.AdmitPlayer), Accessor = "AdmitPlayerOutbox")]` on an empty `public partial struct AdmitPlayerOutbox` generates `MsgId`, `Target` (a `Gw.Identity`), and `Name`. Insert through `ctx.Db.AdmitPlayerOutbox.Insert(...)` inside a reducer, with `MsgId = 0` for automatic allocation. Use the generated receiver identity type, not an unwrapped `SpacetimeDB.Identity`. + +Alternatively, declare `[Table(Accessor = "AdmitPlayerOutbox", Outbox = typeof(Gw.Reducers.AdmitPlayer))]` with a `ulong` `[PrimaryKey, AutoInc]` field, exactly one `[Target]` field of type `Gw.Identity`, and matching parameter fields. Field names map to receiver parameters in snake_case; `[Param("name")]` maps a differently named field to the canonical `name` parameter. Additional fields are local callback metadata. Use the manual form if receiver parameters collide with shorthand's `msg_id` or `target`. Outboxes must be in the root assembly, not a referenced library; they cannot also be event or scheduled tables. + +Apply both `[Reducer]` and `[OnResult(typeof(AdmitPlayerOutbox))]` to a `public static void` method with parameters `(ReducerContext ctx, AdmitPlayerOutbox row, Result result)`. Match errors as `Result.ErrR(var error)`. If a row type has several outboxes, select one with `Table = "AccessorName"` on `[OnResult]`; `[Target]` and `[Param]` also accept `Table`. The callback is private: only the host, database owner, and team collaborators can run it, not ordinary clients. See the concepts skill for delivery/transaction guarantees and `/databases/inter-database-communication` for the complete receiver, sender, and callback example. + ## Environment Variables ```csharp @@ -432,6 +450,8 @@ public enum Status { Online, Away, Offline } public partial struct Point { public float X; public float Y; } ``` +`[SpacetimeDB.Type(Name = "game_world.Point")]` overrides a custom type's canonical schema name without renaming the C# type. The runtime accepts `.` or `::` between scope segments. C# receiver bindings use dependency-scoped type names to keep types from different receivers distinct; preserve their generated `Type(Name = ...)` attributes rather than editing generated files. + Tagged enums (discriminated unions): a `partial record` with empty body and no constructor parameters. Payloads are `[Type] partial struct`s: ```csharp diff --git a/skills/rust-server/SKILL.md b/skills/rust-server/SKILL.md index c2e69876968..ff8114750e8 100644 --- a/skills/rust-server/SKILL.md +++ b/skills/rust-server/SKILL.md @@ -42,7 +42,7 @@ pub struct Entity { } ``` -Options: `accessor = snake_case` (required), `public`, `scheduled(reducer_fn)`, `index(...)` +Options: `accessor = snake_case` (required), `public`, `scheduled(reducer_fn)`, `index(...)`, `cache_policy = required_in_memory | required_on_disk | no_requirement` (default: `required_in_memory`; see the concepts skill for storage semantics). `ctx.db` accessors use the `accessor` name (snake_case). @@ -292,7 +292,7 @@ Construct a connection ID from a numeric representation with `ConnectionId::from A reducer calls a reducer in another database by inserting a row into an outbox table. The call is sent only if the transaction commits, runs exactly once, and runs in order with other calls through the same outbox to the same database. The sending reducer doesn't wait for it. Both databases must be on the same server. -Generate receiver bindings by listing the receiving module under `dependencies` in the sending database's `spacetime.json`, then running `spacetime generate `. Rust bindings are written to `src/remote_bindings/`. +Generate receiver bindings by listing the receiving module under `dependencies` in the sending database's `spacetime.json`, then running `spacetime generate `. Rust bindings are written to `src/remote_bindings/`, with `mod.rs` roots. Regenerate older bindings and remove obsolete `lib.rs` path overrides. With `game_world` imported as a module identifier, `spacetimedb::outbox!(game_world::admit_player);` generates `AdmitPlayerOutbox` with `msg_id`, `target`, and the reducer argument columns. Optional `accessor = custom_outbox` and `name = "custom_outbox"` override table names. Use a manual table (below) for extra columns, reducer arguments named `msg_id` or `target`, or multiple outboxes for the same reducer. ```json { diff --git a/skills/typescript-client/SKILL.md b/skills/typescript-client/SKILL.md index a232086ad3a..914adaea413 100644 --- a/skills/typescript-client/SKILL.md +++ b/skills/typescript-client/SKILL.md @@ -17,6 +17,8 @@ Generated bindings convert snake_case names to camelCase, including row fields: The examples below use bundler-style extensionless imports. For NodeNext or direct-TypeScript execution, choose the matching binding import extension and use explicit file imports in your application; see https://spacetimedb.com/docs/clients/typescript#import-extensions. +`withUri` takes the server base URI, not a subscription endpoint. It preserves a path prefix: `wss://example.com/stdb` (or `/stdb/`) uses `/stdb/v1/database//subscribe` and the HTTPS token-exchange endpoint `/stdb/v1/identity/websocket-token`. A reverse proxy must forward both endpoints, stripping its prefix when forwarding to a root-mounted server. + ## React: main.tsx ```typescript @@ -164,6 +166,8 @@ conn.subscriptionBuilder().subscribe('SELECT * FROM by_id(42)'); Use explicit queries for every table on that connection, not subscribe-all, which skips views with arguments. Only `SELECT * FROM view_name(literal_args)` is supported. All argument values share one cache table; unsubscribe from obsolete arguments to avoid combining their rows. Validate/encode dynamic values as SQL literals rather than concatenating untrusted input. In React, raw SQL subscriptions need explicit lifetime management and cleanup; `useTable` does not supply an argument-bearing view builder. +A server message that cannot be decoded or applied ends the connection without automatic retry: errors go to `onConnectError` before establishment or `onDisconnect` afterwards. Synchronous exceptions thrown by user callbacks are logged without preventing other callbacks from running. TypeScript SDKs containing the row-boundary decoding fix (#6091) can read rows with appended table columns using older generated bindings; removing, reordering, or changing existing column types is not. Regenerate bindings to access added columns. + ## Automatic Reconnect and Token Refresh The React provider's connection manager enables automatic reconnect; the explicit `.withAutomaticReconnect()` above also shows the setting to use for direct connections. Without it, a direct connection does not recover automatically. For direct connections, initial failures are not retried. After an established connection drops, retries use exponential backoff and jitter from `minDelayMs` (default 1 s) up to `maxDelayMs` (default 30 s), until `disconnect()` or a terminal failure. Tune these with `.withAutomaticReconnect({ minDelayMs, maxDelayMs })`; values below the 500 ms and 1 s floors are raised with a warning, so that retrying clients cannot overwhelm the database. While mounted, the React provider also preserves its separate connection-manager retries: it builds a replacement connection after an initial or terminal failure that the core connection will not retry. It respects an explicit `disconnect()`. diff --git a/skills/typescript-server/SKILL.md b/skills/typescript-server/SKILL.md index d3348b5a04d..18f2987af7d 100644 --- a/skills/typescript-server/SKILL.md +++ b/skills/typescript-server/SKILL.md @@ -13,6 +13,10 @@ metadata: # SpacetimeDB TypeScript SDK Reference +## Runtime Memory + +V8's module memory limit includes `ArrayBuffer` allocations (and typed-array backing buffers), not just ordinary JavaScript objects. Limit peak buffer allocations and copies. This is separate from the storage engine's resident-memory budget; changing table cache policies does not increase the V8 limit. + ## Module Structure Tables are built with `table()`, bound with `schema()`, and exported as default. Reducers and lifecycle hooks are `export const`: @@ -72,7 +76,7 @@ const entity = table( ); ``` -Options: `name` (snake_case, recommended), `public: true`, `event: true`, `indexes: [...]` +Options: `name` (snake_case, recommended), `public: true`, `event: true`, `indexes: [...]`, `cachePolicy: 'required_in_memory' | 'required_on_disk' | 'no_requirement'` (default: `required_in_memory`; see the concepts skill for storage semantics). `ctx.db` accessors are the keys passed to `schema({...})`, verbatim: `schema({ scoreRecord })` -> `ctx.db.scoreRecord`. Keep TypeScript identifiers and accessors camelCase. Use explicit `name: 'snake_case'` strings when you need a canonical database name that differs from the TypeScript identifier. @@ -279,8 +283,18 @@ export default spacetimedb; `myAuth` is the accessor (`ctx.db.myAuth.
`); `auth_data` is the canonical namespace used in SQL and wire names. Without an explicit `name`, the root's case policy derives it (`myAuth` → `my_auth` by default). Pin `name` when renaming an accessor: changing the canonical namespace drops its tables and their data. The library keeps its own flat `ctx.db` accessors. To call a library function directly, pass `ctx.as.myAuth`; inside `withTx`, use `tx.as.myAuth`. Nested TypeScript submodules are supported. Lifecycle reducers and nonempty environment declarations belong in the root. Submodule routers are ignored; register delegated handlers on the root router. Composition is not cross-language. +Inside a submodule view, `ctx.from` also uses the library's local schema keys. For `schema({ sessions })` where the table declares `name: 'auth_sessions'`, return `ctx.from.sessions`, not `ctx.from.auth_sessions` or a consumer namespace prefix. Mount qualification is automatic, including explicitly named tables. Raw SQL uses the full canonical path; never mix an accessor namespace with a canonical table name. See the [submodule view example](https://spacetimedb.com/docs/modules#accessor-and-canonical-namespace-names). + Official reusable libraries include `@spacetimedb/cron`, `@spacetimedb/retry`, `@spacetimedb/rate-limit`, and `@spacetimedb/crypto`. Their registration shapes differ: `@spacetimedb/rate-limit/submodule` is mountable, cron/retry expose factories, and crypto exports helpers. Consult the chosen package's README/exports rather than assuming every package root is a mountable module. +Additional mountable packages include `@spacetimedb/auth/submodule` (application-managed sign-in and sessions, distinct from hosted SpacetimeAuth), `@spacetimedb/agents/submodule` (conversations/model calls), and `@spacetimedb/files/submodule` (database-backed files). Auth and Agents require root initialization via `install(ctx.as.auth)` / `install(ctx.as.agents)`. Auth HTTP handlers must be delegated from the root router; configure its signing key first. Agents hosts must authenticate callers, derive owners from trusted state, and enforce quotas before paid model calls. Files helpers accept `ctx.as.files` from reducers or `tx.as.files` inside `withTx`. These libraries require SDK/CLI/server 2.12+. Follow the [package integration guides](https://spacetimedb.com/docs/modules#reusable-typescript-packages) for exact exports and initialization rather than assuming all packages share an `install` API. + +For large external files, `@spacetimedb/s3/submodule` supplies the private state tables; `@spacetimedb/s3` supplies `client` and `s3Tick`. Declare AWS credentials on the root environment, construct a client with `client(options)`, call its `initialize(tx)` method during initialization, and schedule its `reconcile(ctx, credentials)` method in a procedure. Derive owners on the server. The [S3 guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts) specifies bucket constraints and reconciliation behavior; restoring an old database can remove newer S3 objects under its dedicated prefix. + +For server-side PostHog analytics, mount `@spacetimedb/posthog/submodule` in the root schema, then call `posthog.install(ctx.as.posthog)` from the root init reducer. After the host reducer's authorization and state change, call `posthog.enqueueEventInTx(ctx.as.posthog, args)` to queue an event in that same transaction; it does not make a network request. Use `tx.as.posthog` inside a procedure's `withTx`, not the procedure context. An administrator must configure the provider before scheduled delivery can send events. See the [package integration guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-posthog-ts#integrate-into-an-application) for its exact schema, imports, arguments, and delivery semantics. + +For Stripe billing, mount `@spacetimedb/stripe/submodule`, call `stripe.install(ctx.as.stripe)` from the root init reducer, and configure credentials as an administrator. Register a root HTTP handler that calls `stripe.handleStripeWebhook(ctx, req, { stripe: tx => tx.as.stripe })`; the selector receives the host transaction. Call network helpers such as `stripe.createUserCheckoutSession(ctx.as.stripe, args)` from a procedure, outside `withTx`. Derive `userId`, catalog prices, and return URLs from trusted application context; helpers do not authenticate callers. An optional synchronous `onEvent(tx, event)` callback writes fulfillment records in the same transaction as the webhook state; validate event fields and deduplicate by business-object ID, not only event ID. See the [exact integration schema and fulfillment rules](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts#integrate-into-an-application). + ## Environment Variables ```typescript @@ -494,7 +508,7 @@ Handlers are synchronous: return `SyncResponse` directly rather than marking the ## Module Unit Tests -Use `spacetimedb` 2.12+ and Node.js 22+ in the **module** project, not the client. Set `"type": "module"` in `package.json` and install the test runner with `npm install --save-dev vitest@^3.2.4`. Configure the host-import replacement: +Use `spacetimedb` 2.12+ and a supported Node.js release (22.23.4+, 24.22.1+, or 26.12.1+ on those release lines) in the **module** project, not the client. Set `"type": "module"` in `package.json` and install the test runner with `npm install --save-dev vitest@^3.2.4`. Configure the host-import replacement: ```typescript // vitest.config.ts @@ -522,4 +536,4 @@ it('inserts a record', () => { }); ``` -Run `npx vitest run`. Create a fresh harness per test. `withReducerTx` commits on normal return and rolls back/rethrows on exceptions; do not catch a failure inside the transaction if rollback is expected. Callbacks must be synchronous. Use `TestAuth.fromJwtPayload(JSON.stringify({ iss: 'test', sub: 'alice' }), connectionId)` for client authorization tests; internal auth represents the database, not a client or the publisher. The harness exposes `clock`, `rng`, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or scheduling; invoke lifecycle/scheduled reducers explicitly and retain live integration tests for those host behaviors. +Run `npx vitest run`. Create a fresh harness per test. `withReducerTx` commits on normal return and rolls back/rethrows on exceptions; do not catch a failure inside the transaction if rollback is expected. Callbacks must be synchronous. Use `TestAuth.fromJwtPayload(JSON.stringify({ iss: 'test', sub: 'alice' }), connectionId)` for client authorization tests; internal auth represents the database, not a client or the publisher. The harness exposes `clock`, `rng`, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or scheduling; invoke lifecycle/scheduled reducers explicitly and retain live integration tests for those host behaviors. It does not currently supply namespaced `ctx.as` / `tx.as` helper contexts for mounted submodules; test those integrations against a running database. diff --git a/skills/unreal/SKILL.md b/skills/unreal/SKILL.md index b30759ca5e2..144dfaef4b4 100644 --- a/skills/unreal/SKILL.md +++ b/skills/unreal/SKILL.md @@ -153,7 +153,7 @@ void AGameManager::EndPlay(const EEndPlayReason::Type EndPlayReason) void AGameManager::Tick(float DeltaTime) { - if (Conn && Conn->IsActive()) + if (Conn) // Keep ticking during automatic recovery, too. { Conn->FrameTick(); } @@ -222,6 +222,18 @@ Save the `Token` for future reconnection. The `Identity` is the user's persisten --- +## Automatic Reconnect and Token Refresh + +Automatic reconnect is opt-in: add `->WithAutomaticReconnect()` to the builder. Regenerate bindings to get the reconnect methods. Initial connection failures are not retried; after an established connection drops, retries continue with exponential backoff and jitter. Configure `FAutomaticReconnectOptions.MinDelaySeconds` (default 1) and `MaxDelaySeconds` (default 30) with `->WithAutomaticReconnectOptions(Options)`; the effective floors are 0.5 and 1 second. `Disconnect()` cancels recovery. Keep `FrameTick()` running even when `IsActive()` is false; `IsReconnecting()` reports recovery in progress. + +`OnConnect` runs once. `OnAutomaticReconnect` takes the same `FOnConnectDelegate` and runs after recovery, before subscription replay; use it to save the new token. Register subscriptions and row callbacks once, not on every recovery or `OnApplied`: subscriptions replay atomically, their `OnApplied` callbacks run again, and unchanged rows do not fire row callbacks. Cached rows remain readable but stale until reconciliation. + +Existing disconnect/error delegates keep their signatures. `OnDisconnectWithReconnect` and `OnConnectErrorWithReconnect` additionally receive `bWillReconnect`, `NextReconnectAttempt`, and `NextReconnectDelaySeconds`. Do not create a replacement connection while a retry is pending. Calls are never replayed: interrupted calls may have executed and report `UnknownResult`; calls during recovery report `Disconnected`. + +For expiring credentials, use `WithToken` for the initial token and `WithTokenProvider` for recovery. Its `FTokenProviderDelegate` receives `UReconnectTokenRequest*`; complete it asynchronously with `Request->Complete(NewToken, FString())` or an empty token and an error. Tokens must retain the original identity. Provider failures retry; rejection of a fresh token is terminal. The server must support session replacement and batch subscriptions. See https://spacetimedb.com/docs/clients/unreal#method-withautomaticreconnect. + +--- + ## Subscribing to Tables After connecting, subscribe to receive table data: @@ -304,7 +316,7 @@ UFUNCTION() void OnUserUpdate(const FEventContext& Context, const FUserType& OldRow, const FUserType& NewRow); ``` -Register callbacks before connecting or in `HandleSubscriptionApplied`. +Register row callbacks once before subscribing, for example in `HandleConnect`. Do not register them in `HandleSubscriptionApplied`: it runs again after automatic subscription replay. --- diff --git a/tools/llm-sequential-upgrade/CLAUDE.md b/tools/llm-sequential-upgrade/CLAUDE.md index b83f19f48a9..608cdfa3eda 100644 --- a/tools/llm-sequential-upgrade/CLAUDE.md +++ b/tools/llm-sequential-upgrade/CLAUDE.md @@ -41,6 +41,8 @@ POSIX: `mkdir -p` not `New-Item`, `sleep` not `Start-Sleep`, `2>/dev/null` not ` Do NOT read any files under: - `../llm-oneshot/apps/chat-app/typescript/` (reference implementations) - `../llm-oneshot/apps/chat-app/staging/` +- Published reference apps in the `spacetimedb-llm-oneshot-results` and + `spacetimedb-llm-sequential-upgrade-results` checkouts, wherever they are located - Any other AI-generated app code in this workspace Only read files you created, the backend instructions, and the feature prompts.