Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

Talking to the server

One definition, the endpoint's

A page talks to its server through endpoints: handlers for one HTTP method at one path, in a route's +server.roc, typed at both ends. The server answers a page's reads as it renders and sends the answers with the page. Event handlers send endpoints, forms post to them, and pages follow events and channels live. Other clients (another app, curl) get the same answers, behind the same middleware.

A page's data: read!#

Write a get! in a route's +server.roc, and read it in a component with Api.get_….read!(). Api is the module rocx writes, with a function per endpoint. The value is the handler's typed result, for a memo or straight in markup:

site/routes/api/echo/[message]/+server.roc
import pf.Server
import pf.Endpoint

## GET /api/echo/:message: the message, said back. The echo demo reads it for each message as the
## page renders (`Endpoint.read!`), so the page carries every answer and picking asks nothing.
get! : { request : Server.Request, params : { message : Str }, context : c } => Try(Str, Endpoint.Refusal)
get! = |{ params, .. }| Ok("Echo: ${params.message}")
site/Demos/Echo.rocx, in part
echo! : Str => Str
echo! = |message| Api.get_api_echo_message({ message: message }).read!()
…
messages : List(Str)
messages = ["the page, rendered on the server", "hello", "this site, as files"]
…
view! : {} => Html
view! = |{}| {
	(draft!, set_draft!) = create_signal!("the page, rendered on the server")
	# A GET per message, answered as the server renders; in the browser, read from the page.
	answers! = create_memo!(|| said_to!(messages))
	said! = create_memo!(|| answer_to(answers!(), draft!()))
	<form class="echo" on:submit={|| {}}>
		{...messages.map(|message|
			<button
				key={message}
				type="button"
				aria-pressed={if (message == draft!()) "true" else "false"}
				on:click={|| set_draft!(message)}
			>
				{message}
			</button>
		)}
		<Errored fallback={|problem, retry|
			<output class="echo-answer failed">
				{problem} <button type="button" on:click={retry}>Again</button>
			</output>
		}>
			<Loading fallback={<output class="echo-answer">…</output>}>
				<Answer said!={said!} />
			</Loading>
		</Errored>
	</form>
}
Echo: the page, rendered on the server

This component, live. Every answer came with the page, so a click asks nothing, even on this site's static copy.

What the runtime did, newest first

  1. Waking up…

From the server's render to a click#

  1. server The component runs as the server renders the page, and the memo reads GET /api/echo/{message} for each message. The server answers each read in-process, through the endpoint's route and middleware, with accept: application/json and the page's cookies and headers. A URL read twice is asked once.
  2. server The page goes out with the chosen answer in the <output>, and every answer in a script at its end, each under its URL (GET /api/echo/hello).
  3. browser Hydrating, the browser runs the same component. The memo finds its answers in the page and asks nothing; the server's nodes are kept.
  4. browser A click, on:click={|| set_draft!(message)}, writes the signal. The memo reruns and finds that message's answer, and the one text node showing it is patched. Nothing is asked.
  5. browser A read whose answer isn't in the page GETs the endpoint's URL: a URL built from a signal (one an <input> writes, say), a read redone with refresh!(memo!), and every read on the page after a submission's result. Meanwhile the memo keeps its last value and is_pending!(memo!) is true; <Loading> waits only for first values. Answers may arrive in any order: the memo takes only the one for its latest ask.
site/routes/(members)/members/+page.rocx, in part
member! : {} => Str
member! = |{}| Api.get_api_members({}).read!().member
site/routes/(members)/api/members/+server.roc
import pf.Server
import pf.Endpoint

## GET /api/members, as JSON: who you are, behind the same middleware as the page (/members): its
## group's.
get! : { request : Server.Request, params : {}, context : { facts : Str, member : Str } } => Try({ member : Str }, Endpoint.Refusal)
get! = |{ context, .. }| Ok({ member: context.member })

When a read fails#

