Part VI · Complete Annotated Examples & Showcase Applications
Appendix C.3
Complete Examples Catalog: Databases, Tooling, SIMD, Reactor, UI, FFI & Durable Workflows (Examples 23–32)
Unabridged listings covering Zero-FFI DBs, VKP1 signing, LSP/fmt, ARM64, readiness reactors, RGBA32 UI, FFI, and durable sagas
Complete unabridged source listings for Examples 23 through 32, covering Zero-FFI databases, signed VKP1 bundles, everyday batteries, HTML5 components, developer tooling, SIMD & AArch64 cross-compilation, the readiness reactor, TUI & 2D UI, opt-in FFI, and Durable Workflows.
Example 23: 23_zero_ffi_databases_kv_pg_redis.vk
Run command: veko -A examples/23_zero_ffi_databases_kv_pg_redis.vk
Example 23: Zero-FFI Database Stack — Crash-Safe Embedded KV, Postgres SCRAM-SHA-256, Redis RESP3 & Sidecar RPC Demonstrates lib/db/kv (CRC-32 WAL, crash recovery, compaction, AES-256-GCM at-rest sealing), lib/db/postgres (v3.0 binary wire + RFC 7677 SCRAM-SHA-256 over loopback TCP), lib/db/redis (RESP3 client/server + pipeline over loopback TCP), and lib/db/sidecar (VKSC framing). Track C (Native) : veko compile --native examples/23_zero_ffi_databases_kv_pg_redis.vk -o dist/23.exe ; ./dist/23.exe
1 │ // Example 23: Zero-FFI Database Stack — Crash-Safe Embedded KV, Postgres SCRAM-SHA-256, Redis RESP3 & Sidecar RPC
2 │ // Demonstrates `lib/db/kv` (CRC-32 WAL, crash recovery, compaction, AES-256-GCM at-rest sealing),
3 │ // `lib/db/postgres` (v3.0 binary wire + RFC 7677 SCRAM-SHA-256 over loopback TCP),
4 │ // `lib/db/redis` (RESP3 client/server + pipeline over loopback TCP), and `lib/db/sidecar` (`VKSC` framing).
5 │ //
6 │ // Track A (ORO VM) : veko run --allow-net --allow-listen --allow-private-net examples/23_zero_ffi_databases_kv_pg_redis.vk
7 │ // Track B (Wasm 3) : veko run --wasm --check-slabs --fuel=0 --allow-net --allow-listen --allow-private-net --allow-fs=. examples/23_zero_ffi_databases_kv_pg_redis.vk
8 │ // Track C (Native) : veko compile --native examples/23_zero_ffi_databases_kv_pg_redis.vk -o dist/23.exe ; ./dist/23.exe
9 │
10 │ use [
11 │ io
12 │ inet = io/net
13 │ hex = codec/hex
14 │ sha = crypto/sha256
15 │ kdf = crypto/kdf
16 │ kv = db/kv
17 │ pg = db/postgres
18 │ redis = db/redis
19 │ sc = db/sidecar
20 │ ]
21 │
22 │ // 1. Embedded Crash-Safe Transactional KV Store (`db/kv`)
23 │ kv_path = str/join [(os/temp-dir) '/veko_ex23_store.vkkv'] ''
24 │ _ = os/remove/or kv_path [.ok]
25 │ defer [ _ = os/remove/or kv_path [.ok] ]
26 │
27 │ enc_key = bytes/fill 32 0x5A
28 │ mut store = kv/open kv_path
29 │ _ = kv/put-val mut store 'node:1' { host = 'eu-west-1', active = true }
30 │ _ = kv/batch mut store [
31 │ kv/BatchOp { op = .put, key = 'cfg/mode', val = bytes/from-str 'production' }
32 │ kv/BatchOp { op = .put, key = 'cfg/temp', val = bytes/from-str 'drop-me' }
33 │ kv/BatchOp { op = .del, key = 'cfg/temp' }
34 │ ]
35 │ _ = kv/put-sealed mut store 'vault/api-key' enc_key (bytes/from-str 'sk-live-veko-999')
36 │ _ = kv/compact mut store
37 │ _ = kv/close mut store
38 │
39 │ // Reopen from disk and verify durable WAL replay, prefix scan, and sealed decryption
40 │ mut store2 = kv/open kv_path
41 │ node1 = kv/get-val store2 'node:1'
42 │ cfg_ks = kv/scan-prefix store2 'cfg/'
43 │ secret_len = kv/with-open-sealed store2 'vault/api-key' enc_key fn [pt] [ len pt ]
44 │ _ = kv/close mut store2
45 │ if node1.host != 'eu-west-1' or (len cfg_ks) != 1 or cfg_ks[0] != 'cfg/mode' or secret_len != 16 [
46 │ err 'example23: db/kv verification failed'
47 │ ]
48 │ println (str/join ['kv=ok|node=' node1.host '|sealed_len=' (mold secret_len)] '')
49 │
50 │ // 2. Pure-Veko PostgreSQL v3.0 Wire Protocol + SCRAM-SHA-256 Loopback Session
51 │ pg_ln = net/listen-tcp .ip '127.0.0.1:0'
52 │ pg_port = str/to-i64 (str/split (net/addr pg_ln) ':')[1]
53 │
54 │ pg_srv = spawn [
55 │ sock = net/accept pg_ln
56 │ defer [ _ = net/close/or sock [.ok] ]
57 │ mut st = inet/tcp-stream (as-i64 sock) 'pg-client'
58 │
59 │ // Read StartupMessage (4B len + payload)
60 │ lbuf = io/read mut st 4
61 │ slen = bytes/get-u32-be lbuf 0
62 │ _ = io/read mut st (slen - 4)
63 │
64 │ // Send AuthenticationSASL (code 10, 'SCRAM-SHA-256\0\0')
65 │ mut sasl_p = bytes/with-cap 32
66 │ _ = bytes/push-u32-be mut sasl_p 10
67 │ _ = bytes/push-all mut sasl_p (bytes/from-str 'SCRAM-SHA-256')
68 │ _ = bytes/push mut sasl_p 0
69 │ _ = bytes/push mut sasl_p 0
70 │ _ = io/write-all mut st (pg/encode-msg 82 sasl_p)
71 │
72 │ // Read SASLInitialResponse ('p')
73 │ m1 = pg/read-msg mut st
74 │ // Extract client-first after mech\0 + len(4B)
75 │ mut z0 = 0
76 │ while z0 < (len m1.body) and m1.body[z0] != 0 [ z0 = z0 + 1 ]
77 │ cf_str = bytes/to-str m1.body[(z0 + 5)..(len m1.body)]
78 │ cf_bare = cf_str[3..(len cf_str)]
79 │ // Extract client nonce r=...
80 │ ri = str/index-of cf_bare 'r='
81 │ cnonce = cf_bare[(ri + 2)..(len cf_bare)]
82 │ full_nonce = str/join [cnonce 'SRV99'] ''
83 │ salt = bytes/from-str 'veko-pg-salt-123'
84 │ iters = 64
85 │ sf_str = str/join ['r=' full_nonce ',s=' (hex/b64-encode salt) ',i=' (mold iters)] ''
86 │
87 │ // Send AuthenticationSASLContinue (code 11)
88 │ mut cont_p = bytes/with-cap (4 + (len sf_str))
89 │ _ = bytes/push-u32-be mut cont_p 11
90 │ _ = bytes/push-all mut cont_p (bytes/from-str sf_str)
91 │ _ = io/write-all mut st (pg/encode-msg 82 cont_p)
92 │
93 │ // Read SASLResponse ('p') and compute server-final v=<b64>
94 │ _ = pg/read-msg mut st
95 │ salted = kdf/pbkdf2-sha256 (bytes/from-str 'veko-pass') salt iters 32
96 │ server_key = sha/hmac-sha256 salted (bytes/from-str 'Server Key')
97 │ auth_msg = bytes/from-str (str/join [cf_bare ',' sf_str ',c=biws,r=' full_nonce] '')
98 │ srv_sig = sha/hmac-sha256 server_key auth_msg
99 │ sfin = str/join ['v=' (hex/b64-encode srv_sig)] ''
100 │ mut fin_p = bytes/with-cap (4 + (len sfin))
101 │ _ = bytes/push-u32-be mut fin_p 12
102 │ _ = bytes/push-all mut fin_p (bytes/from-str sfin)
103 │ _ = io/write-all mut st (pg/encode-msg 82 fin_p)
104 │
105 │ // Send AuthenticationOk (0) + ReadyForQuery ('Z', 'I')
106 │ mut ok_p = bytes/with-cap 4
107 │ _ = bytes/push-u32-be mut ok_p 0
108 │ _ = io/write-all mut st (pg/encode-msg 82 ok_p)
109 │ _ = io/write-all mut st (pg/encode-msg 90 (bytes/from-str 'I'))
110 │
111 │ // Handle 1 Simple Query ('Q') -> RowDescription ('T') + DataRow ('D') + CommandComplete ('C') + ReadyForQuery ('Z')
112 │ _ = pg/read-msg mut st
113 │ mut t_body = bytes/with-cap 32
114 │ _ = bytes/push-u16-be mut t_body 1
115 │ _ = bytes/push-all mut t_body (bytes/from-str 'engine')
116 │ _ = bytes/push mut t_body 0
117 │ _ = bytes/push-all mut t_body (bytes/fill 18 0)
118 │ _ = io/write-all mut st (pg/encode-msg 84 t_body)
119 │
120 │ val_b = bytes/from-str 'veko-pg-v3'
121 │ mut d_body = bytes/with-cap (6 + (len val_b))
122 │ _ = bytes/push-u16-be mut d_body 1
123 │ _ = bytes/push-u32-be mut d_body (len val_b)
124 │ _ = bytes/push-all mut d_body val_b
125 │ _ = io/write-all mut st (pg/encode-msg 68 d_body)
126 │
127 │ mut c_body = bytes/with-cap 16
128 │ _ = bytes/push-all mut c_body (bytes/from-str 'SELECT 1')
129 │ _ = bytes/push mut c_body 0
130 │ _ = io/write-all mut st (pg/encode-msg 67 c_body)
131 │ _ = io/write-all mut st (pg/encode-msg 90 (bytes/from-str 'I'))
132 │ _ = pg/read-msg/or mut st [ pg/PgMsg { tag = 88, body = bytes/with-cap 0 } ]
133 │ 'pg-ok'
134 │ ]
135 │
136 │ mut pg_st = inet/dial-tcp '127.0.0.1' pg_port
137 │ mut conn = pg/connect-stream mut pg_st 'veko' 'veko-pass' 'appdb'
138 │ qres = pg/query mut conn 'SELECT engine FROM status'
139 │ _ = pg/close mut conn
140 │ _ = task/await pg_srv
141 │ _ = net/close pg_ln
142 │
143 │ if (len qres.rows) != 1 or qres.columns[0] != 'engine' or qres.rows[0][0] != 'veko-pg-v3' [
144 │ err 'example23: postgres query failed'
145 │ ]
146 │ println (str/join ['postgres=scram-sha-256|' qres.columns[0] '=' (str/append qres.rows[0][0] '')] '')
147 │
148 │ // 3. Pure-Veko Redis RESP3 Loopback Session + Pipelining
149 │ rd_ln = net/listen-tcp .ip '127.0.0.1:0'
150 │ rd_port = str/to-i64 (str/split (net/addr rd_ln) ':')[1]
151 │
152 │ rd_srv = spawn [
153 │ sock = net/accept rd_ln
154 │ defer [ _ = net/close/or sock [.ok] ]
155 │ mut st = inet/tcp-stream (as-i64 sock) 'redis-cli'
156 │ mut kv_mem = {}
157 │ mut rx = bytes/with-cap 0
158 │ mut handled = 0
159 │ while handled < 3 [
160 │ chunk = io/read mut st 4096
161 │ if (len chunk) == 0 [ break ]
162 │ _ = bytes/push-all mut rx chunk
163 │ mut progress = true
164 │ while progress and (len rx) > 0 [
165 │ dec = redis/decode-bytes rx
166 │ if err? dec [
167 │ progress = false
168 │ ] else [
169 │ rx = rx[dec.consumed..(len rx)]
170 │ argv = dec.value
171 │ op = str/upper (str/append argv[0] '')
172 │ if op == 'PING' [
173 │ _ = io/write-all mut st (bytes/from-str '+PONG\r\n')
174 │ ] else [
175 │ if op == 'SET' [
176 │ map/set mut kv_mem (str/append argv[1] '') (str/append argv[2] '')
177 │ _ = io/write-all mut st (bytes/from-str '+OK\r\n')
178 │ ] else [
179 │ if op == 'GET' [
180 │ k = str/append argv[1] ''
181 │ v = if map/has? kv_mem k [ map/get kv_mem k ] else [ .null ]
182 │ _ = io/write-all mut st (redis/encode-value v)
183 │ ]
184 │ ]
185 │ ]
186 │ handled = handled + 1
187 │ ]
188 │ ]
189 │ ]
190 │ handled
191 │ ]
192 │
193 │ mut rd_st = inet/dial-tcp '127.0.0.1' rd_port
194 │ mut rcli = redis/from-stream rd_st
195 │ replies = redis/pipeline mut rcli [
196 │ ['PING']
197 │ ['SET' 'lang' 'veko']
198 │ ['GET' 'lang']
199 │ ]
200 │ _ = redis/close mut rcli
201 │ _ = task/await rd_srv
202 │ _ = net/close rd_ln
203 │
204 │ if replies[0] != 'PONG' or replies[1] != 'OK' or replies[2] != 'veko' [
205 │ err 'example23: redis RESP3 pipeline failed'
206 │ ]
207 │ println (str/join ['redis=resp3|' (str/append replies[0] '') '|' (str/append replies[2] '')] '')
208 │
209 │ // 4. Zero-FFI Sidecar RPC Envelope (`VKSC` + CRC-32 + `codec/vbin`)
210 │ sreq = sc/SidecarReq { id = 101, method = 'sqlite.exec', params = { sql = 'SELECT 42' } }
211 │ sresp = sc/SidecarResp { id = 101, ok = true, result = [42], error_msg = '' }
212 │ dec_sreq = sc/decode-req (sc/encode-req sreq)
213 │ dec_sresp = sc/decode-resp (sc/encode-resp sresp)
214 │ if dec_sreq.method != 'sqlite.exec' or not dec_sresp.ok or dec_sresp.result[0] != 42 [
215 │ err 'example23: sidecar framing failed'
216 │ ]
217 │ println (str/join ['sidecar=vksc|' dec_sreq.method '|res=' (mold dec_sresp.result[0])] '')Example 24: 24_signed_vkp_package_bundles.vk
Run command: veko -A examples/24_signed_vkp_package_bundles.vk
Example 24: Signed 'VKP1' Package Bundles (Merkle Tree + Hybrid Ed25519 & Post-Quantum ML-DSA-65) Demonstrates packing a multi-module Veko package into a single-file 'VKP1' archive, dual-signing with Ed25519 + FIPS 204 ML-DSA-65, verifying trust anchors, extracting modules, and rejecting both tampered bytes and untrusted keys. Track C (Native) : veko compile --native examples/24_signed_vkp_package_bundles.vk -o dist/24.exe ; ./dist/24.exe
1 │ // Example 24: Signed `'VKP1'` Package Bundles (Merkle Tree + Hybrid Ed25519 & Post-Quantum ML-DSA-65)
2 │ // Demonstrates packing a multi-module Veko package into a single-file `'VKP1'` archive,
3 │ // dual-signing with Ed25519 + FIPS 204 ML-DSA-65, verifying trust anchors, extracting modules,
4 │ // and rejecting both tampered bytes and untrusted keys.
5 │ //
6 │ // Track A (ORO VM) : veko run examples/24_signed_vkp_package_bundles.vk
7 │ // Track B (Wasm 3) : veko run --wasm --check-slabs --fuel=0 examples/24_signed_vkp_package_bundles.vk
8 │ // Track C (Native) : veko compile --native examples/24_signed_vkp_package_bundles.vk -o dist/24.exe ; ./dist/24.exe
9 │
10 │ use [
11 │ hex = codec/hex
12 │ x25 = crypto/x25519
13 │ dsa = crypto/mldsa
14 │ vkp = pkg/vkp
15 │ ]
16 │
17 │ // 1. Generate classical Ed25519 + post-quantum ML-DSA-65 signing keys
18 │ ed_seed = bytes/from-str 'vkp1-example-ed25519-seed-012345'
19 │ ed_pk = x25/ed25519-pubkey ed_seed
20 │ pq_kp = dsa/keygen .mldsa65
21 │
22 │ manifest = {
23 │ name = 'veko-stats'
24 │ version = '1.0.0'
25 │ description = 'Pure-Veko descriptive statistics package'
26 │ }
27 │ files = {
28 │ 'mod.vk' = 'use [st = math/stats]\npub mean = fn [xs block] i64 [ st/avg xs ]\n'
29 │ 'math/stats.vk' = 'pub avg = fn [xs block] i64 [ (xs[0] + xs[1]) / 2 ]\n'
30 │ }
31 │
32 │ // 2. Pack and hybrid dual-sign (Ed25519 + ML-DSA-65)
33 │ bundle_bytes = vkp/pack manifest files ed_seed pq_kp
34 │ ed_trust = vkp/format-trust-key .ed25519 ed_pk
35 │ pq_trust = vkp/format-trust-key .mldsa65 pq_kp.pk
36 │
37 │ // 3. Verify against trusted Ed25519 and ML-DSA-65 keys
38 │ verified_ed = vkp/verify bundle_bytes [ed_trust]
39 │ verified_pq = vkp/verify bundle_bytes [pq_trust]
40 │ if (len verified_ed.entries) != 2 or (len verified_pq.signatures) != 2 [
41 │ err 'example24: vkp verify failed'
42 │ ]
43 │ mod_src = vkp/extract-module verified_pq 'math/stats.vk'
44 │ if not (str/contains? mod_src 'pub avg') [
45 │ err 'example24: extract-module failed'
46 │ ]
47 │
48 │ // 4. Tamper detection: flip 1 byte in payload -> rejected by SHA-256 / Merkle / signature check
49 │ mut tampered = bytes/with-cap (len bundle_bytes)
50 │ _ = bytes/push-all mut tampered bundle_bytes
51 │ flip_pos = (len tampered) / 2
52 │ _ = bytes/set mut tampered flip_pos ((tampered[flip_pos]) ^ 0x01)
53 │ tamper_ok = vkp/verify/or tampered [ed_trust] [ .rejected ]
54 │ if tamper_ok != .rejected [
55 │ err 'example24: tampered bundle was not rejected'
56 │ ]
57 │
58 │ // 5. Trust-anchor enforcement: valid bundle signed by unknown key -> rejected
59 │ other_seed = bytes/from-str 'untrusted-other-ed25519-seed-999'
60 │ other_trust = vkp/format-trust-key .ed25519 (x25/ed25519-pubkey other_seed)
61 │ untrusted_ok = vkp/verify/or bundle_bytes [other_trust] [ .rejected ]
62 │ if untrusted_ok != .rejected [
63 │ err 'example24: untrusted key was not rejected'
64 │ ]
65 │
66 │ println (str/join ['vkp1=ok|bytes=' (mold (len bundle_bytes)) '|entries=' (mold (len verified_pq.entries)) '|sigs=Ed25519+ML-DSA-65|merkle=' (hex/encode verified_pq.merkle_root)[0..16]] '')
67 │ println 'security=tamper-rejected|untrusted-key-rejected'Example 25: 25_batteries_datetime_fs_archives_and_toml.vk
Run command: veko -A examples/25_batteries_datetime_fs_archives_and_toml.vk
Example 25: Batteries-Included Stdlib — DateTime, UTF-8, FS, Slog, Tar/Zip, TOML, IP/CIDR, SemVer, TOTP, Diff & Retry Demonstrates all pure-Veko Tier 1 & Tier 2 utility batteries with consistent SVO APIs. Track C (Native) : veko compile --native examples/25_batteries_datetime_fs_archives_and_toml.vk -o dist/25.exe ; ./dist/25.exe
1 │ // Example 25: Batteries-Included Stdlib — DateTime, UTF-8, FS, Slog, Tar/Zip, TOML, IP/CIDR, SemVer, TOTP, Diff & Retry
2 │ // Demonstrates all pure-Veko Tier 1 & Tier 2 utility batteries with consistent SVO APIs.
3 │ //
4 │ // Track A (ORO VM) : veko run examples/25_batteries_datetime_fs_archives_and_toml.vk
5 │ // Track B (Wasm 3) : veko run --wasm --check-slabs --fuel=0 --allow-fs=. examples/25_batteries_datetime_fs_archives_and_toml.vk
6 │ // Track C (Native) : veko compile --native examples/25_batteries_datetime_fs_archives_and_toml.vk -o dist/25.exe ; ./dist/25.exe
7 │
8 │ use [
9 │ dt = datetime
10 │ utf8
11 │ fs
12 │ slog
13 │ tar = archive/tar
14 │ zip = archive/zip
15 │ toml = codec/toml
16 │ ip = net/ip
17 │ sv = semver
18 │ totp = auth/totp
19 │ diff
20 │ retry
21 │ ]
22 │
23 │ // 1. Calendar DateTime (RFC 3339 & HTTP IMF-fixdate)
24 │ t_parsed = dt/parse-rfc3339 '2026-12-02T14:30:00Z'
25 │ t_next = t_parsed \ dt/add-days 7 \ dt/with-offset 3600
26 │ http_d = dt/format-http t_parsed
27 │ if (dt/format-rfc3339 t_next) != '2026-12-09T15:30:00+01:00' or http_d != 'Wed, 02 Dec 2026 14:30:00 GMT' [
28 │ err 'example25: datetime mismatch'
29 │ ]
30 │ println (str/join ['datetime=' (dt/format-rfc3339 t_next) '|http=' http_d] '')
31 │
32 │ // 2. UTF-8 multi-byte codepoints & safe rune slicing
33 │ greek = utf8/from-runes [86 101 107 111 32 0x03BB 0x03A9] // 'Veko <lambda><Omega>'
34 │ sliced = utf8/rune-slice greek 5 7
35 │ if (not (utf8/valid? (bytes/from-str greek))) or (utf8/rune-count greek) != 7 or (utf8/runes sliced) != [0x03BB 0x03A9] [
36 │ err 'example25: utf8 mismatch'
37 │ ]
38 │ println (str/join ['utf8=ok|runes=' (mold (utf8/rune-count greek))] '')
39 │
40 │ // 3. Ergonomic FS (`with-temp-dir`, `mkdir-all`, `write-atomic`, `copy-file`, `glob-dir`)
41 │ fs_count = fs/with-temp-dir 'veko_ex25' fn [dir] [
42 │ sub_d = str/join [dir '/cfg/nested'] ''
43 │ _ = fs/mkdir-all sub_d
44 │ f1 = str/join [dir '/app.toml'] ''
45 │ f2 = str/join [sub_d '/copy.toml'] ''
46 │ _ = fs/write-atomic f1 (bytes/from-str 'mode = "prod"\n')
47 │ _ = fs/copy-file f1 f2
48 │ len (fs/glob-dir dir '*.toml')
49 │ ]
50 │ if fs_count != 2 [ err 'example25: fs helper mismatch' ]
51 │ println (str/join ['fs=ok|glob_toml=' (mold fs_count)] '')
52 │
53 │ // 4. Structured Logger (`slog`: JSON & kv with contextual child fields)
54 │ lg = (slog/new-json .info) \ slog/with-fields { service = 'edge-api', region = 'eu-west' }
55 │ log_line = slog/format-line lg .info 'boot complete' { port = 8443 }
56 │ log_obj = json/decode log_line
57 │ if log_obj.level != 'INFO' or log_obj.service != 'edge-api' or log_obj.port != 8443 [
58 │ err 'example25: slog mismatch'
59 │ ]
60 │ println (str/join ['slog=ok|level=' log_obj.level '|service=' log_obj.service] '')
61 │
62 │ // 5. Archives (`.tar.gz` and `.zip` with DEFLATE + CRC-32)
63 │ tgz = tar/pack-gz [
64 │ tar/TarEntry { path = 'manifest.toml', data = bytes/from-str 'name = "veko"\n' }
65 │ tar/TarEntry { path = 'src/main.vk', data = bytes/from-str 'println "hi"\n' }
66 │ ]
67 │ tar_out = tar/unpack-gz tgz
68 │ zp = zip/pack [
69 │ zip/ZipEntry { path = 'notes.txt', data = bytes/from-str 'veko zip payload veko zip payload veko zip payload' }
70 │ ]
71 │ zip_out = zip/unpack zp
72 │ if (len tar_out) != 2 or (len zip_out) != 1 or (bytes/to-str zip_out[0].data) != 'veko zip payload veko zip payload veko zip payload' [
73 │ err 'example25: archive mismatch'
74 │ ]
75 │ println (str/join ['archives=tar.gz(' (mold (len tgz)) 'B)+zip(' (mold (len zp)) 'B)'] '')
76 │
77 │ // 6. TOML v1.0 config decode & round-trip encode
78 │ cfg_src = 'app = "veko-node"\n[server]\nhost = "127.0.0.1"\nport = 8_443\nworkers = 4\ntls = true\n'
79 │ cfg = toml/decode cfg_src
80 │ re_cfg = toml/decode (toml/encode cfg)
81 │ if re_cfg.app != 'veko-node' or re_cfg.server.port != 8443 or re_cfg.server.tls != true [
82 │ err 'example25: toml mismatch'
83 │ ]
84 │ println (str/join ['toml=ok|app=' re_cfg.app '|port=' (mold re_cfg.server.port)] '')
85 │
86 │ // 7. IPv4/IPv6 CIDR, SemVer 2.0, TOTP 2FA, Unified Diff, & Retry/RateLimiter
87 │ cidr6 = ip/parse-cidr '2001:db8::/32'
88 │ addr6 = ip/parse '2001:0db8:0000:0000::0042'
89 │ ver = sv/parse 'v1.4.0'
90 │ totp_sec = bytes/from-str '12345678901234567890'
91 │ otp = totp/totp-at totp_sec 59 30 .sha1 6
92 │ udiff = diff/format-unified 'old.vk' 'new.vk' 'a = 1\nb = 2' 'a = 1\nb = 9'
93 │ ropts = retry/RetryOpts { max_attempts = 3, base_delay = 1ms, max_delay = 5ms, jitter_pct = 0 }
94 │ r_res = retry/run ropts fn [n] [ if n < 1 [ err 'transient' ] else [ 'recovered' ] ]
95 │ mut rl = retry/RateLimiter { capacity = 1, tokens = 1, refill_per_sec = 5, last_ns = 0 }
96 │ rl_ok = (retry/allow-at? mut rl 1 0) and (not (retry/allow-at? mut rl 1 0))
97 │
98 │ if (not (ip/contains? cidr6 addr6)) or (ip/format addr6) != '2001:db8::42' or (not (sv/satisfies? ver '^1.2.0')) or otp != '287082' or (not (str/contains? udiff '+b = 9')) or r_res != 'recovered' or (not rl_ok) [
99 │ err 'example25: tier2 battery check failed'
100 │ ]
101 │ println (str/join ['tier2=ip(' (ip/format addr6) ')+semver(' (sv/format ver) ')+totp(' otp ')+diff+retry(' r_res ')'] '')Example 26: 26_pure_vk_html_components_and_http_client.vk
Run command: veko -A examples/26_pure_vk_html_components_and_http_client.vk
Example 26: Pure-Veko HTML5 Component DSL (lib/html), Safe Templates (lib/template) & Unified HTTP Client (lib/net/client) Demonstrates building reusable pure-Veko UI components (both homoiconic Hiccup blocks and typed builders), serving them via web/page & web/view with gzip compression and redirects, and consuming them with the 3-track pure-Veko net/client (hc/get, hc/post-json). Track C (Native) : veko compile --native examples/26_pure_vk_html_components_and_http_client.vk -o dist/26.exe ; ./dist/26.exe
1 │ // Example 26: Pure-Veko HTML5 Component DSL (`lib/html`), Safe Templates (`lib/template`) & Unified HTTP Client (`lib/net/client`)
2 │ // Demonstrates building reusable pure-Veko UI components (both homoiconic Hiccup blocks and
3 │ // typed builders), serving them via `web/page` & `web/view` with gzip compression and redirects,
4 │ // and consuming them with the 3-track pure-Veko `net/client` (`hc/get`, `hc/post-json`).
5 │ //
6 │ // Track A (ORO VM) : veko run --allow-net --allow-listen --allow-private-net examples/26_pure_vk_html_components_and_http_client.vk
7 │ // Track B (Wasm 3) : veko run --wasm --check-slabs --fuel=0 --allow-net --allow-listen --allow-private-net examples/26_pure_vk_html_components_and_http_client.vk
8 │ // Track C (Native) : veko compile --native examples/26_pure_vk_html_components_and_http_client.vk -o dist/26.exe ; ./dist/26.exe
9 │
10 │ use [
11 │ html
12 │ tpl = template
13 │ deflate = compress/deflate
14 │ web
15 │ hc = net/client
16 │ ]
17 │
18 │ // Reusable pure-Veko UI components (auto-escaping XSS by default!)
19 │ badge-comp = fn [label str, kind str] block [
20 │ [.span { class = (str/join ['badge badge-' kind] '') } [label]]
21 │ ]
22 │
23 │ service-card = fn [name str, status str, tags block] html/Node [
24 │ html/article { class = 'card' } [
25 │ (html/h2 {} [(html/text name)])
26 │ (badge-comp status (if status == 'healthy' [ 'ok' ] else [ 'warn' ]))
27 │ (html/ul { class = 'tags' } (map tags fn [t] [ [.li [t]] ]))
28 │ ]
29 │ ]
30 │
31 │ dashboard-page = fn [viewer str, services block] html/Node [
32 │ html/document 'Veko Control Plane' [
33 │ (html/style-el 'body{font-family:system-ui}.card{border:1px solid #ddd;padding:12px}')
34 │ ] [
35 │ [.header { class = 'topbar' } [
36 │ [.h1 ['Veko Services']]
37 │ [.p ['Signed in as: ' viewer]]
38 │ ]]
39 │ [.main { class = 'grid' } (map services fn [s] [
40 │ service-card s.name s.status s.tags
41 │ ])]
42 │ ]
43 │ ]
44 │
45 │ // 1. Render component tree and verify automatic XSS escaping
46 │ xss_html = html/render (dashboard-page '<script>alert(1)</script>' [
47 │ { name = 'gateway', status = 'healthy', tags = ['tls13-pqc' 'http2'] }
48 │ { name = 'vault', status = 'healthy', tags = ['aes256-gcm' 'wal'] }
49 │ ])
50 │ if (not (str/contains? xss_html '<script>alert(1)</script>')) or (not (str/contains? xss_html '<li>tls13-pqc</li>')) [
51 │ err 'example26: html component rendering failed'
52 │ ]
53 │ println (str/join ['html_dsl=ok|bytes=' (mold (len xss_html))] '')
54 │
55 │ // 2. Safe HTML template rendering (`template/render-html`)
56 │ t_out = tpl/render-html '<div>{{ title }}: {{#each items}}[{{ . }}]{{/each}}</div>' {
57 │ title = 'Nodes & Peers'
58 │ items = ['eu-1' 'us-2']
59 │ }
60 │ if t_out != '<div>Nodes & Peers: [eu-1][us-2]</div>' [
61 │ err 'example26: template rendering failed'
62 │ ]
63 │ println (str/join ['template=' t_out] '')
64 │
65 │ // 3. Live loopback `web/page` + `302` redirect + `gzip` response + `net/client` (`hc/get` & `hc/post-json`)
66 │ ln = net/listen-tcp .ip '127.0.0.1:0'
67 │ port = str/to-i64 (str/split (net/addr ln) ':')[1]
68 │
69 │ srv = spawn [
70 │ mut app = web/new-app
71 │ web/use-security-headers mut app
72 │ web/get mut app '/old' fn [req web/Request] web/Response [
73 │ _ = req
74 │ web/redirect 302 '/dashboard'
75 │ ]
76 │ web/get mut app '/dashboard' fn [req web/Request] web/Response [
77 │ _ = req
78 │ doc = dashboard-page 'Ada' [
79 │ { name = 'edge-proxy', status = 'healthy', tags = ['oro' 'pqc'] }
80 │ ]
81 │ gz = deflate/gzip-compress (bytes/from-str (html/render doc))
82 │ mut r = web/response 200 'text/html; charset=utf-8' gz
83 │ mut hdrs = r.headers
84 │ map/set mut hdrs 'Content-Encoding' 'gzip'
85 │ put mut r .headers hdrs
86 │ r
87 │ ]
88 │ web/post mut app '/api/echo' fn [req web/Request] web/Response [
89 │ body_m = web/bind-json req
90 │ web/json-resp 201 { echoed = body_m.msg, framework = 'veko/web' }
91 │ ]
92 │ // Serve 3 sequential requests: GET /old -> GET /dashboard -> POST /api/echo
93 │ _ = web/serve-loop ln app 3
94 │ 'served-3'
95 │ ]
96 │
97 │ base = str/join ['http://127.0.0.1:' (mold port)] ''
98 │ r_dash = hc/get (str/join [base '/old'] '') (hc/RequestOpts { timeout = 5s })
99 │ dash_txt = hc/text-body r_dash
100 │ if r_dash.status != 200 or (not (str/contains? r_dash.final_url '/dashboard')) or (not (str/contains? dash_txt '<h2>edge-proxy</h2>')) [
101 │ err 'example26: net/client redirect + gzip html failed'
102 │ ]
103 │
104 │ r_post = hc/post-json (str/join [base '/api/echo'] '') { msg = 'hello-pure-veko' } (hc/RequestOpts { timeout = 5s })
105 │ j_post = hc/json-body r_post
106 │ _ = task/await srv
107 │ _ = net/close ln
108 │
109 │ if r_post.status != 201 or j_post.echoed != 'hello-pure-veko' or j_post.framework != 'veko/web' [
110 │ err 'example26: net/client post-json failed'
111 │ ]
112 │ println (str/join ['client_redirect_gzip=' (mold r_dash.status) '|final=/dashboard|post_json=' (mold r_post.status) ':' j_post.echoed] '')Example 27: 27_tooling_fmt_lsp_and_v2vk.vk
Run command: veko -A examples/27_tooling_fmt_lsp_and_v2vk.vk
Example 27: Developer Tooling Ecosystem — veko fmt, veko lsp (JSON-RPC 2.0) & veko v2vk Demonstrates invoking the self-hosted formatter, native LSP protocol handlers (initialize, didOpen diagnostics, hover, definition, completion, formatting, quick-fix), and assisted V-to-Veko source migration directly in pure Veko. Track C (Native) : veko compile --native examples/27_tooling_fmt_lsp_and_v2vk.vk -o dist/27.exe ; ./dist/27.exe
1 │ // Example 27: Developer Tooling Ecosystem — `veko fmt`, `veko lsp` (JSON-RPC 2.0) & `veko v2vk`
2 │ // Demonstrates invoking the self-hosted formatter, native LSP protocol handlers
3 │ // (initialize, didOpen diagnostics, hover, definition, completion, formatting, quick-fix),
4 │ // and assisted V-to-Veko source migration directly in pure Veko.
5 │ //
6 │ // Track A (ORO VM) : veko run examples/27_tooling_fmt_lsp_and_v2vk.vk
7 │ // Track C (Native) : veko compile --native examples/27_tooling_fmt_lsp_and_v2vk.vk -o dist/27.exe ; ./dist/27.exe
8 │
9 │ use [
10 │ fcmd = fmt_cmd
11 │ lsp = lsp_cmd
12 │ v2vk = v2vk_cmd
13 │ mig = migrate_cmd
14 │ ]
15 │
16 │ // 1. Canonical formatter (`fmt_cmd/format-source`) + idempotency
17 │ messy = ' // Demo function\nadd-pair = fn [a i64, b i64] i64 [\n mut sum = a + b \n\n\n sum\n ]\n'
18 │ clean1 = fcmd/format-source messy
19 │ clean2 = fcmd/format-source clean1
20 │ if clean1 != clean2 or (not (str/contains? clean1 '\tmut sum = a + b\n')) [
21 │ err 'example27: formatter idempotency failed'
22 │ ]
23 │ println (str/join ['fmt=ok|idempotent=true|bytes=' (mold (len clean1))] '')
24 │
25 │ // 2. Native LSP JSON-RPC 2.0 session (initialize, didOpen, hover, definition, completion, symbols, formatting, codeAction)
26 │ mut st = lsp/new-state
27 │ init_out = lsp/handle-message mut st {
28 │ jsonrpc = '2.0', id = 1, method = 'initialize', params = {}
29 │ }
30 │ if (len init_out) != 1 or init_out[0].result.serverInfo.name != 'veko-lsp' [
31 │ err 'example27: lsp initialize failed'
32 │ ]
33 │
34 │ uri = 'file:///demo/service.vk'
35 │ doc_src = '// Computes double.\ndouble-it = fn [n i64] i64 [\n n * 2\n]\nres = double-it 21\n'
36 │ open_out = lsp/handle-message mut st {
37 │ jsonrpc = '2.0'
38 │ method = 'textDocument/didOpen'
39 │ params = { textDocument = { uri = uri, languageId = 'veko', version = 1, text = doc_src } }
40 │ }
41 │ if (len open_out[0].params.diagnostics) != 0 [
42 │ err 'example27: expected 0 diagnostics on valid doc'
43 │ ]
44 │
45 │ hov_out = lsp/handle-message mut st {
46 │ jsonrpc = '2.0', id = 2, method = 'textDocument/hover'
47 │ params = { textDocument = { uri = uri }, position = { line = 4, character = 8 } }
48 │ }
49 │ def_out = lsp/handle-message mut st {
50 │ jsonrpc = '2.0', id = 3, method = 'textDocument/definition'
51 │ params = { textDocument = { uri = uri }, position = { line = 4, character = 8 } }
52 │ }
53 │ sym_out = lsp/handle-message mut st {
54 │ jsonrpc = '2.0', id = 4, method = 'textDocument/documentSymbol'
55 │ params = { textDocument = { uri = uri } }
56 │ }
57 │ fmt_out = lsp/handle-message mut st {
58 │ jsonrpc = '2.0', id = 5, method = 'textDocument/formatting'
59 │ params = { textDocument = { uri = uri } }
60 │ }
61 │ if (not (str/contains? hov_out[0].result.contents.value 'Computes double')) or def_out[0].result.range.start.line != 1 or (len sym_out[0].result) < 2 or (len fmt_out[0].result) != 1 [
62 │ err 'example27: lsp hover/def/sym/fmt failed'
63 │ ]
64 │
65 │ // Test diagnostic + 1-click quickfix codeAction on typo
66 │ bad_uri = 'file:///demo/typo.vk'
67 │ bad_out = lsp/handle-message mut st {
68 │ jsonrpc = '2.0'
69 │ method = 'textDocument/didOpen'
70 │ params = { textDocument = { uri = bad_uri, languageId = 'veko', version = 1, text = 'count = 10\nx = coumt + 1\n' } }
71 │ }
72 │ ca_out = lsp/handle-message mut st {
73 │ jsonrpc = '2.0', id = 6, method = 'textDocument/codeAction'
74 │ params = { textDocument = { uri = bad_uri }, context = { diagnostics = bad_out[0].params.diagnostics } }
75 │ }
76 │ if (len bad_out[0].params.diagnostics) == 0 or (len ca_out[0].result) == 0 [
77 │ err 'example27: lsp diagnostics/codeAction failed'
78 │ ]
79 │ println (str/join ['lsp=ok|hover=true|def_line=' (mold def_out[0].result.range.start.line) '|symbols=' (mold (len sym_out[0].result)) '|quickfix=' ca_out[0].result[0].title] '')
80 │
81 │ // 3. Assisted V-to-Veko migration (`v2vk_cmd/translate-v-source`)
82 │ v_sample = 'module demo\nimport os\npub struct User {\n name string\n age int = 18\n}\npub fn greet(u User) string {\n msg := os.read_file(\'hi.txt\') or { \'fallback\' }\n if u.age >= 18 {\n return msg\n } else {\n return \'minor\'\n }\n}\n'
83 │ vk_out = v2vk/translate-v-source v_sample
84 │ if (not (str/contains? vk_out 'pub User = struct {')) or (not (str/contains? vk_out 'pub greet = fn [u User] str [')) or (not (str/contains? vk_out '/or')) or (not (str/contains? vk_out 'TODO(v2vk)')) [
85 │ err 'example27: v2vk migration failed'
86 │ ]
87 │ println (str/join ['v2vk=ok|migrated_bytes=' (mold (len vk_out))] '')
88 │
89 │ // 4. Assisted Go, Python, & Rust migration with automatic stdlib & popular dependency mapping
90 │ go_sample = 'package svc\nimport (\n "net/http"\n "time"\n "github.com/golang-jwt/jwt/v5"\n)\ntype Config struct {\n Host string\n Port int\n}\nfunc Fetch(u string) (string, error) {\n defer fmt.Println("done")\n res := http.Get(u)\n return res\n}\n'
91 │ go_vk = mig/translate-go-source go_sample
92 │ if (not (str/contains? go_vk 'hc = net/client')) or (not (str/contains? go_vk 'jwt = auth/jwt')) or (not (str/contains? go_vk 'pub Config = struct {')) or (not (str/contains? go_vk 'defer [')) [
93 │ err 'example27: go2vk migration failed'
94 │ ]
95 │
96 │ py_sample = 'import requests\nimport tomllib\nfrom dataclasses import dataclass\n@dataclass\nclass Node:\n host: str\n port: int = 8080\ndef fetch_node(u: str) -> str:\n # Fetch endpoint\n r = requests.get(u)\n return r\n'
97 │ py_vk = mig/translate-py-source py_sample
98 │ if (not (str/contains? py_vk 'hc = net/client')) or (not (str/contains? py_vk 'toml = codec/toml')) or (not (str/contains? py_vk 'pub Node = struct {')) or (not (str/contains? py_vk 'pub fetch_node = fn [u str] str [')) [
99 │ err 'example27: py2vk migration failed'
100 │ ]
101 │
102 │ rs_sample = 'use reqwest::Client;\nuse sha2::Sha256;\nuse std::fs;\n#[derive(Debug)]\npub struct Peer {\n pub host: String,\n pub port: i64,\n}\npub fn read_cfg(p: &str, buf: &mut Vec<u8>) -> Result<String, String> {\n let raw = fs::read_to_string(p);\n return raw;\n}\n'
103 │ rs_vk = mig/translate-rs-source rs_sample
104 │ if (not (str/contains? rs_vk 'hc = net/client')) or (not (str/contains? rs_vk 'sha = crypto/sha256')) or (not (str/contains? rs_vk 'pub Peer = struct {')) or (not (str/contains? rs_vk 'mut buf bytes')) [
105 │ err 'example27: rs2vk migration failed'
106 │ ]
107 │ println (str/join ['migrate=ok|go=' (mold (len go_vk)) 'B|py=' (mold (len py_vk)) 'B|rs=' (mold (len rs_vk)) 'B'] '')Example 28: 28_simd_optimization_and_arm64_cross_compile.vk
Run command: veko -A examples/28_simd_optimization_and_arm64_cross_compile.vk
Example 28: Phase 5 No-JIT Hardware Intrinsics, Bulk SIMD Bytes & Cross-Target Verification Demonstrates the 6 Phase 5 hardware/bulk builtins across all 3 execution tracks (f64/sqrt, bytes/eq, bytes/index-of, bytes/xor, bytes/xor!, bytes/aes-enc-block), NIST FIPS-197 AES-128 & AES-256 Known-Answer Tests, AES-256-GCM AEAD round-trip, and IEEE 802.3 Sarwate table-driven bits/crc32. Cross AArch64 : veko compile --native --target=linux-arm64 examples/28_simd_optimization_and_arm64_cross_compile.vk -o dist/28_arm64 Cross macOS arm64: veko compile --native --target=macos-arm64 examples/28_simd_optimization_and_arm64_cross_compile.vk -o dist/28_macos
1 │ // Example 28: Phase 5 No-JIT Hardware Intrinsics, Bulk SIMD Bytes & Cross-Target Verification
2 │ // Demonstrates the 6 Phase 5 hardware/bulk builtins across all 3 execution tracks
3 │ // (`f64/sqrt`, `bytes/eq`, `bytes/index-of`, `bytes/xor`, `bytes/xor!`, `bytes/aes-enc-block`),
4 │ // NIST FIPS-197 AES-128 & AES-256 Known-Answer Tests, AES-256-GCM AEAD round-trip,
5 │ // and IEEE 802.3 Sarwate table-driven `bits/crc32`.
6 │ //
7 │ // Track A (ORO VM) : veko run examples/28_simd_optimization_and_arm64_cross_compile.vk
8 │ // Track B (Wasm3) : veko run --wasm --fuel=0 examples/28_simd_optimization_and_arm64_cross_compile.vk
9 │ // Track C (Native) : veko run --native examples/28_simd_optimization_and_arm64_cross_compile.vk
10 │ // Cross AArch64 : veko compile --native --target=linux-arm64 examples/28_simd_optimization_and_arm64_cross_compile.vk -o dist/28_arm64
11 │ // Cross macOS arm64: veko compile --native --target=macos-arm64 examples/28_simd_optimization_and_arm64_cross_compile.vk -o dist/28_macos
12 │
13 │ use [
14 │ m = math
15 │ bits
16 │ hex = codec/hex
17 │ aes = crypto/aes
18 │ ]
19 │
20 │ must = fn [cond bool, msg str] [
21 │ if not cond [
22 │ println (str/join ['FAIL: ' msg] '')
23 │ os/exit 1
24 │ ]
25 │ .ok
26 │ ]
27 │
28 │ // 1. Hardware IEEE-754 square root (`f64/sqrt` -> SQRTSD / FSQRT / f64.sqrt)
29 │ s81 = f64/sqrt 81.0
30 │ s2 = f64/sqrt 2.0
31 │ s0 = f64/sqrt 0.0
32 │ m2 = m/sqrt 2.0
33 │ must (s81 == 9.0 and s0 == 0.0) 'f64/sqrt exact values'
34 │ must ((abs (s2 - 1.4142135623730951)) < 0.000000000001 and (abs (m2 - s2)) < 0.000000000001) 'f64/sqrt vs math/sqrt parity'
35 │ println 'sqrt=ok|f64_sqrt_81=9.0|math_sqrt_parity=true'
36 │
37 │ // 2. Bulk SIMD / 8-byte word-wide buffer builtins (`bytes/eq`, `bytes/index-of`, `bytes/xor`, `bytes/xor!`)
38 │ // Exercise 96-byte buffers so x86_64 AVX2/SSE2 (32B/16B lanes) and ARM64 8B word loops both run.
39 │ mut buf_a = bytes/with-cap 96
40 │ mut buf_b = bytes/with-cap 96
41 │ mut key_buf = bytes/with-cap 96
42 │ mut i = 0
43 │ while i < 96 [
44 │ _ = bytes/push mut buf_a ((i * 7 + 13) & 0xff)
45 │ _ = bytes/push mut buf_b ((i * 7 + 13) & 0xff)
46 │ _ = bytes/push mut key_buf ((i * 19 + 5) & 0xff)
47 │ i = i + 1
48 │ ]
49 │
50 │ must (bytes/eq buf_a buf_b) 'bytes/eq equal 96B buffers'
51 │ _ = bytes/set mut buf_b 95 ((buf_b[95] ^ 1) & 0xff)
52 │ must (not (bytes/eq buf_a buf_b)) 'bytes/eq detects trailing-byte diff'
53 │
54 │ // Search with `bytes/index-of` across >64B haystack
55 │ hay = bytes/from-str 'veko-simd-acceleration-pipeline-zero-jit-deterministic-memory-sentinel-99-tail'
56 │ pos_mid = bytes/index-of hay (bytes/from-str 'sentinel-99')
57 │ pos_head = bytes/index-of hay (bytes/from-str 'veko-simd')
58 │ pos_miss = bytes/index-of hay (bytes/from-str 'not-present')
59 │ pos_empty = bytes/index-of hay (bytes/with-cap 0)
60 │ must (pos_head == 0 and pos_mid == 62 and pos_miss == -1 and pos_empty == 0) 'bytes/index-of positions'
61 │
62 │ // Functional `bytes/xor` and in-place ORO `bytes/xor!` round-trip
63 │ xored = bytes/xor buf_a key_buf
64 │ restored = bytes/xor xored key_buf
65 │ must ((not (bytes/eq xored buf_a)) and (bytes/eq restored buf_a)) 'bytes/xor round-trip'
66 │ mut in_place = bytes/with-cap 96
67 │ _ = bytes/push-all mut in_place buf_a
68 │ _ = bytes/xor! mut in_place key_buf
69 │ must (bytes/eq in_place xored) 'bytes/xor! parity with bytes/xor'
70 │ _ = bytes/xor! mut in_place key_buf
71 │ must (bytes/eq in_place buf_a) 'bytes/xor! inverse'
72 │ println (str/join ['bytes_bulk=ok|len=96|index_of=' (mold pos_mid) '|xor_inplace=true'] '')
73 │
74 │ // 3. Hardware AES-NI / Constant-Time Algebraic `bytes/aes-enc-block` (NIST FIPS-197 Known-Answer Tests)
75 │ // FIPS-197 Appendix B (AES-128 via `crypto/aes/encrypt-block` -> `bytes/aes-enc-block`)
76 │ k128 = hex/decode '2b7e151628aed2a6abf7158809cf4f3c'
77 │ pt128 = hex/decode '3243f6a8885a308d313198a2e0370734'
78 │ ct128 = aes/encrypt-block k128 pt128
79 │ h128 = hex/encode ct128
80 │ must (h128 == '3925841d02dc09fbdc118597196a0b32') (str/join ['FIPS-197 AES-128 mismatch: ' h128] '')
81 │
82 │ // FIPS-197 Appendix C.3 (AES-256)
83 │ k256 = hex/decode '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f'
84 │ pt256 = hex/decode '00112233445566778899aabbccddeeff'
85 │ ct256 = aes/encrypt-block k256 pt256
86 │ h256 = hex/encode ct256
87 │ must (h256 == '8ea2b7ca516745bfeafc49904b496089') (str/join ['FIPS-197 AES-256 mismatch: ' h256] '')
88 │
89 │ // Direct `bytes/aes-enc-block` bounds check (`rk` must be 176/208/240 bytes) + zero-key direct call
90 │ bad_rk = bytes/aes-enc-block/or pt128 k128 [ bytes/fill 1 0xff ]
91 │ must ((len bad_rk) == 1 and bad_rk[0] == 0xff) 'bytes/aes-enc-block rejects unexpanded key'
92 │ z_blk = bytes/fill 16 0
93 │ z_rk = bytes/fill 176 0
94 │ z_ct = bytes/aes-enc-block z_blk z_rk
95 │ must ((len z_ct) == 16) 'bytes/aes-enc-block direct 176B round-key call'
96 │
97 │ p128 = h128[0..16]
98 │ p256 = h256[0..16]
99 │ println (str/join ['aes_nist_kat=ok|aes128=' p128 '...|aes256=' p256 '...'] '')
100 │
101 │ // 4. Accelerated AES-256-GCM AEAD round-trip + IEEE 802.3 Sarwate CRC32
102 │ nonce = hex/decode '00112233445566778899aabb'
103 │ aad = bytes/from-str 'veko-phase5-arm64'
104 │ msg = bytes/from-str 'Deterministic No-JIT ORO execution across x86_64, AArch64, and Wasm 3.0!'
105 │ sealed = aes/gcm-encrypt k256 nonce msg aad
106 │ opened = aes/gcm-decrypt k256 nonce sealed aad
107 │ must (bytes/eq opened msg) 'AES-256-GCM round-trip'
108 │
109 │ crc = bits/crc32 (bytes/from-str '123456789')
110 │ must (crc == 0xcbf43926) 'IEEE 802.3 CRC32 vector'
111 │ println (str/join ['aes256_gcm=ok|sealed_len=' (mold (len sealed)) '|crc32_ieee=0xcbf43926'] '')Example 29: 29_async_reactor_http_server_and_client.vk
Run command: veko -A examples/29_async_reactor_http_server_and_client.vk
Demonstrates Veko's Readiness Reactor (lib/reactor.vk), non-blocking sockets (lib/io/net.vk), concurrent multiplexed HTTP/1.1 server (web/serve-async), concurrent batch HTTP/1.1 client (net/client/request-batch), cross-thread spawn wakeup, timers, and incremental WebSocket framing.
1 │ // examples/29_async_reactor_http_server_and_client.vk
2 │ // Demonstrates Veko's Readiness Reactor (`lib/reactor.vk`), non-blocking sockets (`lib/io/net.vk`),
3 │ // concurrent multiplexed HTTP/1.1 server (`web/serve-async`), concurrent batch HTTP/1.1 client
4 │ // (`net/client/request-batch`), cross-thread `spawn` wakeup, timers, and incremental WebSocket framing.
5 │
6 │ use [
7 │ reactor
8 │ inet = io/net
9 │ web
10 │ hc = net/client
11 │ ws = net/websocket
12 │ ]
13 │
14 │ println '=== Veko Readiness Reactor & Non-Blocking HTTP ==='
15 │
16 │ // 1. Reactor timers + cross-thread `spawn` wakeup (`reactor/waker` -> `reactor/wake-handle`)
17 │ mut r = reactor/new
18 │ if err? r [ return (err 'reactor/new failed') ]
19 │ w = reactor/waker r
20 │ tid = reactor/after mut r 15ms
21 │
22 │ t0 = time/now
23 │ wk_task = spawn [
24 │ time/sleep 5ms
25 │ _ = reactor/wake-handle w
26 │ .woken
27 │ ]
28 │ _ = reactor/poll mut r 2s
29 │ wake_ms = (as-i64 (time/since t0)) / 1000000
30 │ wk_res = task/await wk_task
31 │ if wk_res != .woken [ return (err 'worker wakeup failed') ]
32 │
33 │ // Wait until one-shot timer fires
34 │ mut timer_fired = false
35 │ mut spins = 0
36 │ while (not timer_fired) and spins < 40 [
37 │ _ = reactor/poll mut r 20ms
38 │ due = reactor/due-timers mut r
39 │ mut di = 0
40 │ while di < (len due) [
41 │ if due[di] == tid [ timer_fired = true ]
42 │ di = di + 1
43 │ ]
44 │ spins = spins + 1
45 │ ]
46 │ _ = reactor/close mut r
47 │ if not timer_fired [ return (err 'reactor timer did not fire') ]
48 │ println (str/join ['[1/4] Reactor wake + timer OK (woke in ' (mold wake_ms) ' ms, timer #' (mold tid) ' fired)'] '')
49 │
50 │ // 2. Build a web/App served by a single-threaded non-blocking `web/serve-async` reactor
51 │ make-demo-app = fn [] web/App [
52 │ mut app = web/new-app
53 │ web/use-security-headers mut app
54 │ web/get mut app '/ping' fn [req web/Request] web/Response [
55 │ web/json-resp 200 { ok = true, path = req.path }
56 │ ]
57 │ web/get mut app '/items/:id' fn [req web/Request] web/Response [
58 │ web/json-resp 200 { item = (web/param req 'id' '0'), kind = 'async' }
59 │ ]
60 │ web/post mut app '/echo' fn [req web/Request] web/Response [
61 │ web/json-resp 200 { echoed = (bytes/to-str req.body), bytes = (len req.body) }
62 │ ]
63 │ app
64 │ ]
65 │
66 │ ln = net/listen-tcp .ip '127.0.0.1:0'
67 │ addr = net/addr ln
68 │ parts = str/split addr ':'
69 │ port = str/to-i64 parts[1]
70 │ base = str/join ['http://127.0.0.1:' (mold port)] ''
71 │
72 │ // Launch single-threaded reactor server handling 5 concurrent connections
73 │ srv_task = spawn [
74 │ web/serve-async ln (make-demo-app) 5
75 │ ]
76 │
77 │ // 3. Open a stalled slow client (sends only half an HTTP request and pauses!)
78 │ slow_fd = inet/dial-tcp-nonblock '127.0.0.1' port
79 │ if err? slow_fd [ return (err 'slow_fd dial failed') ]
80 │ // Wait briefly for non-blocking connect to complete
81 │ mut sr = reactor/new
82 │ slow_tok = reactor/register mut sr slow_fd (reactor/EV-WRITE)
83 │ _ = reactor/poll mut sr 500ms
84 │ _ = reactor/unregister mut sr slow_tok
85 │ _ = reactor/close mut sr
86 │ if (inet/sock-error slow_fd) != 0 [ return (err 'slow_fd SO_ERROR nonzero') ]
87 │
88 │ // Verify .secret firewall blocks `net/try-write`
89 │ sec_tok = bytes/with-secret 8
90 │ sec_blocked = net/try-write/or slow_fd sec_tok [ -999 ]
91 │ if sec_blocked != -999 [ return (err 'secret firewall failed on net/try-write') ]
92 │
93 │ // Send ONLY the first line (incomplete headers -> server MUST NOT block other clients!)
94 │ _ = inet/try-write slow_fd (bytes/from-str 'GET /ping HTTP/1.1\r\n')
95 │
96 │ // 4. Fire 4 concurrent HTTP/1.1 requests simultaneously over `net/client/request-batch`
97 │ batch_reqs = [
98 │ (hc/AsyncRequest { method = 'GET', url = (str/append base '/ping') })
99 │ (hc/AsyncRequest { method = 'GET', url = (str/append base '/items/42') })
100 │ (hc/AsyncRequest { method = 'GET', url = (str/append base '/items/99') })
101 │ (hc/AsyncRequest { method = 'POST', url = (str/append base '/echo'), body = (bytes/from-str 'hello-reactor') })
102 │ ]
103 │ resps = hc/request-batch batch_reqs
104 │ if (len resps) != 4 [ return (err 'expected 4 batch responses') ]
105 │
106 │ r0 = resps[0]
107 │ r1 = resps[1]
108 │ r2 = resps[2]
109 │ r3 = resps[3]
110 │ if err? r0 or err? r1 or err? r2 or err? r3 [
111 │ return (err 'one or more concurrent HTTP batch requests failed')
112 │ ]
113 │ if r0.status != 200 or r1.status != 200 or r2.status != 200 or r3.status != 200 [
114 │ return (err 'unexpected HTTP status in batch')
115 │ ]
116 │ j1 = hc/json-body r1
117 │ j2 = hc/json-body r2
118 │ j3 = hc/json-body r3
119 │ if (map/get j1 'item') != '42' or (map/get j2 'item') != '99' or (map/get j3 'echoed') != 'hello-reactor' [
120 │ return (err 'unexpected JSON payload in concurrent batch')
121 │ ]
122 │ println (str/join ['[2/4] Concurrent 4-way HTTP batch completed while slow client stalled (' (mold r0.status) '/' (mold r1.status) '/' (mold r2.status) '/' (mold r3.status) ')'] '')
123 │
124 │ // 5. Complete the stalled slow client and read its HTTP 200 response non-blockingly
125 │ _ = inet/try-write slow_fd (bytes/from-str 'Host: 127.0.0.1\r\nConnection: close\r\n\r\n')
126 │ mut slow_rx = bytes/with-cap 512
127 │ mut slow_r = reactor/new
128 │ st2 = reactor/register mut slow_r slow_fd (reactor/EV-READ)
129 │ mut slow_done = false
130 │ mut si = 0
131 │ while (not slow_done) and si < 50 [
132 │ _ = reactor/poll mut slow_r 50ms
133 │ nr = inet/try-read-into/or slow_fd mut slow_rx 512 [ -2 ]
134 │ if nr == 0 [ slow_done = true ]
135 │ if nr == -2 [ slow_done = true ]
136 │ si = si + 1
137 │ ]
138 │ _ = reactor/unregister mut slow_r st2
139 │ _ = reactor/close mut slow_r
140 │ _ = net/close/or slow_fd [ .ok ]
141 │
142 │ slow_txt = bytes/to-str slow_rx
143 │ if not (str/contains? slow_txt '200 OK') or not (str/contains? slow_txt '"/ping"') [
144 │ return (err 'slow client did not receive HTTP 200 response')
145 │ ]
146 │ served = task/await srv_task
147 │ _ = net/close/or ln [ .ok ]
148 │ if served != 5 [ return (err (str/join ['expected 5 served requests, got ' (mold served)] '')) ]
149 │ println (str/join ['[3/4] Slow client completed + single-thread server served ' (mold served) ' requests'] '')
150 │
151 │ // 6. Incremental non-blocking WebSocket frame parsing (`ws/try-decode-frame`)
152 │ wf = ws/Frame { fin = true, opcode = (ws/OP-TEXT), masked = false, payload = (bytes/from-str 'reactor-ws') }
153 │ wwire = ws/encode-frame wf (bytes/with-cap 0)
154 │ part = ws/try-decode-frame wwire[0..4]
155 │ full = ws/try-decode-frame wwire
156 │ if part.complete or (not full.complete) or (bytes/to-str full.frame.payload) != 'reactor-ws' [
157 │ return (err 'incremental websocket frame decode failed')
158 │ ]
159 │ println '[4/4] Incremental WebSocket try-decode-frame + secret firewall OK'
160 │ println 'PASS: Example 29 (Readiness Reactor & Non-Blocking HTTP)'Example 30: 30_tui_and_native_ui_canvas.vk
Run command: veko -A examples/30_tui_and_native_ui_canvas.vk
Phase 6 showcase: 1. Pure-Veko lib/tui.vk double-buffered ANSI terminal dashboard, diffing renderer, & CSI key decoder 2. Pure-Veko lib/ui/canvas.vk + lib/ui/widgets.vk RGBA32 software rasterizer, hit-tested widgets, & BMP/PPM export 3. .ui-gated lib/ui.vk native window presentation (VEKO_HEADLESS=1 supported for CI/automated runs)
1 │ // examples/30_tui_and_native_ui_canvas.vk
2 │ // Phase 6 showcase:
3 │ // 1. Pure-Veko `lib/tui.vk` double-buffered ANSI terminal dashboard, diffing renderer, & CSI key decoder
4 │ // 2. Pure-Veko `lib/ui/canvas.vk` + `lib/ui/widgets.vk` RGBA32 software rasterizer, hit-tested widgets, & BMP/PPM export
5 │ // 3. `.ui`-gated `lib/ui.vk` native window presentation (`VEKO_HEADLESS=1` supported for CI/automated runs)
6 │
7 │ use [
8 │ tui
9 │ cv = ui/canvas
10 │ w = ui/widgets
11 │ ui
12 │ ]
13 │
14 │ run-tui-demo = fn [] any [
15 │ mut scr = tui/new-screen 60 12
16 │ bg = tui/color-surface
17 │ fg = tui/color-white
18 │ cy = tui/color-cyan
19 │ em = tui/color-emerald
20 │ sl = tui/color-slate
21 │
22 │ tui/clear mut scr fg bg
23 │ tui/draw-box mut scr 0 0 60 12 'Veko 1.0 Node Monitor' .rounded cy bg
24 │ tui/draw-text mut scr 2 2 'Status: HEALTHY Track: 3-Track Native/Wasm/VM' em bg (tui/STYLE-BOLD)
25 │ tui/draw-text mut scr 2 4 'CPU:' sl bg 0
26 │ tui/draw-progress mut scr 7 4 24 75 em sl bg
27 │ tui/draw-text mut scr 33 4 '75%' fg bg (tui/STYLE-BOLD)
28 │ tui/draw-text mut scr 2 5 'Lat:' sl bg 0
29 │ tui/draw-sparkline mut scr 7 5 [12 18 15 24 31 28 19 14 22 35 27 16] cy bg
30 │
31 │ tui/draw-table mut scr 2 7 ['Service' 'Port' 'State'] [
32 │ ['http-api' '8080' 'UP']
33 │ ['reactor' '9090' 'UP']
34 │ ] [12 6 8] fg cy bg
35 │ tui/draw-menu mut scr 36 7 20 ['Overview' 'Metrics' 'Logs'] 1 fg bg cy bg
36 │
37 │ frame1 = tui/render-diff mut scr
38 │ frame2 = tui/render-diff mut scr
39 │ tui/draw-text mut scr 33 4 '76%' fg bg (tui/STYLE-BOLD)
40 │ frame3 = tui/render-diff mut scr
41 │ plain = tui/render-plain scr
42 │
43 │ if (len frame1) == 0 [ return (err 'tui: expected non-empty initial ANSI frame') ]
44 │ if (len frame2) != 0 [ return (err 'tui: expected empty diff frame when screen unchanged') ]
45 │ if (len frame3) == 0 or (len frame3) >= (len frame1) [ return (err 'tui: expected compact delta frame') ]
46 │ if not (str/contains? plain 'Veko 1.0 Node Monitor') [ return (err 'tui: missing title in plain render') ]
47 │
48 │ // Verify CSI arrow + Ctrl-C decoding
49 │ mut up_bytes = bytes/with-cap 3
50 │ bytes/push mut up_bytes 27
51 │ bytes/push mut up_bytes 91
52 │ bytes/push mut up_bytes 65
53 │ ev_up = tui/parse-key up_bytes
54 │ if ev_up.kind != .up [ return (err 'tui: CSI Up parse failed') ]
55 │
56 │ mut ctrl_c = bytes/with-cap 1
57 │ bytes/push mut ctrl_c 3
58 │ ev_cc = tui/parse-key ctrl_c
59 │ if ev_cc.kind != .char or (not ev_cc.ctrl) or ev_cc.ch != 'c' [ return (err 'tui: Ctrl-C parse failed') ]
60 │
61 │ println (str/join ['tui-ok: frame1=' (mold (len frame1)) 'B delta=' (mold (len frame3)) 'B key=up+ctrl-c'] '')
62 │ .ok
63 │ ]
64 │
65 │ run-canvas-and-window-demo = fn [] any [
66 │ cw = 240
67 │ ch = 140
68 │ mut c = cv/new-canvas cw ch
69 │ th = w/dark-theme
70 │ cv/fill-gradient-v mut c 0 0 cw ch th.bg (cv/rgb 20 30 52)
71 │
72 │ root = w/Rect { x = 8, y = 8, w = (cw - 16), h = (ch - 16) }
73 │ rows = w/vstack root [28 52 32] 6
74 │ w/panel mut c rows[0] 'VEKO 1.0 NATIVE UI' th
75 │
76 │ cols = w/hstack rows[1] [108 110] 6
77 │ w/panel mut c cols[0] 'LOAD' th
78 │ w/progress-bar mut c (w/Rect { x = (cols[0].x + 8), y = (cols[0].y + 28), w = 92, h = 14 }) 82 th
79 │
80 │ w/panel mut c cols[1] 'THROUGHPUT' th
81 │ w/sparkline mut c (w/Rect { x = (cols[1].x + 8), y = (cols[1].y + 24), w = 94, h = 22 }) [10 22 18 35 28 48 42 56] th.accent th
82 │
83 │ mut st = w/new-state
84 │ btn_rect = w/Rect { x = rows[2].x, y = rows[2].y, w = 104, h = 26 }
85 │ w/apply-mouse mut st (btn_rect.x + 20) (btn_rect.y + 10) true true
86 │ clicked = w/button mut c mut st 'deploy' btn_rect 'DEPLOY' th
87 │ if not clicked [ return (err 'ui/widgets: expected button click hit') ]
88 │
89 │ // Verify pixel rasterization + zero-dependency BMP & PPM export
90 │ center_px = cv/get-pixel c (btn_rect.x + 4) (btn_rect.y + 4)
91 │ if center_px.a != 255 [ return (err 'ui/canvas: expected opaque button pixel') ]
92 │ bmp = cv/encode-bmp c
93 │ ppm = cv/encode-ppm c
94 │ expected_bmp = 54 + cw * 3 * ch
95 │ if bmp[0] != 66 or bmp[1] != 77 or (len bmp) != expected_bmp [
96 │ return (err 'ui/canvas: invalid BMP output')
97 │ ]
98 │ if ppm[0] != 80 or ppm[1] != 54 [
99 │ return (err 'ui/canvas: invalid PPM output')
100 │ ]
101 │
102 │ // Present through `.ui`-gated window surface (native Win32 or offscreen/headless)
103 │ win = ui/open-window 'Veko 1.0 UI Demo' cw ch
104 │ _ = ui/present-canvas win c
105 │ evs = ui/poll win
106 │ if (len evs) < 0 [ return (err 'ui: poll failed') ]
107 │ _ = ui/close-window win
108 │
109 │ println (str/join ['ui-ok: canvas=' (mold cw) 'x' (mold ch) ' bmp=' (mold (len bmp)) 'B ppm=' (mold (len ppm)) 'B'] '')
110 │ .ok
111 │ ]
112 │
113 │ main = fn [] any [
114 │ r1 = run-tui-demo
115 │ if err? r1 [ return r1 ]
116 │ r2 = run-canvas-and-window-demo
117 │ if err? r2 [ return r2 ]
118 │ .ok
119 │ ]
120 │
121 │ res = main
122 │ if err? res [
123 │ println (str/append 'FAIL: ' (mold res))
124 │ os/exit 1
125 │ ]Example 31: 31_opt_in_ffi_and_c_struct_packing.vk
Run command: veko -C ffi examples/31_opt_in_ffi_and_c_struct_packing.vk
Phase 6 showcase: Opt-In .ffi Foreign Library Boundary & C-Struct Packing. - Denied by default unless compiled/run with --allow-ffi (or allow-caps = [.ffi] in veko.vk) - Strictly forbidden on --wasm zero-trust targets - Zero-W^X static AOT C-ABI trampolines on Win64 (kernel32.dll) and Linux x86_64 (libc.so.6 dynamic ELF64)
1 │ // examples/31_opt_in_ffi_and_c_struct_packing.vk
2 │ // Phase 6 showcase: Opt-In `.ffi` Foreign Library Boundary & C-Struct Packing.
3 │ // - Denied by default unless compiled/run with `--allow-ffi` (or `allow-caps = [.ffi]` in `veko.vk`)
4 │ // - Strictly forbidden on `--wasm` zero-trust targets
5 │ // - Zero-W^X static AOT C-ABI trampolines on Win64 (`kernel32.dll`) and Linux x86_64 (`libc.so.6` dynamic ELF64)
6 │
7 │ use [ffi]
8 │
9 │ test-c-struct-packing = fn [] any [
10 │ // Pack a C struct: { int32_t code; uint32_t flags; int64_t timestamp; char tag[16]; }
11 │ mut buf = bytes/with-cap 32
12 │ ffi/pack-i32 mut buf -42
13 │ ffi/pack-u32 mut buf 0x12345678
14 │ ffi/pad-align mut buf 8
15 │ ffi/pack-i64 mut buf 1735689600000
16 │ ffi/pack-cstr mut buf 'veko-ffi'
17 │
18 │ code = ffi/unpack-i32 buf 0
19 │ flags = ffi/unpack-u32 buf 4
20 │ ts = ffi/unpack-i64 buf 8
21 │ tag = ffi/unpack-cstr buf 16
22 │ if code != -42 or flags != 0x12345678 or ts != 1735689600000 or tag != 'veko-ffi' [
23 │ return (err 'ffi: C-struct pack/unpack round-trip mismatch')
24 │ ]
25 │ println (str/join ['c-struct-ok: code=' (mold code) ' flags=' (mold flags) ' tag=' tag] '')
26 │ .ok
27 │ ]
28 │
29 │ test-live-c-abi = fn [] any [
30 │ is_win = (os/getenv/or 'OS' ['']) == 'Windows_NT'
31 │ is_mac = os/exists? '/System/Library/CoreServices/SystemVersion.plist'
32 │ lib_name = if is_win [ 'kernel32.dll' ] else [
33 │ if is_mac [ '/usr/lib/libSystem.B.dylib' ] else [ 'libc.so.6' ]
34 │ ]
35 │ pid_sym_name = if is_win [ 'GetCurrentProcessId' ] else [ 'getpid' ]
36 │ len_sym_name = if is_win [ 'lstrlenA' ] else [ 'strlen' ]
37 │
38 │ lib = ffi/open-lib lib_name
39 │ if err? lib [ return lib ]
40 │
41 │ pid_sym = ffi/resolve lib pid_sym_name
42 │ if err? pid_sym [
43 │ _ = ffi/close-lib lib
44 │ return pid_sym
45 │ ]
46 │ pid = ffi/call-c pid_sym []
47 │ if pid <= 0 [
48 │ _ = ffi/close-lib lib
49 │ return (err 'ffi: expected positive OS process id')
50 │ ]
51 │
52 │ len_sym = ffi/resolve lib len_sym_name
53 │ if err? len_sym [
54 │ _ = ffi/close-lib lib
55 │ return len_sym
56 │ ]
57 │ n = ffi/call-c len_sym ['veko-1.0-ffi']
58 │ if n != 12 [
59 │ _ = ffi/close-lib lib
60 │ return (err (str/append 'ffi: expected C strlen=12, got ' (mold n)))
61 │ ]
62 │
63 │ _ = ffi/close-lib lib
64 │ println (str/join ['ffi-ok: lib=' lib_name ' pid=' (mold pid) ' strlen=' (mold n)] '')
65 │ .ok
66 │ ]
67 │
68 │ main = fn [] any [
69 │ r1 = test-c-struct-packing
70 │ if err? r1 [ return r1 ]
71 │ r2 = test-live-c-abi
72 │ if err? r2 [ return r2 ]
73 │ .ok
74 │ ]
75 │
76 │ res = main
77 │ if err? res [
78 │ println (str/append 'FAIL: ' (mold res))
79 │ os/exit 1
80 │ ]Example 32: 32_durable_objects_and_workflows.vk
Run command: veko -A examples/32_durable_objects_and_workflows.vk
Showcases Durable Objects (lib/durable/object.vk) & Durable Workflows (lib/durable/workflow.vk) backed by lib/db/kv.vk's CRC-32 crash-safe WAL: 1. Durable Object state, atomic mutate with rollback on error, durable alarms, & FIFO inbox 2. Crash-resilient Durable Workflow: step memoization across DB reopen, durable retries, external signal (wait-event/send-event), durable timer (sleep-until), and LIFO saga compensation
1 │ // examples/32_durable_objects_and_workflows.vk
2 │ // Showcases Durable Objects (`lib/durable/object.vk`) & Durable Workflows (`lib/durable/workflow.vk`)
3 │ // backed by `lib/db/kv.vk`'s CRC-32 crash-safe WAL:
4 │ // 1. Durable Object state, atomic `mutate` with rollback on error, durable alarms, & FIFO inbox
5 │ // 2. Crash-resilient Durable Workflow: step memoization across DB reopen, durable retries,
6 │ // external signal (`wait-event`/`send-event`), durable timer (`sleep-until`), and LIFO saga compensation
7 │
8 │ use [
9 │ d = durable
10 │ dobj = durable/object
11 │ wf = durable/workflow
12 │ ]
13 │
14 │ run-durable-object-demo = fn [store_path str] any [
15 │ mut db = d/open-store-fast store_path
16 │ mut acct = d/object mut db 'account' 'acct-001'
17 │ _ = dobj/put-fields mut db mut acct { owner = 'Alice', balance = 500, tier = 'gold' }
18 │
19 │ // Atomic transactional turn: deduct 120 -> 380
20 │ bal1 = dobj/mutate mut db mut acct fn [st] [
21 │ b = as-i64 (map/get/or st 'balance' [ 0 ])
22 │ if b < 120 [ return (err 'insufficient funds') ]
23 │ mut next = st
24 │ map/set mut next 'balance' (b - 120)
25 │ { state = next, result = (b - 120) }
26 │ ]
27 │ if bal1 != 380 [ return (err 'durable object mutate failed') ]
28 │
29 │ // Failing turn MUST roll back atomically (balance remains 380, version unchanged)
30 │ v_before = acct.version
31 │ bad = dobj/mutate mut db mut acct fn [st] [
32 │ b = as-i64 (map/get/or st 'balance' [ 0 ])
33 │ if b < 9999 [ return (err 'overdraft rejected') ]
34 │ { state = st, result = 0 }
35 │ ]
36 │ if (not (err? bad)) or acct.version != v_before [
37 │ return (err 'durable object rollback violated')
38 │ ]
39 │
40 │ // Schedule durable alarm (10ms) and enqueue 2 FIFO inbox messages
41 │ _ = dobj/set-alarm mut db mut acct 10ms 'reconcile'
42 │ _ = dobj/enqueue mut db mut acct 'deposit' 25
43 │ _ = dobj/enqueue mut db mut acct 'note' 'payroll'
44 │ _ = d/close-store mut db
45 │
46 │ // Simulate process restart: sleep past alarm, reopen store, verify durability
47 │ time/sleep 40ms
48 │ mut db2 = d/open-store-fast store_path
49 │ mut acct2 = d/object mut db2 'account' 'acct-001'
50 │ persisted_bal = dobj/get db2 acct2 'balance'
51 │ due = dobj/poll-due-alarms mut db2 'account'
52 │ msgs = dobj/drain-inbox mut db2 mut acct2
53 │ ids = dobj/list-ids db2 'account'
54 │ _ = d/close-store mut db2
55 │
56 │ if persisted_bal != 380 [ return (err 'persisted balance mismatch') ]
57 │ if (len due) != 1 or due[0].tag != 'reconcile' [ return (err 'durable alarm did not fire') ]
58 │ if (len msgs) != 2 or msgs[0].kind != 'deposit' or msgs[1].payload != 'payroll' [ return (err 'durable inbox mismatch') ]
59 │ if (len ids) != 1 or ids[0] != 'acct-001' [ return (err 'list-ids mismatch') ]
60 │
61 │ println (str/join ['do-ok: id=acct-001 ver=' (mold acct2.version) ' bal=' (mold persisted_bal) ' alarms=' (mold (len due)) ' inbox=' (mold (len msgs))] '')
62 │ .ok
63 │ ]
64 │
65 │ run-durable-workflow-demo = fn [store_path str] any [
66 │ // Phase 1: Start order workflow, run step 1 + retry step 2, then suspend waiting for payment signal
67 │ mut db1 = d/open-store-fast store_path
68 │ mut run1 = d/workflow mut db1 'ord-77' 'fulfill-order' { sku = 'VEKO-PRO', qty = 2 }
69 │ inv = wf/step mut db1 mut run1 'reserve-inventory' fn [] [ 'res-901' ]
70 │ if inv != 'res-901' [ return (err 'step 1 failed') ]
71 │
72 │ ship_quote = wf/step-with-retry mut db1 mut run1 'fetch-quote' 3 5ms fn [attempt] [
73 │ if attempt < 2 [ return (err 'transient carrier timeout') ]
74 │ { carrier = 'fastpost', cents = 1299 }
75 │ ]
76 │ if err? ship_quote [ return ship_quote ]
77 │
78 │ // Wait for external 'payment-confirmed' signal -> suspends in .waiting state
79 │ w1 = wf/wait-event mut db1 mut run1 'payment-confirmed'
80 │ if w1.ready or run1.status != .waiting [ return (err 'workflow should wait for event') ]
81 │ _ = d/close-store mut db1
82 │
83 │ // Phase 2: External webhook delivers signal & worker restarts and replays the workflow!
84 │ mut db2 = d/open-store-fast store_path
85 │ _ = wf/send-event mut db2 'ord-77' 'payment-confirmed' { receipt = 'rcpt-555', paid = true }
86 │
87 │ mut run2 = d/workflow mut db2 'ord-77' 'fulfill-order' { sku = 'VEKO-PRO', qty = 2 }
88 │ // Completed steps MUST replay from db/kv without invoking the closures!
89 │ inv_replayed = wf/step mut db2 mut run2 'reserve-inventory' fn [] [ 'BAD-DUPLICATE-RESERVATION' ]
90 │ quote_replayed = wf/step-with-retry mut db2 mut run2 'fetch-quote' 3 5ms fn [attempt] [
91 │ err 'MUST NOT RE-RUN COMPLETED RETRY STEP'
92 │ ]
93 │ if inv_replayed != 'res-901' [ return (err 'step 1 replay failed') ]
94 │ if err? quote_replayed [ return (err 'step 2 replay failed') ]
95 │
96 │ w2 = wf/wait-event mut db2 mut run2 'payment-confirmed'
97 │ if (not w2.ready) or w2.payload.receipt != 'rcpt-555' [ return (err 'signal delivery failed') ]
98 │
99 │ // Durable sleep step (10ms)
100 │ ready0 = wf/sleep-until mut db2 mut run2 'cooling-window' 10ms
101 │ if ready0 [ return (err 'sleep-until should initially suspend') ]
102 │ time/sleep 40ms
103 │ ready1 = wf/sleep-until mut db2 mut run2 'cooling-window' 10ms
104 │ if not ready1 [ return (err 'sleep-until did not resume after deadline') ]
105 │
106 │ _ = wf/complete mut db2 mut run2 { reservation = inv_replayed, receipt = w2.payload.receipt }
107 │ hist = wf/history db2 'ord-77'
108 │
109 │ // Phase 3: Demonstrate LIFO Saga compensation on a failing workflow
110 │ mut fail_run = d/workflow mut db2 'ord-88' 'fulfill-order' { sku = 'BAD-SKU' }
111 │ _ = wf/record-compensation mut db2 mut fail_run 'release-inventory' 'res-888'
112 │ _ = wf/record-compensation mut db2 mut fail_run 'void-auth' 'auth-888'
113 │ mut comp_order = []
114 │ n_comp = wf/run-compensations mut db2 mut fail_run fn [cname data] [
115 │ push mut comp_order (str/join [cname ':' (str/append '' data)] '')
116 │ .ok
117 │ ]
118 │ runs = wf/list-runs db2
119 │ _ = d/close-store mut db2
120 │
121 │ if n_comp != 2 or fail_run.status != .compensated [ return (err 'saga compensation count mismatch') ]
122 │ if (len runs) != 2 [ return (err 'list-runs count mismatch') ]
123 │
124 │ println (str/join ['wf-ok: id=ord-77 steps=' (mold run2.step_count) ' history=' (mold (len hist)) ' saga-compensated=' (mold n_comp)] '')
125 │ .ok
126 │ ]
127 │
128 │ main = fn [] any [
129 │ p = str/join [(os/temp-dir) '/veko_ex32_durable.vkkv'] ''
130 │ _ = os/remove/or p [.ok]
131 │ defer [ _ = os/remove/or p [.ok] ]
132 │ r1 = run-durable-object-demo p
133 │ if err? r1 [ return r1 ]
134 │ r2 = run-durable-workflow-demo p
135 │ if err? r2 [ return r2 ]
136 │ .ok
137 │ ]
138 │
139 │ res = main
140 │ if err? res [
141 │ println (str/append 'FAIL: ' (mold res))
142 │ os/exit 1
143 │ ]