← Back to Demos & Examples

14_http_json_api_server.vk

Raw .vk
// Example 14: Multi-Worker Concurrent HTTP/1.1 + JSON REST Microservice
// Demonstrates `codec/http1`, `net/*`, shared-nothing `spawn` actor + worker pool,
// reusable per-worker channels, typed `struct` + `struct/with`, `parse-block`, and `.secret` firewall.
//
// Track A (ORO VM) : veko run --allow-net --allow-listen --allow-private-net examples/14_http_json_api_server.vk
// Track A (.vko)   : veko compile --vko examples/14_http_json_api_server.vk -o dist/14.vko ; veko run --allow-net --allow-listen --allow-private-net dist/14.vko
// Track B (Wasm 3) : veko run --wasm --allow-net --allow-listen --allow-private-net examples/14_http_json_api_server.vk
// Track C (Native) : veko compile --native examples/14_http_json_api_server.vk -o dist/14.exe ; ./dist/14.exe

use [http = codec/http1, json, bytes, net, str, time]

TaskItem = struct {
	id       i64
	title    str
	priority i64 = 1
	done     bool = false
}

ApiMetrics = struct {
	handled i64
	created i64
	workers i64
}

parse-port = fn [addr str] i64 [
	parts = str/split addr ':'
	str/to-i64/or parts[1] [0]
]

is-json-map? = fn [v any] bool [
	(type-of v) == .map_val
]

is-json-str? = fn [v any] bool [
	t = type-of v
	t == .str or t == .str_inline or t == .str_heap
]

is-json-num? = fn [v any] bool [
	t = type-of v
	t == .i64_val or t == .f64_val
]

// Loop `net/read-bytes/or` until full HTTP/1.1 headers + Content-Length body arrive
read-http-request = fn [sock any] any [
	mut buf = bytes/with-cap 0
	forever [
		chunk = net/read-bytes/or sock 4096 [bytes/with-cap 0]
		if (len chunk) == 0 [
			return (err 'http: unexpected EOF reading request')
		]
		bytes/push-all (mut buf) chunk
		dec = http/decode-request buf
		if ok? dec [
			return dec
		]
	]
	err 'http: unreachable'
]

read-http-response = fn [sock any] any [
	mut buf = bytes/with-cap 0
	forever [
		chunk = net/read-bytes/or sock 4096 [bytes/with-cap 0]
		if (len chunk) == 0 [
			return (err 'http: unexpected EOF reading response')
		]
		bytes/push-all (mut buf) chunk
		dec = http/decode-response buf
		if ok? dec [
			return dec
		]
	]
	err 'http: unreachable'
]

// Parse `/items/<id>` (need_done=false) or `/items/<id>/done` (need_done=true)
parse-item-id = fn [target str, need_done bool] i64 [
	parts = str/split target '/'
	if need_done [
		if (len parts) == 4 and parts[1] == 'items' and parts[3] == 'done' [
			return (str/to-i64/or parts[2] [-1])
		]
		return -1
	]
	if (len parts) == 3 and parts[1] == 'items' [
		return (str/to-i64/or parts[2] [-1])
	]
	-1
]

// Dedicated store actor owns mutable REST state inside its isolated task heap
run-store-actor = fn [store_ch any, worker_count i64] i64 [
	mut items = []
	mut next_id = 1
	mut handled = 0
	mut created = 0

	forever [
		cmd = chan/recv/or store_ch [break]
		op = cmd.op
		handled = handled + 1

		resp = match op [
			'health' [
				{ status = 200, reason = 'OK', body = { status = 'ok', service = 'veko-api' } }
			]
			'create' [
				item = TaskItem {
					id       = next_id
					title    = cmd.title
					priority = cmd.priority
					done     = false
				}
				push mut items item
				next_id = next_id + 1
				created = created + 1
				{ status = 201, reason = 'Created', body = item }
			]
			'list' [
				{ status = 200, reason = 'OK', body = { count = (len items), items = items } }
			]
			'get' [
				mut found = .none
				mut i = 0
				while i < (len items) [
					it = items[i]
					if it.id == cmd.id [
						found = it
					]
					i = i + 1
				]
				if found == .none [
					{ status = 404, reason = 'Not Found', body = { error = 'not_found', id = cmd.id } }
				] else [
					{ status = 200, reason = 'OK', body = found }
				]
			]
			'done' [
				mut updated = .none
				mut next_items = []
				mut i = 0
				while i < (len items) [
					it = items[i]
					if it.id == cmd.id [
						u = it \ struct/with { done = true }
						updated = u
						push mut next_items u
					] else [
						push mut next_items it
					]
					i = i + 1
				]
				items = next_items
				if updated == .none [
					{ status = 404, reason = 'Not Found', body = { error = 'not_found', id = cmd.id } }
				] else [
					{ status = 200, reason = 'OK', body = updated }
				]
			]
			'metrics' [
				m = ApiMetrics { handled = handled, created = created, workers = worker_count }
				{ status = 200, reason = 'OK', body = m }
			]
			'bad_request' [
				{ status = 400, reason = 'Bad Request', body = { error = 'invalid_json' } }
			]
			_ [
				{ status = 404, reason = 'Not Found', body = { error = 'not_found' } }
			]
		]
		chan/send cmd.reply resp
	]
	handled
]