An answer other than 200 fails the memo or hole that read it, and the nearest <Errored> shows its fallback, given why as text (GET /api/notes/9: 404: Not found) and a function that tries again. To handle a refusal yourself, use Api.get_….send!({}) instead, which returns Ok(result) or Err(problem). A problem is a Server.Problem:

A refusal met during the server's render goes in the page too, so the browser fails in the same place without asking again.

Who is asking#

The server's GETs during a render carry the page's cookies and headers. So a handler works out who is asking from the request, whoever sent it, and never takes the browser's word for it. The bag on the components page finds its owner this way:

site/Demos/Bag.rocx, in part
## Who is reading: `GET /api/reader`, what a session would say on the server (here, always Ada).
## The server renders the bag with it, and puts the answer in the page, so the browser doesn't ask
## again.
reader! : {} => Str
reader! = |{}| Api.get_api_reader({}).read!()
site/routes/api/reader/+server.roc
import pf.Server
import pf.Endpoint

## GET /api/reader: who is reading, as a session would say on the server (here, always Ada). The
## bag demo reads it as the page renders, and the page carries the answer.
get! : { request : Server.Request, params : {}, context : c } => Try(Str, Endpoint.Refusal)
get! = |_| Ok("Ada")

What its directories' middleware hands on, such as who is signed in, is a handler's context: get! = |{ context, .. }| Ok({ member: context.member }) (middleware). A handler can use what only the server has (the database, Kv, jobs, email), and none of it reaches the browser.

Endpoints: +server.roc#

A route's +server.roc (+server.rocx if it has markup) answers HTTP methods at its path: get!, post!, put!, patch! and delete!. Each handler is given a record: the request, the path's params (strings, or the types its annotation gives them), its middleware's context and, for a method with a body, the body, read as its annotated type. It answers Ok(result), sent as JSON, or Err(refusal), sent as a status and why. An Endpoint.Refusal is:

A handler whose answer is always its own (a redirect that sets a cookie, a file) is annotated Try(Server.Response, Endpoint.Refusal) and answers Ok(response), sent as is. A route file may also name rules to read and check its body with (post_body); a body that fails them is refused before the handler runs.

site/routes/api/shout/+server.roc
import pf.Server
import pf.Endpoint

## POST /api/shout: what it is sent, shouted. Nothing to shout is refused, with a 400.
post! : { request : Server.Request, params : {}, context : c, body : Str } => Try(Str, Endpoint.Refusal)
post! = |{ body, .. }|
	if (body.trim().is_empty()) Err(BadRequest("say something to shout")) else Ok(body.with_ascii_uppercased())
site/routes/api/shout/[word]/+server.roc
import pf.Server
import pf.Endpoint

## GET /api/shout/:word: the word, shouted, and how many bytes it has.
get! : { request : Server.Request, params : { word : Str }, context : c } => Try({ word : Str, shouted : Str, bytes : U64 }, Endpoint.Refusal)
get! = |{ params, .. }|
	Ok({ word: params.word, shouted: params.word.with_ascii_uppercased(), bytes: params.word.to_utf8().len() })

What they answered when this page's endpoint asked them during its render:

RequestBodyStatusAnswer
GET /api/shout/rocx none 200 {"bytes":4,"shouted":"ROCX","word":"rocx"}
POST /api/shout "hi" 200 "HI"
POST /api/shout "" 400 say something to shout
POST /api/shout {} 400 POST /api/shout can't read its body: Invalid JSON

The app calls them as functions. rocx writes Generated/Api.roc, the app's contract: for each endpoint, a function of the path's params ({} with none), typed by the handler's annotation. It holds the method, URL and types, nothing the handler does, so the browser gets it too and any module may import it: a component, a route, a job, an actor. Generated/Handlers.roc, the server's alone, binds each endpoint to its handler for the router (Endpoint.bind checks that the two agree):

