Skip to content

Commit 837c1f7

Browse files
committed
Add Stack Bench and supporting SDK improvements
1 parent baca5cd commit 837c1f7

900 files changed

Lines changed: 158924 additions & 73 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.gitattributes‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,5 @@
22
**/ModuleBindings/** linguist-generated=true eol=lf
33
/docs/llms/** linguist-generated=true
44
/docs/llms/*-details.json linguist-generated=false
5+
/tools/stack-bench/** text eol=lf
6+
/tools/stack-bench/**/*.woff2 -text -diff

‎codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,8 @@ Lifecycle: Write → Compile → Publish (`spacetime publish`) → Hot-swap (rep
101101

102102
## Identity
103103

104-
- **Identity**: A long-lived, globally unique identifier for a user.
105-
- **ConnectionId**: Identifies a specific client connection.
104+
- **Identity**: A long-lived, globally unique identifier for a user, derived from the token's issuer and subject claims. The same token yields the same identity on every connection.
105+
- **ConnectionId**: Identifies one client connection. A new connection gets a new connection ID; a disconnect ends the connection, not the identity.
106106
- Always use `ctx.sender` / `ctx.Sender` / `ctx.sender()` for authorization.
107107

108108
SpacetimeDB works with many OIDC providers, including SpacetimeAuth (built-in), Auth0, Clerk, Keycloak, Google, and GitHub.

‎codex-plugin/plugins/spacetimedb/skills/cpp-server/SKILL.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,8 @@ SPACETIMEDB_CLIENT_DISCONNECTED(on_disconnect, ReducerContext ctx) {
138138
}
139139
```
140140

141+
Connection hooks run once per connection. The same authenticated principal keeps the same identity (`ctx.sender()`) across connections, while each connection has its own connection ID (`ctx.connection_id()`). A disconnect ends one connection; it does not end the identity, which returns unchanged on the next connection with the same token. Use connection IDs for presence and other connection-scoped state.
142+
141143
## Authentication & Timestamps
142144

143145
```cpp

‎codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,9 @@ public static void OnConnect(ReducerContext ctx) { ... }
162162
public static void OnDisconnect(ReducerContext ctx) { ... }
163163
```
164164

165-
`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.
165+
Connection hooks run once per connection. The same authenticated principal keeps the same identity (`ctx.Sender`) across connections, while each connection has its own connection ID (`ctx.ConnectionId`). A disconnect ends one connection; it does not end the identity, which returns unchanged on the next connection with the same token. Use connection IDs for presence and other connection-scoped state.
166+
167+
`ctx.ConnectionId` is typed `ConnectionId?`. It is present inside connection lifecycle reducers and reducers invoked over a connection, and null in `Init` and scheduled reducers. Check or unwrap it before storing it in a non-nullable column or passing it to an index accessor.
166168

167169
## Views
168170

‎codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,8 @@ pub fn on_connect(ctx: &ReducerContext) { ... }
150150
pub fn on_disconnect(ctx: &ReducerContext) { ... }
151151
```
152152

153+
Connection hooks run once per connection. The same authenticated principal keeps the same identity (`ctx.sender()`) across connections, while each connection has its own connection ID (`ctx.connection_id()`). A disconnect ends one connection; it does not end the identity, which returns unchanged on the next connection with the same token. Use connection IDs for presence and other connection-scoped state.
154+
153155
The current connection ID is available through `ctx.connection_id()` (not a public field) and may be absent outside connection-scoped calls.
154156

155157
## Views

‎codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md‎

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Generated bindings convert snake_case names to camelCase, including row fields:
1818
## React: main.tsx
1919

2020
```typescript
21-
import React, { useEffect, useMemo } from 'react';
21+
import React, { useMemo } from 'react';
2222
import ReactDOM from 'react-dom/client';
2323
import { SpacetimeDBProvider } from 'spacetimedb/react';
2424
import { DbConnection } from './module_bindings';
@@ -30,6 +30,7 @@ function Root() {
3030
DbConnection.builder()
3131
.withUri(SPACETIMEDB_URI)
3232
.withDatabaseName(MODULE_NAME)
33+
// Reuse the token issued on the previous connection.
3334
.withToken(localStorage.getItem('auth_token') || undefined),
3435
[]
3536
);
@@ -46,27 +47,18 @@ ReactDOM.createRoot(document.getElementById('root')!).render(<Root />);
4647
## React: App.tsx
4748

4849
```typescript
50+
import { useEffect } from 'react';
4951
import { useTable, useSpacetimeDB } from 'spacetimedb/react';
5052
import { DbConnection, tables } from './module_bindings';
5153

5254
function App() {
53-
const { isActive, identity: myIdentity, token, getConnection } = useSpacetimeDB();
55+
const { identity: myIdentity, token, getConnection } = useSpacetimeDB();
5456
const conn = getConnection() as DbConnection | null;
5557

56-
// Save auth token
58+
// Persist the issued token for the next page load.
5759
useEffect(() => { if (token) localStorage.setItem('auth_token', token); }, [token]);
5860

59-
// Subscribe when connected. Prefer typed query builders over raw SQL
60-
useEffect(() => {
61-
if (!conn || !isActive) return;
62-
conn.subscriptionBuilder()
63-
.onApplied(() => setSubscribed(true))
64-
.subscribe([tables.entity, tables.record]);
65-
// Or with filters: tables.entity.where(r => r.active.eq(true))
66-
// Or raw SQL: 'SELECT * FROM entity'
67-
}, [conn, isActive]);
68-
69-
// Reactive data. Returns [rows, isReady]
61+
// useTable owns the subscription and cleanup. Returns [rows, isReady].
7062
const [entities, entitiesReady] = useTable(tables.entity);
7163
const [records, recordsReady] = useTable(tables.record);
7264

@@ -80,8 +72,8 @@ function App() {
8072
}
8173
);
8274

83-
// Call reducers with object syntax
84-
conn?.reducers.addRecord({ data }).catch(console.error);
75+
// A callback for a UI event; defining it does not call the reducer during render.
76+
const addRecord = (data: string) => conn?.reducers.addRecord({ data }).catch(console.error);
8577

8678
// Compare identities
8779
const isMe = row.owner.toHexString() === myIdentity?.toHexString();
@@ -111,7 +103,9 @@ conn.db.user.onUpdate((ctx, oldUser, newUser) => console.log('Updated:', newUser
111103

112104
## Gotchas
113105

114-
- **`useTable` rows are `readonly`.** Copy before sorting/mutating, or it fails to type-check:
106+
- **Subscription rows have no presentation order.** A server view's array order does not
107+
define client cache iteration order. `useTable` rows are `readonly`; a sorted copy can
108+
express the application's display order:
115109
`const [rows] = useTable(tables.message); const sorted = [...rows].sort(...)`.
116-
- **bigint in JSX.** ids/counts from `t.u64()`/`t.i64()` columns are `bigint`, which React
117-
cannot render. Wrap it: `{Number(row.id)}` or `{String(count)}`.
110+
- **64-bit display values.** `{String(row.id)}` preserves the full `bigint` value.
111+
Conversion to `Number` can lose precision outside JavaScript's safe integer range.

‎codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,11 @@ Every column is a `t` builder value:
9898

9999
Modifiers: `.primaryKey()`, `.autoInc()`, `.unique()`, `.index('btree')`, `.default(value)`.
100100

101+
`.primaryKey()` and `.unique()` apply to one column. For uniqueness across
102+
multiple columns, use a surrogate key, the multi-column index below, and a
103+
reducer that rejects an existing index match before inserting. An index alone
104+
does not enforce uniqueness.
105+
101106
Use `.default(value)` only for a newly appended migration-safe field. Do not put defaults on primary-key, unique, or auto-increment columns.
102107

103108
Optional columns: `nickname: t.option(t.string())`
@@ -130,7 +135,9 @@ export { default } from './schema'; // re-export the schema for the module ent
130135

131136
## Reducers
132137

133-
Reducers are created with `spacetimedb.reducer(...)`; the export name becomes the reducer name:
138+
Reducers are created with `spacetimedb.reducer(...)`. An exported `signUp`
139+
becomes `signUp` in generated clients and `sign_up` in `spacetime call` and
140+
`describe`:
134141

135142
```typescript
136143
export const createEntity = spacetimedb.reducer(
@@ -178,10 +185,17 @@ export const onConnect = spacetimedb.clientConnected((ctx) => { ... });
178185
export const onDisconnect = spacetimedb.clientDisconnected((ctx) => { ... });
179186
```
180187

181-
`ctx.connectionId` is `ConnectionId | null`, including in lifecycle contexts. Guard it before passing it to a helper or using it as a table key.
188+
Connection hooks run once per connection. The same authenticated principal keeps the same identity (`ctx.sender`) across connections, while each connection has its own connection ID (`ctx.connectionId`). A disconnect ends one connection; it does not end the identity, which returns unchanged on the next connection with the same token. Use connection IDs for presence and other connection-scoped state.
189+
190+
`ctx.connectionId` is typed `ConnectionId | null`. It is present inside connection lifecycle hooks and reducers invoked over a connection, and `null` in `init` and scheduled reducers. Guard it before passing it to a helper or using it as a table key.
182191

183192
## Reducer Context API
184193

194+
Each reducer call runs in one database transaction. An error that escapes the
195+
reducer rolls back its database changes. `ctx.sender` identifies the caller;
196+
application roles and permissions are not inferred from that identity. Table
197+
visibility and view filters control reads, not authorization to call reducers.
198+
185199
`ctx` is the only source of sender identity, time, and randomness; stdlib clocks and RNG are unavailable in modules. Let exported callbacks infer their context type. In helpers, use `ReducerCtx<InferSchema<typeof spacetimedb>>`; do not annotate a context as `any`, because that erases table row types and can make `bigint` expressions infer as `number`.
186200

187201
```typescript
@@ -278,17 +292,30 @@ const Shape = t.enum('Shape', {
278292
A client subscribing to a view receives only the rows it returns. Use a per-user view
279293
(keyed on `ctx.sender`) for per-viewer access control: deleting a row it depends on
280294
(e.g. a membership row) automatically drops the rows it was exposing from that client.
295+
Use index accessors in views. Do not scan a whole table with `.iter()` when an
296+
indexed lookup can select the required rows.
281297

282298
`t.row(...)` and `t.object(...)` return schema builders, not TypeScript runtime row types. Let a view callback infer its result, or annotate a separately declared structural type such as `Array<{ sku: bigint; label: string }>`. A named output type must not reuse the generated PascalCase name of its view accessor (for example, reserve `DiscountedProduct` for a `discounted_product` view).
283299

300+
A view context is `ViewCtx<S>` (and `AnonymousViewCtx<S>`), both exported from
301+
`spacetimedb/server`. It carries `sender`, a read-only `db`, and `from`; it is
302+
not a `ReducerCtx`, so a helper shared between a reducer and a view must accept
303+
either:
304+
305+
```typescript
306+
import type { ReducerCtx, ViewCtx, InferSchema } from 'spacetimedb/server';
307+
type S = InferSchema<typeof spacetimedb>;
308+
function stockOf(ctx: ReducerCtx<S> | ViewCtx<S>, itemId: bigint) { ... }
309+
```
310+
284311
Both `spacetimedb.view(...)` and `spacetimedb.anonymousView(...)` take three arguments: view options, the declared return schema, and the callback.
285312

286313
```typescript
287314
// Anonymous view (same for all clients):
288315
export const activeUsers = spacetimedb.anonymousView(
289316
{ name: 'active_users', public: true },
290317
t.array(entity.rowType),
291-
(ctx) => [...ctx.db.entity.iter()].filter(e => e.active)
318+
(ctx) => [...ctx.db.entity.active.filter(true)] // active: t.bool().index('btree')
292319
);
293320

294321
// Per-user view (varies by ctx.sender):

‎crates/bindings-typescript/src/lib/query.ts‎

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -248,19 +248,21 @@ export type NamespacedQueryBuilder<SchemaDef extends UntypedSchemaDef> =
248248
* A runtime reference to a table. This materializes the RowExpr for us.
249249
* TODO: Maybe add the full SchemaDef to the type signature depending on how joins will work.
250250
*/
251-
export type TableRef<TableDef extends TypedTableDef> = Readonly<{
252-
type: 'table';
253-
sourceName: TableDef['sourceName'];
254-
accessorName: string;
255-
cols: RowExpr<TableDef>;
256-
indexedCols: IndexedRowExpr<TableDef>;
257-
tableDef: TableDef;
251+
// Keep this named so TypeScript diagnostics show `TableRef` instead of its
252+
// expanded structure.
253+
export interface TableRef<TableDef extends TypedTableDef> {
254+
readonly type: 'table';
255+
readonly sourceName: TableDef['sourceName'];
256+
readonly accessorName: string;
257+
readonly cols: RowExpr<TableDef>;
258+
readonly indexedCols: IndexedRowExpr<TableDef>;
259+
readonly tableDef: TableDef;
258260
// Delegated UntypedTableDef properties for compatibility.
259-
columns: TableDef['columns'];
260-
indexes: TableDef['indexes'];
261-
rowType: TableDef['rowType'];
262-
constraints: any;
263-
}>;
261+
readonly columns: TableDef['columns'];
262+
readonly indexes: TableDef['indexes'];
263+
readonly rowType: TableDef['rowType'];
264+
readonly constraints: any;
265+
}
264266

265267
class TableRefImpl<TableDef extends TypedTableDef>
266268
implements TableRef<TableDef>, From<TableDef>
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2+
import { tmpdir } from 'node:os';
3+
import path from 'node:path';
4+
import { fileURLToPath } from 'node:url';
5+
import * as ts from 'typescript';
6+
import { describe, expect, it } from 'vitest';
7+
8+
const bindingsRoot = path.resolve(
9+
path.dirname(fileURLToPath(import.meta.url)),
10+
'..'
11+
);
12+
13+
function runTypecheck(source: string) {
14+
const tmpDir = mkdtempSync(path.join(tmpdir(), 'stdb-tableref-diag-'));
15+
const reproPath = path.join(tmpDir, 'repro.ts');
16+
writeFileSync(reproPath, source);
17+
18+
try {
19+
const options: ts.CompilerOptions = {
20+
target: ts.ScriptTarget.ESNext,
21+
module: ts.ModuleKind.ESNext,
22+
strict: true,
23+
noEmit: true,
24+
skipLibCheck: true,
25+
forceConsistentCasingInFileNames: true,
26+
allowImportingTsExtensions: true,
27+
noImplicitAny: true,
28+
moduleResolution: ts.ModuleResolutionKind.Bundler,
29+
useDefineForClassFields: true,
30+
verbatimModuleSyntax: true,
31+
isolatedModules: true,
32+
};
33+
34+
const host = ts.createCompilerHost(options);
35+
const program = ts.createProgram(
36+
[reproPath, path.join(bindingsRoot, 'src/server/sys.d.ts')],
37+
options,
38+
host
39+
);
40+
const diagnostics = ts.getPreEmitDiagnostics(program);
41+
return diagnostics.map(d =>
42+
ts.flattenDiagnosticMessageText(d.messageText, '\n')
43+
);
44+
} finally {
45+
rmSync(tmpDir, { recursive: true, force: true });
46+
}
47+
}
48+
49+
describe('TableRef diagnostics', () => {
50+
const source = `
51+
import { t } from ${JSON.stringify(path.join(bindingsRoot, 'src/server/index.ts'))};
52+
import { table } from ${JSON.stringify(path.join(bindingsRoot, 'src/lib/table.ts'))};
53+
import { createTableRefFromDef } from ${JSON.stringify(path.join(bindingsRoot, 'src/lib/query.ts'))};
54+
import type { AllUnique } from ${JSON.stringify(path.join(bindingsRoot, 'src/lib/constraints.ts'))};
55+
56+
const cartItem = table(
57+
{ name: 'cart_item' },
58+
{ id: t.u64().primaryKey().autoInc(), accountId: t.u64(), quantity: t.u32() }
59+
);
60+
61+
const ref = createTableRefFromDef(cartItem as any, 'cartItem');
62+
type Boom = AllUnique<typeof ref, ['accountId']>;
63+
declare const b: Boom;
64+
`;
65+
66+
it('names the type instead of dumping its structure', () => {
67+
const messages = runTypecheck(source);
68+
const constraintError = messages.find(m =>
69+
m.includes("does not satisfy the constraint 'UntypedTableDef'")
70+
);
71+
72+
expect(constraintError).toBeDefined();
73+
// The name, not the shape.
74+
expect(constraintError).toContain('TableRef<');
75+
expect(constraintError).not.toContain('type: "table"');
76+
expect(constraintError).not.toContain('accessorName');
77+
expect(constraintError.length).toBeLessThan(250);
78+
}, 15000);
79+
});

‎crates/cli/build.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ fn generate_template_files() {
110110

111111
// Embed skill files from skills/*/SKILL.md
112112
let skills_dir = repo_root.join("skills");
113+
println!("cargo:rerun-if-changed={}", skills_dir.display());
113114
let skill_names = discover_skill_names(&skills_dir);
114115

115116
generated_code.push_str("pub fn get_skill(name: &str) -> Option<&'static str> {\n");

0 commit comments

Comments
 (0)