// Worker pool loop: reuses one `reply_ch` per worker across all handled connections
worker-loop = fn [work_ch any, store_ch any] i64 [
	reply_ch = chan/new 1
	mut served = 0

	forever [
		conn = chan/recv/or work_ch [break]
		req = read-http-request conn
		if ok? req [
			method = req.method
			target = req.target
			req_body = req.body

			mut cmd = { op = 'not_found', reply = reply_ch }
			if method == 'GET' and target == '/health' [
				cmd = { op = 'health', reply = reply_ch }
			] else [
				if method == 'GET' and target == '/items' [
					cmd = { op = 'list', reply = reply_ch }
				] else [
					if method == 'GET' and target == '/metrics' [
						cmd = { op = 'metrics', reply = reply_ch }
					] else [
						if method == 'POST' and target == '/items' [
							body_str = bytes/to-str req_body
							dec = json/decode/or body_str [.none]
							if err? dec or dec == .none or not (is-json-map? dec) [
								cmd = { op = 'bad_request', reply = reply_ch }
							] else [
								raw_title = map/get/or dec 'title' [.none]
								if not (is-json-str? raw_title) [
									cmd = { op = 'bad_request', reply = reply_ch }
								] else [
									raw_prio = map/get/or dec 'priority' [.none]
									if raw_prio != .none and raw_prio != .null and not (is-json-num? raw_prio) [
										cmd = { op = 'bad_request', reply = reply_ch }
									] else [
										prio = if raw_prio == .none or raw_prio == .null [ 1 ] else [ as-i64 raw_prio ]
										cmd = { op = 'create', title = raw_title, priority = prio, reply = reply_ch }
									]
								]
							]
						] else [
							if method == 'POST' [
								done_id = parse-item-id target true
								if done_id > 0 [
									cmd = { op = 'done', id = done_id, reply = reply_ch }
								]
							] else [
								if method == 'GET' [
									get_id = parse-item-id target false
									if get_id > 0 [
										cmd = { op = 'get', id = get_id, reply = reply_ch }
									]
								]
							]
						]
					]
				]
			]

			chan/send store_ch cmd
			res = chan/recv reply_ch
			json_out = json/encode/or res.body ['{"error":"encode"}']
			hdrs = { Content-Type = 'application/json', Connection = 'close' }
			wire = http/encode-response res.status res.reason hdrs (bytes/from-str json_out)
			_ = net/write/or conn wire [0]
			served = served + 1
		]
		net/close conn
	]

	chan/close reply_ch
	served
]

accept-loop = fn [ln any, work_ch any, total_reqs i64] i64 [
	mut accepted = 0
	while accepted < total_reqs [
		conn = net/accept ln
		chan/send work_ch conn
		accepted = accepted + 1
	]
	chan/close work_ch
	accepted
]

http-call = fn [host str, port i64, method str, target str, body_str str] any [
	cli = net/connect-tcp host port
	hdrs = { Host = '127.0.0.1', Content-Type = 'application/json', Connection = 'close' }
	wire = http/encode-request method target hdrs (bytes/from-str body_str)
	_ = net/write cli wire
	resp = read-http-response cli
	net/close cli
	resp
]

// 1. Secret governance firewall check & homoiconic `http/request-to-block` + `parse-block` audit
mut admin_tok = bytes/with-secret 16b
bytes/push-all (mut admin_tok) (bytes/from-str 'vk-admin-secret')
sec_box = [admin_tok]
sec_verdict = json/encode/or { token = sec_box[0] } ['secret-json-blocked']

