Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ spacetime generate --lang typescript|csharp|rust --out-dir ./bindings --module-p
spacetime generate --lang unrealcpp --uproject-dir ./MyGame --module-path ./server --unreal-module-name MyGame
```

### TypeScript Import Extensions

For TypeScript client bindings, `spacetime generate --lang typescript --import-extension none|js|ts` selects the relative import suffix: `none` is the bundler-friendly default, `js` suits `moduleResolution: "nodenext"`, and `ts` suits runtimes executing TypeScript source directly. Set `"import-extension"` per `generate` entry in `spacetime.json` to persist it. This setting changes imports inside generated files, not application imports; NodeNext applications should import an explicit file such as `./module_bindings/index.js`. See https://spacetimedb.com/docs/clients/typescript#import-extensions for direct-TypeScript typecheck settings.

### 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.
Expand Down
2 changes: 1 addition & 1 deletion codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ This describes Spacetime 2.x. The API changed substantially from 1.x, so older a
- **App types.** It is used for games, such as BitCraft Online, and for web apps such as chat, collaboration tools, dashboards, and SaaS. The TypeScript SDK has quickstarts for React, Next.js, Vue, Svelte, and more. ([React quickstart](https://spacetimedb.com/docs/quickstarts/react/))
- **Storage.** Tiered storage keeps hot data in memory and colder data on disk. On Maincloud, tables can also be backed by object storage, so a single database can store an effectively unbounded amount of data. ([How does Spacetime scale?](https://spacetimedb.com/blog/how-does-spacetime-scale))
- **Scaling.** Each database runs its transactions one at a time on a single thread. One app can span many databases with asynchronous inter-database communication, and Maincloud replicates each database. ([How does Spacetime scale?](https://spacetimedb.com/blog/how-does-spacetime-scale))
- **Durability.** Transactions are ACID with serializable isolation. By default, clients see a transaction's results, including the acknowledgment of their own writes, only after it is durable. ([Confirmed reads](https://spacetimedb.com/docs/clients/typescript/#method-withconfirmedreads))
- **Durability.** Transactions are ACID with serializable isolation. By default, clients see a transaction's results, including the acknowledgment of their own writes, only after it is durable. ([Confirmed reads](https://spacetimedb.com/docs/clients/typescript/#method-withconfirmedreads)) An HTTP durability-confirmation timeout after five seconds returns `504` with an unknown outcome, not proof of rollback; do not retry non-idempotent calls without deduplication. ([HTTP calls](https://spacetimedb.com/docs/http/database#post-v1databasename_or_identitycallreducer))
- **Module languages.** TypeScript, Rust, C#, and C++. TypeScript modules run on V8 and can use npm packages, which are bundled when you publish; Rust, C#, and C++ modules compile to WebAssembly. ([Language support](https://spacetimedb.com/docs/intro/language-support/))
- **Composing modules.** TypeScript and C# modules can mount other modules as submodules, each under its own namespace, to reuse logic such as authentication, rate limiting, or email. Official and community modules are listed at spacetimedb.com/modules. ([Modules](https://spacetimedb.com/docs/modules/))
- **External APIs.** Reducers are deterministic and make no network calls. Procedures make outbound HTTP requests, with a 30-second default timeout and a 180-second maximum. ([Procedures](https://spacetimedb.com/docs/functions/procedures/))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ Automatic reconnect is opt-in: add `.WithAutomaticReconnect()` to the builder. I

Keep calling `FrameTick()` while `IsActive` is false. `IsReconnecting` is true while recovering before the next handshake. Use `.OnDisconnect((conn, error, next) => ...)` and `.OnConnectError((error, next) => ...)` to inspect `NextReconnect?`: a non-null value provides `Attempt` and `Delay`; null means no retry is scheduled. Existing callback overloads still work.

`OnConnect` runs on every successful reconnect, so create the subscription in the example above only on the first connection, or move it after `Build()`. Register row callbacks once as well. The same connection, identity, table handles, and subscriptions survive; each attempt gets a fresh `ConnectionId`. Cached rows stay readable but stale during outages. The SDK replays subscriptions in one batch and emits only net row changes. Subscription `OnApplied` runs again after replay; use it to mark data ready, not for repeated one-time setup.
`OnConnect` runs once per `DbConnection`, on the first successful connection. Successful automatic reconnects invoke `OnAutomaticReconnect` before subscription replay instead. Register subscriptions and row callbacks once, either in `OnConnect` or after `Build()`, and use `OnAutomaticReconnect` for recovery-specific work such as saving a refreshed token. The same connection, identity, table handles, and subscriptions survive; each attempt gets a fresh `ConnectionId`. Cached rows stay readable but stale during outages. The SDK replays subscriptions in one batch and emits only net row changes. Subscription `OnApplied` runs again after replay; use it to mark data ready, not for repeated one-time setup.

For expiring credentials, combine `.WithToken(initialToken)` with `.WithTokenProvider(() => RefreshTokenAsync())`, where your provider returns `Task<string>` for the same identity. The provider is not called for the initial connection. Before retries, it is called when remaining validity is at most 30 seconds or 5% of the token lifetime, whichever is greater, when expiry cannot be read, or after a reused token is rejected. Provider failures retry; rejection of a freshly provided token is terminal. No periodic refresh runs while connected. Disconnecting ignores a pending provider result but does not cancel the provider's own work.
For expiring credentials, combine `.WithToken(initialToken)` with `.WithTokenProvider(() => RefreshTokenAsync())`, where your provider returns `Task<string>` for the same identity. The provider is not called for the initial connection. Before retries, it is called when remaining validity is at most 30 seconds or 5% of the token lifetime, whichever is greater, when expiry cannot be read, or after a reused token is rejected. Provider failures retry; rejection of a freshly provided token is terminal. No periodic refresh runs while connected. After recovery, persist the token passed to `OnAutomaticReconnect` if the application stores tokens. Disconnecting ignores a pending provider result but does not cancel the provider's own work.

Calls made while disconnected fail immediately. Pending reducer calls receive `Status.UnknownResult`; pending procedures and one-off queries fail with `UnknownResultException`. These calls may already have executed and are never replayed. Regenerate bindings so unhandled unknown reducer outcomes reach `OnUnhandledReducerError`.

Expand Down
2 changes: 2 additions & 0 deletions codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -507,4 +507,6 @@ mod tests {

`with_reducer_tx` commits on `Ok` and rolls back on `Err` or panic unwinding; propagate reducer errors with `?` when the reducer returns `Result`. Create a new `TestContext` for each test: cloning shares the database. Use `TestAuth::from_jwt_payload(payload, connection_id)?` for client calls and `TestAuth::internal()` for the database itself. The harness exposes `clock`, `rng`, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or timers. Invoke lifecycle/scheduled reducers explicitly and retain integration tests for host behavior.

In SDK 2.13+, native tests support `ProcedureContext::with_tx` and environment reads. Use `TestContext::set_env` / `unset_env` for module-declared environment keys; undeclared keys and disallowed values are rejected. Clones share the same test environment. The `with_tx` panic workaround applies only to SDK 2.12.

See https://spacetimedb.com/docs/how-to/unit-testing for test setup, HTTP mocking, and current limitations.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ metadata:

Generated bindings convert snake_case names to camelCase, including row fields: a server column `trip_id` is `tripId` on client rows.

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.

## React: main.tsx

```typescript
Expand All @@ -34,7 +36,8 @@ function Root() {
.withDatabaseName(MODULE_NAME)
.withToken(localStorage.getItem(TOKEN_KEY) ?? undefined)
.withAutomaticReconnect()
.onConnect((_conn, _identity, token) => localStorage.setItem(TOKEN_KEY, token)),
.onConnect((_conn, _identity, token) => localStorage.setItem(TOKEN_KEY, token))
.onAutomaticReconnect((_conn, _identity, token) => localStorage.setItem(TOKEN_KEY, token)),
[]
);
return (
Expand Down Expand Up @@ -110,6 +113,10 @@ const conn = DbConnection.builder()
localStorage.setItem(TOKEN_KEY, token);
console.log('Connected as:', identity.toHexString());
})
.onAutomaticReconnect((_conn, identity, token) => {
localStorage.setItem(TOKEN_KEY, token);
console.log('Reconnected as:', identity.toHexString());
})
.onDisconnect((_ctx, error, nextAttempt, delayMs) => {
if (nextAttempt !== undefined) {
console.warn(`Reconnect attempt ${nextAttempt} in ${delayMs} ms`, error);
Expand Down Expand Up @@ -161,7 +168,7 @@ Use explicit queries for every table on that connection, not subscribe-all, whic

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()`.

The same connection, identity, table handles, subscriptions, and row callbacks survive recovery. Each attempt gets a fresh connection ID. `onConnect` runs again before subscription replay, so register subscriptions and row callbacks once, outside that callback. The SDK replays subscriptions in one batch, retains readable but stale cached rows during outages, and emits net row changes after reconciliation. Subscription `onApplied` runs again after replay; keep one-time setup separate.
The same connection, identity, table handles, subscriptions, and row callbacks survive recovery. Each attempt gets a fresh connection ID. `onConnect` fires once per `DbConnection`; successful automatic reconnects invoke `onAutomaticReconnect` before subscription replay instead. Register subscriptions and row callbacks once, either in `onConnect` or after `build()`, and use `onAutomaticReconnect` for recovery-specific work such as saving a refreshed token. The SDK replays subscriptions in one batch, retains readable but stale cached rows during outages, and emits net row changes after reconciliation. Subscription `onApplied` runs again after replay; keep one-time setup separate.

In React, let `useTable` manage its own subscriptions. Do not add a second subscription effect for the same queries or recreate subscriptions whenever `isActive` changes. Use the hook's `isReady` result for data readiness: a successful reconnect handshake does not mean replay has completed. Invoke reducers from event handlers, not during rendering. For a manually created subscription, retain its handle and call `unsubscribe()` when it is no longer needed, including during an outage.

Expand Down
4 changes: 2 additions & 2 deletions codex-plugin/plugins/spacetimedb/skills/unity/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public class SpacetimeManager : MonoBehaviour

## Automatic Reconnect

Add `.WithAutomaticReconnect()` to the builder to recover an established connection after an outage. In the singleton above, create subscriptions only on the first `OnConnected`, or move them after `Build()`: `OnConnected` runs again after each successful reconnect. Keep calling `FrameTick()` during outages, or use `SpacetimeDBNetworkManager`, which also ticks reconnecting connections. Do not gate ticking on `IsActive`.
Add `.WithAutomaticReconnect()` to the builder to recover an established connection after an outage. In the singleton above, create subscriptions in `OnConnected` or move them after `Build()`: `OnConnected` runs only on the first successful connection. Successful automatic reconnects invoke `OnAutomaticReconnect` before subscription replay; use it for recovery-specific work such as saving a refreshed token. Keep calling `FrameTick()` during outages, or use `SpacetimeDBNetworkManager`, which also ticks reconnecting connections. Do not gate ticking on `IsActive`.

The SDK retains the identity, table handles, callbacks, and subscriptions, and replays subscriptions in one batch. Cached rows stay readable during an outage; row callbacks report net changes after recovery. `OnApplied` runs again, so separate one-time object setup from marking data ready. Each reconnect attempt has a fresh `ConnectionId`.

Expand Down Expand Up @@ -234,6 +234,6 @@ The SpacetimeDB SDK uses code generation. If you encounter issues with IL2CPP bu
### Token Persistence
Token save/load via `PlayerPrefs` is demonstrated in the SpacetimeManager singleton above. Persisting the server-issued token and passing it back on reconnect keeps the same identity; without a saved token the server issues a new identity in the `OnConnect` callback. This token does not expire and a lost one can't be recovered, so self-issued identities are for development. For production, authenticate with an OIDC provider such as SpacetimeAuth, which handles token lifecycle.

With automatic reconnect enabled, the SDK retains the authentication token and passes it to `OnConnect`, including on WebGL. Without automatic reconnect, a WebGL connection using a saved token may return a short-lived WebSocket token instead; in that case, keep the original saved token rather than overwriting it in the callback above.
With automatic reconnect enabled, the SDK retains the authentication token and passes it to `OnConnect` on the initial connection, including on WebGL. Successful recovery passes the retained or refreshed token to `OnAutomaticReconnect`. Without automatic reconnect, a WebGL connection using a saved token may return a short-lived WebSocket token instead; in that case, keep the original saved token rather than overwriting it in the callback above.

For expiring credentials, configure `.WithToken(initialToken)`, `.WithAutomaticReconnect()`, and `.WithTokenProvider(() => RefreshTokenAsync())`. The provider returns `Task<string>` for the same identity. It is used before reconnect attempts when expiry is unreadable, remaining validity is at most 30 seconds or 5% of the original lifetime, or a reused token is rejected. It is not called for the initial connection or periodically while connected. Provider failures retry; rejection of a freshly provided token stops recovery. `Disconnect()` ignores a pending provider result without canceling the provider's own asynchronous work.
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ For all available publishing options and flags, see the [`spacetime publish` CLI

### Environment Variables

Modules can declare environment variables for configuration and secrets. Each publish supplies the complete set of values from the target's `env` configuration and declared shell variables. Required values must be supplied on every publish; omitted optional values are removed. The module and its environment update atomically.
Modules can declare environment variables for configuration and secrets. Each publish supplies values from the target's `env` configuration and declared shell variables, then preserves unspecified stored values by default. Required values must exist in the resulting environment; optional values are removed only when you unset them explicitly or use `--replace-env`. The module and its environment update atomically.

See [Environment Variables](./00700-environment-variables.md) for declarations, reading values in module code, publishing examples, and private tables for secrets that need to change without republishing.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ The sending module needs **receiver bindings**: code generated from the receivin

`parent` makes `game-world` a child database of `lobby` when it's first published, so that it inherits the lobby's team permissions. Async IDC doesn't require this; any database can call another on the same server.

`name` is the name of the directory created for the generated code, and `database` refers to either a deployed receiving database or the receiving database's source code. Next generate the bindings:
`name` is the name of the directory created for the generated code. `database` must match another target in the same `spacetime.json`; here, it selects the `game-world` child's local `./game_world` module source. It does not fetch a deployed database's schema, so the receiving module's source must be available locally. Next generate the bindings:

```bash
spacetime generate lobby
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,12 @@ Use the context-provided random API for any reducer logic that needs random valu
const fraction = ctx.random(); // [0.0, 1.0)
const roll = ctx.random.integerInRange(1, 6); // inclusive
const bytes = ctx.random.fill(new Uint8Array(16));
const cards = ['ace', 'king', 'queen'];
const shuffledCards = ctx.random.shuffle([...cards]);
```

In SpacetimeDB 2.13+, `ctx.random.shuffle(array)` shuffles the array in place and returns the same array. Copy it first, as above, to preserve the original order.

</TabItem>
<TabItem value="csharp" label="C#">

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ const myTable = table(
const spacetimedb = schema({ myTable });
export default spacetimedb;

export const insertAValue = spacetimedb.procedure({ a: t.u32(), b: t.u32() }, t.unit(), (ctx, { a, b }) => {
export const insertAValue = spacetimedb.procedure({ a: t.u32(), b: t.string() }, t.unit(), (ctx, { a, b }) => {
ctx.withTx(ctx => {
ctx.db.myTable.insert({ a, b });
});
Expand Down Expand Up @@ -915,6 +915,11 @@ Procedures can't send requests at the same time as holding open a [transaction](
</TabItem>
</Tabs>

Procedure HTTP requests automatically accept gzip and Brotli responses and expose the decoded
Comment thread
clockwork-labs-bot marked this conversation as resolved.
Resolved
response body to module code. If you set an `Accept-Encoding` header yourself, the response body is
still decoded by the host, so do not manually decompress it in the module. Headers that describe the
compressed wire body, such as `Content-Encoding` and `Content-Length`, may be absent after decoding.

:::note
If no timeout is specified, HTTP requests default to 30 seconds. User-specified timeouts are clamped to a maximum of 180 seconds by the host.
:::
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,9 @@ public static readonly List<string> OIDC_CLIENT_IDS = new()
{
"client_XXXXXXXXXXXXXXXXXXXXXX",
};
public void Connect(ReducerContext ctx)

[Reducer(ReducerKind.ClientConnected)]
public static void Connect(ReducerContext ctx)
{
var claims = ctx.SenderAuth.Jwt ?? throw new Exception("Client connected without JWT");
if (claims.Issuer != "https://auth.spacetimedb.com/oidc")
Expand Down
Loading
Loading