IO and storage

Files, HTTP, JSON, and a persistent store with atomic commits — the runtime's outward-facing verbs.

File IO

// Read — encoding controls how `data` is decoded.
//   "utf8"  → string
//   "bytes" → bytes (raw octets)
r := io/file/read(path = "config.json", encoding = "utf8")
if (r/ok) { print r/data }

// Write returns the same [ok, ...] envelope.
w := io/file/write(path = "out.txt", data = "hello", encoding = "utf8")
print w/ok    // → true

// Reading a missing path raises — guard when absence is expected.
if (io/file/exists(path = "maybe.json"))
{
    print io/file/read(path = "maybe.json", encoding = "utf8")/data
}

The executor-backed families (io/file/*, io/http/*, io/process/*) return flat [ok = bool, …] records — failure is a value you branch on. Beneath them, the io/fs/* builtins (list, stat, mkdir, mkdtemp, copy, rename, remove, ...) return raw values and raise on faults, and path/exists / path/is_file / path/is_dir cover the quick predicates.

HTTP client

WidgetCreate::(name: string, count: int)
WidgetRef::(id: string)
WidgetResponse::(widget: WidgetRef)

payload: WidgetCreate := WidgetCreate(name = "widget-1", count = 3)
resp := io/http/post(
    url        = "https://api.example/v1/widgets",
    headers    = [[name = "authorization", value = "Bearer ..."]],
    data       = json/encode(payload),
    timeout_ms = 10000
)

if (resp/ok and resp/code == 201)
{
    parsed: WidgetResponse := json/parse(resp/body)
    print parsed/widget/id
}

The response contract is rich but flat: ok, code, body, headers_by_name, typed transport errors (E_HTTP_DNS, E_HTTP_TIMEOUT, ...), retry classification, and per-phase timings. io/http/get|post|put|delete are the convenience verbs; sessions reuse connections; pass async = true to get a task instead of blocking. Beneath HTTP, io/* also covers TCP/UDP and Unix sockets, process control, and TUN/TAP devices.

HTTP server

web := import("elder/web")

Reply::(code: int, body: string, mime: string = "text/plain")

handler::(request, body = []) {
    path: string := get(request, "full_path", "")
    if (path == "/health") { return Reply(code = 200, body = "ok") }
    return Reply(code = 404, body = "not found")
}

io/apie/serve(host = "127.0.0.1", port = 18085, preprocessor = handler,
    preprocessor_terminal = true)

APIE — the eons web server, itself written in Elder — accepts a handler functor and dispatches every request to it as a task. Larger apps wrap the handler with a router and middlewares; FacetFactory (which serves this page) is one such handler.

JSON

Person::(name: string, ages: list(int))
Flags::(version: int, enabled: list(bool))

// Bind the decoded data to its named type.
parsed: Person :=
    json/parse('{"name":"ada","ages":[12,13]}')
print parsed/name      // → "ada"
print parsed/ages[1]   // → 13

flags: Flags := Flags(version = 1, enabled = [true, false])
encoded: string := json/encode(flags)
print encoded

json/parse decodes external JSON. The receiving type checks the field shape. json/encode serializes values for a JSON consumer. The per-record store uses CBOR on disk.

Persistent state, two shapes

Persistence is part of the runtime, not a bolted-on ORM. fs_open(path) opens a locked store; from there you pick the write shape. Snapshots (fs/load + fs/commit) persist a whole state record with atomic, generation-checked commits — right for config-plus-small-state. Per-record (store/*) addresses records independently with per-key revisions — right for high-write state:

User::(name: string, role: string)
AuditEvent::(event: string, id: string)

fs := fs_open("./state")

// Give the stored value a closed shape.
ada: User := User(name = "Ada", role = "engineer")
store/set(fs, collection = "users", key = "u1", value = ada)

rec := store/get(fs, collection = "users", key = "u1")
user: User := rec/value
print user/name         // → "Ada"
print rec/revision      // → monotonic int, bumped on each set

// Compare-and-swap: only write if nobody else has since you read.
promoted: User := User(name = user/name, role = "lead")
store/set(fs, collection = "users", key = "u1", value = promoted,
          base_revision = rec/revision)

// Atomic batch — all writes land together or not at all.
store/transaction(fs)
{
    bea: User := User(name = "Bea", role = "engineer")
    audit: AuditEvent := AuditEvent(event = "user_create", id = "u2")
    store/set(collection = "users", key = "u2", value = bea)
    store/set(collection = "audit", key = id/uuid(),
              value = audit)
}

Records round-trip through canonical CBOR; a conflicting CAS raises E_STORE_CONFLICT; store/scan pages through a collection. The backing substrate defaults to ~/.eons/elder_fs.db (ELDER_FS_STORE redirects it). store/* is process-local by design — when state must span processes or hosts, that's the Constellatus registry's job, not IPC around a file lock.

Time, IDs, randomness

// Timing and sleep
start := time/epoch_ms()
sleep(50)
print time/epoch_ms() - start >= 50   // → true
print time/strftime("%Y-%m-%d", time/epoch_ms())

// IDs
print id/uuid()                        // → "6ec7f6fa-9803-..."
print id/stable_from(["user", "ada"])  // deterministic id from seed fields

// Deterministic, seedable randomness (rng/* is pure — no ambient state);
// real entropy is capability-gated behind `unsafe { io/rand/entropy() }`.