Generated/Api.roc, both copies
post_api_shout : {} -> Endpoint(context, Str, Str)
post_api_shout = |_params| Endpoint.remote("POST", "/api/shout")
get_api_shout_word : { word : Str } -> Endpoint(context, {}, { word : Str, shouted : Str, bytes : U64 })
get_api_shout_word = |params| Endpoint.remote("GET", "/api/shout/${Server.encode_segment(params.word)}")
Generated/Handlers.roc, the server's
post_api_shout = |params| Endpoint.bind(Api.post_api_shout(params), |request, context, body| ApiShoutServer.post!({ request: request, params: params, context: context, body: body }))
get_api_shout_word = |params| Endpoint.bind(Api.get_api_shout_word(params), |request, context, {}| ApiShoutWordServer.get!({ request: request, params: params, context: context }))

In the browser, an event handler (an on:click, say) sends any endpoint with Api.….send!(arg) and gets Ok(result) or Err(problem). The handler pauses until the answer is in, then runs again; only that run's writes are kept. This component shouts the clicked word, Api.get_api_shout_word({ word: word }).send!({}). On this site's static copy, the three words' answers are files written at build time:

What the runtime did, newest first

  1. Nothing yet: shout a word.

On the server, a handler sends the app's own endpoints the same way, Api.….send!(arg), answered in-process: no HTTP, but through the endpoint's route and middleware, with the request's headers (cookies, authorization). What guards an endpoint guards every way to it, an MCP tool's call too. This page's endpoint asked the shout endpoint this way: ROCX, 4 bytes.

The component: site/Demos/Shout.rocx
site/Demos/Shout.rocx
import pf.Html
import pf.Solid exposing [create_signal!]
import pf.Server as Http
import ../Generated/Api

## Asks an endpoint, `GET /api/shout/{word}`, which a route's `+server.roc` answers, for the word
## clicked. `Api.get_api_shout_word` is what rocx wrote for it: on the server, the handler; in the
## browser's copy, its method and URL. A handler that asks the server waits for the answer: it runs
## again once the answer is in, and only that run's writes are kept. A copy of the site as files has
## these words' answers as files, which the server wrote as the site was built.
Shout := [].{
	Answer : [Nothing, Shouted(Str), Failed(Str)]

	## The words there are buttons for.
	words : List(Str)
	words = ["rocx", "hello", "static"]

	view! : {} => Html
	view! = |{}| {
		(answer!, set_answer!) = create_signal!(nothing)
		shout! = |word| {
			sent : Try({ word : Str, shouted : Str, bytes : U64 }, Http.Problem)
			sent = Api.get_api_shout_word({ word: word }).send!({})
			match sent {
				Ok(shouted) => set_answer!(Shouted("${shouted.shouted}: ${shouted.bytes.to_str()} bytes"))
				Err(problem) => set_answer!(Failed(explain(problem)))
			}
		}
		<div class="echo shout">
			{...words.map(|word|
				<button key={word} type="button" on:click={|| shout!(word)}>{"Shout “${word}”"}</button>
			)}
			<output class="echo-answer" class:failed={failed(answer!())}>{said(answer!())}</output>
		</div>
	}

	<style>
		.echo {
			display: flex;
			flex-wrap: wrap;
			gap: var(--space-2);
		}

		button {
			background: var(--accent);
			color: var(--accent-text);
		}

		button:hover:not(:disabled) {
			background: var(--accent-strong);
		}

		.echo-answer {
			flex-basis: 100%;
			min-height: 1.5em;
			padding: var(--space-3) var(--space-4);
			border-radius: var(--radius-sm);
			background: var(--bg-sunken);
			font: var(--size-sm) var(--mono);
		}

		.failed {
			background: var(--bad-soft);
			color: var(--bad);
		}
	</style>
}

nothing : Shout.Answer
nothing = Nothing

said : Shout.Answer -> Str
said = |answer|
	match answer {
		Nothing => ""
		Shouted(shouted) => shouted
		Failed(why) => why
	}

failed : Shout.Answer -> Bool
failed = |answer|
	match answer {
		Failed(_) => Bool.True
		_ => Bool.False
	}