sample_req_wire = http/encode-request 'POST' '/items' { Host = '127.0.0.1', Content-Type = 'application/json' } (bytes/from-str '{"title":"probe"}')
sample_req = http/decode-request sample_req_wire
mut parsed_method = ''
mut parsed_target = ''
req_blk_ok = parse-block (http/request-to-block sample_req) [
	any [
		[.req m = str! t = str! _v = str! _h = map! _b = any!] [
			parsed_method = m
			parsed_target = t
		]
	]
]

// 2. Bind ephemeral loopback HTTP/1.1 listener and launch store actor + 2 workers
ln = net/listen-tcp .ip '127.0.0.1:0'
port = parse-port (net/addr ln)

store_ch = chan/new 16
work_ch  = chan/new 16

store_task = spawn [run-store-actor store_ch 2]
w1 = spawn [worker-loop work_ch store_ch]
w2 = spawn [worker-loop work_ch store_ch]
acceptor = spawn [accept-loop ln work_ch 8]

// 3. Exercise REST API over real loopback TCP HTTP/1.1 connections
t0 = time/now

r_health = http-call '127.0.0.1' port 'GET' '/health' ''
d_health = json/decode/or (bytes/to-str r_health.body) [{}]

r_c1 = http-call '127.0.0.1' port 'POST' '/items' '{"title":"compile-native","priority":3}'
d_c1 = json/decode/or (bytes/to-str r_c1.body) [{}]
c1_id = as-i64 (json/get d_c1 'id')

r_c2 = http-call '127.0.0.1' port 'POST' '/items' '{"title":"audit-wasm","priority":2}'
d_c2 = json/decode/or (bytes/to-str r_c2.body) [{}]
c2_id = as-i64 (json/get d_c2 'id')

r_bad = http-call '127.0.0.1' port 'POST' '/items' '{malformed-json'
d_bad = json/decode/or (bytes/to-str r_bad.body) [{}]

r_list = http-call '127.0.0.1' port 'GET' '/items' ''
d_list = json/decode/or (bytes/to-str r_list.body) [{}]
list_count = as-i64 (json/get d_list 'count')

r_done = http-call '127.0.0.1' port 'POST' '/items/1/done' ''
d_done = json/decode/or (bytes/to-str r_done.body) [{}]

r_miss = http-call '127.0.0.1' port 'GET' '/items/99' ''
d_miss = json/decode/or (bytes/to-str r_miss.body) [{}]

r_met = http-call '127.0.0.1' port 'GET' '/metrics' ''
d_met = json/decode/or (bytes/to-str r_met.body) [{}]
met_handled = as-i64 (json/get d_met 'handled')
met_created = as-i64 (json/get d_met 'created')
met_workers = as-i64 (json/get d_met 'workers')

elapsed = time/since t0
timing_ok = elapsed >= 0ns

// 4. Clean deterministic shutdown
accepted_total = task/await acceptor
served_total = (task/await w1) + (task/await w2)
chan/close store_ch
actor_handled = task/await store_task
net/close ln

println (str/join ['secret-firewall=' sec_verdict] '')
println (str/join ['req-block-parsed=' (mold req_blk_ok) ':' parsed_method ':' parsed_target] '')
println (str/join ['health=' (mold r_health.status) ':' (mold (json/get d_health 'status'))] '')
println (str/join ['created-ids=' (mold c1_id) ',' (mold c2_id) '|statuses=' (mold r_c1.status) ',' (mold r_c2.status)] '')
println (str/join ['malformed-json=' (mold r_bad.status) ':' (mold (json/get d_bad 'error'))] '')
println (str/join ['list-count=' (mold list_count)] '')
println (str/join ['done-item1=' (mold r_done.status) ':done=' (mold (json/get d_done 'done'))] '')
println (str/join ['missing-item=' (mold r_miss.status) ':' (mold (json/get d_miss 'error'))] '')
println (str/join ['metrics=handled:' (mold met_handled) ',created:' (mold met_created) ',workers:' (mold met_workers)] '')
println (str/join ['pool=accepted:' (mold accepted_total) ',served:' (mold served_total) ',actor:' (mold actor_handled) ',timing-ok=' (mold timing_ok)] '')