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:
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}")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>
}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
- Waking up…
From the server's render to a click#
- 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, withaccept: application/jsonand the page's cookies and headers. A URL read twice is asked once. - 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). - 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.
- 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. - 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 withrefresh!(memo!), and every read on the page after a submission's result. Meanwhile the memo keeps its last value andis_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.
member! : {} => Str
member! = |{}| Api.get_api_members({}).read!().memberimport 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:
HttpErr(why): no answer came (the network, say);Refused(status, why): the endpoint's or its middleware's refusal, or a 404 for a path the server doesn't have;BadAnswer(why): an answer of another type, from a server of another build.
A refusal met during the server's render goes in the page too, so the browser fails in the same place without asking again.
- A redirect redirects the whole page. When a read's middleware redirects during the render (a signed-out visitor sent to sign in), the page answers with that redirect.
- A failure nothing catches shows the app's error page (
routes/+error.rocx), with the refusal's status if it is a 4xx: an endpoint answeringNotFoundmakes the page a 404. A 5xx, or no answer, is a 500. When an<Errored>catches the failure, its fallback shows and the page is a 200, unless the fallback sets a status with<HttpStatusCode>. - Guard the root layout's reads. They run for every page, with nothing above to catch a failure. Wrap the holes that read in an
<Errored>, or one failure makes every page a 500.
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:
## 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!()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:
BadRequest(why)(400),Unauthorized(401),Forbidden(403),NotFound(404),Conflict(why)(409) orStatus(code, why);Json(code, json): a JSON body, sent asapplication/json, such as a form's issues (Issues.refusal);Answer(response): a response of its own in the result's place (JSON with a cookie).
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.
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())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:
| Request | Body | Status | Answer |
|---|---|---|---|
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):
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)}")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
- 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.
- A path is a page or an endpoint. A page's endpoints live under
routes/api/, at the page's path. A directory holding both still works: a browser's GET (accepting HTML) gets the page, anything else the endpoints, each answer sayingVary: Accept. An unanswered method is a 405 listing the answered ones (Allow). - Behind middleware. A POST, PUT, PATCH or DELETE from another site's page (its
Originisn't this server) gets a 403, unless the app sayscross_site: Allowed. Clients that aren't pages, such ascurl, send noOriginand get through. A directory's+middleware.rocadds more around its routes (middleware). - Typed at both ends. Both copies of
Apitake their types from the handler's annotation, whichrocx buildrequires. A component that sends the wrong body, or reads the answer as anything else, doesn't compile, androcx checkpoints at its line. - JSON both ways. An
F64goes as a number; NaN or an infinity, which JSON can't write, is a 500 that says so. ATrygoes as its tag,{"Ok":5}or{"Err":"Empty"}, except two shapes:Try(a, [Null])is a value that may benull, and a record field'sTry(a, [Missing])may be left out.
The component: 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.
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>- With JavaScript, the runtime sends every form that posts to one of the app's endpoints with
fetch, and the page stays.pending!()is true while the answer is on its way and, after a result, until the page's reads are read again, so the new data and the result show together. Thenresult!()is the result, orerror!()the refusal (Refused(409, "…")) or why no answer came.input!()is what was sent, as the endpoint reads it. After a refusal,field!(name)gives back what was typed in a field; after a result it is"", and the form is emptied (unless it, or what is around it, saysdata-rocx-keep, which keepsfield!too), so an add form isn't filled again;emptied!()says whether it was, for a page that keeps what was typed in signals of its own. Only the latest submission counts; in an event handler,clear!()forgets it andretry!()sends it again. An endpoint's redirect (Ok(Server.redirect(…)), setting a cookie, say) sends the browser there in place, and the layouts it keeps read their data again. - A form nothing on the page reads (no component reads its endpoint's submissions) is answered as a plain form, still without a load: back to its page with the flash, or to the endpoint's redirect. Coming back to the page it is on keeps the page, its signals and its scroll. If the answer is a failure (a 500, a middleware's refusal), the nearest
<Errored>around the form shows it. - What the server rendered follows too. After a result, a
<NoHydration>part that read an endpoint as the server rendered it is taken again from the page's new document. One that read nothing costs nothing. - Leave one to the browser with
data-rocx-reloadon the form, its button or an element around it: a plain post and a load, as for a sign-out that must drop every state. - Without JavaScript (before the runtime loads, or with it off), the form posts as forms always have. Instead of JSON or text, which the browser would show as a bare page, the endpoint sends the browser back to the form's page with a flash: where the form posted, what was typed, and the result or refusal. The server keeps the flash for a minute (a cookie holds its id) for the next page view to read once; a typed password is never sent back. There the submission is the flash, so the page shows the refusal and the typed field as it would with JavaScript, and hydrates as rendered.
Server.flash!({})reads the flash as it came. - The endpoint says where to go next, either way:
Ok(Server.redirect(…)), its annotation answeringServer.Response, as behind this site's joining page (which sets a cookie too). - Without a form.
use_action!(endpoint)(Solid Router'suseAction) is a function an event handler calls with the endpoint's arg. Each call is a submission, sent as JSON once the handler is done; the handler doesn't wait for the answer. - Every submission, and optimistic values.
use_submissions!(endpoint)(useSubmissions) lists every submission to an endpoint, from forms or actions:all!(),pending!(),pending_inputs!(),clear!(id)andretry!(id). An optimistic value is a memo of the endpoint's data withpending_inputs!()applied: see actions and optimistic values, live on the components page. - Files. A form with an
<input type="file">(enctype="multipart/form-data") is sent as the browser sends it, with or without JavaScript. The endpoint reads a file's field as the file's name, and the file withServer.file(request, "photo"): its name, type and bytes, whichStorage.put_upload!can keep. An action whose arg holds the URL of a file the page has (dropped, pasted or picked) is sent the same way. A request's body, files included, is 16 MiB at most unless the server's--max-bodysays more; over that, the answer is a 413.
Where Roc Solid differs from Solid Router here:
- A record has no getters, so a submission's fields are methods (
submission.pending!()), andinput!()is the endpoint's own type, not aFormData. - The form's
actionisEndpoint.url_of(endpoint): Roc can't turn an endpoint into a string by itself. - Solid's
action.withisEndpoint.with_fields(endpoint, { id }), which puts fields in the form's URL; an action binds its values with a closure instead. - Revalidate keys are URLs, not query keys: the handler names which of the page's reads a result redoes with
Router.revalidate!([url]), each a URL or its beginning.
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:
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({})
},
),
)
}
}- A stream is a loop.
Events.streamis givensend!, to send an event, andsleep!, to wait some milliseconds; the stream ends when the loop returns. The server runs it as a call of its own, paused while it sleeps, so it holds up no other request. When the page goes,send!answersErr(Gone), a sleep ends early, and?ends the loop.Events.from_list(items, ms)andEvents.mapmake the simple ones. - Each event is JSON, typed by
events!'s annotation, sent as adata:line; anendevent closes the stream, so the browser doesn't ask again. Anything may listen:curl -N -H 'accept: text/event-stream' localhost:8080/api/count/3. - A component listens with
Endpoint.listen!(endpoint, heard!).heard!runs like a click's handler: withEvent(counted)for each event, typed as the endpoint's events; thenEnded; orFailed(problem), a refusal beingRefused(status, why). Started from an effect or an event handler, it listens until its component goes. When an event says an endpoint's data changed,refresh!(memo!)reads it again. - Behind middleware, as any endpoint. A guard refuses a stream before the loop runs.
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
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:
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))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>- Subscribe from an effect.
Endpoint.subscribe!hears the channel until the effect runs again or its component goes.Endpoint.say!sends to the server, where the route'sreceive!hears it. - Publish from anywhere on the server:
Endpoint.publish!, from a request, a job or an actor, reaches every page subscribed with the same params, in the order published. - One stream a tab. A tab's subscriptions share one connection. Each channel's check runs again every 15 seconds, so someone who loses access stops hearing. A subscriber that may have missed something hears
Resync, its cue to read its data again.
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#
It names each endpoint by its method and path, in
Generated/Api.roc:get_api_echo_messageforget!inroutes/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'sChannel(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 buildsays so, and suggests moving the type to a module of its own.It routes them.
Generated/Routes.rocgives each path's requests to its page or its endpoints (each with its handler fromGenerated/Handlers.roc), behind its folders' middleware. The server's GETs during a render go the same way.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 sameApibut noHandlersand 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#
- A page reads with GET. During a render, the server answers GETs of the app's own endpoints (a path,
/…). A POST or another site's URL is for an event handler to send from the browser. For another server's data during a render, give the app an endpoint whose handler fetches it withHttp.fetch!(url, init). - Types must compile in the browser. A handler may use what only the server has, but the types it takes and answers must compile in the browser's copy:
rocx buildrefuses a type from a module that importspf.Db, at the route's line, naming the type and the module. - A static copy of the site has no server. Its pages are files, and so are the answers the server gave at build time: each page's GETs, in the page, and the GETs its components send from event handlers (
just sitewrites those). Any other read, a POST or a stream needs the server (just dev, or wherever the app runs). roc-solid.github.io is such a copy: this page's echo and shout work there, and a demo that sends or follows something (the planner's moves, the lobby's channel) says no server answers. - Only the endpoints' handlers stay on the server. Anything else a component imports ships to the browser. The server must check each request itself.