explain : Http.Problem -> Str
explain = |problem|
	match problem {
		HttpErr(why) => "No answer: ${why}"
		Refused(404, _) => "No server here: this copy of the site is static files. With just dev, Roc answers."
		Refused(status, text) => "Refused (${status.to_str()}): ${text}"
		BadAnswer(why) => "The answer wasn't a Str: ${why}"
	}

Forms: actions and submissions#

A form posts to an endpoint like any HTML form, and the endpoint reads the fields by its body's type. For { name : Str, count : U64, gift : Bool, toppings : List(Str) }, a number is read from its text, an unticked box is Bool.False, and a name sent several times is a list. A missing or wrong field is a 400 that names it. JSON and forms read into the same typed record, so one endpoint takes both.

What Solid Router calls an action is the endpoint here: it already has a URL, a method and types. use_submission!(endpoint), in a component, is the latest submission to it: whether it is on its way, what was sent, and the result or refusal.

A form that shows its refusal
import pf.Router exposing [use_submission!]

join = Api.post_api_members_join({})
submission = use_submission!(join)
<form method="post" action={Endpoint.url_of(join)}>
	<input name="name" value={submission.field!("name")} />
	<button disabled?={submission.pending!()}>Join</button>
	{match submission.error!() {
		Ok(problem) => <p class="problem">{Server.explain(problem)}</p>
		Err(_) => <></>
	}}
</form>

Where Roc Solid differs from Solid Router here:

Events, as they happen#

