Adding a capability
The counter's only effect is Render. Most apps need more: HTTP, storage,
timers, or something of their own. The
counter-http
example is the counter with two more effects: it keeps the count on a server,
over HTTP, and hears about changes from other clients through Server-Sent
Events:
// Rust: shared/src/app.rs
#[effect(facet_typegen)]
#[derive(Debug)]
pub enum Effect {
Render(RenderOperation),
Http(HttpRequest),
ServerSentEvents(SseRequest),
}
The two are different kinds of capability. HTTP comes from crux_http, which
defines the shell side of its protocol along with the core side.
Server-Sent Events are a local capability of this app: a stream operation
declared in shared/src/sse.rs, which the shell answers with a Chunk per
batch of bytes it reads, then Done:
// Rust: shared/src/sse.rs
/// Open a Server-Sent Events stream on `url`. The shell answers with a
/// sequence of [`SseResponse`]s: a `Chunk` per batch of bytes it reads, then
/// one `Done` when the server closes the connection.
#[derive(Operation, Facet, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[operation(stream, output = SseResponse)]
pub struct SseRequest {
pub url: String,
}
#[derive(Facet, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[repr(C)]
pub enum SseResponse {
Chunk(Vec<u8>),
Done,
}
How the core uses them is the subject of Part II, from Managed Effects to Building Capabilities. Here we look at the shell.
Implementing the handler
The generated EffectHandler has an http method for the Http effect and a
serverSentEvents method for the ServerSentEvents effect.
Here's the Swift handler. HTTP is one line, delegating to
SessionHttpHandler, the shell's own HTTP client. Server-Sent Events are the
app's own capability, so the shell is the one implementing the stream, sending
each event it reads into the EffectSink it's given:
// Swift: apple/CounterApp/CounterHandler.swift
import App
import Foundation
/// `CounterHandler` is the shell's side of the effect protocol: it implements
/// the generated `EffectHandler`, which has one method per operation the app
/// declares. Nothing here calls `resolve`: the generated `EffectDispatcher`
/// does that, exactly as often as the operation's kind says.
///
/// There is no `render` method: the generated `Core` intercepts `Render`
/// before the dispatcher sees it, so the protocol's default no-op stands.
struct CounterHandler: EffectHandler {
/// The shell's own HTTP client, over the shared `URLSession` (see
/// `http.swift`).
let httpHandler = SessionHttpHandler()
/// `Http` is a request: the shell performs it and answers with exactly one
/// `HttpResult`. `SessionHttpHandler` sends the request, so this line
/// delegates.
func http(_ operation: HttpRequest) async -> HttpResult {
await httpHandler.request(operation)
}
/// `ServerSentEvents` is a stream: every item sent into `sink` is one
/// resolution of the request that opened it.
///
/// Server-Sent Events are this app's own capability (see
/// `shared/src/sse.rs`), so the shell implements the operation here. That is the pattern for any
/// custom capability.
///
/// Each complete event (the bytes up to a blank line) goes back as a
/// `chunk`, for the core to decode. When the server closes the connection
/// the stream ends with `done`, and nothing is sent after it.
func serverSentEvents(_ operation: SseRequest, into sink: EffectSink<SseResponse>) {
guard let url = URL(string: operation.url) else { return }
Task {
do {
let (bytes, _) = try await URLSession.shared.bytes(from: url)
var buffer = Data()
for try await byte in bytes {
buffer.append(byte)
if buffer.suffix(2) == Data([0x0A, 0x0A]) {
sink.send(.chunk([UInt8](buffer)))
buffer = Data()
}
}
sink.send(.done)
} catch {
print("SSE error: \(error)")
}
}
}
}
SessionHttpHandler sends the request with URLSession. As the doc of
HttpRequest says, every HTTP status is an answer, and only a transport
failure is an error:
// Swift: apple/CounterApp/http.swift
import App
import Foundation
/// Sends an `HttpRequest` over a `URLSession`.
///
/// Every response is an answer, whatever its status. Only a transport failure
/// is an error, as the doc of `HttpRequest` says.
final class SessionHttpHandler {
private let session: URLSession
init(session: URLSession = .shared) {
self.session = session
}
func request(_ operation: HttpRequest) async -> HttpResult {
// `URL(string:)` also accepts a relative URL, so check for a scheme.
guard let url = URL(string: operation.url), url.scheme != nil else {
return .err(.url("Not an absolute URL: \(operation.url)"))
}
let method = operation.method.uppercased()
if !operation.body.isEmpty, method == "GET" || method == "HEAD" {
return .err(.io("A \(method) request cannot have a body"))
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = operation.method
for header in operation.headers {
urlRequest.addValue(header.value, forHTTPHeaderField: header.name)
}
if !operation.body.isEmpty {
urlRequest.httpBody = Data(operation.body)
}
do {
let (data, response) = try await session.data(for: urlRequest)
guard let httpResponse = response as? HTTPURLResponse else {
return .err(.io("Not an HTTP response"))
}
let headers = httpResponse.allHeaderFields.compactMap { name, value in
(name as? String).map { HttpHeader(name: $0, value: "\(value)") }
}
return .ok(
HttpResponse(
status: UInt16(httpResponse.statusCode),
headers: headers,
body: [UInt8](data)
)
)
} catch let error as URLError where error.code == .timedOut {
return .err(.timeout)
} catch let error as URLError where error.code == .badURL || error.code == .unsupportedURL {
return .err(.url(error.localizedDescription))
} catch {
return .err(.io(error.localizedDescription))
}
}
}
The Kotlin
and TypeScript
handlers have the same shape. In each handler, a request's method returns its
output, and a stream's method sends each output into its sink. The generated
Core passes these outputs back to the core.
Where next
You now have the shape of every Crux app: a core that describes what it wants done, and a shell that does it, through a handler with a method per operation.
- To see what the generated
Coredoes for you, build one by hand in Part I. It builds the same counter step by step, writing the loop between the shell and the core itself. - For depth, continue to Part II, which builds a Weather app with HTTP, key-value storage, timers and location, and covers managed effects, testing with effects and building capabilities.