diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 60dccca517c..82bc1434fc0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2402,3 +2402,37 @@ jobs: # - name: Print rows in the user table # if: always() # run: spacetime sql quickstart-chat "SELECT * FROM user" + + typescript-submodules: + needs: [merge_queue_noop, upload-build-artifacts-linux] + if: ${{ needs.merge_queue_noop.outputs.skip != 'true' }} + name: TypeScript - Submodules + runs-on: spacetimedb-new-runner-2 + env: + ARTIFACT_SUFFIX: linux + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + + - uses: ./.github/actions/setup-pnpm + with: + run_install: true + + - name: Install Rust toolchain + uses: dsherret/rust-toolchain-file@v1 + - name: Set default rust toolchain + run: rustup default $(rustup show active-toolchain | cut -d' ' -f1) + + - *set-cargo-target-dir + - *download-build-artifacts + - *extract-build-artifacts + + - *expose-spacetime-cli + + - name: Check TypeScript submodules + run: cargo ci typescript-submodules diff --git a/.gitignore b/.gitignore index 9a0feb4a739..a907d1c78eb 100644 --- a/.gitignore +++ b/.gitignore @@ -205,6 +205,14 @@ __pycache__/ ## JetBrains .idea/ +# TypeScript submodule development outputs +spacetime-*-ts/example/.stdb-server-token +spacetime-*-ts/example/public/app.js +spacetime-*-ts/example/public/app.js.map +spacetime-*-ts/example/public/app.css +spacetime-*-ts/example/public/app.css.map +spacetime-*-ts/ts-codegen/ + /protobuf cs-src/ crates/bench/spacetime.svg diff --git a/.prettierignore b/.prettierignore index 5ac53d5578c..79e3414c0ff 100644 --- a/.prettierignore +++ b/.prettierignore @@ -4,4 +4,9 @@ dist target .github coverage +**/public/app.js +**/public/app.js.map +**/public/app.css +**/public/app.css.map +**/src/module_bindings/** crates/bindings-typescript/src/server/test-utils/portable-datastore-wasm diff --git a/Cargo.lock b/Cargo.lock index 46f43fca21e..1a540dbad83 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1133,6 +1133,15 @@ dependencies = [ "duct", ] +[[package]] +name = "ci-typescript-submodules" +version = "0.1.0" +dependencies = [ + "anyhow", + "ci-common", + "clap 4.5.50", +] + [[package]] name = "ci-typescript-test" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 9e843d8acd8..5325197d478 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -87,6 +87,7 @@ members = [ "tools/ci/commands/publish-checks", "tools/ci/commands/run-spacetime", "tools/ci/commands/typescript-test", + "tools/ci/commands/typescript-submodules", "tools/ci/commands/version-upgrade-check", "tools/ci/commands/docs", "tools/ci/commands/codeowners-check", diff --git a/crates/bindings-typescript/src/lib/type_builders.ts b/crates/bindings-typescript/src/lib/type_builders.ts index 41d2da11015..a2609c24f8e 100644 --- a/crates/bindings-typescript/src/lib/type_builders.ts +++ b/crates/bindings-typescript/src/lib/type_builders.ts @@ -1762,6 +1762,9 @@ class SimpleSumBuilderImpl } } +// Named so declaration files can refer to enum and unit builder instances. +export type { SumBuilderImpl, SimpleSumBuilderImpl, UnitBuilder }; + export const SimpleSumBuilder: { new ( variants: Variants, diff --git a/crates/bindings-typescript/src/server/index.ts b/crates/bindings-typescript/src/server/index.ts index c3a3d3c1458..afcf332ee34 100644 --- a/crates/bindings-typescript/src/server/index.ts +++ b/crates/bindings-typescript/src/server/index.ts @@ -38,4 +38,13 @@ export { ScheduleAt } from '../lib/schedule_at'; export type { Environment } from './environment'; +// Named so libraries built on this package can emit declaration files for +// the tables, schemas, and exports they create. +export type { CoerceRow } from '../lib/table'; +export type { TableSchema } from '../lib/table_schema'; +export type { TablesToSchema } from '../lib/schema'; +export type { EnvironmentValue } from '../lib/environment'; +export type { ReadonlyDbView } from './db_view'; +export type { Schema } from './schema'; + import './polyfills'; // Ensure polyfills are loaded diff --git a/eslint.config.js b/eslint.config.js index 1594430d0d0..f3928b57aa2 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -20,6 +20,9 @@ export default tseslint.config( '**/dist/**', '**/build/**', '**/coverage/**', + '**/public/app.js', + '**/src/module_bindings/**', + '**/ts-codegen/**', '**/templates/angular-ts/.angular/**', '**/src/server/test-utils/portable-datastore-wasm/**', ], @@ -63,6 +66,7 @@ export default tseslint.config( './tsconfig.json', './crates/bindings-typescript/tsconfig.json', './crates/bindings-typescript/test-app/tsconfig.json', + './spacetime-example-ui-ts/tsconfig.json', './templates/react-ts/tsconfig.json', './templates/chat-react-ts/tsconfig.json', './templates/money-exchange-react-ts/tsconfig.json', @@ -119,6 +123,19 @@ export default tseslint.config( ], }, }, + { + files: ['spacetime-*-ts/**/example/public/ui.js'], + languageOptions: { + sourceType: 'script', + globals: globals.browser, + }, + }, + { + files: ['spacetime-*-ts/**/*.{ts,tsx}'], + rules: { + '@typescript-eslint/no-explicit-any': 'error', + }, + }, { files: ['templates/angular-ts/src/**/*.ts'], rules: { diff --git a/package.json b/package.json index a97c459e51c..eee6d27f423 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ }, "type": "module", "scripts": { - "run-all": "pnpm -r -F ./crates/bindings-typescript -F ./crates/bindings-typescript/examples/quickstart-chat -F ./crates/bindings-typescript/test-app -F ./docs -F \"./templates/**\" run", + "run-all": "pnpm -r -F ./crates/bindings-typescript -F ./crates/bindings-typescript/test-app -F ./docs -F \"./templates/**\" -F \"./spacetime-*-ts/**\" run", "format": "pnpm run-all format && prettier eslint.config.js --write", "lint": "pnpm run-all lint && prettier eslint.config.js --check", "build": "pnpm run-all build", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b81af01e332..1824325e226 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -384,6 +384,339 @@ importers: specifier: ~5.6.2 version: 5.6.3 + spacetime-cron-ts: + dependencies: + cron-parser: + specifier: 5.5.0 + version: 5.5.0 + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + eslint: + specifier: ^9.17.0 + version: 9.33.0(jiti@2.6.1) + prettier: + specifier: ^3.3.3 + version: 3.6.2 + spacetimedb: + specifier: workspace:* + version: link:../crates/bindings-typescript + tsx: + specifier: ^4.21.0 + version: 4.21.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-cron-ts/example: + dependencies: + '@spacetimedb/example-ui': + specifier: workspace:* + version: link:../../spacetime-example-ui-ts + dotenv: + specifier: ^16.4.7 + version: 16.6.1 + express: + specifier: ^4.21.2 + version: 4.21.2 + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/express': + specifier: ^4.17.21 + version: 4.17.23 + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + esbuild: + specifier: ^0.28.0 + version: 0.28.2 + tsx: + specifier: ^4.21.0 + version: 4.21.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-cron-ts/example/spacetimedb: + dependencies: + '@spacetimedb/cron': + specifier: workspace:* + version: link:../.. + spacetimedb: + specifier: workspace:* + version: link:../../../crates/bindings-typescript + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-cron-ts/spacetimedb: + dependencies: + '@spacetimedb/cron': + specifier: workspace:* + version: link:.. + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-crypto-ts: + dependencies: + '@noble/hashes': + specifier: ^2.2.0 + version: 2.4.0 + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + eslint: + specifier: ^9.17.0 + version: 9.33.0(jiti@2.6.1) + prettier: + specifier: ^3.3.3 + version: 3.6.2 + tsx: + specifier: ^4.21.0 + version: 4.21.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-example-ui-ts: + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + eslint: + specifier: ^9.17.0 + version: 9.33.0(jiti@2.6.1) + jsdom: + specifier: ^26.1.0 + version: 26.1.0 + prettier: + specifier: ^3.3.3 + version: 3.6.2 + typescript: + specifier: ~5.6.2 + version: 5.6.3 + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + + spacetime-rate-limit-ts: + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + eslint: + specifier: ^9.17.0 + version: 9.33.0(jiti@2.6.1) + prettier: + specifier: ^3.3.3 + version: 3.6.2 + spacetimedb: + specifier: workspace:* + version: link:../crates/bindings-typescript + tsx: + specifier: ^4.21.0 + version: 4.21.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-rate-limit-ts/example: + dependencies: + '@spacetimedb/example-ui': + specifier: workspace:* + version: link:../../spacetime-example-ui-ts + dotenv: + specifier: ^16.4.7 + version: 16.6.1 + express: + specifier: ^4.21.2 + version: 4.21.2 + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/express': + specifier: ^4.17.21 + version: 4.17.23 + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + esbuild: + specifier: ^0.28.0 + version: 0.28.2 + tsx: + specifier: ^4.21.0 + version: 4.21.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-rate-limit-ts/example/spacetimedb: + dependencies: + '@spacetimedb/rate-limit': + specifier: workspace:* + version: link:../.. + spacetimedb: + specifier: workspace:* + version: link:../../../crates/bindings-typescript + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-rate-limit-ts/spacetimedb: + dependencies: + '@spacetimedb/rate-limit': + specifier: workspace:* + version: link:.. + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-resend-ts: + dependencies: + '@spacetimedb/crypto': + specifier: workspace:^ + version: link:../spacetime-crypto-ts + valibot: + specifier: ^1.4.2 + version: 1.5.0(typescript@5.9.3) + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + eslint: + specifier: ^9.17.0 + version: 9.33.0(jiti@2.6.1) + prettier: + specifier: ^3.3.3 + version: 3.6.2 + spacetimedb: + specifier: workspace:* + version: link:../crates/bindings-typescript + tsx: + specifier: ^4.21.0 + version: 4.21.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-resend-ts/example: + dependencies: + '@spacetimedb/example-ui': + specifier: workspace:* + version: link:../../spacetime-example-ui-ts + dotenv: + specifier: ^16.4.7 + version: 16.6.1 + express: + specifier: ^4.21.2 + version: 4.21.2 + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/express': + specifier: ^4.17.21 + version: 4.17.23 + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + esbuild: + specifier: ^0.28.0 + version: 0.28.2 + resend: + specifier: ^6.12.2 + version: 6.30.0 + tsx: + specifier: ^4.21.0 + version: 4.21.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-resend-ts/example/spacetimedb: + dependencies: + '@spacetimedb/rate-limit': + specifier: workspace:* + version: link:../../../spacetime-rate-limit-ts + '@spacetimedb/resend': + specifier: workspace:* + version: link:../.. + spacetimedb: + specifier: workspace:* + version: link:../../../crates/bindings-typescript + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-retry-ts: + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + eslint: + specifier: ^9.17.0 + version: 9.33.0(jiti@2.6.1) + prettier: + specifier: ^3.3.3 + version: 3.6.2 + spacetimedb: + specifier: workspace:* + version: link:../crates/bindings-typescript + tsx: + specifier: ^4.21.0 + version: 4.21.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-retry-ts/spacetimedb: + dependencies: + '@spacetimedb/retry': + specifier: workspace:* + version: link:.. + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + templates/angular-ts: dependencies: '@angular/common': @@ -2618,6 +2951,12 @@ packages: cpu: [ppc64] os: [aix] + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + '@esbuild/android-arm64@0.17.6': resolution: {integrity: sha512-YnYSCceN/dUzUr5kdtUzB+wZprCafuD89Hs0Aqv9QSdwhYQybhXTaSTcrl6X/aWThn1a/j0eEpUBGOE7269REg==} engines: {node: '>=12'} @@ -2660,6 +2999,12 @@ packages: cpu: [arm64] os: [android] + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + '@esbuild/android-arm@0.17.6': resolution: {integrity: sha512-bSC9YVUjADDy1gae8RrioINU6e1lCkg3VGVwm0QQ2E1CWcC4gnMce9+B6RpxuSsrsXsk1yojn7sp1fnG8erE2g==} engines: {node: '>=12'} @@ -2702,6 +3047,12 @@ packages: cpu: [arm] os: [android] + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + '@esbuild/android-x64@0.17.6': resolution: {integrity: sha512-MVcYcgSO7pfu/x34uX9u2QIZHmXAB7dEiLQC5bBl5Ryqtpj9lT2sg3gNDEsrPEmimSJW2FXIaxqSQ501YLDsZQ==} engines: {node: '>=12'} @@ -2744,6 +3095,12 @@ packages: cpu: [x64] os: [android] + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + '@esbuild/darwin-arm64@0.17.6': resolution: {integrity: sha512-bsDRvlbKMQMt6Wl08nHtFz++yoZHsyTOxnjfB2Q95gato+Yi4WnRl13oC2/PJJA9yLCoRv9gqT/EYX0/zDsyMA==} engines: {node: '>=12'} @@ -2786,6 +3143,12 @@ packages: cpu: [arm64] os: [darwin] + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + '@esbuild/darwin-x64@0.17.6': resolution: {integrity: sha512-xh2A5oPrYRfMFz74QXIQTQo8uA+hYzGWJFoeTE8EvoZGHb+idyV4ATaukaUvnnxJiauhs/fPx3vYhU4wiGfosg==} engines: {node: '>=12'} @@ -2828,6 +3191,12 @@ packages: cpu: [x64] os: [darwin] + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + '@esbuild/freebsd-arm64@0.17.6': resolution: {integrity: sha512-EnUwjRc1inT4ccZh4pB3v1cIhohE2S4YXlt1OvI7sw/+pD+dIE4smwekZlEPIwY6PhU6oDWwITrQQm5S2/iZgg==} engines: {node: '>=12'} @@ -2870,6 +3239,12 @@ packages: cpu: [arm64] os: [freebsd] + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + '@esbuild/freebsd-x64@0.17.6': resolution: {integrity: sha512-Uh3HLWGzH6FwpviUcLMKPCbZUAFzv67Wj5MTwK6jn89b576SR2IbEp+tqUHTr8DIl0iDmBAf51MVaP7pw6PY5Q==} engines: {node: '>=12'} @@ -2912,6 +3287,12 @@ packages: cpu: [x64] os: [freebsd] + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + '@esbuild/linux-arm64@0.17.6': resolution: {integrity: sha512-bUR58IFOMJX523aDVozswnlp5yry7+0cRLCXDsxnUeQYJik1DukMY+apBsLOZJblpH+K7ox7YrKrHmJoWqVR9w==} engines: {node: '>=12'} @@ -2954,6 +3335,12 @@ packages: cpu: [arm64] os: [linux] + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + '@esbuild/linux-arm@0.17.6': resolution: {integrity: sha512-7YdGiurNt7lqO0Bf/U9/arrPWPqdPqcV6JCZda4LZgEn+PTQ5SMEI4MGR52Bfn3+d6bNEGcWFzlIxiQdS48YUw==} engines: {node: '>=12'} @@ -2996,6 +3383,12 @@ packages: cpu: [arm] os: [linux] + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + '@esbuild/linux-ia32@0.17.6': resolution: {integrity: sha512-ujp8uoQCM9FRcbDfkqECoARsLnLfCUhKARTP56TFPog8ie9JG83D5GVKjQ6yVrEVdMie1djH86fm98eY3quQkQ==} engines: {node: '>=12'} @@ -3038,6 +3431,12 @@ packages: cpu: [ia32] os: [linux] + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + '@esbuild/linux-loong64@0.17.6': resolution: {integrity: sha512-y2NX1+X/Nt+izj9bLoiaYB9YXT/LoaQFYvCkVD77G/4F+/yuVXYCWz4SE9yr5CBMbOxOfBcy/xFL4LlOeNlzYQ==} engines: {node: '>=12'} @@ -3080,6 +3479,12 @@ packages: cpu: [loong64] os: [linux] + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + '@esbuild/linux-mips64el@0.17.6': resolution: {integrity: sha512-09AXKB1HDOzXD+j3FdXCiL/MWmZP0Ex9eR8DLMBVcHorrWJxWmY8Nms2Nm41iRM64WVx7bA/JVHMv081iP2kUA==} engines: {node: '>=12'} @@ -3122,6 +3527,12 @@ packages: cpu: [mips64el] os: [linux] + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + '@esbuild/linux-ppc64@0.17.6': resolution: {integrity: sha512-AmLhMzkM8JuqTIOhxnX4ubh0XWJIznEynRnZAVdA2mMKE6FAfwT2TWKTwdqMG+qEaeyDPtfNoZRpJbD4ZBv0Tg==} engines: {node: '>=12'} @@ -3164,6 +3575,12 @@ packages: cpu: [ppc64] os: [linux] + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + '@esbuild/linux-riscv64@0.17.6': resolution: {integrity: sha512-Y4Ri62PfavhLQhFbqucysHOmRamlTVK10zPWlqjNbj2XMea+BOs4w6ASKwQwAiqf9ZqcY9Ab7NOU4wIgpxwoSQ==} engines: {node: '>=12'} @@ -3206,6 +3623,12 @@ packages: cpu: [riscv64] os: [linux] + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + '@esbuild/linux-s390x@0.17.6': resolution: {integrity: sha512-SPUiz4fDbnNEm3JSdUW8pBJ/vkop3M1YwZAVwvdwlFLoJwKEZ9L98l3tzeyMzq27CyepDQ3Qgoba44StgbiN5Q==} engines: {node: '>=12'} @@ -3248,6 +3671,12 @@ packages: cpu: [s390x] os: [linux] + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + '@esbuild/linux-x64@0.17.6': resolution: {integrity: sha512-a3yHLmOodHrzuNgdpB7peFGPx1iJ2x6m+uDvhP2CKdr2CwOaqEFMeSqYAHU7hG+RjCq8r2NFujcd/YsEsFgTGw==} engines: {node: '>=12'} @@ -3290,6 +3719,12 @@ packages: cpu: [x64] os: [linux] + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + '@esbuild/netbsd-arm64@0.24.2': resolution: {integrity: sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==} engines: {node: '>=18'} @@ -3320,6 +3755,12 @@ packages: cpu: [arm64] os: [netbsd] + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + '@esbuild/netbsd-x64@0.17.6': resolution: {integrity: sha512-EanJqcU/4uZIBreTrnbnre2DXgXSa+Gjap7ifRfllpmyAU7YMvaXmljdArptTHmjrkkKm9BK6GH5D5Yo+p6y5A==} engines: {node: '>=12'} @@ -3362,6 +3803,12 @@ packages: cpu: [x64] os: [netbsd] + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + '@esbuild/openbsd-arm64@0.24.2': resolution: {integrity: sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==} engines: {node: '>=18'} @@ -3392,6 +3839,12 @@ packages: cpu: [arm64] os: [openbsd] + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + '@esbuild/openbsd-x64@0.17.6': resolution: {integrity: sha512-xaxeSunhQRsTNGFanoOkkLtnmMn5QbA0qBhNet/XLVsc+OVkpIWPHcr3zTW2gxVU5YOHFbIHR9ODuaUdNza2Vw==} engines: {node: '>=12'} @@ -3434,6 +3887,12 @@ packages: cpu: [x64] os: [openbsd] + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + '@esbuild/openharmony-arm64@0.25.9': resolution: {integrity: sha512-4Xd0xNiMVXKh6Fa7HEJQbrpP3m3DDn43jKxMjxLLRjWnRsfxjORYJlXPO4JNcXtOyfajXorRKY9NkOpTHptErg==} engines: {node: '>=18'} @@ -3458,6 +3917,12 @@ packages: cpu: [arm64] os: [openharmony] + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + '@esbuild/sunos-x64@0.17.6': resolution: {integrity: sha512-gnMnMPg5pfMkZvhHee21KbKdc6W3GR8/JuE0Da1kjwpK6oiFU3nqfHuVPgUX2rsOx9N2SadSQTIYV1CIjYG+xw==} engines: {node: '>=12'} @@ -3500,6 +3965,12 @@ packages: cpu: [x64] os: [sunos] + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + '@esbuild/win32-arm64@0.17.6': resolution: {integrity: sha512-G95n7vP1UnGJPsVdKXllAJPtqjMvFYbN20e8RK8LVLhlTiSOH1sd7+Gt7rm70xiG+I5tM58nYgwWrLs6I1jHqg==} engines: {node: '>=12'} @@ -3542,6 +4013,12 @@ packages: cpu: [arm64] os: [win32] + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + '@esbuild/win32-ia32@0.17.6': resolution: {integrity: sha512-96yEFzLhq5bv9jJo5JhTs1gI+1cKQ83cUpyxHuGqXVwQtY5Eq54ZEsKs8veKtiKwlrNimtckHEkj4mRh4pPjsg==} engines: {node: '>=12'} @@ -3584,6 +4061,12 @@ packages: cpu: [ia32] os: [win32] + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + '@esbuild/win32-x64@0.17.6': resolution: {integrity: sha512-n6d8MOyUrNp6G4VSpRcgjs5xj4A91svJSaiwLIDWVWEsZtpN5FA9NlBbZHDmAJc2e8e6SF4tkBD3HAvPF+7igA==} engines: {node: '>=12'} @@ -3626,6 +4109,12 @@ packages: cpu: [x64] os: [win32] + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + '@eslint-community/eslint-utils@4.7.0': resolution: {integrity: sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -4269,6 +4758,10 @@ packages: '@napi-rs/wasm-runtime@1.1.1': resolution: {integrity: sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A==} + '@noble/hashes@2.4.0': + resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==} + engines: {node: '>= 20.19.0'} + '@node-rs/jieba-android-arm-eabi@1.10.4': resolution: {integrity: sha512-MhyvW5N3Fwcp385d0rxbCWH42kqDBatQTyP8XbnYbju2+0BO/eTeCCLYj7Agws4pwxn2LtdldXRSKavT7WdzNA==} engines: {node: '>= 10'} @@ -6053,6 +6546,9 @@ packages: '@speed-highlight/core@1.2.14': resolution: {integrity: sha512-G4ewlBNhUtlLvrJTb88d2mdy2KRijzs4UhnlrOSRT4bmjh/IqNElZa3zkrZ+TC47TwtlDWzVLFADljF1Ijp5hA==} + '@stablelib/base64@1.0.1': + resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==} + '@standard-schema/spec@1.0.0': resolution: {integrity: sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==} @@ -8299,6 +8795,10 @@ packages: create-require@1.1.1: resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==} + cron-parser@5.5.0: + resolution: {integrity: sha512-oML4lKUXxizYswqmxuOCpgFS8BNUJpIu6k/2HVHyaL8Ynnf3wdf9tkns0yRdJLSIjkJ+b0DXHMZEHGpMwjnPww==} + engines: {node: '>=18'} + croner@9.1.0: resolution: {integrity: sha512-p9nwwR4qyT5W996vBZhdvBCnMhicY5ytZkR4D1Xj0wuTDEiMnjwR57Q3RXYY/s0EpX6Ay3vgIcfaR+ewGHsi+g==} engines: {node: '>=18.0'} @@ -8983,6 +9483,11 @@ packages: engines: {node: '>=18'} hasBin: true + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} + engines: {node: '>=18'} + hasBin: true + escalade@3.1.1: resolution: {integrity: sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==} engines: {node: '>=6'} @@ -9244,6 +9749,9 @@ packages: fast-npm-meta@0.4.8: resolution: {integrity: sha512-ybZVlDZ2PkO79dosM+6CLZfKWRH8MF0PiWlw8M4mVWJl8IEJrPfxYc7Tsu830Dwj/R96LKXfePGTSzKWbPJ08w==} + fast-sha256@1.3.0: + resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==} + fast-uri@3.1.0: resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} @@ -10632,6 +11140,10 @@ packages: lunr@2.3.9: resolution: {integrity: sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==} + luxon@3.7.2: + resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==} + engines: {node: '>=12'} + lz-string@1.5.0: resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} hasBin: true @@ -11890,6 +12402,9 @@ packages: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} + postal-mime@2.7.6: + resolution: {integrity: sha512-UUlyE2KlxmvwMGq060onF/VWU3zD6dVW31FwokQ5v26jWd35fbs2MoTFzh+jXnPwAyV2MULMKXcBInGOl5TO6Q==} + postcss-attribute-case-insensitive@7.0.1: resolution: {integrity: sha512-Uai+SupNSqzlschRyNx3kbCTWgY/2hcwtHEI/ej2LJWc9JJ77qKgGptd8DHwY1mXtZ7Aoh4z4yxfwMBue9eNgw==} engines: {node: '>=18'} @@ -13047,6 +13562,15 @@ packages: requires-port@1.0.0: resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==} + resend@6.30.0: + resolution: {integrity: sha512-rED9rVw8N6cUvjmpYQwfZKBzd/cgWT+jURekVxtjFV2+YyK2/Tu2JOnE68sgqXlMBSYRoWgI6R0xlx3ANc/xeA==} + engines: {node: '>=20'} + peerDependencies: + '@react-email/render': '*' + peerDependenciesMeta: + '@react-email/render': + optional: true + reserved-identifiers@1.2.0: resolution: {integrity: sha512-yE7KUfFvaBFzGPs5H3Ops1RevfUEsDc5Iz65rOwWg4lE8HJSYtle77uul3+573457oHvBKuHYDl/xqUkKpEEdw==} engines: {node: '>=18'} @@ -13539,6 +14063,9 @@ packages: standard-as-callback@2.1.0: resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==} + standardwebhooks@1.1.1: + resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==} + statuses@1.5.0: resolution: {integrity: sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==} engines: {node: '>= 0.6'} @@ -14452,6 +14979,14 @@ packages: typescript: optional: true + valibot@1.5.0: + resolution: {integrity: sha512-nil6AkP2TChWL43Z5uJ6GTxX01CUA+g8LWUM+N/rB9NBbkUMaUsi9PUNzlUPgoKASgmx9f7eGOYpJ04/fSa6FQ==} + peerDependencies: + typescript: '>=5' + peerDependenciesMeta: + typescript: + optional: true + validate-npm-package-license@3.0.4: resolution: {integrity: sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==} @@ -17991,6 +18526,9 @@ snapshots: '@esbuild/aix-ppc64@0.27.3': optional: true + '@esbuild/aix-ppc64@0.28.2': + optional: true + '@esbuild/android-arm64@0.17.6': optional: true @@ -18012,6 +18550,9 @@ snapshots: '@esbuild/android-arm64@0.27.3': optional: true + '@esbuild/android-arm64@0.28.2': + optional: true + '@esbuild/android-arm@0.17.6': optional: true @@ -18033,6 +18574,9 @@ snapshots: '@esbuild/android-arm@0.27.3': optional: true + '@esbuild/android-arm@0.28.2': + optional: true + '@esbuild/android-x64@0.17.6': optional: true @@ -18054,6 +18598,9 @@ snapshots: '@esbuild/android-x64@0.27.3': optional: true + '@esbuild/android-x64@0.28.2': + optional: true + '@esbuild/darwin-arm64@0.17.6': optional: true @@ -18075,6 +18622,9 @@ snapshots: '@esbuild/darwin-arm64@0.27.3': optional: true + '@esbuild/darwin-arm64@0.28.2': + optional: true + '@esbuild/darwin-x64@0.17.6': optional: true @@ -18096,6 +18646,9 @@ snapshots: '@esbuild/darwin-x64@0.27.3': optional: true + '@esbuild/darwin-x64@0.28.2': + optional: true + '@esbuild/freebsd-arm64@0.17.6': optional: true @@ -18117,6 +18670,9 @@ snapshots: '@esbuild/freebsd-arm64@0.27.3': optional: true + '@esbuild/freebsd-arm64@0.28.2': + optional: true + '@esbuild/freebsd-x64@0.17.6': optional: true @@ -18138,6 +18694,9 @@ snapshots: '@esbuild/freebsd-x64@0.27.3': optional: true + '@esbuild/freebsd-x64@0.28.2': + optional: true + '@esbuild/linux-arm64@0.17.6': optional: true @@ -18159,6 +18718,9 @@ snapshots: '@esbuild/linux-arm64@0.27.3': optional: true + '@esbuild/linux-arm64@0.28.2': + optional: true + '@esbuild/linux-arm@0.17.6': optional: true @@ -18180,6 +18742,9 @@ snapshots: '@esbuild/linux-arm@0.27.3': optional: true + '@esbuild/linux-arm@0.28.2': + optional: true + '@esbuild/linux-ia32@0.17.6': optional: true @@ -18201,6 +18766,9 @@ snapshots: '@esbuild/linux-ia32@0.27.3': optional: true + '@esbuild/linux-ia32@0.28.2': + optional: true + '@esbuild/linux-loong64@0.17.6': optional: true @@ -18222,6 +18790,9 @@ snapshots: '@esbuild/linux-loong64@0.27.3': optional: true + '@esbuild/linux-loong64@0.28.2': + optional: true + '@esbuild/linux-mips64el@0.17.6': optional: true @@ -18243,6 +18814,9 @@ snapshots: '@esbuild/linux-mips64el@0.27.3': optional: true + '@esbuild/linux-mips64el@0.28.2': + optional: true + '@esbuild/linux-ppc64@0.17.6': optional: true @@ -18264,6 +18838,9 @@ snapshots: '@esbuild/linux-ppc64@0.27.3': optional: true + '@esbuild/linux-ppc64@0.28.2': + optional: true + '@esbuild/linux-riscv64@0.17.6': optional: true @@ -18285,6 +18862,9 @@ snapshots: '@esbuild/linux-riscv64@0.27.3': optional: true + '@esbuild/linux-riscv64@0.28.2': + optional: true + '@esbuild/linux-s390x@0.17.6': optional: true @@ -18306,6 +18886,9 @@ snapshots: '@esbuild/linux-s390x@0.27.3': optional: true + '@esbuild/linux-s390x@0.28.2': + optional: true + '@esbuild/linux-x64@0.17.6': optional: true @@ -18327,6 +18910,9 @@ snapshots: '@esbuild/linux-x64@0.27.3': optional: true + '@esbuild/linux-x64@0.28.2': + optional: true + '@esbuild/netbsd-arm64@0.24.2': optional: true @@ -18342,6 +18928,9 @@ snapshots: '@esbuild/netbsd-arm64@0.27.3': optional: true + '@esbuild/netbsd-arm64@0.28.2': + optional: true + '@esbuild/netbsd-x64@0.17.6': optional: true @@ -18363,6 +18952,9 @@ snapshots: '@esbuild/netbsd-x64@0.27.3': optional: true + '@esbuild/netbsd-x64@0.28.2': + optional: true + '@esbuild/openbsd-arm64@0.24.2': optional: true @@ -18378,6 +18970,9 @@ snapshots: '@esbuild/openbsd-arm64@0.27.3': optional: true + '@esbuild/openbsd-arm64@0.28.2': + optional: true + '@esbuild/openbsd-x64@0.17.6': optional: true @@ -18399,6 +18994,9 @@ snapshots: '@esbuild/openbsd-x64@0.27.3': optional: true + '@esbuild/openbsd-x64@0.28.2': + optional: true + '@esbuild/openharmony-arm64@0.25.9': optional: true @@ -18411,6 +19009,9 @@ snapshots: '@esbuild/openharmony-arm64@0.27.3': optional: true + '@esbuild/openharmony-arm64@0.28.2': + optional: true + '@esbuild/sunos-x64@0.17.6': optional: true @@ -18432,6 +19033,9 @@ snapshots: '@esbuild/sunos-x64@0.27.3': optional: true + '@esbuild/sunos-x64@0.28.2': + optional: true + '@esbuild/win32-arm64@0.17.6': optional: true @@ -18453,6 +19057,9 @@ snapshots: '@esbuild/win32-arm64@0.27.3': optional: true + '@esbuild/win32-arm64@0.28.2': + optional: true + '@esbuild/win32-ia32@0.17.6': optional: true @@ -18474,6 +19081,9 @@ snapshots: '@esbuild/win32-ia32@0.27.3': optional: true + '@esbuild/win32-ia32@0.28.2': + optional: true + '@esbuild/win32-x64@0.17.6': optional: true @@ -18495,6 +19105,9 @@ snapshots: '@esbuild/win32-x64@0.27.3': optional: true + '@esbuild/win32-x64@0.28.2': + optional: true + '@eslint-community/eslint-utils@4.7.0(eslint@9.33.0(jiti@2.6.1))': dependencies: eslint: 9.33.0(jiti@2.6.1) @@ -19365,6 +19978,8 @@ snapshots: '@tybys/wasm-util': 0.10.1 optional: true + '@noble/hashes@2.4.0': {} + '@node-rs/jieba-android-arm-eabi@1.10.4': optional: true @@ -21245,6 +21860,8 @@ snapshots: '@speed-highlight/core@1.2.14': {} + '@stablelib/base64@1.0.1': {} + '@standard-schema/spec@1.0.0': {} '@supabase/auth-js@2.97.0': @@ -24595,6 +25212,10 @@ snapshots: create-require@1.1.1: {} + cron-parser@5.5.0: + dependencies: + luxon: 3.7.2 + croner@9.1.0: {} cross-spawn@7.0.6: @@ -25346,6 +25967,35 @@ snapshots: '@esbuild/win32-ia32': 0.27.3 '@esbuild/win32-x64': 0.27.3 + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + escalade@3.1.1: {} escalade@3.2.0: {} @@ -25708,6 +26358,8 @@ snapshots: fast-npm-meta@0.4.8: {} + fast-sha256@1.3.0: {} + fast-uri@3.1.0: {} fastq@1.19.1: @@ -27273,6 +27925,8 @@ snapshots: lunr@2.3.9: {} + luxon@3.7.2: {} + lz-string@1.5.0: {} magic-string-ast@0.7.1: @@ -28406,7 +29060,7 @@ snapshots: defu: 6.1.4 destr: 2.0.5 dot-prop: 10.1.0 - esbuild: 0.27.2 + esbuild: 0.27.3 escape-string-regexp: 5.0.0 etag: 1.8.1 exsolve: 1.0.8 @@ -29261,6 +29915,8 @@ snapshots: possible-typed-array-names@1.1.0: {} + postal-mime@2.7.6: {} + postcss-attribute-case-insensitive@7.0.1(postcss@8.5.6): dependencies: postcss: 8.5.6 @@ -30560,6 +31216,11 @@ snapshots: requires-port@1.0.0: {} + resend@6.30.0: + dependencies: + postal-mime: 2.7.6 + standardwebhooks: 1.1.1 + reserved-identifiers@1.2.0: {} resolve-alpn@1.2.1: {} @@ -31177,6 +31838,11 @@ snapshots: standard-as-callback@2.1.0: {} + standardwebhooks@1.1.1: + dependencies: + '@stablelib/base64': 1.0.1 + fast-sha256: 1.3.0 + statuses@1.5.0: {} statuses@2.0.1: {} @@ -32152,6 +32818,10 @@ snapshots: optionalDependencies: typescript: 5.6.3 + valibot@1.5.0(typescript@5.9.3): + optionalDependencies: + typescript: 5.9.3 + validate-npm-package-license@3.0.4: dependencies: spdx-correct: 3.2.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 0ae08557f54..5ce55660405 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -29,4 +29,8 @@ packages: - 'modules/sdk-test-case-conversion-ts' - 'docs' - 'codex-plugin/scripts' + - 'spacetime-*-ts' + - 'spacetime-*-ts/example' + - 'spacetime-*-ts/spacetimedb' + - 'spacetime-*-ts/example/spacetimedb' minimumReleaseAge: 1440 diff --git a/spacetime-cron-ts/.npmrc b/spacetime-cron-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-cron-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-cron-ts/LICENSE.txt b/spacetime-cron-ts/LICENSE.txt new file mode 120000 index 00000000000..cc1ff9bdd72 --- /dev/null +++ b/spacetime-cron-ts/LICENSE.txt @@ -0,0 +1 @@ +../licenses/apache2.txt \ No newline at end of file diff --git a/spacetime-cron-ts/README.md b/spacetime-cron-ts/README.md new file mode 100644 index 00000000000..54aa87e6dda --- /dev/null +++ b/spacetime-cron-ts/README.md @@ -0,0 +1,347 @@ +# @spacetimedb/cron + +Run recurring tasks in your SpacetimeDB application, such as daily reports, +scheduled cleanup, or periodic data updates. Choose a calendar schedule or a +fixed interval, pass arguments to each job, and inspect recent results. + +Schedules are stored in your database. Your application can change or cancel +them at runtime. Calendar schedules support time zones and daylight-saving +changes. + +## Requirements + +- A SpacetimeDB CLI and server compatible with the host SDK +- The `spacetimedb` npm version required by this package's peer dependency +- Host support for the `spacetime:sys@2.0` volatile procedure used by failure + recovery +- Node.js 20 or later for package tooling + +## Install + +```bash +npm install @spacetimedb/cron spacetimedb +``` + +## Quick start + +This module records a report each weekday at 9 AM in New York. Replace the +handler's database write with the work your application needs. + +```ts +import { schema, table, t } from 'spacetimedb/server'; +import { client, cronTable } from '@spacetimedb/cron'; + +const dailyReport = cronTable({ name: 'daily_report' }); +const cron = client({ + jobs: [dailyReport], + reconcileEverySeconds: 300, +}); + +const report = table( + { name: 'report', public: true }, + { + id: t.u64().primaryKey().autoInc(), + generatedAt: t.timestamp(), + } +); + +const spacetimedb = schema({ ...cron.tables, report }); +export default spacetimedb; + +export const generateReport = dailyReport.cronReducer( + spacetimedb, + (ctx, invocation) => { + ctx.db.report.insert({ + id: 0n, + generatedAt: invocation.scheduledFor, + }); + } +); + +export const cronReconcile = cron.reconcileReducer(spacetimedb); +export const { jobs: cronJobs } = cron.publicViews(spacetimedb); + +export const init = spacetimedb.init(ctx => { + cron.schedule(ctx, dailyReport, '0 9 * * 1-5', { + timezone: 'America/New_York', + maxFailures: 3, + }); +}); +``` + +`init` creates the schedule for a new database. Later module publishes keep +schedule changes made at runtime. To run at a fixed interval instead, pass +`{ everySeconds: 30 }` in place of the cron expression. + +The repair sweep checks every five minutes for jobs that lost their next +scheduled run. Failure recovery is best effort; see [Execution model](#execution-model) +for crash behavior. `maxFailures: 3` disables the job after three consecutive +recorded failures. The `cronJobs` view lets clients subscribe to job status. + +See the [browser example](./example/) to change schedules and try a cleanup +job with arguments. + +## API + +### Registering jobs + +Create one handle for each statically known job: + +```ts +const cleanup = cronTable({ name: 'cleanup' }); +``` + +Declare a SpacetimeDB type when a job needs durable arguments: + +```ts +const archiveWorkspace = cronTable({ + name: 'archive_workspace', + args: t.object('ArchiveWorkspaceCronArgs', { + workspaceId: t.u64(), + retainDays: t.u32(), + }), +}); +``` + +The handle carries the inferred argument type through `cron.schedule()`, +`cronReducer()`, and `cronProcedure()`. The argument builder may be any +SpacetimeDB type, although a named `t.object()` gives most jobs the clearest +call site and database schema. + +Job names use lowercase snake_case and may contain up to 48 characters. Pass +every handle to one `client()` call when the module loads, then register +exactly one reducer or procedure for each handle after `schema()`. +`cron.schedule()` rejects a configuration with a missing handler. When +`reconcileEverySeconds` is configured, export `cron.reconcileReducer()`. +Applications that expose cron status export the `jobs` view returned by +`cron.publicViews()`. + +Use `cronReducer` for deterministic database work. The handler receives the +host module's reducer context, inferred from `spacetimedb`, and a +`CronInvocation`. Registration fails to compile if the schema does not include +`cron.tables`: + +```ts +export const runCleanup = cleanup.cronReducer( + spacetimedb, + (ctx, invocation) => { + console.log(invocation.id); + // Database writes commit together when the handler succeeds. + } +); +``` + +Use `cronProcedure` for HTTP requests and other procedure capabilities: + +```ts +export const syncRemote = remoteSync.cronProcedure( + spacetimedb, + (ctx, invocation) => { + sendRequest({ idempotencyKey: invocation.id }); + } +); +``` + +Handlers complete synchronously. SpacetimeDB procedure APIs, including `ctx.http.fetch` and `ctx.withTx`, expose synchronous module calls. + +Argument-bearing handlers receive their typed payload before the invocation +metadata: + +```ts +export const runArchive = archiveWorkspace.cronReducer( + spacetimedb, + (ctx, args, invocation) => { + archiveRows(ctx, args.workspaceId, args.retainDays); + console.log(invocation.id); + } +); +``` + +### Scheduling and cancellation + +`cron.schedule()` first repairs any enabled jobs with missing triggers. It then +creates or replaces the requested schedule, clears failure state, increments +the job generation, and enables the job. + +```ts +cron.schedule(ctx, cleanup, '30 2 * * *', { timezone: 'UTC' }); +cron.schedule(ctx, cleanup, { everySeconds: 300 }); + +cron.schedule(ctx, archiveWorkspace, '0 3 * * *', { + timezone: 'UTC', + args: { workspaceId: 42n, retainDays: 90 }, +}); +``` + +Arguments are required when scheduling an argument-bearing job. Rescheduling +replaces the schedule, arguments, generation, and pending fire atomically. A +handler receives the argument value read at the start of its fire. + +Cron expressions accept five fields or six fields when seconds are included. Fixed intervals accept whole seconds from 1 through 31,536,000. + +`cron.unschedule()` runs the same opportunistic repair before removing the +target fire, incrementing its generation, and leaving job and history rows +available for inspection. + +```ts +cron.unschedule(ctx, cleanup); +``` + +Application reducers must authorize schedule changes. + +Input errors from `cron.schedule()` are thrown as `SenderError`s. `errors` +holds the codes a caller can receive at runtime, for example +`errors.invalidExpression` (`cron.invalid_expression`). Codes may be followed +by `:` and detail text. + +- `notAuthorized`: a client called a `_cron` function directly. +- `invalidMaxFailures`, `invalidInterval`, `invalidExpression`, + `invalidTimezone`, `unsatisfiableExpression`, `missingArgs`, and + `unexpectedArgs`: `cron.schedule()` rejected its input. +- `invalidScheduleState`, `invalidArgsState`, `invalidTrigger`, and + `noFutureOccurrence`: stored in the private `cron_job.disabledReason` when + cron disables a job. + +Programming errors, such as invalid job definitions or client configuration, +missing handler registration, a job handle from another client, or a handler +that returns a promise, fail module loading or the call with `cron.*` codes +that are not exported. + +### Database state + +The package adds these shared tables: + +| Table | Purpose | +| ---------- | ------------------------------------------------------------------- | +| `cron_job` | Private schedule, typed arguments, generation, health, and next run | +| `cron_run` | Completed invocation identity, outcome, and bounded history | + +When `reconcileEverySeconds` is set, the package also adds +`cron_reconcile_tick`. It contains one native interval row that periodically +repairs enabled jobs with missing triggers. + +Each job receives one `_fire` schedule table bound directly to its +`_cron` reducer or procedure. An enabled job owns exactly one row in +that table. Calendar jobs replace one-shot rows after each fire. Fixed-rate +jobs retain one native interval row. + +The package owns the shared names above, the public view name `cron_jobs`, every +`_fire` table, and every `_cron` scheduled function. +Enabling periodic reconciliation also reserves `cron_reconcile` and +`cron_reconcile_tick`. Consumer modules should keep those database function, +table, and view names available for cron. + +`cron_job` is always private. Registering `cron.publicViews()` exposes +`cron_jobs`, a subscribable projection of job state that omits typed arguments +and detailed failure text. Its optional `disabledReason` is one of +`disabled_by_operator`, `failure_threshold_reached`, +`lost_fire_threshold_reached`, `invalid_schedule_state`, or `disabled`. +`publicTables` defaults to `false`; enabling it exposes each per-job fire table +and `cron_run`, including run error details. The fire-table `recovery` column is +internal. Stored schedule rows leave it empty. + +For calendar jobs, `cron_jobs.nextRunAt` and the job's fire-table `targetAt` +identify the logical next occurrence. For native interval jobs, `nextRunAt` is +an estimate based on the most recent fire. The database owner and module +reducers can inspect the private `cron_job` table directly. + +### Execution model + +Each fire table is bound directly to one statically registered handler. + +For reducer jobs, the middleware rearms a calendar schedule before calling the +handler. On success, the successor, application writes, job health, and run +record commit in one transaction. On failure, the middleware serializes the +fire row with an internal recovery payload, schedules the same +`_cron` reducer through +`volatile_nonatomic_schedule_immediate`, and rethrows. The fire transaction +rolls back, including partial application writes. The recovery invocation runs +in a fresh transaction. It validates the database caller, generation, and +sequence before it records the failure. Calendar recovery replaces the pending +fire. Native interval rows persist, so interval recovery keeps that row and +updates job health. + +Recovery calls do not run the application handler. + +The volatile call is best effort and is not persisted. A process crash, +uncatchable trap, or lost message can temporarily leave an enabled calendar job +without a fire. The package detects that broken invariant during every +`cron.schedule()` and `cron.unschedule()` operation. Set +`reconcileEverySeconds` to add a low-frequency native interval sweep: + +```ts +const cron = client({ jobs, reconcileEverySeconds: 300 }); + +// Export after registering the job handlers. +export const cronReconcile = cron.reconcileReducer(spacetimedb); +``` + +Repair removes any stale trigger, inserts a valid current-generation trigger, +and records one `Failed` run with error `lost_fire`. The normal failure counter, +history cap, and automatic disable policy apply. Without the optional sweep, +repair occurs on the next management operation. With it, detection is bounded +by the configured interval and scheduler availability. + +Procedure jobs secure the next calendar fire in a committed transaction, run +the procedure work, then record the outcome in another transaction. A process +failure during external work can lose the run record, but it does not remove +the next calendar fire. `CronInvocation.id` is stable and should be used as an +external idempotency key. + +`maxFailures` counts consecutive recorded failures. A positive threshold +disables the job and stores the reason. A successful invocation resets the +counter. + +### Argument schema changes + +Job names and argument builders are part of the module's database schema. +Adding a new job adds a new internal union variant. Changing the argument +builder for an existing job requires a SpacetimeDB schema migration. For an +incompatible payload change, a new job name provides a clean version boundary. + +### Scheduling behavior + +- The next calendar occurrence is computed strictly after the dispatch timestamp. +- An overdue one-shot trigger produces one catch-up invocation. Intermediate missed occurrences are skipped. +- Spring-forward and fall-back behavior follows `cron-parser` 5.x. +- Sparse expressions use internal checkpoint triggers so valid occurrences beyond the host timer horizon remain scheduled. +- Fixed intervals use SpacetimeDB native `ScheduleAt.interval` rows. + +A long-running procedure delays other scheduled work in the same module. + +### Run history + +`historyCap` defaults to five completed records per job and accepts values from +0 through 1,000. + +Run statuses are: + +- `Ok`: the handler completed without throwing +- `Failed`: the handler threw, or reconciliation recorded a lost fire + +### Parser exports + +```ts +import { + isValidTimezone, + nextFireAfter, + parseCronExpression, +} from '@spacetimedb/cron/parser'; +``` + +## Testing + +```bash +pnpm test +pnpm lint +pnpm typecheck +pnpm run test:recovery +pnpm run test:module:local +``` + +`test:module:local` requires a running local SpacetimeDB server. +`test:recovery` tests scheduled work across a host restart. + +## License + +Apache-2.0. See [`LICENSE.txt`](./LICENSE.txt). diff --git a/spacetime-cron-ts/example/.env.example b/spacetime-cron-ts/example/.env.example new file mode 100644 index 00000000000..b43135687a0 --- /dev/null +++ b/spacetime-cron-ts/example/.env.example @@ -0,0 +1,9 @@ +# Copy to .env. The example server loads this on startup. + +# ---------------- Static server ---------------- +HOST=127.0.0.1 +PORT=8788 + +# ---------------- SpacetimeDB ---------------- +STDB_URI=ws://127.0.0.1:3000 +SPACETIMEDB_DB_NAME=spacetime-cron-example diff --git a/spacetime-cron-ts/example/.npmrc b/spacetime-cron-ts/example/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-cron-ts/example/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-cron-ts/example/README.md b/spacetime-cron-ts/example/README.md new file mode 100644 index 00000000000..b7463c6f258 --- /dev/null +++ b/spacetime-cron-ts/example/README.md @@ -0,0 +1,82 @@ +# Cron example + +A dashboard for scheduling recurring tasks and viewing their results. + +The example starts with two tasks: + +- **Digest** adds a summary to the activity log at 9 AM on weekdays, New York time. +- **Cleanup** runs every five minutes and trims the activity log to its newest + 50 entries. You can change how many entries it keeps. + +## Run it locally + +Requires Node.js 20+, pnpm 10, and the SpacetimeDB CLI and server built from +this checkout. + +Start SpacetimeDB in a separate terminal: + +```bash +spacetime start +``` + +From `spacetime-cron-ts/example`, run: + +```bash +pnpm install +pnpm run build:module +pnpm run dev +``` + +Open . The two tasks appear on the first publish. + +## Try it + +1. Click **Schedule job** and select **Digest**. +2. Choose **Every 10 seconds**, then click **Schedule job** to save. +3. Wait for a run to appear. Each run adds an entry to the activity log. +4. Select **Cleanup**, choose **Every 10 seconds**, and set **Rows to keep** to + `3`. After enough digest runs, cleanup removes the older activity entries. +5. Click **Unschedule** on a task to stop it. Schedule it again to restart it. + +You can set a fixed interval, such as every 30 seconds, or a calendar schedule, +such as weekdays at 9 AM. Saving a schedule replaces the previous one for that +task. Schedules keep running when you close the browser, as long as SpacetimeDB +is running. + +## Change the example + +- [spacetimedb/src/index.ts](./spacetimedb/src/index.ts) defines the two tasks, + their starting schedules, and what each task does. +- [src/app.ts](./src/app.ts) connects the dashboard to SpacetimeDB and handles + the controls. + +After changing the server code, run `pnpm run build:module`. This keeps existing +data and schedules. Restart `pnpm run dev` after changing the browser code. + +To restore the starting schedules, run `pnpm run build:module:fresh`. **This +deletes all data in the local `spacetime-cron-example` database.** + +For instructions on adding scheduled tasks to your own app, see the +[Cron quick start](../README.md#quick-start). + +## Configuration + +See [.env.example](./.env.example) to change the database address or web-server +port. The defaults work without a `.env` file. + +## Before deploying + +Anyone who connects to this example can change schedules and read the activity +and run history. Add permission checks and restrict access to that data before +using these controls in a public app. + +The example also checks for interrupted schedules every five minutes. For the +details of failed tasks and recovery, see +[Cron's execution model](../README.md#execution-model). + +## Troubleshooting + +- **Nothing runs:** the starting digest schedule only runs on weekday mornings. + Use **Every 10 seconds** to see a result sooner. +- **A task stops running:** check its recent failed runs before scheduling it + again. Repeated failures can disable a task. diff --git a/spacetime-cron-ts/example/package.json b/spacetime-cron-ts/example/package.json new file mode 100644 index 00000000000..ae3e62fda24 --- /dev/null +++ b/spacetime-cron-ts/example/package.json @@ -0,0 +1,28 @@ +{ + "name": "spacetime-cron-example", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "spacetime:generate": "spacetime generate --lang typescript --out-dir src/module_bindings/app --module-path ./spacetimedb -y", + "build:module": "pnpm --dir spacetimedb run build && pnpm --dir spacetimedb run publish:local && pnpm run spacetime:generate && pnpm run build:app", + "build:module:fresh": "pnpm --dir spacetimedb run build && pnpm --dir spacetimedb run publish:local:reset && pnpm run spacetime:generate && pnpm run build:app", + "check": "tsc --noEmit", + "build:app": "pnpm run check && esbuild src/app.ts --bundle --format=esm --outfile=public/app.js --target=es2022 --sourcemap", + "build": "pnpm run spacetime:generate && pnpm run build:app", + "dev": "pnpm run build && tsx server.ts" + }, + "dependencies": { + "@spacetimedb/example-ui": "workspace:*", + "dotenv": "^16.4.7", + "express": "^4.21.2", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/express": "^4.17.21", + "@types/node": "^22.10.2", + "esbuild": "^0.28.0", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-cron-ts/example/public/index.html b/spacetime-cron-ts/example/public/index.html new file mode 100644 index 00000000000..9326b444d62 --- /dev/null +++ b/spacetime-cron-ts/example/public/index.html @@ -0,0 +1,272 @@ + + + + + + + SpacetimeDB Cron + + + + +
+
+ + + SpacetimeDB + Cron + +
+ + + Connecting + + +
+
+ +
+
+ +
+ 0 + Configured jobs +
+
+
+ +
+ 0 + Healthy schedules +
+
+
+ +
+ 0 + Total dispatches +
+
+
+ +
+
+
+
+

Configured jobs

+

+ Schedules + 0 +

+
+ + + Live state + +
+
+
+ +

No jobs scheduled

+

Choose a preset or configure a schedule below.

+
+ +
+
+ +
+
+
+
+

Execution history

+

+ Recent runs + 0 +

+
+
+
+
+ +

Runs will appear after a job fires.

+
+ +
+
+ +
+
+
+

Application output

+

+ Activity + 0 +

+
+
+
+
+ +

Handler output will appear here.

+
+ +
+
+
+
+ +
+
+

Try the API

+

Schedule a job

+

+ Configure one of the example handlers with a calendar expression or + a fixed interval. Scheduling the same job again replaces its current + configuration. +

+
+ + + +
+
+ +
+
+ + + + + +
+
+

+ +
+
+
+ + +
+ + + diff --git a/spacetime-cron-ts/example/public/styles.css b/spacetime-cron-ts/example/public/styles.css new file mode 100644 index 00000000000..83580dfa79e --- /dev/null +++ b/spacetime-cron-ts/example/public/styles.css @@ -0,0 +1,982 @@ +:root { + color-scheme: dark; + --page: #070b0f; + --surface: #0d1419; + --surface-raised: #111b21; + --surface-soft: #152128; + --line: #22313b; + --line-strong: #324750; + --text: #f3f5f6; + --muted: #8a9aa5; + --muted-bright: #b9c4ca; + --accent: #49d4ba; + --accent-strong: #78ead4; + --blue: #52b8f4; + --violet: #a997ff; + --green: #4cf490; + --amber: #f4c95d; + --red: #ff8f8f; + --radius-lg: 18px; + --radius-md: 12px; + --radius-sm: 8px; + font-family: + Inter, + ui-sans-serif, + system-ui, + -apple-system, + BlinkMacSystemFont, + 'Segoe UI', + sans-serif; +} + +* { + box-sizing: border-box; +} + +html { + min-width: 320px; + scroll-behavior: smooth; +} + +body { + min-height: 100vh; + margin: 0; + color: var(--text); + background: + radial-gradient( + circle at 15% -10%, + rgb(73 212 186 / 12%), + transparent 32rem + ), + radial-gradient(circle at 95% 8%, rgb(82 184 244 / 8%), transparent 28rem), + var(--page); +} + +button, +input, +select { + font: inherit; +} + +button, +a, +select { + -webkit-tap-highlight-color: transparent; +} + +button { + color: inherit; +} + +a { + color: inherit; +} + +[hidden] { + display: none !important; +} + +.shell { + width: min(1240px, calc(100% - 40px)); + margin: 0 auto; + padding: 20px 0 36px; +} + +.topbar { + position: relative; + z-index: 10; + display: flex; + align-items: center; + justify-content: space-between; + min-height: 68px; + padding: 14px 16px 14px 20px; + border: 1px solid rgb(255 255 255 / 7%); + border-radius: var(--radius-lg); + background: rgb(13 20 25 / 82%); + box-shadow: 0 18px 60px rgb(0 0 0 / 18%); + backdrop-filter: blur(18px); +} + +.brand { + display: inline-flex; + align-items: center; + gap: 11px; + text-decoration: none; +} + +.brand img { + width: 31px; + height: 28px; +} + +.brand-name { + font-size: 1.02rem; + font-weight: 680; + letter-spacing: -0.025em; +} + +.brand-product { + padding: 4px 8px; + border: 1px solid var(--line-strong); + border-radius: 6px; + color: var(--muted-bright); + background: var(--surface-soft); + font-size: 0.7rem; + font-weight: 700; + letter-spacing: 0.08em; + line-height: 1; + text-transform: uppercase; +} + +.topbar-actions, +.form-actions { + display: flex; + align-items: center; + gap: 12px; +} + +.connection { + display: inline-flex; + align-items: center; + gap: 8px; + min-height: 36px; + padding: 0 12px; + border: 1px solid var(--line); + border-radius: 999px; + color: var(--muted-bright); + background: rgb(7 11 15 / 55%); + font-size: 0.78rem; + font-weight: 600; +} + +.connection-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--amber); + box-shadow: 0 0 0 4px rgb(244 201 93 / 10%); +} + +.connection[data-state='connected'] .connection-dot { + background: var(--green); + box-shadow: 0 0 0 4px rgb(76 244 144 / 10%); +} + +.connection[data-state='error'] .connection-dot, +.connection[data-state='disconnected'] .connection-dot { + background: var(--red); + box-shadow: 0 0 0 4px rgb(255 143 143 / 10%); +} + +.button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + min-height: 40px; + padding: 0 15px; + border: 1px solid transparent; + border-radius: var(--radius-sm); + cursor: pointer; + font-size: 0.82rem; + font-weight: 700; + transition: + border-color 150ms ease, + background 150ms ease, + color 150ms ease, + transform 150ms ease; +} + +.button:not(:disabled):active { + transform: translateY(1px); +} + +.button:disabled { + cursor: not-allowed; + opacity: 0.45; +} + +.button-primary { + color: #04100d; + background: var(--accent); + box-shadow: 0 8px 28px rgb(73 212 186 / 13%); +} + +.button-primary:not(:disabled):hover { + background: var(--accent-strong); +} + +.button-secondary { + border-color: var(--line); + color: var(--muted-bright); + background: var(--surface-raised); +} + +.button-secondary:not(:disabled):hover { + border-color: var(--line-strong); + color: var(--text); + background: var(--surface-soft); +} + +.button-small { + min-height: 32px; + padding: 0 11px; + font-size: 0.74rem; +} + +.eyebrow, +.panel-kicker { + margin: 0 0 10px; + color: var(--accent); + font-size: 0.69rem; + font-weight: 800; + letter-spacing: 0.15em; + text-transform: uppercase; +} + +.summary { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 12px; + margin-top: 12px; +} + +.summary-card { + display: flex; + align-items: center; + gap: 14px; + min-height: 92px; + padding: 18px 20px; + border: 1px solid var(--line); + border-radius: var(--radius-md); + background: rgb(13 20 25 / 75%); +} + +.summary-card strong { + display: block; +} + +.summary-card strong { + font-size: 1.55rem; + font-weight: 620; + letter-spacing: -0.04em; +} + +.summary-card div > span { + margin-top: 2px; + color: var(--muted); + font-size: 0.76rem; +} + +.summary-card .summary-icon { + display: grid; + width: 40px; + height: 40px; + flex: 0 0 auto; + border: 1px solid; + border-radius: 10px; + place-items: center; + line-height: 0; +} + +.summary-icon svg, +.empty-icon svg { + width: 18px; + height: 18px; + fill: none; + stroke: currentColor; + stroke-linecap: round; + stroke-linejoin: round; + stroke-width: 1.8; +} + +.summary-icon-blue { + border-color: rgb(82 184 244 / 22%); + color: var(--blue); + background: rgb(82 184 244 / 8%); +} + +.summary-icon-green { + border-color: rgb(76 244 144 / 22%); + color: var(--green); + background: rgb(76 244 144 / 8%); +} + +.summary-icon-violet { + border-color: rgb(169 151 255 / 22%); + color: var(--violet); + background: rgb(169 151 255 / 8%); +} + +.workspace { + display: grid; + grid-template-columns: minmax(0, 1.3fr) minmax(320px, 0.7fr); + gap: 12px; + margin-top: 12px; +} + +.workspace-side { + display: grid; + grid-template-rows: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.panel { + min-width: 0; + overflow: hidden; + border: 1px solid var(--line); + border-radius: var(--radius-lg); + background: rgb(13 20 25 / 82%); +} + +.panel-header { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 84px; + padding: 20px 22px; + border-bottom: 1px solid var(--line); +} + +.panel-header-compact { + min-height: 76px; + padding: 17px 20px; +} + +.panel-kicker { + margin-bottom: 6px; + color: var(--muted); + font-size: 0.61rem; +} + +.panel h2 { + display: flex; + align-items: center; + gap: 9px; + margin: 0; + font-size: 1rem; + font-weight: 650; + letter-spacing: -0.02em; +} + +.count { + display: inline-grid; + min-width: 22px; + height: 22px; + padding: 0 6px; + border: 1px solid var(--line); + border-radius: 999px; + place-items: center; + color: var(--muted); + background: var(--page); + font-size: 0.65rem; +} + +.live-label { + display: inline-flex; + align-items: center; + gap: 7px; + color: var(--muted); + font-size: 0.69rem; + font-weight: 650; +} + +.live-label span { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--accent); + box-shadow: 0 0 9px rgb(73 212 186 / 60%); +} + +.panel-body { + min-height: 360px; + padding: 12px; +} + +.panel-body-compact { + min-height: 208px; +} + +.empty-state { + display: grid; + min-height: 335px; + padding: 36px 20px; + place-content: center; + place-items: center; + text-align: center; +} + +.empty-state-small { + min-height: 182px; +} + +.empty-icon { + display: grid; + width: 42px; + height: 42px; + margin-bottom: 13px; + border: 1px solid var(--line); + border-radius: 12px; + place-items: center; + color: var(--accent); + background: var(--surface-raised); + line-height: 0; +} + +.empty-state h3 { + margin: 0; + font-size: 0.91rem; + font-weight: 650; +} + +.empty-state p { + max-width: 280px; + margin: 7px 0 0; + color: var(--muted); + font-size: 0.76rem; + line-height: 1.55; +} + +.job-list, +.event-list { + margin: 0; + padding: 0; + list-style: none; +} + +.job-list { + display: grid; + gap: 9px; +} + +.job-card { + padding: 17px; + border: 1px solid var(--line); + border-radius: var(--radius-md); + background: var(--surface-raised); +} + +.job-card[data-enabled='false'] { + opacity: 0.72; +} + +.job-card-top, +.event-item { + display: flex; + align-items: center; +} + +.job-card-top { + justify-content: space-between; + gap: 16px; +} + +.job-identity { + display: flex; + align-items: center; + min-width: 0; + gap: 11px; +} + +.job-icon { + display: grid; + width: 38px; + height: 38px; + flex: 0 0 auto; + border: 1px solid rgb(73 212 186 / 20%); + border-radius: 10px; + place-items: center; + color: var(--accent); + background: rgb(73 212 186 / 7%); + font-size: 0.76rem; + font-weight: 800; + line-height: 1; +} + +.job-identity strong, +.job-identity code { + display: block; +} + +.job-identity strong { + overflow: hidden; + font-size: 0.9rem; + font-weight: 650; + text-overflow: ellipsis; + white-space: nowrap; +} + +.job-identity code, +.job-schedule code, +.preset code { + color: var(--muted); + font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', monospace; + font-size: 0.67rem; +} + +.job-identity code { + margin-top: 3px; +} + +.status-badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 5px 8px; + border: 1px solid; + border-radius: 999px; + font-size: 0.63rem; + font-weight: 750; + text-transform: capitalize; +} + +.status-badge::before { + width: 5px; + height: 5px; + border-radius: 50%; + background: currentColor; + content: ''; +} + +.status-badge.enabled { + border-color: rgb(76 244 144 / 20%); + color: var(--green); + background: rgb(76 244 144 / 7%); +} + +.status-badge.disabled { + border-color: rgb(255 143 143 / 20%); + color: var(--red); + background: rgb(255 143 143 / 7%); +} + +.job-schedule { + margin: 15px 0; + padding: 10px 12px; + overflow: hidden; + border: 1px solid rgb(255 255 255 / 5%); + border-radius: var(--radius-sm); + background: rgb(7 11 15 / 45%); + text-overflow: ellipsis; + white-space: nowrap; +} + +.job-schedule code { + color: var(--muted-bright); +} + +.job-footer { + display: flex; + align-items: end; + justify-content: space-between; + gap: 16px; +} + +.job-metrics { + display: flex; + min-width: 0; + gap: 22px; +} + +.metric span, +.metric strong { + display: block; +} + +.metric span { + margin-bottom: 3px; + color: var(--muted); + font-size: 0.59rem; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.metric strong { + max-width: 200px; + overflow: hidden; + color: var(--muted-bright); + font-size: 0.72rem; + font-weight: 570; + text-overflow: ellipsis; + white-space: nowrap; +} + +.metric strong.unhealthy { + color: var(--amber); +} + +.event-list { + max-height: 320px; + overflow-y: auto; +} + +.event-item { + align-items: flex-start; + gap: 11px; + padding: 12px 8px; + border-bottom: 1px solid rgb(34 49 59 / 70%); +} + +.event-item:last-child { + border-bottom: 0; +} + +.event-marker { + width: 8px; + height: 8px; + margin-top: 5px; + flex: 0 0 auto; + border: 2px solid var(--surface); + border-radius: 50%; + background: var(--accent); + box-shadow: 0 0 0 2px rgb(73 212 186 / 18%); +} + +.event-marker.ok { + background: var(--green); + box-shadow: 0 0 0 2px rgb(76 244 144 / 16%); +} + +.event-marker.failed { + background: var(--red); + box-shadow: 0 0 0 2px rgb(255 143 143 / 16%); +} + +.event-content { + min-width: 0; +} + +.event-title, +.event-copy, +.event-time { + display: block; +} + +.event-title { + overflow: hidden; + font-size: 0.76rem; + font-weight: 650; + text-overflow: ellipsis; + white-space: nowrap; +} + +.event-copy { + margin-top: 3px; + overflow-wrap: anywhere; + color: var(--muted-bright); + font-size: 0.7rem; + line-height: 1.45; +} + +.event-time { + margin-top: 4px; + color: var(--muted); + font-size: 0.62rem; +} + +.scheduler { + display: grid; + grid-template-columns: minmax(260px, 0.7fr) minmax(0, 1.3fr); + gap: 40px; + margin-top: 12px; + padding: 36px; + scroll-margin-top: 20px; + border: 1px solid var(--line); + border-radius: var(--radius-lg); + background: + linear-gradient(125deg, rgb(73 212 186 / 4%), transparent 36%), + var(--surface); +} + +.scheduler-intro h2 { + margin: 0; + font-size: 1.65rem; + font-weight: 590; + letter-spacing: -0.04em; +} + +.scheduler-intro > p:not(.eyebrow) { + margin: 13px 0 0; + color: var(--muted); + font-size: 0.79rem; + line-height: 1.6; +} + +.presets { + display: grid; + gap: 7px; + margin-top: 22px; +} + +.preset { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + width: 100%; + min-height: 43px; + padding: 0 12px; + border: 1px solid var(--line); + border-radius: var(--radius-sm); + cursor: pointer; + color: var(--muted-bright); + background: var(--surface-raised); + text-align: left; + transition: + border-color 150ms ease, + background 150ms ease; +} + +.preset:hover { + border-color: var(--line-strong); + background: var(--surface-soft); +} + +.preset span { + font-size: 0.7rem; + font-weight: 650; +} + +.schedule-form { + align-self: center; + padding: 22px; + border: 1px solid var(--line); + border-radius: var(--radius-md); + background: rgb(7 11 15 / 36%); +} + +.field-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; +} + +.field { + display: grid; + min-width: 0; + gap: 7px; +} + +.field-wide { + grid-column: 1 / -1; +} + +.field > span { + color: var(--muted-bright); + font-size: 0.67rem; + font-weight: 700; +} + +.field input, +.field select { + width: 100%; + min-width: 0; + min-height: 42px; + padding: 0 12px; + border: 1px solid var(--line); + border-radius: var(--radius-sm); + outline: none; + color: var(--text); + background: var(--surface-raised); + font-size: 0.78rem; + transition: + border-color 150ms ease, + box-shadow 150ms ease; +} + +.field select { + cursor: pointer; +} + +.field input:focus, +.field select:focus { + border-color: rgb(73 212 186 / 70%); + box-shadow: 0 0 0 3px rgb(73 212 186 / 9%); +} + +.field small { + color: var(--muted); + font-size: 0.62rem; +} + +.form-actions { + min-height: 58px; + margin-top: 18px; + padding-top: 17px; + border-top: 1px solid var(--line); + justify-content: space-between; +} + +.form-status { + margin: 0; + color: var(--muted); + font-size: 0.7rem; + line-height: 1.45; +} + +.form-status[data-tone='success'] { + color: var(--green); +} + +.form-status[data-tone='error'] { + color: var(--red); +} + +.footer { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 28px 0 2px; + color: var(--muted); + font-size: 0.68rem; +} + +.footer img { + width: 18px; + height: 16px; +} + +.footer a { + color: var(--muted-bright); + font-weight: 650; + text-decoration: none; +} + +.footer a:hover { + color: var(--text); +} + +.footer-divider { + width: 1px; + height: 14px; + margin: 0 3px; + background: var(--line-strong); +} + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 3px; +} + +@media (max-width: 940px) { + .workspace, + .scheduler { + grid-template-columns: 1fr; + } + + .workspace-side { + grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-rows: auto; + } + + .scheduler { + gap: 28px; + } + + .presets { + grid-template-columns: repeat(3, 1fr); + } + + .preset { + align-items: flex-start; + flex-direction: column; + gap: 5px; + padding: 11px; + } +} + +@media (max-width: 680px) { + .shell { + width: min(100% - 24px, 1240px); + padding-top: 12px; + } + + .topbar { + align-items: flex-start; + flex-direction: column; + gap: 14px; + padding: 16px; + } + + .topbar-actions { + width: 100%; + } + + .connection, + .topbar-actions .button { + flex: 1; + } + + .summary { + grid-template-columns: 1fr; + } + + .summary-card { + min-height: 76px; + } + + .workspace-side { + grid-template-columns: 1fr; + } + + .panel-header { + padding: 17px; + } + + .job-footer { + align-items: stretch; + flex-direction: column; + } + + .job-metrics { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 10px; + } + + .metric strong { + max-width: 100%; + } + + .scheduler { + padding: 24px 18px; + } + + .presets, + .field-grid { + grid-template-columns: 1fr; + } + + .field-wide { + grid-column: auto; + } + + .schedule-form { + padding: 17px; + } + + .form-actions { + align-items: stretch; + flex-direction: column; + } + + .form-actions .button { + width: 100%; + } +} + +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } + + *, + *::before, + *::after { + scroll-behavior: auto !important; + transition-duration: 0.01ms !important; + } +} diff --git a/spacetime-cron-ts/example/server.ts b/spacetime-cron-ts/example/server.ts new file mode 100644 index 00000000000..fced927aae4 --- /dev/null +++ b/spacetime-cron-ts/example/server.ts @@ -0,0 +1,52 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { existsSync, readFileSync } from 'node:fs'; +import express, { type Request, type Response } from 'express'; +import dotenv from 'dotenv'; +import { exampleUiAssetsDir } from '@spacetimedb/example-ui/server'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const inheritedEnv = new Set(Object.keys(process.env)); + +function loadEnv(pathname: string, override: boolean): void { + if (!existsSync(pathname)) return; + + const parsed = dotenv.parse(readFileSync(pathname)); + for (const [key, value] of Object.entries(parsed)) { + if (value.trim() === '') continue; + if (inheritedEnv.has(key)) continue; + if (override || process.env[key] === undefined) { + process.env[key] = value; + } + } +} + +// Shared env supplies defaults; example-local env wins for app settings. +// Explicit process environment has highest priority. +loadEnv(path.resolve(__dirname, '..', '..', '.env'), false); +loadEnv(path.resolve(__dirname, '..', '.env'), false); +loadEnv(path.resolve(__dirname, '.env'), true); + +const PORT = Number.parseInt(process.env.PORT ?? '8788', 10); +const HOST = process.env.HOST?.trim() || '127.0.0.1'; +const STDB_URI = process.env.STDB_URI ?? 'ws://127.0.0.1:3000'; +const DB_NAME = process.env.SPACETIMEDB_DB_NAME ?? 'spacetime-cron-example'; + +const app = express(); +app.use(express.json({ limit: '256kb' })); +app.use('/assets', express.static(exampleUiAssetsDir)); +app.use(express.static(path.join(__dirname, 'public'))); + +app.get('/api/health', (_req: Request, res: Response) => { + res.json({ ok: true, databaseName: DB_NAME }); +}); + +app.get('/api/config', (_req: Request, res: Response) => { + res.json({ spacetimeUri: STDB_URI, databaseName: DB_NAME }); +}); + +app.listen(PORT, HOST, () => { + console.log(`Cron example running at http://${HOST}:${PORT}`); + console.log(` SpacetimeDB: ${STDB_URI} (${DB_NAME})`); +}); diff --git a/spacetime-cron-ts/example/spacetimedb/.npmrc b/spacetime-cron-ts/example/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-cron-ts/example/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-cron-ts/example/spacetimedb/package.json b/spacetime-cron-ts/example/spacetimedb/package.json new file mode 100644 index 00000000000..d8cb9efbd6e --- /dev/null +++ b/spacetime-cron-ts/example/spacetimedb/package.json @@ -0,0 +1,19 @@ +{ + "name": "spacetime-cron-example-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-cron-example", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-cron-example" + }, + "dependencies": { + "@spacetimedb/cron": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-cron-ts/example/spacetimedb/src/index.ts b/spacetime-cron-ts/example/spacetimedb/src/index.ts new file mode 100644 index 00000000000..eeabd879ede --- /dev/null +++ b/spacetime-cron-ts/example/spacetimedb/src/index.ts @@ -0,0 +1,147 @@ +import { schema, table, t, SenderError } from 'spacetimedb/server'; +import { client, cronTable, type CronJobReference } from '@spacetimedb/cron'; + +const digest = cronTable({ name: 'digest' }); +const cleanup = cronTable({ + name: 'cleanup', + args: t.object('CleanupCronArgs', { keep: t.u32() }), +}); + +const cron = client({ + jobs: [digest, cleanup], + publicTables: true, + reconcileEverySeconds: 300, +}); + +const activityLog = table( + { name: 'activity_log', public: true }, + { + id: t.u64().primaryKey().autoInc(), + jobName: t.string().index(), + message: t.string(), + at: t.timestamp().index(), + } +); + +const spacetimedb = schema({ ...cron.tables, activityLog }); +export default spacetimedb; + +export const runDigest = digest.cronReducer(spacetimedb, ctx => { + const entries = ctx.db.activityLog.count(); + ctx.db.activityLog.insert({ + id: 0n, + jobName: 'digest', + message: `digest generated over ${entries} log entries`, + at: ctx.timestamp, + }); +}); + +export const runCleanup = cleanup.cronReducer(spacetimedb, (ctx, args) => { + const total = Number(ctx.db.activityLog.count()); + if (total <= args.keep) return; + const excess = total - args.keep + 1; + const oldest = [...ctx.db.activityLog.iter()] + .sort((left, right) => { + const delta = + left.at.microsSinceUnixEpoch - right.at.microsSinceUnixEpoch; + return delta < 0n ? -1 : delta > 0n ? 1 : 0; + }) + .slice(0, excess); + for (const row of oldest) { + ctx.db.activityLog.delete(row); + } + ctx.db.activityLog.insert({ + id: 0n, + jobName: 'cleanup', + message: `pruned ${oldest.length} old entries`, + at: ctx.timestamp, + }); +}); + +export const cronReconcile = cron.reconcileReducer(spacetimedb); +export const { jobs: cronJobs } = cron.publicViews(spacetimedb); + +export const init = spacetimedb.init(ctx => { + // Code-declared defaults on first publish. Both are runtime state after + // this: reschedule or disable them from the UI without republishing. + cron.schedule(ctx, digest, '0 9 * * 1-5', { timezone: 'America/New_York' }); + cron.schedule(ctx, cleanup, { everySeconds: 300 }, { args: { keep: 50 } }); +}); + +// These reducers are open so the local browser can exercise the submodule. +// Production applications must enforce their own admin policy. + +const jobs: Record = { digest, cleanup }; + +function jobByName(name: string): CronJobReference { + const job = jobs[name]; + if (!job) throw new SenderError(`example.unknown_job:${name}`); + return job; +} + +function cleanupKeep(value: number): number { + if (!Number.isInteger(value) || value < 1 || value > 1_000) { + throw new SenderError('cleanup.invalid_keep:must be between 1 and 1000'); + } + return value; +} + +export const scheduleCron = spacetimedb.reducer( + { + name: t.string(), + expression: t.string(), + timezone: t.string(), + keep: t.u32(), + }, + (ctx, args) => { + try { + if (args.name === 'cleanup') { + cron.schedule(ctx, cleanup, args.expression, { + timezone: args.timezone, + args: { keep: cleanupKeep(args.keep) }, + }); + } else if (args.name === 'digest') { + cron.schedule(ctx, digest, args.expression, { + timezone: args.timezone, + }); + } else { + throw new SenderError(`example.unknown_job:${args.name}`); + } + } catch (err) { + throw err instanceof SenderError + ? err + : new SenderError(err instanceof Error ? err.message : String(err)); + } + } +); + +export const scheduleEvery = spacetimedb.reducer( + { name: t.string(), seconds: t.u32(), keep: t.u32() }, + (ctx, args) => { + try { + if (args.name === 'cleanup') { + cron.schedule( + ctx, + cleanup, + { everySeconds: args.seconds }, + { args: { keep: cleanupKeep(args.keep) } } + ); + } else if (args.name === 'digest') { + cron.schedule(ctx, digest, { everySeconds: args.seconds }); + } else { + throw new SenderError(`example.unknown_job:${args.name}`); + } + } catch (err) { + throw err instanceof SenderError + ? err + : new SenderError(err instanceof Error ? err.message : String(err)); + } + } +); + +export const unscheduleJob = spacetimedb.reducer( + { name: t.string() }, + (ctx, { name }) => { + cron.unschedule(ctx, jobByName(name)); + } +); diff --git a/spacetime-cron-ts/example/spacetimedb/tsconfig.json b/spacetime-cron-ts/example/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..4b41d0f867b --- /dev/null +++ b/spacetime-cron-ts/example/spacetimedb/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "isolatedModules": true + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/spacetime-cron-ts/example/src/app.ts b/spacetime-cron-ts/example/src/app.ts new file mode 100644 index 00000000000..38b944d0dd6 --- /dev/null +++ b/spacetime-cron-ts/example/src/app.ts @@ -0,0 +1,449 @@ +import { DbConnection, tables, type ErrorContext } from './module_bindings/app'; +import type { CronSchedule } from './module_bindings/app/types'; + +interface ServerConfig { + spacetimeUri: string; + databaseName: string; +} + +type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error'; +type StatusTone = 'neutral' | 'success' | 'error'; + +let connection: DbConnection | null = null; + +function element( + tag: T, + className?: string, + text?: string +): HTMLElementTagNameMap[T] { + const node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; +} + +function byId(id: string): T { + const node = document.getElementById(id); + if (!node) throw new Error(`Missing required element #${id}`); + return node as T; +} + +function setText(id: string, value: string | number | bigint): void { + byId(id).textContent = String(value); +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function formatTime(micros: bigint): string { + return new Date(Number(micros / 1_000n)).toLocaleString(undefined, { + dateStyle: 'medium', + timeStyle: 'medium', + }); +} + +function formatJobName(name: string): string { + return name + .split('_') + .map(part => `${part.charAt(0).toUpperCase()}${part.slice(1)}`) + .join(' '); +} + +function scheduleLabel(schedule: CronSchedule): string { + if (schedule.tag === 'Cron') { + return `${schedule.value.expression} · ${schedule.value.timezone}`; + } + return `Every ${schedule.value.seconds} seconds`; +} + +function nextRunLabel(nextRunAt?: { microsSinceUnixEpoch: bigint }): string { + return nextRunAt ? formatTime(nextRunAt.microsSinceUnixEpoch) : 'Not armed'; +} + +function setConnection(state: ConnectionState, label: string): void { + byId('connection').dataset.state = state; + setText('conn', label); + const enabled = state === 'connected'; + byId('open-scheduler').disabled = !enabled; + byId('btn-schedule').disabled = !enabled; +} + +function setFormStatus(text: string, tone: StatusTone = 'neutral'): void { + const status = byId('form-status'); + status.textContent = text; + status.dataset.tone = tone; +} + +function setCollectionVisibility( + listId: string, + emptyId: string, + hasItems: boolean +): void { + byId(listId).hidden = !hasItems; + byId(emptyId).hidden = hasItems; +} + +function metric(label: string, value: string, unhealthy = false): HTMLElement { + const node = element('div', 'metric'); + const valueNode = element( + 'strong', + unhealthy ? 'unhealthy' : undefined, + value + ); + node.append(element('span', undefined, label), valueNode); + return node; +} + +function renderJobs(): void { + if (!connection) return; + const jobs = [...connection.db.cronJobs.iter()].sort((left, right) => + left.name.localeCompare(right.name) + ); + const list = byId('jobs'); + list.replaceChildren(); + + let healthy = 0; + let dispatches = 0n; + + for (const job of jobs) { + if (job.enabled && job.consecutiveFailures === 0) healthy += 1; + dispatches += job.fireCount; + + const item = element('li', 'job-card'); + item.dataset.enabled = String(job.enabled); + + const heading = element('div', 'job-card-top'); + const identity = element('div', 'job-identity'); + const name = element('div'); + name.append( + element('strong', undefined, formatJobName(job.name)), + element('code', undefined, job.name) + ); + identity.append( + element('span', 'job-icon', job.name.charAt(0).toUpperCase()), + name + ); + + const statusText = job.enabled ? 'enabled' : 'disabled'; + const status = element('span', `status-badge ${statusText}`, statusText); + if (job.disabledReason) status.title = job.disabledReason; + heading.append(identity, status); + + const schedule = element('div', 'job-schedule'); + schedule.append(element('code', undefined, scheduleLabel(job.schedule))); + + const footer = element('div', 'job-footer'); + const metrics = element('div', 'job-metrics'); + metrics.append( + metric('Next run', nextRunLabel(job.nextRunAt)), + metric('Dispatches', String(job.fireCount)), + metric( + 'Failures', + String(job.consecutiveFailures), + job.consecutiveFailures > 0 + ) + ); + footer.append(metrics); + + if (job.enabled) { + const button = element( + 'button', + 'button button-secondary button-small', + 'Unschedule' + ); + button.type = 'button'; + button.onclick = async () => { + const current = connection; + if (!current) return; + button.disabled = true; + setFormStatus(`Unscheduling ${formatJobName(job.name)}...`); + try { + await current.reducers.unscheduleJob({ name: job.name }); + setFormStatus(`${formatJobName(job.name)} unscheduled.`, 'success'); + } catch (error) { + setFormStatus(errorMessage(error), 'error'); + button.disabled = false; + } + }; + footer.append(button); + } + + item.append(heading, schedule, footer); + list.append(item); + } + + setText('job-count', jobs.length); + setText('stat-jobs', jobs.length); + setText('stat-healthy', healthy); + setText('stat-fires', dispatches); + setCollectionVisibility('jobs', 'jobs-empty', jobs.length > 0); +} + +function renderRuns(): void { + if (!connection) return; + const runs = [...connection.db.cronRun.iter()] + .sort((left, right) => { + const leftTime = left.scheduledFor.microsSinceUnixEpoch; + const rightTime = right.scheduledFor.microsSinceUnixEpoch; + if (leftTime !== rightTime) return leftTime > rightTime ? -1 : 1; + const byName = left.jobName.localeCompare(right.jobName); + if (byName !== 0) return byName; + return left.sequence > right.sequence + ? -1 + : left.sequence < right.sequence + ? 1 + : 0; + }) + .slice(0, 20); + const list = byId('runs'); + list.replaceChildren(); + + for (const run of runs) { + const failed = run.status.tag === 'Failed'; + const item = element('li', 'event-item'); + const marker = element('span', `event-marker ${failed ? 'failed' : 'ok'}`); + marker.setAttribute('aria-hidden', 'true'); + const content = element('div', 'event-content'); + content.append( + element( + 'span', + 'event-title', + `${formatJobName(run.jobName)} · ${run.status.tag}` + ) + ); + if (run.error) { + content.append(element('span', 'event-copy', run.error)); + } + content.append( + element( + 'time', + 'event-time', + formatTime(run.scheduledFor.microsSinceUnixEpoch) + ) + ); + item.append(marker, content); + list.append(item); + } + + setText('run-count', runs.length); + setCollectionVisibility('runs', 'runs-empty', runs.length > 0); +} + +function renderActivity(): void { + if (!connection) return; + const entries = [...connection.db.activityLog.iter()] + .sort((left, right) => { + const leftTime = left.at.microsSinceUnixEpoch; + const rightTime = right.at.microsSinceUnixEpoch; + if (leftTime !== rightTime) return leftTime > rightTime ? -1 : 1; + return left.id > right.id ? -1 : left.id < right.id ? 1 : 0; + }) + .slice(0, 20); + const list = byId('activity'); + list.replaceChildren(); + + for (const entry of entries) { + const item = element('li', 'event-item'); + const marker = element('span', 'event-marker'); + marker.setAttribute('aria-hidden', 'true'); + const content = element('div', 'event-content'); + content.append( + element('span', 'event-title', formatJobName(entry.jobName)), + element('span', 'event-copy', entry.message), + element('time', 'event-time', formatTime(entry.at.microsSinceUnixEpoch)) + ); + item.append(marker, content); + list.append(item); + } + + setText('activity-count', entries.length); + setCollectionVisibility('activity', 'activity-empty', entries.length > 0); +} + +function renderAll(): void { + renderJobs(); + renderRuns(); + renderActivity(); +} + +function updateScheduleFields(): void { + const kind = byId('spec-kind'); + const expression = byId('spec-expr'); + const isCron = kind.value === 'cron'; + setText('spec-expr-label', isCron ? 'Expression' : 'Seconds'); + setText( + 'spec-help', + isCron + ? 'Use five fields, or six fields to include seconds.' + : 'Enter a whole number of seconds.' + ); + expression.placeholder = isCron ? '*/10 * * * * *' : '10'; + byId('spec-tz-wrap').hidden = !isCron; +} + +function applyPreset(preset: string): void { + const kind = byId('spec-kind'); + const expression = byId('spec-expr'); + const timezone = byId('spec-tz'); + + if (preset === 'weekday') { + kind.value = 'cron'; + expression.value = '0 9 * * 1-5'; + timezone.value = 'America/New_York'; + } else if (preset === 'five-minutes') { + kind.value = 'every'; + expression.value = '300'; + } else { + kind.value = 'cron'; + expression.value = '*/10 * * * * *'; + timezone.value = 'UTC'; + } + + updateScheduleFields(); + setFormStatus('Preset applied.'); + expression.focus(); +} + +function registerUiHandlers(): void { + const form = byId('schedule-form'); + const kind = byId('spec-kind'); + const expression = byId('spec-expr'); + const timezone = byId('spec-tz'); + const jobName = byId('job-name'); + const cleanupKeep = byId('cleanup-keep'); + const submit = byId('btn-schedule'); + + form.onsubmit = async event => { + event.preventDefault(); + const current = connection; + if (!current) { + setFormStatus('Connect to SpacetimeDB before scheduling a job.', 'error'); + return; + } + + const name = jobName.value; + const keep = Number(cleanupKeep.value); + submit.disabled = true; + setFormStatus(''); + try { + if ( + name === 'cleanup' && + (!Number.isInteger(keep) || keep < 1 || keep > 1_000) + ) { + throw new Error('Rows to keep must be an integer from 1 through 1000.'); + } + if (kind.value === 'cron') { + const value = expression.value.trim(); + if (!value) throw new Error('Enter a cron expression.'); + setFormStatus(`Scheduling ${formatJobName(name)}...`); + await current.reducers.scheduleCron({ + name, + expression: value, + timezone: timezone.value.trim() || 'UTC', + keep, + }); + } else { + const seconds = Number(expression.value); + if (!Number.isInteger(seconds) || seconds < 1) { + throw new Error('Interval seconds must be a positive integer.'); + } + setFormStatus(`Scheduling ${formatJobName(name)}...`); + await current.reducers.scheduleEvery({ name, seconds, keep }); + } + setFormStatus(`${formatJobName(name)} scheduled.`, 'success'); + } catch (error) { + setFormStatus(errorMessage(error), 'error'); + } finally { + submit.disabled = connection === null; + } + }; + + kind.onchange = () => { + const isCron = kind.value === 'cron'; + expression.value = isCron ? '*/10 * * * * *' : '10'; + updateScheduleFields(); + setFormStatus(''); + }; + + jobName.onchange = () => { + byId('cleanup-keep-wrap').hidden = jobName.value !== 'cleanup'; + setFormStatus(''); + }; + + for (const preset of document.querySelectorAll( + '[data-preset]' + )) { + preset.onclick = () => applyPreset(preset.dataset.preset ?? ''); + } + + byId('open-scheduler').onclick = () => { + byId('scheduler').scrollIntoView({ behavior: 'smooth', block: 'center' }); + window.setTimeout(() => jobName.focus(), 250); + }; + + updateScheduleFields(); +} + +function registerRowCallbacks(connection: DbConnection): void { + connection.db.cronJobs.onInsert(renderJobs); + connection.db.cronJobs.onUpdate(renderJobs); + connection.db.cronJobs.onDelete(renderJobs); + connection.db.cronRun.onInsert(renderRuns); + connection.db.cronRun.onUpdate(renderRuns); + connection.db.cronRun.onDelete(renderRuns); + connection.db.activityLog.onInsert(renderActivity); + connection.db.activityLog.onUpdate(renderActivity); + connection.db.activityLog.onDelete(renderActivity); +} + +function subscribeToTables(connection: DbConnection): void { + connection + .subscriptionBuilder() + .onApplied(renderAll) + .onError((ctx: ErrorContext) => + console.error('subscription error', ctx.event) + ) + .subscribe([tables.cronJobs, tables.cronRun, tables.activityLog]); +} + +async function loadServerConfig(): Promise { + const response = await fetch('/api/config'); + if (!response.ok) { + throw new Error(`Config request failed: ${response.status}`); + } + return (await response.json()) as ServerConfig; +} + +function connect(config: ServerConfig): void { + DbConnection.builder() + .withUri(config.spacetimeUri) + .withDatabaseName(config.databaseName) + .onConnect((current: DbConnection) => { + connection = current; + setConnection('connected', config.databaseName); + registerRowCallbacks(current); + subscribeToTables(current); + }) + .onConnectError((_ctx: ErrorContext, error: Error) => { + setConnection('error', 'Connection failed'); + setFormStatus(error.message, 'error'); + }) + .onDisconnect((_ctx, error) => { + connection = null; + setConnection('disconnected', 'Disconnected'); + if (error) setFormStatus(error.message, 'error'); + }) + .build(); +} + +async function main(): Promise { + registerUiHandlers(); + setConnection('connecting', 'Connecting'); + connect(await loadServerConfig()); +} + +void main().catch(error => { + setConnection('error', 'Configuration failed'); + setFormStatus(errorMessage(error), 'error'); +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/activity_log_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/activity_log_table.ts new file mode 100644 index 00000000000..e6c83267786 --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/activity_log_table.ts @@ -0,0 +1,18 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + id: __t.u64().primaryKey(), + jobName: __t.string().name("job_name"), + message: __t.string(), + at: __t.timestamp(), +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/cleanup_fire_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/cleanup_fire_table.ts new file mode 100644 index 00000000000..107696eecfe --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/cleanup_fire_table.ts @@ -0,0 +1,26 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; +import { + CronFireRecovery, +} from "./types"; + + +export default __t.row({ + scheduledId: __t.u64().primaryKey().name("scheduled_id"), + scheduledAt: __t.scheduleAt().name("scheduled_at"), + jobName: __t.string().name("job_name"), + generation: __t.u64(), + targetAt: __t.option(__t.timestamp()).name("target_at"), + get recovery() { + return __t.option(CronFireRecovery); + }, +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/cron_jobs_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/cron_jobs_table.ts new file mode 100644 index 00000000000..a7f49c2639a --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/cron_jobs_table.ts @@ -0,0 +1,30 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; +import { + CronSchedule, +} from "./types"; + + +export default __t.row({ + name: __t.string().primaryKey(), + get schedule() { + return CronSchedule; + }, + enabled: __t.bool(), + maxFailures: __t.u32().name("max_failures"), + consecutiveFailures: __t.u32().name("consecutive_failures"), + fireCount: __t.u64().name("fire_count"), + generation: __t.u64(), + lastRunAt: __t.option(__t.timestamp()).name("last_run_at"), + nextRunAt: __t.option(__t.timestamp()).name("next_run_at"), + disabledReason: __t.option(__t.string()).name("disabled_reason"), +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/cron_reconcile_tick_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/cron_reconcile_tick_table.ts new file mode 100644 index 00000000000..e58ad71b8ca --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/cron_reconcile_tick_table.ts @@ -0,0 +1,17 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + scheduledId: __t.u64().primaryKey().name("scheduled_id"), + scheduledAt: __t.scheduleAt().name("scheduled_at"), + key: __t.string(), +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/cron_run_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/cron_run_table.ts new file mode 100644 index 00000000000..122a896817f --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/cron_run_table.ts @@ -0,0 +1,28 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; +import { + CronRunStatus, +} from "./types"; + + +export default __t.row({ + invocationId: __t.string().primaryKey().name("invocation_id"), + jobName: __t.string().name("job_name"), + generation: __t.u64(), + sequence: __t.u64(), + scheduledFor: __t.timestamp().name("scheduled_for"), + completedAt: __t.timestamp().name("completed_at"), + get status() { + return CronRunStatus; + }, + error: __t.option(__t.string()), +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/digest_fire_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/digest_fire_table.ts new file mode 100644 index 00000000000..107696eecfe --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/digest_fire_table.ts @@ -0,0 +1,26 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; +import { + CronFireRecovery, +} from "./types"; + + +export default __t.row({ + scheduledId: __t.u64().primaryKey().name("scheduled_id"), + scheduledAt: __t.scheduleAt().name("scheduled_at"), + jobName: __t.string().name("job_name"), + generation: __t.u64(), + targetAt: __t.option(__t.timestamp()).name("target_at"), + get recovery() { + return __t.option(CronFireRecovery); + }, +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/index.ts b/spacetime-cron-ts/example/src/module_bindings/app/index.ts new file mode 100644 index 00000000000..a7dadc03843 --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/index.ts @@ -0,0 +1,203 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +// This was generated using spacetimedb cli version 2.11.0 (commit 094df0ed2107fe3a359f5e4ee7a4c344802fc96c). + +/* eslint-disable */ +/* tslint:disable */ +import { + DbConnectionBuilder as __DbConnectionBuilder, + DbConnectionImpl as __DbConnectionImpl, + SubscriptionBuilderImpl as __SubscriptionBuilderImpl, + TypeBuilder as __TypeBuilder, + Uuid as __Uuid, + convertToAccessorMap as __convertToAccessorMap, + makeQueryBuilder as __makeQueryBuilder, + procedureSchema as __procedureSchema, + procedures as __procedures, + reducerSchema as __reducerSchema, + reducers as __reducers, + schema as __schema, + t as __t, + table as __table, + type AlgebraicTypeType as __AlgebraicTypeType, + type DbConnectionConfig as __DbConnectionConfig, + type ErrorContextInterface as __ErrorContextInterface, + type Event as __Event, + type EventContextInterface as __EventContextInterface, + type Infer as __Infer, + type QueryBuilder as __QueryBuilder, + type ReducerEventContextInterface as __ReducerEventContextInterface, + type RemoteModule as __RemoteModule, + type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, + type SubscriptionHandleImpl as __SubscriptionHandleImpl, +} from "spacetimedb"; + +// Import all reducer arg schemas +import ScheduleCronReducer from "./schedule_cron_reducer"; +import ScheduleEveryReducer from "./schedule_every_reducer"; +import UnscheduleJobReducer from "./unschedule_job_reducer"; + +// Import all procedure arg schemas + +// Import all table schema definitions +import ActivityLogRow from "./activity_log_table"; +import CleanupFireRow from "./cleanup_fire_table"; +import CronJobsRow from "./cron_jobs_table"; +import CronReconcileTickRow from "./cron_reconcile_tick_table"; +import CronRunRow from "./cron_run_table"; +import DigestFireRow from "./digest_fire_table"; + +/** Type-only namespace exports for generated type groups. */ + +/** The schema information for all tables in this module. This is defined the same was as the tables would have been defined in the server. */ +const tablesSchema = __schema({ + activityLog: __table({ + name: 'activity_log', + indexes: [ + { accessor: 'at', name: 'activity_log_at_idx_btree', algorithm: 'btree', columns: [ + 'at', + ] }, + { accessor: 'id', name: 'activity_log_id_idx_btree', algorithm: 'btree', columns: [ + 'id', + ] }, + { accessor: 'jobName', name: 'activity_log_job_name_idx_btree', algorithm: 'btree', columns: [ + 'jobName', + ] }, + ], + constraints: [ + { name: 'activity_log_id_key', constraint: 'unique', columns: ['id'] }, + ], + }, ActivityLogRow), + cleanupFire: __table({ + name: 'cleanup_fire', + indexes: [ + { accessor: 'jobName', name: 'cleanup_fire_job_name_idx_btree', algorithm: 'btree', columns: [ + 'jobName', + ] }, + { accessor: 'scheduledId', name: 'cleanup_fire_scheduled_id_idx_btree', algorithm: 'btree', columns: [ + 'scheduledId', + ] }, + ], + constraints: [ + { name: 'cleanup_fire_job_name_key', constraint: 'unique', columns: ['jobName'] }, + { name: 'cleanup_fire_scheduled_id_key', constraint: 'unique', columns: ['scheduledId'] }, + ], + }, CleanupFireRow), + cronReconcileTick: __table({ + name: 'cron_reconcile_tick', + indexes: [ + { accessor: 'key', name: 'cron_reconcile_tick_key_idx_btree', algorithm: 'btree', columns: [ + 'key', + ] }, + { accessor: 'scheduledId', name: 'cron_reconcile_tick_scheduled_id_idx_btree', algorithm: 'btree', columns: [ + 'scheduledId', + ] }, + ], + constraints: [ + { name: 'cron_reconcile_tick_key_key', constraint: 'unique', columns: ['key'] }, + { name: 'cron_reconcile_tick_scheduled_id_key', constraint: 'unique', columns: ['scheduledId'] }, + ], + }, CronReconcileTickRow), + cronRun: __table({ + name: 'cron_run', + indexes: [ + { accessor: 'invocationId', name: 'cron_run_invocation_id_idx_btree', algorithm: 'btree', columns: [ + 'invocationId', + ] }, + { accessor: 'jobName', name: 'cron_run_job_name_idx_btree', algorithm: 'btree', columns: [ + 'jobName', + ] }, + ], + constraints: [ + { name: 'cron_run_invocation_id_key', constraint: 'unique', columns: ['invocationId'] }, + ], + }, CronRunRow), + digestFire: __table({ + name: 'digest_fire', + indexes: [ + { accessor: 'jobName', name: 'digest_fire_job_name_idx_btree', algorithm: 'btree', columns: [ + 'jobName', + ] }, + { accessor: 'scheduledId', name: 'digest_fire_scheduled_id_idx_btree', algorithm: 'btree', columns: [ + 'scheduledId', + ] }, + ], + constraints: [ + { name: 'digest_fire_job_name_key', constraint: 'unique', columns: ['jobName'] }, + { name: 'digest_fire_scheduled_id_key', constraint: 'unique', columns: ['scheduledId'] }, + ], + }, DigestFireRow), + cronJobs: __table({ + name: 'cron_jobs', + indexes: [ + ], + constraints: [ + ], + }, CronJobsRow), +}); + +/** The schema information for all reducers in this module. This is defined the same way as the reducers would have been defined in the server, except the body of the reducer is omitted in code generation. */ +const reducersSchema = __reducers( + __reducerSchema("schedule_cron", ScheduleCronReducer), + __reducerSchema("schedule_every", ScheduleEveryReducer), + __reducerSchema("unschedule_job", UnscheduleJobReducer), +); + +/** The schema information for all procedures in this module. This is defined the same way as the procedures would have been defined in the server. */ +const proceduresSchema = __procedures( +); + +/** The remote SpacetimeDB module schema, both runtime and type information. */ +const REMOTE_MODULE = { + versionInfo: { + cliVersion: "2.11.0" as const, + }, + tables: tablesSchema.schemaType.tables, + reducers: reducersSchema.reducersType.reducers, + ...proceduresSchema, +} satisfies __RemoteModule< + typeof tablesSchema.schemaType, + typeof reducersSchema.reducersType, + typeof proceduresSchema +>; + +/** The tables available in this remote SpacetimeDB module. Each table reference doubles as a query builder. */ +export const tables: __QueryBuilder = __makeQueryBuilder(tablesSchema.schemaType); + +/** The reducers available in this remote SpacetimeDB module. */ +export const reducers = __convertToAccessorMap(reducersSchema.reducersType.reducers); + +/** The procedures available in this remote SpacetimeDB module. */ +export const procedures = __convertToAccessorMap(proceduresSchema.procedures); + +/** The context type returned in callbacks for all possible events. */ +export type EventContext = __EventContextInterface; +/** The context type returned in callbacks for reducer events. */ +export type ReducerEventContext = __ReducerEventContextInterface; +/** The context type returned in callbacks for subscription events. */ +export type SubscriptionEventContext = __SubscriptionEventContextInterface; +/** The context type returned in callbacks for error events. */ +export type ErrorContext = __ErrorContextInterface; +/** The subscription handle type to manage active subscriptions created from a {@link SubscriptionBuilder}. */ +export type SubscriptionHandle = __SubscriptionHandleImpl; + +/** Builder class to configure a new subscription to the remote SpacetimeDB instance. */ +export class SubscriptionBuilder extends __SubscriptionBuilderImpl {} + +/** Builder class to configure a new database connection to the remote SpacetimeDB instance. */ +export class DbConnectionBuilder extends __DbConnectionBuilder {} + +/** The typed database connection to manage connections to the remote SpacetimeDB instance. This class has type information specific to the generated module. */ +export class DbConnection extends __DbConnectionImpl { + /** Creates a new {@link DbConnectionBuilder} to configure and connect to the remote SpacetimeDB instance. */ + static builder = (): DbConnectionBuilder => { + return new DbConnectionBuilder(REMOTE_MODULE, (config: __DbConnectionConfig) => new DbConnection(config)); + }; + + /** Creates a new {@link SubscriptionBuilder} to configure a subscription to the remote SpacetimeDB instance. */ + override subscriptionBuilder = (): SubscriptionBuilder => { + return new SubscriptionBuilder(this); + }; +} + diff --git a/spacetime-cron-ts/example/src/module_bindings/app/schedule_cron_reducer.ts b/spacetime-cron-ts/example/src/module_bindings/app/schedule_cron_reducer.ts new file mode 100644 index 00000000000..708fe42e2e6 --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/schedule_cron_reducer.ts @@ -0,0 +1,18 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + name: __t.string(), + expression: __t.string(), + timezone: __t.string(), + keep: __t.u32(), +}; diff --git a/spacetime-cron-ts/example/src/module_bindings/app/schedule_every_reducer.ts b/spacetime-cron-ts/example/src/module_bindings/app/schedule_every_reducer.ts new file mode 100644 index 00000000000..e054dd57fa5 --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/schedule_every_reducer.ts @@ -0,0 +1,17 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + name: __t.string(), + seconds: __t.u32(), + keep: __t.u32(), +}; diff --git a/spacetime-cron-ts/example/src/module_bindings/app/types.ts b/spacetime-cron-ts/example/src/module_bindings/app/types.ts new file mode 100644 index 00000000000..c538888e35f --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/types.ts @@ -0,0 +1,153 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const ActivityLog = __t.object("ActivityLog", { + id: __t.u64(), + jobName: __t.string(), + message: __t.string(), + at: __t.timestamp(), +}); +export type ActivityLog = __Infer; + +export const CleanupCronArgs = __t.object("CleanupCronArgs", { + keep: __t.u32(), +}); +export type CleanupCronArgs = __Infer; + +export const CleanupFire = __t.object("CleanupFire", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), + jobName: __t.string(), + generation: __t.u64(), + targetAt: __t.option(__t.timestamp()), + get recovery() { + return __t.option(CronFireRecovery); + }, +}); +export type CleanupFire = __Infer; + +export const CronFireRecovery = __t.object("CronFireRecovery", { + sequence: __t.u64(), + scheduledFor: __t.timestamp(), + error: __t.string(), +}); +export type CronFireRecovery = __Infer; + +export const CronJob = __t.object("CronJob", { + name: __t.string(), + get schedule() { + return CronSchedule; + }, + get args() { + return CronJobArgsValue; + }, + enabled: __t.bool(), + maxFailures: __t.u32(), + consecutiveFailures: __t.u32(), + fireCount: __t.u64(), + generation: __t.u64(), + lastRunAt: __t.option(__t.timestamp()), + nextRunAt: __t.option(__t.timestamp()), + disabledReason: __t.option(__t.string()), +}); +export type CronJob = __Infer; + +// The tagged union or sum type for the algebraic type `CronJobArgsValue`. +export const CronJobArgsValue = __t.enum("CronJobArgsValue", { + get Cleanup() { + return CleanupCronArgs; + }, + Digest: __t.unit(), +}); +export type CronJobArgsValue = __Infer; + +export const CronJobView = __t.object("CronJobView", { + name: __t.string(), + get schedule() { + return CronSchedule; + }, + enabled: __t.bool(), + maxFailures: __t.u32(), + consecutiveFailures: __t.u32(), + fireCount: __t.u64(), + generation: __t.u64(), + lastRunAt: __t.option(__t.timestamp()), + nextRunAt: __t.option(__t.timestamp()), + disabledReason: __t.option(__t.string()), +}); +export type CronJobView = __Infer; + +export const CronJobs = __t.object("CronJobs", {}); +export type CronJobs = __Infer; + +export const CronReconcileTick = __t.object("CronReconcileTick", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), + key: __t.string(), +}); +export type CronReconcileTick = __Infer; + +export const CronRun = __t.object("CronRun", { + invocationId: __t.string(), + jobName: __t.string(), + generation: __t.u64(), + sequence: __t.u64(), + scheduledFor: __t.timestamp(), + completedAt: __t.timestamp(), + get status() { + return CronRunStatus; + }, + error: __t.option(__t.string()), +}); +export type CronRun = __Infer; + +// The tagged union or sum type for the algebraic type `CronRunStatus`. +export const CronRunStatus = __t.enum("CronRunStatus", { + Ok: __t.unit(), + Failed: __t.unit(), +}); +export type CronRunStatus = __Infer; + +// The tagged union or sum type for the algebraic type `CronSchedule`. +export const CronSchedule = __t.enum("CronSchedule", { + get Cron() { + return CronSpec; + }, + get Every() { + return EverySpec; + }, +}); +export type CronSchedule = __Infer; + +export const CronSpec = __t.object("CronSpec", { + expression: __t.string(), + timezone: __t.string(), +}); +export type CronSpec = __Infer; + +export const DigestFire = __t.object("DigestFire", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), + jobName: __t.string(), + generation: __t.u64(), + targetAt: __t.option(__t.timestamp()), + get recovery() { + return __t.option(CronFireRecovery); + }, +}); +export type DigestFire = __Infer; + +export const EverySpec = __t.object("EverySpec", { + seconds: __t.u32(), +}); +export type EverySpec = __Infer; + diff --git a/spacetime-cron-ts/example/src/module_bindings/app/types/procedures.ts b/spacetime-cron-ts/example/src/module_bindings/app/types/procedures.ts new file mode 100644 index 00000000000..d5ac825c9ab --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/types/procedures.ts @@ -0,0 +1,10 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from "spacetimedb"; + +// Import all procedure arg schemas + + diff --git a/spacetime-cron-ts/example/src/module_bindings/app/types/reducers.ts b/spacetime-cron-ts/example/src/module_bindings/app/types/reducers.ts new file mode 100644 index 00000000000..3f09c30fc78 --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/types/reducers.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from "spacetimedb"; + +// Import all reducer arg schemas +import ScheduleCronReducer from "../schedule_cron_reducer"; +import ScheduleEveryReducer from "../schedule_every_reducer"; +import UnscheduleJobReducer from "../unschedule_job_reducer"; + +export type ScheduleCronParams = __Infer; +export type ScheduleEveryParams = __Infer; +export type UnscheduleJobParams = __Infer; + diff --git a/spacetime-cron-ts/example/src/module_bindings/app/unschedule_job_reducer.ts b/spacetime-cron-ts/example/src/module_bindings/app/unschedule_job_reducer.ts new file mode 100644 index 00000000000..ce493ee8574 --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/unschedule_job_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + name: __t.string(), +}; diff --git a/spacetime-cron-ts/example/tsconfig.json b/spacetime-cron-ts/example/tsconfig.json new file mode 100644 index 00000000000..143c4fb996c --- /dev/null +++ b/spacetime-cron-ts/example/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "isolatedModules": true, + "allowImportingTsExtensions": true + }, + "include": ["src/**/*.ts", "server.ts"], + "exclude": ["node_modules", "spacetimedb"] +} diff --git a/spacetime-cron-ts/package.json b/spacetime-cron-ts/package.json new file mode 100644 index 00000000000..1a0b050d738 --- /dev/null +++ b/spacetime-cron-ts/package.json @@ -0,0 +1,84 @@ +{ + "name": "@spacetimedb/cron", + "description": "Calendar and interval scheduling for SpacetimeDB TypeScript modules.", + "version": "0.1.0", + "license": "Apache-2.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./parser": { + "types": "./src/parser.ts", + "default": "./src/parser.ts" + } + }, + "files": [ + "dist", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./parser": { + "types": "./dist/parser.d.ts", + "default": "./dist/parser.js" + } + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/clockworklabs/SpacetimeDB.git", + "directory": "spacetime-cron-ts" + }, + "homepage": "https://github.com/clockworklabs/SpacetimeDB/tree/master/spacetime-cron-ts#readme", + "bugs": { + "url": "https://github.com/clockworklabs/SpacetimeDB/issues" + }, + "keywords": [ + "spacetimedb", + "cron", + "scheduler", + "typescript" + ], + "scripts": { + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "pnpm run test:parser && pnpm run test:schedule && pnpm run test:validation && pnpm run test:registration", + "test:parser": "tsx scripts/test-cron-parser.ts", + "test:module:local": "node scripts/test-module-local.mjs", + "test:registration": "node --js-explicit-resource-management --import tsx --import ./scripts/sys-abi-test-register.mjs scripts/test-registration.ts", + "test:recovery": "node scripts/test-recovery.mjs", + "test:schedule": "tsx scripts/test-schedule.ts", + "test:validation": "tsx scripts/test-validation.ts", + "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json", + "prepack": "pnpm run build && node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" + }, + "dependencies": { + "cron-parser": "5.5.0" + }, + "peerDependencies": { + "spacetimedb": "workspace:^" + }, + "devDependencies": { + "eslint": "^9.17.0", + "prettier": "^3.3.3", + "@types/node": "^22.10.2", + "spacetimedb": "workspace:*", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-cron-ts/scripts/sys-abi-test-register.mjs b/spacetime-cron-ts/scripts/sys-abi-test-register.mjs new file mode 100644 index 00000000000..6a9b9e9d245 --- /dev/null +++ b/spacetime-cron-ts/scripts/sys-abi-test-register.mjs @@ -0,0 +1,27 @@ +import { register } from 'node:module'; + +// Host syscall modules exist only inside SpacetimeDB. Stub the bindings that +// `spacetimedb/server` reads while loading. +const stubs = { + 'spacetime:sys@2.0': + 'export const moduleHooks = Symbol(); export function row_iter_bsatn_close() {} export function volatile_nonatomic_schedule_immediate() {}', + 'spacetime:sys@2.1': 'export {};', + 'spacetime:sys@2.2': 'export function env_get() {}', +}; + +const loaderSource = ` + const stubs = ${JSON.stringify(stubs)}; + export function resolve(specifier, context, nextResolve) { + return specifier in stubs + ? { + shortCircuit: true, + url: 'data:text/javascript,' + encodeURIComponent(stubs[specifier]), + } + : nextResolve(specifier, context); + } +`; + +register( + `data:text/javascript,${encodeURIComponent(loaderSource)}`, + import.meta.url +); diff --git a/spacetime-cron-ts/scripts/test-cron-parser.ts b/spacetime-cron-ts/scripts/test-cron-parser.ts new file mode 100644 index 00000000000..b0e4151fa9b --- /dev/null +++ b/spacetime-cron-ts/scripts/test-cron-parser.ts @@ -0,0 +1,210 @@ +// Pure-Node sanity test. No STDB needed. + +import { + MAX_CRON_EXPRESSION_LENGTH, + MAX_TIMEZONE_LENGTH, + isValidTimezone, + nextFireAfter, + parseCronExpression, +} from '../src/parser'; + +function assert(cond: boolean, msg: string): void { + if (!cond) { + process.stderr.write(`FAIL: ${msg}\n`); + process.exit(1); + } +} + +function check( + expr: string, + fromIso: string, + expectIso: string, + timezone = 'UTC' +): void { + const parsed = parseCronExpression(expr); + const fromMicros = BigInt(new Date(fromIso).getTime()) * 1000n; + const next = nextFireAfter(parsed, fromMicros, timezone); + if (next === undefined) { + assert( + false, + `${expr} [${timezone}] from ${fromIso} → undefined (expected ${expectIso})` + ); + return; + } + const got = new Date(Number(next / 1000n)).toISOString(); + assert( + got === expectIso, + `${expr} [${timezone}] from ${fromIso} → ${got} (expected ${expectIso})` + ); + process.stdout.write( + ` ${expr.padEnd(15)} [${timezone.padEnd(20)}] from ${fromIso} → ${got} ✓\n` + ); +} + +process.stdout.write('cron parser tests\n'); + +// "every minute" +check('* * * * *', '2026-05-04T12:00:00.000Z', '2026-05-04T12:01:00.000Z'); +check('* * * * *', '2026-05-04T12:00:30.000Z', '2026-05-04T12:01:00.000Z'); + +// every 15 minutes +check('*/15 * * * *', '2026-05-04T12:00:00.000Z', '2026-05-04T12:15:00.000Z'); +check('*/15 * * * *', '2026-05-04T12:50:00.000Z', '2026-05-04T13:00:00.000Z'); + +// daily at 9:00 UTC +check('0 9 * * *', '2026-05-04T08:00:00.000Z', '2026-05-04T09:00:00.000Z'); +check('0 9 * * *', '2026-05-04T09:00:00.000Z', '2026-05-05T09:00:00.000Z'); + +// Mondays at 9:00 UTC (Mon = 1) +check('0 9 * * 1', '2026-05-04T08:00:00.000Z', '2026-05-04T09:00:00.000Z'); // Mon May 4 +check('0 9 * * MON', '2026-05-04T10:00:00.000Z', '2026-05-11T09:00:00.000Z'); // next Mon + +// First of the month at midnight +check('0 0 1 * *', '2026-05-04T00:00:00.000Z', '2026-06-01T00:00:00.000Z'); + +// Range + list: weekdays at quarter past 9 +check('15 9 * * 1-5', '2026-05-02T00:00:00.000Z', '2026-05-04T09:15:00.000Z'); // skip weekend + +// Step inside range: every 5 minutes between :00 and :30 +check('0-30/5 * * * *', '2026-05-04T12:00:00.000Z', '2026-05-04T12:05:00.000Z'); +check('0-30/5 * * * *', '2026-05-04T12:30:00.000Z', '2026-05-04T13:00:00.000Z'); + +// DOM + DOW union (Vixie cron); next Mon (May 11) wins over next 1st (Jun 1). +check('0 0 1 * 1', '2026-05-04T00:00:00.000Z', '2026-05-11T00:00:00.000Z'); + +// Named months +check('0 0 1 JAN *', '2026-05-04T00:00:00.000Z', '2027-01-01T00:00:00.000Z'); + +// Unsatisfiable (Feb 31): cron-parser rejects up-front in strict mode. +let unsatThrew = false; +try { + parseCronExpression('0 0 31 2 *'); +} catch { + unsatThrew = true; +} +assert(unsatThrew, '0 0 31 2 * should be rejected as unsatisfiable'); +process.stdout.write( + ' 0 0 31 2 * rejected as unsatisfiable ✓\n' +); + +// Validation +let threw = false; +try { + parseCronExpression('invalid'); +} catch { + threw = true; +} +assert(threw, 'invalid expression should throw'); + +assert( + parseCronExpression(' 0 9 * * * ').expression === '0 9 * * *', + 'expression should be normalized' +); +for (const invalid of ['', ' ', '*'.repeat(MAX_CRON_EXPRESSION_LENGTH + 1)]) { + let invalidThrew = false; + try { + parseCronExpression(invalid); + } catch { + invalidThrew = true; + } + assert( + invalidThrew, + `expression should be rejected: ${JSON.stringify(invalid.slice(0, 20))}` + ); +} + +const hashed = parseCronExpression('H * * * *'); +const hashedFrom = + BigInt(new Date('2026-05-04T12:00:00.000Z').getTime()) * 1000n; +assert( + nextFireAfter(hashed, hashedFrom, 'UTC') === + nextFireAfter(hashed, hashedFrom, 'UTC'), + 'hashed expressions should resolve deterministically' +); + +process.stdout.write('\ntimezone tests\n'); + +// 9am Pacific: 17:00 UTC in PST, 16:00 UTC in PDT. +check( + '0 9 * * *', + '2026-01-15T00:00:00.000Z', + '2026-01-15T17:00:00.000Z', + 'America/Los_Angeles' +); +check( + '0 9 * * *', + '2026-07-15T00:00:00.000Z', + '2026-07-15T16:00:00.000Z', + 'America/Los_Angeles' +); + +// 9am Tokyo = 00:00 UTC same day. +check( + '0 9 * * *', + '2026-05-03T23:59:00.000Z', + '2026-05-04T00:00:00.000Z', + 'Asia/Tokyo' +); +// 00:00 UTC IS 9am Tokyo today; strict-after means next is tomorrow. +check( + '0 9 * * *', + '2026-05-04T00:00:00.000Z', + '2026-05-05T00:00:00.000Z', + 'Asia/Tokyo' +); + +// "Every Monday 9am" in NY (EST/EDT) +check( + '0 9 * * MON', + '2026-01-04T00:00:00.000Z', + '2026-01-05T14:00:00.000Z', + 'America/New_York' +); // Mon Jan 5 9am EST = 14:00 UTC + +// During the New York DST spring-forward, 02:30 resolves to the next available local time. +check( + '30 2 * * *', + '2026-03-08T00:00:00.000Z', + '2026-03-08T07:30:00.000Z', + 'America/New_York' +); + +// DST fall-back: 01:30 NY happens twice, fires once at first occurrence. +check( + '30 1 * * *', + '2026-10-31T23:59:59.000Z', + '2026-11-01T05:30:00.000Z', + 'America/New_York' +); +check( + '30 1 * * *', + '2026-11-01T05:30:00.000Z', + '2026-11-02T06:30:00.000Z', + 'America/New_York' +); + +// IANA validation +assert(isValidTimezone('UTC'), 'UTC should be valid'); +assert( + isValidTimezone('America/Los_Angeles'), + 'America/Los_Angeles should be valid' +); +assert(!isValidTimezone('Not_A_Real/Timezone'), 'bogus tz should be invalid'); +assert( + !isValidTimezone(' UTC'), + 'timezone with surrounding whitespace should be invalid' +); +assert( + !isValidTimezone('x'.repeat(MAX_TIMEZONE_LENGTH + 1)), + 'oversized timezone should be invalid' +); +assert( + nextFireAfter(parseCronExpression('* * * * *'), 0n, 'Not_A_Real/Timezone') === + undefined, + 'nextFireAfter should reject an invalid timezone' +); +process.stdout.write( + ' isValidTimezone gate ✓\n' +); + +process.stdout.write('\nall parser tests passed.\n'); diff --git a/spacetime-cron-ts/scripts/test-module-local.mjs b/spacetime-cron-ts/scripts/test-module-local.mjs new file mode 100644 index 00000000000..90b1f627937 --- /dev/null +++ b/spacetime-cron-ts/scripts/test-module-local.mjs @@ -0,0 +1,509 @@ +// Local integration suite for @spacetimedb/cron. Publishes the demo module +// (spacetimedb/) and the example module (example/spacetimedb/) against a +// running local SpacetimeDB and drives the full fire semantics: +// single-stage scheduled handlers, volatile failure recovery, lost-fire repair, +// payload rollback, auto-disable, procedures, generations, and cancellation. +// +// Requires: `spacetime start` running locally. +import * as assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; + +const database = `cron-release-${process.pid}-${Date.now()}`; +const exampleDatabase = `${database}-example`; +const serverArgs = ['--server', 'local']; +let published = false; +let examplePublished = false; + +function run(args, options = {}) { + const result = spawnSync('spacetime', args, { + cwd: new URL('..', import.meta.url), + encoding: 'utf8', + shell: false, + }); + if (options.expectFailure) { + assert.notEqual( + result.status, + 0, + `command unexpectedly succeeded: spacetime ${args.join(' ')}` + ); + return result; + } + assert.equal( + result.status, + 0, + `command failed: spacetime ${args.join(' ')}\n${result.stdout}\n${result.stderr}` + ); + return result; +} + +function call(name, ...args) { + return run(['call', ...serverArgs, database, name, ...args]); +} + +function callExpectFailure(name, ...args) { + return run(['call', ...serverArgs, database, name, ...args], { + expectFailure: true, + }); +} + +function sql(query, target = database) { + const result = run(['sql', ...serverArgs, '--format', 'json', target, query]); + return JSON.parse(result.stdout)[0].rows; +} + +function sqlExpectFailure(query, target = database) { + return run(['sql', ...serverArgs, '--format', 'json', target, query], { + expectFailure: true, + }); +} + +function count(table, where = '') { + return Number(sql(`SELECT COUNT(*) AS count FROM ${table} ${where}`)[0][0]); +} + +function jobRow(name) { + const rows = sql( + `SELECT enabled, fireCount, consecutiveFailures, disabledReason, generation FROM cron_job WHERE name = '${name}'` + ); + assert.equal(rows.length, 1, `expected one cron_job row for ${name}`); + const [enabled, fireCount, consecutiveFailures, disabledReason, generation] = + rows[0]; + return { + enabled, + fireCount, + consecutiveFailures, + disabledReason, + generation, + }; +} + +function publicDisabledReason(name) { + const rows = sql( + `SELECT disabledReason FROM cron_jobs WHERE name = '${name}'` + ); + assert.equal(rows.length, 1, `expected one cron_jobs row for ${name}`); + const option = rows[0][0]; + assert.deepEqual(option?.[0], 0, `expected a disabled reason for ${name}`); + return option[1]; +} + +function wait(milliseconds) { + return new Promise(resolve => setTimeout(resolve, milliseconds)); +} + +async function poll(description, check, timeoutMilliseconds = 15_000) { + const deadline = Date.now() + timeoutMilliseconds; + let lastError; + + while (Date.now() < deadline) { + try { + const result = check(); + if (result) return result; + lastError = undefined; + } catch (error) { + lastError = error; + } + await wait(200); + } + + const detail = lastError instanceof Error ? `: ${lastError.message}` : ''; + throw new Error(`timed out waiting for ${description}${detail}`); +} + +try { + run([ + 'publish', + ...serverArgs, + '--yes', + '--module-path', + 'spacetimedb', + database, + ]); + published = true; + + // init seeded the heartbeat job (every 30s) declaratively. + assert.equal(count('cron_job'), 1, 'init must seed exactly one job'); + assert.equal( + count('cron_jobs'), + 1, + 'public job view must expose seeded state' + ); + assert.equal( + sql("SELECT name, enabled FROM cron_jobs WHERE name = 'heartbeat'").length, + 1, + 'public job view must support filtered operational queries' + ); + sqlExpectFailure('SELECT args FROM cron_jobs'); + assert.equal( + count('heartbeat_fire', "WHERE jobName = 'heartbeat'"), + 1, + 'seeded job must have exactly one pending fire' + ); + assert.equal( + count('cron_reconcile_tick'), + 1, + 'configured reconciliation must keep one native interval row' + ); + + // Management operations opportunistically repair an enabled job whose fire + // disappeared, record the loss, and preserve the one-row invariant. + call('drop_heartbeat_fire_for_test'); + assert.equal(count('heartbeat_fire'), 0); + assert.equal(jobRow('heartbeat').enabled, true); + call( + 'schedule_report', + JSON.stringify('0 0 1 1 *'), + JSON.stringify('UTC'), + '0', + JSON.stringify('reconcile-probe'), + '1' + ); + assert.equal( + count('heartbeat_fire', "WHERE jobName = 'heartbeat'"), + 1, + 'management scheduling must repair another enabled job' + ); + assert.equal( + count('cron_run', "WHERE jobName = 'heartbeat'"), + 1, + 'opportunistic repair must record lost_fire' + ); + assert.deepEqual( + sql("SELECT error FROM cron_run WHERE jobName = 'heartbeat'")[0][0], + [0, 'lost_fire'], + 'repair history must preserve the lost_fire reason' + ); + + // The optional interval sweep repairs the same invariant without a + // management call. + call('schedule_every', JSON.stringify('heartbeat'), '30', '0'); + call('drop_heartbeat_fire_for_test'); + await poll('the reconciliation sweep to restore heartbeat', () => { + return ( + count('heartbeat_fire', "WHERE jobName = 'heartbeat'") === 1 && + count('cron_run', "WHERE jobName = 'heartbeat'") >= 2 + ); + }); + assert.equal( + count('heartbeat_fire', "WHERE jobName = 'heartbeat'"), + 1, + 'reconciliation sweep must restore a missing fire' + ); + assert.equal( + count('cron_run', "WHERE jobName = 'heartbeat'"), + 2, + 'sweep repair must record lost_fire' + ); + + // Lost fires participate in the normal consecutive-failure policy. + call('schedule_every', JSON.stringify('heartbeat'), '30', '1'); + call('drop_heartbeat_fire_for_test'); + await poll( + 'the lost-fire policy to disable heartbeat', + () => jobRow('heartbeat').enabled === false + ); + const lostFireDisabled = jobRow('heartbeat'); + assert.equal(lostFireDisabled.enabled, false); + assert.match( + String(lostFireDisabled.disabledReason), + /failed_1_consecutive_times:lost_fire/ + ); + assert.equal( + publicDisabledReason('heartbeat'), + 'lost_fire_threshold_reached', + 'public view must expose a safe lost-fire reason code' + ); + assert.equal(count('heartbeat_fire'), 0); + call('schedule_every', JSON.stringify('heartbeat'), '30', '0'); + + // Chain job fires on cadence and keeps the single-pending-fire invariant. + call( + 'schedule_report', + JSON.stringify('*/1 * * * * *'), + JSON.stringify('UTC'), + '0', + JSON.stringify('primary'), + '25' + ); + await poll( + 'at least two report fires', + () => count('tick_log', "WHERE jobName = 'report'") >= 2 + ); + const reportTicks = count('tick_log', "WHERE jobName = 'report'"); + assert.ok( + reportTicks >= 2, + `expected at least two report fires, got ${reportTicks}` + ); + assert.equal( + count('report_fire', "WHERE jobName = 'report'"), + 1, + 'chain job must keep exactly one pending fire' + ); + const report = jobRow('report'); + assert.equal(report.enabled, true); + // Fires keep landing between queries, so bound rather than equate. + assert.ok( + Number(report.fireCount) >= reportTicks, + `fireCount ${report.fireCount} must cover observed ticks ${reportTicks}` + ); + const reportArgs = sql( + "SELECT value, count FROM argument_log WHERE jobName = 'report'" + ); + assert.ok(reportArgs.length >= 2, 'report arguments must reach every fire'); + assert.ok( + reportArgs.every( + ([value, batchSize]) => value === 'primary' && batchSize === 25 + ), + 'report fires must receive the scheduled typed arguments' + ); + + const reportGeneration = BigInt(report.generation); + call( + 'schedule_report', + JSON.stringify('*/1 * * * * *'), + JSON.stringify('UTC'), + '0', + JSON.stringify('replacement'), + '7' + ); + assert.equal( + BigInt(jobRow('report').generation), + reportGeneration + 1n, + 'rescheduling typed work must start a new generation' + ); + await poll( + 'the replacement report arguments', + () => + count( + 'argument_log', + "WHERE jobName = 'report' AND value = 'replacement' AND count = 7" + ) >= 1 + ); + assert.ok( + count( + 'argument_log', + "WHERE jobName = 'report' AND value = 'replacement' AND count = 7" + ) >= 1, + 'rescheduling must replace the durable arguments' + ); + + // A failed payload rolls back its writes. Volatile recovery rearms the + // calendar chain, records the failure, and disables at the threshold. + call( + 'schedule_cron', + JSON.stringify('flaky'), + JSON.stringify('*/1 * * * * *'), + JSON.stringify('UTC'), + '2' + ); + call('set_flaky_failing', 'true'); + await poll('the flaky job to reach its failure threshold', () => { + const state = jobRow('flaky'); + return !state.enabled && Number(state.consecutiveFailures) >= 2; + }); + assert.equal( + count('tick_log', "WHERE jobName = 'flaky'"), + 0, + 'failed payload writes must roll back' + ); + const flaky = jobRow('flaky'); + assert.equal(flaky.enabled, false, 'flaky must auto-disable'); + assert.equal(Number(flaky.consecutiveFailures), 2); + assert.match( + String(flaky.disabledReason), + /failed_2_consecutive_times:flaky\.failure/ + ); + assert.equal( + publicDisabledReason('flaky'), + 'failure_threshold_reached', + 'public view must not expose handler errors' + ); + assert.equal( + count('flaky_fire', "WHERE jobName = 'flaky'"), + 0, + 'auto-disabled job must have no pending fire' + ); + assert.equal( + count('cron_run', "WHERE jobName = 'flaky'"), + 2, + 'each failed invocation must have one durable run record' + ); + + // Native interval rows persist after a failed transaction. The explicit + // recovery payload must still record the failure and apply maxFailures. + const failuresBeforeInterval = count('cron_run', "WHERE jobName = 'flaky'"); + call('schedule_every', JSON.stringify('flaky'), '1', '1'); + await poll('the failed interval job to disable itself', () => { + const state = jobRow('flaky'); + return !state.enabled && Number(state.consecutiveFailures) >= 1; + }); + assert.equal( + count('cron_run', "WHERE jobName = 'flaky'"), + failuresBeforeInterval + 1, + 'interval recovery must commit one failed run record' + ); + assert.equal( + count('flaky_fire', "WHERE jobName = 'flaky'"), + 0, + 'an interval job disabled by maxFailures must remove its persistent fire' + ); + + // Recovery: fix the payload and reschedule; the chain resumes cleanly. + call('set_flaky_failing', 'false'); + call('schedule_every', JSON.stringify('flaky'), '1', '0'); + await poll( + 'the rescheduled flaky job to fire', + () => count('tick_log', "WHERE jobName = 'flaky'") >= 1 + ); + assert.ok( + count('tick_log', "WHERE jobName = 'flaky'") >= 1, + 'rescheduled job must fire again' + ); + assert.equal(jobRow('flaky').enabled, true); + + // Rescheduling creates a new generation so stale fire or recovery work cannot + // mutate the replacement schedule. + const recoveredGeneration = BigInt(jobRow('flaky').generation); + call('schedule_every', JSON.stringify('flaky'), '2', '0'); + assert.equal( + BigInt(jobRow('flaky').generation), + recoveredGeneration + 1n, + 'reschedule must increment the generation' + ); + assert.equal( + count('flaky_fire', "WHERE jobName = 'flaky'"), + 1, + 'reschedule must atomically replace the pending trigger' + ); + + // Procedure job: fires through the two-transaction middleware. + call( + 'schedule_probe', + JSON.stringify('*/1 * * * * *'), + JSON.stringify('UTC'), + '0', + JSON.stringify('health-check') + ); + await poll('the procedure job to fire with its arguments', () => { + return ( + count('tick_log', "WHERE jobName = 'probe'") >= 1 && + count( + 'argument_log', + "WHERE jobName = 'probe' AND value = 'health-check'" + ) >= 1 + ); + }); + assert.ok( + count('tick_log', "WHERE jobName = 'probe'") >= 1, + 'procedure job must fire' + ); + assert.ok( + count( + 'argument_log', + "WHERE jobName = 'probe' AND value = 'health-check'" + ) >= 1, + 'procedure job must receive its typed arguments' + ); + assert.equal(count('probe_fire', "WHERE jobName = 'probe'"), 1); + + // Unschedule disarms and disables without deleting state. + call('unschedule_job', JSON.stringify('probe')); + assert.equal( + count('probe_fire', "WHERE jobName = 'probe'"), + 0, + 'unschedule must disarm' + ); + assert.equal(jobRow('probe').enabled, false); + + // Procedure failures are recorded in a committed follow-up transaction and + // participate in the same automatic disable policy. + call('unschedule_job', JSON.stringify('flaky')); + call('set_flaky_failing', 'true'); + const successfulProbeTicks = count('tick_log', "WHERE jobName = 'probe'"); + call( + 'schedule_probe', + JSON.stringify('*/1 * * * * *'), + JSON.stringify('UTC'), + '1', + JSON.stringify('failure-check') + ); + await poll( + 'the failed procedure to disable itself', + () => jobRow('probe').enabled === false + ); + const failedProbe = jobRow('probe'); + assert.equal( + failedProbe.enabled, + false, + 'failed procedure must auto-disable' + ); + assert.equal(Number(failedProbe.consecutiveFailures), 1); + assert.match(String(failedProbe.disabledReason), /probe\.failure/); + assert.equal( + count('tick_log', "WHERE jobName = 'probe'"), + successfulProbeTicks, + 'failed procedure must not report successful application work' + ); + call('set_flaky_failing', 'false'); + + // History stays capped (default 5 per job) despite many report fires. + const reportFireCountBeforeHistoryCheck = Number(jobRow('report').fireCount); + await poll( + 'additional report fires for history pruning', + () => + Number(jobRow('report').fireCount) >= + reportFireCountBeforeHistoryCheck + 2 + ); + assert.ok( + count('cron_run', "WHERE jobName = 'report'") <= 5, + 'completed history must stay bounded' + ); + + // Validation rejections surface as failed calls before any row changes. + callExpectFailure( + 'schedule_cron', + JSON.stringify('report'), + JSON.stringify('not a cron'), + JSON.stringify('UTC'), + '0' + ); + callExpectFailure( + 'schedule_cron', + JSON.stringify('report'), + JSON.stringify('* * * * *'), + JSON.stringify('Mars/Olympus'), + '0' + ); + callExpectFailure('schedule_every', JSON.stringify('report'), '0', '0'); + callExpectFailure('schedule_every', JSON.stringify('nope'), '5', '0'); + + // Scheduled job reducers reject direct client calls. + callExpectFailure('forge_report_fire_for_test'); + + // The example module publishes and seeds its declared jobs. + run([ + 'publish', + ...serverArgs, + '--yes', + '--module-path', + 'example/spacetimedb', + exampleDatabase, + ]); + examplePublished = true; + assert.equal( + Number( + sql('SELECT COUNT(*) AS count FROM cron_job', exampleDatabase)[0][0] + ), + 2, + 'example init must seed digest and cleanup' + ); + + console.log('cron module local test passed'); +} finally { + if (published) { + run(['delete', ...serverArgs, '--yes', database]); + } + if (examplePublished) { + run(['delete', ...serverArgs, '--yes', exampleDatabase]); + } +} diff --git a/spacetime-cron-ts/scripts/test-recovery.mjs b/spacetime-cron-ts/scripts/test-recovery.mjs new file mode 100644 index 00000000000..72d3a550790 --- /dev/null +++ b/spacetime-cron-ts/scripts/test-recovery.mjs @@ -0,0 +1,322 @@ +// Crash-recovery integration test for @spacetimedb/cron. Runs an isolated +// SpacetimeDB instance so force-stopping it cannot disturb another server. The +// probe procedure remains in flight while the host is killed. The procedure's +// first transaction must preserve the calendar chain before the interruption. +// Procedures run in a pool of instances, so later occurrences can execute while +// the probe blocks. The two-second schedule leaves time for the pre-kill checks +// and the kill before the next occurrence. +import * as assert from 'node:assert/strict'; +import { spawn, spawnSync } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdtemp, rm } from 'node:fs/promises'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = fileURLToPath(new URL('..', import.meta.url)); +const dataDir = await mkdtemp(path.join(os.tmpdir(), 'cron-recovery-')); +const port = await reservePort(); +const serverUrl = `http://127.0.0.1:${port}`; +const database = 'cron-recovery'; +const serverLogs = []; +let server; + +function wait(milliseconds) { + return new Promise(resolve => setTimeout(resolve, milliseconds)); +} + +async function reservePort() { + const listener = net.createServer(); + listener.unref(); + await new Promise((resolve, reject) => { + listener.once('error', reject); + listener.listen(0, '127.0.0.1', resolve); + }); + const address = listener.address(); + assert.ok(address && typeof address === 'object'); + const selected = address.port; + await new Promise((resolve, reject) => + listener.close(error => (error ? reject(error) : resolve())) + ); + return selected; +} + +function run(args) { + const result = spawnSync('spacetime', args, { + cwd: root, + encoding: 'utf8', + shell: false, + windowsHide: true, + }); + assert.ifError(result.error); + assert.equal( + result.status, + 0, + `command failed: spacetime ${args.join(' ')}\n${result.stdout}\n${result.stderr}` + ); + return result; +} + +function call(name, ...args) { + return run(['call', '--server', serverUrl, database, name, ...args]); +} + +function sql(query) { + const result = run([ + 'sql', + '--server', + serverUrl, + '--format', + 'json', + database, + query, + ]); + return JSON.parse(result.stdout)[0].rows; +} + +function statusTag(value) { + const tags = ['Ok', 'Failed']; + assert.ok(Array.isArray(value), `unexpected status encoding: ${value}`); + const tag = tags[value[0]]; + assert.ok(tag, `unknown status variant: ${value[0]}`); + return tag; +} + +function timestampMillis(value) { + return Number(BigInt(value[0]) / 1000n); +} + +function runs() { + return sql( + "SELECT invocationId, sequence, scheduledFor, completedAt, status FROM cron_run WHERE jobName = 'recovery_probe'" + ).map(([invocationId, sequence, scheduledFor, completedAt, status]) => ({ + invocationId, + sequence: BigInt(sequence), + scheduledFor: timestampMillis(scheduledFor), + completedAt: timestampMillis(completedAt), + status: statusTag(status), + })); +} + +function job() { + const rows = sql( + "SELECT enabled, fireCount, consecutiveFailures FROM cron_job WHERE name = 'recovery_probe'" + ); + assert.equal(rows.length, 1, 'expected the recovery probe job'); + const [enabled, fireCount, consecutiveFailures] = rows[0]; + return { + enabled, + fireCount: BigInt(fireCount), + consecutiveFailures: Number(consecutiveFailures), + }; +} + +function blockingInvocationId() { + const rows = sql( + 'SELECT invocationId FROM recovery_probe_state WHERE singleton = true' + ); + return rows[0]?.[0]; +} + +async function poll(description, check, timeoutMilliseconds = 30_000) { + const deadline = Date.now() + timeoutMilliseconds; + let lastError; + while (Date.now() < deadline) { + try { + const result = await check(); + if (result) return result; + lastError = undefined; + } catch (error) { + lastError = error; + } + await wait(200); + } + const detail = lastError instanceof Error ? `: ${lastError.message}` : ''; + throw new Error(`timed out waiting for ${description}${detail}`); +} + +function startServer() { + const child = spawn( + 'spacetime', + [ + 'start', + '--listen-addr', + `127.0.0.1:${port}`, + '--data-dir', + dataDir, + '--non-interactive', + ], + { + cwd: root, + shell: false, + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'], + } + ); + let output = ''; + const capture = chunk => { + output = `${output}${chunk}`.slice(-20_000); + }; + child.stdout.on('data', capture); + child.stderr.on('data', capture); + serverLogs.push(() => output); + return child; +} + +// A process killed by a signal reports signalCode and leaves exitCode null. +function hasExited(child) { + return child.exitCode !== null || child.signalCode !== null; +} + +async function waitForServer(child) { + await poll( + 'isolated SpacetimeDB server', + () => + new Promise(resolve => { + if (hasExited(child)) { + resolve(false); + return; + } + const socket = net.createConnection({ host: '127.0.0.1', port }); + socket.once('connect', () => { + socket.destroy(); + resolve(true); + }); + socket.once('error', () => resolve(false)); + socket.setTimeout(500, () => { + socket.destroy(); + resolve(false); + }); + }) + ); + if (hasExited(child)) { + throw new Error(`isolated server exited early\n${serverLogs.at(-1)?.()}`); + } +} + +async function stopServer(child) { + if (!child || hasExited(child)) return; + const exited = once(child, 'exit'); + if (process.platform === 'win32') { + spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { + encoding: 'utf8', + windowsHide: true, + }); + } else { + child.kill('SIGKILL'); + } + await Promise.race([exited, wait(5_000)]); + if (!hasExited(child)) { + throw new Error(`failed to stop isolated server process ${child.pid}`); + } +} + +try { + server = startServer(); + await waitForServer(server); + run([ + 'publish', + '--server', + serverUrl, + '--yes', + '--module-path', + 'spacetimedb', + database, + ]); + + call( + 'schedule_cron', + JSON.stringify('recovery_probe'), + JSON.stringify('*/2 * * * * *'), + JSON.stringify('UTC'), + '0' + ); + const blockedInvocation = await poll( + 'the recovery probe to enter its blocking section', + blockingInvocationId + ); + assert.match(blockedInvocation, /^recovery_probe:[0-9]+:1$/); + assert.equal( + job().fireCount, + 1n, + 'the first transaction must reserve exactly one invocation before blocking' + ); + assert.equal( + runs().some(run => run.sequence === 1n), + false, + 'the blocked invocation must not have a completed outcome' + ); + assert.equal( + Number( + sql( + "SELECT COUNT(*) AS count FROM tick_log WHERE jobName = 'recovery_probe'" + )[0][0] + ), + 0, + 'the blocked handler must not record completed application work' + ); + assert.equal( + Number( + sql( + "SELECT COUNT(*) AS count FROM recovery_probe_fire WHERE jobName = 'recovery_probe'" + )[0][0] + ), + 1, + 'the first transaction must persist the successor before blocking' + ); + + await stopServer(server); + server = undefined; + const stoppedAt = Date.now(); + + // Leave several calendar occurrences behind us. Recovery should execute at + // most one overdue occurrence before resuming from the current time. + await wait(5_000); + + server = startServer(); + await waitForServer(server); + const restartedAt = Date.now(); + await poll('a successful post-restart recovery probe', () => { + const recovered = runs().some( + run => run.completedAt >= restartedAt && run.status === 'Ok' + ); + const state = job(); + return recovered && state.enabled && state.consecutiveFailures === 0; + }); + await wait(500); + const overdue = runs().filter( + run => run.completedAt >= stoppedAt && run.scheduledFor < restartedAt + ); + assert.ok( + overdue.length <= 1, + `calendar recovery must not replay every occurrence missed during downtime: ${overdue + .map(run => run.invocationId) + .join(', ')}` + ); + assert.equal( + Number( + sql( + "SELECT COUNT(*) AS count FROM recovery_probe_fire WHERE jobName = 'recovery_probe'" + )[0][0] + ), + 1, + 'the recovered calendar job must retain one successor trigger' + ); + + console.log('cron crash-recovery test passed'); +} catch (error) { + const logs = serverLogs.map( + (read, index) => `server ${index + 1}:\n${read()}` + ); + if (logs.length > 0) console.error(logs.join('\n')); + throw error; +} finally { + await stopServer(server); + await rm(dataDir, { + recursive: true, + force: true, + maxRetries: 5, + retryDelay: 200, + }); +} diff --git a/spacetime-cron-ts/scripts/test-registration.ts b/spacetime-cron-ts/scripts/test-registration.ts new file mode 100644 index 00000000000..1f554755447 --- /dev/null +++ b/spacetime-cron-ts/scripts/test-registration.ts @@ -0,0 +1,147 @@ +import * as assert from 'node:assert/strict'; +import { schema } from 'spacetimedb/server'; +import { client, cronTable, publicDisabledReason } from '../src/cron'; +import { errors, internalErrors } from '../src/errors'; + +const expectCode = (code: string) => ({ + message: new RegExp(`^${code}(:|$)`), +}); + +{ + const job = cronTable({ name: 'owned' }); + const other = cronTable({ name: 'other' }); + const cron = client({ jobs: [job] }); + client({ jobs: [other] }); + assert.throws( + () => cron.unschedule({} as never, other), + expectCode(internalErrors.foreignJobHandle) + ); + assert.throws( + () => client({ jobs: [{ jobName: 'plain' }] }), + expectCode(internalErrors.foreignJobHandle) + ); +} + +assert.throws(() => client({ jobs: [] }), expectCode(internalErrors.noJobs)); + +{ + const job = cronTable({ name: 'duplicate' }); + assert.throws(() => client({ jobs: [job, job] }), { + message: /^cron\.duplicate_job:duplicate$/, + }); +} + +{ + const job = cronTable({ name: 'wired_once' }); + client({ jobs: [job] }); + assert.throws(() => client({ jobs: [job] }), { + message: /^cron\.job_already_wired:wired_once$/, + }); +} + +{ + const job = cronTable({ name: 'not_wired' }); + const other = client({ jobs: [cronTable({ name: 'other_client' })] }); + const spacetimedb = schema({ ...other.tables }); + assert.throws(() => job.cronReducer(spacetimedb, () => {}), { + message: /^cron\.not_wired:not_wired:/, + }); +} + +{ + const job = cronTable({ name: 'missing_handler' }); + const cron = client({ jobs: [job], reconcileEverySeconds: 60 }); + const spacetimedb = schema({ ...cron.tables }); + assert.throws(() => cron.reconcileReducer(spacetimedb), { + message: /^cron\.missing_handlers:missing_handler$/, + }); +} + +{ + const job = cronTable({ name: 'unscheduled_handler' }); + const cron = client({ jobs: [job] }); + assert.throws(() => cron.schedule({} as never, job, { everySeconds: 60 }), { + message: /^cron\.missing_handlers:unscheduled_handler$/, + }); +} + +{ + const job = cronTable({ name: 'duplicate_handler' }); + const cron = client({ jobs: [job] }); + const spacetimedb = schema({ ...cron.tables }); + job.cronReducer(spacetimedb, () => {}); + assert.throws(() => job.cronProcedure(spacetimedb, () => {}), { + message: /^cron\.handler_already_registered:duplicate_handler:reducer$/, + }); +} + +{ + const job = cronTable({ name: 'no_reconciler' }); + const cron = client({ jobs: [job] }); + const spacetimedb = schema({ ...cron.tables }); + job.cronReducer(spacetimedb, () => {}); + assert.throws( + () => cron.reconcileReducer(spacetimedb), + expectCode(internalErrors.reconcileNotConfigured) + ); +} + +{ + const job = cronTable({ name: 'reconcile_once' }); + const cron = client({ jobs: [job], reconcileEverySeconds: 60 }); + const spacetimedb = schema({ ...cron.tables }); + job.cronReducer(spacetimedb, () => {}); + cron.reconcileReducer(spacetimedb); + assert.throws( + () => cron.reconcileReducer(spacetimedb), + expectCode(internalErrors.reconcileReducerAlreadyRegistered) + ); +} + +{ + const job = cronTable({ name: 'views_once' }); + const cron = client({ jobs: [job] }); + const spacetimedb = schema({ ...cron.tables }); + cron.publicViews(spacetimedb); + assert.throws( + () => cron.publicViews(spacetimedb), + expectCode(internalErrors.publicViewsAlreadyRegistered) + ); +} + +{ + const firstJob = cronTable({ name: 'first_job' }); + const secondJob = cronTable({ name: 'second_job' }); + const cron = client({ + jobs: [firstJob, secondJob], + reconcileEverySeconds: 60, + }); + assert.deepEqual(Object.keys(cron.tables).sort(), [ + 'cronJob', + 'cronReconcileTick', + 'cronRun', + 'firstJobFire', + 'secondJobFire', + ]); +} + +assert.deepEqual( + [ + 'failed_1_consecutive_times:secret application failure', + 'failed_1_consecutive_times:lost_fire', + `${errors.invalidScheduleState}:secret parser detail`, + 'disabled_by_operator', + 'unrecognized private detail', + undefined, + ].map(publicDisabledReason), + [ + 'failure_threshold_reached', + 'lost_fire_threshold_reached', + 'invalid_schedule_state', + 'disabled_by_operator', + 'disabled', + undefined, + ] +); + +process.stdout.write('cron registration tests passed\n'); diff --git a/spacetime-cron-ts/scripts/test-schedule.ts b/spacetime-cron-ts/scripts/test-schedule.ts new file mode 100644 index 00000000000..cbd4e4f0786 --- /dev/null +++ b/spacetime-cron-ts/scripts/test-schedule.ts @@ -0,0 +1,199 @@ +// Unit tests for calendar occurrence computation. +// Run: pnpm test:schedule +import { + parseCronExpression, + nextFireAfter, + isValidTimezone, +} from '../src/parser'; + +let failures = 0; +function check(name: string, cond: boolean, detail?: string) { + if (cond) { + console.log(`ok ${name}`); + } else { + failures++; + console.error(`FAIL ${name}${detail ? `: ${detail}` : ''}`); + } +} + +const MICROS = 1000n; +function utcMicros( + y: number, + mo: number, + d: number, + h = 0, + mi = 0, + s = 0 +): bigint { + return BigInt(Date.UTC(y, mo - 1, d, h, mi, s)) * MICROS; +} +function fmt(micros: bigint | undefined, tz = 'UTC'): string { + if (micros === undefined) return 'undefined'; + return new Date(Number(micros / MICROS)).toLocaleString('en-US', { + timeZone: tz, + hour12: false, + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + }); +} + +// 1. Basic calendar step: next minute boundary, strictly after `now`. +{ + const parsed = parseCronExpression('* * * * *'); + const now = utcMicros(2026, 8, 12, 10, 0, 30); // 10:00:30 + const next = nextFireAfter(parsed, now, 'UTC'); + check( + 'next-minute boundary', + next === utcMicros(2026, 8, 12, 10, 1, 0), + fmt(next) + ); +} + +// 2. Strictly-after semantics: asking at an exact occurrence must return the NEXT one. +{ + const parsed = parseCronExpression('* * * * *'); + const now = utcMicros(2026, 8, 12, 10, 1, 0); // exactly on an occurrence + const next = nextFireAfter(parsed, now, 'UTC'); + check( + 'strictly-after at exact occurrence', + next === utcMicros(2026, 8, 12, 10, 2, 0), + fmt(next) + ); +} + +// 3. Seconds granularity (6-field cron, used by the integration test). +{ + const parsed = parseCronExpression('*/2 * * * * *'); + const now = utcMicros(2026, 8, 12, 10, 0, 1); + const next = nextFireAfter(parsed, now, 'UTC'); + check( + 'seconds-granularity */2', + next === utcMicros(2026, 8, 12, 10, 0, 2), + fmt(next) + ); +} + +// 4. Timezone correctness: 09:00 America/New_York in August = 13:00 UTC (EDT, UTC-4). +{ + const parsed = parseCronExpression('0 9 * * *'); + const now = utcMicros(2026, 8, 12, 0, 0, 0); + const next = nextFireAfter(parsed, now, 'America/New_York'); + check('tz offset EDT', next === utcMicros(2026, 8, 12, 13, 0, 0), fmt(next)); +} + +// 5. DST spring-forward: 2026-03-08 02:30 does not exist in America/New_York. +// The job must not be lost and must not fire twice; document what it does. +{ + const parsed = parseCronExpression('30 2 * * *'); + const start = utcMicros(2026, 3, 7, 12, 0, 0); + const a = nextFireAfter(parsed, start, 'America/New_York'); + const b = + a !== undefined ? nextFireAfter(parsed, a, 'America/New_York') : undefined; + const c = + b !== undefined ? nextFireAfter(parsed, b, 'America/New_York') : undefined; + // Starting after noon on March 7 makes the first result the March 8 slot. + check( + 'spring-forward: occurrence exists', + a !== undefined && b !== undefined && c !== undefined + ); + check( + 'spring-forward: monotonic chain', + a !== undefined && b !== undefined && c !== undefined && a < b && b < c, + `${fmt(a, 'America/New_York')} | ${fmt(b, 'America/New_York')} | ${fmt(c, 'America/New_York')}` + ); + console.log( + ` info: 02:30 chain around spring-forward fires at: ${fmt(a, 'America/New_York')}, ${fmt(b, 'America/New_York')}, ${fmt(c, 'America/New_York')} (local NY time)` + ); +} + +// 6. DST fall-back: 2026-11-01 01:30 occurs twice in America/New_York. +// The chain must fire exactly once per calendar day, not twice. +{ + const parsed = parseCronExpression('30 1 * * *'); + const start = utcMicros(2026, 10, 31, 12, 0, 0); + const fires: bigint[] = []; + let cursor: bigint | undefined = start; + for (let i = 0; i < 3 && cursor !== undefined; i++) { + cursor = nextFireAfter(parsed, cursor, 'America/New_York'); + if (cursor !== undefined) fires.push(cursor); + } + const days = fires.map(f => + new Date(Number(f / MICROS)).toLocaleDateString('en-US', { + timeZone: 'America/New_York', + }) + ); + check( + 'fall-back: one fire per day', + new Set(days).size === days.length, + fires.map(f => fmt(f, 'America/New_York')).join(' | ') + ); + console.log( + ` info: 01:30 chain around fall-back fires at: ${fires.map(f => fmt(f, 'America/New_York')).join(', ')} (local NY time)` + ); +} + +// 7a. Statically impossible expressions are rejected at PARSE time (finding: +// cron-parser refuses Feb 30 outright, so create_job's validateSchedule +// catches these as invalid_expression before any row exists). +{ + let threw = false; + try { + parseCronExpression('0 0 30 2 *'); + } catch { + threw = true; + } + check('impossible Feb 30 rejected at parse', threw); +} + +// 7b. nextFireAfter -> undefined is still reachable at JS date bounds, so the +// fire reducer's disable-loudly path has a real (if exotic) trigger. +{ + const parsed = parseCronExpression('0 0 1 1 *'); + const nearMax = 8_640_000_000_000_000n * 1000n - 1_000_000n; // ~max JS date, in micros + const next = nextFireAfter(parsed, nearMax, 'UTC'); + check('date-bound overflow -> undefined', next === undefined, fmt(next)); +} + +// 8. Chain-step simulation: late fire does not drift the schedule. +// Job '0 * * * *' (hourly). Fire lands 7 minutes late; next must still be the +// top of the NEXT hour, not lateFire+1h. +{ + const parsed = parseCronExpression('0 * * * *'); + const lateFire = utcMicros(2026, 8, 12, 9, 7, 0); // fired late at 09:07 + const next = nextFireAfter(parsed, lateFire, 'UTC'); + check( + 'late fire re-arms nominal slot', + next === utcMicros(2026, 8, 12, 10, 0, 0), + fmt(next) + ); +} + +// 9. Catch-up semantics: an armed fire far in the past re-arms to the next FUTURE +// occurrence, skipping intermediate ones. This is one catch-up run. +{ + const parsed = parseCronExpression('*/5 * * * *'); + const wokeUpAt = utcMicros(2026, 8, 12, 11, 3, 0); // was down for hours + const next = nextFireAfter(parsed, wokeUpAt, 'UTC'); + check( + 'catch-up skips missed occurrences', + next === utcMicros(2026, 8, 12, 11, 5, 0), + fmt(next) + ); +} + +// 10. Timezone validation. +{ + check('valid tz', isValidTimezone('America/New_York')); + check('invalid tz rejected', !isValidTimezone('Mars/Olympus_Mons')); +} + +console.log( + failures === 0 + ? '\nAll schedule tests passed.' + : `\n${failures} test(s) FAILED.` +); +process.exit(failures === 0 ? 0 : 1); diff --git a/spacetime-cron-ts/scripts/test-types.ts b/spacetime-cron-ts/scripts/test-types.ts new file mode 100644 index 00000000000..210248f9f65 --- /dev/null +++ b/spacetime-cron-ts/scripts/test-types.ts @@ -0,0 +1,78 @@ +// Compile-time API coverage. This file is checked by `pnpm typecheck`. +import { schema, t, table } from 'spacetimedb/server'; +import { + client, + cronTable, + type CronInvocation, + type CronJobReference, +} from '../src/index'; + +const heartbeat = cronTable({ name: 'heartbeat' }); +const report = cronTable({ + name: 'report', + args: t.object('TypeTestReportArgs', { + tenantId: t.u64(), + batchSize: t.u32(), + }), +}); +const cron = client({ + jobs: [heartbeat, report], + reconcileEverySeconds: 300, +}); +const log = table({ name: 'log' }, { id: t.u64().primaryKey() }); +const spacetimedb = schema({ ...cron.tables, log }); + +export const beat = heartbeat.cronReducer(spacetimedb, (ctx, invocation) => { + ctx.db.log.insert({ id: invocation.sequence }); + ctx.db.heartbeatFire.jobName.find('heartbeat'); + const checked: CronInvocation = invocation; + void checked; +}); + +export const runReport = report.cronProcedure( + spacetimedb, + (ctx, args, invocation) => { + const tenantId: bigint = args.tenantId; + const batchSize: number = args.batchSize; + ctx.withTx(tx => tx.db.log.insert({ id: tenantId })); + void batchSize; + void invocation; + } +); + +export const init = spacetimedb.init(ctx => { + cron.schedule(ctx, heartbeat, { everySeconds: 30 }); + cron.schedule(ctx, heartbeat, '0 * * * *', { timezone: 'UTC' }); + cron.schedule(ctx, report, '0 9 * * *', { + timezone: 'UTC', + args: { tenantId: 42n, batchSize: 100 }, + }); + + // @ts-expect-error Argument-bearing jobs require scheduling options with args. + cron.schedule(ctx, report, '0 9 * * *'); + // @ts-expect-error Argument-bearing jobs require an args property. + cron.schedule(ctx, report, '0 9 * * *', { timezone: 'UTC' }); + cron.schedule(ctx, report, '0 9 * * *', { + // @ts-expect-error tenantId is a u64 and therefore a bigint. + args: { tenantId: 42, batchSize: 100 }, + }); + cron.schedule( + ctx, + heartbeat, + { everySeconds: 30 }, + { + // @ts-expect-error Argumentless jobs do not accept an args property. + args: {}, + } + ); + + const reference: CronJobReference = report; + cron.unschedule(ctx, reference); +}); + +export const cronReconcile = cron.reconcileReducer(spacetimedb); +export const { jobs: cronJobs } = cron.publicViews(spacetimedb); + +// A schema without the cron tables cannot register cron handlers. +// @ts-expect-error The host schema must include cron.tables. +heartbeat.cronReducer(schema({ log }), () => {}); diff --git a/spacetime-cron-ts/scripts/test-validation.ts b/spacetime-cron-ts/scripts/test-validation.ts new file mode 100644 index 00000000000..549497ea7fc --- /dev/null +++ b/spacetime-cron-ts/scripts/test-validation.ts @@ -0,0 +1,97 @@ +import * as assert from 'node:assert/strict'; +import { + boundedScheduleTime, + CHECKPOINT_DELAY_MICROS, + MAX_ERROR_LENGTH, + MAX_FAILURES, + MAX_HISTORY_CAP, + MAX_INTERVAL_SECONDS, + normalizeHistoryCap, + normalizeJobArgs, + normalizeJobName, + normalizeMaxFailures, + normalizeReconcileEverySeconds, + normalizeSchedule, + truncateError, +} from '../src/schedule'; + +const utcMicros = (iso: string) => BigInt(Date.parse(iso)) * 1_000n; + +assert.equal(normalizeJobName('daily_report'), 'daily_report'); +for (const invalid of [ + '', + 'DailyReport', + 'daily-report', + '_daily', + 'daily__report', +]) { + assert.throws(() => normalizeJobName(invalid), /cron\.invalid_job_name/); +} +assert.throws(() => normalizeJobName(`a${'b'.repeat(48)}`), /invalid_job_name/); + +const now = utcMicros('2028-03-01T00:00:00.000Z'); +for (const everySeconds of [0, -1, 1.5, MAX_INTERVAL_SECONDS + 1]) { + assert.throws( + () => normalizeSchedule({ everySeconds }, undefined, now), + /cron\.invalid_interval/ + ); +} +assert.equal( + normalizeSchedule({ everySeconds: 30 }, undefined, now).firstAt, + now + 30_000_000n +); + +for (const maxFailures of [-1, 1.5, MAX_FAILURES + 1]) { + assert.throws( + () => normalizeMaxFailures(maxFailures), + /invalid_max_failures/ + ); +} +assert.equal(normalizeMaxFailures(undefined), 0); +assert.equal(normalizeMaxFailures(MAX_FAILURES), MAX_FAILURES); + +assert.deepEqual(normalizeJobArgs('heartbeat', false, undefined), {}); +assert.deepEqual( + normalizeJobArgs('report', true, { args: { tenantId: 42n } }), + { tenantId: 42n } +); +assert.equal( + normalizeJobArgs('optional', true, { args: undefined }), + undefined +); +assert.throws( + () => normalizeJobArgs('report', true, undefined), + /cron\.missing_args:report/ +); +assert.throws( + () => normalizeJobArgs('heartbeat', false, { args: {} }), + /cron\.unexpected_args:heartbeat/ +); + +for (const historyCap of [-1, 1.5, MAX_HISTORY_CAP + 1]) { + assert.throws(() => normalizeHistoryCap(historyCap), /invalid_history_cap/); +} +assert.equal(normalizeHistoryCap(undefined), 5); + +for (const seconds of [0, -1, 1.5, MAX_INTERVAL_SECONDS + 1]) { + assert.throws( + () => normalizeReconcileEverySeconds(seconds), + /invalid_reconcile_interval/ + ); +} +assert.equal(normalizeReconcileEverySeconds(undefined), undefined); +assert.equal(normalizeReconcileEverySeconds(300), 300); + +const leapDay = normalizeSchedule('0 0 29 2 *', { timezone: 'UTC' }, now); +assert.ok(leapDay.firstAt !== undefined); +assert.ok(leapDay.firstAt - now > CHECKPOINT_DELAY_MICROS); +assert.equal( + boundedScheduleTime(now, leapDay.firstAt), + now + CHECKPOINT_DELAY_MICROS +); + +const longError = 'x'.repeat(MAX_ERROR_LENGTH + 100); +assert.equal(truncateError(longError).length, MAX_ERROR_LENGTH); +assert.match(truncateError(longError), /\.\.\.$/); + +console.log('cron validation tests passed'); diff --git a/spacetime-cron-ts/spacetimedb/.npmrc b/spacetime-cron-ts/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-cron-ts/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-cron-ts/spacetimedb/package.json b/spacetime-cron-ts/spacetimedb/package.json new file mode 100644 index 00000000000..d7d8053aa05 --- /dev/null +++ b/spacetime-cron-ts/spacetimedb/package.json @@ -0,0 +1,19 @@ +{ + "name": "spacetime-cron-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-cron", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-cron" + }, + "dependencies": { + "@spacetimedb/cron": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-cron-ts/spacetimedb/src/index.ts b/spacetime-cron-ts/spacetimedb/src/index.ts new file mode 100644 index 00000000000..facc80abeb5 --- /dev/null +++ b/spacetime-cron-ts/spacetimedb/src/index.ts @@ -0,0 +1,293 @@ +import { schema, table, t, SenderError } from 'spacetimedb/server'; +import { + client, + cronTable, + type CronJobHandle, + type CronJobReference, +} from '@spacetimedb/cron'; + +const heartbeat = cronTable({ name: 'heartbeat' }); +const report = cronTable({ + name: 'report', + args: t.object('ReportCronArgs', { + label: t.string(), + batchSize: t.u32(), + }), +}); +const flaky = cronTable({ name: 'flaky' }); +const probe = cronTable({ + name: 'probe', + args: t.object('ProbeCronArgs', { source: t.string() }), +}); +const recoveryProbe = cronTable({ name: 'recovery_probe' }); + +const cron = client({ + jobs: [heartbeat, report, flaky, probe, recoveryProbe], + publicTables: true, + reconcileEverySeconds: 2, +}); + +const tickLog = table( + { name: 'tick_log', public: true }, + { + id: t.u64().primaryKey().autoInc(), + jobName: t.string().index(), + at: t.timestamp(), + } +); + +const flakyState = table( + { name: 'flaky_state', public: true }, + { + singleton: t.bool().primaryKey(), + failing: t.bool(), + } +); + +const argumentLog = table( + { name: 'argument_log', public: true }, + { + id: t.u64().primaryKey().autoInc(), + jobName: t.string().index(), + value: t.string(), + count: t.u32(), + invocationId: t.string(), + } +); + +const recoveryProbeState = table( + { name: 'recovery_probe_state' }, + { + singleton: t.bool().primaryKey(), + invocationId: t.string(), + } +); + +const spacetimedb = schema({ + ...cron.tables, + tickLog, + flakyState, + argumentLog, + recoveryProbeState, +}); +export default spacetimedb; + +export const runHeartbeat = heartbeat.cronReducer(spacetimedb, ctx => { + ctx.db.tickLog.insert({ id: 0n, jobName: 'heartbeat', at: ctx.timestamp }); +}); + +export const runReport = report.cronReducer( + spacetimedb, + (ctx, args, invocation) => { + ctx.db.tickLog.insert({ id: 0n, jobName: 'report', at: ctx.timestamp }); + ctx.db.argumentLog.insert({ + id: 0n, + jobName: 'report', + value: args.label, + count: args.batchSize, + invocationId: invocation.id, + }); + } +); + +// Integration-only authorization probe. Direct calls must not execute a +// reducer that is reserved for the scheduler. +export const forgeReportFireForTest = spacetimedb.reducer(ctx => { + const fire = ctx.db.reportFire.jobName.find('report'); + if (!fire) throw new SenderError('test.missing_report_fire'); + runReport(ctx, { arg: fire }); +}); + +// Handler writes roll back on failure. Volatile recovery records the failure +// and restores calendar jobs after the scheduled transaction aborts. +export const runFlaky = flaky.cronReducer(spacetimedb, ctx => { + ctx.db.tickLog.insert({ id: 0n, jobName: 'flaky', at: ctx.timestamp }); + const state = ctx.db.flakyState.singleton.find(true); + if (state?.failing) throw new Error('flaky.failure'); +}); + +// Procedure job: the natural home for side-effecting work such as outbound +// HTTP. Here it writes through withTx so the local suite can observe it. +export const runProbe = probe.cronProcedure( + spacetimedb, + (ctx, args, invocation) => { + const failing = ctx.withTx( + tx => tx.db.flakyState.singleton.find(true)?.failing ?? false + ); + if (failing) throw new Error('probe.failure'); + ctx.withTx(tx => { + tx.db.tickLog.insert({ id: 0n, jobName: 'probe', at: tx.timestamp }); + tx.db.argumentLog.insert({ + id: 0n, + jobName: 'probe', + value: args.source, + count: 0, + invocationId: invocation.id, + }); + }); + } +); + +function blockUntilHostStops(): never { + for (;;) { + // The recovery test terminates the isolated host after observing its + // durable entry marker. V8 2.8 does not time out this execution path. + } +} + +// The first run remains in flight until the recovery test kills its isolated +// host. Its separate transactions prove what survives the interruption. +export const runRecoveryProbe = recoveryProbe.cronProcedure( + spacetimedb, + (ctx, run) => { + if (run.sequence === 1n) { + ctx.withTx(tx => { + tx.db.recoveryProbeState.insert({ + singleton: true, + invocationId: run.id, + }); + }); + blockUntilHostStops(); + } + ctx.withTx(tx => { + tx.db.tickLog.insert({ + id: 0n, + jobName: 'recovery_probe', + at: tx.timestamp, + }); + }); + } +); + +export const cronReconcile = cron.reconcileReducer(spacetimedb); +export const { jobs: cronJobs } = cron.publicViews(spacetimedb); + +export const init = spacetimedb.init(ctx => { + ctx.db.flakyState.insert({ singleton: true, failing: false }); + // Code-declared default for a fresh database. + cron.schedule(ctx, heartbeat, { everySeconds: 30 }); +}); + +// CLI-facing management over the library helpers. + +const argumentlessJobs: Record = { + heartbeat, + flaky, + recovery_probe: recoveryProbe, +}; + +const allJobs: Record = { + ...argumentlessJobs, + report, + probe, +}; + +function argumentlessJobByName(name: string): CronJobHandle { + const job = argumentlessJobs[name]; + if (!job) throw new SenderError(`test.unknown_job:${name}`); + return job; +} + +function jobByName(name: string): CronJobReference { + const job = allJobs[name]; + if (!job) throw new SenderError(`test.unknown_job:${name}`); + return job; +} + +function scheduleSafely(operation: () => void): void { + try { + operation(); + } catch (err) { + throw err instanceof SenderError + ? err + : new SenderError(err instanceof Error ? err.message : String(err)); + } +} + +export const scheduleCron = spacetimedb.reducer( + { + name: t.string(), + expression: t.string(), + timezone: t.string(), + maxFailures: t.u32(), + }, + (ctx, args) => { + scheduleSafely(() => { + cron.schedule(ctx, argumentlessJobByName(args.name), args.expression, { + timezone: args.timezone, + maxFailures: args.maxFailures, + }); + }); + } +); + +export const scheduleEvery = spacetimedb.reducer( + { name: t.string(), seconds: t.u32(), maxFailures: t.u32() }, + (ctx, args) => { + scheduleSafely(() => { + cron.schedule( + ctx, + argumentlessJobByName(args.name), + { everySeconds: args.seconds }, + { maxFailures: args.maxFailures } + ); + }); + } +); + +export const scheduleReport = spacetimedb.reducer( + { + expression: t.string(), + timezone: t.string(), + maxFailures: t.u32(), + label: t.string(), + batchSize: t.u32(), + }, + (ctx, args) => { + scheduleSafely(() => { + cron.schedule(ctx, report, args.expression, { + timezone: args.timezone, + maxFailures: args.maxFailures, + args: { label: args.label, batchSize: args.batchSize }, + }); + }); + } +); + +export const scheduleProbe = spacetimedb.reducer( + { + expression: t.string(), + timezone: t.string(), + maxFailures: t.u32(), + source: t.string(), + }, + (ctx, args) => { + scheduleSafely(() => { + cron.schedule(ctx, probe, args.expression, { + timezone: args.timezone, + maxFailures: args.maxFailures, + args: { source: args.source }, + }); + }); + } +); + +export const unscheduleJob = spacetimedb.reducer( + { name: t.string() }, + (ctx, { name }) => { + cron.unschedule(ctx, jobByName(name)); + } +); + +export const setFlakyFailing = spacetimedb.reducer( + { failing: t.bool() }, + (ctx, { failing }) => { + const state = ctx.db.flakyState.singleton.find(true); + if (state) ctx.db.flakyState.singleton.update({ ...state, failing }); + } +); + +// Integration-only fault injection for the lost-fire reconciler. +export const dropHeartbeatFireForTest = spacetimedb.reducer(ctx => { + ctx.db.heartbeatFire.jobName.delete('heartbeat'); +}); diff --git a/spacetime-cron-ts/spacetimedb/tsconfig.json b/spacetime-cron-ts/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..8d8f9b03455 --- /dev/null +++ b/spacetime-cron-ts/spacetimedb/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src"] +} diff --git a/spacetime-cron-ts/src/cron.ts b/spacetime-cron-ts/src/cron.ts new file mode 100644 index 00000000000..2865277631b --- /dev/null +++ b/spacetime-cron-ts/src/cron.ts @@ -0,0 +1,927 @@ +// eslint-disable-next-line @typescript-eslint/triple-slash-reference +/// +import { volatile_nonatomic_schedule_immediate } from 'spacetime:sys@2.0'; +import { BinaryWriter, Timestamp } from 'spacetimedb'; +import { + ScheduleAt, + SenderError, + t, + toCamelCase, + type Infer, + type VariantsObj, +} from 'spacetimedb/server'; +import { errors, internalErrors } from './errors.js'; +import { + boundedScheduleTime, + CronInputError, + MAX_FAILURES, + normalizeHistoryCap, + normalizeJobArgs, + normalizeJobName, + normalizeMaxFailures, + normalizeReconcileEverySeconds, + normalizeSchedule, + nextOccurrence, + ONE_SECOND_MICROS, + truncateError, +} from './schedule.js'; +import { + cronFireTable, + cronJobTable, + cronJobView, + cronReconcileTickTable, + cronRunTable, + type CronFireTable, + type CronFireTableDef, + type CronProcedureCtx, + type CronReconcileTickTableDef, + type CronTx, + type FireRow, + type JobRow, +} from './tables.js'; +import type { + CronArgsBuilder, + CronClient, + CronConfig, + CronInvocation, + CronJobHandle, + CronJobReference, + CronPublicViews, + CronSchema, + CronTableOpts, + CronTableWithArgsOpts, + CronTables, + ScheduleSpec, +} from './types.js'; + +const RECONCILE_REDUCER_NAME = 'cron_reconcile'; +const RECONCILE_TICK_KEY = 'cron'; + +const PUBLIC_DISABLED_REASONS = { + disabled: 'disabled', + disabledByOperator: 'disabled_by_operator', + failureThresholdReached: 'failure_threshold_reached', + invalidScheduleState: 'invalid_schedule_state', + lostFireThresholdReached: 'lost_fire_threshold_reached', +} as const; + +type RunStatus = 'Ok' | 'Failed'; + +export function publicDisabledReason( + reason: string | undefined +): string | undefined { + if (reason === undefined) return undefined; + if (reason === 'disabled_by_operator') { + return PUBLIC_DISABLED_REASONS.disabledByOperator; + } + if (reason.startsWith(`${errors.invalidScheduleState}:`)) { + return PUBLIC_DISABLED_REASONS.invalidScheduleState; + } + if (/^failed_[1-9][0-9]*_consecutive_times:lost_fire$/.test(reason)) { + return PUBLIC_DISABLED_REASONS.lostFireThresholdReached; + } + if (/^failed_[1-9][0-9]*_consecutive_times:/.test(reason)) { + return PUBLIC_DISABLED_REASONS.failureThresholdReached; + } + return PUBLIC_DISABLED_REASONS.disabled; +} + +type InternalHandler = (...args: unknown[]) => unknown; + +interface RuntimeScheduleOpts { + timezone?: string; + maxFailures?: number; + args?: unknown; +} + +interface JobMetadata { + readonly handle: CronJobReference; + readonly argsType: CronArgsBuilder; + readonly hasArgs: boolean; + readonly fireTableName: string; + readonly fireAccessor: string; + readonly reducerName: string; + fire: CronFireTableDef | undefined; + core: Core | undefined; + registration: 'reducer' | 'procedure' | undefined; +} + +interface Core { + readonly jobs: Map; + readonly historyCap: number; + readonly reconcileEverySeconds: number | undefined; + readonly reconcileTick: CronReconcileTickTableDef | undefined; + reconcileRegistered: boolean; + publicViewsRegistered: boolean; +} + +interface PreparedFire { + readonly invocation: CronInvocation; + readonly args: unknown; +} + +const metadata = new WeakMap(); + +function isThenable(value: unknown): value is PromiseLike { + return ( + (typeof value === 'object' || typeof value === 'function') && + value !== null && + 'then' in value && + typeof value.then === 'function' + ); +} + +function invocationId( + jobName: string, + generation: bigint, + sequence: bigint +): string { + return `${jobName}:${generation}:${sequence}`; +} + +function requireMetadata(job: CronJobReference): JobMetadata { + const value = metadata.get(job); + if (!value) throw new Error(internalErrors.foreignJobHandle); + return value; +} + +function requireCore(job: CronJobReference): Core { + const value = requireMetadata(job).core; + if (!value) { + throw new Error( + `${internalErrors.notWired}:${job.jobName}:pass the job to client() first` + ); + } + return value; +} + +function requireRegisteredHandlers(core: Core): void { + const missing = [...core.jobs.values()] + .filter(job => !job.registration) + .map(job => job.handle.jobName); + if (missing.length > 0) { + throw new Error(`${internalErrors.missingHandlers}:${missing.join(',')}`); + } +} + +function requireFire(job: JobMetadata): CronFireTableDef { + if (!job.fire) { + throw new Error( + `${internalErrors.notWired}:${job.handle.jobName}:pass the job to client() first` + ); + } + return job.fire; +} + +function requireDatabaseCaller( + ctx: Pick +): void { + if (!ctx.sender.isEqual(ctx.databaseIdentity)) { + throw new SenderError(errors.notAuthorized); + } +} + +function fireTable(ctx: CronTx, job: JobMetadata): CronFireTable { + const value = ctx.db[job.fireAccessor]; + if (!value) { + throw new Error( + `${internalErrors.missingTable}:${job.fireTableName}:spread cron.tables into schema()` + ); + } + // The accessor was derived from the fire table registered by client(). + return value as CronFireTable; +} + +function jobArgs(row: JobRow): unknown { + return 'value' in row.args ? row.args.value : undefined; +} + +function pruneHistory(ctx: CronTx, core: Core, jobName: string): void { + const rows = [...ctx.db.cronRun.jobName.filter(jobName)].sort( + (left, right) => + left.sequence < right.sequence + ? -1 + : left.sequence > right.sequence + ? 1 + : 0 + ); + const removeCount = Math.max(0, rows.length - core.historyCap); + for (const row of rows.slice(0, removeCount)) { + ctx.db.cronRun.delete(row); + } +} + +function recordRun( + ctx: CronTx, + core: Core, + invocation: CronInvocation, + status: RunStatus, + error: string | undefined +): void { + if (core.historyCap === 0) return; + if (ctx.db.cronRun.invocationId.find(invocation.id)) return; + ctx.db.cronRun.insert({ + invocationId: invocation.id, + jobName: invocation.jobName, + generation: invocation.generation, + sequence: invocation.sequence, + scheduledFor: invocation.scheduledFor, + completedAt: ctx.timestamp, + status: { tag: status }, + error, + }); + pruneHistory(ctx, core, invocation.jobName); +} + +function disarmFire(ctx: CronTx, job: JobMetadata): void { + const tableView = fireTable(ctx, job); + const pending = tableView.jobName.find(job.handle.jobName); + if (pending) tableView.delete(pending); +} + +function insertFire( + ctx: CronTx, + job: JobMetadata, + row: JobRow, + targetMicros: bigint | undefined +): Timestamp | undefined { + const tableView = fireTable(ctx, job); + if (row.schedule.tag === 'every') { + tableView.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.interval( + BigInt(row.schedule.value.seconds) * ONE_SECOND_MICROS + ), + jobName: row.name, + generation: row.generation, + targetAt: undefined, + recovery: undefined, + }); + return new Timestamp( + ctx.timestamp.microsSinceUnixEpoch + + BigInt(row.schedule.value.seconds) * ONE_SECOND_MICROS + ); + } + if (targetMicros === undefined) return undefined; + const targetAt = new Timestamp(targetMicros); + tableView.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.time( + boundedScheduleTime(ctx.timestamp.microsSinceUnixEpoch, targetMicros) + ), + jobName: row.name, + generation: row.generation, + targetAt, + recovery: undefined, + }); + return targetAt; +} + +function replaceFire(ctx: CronTx, job: JobMetadata, row: JobRow): JobRow { + disarmFire(ctx, job); + + let targetMicros: bigint | undefined; + if (row.schedule.tag === 'cron') { + try { + targetMicros = nextOccurrence( + row.schedule, + ctx.timestamp.microsSinceUnixEpoch + ); + } catch (error) { + return disableJob( + ctx, + job, + row, + `${errors.invalidScheduleState}:${truncateError(error)}` + ); + } + if (targetMicros === undefined) { + return disableJob(ctx, job, row, errors.noFutureOccurrence); + } + } + + const nextRunAt = insertFire(ctx, job, row, targetMicros); + const updated = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(updated); + return updated; +} + +function ensureReconcileTick(ctx: CronTx, core: Core): void { + const everySeconds = core.reconcileEverySeconds; + if (everySeconds === undefined) return; + if (!core.reconcileRegistered) { + throw new Error( + `${internalErrors.reconcileReducerNotRegistered}:export cron.reconcileReducer()` + ); + } + const tick = ctx.db.cronReconcileTick; + if (!tick) { + throw new Error( + `${internalErrors.missingTable}:cron_reconcile_tick:spread cron.tables into schema()` + ); + } + if (tick.key.find(RECONCILE_TICK_KEY)) return; + tick.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.interval(BigInt(everySeconds) * ONE_SECOND_MICROS), + key: RECONCILE_TICK_KEY, + }); +} + +function reconcileLostFires(ctx: CronTx, core: Core): void { + for (const job of core.jobs.values()) { + const row = ctx.db.cronJob.name.find(job.handle.jobName); + if (!row || !row.enabled) { + disarmFire(ctx, job); + continue; + } + if (row.args.tag !== job.handle.jobName) { + disableJob(ctx, job, row, errors.invalidArgsState); + continue; + } + + const pending = fireTable(ctx, job).jobName.find(row.name); + const validPending = + pending?.generation === row.generation && + pending.recovery === undefined && + (row.schedule.tag === 'cron' + ? pending.targetAt !== undefined + : pending.targetAt === undefined); + if (validPending) continue; + + const sequence = row.fireCount + 1n; + const invocation: CronInvocation = { + id: invocationId(row.name, row.generation, sequence), + jobName: row.name, + generation: row.generation, + sequence, + scheduledFor: row.nextRunAt ?? ctx.timestamp, + }; + replaceFire(ctx, job, row); + applyOutcome(ctx, core, job, invocation, 'Failed', 'lost_fire', true); + } +} + +function disableJob( + ctx: CronTx, + job: JobMetadata, + row: JobRow, + reason: string +): JobRow { + disarmFire(ctx, job); + const updated = { + ...row, + enabled: false, + nextRunAt: undefined, + disabledReason: truncateError(reason), + }; + ctx.db.cronJob.name.update(updated); + return updated; +} + +function applyOutcome( + ctx: CronTx, + core: Core, + job: JobMetadata, + invocation: CronInvocation, + status: RunStatus, + error: string | undefined, + advanceFireCount: boolean +): void { + if (ctx.db.cronRun.invocationId.find(invocation.id)) return; + + let row = ctx.db.cronJob.name.find(invocation.jobName); + if (row && row.generation === invocation.generation) { + if (advanceFireCount && invocation.sequence !== row.fireCount + 1n) { + return; + } + const consecutiveFailures = + status === 'Failed' + ? Math.min(row.consecutiveFailures + 1, MAX_FAILURES) + : 0; + row = { + ...row, + fireCount: + invocation.sequence > row.fireCount + ? invocation.sequence + : row.fireCount, + consecutiveFailures, + lastRunAt: ctx.timestamp, + }; + ctx.db.cronJob.name.update(row); + if ( + status === 'Failed' && + row.enabled && + row.maxFailures > 0 && + consecutiveFailures >= row.maxFailures + ) { + disableJob( + ctx, + job, + row, + `failed_${consecutiveFailures}_consecutive_times:${error ?? status}` + ); + } + } + + recordRun(ctx, core, invocation, status, error); +} + +function prepareFire( + ctx: CronTx, + job: JobMetadata, + arg: FireRow, + reserveSequence: boolean +): PreparedFire | undefined { + let row = ctx.db.cronJob.name.find(job.handle.jobName); + if (!row || !row.enabled || row.generation !== arg.generation) return; + if (row.args.tag !== job.handle.jobName) { + disableJob(ctx, job, row, errors.invalidArgsState); + return; + } + + const nowMicros = ctx.timestamp.microsSinceUnixEpoch; + let scheduledFor = ctx.timestamp; + if (row.schedule.tag === 'cron') { + if (!arg.targetAt) { + disableJob(ctx, job, row, `${errors.invalidTrigger}:missing_target`); + return; + } + const tableView = fireTable(ctx, job); + const fired = tableView.scheduledId.find(arg.scheduledId); + if (fired) tableView.delete(fired); + + const targetMicros = arg.targetAt.microsSinceUnixEpoch; + if (targetMicros > nowMicros) { + const nextRunAt = insertFire(ctx, job, row, targetMicros); + ctx.db.cronJob.name.update({ ...row, nextRunAt }); + return; + } + + scheduledFor = arg.targetAt; + const nextAt = nextOccurrence(row.schedule, nowMicros); + if (nextAt === undefined) { + row = disableJob(ctx, job, row, errors.noFutureOccurrence); + } else { + const nextRunAt = insertFire(ctx, job, row, nextAt); + row = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(row); + } + } else { + const nextRunAt = new Timestamp( + nowMicros + BigInt(row.schedule.value.seconds) * ONE_SECOND_MICROS + ); + row = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(row); + } + + const sequence = row.fireCount + 1n; + if (reserveSequence) { + row = { ...row, fireCount: sequence }; + ctx.db.cronJob.name.update(row); + } + return { + args: jobArgs(row), + invocation: { + id: invocationId(row.name, row.generation, sequence), + jobName: row.name, + generation: row.generation, + sequence, + scheduledFor, + }, + }; +} + +function invokeHandler( + handler: InternalHandler, + ctx: unknown, + job: JobMetadata, + prepared: PreparedFire +): unknown { + return job.hasArgs + ? handler(ctx, prepared.args, prepared.invocation) + : handler(ctx, prepared.invocation); +} + +function encodeFireArgument(job: JobMetadata, arg: FireRow): Uint8Array { + const writer = new BinaryWriter(256); + // A reducer with one row parameter has the same BSATN field sequence as + // the row itself. The SDK serializer keeps this encoding tied to the + // generated fire-table schema. + requireFire(job).rowType.serialize(writer, arg); + return writer.getBuffer(); +} + +function scheduleRecovery( + job: JobMetadata, + arg: FireRow, + invocation: CronInvocation, + error: string +): void { + const recoveryArg: FireRow = { + ...arg, + recovery: { + sequence: invocation.sequence, + scheduledFor: invocation.scheduledFor, + error, + }, + }; + volatile_nonatomic_schedule_immediate( + job.reducerName, + encodeFireArgument(job, recoveryArg) + ); +} + +function executeReducer( + ctx: CronTx, + core: Core, + job: JobMetadata, + arg: FireRow, + handler: InternalHandler +): void { + requireDatabaseCaller(ctx); + if (arg.recovery) { + recoverFailure(ctx, core, job, arg); + return; + } + const prepared = prepareFire(ctx, job, arg, false); + if (!prepared) return; + + try { + const result = invokeHandler(handler, ctx, job, prepared); + if (isThenable(result)) { + throw new Error( + `${internalErrors.asyncReducerHandler}:reducers must complete synchronously` + ); + } + } catch (error) { + const detail = truncateError(error); + try { + scheduleRecovery(job, arg, prepared.invocation, detail); + } catch { + // Volatile recovery is best effort. Reconciliation repairs a missing + // calendar fire if the host loses this request. + } + throw error; + } + + applyOutcome(ctx, core, job, prepared.invocation, 'Ok', undefined, true); +} + +function executeProcedure( + ctx: CronProcedureCtx, + core: Core, + job: JobMetadata, + arg: FireRow, + handler: InternalHandler +): void { + requireDatabaseCaller(ctx); + if (arg.recovery) { + throw new SenderError(internalErrors.invalidProcedureRecovery); + } + const prepared = ctx.withTx(tx => prepareFire(tx, job, arg, true)); + if (!prepared) return; + + let error: string | undefined; + try { + const result = invokeHandler(handler, ctx, job, prepared); + if (isThenable(result)) { + throw new Error( + `${internalErrors.asyncProcedureHandler}:procedures must complete synchronously` + ); + } + } catch (caught) { + error = truncateError(caught); + } + + ctx.withTx(tx => { + applyOutcome( + tx, + core, + job, + prepared.invocation, + error === undefined ? 'Ok' : 'Failed', + error, + false + ); + }); +} + +function recoverFailure( + ctx: CronTx, + core: Core, + job: JobMetadata, + arg: FireRow +): void { + const recovery = arg.recovery; + if (!recovery || arg.jobName !== job.handle.jobName) return; + const jobName = job.handle.jobName; + let row = ctx.db.cronJob.name.find(jobName); + if ( + !row || + !row.enabled || + row.generation !== arg.generation || + recovery.sequence !== row.fireCount + 1n + ) { + return; + } + + if (row.schedule.tag === 'cron') { + // Replace the fire unconditionally so stale visible state cannot block + // recovery. + row = replaceFire(ctx, job, row); + } else { + const nextRunAt = new Timestamp( + ctx.timestamp.microsSinceUnixEpoch + + BigInt(row.schedule.value.seconds) * ONE_SECOND_MICROS + ); + row = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(row); + } + + const invocation: CronInvocation = { + id: invocationId(jobName, arg.generation, recovery.sequence), + jobName, + generation: arg.generation, + sequence: recovery.sequence, + scheduledFor: recovery.scheduledFor, + }; + applyOutcome( + ctx, + core, + job, + invocation, + 'Failed', + truncateError(recovery.error), + true + ); +} + +function registerJob(job: JobMetadata, kind: 'reducer' | 'procedure'): Core { + const core = requireCore(job.handle); + if (job.registration) { + throw new Error( + `${internalErrors.handlerAlreadyRegistered}:${job.handle.jobName}:${job.registration}` + ); + } + job.registration = kind; + return core; +} + +/** Declare a job. Pass every job to `client()` before registering handlers. */ +export function cronTable< + const Name extends string, + ArgsBuilder extends CronArgsBuilder, +>( + opts: CronTableWithArgsOpts +): CronJobHandle>; +export function cronTable( + opts: CronTableOpts +): CronJobHandle; +export function cronTable( + opts: CronTableOpts | CronTableWithArgsOpts +): CronJobReference { + const jobName = normalizeJobName(opts.name); + const hasArgs = 'args' in opts; + const handle = { + jobName, + cronReducer(spacetimedb: CronSchema, handler: InternalHandler) { + const job = requireMetadata(handle); + const core = registerJob(job, 'reducer'); + const fire = requireFire(job); + return spacetimedb.reducer( + { name: job.reducerName, onSchedule: fire }, + { arg: fire.rowType }, + (ctx: CronTx, { arg }: { arg: FireRow }) => { + executeReducer(ctx, core, job, arg, handler); + } + ); + }, + cronProcedure(spacetimedb: CronSchema, handler: InternalHandler) { + const job = requireMetadata(handle); + const core = registerJob(job, 'procedure'); + const fire = requireFire(job); + return spacetimedb.procedure( + { name: job.reducerName, onSchedule: fire }, + { arg: fire.rowType }, + t.unit(), + (ctx: CronProcedureCtx, { arg }: { arg: FireRow }) => { + executeProcedure(ctx, core, job, arg, handler); + return {}; + } + ); + }, + }; + metadata.set(handle, { + handle, + argsType: 'args' in opts ? opts.args : t.unit(), + hasArgs, + fireTableName: `${jobName}_fire`, + fireAccessor: toCamelCase(`${jobName}_fire`), + reducerName: `${jobName}_cron`, + fire: undefined, + core: undefined, + registration: undefined, + }); + return handle; +} + +/** Create the cron tables for `config.jobs` and the functions that manage them. */ +export function client( + config: Config +): CronClient { + const { jobs } = config; + if (jobs.length === 0) throw new Error(internalErrors.noJobs); + const historyCap = normalizeHistoryCap(config.historyCap); + const isPublic = config.publicTables ?? false; + const reconcileEverySeconds = normalizeReconcileEverySeconds( + config.reconcileEverySeconds + ); + + const jobsByName = new Map(); + const argumentTypes: VariantsObj = {}; + const usedAccessors = new Set(['cronJob', 'cronRun', 'cronReconcileTick']); + const sortedJobs = [...jobs].sort((left, right) => + left.jobName < right.jobName ? -1 : left.jobName > right.jobName ? 1 : 0 + ); + for (const handle of sortedJobs) { + const job = requireMetadata(handle); + if (jobsByName.has(handle.jobName)) { + throw new Error(`${internalErrors.duplicateJob}:${handle.jobName}`); + } + if (job.core) { + throw new Error(`${internalErrors.jobAlreadyWired}:${handle.jobName}`); + } + if (usedAccessors.has(job.fireAccessor)) { + throw new Error( + `${internalErrors.tableKeyCollision}:${job.fireAccessor}` + ); + } + usedAccessors.add(job.fireAccessor); + jobsByName.set(handle.jobName, job); + argumentTypes[handle.jobName] = job.argsType; + } + + const tables: Record = { + cronJob: cronJobTable(argumentTypes), + cronRun: cronRunTable(isPublic), + }; + const reconcileTick = + reconcileEverySeconds === undefined + ? undefined + : cronReconcileTickTable(isPublic); + if (reconcileTick) tables.cronReconcileTick = reconcileTick; + for (const job of jobsByName.values()) { + job.fire = cronFireTable(job.fireTableName, isPublic); + tables[job.fireAccessor] = job.fire; + } + + const core: Core = { + jobs: jobsByName, + historyCap, + reconcileEverySeconds, + reconcileTick, + reconcileRegistered: false, + publicViewsRegistered: false, + }; + for (const job of jobsByName.values()) job.core = core; + + function jobInThisClient(handle: CronJobReference): JobMetadata { + const job = requireMetadata(handle); + if (job.core !== core) throw new Error(internalErrors.foreignJobHandle); + return job; + } + + function reconcileReducer(spacetimedb: CronSchema) { + if (core.reconcileRegistered) { + throw new Error(internalErrors.reconcileReducerAlreadyRegistered); + } + const tick = core.reconcileTick; + if (tick === undefined) { + throw new Error( + `${internalErrors.reconcileNotConfigured}:set client({ reconcileEverySeconds })` + ); + } + requireRegisteredHandlers(core); + core.reconcileRegistered = true; + return spacetimedb.reducer( + { name: RECONCILE_REDUCER_NAME, onSchedule: tick }, + { arg: tick.rowType }, + (ctx: CronTx) => { + requireDatabaseCaller(ctx); + reconcileLostFires(ctx, core); + } + ); + } + + function publicViews(spacetimedb: CronSchema): CronPublicViews { + if (core.publicViewsRegistered) { + throw new Error(internalErrors.publicViewsAlreadyRegistered); + } + core.publicViewsRegistered = true; + const jobsView = spacetimedb.anonymousView( + { name: 'cron_jobs', public: true }, + t.array(cronJobView), + (ctx: { db: { cronJob: { iter(): Iterable } } }) => + [...ctx.db.cronJob.iter()].map(row => ({ + name: row.name, + schedule: row.schedule, + enabled: row.enabled, + maxFailures: row.maxFailures, + consecutiveFailures: row.consecutiveFailures, + fireCount: row.fireCount, + generation: row.generation, + lastRunAt: row.lastRunAt, + nextRunAt: row.nextRunAt, + disabledReason: publicDisabledReason(row.disabledReason), + })) + ); + return { jobs: jobsView }; + } + + function schedule( + ctx: CronTx, + handle: CronJobReference, + spec: ScheduleSpec, + opts?: RuntimeScheduleOpts + ): void { + const job = jobInThisClient(handle); + requireRegisteredHandlers(core); + let normalized; + let maxFailures: number; + let args: unknown; + try { + normalized = normalizeSchedule( + spec, + opts, + ctx.timestamp.microsSinceUnixEpoch + ); + maxFailures = normalizeMaxFailures(opts?.maxFailures); + args = normalizeJobArgs(handle.jobName, job.hasArgs, opts); + } catch (error) { + throw error instanceof CronInputError + ? new SenderError(error.message) + : error; + } + + ensureReconcileTick(ctx, core); + reconcileLostFires(ctx, core); + + const existing = ctx.db.cronJob.name.find(handle.jobName); + const generation = (existing?.generation ?? 0n) + 1n; + disarmFire(ctx, job); + + // The stored enum type is built from every job, so its static type keeps + // only the tag. + const taggedArgs = { tag: handle.jobName, value: args }; + let row: JobRow = { + name: handle.jobName, + schedule: normalized.schedule, + args: taggedArgs, + enabled: true, + maxFailures, + consecutiveFailures: 0, + fireCount: existing?.fireCount ?? 0n, + generation, + lastRunAt: existing?.lastRunAt, + nextRunAt: undefined, + disabledReason: undefined, + }; + if (existing) ctx.db.cronJob.name.update(row); + else ctx.db.cronJob.insert(row); + + const nextRunAt = insertFire(ctx, job, row, normalized.firstAt); + if (!nextRunAt) { + throw new SenderError(errors.unsatisfiableExpression); + } + row = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(row); + } + + function unschedule(ctx: CronTx, handle: CronJobReference): void { + const job = jobInThisClient(handle); + requireRegisteredHandlers(core); + ensureReconcileTick(ctx, core); + reconcileLostFires(ctx, core); + const row = ctx.db.cronJob.name.find(handle.jobName); + if (!row) return; + disarmFire(ctx, job); + ctx.db.cronJob.name.update({ + ...row, + enabled: false, + generation: row.generation + 1n, + consecutiveFailures: 0, + nextRunAt: undefined, + disabledReason: 'disabled_by_operator', + }); + } + + return { + // The keys were derived from config.jobs exactly as CronTables derives them. + tables: tables as CronTables, + reconcileReducer, + publicViews, + schedule, + unschedule, + }; +} diff --git a/spacetime-cron-ts/src/errors.ts b/spacetime-cron-ts/src/errors.ts new file mode 100644 index 00000000000..dec3625de48 --- /dev/null +++ b/spacetime-cron-ts/src/errors.ts @@ -0,0 +1,48 @@ +/** + * Codes a caller can receive at runtime. `schedule()` throws the input codes as + * `SenderError`s; the disabled-reason codes are stored on the job row. Some are + * followed by `:` and detail text. + */ +export const errors = { + notAuthorized: 'cron.not_authorized', + // Thrown by `schedule()`. + invalidMaxFailures: 'cron.invalid_max_failures', + invalidInterval: 'cron.invalid_interval', + invalidExpression: 'cron.invalid_expression', + invalidTimezone: 'cron.invalid_timezone', + unsatisfiableExpression: 'cron.unsatisfiable_expression', + missingArgs: 'cron.missing_args', + unexpectedArgs: 'cron.unexpected_args', + // Stored as a job's disabled reason. + invalidScheduleState: 'cron.invalid_schedule_state', + invalidArgsState: 'cron.invalid_args_state', + invalidTrigger: 'cron.invalid_trigger', + noFutureOccurrence: 'cron.no_future_occurrence', +} as const; + +/** + * Module-definition and handler programming errors. They fail module loading + * or an invocation and are not exported from the package. + */ +export const internalErrors = { + foreignJobHandle: 'cron.foreign_job_handle', + notWired: 'cron.not_wired', + noJobs: 'cron.no_jobs', + duplicateJob: 'cron.duplicate_job', + jobAlreadyWired: 'cron.job_already_wired', + tableKeyCollision: 'cron.table_key_collision', + missingTable: 'cron.missing_table', + missingHandlers: 'cron.missing_handlers', + handlerAlreadyRegistered: 'cron.handler_already_registered', + reconcileNotConfigured: 'cron.reconcile_not_configured', + reconcileReducerNotRegistered: 'cron.reconcile_reducer_not_registered', + reconcileReducerAlreadyRegistered: + 'cron.reconcile_reducer_already_registered', + publicViewsAlreadyRegistered: 'cron.public_views_already_registered', + asyncReducerHandler: 'cron.async_reducer_handler', + asyncProcedureHandler: 'cron.async_procedure_handler', + invalidProcedureRecovery: 'cron.invalid_procedure_recovery', + invalidJobName: 'cron.invalid_job_name', + invalidHistoryCap: 'cron.invalid_history_cap', + invalidReconcileInterval: 'cron.invalid_reconcile_interval', +} as const; diff --git a/spacetime-cron-ts/src/index.ts b/spacetime-cron-ts/src/index.ts new file mode 100644 index 00000000000..afae7976272 --- /dev/null +++ b/spacetime-cron-ts/src/index.ts @@ -0,0 +1,30 @@ +export { client, cronTable } from './cron.js'; +export { errors } from './errors.js'; +export type { + CronArgsBuilder, + CronClient, + CronConfig, + CronFunctionExport, + CronHandler, + CronInvocation, + CronJobHandle, + CronJobReference, + CronProcedureCtx, + CronPublicViews, + CronSchedule, + CronSchema, + CronTableOpts, + CronTableWithArgsOpts, + CronTables, + CronTx, + ScheduleOpts, + ScheduleSpec, +} from './types.js'; +export { + parseCronExpression, + nextFireAfter, + isValidTimezone, + MAX_CRON_EXPRESSION_LENGTH, + MAX_TIMEZONE_LENGTH, + type ParsedCron, +} from './parser.js'; diff --git a/spacetime-cron-ts/src/parser.ts b/spacetime-cron-ts/src/parser.ts new file mode 100644 index 00000000000..dc2e2f94a67 --- /dev/null +++ b/spacetime-cron-ts/src/parser.ts @@ -0,0 +1,58 @@ +import { CronExpressionParser } from 'cron-parser'; + +// Avoids cron-parser's Math.random fallback (blocked in STDB reducers). +const HASH_SEED = 'spacetimedb-cron-submodule'; +export const MAX_CRON_EXPRESSION_LENGTH = 256; +export const MAX_TIMEZONE_LENGTH = 128; + +export type ParsedCron = { expression: string }; + +export function parseCronExpression(expr: string): ParsedCron { + const expression = expr.trim(); + if (expression.length === 0) throw new Error('cron expression is empty'); + if (expression.length > MAX_CRON_EXPRESSION_LENGTH) { + throw new Error( + `cron expression exceeds ${MAX_CRON_EXPRESSION_LENGTH} characters` + ); + } + CronExpressionParser.parse(expression, { hashSeed: HASH_SEED }); + return { expression }; +} + +// JS Date max range. +const MAX_SAFE_DATE_MS = 8_640_000_000_000_000; + +export function nextFireAfter( + parsed: ParsedCron, + afterMicros: bigint, + timezone: string = 'UTC' +): bigint | undefined { + if (!isValidTimezone(timezone)) return undefined; + const afterMs = Number(afterMicros / 1000n); + if (!Number.isFinite(afterMs) || Math.abs(afterMs) > MAX_SAFE_DATE_MS) { + return undefined; + } + try { + const interval = CronExpressionParser.parse(parsed.expression, { + currentDate: new Date(afterMs), + tz: timezone, + hashSeed: HASH_SEED, + }); + return BigInt(interval.next().getTime()) * 1000n; + } catch { + return undefined; + } +} + +export function isValidTimezone(tz: string): boolean { + if (tz.length === 0 || tz.length > MAX_TIMEZONE_LENGTH || tz !== tz.trim()) { + return false; + } + if (tz === 'UTC') return true; + try { + new Intl.DateTimeFormat('en-US', { timeZone: tz }); + return true; + } catch { + return false; + } +} diff --git a/spacetime-cron-ts/src/schedule.ts b/spacetime-cron-ts/src/schedule.ts new file mode 100644 index 00000000000..a8637e24fe5 --- /dev/null +++ b/spacetime-cron-ts/src/schedule.ts @@ -0,0 +1,185 @@ +import { + MAX_CRON_EXPRESSION_LENGTH, + MAX_TIMEZONE_LENGTH, + isValidTimezone, + nextFireAfter, + parseCronExpression, +} from './parser.js'; +import { errors, internalErrors } from './errors.js'; +import type { CronSchedule, ScheduleSpec } from './types.js'; + +export const ONE_SECOND_MICROS = 1_000_000n; +export const MAX_INTERVAL_SECONDS = 31_536_000; +export const MAX_HISTORY_CAP = 1_000; +export const MAX_FAILURES = 4_294_967_295; +export const MAX_ERROR_LENGTH = 1_024; + +// The host limit is roughly 795 days. Annual checkpoints leave ample room for +// execution delay and keep valid sparse schedules, such as February 29, armed. +export const CHECKPOINT_DELAY_MICROS = + 365n * 24n * 60n * 60n * ONE_SECOND_MICROS; + +const JOB_NAME_PATTERN = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/; +const MAX_JOB_NAME_LENGTH = 48; + +export class CronInputError extends Error {} + +export interface NormalizedSchedule { + schedule: CronSchedule; + firstAt: bigint | undefined; +} + +export function normalizeJobName(name: string): string { + const normalized = name.trim(); + if ( + normalized.length === 0 || + normalized.length > MAX_JOB_NAME_LENGTH || + !JOB_NAME_PATTERN.test(normalized) + ) { + throw new CronInputError( + `${internalErrors.invalidJobName}:use 1-48 lowercase snake_case characters` + ); + } + return normalized; +} + +export function normalizeHistoryCap(value: number | undefined): number { + const cap = value ?? 5; + if (!Number.isSafeInteger(cap) || cap < 0 || cap > MAX_HISTORY_CAP) { + throw new CronInputError( + `${internalErrors.invalidHistoryCap}:must be an integer between 0 and ${MAX_HISTORY_CAP}` + ); + } + return cap; +} + +export function normalizeReconcileEverySeconds( + value: number | undefined +): number | undefined { + if (value === undefined) return undefined; + if ( + !Number.isSafeInteger(value) || + value < 1 || + value > MAX_INTERVAL_SECONDS + ) { + throw new CronInputError( + `${internalErrors.invalidReconcileInterval}:seconds must be an integer between 1 and ${MAX_INTERVAL_SECONDS}` + ); + } + return value; +} + +export function normalizeMaxFailures(value: number | undefined): number { + const failures = value ?? 0; + if ( + !Number.isSafeInteger(failures) || + failures < 0 || + failures > MAX_FAILURES + ) { + throw new CronInputError( + `${errors.invalidMaxFailures}:must be an integer between 0 and ${MAX_FAILURES}` + ); + } + return failures; +} + +export function normalizeJobArgs( + jobName: string, + hasArgs: boolean, + opts: { args?: unknown } | undefined +): unknown { + const supplied = Object.prototype.hasOwnProperty.call(opts ?? {}, 'args'); + if (hasArgs && !supplied) { + throw new CronInputError(`${errors.missingArgs}:${jobName}`); + } + if (!hasArgs && supplied) { + throw new CronInputError(`${errors.unexpectedArgs}:${jobName}`); + } + return hasArgs ? opts?.args : {}; +} + +export function normalizeSchedule( + spec: ScheduleSpec, + opts: { timezone?: string } | undefined, + nowMicros: bigint +): NormalizedSchedule { + if (typeof spec !== 'string') { + const seconds = spec.everySeconds; + if ( + !Number.isSafeInteger(seconds) || + seconds < 1 || + seconds > MAX_INTERVAL_SECONDS + ) { + throw new CronInputError( + `${errors.invalidInterval}:seconds must be an integer between 1 and ${MAX_INTERVAL_SECONDS}` + ); + } + return { + schedule: { tag: 'every', value: { seconds } }, + firstAt: nowMicros + BigInt(seconds) * ONE_SECOND_MICROS, + }; + } + + const expression = spec.trim(); + const timezone = (opts?.timezone ?? 'UTC').trim() || 'UTC'; + if (expression.length === 0) { + throw new CronInputError(`${errors.invalidExpression}:empty`); + } + if (expression.length > MAX_CRON_EXPRESSION_LENGTH) { + throw new CronInputError(`${errors.invalidExpression}:too_long`); + } + if (timezone.length > MAX_TIMEZONE_LENGTH) { + throw new CronInputError(`${errors.invalidTimezone}:too_long`); + } + if (!isValidTimezone(timezone)) { + throw new CronInputError(`${errors.invalidTimezone}:${timezone}`); + } + + let firstAt: bigint | undefined; + try { + firstAt = nextFireAfter( + parseCronExpression(expression), + nowMicros, + timezone + ); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new CronInputError(`${errors.invalidExpression}:${detail}`); + } + if (firstAt === undefined) { + throw new CronInputError(errors.unsatisfiableExpression); + } + return { + schedule: { tag: 'cron', value: { expression, timezone } }, + firstAt, + }; +} + +export function nextOccurrence( + schedule: CronSchedule, + afterMicros: bigint +): bigint | undefined { + if (schedule.tag === 'every') { + return afterMicros + BigInt(schedule.value.seconds) * ONE_SECOND_MICROS; + } + return nextFireAfter( + parseCronExpression(schedule.value.expression), + afterMicros, + schedule.value.timezone + ); +} + +export function boundedScheduleTime( + nowMicros: bigint, + targetMicros: bigint +): bigint { + const checkpoint = nowMicros + CHECKPOINT_DELAY_MICROS; + return targetMicros < checkpoint ? targetMicros : checkpoint; +} + +export function truncateError(error: unknown): string { + const message = error instanceof Error ? error.message : String(error); + return message.length <= MAX_ERROR_LENGTH + ? message + : `${message.slice(0, MAX_ERROR_LENGTH - 3)}...`; +} diff --git a/spacetime-cron-ts/src/sys-abi.d.ts b/spacetime-cron-ts/src/sys-abi.d.ts new file mode 100644 index 00000000000..1453a30d467 --- /dev/null +++ b/spacetime-cron-ts/src/sys-abi.d.ts @@ -0,0 +1,10 @@ +// Ambient declaration for the host syscall used by the failure-reporting +// bridge. The SDK keeps this module internal, while the module bundler +// resolves the direct import inside the host. Keep this dependency isolated +// here so it can be replaced without changing the public cron API. +declare module 'spacetime:sys@2.0' { + export function volatile_nonatomic_schedule_immediate( + reducerName: string, + args: Uint8Array + ): void; +} diff --git a/spacetime-cron-ts/src/tables.ts b/spacetime-cron-ts/src/tables.ts new file mode 100644 index 00000000000..317c45e4d5e --- /dev/null +++ b/spacetime-cron-ts/src/tables.ts @@ -0,0 +1,153 @@ +import type { Identity, Timestamp } from 'spacetimedb'; +import { t, table, type Infer, type VariantsObj } from 'spacetimedb/server'; + +const cronSchedule = t.enum('CronSchedule', { + cron: t.object('CronSpec', { + expression: t.string(), + timezone: t.string(), + }), + every: t.object('EverySpec', { + seconds: t.u32(), + }), +}); + +const cronRunStatus = t.enum('CronRunStatus', ['Ok', 'Failed']); + +const cronFireRecovery = t.object('CronFireRecovery', { + sequence: t.u64(), + scheduledFor: t.timestamp(), + error: t.string(), +}); + +/** Public projection of `cron_job` without typed arguments. */ +export const cronJobView = t.row('CronJobView', { + name: t.string().primaryKey(), + schedule: cronSchedule, + enabled: t.bool(), + maxFailures: t.u32(), + consecutiveFailures: t.u32(), + fireCount: t.u64(), + generation: t.u64(), + lastRunAt: t.option(t.timestamp()), + nextRunAt: t.option(t.timestamp()), + disabledReason: t.option(t.string()), +}); + +export function cronJobTable(args: VariantsObj) { + return table( + { name: 'cron_job', public: false }, + { + name: t.string().primaryKey(), + schedule: cronSchedule, + args: t.enum('CronJobArgsValue', args), + enabled: t.bool(), + maxFailures: t.u32(), + consecutiveFailures: t.u32(), + fireCount: t.u64(), + generation: t.u64(), + lastRunAt: t.option(t.timestamp()), + nextRunAt: t.option(t.timestamp()), + disabledReason: t.option(t.string()), + } + ); +} + +export function cronRunTable(isPublic: boolean) { + return table( + { name: 'cron_run', public: isPublic }, + { + invocationId: t.string().primaryKey(), + jobName: t.string().index(), + generation: t.u64(), + sequence: t.u64(), + scheduledFor: t.timestamp(), + completedAt: t.timestamp(), + status: cronRunStatus, + error: t.option(t.string()), + } + ); +} + +export function cronFireTable(name: string, isPublic: boolean) { + return table( + { name, public: isPublic }, + { + scheduledId: t.u64().primaryKey().autoInc(), + scheduledAt: t.scheduleAt(), + jobName: t.string().unique(), + generation: t.u64(), + targetAt: t.option(t.timestamp()), + recovery: t.option(cronFireRecovery), + } + ); +} + +export function cronReconcileTickTable(isPublic: boolean) { + return table( + { name: 'cron_reconcile_tick', public: isPublic }, + { + scheduledId: t.u64().primaryKey().autoInc(), + scheduledAt: t.scheduleAt(), + key: t.string().unique(), + } + ); +} + +export type CronJobTableDef = ReturnType; +export type CronRunTableDef = ReturnType; +export type CronFireTableDef = ReturnType; +export type CronReconcileTickTableDef = ReturnType< + typeof cronReconcileTickTable +>; + +export type JobRow = Infer; +export type RunRow = Infer; +export type FireRow = Infer; +export type ReconcileTickRow = Infer; + +/** The cron tables of a host reducer or transaction context. */ +export interface CronDb { + readonly cronJob: { + readonly name: { + find(name: string): JobRow | null; + update(row: JobRow): JobRow; + }; + insert(row: JobRow): JobRow; + }; + readonly cronRun: { + readonly invocationId: { find(id: string): RunRow | null }; + readonly jobName: { filter(jobName: string): Iterable }; + insert(row: RunRow): RunRow; + delete(row: RunRow): boolean; + }; + readonly cronReconcileTick?: { + readonly key: { find(key: string): ReconcileTickRow | null }; + insert(row: ReconcileTickRow): ReconcileTickRow; + }; + /** Per-job fire tables, keyed by `Fire`. */ + readonly [accessor: string]: unknown; +} + +/** The parts of a host fire table that cron reads and writes. */ +export interface CronFireTable { + readonly jobName: { find(jobName: string): FireRow | null }; + readonly scheduledId: { find(scheduledId: bigint): FireRow | null }; + insert(row: FireRow): FireRow; + delete(row: FireRow): boolean; +} + +/** A host reducer context whose schema includes `cron.tables`. */ +export interface CronTx { + readonly sender: Identity; + readonly databaseIdentity: Identity; + readonly timestamp: Timestamp; + readonly db: CronDb; +} + +/** A host procedure context whose schema includes `cron.tables`. */ +export interface CronProcedureCtx { + readonly sender: Identity; + readonly databaseIdentity: Identity; + readonly timestamp: Timestamp; + withTx(body: (tx: CronTx) => T): T; +} diff --git a/spacetime-cron-ts/src/types.ts b/spacetime-cron-ts/src/types.ts new file mode 100644 index 00000000000..c1ea018aef2 --- /dev/null +++ b/spacetime-cron-ts/src/types.ts @@ -0,0 +1,158 @@ +import type { Timestamp } from 'spacetimedb'; +import type { + ModuleExport, + toCamelCase, + VariantsObj, +} from 'spacetimedb/server'; +import type { + CronFireTableDef, + CronJobTableDef, + CronProcedureCtx, + CronReconcileTickTableDef, + CronRunTableDef, + CronTx, + FireRow, +} from './tables.js'; + +export type { CronProcedureCtx, CronTx } from './tables.js'; + +export type CronSchedule = + | { tag: 'cron'; value: { expression: string; timezone: string } } + | { tag: 'every'; value: { seconds: number } }; + +/** A cron expression or a fixed interval in seconds. */ +export type ScheduleSpec = string | { everySeconds: number }; + +interface SchedulePolicyOpts { + /** IANA timezone for cron expressions. Defaults to `UTC`. */ + timezone?: string; + /** Consecutive failures before automatic disablement. `0` disables this policy. */ + maxFailures?: number; +} + +/** Schedule policy plus the durable arguments required by an argument-bearing job. */ +export type ScheduleOpts = SchedulePolicyOpts & + ([Args] extends [undefined] ? { args?: never } : { args: Args }); + +/** Any SpacetimeDB type builder accepted as a cron argument payload. */ +export type CronArgsBuilder = VariantsObj[string]; + +export interface CronTableOpts { + /** Stable snake_case job name. */ + name: Name; +} + +export interface CronTableWithArgsOpts< + Name extends string = string, + ArgsBuilder extends CronArgsBuilder = CronArgsBuilder, +> extends CronTableOpts { + /** Typed payload persisted with the schedule and copied into each invocation. */ + args: ArgsBuilder; +} + +export interface CronConfig { + /** Every job handle in the module, each created by `cronTable()`. */ + jobs: readonly CronJobReference[]; + /** Completed run records retained per job. Defaults to `5`. */ + historyCap?: number; + /** Expose trigger and run tables to subscriptions. Defaults to `false`. */ + publicTables?: boolean; + /** + * Optional native interval that repairs enabled jobs with missing triggers. + * Management operations always run the same repair opportunistically. + */ + reconcileEverySeconds?: number; +} + +/** Stable metadata supplied to every cron invocation. */ +export interface CronInvocation { + /** Unique across every generation of every job. */ + readonly id: string; + readonly jobName: string; + readonly generation: bigint; + readonly sequence: bigint; + /** Logical calendar occurrence or interval fire time. */ + readonly scheduledFor: Timestamp; +} + +export type CronHandler = [Args] extends [undefined] + ? (ctx: Ctx, invocation: CronInvocation) => void + : (ctx: Ctx, args: Args, invocation: CronInvocation) => void; + +/** A scheduled reducer or procedure registered for one job. */ +export type CronFunctionExport = ModuleExport & + ((ctx: Ctx, args: { arg: FireRow }) => unknown); + +/** + * The host schema returned by `schema()`. Handler contexts are inferred from + * its reducer and procedure exports. + */ +export interface CronSchema< + Tx extends CronTx = CronTx, + Proc extends CronProcedureCtx = CronProcedureCtx, +> { + reducer(...args: unknown[]): CronFunctionExport; + procedure(...args: unknown[]): CronFunctionExport; + anonymousView(...args: unknown[]): ModuleExport; +} + +export interface CronJobReference { + readonly jobName: Name; +} + +export interface CronJobHandle + extends CronJobReference { + cronReducer( + spacetimedb: CronSchema, + handler: CronHandler + ): CronFunctionExport; + cronProcedure( + spacetimedb: CronSchema, + handler: CronHandler + ): CronFunctionExport; +} + +type FireAccessor = ReturnType< + typeof toCamelCase<`${Name}_fire`> +>; + +/** The tables to spread into the host's `schema()` call. */ +export type CronTables = { + readonly cronJob: CronJobTableDef; + readonly cronRun: CronRunTableDef; +} & { + readonly [Job in Config['jobs'][number] as FireAccessor< + Job['jobName'] + >]: CronFireTableDef; +} & (Config extends { reconcileEverySeconds: number } + ? { readonly cronReconcileTick: CronReconcileTickTableDef } + : unknown); + +export interface CronPublicViews { + /** Sanitized job state. Typed application arguments remain private. */ + readonly jobs: ModuleExport; +} + +export interface CronClient { + /** Spread into the host's `schema()` call. */ + readonly tables: CronTables; + /** Register and export the optional lost-trigger reconciliation sweep. */ + reconcileReducer( + spacetimedb: CronSchema + ): ModuleExport; + /** Register the optional public job-state view exactly once. */ + publicViews( + spacetimedb: CronSchema + ): CronPublicViews; + /** Create or replace a job schedule and arm its first trigger. */ + schedule( + ctx: CronTx, + job: CronJobHandle, + spec: ScheduleSpec, + ...options: [Args] extends [undefined] + ? [opts?: ScheduleOpts] + : [opts: ScheduleOpts>] + ): void; + /** Disable a job and remove its pending trigger. */ + unschedule(ctx: CronTx, job: CronJobReference): void; +} diff --git a/spacetime-cron-ts/tsconfig.build.json b/spacetime-cron-ts/tsconfig.build.json new file mode 100644 index 00000000000..8635027968f --- /dev/null +++ b/spacetime-cron-ts/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/spacetime-cron-ts/tsconfig.json b/spacetime-cron-ts/tsconfig.json new file mode 100644 index 00000000000..77da6c09f65 --- /dev/null +++ b/spacetime-cron-ts/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "declaration": false, + "noEmit": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "isolatedModules": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/spacetime-crypto-ts/.npmrc b/spacetime-crypto-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-crypto-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-crypto-ts/LICENSE.txt b/spacetime-crypto-ts/LICENSE.txt new file mode 120000 index 00000000000..cc1ff9bdd72 --- /dev/null +++ b/spacetime-crypto-ts/LICENSE.txt @@ -0,0 +1 @@ +../licenses/apache2.txt \ No newline at end of file diff --git a/spacetime-crypto-ts/README.md b/spacetime-crypto-ts/README.md new file mode 100644 index 00000000000..7313d5d62b5 --- /dev/null +++ b/spacetime-crypto-ts/README.md @@ -0,0 +1,76 @@ +# @spacetimedb/crypto + +Hash data, create HMAC signatures, and verify webhook signatures in SpacetimeDB. +The package also includes byte comparison and hex and base64 conversion helpers. + +## Install + +```bash +npm install @spacetimedb/crypto +``` + +## Verify a webhook + +In your HTTP handler, verify a Stripe webhook with the raw request body and +the module's timestamp: + +```ts +import { SyncResponse } from 'spacetimedb/server'; +import { verifyStripeSignature } from '@spacetimedb/crypto'; + +const result = verifyStripeSignature({ + rawBody, + signatureHeader: request.headers.get('stripe-signature') ?? '', + secret: webhookSecret, + nowSeconds: Number(ctx.timestamp.microsSinceUnixEpoch / 1_000_000n), +}); +if (!result.ok) { + return new SyncResponse(result.reason, { status: 400 }); +} +``` + +Verify the raw webhook body before parsing it. Store webhook secrets in private +tables and keep them out of public rows and procedure results. + +## API + +- `sha256(data)` and `hmacSha256(key, message)` return `Uint8Array` digests. +- `timingSafeEqual(a, b)` compares every byte in equal-length arrays. +- `hexToBytes`, `bytesToHex`, and `base64ToBytes` convert common encodings. + Base64 accepts canonical padded or unpadded standard encoding and rejects + whitespace, misplaced padding, invalid lengths, and non-canonical pad bits. +- `verifyStripeSignature(options)` verifies Stripe's `v1` signature format. +- `verifySvixSignature(options)` verifies Svix-compatible signatures, including + Resend webhooks. +- `verifyGithubSignature(options)` verifies GitHub's SHA-256 webhook signature. + +The verifiers return `{ ok: true }` or `{ ok: false, reason }`, with these +`errors` codes: + +| Code | Meaning | +| ------------------------------------ | ------------------------------------------------------ | +| `crypto.missing_signature` | The header has no timestamp or no supported signature. | +| `crypto.invalid_timestamp` | The signed timestamp is not an integer. | +| `crypto.timestamp_outside_tolerance` | The timestamp is outside `toleranceSeconds`. | +| `crypto.invalid_secret` | The Svix secret is not valid base64. | +| `crypto.signature_mismatch` | No signature matches the body and secret. | + +Package entrypoints: + +- `@spacetimedb/crypto` exports hashing, encoding, comparison, and vendor + verification helpers. +- `@spacetimedb/crypto/vendors` is the focused webhook-verification + entrypoint. + +## Testing + +```bash +pnpm test +pnpm run lint +``` + +Tests use published vendor vectors and local fixtures; no network is required. + +## License + +Apache-2.0. See [`LICENSE.txt`](./LICENSE.txt). diff --git a/spacetime-crypto-ts/package.json b/spacetime-crypto-ts/package.json new file mode 100644 index 00000000000..1dc6ba7f5f6 --- /dev/null +++ b/spacetime-crypto-ts/package.json @@ -0,0 +1,74 @@ +{ + "name": "@spacetimedb/crypto", + "description": "Deterministic hashing, encoding, and webhook-signature helpers for SpacetimeDB TypeScript modules.", + "version": "0.1.0", + "license": "Apache-2.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./vendors": { + "types": "./src/vendors.ts", + "default": "./src/vendors.ts" + } + }, + "files": [ + "dist", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./vendors": { + "types": "./dist/vendors.d.ts", + "default": "./dist/vendors.js" + } + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/clockworklabs/SpacetimeDB.git", + "directory": "spacetime-crypto-ts" + }, + "homepage": "https://github.com/clockworklabs/SpacetimeDB/tree/master/spacetime-crypto-ts#readme", + "bugs": { + "url": "https://github.com/clockworklabs/SpacetimeDB/issues" + }, + "keywords": [ + "spacetimedb", + "cryptography", + "webhooks", + "typescript" + ], + "scripts": { + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "tsx scripts/test-vectors.ts", + "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json", + "prepack": "pnpm run build && node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" + }, + "devDependencies": { + "eslint": "^9.17.0", + "prettier": "^3.3.3", + "@types/node": "^22.10.2", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + }, + "dependencies": { + "@noble/hashes": "^2.2.0" + } +} diff --git a/spacetime-crypto-ts/scripts/test-vectors.ts b/spacetime-crypto-ts/scripts/test-vectors.ts new file mode 100644 index 00000000000..cac4ed1d834 --- /dev/null +++ b/spacetime-crypto-ts/scripts/test-vectors.ts @@ -0,0 +1,359 @@ +// Verify the @noble/hashes wrappers and signature helpers against test vectors. +// Run via: pnpm test +// +// Sources: +// SHA-256 vectors: NIST CAVS examples + RFC 6234 §8.5 +// HMAC-SHA256 vectors: RFC 4231 §4 + +import { sha256 } from '../src/sha256'; +import { hmacSha256 } from '../src/hmac'; +import { + bytesToHex, + hexToBytes, + timingSafeEqual, + base64ToBytes, +} from '../src/timing'; +import { + errors, + verifyStripeSignature, + verifyGithubSignature, + verifySvixSignature, + type VerifyResult, +} from '../src/vendors'; + +const enc = new TextEncoder(); + +let pass = 0, + fail = 0; + +function assertEq(label: string, got: string, expected: string): void { + if (got === expected) { + process.stdout.write(` OK ${label}\n`); + pass++; + } else { + process.stdout.write( + ` FAIL ${label}\n got: ${got}\n expected: ${expected}\n` + ); + fail++; + } +} + +function assert(label: string, cond: boolean): void { + if (cond) { + process.stdout.write(` OK ${label}\n`); + pass++; + } else { + process.stdout.write(` FAIL ${label}\n`); + fail++; + } +} + +function assertResult( + label: string, + got: VerifyResult, + expected: VerifyResult +): void { + assertEq(label, JSON.stringify(got), JSON.stringify(expected)); +} + +const ok: VerifyResult = { ok: true }; +const fails = (reason: keyof typeof errors): VerifyResult => ({ + ok: false, + reason: errors[reason], +}); + +// SHA-256 +process.stdout.write('SHA-256\n'); +assertEq( + 'empty string', + bytesToHex(sha256(enc.encode(''))), + 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' +); +assertEq( + '"abc"', + bytesToHex(sha256(enc.encode('abc'))), + 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad' +); +assertEq( + 'NIST 448-bit message', + bytesToHex( + sha256( + enc.encode('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq') + ) + ), + '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1' +); +// One million "a" characters exercises message-length packing in the padding. +const millionA = new Uint8Array(1_000_000); +millionA.fill(0x61); +assertEq( + '1,000,000 × "a"', + bytesToHex(sha256(millionA)), + 'cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0' +); + +// HMAC-SHA256 (RFC 4231 test cases) +process.stdout.write('\nHMAC-SHA256 (RFC 4231)\n'); + +assertEq( + 'TC1: 20 × 0x0b key, "Hi There"', + bytesToHex( + hmacSha256( + hexToBytes('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b'), + enc.encode('Hi There') + ) + ), + 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7' +); + +assertEq( + 'TC2: "Jefe" key, "what do ya want for nothing?"', + bytesToHex( + hmacSha256(enc.encode('Jefe'), enc.encode('what do ya want for nothing?')) + ), + '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843' +); + +assertEq( + 'TC3: 20 × 0xaa key, 50 × 0xdd data', + bytesToHex( + hmacSha256( + hexToBytes('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'), + hexToBytes('dd'.repeat(50)) + ) + ), + '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe' +); + +assertEq( + 'TC4: 25-byte key, 50 × 0xcd', + bytesToHex( + hmacSha256( + hexToBytes('0102030405060708090a0b0c0d0e0f10111213141516171819'), + hexToBytes('cd'.repeat(50)) + ) + ), + '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b' +); + +assertEq( + 'TC6: 131-byte key (forces hash-down), short data', + bytesToHex( + hmacSha256( + hexToBytes('aa'.repeat(131)), + enc.encode('Test Using Larger Than Block-Size Key - Hash Key First') + ) + ), + '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54' +); + +assertEq( + 'TC7: 131-byte key, long data', + bytesToHex( + hmacSha256( + hexToBytes('aa'.repeat(131)), + enc.encode( + 'This is a test using a larger than block-size key and a larger than block-size data. ' + + 'The key needs to be hashed before being used by the HMAC algorithm.' + ) + ) + ), + '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2' +); + +// timingSafeEqual +process.stdout.write('\ntimingSafeEqual\n'); +assert( + 'equal returns true', + timingSafeEqual(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3])) +); +assert( + 'differing byte returns false', + !timingSafeEqual(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 4])) +); +assert( + 'different length returns false', + !timingSafeEqual(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3, 4])) +); +assert( + 'two empty returns true', + timingSafeEqual(new Uint8Array([]), new Uint8Array([])) +); + +// Base64 round-trip +process.stdout.write('\nbase64\n'); +const b64Cases: Array<[string, string]> = [ + ['', ''], + ['f', 'Zg=='], + ['fo', 'Zm8='], + ['foo', 'Zm9v'], + ['foob', 'Zm9vYg=='], + ['fooba', 'Zm9vYmE='], + ['foobar', 'Zm9vYmFy'], +]; +for (const [plain, b64] of b64Cases) { + const decoded = new TextDecoder().decode(base64ToBytes(b64)); + assertEq(`decode("${b64}")`, decoded, plain); +} +assertEq( + 'decode unpadded Zg', + new TextDecoder().decode(base64ToBytes('Zg')), + 'f' +); +for (const malformed of [ + 'A', + '=AAA', + 'A=AA', + 'AA=A', + 'AAAA=', + 'AA===', + 'Zh==', + 'Zm9=', + 'Zg==\n', + '\u0100AAA', + 'AA\u0100A', +]) { + let threw = false; + try { + base64ToBytes(malformed); + } catch { + threw = true; + } + assert(`reject malformed base64 ${JSON.stringify(malformed)}`, threw); +} + +// Stripe signature round-trip +// Construct a header the way Stripe does, then verify it round-trips. +process.stdout.write('\nStripe webhook signature\n'); +const stripeSecret = 'whsec_test_secret_1234567890'; +const stripeBody = '{"id":"evt_test","type":"customer.created"}'; +const stripeTs = '1700000000'; +const stripeMac = hmacSha256( + enc.encode(stripeSecret), + enc.encode(`${stripeTs}.${stripeBody}`) +); +const stripeHeader = `t=${stripeTs},v1=${bytesToHex(stripeMac)}`; +const stripe = { + rawBody: stripeBody, + signatureHeader: stripeHeader, + secret: stripeSecret, + toleranceSeconds: Infinity, +}; +assertResult('valid signature passes', verifyStripeSignature(stripe), ok); +assertResult( + 'mutated body fails', + verifyStripeSignature({ ...stripe, rawBody: stripeBody + 'x' }), + fails('signatureMismatch') +); +assertResult( + 'wrong secret fails', + verifyStripeSignature({ ...stripe, secret: 'whsec_wrong' }), + fails('signatureMismatch') +); +assertResult( + 'missing v1 entry fails', + verifyStripeSignature({ ...stripe, signatureHeader: `t=${stripeTs}` }), + fails('missingSignature') +); +assertResult( + 'non-numeric timestamp fails', + verifyStripeSignature({ + ...stripe, + signatureHeader: `t=soon,v1=${bytesToHex(stripeMac)}`, + }), + fails('invalidTimestamp') +); +assertResult( + 'old timestamp rejected when tolerance enforced', + verifyStripeSignature({ + ...stripe, + toleranceSeconds: 300, + nowSeconds: Number(stripeTs) + 1000, + }), + fails('timestampOutsideTolerance') +); +assertResult( + 'multiple v1 entries: any match wins', + verifyStripeSignature({ + ...stripe, + signatureHeader: `t=${stripeTs},v1=deadbeef,v1=${bytesToHex(stripeMac)}`, + }), + ok +); + +// GitHub signature round-trip +process.stdout.write('\nGitHub webhook signature\n'); +const ghSecret = "It's a Secret to Everybody"; +const ghBody = 'Hello, World!'; +const ghMac = hmacSha256(enc.encode(ghSecret), enc.encode(ghBody)); +const github = { + rawBody: ghBody, + signatureHeader: `sha256=${bytesToHex(ghMac)}`, + secret: ghSecret, +}; +assertResult('roundtrip passes', verifyGithubSignature(github), ok); +assertResult( + 'missing prefix fails', + verifyGithubSignature({ ...github, signatureHeader: bytesToHex(ghMac) }), + fails('missingSignature') +); +assertResult( + 'wrong secret fails', + verifyGithubSignature({ ...github, secret: 'wrong' }), + fails('signatureMismatch') +); +// Known vector from GitHub docs. +assertEq( + 'docs example body→hex', + bytesToHex(hmacSha256(enc.encode(ghSecret), enc.encode(ghBody))), + '757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17' +); + +// Svix (Resend) signature round-trip +process.stdout.write('\nsvix (Resend) signature\n'); +const svixSecretRaw = new Uint8Array(32).fill(0x42); +const toBase64 = (bytes: Uint8Array) => Buffer.from(bytes).toString('base64'); +const svixId = 'msg_test_123'; +const svixTs = '1700000000'; +const svixBody = '{"event":"email.delivered"}'; +const svixMac = hmacSha256( + svixSecretRaw, + enc.encode(`${svixId}.${svixTs}.${svixBody}`) +); +const svix = { + rawBody: svixBody, + svixId, + svixTimestamp: svixTs, + svixSignature: `v1,${toBase64(svixMac)}`, + secret: `whsec_${toBase64(svixSecretRaw)}`, + toleranceSeconds: Infinity, +}; +assertResult('valid svix signature passes', verifySvixSignature(svix), ok); +assertResult( + 'mutated svix body fails', + verifySvixSignature({ ...svix, rawBody: svixBody + 'x' }), + fails('signatureMismatch') +); +assertResult( + 'invalid base64 secret fails', + verifySvixSignature({ ...svix, secret: 'whsec_not base64' }), + fails('invalidSecret') +); +assertResult( + 'no v1 signature fails', + verifySvixSignature({ ...svix, svixSignature: 'v2,abc' }), + fails('missingSignature') +); +assertResult( + 'old svix timestamp rejected', + verifySvixSignature({ + ...svix, + toleranceSeconds: 300, + nowSeconds: Number(svixTs) + 301, + }), + fails('timestampOutsideTolerance') +); + +// Summary +process.stdout.write(`\n${pass} pass, ${fail} fail\n`); +if (fail > 0) process.exit(1); diff --git a/spacetime-crypto-ts/src/hmac.ts b/spacetime-crypto-ts/src/hmac.ts new file mode 100644 index 00000000000..f37d752e0ec --- /dev/null +++ b/spacetime-crypto-ts/src/hmac.ts @@ -0,0 +1,6 @@ +import { hmac } from '@noble/hashes/hmac.js'; +import { sha256 } from '@noble/hashes/sha2.js'; + +export function hmacSha256(key: Uint8Array, message: Uint8Array): Uint8Array { + return hmac(sha256, key, message); +} diff --git a/spacetime-crypto-ts/src/index.ts b/spacetime-crypto-ts/src/index.ts new file mode 100644 index 00000000000..af3dead812d --- /dev/null +++ b/spacetime-crypto-ts/src/index.ts @@ -0,0 +1,20 @@ +export { sha256, SHA256_BYTES } from './sha256.js'; +export { hmacSha256 } from './hmac.js'; +export { + timingSafeEqual, + hexToBytes, + bytesToHex, + base64ToBytes, +} from './timing.js'; + +export { + errors, + verifyStripeSignature, + verifySvixSignature, + verifyGithubSignature, + type StripeVerifyOpts, + type SvixVerifyOpts, + type GithubVerifyOpts, + type VerifyFailure, + type VerifyResult, +} from './vendors.js'; diff --git a/spacetime-crypto-ts/src/sha256.ts b/spacetime-crypto-ts/src/sha256.ts new file mode 100644 index 00000000000..6b93c308010 --- /dev/null +++ b/spacetime-crypto-ts/src/sha256.ts @@ -0,0 +1,7 @@ +import { sha256 as nobleSha256 } from '@noble/hashes/sha2.js'; + +export function sha256(data: Uint8Array): Uint8Array { + return nobleSha256(data); +} + +export const SHA256_BYTES = 32; diff --git a/spacetime-crypto-ts/src/timing.ts b/spacetime-crypto-ts/src/timing.ts new file mode 100644 index 00000000000..ff1f671ba60 --- /dev/null +++ b/spacetime-crypto-ts/src/timing.ts @@ -0,0 +1,85 @@ +/** + * Compare two byte arrays in time independent of their content. Returns true + * iff both have the same length AND identical bytes. + * + * IMPORTANT: this is only constant-time when arrays are equal length. The + * length check is up front and leaks length info, which is fine for fixed-size + * tags (HMAC outputs, JWT signatures). For variable-length comparisons you'd + * need to also pad to a max length. + * + * Note: the JIT can sometimes shortcut bitwise OR chains. The accumulator + * pattern below is the standard timing-safe construction; it's about as + * practical in pure JS without going to WASM. + */ +export function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean { + if (a.length !== b.length) return false; + let diff = 0; + for (let i = 0; i < a.length; i++) { + diff |= a[i]! ^ b[i]!; + } + return diff === 0; +} + +export { hexToBytes, bytesToHex } from '@noble/hashes/utils.js'; + +/** Decode standard base64 (with or without padding). Throws on invalid input. */ +export function base64ToBytes(b64: string): Uint8Array { + if (/\s/.test(b64)) throw new Error('base64: whitespace is not allowed'); + if (b64.length % 4 === 1) throw new Error('base64: invalid length'); + const firstPad = b64.indexOf('='); + if (firstPad >= 0) { + const padding = b64.length - firstPad; + if ( + padding > 2 || + b64.length % 4 !== 0 || + !/^=+$/.test(b64.slice(firstPad)) + ) { + throw new Error('base64: invalid padding'); + } + } + + let s = b64; + while (s.length % 4 !== 0) s += '='; + const ALPHABET = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + const lookup = new Int8Array(256).fill(-1); + for (let i = 0; i < ALPHABET.length; i++) lookup[ALPHABET.charCodeAt(i)] = i; + lookup[0x3d /* '=' */] = 0; // Padding is removed after decoding. + + // Count pad to compute output length. + let pad = 0; + if (s.endsWith('==')) pad = 2; + else if (s.endsWith('=')) pad = 1; + + const out = new Uint8Array((s.length / 4) * 3 - pad); + let oi = 0; + for (let i = 0; i < s.length; i += 4) { + const c0 = lookup[s.charCodeAt(i)] ?? -1; + const c1 = lookup[s.charCodeAt(i + 1)] ?? -1; + const c2 = lookup[s.charCodeAt(i + 2)] ?? -1; + const c3 = lookup[s.charCodeAt(i + 3)] ?? -1; + if (c0 < 0 || c1 < 0 || c2 < 0 || c3 < 0) { + throw new Error('base64: invalid char'); + } + const finalQuartet = i + 4 === s.length; + if ( + s[i] === '=' || + s[i + 1] === '=' || + (!finalQuartet && (s[i + 2] === '=' || s[i + 3] === '=')) + ) { + throw new Error('base64: invalid padding'); + } + if (s[i + 2] === '=' && s[i + 3] !== '=') + throw new Error('base64: invalid padding'); + if (s[i + 2] === '=' && (c1 & 0x0f) !== 0) + throw new Error('base64: non-canonical padding'); + if (s[i + 3] === '=' && s[i + 2] !== '=' && (c2 & 0x03) !== 0) { + throw new Error('base64: non-canonical padding'); + } + const v = (c0 << 18) | (c1 << 12) | (c2 << 6) | c3; + if (oi < out.length) out[oi++] = (v >> 16) & 0xff; + if (oi < out.length) out[oi++] = (v >> 8) & 0xff; + if (oi < out.length) out[oi++] = v & 0xff; + } + return out; +} diff --git a/spacetime-crypto-ts/src/vendors.ts b/spacetime-crypto-ts/src/vendors.ts new file mode 100644 index 00000000000..a1eb3d3a238 --- /dev/null +++ b/spacetime-crypto-ts/src/vendors.ts @@ -0,0 +1,190 @@ +// Reference docs: +// Stripe: https://docs.stripe.com/webhooks/signatures +// Resend (svix): https://docs.svix.com/receiving/verifying-payloads/how-manual +// GitHub: https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries + +import { hmacSha256 } from './hmac.js'; +import { timingSafeEqual, hexToBytes, base64ToBytes } from './timing.js'; + +const enc = new TextEncoder(); + +/** Reasons a webhook signature check fails. */ +export const errors = { + missingSignature: 'crypto.missing_signature', + invalidTimestamp: 'crypto.invalid_timestamp', + timestampOutsideTolerance: 'crypto.timestamp_outside_tolerance', + invalidSecret: 'crypto.invalid_secret', + signatureMismatch: 'crypto.signature_mismatch', +} as const; + +export type VerifyFailure = (typeof errors)[keyof typeof errors]; + +export type VerifyResult = { ok: true } | { ok: false; reason: VerifyFailure }; + +const verified: VerifyResult = { ok: true }; +const failed = (reason: VerifyFailure): VerifyResult => ({ ok: false, reason }); + +function checkTimestamp( + value: string, + toleranceSeconds: number, + nowSeconds: number | undefined +): VerifyResult { + const t = Number.parseInt(value, 10); + if (!Number.isFinite(t)) return failed(errors.invalidTimestamp); + const now = nowSeconds ?? Math.floor(Date.now() / 1000); + if (toleranceSeconds !== Infinity && Math.abs(now - t) > toleranceSeconds) { + return failed(errors.timestampOutsideTolerance); + } + return verified; +} + +// Stripe + +export interface StripeVerifyOpts { + /** The raw request body, exactly as received (do NOT re-stringify JSON). */ + rawBody: string; + /** Value of the `stripe-signature` request header. */ + signatureHeader: string; + /** The webhook signing secret, e.g. `whsec_...`. */ + secret: string; + /** + * Maximum age of the signed timestamp, in seconds. Stripe recommends 300 + * (5 minutes) to protect against replay. Pass `Infinity` to skip the check + * (only for tests). + */ + toleranceSeconds?: number; + /** Current Unix time in seconds. Defaults to `Date.now()/1000` but the + * STDB module runtime should pass `ctx.timestamp` converted to seconds. */ + nowSeconds?: number; +} + +/** + * Verify a Stripe webhook signature. Succeeds when the signature header + * contains at least one valid v1 signature and the timestamp is within + * tolerance. + */ +export function verifyStripeSignature(opts: StripeVerifyOpts): VerifyResult { + // Parse "t=1709836800,v1=abcdef,v1=12345..." into a map. + // Multiple v1 entries are possible after key rotation; any match wins. + const fields: Record = {}; + for (const part of opts.signatureHeader.split(',')) { + const eq = part.indexOf('='); + if (eq < 0) continue; + const k = part.slice(0, eq).trim(); + const v = part.slice(eq + 1).trim(); + (fields[k] ??= []).push(v); + } + + const tStr = fields.t?.[0]; + const v1List = fields.v1; + if (!tStr || !v1List) return failed(errors.missingSignature); + const timestamp = checkTimestamp( + tStr, + opts.toleranceSeconds ?? 300, + opts.nowSeconds + ); + if (!timestamp.ok) return timestamp; + + const signed = enc.encode(`${tStr}.${opts.rawBody}`); + const expected = hmacSha256(enc.encode(opts.secret), signed); + + for (const v1Hex of v1List) { + let candidate: Uint8Array; + try { + candidate = hexToBytes(v1Hex); + } catch { + continue; + } + if (timingSafeEqual(expected, candidate)) return verified; + } + return failed(errors.signatureMismatch); +} + +// Resend webhooks use Svix signatures. + +export interface SvixVerifyOpts { + rawBody: string; + /** `svix-id` header. */ + svixId: string; + /** `svix-timestamp` header (Unix seconds as string). */ + svixTimestamp: string; + /** `svix-signature` header, space-separated list like `v1,base64sig`. */ + svixSignature: string; + /** Endpoint secret, in the form `whsec_`. */ + secret: string; + toleranceSeconds?: number; + nowSeconds?: number; +} + +/** Verify a Svix webhook signature, as sent by Resend, Clerk, and others. */ +export function verifySvixSignature(opts: SvixVerifyOpts): VerifyResult { + const timestamp = checkTimestamp( + opts.svixTimestamp, + opts.toleranceSeconds ?? 300, + opts.nowSeconds + ); + if (!timestamp.ok) return timestamp; + + // Strip the `whsec_` prefix, base64-decode the rest. + const secretBody = opts.secret.startsWith('whsec_') + ? opts.secret.slice('whsec_'.length) + : opts.secret; + let secretBytes: Uint8Array; + try { + secretBytes = base64ToBytes(secretBody); + } catch { + return failed(errors.invalidSecret); + } + + const signed = enc.encode( + `${opts.svixId}.${opts.svixTimestamp}.${opts.rawBody}` + ); + const expected = hmacSha256(secretBytes, signed); + + // Header is `v1, v1, ...`. Any match wins. + const signatures = opts.svixSignature + .split(' ') + .filter(part => part.startsWith('v1,')); + if (signatures.length === 0) return failed(errors.missingSignature); + for (const part of signatures) { + let candidate: Uint8Array; + try { + candidate = base64ToBytes(part.slice('v1,'.length)); + } catch { + continue; + } + if (timingSafeEqual(expected, candidate)) return verified; + } + return failed(errors.signatureMismatch); +} + +// GitHub + +export interface GithubVerifyOpts { + rawBody: string; + /** `x-hub-signature-256` header, of form `sha256=`. */ + signatureHeader: string; + /** Webhook secret as configured in the GitHub repo/org webhook settings. */ + secret: string; +} + +/** Verify a GitHub webhook signature (HMAC-SHA256 of body, hex-encoded). */ +export function verifyGithubSignature(opts: GithubVerifyOpts): VerifyResult { + const prefix = 'sha256='; + if (!opts.signatureHeader.startsWith(prefix)) { + return failed(errors.missingSignature); + } + let candidate: Uint8Array; + try { + candidate = hexToBytes(opts.signatureHeader.slice(prefix.length)); + } catch { + return failed(errors.signatureMismatch); + } + const expected = hmacSha256( + enc.encode(opts.secret), + enc.encode(opts.rawBody) + ); + return timingSafeEqual(expected, candidate) + ? verified + : failed(errors.signatureMismatch); +} diff --git a/spacetime-crypto-ts/tsconfig.build.json b/spacetime-crypto-ts/tsconfig.build.json new file mode 100644 index 00000000000..8635027968f --- /dev/null +++ b/spacetime-crypto-ts/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/spacetime-crypto-ts/tsconfig.json b/spacetime-crypto-ts/tsconfig.json new file mode 100644 index 00000000000..8d86936bedc --- /dev/null +++ b/spacetime-crypto-ts/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "resolveJsonModule": true, + "noUncheckedIndexedAccess": true, + "isolatedModules": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"] +} diff --git a/spacetime-example-ui-ts/.npmrc b/spacetime-example-ui-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-example-ui-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-example-ui-ts/assets/brand.svg b/spacetime-example-ui-ts/assets/brand.svg new file mode 100644 index 00000000000..77cc436631a --- /dev/null +++ b/spacetime-example-ui-ts/assets/brand.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/spacetime-example-ui-ts/assets/logo.svg b/spacetime-example-ui-ts/assets/logo.svg new file mode 100644 index 00000000000..adaf36cbf9c --- /dev/null +++ b/spacetime-example-ui-ts/assets/logo.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/spacetime-example-ui-ts/package.json b/spacetime-example-ui-ts/package.json new file mode 100644 index 00000000000..a14a64a8de3 --- /dev/null +++ b/spacetime-example-ui-ts/package.json @@ -0,0 +1,34 @@ +{ + "name": "@spacetimedb/example-ui", + "description": "Shared UI and server utilities for SpacetimeDB submodule examples.", + "version": "0.1.0", + "private": true, + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./server": { + "types": "./src/server.ts", + "default": "./src/server.ts" + }, + "./styles.css": "./src/styles/index.css" + }, + "scripts": { + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "eslint": "^9.17.0", + "jsdom": "^26.1.0", + "prettier": "^3.3.3", + "typescript": "~5.6.2", + "vitest": "^3.2.4" + } +} diff --git a/spacetime-example-ui-ts/scripts/auth.test.ts b/spacetime-example-ui-ts/scripts/auth.test.ts new file mode 100644 index 00000000000..baf33343274 --- /dev/null +++ b/spacetime-example-ui-ts/scripts/auth.test.ts @@ -0,0 +1,139 @@ +// @vitest-environment jsdom + +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { + authModeCopy, + authUrlState, + clearAuthResultParams, + mountAuthPanel, +} from '../src/auth-panel'; + +beforeEach(() => { + document.body.replaceChildren(); + vi.restoreAllMocks(); +}); + +describe('authModeCopy', () => { + it('returns login copy for the selected product', () => { + expect(authModeCopy('login', 'Grid')).toEqual({ + title: 'Welcome to Grid', + subtitle: 'Sign in to continue.', + submit: 'Sign in', + showEmail: true, + showName: false, + showPassword: true, + showForgot: true, + togglePrompt: "Don't have an account?", + toggleText: 'Sign up', + }); + }); +}); + +describe('authUrlState', () => { + it('reads a password reset token', () => { + expect( + authUrlState({ + pathname: '/auth/password/reset', + search: '?token=reset-123', + }) + ).toEqual({ + mode: 'reset', + resetToken: 'reset-123', + oauthError: undefined, + verified: false, + }); + }); + + it('reads OAuth and verification results', () => { + expect( + authUrlState({ pathname: '/', search: '?error=denied&verified=1' }) + ).toEqual({ + mode: 'login', + resetToken: undefined, + oauthError: 'denied', + verified: true, + }); + }); +}); + +describe('clearAuthResultParams', () => { + it('removes callback results and retains unrelated parameters', () => { + let nextUrl = ''; + clearAuthResultParams( + { pathname: '/notes', search: '?error=denied&verified=1&tab=active' }, + { + replaceState: (_data, _unused, url) => { + nextUrl = String(url); + }, + } + ); + expect(nextUrl).toBe('/notes?tab=active'); + }); +}); + +describe('mountAuthPanel', () => { + it('submits password login through the supplied action', async () => { + const login = vi.fn(async () => undefined); + const root = document.createElement('div'); + document.body.append(root); + mountAuthPanel(root, { + productName: 'Grid', + actions: { + login, + signup: vi.fn(async () => undefined), + forgotPassword: vi.fn(async () => undefined), + resetPassword: vi.fn(async () => undefined), + oauthStart: vi.fn(), + }, + }); + + const email = root.querySelector('input[type="email"]'); + const password = root.querySelector( + 'input[type="password"]' + ); + const form = root.querySelector('form'); + expect(email).not.toBeNull(); + expect(password).not.toBeNull(); + expect(form).not.toBeNull(); + email!.value = 'user@example.com'; + password!.value = 'password-123'; + form!.requestSubmit(); + + await vi.waitFor(() => { + expect(login).toHaveBeenCalledWith({ + email: 'user@example.com', + password: 'password-123', + }); + }); + }); + + it('changes modes and enables configured OAuth providers', () => { + const oauthStart = vi.fn(); + const root = document.createElement('div'); + document.body.append(root); + const panel = mountAuthPanel(root, { + productName: 'Chat', + actions: { + login: vi.fn(async () => undefined), + signup: vi.fn(async () => undefined), + forgotPassword: vi.fn(async () => undefined), + resetPassword: vi.fn(async () => undefined), + oauthStart, + }, + }); + + const google = root.querySelector( + '[data-provider="google"]' + ); + const modeToggle = + root.querySelectorAll('.auth-link')[1]; + expect(google?.disabled).toBe(true); + modeToggle.click(); + expect(root.querySelector('h1')?.textContent).toBe('Create account'); + + panel.setProviders({ google: true }); + expect(google?.disabled).toBe(false); + google?.click(); + expect(oauthStart).toHaveBeenCalledWith('google'); + }); +}); diff --git a/spacetime-example-ui-ts/scripts/server.test.ts b/spacetime-example-ui-ts/scripts/server.test.ts new file mode 100644 index 00000000000..de9df7ebcd8 --- /dev/null +++ b/spacetime-example-ui-ts/scripts/server.test.ts @@ -0,0 +1,65 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { + discardStoredServerToken, + exampleUiAssetsDir, + loadServerToken, + saveServerToken, +} from '../src/server'; + +const temporaryDirectories: string[] = []; + +function temporaryTokenPath(): string { + const directory = mkdtempSync(path.join(tmpdir(), 'stdb-example-ui-')); + temporaryDirectories.push(directory); + return path.join(directory, 'server-token'); +} + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { recursive: true, force: true }); + } +}); + +describe('example server support', () => { + it('resolves the shared SVG assets', () => { + for (const filename of ['brand.svg', 'logo.svg']) { + expect( + readFileSync(path.join(exampleUiAssetsDir, filename), 'utf8') + ).toMatch(/^ { + const tokenPath = temporaryTokenPath(); + writeFileSync(tokenPath, 'stored-token\n'); + + expect(loadServerToken(tokenPath, ' environment-token ')).toEqual({ + token: 'environment-token', + source: 'environment', + }); + }); + + it('saves, loads, and discards a server token', () => { + const tokenPath = temporaryTokenPath(); + + expect(loadServerToken(tokenPath, undefined)).toEqual({ + token: undefined, + source: 'none', + }); + + saveServerToken(tokenPath, ' generated-token '); + expect(loadServerToken(tokenPath, undefined)).toEqual({ + token: 'generated-token', + source: 'file', + }); + + discardStoredServerToken(tokenPath); + expect(loadServerToken(tokenPath, undefined)).toEqual({ + token: undefined, + source: 'none', + }); + }); +}); diff --git a/spacetime-example-ui-ts/src/auth-panel.ts b/spacetime-example-ui-ts/src/auth-panel.ts new file mode 100644 index 00000000000..7718ea23e15 --- /dev/null +++ b/spacetime-example-ui-ts/src/auth-panel.ts @@ -0,0 +1,448 @@ +import { githubIcon, googleIcon, spacetimeMark } from './icons'; + +export type AuthMode = 'login' | 'signup' | 'forgot' | 'reset'; + +export type AuthProviderAvailability = { + google: boolean; + github: boolean; +}; + +export type AuthPanelActions = { + login(args: { email: string; password: string }): Promise; + signup(args: { + email: string; + password: string; + name?: string; + }): Promise; + forgotPassword(email: string): Promise; + resetPassword(token: string, newPassword: string): Promise; + oauthStart(provider: 'google' | 'github'): void; +}; + +export type AuthPanelOptions = { + productName: string; + actions: AuthPanelActions; + logoSrc?: string; + initialMode?: AuthMode; + resetToken?: string; +}; + +export type AuthPanelController = { + destroy(): void; + focus(): void; + setMode(mode: AuthMode, resetToken?: string): void; + setProviders(providers: Partial): void; + showMessage(kind: 'error' | 'success', message: string): void; +}; + +type AuthModeCopy = { + title: string; + subtitle: string; + submit: string; + showEmail: boolean; + showName: boolean; + showPassword: boolean; + showForgot: boolean; + togglePrompt: string; + toggleText: string; +}; + +export function authModeCopy( + mode: AuthMode, + productName: string +): AuthModeCopy { + switch (mode) { + case 'signup': + return { + title: 'Create account', + subtitle: `Create an account to continue to ${productName}.`, + submit: 'Create account', + showEmail: true, + showName: true, + showPassword: true, + showForgot: false, + togglePrompt: 'Already have an account?', + toggleText: 'Sign in', + }; + case 'forgot': + return { + title: 'Reset your password', + subtitle: + 'Enter your email. A reset link will be sent if the account exists.', + submit: 'Send reset email', + showEmail: true, + showName: false, + showPassword: false, + showForgot: false, + togglePrompt: '', + toggleText: 'Back to sign in', + }; + case 'reset': + return { + title: 'Set a new password', + subtitle: 'Enter a new password with at least eight characters.', + submit: 'Reset password', + showEmail: false, + showName: false, + showPassword: true, + showForgot: false, + togglePrompt: '', + toggleText: 'Back to sign in', + }; + case 'login': + return { + title: `Welcome to ${productName}`, + subtitle: 'Sign in to continue.', + submit: 'Sign in', + showEmail: true, + showName: false, + showPassword: true, + showForgot: true, + togglePrompt: "Don't have an account?", + toggleText: 'Sign up', + }; + } +} + +export function authUrlState(location: Pick): { + mode: AuthMode; + resetToken?: string; + oauthError?: string; + verified: boolean; +} { + const params = new URLSearchParams(location.search); + const resetToken = + location.pathname === '/auth/password/reset' + ? (params.get('token') ?? undefined) + : undefined; + return { + mode: resetToken ? 'reset' : 'login', + resetToken, + oauthError: params.get('error') ?? undefined, + verified: params.get('verified') === '1', + }; +} + +export function clearAuthResultParams( + location: Pick, + history: Pick +): void { + const params = new URLSearchParams(location.search); + const hadResult = params.has('error') || params.has('verified'); + if (!hadResult) return; + params.delete('error'); + params.delete('verified'); + const search = params.toString(); + history.replaceState( + {}, + '', + `${location.pathname}${search ? `?${search}` : ''}` + ); +} + +function element( + tag: K, + className?: string +): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + if (className) node.className = className; + return node; +} + +function field( + id: string, + labelText: string, + type: HTMLInputElement['type'], + autocomplete: HTMLInputElement['autocomplete'], + placeholder: string +): { wrapper: HTMLDivElement; input: HTMLInputElement } { + const wrapper = element('div', 'auth-field'); + const label = element('label'); + label.htmlFor = id; + label.textContent = labelText; + const input = element('input'); + input.id = id; + input.type = type; + input.autocomplete = autocomplete; + input.placeholder = placeholder; + wrapper.append(label, input); + return { wrapper, input }; +} + +function oauthButton( + provider: 'google' | 'github', + label: string +): HTMLButtonElement { + const button = element('button', 'btn oauth block'); + button.type = 'button'; + button.dataset.provider = provider; + button.append(provider === 'google' ? googleIcon() : githubIcon(), label); + return button; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +export function mountAuthPanel( + root: HTMLElement, + options: AuthPanelOptions +): AuthPanelController { + const abort = new AbortController(); + let mode = options.initialMode ?? 'login'; + let resetToken = options.resetToken; + let providers: AuthProviderAvailability = { google: false, github: false }; + root.classList.add('example-auth-panel'); + + const form = element('form', 'auth-card'); + + const logoLink = element('a'); + logoLink.href = 'https://spacetimedb.com'; + logoLink.target = '_blank'; + logoLink.rel = 'noopener noreferrer'; + logoLink.className = 'auth-logo-link'; + const logo = options.logoSrc + ? Object.assign(element('img', 'auth-logo'), { + src: options.logoSrc, + alt: 'SpacetimeDB', + }) + : spacetimeMark(); + logoLink.append(logo); + + const title = element('h1'); + const subtitle = element('p', 'auth-sub'); + const oauth = element('div', 'auth-oauth'); + const google = oauthButton('google', 'Continue with Google'); + const github = oauthButton('github', 'Continue with GitHub'); + oauth.append(google, github); + + const divider = element('div', 'auth-divider'); + const dividerText = element('span'); + dividerText.textContent = 'or'; + divider.append(dividerText); + + const email = field( + 'example-auth-email', + 'Email', + 'email', + 'email', + 'you@example.com' + ); + const name = field( + 'example-auth-name', + 'Name (optional)', + 'text', + 'name', + 'Display name' + ); + const password = field( + 'example-auth-password', + 'Password', + 'password', + 'current-password', + '' + ); + password.input.minLength = 8; + + const message = element('p', 'auth-message'); + message.setAttribute('role', 'status'); + message.setAttribute('aria-live', 'polite'); + message.hidden = true; + + const submit = element('button', 'btn primary block'); + submit.type = 'submit'; + + const forgotFoot = element('p', 'auth-foot'); + const forgot = element('button', 'auth-link'); + forgot.type = 'button'; + forgot.textContent = 'Forgot password?'; + forgotFoot.append(forgot); + + const toggleFoot = element('p', 'auth-foot'); + const togglePrompt = element('span'); + const toggle = element('button', 'auth-link'); + toggle.type = 'button'; + toggleFoot.append(togglePrompt, document.createTextNode(' '), toggle); + + form.append( + logoLink, + title, + subtitle, + oauth, + divider, + email.wrapper, + name.wrapper, + password.wrapper, + message, + submit, + forgotFoot, + toggleFoot + ); + root.replaceChildren(form); + + function showMessage(kind: 'error' | 'success', text: string): void { + message.className = `auth-message ${kind}`; + message.textContent = text; + message.hidden = false; + } + + function clearMessage(): void { + message.textContent = ''; + message.hidden = true; + } + + function applyMode(): void { + const copy = authModeCopy(mode, options.productName); + title.textContent = copy.title; + subtitle.textContent = copy.subtitle; + submit.textContent = copy.submit; + email.wrapper.hidden = !copy.showEmail; + email.input.required = copy.showEmail; + name.wrapper.hidden = !copy.showName; + password.wrapper.hidden = !copy.showPassword; + password.input.required = copy.showPassword; + password.input.autocomplete = + mode === 'login' ? 'current-password' : 'new-password'; + password.input.placeholder = mode === 'login' ? '' : 'Minimum 8 characters'; + forgotFoot.hidden = !copy.showForgot; + togglePrompt.textContent = copy.togglePrompt; + toggle.textContent = copy.toggleText; + clearMessage(); + } + + function applyProviders(): void { + for (const [button, enabled, envNames] of [ + [google, providers.google, 'GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET'], + [github, providers.github, 'GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET'], + ] as const) { + button.disabled = !enabled; + button.setAttribute('aria-disabled', String(!enabled)); + button.title = enabled ? '' : `Set ${envNames} in .env`; + } + } + + async function run(action: () => Promise): Promise { + clearMessage(); + submit.disabled = true; + form.setAttribute('aria-busy', 'true'); + try { + await action(); + } catch (error) { + showMessage('error', errorMessage(error)); + } finally { + submit.disabled = false; + form.removeAttribute('aria-busy'); + } + } + + form.addEventListener( + 'submit', + event => { + event.preventDefault(); + void run(async () => { + const emailValue = email.input.value.trim(); + const passwordValue = password.input.value; + if (mode === 'signup') { + await options.actions.signup({ + email: emailValue, + password: passwordValue, + name: name.input.value.trim() || undefined, + }); + return; + } + if (mode === 'forgot') { + await options.actions.forgotPassword(emailValue); + mode = 'login'; + applyMode(); + showMessage( + 'success', + 'If the account exists, a password reset link was sent.' + ); + return; + } + if (mode === 'reset') { + if (!resetToken) throw new Error('auth.missing_reset_token'); + await options.actions.resetPassword(resetToken, passwordValue); + resetToken = undefined; + mode = 'login'; + window.history.replaceState({}, '', '/'); + applyMode(); + showMessage( + 'success', + 'Password reset. Sign in with the new password.' + ); + return; + } + await options.actions.login({ + email: emailValue, + password: passwordValue, + }); + }); + }, + { signal: abort.signal } + ); + + forgot.addEventListener( + 'click', + () => { + mode = 'forgot'; + applyMode(); + email.input.focus(); + }, + { signal: abort.signal } + ); + + toggle.addEventListener( + 'click', + () => { + mode = + mode === 'forgot' || mode === 'reset' + ? 'login' + : mode === 'login' + ? 'signup' + : 'login'; + applyMode(); + email.input.focus(); + }, + { signal: abort.signal } + ); + + for (const button of [google, github]) { + button.addEventListener( + 'click', + () => { + const provider = button.dataset.provider as 'google' | 'github'; + if (!providers[provider]) { + showMessage('error', `${provider} OAuth is not configured.`); + return; + } + options.actions.oauthStart(provider); + }, + { signal: abort.signal } + ); + } + + applyMode(); + applyProviders(); + + return { + destroy() { + abort.abort(); + root.replaceChildren(); + root.classList.remove('example-auth-panel'); + }, + focus() { + (mode === 'reset' ? password.input : email.input).focus(); + }, + setMode(nextMode, nextResetToken) { + mode = nextMode; + resetToken = nextResetToken; + applyMode(); + }, + setProviders(nextProviders) { + providers = { ...providers, ...nextProviders }; + applyProviders(); + }, + showMessage, + }; +} diff --git a/spacetime-example-ui-ts/src/icons.ts b/spacetime-example-ui-ts/src/icons.ts new file mode 100644 index 00000000000..f04ada242fa --- /dev/null +++ b/spacetime-example-ui-ts/src/icons.ts @@ -0,0 +1,51 @@ +export function googleIcon(): SVGSVGElement { + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('aria-hidden', 'true'); + for (const [fill, d] of [ + [ + '#4285F4', + 'M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.76h3.56c2.08-1.92 3.28-4.74 3.28-8.09z', + ], + [ + '#34A853', + 'M12 23c2.97 0 5.46-.98 7.28-2.66l-3.56-2.76c-.98.66-2.24 1.06-3.72 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84A11 11 0 0 0 12 23z', + ], + [ + '#FBBC05', + 'M5.84 14.11A6.6 6.6 0 0 1 5.5 12c0-.73.13-1.44.34-2.11V7.05H2.18A11 11 0 0 0 1 12c0 1.78.43 3.46 1.18 4.95l3.66-2.84z', + ], + [ + '#EA4335', + 'M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1A11 11 0 0 0 2.18 7.05l3.66 2.84C6.71 7.3 9.14 5.38 12 5.38z', + ], + ]) { + const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute('fill', fill); + path.setAttribute('d', d); + svg.append(path); + } + return svg; +} + +export function githubIcon(): SVGSVGElement { + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('fill', 'currentColor'); + svg.setAttribute('aria-hidden', 'true'); + const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute( + 'd', + 'M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.1.79-.25.79-.56v-2c-3.2.7-3.87-1.36-3.87-1.36-.53-1.34-1.3-1.7-1.3-1.7-1.06-.72.08-.7.08-.7 1.17.08 1.79 1.2 1.79 1.2 1.04 1.78 2.73 1.26 3.4.96.11-.75.41-1.26.74-1.55-2.55-.29-5.24-1.28-5.24-5.7 0-1.26.45-2.29 1.19-3.1-.12-.29-.52-1.47.11-3.06 0 0 .97-.31 3.18 1.18a11 11 0 0 1 5.78 0c2.2-1.49 3.18-1.18 3.18-1.18.63 1.59.23 2.77.11 3.06.74.81 1.19 1.84 1.19 3.1 0 4.43-2.7 5.41-5.27 5.69.42.36.79 1.08.79 2.18v3.23c0 .31.21.67.8.56A11.51 11.51 0 0 0 23.5 12C23.5 5.65 18.35.5 12 .5z' + ); + svg.append(path); + return svg; +} + +export function spacetimeMark(): HTMLImageElement { + const image = document.createElement('img'); + image.src = '/assets/logo.svg'; + image.alt = 'SpacetimeDB'; + image.classList.add('auth-logo'); + return image; +} diff --git a/spacetime-example-ui-ts/src/index.ts b/spacetime-example-ui-ts/src/index.ts new file mode 100644 index 00000000000..b23ec22f07d --- /dev/null +++ b/spacetime-example-ui-ts/src/index.ts @@ -0,0 +1,11 @@ +export { + authModeCopy, + authUrlState, + clearAuthResultParams, + mountAuthPanel, + type AuthMode, + type AuthPanelActions, + type AuthPanelController, + type AuthPanelOptions, + type AuthProviderAvailability, +} from './auth-panel'; diff --git a/spacetime-example-ui-ts/src/server.ts b/spacetime-example-ui-ts/src/server.ts new file mode 100644 index 00000000000..c81955b7853 --- /dev/null +++ b/spacetime-example-ui-ts/src/server.ts @@ -0,0 +1,73 @@ +import { spawnSync } from 'node:child_process'; +import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +export const exampleUiAssetsDir = fileURLToPath( + new URL('../assets/', import.meta.url) +); + +export type StoredServerToken = { + token: string | undefined; + source: 'environment' | 'file' | 'none'; +}; + +export function loadServerToken( + tokenPath: string, + environmentToken: string | undefined +): StoredServerToken { + const explicit = environmentToken?.trim(); + if (explicit) return { token: explicit, source: 'environment' }; + if (!existsSync(tokenPath)) return { token: undefined, source: 'none' }; + + const stored = readFileSync(tokenPath, 'utf8').trim(); + return stored + ? { token: stored, source: 'file' } + : { token: undefined, source: 'none' }; +} + +export function saveServerToken(tokenPath: string, token: string): void { + writeFileSync(tokenPath, `${token.trim()}\n`, { + encoding: 'utf8', + mode: 0o600, + }); +} + +export function discardStoredServerToken(tokenPath: string): void { + if (existsSync(tokenPath)) unlinkSync(tokenPath); +} + +export function grantServerIdentity(options: { + spacetimeBin?: string; + server: string; + database: string; + procedure: string; + identity: string; +}): void { + const spacetimeBin = options.spacetimeBin ?? 'spacetime'; + const result = spawnSync( + spacetimeBin, + [ + 'call', + '--server', + options.server, + options.database, + options.procedure, + JSON.stringify(options.identity), + ], + { encoding: 'utf8', shell: false } + ); + + if (result.error) { + throw new Error(`failed to run ${spacetimeBin}: ${result.error.message}`); + } + if (result.status !== 0) { + const detail = result.stderr.trim() || result.stdout.trim(); + throw new Error( + [ + `could not authorize the example server identity with ${options.procedure}`, + detail || `${spacetimeBin} exited ${result.status}`, + 'Publish the database with the currently logged-in CLI identity, then restart the example.', + ].join(': ') + ); + } +} diff --git a/spacetime-example-ui-ts/src/styles/index.css b/spacetime-example-ui-ts/src/styles/index.css new file mode 100644 index 00000000000..dd60f24604d --- /dev/null +++ b/spacetime-example-ui-ts/src/styles/index.css @@ -0,0 +1,253 @@ +:root { + --font-inter: 'Inter Variable', 'Inter', sans-serif; + --font-source: 'Source Code Pro Variable', 'Source Code Pro', monospace; + --font-ibm: 'IBM Plex Mono', monospace; + --color-green: #4cf490; + --color-green-10: #4cf4901a; + --color-green-20: #4cf49033; + --color-green-25: #4cf49040; + --color-green-50: #4cf49080; + --color-green-75: #4cf490bf; + --color-white: #d7d8d9; + --color-yellow: #fbdc8e; + --color-yellow-10: #fbdc8e1a; + --color-yellow-20: #fbdc8e33; + --color-purple: #a880ff; + --color-purple-2: #8a38f5; + --color-orange: #ff9e9e; + --color-blue: #02befa; + --color-blue-10: #02befa1a; + --color-blue-20: #02befa33; + --color-pink: #ff80fb; + --color-teal: #00ccb4; + --color-red: #ff4c4c; + --color-brown: #3b3b3b; + --color-n1: #e6e9f0; + --color-n2: #ced3e0; + --color-n3: #b6c0cf; + --color-n4: #6f7987; + --color-n5: #363840; + --color-n6: #202126; + --color-n7: #050505; + --color-n8: #060606; + --color-shade1: #162d38; + --color-shade2: #122530; + --color-shade3: #122129; + --color-shade4: #121e24; + --color-shade5: #0f191f; + --color-shade6: #0e161a; + --color-shade7: #0b1114; + --color-shade8: #0b0e12; + --color-border: var(--color-shade4); + --color-text: var(--color-n1); + --radius-sm: 6px; + --radius: 10px; + --radius-lg: 14px; +} + +.example-auth-panel { + width: min(380px, 100%); +} + +.auth-card { + box-sizing: border-box; + width: 100%; + padding: 28px; + display: flex; + flex-direction: column; + gap: 12px; + color: var(--color-n1); + background: linear-gradient(180deg, var(--color-shade5), var(--color-shade6)); + border: 1px solid var(--color-shade4); + border-radius: var(--radius-lg); +} + +.auth-logo-link { + display: inline-flex; + align-self: center; +} + +.auth-logo { + width: 56px; + height: 56px; + display: block; +} + +.auth-card h1 { + margin: 0; + color: var(--color-n1); + font-family: var(--font-inter); + font-size: 18px; + line-height: 24px; + text-align: center; +} + +.auth-sub, +.auth-foot, +.auth-message { + margin: 0; + font-family: var(--font-inter); + font-size: 12px; + line-height: 18px; + text-align: center; +} + +.auth-sub, +.auth-foot { + color: var(--color-n4); +} + +.auth-sub { + margin-bottom: 8px; + font-size: 13px; +} + +.auth-oauth, +.auth-field { + display: flex; + flex-direction: column; +} + +.auth-oauth { + gap: 8px; +} + +.auth-field { + gap: 4px; +} + +.auth-field label { + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 10px; + line-height: 14px; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.auth-field input, +.auth-card .btn { + box-sizing: border-box; + width: 100%; + height: 40px; + font-family: var(--font-inter); + font-size: 13px; + font-weight: 600; +} + +.auth-field input { + padding: 0 12px; + color: var(--color-n1); + background: var(--color-shade6); + border: 1px solid var(--color-shade4); + border-radius: var(--radius-sm); + outline: none; +} + +.auth-field input:focus { + border-color: var(--color-green); + box-shadow: 0 0 0 3px var(--color-green-20); +} + +.auth-card .btn { + display: flex; + align-items: center; + justify-content: center; + padding: 0 14px; + border-radius: var(--radius-sm); + cursor: pointer; +} + +.auth-card .btn.oauth { + gap: 10px; + color: var(--color-n1); + background: var(--color-shade7); + border: 1px solid var(--color-shade4); +} + +.auth-card .btn.oauth:hover:not(:disabled) { + background: var(--color-shade4); + border-color: var(--color-n4); +} + +.auth-card .btn.oauth svg { + width: 16px; + height: 16px; + flex-shrink: 0; +} + +.auth-card .btn.primary { + margin-top: 4px; + color: var(--color-n8); + background: var(--color-n3); + border: 2px solid var(--color-n3); +} + +.auth-card .btn.primary:hover:not(:disabled) { + color: var(--color-n8); + background: var(--color-white); + border-color: var(--color-white); +} + +.auth-card .btn:disabled { + cursor: not-allowed; + opacity: 0.45; +} + +.auth-divider { + display: flex; + align-items: center; + gap: 8px; + margin: 4px 0; + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.auth-divider::before, +.auth-divider::after { + height: 1px; + flex: 1; + content: ''; + background: var(--color-shade4); +} + +.auth-link { + padding: 0; + color: var(--color-green); + font: inherit; + font-weight: 600; + background: none; + border: 0; + cursor: pointer; +} + +.auth-link:hover { + text-decoration: underline; +} + +.auth-message { + padding: 8px 10px; + border: 1px solid transparent; + border-radius: var(--radius-sm); +} + +.auth-message.error { + color: var(--color-orange); + background: #ff9e9e12; + border-color: #ff9e9e40; +} + +.auth-message.success { + color: var(--color-green); + background: var(--color-green-10); + border-color: var(--color-green-25); +} + +@media (max-width: 480px) { + .auth-card { + padding: 22px; + } +} diff --git a/spacetime-example-ui-ts/tsconfig.json b/spacetime-example-ui-ts/tsconfig.json new file mode 100644 index 00000000000..20fc11f9205 --- /dev/null +++ b/spacetime-example-ui-ts/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "allowImportingTsExtensions": true, + "isolatedModules": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"] +} diff --git a/spacetime-rate-limit-ts/.npmrc b/spacetime-rate-limit-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-rate-limit-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-rate-limit-ts/LICENSE.txt b/spacetime-rate-limit-ts/LICENSE.txt new file mode 120000 index 00000000000..cc1ff9bdd72 --- /dev/null +++ b/spacetime-rate-limit-ts/LICENSE.txt @@ -0,0 +1 @@ +../licenses/apache2.txt \ No newline at end of file diff --git a/spacetime-rate-limit-ts/README.md b/spacetime-rate-limit-ts/README.md new file mode 100644 index 00000000000..0015dc743c0 --- /dev/null +++ b/spacetime-rate-limit-ts/README.md @@ -0,0 +1,178 @@ +# @spacetimedb/rate-limit + +Limit how often a user or service can perform an action in your SpacetimeDB +application. For example, allow each user to create 10 posts per minute. + +Choose a limit for each action, check it before doing the work, and report how +much capacity remains. Limits reset after a fixed time window, and expired +tracking records are cleaned up automatically. + +## Install + +```bash +npm install @spacetimedb/rate-limit spacetimedb +``` + +## Integrate into an application + +Add Rate Limit to your module and initialize it. This example limits each user +to 10 posts per minute: + +```ts +import { schema, SenderError, t, table } from 'spacetimedb/server'; +import * as rateLimit from '@spacetimedb/rate-limit/submodule'; + +const post = table( + { name: 'post', public: true }, + { + id: t.u64().primaryKey().autoInc(), + author: t.identity(), + body: t.string(), + createdAt: t.timestamp(), + } +); + +const spacetimedb = schema({ + rateLimit, + post, +}); + +export const init = spacetimedb.init(ctx => { + rateLimit.install(ctx.as.rateLimit); +}); + +export default spacetimedb; +``` + +Configure the limit once, then check it in the same transaction that creates +the post. Use the caller's identity or authenticated user ID as the key: + +```ts +const postLimiter = rateLimit.client({ + scope: 'post.create', + limit: 10, + windowSeconds: 60, +}); + +export const createPost = spacetimedb.procedure( + { body: t.string() }, + t.unit(), + (ctx, args) => { + ctx.withTx(tx => { + const actor = ctx.sender.toHexString(); + const result = postLimiter.consume(tx.as.rateLimit, { key: actor }); + if (!result.allowed) throw new SenderError('post.rate_limited'); + const body = args.body.trim(); + if (!body) throw new SenderError('post.empty'); + tx.db.post.insert({ + id: 0n, + author: ctx.sender, + body, + createdAt: ctx.timestamp, + }); + }); + return {}; + } +); +``` + +The generated client calls the product-facing operation: + +```ts +await conn.procedures.createPost({ body: 'Hello' }); +``` + +A view can report the caller's remaining capacity with `peek`: + +```ts +export const postLimitStatus = spacetimedb.view( + { name: 'post_limit_status', public: true }, + t.array( + t.object('PostLimitStatus', { + limit: t.u32(), + windowSeconds: t.u32(), + used: t.u32(), + remaining: t.u32(), + resetAt: t.option(t.timestamp()), + }) + ), + ctx => [postLimiter.peek(ctx.db.rateLimit, ctx.sender.toHexString())] +); +``` + +Mounted as `rateLimit`, the submodule owns these tables: + +- `rate_limit.rate_limit_bucket` +- `rate_limit.rate_limit_admin_identity` +- `rate_limit.rate_limit_config` +- `rate_limit.rate_limit_sweep_tick` + +It also exposes the public admin view `rate_limit.admin_rate_limit_buckets`. +The view returns at most 1,000 rows and returns an empty set to non-admins. + +## API + +`client({ scope, limit, windowSeconds })` configures the policy for one scope. +Each scope can be configured once per module; a second `client` call with the +same scope fails module loading with `rate_limit.duplicate_scope`. +`resetRegisteredScopes()` clears the configured scopes, for example between +tests that configure the same scope again. When a +policy depends on application state, such as an upgrade tier, create one client +per tier with its own scope. +The returned limiter exposes `scope`, `limit`, and `windowSeconds`, plus: + +- `consume(ctx, { key, cost? })` spends `cost` (default 1) from the actor's + bucket in the caller's transaction and returns whether it was allowed, the + remaining capacity, the reset time, and the retry delay. `cost` must be a + positive integer no greater than `limit`; otherwise `consume` throws + `errors.invalidCost`, since the request could never be allowed. +- `peek(db, key, now?)` reads the actor's bucket without spending from it. + Views have no clock, so a view reports an expired window until the sweep + removes it; compare `resetAt` with the current time, or pass `now` from a + reducer or procedure to report an expired window as fresh. + +`key` identifies the actor; the limiter combines it with the scope. Scopes are +at most 128 characters. A key must be 1 to 256 characters; otherwise `consume` +and `peek` throw `errors.invalidActorKey`. + +`install(ctx)` makes the publishing identity the first administrator and +schedules a sweep of expired buckets every 30 seconds. Call it from the host's +`init` reducer. Repeated installation does not add administrators or timers. + +Admin operations: + +- `isAdmin(db, identity)` and `requireAdmin(ctx)` check the submodule's admin + table for host operations that share its administrators. +- `addRateLimitAdmin` and `removeRateLimitAdmin` grant and revoke access. The + last administrator cannot be removed. +- `updateConfig({ sweepBatch })` sets how many expired rows each scheduled sweep + deletes: 500 by default, at most 10,000. +- `runSweep({ maxRows })` deletes expired buckets now, and + `resetBuckets({ maxRows })` deletes buckets regardless of expiry. Both remove + 500 rows by default and accept at most 10,000 per call. + +`errors` holds the stable codes a caller can receive as a `SenderError`: +`notAuthorized`, `cannotRemoveLastAdmin`, `invalidActorKey`, `invalidCost`, +`invalidSweepBatch`, and `invalidMaxRows`. An invalid policy passed to `client` +fails module loading instead. + +Package entrypoints: + +- `@spacetimedb/rate-limit/submodule` supplies the submodule namespace, + `install`, the limiter client, and the admin operations. +- `@spacetimedb/rate-limit` exports `client`, `errors`, and their types. + +See the +[Powerhouse host module](./example/spacetimedb/) +for per-action and per-tier policies, caller-visible status, and admin controls. + +## Testing + +```bash +pnpm test +pnpm run typecheck +``` + +## License + +[Apache-2.0](./LICENSE.txt). diff --git a/spacetime-rate-limit-ts/example/.env.example b/spacetime-rate-limit-ts/example/.env.example new file mode 100644 index 00000000000..e911ba7a27d --- /dev/null +++ b/spacetime-rate-limit-ts/example/.env.example @@ -0,0 +1,4 @@ +HOST=127.0.0.1 +PORT=8792 +STDB_URI=ws://127.0.0.1:3000 +SPACETIMEDB_DB_NAME=spacetime-rate-limit-example diff --git a/spacetime-rate-limit-ts/example/.npmrc b/spacetime-rate-limit-ts/example/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-rate-limit-ts/example/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-rate-limit-ts/example/README.md b/spacetime-rate-limit-ts/example/README.md new file mode 100644 index 00000000000..4e078a5d432 --- /dev/null +++ b/spacetime-rate-limit-ts/example/README.md @@ -0,0 +1,85 @@ +# Powerhouse rate-limit example + +A reactor game that shows how to limit repeated actions. Tap the reactor to +generate energy, buy upgrades, and watch what happens when you act too quickly. + +## Run it locally + +Requires Node.js 20+, pnpm 10, and the SpacetimeDB CLI and server built from +this checkout. + +Start SpacetimeDB in a separate terminal: + +```bash +spacetime start +``` + +From `spacetime-rate-limit-ts/example`, run: + +```bash +pnpm install +pnpm run build:module +pnpm run dev +``` + +Open . + +## Try it + +1. Tap the reactor to generate energy. Watch **Tap Charges** decrease. +2. Keep tapping until you reach the limit. Wait for the charges to refill, then + tap again. +3. Watch the heat meter too. Overheating can stop your taps even when you have + charges left. Heat is a separate game rule. +4. Spend energy on upgrades and try the other actions. They have their own + limits and cooldowns. +5. Open the app in a private browser window to join as another player. Players + have separate tap limits, while the reactor and upgrade purchases are shared. + +## Change the example + +- [spacetimedb/src/index.ts](./spacetimedb/src/index.ts) sets the limits and + checks them when a player acts. +- [spacetimedb/src/reactor-rules.ts](./spacetimedb/src/reactor-rules.ts) defines + the game rules and upgrades. +- [src/app.ts](./src/app.ts) connects the browser to SpacetimeDB. +- [public/ui.js](./public/ui.js) handles the game display and controls. + +After changing the server code, run `pnpm run build:module`. This keeps current +players and upgrades. Restart `pnpm run dev` after changing the browser code. + +To start over, run `pnpm run build:module:fresh`. **This deletes all data in the +local `spacetime-rate-limit-example` database.** + +For instructions on limiting actions in your own app, see the +[Rate Limit integration guide](../README.md#integrate-into-an-application). + +## Configuration + +See [.env.example](./.env.example) to change the database address or web-server +port. The defaults work without a `.env` file. + +## Optional admin controls + +The CLI identity that first publishes the database is its initial administrator. +To grant access to your browser identity, run this command while logged in as +that administrator. Replace `BROWSER_IDENTITY_HEX` with the connected browser's +identity: + +```bash +spacetime call --server local spacetime-rate-limit-example rate_limit.add_rate_limit_admin 0x +``` + +## Before deploying + +This game uses browser identities to distinguish players. In an app with user +accounts, connect the limits to those accounts so a user cannot get a fresh +allowance by opening a new browser session. Keep permission checks on the server; +rate limits do not decide who is allowed to perform an action. + +## Troubleshooting + +- **Taps are rejected:** check both **Tap Charges** and reactor heat. Either can + stop an action. +- **Debug data is empty:** grant your browser identity admin access using the + command above. diff --git a/spacetime-rate-limit-ts/example/package.json b/spacetime-rate-limit-ts/example/package.json new file mode 100644 index 00000000000..040123411dd --- /dev/null +++ b/spacetime-rate-limit-ts/example/package.json @@ -0,0 +1,29 @@ +{ + "name": "spacetime-rate-limit-example", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "spacetime:generate": "spacetime generate --lang typescript --out-dir src/module_bindings/app --module-path ./spacetimedb -y", + "build:module": "pnpm --dir spacetimedb run build && pnpm --dir spacetimedb run publish:local && pnpm run spacetime:generate && pnpm run build:app", + "build:module:fresh": "pnpm --dir spacetimedb run build && pnpm --dir spacetimedb run publish:local:reset && pnpm run spacetime:generate && pnpm run build:app", + "check": "tsc --noEmit", + "test": "tsx scripts/test-reactor-rules.ts", + "build:app": "pnpm run check && esbuild src/app.ts --bundle --format=esm --outfile=public/app.js --target=es2022 --sourcemap", + "build": "pnpm run spacetime:generate && pnpm run build:app", + "dev": "pnpm run build && tsx server.ts" + }, + "dependencies": { + "@spacetimedb/example-ui": "workspace:*", + "dotenv": "^16.4.7", + "express": "^4.21.2", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/express": "^4.17.21", + "@types/node": "^22.10.2", + "esbuild": "^0.28.0", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-rate-limit-ts/example/public/index.html b/spacetime-rate-limit-ts/example/public/index.html new file mode 100644 index 00000000000..17da917c786 --- /dev/null +++ b/spacetime-rate-limit-ts/example/public/index.html @@ -0,0 +1,174 @@ + + + + + + + + + Powerhouse + + + +
+
+
+ SpacetimeDB +
+

Powerhouse

+ Tap the core for energy, buy upgrades, and outproduce the crew. + Don't let it overheat. +
+
+
+ +
+
+
+ + + + 0 +
+ +
+ +
+
+
+ +
+
+
+ Core Heat + 0% · + stable +
+
+
+
+
+ Tap Charges + 8 / 8 · 6s window +
+
+
+
+
+ + +
+ +
+ Built on + SpacetimeDB +
+
+ + + + + diff --git a/spacetime-rate-limit-ts/example/public/styles.css b/spacetime-rate-limit-ts/example/public/styles.css new file mode 100644 index 00000000000..778fdee22cb --- /dev/null +++ b/spacetime-rate-limit-ts/example/public/styles.css @@ -0,0 +1,1310 @@ +:root { + color-scheme: dark; + --demo-panel-height: auto; + --bg: #061013; + --panel: #0b181d; + --panel-2: #0e2028; + --line: #173846; + --line-strong: #24586d; + --text: #f1f7fb; + --muted: #8da8b8; + --accent: #22c7b8; + --accent-2: #ffce5c; + --danger: #ff6a66; + --ok: #52df8f; + --button: #b9c5d4; + font-family: + Inter, + ui-sans-serif, + system-ui, + -apple-system, + BlinkMacSystemFont, + 'Segoe UI', + sans-serif; +} + +* { + box-sizing: border-box; +} + +html, +body { + min-height: 100%; +} + +body { + margin: 0; + min-height: 100dvh; + background: + radial-gradient( + circle at 55% 20%, + rgba(34, 199, 184, 0.09), + transparent 32rem + ), + radial-gradient( + circle at 20% 88%, + rgba(255, 206, 92, 0.07), + transparent 30rem + ), + var(--bg); + color: var(--text); +} + +button, +input { + font: inherit; +} + +button { + border: 1px solid var(--line-strong); + background: #0b1c23; + color: var(--text); + border-radius: 8px; + min-height: 38px; + padding: 0 14px; + font-weight: 800; + cursor: pointer; +} + +button.primary { + background: var(--button); + border-color: var(--button); + color: #020609; +} + +button:disabled { + cursor: not-allowed; + opacity: 0.5; +} + +.shell { + width: min(1180px, calc(100vw - 32px)); + margin: 0 auto; + padding: 16px 0 18px; + display: grid; + grid-template-rows: auto auto auto; + gap: 14px; + align-content: start; +} + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 12px 14px; + border: 1px solid var(--line); + border-radius: 8px; + background: rgba(11, 24, 29, 0.92); + box-shadow: 0 18px 55px rgba(0, 0, 0, 0.24); +} + +.app-title { + display: flex; + align-items: center; + gap: 10px; + font-weight: 900; +} + +.app-title h1 { + margin: 0; + font-size: 18px; + line-height: 1.1; +} + +.app-title-text { + display: flex; + flex-direction: column; + gap: 3px; + min-width: 0; +} + +.app-sub { + color: var(--muted); + font-weight: 600; + font-size: 12px; + line-height: 1.3; +} + +.app-mark { + height: 24px; + width: auto; + display: block; +} + +.brand { + display: flex; + align-items: center; + gap: 10px; + font-weight: 800; +} + +.brand img { + width: 28px; + height: 28px; +} + +.page-foot { + display: flex; + align-items: center; + justify-content: center; + gap: 11px; + margin-top: 0; + padding-top: 12px; + border-top: 1px solid rgba(23, 56, 70, 0.4); +} + +.page-foot .by { + color: #7e9cad; + font: + 800 10px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.12em; + text-transform: uppercase; +} + +.page-foot img { + height: 28px; + width: auto; + opacity: 0.9; +} + +.layout { + display: grid; + grid-template-columns: minmax(420px, 0.95fr) minmax(360px, 1fr); + gap: 14px; + min-height: 0; + margin-top: 0; + align-items: start; +} + +.panel { + border: 1px solid var(--line); + border-radius: 8px; + background: rgba(11, 24, 29, 0.94); +} + +.arena { + height: 640px; + min-height: 0; + padding: 16px; + display: grid; + grid-template-rows: auto minmax(360px, 1fr) auto; + gap: 12px; +} + +.energy-banner { + border: 1px solid rgba(34, 199, 184, 0.26); + border-radius: 8px; + padding: 10px 14px; + background: + linear-gradient(135deg, rgba(34, 199, 184, 0.11), rgba(255, 206, 92, 0.05)), + #08141a; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 16px; + animation: reactor-hum 3.4s ease-in-out infinite; +} + +@keyframes reactor-hum { + 0%, + 100% { + box-shadow: 0 0 0 0 rgba(34, 199, 184, 0); + } + 50% { + box-shadow: 0 0 20px 0 rgba(34, 199, 184, 0.1); + } +} + +.energy-banner.gain strong { + animation: energy-pop 0.34s ease; +} + +@keyframes energy-pop { + 0% { + transform: scale(1); + text-shadow: 0 0 15px rgba(255, 206, 92, 0.14); + } + 35% { + transform: scale(1.045); + text-shadow: 0 0 16px rgba(255, 206, 92, 0.34); + } + 100% { + transform: scale(1); + text-shadow: 0 0 15px rgba(255, 206, 92, 0.14); + } +} + +.energy-banner.gain .energy-icon { + animation: bolt-flicker 0.34s ease; +} + +@keyframes bolt-flicker { + 0% { + filter: drop-shadow(0 0 12px rgba(255, 206, 92, 0.28)); + } + 35% { + filter: drop-shadow(0 0 15px rgba(255, 206, 92, 0.45)) brightness(1.18); + } + 100% { + filter: drop-shadow(0 0 12px rgba(255, 206, 92, 0.28)); + } +} + +.energy-icon { + width: 40px; + height: 40px; + color: var(--accent-2); + filter: drop-shadow(0 0 12px rgba(255, 206, 92, 0.28)); +} + +.energy-icon .icon-bolt { + fill: currentColor; +} + +.color-dot { + width: 22px; + height: 22px; + min-height: 0; + padding: 0; + border-radius: 999px; + border: 2px solid rgba(241, 247, 251, 0.72); + background: var(--player-color, var(--accent)); + box-shadow: + 0 0 0 3px rgba(6, 16, 19, 0.95), + 0 0 18px var(--player-color, var(--accent)); +} + +.color-palette { + position: absolute; + left: 0; + top: calc(100% + 8px); + z-index: 5; + display: none; + grid-template-columns: repeat(4, 22px); + gap: 8px; + padding: 9px; + border: 1px solid var(--line); + border-radius: 8px; + background: #071318; + box-shadow: 0 18px 42px rgba(0, 0, 0, 0.34); +} + +.color-palette.open { + display: grid; +} + +.color-swatch { + width: 22px; + height: 22px; + min-height: 0; + padding: 0; + border-radius: 999px; + border: 1px solid rgba(241, 247, 251, 0.28); + background: var(--swatch); +} + +.energy-banner strong { + display: block; + font-size: clamp(28px, 4vw, 42px); + line-height: 0.95; + letter-spacing: 0; + text-align: right; + transform-origin: right center; + text-shadow: 0 0 15px rgba(255, 206, 92, 0.14); +} + +.reactor-wrap { + position: relative; + display: grid; + place-items: center; + text-align: center; + min-height: 0; + padding: 0; + isolation: isolate; +} + +.reactor-wrap::before, +.reactor-wrap::after { + content: ''; + position: absolute; + border-radius: 999px; + pointer-events: none; + transition: + opacity 220ms ease, + transform 220ms ease, + border-color 220ms ease, + box-shadow 220ms ease; + z-index: 0; +} + +.reactor-wrap::before { + width: min(400px, 72%); + aspect-ratio: 1; + background: radial-gradient( + circle, + rgba(34, 199, 184, 0.18), + rgba(34, 199, 184, 0.06) 38%, + transparent 68% + ); + filter: blur(22px); + opacity: 0.58; + transform: scale(0.94); +} + +.reactor-wrap::after { + width: min(330px, 60%); + aspect-ratio: 1; + border: 1px solid rgba(34, 199, 184, 0.28); + box-shadow: + 0 0 38px rgba(34, 199, 184, 0.12), + inset 0 0 46px rgba(34, 199, 184, 0.08); + opacity: 0.72; +} + +.reactor-wrap.warm::before { + background: radial-gradient( + circle, + rgba(255, 206, 92, 0.2), + rgba(34, 199, 184, 0.08) 38%, + transparent 70% + ); + opacity: 0.72; + transform: scale(1); +} + +.reactor-wrap.warm::after { + border-color: rgba(255, 206, 92, 0.32); + box-shadow: + 0 0 44px rgba(255, 206, 92, 0.16), + inset 0 0 48px rgba(34, 199, 184, 0.08); +} + +.reactor-wrap.critical::before { + background: radial-gradient( + circle, + rgba(255, 106, 102, 0.24), + rgba(255, 206, 92, 0.12) 36%, + transparent 70% + ); + opacity: 0.86; + transform: scale(1.06); +} + +.reactor-wrap.critical::after { + border-color: rgba(255, 106, 102, 0.42); + box-shadow: + 0 0 54px rgba(255, 106, 102, 0.22), + inset 0 0 54px rgba(255, 106, 102, 0.08); +} + +.pop-layer { + position: absolute; + inset: 0; + pointer-events: none; + overflow: visible; + z-index: 3; +} + +.energy-pop { + position: absolute; + left: 50%; + top: 36%; + color: var(--pop-color, var(--accent-2)); + font-weight: 900; + font-size: 24px; + line-height: 1; + padding: 6px 11px; + border: 1px solid + color-mix(in srgb, var(--pop-color, var(--accent-2)) 58%, white 6%); + border-radius: 999px; + background: rgba(4, 13, 17, 0.76); + box-shadow: + 0 0 0 3px rgba(4, 13, 17, 0.56), + 0 0 28px + color-mix(in srgb, var(--pop-color, var(--accent-2)) 58%, transparent); + text-shadow: 0 2px 16px + color-mix(in srgb, var(--pop-color, var(--accent-2)) 65%, transparent); + transform: translate(-50%, -50%); + animation: energyPop 900ms ease-out forwards; + will-change: transform, opacity; +} + +.energy-pop.cooling { + color: var(--pop-color, var(--ok)); + text-shadow: 0 2px 16px rgba(82, 223, 143, 0.45); +} + +.energy-pop.blocked { + color: var(--danger); + border-color: rgba(255, 106, 102, 0.55); + text-shadow: 0 2px 16px rgba(255, 106, 102, 0.45); +} + +.energy-pop.surge-pop { + color: var(--pop-color, var(--accent-2)); + font-size: 22px; + text-shadow: + 0 2px 18px rgba(255, 206, 92, 0.6), + 0 0 34px rgba(255, 106, 102, 0.32); +} + +@keyframes energyPop { + 0% { + opacity: 0; + transform: translate(-50%, -20%) scale(0.82); + } + 18% { + opacity: 1; + transform: translate(calc(-50% + var(--pop-x)), -58%) scale(1.08); + } + 100% { + opacity: 0; + transform: translate(calc(-50% + var(--pop-x)), -150%) scale(0.92); + } +} + +.reactor-button { + width: min(250px, 52vw); + aspect-ratio: 1; + border-radius: 999px; + border: 1px solid rgba(34, 199, 184, 0.45); + background: + radial-gradient( + circle at 50% 48%, + rgba(255, 255, 255, 0.95) 0 3%, + transparent 4% + ), + radial-gradient( + circle at 50% 50%, + #22c7b8 0 13%, + #116d73 14% 34%, + #0b2630 35% 58%, + #071218 59% 100% + ); + box-shadow: + 0 0 0 14px rgba(34, 199, 184, 0.05), + 0 0 80px rgba(34, 199, 184, 0.2), + inset 0 0 50px rgba(255, 255, 255, 0.08); + color: var(--text); + display: grid; + place-items: center; + padding: 0; + transition: + transform 120ms ease, + box-shadow 160ms ease, + filter 160ms ease; + z-index: 1; +} + +.reactor-button:not(:disabled):active { + transform: scale(0.985); +} + +.reactor-button.hot { + border-color: rgba(255, 106, 102, 0.75); + background: + radial-gradient( + circle at 50% 48%, + rgba(255, 255, 255, 0.95) 0 3%, + transparent 4% + ), + radial-gradient( + circle at 50% 50%, + #ffce5c 0 13%, + #b44538 14% 34%, + #311217 35% 58%, + #071218 59% 100% + ); + box-shadow: + 0 0 0 14px rgba(255, 106, 102, 0.06), + 0 0 90px rgba(255, 106, 102, 0.22), + inset 0 0 50px rgba(255, 255, 255, 0.08); +} + +.reactor-copy { + display: grid; + gap: 6px; + padding: 0; +} + +.reactor-copy b { + font-size: clamp(24px, 5vw, 42px); + line-height: 1; + text-shadow: + 0 1px 3px rgba(0, 0, 0, 0.65), + 0 0 26px rgba(2, 10, 14, 0.88); +} + +.reactor-copy span { + color: #d8f5fb; + font: + 800 12px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.08em; + text-transform: uppercase; + text-shadow: + 0 1px 3px rgba(0, 0, 0, 0.7), + 0 0 16px rgba(2, 10, 14, 0.82); +} + +.meter { + display: grid; + gap: 6px; + margin: 0 auto; + max-width: 520px; +} + +.meter + .meter { + margin-top: 10px; +} + +.meter-head { + display: flex; + justify-content: space-between; + color: var(--muted); + font-size: 13px; +} + +.track { + height: 14px; + overflow: hidden; + border: 1px solid var(--line); + border-radius: 999px; + background: #061014; +} + +.fill { + height: 100%; + width: 0%; + background: linear-gradient( + 90deg, + var(--accent), + var(--accent-2), + var(--danger) + ); + transition: width 80ms linear; +} + +.charge-segments { + display: grid; + grid-template-columns: repeat(var(--charge-limit, 8), minmax(0, 1fr)); + gap: 4px; + padding: 3px; + border: 1px solid var(--line); + border-radius: 8px; + background: #061014; +} + +.charge-segment { + height: 12px; + border-radius: 4px; + background: #0b1c23; + border: 1px solid rgba(174, 232, 255, 0.1); +} + +.charge-segment.active { + border-color: rgba(174, 232, 255, 0.35); + background: linear-gradient(180deg, #5ed7ff, #168fc2); + box-shadow: 0 0 10px rgba(94, 215, 255, 0.2); +} + +.systems-dock { + position: absolute; + inset: 0; + pointer-events: none; + z-index: 2; +} + +.system-control { + position: absolute; + width: 128px; + aspect-ratio: 1; + pointer-events: auto; +} + +.system-control:nth-child(1) { + left: calc(50% + 150px); + top: calc(50% - 92px); + transform: translate(-50%, -50%); +} + +.system-control:nth-child(2) { + left: calc(50% - 150px); + top: calc(50% + 92px); + transform: translate(-50%, -50%); +} + +.system-control button { + width: 100%; + height: 100%; + border-radius: 999px; + display: grid; + gap: 4px; + place-items: center; + line-height: 1.15; + padding: 13px; + background: + radial-gradient( + circle at 50% 43%, + rgba(241, 247, 251, 0.1) 0 19%, + transparent 20% + ), + radial-gradient(circle at 50% 50%, #102c35 0 48%, #071419 49% 100%); + color: rgba(241, 247, 251, 0.92); + box-shadow: + inset 0 0 0 1px rgba(205, 245, 255, 0.08), + 0 16px 34px rgba(0, 0, 0, 0.34); + transition: + transform 120ms ease, + filter 160ms ease, + box-shadow 180ms ease; +} + +.system-control button:not(:disabled):active { + transform: scale(0.96); + filter: brightness(1.18); +} + +.system-control button > span { + color: var(--text); + text-shadow: 0 2px 12px rgba(0, 0, 0, 0.74); +} + +.system-control button > span:first-child { + font-size: 15px; + align-self: end; +} + +.system-control button > .button-sub { + align-self: start; + max-width: 102px; + text-align: center; +} + +.system-control button.coolant { + color: #74f0ac; + border-color: rgba(82, 223, 143, 0.62); + box-shadow: + inset 0 0 0 1px rgba(82, 223, 143, 0.13), + 0 16px 34px rgba(0, 0, 0, 0.34), + 0 0 24px rgba(82, 223, 143, 0.1); +} + +.system-control button.surge { + color: #ffdc72; + border-color: rgba(255, 206, 92, 0.68); + box-shadow: + inset 0 0 0 1px rgba(255, 206, 92, 0.14), + 0 16px 34px rgba(0, 0, 0, 0.34), + 0 0 24px rgba(255, 206, 92, 0.12); +} + +.system-control button:disabled { + opacity: 0.52; + filter: saturate(0.45); +} + +.system-control button.fired { + animation: systemFire 520ms ease-out; +} + +@keyframes systemFire { + 0% { + transform: scale(1); + filter: brightness(1); + } + 28% { + transform: scale(1.12); + filter: brightness(1.48); + } + 100% { + transform: scale(1); + filter: brightness(1); + } +} + +.button-sub { + color: rgba(2, 6, 9, 0.68); + font: + 800 10px/1.2 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +button:not(.primary) .button-sub { + color: var(--muted); +} + +.cooldown { + min-height: 18px; + color: var(--muted); + font: + 700 11px/1.4 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.cooldown.blocked { + color: var(--danger); +} + +.side { + height: 640px; + min-height: 0; +} + +.box { + padding: 16px; +} + +.box h2 { + margin: 0; + font-size: 18px; +} + +.sub { + color: var(--muted); + margin-top: 4px; + font-size: 13px; +} + +.console-panel { + height: 100%; + min-height: 0; + display: grid; + grid-template-rows: auto minmax(0, 1fr); + gap: 14px; +} + +.tabs { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 0; + padding: 16px 16px 0; + border-bottom: 1px solid var(--line); +} + +.tab { + min-height: 36px; + padding: 0 4px 10px; + border: 0; + border-radius: 0; + background: transparent; + color: var(--muted); + position: relative; + display: flex; + align-items: center; + justify-content: center; + gap: 7px; + box-shadow: none; +} + +.tab[aria-selected='true'] { + background: transparent; + color: var(--text); +} + +.tab[aria-selected='true']::after { + content: ''; + position: absolute; + left: 18px; + right: 18px; + bottom: -1px; + height: 2px; + border-radius: 999px 999px 0 0; + background: var(--accent); + box-shadow: 0 0 14px rgba(34, 199, 184, 0.35); +} + +.tab:not([aria-selected='true']):hover { + color: #c7dbe4; +} + +.tab-count { + color: var(--muted); + font: + 800 11px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; +} + +.tab[aria-selected='true'] .tab-count { + color: var(--accent-2); +} + +.tab-content { + min-height: 0; + padding: 0 16px 16px; + overflow: hidden; + display: grid; +} + +.tab-pane { + display: none; + height: 100%; + min-height: 0; +} + +.tab-pane.active { + display: grid; + align-content: start; + overflow: auto; +} + +.pane-empty { + align-self: center; + display: grid; + justify-items: center; + align-content: center; + gap: 5px; + min-height: 160px; + padding: 24px 16px; + text-align: center; +} + +.pane-empty b { + color: #c7dbe4; + font-size: 14px; +} + +.pane-empty span { + color: var(--muted); + font-size: 12px; + max-width: 240px; +} + +.pane-spinner { + width: 22px; + height: 22px; + margin-bottom: 6px; + border-radius: 999px; + border: 2px solid var(--line); + border-top-color: var(--accent); + animation: pane-spin 0.8s linear infinite; +} + +@keyframes pane-spin { + to { + transform: rotate(360deg); + } +} + +.shop-list { + display: grid; + gap: 8px; +} + +.shop-item { + border: 1px solid var(--line); + border-radius: 8px; + padding: 11px 12px; + background: #08141a; + display: grid; + grid-template-columns: 38px minmax(0, 1fr) auto; + gap: 12px; + align-items: center; +} + +.shop-item.locked { + opacity: 0.55; +} + +.shop-icon { + width: 38px; + height: 38px; + display: grid; + place-items: center; + border-radius: 8px; + border: 1px solid + color-mix(in srgb, var(--lane, var(--line-strong)) 36%, var(--line)); + background: color-mix(in srgb, var(--lane, var(--accent)) 9%, #071318); + color: var(--lane, var(--accent)); +} + +.shop-icon svg { + width: 20px; + height: 20px; +} + +.shop-head { + min-width: 0; +} + +.shop-title { + display: flex; + align-items: baseline; + gap: 8px; + min-width: 0; +} + +.shop-title b { + font-size: 15px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.shop-level { + flex: none; + color: var(--lane, var(--accent)); + font: + 800 10px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.06em; + text-transform: uppercase; + padding: 2px 6px; + border-radius: 999px; + border: 1px solid + color-mix(in srgb, var(--lane, var(--accent)) 38%, transparent); + background: color-mix(in srgb, var(--lane, var(--accent)) 11%, transparent); +} + +.shop-effect { + display: block; + margin-top: 3px; + color: color-mix(in srgb, var(--lane, var(--accent)) 74%, var(--text)); + font: + 700 12px/1.3 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; +} + +.shop-desc { + margin: 3px 0 0; + color: var(--muted); + font-size: 12px; + line-height: 1.35; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.shop-cost { + margin-top: 8px; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 9px; + align-items: center; +} + +.shop-cost-track { + height: 5px; + overflow: hidden; + border: 1px solid var(--line); + border-radius: 999px; + background: #061014; +} + +.shop-cost-fill { + height: 100%; + width: 0%; + background: color-mix(in srgb, var(--lane, var(--accent)) 52%, #0a1620); + transition: + width 120ms linear, + background 200ms ease, + box-shadow 200ms ease; +} + +.shop-item.affordable .shop-cost-fill { + background: var(--lane, var(--accent)); + box-shadow: 0 0 9px + color-mix(in srgb, var(--lane, var(--accent)) 70%, transparent); +} + +.shop-cost-text { + color: var(--muted); + font: + 700 10px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.03em; + white-space: nowrap; +} + +.shop-item.affordable .shop-cost-text { + color: color-mix(in srgb, var(--lane, var(--accent)) 60%, var(--text)); +} + +.shop-buy-row { + display: grid; + justify-items: end; + align-items: center; +} + +.shop-buy-row button { + min-height: 32px; + width: 96px; + padding: 0 12px; + white-space: nowrap; + transition: transform 110ms ease; +} + +.shop-buy-row button:not(:disabled):hover { + transform: translateY(-1px); +} + +.shop-buy-row button:not(:disabled):active { + transform: translateY(0); +} + +.player-list, +.activity-list { + display: grid; + gap: 8px; + align-content: start; +} + +.player-row { + border: 1px solid var(--line); + border-radius: 8px; + background: #08141a; + padding: 10px 12px; +} + +.activity-row { + min-height: 30px; + display: grid; + grid-template-columns: 54px minmax(0, 1fr) auto; + gap: 10px; + align-items: center; + padding: 5px 0; + border-bottom: 1px solid rgba(23, 56, 70, 0.72); + border-left: 2px solid var(--player-color, transparent); + padding-left: 8px; +} + +.activity-row:last-child { + border-bottom: 0; +} + +.player-row { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + gap: 10px; + align-items: center; + position: relative; +} + +.player-row.current { + border-color: rgba(34, 199, 184, 0.34); +} + +.player-color { + width: 10px; + height: 10px; + border-radius: 999px; + background: var(--player-color, var(--accent)); + box-shadow: 0 0 14px var(--player-color, var(--accent)); +} + +.player-color-wrap { + position: relative; + display: grid; + place-items: center; +} + +.player-color-wrap .color-dot { + width: 10px; + height: 10px; + min-height: 10px; + border-width: 1px; + position: relative; + box-shadow: 0 0 14px var(--player-color, var(--accent)); +} + +.player-color-wrap .color-dot::after { + content: ''; + position: absolute; + inset: -8px; + border-radius: 999px; +} + +.player-palette { + left: -8px; + top: calc(100% + 10px); +} + +.player-meta { + display: flex; + align-items: baseline; + gap: 7px; + min-width: 0; +} + +.self-pill { + color: var(--accent-2); + font: + 800 9px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + text-transform: uppercase; + letter-spacing: 0.08em; +} + +.player-row b, +.activity-row b { + display: block; + font-size: 13px; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.player-row span, +.activity-row span { + color: var(--muted); + font: + 700 11px/1.4 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; +} + +.activity-row time { + color: var(--muted); + font: + 700 11px/1.4 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + white-space: nowrap; +} + +.event-chip { + display: block; + width: 48px; + min-width: 48px; + max-width: 48px; + padding: 4px 0; + border: 1px solid var(--line); + border-radius: 7px; + text-align: center; + color: var(--muted); + background: #071318; + font: + 800 10px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.03em; + text-transform: uppercase; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.event-chip.tap { + border-color: rgba(34, 199, 184, 0.42); + color: #9ef4ea; + background: rgba(34, 199, 184, 0.08); +} + +.event-chip.surge { + border-color: rgba(255, 206, 92, 0.46); + color: #ffdf86; + background: rgba(255, 206, 92, 0.08); +} + +.event-chip.repair { + border-color: rgba(82, 223, 143, 0.44); + color: #a9f5c8; + background: rgba(82, 223, 143, 0.08); +} + +.event-chip.upgrade { + border-color: rgba(174, 232, 255, 0.4); + color: #c9efff; + background: rgba(174, 232, 255, 0.07); +} + +.event-chip.blocked { + border-color: rgba(255, 106, 102, 0.52); + color: #ffaaa7; + background: rgba(255, 106, 102, 0.08); +} + +.player-score { + color: var(--accent-2); + white-space: nowrap; + font: + 800 12px/1.4 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; +} + +@media (max-width: 900px) { + .layout { + grid-template-columns: 1fr; + } + .arena, + .side { + height: auto; + } +} + +@media (max-width: 560px) { + .shell { + width: min(100vw - 16px, 1320px); + } + .topbar { + align-items: flex-start; + flex-direction: column; + } + .reactor-wrap { + min-height: 420px; + } + .console-panel { + min-height: 0; + } + .tabs { + grid-template-columns: 1fr; + } + .system-control:nth-child(1), + .system-control:nth-child(2) { + position: absolute; + left: 50%; + right: auto; + top: auto; + bottom: auto; + transform: translateX(-50%); + } + .system-control:nth-child(1) { + top: 0; + } + .system-control:nth-child(2) { + bottom: 0; + } +} diff --git a/spacetime-rate-limit-ts/example/public/ui.js b/spacetime-rate-limit-ts/example/public/ui.js new file mode 100644 index 00000000000..16e5aa8d461 --- /dev/null +++ b/spacetime-rate-limit-ts/example/public/ui.js @@ -0,0 +1,763 @@ +const state = { + conn: 'connecting', + reactor: null, + events: [], + players: [], + statuses: [], + shop: [], + activeTab: 'shop', + currentIdentityHex: null, + colorPaletteOpen: false, +}; + +const $ = id => document.getElementById(id); +const fmt = new Intl.NumberFormat(); +const COOLANT_UNLOCK_LEVEL = 2; +const SURGE_UNLOCK_LEVEL = 2; +const PLAYER_COLORS = [ + '#22c7b8', + '#ffce5c', + '#52df8f', + '#ff6a66', + '#aee8ff', + '#d28cff', + '#ff9f6e', + '#8ddf65', +]; + +// Upgrade lanes reuse the colors the reactor already assigns to each system: +// amber = power/surge, green = cooling/coolant, cyan = tap charges. +const UPGRADE_LANES = { + power: { + color: 'var(--accent-2)', + count: 'powerUpgradeCount', + icon: '', + }, + cooling: { + color: 'var(--ok)', + count: 'coolingUpgradeCount', + icon: '', + }, + capacity: { + color: '#aee8ff', + count: 'capacityUpgradeCount', + icon: '', + }, + charges: { + color: '#5ed7ff', + count: 'chargeUpgradeCount', + icon: '', + }, + bay: { + color: 'var(--muted)', + count: 'bayUpgradeCount', + icon: '', + }, +}; + +function upgradeLaneColor(id) { + return UPGRADE_LANES[id]?.color ?? 'var(--accent)'; +} + +function upgradeLevel(id) { + const lane = UPGRADE_LANES[id]; + if (!lane) return 0; + return Number(state.reactor?.[lane.count] ?? 0); +} + +function costPercent(energy, cost) { + if (cost <= 0n) return 100; + if (energy >= cost) return 100; + return Number((energy * 100n) / cost); +} + +function microsToMs(ts) { + if (!ts || ts.microsSinceUnixEpoch == null) return 0; + return Number(ts.microsSinceUnixEpoch / 1000n); +} + +function eventTime(ts) { + const ms = microsToMs(ts); + return ms + ? new Date(ms).toLocaleTimeString([], { + hour: 'numeric', + minute: '2-digit', + second: '2-digit', + }) + : ''; +} + +function identityHex(identity) { + if (!identity) return ''; + if (typeof identity.toHexString === 'function') return identity.toHexString(); + return String(identity); +} + +function secondsUntil(ts) { + const ms = microsToMs(ts); + if (!ms) return 0; + return Math.max(0, Math.ceil((ms - Date.now()) / 1000)); +} + +function secondsUntilPrecise(ts) { + const ms = microsToMs(ts); + if (!ms) return 0; + return Math.max(0, (ms - Date.now()) / 1000); +} + +function formatSeconds(seconds) { + if (seconds <= 0) return 'ready'; + return `${seconds.toFixed(1)}s`; +} + +function effectiveReactor(reactor) { + if (!reactor) return null; + const elapsed = Math.max( + 0, + (Date.now() - microsToMs(reactor.updatedAt)) / 1000 + ); + const cooling = Number(reactor.coolingPerSecond ?? 4); + const capacity = Number(reactor.heatCapacity ?? 100); + const heat = Math.max(0, Number(reactor.heat ?? 0) - elapsed * cooling); + return { + ...reactor, + heat, + heatCapacity: capacity, + coolingPerSecond: cooling, + overheated: Boolean(reactor.overheated) && heat > capacity * 0.45, + }; +} + +function coolingText(reactor) { + if (!reactor || reactor.heat <= 0) return 'stable'; + if (reactor.overheated) { + const recoverAt = reactor.heatCapacity * 0.45; + const seconds = + Math.max(0, reactor.heat - recoverAt) / reactor.coolingPerSecond; + return seconds > 0 ? `Cooling ${formatSeconds(seconds)}` : 'safe'; + } + return `cooling ${formatSeconds(reactor.heat / reactor.coolingPerSecond)}`; +} + +function statusByScope(scope) { + return state.statuses.find(row => row.scope === scope); +} + +function effectiveStatus(scope) { + const row = statusByScope(scope); + if (!row) return null; + const seconds = secondsUntilPrecise(row.resetAt); + if (seconds <= 0) { + return { + ...row, + used: 0, + remaining: row.limit, + }; + } + return row; +} + +function isCooling(scope) { + const row = effectiveStatus(scope); + if (!row || row.remaining > 0) return false; + return secondsUntil(row.resetAt) > 0; +} + +function cooldownText(scope) { + const row = effectiveStatus(scope); + if (!row) return ''; + const seconds = secondsUntilPrecise(row.resetAt); + if (row.remaining <= 0 && seconds > 0) { + return scope === 'reactor.tap' + ? `Resets in ${formatSeconds(seconds)}` + : `Ready in ${formatSeconds(seconds)}`; + } + return `${row.remaining}/${row.limit} ready`; +} + +function cooldownButtonText(scope) { + const row = effectiveStatus(scope); + const seconds = secondsUntilPrecise(row?.resetAt); + return seconds > 0 ? formatSeconds(seconds) : 'Wait'; +} + +function tapChargeInfo(scope) { + const row = effectiveStatus(scope); + if (!row) return 'waiting'; + const seconds = secondsUntilPrecise(row.resetAt); + const reset = + seconds > 0 + ? `resets in ${formatSeconds(seconds)}` + : `${row.windowSeconds}s window`; + return `${row.remaining} / ${row.limit} · ${reset}`; +} + +function renderChargeSegments(scope) { + const row = effectiveStatus(scope); + const node = $('tapChargeSegments'); + if (!node) return; + const limit = row?.limit ?? 8; + const remaining = row?.remaining ?? 0; + node.style.setProperty('--charge-limit', String(Math.max(1, limit))); + node.innerHTML = Array.from( + { length: limit }, + (_value, index) => + `` + ).join(''); +} + +function hasCoolantFlush(reactor) { + return Number(reactor?.coolingUpgradeCount ?? 0) >= COOLANT_UNLOCK_LEVEL; +} + +function hasSurgeBurst(reactor) { + return Number(reactor?.powerUpgradeCount ?? 0) >= SURGE_UNLOCK_LEVEL; +} + +function romanLevel(value) { + const numerals = [ + [10, 'X'], + [9, 'IX'], + [5, 'V'], + [4, 'IV'], + [1, 'I'], + ]; + let n = Math.max(1, Math.min(20, Math.trunc(Number(value) || 1))); + let out = ''; + for (const [amount, label] of numerals) { + while (n >= amount) { + out += label; + n -= amount; + } + } + return out; +} + +function surgeLevel(reactor) { + return romanLevel(reactor?.reactorLevel ?? 1); +} + +function coolantLevel(reactor) { + return romanLevel(Math.max(1, Number(reactor?.coolingUpgradeCount ?? 0))); +} + +function surgePreview(reactor) { + const level = reactor?.reactorLevel ?? 1; + const heat = Math.max(28, Math.floor((reactor?.heatCapacity ?? 100) * 0.25)); + return `+${fmt.format(level * 10)} energy
+${heat} heat`; +} + +function coolantAmount(reactor) { + return Math.max(65, Math.floor((reactor?.heatCapacity ?? 100) * 0.55)); +} + +function coolantPreview(reactor) { + return `Vent -${coolantAmount(reactor)} heat`; +} + +function spawnReactorPop(text, kind = '', color = '') { + const layer = $('popLayer'); + const pop = document.createElement('div'); + pop.className = `energy-pop ${kind}`; + pop.textContent = text; + pop.style.setProperty( + '--pop-x', + `${Math.round((Math.random() - 0.5) * 90)}px` + ); + if (color) pop.style.setProperty('--pop-color', color); + layer.appendChild(pop); + window.setTimeout(() => pop.remove(), 850); +} + +function spawnEventPop(event) { + if (!event.allowed) { + if (event.scope === 'reactor.tap') + spawnReactorPop('WAIT', 'blocked', event.actorColor); + return; + } + if (event.energyDelta > 0n) { + const prefix = + event.kind === 'overcharge' || event.kind === 'overcharge_overheated' + ? 'SURGE +' + : '+'; + const kind = + event.kind === 'overcharge' || event.kind === 'overcharge_overheated' + ? 'surge-pop' + : ''; + spawnReactorPop( + `${prefix}${fmt.format(event.energyDelta)}`, + kind, + event.actorColor + ); + return; + } + if (event.kind === 'repair') { + spawnReactorPop('VENT', 'cooling', event.actorColor); + } +} + +function setBusy(button, busy) { + button.dataset.busy = busy ? 'true' : 'false'; +} + +function flashButton(button, allowed) { + button.classList.remove('fired'); + void button.offsetWidth; + if (allowed) button.classList.add('fired'); + window.setTimeout(() => button.classList.remove('fired'), 460); +} + +async function callAction(button, fn) { + if (button.dataset.busy === 'true') return; + if (!window.reactor) throw new Error('reactor.not_ready'); + setBusy(button, true); + try { + const result = await fn(); + flashButton(button, result.allowed); + render(); + } catch (err) { + console.error('reactor action failed', err); + render(); + } finally { + setBusy(button, false); + } +} + +let energyShown = 0; +let energyTarget = 0; +let energyReady = false; +let energyTween = null; +let energyGainTimer = null; + +function pulseEnergyGain() { + const banner = document.querySelector('.energy-banner'); + if (!banner) return; + banner.classList.remove('gain'); + void banner.offsetWidth; + banner.classList.add('gain'); + window.clearTimeout(energyGainTimer); + energyGainTimer = window.setTimeout( + () => banner.classList.remove('gain'), + 460 + ); +} + +function writeEnergy() { + $('energy').textContent = fmt.format(Math.round(energyShown)); +} + +function startEnergyTween() { + if (energyTween != null) return; + energyTween = window.setInterval(() => { + const diff = energyTarget - energyShown; + if (Math.abs(diff) < 0.5) { + energyShown = energyTarget; + writeEnergy(); + window.clearInterval(energyTween); + energyTween = null; + return; + } + energyShown += diff * 0.25; + writeEnergy(); + }, 16); +} + +function setEnergy(value) { + const next = Number(value); + if (!energyReady) { + energyReady = true; + energyShown = next; + energyTarget = next; + writeEnergy(); + return; + } + if (next > energyTarget) pulseEnergyGain(); + energyTarget = next; + if (energyShown !== energyTarget) startEnergyTween(); +} + +function renderStats() { + const reactor = effectiveReactor(state.reactor); + const energy = reactor?.energy ?? 0n; + const level = reactor?.reactorLevel ?? 1; + const capacity = reactor?.heatCapacity ?? 100; + const heat = reactor?.heat ?? 0; + const heatPct = capacity <= 0 ? 0 : (heat / capacity) * 100; + const overheated = Boolean(reactor?.overheated); + const tapCooling = isCooling('reactor.tap'); + + if (reactor) setEnergy(energy); + $('heatText').textContent = `${heat.toFixed(1)} / ${capacity}`; + $('coolText').textContent = coolingText(reactor); + $('heatFill').style.width = `${Math.max(0, Math.min(100, heatPct))}%`; + $('tapChargeInfo').textContent = tapChargeInfo('reactor.tap'); + renderChargeSegments('reactor.tap'); + + $('reactorWrap').classList.toggle('warm', heatPct >= 35 && heatPct < 70); + $('reactorWrap').classList.toggle('critical', overheated || heatPct >= 70); + $('tapBtn').classList.toggle( + 'hot', + overheated || heatPct >= 75 || tapCooling + ); + $('tapBtn').disabled = state.conn !== 'connected' || overheated || tapCooling; + $('reactorLabel').textContent = overheated + ? 'Overheated' + : tapCooling + ? 'No Charges' + : 'Tap'; + $('reactorHint').textContent = overheated + ? coolingText(reactor) + : tapCooling + ? cooldownText('reactor.tap') + : `+${level} energy · +${reactor?.tapHeatGain ?? 13} heat`; +} + +function paneEmpty(title, sub) { + if (state.conn !== 'connected') { + const connecting = + state.conn === 'error' + ? ['Reconnecting', 'Lost the link to SpacetimeDB.'] + : ['Connecting', 'Linking up with SpacetimeDB.']; + return `
${connecting[0]}${connecting[1]}
`; + } + return `
${title}${sub}
`; +} + +function renderShop() { + const reactor = effectiveReactor(state.reactor); + const energy = reactor?.energy ?? 0n; + const upgradeCooling = isCooling('reactor.upgrade'); + const rows = state.shop.filter(item => item.available); + $('shopList').innerHTML = + rows.length === 0 + ? paneEmpty('Loading upgrades', 'Fetching the reactor shop.') + : rows + .map(item => { + const affordable = energy >= item.cost; + const disabled = + state.conn !== 'connected' || upgradeCooling || !affordable; + const buttonText = upgradeCooling + ? cooldownButtonText('reactor.upgrade') + : 'Install'; + const lane = UPGRADE_LANES[item.id]; + const level = upgradeLevel(item.id); + return ` +
+ +
+
${item.name}${level > 0 ? `Lv ${level}` : ''}
+ ${item.effect} +

${item.description}

+
+
+ ${fmt.format(energy)} / ${fmt.format(item.cost)} +
+
+
+ +
+
+ `; + }) + .join(''); +} + +function renderPlayers() { + const rows = state.players ?? []; + $('playerCount').textContent = rows.length.toString(); + $('playerList').innerHTML = + rows.length === 0 + ? paneEmpty('No crew yet', 'Open another tab to bring a pilot online.') + : rows + .map(player => { + const isCurrent = + identityHex(player.identity) === state.currentIdentityHex; + const colorControl = isCurrent + ? `
+ +
+ ${PLAYER_COLORS.map( + swatch => + `` + ).join('')} +
+
` + : ''; + return ` +
+ ${colorControl} +
+
${player.displayName}${isCurrent ? 'You' : ''}
+ ${player.taps} taps · ${player.surges} surges · ${player.coolantUses} vents +
+
${fmt.format(player.contributedEnergy)}
+
+ `; + }) + .join(''); +} + +function activityChip(event) { + if (!event.allowed) return { className: 'blocked', label: 'Wait' }; + if (event.kind === 'tap' || event.kind === 'tap_overheated') + return { className: 'tap', label: 'Tap' }; + if (event.kind === 'overcharge' || event.kind === 'overcharge_overheated') + return { className: 'surge', label: 'Surge' }; + if (event.kind === 'repair') return { className: 'repair', label: 'Vent' }; + if (event.kind === 'upgrade') return { className: 'upgrade', label: 'Shop' }; + return { className: '', label: 'Room' }; +} + +function renderActivity() { + const rows = (state.events ?? []).slice(0, 18); + $('activityCount').textContent = rows.length.toString(); + $('activityList').innerHTML = + rows.length === 0 + ? paneEmpty('No activity yet', 'Tap the core to start the feed.') + : rows + .map(event => { + const delta = + event.energyDelta === 0n + ? '' + : ` ${event.energyDelta > 0n ? '+' : ''}${event.energyDelta.toString()} energy`; + const chip = activityChip(event); + return ` +
+ ${chip.label} + ${event.actorName}${delta} + +
+ `; + }) + .join(''); +} + +function renderTabs() { + $('shopCount').textContent = state.shop.length.toString(); + for (const tab of document.querySelectorAll('[data-tab]')) { + const active = tab.dataset.tab === state.activeTab; + tab.setAttribute('aria-selected', active ? 'true' : 'false'); + } + for (const pane of document.querySelectorAll('[data-pane]')) { + pane.classList.toggle('active', pane.dataset.pane === state.activeTab); + } +} + +function renderSystems() { + const reactor = effectiveReactor(state.reactor); + const heat = reactor?.heat ?? 0; + const overheated = Boolean(reactor?.overheated); + const systems = []; + const coolantUnlocked = hasCoolantFlush(reactor); + const surgeUnlocked = hasSurgeBurst(reactor); + + const repairCooling = isCooling('reactor.repair'); + const useful = overheated || heat >= 35; + if (coolantUnlocked) { + systems.push(` +
+ +
${repairCooling ? cooldownText('reactor.repair') : ''}
+
+ `); + } + + const surgeCooling = isCooling('reactor.overcharge'); + if (surgeUnlocked) { + systems.push(` +
+ +
${surgeCooling ? cooldownText('reactor.overcharge') : ''}
+
+ `); + } + + $('systemDock').innerHTML = systems.join(''); +} + +function updateShopTimers() { + const reactor = effectiveReactor(state.reactor); + const energy = reactor?.energy ?? 0n; + const upgradeCooling = isCooling('reactor.upgrade'); + + for (const item of state.shop.filter(row => row.available)) { + const button = document.querySelector( + `.upgrade-btn[data-upgrade-id="${item.id}"]` + ); + if (button instanceof HTMLButtonElement) { + const affordable = energy >= item.cost; + button.disabled = + state.conn !== 'connected' || upgradeCooling || !affordable; + button.textContent = upgradeCooling + ? cooldownButtonText('reactor.upgrade') + : 'Install'; + + const row = button.closest('.shop-item'); + if (row instanceof HTMLElement) { + row.classList.toggle('affordable', affordable); + const fill = row.querySelector('.shop-cost-fill'); + if (fill instanceof HTMLElement) + fill.style.width = `${costPercent(energy, item.cost)}%`; + const costText = row.querySelector('.shop-cost-text'); + if (costText) + costText.textContent = `${fmt.format(energy)} / ${fmt.format(item.cost)}`; + } + } + } +} + +function updateSystemTimers() { + const reactor = effectiveReactor(state.reactor); + const heat = reactor?.heat ?? 0; + const overheated = Boolean(reactor?.overheated); + + const repairBtn = $('repairBtn'); + if (repairBtn) { + const cooling = isCooling('reactor.repair'); + const useful = overheated || heat >= 35; + repairBtn.disabled = state.conn !== 'connected' || cooling || !useful; + const hint = $('repairHint'); + if (hint) + hint.textContent = cooling + ? cooldownText('reactor.repair') + : coolantPreview(reactor); + const cooldown = $('repairCooldown'); + if (cooldown) { + cooldown.textContent = cooling ? cooldownText('reactor.repair') : ''; + cooldown.classList.toggle('blocked', cooling); + } + } + + const surgeBtn = $('overchargeBtn'); + if (surgeBtn) { + const cooling = isCooling('reactor.overcharge'); + surgeBtn.disabled = state.conn !== 'connected' || overheated || cooling; + const hint = $('overchargeHint'); + if (hint) + hint.innerHTML = overheated + ? 'Core cooling' + : cooling + ? cooldownText('reactor.overcharge') + : surgePreview(reactor); + const cooldown = $('overchargeCooldown'); + if (cooldown) { + cooldown.textContent = cooling ? cooldownText('reactor.overcharge') : ''; + cooldown.classList.toggle('blocked', cooling); + } + } +} + +function render() { + renderStats(); + renderTabs(); + renderShop(); + renderSystems(); + renderPlayers(); + renderActivity(); +} + +function renderLive() { + renderStats(); + updateShopTimers(); + updateSystemTimers(); +} + +function animationLoop() { + renderLive(); + requestAnimationFrame(animationLoop); +} + +window.addEventListener('reactor:connState', ev => { + state.conn = ev.detail.state; + if (ev.detail.detail) { + console.warn('reactor connection state', ev.detail); + } + render(); +}); + +window.addEventListener('reactor:data', ev => { + state.reactor = ev.detail.state; + state.events = ev.detail.events ?? []; + state.players = ev.detail.players ?? []; + state.statuses = ev.detail.statuses ?? []; + state.shop = ev.detail.shop ?? []; + state.currentIdentityHex = ev.detail.currentIdentityHex ?? null; + render(); +}); + +window.addEventListener('reactor:eventInserted', ev => { + spawnEventPop(ev.detail.event); +}); + +window.addEventListener('reactor:ready', () => { + render(); +}); + +$('tapBtn').addEventListener('click', () => + callAction($('tapBtn'), () => window.reactor.tap()) +); +$('playerList').addEventListener('click', ev => { + const target = ev.target instanceof Element ? ev.target : null; + if (!target) return; + + if (target.closest('#crewColorDot')) { + state.colorPaletteOpen = !state.colorPaletteOpen; + renderPlayers(); + return; + } + + const button = target.closest('[data-color]'); + if (!(button instanceof HTMLButtonElement)) return; + const color = button.dataset.color; + if (!color || !window.reactor) return; + state.colorPaletteOpen = false; + window.reactor + .setPlayerColor(color) + .catch(err => console.error('setPlayerColor failed', err)); + renderPlayers(); +}); +document.addEventListener('pointerdown', ev => { + if (!state.colorPaletteOpen) return; + const target = ev.target instanceof Element ? ev.target : null; + if (target?.closest('#crewColorDot, #crewColorPalette')) return; + state.colorPaletteOpen = false; + renderPlayers(); +}); +document.addEventListener('keydown', ev => { + if (ev.key !== 'Escape' || !state.colorPaletteOpen) return; + state.colorPaletteOpen = false; + renderPlayers(); +}); +$('shopList').addEventListener('click', ev => { + const button = + ev.target instanceof Element ? ev.target.closest('.upgrade-btn') : null; + if (button instanceof HTMLButtonElement) { + const upgradeId = button.dataset.upgradeId; + if (upgradeId) + callAction(button, () => window.reactor.buyUpgrade(upgradeId)); + } +}); +document.querySelector('.tabs').addEventListener('click', ev => { + const button = + ev.target instanceof Element ? ev.target.closest('[data-tab]') : null; + if (!(button instanceof HTMLButtonElement)) return; + state.activeTab = button.dataset.tab; + renderTabs(); +}); +$('systemDock').addEventListener('click', ev => { + const button = + ev.target instanceof Element ? ev.target.closest('button') : null; + if (!(button instanceof HTMLButtonElement)) return; + if (button.id === 'repairBtn') + callAction(button, () => window.reactor.repair()); + if (button.id === 'overchargeBtn') + callAction(button, () => window.reactor.overcharge()); +}); +render(); +requestAnimationFrame(animationLoop); diff --git a/spacetime-rate-limit-ts/example/scripts/test-reactor-rules.ts b/spacetime-rate-limit-ts/example/scripts/test-reactor-rules.ts new file mode 100644 index 00000000000..4c97f60d734 --- /dev/null +++ b/spacetime-rate-limit-ts/example/scripts/test-reactor-rules.ts @@ -0,0 +1,52 @@ +import * as assert from 'node:assert/strict'; +import { + COOLANT_UNLOCK_LEVEL, + MAX_BAY_LEVEL, + SURGE_UNLOCK_LEVEL, + hasCoolantFlush, + hasSurgeBurst, + roomTuning, + tapLimitForState, + upgradeAvailable, + upgradeOffer, + upgradeWindowForState, + type UpgradeState, +} from '../spacetimedb/src/reactor-rules'; + +const state: UpgradeState = { + powerUpgradeCount: 0, + coolingUpgradeCount: 0, + capacityUpgradeCount: 0, + chargeUpgradeCount: 0, + bayUpgradeCount: 0, +}; + +assert.deepEqual(roomTuning(state, 1), { + heatCapacity: 100, + coolingPerSecond: 4, + tapHeatGain: 12, +}); +assert.deepEqual(roomTuning(state, 3), { + heatCapacity: 250, + coolingPerSecond: 12, + tapHeatGain: 12, +}); +assert.equal(upgradeOffer(state, 'power').cost, 12n); +assert.equal(tapLimitForState({ chargeUpgradeCount: 2 }), 12); +assert.equal(upgradeWindowForState({ bayUpgradeCount: 99 }), 5); +assert.equal(upgradeWindowForState({ bayUpgradeCount: MAX_BAY_LEVEL }), 5); +assert.equal( + upgradeAvailable({ ...state, bayUpgradeCount: MAX_BAY_LEVEL }, 'bay'), + false +); +assert.equal(upgradeAvailable(state, 'charges'), true); +assert.equal( + hasCoolantFlush({ coolingUpgradeCount: COOLANT_UNLOCK_LEVEL }), + true +); +assert.equal( + hasSurgeBurst({ powerUpgradeCount: SURGE_UNLOCK_LEVEL - 1 }), + false +); + +console.log('reactor rules tests passed'); diff --git a/spacetime-rate-limit-ts/example/server.ts b/spacetime-rate-limit-ts/example/server.ts new file mode 100644 index 00000000000..a869599910a --- /dev/null +++ b/spacetime-rate-limit-ts/example/server.ts @@ -0,0 +1,42 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import express, { type Request, type Response } from 'express'; +import dotenv from 'dotenv'; +import { exampleUiAssetsDir } from '@spacetimedb/example-ui/server'; + +dotenv.config(); + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +const PORT = Number.parseInt(process.env.PORT ?? '8792', 10); +const HOST = process.env.HOST?.trim() || '127.0.0.1'; +const STDB_URI = process.env.STDB_URI ?? 'ws://127.0.0.1:3000'; +const DB_NAME = + process.env.SPACETIMEDB_DB_NAME ?? 'spacetime-rate-limit-example'; + +const app = express(); +app.use(express.json({ limit: '256kb' })); +app.use('/assets', express.static(exampleUiAssetsDir)); +app.use( + express.static(path.join(__dirname, 'public'), { + etag: false, + lastModified: false, + setHeaders(res) { + res.setHeader('Cache-Control', 'no-store'); + }, + }) +); + +app.get('/api/health', (_req: Request, res: Response) => { + res.json({ ok: true, databaseName: DB_NAME }); +}); + +app.get('/api/config', (_req: Request, res: Response) => { + res.json({ spacetimeUri: STDB_URI, databaseName: DB_NAME }); +}); + +app.listen(PORT, HOST, () => { + console.log(`Rate-limit example running at http://${HOST}:${PORT}`); + console.log(` STDB -> ${STDB_URI} (${DB_NAME})`); +}); diff --git a/spacetime-rate-limit-ts/example/spacetimedb/.npmrc b/spacetime-rate-limit-ts/example/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-rate-limit-ts/example/spacetimedb/package.json b/spacetime-rate-limit-ts/example/spacetimedb/package.json new file mode 100644 index 00000000000..a3962a12a79 --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/package.json @@ -0,0 +1,19 @@ +{ + "name": "spacetime-rate-limit-example-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-rate-limit-example", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-rate-limit-example" + }, + "dependencies": { + "@spacetimedb/rate-limit": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts new file mode 100644 index 00000000000..7aa70cfd79c --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts @@ -0,0 +1,1060 @@ +import { t, Range, SenderError } from 'spacetimedb/server'; +import * as rateLimit from '@spacetimedb/rate-limit/submodule'; +import { ScheduleAt, Timestamp } from 'spacetimedb'; +import { + COOLANT_UNLOCK_LEVEL, + MAX_BAY_LEVEL, + MAX_CHARGE_LEVEL, + PLAYER_COLORS, + POWER_PER_UPGRADE, + SURGE_UNLOCK_LEVEL, + hasCoolantFlush, + hasSurgeBurst, + overheatRecoverAt, + playerColor, + playerName, + roomTuning, + tapLimitForState, + upgradeAvailable, + upgradeOffer, + upgradeWindowForState, + type UpgradeLane, +} from './reactor-rules'; +import { + rateLimitEvent, + reactorEvent, + reactorRoomState, + rateLimitDemoSweepTick, + spacetimedb, + type Tx, +} from './schema'; + +const ONE_SECOND_MICROS = 1_000_000n; + +const TAP_SCOPE = 'reactor.tap'; +const OVERCHARGE_SCOPE = 'reactor.overcharge'; +const UPGRADE_SCOPE = 'reactor.upgrade'; +const REPAIR_SCOPE = 'reactor.repair'; +const SHARED_REACTOR_KEY = 'room'; + +const TAP_WINDOW_SECONDS = 6; +const OVERCHARGE_LIMIT = 3; +const OVERCHARGE_WINDOW_SECONDS = 25; +const UPGRADE_LIMIT = 2; +const REPAIR_LIMIT = 1; +const REPAIR_WINDOW_SECONDS = 18; + +// Tap Batteries and Upgrade Bay levels change a policy, so each level has its +// own limiter and scope. Buying a level starts a fresh bucket. +const tapLimiters = Array.from({ length: MAX_CHARGE_LEVEL + 1 }, (_, level) => + rateLimit.client({ + scope: `${TAP_SCOPE}.${level}`, + limit: tapLimitForState({ chargeUpgradeCount: level }), + windowSeconds: TAP_WINDOW_SECONDS, + }) +); +const overchargeLimiter = rateLimit.client({ + scope: OVERCHARGE_SCOPE, + limit: OVERCHARGE_LIMIT, + windowSeconds: OVERCHARGE_WINDOW_SECONDS, +}); +const upgradeLimiters = Array.from({ length: MAX_BAY_LEVEL + 1 }, (_, level) => + rateLimit.client({ + scope: `${UPGRADE_SCOPE}.${level}`, + limit: UPGRADE_LIMIT, + windowSeconds: upgradeWindowForState({ bayUpgradeCount: level }), + }) +); +const repairLimiter = rateLimit.client({ + scope: REPAIR_SCOPE, + limit: REPAIR_LIMIT, + windowSeconds: REPAIR_WINDOW_SECONDS, +}); + +function tapLimiter(state: { chargeUpgradeCount: number } | null) { + return tapLimiters[ + Math.min(state?.chargeUpgradeCount ?? 0, MAX_CHARGE_LEVEL) + ]; +} + +function upgradeLimiter(state: { bayUpgradeCount: number } | null) { + return upgradeLimiters[Math.min(state?.bayUpgradeCount ?? 0, MAX_BAY_LEVEL)]; +} + +const DEFAULT_RETAIN_EVENTS = 2000; +const DEFAULT_EVENT_PRUNE_BATCH = 500; +const DEFAULT_RETAIN_REACTOR_EVENTS = 80; +const ACTIVE_CREW_WINDOW_SECONDS = 60; +const MAX_CREW_SCALING = 6; +const ADMIN_EVENT_VIEW_LIMIT = 1000; + +export default spacetimedb; + +type ReactorStateRow = NonNullable< + ReturnType +>; +type ReactorPlayerRow = NonNullable< + ReturnType +>; + +function takeRows(rows: Iterable, limit: number): T[] { + const result: T[] = []; + for (const row of rows) { + if (result.length >= limit) break; + result.push(row); + } + return result; +} + +const reactorLimitStatusRow = t.object('ReactorLimitStatusRow', { + scope: t.string(), + label: t.string(), + limit: t.u32(), + windowSeconds: t.u32(), + used: t.u32(), + remaining: t.u32(), + resetAt: t.option(t.timestamp()), +}); + +const reactorShopItem = t.object('ReactorShopItemRow', { + slot: t.u32(), + id: t.string(), + name: t.string(), + description: t.string(), + effect: t.string(), + cost: t.u64(), + available: t.bool(), +}); + +const reactorPlayer = t.object('ReactorPlayerRow', { + identity: t.identity(), + displayName: t.string(), + color: t.string(), + contributedEnergy: t.u64(), + taps: t.u32(), + surges: t.u32(), + coolantUses: t.u32(), + upgradesBought: t.u32(), + joinedAt: t.timestamp(), + updatedAt: t.timestamp(), +}); + +const reactorActionResult = t.object('ReactorActionResult', { + allowed: t.bool(), + action: t.string(), + message: t.string(), + energy: t.u64(), + energyDelta: t.i64(), + retryAfterSeconds: t.u32(), + resetAt: t.timestamp(), +}); + +function actorKey(ctx: { sender: { toHexString(): string } }): string { + return ctx.sender.toHexString(); +} + +function clampU32(value: number, min = 0, max = 0xffff_ffff): number { + return Math.max(min, Math.min(max, Math.trunc(value))); +} + +function requireUpgradeLane(value: string): UpgradeLane { + if ( + value === 'power' || + value === 'cooling' || + value === 'capacity' || + value === 'charges' || + value === 'bay' + ) + return value; + throw new SenderError('reactor.invalid_upgrade'); +} + +function activeCrewCount(tx: Tx): number { + const activeAfter = + tx.timestamp.microsSinceUnixEpoch - + BigInt(ACTIVE_CREW_WINDOW_SECONDS) * ONE_SECOND_MICROS; + let count = 0; + for (const _row of tx.db.reactorPlayerState.updatedAt.filter( + new Range({ tag: 'included', value: new Timestamp(activeAfter) }) + )) + count++; + return clampU32(Math.max(1, count), 1, MAX_CREW_SCALING); +} + +function tunedState(tx: Tx, state: ReactorStateRow): ReactorStateRow { + const tuning = roomTuning(state, activeCrewCount(tx)); + const heat = clampU32(state.heat, 0, tuning.heatCapacity); + return { + ...state, + ...tuning, + heat, + overheated: + state.overheated && heat > Math.floor(tuning.heatCapacity * 0.45), + }; +} + +function requirePlayerColor(color: string): string { + if (PLAYER_COLORS.includes(color)) return color; + throw new SenderError('reactor.invalid_player_color'); +} + +function ensurePlayer(tx: Tx): ReactorPlayerRow { + const existing = tx.db.reactorPlayerState.identity.find(tx.sender); + if (existing) return putPlayer(tx, existing); + const created = { + identity: tx.sender, + displayName: playerName(tx.sender), + color: playerColor(tx.sender), + contributedEnergy: 0n, + taps: 0, + surges: 0, + coolantUses: 0, + upgradesBought: 0, + joinedAt: tx.timestamp, + updatedAt: tx.timestamp, + }; + tx.db.reactorPlayerState.insert(created); + return created; +} + +function putPlayer(tx: Tx, player: ReactorPlayerRow): ReactorPlayerRow { + const next = { ...player, updatedAt: tx.timestamp }; + tx.db.reactorPlayerState.identity.update(next); + return next; +} + +function ensureState(tx: Tx): ReactorStateRow { + ensurePlayer(tx); + const existing = tx.db.reactorRoomState.singleton.find(true); + if (existing) return existing; + const tuningBase = { + coolingUpgradeCount: 0, + capacityUpgradeCount: 0, + }; + const tuning = roomTuning(tuningBase, activeCrewCount(tx)); + const created = { + singleton: true, + energy: 0n, + reactorLevel: 1, + upgradeCount: 0, + powerUpgradeCount: 0, + coolingUpgradeCount: 0, + capacityUpgradeCount: 0, + chargeUpgradeCount: 0, + bayUpgradeCount: 0, + combo: 0, + bestCombo: 0, + heat: 0, + heatCapacity: tuning.heatCapacity, + coolingPerSecond: tuning.coolingPerSecond, + tapHeatGain: tuning.tapHeatGain, + overheated: false, + updatedAt: tx.timestamp, + }; + tx.db.reactorRoomState.insert(created); + return created; +} + +function putState(tx: Tx, state: ReactorStateRow): ReactorStateRow { + const next = { ...state, updatedAt: tx.timestamp }; + tx.db.reactorRoomState.singleton.update(next); + return next; +} + +function cooledState(tx: Tx, state: ReactorStateRow): ReactorStateRow { + const tuned = tunedState(tx, state); + const elapsedSeconds = Number( + (tx.timestamp.microsSinceUnixEpoch - tuned.updatedAt.microsSinceUnixEpoch) / + ONE_SECOND_MICROS + ); + if ( + elapsedSeconds <= 0 && + tuned.heat === state.heat && + tuned.heatCapacity === state.heatCapacity && + tuned.coolingPerSecond === state.coolingPerSecond && + tuned.tapHeatGain === state.tapHeatGain && + tuned.overheated === state.overheated + ) + return state; + + const heat = Math.max( + 0, + tuned.heat - Math.max(0, elapsedSeconds) * tuned.coolingPerSecond + ); + const overheated = tuned.overheated && heat > overheatRecoverAt(tuned); + if ( + heat === state.heat && + overheated === state.overheated && + tuned.heatCapacity === state.heatCapacity && + tuned.coolingPerSecond === state.coolingPerSecond && + tuned.tapHeatGain === state.tapHeatGain + ) + return state; + + return putState(tx, { + ...tuned, + heat, + overheated, + }); +} + +function currentState(tx: Tx): ReactorStateRow { + return cooledState(tx, ensureState(tx)); +} + +function pruneRateLimitEvents( + tx: Tx, + retainEvents: number, + pruneBatch: number +): number { + const total = Number(tx.db.rateLimitEvent.count()); + if (total <= retainEvents) return 0; + + const toDelete = Math.min(pruneBatch, total - retainEvents); + let deleted = 0; + for (const row of tx.db.rateLimitEvent.createdAt.filter(new Range())) { + if (deleted >= toDelete) break; + tx.db.rateLimitEvent.delete(row); + deleted++; + } + return deleted; +} + +function pruneReactorEvents(tx: Tx): void { + const rows = [...tx.db.reactorEvent.iter()].sort((a, b) => + a.id < b.id ? -1 : a.id > b.id ? 1 : 0 + ); + const extra = rows.length - DEFAULT_RETAIN_REACTOR_EVENTS; + if (extra <= 0) return; + for (let i = 0; i < extra; i++) tx.db.reactorEvent.delete(rows[i]); +} + +function requirePositive(code: string, value: number): number { + if (value <= 0) throw new SenderError(code); + return value; +} + +function recordLimitHit( + tx: Tx, + limiter: rateLimit.RateLimitClient, + result: rateLimit.RateLimitResult +) { + tx.db.rateLimitEvent.insert({ + id: 0n, + scope: result.scope, + key: result.key, + allowed: result.allowed, + limit: result.limit, + used: result.used, + remaining: result.remaining, + retryAfterSeconds: result.retryAfterSeconds, + windowSeconds: limiter.windowSeconds, + cost: 1, + resetAt: result.resetAt, + createdAt: tx.timestamp, + }); +} + +function recordReactorEvent( + tx: Tx, + args: { + kind: string; + scope: string; + message: string; + allowed: boolean; + energyDelta?: bigint; + retryAfterSeconds?: number; + } +) { + const player = ensurePlayer(tx); + tx.db.reactorEvent.insert({ + id: 0n, + identity: tx.sender, + actorName: player.displayName, + actorColor: player.color, + kind: args.kind, + scope: args.scope, + message: args.message, + allowed: args.allowed, + energyDelta: args.energyDelta ?? 0n, + retryAfterSeconds: args.retryAfterSeconds ?? 0, + createdAt: tx.timestamp, + }); + pruneReactorEvents(tx); +} + +function emptyActionResult(tx: Tx, action: string, message: string) { + const state = currentState(tx); + return { + allowed: true, + action, + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: tx.timestamp, + }; +} + +export const init = spacetimedb.init(ctx => { + rateLimit.install(ctx.as.rateLimit); + if (ctx.db.rateLimitDemoConfig.singleton.find(true) == null) { + ctx.db.rateLimitDemoConfig.insert({ + singleton: true, + retainEvents: DEFAULT_RETAIN_EVENTS, + eventPruneBatch: DEFAULT_EVENT_PRUNE_BATCH, + updatedAt: ctx.timestamp, + }); + } + if (ctx.db.rateLimitDemoSweepTick.count() === 0n) { + ctx.db.rateLimitDemoSweepTick.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.interval(30n * ONE_SECOND_MICROS), + }); + } +}); + +export const reactorState = spacetimedb.view( + { name: 'reactor_state', public: true }, + t.array(reactorRoomState.rowType), + ctx => { + const row = ctx.db.reactorRoomState.singleton.find(true); + return row ? [row] : []; + } +); + +export const reactorEvents = spacetimedb.view( + { name: 'reactor_events', public: true }, + t.array(reactorEvent.rowType), + ctx => + [...ctx.db.reactorEvent.iter()] + .sort((a, b) => (a.id < b.id ? 1 : a.id > b.id ? -1 : 0)) + .slice(0, DEFAULT_RETAIN_REACTOR_EVENTS) +); + +export const reactorPlayers = spacetimedb.view( + { name: 'reactor_players', public: true }, + t.array(reactorPlayer), + ctx => + [...ctx.db.reactorPlayerState.iter()] + .sort((a, b) => { + if (a.contributedEnergy === b.contributedEnergy) + return a.displayName.localeCompare(b.displayName); + return a.contributedEnergy < b.contributedEnergy ? 1 : -1; + }) + .slice(0, 16) +); + +export const reactorLimitStatus = spacetimedb.view( + { name: 'reactor_limit_status', public: true }, + t.array(reactorLimitStatusRow), + ctx => { + const state = ctx.db.reactorRoomState.singleton.find(true); + const db = ctx.db.rateLimit; + const actor = actorKey(ctx); + return [ + { + scope: TAP_SCOPE, + label: 'Tap Coils', + ...tapLimiter(state).peek(db, actor), + }, + { + scope: OVERCHARGE_SCOPE, + label: 'Overcharger', + ...overchargeLimiter.peek(db, actor), + }, + { + scope: UPGRADE_SCOPE, + label: 'Upgrade Bay', + ...upgradeLimiter(state).peek(db, SHARED_REACTOR_KEY), + }, + { + scope: REPAIR_SCOPE, + label: 'Repair Drones', + ...repairLimiter.peek(db, actor), + }, + ]; + } +); + +export const reactorShop = spacetimedb.view( + { name: 'reactor_shop', public: true }, + t.array(reactorShopItem), + ctx => { + const state = ctx.db.reactorRoomState.singleton.find(true); + const base = state ?? { + powerUpgradeCount: 0, + coolingUpgradeCount: 0, + capacityUpgradeCount: 0, + chargeUpgradeCount: 0, + bayUpgradeCount: 0, + }; + return (['power', 'cooling', 'capacity', 'charges', 'bay'] as const).map( + lane => { + const offer = upgradeOffer(base, lane); + return { + slot: offer.slot, + id: offer.id, + name: offer.name, + description: offer.description, + effect: offer.effect, + cost: offer.cost, + available: upgradeAvailable(base, lane), + }; + } + ); + } +); + +export const rateLimitEventsAdmin = spacetimedb.view( + { name: 'rate_limit_events_admin', public: true }, + t.array(rateLimitEvent.rowType), + ctx => + rateLimit.isAdmin(ctx.db.rateLimit, ctx.sender) + ? takeRows(ctx.db.rateLimitEvent.iter(), ADMIN_EVENT_VIEW_LIMIT) + : [] +); + +export const startReactor = spacetimedb.procedure( + {}, + reactorActionResult, + ctx => { + let out: ReturnType | null = null; + ctx.withTx(tx => { + ensurePlayer(tx); + out = emptyActionResult(tx, 'start', 'Reactor online.'); + }); + if (!out) throw new Error('reactor.start_tx_failed'); + return out; + } +); + +export const tapReactor = spacetimedb.procedure( + {}, + reactorActionResult, + ctx => { + const key = actorKey(ctx); + let out: ReturnType | null = null; + ctx.withTx(tx => { + const limiter = tapLimiter(currentState(tx)); + const result = limiter.consume(tx.as.rateLimit, { key }); + recordLimitHit(tx, limiter, result); + const state = currentState(tx); + if (!result.allowed) { + const next = putState(tx, { + ...state, + combo: 0, + }); + const message = `Tap coils cooling for ${result.retryAfterSeconds}s.`; + recordReactorEvent(tx, { + kind: 'tap_rate_limited', + scope: TAP_SCOPE, + message, + allowed: false, + retryAfterSeconds: result.retryAfterSeconds, + }); + out = { + allowed: false, + action: 'tap', + message, + energy: next.energy, + energyDelta: 0n, + retryAfterSeconds: result.retryAfterSeconds, + resetAt: result.resetAt, + }; + return; + } + if (state.overheated) { + const message = 'Core is overheated.'; + recordReactorEvent(tx, { + kind: 'tap_heat_blocked', + scope: TAP_SCOPE, + message, + allowed: false, + }); + out = { + allowed: false, + action: 'tap', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + return; + } + + const gain = BigInt(state.reactorLevel); + const player = ensurePlayer(tx); + const combo = clampU32(state.combo + 1); + const heat = clampU32( + state.heat + state.tapHeatGain, + 0, + state.heatCapacity + ); + const next = putState(tx, { + ...state, + energy: state.energy + gain, + combo, + bestCombo: Math.max(state.bestCombo, combo), + heat, + overheated: heat >= state.heatCapacity, + }); + putPlayer(tx, { + ...player, + contributedEnergy: player.contributedEnergy + gain, + taps: clampU32(player.taps + 1), + }); + const message = + heat >= state.heatCapacity + ? 'Energy gained, but the core overheated.' + : `+${gain.toString()} energy.`; + recordReactorEvent(tx, { + kind: heat >= state.heatCapacity ? 'tap_overheated' : 'tap', + scope: TAP_SCOPE, + message, + allowed: true, + energyDelta: gain, + }); + out = { + allowed: true, + action: 'tap', + message, + energy: next.energy, + energyDelta: gain, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + }); + if (!out) throw new Error('reactor.tap_tx_failed'); + return out; + } +); + +export const overcharge = spacetimedb.procedure( + {}, + reactorActionResult, + ctx => { + let locked: { + allowed: boolean; + action: string; + message: string; + energy: bigint; + energyDelta: bigint; + retryAfterSeconds: number; + resetAt: Tx['timestamp']; + } | null = null; + ctx.withTx(tx => { + const state = currentState(tx); + if (hasSurgeBurst(state)) return; + const message = `Install Plasma Coils level ${SURGE_UNLOCK_LEVEL} to unlock Surge Burst.`; + recordReactorEvent(tx, { + kind: 'system_locked', + scope: OVERCHARGE_SCOPE, + message, + allowed: false, + }); + locked = { + allowed: false, + action: 'overcharge', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: tx.timestamp, + }; + }); + if (locked) return locked; + + const key = actorKey(ctx); + let out: ReturnType | null = null; + ctx.withTx(tx => { + const result = overchargeLimiter.consume(tx.as.rateLimit, { key }); + recordLimitHit(tx, overchargeLimiter, result); + const state = currentState(tx); + if (!result.allowed || state.overheated) { + const message = result.allowed + ? 'Core is still cooling from the last overheat.' + : `Surge vents cooling down for ${result.retryAfterSeconds}s.`; + const next = putState(tx, { + ...state, + combo: 0, + overheated: state.overheated, + }); + recordReactorEvent(tx, { + kind: 'overcharge_blocked', + scope: OVERCHARGE_SCOPE, + message, + allowed: false, + retryAfterSeconds: result.retryAfterSeconds, + }); + out = { + allowed: false, + action: 'overcharge', + message, + energy: next.energy, + energyDelta: 0n, + retryAfterSeconds: result.retryAfterSeconds, + resetAt: result.resetAt, + }; + return; + } + + const gain = BigInt(state.reactorLevel * 10); + const player = ensurePlayer(tx); + const surgeHeat = Math.max(28, Math.floor(state.heatCapacity * 0.25)); + const heat = clampU32(state.heat + surgeHeat, 0, state.heatCapacity); + const combo = clampU32(state.combo + 3); + const next = putState(tx, { + ...state, + energy: state.energy + gain, + combo, + bestCombo: Math.max(state.bestCombo, combo), + heat, + overheated: heat >= state.heatCapacity, + }); + putPlayer(tx, { + ...player, + contributedEnergy: player.contributedEnergy + gain, + surges: clampU32(player.surges + 1), + }); + const message = + heat >= state.heatCapacity + ? `Surge Burst yielded +${gain.toString()} and blew the safeties.` + : `Surge Burst yielded +${gain.toString()} energy.`; + recordReactorEvent(tx, { + kind: + heat >= state.heatCapacity ? 'overcharge_overheated' : 'overcharge', + scope: OVERCHARGE_SCOPE, + message, + allowed: true, + energyDelta: gain, + }); + out = { + allowed: true, + action: 'overcharge', + message, + energy: next.energy, + energyDelta: gain, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + }); + if (!out) throw new Error('reactor.overcharge_tx_failed'); + return out; + } +); + +export const buyUpgrade = spacetimedb.procedure( + { upgradeId: t.string() }, + reactorActionResult, + (ctx, args) => { + const lane = requireUpgradeLane(args.upgradeId); + let out: ReturnType | null = null; + ctx.withTx(tx => { + const state = currentState(tx); + if (!upgradeAvailable(state, lane)) { + throw new SenderError('reactor.upgrade_maxed'); + } + const limiter = upgradeLimiter(state); + const result = limiter.consume(tx.as.rateLimit, { + key: SHARED_REACTOR_KEY, + }); + recordLimitHit(tx, limiter, result); + const offer = upgradeOffer(state, lane); + const cost = offer.cost; + if (!result.allowed) { + const message = `Upgrade bay cooling down for ${result.retryAfterSeconds}s.`; + recordReactorEvent(tx, { + kind: 'upgrade_blocked', + scope: UPGRADE_SCOPE, + message, + allowed: false, + retryAfterSeconds: result.retryAfterSeconds, + }); + out = { + allowed: false, + action: 'upgrade', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: result.retryAfterSeconds, + resetAt: result.resetAt, + }; + return; + } + if (state.energy < cost) { + const message = `Need ${cost.toString()} energy for ${offer.name}.`; + recordReactorEvent(tx, { + kind: 'upgrade_insufficient_energy', + scope: UPGRADE_SCOPE, + message, + allowed: false, + }); + out = { + allowed: false, + action: 'upgrade', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + return; + } + + const player = ensurePlayer(tx); + const upgradeCount = clampU32(state.upgradeCount + 1); + const powerUpgradeCount = + lane === 'power' + ? clampU32(state.powerUpgradeCount + 1) + : state.powerUpgradeCount; + const coolingUpgradeCount = + lane === 'cooling' + ? clampU32(state.coolingUpgradeCount + 1) + : state.coolingUpgradeCount; + const capacityUpgradeCount = + lane === 'capacity' + ? clampU32(state.capacityUpgradeCount + 1) + : state.capacityUpgradeCount; + const chargeUpgradeCount = + lane === 'charges' + ? clampU32(state.chargeUpgradeCount + 1) + : state.chargeUpgradeCount; + const bayUpgradeCount = + lane === 'bay' + ? clampU32(state.bayUpgradeCount + 1) + : state.bayUpgradeCount; + const tuned = tunedState(tx, { + ...state, + upgradeCount, + powerUpgradeCount, + coolingUpgradeCount, + capacityUpgradeCount, + chargeUpgradeCount, + bayUpgradeCount, + reactorLevel: clampU32(1 + powerUpgradeCount * POWER_PER_UPGRADE), + }); + const next = putState(tx, { + ...tuned, + energy: state.energy - cost, + heat: Math.max(0, tuned.heat - 18), + overheated: false, + }); + putPlayer(tx, { + ...player, + upgradesBought: clampU32(player.upgradesBought + 1), + }); + const delta = -cost; + const message = `${offer.name} installed. ${offer.effect}.`; + recordReactorEvent(tx, { + kind: 'upgrade', + scope: UPGRADE_SCOPE, + message, + allowed: true, + energyDelta: delta, + }); + out = { + allowed: true, + action: 'upgrade', + message, + energy: next.energy, + energyDelta: delta, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + }); + if (!out) throw new Error('reactor.upgrade_tx_failed'); + return out; + } +); + +export const repairReactor = spacetimedb.procedure( + {}, + reactorActionResult, + ctx => { + let locked: { + allowed: boolean; + action: string; + message: string; + energy: bigint; + energyDelta: bigint; + retryAfterSeconds: number; + resetAt: Tx['timestamp']; + } | null = null; + ctx.withTx(tx => { + const state = currentState(tx); + if (hasCoolantFlush(state)) return; + const message = `Install Thermal Vents level ${COOLANT_UNLOCK_LEVEL} to unlock Coolant Flush.`; + recordReactorEvent(tx, { + kind: 'system_locked', + scope: REPAIR_SCOPE, + message, + allowed: false, + }); + locked = { + allowed: false, + action: 'repair', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: tx.timestamp, + }; + }); + if (locked) return locked; + + const key = actorKey(ctx); + let out: ReturnType | null = null; + ctx.withTx(tx => { + const result = repairLimiter.consume(tx.as.rateLimit, { key }); + recordLimitHit(tx, repairLimiter, result); + const state = currentState(tx); + if (!result.allowed) { + const message = `Coolant system cooling down for ${result.retryAfterSeconds}s.`; + recordReactorEvent(tx, { + kind: 'repair_blocked', + scope: REPAIR_SCOPE, + message, + allowed: false, + retryAfterSeconds: result.retryAfterSeconds, + }); + out = { + allowed: false, + action: 'repair', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: result.retryAfterSeconds, + resetAt: result.resetAt, + }; + return; + } + + const next = putState(tx, { + ...state, + combo: 0, + heat: Math.max( + 0, + state.heat - Math.max(65, Math.floor(state.heatCapacity * 0.55)) + ), + overheated: false, + }); + const player = ensurePlayer(tx); + putPlayer(tx, { + ...player, + coolantUses: clampU32(player.coolantUses + 1), + }); + const message = 'Coolant flushed.'; + recordReactorEvent(tx, { + kind: 'repair', + scope: REPAIR_SCOPE, + message, + allowed: true, + }); + out = { + allowed: true, + action: 'repair', + message, + energy: next.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + }); + if (!out) throw new Error('reactor.repair_tx_failed'); + return out; + } +); + +export const runSweep = spacetimedb.procedure( + { maxRows: t.option(t.u32()) }, + t.u32(), + (ctx, args) => { + const deleted = rateLimit.runSweep(ctx.as.rateLimit, { + maxRows: args.maxRows, + }); + ctx.withTx(tx => { + const demo = tx.db.rateLimitDemoConfig.singleton.find(true); + const retainEvents = Number(demo?.retainEvents ?? DEFAULT_RETAIN_EVENTS); + const pruneBatch = Number( + demo?.eventPruneBatch ?? DEFAULT_EVENT_PRUNE_BATCH + ); + pruneRateLimitEvents(tx, retainEvents, pruneBatch); + }); + return deleted; + } +); + +export const setPlayerColor = spacetimedb.reducer( + { color: t.string() }, + (ctx, args) => { + const color = requirePlayerColor(args.color); + const player = ensurePlayer(ctx); + putPlayer(ctx, { + ...player, + color, + }); + } +); + +export const resetDemo = spacetimedb.reducer({}, ctx => { + rateLimit.requireAdmin(ctx.as.rateLimit); + rateLimit.resetBuckets(ctx.as.rateLimit, {}); + for (const row of ctx.db.rateLimitEvent.iter()) + ctx.db.rateLimitEvent.delete(row); + for (const row of ctx.db.reactorEvent.iter()) ctx.db.reactorEvent.delete(row); + for (const row of ctx.db.reactorPlayerState.iter()) + ctx.db.reactorPlayerState.delete(row); + for (const row of ctx.db.reactorRoomState.iter()) + ctx.db.reactorRoomState.delete(row); +}); + +export const updateConfig = spacetimedb.reducer( + { + sweepBatch: t.option(t.u32()), + retainEvents: t.option(t.u32()), + eventPruneBatch: t.option(t.u32()), + }, + (ctx, args) => { + rateLimit.requireAdmin(ctx.as.rateLimit); + if (args.sweepBatch !== undefined) { + rateLimit.updateConfig(ctx.as.rateLimit, { sweepBatch: args.sweepBatch }); + } + if (args.retainEvents !== undefined || args.eventPruneBatch !== undefined) { + const demo = ctx.db.rateLimitDemoConfig.singleton.find(true); + if (!demo) throw new Error('reactor.demo_config_missing'); + ctx.db.rateLimitDemoConfig.singleton.update({ + ...demo, + retainEvents: + args.retainEvents === undefined + ? demo.retainEvents + : requirePositive( + 'reactor.invalid_retain_events', + args.retainEvents + ), + eventPruneBatch: + args.eventPruneBatch === undefined + ? demo.eventPruneBatch + : requirePositive( + 'reactor.invalid_event_prune_batch', + args.eventPruneBatch + ), + updatedAt: ctx.timestamp, + }); + } + } +); + +export const rateLimitDemoSweep = spacetimedb.reducer( + { onSchedule: rateLimitDemoSweepTick }, + { arg: rateLimitDemoSweepTick.rowType }, + (ctx, _args) => { + const demo = ctx.db.rateLimitDemoConfig.singleton.find(true); + const retainEvents = Number(demo?.retainEvents ?? DEFAULT_RETAIN_EVENTS); + const pruneBatch = Number( + demo?.eventPruneBatch ?? DEFAULT_EVENT_PRUNE_BATCH + ); + pruneRateLimitEvents(ctx, retainEvents, pruneBatch); + } +); diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/model.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/model.ts new file mode 100644 index 00000000000..bf9e2bf316c --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/model.ts @@ -0,0 +1,74 @@ +import { table, t } from 'spacetimedb/server'; + +export const rateLimitEvent = table( + { name: 'rate_limit_event', public: false }, + { + id: t.u64().primaryKey().autoInc(), + scope: t.string().index(), + key: t.string(), + allowed: t.bool().index(), + limit: t.u32(), + used: t.u32(), + remaining: t.u32(), + retryAfterSeconds: t.u32(), + windowSeconds: t.u32(), + cost: t.u32(), + resetAt: t.timestamp(), + createdAt: t.timestamp().index(), + } +); +export const reactorRoomState = table( + { name: 'reactor_room_state', public: false }, + { + singleton: t.bool().primaryKey(), + energy: t.u64(), + reactorLevel: t.u32(), + upgradeCount: t.u32(), + powerUpgradeCount: t.u32(), + coolingUpgradeCount: t.u32(), + capacityUpgradeCount: t.u32(), + chargeUpgradeCount: t.u32(), + bayUpgradeCount: t.u32(), + combo: t.u32(), + bestCombo: t.u32(), + heat: t.u32(), + heatCapacity: t.u32(), + coolingPerSecond: t.u32(), + tapHeatGain: t.u32(), + overheated: t.bool(), + updatedAt: t.timestamp(), + } +); + +export const reactorPlayerState = table( + { name: 'reactor_player_state', public: false }, + { + identity: t.identity().primaryKey(), + displayName: t.string(), + color: t.string(), + contributedEnergy: t.u64(), + taps: t.u32(), + surges: t.u32(), + coolantUses: t.u32(), + upgradesBought: t.u32(), + joinedAt: t.timestamp(), + updatedAt: t.timestamp().index(), + } +); + +export const reactorEvent = table( + { name: 'reactor_event', public: false }, + { + id: t.u64().primaryKey().autoInc(), + identity: t.identity().index(), + actorName: t.string(), + actorColor: t.string(), + kind: t.string().index(), + scope: t.string(), + message: t.string(), + allowed: t.bool().index(), + energyDelta: t.i64(), + retryAfterSeconds: t.u32(), + createdAt: t.timestamp().index(), + } +); diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/reactor-rules.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/reactor-rules.ts new file mode 100644 index 00000000000..d7ebe38ec27 --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/reactor-rules.ts @@ -0,0 +1,231 @@ +export const TAP_LIMIT = 8; +export const UPGRADE_WINDOW_SECONDS = 20; +export const COOLANT_UNLOCK_LEVEL = 2; +export const SURGE_UNLOCK_LEVEL = 2; + +const BASE_HEAT_CAPACITY = 100; +const BASE_HEAT_COOL_PER_SECOND = 4; +const BASE_TAP_HEAT_GAIN = 12; +const MAX_CREW_SCALING = 6; +const HEAT_CAPACITY_PER_EXTRA_CREW = 75; +const COOLING_PER_EXTRA_CREW = 4; +const POWER_UPGRADE_BASE_COST = 12; +const COOLING_UPGRADE_BASE_COST = 16; +const CAPACITY_UPGRADE_BASE_COST = 14; +const CHARGE_UPGRADE_BASE_COST = 18; +const BAY_UPGRADE_BASE_COST = 20; +const POWER_UPGRADE_COST_STEP = 18; +const COOLING_UPGRADE_COST_STEP = 18; +const CAPACITY_UPGRADE_COST_STEP = 20; +const CHARGE_UPGRADE_COST_STEP = 22; +const BAY_UPGRADE_COST_STEP = 24; +export const POWER_PER_UPGRADE = 1; +const COOLING_PER_UPGRADE = 2; +const CAPACITY_PER_UPGRADE = 30; +const CHARGES_PER_UPGRADE = 2; +const UPGRADE_WINDOW_REDUCTION_SECONDS = 3; +const MIN_UPGRADE_WINDOW_SECONDS = 5; +// Each level of these lanes has its own rate-limit policy, so they are capped. +export const MAX_CHARGE_LEVEL = 5; +export const MAX_BAY_LEVEL = + (UPGRADE_WINDOW_SECONDS - MIN_UPGRADE_WINDOW_SECONDS) / + UPGRADE_WINDOW_REDUCTION_SECONDS; + +export const PLAYER_COLORS = [ + '#22c7b8', + '#ffce5c', + '#52df8f', + '#ff6a66', + '#aee8ff', + '#d28cff', + '#ff9f6e', + '#8ddf65', +]; + +export type UpgradeLane = 'power' | 'cooling' | 'capacity' | 'charges' | 'bay'; + +export interface UpgradeState { + powerUpgradeCount: number; + coolingUpgradeCount: number; + capacityUpgradeCount: number; + chargeUpgradeCount: number; + bayUpgradeCount: number; +} + +export interface UpgradeOffer { + slot: number; + id: UpgradeLane; + name: string; + description: string; + effect: string; + cost: bigint; + level: number; +} + +function upgradeLevel(state: UpgradeState, lane: UpgradeLane): number { + if (lane === 'power') return Number(state.powerUpgradeCount); + if (lane === 'cooling') return Number(state.coolingUpgradeCount); + if (lane === 'charges') return Number(state.chargeUpgradeCount); + if (lane === 'bay') return Number(state.bayUpgradeCount); + return Number(state.capacityUpgradeCount); +} + +function upgradeCost(lane: UpgradeLane, level: number): bigint { + if (lane === 'power') + return BigInt(POWER_UPGRADE_BASE_COST + level * POWER_UPGRADE_COST_STEP); + if (lane === 'cooling') + return BigInt( + COOLING_UPGRADE_BASE_COST + level * COOLING_UPGRADE_COST_STEP + ); + if (lane === 'charges') + return BigInt(CHARGE_UPGRADE_BASE_COST + level * CHARGE_UPGRADE_COST_STEP); + if (lane === 'bay') + return BigInt(BAY_UPGRADE_BASE_COST + level * BAY_UPGRADE_COST_STEP); + return BigInt( + CAPACITY_UPGRADE_BASE_COST + level * CAPACITY_UPGRADE_COST_STEP + ); +} + +export function upgradeWindowForState( + state: Pick | null | undefined +): number { + const level = Number(state?.bayUpgradeCount ?? 0); + return Math.max( + MIN_UPGRADE_WINDOW_SECONDS, + UPGRADE_WINDOW_SECONDS - level * UPGRADE_WINDOW_REDUCTION_SECONDS + ); +} + +export function upgradeAvailable( + state: UpgradeState, + lane: UpgradeLane +): boolean { + const level = upgradeLevel(state, lane); + if (lane === 'charges') return level < MAX_CHARGE_LEVEL; + if (lane === 'bay') return level < MAX_BAY_LEVEL; + return true; +} + +export function upgradeOffer( + state: UpgradeState, + lane: UpgradeLane +): UpgradeOffer { + const level = upgradeLevel(state, lane); + if (lane === 'power') { + return { + slot: 0, + id: lane, + name: 'Plasma Coils', + description: + level + 1 === SURGE_UNLOCK_LEVEL + ? 'More tap energy. Unlocks Surge Burst.' + : level >= SURGE_UNLOCK_LEVEL + ? 'More tap energy. Stronger surges.' + : 'More energy per tap.', + effect: `+${POWER_PER_UPGRADE} energy per tap${level + 1 === SURGE_UNLOCK_LEVEL ? ' + unlock Surge Burst' : ''}`, + cost: upgradeCost(lane, level), + level, + }; + } + if (lane === 'cooling') { + return { + slot: 1, + id: lane, + name: 'Thermal Vents', + description: + level + 1 === COOLANT_UNLOCK_LEVEL + ? 'Faster cooling. Unlocks Coolant Flush.' + : level >= COOLANT_UNLOCK_LEVEL + ? 'Faster cooling. Quicker Coolant recharge.' + : 'Faster passive cooling.', + effect: `+${COOLING_PER_UPGRADE} cooling / sec${level + 1 === COOLANT_UNLOCK_LEVEL ? ' + unlock Coolant Flush' : ''}`, + cost: upgradeCost(lane, level), + level, + }; + } + if (lane === 'charges') { + return { + slot: 3, + id: lane, + name: 'Tap Batteries', + description: 'More taps before a recharge.', + effect: `+${CHARGES_PER_UPGRADE} tap charges`, + cost: upgradeCost(lane, level), + level, + }; + } + if (lane === 'bay') { + return { + slot: 4, + id: lane, + name: 'Upgrade Bay', + description: 'Shorter cooldown between installs.', + effect: `-${UPGRADE_WINDOW_REDUCTION_SECONDS}s shop cooldown`, + cost: upgradeCost(lane, level), + level, + }; + } + return { + slot: 2, + id: lane, + name: 'Heat Sinks', + description: 'More heat before the core overheats.', + effect: `+${CAPACITY_PER_UPGRADE} heat capacity`, + cost: upgradeCost(lane, level), + level, + }; +} + +export function tapLimitForState( + state: Pick +): number { + return TAP_LIMIT + Number(state.chargeUpgradeCount) * CHARGES_PER_UPGRADE; +} + +export function hasCoolantFlush( + state: Pick +): boolean { + return state.coolingUpgradeCount >= COOLANT_UNLOCK_LEVEL; +} + +export function hasSurgeBurst( + state: Pick +): boolean { + return state.powerUpgradeCount >= SURGE_UNLOCK_LEVEL; +} + +export function overheatRecoverAt(state: { heatCapacity: number }): number { + return Math.floor(state.heatCapacity * 0.45); +} + +export function roomTuning( + state: Pick, + activeCrew: number +): { heatCapacity: number; coolingPerSecond: number; tapHeatGain: number } { + const crew = Math.max(1, Math.min(MAX_CREW_SCALING, Math.trunc(activeCrew))); + const clampU32 = (value: number) => + Math.max(0, Math.min(0xffff_ffff, Math.trunc(value))); + return { + heatCapacity: clampU32( + BASE_HEAT_CAPACITY + + Number(state.capacityUpgradeCount) * CAPACITY_PER_UPGRADE + + Math.max(0, crew - 1) * HEAT_CAPACITY_PER_EXTRA_CREW + ), + coolingPerSecond: clampU32( + BASE_HEAT_COOL_PER_SECOND + + Number(state.coolingUpgradeCount) * COOLING_PER_UPGRADE + + Math.max(0, crew - 1) * COOLING_PER_EXTRA_CREW + ), + tapHeatGain: BASE_TAP_HEAT_GAIN, + }; +} + +export function playerName(identity: { toHexString(): string }): string { + return `Crewmate ${identity.toHexString().slice(0, 6).toUpperCase()}`; +} + +export function playerColor(identity: { toHexString(): string }): string { + const hex = identity.toHexString().slice(-8); + const index = Number.parseInt(hex, 16) % PLAYER_COLORS.length; + return PLAYER_COLORS[index]!; +} diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/schema.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/schema.ts new file mode 100644 index 00000000000..0e8d8e1e93a --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/schema.ts @@ -0,0 +1,52 @@ +import * as rateLimit from '@spacetimedb/rate-limit/submodule'; +import { + schema, + table, + t, + type InferSchema, + type ReducerCtx, +} from 'spacetimedb/server'; +import { + rateLimitEvent, + reactorEvent, + reactorPlayerState, + reactorRoomState, +} from './model'; + +export { + rateLimitEvent, + reactorEvent, + reactorPlayerState, + reactorRoomState, +} from './model'; + +export const rateLimitDemoConfig = table( + { name: 'rate_limit_demo_config', public: true }, + { + singleton: t.bool().primaryKey(), + retainEvents: t.u32(), + eventPruneBatch: t.u32(), + updatedAt: t.timestamp(), + } +); + +export const rateLimitDemoSweepTick = table( + { name: 'rate_limit_demo_sweep_tick' }, + { + scheduledId: t.u64().primaryKey().autoInc(), + scheduledAt: t.scheduleAt(), + } +); + +export const spacetimedb = schema({ + rateLimit, + rateLimitEvent, + reactorRoomState, + reactorPlayerState, + reactorEvent, + rateLimitDemoConfig, + rateLimitDemoSweepTick, +}); + +export type Schema = InferSchema; +export type Tx = ReducerCtx; diff --git a/spacetime-rate-limit-ts/example/spacetimedb/tsconfig.json b/spacetime-rate-limit-ts/example/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..48cc3989f52 --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src"] +} diff --git a/spacetime-rate-limit-ts/example/src/app.ts b/spacetime-rate-limit-ts/example/src/app.ts new file mode 100644 index 00000000000..817eccd57df --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/app.ts @@ -0,0 +1,436 @@ +import { + DbConnection, + tables, + type ErrorContext, + type EventContext, +} from './module_bindings/app/index.ts'; + +type TimestampLike = { microsSinceUnixEpoch: bigint }; + +type ReactorState = { + singleton: boolean; + energy: bigint; + reactorLevel: number; + upgradeCount: number; + powerUpgradeCount: number; + coolingUpgradeCount: number; + capacityUpgradeCount: number; + chargeUpgradeCount: number; + bayUpgradeCount: number; + combo: number; + bestCombo: number; + heat: number; + heatCapacity: number; + coolingPerSecond: number; + tapHeatGain: number; + overheated: boolean; + updatedAt: TimestampLike; +}; + +type ReactorEvent = { + id: bigint; + identity: unknown; + actorName: string; + actorColor: string; + kind: string; + scope: string; + message: string; + allowed: boolean; + energyDelta: bigint; + retryAfterSeconds: number; + createdAt: TimestampLike; +}; + +type ReactorPlayer = { + identity: unknown; + displayName: string; + color: string; + contributedEnergy: bigint; + taps: number; + surges: number; + coolantUses: number; + upgradesBought: number; + joinedAt: TimestampLike; + updatedAt: TimestampLike; +}; + +type ReactorLimitStatus = { + scope: string; + label: string; + limit: number; + windowSeconds: number; + used: number; + remaining: number; + resetAt?: TimestampLike; +}; + +type ReactorShopItem = { + slot: number; + id: string; + name: string; + description: string; + effect: string; + cost: bigint; + available: boolean; +}; + +type RateLimitDemoConfig = { + singleton: boolean; + retainEvents: number; + eventPruneBatch: number; + updatedAt: TimestampLike; +}; + +type ReactorActionResult = { + allowed: boolean; + action: string; + message: string; + energy: bigint; + energyDelta: bigint; + retryAfterSeconds: number; + resetAt: TimestampLike; +}; + +type ReactorActions = { + start: () => Promise; + tap: () => Promise; + overcharge: () => Promise; + buyUpgrade: (upgradeId: string) => Promise; + repair: () => Promise; + setPlayerColor: (color: string) => Promise; + runSweep: (maxRows?: number) => Promise; + resetDemo: () => Promise; + updateConfig: (args: { + sweepBatch?: number; + retainEvents?: number; + eventPruneBatch?: number; + }) => Promise; +}; + +declare global { + interface Window { + reactor?: ReactorActions; + } +} + +interface ServerConfig { + spacetimeUri: string; + databaseName: string; +} + +type TableEvents = { + iter(): Iterable; + onInsert(cb: (ctx: EventContext, row: T) => void): void; + onUpdate(cb: (ctx: EventContext, old: T, row: T) => void): void; + onDelete(cb: (ctx: EventContext, row: T) => void): void; +}; + +type SingletonTable = { + singleton: { find(key: boolean): T | null | undefined }; + onInsert(cb: (ctx: EventContext, row: T) => void): void; + onUpdate(cb: (ctx: EventContext, old: T, row: T) => void): void; + onDelete?(cb: (ctx: EventContext, row: T) => void): void; +}; + +type NamespacedDb = DbConnection['db'] & { + reactorState: TableEvents; + reactorEvents: TableEvents; + reactorLimitStatus: TableEvents; + reactorPlayers: TableEvents; + reactorShop: TableEvents; + rateLimitDemoConfig: SingletonTable; +}; + +let currentConn: DbConnection | null = null; +let reconnectTimer: ReturnType | null = null; +let reconnectAttempt = 0; +let serverConfig: ServerConfig | null = null; +let currentIdentityHex: string | null = null; + +const RECONNECT_DELAYS_MS = [1000, 2000, 5000, 10000, 15000]; +const CONNECT_TIMEOUT_MS = 8000; +const TOKEN_STORAGE_PREFIX = 'reactor-clicker.stdb-token'; + +function emitConnectionState( + state: 'connecting' | 'connected' | 'error', + detail?: string +): void { + window.dispatchEvent( + new CustomEvent('reactor:connState', { detail: { state, detail } }) + ); +} + +function emitReactorState(): void { + if (!currentConn) { + window.dispatchEvent( + new CustomEvent('reactor:data', { + detail: { + state: null, + events: [], + players: [], + statuses: [], + shop: [], + demoConfig: null, + currentIdentityHex: null, + }, + }) + ); + return; + } + + const db = currentConn.db as NamespacedDb; + window.dispatchEvent( + new CustomEvent('reactor:data', { + detail: { + state: [...db.reactorState.iter()][0] ?? null, + events: [...db.reactorEvents.iter()].sort((a, b) => + a.id < b.id ? 1 : a.id > b.id ? -1 : 0 + ), + players: [...db.reactorPlayers.iter()].sort((a, b) => { + if (a.contributedEnergy === b.contributedEnergy) + return a.displayName.localeCompare(b.displayName); + return a.contributedEnergy < b.contributedEnergy ? 1 : -1; + }), + statuses: [...db.reactorLimitStatus.iter()].sort((a, b) => + a.label.localeCompare(b.label) + ), + shop: [...db.reactorShop.iter()].sort((a, b) => a.slot - b.slot), + demoConfig: db.rateLimitDemoConfig.singleton.find(true) ?? null, + currentIdentityHex, + }, + }) + ); +} + +function emitReactorEvent(row: ReactorEvent): void { + window.dispatchEvent( + new CustomEvent('reactor:eventInserted', { detail: { event: row } }) + ); +} + +async function loadServerConfig(): Promise { + const r = await fetch('/api/config'); + if (!r.ok) throw new Error(`/api/config returned ${r.status}`); + return (await r.json()) as ServerConfig; +} + +function isStoredTokenAuthError(err: unknown): boolean { + const message = err instanceof Error ? err.message : String(err); + return /unauthorized|verify token|websocket-token/i.test(message); +} + +function connectOnce( + cfg: ServerConfig, + tokenKey: string, + token?: string +): Promise { + return new Promise((resolve, reject) => { + let settled = false; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + reject(new Error('stdb.connect_timeout')); + }, CONNECT_TIMEOUT_MS); + const settle = (fn: () => void) => { + if (settled) return; + settled = true; + clearTimeout(timer); + fn(); + }; + + const builder = DbConnection.builder() + .withUri(cfg.spacetimeUri) + .withDatabaseName(cfg.databaseName) + .onConnect((conn, identity, nextToken) => + settle(() => { + currentIdentityHex = + typeof (identity as { toHexString?: () => string }).toHexString === + 'function' + ? (identity as { toHexString: () => string }).toHexString() + : String(identity); + window.localStorage.setItem(tokenKey, nextToken); + resolve(conn); + }) + ) + .onDisconnect((_ctx, err) => { + currentConn = null; + window.reactor = undefined; + emitConnectionState('error', err?.message ?? 'disconnected'); + scheduleReconnect(); + }) + .onConnectError((_ctx, err) => settle(() => reject(err))); + if (token) builder.withToken(token); + builder.build(); + }); +} + +async function connect(cfg: ServerConfig): Promise { + const tokenKey = `${TOKEN_STORAGE_PREFIX}.${cfg.spacetimeUri}.${cfg.databaseName}`; + const token = window.localStorage.getItem(tokenKey) ?? undefined; + try { + return await connectOnce(cfg, tokenKey, token); + } catch (err) { + if (token && isStoredTokenAuthError(err)) { + window.localStorage.removeItem(tokenKey); + return connectOnce(cfg, tokenKey); + } + throw err; + } +} + +function scheduleReconnect(): void { + if (reconnectTimer != null) return; + const delay = + RECONNECT_DELAYS_MS[ + Math.min(reconnectAttempt, RECONNECT_DELAYS_MS.length - 1) + ]; + reconnectTimer = setTimeout(() => { + reconnectTimer = null; + reconnectAttempt++; + main().catch(err => { + emitConnectionState( + 'error', + err instanceof Error ? err.message : String(err) + ); + scheduleReconnect(); + }); + }, delay); +} + +type TableSyncState = { + subscriptionApplied: boolean; + seenEventIds: Set; +}; + +function subscribeToTables( + connection: DbConnection, + state: TableSyncState +): void { + const db = connection.db as NamespacedDb; + connection + .subscriptionBuilder() + .onApplied(() => { + for (const row of db.reactorEvents.iter()) { + state.seenEventIds.add(row.id.toString()); + } + state.subscriptionApplied = true; + emitReactorState(); + }) + .onError((ctx: ErrorContext) => + console.error('subscription error', ctx.event) + ) + .subscribe([ + tables.reactorState, + tables.reactorEvents, + tables.reactorLimitStatus, + tables.reactorPlayers, + tables.reactorShop, + tables.rateLimitDemoConfig, + ]); +} + +function registerRowCallbacks( + connection: DbConnection, + state: TableSyncState +): void { + const db = connection.db as NamespacedDb; + db.reactorState.onInsert(() => emitReactorState()); + db.reactorState.onUpdate(() => emitReactorState()); + db.reactorState.onDelete(() => emitReactorState()); + db.reactorEvents.onInsert((_ctx, row) => { + const id = row.id.toString(); + const isNewLiveEvent = + state.subscriptionApplied && !state.seenEventIds.has(id); + state.seenEventIds.add(id); + if (isNewLiveEvent) emitReactorEvent(row); + emitReactorState(); + }); + db.reactorEvents.onUpdate(() => emitReactorState()); + db.reactorEvents.onDelete(() => emitReactorState()); + db.reactorLimitStatus.onInsert(() => emitReactorState()); + db.reactorLimitStatus.onUpdate(() => emitReactorState()); + db.reactorLimitStatus.onDelete(() => emitReactorState()); + db.reactorPlayers.onInsert(() => emitReactorState()); + db.reactorPlayers.onUpdate(() => emitReactorState()); + db.reactorPlayers.onDelete(() => emitReactorState()); + db.reactorShop.onInsert(() => emitReactorState()); + db.reactorShop.onUpdate(() => emitReactorState()); + db.reactorShop.onDelete(() => emitReactorState()); + db.rateLimitDemoConfig.onInsert(() => emitReactorState()); + db.rateLimitDemoConfig.onUpdate(() => emitReactorState()); + db.rateLimitDemoConfig.onDelete?.(() => emitReactorState()); +} + +function requireConn(): DbConnection { + if (!currentConn) throw new Error('stdb.disconnected'); + return currentConn; +} + +function installReactorActions(): ReactorActions { + const actions: ReactorActions = { + start: async () => requireConn().procedures.startReactor({}), + tap: async () => requireConn().procedures.tapReactor({}), + overcharge: async () => requireConn().procedures.overcharge({}), + buyUpgrade: async (upgradeId: string) => + requireConn().procedures.buyUpgrade({ upgradeId }), + repair: async () => requireConn().procedures.repairReactor({}), + setPlayerColor: async (color: string) => { + requireConn().reducers.setPlayerColor({ color }); + }, + runSweep: async (maxRows?: number) => + requireConn().procedures.runSweep({ maxRows }), + resetDemo: async () => { + requireConn().reducers.resetDemo({}); + }, + updateConfig: async args => { + requireConn().reducers.updateConfig({ + sweepBatch: args.sweepBatch, + retainEvents: args.retainEvents, + eventPruneBatch: args.eventPruneBatch, + }); + }, + }; + window.reactor = actions; + return actions; +} + +async function main(): Promise { + window.reactor = undefined; + emitConnectionState('connecting'); + if (!serverConfig) { + serverConfig = await loadServerConfig(); + } + try { + const conn = await connect(serverConfig); + currentConn = conn; + reconnectAttempt = 0; + const tableSyncState: TableSyncState = { + subscriptionApplied: false, + seenEventIds: new Set(), + }; + registerRowCallbacks(conn, tableSyncState); + subscribeToTables(conn, tableSyncState); + const reactor = installReactorActions(); + window.dispatchEvent(new CustomEvent('reactor:ready')); + emitConnectionState('connected'); + reactor.start().catch((err: unknown) => { + emitConnectionState( + 'error', + err instanceof Error ? err.message : String(err) + ); + }); + } catch (err) { + currentConn = null; + window.reactor = undefined; + throw err; + } +} + +main().catch(err => { + console.error('reactor connection failed', err); + emitConnectionState( + 'error', + err instanceof Error ? err.message : String(err) + ); + scheduleReconnect(); +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/buy_upgrade_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/buy_upgrade_procedure.ts new file mode 100644 index 00000000000..709e3a65208 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/buy_upgrade_procedure.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ReactorActionResult, +} from "./types"; + +export const params = { + upgradeId: __t.string(), +}; +export const returnType = ReactorActionResult \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts new file mode 100644 index 00000000000..e027d9f8555 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts @@ -0,0 +1,257 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +// This was generated using spacetimedb cli version 2.11.0 (commit 094df0ed2107fe3a359f5e4ee7a4c344802fc96c). + +/* eslint-disable */ +/* tslint:disable */ +import { + DbConnectionBuilder as __DbConnectionBuilder, + DbConnectionImpl as __DbConnectionImpl, + SubscriptionBuilderImpl as __SubscriptionBuilderImpl, + TypeBuilder as __TypeBuilder, + Uuid as __Uuid, + convertToAccessorMap as __convertToAccessorMap, + makeQueryBuilder as __makeQueryBuilder, + procedureSchema as __procedureSchema, + procedures as __procedures, + reducerSchema as __reducerSchema, + reducers as __reducers, + schema as __schema, + t as __t, + table as __table, + type AlgebraicTypeType as __AlgebraicTypeType, + type DbConnectionConfig as __DbConnectionConfig, + type ErrorContextInterface as __ErrorContextInterface, + type Event as __Event, + type EventContextInterface as __EventContextInterface, + type Infer as __Infer, + type QueryBuilder as __QueryBuilder, + type ReducerEventContextInterface as __ReducerEventContextInterface, + type RemoteModule as __RemoteModule, + type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, + type SubscriptionHandleImpl as __SubscriptionHandleImpl, +} from "spacetimedb"; + +// Import all reducer arg schemas +import ResetDemoReducer from "./reset_demo_reducer"; +import SetPlayerColorReducer from "./set_player_color_reducer"; +import UpdateConfigReducer from "./update_config_reducer"; + +// Import all procedure arg schemas +import * as BuyUpgradeProcedure from "./buy_upgrade_procedure"; +import * as OverchargeProcedure from "./overcharge_procedure"; +import * as RepairReactorProcedure from "./repair_reactor_procedure"; +import * as RunSweepProcedure from "./run_sweep_procedure"; +import * as StartReactorProcedure from "./start_reactor_procedure"; +import * as TapReactorProcedure from "./tap_reactor_procedure"; + +// Import all table schema definitions +import RateLimitDemoConfigRow from "./rate_limit_demo_config_table"; +import RateLimitEventsAdminRow from "./rate_limit_events_admin_table"; +import ReactorEventsRow from "./reactor_events_table"; +import ReactorLimitStatusRow from "./reactor_limit_status_table"; +import ReactorPlayersRow from "./reactor_players_table"; +import ReactorShopRow from "./reactor_shop_table"; +import ReactorStateRow from "./reactor_state_table"; + +// Import namespace table schema definitions +import RateLimit_RateLimitConfigRow from "./rateLimit/rate_limit_config_table"; +import RateLimit_AdminRateLimitBucketsRow from "./rateLimit/admin_rate_limit_buckets_table"; + +// Import namespace reducer arg schemas +import RateLimit_AddRateLimitAdminReducer from "./rateLimit/add_rate_limit_admin_reducer"; +import RateLimit_RemoveRateLimitAdminReducer from "./rateLimit/remove_rate_limit_admin_reducer"; +import RateLimit_ResetBucketsReducer from "./rateLimit/reset_buckets_reducer"; +import RateLimit_UpdateConfigReducer from "./rateLimit/update_config_reducer"; + +// Import namespace procedure arg schemas +import * as RateLimit_RunSweepProcedure from "./rateLimit/run_sweep_procedure"; + +/** Type-only namespace exports for generated type groups. */ + +/** The schema information for all tables in this module. This is defined the same was as the tables would have been defined in the server. */ +const tablesSchema = __schema({ + rateLimitDemoConfig: __table({ + name: 'rate_limit_demo_config', + indexes: [ + { accessor: 'singleton', name: 'rate_limit_demo_config_singleton_idx_btree', algorithm: 'btree', columns: [ + 'singleton', + ] }, + ], + constraints: [ + { name: 'rate_limit_demo_config_singleton_key', constraint: 'unique', columns: ['singleton'] }, + ], + }, RateLimitDemoConfigRow), + rateLimitEventsAdmin: __table({ + name: 'rate_limit_events_admin', + indexes: [ + ], + constraints: [ + ], + }, RateLimitEventsAdminRow), + reactorEvents: __table({ + name: 'reactor_events', + indexes: [ + ], + constraints: [ + ], + }, ReactorEventsRow), + reactorLimitStatus: __table({ + name: 'reactor_limit_status', + indexes: [ + ], + constraints: [ + ], + }, ReactorLimitStatusRow), + reactorPlayers: __table({ + name: 'reactor_players', + indexes: [ + ], + constraints: [ + ], + }, ReactorPlayersRow), + reactorShop: __table({ + name: 'reactor_shop', + indexes: [ + ], + constraints: [ + ], + }, ReactorShopRow), + reactorState: __table({ + name: 'reactor_state', + indexes: [ + ], + constraints: [ + ], + }, ReactorStateRow), + "rate_limit.rate_limit_config": __table({ + name: 'rate_limit.rate_limit_config', + indexes: [ + { accessor: 'singleton', name: 'rate_limit_config_singleton_idx_btree', algorithm: 'btree', columns: [ + 'singleton', + ] }, + ], + constraints: [ + { name: 'rate_limit_config_singleton_key', constraint: 'unique', columns: ['singleton'] }, + ], + }, RateLimit_RateLimitConfigRow), + "rate_limit.admin_rate_limit_buckets": __table({ + name: 'rate_limit.admin_rate_limit_buckets', + indexes: [ + ], + constraints: [ + ], + }, RateLimit_AdminRateLimitBucketsRow), +}); + +/** The schema information for all reducers in this module. This is defined the same way as the reducers would have been defined in the server, except the body of the reducer is omitted in code generation. */ +const reducersSchema = __reducers( + __reducerSchema("reset_demo", ResetDemoReducer), + __reducerSchema("set_player_color", SetPlayerColorReducer), + __reducerSchema("update_config", UpdateConfigReducer), + __reducerSchema("rate_limit.add_rate_limit_admin", RateLimit_AddRateLimitAdminReducer, "rateLimit.addRateLimitAdmin"), + __reducerSchema("rate_limit.remove_rate_limit_admin", RateLimit_RemoveRateLimitAdminReducer, "rateLimit.removeRateLimitAdmin"), + __reducerSchema("rate_limit.reset_buckets", RateLimit_ResetBucketsReducer, "rateLimit.resetBuckets"), + __reducerSchema("rate_limit.update_config", RateLimit_UpdateConfigReducer, "rateLimit.updateConfig"), +); + +/** The schema information for all procedures in this module. This is defined the same way as the procedures would have been defined in the server. */ +const proceduresSchema = __procedures( + __procedureSchema("buy_upgrade", BuyUpgradeProcedure.params, BuyUpgradeProcedure.returnType), + __procedureSchema("overcharge", OverchargeProcedure.params, OverchargeProcedure.returnType), + __procedureSchema("repair_reactor", RepairReactorProcedure.params, RepairReactorProcedure.returnType), + __procedureSchema("run_sweep", RunSweepProcedure.params, RunSweepProcedure.returnType), + __procedureSchema("start_reactor", StartReactorProcedure.params, StartReactorProcedure.returnType), + __procedureSchema("tap_reactor", TapReactorProcedure.params, TapReactorProcedure.returnType), + __procedureSchema("rate_limit.run_sweep", RateLimit_RunSweepProcedure.params, RateLimit_RunSweepProcedure.returnType, "rateLimit.runSweep"), +); + +/** The remote SpacetimeDB module schema, both runtime and type information. */ +const REMOTE_MODULE = { + versionInfo: { + cliVersion: "2.11.0" as const, + }, + tables: tablesSchema.schemaType.tables, + reducers: reducersSchema.reducersType.reducers, + ...proceduresSchema, +} satisfies __RemoteModule< + typeof tablesSchema.schemaType, + typeof reducersSchema.reducersType, + typeof proceduresSchema +>; + +/** The tables available in this remote SpacetimeDB module. Each table reference doubles as a query builder. */ +const __qb = __makeQueryBuilder(tablesSchema.schemaType); +export const tables = { + rateLimitDemoConfig: __qb.rateLimitDemoConfig, + rateLimitEventsAdmin: __qb.rateLimitEventsAdmin, + reactorEvents: __qb.reactorEvents, + reactorLimitStatus: __qb.reactorLimitStatus, + reactorPlayers: __qb.reactorPlayers, + reactorShop: __qb.reactorShop, + reactorState: __qb.reactorState, + rateLimit: { + rateLimitConfig: __qb["rate_limit.rate_limit_config"], + adminRateLimitBuckets: __qb["rate_limit.admin_rate_limit_buckets"], + }, +} as const; + +/** The reducers available in this remote SpacetimeDB module. */ +const __reducerAccessors = __convertToAccessorMap(reducersSchema.reducersType.reducers); +export const reducers = { + resetDemo: __reducerAccessors.resetDemo, + setPlayerColor: __reducerAccessors.setPlayerColor, + updateConfig: __reducerAccessors.updateConfig, + rateLimit: { + addRateLimitAdmin: __reducerAccessors["rateLimit.addRateLimitAdmin"], + removeRateLimitAdmin: __reducerAccessors["rateLimit.removeRateLimitAdmin"], + resetBuckets: __reducerAccessors["rateLimit.resetBuckets"], + updateConfig: __reducerAccessors["rateLimit.updateConfig"], + }, +} as const; + +/** The procedures available in this remote SpacetimeDB module. */ +const __procedureAccessors = __convertToAccessorMap(proceduresSchema.procedures); +export const procedures = { + buyUpgrade: __procedureAccessors.buyUpgrade, + overcharge: __procedureAccessors.overcharge, + repairReactor: __procedureAccessors.repairReactor, + runSweep: __procedureAccessors.runSweep, + startReactor: __procedureAccessors.startReactor, + tapReactor: __procedureAccessors.tapReactor, + rateLimit: { + runSweep: __procedureAccessors["rateLimit.runSweep"], + }, +} as const; + +/** The context type returned in callbacks for all possible events. */ +export type EventContext = __EventContextInterface; +/** The context type returned in callbacks for reducer events. */ +export type ReducerEventContext = __ReducerEventContextInterface; +/** The context type returned in callbacks for subscription events. */ +export type SubscriptionEventContext = __SubscriptionEventContextInterface; +/** The context type returned in callbacks for error events. */ +export type ErrorContext = __ErrorContextInterface; +/** The subscription handle type to manage active subscriptions created from a {@link SubscriptionBuilder}. */ +export type SubscriptionHandle = __SubscriptionHandleImpl; + +/** Builder class to configure a new subscription to the remote SpacetimeDB instance. */ +export class SubscriptionBuilder extends __SubscriptionBuilderImpl {} + +/** Builder class to configure a new database connection to the remote SpacetimeDB instance. */ +export class DbConnectionBuilder extends __DbConnectionBuilder {} + +/** The typed database connection to manage connections to the remote SpacetimeDB instance. This class has type information specific to the generated module. */ +export class DbConnection extends __DbConnectionImpl { + /** Creates a new {@link DbConnectionBuilder} to configure and connect to the remote SpacetimeDB instance. */ + static builder = (): DbConnectionBuilder => { + return new DbConnectionBuilder(REMOTE_MODULE, (config: __DbConnectionConfig) => new DbConnection(config)); + }; + + /** Creates a new {@link SubscriptionBuilder} to configure a subscription to the remote SpacetimeDB instance. */ + override subscriptionBuilder = (): SubscriptionBuilder => { + return new SubscriptionBuilder(this); + }; +} + diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/overcharge_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/overcharge_procedure.ts new file mode 100644 index 00000000000..d53ce96cf57 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/overcharge_procedure.ts @@ -0,0 +1,19 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ReactorActionResult, +} from "./types"; + +export const params = { +}; +export const returnType = ReactorActionResult \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/add_rate_limit_admin_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/add_rate_limit_admin_reducer.ts new file mode 100644 index 00000000000..e39846ca8d9 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/add_rate_limit_admin_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + identity: __t.identity(), +}; diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/admin_rate_limit_buckets_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/admin_rate_limit_buckets_table.ts new file mode 100644 index 00000000000..189f539a043 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/admin_rate_limit_buckets_table.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + key: __t.string().primaryKey(), + scope: __t.string(), + windowStart: __t.timestamp().name("window_start"), + expiresAt: __t.timestamp().name("expires_at"), + count: __t.u32(), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/rate_limit_config_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/rate_limit_config_table.ts new file mode 100644 index 00000000000..66ffe86e399 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/rate_limit_config_table.ts @@ -0,0 +1,17 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + singleton: __t.bool().primaryKey(), + sweepBatch: __t.u32().name("sweep_batch"), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/remove_rate_limit_admin_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/remove_rate_limit_admin_reducer.ts new file mode 100644 index 00000000000..e39846ca8d9 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/remove_rate_limit_admin_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + identity: __t.identity(), +}; diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/reset_buckets_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/reset_buckets_reducer.ts new file mode 100644 index 00000000000..a7c5cc5274f --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/reset_buckets_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + maxRows: __t.option(__t.u32()), +}; diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/run_sweep_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/run_sweep_procedure.ts new file mode 100644 index 00000000000..9815c99eb38 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/run_sweep_procedure.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const params = { + maxRows: __t.option(__t.u32()), +}; +export const returnType = __t.u32() \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/types.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/types.ts new file mode 100644 index 00000000000..d14931b1fb9 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/types.ts @@ -0,0 +1,44 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const AdminRateLimitBuckets = __t.object("AdminRateLimitBuckets", {}); +export type AdminRateLimitBuckets = __Infer; + +export const RateLimitAdminIdentity = __t.object("RateLimitAdminIdentity", { + identity: __t.identity(), + addedAt: __t.timestamp(), +}); +export type RateLimitAdminIdentity = __Infer; + +export const RateLimitBucket = __t.object("RateLimitBucket", { + key: __t.string(), + scope: __t.string(), + windowStart: __t.timestamp(), + expiresAt: __t.timestamp(), + count: __t.u32(), + updatedAt: __t.timestamp(), +}); +export type RateLimitBucket = __Infer; + +export const RateLimitConfig = __t.object("RateLimitConfig", { + singleton: __t.bool(), + sweepBatch: __t.u32(), + updatedAt: __t.timestamp(), +}); +export type RateLimitConfig = __Infer; + +export const RateLimitSweepTick = __t.object("RateLimitSweepTick", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), +}); +export type RateLimitSweepTick = __Infer; + diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/update_config_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/update_config_reducer.ts new file mode 100644 index 00000000000..54fcf361af1 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/update_config_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + sweepBatch: __t.u32(), +}; diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_demo_config_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_demo_config_table.ts new file mode 100644 index 00000000000..bcb7aa20309 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_demo_config_table.ts @@ -0,0 +1,18 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + singleton: __t.bool().primaryKey(), + retainEvents: __t.u32().name("retain_events"), + eventPruneBatch: __t.u32().name("event_prune_batch"), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_events_admin_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_events_admin_table.ts new file mode 100644 index 00000000000..d6d861cbb6f --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_events_admin_table.ts @@ -0,0 +1,26 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + id: __t.u64().primaryKey(), + scope: __t.string(), + key: __t.string(), + allowed: __t.bool(), + limit: __t.u32(), + used: __t.u32(), + remaining: __t.u32(), + retryAfterSeconds: __t.u32().name("retry_after_seconds"), + windowSeconds: __t.u32().name("window_seconds"), + cost: __t.u32(), + resetAt: __t.timestamp().name("reset_at"), + createdAt: __t.timestamp().name("created_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_events_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_events_table.ts new file mode 100644 index 00000000000..207ec768f97 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_events_table.ts @@ -0,0 +1,25 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + id: __t.u64().primaryKey(), + identity: __t.identity(), + actorName: __t.string().name("actor_name"), + actorColor: __t.string().name("actor_color"), + kind: __t.string(), + scope: __t.string(), + message: __t.string(), + allowed: __t.bool(), + energyDelta: __t.i64().name("energy_delta"), + retryAfterSeconds: __t.u32().name("retry_after_seconds"), + createdAt: __t.timestamp().name("created_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_limit_status_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_limit_status_table.ts new file mode 100644 index 00000000000..fc9f0392d1e --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_limit_status_table.ts @@ -0,0 +1,21 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + scope: __t.string(), + label: __t.string(), + limit: __t.u32(), + windowSeconds: __t.u32().name("window_seconds"), + used: __t.u32(), + remaining: __t.u32(), + resetAt: __t.option(__t.timestamp()).name("reset_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_players_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_players_table.ts new file mode 100644 index 00000000000..e9c658484b7 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_players_table.ts @@ -0,0 +1,24 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + identity: __t.identity(), + displayName: __t.string().name("display_name"), + color: __t.string(), + contributedEnergy: __t.u64().name("contributed_energy"), + taps: __t.u32(), + surges: __t.u32(), + coolantUses: __t.u32().name("coolant_uses"), + upgradesBought: __t.u32().name("upgrades_bought"), + joinedAt: __t.timestamp().name("joined_at"), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_shop_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_shop_table.ts new file mode 100644 index 00000000000..5a0217589e6 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_shop_table.ts @@ -0,0 +1,21 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + slot: __t.u32(), + id: __t.string(), + name: __t.string(), + description: __t.string(), + effect: __t.string(), + cost: __t.u64(), + available: __t.bool(), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_state_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_state_table.ts new file mode 100644 index 00000000000..422838dd710 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_state_table.ts @@ -0,0 +1,31 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + singleton: __t.bool().primaryKey(), + energy: __t.u64(), + reactorLevel: __t.u32().name("reactor_level"), + upgradeCount: __t.u32().name("upgrade_count"), + powerUpgradeCount: __t.u32().name("power_upgrade_count"), + coolingUpgradeCount: __t.u32().name("cooling_upgrade_count"), + capacityUpgradeCount: __t.u32().name("capacity_upgrade_count"), + chargeUpgradeCount: __t.u32().name("charge_upgrade_count"), + bayUpgradeCount: __t.u32().name("bay_upgrade_count"), + combo: __t.u32(), + bestCombo: __t.u32().name("best_combo"), + heat: __t.u32(), + heatCapacity: __t.u32().name("heat_capacity"), + coolingPerSecond: __t.u32().name("cooling_per_second"), + tapHeatGain: __t.u32().name("tap_heat_gain"), + overheated: __t.bool(), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/repair_reactor_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/repair_reactor_procedure.ts new file mode 100644 index 00000000000..d53ce96cf57 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/repair_reactor_procedure.ts @@ -0,0 +1,19 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ReactorActionResult, +} from "./types"; + +export const params = { +}; +export const returnType = ReactorActionResult \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reset_demo_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reset_demo_reducer.ts new file mode 100644 index 00000000000..e18fbc0a086 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reset_demo_reducer.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default {}; diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/run_sweep_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/run_sweep_procedure.ts new file mode 100644 index 00000000000..9815c99eb38 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/run_sweep_procedure.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const params = { + maxRows: __t.option(__t.u32()), +}; +export const returnType = __t.u32() \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/set_player_color_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/set_player_color_reducer.ts new file mode 100644 index 00000000000..42ec3238c75 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/set_player_color_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + color: __t.string(), +}; diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/start_reactor_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/start_reactor_procedure.ts new file mode 100644 index 00000000000..d53ce96cf57 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/start_reactor_procedure.ts @@ -0,0 +1,19 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ReactorActionResult, +} from "./types"; + +export const params = { +}; +export const returnType = ReactorActionResult \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/tap_reactor_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/tap_reactor_procedure.ts new file mode 100644 index 00000000000..d53ce96cf57 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/tap_reactor_procedure.ts @@ -0,0 +1,19 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ReactorActionResult, +} from "./types"; + +export const params = { +}; +export const returnType = ReactorActionResult \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/types.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/types.ts new file mode 100644 index 00000000000..fd9c231c367 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/types.ts @@ -0,0 +1,157 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const RateLimitDemoConfig = __t.object("RateLimitDemoConfig", { + singleton: __t.bool(), + retainEvents: __t.u32(), + eventPruneBatch: __t.u32(), + updatedAt: __t.timestamp(), +}); +export type RateLimitDemoConfig = __Infer; + +export const RateLimitDemoSweepTick = __t.object("RateLimitDemoSweepTick", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), +}); +export type RateLimitDemoSweepTick = __Infer; + +export const RateLimitEvent = __t.object("RateLimitEvent", { + id: __t.u64(), + scope: __t.string(), + key: __t.string(), + allowed: __t.bool(), + limit: __t.u32(), + used: __t.u32(), + remaining: __t.u32(), + retryAfterSeconds: __t.u32(), + windowSeconds: __t.u32(), + cost: __t.u32(), + resetAt: __t.timestamp(), + createdAt: __t.timestamp(), +}); +export type RateLimitEvent = __Infer; + +export const RateLimitEventsAdmin = __t.object("RateLimitEventsAdmin", {}); +export type RateLimitEventsAdmin = __Infer; + +export const ReactorActionResult = __t.object("ReactorActionResult", { + allowed: __t.bool(), + action: __t.string(), + message: __t.string(), + energy: __t.u64(), + energyDelta: __t.i64(), + retryAfterSeconds: __t.u32(), + resetAt: __t.timestamp(), +}); +export type ReactorActionResult = __Infer; + +export const ReactorEvent = __t.object("ReactorEvent", { + id: __t.u64(), + identity: __t.identity(), + actorName: __t.string(), + actorColor: __t.string(), + kind: __t.string(), + scope: __t.string(), + message: __t.string(), + allowed: __t.bool(), + energyDelta: __t.i64(), + retryAfterSeconds: __t.u32(), + createdAt: __t.timestamp(), +}); +export type ReactorEvent = __Infer; + +export const ReactorEvents = __t.object("ReactorEvents", {}); +export type ReactorEvents = __Infer; + +export const ReactorLimitStatus = __t.object("ReactorLimitStatus", {}); +export type ReactorLimitStatus = __Infer; + +export const ReactorLimitStatusRow = __t.object("ReactorLimitStatusRow", { + scope: __t.string(), + label: __t.string(), + limit: __t.u32(), + windowSeconds: __t.u32(), + used: __t.u32(), + remaining: __t.u32(), + resetAt: __t.option(__t.timestamp()), +}); +export type ReactorLimitStatusRow = __Infer; + +export const ReactorPlayerRow = __t.object("ReactorPlayerRow", { + identity: __t.identity(), + displayName: __t.string(), + color: __t.string(), + contributedEnergy: __t.u64(), + taps: __t.u32(), + surges: __t.u32(), + coolantUses: __t.u32(), + upgradesBought: __t.u32(), + joinedAt: __t.timestamp(), + updatedAt: __t.timestamp(), +}); +export type ReactorPlayerRow = __Infer; + +export const ReactorPlayerState = __t.object("ReactorPlayerState", { + identity: __t.identity(), + displayName: __t.string(), + color: __t.string(), + contributedEnergy: __t.u64(), + taps: __t.u32(), + surges: __t.u32(), + coolantUses: __t.u32(), + upgradesBought: __t.u32(), + joinedAt: __t.timestamp(), + updatedAt: __t.timestamp(), +}); +export type ReactorPlayerState = __Infer; + +export const ReactorPlayers = __t.object("ReactorPlayers", {}); +export type ReactorPlayers = __Infer; + +export const ReactorRoomState = __t.object("ReactorRoomState", { + singleton: __t.bool(), + energy: __t.u64(), + reactorLevel: __t.u32(), + upgradeCount: __t.u32(), + powerUpgradeCount: __t.u32(), + coolingUpgradeCount: __t.u32(), + capacityUpgradeCount: __t.u32(), + chargeUpgradeCount: __t.u32(), + bayUpgradeCount: __t.u32(), + combo: __t.u32(), + bestCombo: __t.u32(), + heat: __t.u32(), + heatCapacity: __t.u32(), + coolingPerSecond: __t.u32(), + tapHeatGain: __t.u32(), + overheated: __t.bool(), + updatedAt: __t.timestamp(), +}); +export type ReactorRoomState = __Infer; + +export const ReactorShop = __t.object("ReactorShop", {}); +export type ReactorShop = __Infer; + +export const ReactorShopItemRow = __t.object("ReactorShopItemRow", { + slot: __t.u32(), + id: __t.string(), + name: __t.string(), + description: __t.string(), + effect: __t.string(), + cost: __t.u64(), + available: __t.bool(), +}); +export type ReactorShopItemRow = __Infer; + +export const ReactorState = __t.object("ReactorState", {}); +export type ReactorState = __Infer; + diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/types/procedures.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/types/procedures.ts new file mode 100644 index 00000000000..44dde79c5fd --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/types/procedures.ts @@ -0,0 +1,28 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from "spacetimedb"; + +// Import all procedure arg schemas +import * as BuyUpgradeProcedure from "../buy_upgrade_procedure"; +import * as OverchargeProcedure from "../overcharge_procedure"; +import * as RepairReactorProcedure from "../repair_reactor_procedure"; +import * as RunSweepProcedure from "../run_sweep_procedure"; +import * as StartReactorProcedure from "../start_reactor_procedure"; +import * as TapReactorProcedure from "../tap_reactor_procedure"; + +export type BuyUpgradeArgs = __Infer; +export type BuyUpgradeResult = __Infer; +export type OverchargeArgs = __Infer; +export type OverchargeResult = __Infer; +export type RepairReactorArgs = __Infer; +export type RepairReactorResult = __Infer; +export type RunSweepArgs = __Infer; +export type RunSweepResult = __Infer; +export type StartReactorArgs = __Infer; +export type StartReactorResult = __Infer; +export type TapReactorArgs = __Infer; +export type TapReactorResult = __Infer; + diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/types/reducers.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/types/reducers.ts new file mode 100644 index 00000000000..3bed08e992d --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/types/reducers.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from "spacetimedb"; + +// Import all reducer arg schemas +import ResetDemoReducer from "../reset_demo_reducer"; +import SetPlayerColorReducer from "../set_player_color_reducer"; +import UpdateConfigReducer from "../update_config_reducer"; + +export type ResetDemoParams = __Infer; +export type SetPlayerColorParams = __Infer; +export type UpdateConfigParams = __Infer; + diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/update_config_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/update_config_reducer.ts new file mode 100644 index 00000000000..d7ddcf900e6 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/update_config_reducer.ts @@ -0,0 +1,17 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + sweepBatch: __t.option(__t.u32()), + retainEvents: __t.option(__t.u32()), + eventPruneBatch: __t.option(__t.u32()), +}; diff --git a/spacetime-rate-limit-ts/example/tsconfig.json b/spacetime-rate-limit-ts/example/tsconfig.json new file mode 100644 index 00000000000..ae0d0a4d3c3 --- /dev/null +++ b/spacetime-rate-limit-ts/example/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": ["node"], + "isolatedModules": true, + "allowImportingTsExtensions": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts", "server.ts"], + "exclude": ["node_modules", "spacetimedb"] +} diff --git a/spacetime-rate-limit-ts/package.json b/spacetime-rate-limit-ts/package.json new file mode 100644 index 00000000000..911bb49ad1e --- /dev/null +++ b/spacetime-rate-limit-ts/package.json @@ -0,0 +1,75 @@ +{ + "name": "@spacetimedb/rate-limit", + "description": "Fixed-window rate limiting and bounded expiration sweeps for SpacetimeDB TypeScript modules.", + "version": "0.1.0", + "license": "Apache-2.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./submodule": { + "types": "./src/submodule.ts", + "default": "./src/submodule.ts" + } + }, + "files": [ + "dist", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./submodule": { + "types": "./dist/submodule.d.ts", + "default": "./dist/submodule.js" + } + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/clockworklabs/SpacetimeDB.git", + "directory": "spacetime-rate-limit-ts" + }, + "homepage": "https://github.com/clockworklabs/SpacetimeDB/tree/master/spacetime-rate-limit-ts#readme", + "bugs": { + "url": "https://github.com/clockworklabs/SpacetimeDB/issues" + }, + "keywords": [ + "spacetimedb", + "rate-limit", + "security", + "typescript" + ], + "scripts": { + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "node --js-explicit-resource-management --import tsx --import ./scripts/sys-abi-test-register.mjs scripts/test.ts", + "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json", + "prepack": "pnpm run build && node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" + }, + "peerDependencies": { + "spacetimedb": "workspace:^" + }, + "devDependencies": { + "eslint": "^9.17.0", + "prettier": "^3.3.3", + "@types/node": "^22.10.2", + "spacetimedb": "workspace:*", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-rate-limit-ts/scripts/sys-abi-test-register.mjs b/spacetime-rate-limit-ts/scripts/sys-abi-test-register.mjs new file mode 100644 index 00000000000..30107456e71 --- /dev/null +++ b/spacetime-rate-limit-ts/scripts/sys-abi-test-register.mjs @@ -0,0 +1,27 @@ +import { register } from 'node:module'; + +// Host syscall modules exist only inside SpacetimeDB. Stub the bindings that +// `spacetimedb/server` reads while loading. +const stubs = { + 'spacetime:sys@2.0': + 'export const moduleHooks = Symbol(); export function row_iter_bsatn_close() {}', + 'spacetime:sys@2.1': 'export {};', + 'spacetime:sys@2.2': 'export function env_get() {}', +}; + +const loaderSource = ` + const stubs = ${JSON.stringify(stubs)}; + export function resolve(specifier, context, nextResolve) { + return specifier in stubs + ? { + shortCircuit: true, + url: 'data:text/javascript,' + encodeURIComponent(stubs[specifier]), + } + : nextResolve(specifier, context); + } +`; + +register( + `data:text/javascript,${encodeURIComponent(loaderSource)}`, + import.meta.url +); diff --git a/spacetime-rate-limit-ts/scripts/test.ts b/spacetime-rate-limit-ts/scripts/test.ts new file mode 100644 index 00000000000..c2b87d900a2 --- /dev/null +++ b/spacetime-rate-limit-ts/scripts/test.ts @@ -0,0 +1,185 @@ +import { Timestamp } from 'spacetimedb'; +import { SenderError } from 'spacetimedb/server'; +import { + client, + errors, + MAX_SWEEP_BATCH, + resetRegisteredScopes, + sweepRateLimits, + type RateLimitBucketRow, +} from '../src/limit'; + +let pass = 0; +let fail = 0; + +function assert(cond: boolean, name: string, detail = ''): void { + if (cond) { + pass++; + process.stdout.write(` ok ${name}\n`); + } else { + fail++; + process.stdout.write( + ` FAIL ${name}${detail ? `\n ${detail}` : ''}\n` + ); + } +} + +function assertThrows( + fn: () => void, + expected: string, + name: string, + type: new (message: string) => Error = Error +): void { + try { + fn(); + assert(false, name, `expected ${expected}`); + } catch (error) { + assert(error instanceof type && error.message === expected, name); + } +} + +function makeTx(nowMicros = 0n) { + const rows = new Map(); + const tx = { + timestamp: new Timestamp(nowMicros), + db: { + rateLimitBucket: { + key: { + find: (key: string) => rows.get(key), + update: (row: RateLimitBucketRow) => rows.set(row.key, row), + }, + insert: (row: RateLimitBucketRow) => rows.set(row.key, row), + delete: (row: RateLimitBucketRow) => rows.delete(row.key), + }, + }, + rows, + }; + return tx; +} + +function byExpiry(rows: Map) { + return [...rows.values()].sort((a, b) => + a.expiresAt.microsSinceUnixEpoch < b.expiresAt.microsSinceUnixEpoch ? -1 : 1 + ); +} + +process.stdout.write('\nrate limiter\n'); + +{ + const tx = makeTx(); + const tap = client({ scope: 'tap', windowSeconds: 60, limit: 1 }); + const other = client({ scope: 'other', windowSeconds: 60, limit: 1 }); + assert(tap.consume(tx, { key: 'alice' }).allowed, 'first call allowed'); + assert(!tap.consume(tx, { key: 'alice' }).allowed, 'limit enforced'); + assert( + other.consume(tx, { key: 'alice' }).allowed, + 'scopes have independent buckets' + ); + assert( + tap.consume(tx, { key: 'bob' }).allowed, + 'actors have independent buckets' + ); + assertThrows( + () => client({ scope: 'tap', windowSeconds: 30, limit: 5 }), + 'rate_limit.duplicate_scope', + 'a scope can be configured once' + ); + resetRegisteredScopes(); + assert( + client({ scope: 'tap', windowSeconds: 30, limit: 5 }).limit === 5, + 'reset lets a scope be configured again' + ); + assertThrows( + () => tap.consume(tx, { key: '' }), + errors.invalidActorKey, + 'empty actor key rejected', + SenderError + ); +} + +{ + const tx = makeTx(); + const upload = client({ scope: 'upload', limit: 3, windowSeconds: 60 }); + assertThrows( + () => upload.consume(tx, { key: 'alice', cost: 4 }), + errors.invalidCost, + 'cost above the limit rejected', + SenderError + ); + assertThrows( + () => upload.consume(tx, { key: 'alice', cost: 0 }), + errors.invalidCost, + 'non-positive cost rejected', + SenderError + ); + assert(tx.rows.size === 0, 'rejected cost leaves the bucket untouched'); + const full = upload.consume(tx, { key: 'alice', cost: 3 }); + assert( + full.allowed && full.remaining === 0, + 'cost equal to the limit allowed' + ); +} + +{ + const tx = makeTx(); + const login = client({ scope: 'auth.login', limit: 2, windowSeconds: 60 }); + const one = login.consume(tx, { key: 'ip:1' }); + const two = login.consume(tx, { key: 'ip:1' }); + const three = login.consume(tx, { key: 'ip:1' }); + assert(one.allowed && one.remaining === 1, 'first request allowed'); + assert(two.allowed && two.remaining === 0, 'second request allowed'); + assert( + !three.allowed && three.retryAfterSeconds === 60, + 'third request blocked' + ); + const status = login.peek(tx.db, 'ip:1', tx.timestamp); + assert( + status.used === 2 && status.remaining === 0 && status.limit === 2, + 'peek reports the open window' + ); + assert( + login.peek(tx.db, 'ip:2').used === 0, + 'peek reports an unused bucket as fresh' + ); + tx.timestamp = new Timestamp(61_000_000n); + const expired = login.peek(tx.db, 'ip:1', tx.timestamp); + assert( + expired.used === 0 && expired.resetAt === undefined, + 'peek reports an expired window as fresh' + ); + const next = login.consume(tx, { key: 'ip:1' }); + assert(next.allowed && next.used === 1, 'expired window resets'); +} + +{ + const tx = makeTx(); + const a = client({ scope: 'a:actor:b', limit: 1, windowSeconds: 1 }); + const b = client({ scope: 'a', limit: 1, windowSeconds: 1 }); + assert( + a.consume(tx, { key: 'c' }).key !== b.consume(tx, { key: 'b:actor:c' }).key, + 'compound keys cannot collide through delimiters' + ); +} + +{ + const tx = makeTx(); + const long = client({ scope: 'sweep.long', limit: 1, windowSeconds: 100 }); + const short = client({ scope: 'sweep.short', limit: 1, windowSeconds: 1 }); + long.consume(tx, { key: 'a' }); + long.consume(tx, { key: 'b' }); + const expiredKey = short.consume(tx, { key: 'a' }).key; + tx.timestamp = new Timestamp(2_000_000n); + assert( + sweepRateLimits(tx, byExpiry(tx.rows), 2) === 1, + 'sweep removes only expired buckets' + ); + assert(!tx.rows.has(expiredKey), 'sweep removes the expired bucket'); + assertThrows( + () => sweepRateLimits(tx, [], MAX_SWEEP_BATCH + 1), + errors.invalidSweepBatch, + 'sweep rejects an excessive batch size' + ); +} + +process.stdout.write(`\n${pass} passed, ${fail} failed\n`); +process.exit(fail === 0 ? 0 : 1); diff --git a/spacetime-rate-limit-ts/spacetimedb/.npmrc b/spacetime-rate-limit-ts/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-rate-limit-ts/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-rate-limit-ts/spacetimedb/package.json b/spacetime-rate-limit-ts/spacetimedb/package.json new file mode 100644 index 00000000000..e1bc09577f9 --- /dev/null +++ b/spacetime-rate-limit-ts/spacetimedb/package.json @@ -0,0 +1,19 @@ +{ + "name": "spacetime-rate-limit-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-rate-limit", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-rate-limit" + }, + "dependencies": { + "@spacetimedb/rate-limit": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-rate-limit-ts/spacetimedb/src/index.ts b/spacetime-rate-limit-ts/spacetimedb/src/index.ts new file mode 100644 index 00000000000..af68ebad0f9 --- /dev/null +++ b/spacetime-rate-limit-ts/spacetimedb/src/index.ts @@ -0,0 +1,17 @@ +import spacetimedb from '../../src/submodule/schema'; +import { install } from '../../src/submodule/install'; +export { + adminRateLimitBuckets, + addRateLimitAdmin, + removeRateLimitAdmin, + rateLimitSweep, + resetBuckets, + runSweep, + updateConfig, +} from '../../src/submodule/operations'; + +export default spacetimedb; + +export const init = spacetimedb.init(ctx => { + install(ctx); +}); diff --git a/spacetime-rate-limit-ts/spacetimedb/tsconfig.json b/spacetime-rate-limit-ts/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..8d8f9b03455 --- /dev/null +++ b/spacetime-rate-limit-ts/spacetimedb/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src"] +} diff --git a/spacetime-rate-limit-ts/src/index.ts b/spacetime-rate-limit-ts/src/index.ts new file mode 100644 index 00000000000..d9ec5496c38 --- /dev/null +++ b/spacetime-rate-limit-ts/src/index.ts @@ -0,0 +1,11 @@ +export { + client, + errors, + resetRegisteredScopes, + type RateLimitClient, + type RateLimitPolicy, + type RateLimitReadDb, + type RateLimitResult, + type RateLimitStatus, + type RateLimitTxLike, +} from './limit.js'; diff --git a/spacetime-rate-limit-ts/src/limit.ts b/spacetime-rate-limit-ts/src/limit.ts new file mode 100644 index 00000000000..3437bc63d3a --- /dev/null +++ b/spacetime-rate-limit-ts/src/limit.ts @@ -0,0 +1,253 @@ +import { Timestamp } from 'spacetimedb'; +import { SenderError } from 'spacetimedb/server'; + +const ONE_SECOND_MICROS = 1_000_000n; +const U32_MAX = 0xffff_ffff; + +export const DEFAULT_SWEEP_BATCH = 500; +export const MAX_SWEEP_BATCH = 10_000; +const MAX_SCOPE_LENGTH = 128; +const MAX_ACTOR_KEY_LENGTH = 256; + +/** Codes a reducer, procedure, or view caller can receive as a `SenderError`. */ +export const errors = { + notAuthorized: 'rate_limit.not_authorized', + cannotRemoveLastAdmin: 'rate_limit.cannot_remove_last_admin', + invalidActorKey: 'rate_limit.invalid_actor_key', + invalidCost: 'rate_limit.invalid_cost', + invalidSweepBatch: 'rate_limit.invalid_sweep_batch', + invalidMaxRows: 'rate_limit.invalid_max_rows', +} as const; + +// Policy errors fail the host module while it loads, before any caller. +const policyErrors = { + invalidScope: 'rate_limit.invalid_scope', + duplicateScope: 'rate_limit.duplicate_scope', + invalidLimit: 'rate_limit.invalid_limit', + invalidWindow: 'rate_limit.invalid_window', +} as const; + +export interface RateLimitPolicy { + scope: string; + limit: number; + windowSeconds: number; +} + +export type RateLimitResult = + | { + allowed: true; + key: string; + scope: string; + limit: number; + used: number; + remaining: number; + resetAt: Timestamp; + retryAfterSeconds: 0; + } + | { + allowed: false; + key: string; + scope: string; + limit: number; + used: number; + remaining: 0; + resetAt: Timestamp; + retryAfterSeconds: number; + }; + +/** Current usage of one actor's bucket. `resetAt` is unset when no window is open. */ +export interface RateLimitStatus { + limit: number; + windowSeconds: number; + used: number; + remaining: number; + resetAt: Timestamp | undefined; +} + +export interface RateLimitBucketRow { + key: string; + scope: string; + windowStart: Timestamp; + expiresAt: Timestamp; + count: number; + updatedAt: Timestamp; +} + +export interface RateLimitReadDb { + rateLimitBucket: { + key: { + find(key: string): RateLimitBucketRow | null | undefined; + }; + }; +} + +export interface RateLimitTxLike { + timestamp: Timestamp; + db: { + rateLimitBucket: { + key: { + find(key: string): RateLimitBucketRow | null | undefined; + update(row: RateLimitBucketRow): void; + }; + insert(row: RateLimitBucketRow): void; + delete(row: RateLimitBucketRow): void; + }; + }; +} + +function isPositiveInt(value: number, max = U32_MAX): boolean { + return Number.isInteger(value) && value > 0 && value <= max; +} + +function secondsUntil(now: Timestamp, future: Timestamp): number { + const delta = future.microsSinceUnixEpoch - now.microsSinceUnixEpoch; + if (delta <= 0n) return 0; + return Number((delta + ONE_SECOND_MICROS - 1n) / ONE_SECOND_MICROS); +} + +// Module state lasts for one evaluation of the host module. SpacetimeDB +// evaluates it once in each fresh worker isolate. +const registeredScopes = new Set(); + +/** Forgets every configured scope so `client` can configure them again. */ +export function resetRegisteredScopes(): void { + registeredScopes.clear(); +} + +/** + * Configure the policy for one scope. Each scope may be configured once per + * module so every caller enforces the same limit and window. + */ +export function client({ scope, limit, windowSeconds }: RateLimitPolicy) { + if (scope.length === 0 || scope.length > MAX_SCOPE_LENGTH) + throw new Error(policyErrors.invalidScope); + if (!isPositiveInt(limit)) throw new Error(policyErrors.invalidLimit); + if (!isPositiveInt(windowSeconds)) + throw new Error(policyErrors.invalidWindow); + if (registeredScopes.has(scope)) throw new Error(policyErrors.duplicateScope); + registeredScopes.add(scope); + + function bucketKey(actorKey: string): string { + if (actorKey.length === 0 || actorKey.length > MAX_ACTOR_KEY_LENGTH) + throw new SenderError(errors.invalidActorKey); + // Length-prefix both parts so delimiters inside them cannot collide. + return `${scope.length}:${scope}${actorKey.length}:${actorKey}`; + } + + return { + scope, + limit, + windowSeconds, + + /** + * Spend `cost` (default 1) from the actor's bucket in the caller's + * transaction. A cost above `limit` can never be allowed, so it throws + * `errors.invalidCost`. + */ + consume( + tx: RateLimitTxLike, + opts: { key: string; cost?: number } + ): RateLimitResult { + const key = bucketKey(opts.key); + const cost = opts.cost ?? 1; + if (!isPositiveInt(cost, limit)) { + throw new SenderError(errors.invalidCost); + } + const now = tx.timestamp; + const existing = tx.db.rateLimitBucket.key.find(key); + const open = + existing != null && + existing.expiresAt.microsSinceUnixEpoch > now.microsSinceUnixEpoch; + const used = open ? existing.count : 0; + const resetAt = open + ? existing.expiresAt + : new Timestamp( + now.microsSinceUnixEpoch + BigInt(windowSeconds) * ONE_SECOND_MICROS + ); + + if (used + cost > limit) { + return { + allowed: false, + key, + scope, + limit, + used, + remaining: 0, + resetAt, + retryAfterSeconds: secondsUntil(now, resetAt), + }; + } + + const row = { + key, + scope, + windowStart: open ? existing.windowStart : now, + expiresAt: resetAt, + count: used + cost, + updatedAt: now, + }; + // Update any existing row, including an expired one not yet swept. + if (existing) tx.db.rateLimitBucket.key.update(row); + else tx.db.rateLimitBucket.insert(row); + return { + allowed: true, + key, + scope, + limit, + used: row.count, + remaining: limit - row.count, + resetAt, + retryAfterSeconds: 0, + }; + }, + + /** + * Read the actor's bucket without spending from it. Views have no clock, so + * pass `now` from a reducer or procedure to report an expired window as + * fresh; without it, compare `resetAt` against the caller's clock. + */ + peek(db: RateLimitReadDb, key: string, now?: Timestamp): RateLimitStatus { + const row = db.rateLimitBucket.key.find(bucketKey(key)); + if ( + !row || + (now && row.expiresAt.microsSinceUnixEpoch <= now.microsSinceUnixEpoch) + ) { + return { + limit, + windowSeconds, + used: 0, + remaining: limit, + resetAt: undefined, + }; + } + return { + limit, + windowSeconds, + used: row.count, + remaining: Math.max(0, limit - row.count), + resetAt: row.expiresAt, + }; + }, + }; +} + +export type RateLimitClient = ReturnType; + +export function sweepRateLimits( + tx: RateLimitTxLike, + expiredRows: Iterable, + maxRows: number +): number { + if (!isPositiveInt(maxRows, MAX_SWEEP_BATCH)) { + throw new Error(errors.invalidSweepBatch); + } + const now = tx.timestamp.microsSinceUnixEpoch; + let deleted = 0; + for (const row of expiredRows) { + if (deleted >= maxRows) break; + if (row.expiresAt.microsSinceUnixEpoch > now) continue; + tx.db.rateLimitBucket.delete(row); + deleted++; + } + return deleted; +} diff --git a/spacetime-rate-limit-ts/src/submodule.ts b/spacetime-rate-limit-ts/src/submodule.ts new file mode 100644 index 00000000000..d485ce2c741 --- /dev/null +++ b/spacetime-rate-limit-ts/src/submodule.ts @@ -0,0 +1,24 @@ +export { default } from './submodule/schema.js'; +export { install } from './submodule/install.js'; +export { + client, + errors, + resetRegisteredScopes, + type RateLimitClient, + type RateLimitPolicy, + type RateLimitReadDb, + type RateLimitResult, + type RateLimitStatus, + type RateLimitTxLike, +} from './limit.js'; +export { + adminRateLimitBuckets, + addRateLimitAdmin, + removeRateLimitAdmin, + isAdmin, + requireAdmin, + rateLimitSweep, + resetBuckets, + runSweep, + updateConfig, +} from './submodule/operations.js'; diff --git a/spacetime-rate-limit-ts/src/submodule/install.ts b/spacetime-rate-limit-ts/src/submodule/install.ts new file mode 100644 index 00000000000..b937b4fcf48 --- /dev/null +++ b/spacetime-rate-limit-ts/src/submodule/install.ts @@ -0,0 +1,26 @@ +import { ScheduleAt } from 'spacetimedb'; +import { DEFAULT_SWEEP_BATCH } from '../limit.js'; +import type { ReducerModuleCtx } from './schema.js'; + +const SWEEP_INTERVAL_MICROS = 30_000_000n; + +/** + * Call from the host's init reducer. Makes the publishing identity the first + * administrator and schedules the expired-bucket sweep. Later calls do nothing. + */ +export function install(ctx: ReducerModuleCtx) { + if (ctx.db.rateLimitConfig.singleton.find(true)) return; + ctx.db.rateLimitAdminIdentity.insert({ + identity: ctx.sender, + addedAt: ctx.timestamp, + }); + ctx.db.rateLimitConfig.insert({ + singleton: true, + sweepBatch: DEFAULT_SWEEP_BATCH, + updatedAt: ctx.timestamp, + }); + ctx.db.rateLimitSweepTick.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.interval(SWEEP_INTERVAL_MICROS), + }); +} diff --git a/spacetime-rate-limit-ts/src/submodule/operations.ts b/spacetime-rate-limit-ts/src/submodule/operations.ts new file mode 100644 index 00000000000..86032bc3042 --- /dev/null +++ b/spacetime-rate-limit-ts/src/submodule/operations.ts @@ -0,0 +1,145 @@ +import { Range, SenderError } from 'spacetimedb/server'; +import type { Identity } from 'spacetimedb'; +import { + DEFAULT_SWEEP_BATCH, + MAX_SWEEP_BATCH, + sweepRateLimits, + errors, +} from '../limit.js'; +import { + rateLimitBucket, + rateLimitSweepTick, + spacetimedb, + t, + type ViewModuleCtx, +} from './schema.js'; + +/** Whether `identity` is a rate-limit administrator. */ +export function isAdmin(db: ViewModuleCtx['db'], identity: Identity): boolean { + return db.rateLimitAdminIdentity.identity.find(identity) != null; +} + +/** Throw `errors.notAuthorized` unless the caller is a rate-limit administrator. */ +export function requireAdmin(ctx: Pick): void { + if (!isAdmin(ctx.db, ctx.sender)) { + throw new SenderError(errors.notAuthorized); + } +} + +function positiveU32(code: string, value: number, max: number): number { + if (!Number.isInteger(value) || value <= 0 || value > max) { + throw new SenderError(code); + } + return value; +} + +function maxRowsArg(value: number | undefined): number { + return value === undefined + ? DEFAULT_SWEEP_BATCH + : positiveU32(errors.invalidMaxRows, value, MAX_SWEEP_BATCH); +} + +export const runSweep = spacetimedb.procedure( + { maxRows: t.option(t.u32()) }, + t.u32(), + (ctx, args) => { + const maxRows = maxRowsArg(args.maxRows); + return ctx.withTx(tx => { + requireAdmin(tx); + return sweepRateLimits( + tx, + tx.db.rateLimitBucket.expiresAt.filter( + new Range(undefined, { tag: 'included', value: tx.timestamp }) + ), + maxRows + ); + }); + } +); + +export const addRateLimitAdmin = spacetimedb.reducer( + { identity: t.identity() }, + (ctx, args) => { + requireAdmin(ctx); + if (ctx.db.rateLimitAdminIdentity.identity.find(args.identity) == null) { + ctx.db.rateLimitAdminIdentity.insert({ + identity: args.identity, + addedAt: ctx.timestamp, + }); + } + } +); + +export const removeRateLimitAdmin = spacetimedb.reducer( + { identity: t.identity() }, + (ctx, { identity }) => { + requireAdmin(ctx); + const existing = ctx.db.rateLimitAdminIdentity.identity.find(identity); + if (!existing) return; + if (ctx.db.rateLimitAdminIdentity.count() <= 1n) { + throw new SenderError(errors.cannotRemoveLastAdmin); + } + ctx.db.rateLimitAdminIdentity.delete(existing); + } +); + +export const updateConfig = spacetimedb.reducer( + { sweepBatch: t.u32() }, + (ctx, args) => { + requireAdmin(ctx); + const cfg = ctx.db.rateLimitConfig.singleton.find(true); + if (!cfg) throw new Error('rate_limit.config_missing'); + ctx.db.rateLimitConfig.singleton.update({ + ...cfg, + sweepBatch: positiveU32( + errors.invalidSweepBatch, + args.sweepBatch, + MAX_SWEEP_BATCH + ), + updatedAt: ctx.timestamp, + }); + } +); + +export const resetBuckets = spacetimedb.reducer( + { maxRows: t.option(t.u32()) }, + (ctx, args) => { + requireAdmin(ctx); + const maxRows = maxRowsArg(args.maxRows); + let removed = 0; + for (const row of ctx.db.rateLimitBucket.iter()) { + if (removed >= maxRows) break; + ctx.db.rateLimitBucket.delete(row); + removed++; + } + } +); + +export const adminRateLimitBuckets = spacetimedb.view( + { name: 'admin_rate_limit_buckets', public: true }, + t.array(rateLimitBucket.rowType), + ctx => { + if (!isAdmin(ctx.db, ctx.sender)) return []; + const rows = []; + for (const row of ctx.db.rateLimitBucket.iter()) { + if (rows.length >= 1000) break; + rows.push(row); + } + return rows; + } +); + +export const rateLimitSweep = spacetimedb.reducer( + { onSchedule: rateLimitSweepTick }, + { arg: rateLimitSweepTick.rowType }, + (ctx, _args) => { + sweepRateLimits( + ctx, + ctx.db.rateLimitBucket.expiresAt.filter( + new Range(undefined, { tag: 'included', value: ctx.timestamp }) + ), + ctx.db.rateLimitConfig.singleton.find(true)?.sweepBatch ?? + DEFAULT_SWEEP_BATCH + ); + } +); diff --git a/spacetime-rate-limit-ts/src/submodule/schema.ts b/spacetime-rate-limit-ts/src/submodule/schema.ts new file mode 100644 index 00000000000..6e89b4cfcc8 --- /dev/null +++ b/spacetime-rate-limit-ts/src/submodule/schema.ts @@ -0,0 +1,59 @@ +import { + schema, + table, + t, + type InferSchema, + type ReducerCtx, + type ViewCtx, +} from 'spacetimedb/server'; + +export const rateLimitBucket = table( + { name: 'rate_limit_bucket', public: false }, + { + key: t.string().primaryKey(), + scope: t.string().index(), + windowStart: t.timestamp().index(), + expiresAt: t.timestamp().index(), + count: t.u32(), + updatedAt: t.timestamp(), + } +); + +export const rateLimitAdminIdentity = table( + { name: 'rate_limit_admin_identity', public: false }, + { + identity: t.identity().primaryKey(), + addedAt: t.timestamp(), + } +); + +export const rateLimitConfig = table( + { name: 'rate_limit_config', public: true }, + { + singleton: t.bool().primaryKey(), + sweepBatch: t.u32(), + updatedAt: t.timestamp(), + } +); + +export const rateLimitSweepTick = table( + { name: 'rate_limit_sweep_tick' }, + { + scheduledId: t.u64().primaryKey().autoInc(), + scheduledAt: t.scheduleAt(), + } +); + +export const spacetimedb = schema({ + rateLimitBucket, + rateLimitAdminIdentity, + rateLimitConfig, + rateLimitSweepTick, +}); +export default spacetimedb; + +export type Schema = InferSchema; +export type ReducerModuleCtx = ReducerCtx; +export type ViewModuleCtx = ViewCtx; + +export { t }; diff --git a/spacetime-rate-limit-ts/tsconfig.build.json b/spacetime-rate-limit-ts/tsconfig.build.json new file mode 100644 index 00000000000..8635027968f --- /dev/null +++ b/spacetime-rate-limit-ts/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/spacetime-rate-limit-ts/tsconfig.json b/spacetime-rate-limit-ts/tsconfig.json new file mode 100644 index 00000000000..77da6c09f65 --- /dev/null +++ b/spacetime-rate-limit-ts/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "declaration": false, + "noEmit": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "isolatedModules": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/spacetime-resend-ts/.npmrc b/spacetime-resend-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-resend-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-resend-ts/LICENSE.txt b/spacetime-resend-ts/LICENSE.txt new file mode 120000 index 00000000000..cc1ff9bdd72 --- /dev/null +++ b/spacetime-resend-ts/LICENSE.txt @@ -0,0 +1 @@ +../licenses/apache2.txt \ No newline at end of file diff --git a/spacetime-resend-ts/README.md b/spacetime-resend-ts/README.md new file mode 100644 index 00000000000..7ba61661644 --- /dev/null +++ b/spacetime-resend-ts/README.md @@ -0,0 +1,243 @@ +# @spacetimedb/resend + +Send email from your SpacetimeDB application through [Resend](https://resend.com). +Use it for welcome messages, receipts, and notifications, then track whether +each message was delivered, delayed, or bounced. + +The submodule stores delivery status in your database and updates it from +Resend webhooks. Your application decides who can send email and see its history. + +## Install + +```bash +npm install @spacetimedb/resend spacetimedb +``` + +Requires SpacetimeDB 2.8.3 or later for submodule mounting. + +## Integrate into an application + +Add Resend to your module and initialize it: + +```ts +import { schema } from 'spacetimedb/server'; +import * as resend from '@spacetimedb/resend/submodule'; + +const spacetimedb = schema({ resend }); +export default spacetimedb; + +export const init = spacetimedb.init(ctx => { + resend.install(ctx.as.resend); +}); +``` + +After publishing, configure your Resend API key, sender address, and webhook +signing secret as the database owner or a Resend administrator. When mounted +as `resend`, use `resend.set_resend_config`; the arguments are shown in +[Standalone configuration](#standalone-configuration). + +Call `resend.sendEmailRequest` from a procedure that checks who may send email +and which recipients they may contact. Apply rate limits before sending: + +```ts +resend.sendEmailRequest(ctx.as.resend, { + to: ['delivered@resend.dev'], + subject: 'Welcome', + html: '

Hello.

', + tagsJson: JSON.stringify([ + { name: 'userId', value: 'u_123' }, + { name: 'orgId', value: 'launch' }, + ]), +}); +``` + +For delivery updates, register `makeResendWebhookHandler()` on an HTTP route +and add that URL in Resend. See the [Dispatch example](./example/) for a +complete send procedure, webhook route, and views that show each user only +their own email history. + +### Standalone configuration + +When running Resend as its own database, configure it with the unprefixed +operation below. Credentials are private, and the publishing owner is the +first administrator. + +```bash +spacetime call --server http://127.0.0.1:3000 spacetime-resend set_resend_config \ + '"re_..."' \ + '{"some":"whsec_..."}' \ + '{"some":"onboarding@resend.dev"}' +``` + +Args: `apiKey`, `webhookSigningSecret` (required for webhook ingest), `defaultFrom` (optional). +For `t.option(...)` CLI arguments, use `null` for no value and +`{"some":"value"}` for a string value. + +Verify: + +```bash +spacetime call --server http://127.0.0.1:3000 spacetime-resend get_resend_config_status '{}' +``` + +## Private tables + +| Table | Key | Notes | +| ----------------------- | ----------- | ------------------------------------------------------------ | +| `resend_email` | `resend_id` | one row per outbound email; `status` reflects latest webhook | +| `resend_delivery_event` | `event_id` | append-only audit log of every event for an email | + +- `resend_webhook_event` - idempotency log +- `resend_config` - credentials singleton +- `resend_admin_identity` - admin allowlist + +None of the Resend base tables are subscribable. Email recipients, subject, +body, tracking state, webhook payloads, and signature headers remain private. +Host modules should expose caller- or tenant-scoped views over `userId` or +`orgId`; the included example demonstrates this pattern. + +## API + +**Setup** + +- `set_resend_config(apiKey, webhookSigningSecret, defaultFrom)` +- `get_resend_config_status()` - `{ isConfigured, hasWebhookSecret, apiKeyLength, ... }` +- `add_admin_identity(identity)` / `remove_admin_identity(identity)` + +**Outbound** + +- `send_email({ from, to, subject, html, text, cc, bcc, replyTo, tagsJson, headersJson, scheduledAt, idempotencyKey})` - admin-gated; inserts a `resend_email` row with `status = queued`, returns `{ resendId }`. The first webhook flips it to `sent`/`delivered`. +- `cancel_email({ resendId })` - admin-gated +- `resend_api_request({ method, path, jsonBody, idempotencyKey })` - admin-gated + request to a relative `api.resend.com` path; accepted methods are `GET`, `POST`, + `PATCH`, and `DELETE` + +Email sends accept up to 100 combined `to`, `cc`, and `bcc` recipients. Address +fields are capped at 320 characters, subjects at 998 characters, HTML and text +at 200,000 characters each, and tag or header JSON at 16 KiB. Control characters +in address, subject, and schedule fields are rejected before provider HTTP. + +The generated client calls your application's send procedure, such as the +`sendDispatch` procedure in the example: + +```ts +const result = await conn.procedures.sendDispatch({ + to: 'delivered@resend.dev', + subject: 'Welcome', + message: 'Your workspace is ready.', +}); + +if (!result.ok) throw new Error(result.message); +``` + +Subscribe to a caller-scoped host view for delivery status. Keep the private +Resend tables and generic administrative send operation restricted to +operators. + +**Webhook ingest / replay** + +- `ingest_resend_webhook(eventId, eventType, payloadJson, signatureHeader, timestampHeader)` - deduplicates events by the `svix-id` header passed as `eventId` +- `replay_webhook_event(eventId)` - re-applies a stored event +- `makeResendWebhookHandler()` builds a direct HTTP webhook handler for a host + router. + +The HTTP handler returns 200 after applying an event, for an already processed +event, and for signed event types the submodule does not handle, which are stored +as `Ignored`. Invalid payloads return 400 and retain a failed event record; +redelivery retries failed records. Unexpected transaction failures propagate to +the HTTP runtime. + +The reducer throws, writing nothing, when metadata, size, headers, secret, or +signature checks reject a request. Once a signed event is stored, the reducer +commits: an invalid payload keeps its `Failed` event record with the error +message. Callers read the outcome with `get_webhook_event`. + +Delivery timestamps use the provider's event time. Older events cannot replace +newer status, and an earlier delivery stage cannot replace a later one. Queued +send responses preserve any webhook state already recorded. Opens, clicks, and +complaints update their own fields without changing delivery status. Error, +bounce, and failure details change only when their event sets the status. + +**Admin queries** + +- `get_email`, `list_emails_by_user_id`, `list_emails_by_org_id`, `list_emails_by_status` +- `list_delivery_events_for_email` +- `get_webhook_event` - stored event with `status` (`Received`, `Processed`, + `Ignored`, or `Failed`) and `errorMessage` + +List procedures return at most 1,000 rows. Host applications should expose +caller-scoped, paginated views for product-facing history. + +**Errors** + +`errors` from `@spacetimedb/resend/submodule` lists the `resend.*` codes the +submodule throws. + +Package entrypoints: + +- `@spacetimedb/resend` can run as a standalone email database. +- `@spacetimedb/resend/submodule` supplies submodule configuration, delivery, + webhook, and query helpers. + +## Webhook events handled + +``` +email.sent email.delivered +email.delivery_delayed email.bounced +email.complained email.failed +email.opened email.clicked +``` + +Other signed event types, such as `email.received`, `contact.*`, and `domain.*`, +are acknowledged and stored as `Ignored`. + +`opened` / `clicked` / `complained` are recorded as **flags + timestamps** and leave `status` unchanged. Terminal states (`delivered`, `bounced`, `failed`, `cancelled`) and in-flight states (`queued`, `sent`, `delivery_delayed`) live in the `status` column. + +## Webhook signature verification + +The `ingest_resend_webhook` reducer and the `makeResendWebhookHandler()` route verify Standard Webhooks signatures (svix) using the configured `webhookSigningSecret`. A rejected signature returns 401 with `resend.webhook_signature_mismatch:`, where the reason is a `@spacetimedb/crypto` `errors` code such as `crypto.timestamp_outside_tolerance`. `signatureHeader` and `timestampHeader` are stored on `resend_webhook_event` for forensic replay. + +## Tagging + +`userId` / `orgId` are extracted from Resend `tags` and indexed for per-user / per-org listing. + +- `send_email` takes `tagsJson` as a JSON string in the array form Resend's send API expects: `[{"name":"userId","value":"u_123"}]`. +- Resend webhook payloads carry tags in object form: `{"userId": "u_123", "orgId": "o_456"}`. + +## Integration testing + +```bash +# Build + publish + event paths, idempotency, replay, signed-type checks, and authorization checks +pnpm run test:smoke +``` + +The smoke test publishes only to the dedicated `resend-ts-smoke-test` database. + +For real Resend test-mode: + +```bash +# Bootstrap once with your real key: +spacetime call --server http://127.0.0.1:3000 spacetime-resend set_resend_config '"re_..."' null '{"some":"onboarding@resend.dev"}' + +# Then send to one of Resend's test addresses (delivered@/bounced@/complained@): +spacetime call --server http://127.0.0.1:3000 spacetime-resend send_email \ + null \ + '["delivered@resend.dev"]' \ + '"Test from SpacetimeDB"' \ + '{"some":"

Hello.

"}' \ + null null null null \ + '{"some":"[{\"name\":\"userId\",\"value\":\"u_123\"}]"}' \ + null null null +``` + +The standalone module has no HTTP route. To receive webhooks from Resend, mount the submodule in a host module that registers `makeResendWebhookHandler()` on a router, as the [example](./example/spacetimedb/) does at `/webhook/resend`. Expose the database through a public tunnel such as ngrok and register `https:///v1/database//route/webhook/resend` in Resend's dashboard with the same `whsec_...` you passed to `set_resend_config`. + +## Testing + +```bash +pnpm test +pnpm run lint +``` + +## License + +Apache-2.0. diff --git a/spacetime-resend-ts/example/.env.example b/spacetime-resend-ts/example/.env.example new file mode 100644 index 00000000000..c162013b626 --- /dev/null +++ b/spacetime-resend-ts/example/.env.example @@ -0,0 +1,28 @@ +# Copy to .env. The example server loads this on startup. + +# ---------------- Resend ---------------- +# Required to send email from Dispatch. +RESEND_API_KEY=re_... + +# Required to accept inbound webhooks (Resend dashboard, Webhooks -> your endpoint -> Signing secret). +# The module rejects requests when this is unset or the signature is invalid. +RESEND_WEBHOOK_SECRET=whsec_... + +# Optional comma-separated external recipients. Provider test recipients remain +# available automatically. The module rejects every address outside this list. +RESEND_ALLOWED_RECIPIENTS=you@example.com + +# ---------------- SpacetimeDB ---------------- +STDB_URI=ws://127.0.0.1:3000 +STDB_HTTP=http://127.0.0.1:3000 +SPACETIMEDB_DB_NAME=spacetime-resend-example +# Optional. When unset, the server creates a persistent local identity token in +# .stdb-server-token and the logged-in publishing identity authorizes it. +# STDB_SERVER_TOKEN= + +# ---------------- Static server ---------------- +PORT=8790 +HOST=127.0.0.1 + +# Default "from" address (must be a verified sender in your Resend account, or onboarding@resend.dev for testing). +DEFAULT_FROM=onboarding@resend.dev diff --git a/spacetime-resend-ts/example/.npmrc b/spacetime-resend-ts/example/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-resend-ts/example/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-resend-ts/example/README.md b/spacetime-resend-ts/example/README.md new file mode 100644 index 00000000000..562dbb2de2f --- /dev/null +++ b/spacetime-resend-ts/example/README.md @@ -0,0 +1,94 @@ +# Dispatch email example + +Send an email with Resend and watch its delivery status update in the app. + +## Run it locally + +Requires Node.js 20+, pnpm 10, and the SpacetimeDB CLI and server built from +this checkout. + +Start SpacetimeDB in a separate terminal: + +```bash +spacetime start +``` + +From `spacetime-resend-ts/example`, copy [.env.example](./.env.example) to `.env`. + +You also need a Resend API key. In `.env`, replace `RESEND_API_KEY` with your +key. Leave `RESEND_WEBHOOK_SECRET` empty until you set up a webhook below. +Remove the sample `RESEND_ALLOWED_RECIPIENTS` address or replace it with an +address you control. + +Then publish the example and start its web server: + +```bash +pnpm install +pnpm run build:module +pnpm run dev +``` + +Open . + +## Try it + +1. Click **Delivered** to use Resend's test recipient. +2. Write a subject and message, then send the email. +3. The message appears in the list. To see it change to Delivered, complete + the webhook setup below. +4. Try the **Bounced** and **Complaint** test recipients to see other outcomes. + +To send to a real address, add it to +`RESEND_ALLOWED_RECIPIENTS` and restart the example server. Use a sender that +Resend permits for your account; `DEFAULT_FROM` starts as +`onboarding@resend.dev`. + +## Receive delivery updates + +1. Use a tunnel to expose the example's `/webhook/resend` route. +2. Add that public URL as a webhook endpoint in Resend and select the email + events you want to receive. +3. Copy the endpoint's signing secret into `RESEND_WEBHOOK_SECRET`. +4. Restart `pnpm run dev` and send another test email. + +The local route is `http://127.0.0.1:8790/webhook/resend`. You can also forward +directly to the database route: + +```text +http://127.0.0.1:3000/v1/database/spacetime-resend-example/route/webhook/resend +``` + +The app rejects webhook requests with a missing or invalid signature. +Without a reachable webhook, email status stays Queued. + +## Before deploying + +Anyone who can open this demo can send to the allowed recipients. It limits +each browser identity to five sends per ten minutes and all users to 25 per +hour. Add account-based access checks before making the app public. Expose +only the webhook route when testing through a tunnel. + +The server saves its admin credential in `.stdb-server-token`. Keep that file +and `.env` private. + +## Troubleshooting + +- **Sending fails:** check the API key, allowed recipients, and sender address. +- **Status stays Queued:** check the public webhook URL and signing secret. +- **`resend.not_authorized`:** use the CLI account that published the database, + then restart the example server. + +## Change the example + +- [spacetimedb/src/index.ts](./spacetimedb/src/index.ts): email sending and delivery updates. +- [server.ts](./server.ts): Resend setup and webhook forwarding. +- [src/app.ts](./src/app.ts): email form and message list. + +After changing server code, run `pnpm run build:module`. Restart +`pnpm run dev` after changing browser code or `.env`. + +To start over, run `pnpm run build:module:fresh`. **This deletes all data in +the local `spacetime-resend-example` database.** + +To use the submodule in your own app, see the +[package integration guide](../README.md#integrate-into-an-application). diff --git a/spacetime-resend-ts/example/package.json b/spacetime-resend-ts/example/package.json new file mode 100644 index 00000000000..2dc1f7f6aa2 --- /dev/null +++ b/spacetime-resend-ts/example/package.json @@ -0,0 +1,30 @@ +{ + "name": "spacetime-resend-example", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "spacetime:generate": "spacetime generate --lang typescript --out-dir src/module_bindings --module-path ./spacetimedb -y", + "build:module": "pnpm --dir spacetimedb run build && pnpm --dir spacetimedb run publish:local && pnpm run spacetime:generate && pnpm run build:app", + "build:module:fresh": "pnpm --dir spacetimedb run build && pnpm --dir spacetimedb run publish:local:reset && pnpm run spacetime:generate && pnpm run build:app", + "check": "tsc --noEmit", + "test": "tsx scripts/test-message.ts", + "build:app": "pnpm run check && esbuild src/app.ts --bundle --format=esm --outfile=public/app.js --target=es2022 --sourcemap", + "build": "pnpm run spacetime:generate && pnpm run build:app", + "dev": "pnpm run build && tsx server.ts" + }, + "dependencies": { + "@spacetimedb/example-ui": "workspace:*", + "dotenv": "^16.4.7", + "express": "^4.21.2", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/express": "^4.17.21", + "@types/node": "^22.10.2", + "esbuild": "^0.28.0", + "resend": "^6.12.2", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-resend-ts/example/public/index.html b/spacetime-resend-ts/example/public/index.html new file mode 100644 index 00000000000..c788c2ea747 --- /dev/null +++ b/spacetime-resend-ts/example/public/index.html @@ -0,0 +1,151 @@ + + + + + + + Dispatch + + + +
+
+
+ +
+

Dispatch

+ Send an email, watch its delivery resolve live +
+
+
+ +
+
+
+

Compose

+

+ Dispatched through the mounted Resend submodule. +

+
+ +
+ + +
+
+ Message +
+ + +
+
+ + +
+ +
+
+ +
+ Resend test addresses +
+ + + +
+
+
+ +
+
+
+

Live delivery

+

+ Every dispatch and its lifecycle, streamed from SpacetimeDB. +

+
+
+ 0 sent + +
+
+ +
+
+ 0Sent +
+
+ 0Delivered +
+
+ 0Opened +
+
+ 0Bounced +
+
+ +
+
+
+ +
+ Built on + SpacetimeDB +
+
+ + + + diff --git a/spacetime-resend-ts/example/public/styles.css b/spacetime-resend-ts/example/public/styles.css new file mode 100644 index 00000000000..91cc3c7532b --- /dev/null +++ b/spacetime-resend-ts/example/public/styles.css @@ -0,0 +1,885 @@ +@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500;600&display=swap'); + +:root { + /* Tokens from spacetimedb.com/app/styles/variables.css */ + --font-inter: 'Inter', ui-sans-serif, system-ui, -apple-system, sans-serif; + --font-ibm: 'IBM Plex Mono', ui-monospace, monospace; + + --color-green: #4cf490; + --color-green-10: #4cf4901a; + --color-green-20: #4cf49033; + --color-white: #d7d8d9; + --color-yellow: #fbdc8e; + --color-purple: #a880ff; + --color-orange: #ff9e9e; + --color-blue: #02befa; + --color-pink: #ff80fb; + --color-teal: #00ccb4; + --color-red: #ff4c4c; + + --color-n1: #e6e9f0; + --color-n2: #ced3e0; + --color-n3: #b6c0cf; + --color-n4: #6f7987; + --color-n5: #363840; + --color-n8: #060606; + + --color-shade1: #162d38; + --color-shade4: #121e24; + --color-shade5: #0f191f; + --color-shade6: #0e161a; + --color-shade7: #0b1114; + --color-shade8: #0b0e12; + + --radius-sm: 6px; + --radius: 10px; + --radius-lg: 14px; +} + +* { + box-sizing: border-box; +} +html, +body { + margin: 0; + min-height: 100%; +} +body { + color: var(--color-white); + background: var(--color-shade7); + font-family: var(--font-inter); + -webkit-font-smoothing: antialiased; +} +::selection { + background: var(--color-green); + color: var(--color-n8); +} +a { + color: var(--color-green); + text-decoration: none; +} + +* { + scrollbar-width: thin; + scrollbar-color: var(--color-shade4) transparent; +} +*::-webkit-scrollbar { + width: 6px; + height: 6px; +} +*::-webkit-scrollbar-track { + background: transparent; +} +*::-webkit-scrollbar-thumb { + background: var(--color-shade4); + border-radius: 3px; +} +*::-webkit-scrollbar-thumb:hover { + background: var(--color-shade1); +} + +button, +input, +textarea { + font: inherit; +} +button { + height: 34px; + padding: 0 16px; + border: 1px solid var(--color-shade4); + border-radius: var(--radius-sm); + background: var(--color-shade7); + color: var(--color-n2); + font-family: var(--font-inter); + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: + background 0.18s, + border-color 0.18s, + color 0.18s; +} +button:hover:not(:disabled) { + background: var(--color-shade4); + color: var(--color-white); +} +button:focus-visible { + outline: 2px solid var(--color-green); + outline-offset: 2px; +} +button.primary { + background: var(--color-n3); + border-color: var(--color-n3); + color: var(--color-n8); +} +button.primary:hover:not(:disabled) { + background: var(--color-white); + border-color: var(--color-white); + color: var(--color-n8); +} +button.primary:active:not(:disabled) { + background: var(--color-green); + border-color: var(--color-green); +} +button.primary.sent { + background: var(--color-green); + border-color: var(--color-green); + color: var(--color-n8); + opacity: 1; +} +button:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +input, +textarea { + width: 100%; + padding: 10px 12px; + border: 1px solid var(--color-shade4); + border-radius: var(--radius-sm); + background: var(--color-shade8); + color: var(--color-white); + outline: none; + transition: + border-color 0.15s, + box-shadow 0.15s; +} +input { + height: 40px; + padding: 0 12px; +} +textarea { + min-height: 120px; + resize: none; + line-height: 1.5; + font-size: 14px; +} +input::placeholder, +textarea::placeholder { + color: var(--color-n4); +} +input:focus, +textarea:focus { + border-color: var(--color-green); + box-shadow: 0 0 0 3px var(--color-green-10); +} +label { + display: grid; + gap: 7px; + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 11px; + letter-spacing: 0.07em; + text-transform: uppercase; +} +h1, +h2, +h3, +p { + margin: 0; +} +.muted { + color: var(--color-n4); +} + +.shell { + width: min(1200px, calc(100% - 32px)); + margin: 0 auto; + padding: 16px 0 0; + /* Viewport height gives the feed its own scroll area. Mobile uses auto + height in the media query. */ + height: 100vh; + display: flex; + flex-direction: column; +} + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + border: 1px solid #17303b; + border-radius: var(--radius-lg); + background: linear-gradient(180deg, #0d1920, #0b1319); + box-shadow: inset 0 1px 0 #26435166; + padding: 11px 16px; + margin-bottom: 14px; +} +.brand { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; +} +.brand-mark { + flex: 0 0 auto; + width: 34px; + height: 34px; + border-radius: var(--radius); + display: grid; + place-items: center; + color: var(--color-green); + background: var(--color-green-10); + border: 1px solid var(--color-green-20); +} +.brand-mark svg { + width: 18px; + height: 18px; +} +.brand-text { + display: grid; + gap: 1px; + min-width: 0; +} +.brand-text h1 { + margin: 0; + font-size: 15px; + font-weight: 700; + line-height: 1.2; + color: var(--color-n1); +} +.brand-sub { + color: var(--color-n4); + font-size: 12px; +} + +.workspace { + flex: 1; + display: grid; + grid-template-columns: 372px minmax(0, 1fr); + /* One row that is at least 520px and otherwise fills the viewport, so both + panels are always equal height and grow when the window grows. */ + grid-template-rows: minmax(520px, 1fr); + gap: 14px; + align-items: stretch; + min-height: 0; + margin-bottom: 16px; +} +.panel { + border: 1px solid var(--color-shade4); + border-radius: var(--radius-lg); + background: linear-gradient(180deg, var(--color-shade5), var(--color-shade6)); +} + +/* Compose */ +.compose { + padding: 18px; + display: flex; + flex-direction: column; + gap: 16px; +} +.compose-head { + display: grid; + gap: 3px; +} +.compose-head h2 { + font-size: 15px; + font-weight: 700; + color: var(--color-n1); +} +.compose-head p { + font-size: 13px; +} +.form-grid { + display: flex; + flex-direction: column; + gap: 13px; + flex: 1; + min-height: 0; +} +.form-grid > button.primary { + height: 42px; + font-size: 14px; +} +.field { + display: flex; + flex-direction: column; + gap: 7px; + flex: 1; + min-height: 0; +} +.field textarea, +.field .mail-preview { + flex: 1; + min-height: 120px; +} + +.test-block { + display: grid; + gap: 9px; +} +.test-label { + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 11px; + letter-spacing: 0.07em; + text-transform: uppercase; +} +.test-row { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; +} +.test-row button { + min-width: 0; + height: 32px; + padding: 0 6px; + font-size: 12px; +} +.test-row button b { + display: block; + font-size: 12px; + font-weight: 600; + color: var(--color-n2); +} + +/* Message field with write/preview tabs */ +.field-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; +} +.field-label { + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 11px; + letter-spacing: 0.07em; + text-transform: uppercase; +} +.msg-tabs { + display: inline-flex; + gap: 2px; + padding: 2px; + border: 1px solid var(--color-shade4); + border-radius: var(--radius-sm); + background: var(--color-shade8); +} +.msg-tab { + height: 24px; + padding: 0 12px; + border: 0; + border-radius: 4px; + background: transparent; + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; +} +.msg-tab:hover:not(.active) { + background: transparent; + color: var(--color-n2); +} +.msg-tab.active { + background: var(--color-shade4); + color: var(--color-n1); +} + +.mail-preview { + min-height: 128px; + border: 1px solid var(--color-shade4); + border-radius: var(--radius-sm); + background: #ffffff; + overflow: hidden; +} +.mp-head { + padding: 12px 14px; + border-bottom: 1px solid #e6e8ec; + background: #f6f7f9; +} +.mp-subject { + font-size: 14px; + font-weight: 600; + color: #1f2933; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.mp-from { + margin-top: 3px; + font-size: 12px; + color: #6b7280; +} +.mp-body { + padding: 14px; + font-size: 14px; + color: #1f2933; + line-height: 1.6; + word-break: break-word; +} +.mp-body .mp-empty { + color: #9aa3af; + font-style: italic; +} + +.form-error { + color: var(--color-orange); + font-family: var(--font-ibm); + font-size: 12px; + line-height: 1.4; +} +.form-error:empty { + display: none; +} + +/* Live delivery console */ +.console { + display: grid; + grid-template-rows: auto auto minmax(0, 1fr); + min-height: 0; +} +.console-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + padding: 16px 18px; + border-bottom: 1px solid var(--color-shade4); +} +.console-copy { + display: grid; + gap: 3px; +} +.console-copy h2 { + font-size: 15px; + font-weight: 700; + color: var(--color-n1); +} +.console-copy p { + font-size: 13px; +} +.console-right { + display: flex; + align-items: center; + gap: 12px; +} +.feed-count { + color: var(--color-n5); + font-family: var(--font-ibm); + font-size: 11px; +} +#clear-btn { + height: 30px; + padding: 0 12px; + font-size: 12px; +} +#clear-btn:disabled { + opacity: 0.4; +} + +.metrics { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 10px; + padding: 16px 18px; + border-bottom: 1px solid var(--color-shade4); +} +.metric { + display: grid; + gap: 7px; + padding: 13px; + border: 1px solid var(--color-shade4); + border-radius: var(--radius); + background: var(--color-shade7); +} +.metric strong { + font-size: 25px; + font-weight: 700; + line-height: 1; + color: var(--color-white); + font-variant-numeric: tabular-nums; +} +.metric span { + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 10px; + letter-spacing: 0.06em; + text-transform: uppercase; +} +.metric.delivered strong { + color: var(--color-green); +} +.metric.opened strong { + color: var(--color-green); +} +.metric.bounced strong { + color: var(--color-red); +} + +.feed { + min-height: 0; + overflow-y: auto; + padding: 14px 18px 18px; + display: grid; + gap: 11px; + align-content: start; +} + +.mail { + border: 1px solid var(--color-shade4); + border-radius: var(--radius); + background: var(--color-shade7); + padding: 14px 15px 16px; + transition: border-color 0.15s; +} +.mail:hover { + border-color: var(--color-shade1); +} +.mail.bad { + border-color: #4a2626; +} +.mail-head { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto auto; + gap: 11px; + align-items: center; +} +.mail-del { + width: 26px; + height: 26px; + padding: 0; + flex: 0 0 auto; + border: 1px solid transparent; + border-radius: var(--radius-sm); + background: transparent; + color: var(--color-n5); + font-size: 17px; + line-height: 1; + display: grid; + place-items: center; +} +.mail-del:hover:not(:disabled) { + background: #1a0f0f; + border-color: #4a2626; + color: var(--color-red); +} +.avatar { + width: 36px; + height: 36px; + flex: 0 0 auto; + border-radius: var(--radius); + display: grid; + place-items: center; + font-weight: 700; + font-size: 12px; + color: var(--av, var(--color-n3)); + background: color-mix(in srgb, var(--av, #555) 15%, transparent); + border: 1px solid color-mix(in srgb, var(--av, #555) 32%, transparent); +} +.mail-who { + min-width: 0; +} +.mail-to { + font-size: 14px; + color: var(--color-n1); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.mail-sub { + margin-top: 2px; + font-size: 13px; + color: var(--color-n4); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.mail-when { + flex: 0 0 auto; + text-align: right; + color: var(--color-n5); + font-family: var(--font-ibm); + font-size: 11px; +} + +/* Delivery timeline */ +.track { + display: flex; + margin-top: 15px; +} +.node { + flex: 1; + position: relative; + text-align: center; + min-width: 0; +} +.node::before { + content: ''; + position: absolute; + top: 6px; + left: -50%; + width: 100%; + height: 2px; + background: var(--color-shade4); +} +.node:first-child::before { + display: none; +} +.bead { + position: relative; + z-index: 1; + display: block; + width: 14px; + height: 14px; + margin: 0 auto; + border-radius: 50%; + background: var(--color-shade4); + border: 2px solid var(--color-shade6); +} +.node-label { + display: block; + margin-top: 7px; + font-family: var(--font-ibm); + font-size: 10px; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--color-n5); +} +.node-time { + display: block; + margin-top: 2px; + font-family: var(--font-ibm); + font-size: 10px; + color: var(--color-n5); + min-height: 12px; +} + +.node.done::before { + background: var(--color-green); +} +.node.done .bead { + background: var(--color-green); + box-shadow: 0 0 0 3px var(--color-green-10); +} +.node.done .node-label { + color: var(--color-n2); +} +.node.done .node-time { + color: var(--color-n4); +} + +.node.live::before { + background: var(--color-green); +} +.node.live .bead { + background: var(--color-green); + box-shadow: 0 0 0 5px color-mix(in srgb, var(--color-green) 26%, transparent); + animation: live-pulse 1.8s ease-in-out infinite; +} +.node.live .node-label { + color: var(--color-green); +} + +.node.bad::before { + background: var(--color-red); +} +.node.bad .bead { + background: var(--color-red); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-red) 20%, transparent); +} +.node.bad .node-label { + color: var(--color-red); +} + +.node.warn::before { + background: var(--color-yellow); +} +.node.warn .bead { + background: var(--color-yellow); +} +.node.warn .node-label { + color: var(--color-yellow); +} + +/* One-shot: the node that just reached its state ripples out from the bead. + Applied only to the node that changed this render. */ +.node.just-lit .bead::after { + content: ''; + position: absolute; + inset: -3px; + border-radius: 50%; + border: 2px solid var(--color-green); + animation: bead-ripple 0.65s ease-out forwards; +} +.node.just-lit.bad .bead::after { + border-color: var(--color-red); +} +.node.just-lit.warn .bead::after { + border-color: var(--color-yellow); +} +.node.just-lit::before { + animation: connector-sweep 0.5s ease-out; +} +.node.just-lit .node-label, +.node.just-lit .node-time { + animation: label-in 0.5s ease-out; +} + +.mail.card-enter { + animation: card-enter 0.4s cubic-bezier(0.2, 0.8, 0.2, 1); +} +/* Odometer roll: the current number exits as the incoming value enters. + JavaScript injects the clip window for the animation. */ +.metric strong .odo-clip { + display: block; + overflow: hidden; + height: 1em; +} +.metric strong .odo { + display: block; +} +.metric strong .odo-line { + height: 1em; + line-height: 1; +} +.metric strong .odo.roll-up { + animation: odo-up 0.42s cubic-bezier(0.3, 0.9, 0.3, 1) forwards; +} +.metric strong .odo.roll-down { + animation: odo-down 0.42s cubic-bezier(0.3, 0.9, 0.3, 1) forwards; +} + +@keyframes live-pulse { + 0%, + 100% { + box-shadow: 0 0 0 5px + color-mix(in srgb, var(--color-green) 26%, transparent); + } + 50% { + box-shadow: 0 0 0 8px color-mix(in srgb, var(--color-green) 8%, transparent); + } +} +@keyframes bead-ripple { + 0% { + transform: scale(1); + opacity: 0.9; + } + 100% { + transform: scale(2.6); + opacity: 0; + } +} +@keyframes connector-sweep { + 0% { + clip-path: inset(0 100% 0 0); + } + 100% { + clip-path: inset(0 0 0 0); + } +} +@keyframes label-in { + 0% { + opacity: 0.35; + } + 100% { + opacity: 1; + } +} +@keyframes card-enter { + 0% { + opacity: 0; + transform: translateY(-8px) scale(0.985); + } + 100% { + opacity: 1; + transform: none; + } +} +@keyframes odo-up { + from { + transform: translateY(0); + } + to { + transform: translateY(-1em); + } +} +@keyframes odo-down { + from { + transform: translateY(-1em); + } + to { + transform: translateY(0); + } +} +@media (prefers-reduced-motion: reduce) { + .node.live .bead, + .node.just-lit .bead::after, + .node.just-lit::before, + .node.just-lit .node-label, + .node.just-lit .node-time, + .mail.card-enter, + .metric strong .odo { + animation: none; + } +} + +.mail-err { + margin-top: 12px; + padding: 8px 10px; + border: 1px solid #4a2626; + border-radius: var(--radius-sm); + background: #1a0f0f; + color: var(--color-orange); + font-family: var(--font-ibm); + font-size: 11px; + line-height: 1.4; +} + +.empty { + border: 1px dashed var(--color-shade4); + border-radius: var(--radius); + padding: 34px 18px; + color: var(--color-n4); + text-align: center; + font-size: 13px; + line-height: 1.5; +} + +.page-foot { + min-height: 58px; + display: flex; + align-items: center; + justify-content: center; + gap: 11px; + border-top: 1px solid var(--color-shade4); +} +.page-foot .by { + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 10px; + font-weight: 600; + letter-spacing: 0.12em; + text-transform: uppercase; +} +.page-foot img { + height: 26px; + width: auto; + opacity: 0.85; +} + +@media (max-width: 1040px) { + /* Stack the panels at their natural heights and use page-level scrolling. */ + .shell { + height: auto; + min-height: 100vh; + } + .workspace { + grid-template-columns: 1fr; + grid-template-rows: none; + align-items: start; + } + .console { + min-height: 560px; + } +} +@media (max-width: 560px) { + .metrics { + grid-template-columns: repeat(2, 1fr); + } + .node-label { + font-size: 9px; + } +} diff --git a/spacetime-resend-ts/example/scripts/test-message.ts b/spacetime-resend-ts/example/scripts/test-message.ts new file mode 100644 index 00000000000..c7d2169c2c0 --- /dev/null +++ b/spacetime-resend-ts/example/scripts/test-message.ts @@ -0,0 +1,15 @@ +import assert from 'node:assert/strict'; +import { messageHtml } from '../spacetimedb/src/message'; + +const html = messageHtml( + 'Hello & friends\nNext line\n\nSecond paragraph' +); + +assert.match(html, /BlinkMacSystemFont/); +assert.match(html, /max-width:560px/); +assert.match(html, /Hello <team> & friends
Next line/); +assert.match(html, /Second paragraph/); +assert.equal((html.match(/

/); + +console.log('resend message tests passed'); diff --git a/spacetime-resend-ts/example/server.ts b/spacetime-resend-ts/example/server.ts new file mode 100644 index 00000000000..2fe498fb2db --- /dev/null +++ b/spacetime-resend-ts/example/server.ts @@ -0,0 +1,237 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { existsSync, readFileSync } from 'node:fs'; +import express, { type Request, type Response } from 'express'; +import dotenv from 'dotenv'; +import { + discardStoredServerToken, + exampleUiAssetsDir, + grantServerIdentity, + loadServerToken, + saveServerToken, +} from '@spacetimedb/example-ui/server'; +import { DbConnection, type ErrorContext } from './src/module_bindings'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const inheritedEnv = new Set(Object.keys(process.env)); + +function loadEnv(pathname: string, override: boolean): void { + if (!existsSync(pathname)) return; + + const parsed = dotenv.parse(readFileSync(pathname)); + for (const [key, value] of Object.entries(parsed)) { + if (value.trim() === '') continue; + if (inheritedEnv.has(key)) continue; + if (override || process.env[key] === undefined) { + process.env[key] = value; + } + } +} + +// Shared env supplies secrets/defaults; example-local env wins for app settings. +// Explicit process environment has highest priority. +loadEnv(path.resolve(__dirname, '..', '..', '.env'), false); +loadEnv(path.resolve(__dirname, '..', '.env'), false); +loadEnv(path.resolve(__dirname, '.env'), true); + +const PORT = Number.parseInt(process.env.PORT ?? '8790', 10); +const HOST = process.env.HOST?.trim() || '127.0.0.1'; +const STDB_URI = process.env.STDB_URI ?? 'ws://127.0.0.1:3000'; +const STDB_HTTP = process.env.STDB_HTTP ?? 'http://127.0.0.1:3000'; +const DB_NAME = process.env.SPACETIMEDB_DB_NAME ?? 'spacetime-resend-example'; +const SPACETIME_BIN = process.env.SPACETIME_BIN?.trim() || 'spacetime'; +const RESEND_API_KEY = process.env.RESEND_API_KEY ?? ''; +const RESEND_WEBHOOK_SECRET = process.env.RESEND_WEBHOOK_SECRET ?? ''; +const DEFAULT_FROM = process.env.DEFAULT_FROM ?? 'onboarding@resend.dev'; +const RESEND_TEST_RECIPIENTS = [ + 'delivered@resend.dev', + 'bounced@resend.dev', + 'complained@resend.dev', +]; +const ALLOWED_RECIPIENTS = [ + ...new Set([ + ...RESEND_TEST_RECIPIENTS, + ...(process.env.RESEND_ALLOWED_RECIPIENTS ?? '') + .split(',') + .map(value => value.trim().toLowerCase()) + .filter(Boolean), + ]), +]; +const SERVER_TOKEN_PATH = path.resolve(__dirname, '.stdb-server-token'); + +let stdb: DbConnection | null = null; +let resendConfigured = false; + +type ConnectedServer = { + connection: DbConnection; + identity: string; +}; + +function connectAttempt(token: string | undefined): Promise { + return new Promise((resolve, reject) => { + let builder = DbConnection.builder() + .withUri(STDB_URI) + .withDatabaseName(DB_NAME) + .onConnect((connection, identity, nextToken) => { + if (!process.env.STDB_SERVER_TOKEN?.trim()) { + saveServerToken(SERVER_TOKEN_PATH, nextToken); + } + resolve({ connection, identity: identity.toHexString() }); + }) + .onDisconnect((_ctx, err) => { + console.error( + `[stdb] disconnected: ${err?.message ?? 'unknown'} - exiting for supervisor restart` + ); + process.exit(1); + }) + .onConnectError((_ctx: ErrorContext, err) => reject(err)); + if (token) builder = builder.withToken(token); + builder.build(); + }); +} + +async function connect(): Promise { + const stored = loadServerToken( + SERVER_TOKEN_PATH, + process.env.STDB_SERVER_TOKEN + ); + try { + return await connectAttempt(stored.token); + } catch (error) { + if (stored.source !== 'file') throw error; + discardStoredServerToken(SERVER_TOKEN_PATH); + console.warn( + '[stdb] stored server token was rejected; creating a new identity' + ); + return connectAttempt(undefined); + } +} + +function requireStdb(): DbConnection { + if (!stdb) throw new Error('STDB not connected yet'); + return stdb; +} + +const app = express(); + +// Webhook uses the raw body because Svix signs raw bytes. Register it before express.json(). +app.post( + '/webhook/resend', + express.raw({ type: '*/*', limit: '512kb' }), + handleResendWebhook +); + +app.use(express.json({ limit: '512kb' })); +app.use('/assets', express.static(exampleUiAssetsDir)); +app.use(express.static(path.join(__dirname, 'public'))); + +app.get('/api/health', (_req: Request, res: Response) => { + res.json({ ok: true, databaseName: DB_NAME }); +}); + +app.get('/api/config', (_req: Request, res: Response) => { + res.json({ + spacetimeUri: STDB_URI, + databaseName: DB_NAME, + resendConfigured, + defaultFrom: DEFAULT_FROM, + allowedRecipients: ALLOWED_RECIPIENTS, + }); +}); + +async function handleResendWebhook(req: Request, res: Response): Promise { + const rawBody = + req.body instanceof Buffer ? req.body : Buffer.from(String(req.body ?? '')); + const url = `${STDB_HTTP}/v1/database/${DB_NAME}/route/webhook/resend`; + + const headers: Record = { + 'content-type': 'application/json', + }; + for (const name of ['svix-id', 'svix-timestamp', 'svix-signature']) { + const value = req.headers[name]; + if (typeof value === 'string') headers[name] = value; + else if (Array.isArray(value)) headers[name] = value.join(','); + } + + try { + const upstream = await fetch(url, { + method: 'POST', + headers, + body: rawBody, + }); + const text = await upstream.text(); + res.status(upstream.status).send(text); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + console.error(`[webhook] passthrough to STDB route failed: ${reason}`); + res.status(502).send(`passthrough failed: ${reason}`); + } +} + +async function bootstrapResendConfig(): Promise { + if (!RESEND_API_KEY) { + resendConfigured = false; + process.stdout.write( + ' ! RESEND_API_KEY missing: Dispatch connects; email sends require configuration\n' + ); + return; + } + + await requireStdb().procedures.resend.setResendConfig({ + apiKey: RESEND_API_KEY, + webhookSigningSecret: RESEND_WEBHOOK_SECRET || undefined, + defaultFrom: DEFAULT_FROM, + }); + await requireStdb().procedures.setDispatchPolicy({ + allowedRecipientsJson: JSON.stringify(ALLOWED_RECIPIENTS), + }); + resendConfigured = true; + process.stdout.write(' + Resend config loaded from server environment\n'); +} + +(async () => { + console.log(`[stdb] connecting to ${STDB_URI}/${DB_NAME} ...`); + try { + const connected = await connect(); + stdb = connected.connection; + grantServerIdentity({ + spacetimeBin: SPACETIME_BIN, + server: STDB_HTTP, + database: DB_NAME, + procedure: 'resend.add_admin_identity', + identity: connected.identity, + }); + console.log(`[stdb] connected as authorized server ${connected.identity}`); + } catch (err) { + console.error( + `[stdb] connection or authorization failed: ${err instanceof Error ? err.message : String(err)}` + ); + console.error( + '[stdb] is the SpacetimeDB host running and the module published?' + ); + process.exit(1); + } + + try { + await bootstrapResendConfig(); + } catch (err) { + console.error( + `[resend] configuration failed: ${err instanceof Error ? err.message : String(err)}` + ); + process.exit(1); + } + + app.listen(PORT, HOST, () => { + process.stdout.write(`\nDispatch running at http://${HOST}:${PORT}\n`); + if (!RESEND_WEBHOOK_SECRET) { + process.stdout.write( + ' ! RESEND_WEBHOOK_SECRET not set - incoming webhooks are rejected\n' + ); + } + process.stdout.write( + ` webhook endpoint: POST http://127.0.0.1:${PORT}/webhook/resend\n` + ); + process.stdout.write(` database: ${STDB_URI}/${DB_NAME}\n\n`); + }); +})(); diff --git a/spacetime-resend-ts/example/spacetimedb/.npmrc b/spacetime-resend-ts/example/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-resend-ts/example/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-resend-ts/example/spacetimedb/package.json b/spacetime-resend-ts/example/spacetimedb/package.json new file mode 100644 index 00000000000..375d324832a --- /dev/null +++ b/spacetime-resend-ts/example/spacetimedb/package.json @@ -0,0 +1,20 @@ +{ + "name": "spacetime-resend-example-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-resend-example", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-resend-example" + }, + "dependencies": { + "@spacetimedb/rate-limit": "workspace:*", + "@spacetimedb/resend": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-resend-ts/example/spacetimedb/src/index.ts b/spacetime-resend-ts/example/spacetimedb/src/index.ts new file mode 100644 index 00000000000..fccdac9112a --- /dev/null +++ b/spacetime-resend-ts/example/spacetimedb/src/index.ts @@ -0,0 +1,273 @@ +// The browser never talks to Resend directly and is never granted admin. It calls +// host procedures that forward to the submodule through `ctx.as.resend`. Resend's +// base tables stay private; caller-scoped views below expose only the current +// connection's dispatches. + +import { schema, table, t, SenderError, Router } from 'spacetimedb/server'; +import * as resend from '@spacetimedb/resend/submodule'; +import * as rateLimit from '@spacetimedb/rate-limit/submodule'; +import { messageHtml } from './message'; + +const dispatchPolicy = table( + { name: 'dispatch_policy', public: false }, + { + singleton: t.bool().primaryKey(), + allowedRecipientsJson: t.string(), + updatedAt: t.timestamp(), + } +); + +// Removed dispatches stay in the Resend tables so later webhooks update the +// existing row instead of recreating it. The views skip these ids. +const removedDispatch = table( + { name: 'removed_dispatch', public: false }, + { resendId: t.string().primaryKey() } +); + +const spacetimedb = schema({ + resend, + rateLimit, + dispatchPolicy, + removedDispatch, +}); + +function subjectFor(ctx: { sender: { toHexString(): string } }): string { + return ctx.sender.toHexString(); +} + +export const myDispatchEmails = spacetimedb.view( + { name: 'my_dispatch_emails', public: true }, + resend.t.array(resend.resendEmailTable.rowType), + ctx => + [...ctx.db.resend.resendEmail.byUserId.filter(subjectFor(ctx))].filter( + email => !ctx.db.removedDispatch.resendId.find(email.resendId) + ) +); + +export const myDispatchDeliveryEvents = spacetimedb.view( + { name: 'my_dispatch_delivery_events', public: true }, + resend.t.array(resend.resendDeliveryEventTable.rowType), + ctx => { + const out = []; + for (const email of ctx.db.resend.resendEmail.byUserId.filter( + subjectFor(ctx) + )) { + if (ctx.db.removedDispatch.resendId.find(email.resendId)) continue; + for (const event of ctx.db.resend.resendDeliveryEvent.byResendId.filter( + email.resendId + )) { + out.push(event); + } + } + return out; + } +); + +const MAX_SUBJECT = 200; +const MAX_MESSAGE = 5000; +const MAX_ALLOWED_RECIPIENTS = 10; +const MAX_RECIPIENT_POLICY_LENGTH = 4096; +const CALLER_SEND_LIMIT = 5; +const CALLER_WINDOW_SECONDS = 10 * 60; +const GLOBAL_SEND_LIMIT = 25; +const GLOBAL_WINDOW_SECONDS = 60 * 60; +const callerLimiter = rateLimit.client({ + scope: 'dispatch.send.caller', + limit: CALLER_SEND_LIMIT, + windowSeconds: CALLER_WINDOW_SECONDS, +}); +const globalLimiter = rateLimit.client({ + scope: 'dispatch.send.global', + limit: GLOBAL_SEND_LIMIT, + windowSeconds: GLOBAL_WINDOW_SECONDS, +}); + +function fail(message: string): never { + throw new SenderError(`dispatch.${message}`); +} + +function normalizeEmail(email: string): string { + const out = email.trim().toLowerCase(); + if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(out)) fail('invalid_email'); + return out; +} + +function parseAllowedRecipients(value: string): string[] { + if (value.length > MAX_RECIPIENT_POLICY_LENGTH) { + fail('recipient_policy_too_large'); + } + let parsed: unknown; + try { + parsed = JSON.parse(value); + } catch { + fail('invalid_recipient_policy'); + } + if (!Array.isArray(parsed) || parsed.length === 0) { + fail('invalid_recipient_policy'); + } + const recipients = [ + ...new Set(parsed.map(value => normalizeEmail(String(value)))), + ]; + if (recipients.length > MAX_ALLOWED_RECIPIENTS) { + fail('too_many_allowed_recipients'); + } + return recipients; +} + +function clean( + value: string | undefined, + fallback: string, + max: number +): string { + const out = (value ?? '').trim().replace(/\s+/g, ' '); + return (out || fallback).slice(0, max); +} + +const dispatchSendResult = t.object('DispatchSendResult', { + ok: t.bool(), + resendId: t.option(t.string()), + message: t.string(), +}); + +export const setDispatchPolicy = spacetimedb.procedure( + { allowedRecipientsJson: t.string() }, + t.bool(), + (ctx, args) => { + const isAdmin = ctx.withTx( + tx => tx.db.resend.resendAdminIdentity.identity.find(ctx.sender) != null + ); + if (!isAdmin) fail('not_authorized'); + const recipients = parseAllowedRecipients(args.allowedRecipientsJson); + ctx.withTx(tx => { + const existing = tx.db.dispatchPolicy.singleton.find(true); + const row = { + singleton: true, + allowedRecipientsJson: JSON.stringify(recipients), + updatedAt: ctx.timestamp, + }; + if (existing) tx.db.dispatchPolicy.singleton.update(row); + else tx.db.dispatchPolicy.insert(row); + }); + return true; + } +); + +// The host policy restricts recipients and applies caller and global quotas before +// delegating delivery through the private Resend configuration. +export const sendDispatch = spacetimedb.procedure( + { + to: t.string(), + subject: t.string(), + message: t.string(), + }, + dispatchSendResult, + (ctx, args) => { + const to = normalizeEmail(args.to); + const subject = clean(args.subject, '(no subject)', MAX_SUBJECT); + const message = (args.message ?? '').trim().slice(0, MAX_MESSAGE); + if (!message) fail('empty_message'); + + const policyJson = ctx.withTx( + tx => + tx.db.dispatchPolicy.singleton.find(true)?.allowedRecipientsJson ?? null + ); + if (policyJson == null) fail('policy_missing'); + const allowed = parseAllowedRecipients(policyJson); + if (!allowed.includes(to)) fail('recipient_not_allowed'); + + const authorization = ctx.withTx(tx => { + const caller = callerLimiter.consume(tx.as.rateLimit, { + key: subjectFor(ctx), + }); + if (!caller.allowed) return 'rate_limited' as const; + const global = globalLimiter.consume(tx.as.rateLimit, { key: 'global' }); + return global.allowed ? ('allowed' as const) : ('rate_limited' as const); + }); + if (authorization !== 'allowed') fail(authorization); + + try { + const result = resend.sendEmailRequest(ctx.as.resend, { + to: [to], + subject, + html: messageHtml(message), + text: message, + tagsJson: JSON.stringify([ + { name: 'source', value: 'dispatch' }, + { name: 'userId', value: subjectFor(ctx) }, + ]), + }); + return { + ok: true, + resendId: result.resendId, + message: `Dispatched to ${to}.`, + }; + } catch { + return { + ok: false, + resendId: undefined, + message: 'dispatch.delivery_failed', + }; + } + } +); + +const dispatchDeleteResult = t.object('DispatchDeleteResult', { + ok: t.bool(), + removed: t.u32(), +}); + +// Remove dispatches from the caller's log. This is a demo convenience so the +// log can be pruned. +export const deleteDispatch = spacetimedb.procedure( + { resendId: t.string() }, + dispatchDeleteResult, + (ctx, args) => { + return ctx.withTx(tx => { + const row = tx.db.resend.resendEmail.resendId.find(args.resendId); + if ( + row?.userId !== subjectFor(ctx) || + tx.db.removedDispatch.resendId.find(args.resendId) + ) { + return { ok: true, removed: 0 }; + } + tx.db.removedDispatch.insert({ resendId: args.resendId }); + return { ok: true, removed: 1 }; + }); + } +); + +export const clearDispatches = spacetimedb.procedure( + {}, + dispatchDeleteResult, + ctx => { + return ctx.withTx(tx => { + let removed = 0; + for (const row of tx.db.resend.resendEmail.byUserId.filter( + subjectFor(ctx) + )) { + if (tx.db.removedDispatch.resendId.find(row.resendId)) continue; + tx.db.removedDispatch.insert({ resendId: row.resendId }); + removed += 1; + } + return { ok: true, removed }; + }); + } +); + +// Resend posts delivery webhooks straight to the database over a native STDB HTTP +// route. The submodule verifies the svix signature in-module (via crypto-ts) and +// ingests. No Node relay does any of this work. +const resendWebhookHandler = resend.makeResendWebhookHandler(); +export const resendWebhook = spacetimedb.httpHandler((ctx, req) => + resendWebhookHandler(ctx.as.resend, req) +); +export const router = spacetimedb.httpRouter( + new Router().post('/webhook/resend', resendWebhook) +); + +export const init = spacetimedb.init(ctx => { + resend.install(ctx.as.resend); + rateLimit.install(ctx.as.rateLimit); +}); + +export default spacetimedb; diff --git a/spacetime-resend-ts/example/spacetimedb/src/message.ts b/spacetime-resend-ts/example/spacetimedb/src/message.ts new file mode 100644 index 00000000000..38656a3766c --- /dev/null +++ b/spacetime-resend-ts/example/spacetimedb/src/message.ts @@ -0,0 +1,20 @@ +function escapeHtml(value: string): string { + return value + .replace(/&/g, '&') + .replace(//g, '>'); +} + +export function messageHtml(message: string): string { + const paragraphs = message + .split(/\n{2,}/) + .map(block => escapeHtml(block).replace(/\n/g, '
')) + .map(block => `

${block}

`) + .join(''); + return [ + "
', + paragraphs, + '
', + ].join(''); +} diff --git a/spacetime-resend-ts/example/spacetimedb/tsconfig.json b/spacetime-resend-ts/example/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..f004a6cbc79 --- /dev/null +++ b/spacetime-resend-ts/example/spacetimedb/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "declaration": false, + "noEmit": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "isolatedModules": true, + "allowImportingTsExtensions": true + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/spacetime-resend-ts/example/src/app.ts b/spacetime-resend-ts/example/src/app.ts new file mode 100644 index 00000000000..1193f9e73f4 --- /dev/null +++ b/spacetime-resend-ts/example/src/app.ts @@ -0,0 +1,673 @@ +import { + DbConnection, + tables, + type ErrorContext, + type EventContext, + type SubscriptionEventContext, +} from './module_bindings'; +import type { Timestamp } from 'spacetimedb'; +import { messageHtml } from '../spacetimedb/src/message'; + +type TableAccessor = { + iter(): Iterable; + onInsert(cb: (ctx: EventContext, row: T) => void): void; + onUpdate(cb: (ctx: EventContext, old: T, row: T) => void): void; + onDelete(cb: (ctx: EventContext, row: T) => void): void; +}; + +// Mirrors the caller-scoped my_dispatch_emails view. Options arrive as +// `T | undefined`; status is a tagged enum. +type ResendEmail = { + resendId: string; + fromAddress: string; + toAddressesJson: string; + subject?: string; + status: { tag: string } | string; + lastError?: string; + bouncedAt?: Timestamp; + failedAt?: Timestamp; + failureReason?: string; + complained: boolean; + complainedAt?: Timestamp; + opened: boolean; + openedAt?: Timestamp; + clicked: boolean; + clickedAt?: Timestamp; + deliveredAt?: Timestamp; + sentAt?: Timestamp; + createdAt: Timestamp; + updatedAt: Timestamp; +}; + +type SendResult = { + ok: boolean; + resendId?: string; + message: string; +}; + +type ServerConfig = { + spacetimeUri: string; + databaseName: string; + resendConfigured: boolean; + defaultFrom: string; + allowedRecipients: string[]; +}; + +const $ = (id: string) => + document.getElementById(id) as T; + +let conn: DbConnection | null = null; +let currentConfig: ServerConfig | null = null; +let sending = false; + +function escapeHtml(value: unknown): string { + return String(value ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function tagOf(value: { tag: string } | string | undefined): string { + if (value && typeof value === 'object' && 'tag' in value) return value.tag; + return String(value ?? ''); +} + +function timestampMs(ts: Timestamp | undefined): number { + if (!ts) return 0; + return Number(ts.microsSinceUnixEpoch / 1000n); +} + +function timeLabel(ts: Timestamp | undefined): string { + const ms = timestampMs(ts); + if (!ms) return ''; + return new Date(ms).toLocaleTimeString([], { + hour: 'numeric', + minute: '2-digit', + second: '2-digit', + }); +} + +const AVATAR_COLORS = [ + '#4cf490', + '#02befa', + '#a880ff', + '#fbdc8e', + '#ff9e9e', + '#00ccb4', + '#ff80fb', +]; + +// The Resend test addresses always get the same, recognizable colour. +const KNOWN_AVATAR_COLORS: Record = { + 'delivered@resend.dev': '#4cf490', // green + 'bounced@resend.dev': '#ff9e9e', // orange + 'complained@resend.dev': '#a880ff', // purple +}; + +function avatarColor(seed: string): string { + const known = KNOWN_AVATAR_COLORS[seed.toLowerCase()]; + if (known) return known; + let h = 0; + for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) >>> 0; + return AVATAR_COLORS[h % AVATAR_COLORS.length]; +} + +function recipient(row: ResendEmail): string { + try { + const parsed = JSON.parse(row.toAddressesJson); + if (Array.isArray(parsed) && parsed.length > 0) return String(parsed[0]); + } catch { + /* fall through */ + } + return row.toAddressesJson; +} + +function initials(email: string): string { + const local = email.split('@')[0] ?? email; + return (local.slice(0, 2) || '?').toUpperCase(); +} + +function showError(message: string) { + $('form-error').textContent = message; +} + +function clearError() { + $('form-error').textContent = ''; +} + +let flashTimer: ReturnType | undefined; + +function flashSent() { + const btn = $('send-btn') as HTMLButtonElement; + btn.classList.add('sent'); + btn.textContent = 'Sent'; + if (flashTimer) clearTimeout(flashTimer); + flashTimer = setTimeout(() => { + btn.classList.remove('sent'); + if (!sending) btn.textContent = 'Send'; + }, 1800); +} + +async function loadServerConfig(): Promise { + const res = await fetch('/api/config'); + if (!res.ok) throw new Error(`/api/config returned ${res.status}`); + return (await res.json()) as ServerConfig; +} + +async function connect(config: ServerConfig): Promise { + return new Promise((resolve, reject) => { + DbConnection.builder() + .withUri(config.spacetimeUri) + .withDatabaseName(config.databaseName) + .onConnect(c => resolve(c)) + .onDisconnect((_ctx, err) => { + showError(`Disconnected: ${err?.message ?? 'connection lost'}`); + }) + .onConnectError((_ctx: ErrorContext, err) => reject(err)) + .build(); + }); +} + +function getTableAccessor(name: string): TableAccessor | undefined { + const db = (conn?.db ?? {}) as Record | undefined>; + return db[name]; +} + +function emails(): ResendEmail[] { + return [ + ...(getTableAccessor('myDispatchEmails')?.iter() ?? []), + ].sort((a, b) => { + return timestampMs(b.createdAt) - timestampMs(a.createdAt); + }); +} + +type Node = { + key: string; + label: string; + at?: Timestamp; + state: 'done' | 'live' | 'pending' | 'bad' | 'warn'; +}; + +// Turn a stored email into an ordered set of lifecycle nodes. The EmailStatus enum +// tops out at Delivered; Opened/Clicked are booleans; negatives are terminal. +function timeline(row: ResendEmail): Node[] { + const status = tagOf(row.status); + const nodes: Node[] = [ + { key: 'queued', label: 'Queued', at: row.createdAt, state: 'done' }, + ]; + + const sentReached = + Boolean(row.sentAt) || + Boolean(row.deliveredAt) || + row.opened || + row.clicked || + status === 'Sent' || + status === 'Delivered'; + nodes.push({ + key: 'sent', + label: 'Sent', + at: row.sentAt, + state: sentReached ? 'done' : 'pending', + }); + + if (status === 'Bounced') { + nodes.push({ + key: 'bounced', + label: 'Bounced', + at: row.bouncedAt, + state: 'bad', + }); + return nodes; + } + if (status === 'Failed') { + nodes.push({ + key: 'failed', + label: 'Failed', + at: row.failedAt, + state: 'bad', + }); + return nodes; + } + if (status === 'Cancelled') { + nodes.push({ key: 'cancelled', label: 'Cancelled', state: 'warn' }); + return nodes; + } + + // A complaint (marked as spam) implies the mail was delivered, and it is terminal. + const deliveredReached = + Boolean(row.deliveredAt) || + row.opened || + row.clicked || + status === 'Delivered' || + row.complained; + const delayed = status === 'DeliveryDelayed' && !deliveredReached; + nodes.push({ + key: 'delivered', + label: delayed ? 'Delayed' : 'Delivered', + at: row.deliveredAt, + state: deliveredReached ? 'done' : delayed ? 'warn' : 'pending', + }); + + if (row.complained) { + // Terminal: show completed positive steps followed by Complaint. + // No trailing "pending" steps and no live pulse - the lifecycle is over. + if (row.opened) + nodes.push({ + key: 'opened', + label: 'Opened', + at: row.openedAt, + state: 'done', + }); + if (row.clicked) + nodes.push({ + key: 'clicked', + label: 'Clicked', + at: row.clickedAt, + state: 'done', + }); + nodes.push({ + key: 'complaint', + label: 'Complaint', + at: row.complainedAt, + state: 'bad', + }); + return nodes; + } + + nodes.push({ + key: 'opened', + label: 'Opened', + at: row.openedAt, + state: row.opened ? 'done' : 'pending', + }); + nodes.push({ + key: 'clicked', + label: 'Clicked', + at: row.clickedAt, + state: row.clicked ? 'done' : 'pending', + }); + + // The furthest reached positive node is the live frontier. A completed later + // node makes the final completed positive node the subtle accent. + const lastDone = nodes.map(n => n.state === 'done').lastIndexOf(true); + if ( + lastDone > 0 && + nodes[lastDone].state === 'done' && + nodes.some(n => n.state === 'pending') + ) { + nodes[lastDone].state = 'live'; + } + return nodes; +} + +function headPill(row: ResendEmail): { cls: string; text: string } { + const status = tagOf(row.status); + if (status === 'Bounced') return { cls: 'red', text: 'Bounced' }; + if (status === 'Failed') return { cls: 'red', text: 'Failed' }; + if (status === 'Cancelled') return { cls: 'muted', text: 'Cancelled' }; + if (row.complained) return { cls: 'red', text: 'Complaint' }; + if (row.clicked) return { cls: 'green', text: 'Clicked' }; + if (row.opened) return { cls: 'green', text: 'Opened' }; + if (row.deliveredAt || status === 'Delivered') + return { cls: 'green', text: 'Delivered' }; + if (status === 'DeliveryDelayed') return { cls: 'yellow', text: 'Delayed' }; + if (row.sentAt || status === 'Sent') return { cls: 'green', text: 'Sent' }; + return { cls: 'muted', text: 'Queued' }; +} + +// Per-email rendered-node keys ensure each changed transition animates once. +const lastReached = new Map>(); +const knownEmails = new Set(); +const lastCounts: Record = { + sent: -1, + delivered: -1, + opened: -1, + bounced: -1, +}; + +function prefersReducedMotion(): boolean { + return ( + typeof matchMedia === 'function' && + matchMedia('(prefers-reduced-motion: reduce)').matches + ); +} + +// Odometer roll: stack the current and incoming values in a clip window. An +// increase rolls up from below; a decrease rolls down. +function rollNumber(el: HTMLElement, from: number, to: number) { + const up = to > from; + const top = up ? from : to; + const bottom = up ? to : from; + el.innerHTML = + `` + + `${top}${bottom}` + + ``; + const odo = el.querySelector('.odo'); + if (!odo) { + el.textContent = String(to); + return; + } + // Collapse back to a plain number once the roll finishes (or is superseded). + const settle = () => { + if (el.contains(odo)) el.textContent = String(to); + }; + odo.addEventListener('animationend', settle, { once: true }); + setTimeout(settle, 600); +} + +function bumpMetric(id: string, key: string, value: number) { + const el = $(id); + const prev = lastCounts[key]; + lastCounts[key] = value; + if (prev < 0 || prev === value || prefersReducedMotion()) { + el.textContent = String(value); + return; + } + rollNumber(el, prev, value); +} + +function renderMetrics(list: ResendEmail[]) { + const delivered = list.filter( + r => + r.deliveredAt || r.opened || r.clicked || tagOf(r.status) === 'Delivered' + ).length; + const opened = list.filter(r => r.opened).length; + const bounced = list.filter(r => { + const s = tagOf(r.status); + return s === 'Bounced' || s === 'Failed' || r.complained; + }).length; + bumpMetric('count-sent', 'sent', list.length); + bumpMetric('count-delivered', 'delivered', delivered); + bumpMetric('count-opened', 'opened', opened); + bumpMetric('count-bounced', 'bounced', bounced); +} + +function nodeHtml(node: Node, lit: boolean): string { + const time = node.at ? timeLabel(node.at) : ''; + return ` +
+ + ${escapeHtml(node.label)} + ${escapeHtml(time)} +
`; +} + +function mailHtml( + row: ResendEmail, + nodes: Node[], + newlyLit: Set, + isNew: boolean +): string { + const to = recipient(row); + const pill = headPill(row); + const bad = pill.cls === 'red'; + const subject = + row.subject && row.subject.length ? row.subject : '(no subject)'; + const track = nodes.map(n => nodeHtml(n, newlyLit.has(n.key))).join(''); + const error = + bad && row.failureReason + ? `
${escapeHtml(row.failureReason)}
` + : bad && row.lastError + ? `
${escapeHtml(row.lastError)}
` + : ''; + return ` +
+
+ ${escapeHtml(initials(to))} + + ${escapeHtml(to)} + ${escapeHtml(subject)} + + ${escapeHtml(timeLabel(row.createdAt))} + +
+
${track}
+ ${error} +
`; +} + +function reachedKeys(nodes: Node[]): Set { + return new Set(nodes.filter(n => n.state !== 'pending').map(n => n.key)); +} + +function render() { + const list = emails(); + renderMetrics(list); + $('feed-count').textContent = `${list.length} sent`; + ($('clear-btn') as HTMLButtonElement).disabled = list.length === 0; + + if (list.length === 0) { + $('feed').innerHTML = + `
No dispatches yet.
Compose a message and hit Send to watch it move.
`; + lastReached.clear(); + knownEmails.clear(); + return; + } + + const entries = list.map(row => ({ row, nodes: timeline(row) })); + + $('feed').innerHTML = entries + .map(({ row, nodes }) => { + const reached = reachedKeys(nodes); + const prev = lastReached.get(row.resendId); + const isNew = !knownEmails.has(row.resendId); + const newlyLit = new Set(); + if (prev) for (const k of reached) if (!prev.has(k)) newlyLit.add(k); + return mailHtml(row, nodes, newlyLit, isNew); + }) + .join(''); + + // Record post-render state so the next render can diff against it. + const currentIds = new Set(); + for (const { row, nodes } of entries) { + lastReached.set(row.resendId, reachedKeys(nodes)); + knownEmails.add(row.resendId); + currentIds.add(row.resendId); + } + for (const id of [...knownEmails]) { + if (!currentIds.has(id)) { + knownEmails.delete(id); + lastReached.delete(id); + } + } +} + +// Coalesce the burst of table events from a single webhook (email row update + +// delivery-event insert land together) into one render, so the change diff sees the +// whole transition at once and animates the node that advanced. +let renderScheduled = false; +function scheduleRender() { + if (renderScheduled) return; + renderScheduled = true; + setTimeout(() => { + renderScheduled = false; + render(); + }, 0); +} + +function registerCallbacksForTable(name: string): void { + const accessor = getTableAccessor(name); + if (!accessor) throw new Error(`missing table accessor: ${name}`); + accessor.onInsert(() => scheduleRender()); + accessor.onUpdate(() => scheduleRender()); + accessor.onDelete(() => scheduleRender()); +} + +function registerRowCallbacks(): void { + for (const name of ['myDispatchEmails', 'myDispatchDeliveryEvents']) { + registerCallbacksForTable(name); + } +} + +function subscribeToTables(connection: DbConnection): void { + connection + .subscriptionBuilder() + .onApplied((_ctx: SubscriptionEventContext) => { + render(); + if (!currentConfig?.resendConfigured) { + showError( + 'RESEND_API_KEY is missing in this example server environment.' + ); + } + }) + .onError((ctx: ErrorContext) => { + console.error('subscription error:', ctx.event); + showError('Subscription failed. Check the server console.'); + }) + .subscribe([tables.myDispatchEmails, tables.myDispatchDeliveryEvents]); +} + +async function sendDispatch( + to: string, + subject: string, + message: string +): Promise { + if (!conn) throw new Error('not connected'); + return conn.procedures.sendDispatch({ to, subject, message }); +} + +async function deleteDispatch(resendId: string): Promise { + if (!conn) throw new Error('not connected'); + await conn.procedures.deleteDispatch({ resendId }); +} + +async function clearDispatches(): Promise { + if (!conn) throw new Error('not connected'); + await conn.procedures.clearDispatches({}); +} + +function setSending(next: boolean) { + sending = next; + const btn = $('send-btn') as HTMLButtonElement; + btn.disabled = next; + if (next) btn.textContent = 'Sending...'; + else if (!btn.classList.contains('sent')) btn.textContent = 'Send'; +} + +function renderPreview() { + const subject = + ($('subject-input') as HTMLInputElement).value.trim() || '(no subject)'; + const message = ($('message-input') as HTMLTextAreaElement).value.trim(); + const from = currentConfig?.defaultFrom || 'onboarding@resend.dev'; + const body = message + ? messageHtml(message) + : 'Nothing to preview yet.'; + $('message-preview').innerHTML = ` +
+
${escapeHtml(subject)}
+
From ${escapeHtml(from)}
+
+
${body}
`; +} + +function setMsgTab(tab: 'write' | 'preview') { + const isPreview = tab === 'preview'; + if (isPreview) renderPreview(); + ($('message-input') as HTMLTextAreaElement).hidden = isPreview; + $('message-preview').hidden = !isPreview; + document.querySelectorAll('.msg-tab').forEach(b => { + b.classList.toggle('active', b.dataset.tab === tab); + }); +} + +async function submitCompose() { + if (sending) return; + const to = ($('to-input') as HTMLInputElement).value.trim(); + const subject = ($('subject-input') as HTMLInputElement).value.trim(); + const message = ($('message-input') as HTMLTextAreaElement).value.trim(); + if (!to) { + showError('Add a recipient first.'); + return; + } + if (!message) { + showError('Write a message before sending.'); + return; + } + clearError(); + setSending(true); + try { + const result = await sendDispatch(to, subject, message); + setSending(false); + if (result.ok) { + ($('subject-input') as HTMLInputElement).value = ''; + ($('message-input') as HTMLTextAreaElement).value = ''; + setMsgTab('write'); + flashSent(); + } else { + showError(result.message); + } + } catch (err) { + setSending(false); + showError(err instanceof Error ? err.message : String(err)); + } +} + +function registerUiHandlers(): void { + $('compose-form').addEventListener('submit', event => { + event.preventDefault(); + submitCompose().catch(err => { + console.error(err); + showError(err instanceof Error ? err.message : String(err)); + }); + }); + + document.querySelectorAll('.msg-tab').forEach(button => { + button.addEventListener('click', () => { + setMsgTab(button.dataset.tab === 'preview' ? 'preview' : 'write'); + }); + }); + + document + .querySelectorAll('[data-fill]') + .forEach(button => { + button.addEventListener('click', () => { + const email = button.dataset.fill ?? 'delivered@resend.dev'; + ($('to-input') as HTMLInputElement).value = email; + const subject = $('subject-input') as HTMLInputElement; + const message = $('message-input') as HTMLTextAreaElement; + if (!subject.value.trim()) subject.value = 'Hello from Dispatch'; + if (!message.value.trim()) + message.value = 'Watching this one travel through the pipeline.'; + clearError(); + ($('to-input') as HTMLInputElement).focus(); + }); + }); + + $('feed').addEventListener('click', event => { + const btn = (event.target as HTMLElement).closest( + '[data-del]' + ); + if (!btn) return; + const resendId = btn.dataset.del; + if (!resendId) return; + btn.setAttribute('disabled', 'true'); + deleteDispatch(resendId).catch(err => { + console.error(err); + showError(err instanceof Error ? err.message : String(err)); + }); + }); + + $('clear-btn').addEventListener('click', () => { + clearDispatches().catch(err => { + console.error(err); + showError(err instanceof Error ? err.message : String(err)); + }); + }); +} + +async function main() { + registerUiHandlers(); + currentConfig = await loadServerConfig(); + const recipientInput = $('to-input') as HTMLInputElement; + recipientInput.value = currentConfig.allowedRecipients[0] ?? ''; + conn = await connect(currentConfig); + registerRowCallbacks(); + subscribeToTables(conn); +} + +main().catch(err => { + console.error(err); + showError(err instanceof Error ? err.message : String(err)); +}); diff --git a/spacetime-resend-ts/example/src/module_bindings/clear_dispatches_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/clear_dispatches_procedure.ts new file mode 100644 index 00000000000..6621a844b9c --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/clear_dispatches_procedure.ts @@ -0,0 +1,19 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + DispatchDeleteResult, +} from "./types"; + +export const params = { +}; +export const returnType = DispatchDeleteResult \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/delete_dispatch_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/delete_dispatch_procedure.ts new file mode 100644 index 00000000000..9e246ad1174 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/delete_dispatch_procedure.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + DispatchDeleteResult, +} from "./types"; + +export const params = { + resendId: __t.string(), +}; +export const returnType = DispatchDeleteResult \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/index.ts b/spacetime-resend-ts/example/src/module_bindings/index.ts new file mode 100644 index 00000000000..4d2fadb97d6 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/index.ts @@ -0,0 +1,242 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +// This was generated using spacetimedb cli version 2.11.0 (commit dfdccc7e468cc3d378901eac5ee498b4243f4442). + +/* eslint-disable */ +/* tslint:disable */ +import { + DbConnectionBuilder as __DbConnectionBuilder, + DbConnectionImpl as __DbConnectionImpl, + SubscriptionBuilderImpl as __SubscriptionBuilderImpl, + TypeBuilder as __TypeBuilder, + Uuid as __Uuid, + convertToAccessorMap as __convertToAccessorMap, + makeQueryBuilder as __makeQueryBuilder, + procedureSchema as __procedureSchema, + procedures as __procedures, + reducerSchema as __reducerSchema, + reducers as __reducers, + schema as __schema, + t as __t, + table as __table, + type AlgebraicTypeType as __AlgebraicTypeType, + type DbConnectionConfig as __DbConnectionConfig, + type ErrorContextInterface as __ErrorContextInterface, + type Event as __Event, + type EventContextInterface as __EventContextInterface, + type Infer as __Infer, + type QueryBuilder as __QueryBuilder, + type ReducerEventContextInterface as __ReducerEventContextInterface, + type RemoteModule as __RemoteModule, + type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, + type SubscriptionHandleImpl as __SubscriptionHandleImpl, +} from "spacetimedb"; + +// Import all reducer arg schemas + +// Import all procedure arg schemas +import * as ClearDispatchesProcedure from "./clear_dispatches_procedure"; +import * as DeleteDispatchProcedure from "./delete_dispatch_procedure"; +import * as SendDispatchProcedure from "./send_dispatch_procedure"; +import * as SetDispatchPolicyProcedure from "./set_dispatch_policy_procedure"; + +// Import all table schema definitions +import MyDispatchDeliveryEventsRow from "./my_dispatch_delivery_events_table"; +import MyDispatchEmailsRow from "./my_dispatch_emails_table"; + +// Import namespace table schema definitions +import RateLimit_RateLimitConfigRow from "./rateLimit/rate_limit_config_table"; +import RateLimit_AdminRateLimitBucketsRow from "./rateLimit/admin_rate_limit_buckets_table"; + +// Import namespace reducer arg schemas +import Resend_IngestResendWebhookReducer from "./resend/ingest_resend_webhook_reducer"; +import Resend_ReplayWebhookEventReducer from "./resend/replay_webhook_event_reducer"; +import RateLimit_AddRateLimitAdminReducer from "./rateLimit/add_rate_limit_admin_reducer"; +import RateLimit_RemoveRateLimitAdminReducer from "./rateLimit/remove_rate_limit_admin_reducer"; +import RateLimit_ResetBucketsReducer from "./rateLimit/reset_buckets_reducer"; +import RateLimit_UpdateConfigReducer from "./rateLimit/update_config_reducer"; + +// Import namespace procedure arg schemas +import * as Resend_AddAdminIdentityProcedure from "./resend/add_admin_identity_procedure"; +import * as Resend_CancelEmailProcedure from "./resend/cancel_email_procedure"; +import * as Resend_GetEmailProcedure from "./resend/get_email_procedure"; +import * as Resend_GetResendConfigStatusProcedure from "./resend/get_resend_config_status_procedure"; +import * as Resend_GetWebhookEventProcedure from "./resend/get_webhook_event_procedure"; +import * as Resend_ListDeliveryEventsForEmailProcedure from "./resend/list_delivery_events_for_email_procedure"; +import * as Resend_ListEmailsByOrgIdProcedure from "./resend/list_emails_by_org_id_procedure"; +import * as Resend_ListEmailsByStatusProcedure from "./resend/list_emails_by_status_procedure"; +import * as Resend_ListEmailsByUserIdProcedure from "./resend/list_emails_by_user_id_procedure"; +import * as Resend_RemoveAdminIdentityProcedure from "./resend/remove_admin_identity_procedure"; +import * as Resend_ResendApiRequestProcedure from "./resend/resend_api_request_procedure"; +import * as Resend_SendEmailProcedure from "./resend/send_email_procedure"; +import * as Resend_SetResendConfigProcedure from "./resend/set_resend_config_procedure"; +import * as RateLimit_RunSweepProcedure from "./rateLimit/run_sweep_procedure"; + +/** Type-only namespace exports for generated type groups. */ + +/** The schema information for all tables in this module. This is defined the same was as the tables would have been defined in the server. */ +const tablesSchema = __schema({ + myDispatchDeliveryEvents: __table({ + name: 'my_dispatch_delivery_events', + indexes: [ + ], + constraints: [ + ], + }, MyDispatchDeliveryEventsRow), + myDispatchEmails: __table({ + name: 'my_dispatch_emails', + indexes: [ + ], + constraints: [ + ], + }, MyDispatchEmailsRow), + "rate_limit.rate_limit_config": __table({ + name: 'rate_limit.rate_limit_config', + indexes: [ + { accessor: 'singleton', name: 'rate_limit_config_singleton_idx_btree', algorithm: 'btree', columns: [ + 'singleton', + ] }, + ], + constraints: [ + { name: 'rate_limit_config_singleton_key', constraint: 'unique', columns: ['singleton'] }, + ], + }, RateLimit_RateLimitConfigRow), + "rate_limit.admin_rate_limit_buckets": __table({ + name: 'rate_limit.admin_rate_limit_buckets', + indexes: [ + ], + constraints: [ + ], + }, RateLimit_AdminRateLimitBucketsRow), +}); + +/** The schema information for all reducers in this module. This is defined the same way as the reducers would have been defined in the server, except the body of the reducer is omitted in code generation. */ +const reducersSchema = __reducers( + __reducerSchema("resend.ingest_resend_webhook", Resend_IngestResendWebhookReducer, "resend.ingestResendWebhook"), + __reducerSchema("resend.replay_webhook_event", Resend_ReplayWebhookEventReducer, "resend.replayWebhookEvent"), + __reducerSchema("rate_limit.add_rate_limit_admin", RateLimit_AddRateLimitAdminReducer, "rateLimit.addRateLimitAdmin"), + __reducerSchema("rate_limit.remove_rate_limit_admin", RateLimit_RemoveRateLimitAdminReducer, "rateLimit.removeRateLimitAdmin"), + __reducerSchema("rate_limit.reset_buckets", RateLimit_ResetBucketsReducer, "rateLimit.resetBuckets"), + __reducerSchema("rate_limit.update_config", RateLimit_UpdateConfigReducer, "rateLimit.updateConfig"), +); + +/** The schema information for all procedures in this module. This is defined the same way as the procedures would have been defined in the server. */ +const proceduresSchema = __procedures( + __procedureSchema("clear_dispatches", ClearDispatchesProcedure.params, ClearDispatchesProcedure.returnType), + __procedureSchema("delete_dispatch", DeleteDispatchProcedure.params, DeleteDispatchProcedure.returnType), + __procedureSchema("send_dispatch", SendDispatchProcedure.params, SendDispatchProcedure.returnType), + __procedureSchema("set_dispatch_policy", SetDispatchPolicyProcedure.params, SetDispatchPolicyProcedure.returnType), + __procedureSchema("resend.add_admin_identity", Resend_AddAdminIdentityProcedure.params, Resend_AddAdminIdentityProcedure.returnType, "resend.addAdminIdentity"), + __procedureSchema("resend.cancel_email", Resend_CancelEmailProcedure.params, Resend_CancelEmailProcedure.returnType, "resend.cancelEmail"), + __procedureSchema("resend.get_email", Resend_GetEmailProcedure.params, Resend_GetEmailProcedure.returnType, "resend.getEmail"), + __procedureSchema("resend.get_resend_config_status", Resend_GetResendConfigStatusProcedure.params, Resend_GetResendConfigStatusProcedure.returnType, "resend.getResendConfigStatus"), + __procedureSchema("resend.get_webhook_event", Resend_GetWebhookEventProcedure.params, Resend_GetWebhookEventProcedure.returnType, "resend.getWebhookEvent"), + __procedureSchema("resend.list_delivery_events_for_email", Resend_ListDeliveryEventsForEmailProcedure.params, Resend_ListDeliveryEventsForEmailProcedure.returnType, "resend.listDeliveryEventsForEmail"), + __procedureSchema("resend.list_emails_by_org_id", Resend_ListEmailsByOrgIdProcedure.params, Resend_ListEmailsByOrgIdProcedure.returnType, "resend.listEmailsByOrgId"), + __procedureSchema("resend.list_emails_by_status", Resend_ListEmailsByStatusProcedure.params, Resend_ListEmailsByStatusProcedure.returnType, "resend.listEmailsByStatus"), + __procedureSchema("resend.list_emails_by_user_id", Resend_ListEmailsByUserIdProcedure.params, Resend_ListEmailsByUserIdProcedure.returnType, "resend.listEmailsByUserId"), + __procedureSchema("resend.remove_admin_identity", Resend_RemoveAdminIdentityProcedure.params, Resend_RemoveAdminIdentityProcedure.returnType, "resend.removeAdminIdentity"), + __procedureSchema("resend.resend_api_request", Resend_ResendApiRequestProcedure.params, Resend_ResendApiRequestProcedure.returnType, "resend.resendApiRequest"), + __procedureSchema("resend.send_email", Resend_SendEmailProcedure.params, Resend_SendEmailProcedure.returnType, "resend.sendEmail"), + __procedureSchema("resend.set_resend_config", Resend_SetResendConfigProcedure.params, Resend_SetResendConfigProcedure.returnType, "resend.setResendConfig"), + __procedureSchema("rate_limit.run_sweep", RateLimit_RunSweepProcedure.params, RateLimit_RunSweepProcedure.returnType, "rateLimit.runSweep"), +); + +/** The remote SpacetimeDB module schema, both runtime and type information. */ +const REMOTE_MODULE = { + versionInfo: { + cliVersion: "2.11.0" as const, + }, + tables: tablesSchema.schemaType.tables, + reducers: reducersSchema.reducersType.reducers, + ...proceduresSchema, +} satisfies __RemoteModule< + typeof tablesSchema.schemaType, + typeof reducersSchema.reducersType, + typeof proceduresSchema +>; + +/** The tables available in this remote SpacetimeDB module. Each table reference doubles as a query builder. */ +const __qb = __makeQueryBuilder(tablesSchema.schemaType); +export const tables = { + myDispatchDeliveryEvents: __qb.myDispatchDeliveryEvents, + myDispatchEmails: __qb.myDispatchEmails, + rateLimit: { + rateLimitConfig: __qb["rate_limit.rate_limit_config"], + adminRateLimitBuckets: __qb["rate_limit.admin_rate_limit_buckets"], + }, +} as const; + +/** The reducers available in this remote SpacetimeDB module. */ +const __reducerAccessors = __convertToAccessorMap(reducersSchema.reducersType.reducers); +export const reducers = { + rateLimit: { + addRateLimitAdmin: __reducerAccessors["rateLimit.addRateLimitAdmin"], + removeRateLimitAdmin: __reducerAccessors["rateLimit.removeRateLimitAdmin"], + resetBuckets: __reducerAccessors["rateLimit.resetBuckets"], + updateConfig: __reducerAccessors["rateLimit.updateConfig"], + }, + resend: { + ingestResendWebhook: __reducerAccessors["resend.ingestResendWebhook"], + replayWebhookEvent: __reducerAccessors["resend.replayWebhookEvent"], + }, +} as const; + +/** The procedures available in this remote SpacetimeDB module. */ +const __procedureAccessors = __convertToAccessorMap(proceduresSchema.procedures); +export const procedures = { + clearDispatches: __procedureAccessors.clearDispatches, + deleteDispatch: __procedureAccessors.deleteDispatch, + sendDispatch: __procedureAccessors.sendDispatch, + setDispatchPolicy: __procedureAccessors.setDispatchPolicy, + rateLimit: { + runSweep: __procedureAccessors["rateLimit.runSweep"], + }, + resend: { + addAdminIdentity: __procedureAccessors["resend.addAdminIdentity"], + cancelEmail: __procedureAccessors["resend.cancelEmail"], + getEmail: __procedureAccessors["resend.getEmail"], + getResendConfigStatus: __procedureAccessors["resend.getResendConfigStatus"], + getWebhookEvent: __procedureAccessors["resend.getWebhookEvent"], + listDeliveryEventsForEmail: __procedureAccessors["resend.listDeliveryEventsForEmail"], + listEmailsByOrgId: __procedureAccessors["resend.listEmailsByOrgId"], + listEmailsByStatus: __procedureAccessors["resend.listEmailsByStatus"], + listEmailsByUserId: __procedureAccessors["resend.listEmailsByUserId"], + removeAdminIdentity: __procedureAccessors["resend.removeAdminIdentity"], + resendApiRequest: __procedureAccessors["resend.resendApiRequest"], + sendEmail: __procedureAccessors["resend.sendEmail"], + setResendConfig: __procedureAccessors["resend.setResendConfig"], + }, +} as const; + +/** The context type returned in callbacks for all possible events. */ +export type EventContext = __EventContextInterface; +/** The context type returned in callbacks for reducer events. */ +export type ReducerEventContext = __ReducerEventContextInterface; +/** The context type returned in callbacks for subscription events. */ +export type SubscriptionEventContext = __SubscriptionEventContextInterface; +/** The context type returned in callbacks for error events. */ +export type ErrorContext = __ErrorContextInterface; +/** The subscription handle type to manage active subscriptions created from a {@link SubscriptionBuilder}. */ +export type SubscriptionHandle = __SubscriptionHandleImpl; + +/** Builder class to configure a new subscription to the remote SpacetimeDB instance. */ +export class SubscriptionBuilder extends __SubscriptionBuilderImpl {} + +/** Builder class to configure a new database connection to the remote SpacetimeDB instance. */ +export class DbConnectionBuilder extends __DbConnectionBuilder {} + +/** The typed database connection to manage connections to the remote SpacetimeDB instance. This class has type information specific to the generated module. */ +export class DbConnection extends __DbConnectionImpl { + /** Creates a new {@link DbConnectionBuilder} to configure and connect to the remote SpacetimeDB instance. */ + static builder = (): DbConnectionBuilder => { + return new DbConnectionBuilder(REMOTE_MODULE, (config: __DbConnectionConfig) => new DbConnection(config)); + }; + + /** Creates a new {@link SubscriptionBuilder} to configure a subscription to the remote SpacetimeDB instance. */ + override subscriptionBuilder = (): SubscriptionBuilder => { + return new SubscriptionBuilder(this); + }; +} + diff --git a/spacetime-resend-ts/example/src/module_bindings/my_dispatch_delivery_events_table.ts b/spacetime-resend-ts/example/src/module_bindings/my_dispatch_delivery_events_table.ts new file mode 100644 index 00000000000..bcd9654503f --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/my_dispatch_delivery_events_table.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + eventId: __t.string().primaryKey().name("event_id"), + resendId: __t.string().name("resend_id"), + eventType: __t.string().name("event_type"), + createdAtIso: __t.string().name("created_at_iso"), + detailJson: __t.option(__t.string()).name("detail_json"), + insertedAt: __t.timestamp().name("inserted_at"), +}); diff --git a/spacetime-resend-ts/example/src/module_bindings/my_dispatch_emails_table.ts b/spacetime-resend-ts/example/src/module_bindings/my_dispatch_emails_table.ts new file mode 100644 index 00000000000..da3ee29f660 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/my_dispatch_emails_table.ts @@ -0,0 +1,46 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; +import { + EmailStatus, +} from "./types"; + + +export default __t.row({ + resendId: __t.string().primaryKey().name("resend_id"), + fromAddress: __t.string().name("from_address"), + toAddressesJson: __t.string().name("to_addresses_json"), + subject: __t.option(__t.string()), + get status() { + return EmailStatus; + }, + lastError: __t.option(__t.string()).name("last_error"), + bouncedAt: __t.option(__t.timestamp()).name("bounced_at"), + bounceJson: __t.option(__t.string()).name("bounce_json"), + failedAt: __t.option(__t.timestamp()).name("failed_at"), + failureReason: __t.option(__t.string()).name("failure_reason"), + complained: __t.bool(), + complainedAt: __t.option(__t.timestamp()).name("complained_at"), + opened: __t.bool(), + openedAt: __t.option(__t.timestamp()).name("opened_at"), + clicked: __t.bool(), + clickedAt: __t.option(__t.timestamp()).name("clicked_at"), + deliveredAt: __t.option(__t.timestamp()).name("delivered_at"), + sentAt: __t.option(__t.timestamp()).name("sent_at"), + html: __t.option(__t.string()), + text: __t.option(__t.string()), + tagsJson: __t.option(__t.string()).name("tags_json"), + userId: __t.option(__t.string()).name("user_id"), + orgId: __t.option(__t.string()).name("org_id"), + createdAt: __t.timestamp().name("created_at"), + updatedAt: __t.timestamp().name("updated_at"), + statusUpdatedAt: __t.option(__t.timestamp()).name("status_updated_at"), +}); diff --git a/spacetime-resend-ts/example/src/module_bindings/rateLimit/add_rate_limit_admin_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/add_rate_limit_admin_reducer.ts new file mode 100644 index 00000000000..e39846ca8d9 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/rateLimit/add_rate_limit_admin_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + identity: __t.identity(), +}; diff --git a/spacetime-resend-ts/example/src/module_bindings/rateLimit/admin_rate_limit_buckets_table.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/admin_rate_limit_buckets_table.ts new file mode 100644 index 00000000000..189f539a043 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/rateLimit/admin_rate_limit_buckets_table.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + key: __t.string().primaryKey(), + scope: __t.string(), + windowStart: __t.timestamp().name("window_start"), + expiresAt: __t.timestamp().name("expires_at"), + count: __t.u32(), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-resend-ts/example/src/module_bindings/rateLimit/rate_limit_config_table.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/rate_limit_config_table.ts new file mode 100644 index 00000000000..66ffe86e399 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/rateLimit/rate_limit_config_table.ts @@ -0,0 +1,17 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + singleton: __t.bool().primaryKey(), + sweepBatch: __t.u32().name("sweep_batch"), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-resend-ts/example/src/module_bindings/rateLimit/remove_rate_limit_admin_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/remove_rate_limit_admin_reducer.ts new file mode 100644 index 00000000000..e39846ca8d9 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/rateLimit/remove_rate_limit_admin_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + identity: __t.identity(), +}; diff --git a/spacetime-resend-ts/example/src/module_bindings/rateLimit/reset_buckets_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/reset_buckets_reducer.ts new file mode 100644 index 00000000000..a7c5cc5274f --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/rateLimit/reset_buckets_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + maxRows: __t.option(__t.u32()), +}; diff --git a/spacetime-resend-ts/example/src/module_bindings/rateLimit/run_sweep_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/run_sweep_procedure.ts new file mode 100644 index 00000000000..9815c99eb38 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/rateLimit/run_sweep_procedure.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const params = { + maxRows: __t.option(__t.u32()), +}; +export const returnType = __t.u32() \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/rateLimit/types.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/types.ts new file mode 100644 index 00000000000..d14931b1fb9 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/rateLimit/types.ts @@ -0,0 +1,44 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const AdminRateLimitBuckets = __t.object("AdminRateLimitBuckets", {}); +export type AdminRateLimitBuckets = __Infer; + +export const RateLimitAdminIdentity = __t.object("RateLimitAdminIdentity", { + identity: __t.identity(), + addedAt: __t.timestamp(), +}); +export type RateLimitAdminIdentity = __Infer; + +export const RateLimitBucket = __t.object("RateLimitBucket", { + key: __t.string(), + scope: __t.string(), + windowStart: __t.timestamp(), + expiresAt: __t.timestamp(), + count: __t.u32(), + updatedAt: __t.timestamp(), +}); +export type RateLimitBucket = __Infer; + +export const RateLimitConfig = __t.object("RateLimitConfig", { + singleton: __t.bool(), + sweepBatch: __t.u32(), + updatedAt: __t.timestamp(), +}); +export type RateLimitConfig = __Infer; + +export const RateLimitSweepTick = __t.object("RateLimitSweepTick", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), +}); +export type RateLimitSweepTick = __Infer; + diff --git a/spacetime-resend-ts/example/src/module_bindings/rateLimit/update_config_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/rateLimit/update_config_reducer.ts new file mode 100644 index 00000000000..54fcf361af1 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/rateLimit/update_config_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + sweepBatch: __t.u32(), +}; diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/add_admin_identity_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/add_admin_identity_procedure.ts new file mode 100644 index 00000000000..bfd93108ec4 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/add_admin_identity_procedure.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const params = { + identity: __t.identity(), +}; +export const returnType = __t.unit() \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/cancel_email_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/cancel_email_procedure.ts new file mode 100644 index 00000000000..ec778b46cd0 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/cancel_email_procedure.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const params = { + resendId: __t.string(), +}; +export const returnType = __t.unit() \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/get_email_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/get_email_procedure.ts new file mode 100644 index 00000000000..0744ed77aab --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/get_email_procedure.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ResendEmail, +} from "./types"; + +export const params = { + resendId: __t.string(), +}; +export const returnType = __t.option(ResendEmail) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/get_resend_config_status_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/get_resend_config_status_procedure.ts new file mode 100644 index 00000000000..badd9ab9cc8 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/get_resend_config_status_procedure.ts @@ -0,0 +1,19 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ResendConfigStatus, +} from "./types"; + +export const params = { +}; +export const returnType = ResendConfigStatus \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/get_webhook_event_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/get_webhook_event_procedure.ts new file mode 100644 index 00000000000..8421d69c668 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/get_webhook_event_procedure.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ResendWebhookEvent, +} from "./types"; + +export const params = { + eventId: __t.string(), +}; +export const returnType = __t.option(ResendWebhookEvent) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/ingest_resend_webhook_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/resend/ingest_resend_webhook_reducer.ts new file mode 100644 index 00000000000..1e7afcc3703 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/ingest_resend_webhook_reducer.ts @@ -0,0 +1,19 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + eventId: __t.string(), + eventType: __t.string(), + payloadJson: __t.string(), + signatureHeader: __t.option(__t.string()), + timestampHeader: __t.option(__t.string()), +}; diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/list_delivery_events_for_email_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/list_delivery_events_for_email_procedure.ts new file mode 100644 index 00000000000..27a3a808053 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/list_delivery_events_for_email_procedure.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ResendDeliveryEvent, +} from "./types"; + +export const params = { + resendId: __t.string(), +}; +export const returnType = __t.array(ResendDeliveryEvent) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_org_id_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_org_id_procedure.ts new file mode 100644 index 00000000000..cd1063291da --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_org_id_procedure.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ResendEmail, +} from "./types"; + +export const params = { + orgId: __t.string(), +}; +export const returnType = __t.array(ResendEmail) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_status_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_status_procedure.ts new file mode 100644 index 00000000000..c24fc71c444 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_status_procedure.ts @@ -0,0 +1,23 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ResendEmail, + EmailStatus, +} from "./types"; + +export const params = { + get status() { + return EmailStatus; + }, +}; +export const returnType = __t.array(ResendEmail) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_user_id_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_user_id_procedure.ts new file mode 100644 index 00000000000..f712b807b32 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/list_emails_by_user_id_procedure.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ResendEmail, +} from "./types"; + +export const params = { + userId: __t.string(), +}; +export const returnType = __t.array(ResendEmail) \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/remove_admin_identity_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/remove_admin_identity_procedure.ts new file mode 100644 index 00000000000..bfd93108ec4 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/remove_admin_identity_procedure.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const params = { + identity: __t.identity(), +}; +export const returnType = __t.unit() \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/replay_webhook_event_reducer.ts b/spacetime-resend-ts/example/src/module_bindings/resend/replay_webhook_event_reducer.ts new file mode 100644 index 00000000000..590a453de82 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/replay_webhook_event_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + eventId: __t.string(), +}; diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/resend_api_request_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/resend_api_request_procedure.ts new file mode 100644 index 00000000000..aff60351ebf --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/resend_api_request_procedure.ts @@ -0,0 +1,23 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ResendApiRequestResult, +} from "./types"; + +export const params = { + method: __t.string(), + path: __t.string(), + jsonBody: __t.option(__t.string()), + idempotencyKey: __t.option(__t.string()), +}; +export const returnType = ResendApiRequestResult \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/send_email_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/send_email_procedure.ts new file mode 100644 index 00000000000..67babe6715f --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/send_email_procedure.ts @@ -0,0 +1,31 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + SendEmailResult, +} from "./types"; + +export const params = { + from: __t.option(__t.string()), + to: __t.array(__t.string()), + subject: __t.string(), + html: __t.option(__t.string()), + text: __t.option(__t.string()), + cc: __t.option(__t.array(__t.string())), + bcc: __t.option(__t.array(__t.string())), + replyTo: __t.option(__t.array(__t.string())), + tagsJson: __t.option(__t.string()), + headersJson: __t.option(__t.string()), + scheduledAt: __t.option(__t.string()), + idempotencyKey: __t.option(__t.string()), +}; +export const returnType = SendEmailResult \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/set_resend_config_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/resend/set_resend_config_procedure.ts new file mode 100644 index 00000000000..645c952bd4d --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/set_resend_config_procedure.ts @@ -0,0 +1,18 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const params = { + apiKey: __t.string(), + webhookSigningSecret: __t.option(__t.string()), + defaultFrom: __t.option(__t.string()), +}; +export const returnType = __t.unit() \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/resend/types.ts b/spacetime-resend-ts/example/src/module_bindings/resend/types.ts new file mode 100644 index 00000000000..505864052b1 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/resend/types.ts @@ -0,0 +1,124 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +// The tagged union or sum type for the algebraic type `EmailStatus`. +export const EmailStatus = __t.enum("EmailStatus", { + Queued: __t.unit(), + Sent: __t.unit(), + Delivered: __t.unit(), + DeliveryDelayed: __t.unit(), + Bounced: __t.unit(), + Failed: __t.unit(), + Cancelled: __t.unit(), +}); +export type EmailStatus = __Infer; + +export const ResendAdminIdentity = __t.object("ResendAdminIdentity", { + identity: __t.identity(), + addedAt: __t.timestamp(), +}); +export type ResendAdminIdentity = __Infer; + +export const ResendApiRequestResult = __t.object("ResendApiRequestResult", { + status: __t.u16(), + body: __t.string(), +}); +export type ResendApiRequestResult = __Infer; + +export const ResendConfig = __t.object("ResendConfig", { + singleton: __t.bool(), + apiKey: __t.string(), + webhookSigningSecret: __t.option(__t.string()), + defaultFrom: __t.option(__t.string()), + updatedAt: __t.timestamp(), +}); +export type ResendConfig = __Infer; + +export const ResendConfigStatus = __t.object("ResendConfigStatus", { + isConfigured: __t.bool(), + hasWebhookSecret: __t.bool(), + defaultFrom: __t.option(__t.string()), + apiKeyLength: __t.u16(), +}); +export type ResendConfigStatus = __Infer; + +export const ResendDeliveryEvent = __t.object("ResendDeliveryEvent", { + eventId: __t.string(), + resendId: __t.string(), + eventType: __t.string(), + createdAtIso: __t.string(), + detailJson: __t.option(__t.string()), + insertedAt: __t.timestamp(), +}); +export type ResendDeliveryEvent = __Infer; + +export const ResendEmail = __t.object("ResendEmail", { + resendId: __t.string(), + fromAddress: __t.string(), + toAddressesJson: __t.string(), + subject: __t.option(__t.string()), + get status() { + return EmailStatus; + }, + lastError: __t.option(__t.string()), + bouncedAt: __t.option(__t.timestamp()), + bounceJson: __t.option(__t.string()), + failedAt: __t.option(__t.timestamp()), + failureReason: __t.option(__t.string()), + complained: __t.bool(), + complainedAt: __t.option(__t.timestamp()), + opened: __t.bool(), + openedAt: __t.option(__t.timestamp()), + clicked: __t.bool(), + clickedAt: __t.option(__t.timestamp()), + deliveredAt: __t.option(__t.timestamp()), + sentAt: __t.option(__t.timestamp()), + html: __t.option(__t.string()), + text: __t.option(__t.string()), + tagsJson: __t.option(__t.string()), + userId: __t.option(__t.string()), + orgId: __t.option(__t.string()), + createdAt: __t.timestamp(), + updatedAt: __t.timestamp(), + statusUpdatedAt: __t.option(__t.timestamp()), +}); +export type ResendEmail = __Infer; + +export const ResendWebhookEvent = __t.object("ResendWebhookEvent", { + eventId: __t.string(), + eventType: __t.string(), + payloadJson: __t.string(), + signatureHeader: __t.option(__t.string()), + timestampHeader: __t.option(__t.string()), + get status() { + return WebhookEventStatus; + }, + errorMessage: __t.option(__t.string()), + receivedAt: __t.timestamp(), + processedAt: __t.option(__t.timestamp()), +}); +export type ResendWebhookEvent = __Infer; + +export const SendEmailResult = __t.object("SendEmailResult", { + resendId: __t.string(), +}); +export type SendEmailResult = __Infer; + +// The tagged union or sum type for the algebraic type `WebhookEventStatus`. +export const WebhookEventStatus = __t.enum("WebhookEventStatus", { + Received: __t.unit(), + Processed: __t.unit(), + Ignored: __t.unit(), + Failed: __t.unit(), +}); +export type WebhookEventStatus = __Infer; + diff --git a/spacetime-resend-ts/example/src/module_bindings/send_dispatch_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/send_dispatch_procedure.ts new file mode 100644 index 00000000000..5a200f044d9 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/send_dispatch_procedure.ts @@ -0,0 +1,22 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + DispatchSendResult, +} from "./types"; + +export const params = { + to: __t.string(), + subject: __t.string(), + message: __t.string(), +}; +export const returnType = DispatchSendResult \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/set_dispatch_policy_procedure.ts b/spacetime-resend-ts/example/src/module_bindings/set_dispatch_policy_procedure.ts new file mode 100644 index 00000000000..d27751fdf5d --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/set_dispatch_policy_procedure.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const params = { + allowedRecipientsJson: __t.string(), +}; +export const returnType = __t.bool() \ No newline at end of file diff --git a/spacetime-resend-ts/example/src/module_bindings/types.ts b/spacetime-resend-ts/example/src/module_bindings/types.ts new file mode 100644 index 00000000000..3a76237db76 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/types.ts @@ -0,0 +1,97 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const DispatchDeleteResult = __t.object("DispatchDeleteResult", { + ok: __t.bool(), + removed: __t.u32(), +}); +export type DispatchDeleteResult = __Infer; + +export const DispatchPolicy = __t.object("DispatchPolicy", { + singleton: __t.bool(), + allowedRecipientsJson: __t.string(), + updatedAt: __t.timestamp(), +}); +export type DispatchPolicy = __Infer; + +export const DispatchSendResult = __t.object("DispatchSendResult", { + ok: __t.bool(), + resendId: __t.option(__t.string()), + message: __t.string(), +}); +export type DispatchSendResult = __Infer; + +// The tagged union or sum type for the algebraic type `EmailStatus`. +export const EmailStatus = __t.enum("EmailStatus", { + Queued: __t.unit(), + Sent: __t.unit(), + Delivered: __t.unit(), + DeliveryDelayed: __t.unit(), + Bounced: __t.unit(), + Failed: __t.unit(), + Cancelled: __t.unit(), +}); +export type EmailStatus = __Infer; + +export const MyDispatchDeliveryEvents = __t.object("MyDispatchDeliveryEvents", {}); +export type MyDispatchDeliveryEvents = __Infer; + +export const MyDispatchEmails = __t.object("MyDispatchEmails", {}); +export type MyDispatchEmails = __Infer; + +export const RemovedDispatch = __t.object("RemovedDispatch", { + resendId: __t.string(), +}); +export type RemovedDispatch = __Infer; + +export const ResendDeliveryEvent = __t.object("ResendDeliveryEvent", { + eventId: __t.string(), + resendId: __t.string(), + eventType: __t.string(), + createdAtIso: __t.string(), + detailJson: __t.option(__t.string()), + insertedAt: __t.timestamp(), +}); +export type ResendDeliveryEvent = __Infer; + +export const ResendEmail = __t.object("ResendEmail", { + resendId: __t.string(), + fromAddress: __t.string(), + toAddressesJson: __t.string(), + subject: __t.option(__t.string()), + get status() { + return EmailStatus; + }, + lastError: __t.option(__t.string()), + bouncedAt: __t.option(__t.timestamp()), + bounceJson: __t.option(__t.string()), + failedAt: __t.option(__t.timestamp()), + failureReason: __t.option(__t.string()), + complained: __t.bool(), + complainedAt: __t.option(__t.timestamp()), + opened: __t.bool(), + openedAt: __t.option(__t.timestamp()), + clicked: __t.bool(), + clickedAt: __t.option(__t.timestamp()), + deliveredAt: __t.option(__t.timestamp()), + sentAt: __t.option(__t.timestamp()), + html: __t.option(__t.string()), + text: __t.option(__t.string()), + tagsJson: __t.option(__t.string()), + userId: __t.option(__t.string()), + orgId: __t.option(__t.string()), + createdAt: __t.timestamp(), + updatedAt: __t.timestamp(), + statusUpdatedAt: __t.option(__t.timestamp()), +}); +export type ResendEmail = __Infer; + diff --git a/spacetime-resend-ts/example/src/module_bindings/types/procedures.ts b/spacetime-resend-ts/example/src/module_bindings/types/procedures.ts new file mode 100644 index 00000000000..13622fae9a4 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/types/procedures.ts @@ -0,0 +1,22 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from "spacetimedb"; + +// Import all procedure arg schemas +import * as ClearDispatchesProcedure from "../clear_dispatches_procedure"; +import * as DeleteDispatchProcedure from "../delete_dispatch_procedure"; +import * as SendDispatchProcedure from "../send_dispatch_procedure"; +import * as SetDispatchPolicyProcedure from "../set_dispatch_policy_procedure"; + +export type ClearDispatchesArgs = __Infer; +export type ClearDispatchesResult = __Infer; +export type DeleteDispatchArgs = __Infer; +export type DeleteDispatchResult = __Infer; +export type SendDispatchArgs = __Infer; +export type SendDispatchResult = __Infer; +export type SetDispatchPolicyArgs = __Infer; +export type SetDispatchPolicyResult = __Infer; + diff --git a/spacetime-resend-ts/example/src/module_bindings/types/reducers.ts b/spacetime-resend-ts/example/src/module_bindings/types/reducers.ts new file mode 100644 index 00000000000..c701027cbf1 --- /dev/null +++ b/spacetime-resend-ts/example/src/module_bindings/types/reducers.ts @@ -0,0 +1,10 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from "spacetimedb"; + +// Import all reducer arg schemas + + diff --git a/spacetime-resend-ts/example/tsconfig.json b/spacetime-resend-ts/example/tsconfig.json new file mode 100644 index 00000000000..8e5e2bbddf0 --- /dev/null +++ b/spacetime-resend-ts/example/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "allowImportingTsExtensions": false, + "esModuleInterop": true, + "isolatedModules": true, + "useDefineForClassFields": true, + "lib": ["ES2022", "DOM", "DOM.Iterable"] + }, + "include": ["src/**/*.ts", "scripts/**/*.ts", "server.ts"], + "exclude": ["node_modules", "public", "dist"] +} diff --git a/spacetime-resend-ts/package.json b/spacetime-resend-ts/package.json new file mode 100644 index 00000000000..ec58ab75835 --- /dev/null +++ b/spacetime-resend-ts/package.json @@ -0,0 +1,86 @@ +{ + "name": "@spacetimedb/resend", + "description": "Resend email delivery, webhook verification, and event storage for SpacetimeDB TypeScript modules.", + "version": "0.1.0", + "license": "Apache-2.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./submodule": { + "types": "./src/submodule.ts", + "default": "./src/submodule.ts" + } + }, + "files": [ + "dist", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./submodule": { + "types": "./dist/submodule.d.ts", + "default": "./dist/submodule.js" + } + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/clockworklabs/SpacetimeDB.git", + "directory": "spacetime-resend-ts" + }, + "homepage": "https://github.com/clockworklabs/SpacetimeDB/tree/master/spacetime-resend-ts#readme", + "bugs": { + "url": "https://github.com/clockworklabs/SpacetimeDB/issues" + }, + "keywords": [ + "spacetimedb", + "resend", + "email", + "webhooks" + ], + "scripts": { + "prepack": "pnpm run build && node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"", + "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json", + "build:module": "spacetime build", + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "tsx scripts/test-unit.ts && node --js-explicit-resource-management --import tsx --import ./scripts/sys-abi-test-register.mjs scripts/test-webhooks.ts", + "spacetime:generate": "spacetime generate --lang typescript --out-dir ts-codegen", + "publish:module": "spacetime publish", + "publish:local": "spacetime publish --server local --yes spacetime-resend", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-resend", + "test:smoke": "tsx scripts/test-resend-smoke.ts", + "test:gate:local": "tsx scripts/test-resend-smoke.ts" + }, + "dependencies": { + "@spacetimedb/crypto": "workspace:^", + "valibot": "^1.4.2" + }, + "peerDependencies": { + "spacetimedb": "workspace:^" + }, + "devDependencies": { + "eslint": "^9.17.0", + "prettier": "^3.3.3", + "@types/node": "^22.10.2", + "spacetimedb": "workspace:*", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-resend-ts/scripts/sys-abi-test-register.mjs b/spacetime-resend-ts/scripts/sys-abi-test-register.mjs new file mode 100644 index 00000000000..30107456e71 --- /dev/null +++ b/spacetime-resend-ts/scripts/sys-abi-test-register.mjs @@ -0,0 +1,27 @@ +import { register } from 'node:module'; + +// Host syscall modules exist only inside SpacetimeDB. Stub the bindings that +// `spacetimedb/server` reads while loading. +const stubs = { + 'spacetime:sys@2.0': + 'export const moduleHooks = Symbol(); export function row_iter_bsatn_close() {}', + 'spacetime:sys@2.1': 'export {};', + 'spacetime:sys@2.2': 'export function env_get() {}', +}; + +const loaderSource = ` + const stubs = ${JSON.stringify(stubs)}; + export function resolve(specifier, context, nextResolve) { + return specifier in stubs + ? { + shortCircuit: true, + url: 'data:text/javascript,' + encodeURIComponent(stubs[specifier]), + } + : nextResolve(specifier, context); + } +`; + +register( + `data:text/javascript,${encodeURIComponent(loaderSource)}`, + import.meta.url +); diff --git a/spacetime-resend-ts/scripts/test-resend-smoke.ts b/spacetime-resend-ts/scripts/test-resend-smoke.ts new file mode 100644 index 00000000000..0b62390a589 --- /dev/null +++ b/spacetime-resend-ts/scripts/test-resend-smoke.ts @@ -0,0 +1,602 @@ +// Synthetic signed events only; no provider requests. Add --example to test the native HTTP route. + +import { spawn } from 'node:child_process'; +import { createHmac } from 'node:crypto'; + +type Options = { + server: string; + database: string; + skipBuildPublish: boolean; + example: boolean; +}; + +function parseArgs(argv: string[]): Options { + const opts: Options = { + server: 'http://127.0.0.1:3000', + // Dedicated DB so smoke test never overwrites the dev module's real config. + database: 'resend-ts-smoke-test', + skipBuildPublish: false, + example: false, + }; + for (let i = 0; i < argv.length; i++) { + const raw = argv[i]!; + const flag = raw.replace(/^-+/, '').toLowerCase(); + if (flag === 'skip-build-publish') opts.skipBuildPublish = true; + if (flag === 'example') opts.example = true; + if (flag === 'server') opts.server = argv[++i]!; + if (flag === 'database') opts.database = argv[++i]!; + } + return opts; +} + +function step(name: string) { + process.stdout.write(`\n==> ${name}\n`); +} + +function run( + cmd: string, + args: string[] +): Promise<{ code: number; stdout: string; stderr: string }> { + return new Promise(resolve => { + const child = spawn(cmd, args, { shell: false }); + let stdout = ''; + let stderr = ''; + child.stdout?.on('data', d => (stdout += String(d))); + child.stderr?.on('data', d => (stderr += String(d))); + child.on('close', code => resolve({ code: code ?? 1, stdout, stderr })); + child.on('error', err => + resolve({ code: 1, stdout, stderr: stderr + String(err) }) + ); + }); +} + +async function callReducer( + opts: Options, + name: string, + args: string[] +): Promise { + const result = await run('spacetime', [ + 'call', + '--server', + opts.server, + opts.database, + opts.example ? `resend.${name}` : name, + ...args, + ]); + if (result.code !== 0) { + throw new Error( + `spacetime call ${name} failed: code=${result.code}\nstderr: ${result.stderr}\nstdout: ${result.stdout}` + ); + } + return result.stdout; +} + +// Expects the call to fail. Returns combined stderr/stdout for assertion. +async function expectCallFails( + opts: Options, + name: string, + args: string[], + anonymous = false +): Promise { + const result = await run('spacetime', [ + 'call', + ...(anonymous ? ['--anonymous'] : []), + '--server', + opts.server, + opts.database, + opts.example ? `resend.${name}` : name, + ...args, + ]); + if (result.code === 0) { + throw new Error( + `expected ${name} to fail but it succeeded:\nstdout: ${result.stdout}` + ); + } + return result.stderr + result.stdout; +} + +function quote(s: string): string { + return JSON.stringify(s); +} + +function some(s: string): string { + return JSON.stringify({ some: s }); +} + +const RESEND_WEBHOOK_SECRET_RAW = 'resend_smoke_test_secret'; +const RESEND_WEBHOOK_SECRET = `whsec_${Buffer.from(RESEND_WEBHOOK_SECRET_RAW).toString('base64')}`; + +function svixSignature(args: { + eventId: string; + timestamp: string; + payloadJson: string; +}): string { + const digest = createHmac('sha256', RESEND_WEBHOOK_SECRET_RAW) + .update(`${args.eventId}.${args.timestamp}.${args.payloadJson}`) + .digest('base64'); + return `v1,${digest}`; +} + +async function ingestWebhook( + opts: Options, + eventId: string, + eventType: string, + payloadJson: string +) { + const timestamp = String(Math.floor(Date.now() / 1000)); + await callReducer(opts, 'ingest_resend_webhook', [ + quote(eventId), + quote(eventType), + quote(payloadJson), + some(svixSignature({ eventId, timestamp, payloadJson })), + some(timestamp), + ]); +} + +function eventPayload(args: { + type: string; + emailId: string; + from?: string; + to?: string[]; + subject?: string; + extra?: Record; + createdAt?: string; +}): string { + const data: Record = { + email_id: args.emailId, + created_at: '2026-05-04T00:00:00Z', + from: args.from ?? 'onboarding@resend.dev', + to: args.to ?? ['delivered@resend.dev'], + subject: args.subject ?? 'smoke test', + ...(args.extra ?? {}), + }; + return JSON.stringify({ + type: args.type, + created_at: args.createdAt ?? '2026-05-04T00:00:00Z', + data, + }); +} + +const EMAIL_STATUS = [ + 'Queued', + 'Sent', + 'Delivered', + 'DeliveryDelayed', + 'Bounced', + 'Failed', + 'Cancelled', +] as const; + +function emailStatus(rowText: string): string { + const parsed = JSON.parse(rowText); + const row = parsed?.[1]; + const variant = row?.[4]; + const tag = variant?.[0]; + if (typeof tag !== 'number' || tag < 0 || tag >= EMAIL_STATUS.length) { + throw new Error(`could not parse email status from row: ${rowText}`); + } + return EMAIL_STATUS[tag]!; +} + +const WEBHOOK_EVENT_STATUS = [ + 'Received', + 'Processed', + 'Ignored', + 'Failed', +] as const; + +function webhookEventStatus(rowText: string): string { + const parsed = JSON.parse(rowText); + const row = parsed?.[1]; + const variant = row?.[5]; + const tag = variant?.[0]; + if ( + typeof tag !== 'number' || + tag < 0 || + tag >= WEBHOOK_EVENT_STATUS.length + ) { + throw new Error( + `could not parse webhook event status from row: ${rowText}` + ); + } + return WEBHOOK_EVENT_STATUS[tag]!; +} + +async function main() { + const opts = parseArgs(process.argv.slice(2)); + // Unique run id so re-runs don't collide on idempotent webhook IDs. + const runId = Date.now().toString(36); + const evt = (suffix: string) => `evt_${runId}_${suffix}`; + const em = (suffix: string) => `em_${runId}_${suffix}`; + + if (!opts.skipBuildPublish) { + step('spacetime build'); + const modulePath = opts.example + ? ['--module-path', 'example/spacetimedb'] + : []; + const build = await run('spacetime', ['build', ...modulePath]); + if (build.code !== 0) { + process.stderr.write(build.stderr); + throw new Error('build failed'); + } + + step(`spacetime publish --server ${opts.server} ${opts.database}`); + const publish = await run('spacetime', [ + 'publish', + '--server', + opts.server, + '--yes', + '--delete-data', + ...modulePath, + opts.database, + ]); + if (publish.code !== 0) { + process.stderr.write(publish.stderr); + throw new Error('publish failed'); + } + } + + // Negative path: send_email refuses cleanly when config is not set. + step('negative: send_email before config, expect failure'); + const preBootstrap = await expectCallFails(opts, 'send_email', [ + 'null', + JSON.stringify(['delivered@resend.dev']), + quote('hello'), + some('

hello

'), + 'null', + 'null', + 'null', + 'null', + 'null', + 'null', + 'null', + 'null', + ]); + if (!preBootstrap.toLowerCase().includes('config')) { + throw new Error( + `expected error to mention config; got: ${preBootstrap.slice(0, 400)}` + ); + } + + step('set_resend_config'); + await callReducer(opts, 'set_resend_config', [ + quote('re_smoke_placeholder'), + some(RESEND_WEBHOOK_SECRET), + some('onboarding@resend.dev'), + ]); + + if (opts.example) { + step('HTTP rejects failed payloads on first delivery and redelivery'); + const eventId = evt('invalid_http'); + const payloadJson = JSON.stringify({ type: 'email.sent', data: {} }); + for (let attempt = 0; attempt < 2; attempt++) { + const timestamp = String(Math.floor(Date.now() / 1000)); + const response = await fetch( + `${opts.server}/v1/database/${opts.database}/route/webhook/resend`, + { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'svix-id': eventId, + 'svix-timestamp': timestamp, + 'svix-signature': svixSignature({ + eventId, + timestamp, + payloadJson, + }), + }, + body: payloadJson, + } + ); + if (response.status !== 400) + throw new Error( + `expected invalid payload HTTP 400 on attempt ${attempt}, got ${response.status}: ${await response.text()}` + ); + } + } + + step('negative: anonymous callers cannot query email state'); + const unauthorized = await expectCallFails( + opts, + 'get_email', + [quote(em('a'))], + true + ); + if (!unauthorized.toLowerCase().includes('not_authorized')) { + throw new Error( + `expected get_email to reject a non-admin caller: ${unauthorized.slice(0, 400)}` + ); + } + + step('negative: signed webhook type must match supplied event type'); + const mismatchEventId = evt('metadata_mismatch'); + const mismatchPayload = eventPayload({ + type: 'email.delivered', + emailId: em('metadata_mismatch'), + }); + const mismatchTimestamp = String(Math.floor(Date.now() / 1000)); + const mismatch = await expectCallFails(opts, 'ingest_resend_webhook', [ + quote(mismatchEventId), + quote('email.bounced'), + quote(mismatchPayload), + some( + svixSignature({ + eventId: mismatchEventId, + timestamp: mismatchTimestamp, + payloadJson: mismatchPayload, + }) + ), + some(mismatchTimestamp), + ]); + if (!mismatch.toLowerCase().includes('metadata')) { + throw new Error( + `expected signed metadata mismatch failure: ${mismatch.slice(0, 400)}` + ); + } + + step('reducer keeps a Failed row for an invalid signed payload'); + const invalidEventId = evt('invalid_reducer'); + await ingestWebhook( + opts, + invalidEventId, + 'email.sent', + JSON.stringify({ type: 'email.sent', data: {} }) + ); + const readInvalidEvent = () => + callReducer(opts, 'get_webhook_event', [quote(invalidEventId)]); + let stored = await readInvalidEvent(); + if (webhookEventStatus(stored) !== 'Failed') + throw new Error(`expected Failed webhook row after ingest: ${stored}`); + await callReducer(opts, 'replay_webhook_event', [quote(invalidEventId)]); + stored = await readInvalidEvent(); + if (webhookEventStatus(stored) !== 'Failed') + throw new Error(`expected Failed webhook row after replay: ${stored}`); + + step('signed event types the submodule does not handle are acknowledged'); + await ingestWebhook( + opts, + evt('contact'), + 'contact.created', + JSON.stringify({ + type: 'contact.created', + created_at: '2026-05-04T00:00:00Z', + data: { id: 'contact_smoke' }, + }) + ); + + // Email A happy path: queued -> sent -> delivered, then flag overlays must not roll status back. + step(`ingest email.sent for ${em('a')}`); + await ingestWebhook( + opts, + evt('a'), + 'email.sent', + eventPayload({ type: 'email.sent', emailId: em('a') }) + ); + + step(`ingest email.delivered for ${em('a')}`); + await ingestWebhook( + opts, + evt('b'), + 'email.delivered', + eventPayload({ type: 'email.delivered', emailId: em('a') }) + ); + + step(`verify status=delivered for ${em('a')}`); + let row = await callReducer(opts, 'get_email', [quote(em('a'))]); + if (emailStatus(row) !== 'Delivered') { + throw new Error(`expected delivered for ${em('a')}, got: ${row}`); + } + + step(`ingest email.complained for ${em('a')} (flag, must NOT change status)`); + await ingestWebhook( + opts, + evt('e'), + 'email.complained', + eventPayload({ type: 'email.complained', emailId: em('a') }) + ); + row = await callReducer(opts, 'get_email', [quote(em('a'))]); + if (emailStatus(row) !== 'Delivered') { + throw new Error(`complained should not flip status: ${row}`); + } + + step(`ingest email.opened for ${em('a')} (flag)`); + await ingestWebhook( + opts, + evt('g'), + 'email.opened', + eventPayload({ type: 'email.opened', emailId: em('a') }) + ); + row = await callReducer(opts, 'get_email', [quote(em('a'))]); + if (emailStatus(row) !== 'Delivered') { + throw new Error(`opened should not flip status: ${row}`); + } + + step(`ingest email.clicked for ${em('a')} (flag + detail captured)`); + await ingestWebhook( + opts, + evt('h'), + 'email.clicked', + eventPayload({ + type: 'email.clicked', + emailId: em('a'), + extra: { + click: { + ipAddress: '203.0.113.42', + link: 'https://spacetimedb.com', + timestamp: '2026-05-04T00:00:00Z', + userAgent: 'Mozilla/5.0 (smoke-test)', + }, + }, + }) + ); + const clickEvents = await callReducer( + opts, + 'list_delivery_events_for_email', + [quote(em('a'))] + ); + const clickRows: unknown = JSON.parse(clickEvents); + const clickRow = Array.isArray(clickRows) + ? clickRows.find(row => Array.isArray(row) && row[2] === 'email.clicked') + : undefined; + if (!clickRow) { + throw new Error(`expected click event in delivery log: ${clickEvents}`); + } + const detailOption = Array.isArray(clickRow) ? clickRow[4] : undefined; + const detailJson = + Array.isArray(detailOption) && + detailOption[0] === 0 && + typeof detailOption[1] === 'string' + ? detailOption[1] + : undefined; + const clickDetail = detailJson ? JSON.parse(detailJson) : undefined; + if (clickDetail?.link !== 'https://spacetimedb.com') { + throw new Error(`expected click detail (link) preserved: ${clickEvents}`); + } + + // Email C bounce path with structured detail. + step(`ingest email.bounced for ${em('c')}`); + await ingestWebhook( + opts, + evt('c'), + 'email.bounced', + eventPayload({ + type: 'email.bounced', + emailId: em('c'), + to: ['bounced@resend.dev'], + extra: { + bounce: { + message: 'Mailbox does not exist', + subType: 'NoEmail', + type: 'Permanent', + }, + }, + }) + ); + const bouncedRow = await callReducer(opts, 'get_email', [quote(em('c'))]); + if (emailStatus(bouncedRow) !== 'Bounced') { + throw new Error(`expected bounced for ${em('c')}: ${bouncedRow}`); + } + if (!bouncedRow.includes('Mailbox does not exist')) { + throw new Error(`expected bounce reason in row: ${bouncedRow}`); + } + + step('late sent, delayed, and failed events do not undo a bounce'); + for (const type of ['email.sent', 'email.delivery_delayed']) { + await ingestWebhook( + opts, + evt(`late_${type}`), + type, + eventPayload({ + type, + emailId: em('c'), + createdAt: '2026-05-03T23:59:00Z', + }) + ); + const current = await callReducer(opts, 'get_email', [quote(em('c'))]); + if (emailStatus(current) !== 'Bounced') + throw new Error(`late ${type} changed bounce: ${current}`); + } + await ingestWebhook( + opts, + evt('late_failed'), + 'email.failed', + eventPayload({ + type: 'email.failed', + emailId: em('c'), + extra: { failed: { reason: 'late failure' } }, + }) + ); + const afterLateFailure = await callReducer(opts, 'get_email', [ + quote(em('c')), + ]); + if ( + emailStatus(afterLateFailure) !== 'Bounced' || + afterLateFailure.includes('late failure') + ) + throw new Error(`late failure changed bounce: ${afterLateFailure}`); + await callReducer(opts, 'replay_webhook_event', [ + quote(evt('late_email.sent')), + ]); + if ( + emailStatus(await callReducer(opts, 'get_email', [quote(em('c'))])) !== + 'Bounced' + ) { + throw new Error('administrative replay regressed email status'); + } + + // Email D delivery_delayed status path. + step(`ingest email.delivery_delayed for ${em('d')}`); + await ingestWebhook( + opts, + evt('d'), + 'email.delivery_delayed', + eventPayload({ type: 'email.delivery_delayed', emailId: em('d') }) + ); + const delayed = await callReducer(opts, 'get_email', [quote(em('d'))]); + if (emailStatus(delayed) !== 'DeliveryDelayed') { + throw new Error(`expected delivery_delayed for ${em('d')}: ${delayed}`); + } + + // Email F failed status with reason. + step(`ingest email.failed for ${em('f')}`); + await ingestWebhook( + opts, + evt('f'), + 'email.failed', + eventPayload({ + type: 'email.failed', + emailId: em('f'), + extra: { failed: { reason: 'rate limited by destination MTA' } }, + }) + ); + const failedRow = await callReducer(opts, 'get_email', [quote(em('f'))]); + if (emailStatus(failedRow) !== 'Failed') { + throw new Error(`expected failed for ${em('f')}: ${failedRow}`); + } + if (!failedRow.includes('rate limited')) { + throw new Error(`expected failure reason in row: ${failedRow}`); + } + + // Idempotency + replay. + step( + `verify idempotency: re-ingest ${evt('a')} (already processed, should no-op)` + ); + await ingestWebhook( + opts, + evt('a'), + 'email.sent', + eventPayload({ type: 'email.sent', emailId: em('a') }) + ); + row = await callReducer(opts, 'get_email', [quote(em('a'))]); + if (emailStatus(row) !== 'Delivered') { + throw new Error(`replay broke status: ${row}`); + } + + step(`replay_webhook_event re-applies ${evt('b')} (status stays delivered)`); + await callReducer(opts, 'replay_webhook_event', [quote(evt('b'))]); + row = await callReducer(opts, 'get_email', [quote(em('a'))]); + if (emailStatus(row) !== 'Delivered') { + throw new Error(`replay reducer altered state: ${row}`); + } + + step('negative: replay unknown event_id, expect failure'); + const replayMissing = await expectCallFails(opts, 'replay_webhook_event', [ + quote('evt_does_not_exist_xyz'), + ]); + if (!replayMissing.toLowerCase().includes('not_found')) { + throw new Error( + `expected not_found error; got: ${replayMissing.slice(0, 400)}` + ); + } + + step( + 'done: signed webhook, status, idempotency, replay, and rejection checks passed' + ); +} + +main().catch(err => { + process.stderr.write( + `\nSMOKE TEST FAILED: ${err instanceof Error ? err.message : String(err)}\n` + ); + process.exit(1); +}); diff --git a/spacetime-resend-ts/scripts/test-unit.ts b/spacetime-resend-ts/scripts/test-unit.ts new file mode 100644 index 00000000000..01ac89d0cbf --- /dev/null +++ b/spacetime-resend-ts/scripts/test-unit.ts @@ -0,0 +1,98 @@ +import * as assert from 'node:assert/strict'; +import { buildResendHttpRequest } from '../src/submodule/request'; +import { validateEmailInput } from '../src/submodule/email-input'; +import { parseResendEventType } from '../src/submodule/webhook-metadata'; + +assert.equal( + parseResendEventType('{"type":"email.delivered","data":{}}'), + 'email.delivered' +); +assert.equal(parseResendEventType('{"type":"","data":{}}'), undefined); +assert.equal(parseResendEventType('{"data":{}}'), undefined); +assert.equal(parseResendEventType('{bad json'), undefined); +assert.equal(parseResendEventType('[]'), undefined); + +const request = buildResendHttpRequest({ + method: 'post', + path: '/emails', + apiKey: 're_test_secret', + jsonBody: '{"to":["user@example.com"]}', + idempotencyKey: 'email-user-1', +}); +assert.equal(request.url, 'https://api.resend.com/emails'); +assert.equal(request.method, 'POST'); +assert.equal(request.headers.Authorization, 'Bearer re_test_secret'); +assert.throws( + () => + buildResendHttpRequest({ + method: 'GET', + path: 'https://attacker.example/collect', + apiKey: 're_test_secret', + jsonBody: undefined, + idempotencyKey: undefined, + }), + /resend\.request_path_invalid/ +); +assert.throws( + () => + buildResendHttpRequest({ + method: 'GET', + path: '/emails\u007fblocked', + apiKey: 're_test_secret', + jsonBody: undefined, + idempotencyKey: undefined, + }), + /resend\.request_path_invalid/ +); +assert.throws( + () => + buildResendHttpRequest({ + method: 'TRACE', + path: '/emails', + apiKey: 're_test_secret', + jsonBody: undefined, + idempotencyKey: undefined, + }), + /resend\.request_method_invalid/ +); + +assert.doesNotThrow(() => + validateEmailInput({ + to: ['user@example.com'], + subject: 'Welcome', + text: 'Hello', + }) +); +assert.throws( + () => validateEmailInput({ to: [], subject: 'Welcome', text: 'Hello' }), + /resend\.send_email_no_recipients/ +); +assert.throws( + () => + validateEmailInput({ + to: ['user@example.com\u007fblocked'], + subject: 'Welcome', + text: 'Hello', + }), + /resend\.to_invalid_address/ +); +assert.throws( + () => + validateEmailInput({ + to: ['user@example.com'], + subject: 'Welcome\r\nx-injected: yes', + text: 'Hello', + }), + /resend\.send_email_invalid_subject/ +); +assert.throws( + () => + validateEmailInput({ + to: Array.from({ length: 101 }, (_, index) => `user${index}@example.com`), + subject: 'Welcome', + text: 'Hello', + }), + /resend\.to_too_many/ +); + +console.log('resend unit tests passed'); diff --git a/spacetime-resend-ts/scripts/test-webhooks.ts b/spacetime-resend-ts/scripts/test-webhooks.ts new file mode 100644 index 00000000000..85b3c54bfa0 --- /dev/null +++ b/spacetime-resend-ts/scripts/test-webhooks.ts @@ -0,0 +1,115 @@ +import * as assert from 'node:assert/strict'; +import { createHmac } from 'node:crypto'; +import { Timestamp } from 'spacetimedb'; +import { SenderError } from 'spacetimedb/server'; +import { + ingestResendWebhook, + makeResendWebhookHandler, +} from '../src/submodule/webhooks'; + +const secretRaw = 'resend_unit_test_secret'; +const secret = `whsec_${Buffer.from(secretRaw).toString('base64')}`; +const nowSeconds = 1_800_000_000; +const timestamp = String(nowSeconds); +const payloadJson = JSON.stringify({ + type: 'contact.created', + created_at: '2027-01-15T08:00:00Z', + data: { id: 'contact_1' }, +}); + +// Signed and handled, but fails payload validation. +const invalidPayloadJson = JSON.stringify({ + type: 'email.sent', + created_at: '2027-01-15T08:00:00Z', + data: {}, +}); + +function sign(eventId: string, body = payloadJson): string { + const digest = createHmac('sha256', secretRaw) + .update(`${eventId}.${timestamp}.${body}`) + .digest('base64'); + return `v1,${digest}`; +} + +// The mock context implements only the tables these paths read and write. +type EventRow = { eventId: string; status: { tag: string } }; +const webhookEvents = new Map(); +const tx = { + timestamp: new Timestamp(BigInt(nowSeconds) * 1_000_000n), + db: { + resendConfig: { + singleton: { find: () => ({ webhookSigningSecret: secret }) }, + }, + resendWebhookEvent: { + eventId: { + find: (id: string) => webhookEvents.get(id), + update: (row: EventRow) => webhookEvents.set(row.eventId, row), + }, + insert: (row: EventRow) => webhookEvents.set(row.eventId, row), + }, + }, +}; + +const handler = makeResendWebhookHandler(); +function post(eventId: string, signature: string, body = payloadJson) { + const headers = new Map([ + ['svix-id', eventId], + ['svix-timestamp', timestamp], + ['svix-signature', signature], + ]); + const req = { + method: 'POST', + headers: { get: (name: string) => headers.get(name) ?? null }, + text: () => body, + }; + return handler( + { withTx: (fn: (ctx: typeof tx) => unknown) => fn(tx) } as never, + req as never + ); +} + +const rejected = post('evt_bad_http', sign('evt_other')); +assert.equal(rejected.status, 401); +assert.match(rejected.text(), /resend\.webhook_signature_mismatch/); +assert.equal(webhookEvents.size, 0); + +assert.equal(post('evt_good_http', sign('evt_good_http')).status, 200); +assert.ok(webhookEvents.has('evt_good_http')); + +const invalidHttp = post( + 'evt_invalid_http', + sign('evt_invalid_http', invalidPayloadJson), + invalidPayloadJson +); +assert.equal(invalidHttp.status, 400); +assert.match(invalidHttp.text(), /resend\.webhook_payload_invalid/); +assert.equal(webhookEvents.get('evt_invalid_http')?.status.tag, 'Failed'); + +const ingest = (eventId: string, signature: string, body = payloadJson) => + ingestResendWebhook(tx as never, { + eventId, + eventType: JSON.parse(body).type, + payloadJson: body, + signatureHeader: signature, + timestampHeader: timestamp, + }); + +assert.throws( + () => ingest('evt_bad_reducer', sign('evt_other')), + (error: unknown) => + error instanceof SenderError && + /resend\.webhook_signature_mismatch/.test(error.message) +); +assert.ok(!webhookEvents.has('evt_bad_reducer')); +ingest('evt_good_reducer', sign('evt_good_reducer')); +assert.ok(webhookEvents.has('evt_good_reducer')); + +// The reducer returns so the Failed row commits. +ingest( + 'evt_invalid_reducer', + sign('evt_invalid_reducer', invalidPayloadJson), + invalidPayloadJson +); +assert.equal(webhookEvents.get('evt_invalid_reducer')?.status.tag, 'Failed'); + +process.stdout.write('resend webhook tests passed\n'); diff --git a/spacetime-resend-ts/src/index.ts b/spacetime-resend-ts/src/index.ts new file mode 100644 index 00000000000..72d8ebde3b1 --- /dev/null +++ b/spacetime-resend-ts/src/index.ts @@ -0,0 +1,19 @@ +export { default, init } from './submodule/schema.js'; +export { + ingestResendWebhook, + replayWebhookEvent, +} from './submodule/webhooks.js'; + +export { setResendConfig, getResendConfigStatus } from './submodule/config.js'; +export { addAdminIdentity, removeAdminIdentity } from './submodule/auth.js'; +export { + cancelEmail, + getEmail, + getWebhookEvent, + listDeliveryEventsForEmail, + listEmailsByOrgId, + listEmailsByStatus, + listEmailsByUserId, + resendApiRequest, + sendEmail, +} from './submodule/operations.js'; diff --git a/spacetime-resend-ts/src/submodule.ts b/spacetime-resend-ts/src/submodule.ts new file mode 100644 index 00000000000..6df49341a3f --- /dev/null +++ b/spacetime-resend-ts/src/submodule.ts @@ -0,0 +1,30 @@ +export { default } from './submodule/schema.js'; +export { + resendDeliveryEventTable, + resendEmailTable, + t, +} from './submodule/schema.js'; +export { install } from './submodule/install.js'; +export { errors } from './submodule/errors.js'; +export { + ingestResendWebhook, + replayWebhookEvent, + makeResendWebhookHandler, + type ResendWebhookIngestArgs, +} from './submodule/webhooks.js'; +export { + sendEmailRequest, + sendEmail, + cancelEmail, + getEmail, + getWebhookEvent, + listEmailsByUserId, + listEmailsByOrgId, + listEmailsByStatus, + listDeliveryEventsForEmail, + resendApiRequest, + type SendEmailArgs, +} from './submodule/operations.js'; + +export { setResendConfig, getResendConfigStatus } from './submodule/config.js'; +export { addAdminIdentity, removeAdminIdentity } from './submodule/auth.js'; diff --git a/spacetime-resend-ts/src/submodule/auth.ts b/spacetime-resend-ts/src/submodule/auth.ts new file mode 100644 index 00000000000..83d435636b0 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/auth.ts @@ -0,0 +1,67 @@ +import { + spacetimedb, + t, + type ProcedureModuleCtx, + type WriteCtx, +} from './schema.js'; +import { throwSenderError } from './validation.js'; +import { errors } from './errors.js'; + +// Admin gate. Fresh publishes seed the owner via init. Public submodule calls +// never bootstrap admin state from "first caller wins". Procedure callers must +// pass the outer ctx.sender explicitly; transaction ctx may not carry sender. +type Sender = WriteCtx['sender']; + +export type AdminVerdict = 'admin' | 'denied'; + +export function isAdmin(ctx: WriteCtx, sender: Sender): boolean { + return ctx.db.resendAdminIdentity.identity.find(sender) != null; +} + +export function adminVerdict(ctx: WriteCtx, sender: Sender): AdminVerdict { + return isAdmin(ctx, sender) ? 'admin' : 'denied'; +} + +export function denyIfNotAdmin(verdict: AdminVerdict): void { + if (verdict === 'denied') throwSenderError(errors.notAuthorized); +} + +export function requireAdmin(ctx: WriteCtx, sender: Sender): void { + if (!isAdmin(ctx, sender)) throwSenderError(errors.notAuthorized); +} + +export const addAdminIdentity = spacetimedb.procedure( + { identity: t.identity() }, + t.unit(), + (ctx: ProcedureModuleCtx, { identity }) => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + ctx.withTx(tx => { + if (tx.db.resendAdminIdentity.identity.find(identity) == null) { + tx.db.resendAdminIdentity.insert({ + identity, + addedAt: ctx.timestamp, + }); + } + }); + return {}; + } +); + +export const removeAdminIdentity = spacetimedb.procedure( + { identity: t.identity() }, + t.unit(), + (ctx: ProcedureModuleCtx, { identity }) => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + ctx.withTx(tx => { + const existing = tx.db.resendAdminIdentity.identity.find(identity); + if (!existing) return; + if (tx.db.resendAdminIdentity.count() <= 1n) { + throwSenderError(errors.cannotRemoveLastAdmin); + } + tx.db.resendAdminIdentity.delete(existing); + }); + return {}; + } +); diff --git a/spacetime-resend-ts/src/submodule/config.ts b/spacetime-resend-ts/src/submodule/config.ts new file mode 100644 index 00000000000..0f1e546f60c --- /dev/null +++ b/spacetime-resend-ts/src/submodule/config.ts @@ -0,0 +1,108 @@ +import { + spacetimedb, + t, + type ProcedureModuleCtx, + type WriteCtx, +} from './schema.js'; +import { adminVerdict, denyIfNotAdmin } from './auth.js'; +import { throwSenderError } from './validation.js'; +import { errors } from './errors.js'; + +export type ResendConfig = { + apiKey: string; + webhookSigningSecret: string | undefined; + defaultFrom: string | undefined; +}; + +export function loadConfigOrThrow(ctx: WriteCtx): ResendConfig { + const row = ctx.db.resendConfig.singleton.find(true); + if (!row) { + throwSenderError( + `${errors.configNotSet}: call set_resend_config(...) first` + ); + } + return { + apiKey: row.apiKey, + webhookSigningSecret: row.webhookSigningSecret, + defaultFrom: row.defaultFrom, + }; +} + +export function loadConfigOrThrowFromProcedure( + ctx: ProcedureModuleCtx +): ResendConfig { + return ctx.withTx(tx => loadConfigOrThrow(tx)); +} + +function upsertConfig( + ctx: WriteCtx, + args: { + apiKey: string; + webhookSigningSecret?: string | undefined; + defaultFrom?: string | undefined; + } +) { + const existing = ctx.db.resendConfig.singleton.find(true); + const row = { + singleton: true, + apiKey: args.apiKey, + webhookSigningSecret: + args.webhookSigningSecret ?? existing?.webhookSigningSecret, + defaultFrom: args.defaultFrom ?? existing?.defaultFrom, + updatedAt: ctx.timestamp, + }; + if (!existing) { + ctx.db.resendConfig.insert(row); + return; + } + ctx.db.resendConfig.singleton.update(row); +} + +// Requires an admin seeded by the database owner; no public first-call bootstrap. +export const setResendConfig = spacetimedb.procedure( + { + apiKey: t.string(), + webhookSigningSecret: t.option(t.string()), + defaultFrom: t.option(t.string()), + }, + t.unit(), + (ctx, args) => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + ctx.withTx(tx => { + upsertConfig(tx, args); + }); + return {}; + } +); + +export const getResendConfigStatus = spacetimedb.procedure( + {}, + t.object('ResendConfigStatus', { + isConfigured: t.bool(), + hasWebhookSecret: t.bool(), + defaultFrom: t.option(t.string()), + apiKeyLength: t.u16(), + }), + ctx => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + return ctx.withTx(tx => { + const row = tx.db.resendConfig.singleton.find(true); + if (!row) { + return { + isConfigured: false, + hasWebhookSecret: false, + defaultFrom: undefined, + apiKeyLength: 0, + }; + } + return { + isConfigured: true, + hasWebhookSecret: row.webhookSigningSecret !== undefined, + defaultFrom: row.defaultFrom, + apiKeyLength: row.apiKey.length, + }; + }); + } +); diff --git a/spacetime-resend-ts/src/submodule/email-input.ts b/spacetime-resend-ts/src/submodule/email-input.ts new file mode 100644 index 00000000000..1b52a077e12 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/email-input.ts @@ -0,0 +1,106 @@ +import { errors } from './errors.js'; +import { hasControlCharacter } from './text-validation.js'; + +export type EmailInput = { + from?: string | undefined; + to: string[]; + subject: string; + html?: string | undefined; + text?: string | undefined; + cc?: string[] | undefined; + bcc?: string[] | undefined; + replyTo?: string[] | undefined; + tagsJson?: string | undefined; + headersJson?: string | undefined; + scheduledAt?: string | undefined; +}; + +function fail(code: string): never { + throw new Error(code); +} + +function validateAddressList( + values: string[] | undefined, + tooMany: string, + invalidAddress: string +): void { + if (values === undefined) return; + if (values.length > 100) fail(tooMany); + for (const value of values) { + if ( + value.length === 0 || + value.length > 320 || + hasControlCharacter(value) + ) { + fail(invalidAddress); + } + } +} + +function validateJson( + value: string | undefined, + tooLarge: string, + invalidJson: string, + maxLength: number +): void { + if (value === undefined) return; + if (value.length > maxLength) fail(tooLarge); + let parsed: unknown; + try { + parsed = JSON.parse(value); + } catch { + fail(invalidJson); + } + if (parsed === null || typeof parsed !== 'object') fail(invalidJson); +} + +export function validateEmailInput(args: EmailInput): void { + if (args.to.length === 0) fail(errors.sendEmailNoRecipients); + validateAddressList(args.to, errors.toTooMany, errors.toInvalidAddress); + validateAddressList(args.cc, errors.ccTooMany, errors.ccInvalidAddress); + validateAddressList(args.bcc, errors.bccTooMany, errors.bccInvalidAddress); + validateAddressList( + args.replyTo, + errors.replyToTooMany, + errors.replyToInvalidAddress + ); + const recipientCount = + args.to.length + (args.cc?.length ?? 0) + (args.bcc?.length ?? 0); + if (recipientCount > 100) fail(errors.sendEmailTooManyRecipients); + if ( + args.from !== undefined && + (args.from.length === 0 || + args.from.length > 320 || + hasControlCharacter(args.from)) + ) + fail(errors.sendEmailInvalidFrom); + if ( + args.subject.length === 0 || + args.subject.length > 998 || + hasControlCharacter(args.subject) + ) { + fail(errors.sendEmailInvalidSubject); + } + if (args.html === undefined && args.text === undefined) + fail(errors.sendEmailMissingContent); + if ((args.html?.length ?? 0) > 200_000) fail(errors.sendEmailHtmlTooLarge); + if ((args.text?.length ?? 0) > 200_000) fail(errors.sendEmailTextTooLarge); + validateJson( + args.tagsJson, + errors.tagsTooLarge, + errors.tagsInvalidJson, + 16_384 + ); + validateJson( + args.headersJson, + errors.headersTooLarge, + errors.headersInvalidJson, + 16_384 + ); + if ( + (args.scheduledAt?.length ?? 0) > 128 || + hasControlCharacter(args.scheduledAt ?? '') + ) { + fail(errors.sendEmailInvalidSchedule); + } +} diff --git a/spacetime-resend-ts/src/submodule/email_writes.ts b/spacetime-resend-ts/src/submodule/email_writes.ts new file mode 100644 index 00000000000..1519cb7b101 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/email_writes.ts @@ -0,0 +1,99 @@ +import { + EmailStatus, + type EmailStatusValue, + type ModuleTimestamp, + type WriteCtx, +} from './schema.js'; + +const STATUS_ORDER = { + Queued: 0, + Sent: 1, + DeliveryDelayed: 2, + Delivered: 3, + Cancelled: 4, + Failed: 5, + Bounced: 6, +}; + +// Any field passed as `undefined` preserves the existing row's value. Used by webhooks (sparse per-event fields). +export function upsertEmail( + ctx: WriteCtx, + now: ModuleTimestamp, + args: { + resendId: string; + fromAddress: string; + toAddressesJson: string; + subject: string | undefined; + html: string | undefined; + text: string | undefined; + status: EmailStatusValue | undefined; + statusUpdatedAt?: ModuleTimestamp; + lastError: string | undefined; + bouncedAt: ModuleTimestamp | undefined; + bounceJson: string | undefined; + failedAt: ModuleTimestamp | undefined; + failureReason: string | undefined; + complained: boolean; + complainedAt: ModuleTimestamp | undefined; + opened: boolean; + openedAt: ModuleTimestamp | undefined; + clicked: boolean; + clickedAt: ModuleTimestamp | undefined; + deliveredAt: ModuleTimestamp | undefined; + sentAt: ModuleTimestamp | undefined; + tagsJson: string | undefined; + userId: string | undefined; + orgId: string | undefined; + } +) { + const existing = ctx.db.resendEmail.resendId.find(args.resendId); + const statusTime = args.statusUpdatedAt ?? now; + // Late webhooks and send responses cannot undo a later delivery stage. + const replaceStatus = + args.status !== undefined && + (!existing || + (STATUS_ORDER[args.status.tag] >= STATUS_ORDER[existing.status.tag] && + (existing.status.tag === 'Queued' || + !existing.statusUpdatedAt || + statusTime.microsSinceUnixEpoch >= + existing.statusUpdatedAt.microsSinceUnixEpoch))); + // Error and bounce details describe the status that produced them. + const statusDetail = replaceStatus ? args : undefined; + const row = { + resendId: args.resendId, + fromAddress: args.fromAddress, + toAddressesJson: args.toAddressesJson, + subject: args.subject ?? existing?.subject, + html: args.html ?? existing?.html, + text: args.text ?? existing?.text, + status: + replaceStatus && args.status + ? args.status + : (existing?.status ?? EmailStatus.Queued), + statusUpdatedAt: replaceStatus ? statusTime : existing?.statusUpdatedAt, + lastError: statusDetail?.lastError ?? existing?.lastError, + bouncedAt: statusDetail?.bouncedAt ?? existing?.bouncedAt, + bounceJson: statusDetail?.bounceJson ?? existing?.bounceJson, + failedAt: statusDetail?.failedAt ?? existing?.failedAt, + failureReason: statusDetail?.failureReason ?? existing?.failureReason, + complained: args.complained || (existing?.complained ?? false), + complainedAt: args.complainedAt ?? existing?.complainedAt, + opened: args.opened || (existing?.opened ?? false), + openedAt: args.openedAt ?? existing?.openedAt, + clicked: args.clicked || (existing?.clicked ?? false), + clickedAt: args.clickedAt ?? existing?.clickedAt, + deliveredAt: args.deliveredAt ?? existing?.deliveredAt, + sentAt: args.sentAt ?? existing?.sentAt, + tagsJson: args.tagsJson ?? existing?.tagsJson, + userId: args.userId ?? existing?.userId, + orgId: args.orgId ?? existing?.orgId, + createdAt: existing?.createdAt ?? now, + updatedAt: now, + }; + + if (!existing) { + ctx.db.resendEmail.insert(row); + return; + } + ctx.db.resendEmail.resendId.update(row); +} diff --git a/spacetime-resend-ts/src/submodule/errors.ts b/spacetime-resend-ts/src/submodule/errors.ts new file mode 100644 index 00000000000..20afc973521 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/errors.ts @@ -0,0 +1,44 @@ +export const errors = { + notAuthorized: 'resend.not_authorized', + cannotRemoveLastAdmin: 'resend.cannot_remove_last_admin', + configNotSet: 'resend.config_not_set', + requestInvalid: 'resend.request_invalid', + requestPathInvalid: 'resend.request_path_invalid', + requestMethodInvalid: 'resend.request_method_invalid', + requestBodyTooLarge: 'resend.request_body_too_large', + idempotencyKeyTooLong: 'resend.idempotency_key_too_long', + sendEmailInvalidInput: 'resend.send_email_invalid_input', + sendEmailNoRecipients: 'resend.send_email_no_recipients', + sendEmailTooManyRecipients: 'resend.send_email_too_many_recipients', + sendEmailInvalidFrom: 'resend.send_email_invalid_from', + sendEmailInvalidSubject: 'resend.send_email_invalid_subject', + sendEmailMissingContent: 'resend.send_email_missing_content', + sendEmailHtmlTooLarge: 'resend.send_email_html_too_large', + sendEmailTextTooLarge: 'resend.send_email_text_too_large', + sendEmailInvalidSchedule: 'resend.send_email_invalid_schedule', + sendEmailMissingFrom: 'resend.send_email_missing_from', + sendEmailFailed: 'resend.send_email_failed', + sendEmailInvalidResponse: 'resend.send_email_invalid_response', + toTooMany: 'resend.to_too_many', + toInvalidAddress: 'resend.to_invalid_address', + ccTooMany: 'resend.cc_too_many', + ccInvalidAddress: 'resend.cc_invalid_address', + bccTooMany: 'resend.bcc_too_many', + bccInvalidAddress: 'resend.bcc_invalid_address', + replyToTooMany: 'resend.reply_to_too_many', + replyToInvalidAddress: 'resend.reply_to_invalid_address', + tagsTooLarge: 'resend.tags_too_large', + tagsInvalidJson: 'resend.tags_invalid_json', + headersTooLarge: 'resend.headers_too_large', + headersInvalidJson: 'resend.headers_invalid_json', + cancelEmailFailed: 'resend.cancel_email_failed', + webhookMethodNotAllowed: 'resend.webhook_method_not_allowed', + webhookMetadataInvalid: 'resend.webhook_metadata_invalid', + webhookMetadataMismatch: 'resend.webhook_metadata_mismatch', + webhookPayloadTooLarge: 'resend.webhook_payload_too_large', + webhookHeaderTooLarge: 'resend.webhook_header_too_large', + webhookSecretNotConfigured: 'resend.webhook_secret_not_configured', + webhookSignatureMismatch: 'resend.webhook_signature_mismatch', + webhookPayloadInvalid: 'resend.webhook_payload_invalid', + webhookEventNotFound: 'resend.webhook_event_not_found', +} as const; diff --git a/spacetime-resend-ts/src/submodule/http.ts b/spacetime-resend-ts/src/submodule/http.ts new file mode 100644 index 00000000000..fc924a1184d --- /dev/null +++ b/spacetime-resend-ts/src/submodule/http.ts @@ -0,0 +1,68 @@ +import * as v from 'valibot'; +import { type ProcedureModuleCtx, vResendErrorBody } from './schema.js'; +import { safeJsonParse, throwSenderError } from './validation.js'; +import { buildResendHttpRequest } from './request.js'; +import { errors } from './errors.js'; + +export type ResendHttpResponse = { + status: number; + body: string; +}; + +export function callResend( + ctx: ProcedureModuleCtx, + args: { + method: string; + path: string; + apiKey: string; + jsonBody: string | undefined; + idempotencyKey: string | undefined; + } +): ResendHttpResponse { + let request; + try { + request = buildResendHttpRequest(args); + } catch (error) { + throwSenderError( + error instanceof Error ? error.message : errors.requestInvalid + ); + } + const response = ctx.http.fetch(request.url, { + method: request.method, + headers: request.headers, + body: request.body, + }); + return { + status: response.status, + body: response.text(), + }; +} +export function ensureOkOrThrow( + response: ResendHttpResponse, + errorPrefix: string +): void { + if (response.status >= 200 && response.status < 300) return; + throwSenderError( + `${errorPrefix}:${response.status}${resendErrorSuffix(response.body)}` + ); +} + +export function resendErrorSuffix(body: string): string { + const parsed = safeJsonParse(body); + if (parsed !== undefined) { + const result = v.safeParse(vResendErrorBody, parsed); + if (result.success) { + const parts: string[] = []; + if (result.output.name) parts.push(`name=${result.output.name}`); + if (result.output.message) { + parts.push( + `msg=${result.output.message.replace(/\s+/g, ' ').slice(0, 240)}` + ); + } + if (parts.length > 0) return `:${parts.join('|')}`; + } + } + const compact = body.replace(/\s+/g, ' ').trim(); + if (!compact) return ''; + return `:body=${compact.slice(0, 240)}`; +} diff --git a/spacetime-resend-ts/src/submodule/install.ts b/spacetime-resend-ts/src/submodule/install.ts new file mode 100644 index 00000000000..493ec8558cf --- /dev/null +++ b/spacetime-resend-ts/src/submodule/install.ts @@ -0,0 +1,9 @@ +import type { ReducerModuleCtx } from './schema.js'; + +export function install(ctx: ReducerModuleCtx) { + if (ctx.db.resendAdminIdentity.identity.find(ctx.sender) != null) return; + ctx.db.resendAdminIdentity.insert({ + identity: ctx.sender, + addedAt: ctx.timestamp, + }); +} diff --git a/spacetime-resend-ts/src/submodule/operations.ts b/spacetime-resend-ts/src/submodule/operations.ts new file mode 100644 index 00000000000..e5ba032dc11 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/operations.ts @@ -0,0 +1,370 @@ +import * as v from 'valibot'; +import { + EmailStatus, + emailStatus, + resendDeliveryEventTable, + resendEmailTable, + resendWebhookEventTable, + sendEmailResult, + spacetimedb, + t, + vSendEmailResponse, + type ProcedureModuleCtx, + type WriteCtx, +} from './schema.js'; +import { callResend, ensureOkOrThrow } from './http.js'; +import { + safeJsonParse, + summarizeIssues, + throwSenderError, +} from './validation.js'; +import { upsertEmail } from './email_writes.js'; +import { loadConfigOrThrowFromProcedure } from './config.js'; +import { adminVerdict, denyIfNotAdmin } from './auth.js'; +import { validateEmailInput } from './email-input.js'; +import { errors } from './errors.js'; + +function requireProcedureAdmin(ctx: ProcedureModuleCtx): void { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); +} + +const MAX_QUERY_ROWS = 1000; + +function takeRows(rows: Iterable): T[] { + const out: T[] = []; + for (const row of rows) { + if (out.length >= MAX_QUERY_ROWS) break; + out.push(row); + } + return out; +} + +// Resend's send API takes tags as `[{ name, value }]`. +const vSendTags = v.array(v.object({ name: v.string(), value: v.string() })); + +function extractTagFieldsFromJson(tagsJson: string | undefined): { + userId: string | undefined; + orgId: string | undefined; +} { + const result = v.safeParse(vSendTags, tagsJson && safeJsonParse(tagsJson)); + if (!result.success) return { userId: undefined, orgId: undefined }; + const tags = result.output; + return { + userId: tags.find(tag => tag.name === 'userId')?.value, + orgId: tags.find(tag => tag.name === 'orgId')?.value, + }; +} + +// Resend expects snake_case fields in the POST /emails request body. +type ResendSendEmailBody = { + from: string; + to: string[]; + subject: string; + html?: string; + text?: string; + cc?: string[]; + bcc?: string[]; + reply_to?: string[]; + scheduled_at?: string; + tags?: unknown; + headers?: unknown; +}; + +function buildSendEmailBody(args: { + from: string; + to: string[]; + subject: string; + html: string | undefined; + text: string | undefined; + cc: string[] | undefined; + bcc: string[] | undefined; + replyTo: string[] | undefined; + tagsJson: string | undefined; + headersJson: string | undefined; + scheduledAt: string | undefined; +}): string { + const body: ResendSendEmailBody = { + from: args.from, + to: args.to, + subject: args.subject, + }; + if (args.html !== undefined) body.html = args.html; + if (args.text !== undefined) body.text = args.text; + if (args.cc !== undefined && args.cc.length > 0) body.cc = args.cc; + if (args.bcc !== undefined && args.bcc.length > 0) body.bcc = args.bcc; + if (args.replyTo !== undefined && args.replyTo.length > 0) { + body.reply_to = args.replyTo; + } + if (args.scheduledAt !== undefined) body.scheduled_at = args.scheduledAt; + if (args.tagsJson !== undefined) { + const parsed = safeJsonParse(args.tagsJson); + if (parsed !== undefined) body.tags = parsed; + } + if (args.headersJson !== undefined) { + const parsed = safeJsonParse(args.headersJson); + if (parsed !== undefined) body.headers = parsed; + } + return JSON.stringify(body); +} + +function recordQueuedEmail( + ctx: WriteCtx, + now: ProcedureModuleCtx['timestamp'], + args: { + resendId: string; + from: string; + to: string[]; + subject: string; + html: string | undefined; + text: string | undefined; + tagsJson: string | undefined; + } +) { + const tagFields = extractTagFieldsFromJson(args.tagsJson); + upsertEmail(ctx, now, { + resendId: args.resendId, + fromAddress: args.from, + toAddressesJson: JSON.stringify(args.to), + subject: args.subject, + html: args.html, + text: args.text, + status: EmailStatus.Queued, + lastError: undefined, + bouncedAt: undefined, + bounceJson: undefined, + failedAt: undefined, + failureReason: undefined, + complained: false, + complainedAt: undefined, + opened: false, + openedAt: undefined, + clicked: false, + clickedAt: undefined, + deliveredAt: undefined, + sentAt: undefined, + tagsJson: args.tagsJson, + userId: tagFields.userId, + orgId: tagFields.orgId, + }); +} + +export type SendEmailArgs = { + from?: string | undefined; + to: string[]; + subject: string; + html?: string | undefined; + text?: string | undefined; + cc?: string[] | undefined; + bcc?: string[] | undefined; + replyTo?: string[] | undefined; + tagsJson?: string | undefined; + headersJson?: string | undefined; + scheduledAt?: string | undefined; + idempotencyKey?: string | undefined; +}; + +export function sendEmailRequest(ctx: ProcedureModuleCtx, args: SendEmailArgs) { + try { + validateEmailInput(args); + } catch (error) { + throwSenderError( + error instanceof Error ? error.message : errors.sendEmailInvalidInput + ); + } + const cfg = loadConfigOrThrowFromProcedure(ctx); + const fromAddress = args.from ?? cfg.defaultFrom; + if (!fromAddress) throwSenderError(errors.sendEmailMissingFrom); + + const jsonBody = buildSendEmailBody({ + from: fromAddress, + to: args.to, + subject: args.subject, + html: args.html, + text: args.text, + cc: args.cc, + bcc: args.bcc, + replyTo: args.replyTo, + tagsJson: args.tagsJson, + headersJson: args.headersJson, + scheduledAt: args.scheduledAt, + }); + + const response = callResend(ctx, { + method: 'POST', + path: '/emails', + apiKey: cfg.apiKey, + jsonBody, + idempotencyKey: args.idempotencyKey, + }); + ensureOkOrThrow(response, errors.sendEmailFailed); + + const parsed = safeJsonParse(response.body); + if (parsed === undefined) throwSenderError(errors.sendEmailInvalidResponse); + const result = v.safeParse(vSendEmailResponse, parsed); + if (!result.success) { + throwSenderError( + `${errors.sendEmailInvalidResponse}:${summarizeIssues(result.issues)}` + ); + } + + const resendId = result.output.id; + ctx.withTx(tx => { + recordQueuedEmail(tx, ctx.timestamp, { + resendId, + from: fromAddress, + to: args.to, + subject: args.subject, + html: args.html, + text: args.text, + tagsJson: args.tagsJson, + }); + }); + return { resendId }; +} + +const sendEmailArgs = { + from: t.option(t.string()), + to: t.array(t.string()), + subject: t.string(), + html: t.option(t.string()), + text: t.option(t.string()), + cc: t.option(t.array(t.string())), + bcc: t.option(t.array(t.string())), + replyTo: t.option(t.array(t.string())), + tagsJson: t.option(t.string()), + headersJson: t.option(t.string()), + scheduledAt: t.option(t.string()), + idempotencyKey: t.option(t.string()), +}; + +export const sendEmail = spacetimedb.procedure( + sendEmailArgs, + sendEmailResult, + (ctx, args) => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + return sendEmailRequest(ctx, args); + } +); + +export const cancelEmail = spacetimedb.procedure( + { resendId: t.string() }, + t.unit(), + (ctx, args) => { + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + const cfg = loadConfigOrThrowFromProcedure(ctx); + const response = callResend(ctx, { + method: 'POST', + path: `/emails/${args.resendId}/cancel`, + apiKey: cfg.apiKey, + jsonBody: undefined, + idempotencyKey: undefined, + }); + ensureOkOrThrow(response, errors.cancelEmailFailed); + + ctx.withTx(tx => { + const existing = tx.db.resendEmail.resendId.find(args.resendId); + if (!existing) return; + const updated = { + ...existing, + status: EmailStatus.Cancelled, + statusUpdatedAt: ctx.timestamp, + updatedAt: ctx.timestamp, + }; + tx.db.resendEmail.resendId.update(updated); + }); + return {}; + } +); + +export const getEmail = spacetimedb.procedure( + { resendId: t.string() }, + t.option(resendEmailTable.rowType), + (ctx, { resendId }) => { + requireProcedureAdmin(ctx); + return ctx.withTx( + tx => tx.db.resendEmail.resendId.find(resendId) ?? undefined + ); + } +); + +export const getWebhookEvent = spacetimedb.procedure( + { eventId: t.string() }, + t.option(resendWebhookEventTable.rowType), + (ctx, { eventId }) => { + requireProcedureAdmin(ctx); + return ctx.withTx( + tx => tx.db.resendWebhookEvent.eventId.find(eventId) ?? undefined + ); + } +); + +export const listEmailsByUserId = spacetimedb.procedure( + { userId: t.string() }, + t.array(resendEmailTable.rowType), + (ctx, { userId }) => { + requireProcedureAdmin(ctx); + return ctx.withTx(tx => + takeRows(tx.db.resendEmail.byUserId.filter(userId)) + ); + } +); + +export const listEmailsByOrgId = spacetimedb.procedure( + { orgId: t.string() }, + t.array(resendEmailTable.rowType), + (ctx, { orgId }) => { + requireProcedureAdmin(ctx); + return ctx.withTx(tx => takeRows(tx.db.resendEmail.byOrgId.filter(orgId))); + } +); + +export const listEmailsByStatus = spacetimedb.procedure( + { status: emailStatus }, + t.array(resendEmailTable.rowType), + (ctx, { status }) => { + requireProcedureAdmin(ctx); + return ctx.withTx(tx => + takeRows(tx.db.resendEmail.byStatus.filter(status)) + ); + } +); + +export const listDeliveryEventsForEmail = spacetimedb.procedure( + { resendId: t.string() }, + t.array(resendDeliveryEventTable.rowType), + (ctx, { resendId }) => { + requireProcedureAdmin(ctx); + return ctx.withTx(tx => + takeRows(tx.db.resendDeliveryEvent.byResendId.filter(resendId)) + ); + } +); + +export const resendApiRequest = spacetimedb.procedure( + { + method: t.string(), + path: t.string(), + jsonBody: t.option(t.string()), + idempotencyKey: t.option(t.string()), + }, + t.object('ResendApiRequestResult', { + status: t.u16(), + body: t.string(), + }), + (ctx, args) => { + // Administrators may make authenticated Resend calls with the stored key. + const verdict = ctx.withTx(tx => adminVerdict(tx, ctx.sender)); + denyIfNotAdmin(verdict); + const cfg = loadConfigOrThrowFromProcedure(ctx); + return callResend(ctx, { + method: args.method, + path: args.path, + apiKey: cfg.apiKey, + jsonBody: args.jsonBody, + idempotencyKey: args.idempotencyKey, + }); + } +); diff --git a/spacetime-resend-ts/src/submodule/request.ts b/spacetime-resend-ts/src/submodule/request.ts new file mode 100644 index 00000000000..bbf13cec563 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/request.ts @@ -0,0 +1,68 @@ +import { errors } from './errors.js'; +import { hasControlCharacter } from './text-validation.js'; + +const RESEND_API_BASE = 'https://api.resend.com'; +const ALLOWED_METHODS = new Set(['GET', 'POST', 'PATCH', 'DELETE']); +const MAX_PATH_LENGTH = 2048; +const MAX_JSON_BODY_LENGTH = 256 * 1024; +const MAX_IDEMPOTENCY_KEY_LENGTH = 256; + +export type ResendHttpRequest = { + method: string; + url: string; + headers: Record; + body: string | undefined; +}; + +function validatePath(path: string): string { + const normalized = path.trim(); + if (!normalized.startsWith('/') || normalized.startsWith('//')) { + throw new Error(errors.requestPathInvalid); + } + if (normalized.includes('\\') || normalized.includes('#')) { + throw new Error(errors.requestPathInvalid); + } + if (normalized.length > MAX_PATH_LENGTH || hasControlCharacter(normalized)) { + throw new Error(errors.requestPathInvalid); + } + return normalized; +} + +export function buildResendHttpRequest(args: { + method: string; + path: string; + apiKey: string; + jsonBody: string | undefined; + idempotencyKey: string | undefined; +}): ResendHttpRequest { + const method = args.method.trim().toUpperCase(); + if (!ALLOWED_METHODS.has(method)) { + throw new Error(errors.requestMethodInvalid); + } + + const path = validatePath(args.path); + const body = args.jsonBody?.length ? args.jsonBody : undefined; + if (body !== undefined && body.length > MAX_JSON_BODY_LENGTH) { + throw new Error(errors.requestBodyTooLarge); + } + if ( + args.idempotencyKey && + args.idempotencyKey.length > MAX_IDEMPOTENCY_KEY_LENGTH + ) { + throw new Error(errors.idempotencyKeyTooLong); + } + + const headers: Record = { + Authorization: `Bearer ${args.apiKey}`, + Accept: 'application/json', + }; + if (body !== undefined) headers['Content-Type'] = 'application/json'; + if (args.idempotencyKey) headers['Idempotency-Key'] = args.idempotencyKey; + + return { + method, + url: `${RESEND_API_BASE}${path}`, + headers, + body, + }; +} diff --git a/spacetime-resend-ts/src/submodule/schema.ts b/spacetime-resend-ts/src/submodule/schema.ts new file mode 100644 index 00000000000..44083445f4f --- /dev/null +++ b/spacetime-resend-ts/src/submodule/schema.ts @@ -0,0 +1,283 @@ +import { + schema, + table, + t, + Range, + SenderError, + type ProcedureCtx, + type ReducerCtx, + type TransactionCtx, +} from 'spacetimedb/server'; +import * as v from 'valibot'; +import { install } from './install.js'; + +// Webhook delivery state. Received = ingest accepted. Processed = applied. +// Ignored = event type this submodule does not handle. Failed = invalid payload. +export const webhookEventStatus = t.enum('WebhookEventStatus', [ + 'Received', + 'Processed', + 'Ignored', + 'Failed', +]); +export const WebhookEventStatus = { + Received: { tag: 'Received' as const }, + Processed: { tag: 'Processed' as const }, + Ignored: { tag: 'Ignored' as const }, + Failed: { tag: 'Failed' as const }, +}; + +// Lifecycle of a tracked outbound email. Tags match Resend's +// `email.` webhook events for direct ingestion mapping. +export const emailStatus = t.enum('EmailStatus', [ + 'Queued', + 'Sent', + 'Delivered', + 'DeliveryDelayed', + 'Bounced', + 'Failed', + 'Cancelled', +]); +export const EmailStatus = { + Queued: { tag: 'Queued' as const }, + Sent: { tag: 'Sent' as const }, + Delivered: { tag: 'Delivered' as const }, + DeliveryDelayed: { tag: 'DeliveryDelayed' as const }, + Bounced: { tag: 'Bounced' as const }, + Failed: { tag: 'Failed' as const }, + Cancelled: { tag: 'Cancelled' as const }, +}; +export type EmailStatusValue = (typeof EmailStatus)[keyof typeof EmailStatus]; +export type WebhookEventStatusValue = + (typeof WebhookEventStatus)[keyof typeof WebhookEventStatus]; + +export const resendEmailRow = { + resendId: t.string().primaryKey(), + fromAddress: t.string(), + toAddressesJson: t.string(), + subject: t.option(t.string()), + status: emailStatus, + lastError: t.option(t.string()), + bouncedAt: t.option(t.timestamp()), + bounceJson: t.option(t.string()), + failedAt: t.option(t.timestamp()), + failureReason: t.option(t.string()), + complained: t.bool(), + complainedAt: t.option(t.timestamp()), + opened: t.bool(), + openedAt: t.option(t.timestamp()), + clicked: t.bool(), + clickedAt: t.option(t.timestamp()), + deliveredAt: t.option(t.timestamp()), + sentAt: t.option(t.timestamp()), + html: t.option(t.string()), + text: t.option(t.string()), + tagsJson: t.option(t.string()), + userId: t.option(t.string()), + orgId: t.option(t.string()), + createdAt: t.timestamp(), + updatedAt: t.timestamp(), + statusUpdatedAt: t.option(t.timestamp()), +}; + +export const resendDeliveryEventRow = { + eventId: t.string().primaryKey(), + resendId: t.string(), + eventType: t.string(), + createdAtIso: t.string(), + detailJson: t.option(t.string()), + insertedAt: t.timestamp(), +}; + +export const resendWebhookEventRow = { + eventId: t.string().primaryKey(), + eventType: t.string(), + payloadJson: t.string(), + signatureHeader: t.option(t.string()), + timestampHeader: t.option(t.string()), + status: webhookEventStatus, + errorMessage: t.option(t.string()), + receivedAt: t.timestamp(), + processedAt: t.option(t.timestamp()), +}; + +// Private singleton; secrets never leak via subscription. +export const resendConfigRow = { + singleton: t.bool().primaryKey(), + apiKey: t.string(), + webhookSigningSecret: t.option(t.string()), + defaultFrom: t.option(t.string()), + updatedAt: t.timestamp(), +}; + +// Fresh publishes seed the owner via init; public procedures never bootstrap admin state. +export const resendAdminIdentityRow = { + identity: t.identity().primaryKey(), + addedAt: t.timestamp(), +}; + +export const resendEmailTable = table( + { + name: 'resend_email', + public: false, + indexes: [ + { accessor: 'byUserId', algorithm: 'btree', columns: ['userId'] }, + { accessor: 'byOrgId', algorithm: 'btree', columns: ['orgId'] }, + { accessor: 'byStatus', algorithm: 'btree', columns: ['status'] }, + ], + }, + resendEmailRow +); + +export const resendDeliveryEventTable = table( + { + name: 'resend_delivery_event', + public: false, + indexes: [ + { accessor: 'byResendId', algorithm: 'btree', columns: ['resendId'] }, + ], + }, + resendDeliveryEventRow +); + +// Private because the raw payload and signature headers are operational data. +// Host modules can expose an admin-only view when needed. +export const resendWebhookEventTable = table( + { + name: 'resend_webhook_event', + public: false, + indexes: [ + { accessor: 'byStatus', algorithm: 'btree', columns: ['status'] }, + ], + }, + resendWebhookEventRow +); + +export const resendConfigTable = table( + { name: 'resend_config', public: false, indexes: [] }, + resendConfigRow +); + +export const resendAdminIdentityTable = table( + { name: 'resend_admin_identity', public: false, indexes: [] }, + resendAdminIdentityRow +); + +export const spacetimedb = schema({ + resendEmail: resendEmailTable, + resendDeliveryEvent: resendDeliveryEventTable, + resendWebhookEvent: resendWebhookEventTable, + resendConfig: resendConfigTable, + resendAdminIdentity: resendAdminIdentityTable, +}); + +export const init = spacetimedb.init(ctx => { + install(ctx); +}); + +export default spacetimedb; + +export type ReducerModuleCtx = ReducerCtx; +export type ProcedureModuleCtx = ProcedureCtx; +export type TransactionModuleCtx = TransactionCtx< + typeof spacetimedb.schemaType +>; +export type WriteCtx = ReducerModuleCtx | TransactionModuleCtx; +export type ModuleTimestamp = ReducerModuleCtx['timestamp']; + +export const sendEmailResult = t.object('SendEmailResult', { + resendId: t.string(), +}); + +export { Range, SenderError, t }; + +// Mirror Resend SDK's BaseEmailEventData. +const vBaseEmailEventData = { + broadcast_id: v.optional(v.string()), + created_at: v.string(), + email_id: v.string(), + from: v.string(), + to: v.array(v.string()), + subject: v.string(), + template_id: v.optional(v.string()), + tags: v.optional(v.record(v.string(), v.string())), +}; + +const vBaseEvent = { + created_at: v.string(), +}; + +export const vEmailEvent = v.variant('type', [ + v.object({ + ...vBaseEvent, + type: v.literal('email.sent'), + data: v.object(vBaseEmailEventData), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.delivered'), + data: v.object(vBaseEmailEventData), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.delivery_delayed'), + data: v.object(vBaseEmailEventData), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.complained'), + data: v.object(vBaseEmailEventData), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.bounced'), + data: v.object({ + ...vBaseEmailEventData, + bounce: v.object({ + message: v.string(), + subType: v.string(), + type: v.string(), + }), + }), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.opened'), + data: v.object(vBaseEmailEventData), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.clicked'), + data: v.object({ + ...vBaseEmailEventData, + click: v.object({ + ipAddress: v.string(), + link: v.string(), + timestamp: v.string(), + userAgent: v.string(), + }), + }), + }), + v.object({ + ...vBaseEvent, + type: v.literal('email.failed'), + data: v.object({ + ...vBaseEmailEventData, + failed: v.object({ + reason: v.string(), + }), + }), + }), +]); + +export type EmailEvent = v.InferOutput; +export type EmailEventType = EmailEvent['type']; + +export const vResendErrorBody = v.object({ + name: v.optional(v.string()), + message: v.optional(v.string()), + statusCode: v.optional(v.union([v.number(), v.null()])), +}); + +export const vSendEmailResponse = v.object({ + id: v.string(), +}); diff --git a/spacetime-resend-ts/src/submodule/text-validation.ts b/spacetime-resend-ts/src/submodule/text-validation.ts new file mode 100644 index 00000000000..5409d6119b8 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/text-validation.ts @@ -0,0 +1,7 @@ +export function hasControlCharacter(value: string): boolean { + for (let index = 0; index < value.length; index++) { + const code = value.charCodeAt(index); + if (code <= 0x1f || code === 0x7f) return true; + } + return false; +} diff --git a/spacetime-resend-ts/src/submodule/validation.ts b/spacetime-resend-ts/src/submodule/validation.ts new file mode 100644 index 00000000000..181f0f5e9ad --- /dev/null +++ b/spacetime-resend-ts/src/submodule/validation.ts @@ -0,0 +1,32 @@ +import * as v from 'valibot'; +import { SenderError } from 'spacetimedb/server'; + +export function assertExhaustive(value: never): never { + throw new Error(`Unhandled discriminant: ${value as string}`); +} + +export function throwSenderError(message: string): never { + throw new SenderError(message); +} + +export function safeJsonParse(input: string): unknown { + try { + return JSON.parse(input); + } catch { + return undefined; + } +} + +export function summarizeIssues(issues: v.BaseIssue[]): string { + if (issues.length === 0) return 'no issues'; + const head = issues[0]!; + const path = (head.path ?? []) + .map(p => + typeof p.key === 'string' || typeof p.key === 'number' + ? String(p.key) + : '?' + ) + .join('.'); + const where = path ? ` at ${path}` : ''; + return `${head.message}${where}`; +} diff --git a/spacetime-resend-ts/src/submodule/webhook-metadata.ts b/spacetime-resend-ts/src/submodule/webhook-metadata.ts new file mode 100644 index 00000000000..62b77b6e133 --- /dev/null +++ b/spacetime-resend-ts/src/submodule/webhook-metadata.ts @@ -0,0 +1,13 @@ +export function parseResendEventType(payloadJson: string): string | undefined { + let parsed: unknown; + try { + parsed = JSON.parse(payloadJson); + } catch { + return undefined; + } + if (typeof parsed !== 'object' || parsed === null) return undefined; + const eventType = (parsed as Record).type; + return typeof eventType === 'string' && eventType.length > 0 + ? eventType + : undefined; +} diff --git a/spacetime-resend-ts/src/submodule/webhooks.ts b/spacetime-resend-ts/src/submodule/webhooks.ts new file mode 100644 index 00000000000..b249d22d20d --- /dev/null +++ b/spacetime-resend-ts/src/submodule/webhooks.ts @@ -0,0 +1,402 @@ +import * as v from 'valibot'; +import { Timestamp } from 'spacetimedb'; +import { + EmailStatus, + WebhookEventStatus, + spacetimedb, + t, + vEmailEvent, + type EmailEvent, + type EmailStatusValue, + type ModuleTimestamp, + type ReducerModuleCtx, + type WebhookEventStatusValue, + type WriteCtx, +} from './schema.js'; +import { upsertEmail } from './email_writes.js'; +import { requireAdmin } from './auth.js'; +import { verifySvixSignature } from '@spacetimedb/crypto'; +import { + SyncResponse, + type Request, + type HandlerContext, +} from 'spacetimedb/server'; +import { + assertExhaustive, + safeJsonParse, + summarizeIssues, + throwSenderError, +} from './validation.js'; +import { parseResendEventType } from './webhook-metadata.js'; +import { errors } from './errors.js'; + +type ResendTags = EmailEvent['data']['tags']; + +function tagsToJson(tags: ResendTags): string | undefined { + if (!tags) return undefined; + try { + return JSON.stringify(tags); + } catch { + return undefined; + } +} + +function extractTagFields(tags: ResendTags): { + userId: string | undefined; + orgId: string | undefined; +} { + if (!tags) return { userId: undefined, orgId: undefined }; + return { userId: tags['userId'], orgId: tags['orgId'] }; +} + +function recordDeliveryEvent( + ctx: WriteCtx, + now: ModuleTimestamp, + args: { + eventId: string; + resendId: string; + eventType: string; + createdAtIso: string; + detailJson: string | undefined; + } +) { + if (ctx.db.resendDeliveryEvent.eventId.find(args.eventId)) return; + ctx.db.resendDeliveryEvent.insert({ + eventId: args.eventId, + resendId: args.resendId, + eventType: args.eventType, + createdAtIso: args.createdAtIso, + detailJson: args.detailJson, + insertedAt: now, + }); +} + +function updateWebhookStatus( + ctx: ReducerModuleCtx, + eventId: string, + status: WebhookEventStatusValue, + errorMessage: string | undefined +) { + const existing = ctx.db.resendWebhookEvent.eventId.find(eventId); + if (!existing) return; + + const isTerminal = status.tag !== 'Received'; + const updated = { + ...existing, + status, + errorMessage, + processedAt: isTerminal ? ctx.timestamp : existing.processedAt, + }; + + ctx.db.resendWebhookEvent.eventId.update(updated); +} + +function makeEmailUpsertArgs( + event: EmailEvent, + now: ModuleTimestamp +): Parameters[2] { + const data = event.data; + const tagFields = extractTagFields(data.tags); + const tagsJson = tagsToJson(data.tags); + const subject = data.subject; + + const base = { + resendId: data.email_id, + fromAddress: data.from, + toAddressesJson: JSON.stringify(data.to), + subject, + // undefined preserves whatever send_email recorded. + html: undefined, + text: undefined, + lastError: undefined, + bouncedAt: undefined, + bounceJson: undefined, + failedAt: undefined, + failureReason: undefined, + complained: false, + complainedAt: undefined, + opened: false, + openedAt: undefined, + clicked: false, + clickedAt: undefined, + deliveredAt: undefined, + sentAt: undefined, + tagsJson, + userId: tagFields.userId, + orgId: tagFields.orgId, + // status undefined = preserve existing or default to queued; branches override. + status: undefined as EmailStatusValue | undefined, + } satisfies Parameters[2]; + + switch (event.type) { + case 'email.sent': + return { ...base, status: EmailStatus.Sent, sentAt: now }; + case 'email.delivered': + return { ...base, status: EmailStatus.Delivered, deliveredAt: now }; + case 'email.delivery_delayed': + return { ...base, status: EmailStatus.DeliveryDelayed }; + case 'email.bounced': + return { + ...base, + status: EmailStatus.Bounced, + bouncedAt: now, + bounceJson: JSON.stringify(event.data.bounce), + lastError: event.data.bounce.message, + }; + case 'email.failed': + return { + ...base, + status: EmailStatus.Failed, + failedAt: now, + failureReason: event.data.failed.reason, + lastError: event.data.failed.reason, + }; + case 'email.complained': + return { ...base, complained: true, complainedAt: now }; + case 'email.opened': + return { ...base, opened: true, openedAt: now }; + case 'email.clicked': + return { ...base, clicked: true, clickedAt: now }; + default: + return assertExhaustive(event); + } +} + +function detailJsonForEvent(event: EmailEvent): string | undefined { + switch (event.type) { + case 'email.bounced': + return JSON.stringify(event.data.bounce); + case 'email.failed': + return JSON.stringify(event.data.failed); + case 'email.clicked': + return JSON.stringify(event.data.click); + case 'email.sent': + case 'email.delivered': + case 'email.delivery_delayed': + case 'email.complained': + case 'email.opened': + return undefined; + default: + return assertExhaustive(event); + } +} + +// Resend also sends event types this submodule does not track, such as +// `contact.*`, `domain.*`, and `email.received`. Those are acknowledged as Ignored. +const vHandledEventType = v.object({ + type: v.picklist( + vEmailEvent.options.map(option => option.entries.type.literal) + ), +}); + +function applyResendEvent( + ctx: ReducerModuleCtx, + eventId: string, + payloadJson: string +): { status: WebhookEventStatusValue; error: string | undefined } { + const parsed = safeJsonParse(payloadJson); + if (parsed === undefined) { + return { status: WebhookEventStatus.Failed, error: 'invalid JSON payload' }; + } + + const result = v.safeParse(vEmailEvent, parsed); + if (!result.success) { + if (!v.is(vHandledEventType, parsed)) { + return { status: WebhookEventStatus.Ignored, error: undefined }; + } + return { + status: WebhookEventStatus.Failed, + error: `payload validation failed: ${summarizeIssues(result.issues)}`, + }; + } + + const event = result.output; + const now = ctx.timestamp; + const eventMillis = Date.parse(event.created_at); + if (!Number.isFinite(eventMillis)) { + return { + status: WebhookEventStatus.Failed, + error: 'invalid event timestamp', + }; + } + const eventTime = new Timestamp(BigInt(eventMillis) * 1000n); + upsertEmail(ctx, now, { + ...makeEmailUpsertArgs(event, eventTime), + statusUpdatedAt: eventTime, + }); + recordDeliveryEvent(ctx, now, { + eventId, + resendId: event.data.email_id, + eventType: event.type, + createdAtIso: event.created_at, + detailJson: detailJsonForEvent(event), + }); + return { status: WebhookEventStatus.Processed, error: undefined }; +} + +export interface ResendWebhookIngestArgs { + eventId: string; + eventType: string; + payloadJson: string; + signatureHeader?: string | undefined; + timestampHeader?: string | undefined; +} + +const MAX_WEBHOOK_BODY_LENGTH = 1024 * 1024; +const MAX_WEBHOOK_HEADER_LENGTH = 8192; +const MAX_WEBHOOK_METADATA_LENGTH = 255; + +type WebhookRejection = { status: number; code: string }; + +// The reducer and HTTP route verify, store, and apply events in one transaction. +// Returns a rejection when the request is refused before anything is written, +// otherwise the stored event status. +function applyResendWebhook( + ctx: WriteCtx, + args: Omit +): WebhookRejection | WebhookEventStatusValue { + if ( + args.eventId.length === 0 || + args.eventId.length > MAX_WEBHOOK_METADATA_LENGTH + ) { + return { status: 400, code: errors.webhookMetadataInvalid }; + } + if (args.payloadJson.length > MAX_WEBHOOK_BODY_LENGTH) { + return { status: 413, code: errors.webhookPayloadTooLarge }; + } + if ( + (args.signatureHeader?.length ?? 0) > MAX_WEBHOOK_HEADER_LENGTH || + (args.timestampHeader?.length ?? 0) > MAX_WEBHOOK_HEADER_LENGTH + ) { + return { status: 400, code: errors.webhookHeaderTooLarge }; + } + + const cfg = ctx.db.resendConfig.singleton.find(true); + if (!cfg?.webhookSigningSecret) { + return { status: 500, code: errors.webhookSecretNotConfigured }; + } + const nowSeconds = Number(ctx.timestamp.microsSinceUnixEpoch / 1_000_000n); + const signature = verifySvixSignature({ + svixId: args.eventId, + svixTimestamp: args.timestampHeader ?? '', + svixSignature: args.signatureHeader ?? '', + rawBody: args.payloadJson, + secret: cfg.webhookSigningSecret, + nowSeconds, + }); + if (!signature.ok) { + return { + status: 401, + code: `${errors.webhookSignatureMismatch}:${signature.reason}`, + }; + } + + const signedEventType = parseResendEventType(args.payloadJson); + if ( + !signedEventType || + signedEventType.length > MAX_WEBHOOK_METADATA_LENGTH + ) { + return { status: 400, code: errors.webhookPayloadInvalid }; + } + + const existing = ctx.db.resendWebhookEvent.eventId.find(args.eventId); + if ( + existing?.status.tag === 'Processed' || + existing?.status.tag === 'Ignored' + ) { + return existing.status; + } + + if (!existing) + ctx.db.resendWebhookEvent.insert({ + eventId: args.eventId, + eventType: signedEventType, + payloadJson: args.payloadJson, + signatureHeader: args.signatureHeader, + timestampHeader: args.timestampHeader, + status: WebhookEventStatus.Received, + errorMessage: undefined, + receivedAt: ctx.timestamp, + processedAt: undefined, + }); + + const outcome = applyResendEvent( + ctx as ReducerModuleCtx, + args.eventId, + existing?.payloadJson ?? args.payloadJson + ); + updateWebhookStatus( + ctx as ReducerModuleCtx, + args.eventId, + outcome.status, + outcome.error + ); + return outcome.status; +} + +export const ingestResendWebhook = spacetimedb.reducer( + { + eventId: t.string(), + eventType: t.string(), + payloadJson: t.string(), + signatureHeader: t.option(t.string()), + timestampHeader: t.option(t.string()), + }, + (ctx, { eventType, ...args }) => { + if (eventType !== parseResendEventType(args.payloadJson)) { + throwSenderError(errors.webhookMetadataMismatch); + } + // A Failed event row commits so it can be read and replayed. + const result = applyResendWebhook(ctx, args); + if ('code' in result) throwSenderError(result.code); + } +); + +function webhookJson(body: unknown, status: number): SyncResponse { + return new SyncResponse(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' }, + }); +} + +// Native SpacetimeDB HTTP route handler. Host modules register it on a router so +// Resend can post directly to the database. +export function makeResendWebhookHandler() { + // The host passes the submodule-scoped context, so this handler remains schema-agnostic. + return function resendWebhook( + ctx: HandlerContext, + req: Request + ): SyncResponse { + if (req.method.toUpperCase() !== 'POST') { + return webhookJson( + { ok: false, code: errors.webhookMethodNotAllowed }, + 405 + ); + } + + const args = { + eventId: req.headers.get('svix-id') ?? '', + payloadJson: req.text(), + signatureHeader: req.headers.get('svix-signature') ?? undefined, + timestampHeader: req.headers.get('svix-timestamp') ?? undefined, + }; + const result = ctx.withTx(tx => applyResendWebhook(tx as WriteCtx, args)); + if ('code' in result) + return webhookJson({ ok: false, code: result.code }, result.status); + return result.tag === 'Failed' + ? webhookJson({ ok: false, code: errors.webhookPayloadInvalid }, 400) + : webhookJson({ ok: true, code: 'ok' }, 200); + }; +} + +export const replayWebhookEvent = spacetimedb.reducer( + { eventId: t.string() }, + (ctx, { eventId }) => { + // Administrators may run this operation over stored events. + requireAdmin(ctx, ctx.sender); + const event = ctx.db.resendWebhookEvent.eventId.find(eventId); + if (!event) throwSenderError(`${errors.webhookEventNotFound}:${eventId}`); + const outcome = applyResendEvent(ctx, eventId, event.payloadJson); + updateWebhookStatus(ctx, eventId, outcome.status, outcome.error); + } +); diff --git a/spacetime-resend-ts/tsconfig.build.json b/spacetime-resend-ts/tsconfig.build.json new file mode 100644 index 00000000000..8635027968f --- /dev/null +++ b/spacetime-resend-ts/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/spacetime-resend-ts/tsconfig.json b/spacetime-resend-ts/tsconfig.json new file mode 100644 index 00000000000..d4766a1709a --- /dev/null +++ b/spacetime-resend-ts/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "declaration": false, + "emitDeclarationOnly": false, + "noEmit": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "noImplicitAny": true, + "moduleResolution": "Bundler", + "isolatedDeclarations": false, + "esModuleInterop": false, + "allowSyntheticDefaultImports": false, + "useDefineForClassFields": true, + "isolatedModules": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"], + "exclude": ["node_modules", "dist/**/*"] +} diff --git a/spacetime-retry-ts/.npmrc b/spacetime-retry-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-retry-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-retry-ts/LICENSE.txt b/spacetime-retry-ts/LICENSE.txt new file mode 120000 index 00000000000..cc1ff9bdd72 --- /dev/null +++ b/spacetime-retry-ts/LICENSE.txt @@ -0,0 +1 @@ +../licenses/apache2.txt \ No newline at end of file diff --git a/spacetime-retry-ts/README.md b/spacetime-retry-ts/README.md new file mode 100644 index 00000000000..67594f5f858 --- /dev/null +++ b/spacetime-retry-ts/README.md @@ -0,0 +1,135 @@ +# @spacetimedb/retry + +Retry failed background tasks in your SpacetimeDB application. Pass arguments +to a task, set an attempt limit, and choose how long to wait between attempts. +Each retry waits longer than the last, and administrators can inspect pending +tasks and past attempts. + +## Install + +```bash +npm install @spacetimedb/retry spacetimedb +``` + +`spacetimedb` is a peer dependency. Keep its version aligned with the SDK used +to build the host module. + +## Integrate into an application + +Define the task's arguments, add Retry's tables to your module, then register +the function that does the work. In this example, replace `sendReceipt` with +your application's function. It must be safe to run more than once for the +same order. + +```ts +import { schema, t } from 'spacetimedb/server'; +import { client, retryFailed, retryOk } from '@spacetimedb/retry'; + +const retry = client({ + tasks: { + sendReceipt: t.object('SendReceiptArgs', { orderId: t.u64() }), + }, +}); + +const db = schema({ ...retry.tables }); +export default db; + +export const init = db.init(ctx => retry.install(ctx)); + +export const retryFire = retry.retryReducer(db, { + sendReceipt(ctx, { orderId }) { + const result = sendReceipt(ctx, orderId); + return result.sent ? retryOk() : retryFailed(result.error); + }, +}); + +export const submitRetryTask = db.reducer( + retry.reducers.submitRetryTask.params, + retry.reducers.submitRetryTask.handler +); +``` + +`retryReducer` requires a handler for every task. Registration fails to +compile if the schema does not include `retry.tables`. + +Submit tagged arguments with an attempt cap and base backoff. The first attempt +is scheduled immediately; subsequent delays are `backoffSecs * 2^attempt`. + +Handlers must be idempotent. A returned failure or a thrown exception records a +failed attempt and schedules the next attempt, up to `maxAttempts`. A thrown +`SenderError` marks the task's arguments as invalid: Retry records the attempt +as `GaveUp` with the error message and schedules nothing further. Writes made +by the handler before a failure are committed with that attempt; Retry does not +provide a separate transaction for the handler. A host crash or transaction +abort can still prevent the retry from being scheduled. + +History retains the latest 1,000 attempts across all tasks. The admin history +view returns these attempts newest first. + +## API + +- `client({ tasks })` returns `tables`, `retryReducer`, `install`, `submit`, + `requireAdmin`, `views`, and `reducers`. +- `retryReducer(schema, handlers)` registers the scheduled reducer that runs + attempts. Export its result. Each handler returns `retryOk()` or + `retryFailed(error)`. +- `install(ctx)` seeds the publishing identity as the initial admin. Call it + from the host's `init` reducer. +- `submit(ctx, task)` validates a task and schedules its first attempt without + an authorization check. Call it from host reducers that authorize the caller. +- `reducers.submitRetryTask`, `reducers.addRetryAdminIdentity`, and + `reducers.removeRetryAdminIdentity` require a Retry admin. +- `views.retryTasksAdmin` and `views.retryHistoryAdmin` return up to 1,000 + pending tasks and attempts, newest first, to Retry admins. +- `errors` holds the `retry.*` codes these operations throw as `SenderError`s: + `notAuthorized`, `invalidTaskName`, `invalidMaxAttempts`, + `invalidBackoffSeconds`, `taskAlreadyExists` (followed by `:` and the task + name), and `cannotRemoveLastAdmin`. + +The generated client can submit a task when the host exports +`submitRetryTask`: + +```ts +await conn.reducers.submitRetryTask({ + name: `receipt:${orderId}`, + args: { tag: 'SendReceipt', value: { orderId } }, + maxAttempts: 5, + backoffSecs: 2, +}); +``` + +For user-facing operations, check permissions and set retry limits in a host +reducer: + +```ts +export const requestReceipt = db.reducer( + { orderId: t.u64() }, + (ctx, { orderId }) => { + requireOrderOwner(ctx, orderId); + retry.submit(ctx, { + name: `receipt:${orderId}`, + args: { tag: 'sendReceipt', value: { orderId } }, + maxAttempts: 5, + backoffSecs: 2, + }); + } +); +``` + +Package entrypoints: + +- `@spacetimedb/retry` exports `client`, `errors`, `retryOk`, `retryFailed`, + and the related types. +- `@spacetimedb/retry/submodule` exports `client` and `errors`. + +## Testing + +```bash +pnpm test +pnpm run lint +pnpm --dir spacetimedb run build +``` + +## License + +Apache-2.0. See [`LICENSE.txt`](./LICENSE.txt). diff --git a/spacetime-retry-ts/package.json b/spacetime-retry-ts/package.json new file mode 100644 index 00000000000..eaa4877143d --- /dev/null +++ b/spacetime-retry-ts/package.json @@ -0,0 +1,75 @@ +{ + "name": "@spacetimedb/retry", + "description": "Typed retry dispatch, exponential backoff, and attempt history for SpacetimeDB TypeScript modules.", + "version": "0.1.0", + "license": "Apache-2.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./submodule": { + "types": "./src/submodule.ts", + "default": "./src/submodule.ts" + } + }, + "files": [ + "dist", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./submodule": { + "types": "./dist/submodule.d.ts", + "default": "./dist/submodule.js" + } + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/clockworklabs/SpacetimeDB.git", + "directory": "spacetime-retry-ts" + }, + "homepage": "https://github.com/clockworklabs/SpacetimeDB/tree/master/spacetime-retry-ts#readme", + "bugs": { + "url": "https://github.com/clockworklabs/SpacetimeDB/issues" + }, + "keywords": [ + "spacetimedb", + "retry", + "backoff", + "typescript" + ], + "scripts": { + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "node --js-explicit-resource-management --import tsx --import ./scripts/sys-abi-test-register.mjs scripts/test.ts", + "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json", + "prepack": "pnpm run build && node -e \"require('node:fs').copyFileSync('../licenses/apache2.txt', 'LICENSE')\"", + "postpack": "node -e \"require('node:fs').unlinkSync('LICENSE')\"" + }, + "peerDependencies": { + "spacetimedb": "workspace:^" + }, + "devDependencies": { + "eslint": "^9.17.0", + "prettier": "^3.3.3", + "@types/node": "^22.10.2", + "spacetimedb": "workspace:*", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-retry-ts/scripts/sys-abi-test-register.mjs b/spacetime-retry-ts/scripts/sys-abi-test-register.mjs new file mode 100644 index 00000000000..30107456e71 --- /dev/null +++ b/spacetime-retry-ts/scripts/sys-abi-test-register.mjs @@ -0,0 +1,27 @@ +import { register } from 'node:module'; + +// Host syscall modules exist only inside SpacetimeDB. Stub the bindings that +// `spacetimedb/server` reads while loading. +const stubs = { + 'spacetime:sys@2.0': + 'export const moduleHooks = Symbol(); export function row_iter_bsatn_close() {}', + 'spacetime:sys@2.1': 'export {};', + 'spacetime:sys@2.2': 'export function env_get() {}', +}; + +const loaderSource = ` + const stubs = ${JSON.stringify(stubs)}; + export function resolve(specifier, context, nextResolve) { + return specifier in stubs + ? { + shortCircuit: true, + url: 'data:text/javascript,' + encodeURIComponent(stubs[specifier]), + } + : nextResolve(specifier, context); + } +`; + +register( + `data:text/javascript,${encodeURIComponent(loaderSource)}`, + import.meta.url +); diff --git a/spacetime-retry-ts/scripts/test.ts b/spacetime-retry-ts/scripts/test.ts new file mode 100644 index 00000000000..ba5a6fb1276 --- /dev/null +++ b/spacetime-retry-ts/scripts/test.ts @@ -0,0 +1,240 @@ +import * as assert from 'node:assert/strict'; +import { Identity, Timestamp } from 'spacetimedb'; +import { ScheduleAt, schema, SenderError, t } from 'spacetimedb/server'; +import { + client, + errors, + retryFailed, + retryOk, + type RetryCtx, + type RetryTaskRow as Task, +} from '../src'; + +const calls: string[] = []; +// One argument type may back several tasks. +const sharedArgs = t.object('TestArgs', { value: t.string() }); +const retry = client({ + tasks: { + throws: t.unit(), + rejects: t.unit(), + fails: t.unit(), + succeeds: t.unit(), + first: sharedArgs, + second: sharedArgs, + }, +}); +const retryFire = retry.retryReducer(schema({ ...retry.tables }), { + throws() { + throw new Error('x'.repeat(3000)); + }, + rejects() { + throw new SenderError('order.not_found'); + }, + fails: () => retryFailed('unavailable'), + succeeds: () => retryOk(), + first(_ctx, args) { + calls.push(`first:${args.value}`); + return retryOk(); + }, + second(_ctx, args) { + calls.push(`second:${args.value}`); + return retryOk(); + }, +}); +// The mock context implements only the retry tables, not a full reducer +// context. +const fire = (arg: Task) => { + txInserted.clear(); + retryFire(ctx as never, { arg }); + txInserted.clear(); +}; + +type History = ReturnType[number]; + +const admin = Identity.zero(); +const stranger = new Identity(1n); +const admins = new Map(); +const history = new Map(); +const tasks = new Map(); +let nextHistoryId = 0n; +let nextTaskId = 0n; +let sender = admin; +let now = 10_000_000n; + +// History rows inserted by the current attempt. Like the datastore, an index +// scan yields them before committed rows. +const txInserted = new Set(); +const byRanAt = () => { + const sorted = [...history.values()].sort((a, b) => + a.ranAt.microsSinceUnixEpoch === b.ranAt.microsSinceUnixEpoch + ? Number(a.id - b.id) + : Number(a.ranAt.microsSinceUnixEpoch - b.ranAt.microsSinceUnixEpoch) + ); + return [ + ...sorted.filter(row => txInserted.has(row.id)), + ...sorted.filter(row => !txInserted.has(row.id)), + ].values(); +}; + +const ctx: RetryCtx = { + get sender() { + return sender; + }, + get timestamp() { + return new Timestamp(now); + }, + db: { + retryTask: { + name: { + filter: (name: string) => + [...tasks.values()].filter(row => row.name === name).values(), + }, + iter: () => tasks.values(), + insert(row: Task) { + const inserted = { ...row, scheduledId: ++nextTaskId }; + tasks.set(inserted.scheduledId, inserted); + return inserted; + }, + }, + retryHistory: { + ranAt: { filter: byRanAt }, + insert(row: History) { + const inserted = { ...row, id: ++nextHistoryId }; + history.set(inserted.id, inserted); + txInserted.add(inserted.id); + return inserted; + }, + delete: (row: History) => history.delete(row.id), + count: () => BigInt(history.size), + }, + retryAdminIdentity: { + identity: { + find: (identity: Identity) => + admins.get(identity.toHexString()) ?? null, + }, + insert(row: { identity: Identity; addedAt: Timestamp }) { + admins.set(row.identity.toHexString(), row); + return row; + }, + delete: (row: { identity: Identity }) => + admins.delete(row.identity.toHexString()), + count: () => BigInt(admins.size), + }, + }, +}; + +retry.install(ctx); +assert.equal( + admins.get(admin.toHexString())?.addedAt.microsSinceUnixEpoch, + now +); + +// Submission validates input and requires an admin. +const submit = retry.reducers.submitRetryTask.handler; +const valid = { + name: 'job', + args: { tag: 'first', value: { value: 'payload' } }, + maxAttempts: 3, + backoffSecs: 2, +}; +assert.throws(() => submit(ctx, { ...valid, name: '' }), { + message: errors.invalidTaskName, +}); +assert.throws(() => submit(ctx, { ...valid, maxAttempts: 11 }), { + message: errors.invalidMaxAttempts, +}); +assert.throws(() => submit(ctx, { ...valid, backoffSecs: 0 }), { + message: errors.invalidBackoffSeconds, +}); +submit(ctx, valid); +assert.throws(() => submit(ctx, valid), { + message: `${errors.taskAlreadyExists}:job`, +}); +sender = stranger; +assert.throws(() => submit(ctx, { ...valid, name: 'other' }), { + message: errors.notAuthorized, +}); +assert.deepEqual(retry.views.retryTasksAdmin(ctx), []); + +// Handlers sharing one argument builder dispatch independently. `submit` +// skips the admin check for host reducers that authorize callers themselves. +sender = stranger; +retry.submit(ctx, { + name: 'job2', + args: { tag: 'second', value: { value: 'b' } }, + maxAttempts: 1, + backoffSecs: 1, +}); +sender = admin; +fire(tasks.get(1n)!); +fire(tasks.get(2n)!); +assert.deepEqual(calls, ['first:payload', 'second:b']); + +// Failures back off exponentially, then give up. +tasks.clear(); +const task: Task = { + scheduledId: 0n, + scheduledAt: ScheduleAt.time(0n), + name: 'test', + args: { tag: 'throws' }, + attempt: 0, + maxAttempts: 3, + backoffSecs: 2, +}; +history.clear(); +nextHistoryId = 0n; +fire(task); +assert.equal(history.get(1n)?.status.tag, 'Failed'); +assert.equal(history.get(1n)?.error?.length, 2048); +const [second] = tasks.values(); +assert.equal(second.attempt, 1); +assert.deepEqual(second.scheduledAt, ScheduleAt.time(now + 2_000_000n)); +fire(second); +const third = [...tasks.values()][1]; +assert.equal(third.attempt, 2); +assert.deepEqual(third.scheduledAt, ScheduleAt.time(now + 4_000_000n)); +fire(third); +assert.equal(history.get(3n)?.status.tag, 'GaveUp'); +assert.equal(tasks.size, 2); + +fire({ ...task, args: { tag: 'fails' } }); +assert.equal(history.get(4n)?.error, 'unavailable'); +fire({ ...task, args: { tag: 'toString' } }); +assert.equal(history.get(5n)?.error, 'retry.unknown_handler:toString'); +assert.equal(tasks.size, 4); + +// A SenderError gives up on the first attempt without scheduling another. +fire({ ...task, args: { tag: 'rejects' } }); +assert.equal(history.get(6n)?.status.tag, 'GaveUp'); +assert.equal(history.get(6n)?.error, 'order.not_found'); +assert.equal(tasks.size, 4); + +// The newest pending tasks come first. +assert.deepEqual( + retry.views.retryTasksAdmin(ctx).map(row => row.scheduledId), + [...tasks.keys()].reverse() +); + +// History keeps the latest 1,000 attempts. +for (let i = 0; i < 1000; i++) { + now += 1n; + fire({ ...task, args: { tag: 'succeeds' } }); +} +assert.equal(tasks.size, 4); +assert.equal(history.size, 1000); +assert.equal(history.has(6n), false); +assert.equal(history.has(7n), true); +const recent = retry.views.retryHistoryAdmin(ctx); +assert.equal(recent.length, 1000); +assert.equal(recent[0].id, nextHistoryId); +assert.equal(recent[0].status.tag, 'Ok'); +assert.equal(recent.at(-1)?.id, nextHistoryId - 999n); + +// The last admin cannot be removed. +assert.throws( + () => + retry.reducers.removeRetryAdminIdentity.handler(ctx, { identity: admin }), + { message: errors.cannotRemoveLastAdmin } +); + +process.stdout.write('retry tests passed\n'); diff --git a/spacetime-retry-ts/spacetimedb/.npmrc b/spacetime-retry-ts/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-retry-ts/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-retry-ts/spacetimedb/package.json b/spacetime-retry-ts/spacetimedb/package.json new file mode 100644 index 00000000000..2538269257d --- /dev/null +++ b/spacetime-retry-ts/spacetimedb/package.json @@ -0,0 +1,19 @@ +{ + "name": "spacetime-retry-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-retry", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-retry" + }, + "dependencies": { + "@spacetimedb/retry": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-retry-ts/spacetimedb/src/index.ts b/spacetime-retry-ts/spacetimedb/src/index.ts new file mode 100644 index 00000000000..ae153b03c3d --- /dev/null +++ b/spacetime-retry-ts/spacetimedb/src/index.ts @@ -0,0 +1,81 @@ +import { schema, table, t } from 'spacetimedb/server'; +import { client, retryFailed, retryOk } from '@spacetimedb/retry'; + +const retry = client({ + tasks: { + flaky: t.object('FlakyArgs', { + taskName: t.string(), + succeedAtAttempt: t.u8(), + throwOnFailure: t.bool(), + }), + }, +}); +const { retryTask, retryHistory, retryAdminIdentity } = retry.tables; + +const retryMetric = table( + { name: 'retry_metric', public: true }, + { + id: t.u64().primaryKey().autoInc(), + name: t.string(), + value: t.f64(), + recordedAt: t.timestamp(), + } +); + +const spacetimedb = schema({ + retryTask, + retryHistory, + retryAdminIdentity, + retryMetric, +}); +export default spacetimedb; + +export const retryTasksAdmin = spacetimedb.view( + { name: 'retry_tasks_admin', public: true }, + t.array(retryTask.rowType), + retry.views.retryTasksAdmin +); + +export const retryHistoryAdmin = spacetimedb.view( + { name: 'retry_history_admin', public: true }, + t.array(retryHistory.rowType), + retry.views.retryHistoryAdmin +); + +export const init = spacetimedb.init(ctx => { + retry.install(ctx); +}); + +export const retryFire = retry.retryReducer(spacetimedb, { + flaky(ctx, args) { + const task = ctx.db.retryTask.name.filter(args.taskName).next().value; + const attempt = task?.attempt ?? 0; + if (attempt < args.succeedAtAttempt) { + const message = `simulated failure at attempt ${attempt}`; + if (args.throwOnFailure) throw new Error(message); + return retryFailed(message); + } + ctx.db.retryMetric.insert({ + id: 0n, + name: `flaky-success-${args.taskName}`, + value: attempt, + recordedAt: ctx.timestamp, + }); + return retryOk(); + }, +}); + +export const submitRetryTask = spacetimedb.reducer( + retry.reducers.submitRetryTask.params, + retry.reducers.submitRetryTask.handler +); + +export const addRetryAdminIdentity = spacetimedb.reducer( + retry.reducers.addRetryAdminIdentity.params, + retry.reducers.addRetryAdminIdentity.handler +); + +export const removeRetryAdminIdentity = spacetimedb.reducer( + retry.reducers.removeRetryAdminIdentity.params, + retry.reducers.removeRetryAdminIdentity.handler +); diff --git a/spacetime-retry-ts/spacetimedb/tsconfig.json b/spacetime-retry-ts/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..8d8f9b03455 --- /dev/null +++ b/spacetime-retry-ts/spacetimedb/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src"] +} diff --git a/spacetime-retry-ts/src/handler.ts b/spacetime-retry-ts/src/handler.ts new file mode 100644 index 00000000000..fcf089b4bd6 --- /dev/null +++ b/spacetime-retry-ts/src/handler.ts @@ -0,0 +1,7 @@ +export type RetryResult = { ok: true } | { ok: false; error: string }; + +export const retryOk = (): RetryResult => ({ ok: true }); +export const retryFailed = (error: string): RetryResult => ({ + ok: false, + error, +}); diff --git a/spacetime-retry-ts/src/index.ts b/spacetime-retry-ts/src/index.ts new file mode 100644 index 00000000000..5826d778abd --- /dev/null +++ b/spacetime-retry-ts/src/index.ts @@ -0,0 +1,15 @@ +export { retryFailed, retryOk, type RetryResult } from './handler.js'; +export { + client, + errors, + type RetryArgs, + type RetryConfig, + type RetryCtx, + type RetryHandlers, + type RetryHistoryRow, + type RetryReducerExport, + type RetrySchema, + type RetryTaskRow, + type RetryTasks, + type RetryViewCtx, +} from './submodule.js'; diff --git a/spacetime-retry-ts/src/submodule.ts b/spacetime-retry-ts/src/submodule.ts new file mode 100644 index 00000000000..1a77e6a89f2 --- /dev/null +++ b/spacetime-retry-ts/src/submodule.ts @@ -0,0 +1,350 @@ +import { + Range, + ScheduleAt, + SenderError, + t, + table, + type Infer, + type ModuleExport, + type SumBuilder, + type VariantsObj, +} from 'spacetimedb/server'; +import type { Identity, Timestamp } from 'spacetimedb'; +import { retryFailed, type RetryResult } from './handler.js'; + +const ONE_SECOND_MICROS = 1_000_000n; +const MAX_ATTEMPTS = 10; +const MAX_BACKOFF_SECONDS = 3600; +const MAX_TASK_NAME_LENGTH = 128; +const MAX_ERROR_LENGTH = 2048; +const MAX_ROWS = 1000; + +/** Codes a caller can receive as a `SenderError`. */ +export const errors = { + notAuthorized: 'retry.not_authorized', + invalidTaskName: 'retry.invalid_task_name', + invalidMaxAttempts: 'retry.invalid_max_attempts', + invalidBackoffSeconds: 'retry.invalid_backoff_seconds', + taskAlreadyExists: 'retry.task_already_exists', + cannotRemoveLastAdmin: 'retry.cannot_remove_last_admin', +} as const; + +function retryTaskTable(args: SumBuilder) { + return table( + { name: 'retry_task', public: false }, + { + scheduledId: t.u64().primaryKey().autoInc(), + scheduledAt: t.scheduleAt(), + name: t.string().index(), + args, + attempt: t.u8(), + maxAttempts: t.u8(), + backoffSecs: t.u32(), + } + ); +} + +const retryHistory = table( + { name: 'retry_history', public: false }, + { + id: t.u64().primaryKey().autoInc(), + taskName: t.string(), + attempt: t.u8(), + status: t.enum('RetryHistoryStatus', ['Ok', 'Failed', 'GaveUp']), + error: t.option(t.string()), + ranAt: t.timestamp().index(), + } +); + +const retryAdminIdentity = table( + { name: 'retry_admin_identity', public: false }, + { + identity: t.identity().primaryKey(), + addedAt: t.timestamp(), + } +); + +export type RetryTaskRow = Infer['rowType']>; +export type RetryHistoryRow = Infer; +type AdminRow = Infer; +type TaskInput = Pick< + RetryTaskRow, + 'name' | 'args' | 'maxAttempts' | 'backoffSecs' +>; + +/** The retry tables of a host view context. */ +export interface RetryViewCtx { + readonly sender: Identity; + readonly db: { + readonly retryTask: { iter(): Iterable }; + readonly retryHistory: { + readonly ranAt: { + filter(range: Range): Iterable; + }; + }; + readonly retryAdminIdentity: { + readonly identity: { find(identity: Identity): AdminRow | null }; + }; + }; +} + +/** A host reducer context whose schema includes `retry.tables`. */ +export interface RetryCtx { + readonly sender: Identity; + readonly timestamp: Timestamp; + readonly db: { + readonly retryTask: { + iter(): Iterable; + readonly name: { + filter(name: string): IteratorObject; + }; + insert(row: RetryTaskRow): RetryTaskRow; + }; + readonly retryHistory: { + readonly ranAt: { + filter( + range: Range + ): IteratorObject; + }; + insert(row: RetryHistoryRow): RetryHistoryRow; + delete(row: RetryHistoryRow): boolean; + count(): bigint; + }; + readonly retryAdminIdentity: { + readonly identity: { find(identity: Identity): AdminRow | null }; + insert(row: AdminRow): AdminRow; + delete(row: AdminRow): boolean; + count(): bigint; + }; + }; +} + +/** Task argument types keyed by task tag. */ +export type RetryTasks = VariantsObj; + +export interface RetryConfig { + tasks: Tasks; +} + +/** Tagged task arguments for the configured tasks. */ +export type RetryArgs = { + [K in keyof Tasks & string]: Tasks[K] extends ReturnType + ? { tag: K } + : { tag: K; value: Infer }; +}[keyof Tasks & string]; + +/** One handler per task tag. Each call runs one attempt. */ +export type RetryHandlers = { + [K in keyof Tasks & string]: (ctx: Tx, args: Infer) => RetryResult; +}; + +/** The scheduled reducer that runs attempts. */ +export type RetryReducerExport = ModuleExport & + ((ctx: Tx, args: { arg: RetryTaskRow }) => unknown); + +/** + * The host schema returned by `schema()`. Handler contexts are inferred from + * its reducer exports. + */ +export interface RetrySchema { + reducer(...args: unknown[]): RetryReducerExport; +} + +type InternalHandler = (...args: unknown[]) => RetryResult; + +/** Create the retry tables and the functions that manage them. */ +export function client({ + tasks, +}: RetryConfig) { + const variants: VariantsObj = tasks; + const retryArgs = t.enum('RetryArgs', variants); + const retryTask = retryTaskTable(retryArgs); + + function isAdmin(ctx: RetryViewCtx): boolean { + return ctx.db.retryAdminIdentity.identity.find(ctx.sender) != null; + } + + function requireAdmin(ctx: RetryCtx): void { + if (!isAdmin(ctx)) throw new SenderError(errors.notAuthorized); + } + + function addAdmin(ctx: RetryCtx, identity: Identity): void { + if (ctx.db.retryAdminIdentity.identity.find(identity) == null) { + ctx.db.retryAdminIdentity.insert({ identity, addedAt: ctx.timestamp }); + } + } + + function submitTask(ctx: RetryCtx, task: TaskInput): void { + if (task.name.length === 0 || task.name.length > MAX_TASK_NAME_LENGTH) { + throw new SenderError(errors.invalidTaskName); + } + if ( + !Number.isInteger(task.maxAttempts) || + task.maxAttempts < 1 || + task.maxAttempts > MAX_ATTEMPTS + ) { + throw new SenderError(errors.invalidMaxAttempts); + } + if ( + !Number.isInteger(task.backoffSecs) || + task.backoffSecs < 1 || + task.backoffSecs > MAX_BACKOFF_SECONDS + ) { + throw new SenderError(errors.invalidBackoffSeconds); + } + if (!ctx.db.retryTask.name.filter(task.name).next().done) { + throw new SenderError(`${errors.taskAlreadyExists}:${task.name}`); + } + ctx.db.retryTask.insert({ + ...task, + scheduledId: 0n, + scheduledAt: ScheduleAt.time(ctx.timestamp.microsSinceUnixEpoch), + attempt: 0, + }); + } + + function runAttempt( + handlers: Record, + ctx: RetryCtx, + arg: RetryTaskRow + ): void { + let result: RetryResult; + let permanent = false; + try { + const { tag } = arg.args; + if (!Object.prototype.hasOwnProperty.call(handlers, tag)) { + // Only reachable when handlers bypass `RetryHandlers` typing. + throw new Error(`retry.unknown_handler:${tag}`); + } + result = handlers[tag](ctx, 'value' in arg.args ? arg.args.value : {}); + } catch (error) { + // A caught exception does not roll back the handler's earlier writes. + // A `SenderError` rejects the task's arguments, so retrying cannot help. + permanent = error instanceof SenderError; + result = retryFailed( + error instanceof Error ? error.message : String(error) + ); + } + + const isLast = + !result.ok && (permanent || arg.attempt + 1 >= arg.maxAttempts); + const history = ctx.db.retryHistory; + // Each attempt adds one row, so removing the oldest keeps the bound. Prune + // before inserting: an index scan yields rows inserted in the current + // transaction before committed rows. + if (history.count() >= MAX_ROWS) { + const oldest = history.ranAt.filter(new Range()).next().value; + if (oldest) history.delete(oldest); + } + history.insert({ + id: 0n, + taskName: arg.name, + attempt: arg.attempt, + status: { tag: result.ok ? 'Ok' : isLast ? 'GaveUp' : 'Failed' }, + error: result.ok ? undefined : result.error.slice(0, MAX_ERROR_LENGTH), + ranAt: ctx.timestamp, + }); + if (result.ok || isLast) return; + + const delay = + BigInt(arg.backoffSecs) * (1n << BigInt(arg.attempt)) * ONE_SECOND_MICROS; + ctx.db.retryTask.insert({ + ...arg, + scheduledId: 0n, + scheduledAt: ScheduleAt.time(ctx.timestamp.microsSinceUnixEpoch + delay), + attempt: arg.attempt + 1, + }); + } + + /** + * Register the scheduled reducer that runs attempts. Call after `schema()` + * and export the result. + */ + function retryReducer( + spacetimedb: RetrySchema, + handlers: RetryHandlers + ): RetryReducerExport { + // Each stored task pairs a tag with a value of that tag's argument type, + // so the handler for the tag accepts the value. + const byTag = handlers as Record; + return spacetimedb.reducer( + { onSchedule: retryTask }, + { arg: retryTask.rowType }, + (ctx: Tx, { arg }: { arg: RetryTaskRow }) => { + runAttempt(byTag, ctx, arg); + } + ); + } + + return { + tables: { retryTask, retryHistory, retryAdminIdentity }, + retryReducer, + /** Call from the host's init reducer to seed the publishing identity as admin. */ + install(ctx: RetryCtx): void { + addAdmin(ctx, ctx.sender); + }, + /** Validate and schedule a task's first attempt. The caller authorizes. */ + submit( + ctx: RetryCtx, + task: Omit & { args: RetryArgs } + ): void { + submitTask(ctx, task); + }, + requireAdmin, + views: { + /** The latest pending tasks, newest first. */ + retryTasksAdmin(ctx: RetryViewCtx): RetryTaskRow[] { + if (!isAdmin(ctx)) return []; + return [...ctx.db.retryTask.iter()] + .sort((a, b) => + a.scheduledId > b.scheduledId + ? -1 + : a.scheduledId < b.scheduledId + ? 1 + : 0 + ) + .slice(0, MAX_ROWS); + }, + /** Retained attempt history, newest first. */ + retryHistoryAdmin(ctx: RetryViewCtx): RetryHistoryRow[] { + if (!isAdmin(ctx)) return []; + return [ + ...ctx.db.retryHistory.ranAt.filter(new Range()), + ].reverse(); + }, + }, + reducers: { + submitRetryTask: { + params: { + name: t.string(), + args: retryArgs, + maxAttempts: t.u8(), + backoffSecs: t.u32(), + }, + handler(ctx: RetryCtx, task: TaskInput): void { + requireAdmin(ctx); + submitTask(ctx, task); + }, + }, + addRetryAdminIdentity: { + params: { identity: t.identity() }, + handler(ctx: RetryCtx, { identity }: { identity: Identity }): void { + requireAdmin(ctx); + addAdmin(ctx, identity); + }, + }, + removeRetryAdminIdentity: { + params: { identity: t.identity() }, + handler(ctx: RetryCtx, { identity }: { identity: Identity }): void { + requireAdmin(ctx); + const existing = ctx.db.retryAdminIdentity.identity.find(identity); + if (!existing) return; + if (ctx.db.retryAdminIdentity.count() <= 1n) { + throw new SenderError(errors.cannotRemoveLastAdmin); + } + ctx.db.retryAdminIdentity.delete(existing); + }, + }, + }, + }; +} diff --git a/spacetime-retry-ts/tsconfig.build.json b/spacetime-retry-ts/tsconfig.build.json new file mode 100644 index 00000000000..8635027968f --- /dev/null +++ b/spacetime-retry-ts/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/spacetime-retry-ts/tsconfig.json b/spacetime-retry-ts/tsconfig.json new file mode 100644 index 00000000000..77da6c09f65 --- /dev/null +++ b/spacetime-retry-ts/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "declaration": false, + "noEmit": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "isolatedModules": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/tools/ci/commands/typescript-submodules/Cargo.toml b/tools/ci/commands/typescript-submodules/Cargo.toml new file mode 100644 index 00000000000..26e94017113 --- /dev/null +++ b/tools/ci/commands/typescript-submodules/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "ci-typescript-submodules" +version = "0.1.0" +edition.workspace = true + +[dependencies] +anyhow.workspace = true +clap.workspace = true +ci-common = { path = "../../common" } diff --git a/tools/ci/commands/typescript-submodules/src/main.rs b/tools/ci/commands/typescript-submodules/src/main.rs new file mode 100644 index 00000000000..a562c3eb543 --- /dev/null +++ b/tools/ci/commands/typescript-submodules/src/main.rs @@ -0,0 +1,22 @@ +use anyhow::Result; +use ci_common::pnpm; +use clap::Parser; + +/// Checks TypeScript submodules and builds their packages and examples. +#[derive(Parser)] +struct Cli {} + +fn main() -> Result<()> { + Cli::parse(); + ci_common::ensure_repo_root()?; + + pnpm(["--dir", "crates/bindings-typescript", "run", "build"]).run()?; + for script in ["lint", "typecheck", "test"] { + pnpm(["-r", "-F", "./spacetime-*-ts/**", "run", script]).run()?; + } + + // The recovery test starts and stops its own server on a free local port. + pnpm(["--dir", "spacetime-cron-ts", "run", "test:recovery"]).run()?; + pnpm(["-r", "-F", "./spacetime-*-ts/**", "run", "build"]).run()?; + Ok(()) +} diff --git a/tools/ci/src/main.rs b/tools/ci/src/main.rs index 422af76d4a1..c78376fd786 100644 --- a/tools/ci/src/main.rs +++ b/tools/ci/src/main.rs @@ -64,6 +64,10 @@ const COMMANDS: &[Command] = &[ path: &["typescript-test"], package: "ci-typescript-test", }, + Command { + path: &["typescript-submodules"], + package: "ci-typescript-submodules", + }, Command { path: &["version-upgrade-check"], package: "ci-version-upgrade-check",