An answer is sent once it is whole. For what the server learns piece by piece (a job's progress, a feed, what others did), an endpoint can stream server-sent events instead: events! in a +server.roc answers a GET asking for events (accept: text/event-stream) with Events. This one sends each count from 1 to params.to with its square, 300 ms apart:

site/routes/api/count/[to]/+server.roc
import pf.Server
import pf.Endpoint
import pf.Events

## GET /api/count/5, asked for its events (`accept: text/event-stream`): 1 to 5, each with its
## square, 300 ms apart. A loop: send, sleep, round again; if the page goes, `send!` says so, and
## `?` ends the loop. Its param is a number (`/api/count/five` is no route: 404).
events! : { request : Server.Request, params : { to : U64 }, context : c } => Try(Events({ count : U64, of : U64, square : U64 }), Endpoint.Refusal)
events! = |{ params, .. }| {
	to = params.to
	if to < 1 or to > 20 {
		Err(BadRequest("count to a number from 1 to 20"))
	} else {
		Ok(
			Events.stream(
				|{ send!, sleep! }| {
					var $count = 1
					while $count <= to {
						send!({ count: $count, of: to, square: $count * $count })?
						sleep!(300)
						$count = $count + 1
					}
					Ok({})
				},
			),
		)
	}
}
site/Demos/Count.rocx, in part
start! = || {
	set_heard!([])
	set_state!(Listening)
	Endpoint.listen!(
		Api.events_api_count_to({ to: U64.from_str(to!().trim()) ?? 0 }),
		|event|
			match event {
				Event(counted) => set_heard!(heard!().append(counted))
				Ended => set_state!(Done)
				Failed(problem) => set_state!(Failed(explain(problem)))
			},
	)
}

It isn't live here: this site's static copy is files and can't stream. With just dev, the curl above shows one.

The component: site/Demos/Count.rocx
site/Demos/Count.rocx
import pf.Html
import pf.Solid exposing [create_signal!]
import pf.Endpoint
import pf.Server as Http
import ../Generated/Api

## Listens to an endpoint's events, `GET /api/count/[to]` (a route's `events!`): Start, and the
## server sends each count as it makes it; the component shows each as it comes, says when the server
## stopped sending (it ended the stream), and can start again. `Api.events_api_count_to` is what
## rocx wrote for it, the same in both copies: its URL, and the type of its events, copied from the
## handler's annotation (D-037).
Count := [].{
	State : [Idle, Listening, Done, Failed(Str)]

	view! : {} => Html
	view! = |{}| {
		(to!, set_to!) = create_signal!("5")
		(heard!, set_heard!) = create_signal!([])
		(state!, set_state!) = create_signal!(idle)
		# Each event is a handler's run: what it writes is applied, as a click's is.
		start! = || {
			set_heard!([])
			set_state!(Listening)
			Endpoint.listen!(
				Api.events_api_count_to({ to: U64.from_str(to!().trim()) ?? 0 }),
				|event|
					match event {
						Event(counted) => set_heard!(heard!().append(counted))
						Ended => set_state!(Done)
						Failed(problem) => set_state!(Failed(explain(problem)))
					},
			)
		}
		<div class="count">
			<form class="echo" on:submit={start!}>
				<label class="count-to">
					Count to
					<input type="number" aria-label="Count to (1 to 20: the server refuses others)" value={to!()} on:input.value={set_to!} />
				</label>
				<button type="submit" disabled?={state!() == Listening}>{button(state!())}</button>
				<output class={"echo-answer stream ${kind(state!())}"}>{status(state!(), heard!().len())}</output>
			</form>
			<ol class="counted" aria-live="polite">
				{...heard!().map(|counted|
					<li key={counted.count.to_str()}>{counted.count.to_str()} of {counted.of.to_str()}: squared, {counted.square.to_str()}</li>
				)}
			</ol>
		</div>
	}

	<style>
		.echo {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			gap: var(--space-2);
		}

		.count-to {
			display: flex;
			align-items: center;
			gap: var(--space-2);
		}

		input {
			width: 5rem;
			min-width: 0;
		}

		button {
			background: var(--accent);
			color: var(--accent-text);
		}

		button:hover:not(:disabled) {
			background: var(--accent-strong);
		}

		.echo-answer {
			flex-basis: 100%;
			min-height: 1.5em;
			font: var(--size-sm) var(--mono);
		}

		/* Whether the stream is open: a dot that pulses while it is, a square once the server stopped. */
		.stream::before {
			content: "";
			display: inline-block;
			width: 0.6em;
			height: 0.6em;
			margin-right: 0.5em;
			border-radius: 50%;
			background: currentColor;
			opacity: 0.35;
			vertical-align: 0.05em;
		}

		.stream.live::before {
			background: var(--good);
			box-shadow: 0 0 8px var(--good);
			opacity: 1;
			animation: live 1s ease-in-out infinite alternate;
		}

		.stream.stopped::before {
			border-radius: 2px;
			opacity: 0.7;
		}

		.stream.failed::before {
			background: var(--bad);
			opacity: 1;
		}

		@keyframes live {
			to {
				opacity: 0.3;
			}
		}

		.counted {
			margin: var(--space-2) 0 0;
			padding-left: var(--space-6);
			font: var(--size-sm) var(--mono);
		}

		.counted li {
			animation: counted 0.3s ease-out;
		}

		@keyframes counted {
			from {
				opacity: 0;
				transform: translateY(-0.25rem);
			}
		}

		@media (prefers-reduced-motion: reduce) {
			.stream.live::before,
			.counted li {
				animation: none;
			}
		}
	</style>
}

idle : Count.State
idle = Idle

button : Count.State -> Str
button = |state|
	match state {
		Idle => "Start"
		Listening => "Streaming…"
		_ => "Start again"
	}

kind : Count.State -> Str
kind = |state|
	match state {
		Idle => ""
		Listening => "live"
		Done => "stopped"
		Failed(_) => "failed"
	}

status : Count.State, U64 -> Str
status = |state, count| {
	received = "${count.to_str()} ${if (count == 1) "count" else "counts"}"
	match state {
		Idle => "Not listening: Start, and the server sends a count every 300 ms."
		Listening => "Live: ${received} so far, the stream is open"
		Done => "Stopped: the server sent ${received} and ended the stream"
		Failed(why) => why
	}
}

explain : Http.Problem -> Str
explain = |problem|
	match problem {
		HttpErr(why) => "No answer: ${why}"
		Refused(404, _) => "No server here: this copy of the site is static files. With just dev, Roc answers."
		Refused(status_code, text) => "Refused (${status_code.to_str()}): ${text}"
		BadAnswer(why) => "An event wasn't a count: ${why}"
	}

expect status(Listening, 1) == "Live: 1 count so far, the stream is open"
expect status(Done, 3) == "Stopped: the server sent 3 counts and ended the stream"

Channels: live data for a page#

Each listen! is its own stream, checked once as it starts. For data a page follows live (a board others edit, who is online), use a channel. A route's +server.roc defines one with channel!, a check that lets a subscriber in (Channel.allow(who)) or refuses it. Its annotation types what the server publishes and what pages may say. A lobby that lets everyone in, and a component that subscribes:

site/routes/api/platform/live/lobby/+server.roc
import pf.Server
import pf.Endpoint
import pf.Channel

## The lobby, a channel: anyone may join, and every tab that has hears each wave as it is
## made. Its check lets everyone in; a tab is named by the first letters of its id.
channel! : { request : Server.Request, params : {}, context : c } => Try(Channel({}, { hand : Str, from : Str }, [Wave(Str)]), Endpoint.Refusal)
channel! = |_| Ok(Channel.allow({}))

## What a page says: a wave, published to everyone in the lobby. Only these hands.
receive! = |{ tab, said, channel, .. }|
	match said {
		Wave(hand) =>
			if ["👋", "🎉", "🙌"].contains(hand) {
				Endpoint.publish!(channel, { hand, from: short(tab) })
				Ok({})
			} else {
				Err(BadRequest("wave 👋, 🎉 or 🙌"))
			}
	}

## A subscriber is greeted first, each time it joins.
on_open! = |{ tab, .. }| [{ hand: "👋", from: "the lobby, to tab ${short(tab)}" }]

short = |tab| Str.from_utf8_lossy(tab.to_utf8().take_first(4))
site/Demos/Lobby.rocx, in part
lobby = Api.channel_api_platform_live_lobby({})
create_effect!(
	|| {},
	|{}|
		lobby.subscribe!(
			|event|
				match event {
					Resync => set_state!("In the lobby. Open this page in another tab, join there too, and wave.")
					Message(wave) => set_waves!(waves!().take_last(5).append("${wave.hand} from ${wave.from}"))
					Refused(_, why) => set_state!("No lobby here: ${why}")
					Ended(why) => set_state!("Left: ${why}")
				},
		),
)
		…
		{...["👋", "🎉", "🙌"].map(|hand|
			<button key={hand} type="button" class="wave" on:click={|| lobby.say!(Wave(hand))}>{hand}</button>

The lobby is live on the live and channels page, with the rest: hooks, reconnecting, the latest value with each key.

What rocx build does#

  1. It names each endpoint by its method and path, in Generated/Api.roc: get_api_echo_message for get! in routes/api/echo/[message]/+server.roc. It is a function of the path's params, so no URL is written twice and wrong params don't compile. Its type is copied from the handler's annotation (body and answer; a channel's Channel(who, message, said)), with the imports those types need and no route file. So a module a route imports (a store, a job, an actor) may import Api too, and publish on a channel by name. A module defining a type a route's annotation names can't import Api, since Api imports it: rocx build says so, and suggests moving the type to a module of its own.

  2. It routes them. Generated/Routes.roc gives each path's requests to its page or its endpoints (each with its handler from Generated/Handlers.roc), behind its folders' middleware. The server's GETs during a render go the same way.

  3. It leaves the handlers out of the browser's copy. The browser's app is built from a copy of the app rocx writes (rocx generate --client <dir>), with the same Api but no Handlers and no middleware: only the server runs those, and they may read the environment or the database.

Coming from SolidStart#

SolidStart has server functions ("use server"): code the browser calls at a URL the framework picks. Roc Solid has none. A page's data is a get! endpoint at a URL you choose, read with Api.get_…(params).read!(), so the server's render, hydration, later reads, other clients and the OpenAPI document all meet one handler, behind one middleware. rocx build refuses server!(…) and says what to write instead.

Limits, for now#