convex-rust 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +137 -2
  3. package/dist/cli/bin.d.ts +2 -0
  4. package/dist/cli/bin.js +200 -0
  5. package/dist/cli/build.d.ts +146 -0
  6. package/dist/cli/build.js +902 -0
  7. package/dist/cli/demangle.d.ts +7 -0
  8. package/dist/cli/demangle.js +328 -0
  9. package/dist/cli/diagnostics.d.ts +34 -0
  10. package/dist/cli/diagnostics.js +296 -0
  11. package/dist/cli/generate.d.ts +29 -0
  12. package/dist/cli/generate.js +82 -0
  13. package/dist/cli/manifest.d.ts +24 -0
  14. package/dist/cli/manifest.js +75 -0
  15. package/dist/cli/rustApi.d.ts +78 -0
  16. package/dist/cli/rustApi.js +609 -0
  17. package/dist/cli/scaffold.d.ts +22 -0
  18. package/dist/cli/scaffold.js +114 -0
  19. package/dist/cli/shim.d.ts +30 -0
  20. package/dist/cli/shim.js +140 -0
  21. package/dist/cli/size.d.ts +17 -0
  22. package/dist/cli/size.js +73 -0
  23. package/dist/cli/split.d.ts +20 -0
  24. package/dist/cli/split.js +140 -0
  25. package/dist/cli/symbols.d.ts +30 -0
  26. package/dist/cli/symbols.js +133 -0
  27. package/dist/cli/toolchain.d.ts +53 -0
  28. package/dist/cli/toolchain.js +167 -0
  29. package/dist/cli/validators.d.ts +6 -0
  30. package/dist/cli/validators.js +66 -0
  31. package/dist/cli/wasisdk.d.ts +82 -0
  32. package/dist/cli/wasisdk.js +220 -0
  33. package/dist/cli/wasmHints.d.ts +29 -0
  34. package/dist/cli/wasmHints.js +172 -0
  35. package/dist/runtime/base64.d.ts +4 -0
  36. package/dist/runtime/base64.js +77 -0
  37. package/dist/runtime/crypto.d.ts +7 -0
  38. package/dist/runtime/crypto.js +421 -0
  39. package/dist/runtime/fastjson.d.ts +3 -0
  40. package/dist/runtime/fastjson.js +170 -0
  41. package/dist/runtime/host.d.ts +73 -0
  42. package/dist/runtime/host.js +1230 -0
  43. package/dist/runtime/http.d.ts +40 -0
  44. package/dist/runtime/http.js +157 -0
  45. package/dist/runtime/index.d.ts +2 -0
  46. package/dist/runtime/index.js +1 -0
  47. package/dist/runtime/intl.d.ts +5 -0
  48. package/dist/runtime/intl.js +69 -0
  49. package/dist/runtime/tmpfs.d.ts +129 -0
  50. package/dist/runtime/tmpfs.js +624 -0
  51. package/dist/runtime/wasi.d.ts +33 -0
  52. package/dist/runtime/wasi.js +216 -0
  53. package/package.json +57 -4
  54. package/rust/convex_fn/Cargo.toml +32 -0
  55. package/rust/convex_fn/LICENSE +201 -0
  56. package/rust/convex_fn/build.rs +3 -0
  57. package/rust/convex_fn/src/args.rs +416 -0
  58. package/rust/convex_fn/src/crypto.rs +237 -0
  59. package/rust/convex_fn/src/ctx.rs +1044 -0
  60. package/rust/convex_fn/src/dns.rs +356 -0
  61. package/rust/convex_fn/src/error.rs +179 -0
  62. package/rust/convex_fn/src/executor.rs +577 -0
  63. package/rust/convex_fn/src/fanout.rs +106 -0
  64. package/rust/convex_fn/src/fs.rs +19 -0
  65. package/rust/convex_fn/src/function_ref.rs +219 -0
  66. package/rust/convex_fn/src/http.rs +441 -0
  67. package/rust/convex_fn/src/intl.rs +75 -0
  68. package/rust/convex_fn/src/lib.rs +242 -0
  69. package/rust/convex_fn/src/logging.rs +222 -0
  70. package/rust/convex_fn/src/native.rs +360 -0
  71. package/rust/convex_fn/src/net.rs +122 -0
  72. package/rust/convex_fn/src/sys.rs +178 -0
  73. package/rust/convex_fn/src/values.rs +121 -0
  74. package/rust/convex_fn/src/wire.rs +579 -0
  75. package/rust/convex_fn_macros/Cargo.toml +13 -0
  76. package/rust/convex_fn_macros/LICENSE +201 -0
  77. package/rust/convex_fn_macros/src/derive.rs +632 -0
  78. package/rust/convex_fn_macros/src/lib.rs +338 -0
  79. package/rust/convex_reqwest/Cargo.toml +69 -0
  80. package/rust/convex_reqwest/LICENSE +201 -0
  81. package/rust/convex_reqwest/src/blocking.rs +287 -0
  82. package/rust/convex_reqwest/src/body.rs +152 -0
  83. package/rust/convex_reqwest/src/client.rs +359 -0
  84. package/rust/convex_reqwest/src/config_types.rs +150 -0
  85. package/rust/convex_reqwest/src/error.rs +241 -0
  86. package/rust/convex_reqwest/src/into_url.rs +57 -0
  87. package/rust/convex_reqwest/src/lib.rs +42 -0
  88. package/rust/convex_reqwest/src/multipart.rs +140 -0
  89. package/rust/convex_reqwest/src/request.rs +358 -0
  90. package/rust/convex_reqwest/src/response.rs +310 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Tomás Domingos
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,138 @@
1
- # Temporary Holding Version
1
+ # convex-rust
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run a `"use rust"` crate on stock Convex (the Convex cloud or any self-hosted backend) with no backend or
4
+ CLI changes. The crate is compiled to `wasm32-wasip1`; `convex-rust build` generates ordinary Convex
5
+ `action` / `internalAction` wrappers that run the wasm inside the default Convex runtime, using WebAssembly
6
+ JSPI to await `fetch`, `ctx.runQuery`, `ctx.runMutation`, timers and storage from Rust.
7
+
8
+ Spec: `contracts/V8HOST.md` (guest ABI: `contracts/ABI.md`, manifest: `contracts/MANIFEST.md`).
9
+
10
+ ## Quickstart
11
+
12
+ In an existing Convex project (`npx convex dev` has been run once, so `convex/_generated` and a deployment exist),
13
+ with [rustup](https://rustup.rs) installed:
14
+
15
+ ```sh
16
+ npm install convex-rust
17
+ npx convex-rust init # scaffolds convex/rust, prints the next steps
18
+ npx convex-rust build # compiles the crate to wasm, writes the TS wrappers
19
+ npx convex dev --once # push (or: npx convex deploy)
20
+ npx convex run rust/example:greet '{"name":"you"}' # => { "text": "Hello, you!" }
21
+ ```
22
+
23
+ Verified (stable 1.99.1) from a packed tarball on a fresh project against a stock local backend (actions, `ctx.run_query` into a
24
+ TS query, and an `#[http_action]` route). Stable Rust is enough (the scaffolded `rust-toolchain.toml` says
25
+ `stable`; set `CONVEX_RUST_CHANNEL=nightly-...` for `init` if you want a pinned one). The `wasm32-wasip1` target
26
+ comes from that file; if toolchain or target is missing `build` shows the exact `rustup` command and, in a terminal,
27
+ asks `Run ... now? (Y/n)` (never silently; with no TTY it just fails with the command).
28
+ `npx convex-rust doctor` checks cargo, rustup, toolchain + target, the shipped `convex_fn` crate and `wasm-opt`.
29
+ `wasm-opt` (binaryen, `brew install binaryen`) is optional: it makes release wasm about 30% smaller (`-O3`).
30
+ Wasm SIMD is on by default (`--no-simd` to opt out). Instance reuse, `CONVEX_RUST_TRACE` and build flags: docs/rust/cloud.md.
31
+
32
+ The scaffolded crate depends on `convex_fn` by path into `node_modules/convex-rust/rust/convex_fn` (shipped in this
33
+ package; nothing is fetched from crates.io for it). Commit `convex/rust/Cargo.lock`, `src/_generated/api.rs` and
34
+ the generated `*.ts` wrappers; `_wasm/` is git-ignored, so CI runs `npx convex-rust build` before `npx convex deploy`.
35
+
36
+ ## Build
37
+
38
+ ```sh
39
+ npx convex-rust build [--watch] [--out convex/rust] [--profile dev|release] [--crate <dir>] [--env A,B] [--no-simd] [--single] [--modules] [--group name=a,b] [--split] [--wasi-sdk | --no-wasi-sdk]
40
+ npx convex-rust dev # watch loop next to `npx convex dev` (debounced; dev profile)
41
+ npx convex-rust doctor # check cargo / rustup / target / wasm-opt, with fix commands
42
+ npx convex-rust codegen # only refresh src/_generated/api.rs (typed refs to your TS functions)
43
+ npx convex-rust symbolize [file] [--module m] # turn wasm-function[N]:0x.. in pasted Convex logs into Rust names
44
+ npx convex-rust wasi-sdk # install (if missing) and print the wasi-sdk path used for C dependencies
45
+ ```
46
+
47
+ C-wrapping crates (zstd-sys, bundled SQLite, ring) build with a wasi-sdk: found in `WASI_SDK_PATH` or
48
+ `~/.cache/convex-rust/wasi-sdk-34.0`, downloaded once (about 180 MB) when a C build script is detected
49
+ (`--wasi-sdk` forces, `--no-wasi-sdk` disables). The build also warns about wasm imports that fail on the host
50
+ (sockets, filesystem, threads). See docs/rust/crates.md and docs/rust/cloud.md.
51
+
52
+ 1. `cargo build --target wasm32-wasip1` of the crate (default `convex/rust`, or `--crate`).
53
+ 2. Reads the `convex:manifest` custom section of the wasm.
54
+ In the release profile the crate is built once per Convex module with no setup in the crate: after a first
55
+ build learns the modules, `cargo rustc --lib -- --cfg convex_split --cfg 'convex_keep="<fn>"'` rebuilds only
56
+ your crate per module (dependencies are compiled once), the `#[action]` macro drops the other modules'
57
+ exports and the linker removes their code. Each module imports its own, smaller wasm
58
+ (`<out>/_wasm/<crate>.<module>.wasm`). Over 28 MiB in total (Convex bundles at most 32 MiB) the smallest
59
+ modules are merged with a warning. `convex-rust dev` (dev profile) builds one shared wasm for faster
60
+ rebuilds; `--modules` forces per-module there. Crates with two or more `m-<module>` cargo features use
61
+ those instead. `--group name=a,b` overrides the grouping, `--single` builds one shared wasm. See docs/rust/cloud.md.
62
+ 3. Writes `<out>/_wasm/<crate>.wasm` and one TypeScript module per Rust module
63
+ (`crate::a::b` -> `<out>/a/b.ts`, crate root -> `<out>/lib.ts`), plus `_wasm.d.ts`.
64
+ Files carry a `@generated` header; stale generated files are removed, hand-written files are kept.
65
+
66
+ `--out` must be inside the Convex functions directory. Then push with the stock CLI:
67
+
68
+ ```sh
69
+ npx convex dev --once # or: npx convex deploy
70
+ npx convex run rust/hello:hello
71
+ ```
72
+
73
+ Generated wrapper (args/returns validators come from the Rust types; omitted args default to `v.any()`):
74
+
75
+ ```ts
76
+ import { action } from "../_generated/server";
77
+ import { runRust } from "convex-rust/runtime";
78
+ import wasm from "./_wasm/hello_rust.wasm";
79
+ export const hello = action({
80
+ args: {},
81
+ returns: v.string(),
82
+ handler: (ctx, args) => runRust(ctx, wasm, "convex_run:hello_rust::hello:hello", args),
83
+ });
84
+ ```
85
+
86
+ `#[action(internal)]` functions become `internalAction`.
87
+
88
+ ## Runtime
89
+
90
+ `convex-rust/runtime` exports `runRust(ctx, module, exportName, args)` and `runRustHttp(ctx, module, exportName, request)`
91
+ (the handler body of the `httpAction` generated for `#[http_action]` functions: streamed request and response bodies, 20 MiB
92
+ limits; V8 host only, see `docs/rust/cloud.md#http-actions`). It has no Node built-ins and no
93
+ dependencies besides `convex/values`; it needs `WebAssembly.Suspending` / `WebAssembly.promising` (JSPI),
94
+ which the Convex default runtime provides. The guest's own linear memory is used as is (no extra cap).
95
+
96
+ Supported guest operations: `fetch` (streamed response and request bodies, manual redirects handled by the SDK;
97
+ dropping the Rust future aborts the request; large bodies pass as `{ptr,len}` references instead of base64), `sleep`,
98
+ Convex syscalls (`runQuery`, `runMutation`, `runAction` and `schedule` by path, function handle or component
99
+ reference; `getUserIdentity`; storage incl. `generateUploadUrl`; `vectorSearch`), `componentArgument`, `now`,
100
+ logging (levels map to `console.debug|log|warn|error`) and WASI `fd_write`, `environ_*`,
101
+ `clock_time_get`, `random_get`. Any other syscall name is forwarded to the runtime's `Convex.asyncSyscall`
102
+ (it fails with `Unsupported syscall in the V8 host: <name>` if that is missing); other WASI calls return `ENOSYS`.
103
+
104
+ Errors: Rust errors throw `Error(message)`; `Error::convex(data)` throws `ConvexError(data)`; a panic
105
+ surfaces as `Uncaught Error: <panic message> at file:line`.
106
+
107
+ ## Typed `api.rs`, reqwest, env vars
108
+
109
+ - `build` / `codegen` generate `src/_generated/api.rs` (typed `FunctionRef`s for `ctx.run_query` & co.) by
110
+ bundling your `convex/*.ts` with esbuild and reading the registered functions' validators in a Node
111
+ subprocess. No backend needed; `convex/_generated` must exist.
112
+ - `.cargo/config.toml` holds a managed `[patch.crates-io]` block that swaps `reqwest` for the host-`fetch`
113
+ shim when a dependency uses it. The shim crates ship in `rust/` (copied from the monorepo's `crates/` by
114
+ `npm run vendor-crates`, run on `prepack`); `CONVEX_REQWEST_PATH` / `CONVEX_FN_PATH` override.
115
+ - `[build] target-dir` points outside `convex/` so the stock CLI does not walk cargo output.
116
+ - The default runtime cannot enumerate `process.env`: list the variables Rust may read with
117
+ `build --env A,B` or the deployment variable `CONVEX_RUST_ENV=A,B`.
118
+
119
+ - Crypto (signatures, AES-GCM, SHA-1/SHA-2, HMAC) is provided by the host and required: there is no pure-Rust fallback in wasm32. Keep this package up to date; a host without an operation fails with `host lacks crypto/<op> <alg>`.
120
+
121
+ - `/tmp` is a writable in-memory directory (per call, discarded after it; file data lives in the guest's linear memory; 64 MiB cap by default, `CONVEX_RUST_TMP_BYTES` or `runRust(..., { tmpBytes })`, `0` removes it). Use `convex_fn::fs::temp_dir()`: `std::env::temp_dir()` panics on `wasm32-wasip1`.
122
+ - Time zones and locale formatting come from the runtime's `Intl` via `convex_fn::intl` (`tz_offset_secs`, `local_to_epoch_ms`, `format_date`, `format_number`); an unknown zone is an error, never UTC. `jiff` / `chrono-tz` with a bundled tzdb also work, at a size cost.
123
+ - Fan-out: `ctx.run_action_each(target, args, limit)` / `convex_fn::par_map` run many actions in parallel with a concurrency limit (each is a separate billed action execution).
124
+
125
+ See `docs/rust/cloud.md` for the full guide.
126
+
127
+ ## Limitations
128
+
129
+ - Convex default-runtime limits apply (30 minute actions, 64 MiB RAM documented, code size per the [limits page](https://docs.convex.dev/production/state/limits), actions only, no `"use node"`).
130
+
131
+ ## Development
132
+
133
+ ```sh
134
+ npm run build # tsc -> dist
135
+ npm test # vitest: host import semantics (hand-written wasm guest) + generator output
136
+ ```
137
+
138
+ `test/fixtures/gen-guest.mjs` regenerates the test guest (needs `wasm-opt`).
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env node
2
+ import path from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import fs from "node:fs";
5
+ import { BuildError, buildOnce, codegenOnly, parseGroups, resolveFunctionsDir, watch } from "./build.js";
6
+ import { defaultTargetDir, scaffoldRust } from "./scaffold.js";
7
+ import { findCrateLayout } from "./build.js";
8
+ import { findWasiSdk, installWasiSdk, wasiSdkMode } from "./wasisdk.js";
9
+ import { checkRustToolchain, doctorReport } from "./toolchain.js";
10
+ import { resolveConvexFnPath } from "./shim.js";
11
+ import { readSymbolMaps, symbolize, symbolsDir } from "./symbols.js";
12
+ const USAGE = `convex-rust: "use rust" for stock Convex
13
+
14
+ Usage:
15
+ convex-rust build [--watch] [--out <dir>] [--crate <dir>] [--profile release|dev] [--env A,B] [--no-simd] [--single] [--modules] [--split] [--group name=mod,mod ...]
16
+ convex-rust dev [--out <dir>] [--crate <dir>] [--profile release|dev] [--env A,B] [--no-simd] [--split]
17
+ convex-rust codegen [--out <dir>] [--crate <dir>]
18
+ convex-rust init [--crate <dir>] [--convex-fn-path <dir>]
19
+ convex-rust doctor [--crate <dir>]
20
+ convex-rust symbolize [file] [--module <name>] [--crate <dir>] [--symbols <dir>]
21
+ convex-rust wasi-sdk
22
+
23
+ build Builds the Rust crate (default convex/rust) for wasm32-wasip1 and writes the
24
+ wasm and the TypeScript action wrappers into --out (default convex/rust).
25
+ dev Watch loop for use next to \`npx convex dev\`: rebuilds and regenerates on .rs / Cargo changes
26
+ (debounced), and refreshes src/_generated/api.rs when your TypeScript functions change.
27
+ Same as \`build --watch\`, with the dev profile unless --profile is given.
28
+ codegen Regenerates only src/_generated/api.rs (typed Rust references to your TS functions), no cargo.
29
+ --env Env var names the Rust code may read (Convex env vars cannot be enumerated in the default
30
+ runtime). More can be added at runtime with the deployment variable CONVEX_RUST_ENV=A,B.
31
+ --no-simd Build without wasm SIMD (-C target-feature=+simd128 is on by default). Use it if the runtime
32
+ rejects SIMD wasm (CompileError mentioning simd). Also: CONVEX_RUST_SIMD=0.
33
+ One wasm per Convex module is the default, with no setup in the crate: it is compiled once, then once per
34
+ module with \`--cfg convex_split --cfg convex_keep="<fn>"\` for that module's functions (the #[action] macro
35
+ drops the other exports, so the linker removes their code). Dependencies are compiled once. If the crate
36
+ defines cargo features m-<module> (two or more), those are used instead. Each module's wrapper imports its
37
+ own wasm. A stock deployment compiles every imported wasm on every call (~0.85 ms per MB). If the wasm add
38
+ up to more than 28 MiB (Convex bundles at most 32 MiB), the smallest modules are merged, with a warning.
39
+ --modules Also build one wasm per module in the dev profile (\`dev\` builds one shared wasm by default: the per-module
40
+ build recompiles the crate once per module, ~8x slower rebuilds). Also: CONVEX_RUST_MODULES=1.
41
+ --single Build one shared wasm with the default features instead. Also: CONVEX_RUST_MODULES=0.
42
+ --split Legacy, only with --single: cut per-module wasm from the shared wasm with wasm-opt (keeps everything the
43
+ function table reaches, so it shrinks far less than the default). Also: CONVEX_RUST_SPLIT=1.
44
+ --group name=modA,modB (repeatable) Build the crate once per group with cargo features m-<module> (no default
45
+ features), one wasm per group (overrides the per-module default, e.g. to merge tiny modules into one light
46
+ wasm); each module imports its group's wasm. Modules in no group are not built.
47
+ Also: CONVEX_RUST_GROUPS="light=base,cb;heavy=cpu,data". Feature prefix: --group-prefix (default m-).
48
+ init Creates a starter crate (never overwrites existing files) and prints the next steps.
49
+ doctor Checks cargo, rustup, the toolchain + wasm32-wasip1 target, the shipped convex_fn crate and wasm-opt,
50
+ with the command that fixes each problem. Exit code 1 when something required is missing.
51
+ --wasi-sdk / --no-wasi-sdk C dependencies (zstd-sys, libsqlite3-sys, ...) are compiled with a wasi-sdk clang: WASI_SDK_PATH, or
52
+ ~/.cache/convex-rust/wasi-sdk-34.0. By default (auto) it is downloaded (~180 MB, sha256-pinned) only when a
53
+ dependency has a C build script and none is installed; --wasi-sdk always installs it, --no-wasi-sdk never does.
54
+ Also: CONVEX_RUST_WASI_SDK=1|0.
55
+ symbolize Rewrites wasm-function[123]:0x... frames from pasted Convex logs (file or stdin) into Rust function names, using
56
+ the name map that build keeps in cargo's target dir (not deployed). --module picks the wasm when several were built.
57
+ wasi-sdk Installs the pinned wasi-sdk into the cache dir (if missing) and prints its path.
58
+ `;
59
+ /** Appends `line` to the project's .gitignore unless it is already there. */
60
+ function ensureGitignored(cwd, line) {
61
+ const file = path.join(cwd, ".gitignore");
62
+ let cur = "";
63
+ try {
64
+ cur = fs.readFileSync(file, "utf8");
65
+ }
66
+ catch {
67
+ // no .gitignore yet
68
+ }
69
+ if (cur.split(/\r?\n/).some((l) => l.trim() === line || l.trim() === line.replace(/\/$/, "")))
70
+ return;
71
+ fs.writeFileSync(file, cur + (cur === "" || cur.endsWith("\n") ? "" : "\n") + line + "\n");
72
+ console.error(`updated .gitignore (${line})`);
73
+ }
74
+ async function main(argv) {
75
+ const [command, ...rest] = argv;
76
+ if (!command || command === "--help" || command === "-h" || command === "help") {
77
+ console.log(USAGE);
78
+ return command ? 0 : 1;
79
+ }
80
+ const { values, positionals } = parseArgs({
81
+ args: rest,
82
+ options: {
83
+ watch: { type: "boolean", default: false },
84
+ out: { type: "string" },
85
+ crate: { type: "string" },
86
+ env: { type: "string" },
87
+ "no-simd": { type: "boolean", default: false },
88
+ "wasi-sdk": { type: "boolean", default: false },
89
+ "no-wasi-sdk": { type: "boolean", default: false },
90
+ module: { type: "string" },
91
+ symbols: { type: "string" },
92
+ split: { type: "boolean", default: false },
93
+ single: { type: "boolean", default: false },
94
+ modules: { type: "boolean", default: false },
95
+ group: { type: "string", multiple: true },
96
+ "group-prefix": { type: "string" },
97
+ profile: { type: "string" },
98
+ "convex-fn-path": { type: "string" },
99
+ help: { type: "boolean", short: "h", default: false },
100
+ },
101
+ allowPositionals: command === "symbolize",
102
+ });
103
+ if (values.help) {
104
+ console.log(USAGE);
105
+ return 0;
106
+ }
107
+ const cwd = process.cwd();
108
+ try {
109
+ if (command === "codegen") {
110
+ await codegenOnly({ cwd, crate: values.crate, out: values.out, profile: "release" });
111
+ return 0;
112
+ }
113
+ if (command === "symbolize") {
114
+ let dir = values.symbols;
115
+ if (!dir) {
116
+ const crate = path.resolve(cwd, values.crate ?? path.join(resolveFunctionsDir(cwd), "rust"));
117
+ dir = symbolsDir((await findCrateLayout(crate)).targetDir);
118
+ }
119
+ const input = positionals[0] ? fs.readFileSync(positionals[0], "utf8") : fs.readFileSync(0, "utf8");
120
+ const res = symbolize(input, readSymbolMaps(dir), values.module);
121
+ process.stdout.write(res.text);
122
+ if (res.note)
123
+ console.error(`convex-rust symbolize: ${res.note}`);
124
+ else if (res.replaced === 0)
125
+ console.error("convex-rust symbolize: no wasm-function[N] frames matched the symbol map");
126
+ return res.note ? 1 : 0;
127
+ }
128
+ if (command === "wasi-sdk") {
129
+ const dir = findWasiSdk()?.dir ?? (await installWasiSdk());
130
+ console.log(dir);
131
+ return 0;
132
+ }
133
+ if (command === "build" || command === "dev") {
134
+ const profile = values.profile ??
135
+ (command === "dev" || process.env.CONVEX_RUST_PROFILE === "dev" ? "dev" : "release");
136
+ if (profile !== "release" && profile !== "dev") {
137
+ console.error(`error: --profile must be release or dev (got ${profile}).`);
138
+ return 2;
139
+ }
140
+ const groupSpecs = values.group?.length ? values.group : (process.env.CONVEX_RUST_GROUPS ?? "").split(";").filter((x) => x.trim());
141
+ const opts = { wasiSdk: wasiSdkMode({ wasiSdk: values["wasi-sdk"], noWasiSdk: values["no-wasi-sdk"] }), groups: parseGroups(groupSpecs), groupFeaturePrefix: values["group-prefix"], perModule: values.single || process.env.CONVEX_RUST_MODULES === "0" ? false : values.modules || process.env.CONVEX_RUST_MODULES === "1" ? true : undefined, cwd, crate: values.crate, out: values.out, profile: profile, split: values.split || process.env.CONVEX_RUST_SPLIT === "1", simd: !values["no-simd"] && process.env.CONVEX_RUST_SIMD !== "0", env: (values.env ?? process.env.CONVEX_RUST_BUILD_ENV ?? "").split(",").map((s) => s.trim()).filter(Boolean) };
142
+ if (values.watch || command === "dev")
143
+ await watch(opts);
144
+ else
145
+ await buildOnce(opts);
146
+ return 0;
147
+ }
148
+ if (command === "init") {
149
+ const crate = path.resolve(cwd, values.crate ?? path.join(resolveFunctionsDir(cwd), "rust"));
150
+ const res = scaffoldRust(crate, {
151
+ convexFnPath: values["convex-fn-path"] ?? process.env.CONVEX_FN_PATH,
152
+ channel: process.env.CONVEX_RUST_CHANNEL,
153
+ targetDir: defaultTargetDir(cwd, crate),
154
+ });
155
+ ensureGitignored(cwd, ".convex-rust/");
156
+ for (const f of res.created)
157
+ console.error(`created ${path.relative(cwd, path.join(crate, f))}`);
158
+ for (const f of res.skipped)
159
+ console.error(`skipped ${path.relative(cwd, path.join(crate, f))} (exists)`);
160
+ const tc = checkRustToolchain(crate);
161
+ if (!tc.ok)
162
+ console.error(`\nwarning: ${tc.message}`);
163
+ const rel = path.relative(cwd, crate) || ".";
164
+ console.error([
165
+ "",
166
+ "Next:",
167
+ " npx convex-rust build # compiles the crate (first build downloads crates, ~1 min), writes the wasm + TS wrappers",
168
+ " npx convex dev --once # pushes it (or: npx convex deploy). Needs a configured project: run `npx convex dev` once first.",
169
+ ` npx convex run rust/example:greet '{"name":"you"}'`,
170
+ "",
171
+ `While editing Rust, run \`npx convex-rust dev\` next to \`npx convex dev\`. Commit ${rel}/Cargo.lock and ${rel}/src/_generated/api.rs.`,
172
+ `Check your setup any time with \`npx convex-rust doctor\`.`,
173
+ ].join("\n"));
174
+ return 0;
175
+ }
176
+ if (command === "doctor") {
177
+ const crate = path.resolve(cwd, values.crate ?? path.join(resolveFunctionsDir(cwd), "rust"));
178
+ const hasCrate = fs.existsSync(path.join(crate, "Cargo.toml"));
179
+ const rep = doctorReport(hasCrate ? crate : null, undefined, { convexFnPath: resolveConvexFnPath(crate) ?? "<not found>" });
180
+ for (const l of rep.lines)
181
+ console.log(`${l.ok ? "ok " : l.optional ? "warn" : "FAIL"} ${l.text}`);
182
+ if (!hasCrate)
183
+ console.log(`note ${path.join(crate, "Cargo.toml")} not found: run \`npx convex-rust init\``);
184
+ return rep.ok ? 0 : 1;
185
+ }
186
+ console.error(`error: unknown command ${command}\n\n${USAGE}`);
187
+ return 2;
188
+ }
189
+ catch (e) {
190
+ if (e instanceof BuildError) {
191
+ console.error(`error: ${e.message}`);
192
+ return 1;
193
+ }
194
+ throw e;
195
+ }
196
+ }
197
+ main(process.argv.slice(2)).then((code) => process.exit(code), (e) => {
198
+ console.error(e);
199
+ process.exit(1);
200
+ });