Get started with ThreadOne
Install the SDK, then create a project. The compiler emits Rust and uses its LLVM backend to produce a native executable. It does not execute JavaScript.
threadone doctor
threadone new my-app
cd my-app
threadone run
Read your first program
Open src/main.one. Variables are immutable unless declared with mut. Function inputs/outputs are checked before a native build.
fn greet(name: String) -> String:
return "Hello, " + name
fn main():
message = "Erwin" |> greet
print(message)
Check, test, ship a binary
threadone check
threadone test
threadone build
Run build/app on Unix, or build/app.exe on Windows. The binary needs compatible OS/system libraries but no Node, Python or ThreadOne SDK. Build on each target OS; this preview does not provide a cross-compilation CLI.
A small HTTP service
threadone new my-api --template api
cd my-api
threadone build
Run build/app and open http://127.0.0.1:8080/health. On Unix, set THREADONE_PORT=9000 before the command to change the port. On PowerShell, set $env:THREADONE_PORT='9000'. The api template includes a health route and a typed POST/JSON route. The http template retains the simple GET/HEAD text handler.
A typed JSON API
Save this complete program as users.one and run threadone run users.one. It validates and echoes a User; it does not save to a database. Route programs create their server entry point automatically on port 8080, so do not add fn main to the same file.
type User:
name: String
email: String
bio: String?
route POST "/users" (req):
user = req.json(User) or return 400 "Invalid JSON"
return 201 user
Send a request from a second terminal. On Windows, use curl.exe when PowerShell reserves the curl command name.
curl -i http://127.0.0.1:8080/users \
-H 'Content-Type: application/json' \
-d '{"name":"Erwin","email":"erwin@example.test"}'
A valid request returns status 201 and JSON. The optional bio field may be omitted or null; the response then includes "bio":null. Required fields must be present with the correct type. Unknown and duplicate fields are rejected. Body input and JSON output are limited to 1 MiB. This preview accepts Content-Length request bodies, rejects chunked Transfer-Encoding and Expect requests, and requires UTF-8 bodies. Body deadlines return 408; handler deadlines return 504.
Routes match static paths and named segments such as /users/:id without the query string. At the first differing segment, a static segment takes precedence over a parameter. The winning path is selected before its method, so a method mismatch returns 405 instead of falling through to a less specific route. GET supplies HEAD unless that path has an explicit HEAD route. Unknown paths return 404. TLS and automatic persistence remain unimplemented.
Path parameters and response headers
The SDK provides req.param(name) with separate failure and absence handling, plus response_header(response, name, value) for immutable, validated response headers. Path captures decode percent escapes once; plus remains literal. Invalid UTF-8, decoded separators, controls and dot segments are rejected. Runtime-owned framing headers cannot be overridden.
route GET "/users/:id" (req):
found = req.param("id") or return 400 "Invalid path"
id = found or return 404 "Missing user"
response = text_response(200, id)
return response_header(response, "Cache-Control", "no-store") or return 500 "Header error"
Run examples/http-routing.one with the native SDK for a complete JSON example. These APIs are native-only: browser Check accepts them, but browser Run cannot serve HTTP. The language specification defines parameter names, route precedence and header count, byte and character limits. Read the versioned release report for publication and current-platform validation.
Read request metadata
Read optional query parameters and headers with req.query(name) and req.header(name). Both return String?!: handle invalid or duplicate input first, then handle absence. The native SDK includes examples/request-access.one; the language specification lists decoding and size limits. Browser Run cannot execute this HTTP example.
type SearchResult:
q: String
request_id: String?
route GET "/search" (req):
query = req.query("q") or return 400 "Invalid query"
request_id = req.header("X-Request-ID") or return 400 "Invalid request header"
term = query or "all"
return 200 SearchResult(q: term, request_id: request_id)
Use immutable records
Named constructor fields may appear in any order and are evaluated in source order. Fields cannot be changed in place. A mutable binding may be assigned a new record; existing copied values keep their previous fields.
type User:
name: String
email: String
fn main():
user = User(email: "erwin@example.test", name: "Erwin")
print(user.name)
encoded = json_encode(user) or "Encoding failed"
print(encoded)
Record fields support Int, Bool, String, nominal enums, other nonrecursive records, their Optional forms and immutable scalar, enum or record lists. Namespaced modules remain planned. Strict typed JSON decoding does not replace business validation such as checking an email address or authorizing a request.
Handle an absent value
Use String?, Int?, Bool? or a record type followed by ? when a value may be absent. Wrap a present value with some(value), and use none for an absent value. The compiler requires a known Optional type for none; it does not silently wrap ordinary values.
type Profile:
name: String
bio: String?
fn bio_label(bio: String?) -> String:
return bio or "No biography yet"
fn main():
user = Profile(name: "Erwin", bio: none)
print(bio_label(user.bio))
print(bio_label(some("Building ThreadOne")))
The fallback after or runs only when the value is none. Handle an Optional before arithmetic, Boolean conditions or record field access. A comparison such as user.bio == none checks absence but does not change the variable's type. Constructors still require every named field; pass none explicitly when a field is absent.
Accept optional JSON fields
Missing fields and JSON null decode to none only when the declared field type ends in ?. Present values must have the declared underlying type. Encoding none produces JSON null. Required fields, unknown fields and duplicate fields remain strict; duplicate optional fields are rejected even when a value is null.
type Profile:
name: String
bio: String?
route POST "/profiles" (req):
profile = req.json(Profile) or return 400 "Invalid profile"
return 201 profile
Send {"name":"Erwin"} to this endpoint and its response includes "bio":null. A required name cannot be omitted or null. This validates the record shape, not authentication or application rules. There is no bare null value in ThreadOne source.
Optional values can be parameters and return values. A return type such as String?! represents a fallible Optional: handle the error first, then absence. Nested Optional types, Optional Request/Response/Void and recursive record shapes are not supported. Parenthesize mixed or, pipe and comparison expressions in this preview.
Cooperative I/O without async or await
Write a normal function call. The compiler lowers ThreadOne functions to native Rust async functions, and the runtime drives them on one Tokio current_thread executor with a LocalSet. I/O uses readiness notifications; io_uring and thread-per-core are not implemented in this release.
fn main():
sleep(25) or false
yield_now()
print("Continued after waiting")
sleep accepts 0–60000 milliseconds and yields while waiting. yield_now explicitly gives other ready work a turn. This is cooperative scheduling: a long CPU loop without a yield still blocks the event loop, and a deadline cannot preempt it.
HTTP request arenas remain alive across suspension points. Awaiting handlers have a configurable deadline, returning 504 on timeout; recoverable handler panics return 500. These protections do not make CPU-bound code preemptible. The runtime is still a developer preview.
Try the Redis language bindings
Configure an existing Redis server through THREADONE_REDIS_URL, then place this example in src/main.one. Remote connections require TLS with a rediss:// URL. Credentials come from your environment; do not put real passwords into source code or share them through the playground.
fn round_trip() -> String:
redis_set("threadone:greeting", "Hello", 60000) or return "Redis write failed"
return redis_get("threadone:greeting") or "Redis read failed"
fn main():
print(round_trip())
export THREADONE_REDIS_URL='rediss://user:password@redis.example.com:6379'
threadone run
$env:THREADONE_REDIS_URL='rediss://user:password@redis.example.com:6379'
threadone run
Replace the example address and credentials with your server configuration. Only local development on loopback may opt into plaintext: set THREADONE_REDIS_ALLOW_LOCAL_PLAINTEXT=1 together with a redis://127.0.0.1:6379 URL. Plaintext connections to remote hosts are rejected.
redis_set requires a positive TTL in milliseconds. redis_get returns a UTF-8 String or an error for a missing key. redis_delete returns a count, and redis_ping returns the server response. Calls have bounded concurrency and a timeout. A failed write may have reached the server; do not retry writes blindly. Dragonfly compatibility is not yet verified.
PostgreSQL, MySQL/MariaDB and MongoDB have native language bindings with explicit scalar/Optional contracts. SQL Server remains an experimental Rust adapter. Read the versioned validation report for each server and exact SDK artifact; compilation alone is not proof of database compatibility.
Distinguish a cache miss from a failed read
redis_find returns String?!: a read can fail, succeed without a key, or succeed with UTF-8 text. Handle the read error first and the absent value second. A missing key is not a connection failure, and an empty string is a present value.
fn cached_name(key: String) -> String:
cached = redis_find(key) or return "Cache unavailable"
return cached or "No cached name"
fn main():
print(cached_name("threadone:display-name"))
Configure THREADONE_REDIS_URL as above before running this example. The first or handles connection, protocol, invalid UTF-8 and oversized-value errors. The second or runs only for a missing key. redis_get keeps its earlier String! contract and treats a missing key as an error; existing callers do not change automatically.
redis_find rejects keys larger than 4096 UTF-8 bytes before opening a connection. This is a limit of the new lookup function; redis_get retains its existing key behavior.
Both read functions check the 1 MiB value limit after the driver receives and decodes the response, before copying it into the arena. This does not bound memory consumed by an untrusted server response. Use a trusted Redis endpoint. Dragonfly compatibility and Redis Cluster/Sentinel remain unverified.
Recover from an error
fn describe(text: String) -> String:
value = parse_int(text) or return "Invalid number"
return value |> str
fn main():
print(describe("42"))
The right side of or runs only on failure. A type error reports the source filename, line and column. Use threadone emit to inspect the generated native backend source.
What comes next
Read the implemented language guide before using design-draft examples. The current SDK is for evaluation and experiments; it has not passed the production release gates.