ewe

Types

Possible errors that can occur when reading a body.

pub type BodyError {
  BodyTooLarge
  InvalidBody
}

Constructors

  • BodyTooLarge

    Body is larger than the provided limit.

  • InvalidBody

    Body is malformed.

Contains all server configurations, can be adjusted by different builder functions.

pub opaque type Builder

Represents a chunked response body. This type is used to send a chunked response to the client.

pub type ChunkedBody =
  @internal ChunkedBody

Represents an instruction on how chunked response should be processed.

  • continue processing the chunked response.
  • stop the chunked response normally.
  • stop the chunked response with abnormal reason.
pub opaque type ChunkedNext(user_state)

WebSocket close codes that can be sent when closing a connection. The data parameter allows you to include payload up to 123 bytes in size.

pub type CloseCode {
  NormalClosure(data: String)
  InvalidPayloadData(data: String)
  PolicyViolation(data: String)
  MessageTooBig(data: String)
  InternalError(data: String)
  ServiceRestart(data: String)
  TryAgainLater(data: String)
  BadGateway(data: String)
  CustomCloseCode(code: Int, data: String)
  NoCloseReason
}

Constructors

  • NormalClosure(data: String)

    Standard graceful shutdown (1000). Use when connection completed successfully.

  • InvalidPayloadData(data: String)

    Invalid message format (1007). Received payload that doesn’t match what you expected.

  • PolicyViolation(data: String)

    Application policy violation (1008).Client broke your rules - failed authentication, hit rate limits, or violated business logic.

  • MessageTooBig(data: String)

    Message exceeds size limits (1009). Client sent something bigger than your application allows.

  • InternalError(data: String)

    Server encountered unexpected error (1011). Something went wrong on your side that prevents handling the connection.

  • ServiceRestart(data: String)

    Server is restarting (1012). Planned restart - clients can reconnect after a bit.

  • TryAgainLater(data: String)

    Temporary server overload (1013). Use when server is temporarily unavailable, client should retry.

  • BadGateway(data: String)

    Gateway/proxy received invalid response (1014). You’re acting as a proxy and the upstream server gave you garbage.

  • CustomCloseCode(code: Int, data: String)

    Custom close codes 3000-4999 for application-specific use.

  • NoCloseReason

    Close without a specific reason.

Represents the request body and connection metadata. Access the body using ewe.read_body, or retrieve client information with ewe.get_client_info.

pub type Connection =
  @internal Connection

A convenient alias for a consumer that reads N amount of bytes from the request body stream.

pub type Consumer =
  fn(Int) -> Result(Stream, BodyError)

Error type returned by ewe.file when opening a file for the response body.

pub type FileError {
  NoEntry
  NoAccess
  IsDirectory
  UnknownFileError(dynamic.Dynamic)
}

Constructors

  • NoEntry

    File does not exist.

  • NoAccess

    Missing permission for reading the file, or for searching one of the parents directories.

  • IsDirectory

    The named file is a directory.

  • UnknownFileError(dynamic.Dynamic)

    Untypical file error.

Represents an IP address. Can be either IPv4 or IPv6.

pub type IpAddress {
  IpV4(Int, Int, Int, Int)
  IpV6(Int, Int, Int, Int, Int, Int, Int, Int)
}

Constructors

  • IpV4(Int, Int, Int, Int)
  • IpV6(Int, Int, Int, Int, Int, Int, Int, Int)

A convenient alias for a HTTP request with a Connection as the body.

pub type Request =
  request.Request(Connection)

A convenient alias for a HTTP response with a ResponseBody as the body.

pub type Response =
  response.Response(ResponseBody)

Represents possible response body options.

Types for direct usage:

  • Regular data: TextData, BytesData, BitsData, StringTreeData, Empty.

Types that should never be used directly:

  • File: see ewe.file to construct it.
  • Chunked: indicates that response body is being sent in chunks with chunked transfer encoding.
  • Websocket: indicates that request is being upgraded to a WebSocket connection.
  • SSE: indicates that request is being upgraded to a Server-Sent Events connection.
pub type ResponseBody {
  TextData(String)
  BytesData(bytes_tree.BytesTree)
  BitsData(BitArray)
  StringTreeData(string_tree.StringTree)
  Empty
  File(descriptor: @internal IoDevice, offset: Int, size: Int)
  Chunked
  Websocket
  SSE
}

Constructors

  • TextData(String)

    Allows to set response body from a string.

  • Allows to set response body from bytes.

  • BitsData(BitArray)

    Allows to set response body from bits.

  • StringTreeData(string_tree.StringTree)

    Allows to set response body from a string tree.

  • Empty

    Allows to set empty response body.

  • File(descriptor: @internal IoDevice, offset: Int, size: Int)

    Allows to set response body from a file more efficiently rather than sending contents in regular data types.

  • Chunked

    Indicates that response body is being sent in chunks with chunked transfer encoding.

  • Websocket

    Indicates that request is being upgraded to a WebSocket connection.

  • SSE

    Indicates that request is being upgraded to a Server-Sent Events connection.

Represents a Server-Sent Events connection between a client and a server.

pub type SSEConnection =
  @internal SSEConnection

Represents a Server-Sent Events event. The event fields are:

  • event: a string identifying the type of event described.
  • data: the data field for the message.
  • id: event ID.
  • retry: The reconnection time. If the connection to the server is lost, the browser will wait for the specified time before attempting to reconnect.

Can be created using ewe.event and modified with ewe.event_name, ewe.event_id, and ewe.event_retry.

pub type SSEEvent =
  @internal SSEEvent

Represents an instruction on how Server-Sent Events connection should proceed.

  • continue processing the Server-Sent Events connection.
  • stop the Server-Sent Events connection.
  • stop the Server-Sent Events connection with abnormal reason.
pub opaque type SSENext(user_state)

Represents a socket address with IP and port. Use ewe.get_lcient_info to get the client’s address from a connection, or ewe.get_server_info to get the server’s bound address.

pub type SocketAddress {
  SocketAddress(ip: IpAddress, port: Int)
}

Constructors

The progress of reading the request body stream.

pub type Stream {
  Consumed(
    data: BitArray,
    next: fn(Int) -> Result(Stream, BodyError),
  )
  Done
}

Constructors

  • Consumed(
      data: BitArray,
      next: fn(Int) -> Result(Stream, BodyError),
    )

    Chunk of data has been consumed.

  • Done

    Signifies that the request body stream has been fully consumed.

Represents a WebSocket connection between a client and a server.

pub type WebsocketConnection =
  @internal WebsocketConnection

Represents a WebSocket message received from the client.

pub type WebsocketMessage(user_message) {
  Text(String)
  Binary(BitArray)
  User(user_message)
}

Constructors

  • Text(String)

    Indicate that text frame has been received.

  • Binary(BitArray)

    Indicate that binary frame has been received.

  • User(user_message)

    Indicate that user message has been received from WebSocket selector.

Represents an instruction on how WebSocket connection should proceed.

  • continue processing the WebSocket connection.
  • continue processing the WebSocket connection with selector for custom messages.
  • stop the WebSocket connection.
  • stop the WebSocket connection with abnormal reason.
pub opaque type WebsocketNext(user_state, user_message)

Values

pub fn bind(
  builder: Builder,
  interface interface: String,
) -> Builder

Binds server to a specific network interface (e.g., “0.0.0.0” for all IPv4 interfaces or “127.0.0.1” for localhost). To bind to IPv6 addresses like “::” or “::1”, you must use ewe.enable_ipv6. Crashes the program if the interface is invalid.

pub fn chunked_body(
  req: request.Request(Connection),
  resp: response.Response(a),
  on_init on_init: fn(process.Subject(user_message)) -> user_state,
  handler handler: fn(ChunkedBody, user_state, user_message) -> ChunkedNext(
    user_state,
  ),
  on_close on_close: fn(ChunkedBody, user_state) -> Nil,
) -> response.Response(ResponseBody)

Sets up the connection for chunked response.

on_init function is called once the chunked response process is initialized. The argument is subject that can be used to send chunks to the client. It must return initial state.

handler function is called for every message received. It must return instruction on how chunked response should proceed.

on_close function is called when the chunked response process is going to be stopped.

pub fn chunked_continue(
  user_state: user_state,
) -> ChunkedNext(user_state)

Instructs chunked response to continue processing.

pub fn chunked_stop() -> ChunkedNext(user_state)

Instructs chunked response to stop normally.

pub fn chunked_stop_abnormal(
  reason: String,
) -> ChunkedNext(user_state)

Instructs chunked response to stop with abnormal reason.

pub fn enable_ipv6(builder: Builder) -> Builder

Enables IPv6 support, allowing the server to accept connections over IPv6 addresses. Must be called for binding to IPv6 addresses via ewe.bind.

pub fn enable_tls(
  builder: Builder,
  certificate_file certificate_file: String,
  key_file key_file: String,
) -> Builder

Enables TLS (HTTPS) support, with provided certificate and key files. Crashes the program if the files don’t exist or are invalid.

pub fn event(data: String) -> SSEEvent

Creates a new SSE event with the given data. Use ewe.event_name, ewe.event_id, and ewe.event_retry to modify other fields of the event.

pub fn event_id(event: SSEEvent, id: String) -> SSEEvent

Sets the ID of the event.

pub fn event_name(event: SSEEvent, name: String) -> SSEEvent

Sets the name of the event.

pub fn event_retry(event: SSEEvent, retry: Int) -> SSEEvent

Sets the retry time of the event.

pub fn file(
  path: String,
  offset offset: option.Option(Int),
  limit limit: option.Option(Int),
) -> Result(ResponseBody, FileError)

Creates a file response body. Use offset to skip bytes from the start, and limit to send only a portion of the file.

pub fn get_client_info(
  connection connection: Connection,
) -> Result(SocketAddress, Nil)

Retrieves the client’s socket address from the connection. Returns error if the socket information is unavailable.

pub fn get_server_info(
  listener_name name: process.Name(@internal Message),
) -> SocketAddress

Gets the server’s bound address and port. Requires the server to be running and the listener name to match the one set in ewe.with_name.

pub fn idle_timeout(
  builder: Builder,
  idle_timeout: Int,
) -> Builder

Sets the idle timeout in milliseconds. Connections are closed after this period of inactivity. Defaults to 10_000ms if the value is negative.

pub fn ip_address_to_string(address address: IpAddress) -> String

Converts an IpAddress to its string representation.

pub fn listening(builder: Builder, port port: Int) -> Builder

Sets the listening port for server.

pub fn listening_random(builder: Builder) -> Builder

Sets the listening port to 0, which causes the OS to assign a random available port.

pub fn new(
  handler: fn(request.Request(Connection)) -> response.Response(
    ResponseBody,
  ),
) -> Builder

Creates new server builder with handler provided.

pub fn on_crash(
  builder: Builder,
  on_crash: response.Response(ResponseBody),
) -> Builder

Sets a custom response that will be sent when server crashes.

pub fn on_start(
  builder: Builder,
  on_start: fn(http.Scheme, SocketAddress) -> Nil,
) -> Builder

Sets a callback function called after the server starts. Receives the scheme and server’s socket address.

pub fn quiet(builder: Builder) -> Builder

Sets an empty on_start function.

pub fn read_body(
  req: request.Request(Connection),
  bytes_limit bytes_limit: Int,
) -> Result(request.Request(BitArray), BodyError)

Reads body from the request. Returns BodyTooLarge if body exceeds bytes_limit, or InvalidBody if malformed. Supports both chunked and content-length bodies.

pub fn send_binary_frame(
  conn: WebsocketConnection,
  bits: BitArray,
) -> Result(Nil, socket.SocketReason)

Sends a binary frame to the websocket client.

pub fn send_chunk(
  body: ChunkedBody,
  chunk: BitArray,
) -> Result(Nil, socket.SocketReason)

Sends a chunk to the client.

pub fn send_close_frame(
  conn: WebsocketConnection,
  code: CloseCode,
) -> WebsocketNext(user_state, user_message)

Sends a close frame to the websocket client. Once this function is called, no other frames can be sent on this connection. Returns how the WebSocket connection should proceed - make sure your handler returns this value.

pub fn send_event(
  conn: SSEConnection,
  event: SSEEvent,
) -> Result(Nil, socket.SocketReason)

Sends a Server-Sent Events event to the client.

pub fn send_text_frame(
  conn: WebsocketConnection,
  text: String,
) -> Result(Nil, socket.SocketReason)

Sends a text frame to the websocket client.

pub fn sse(
  req: request.Request(Connection),
  on_init on_init: fn(process.Subject(user_message)) -> user_state,
  handler handler: fn(SSEConnection, user_state, user_message) -> SSENext(
    user_state,
  ),
  on_close on_close: fn(SSEConnection, user_state) -> Nil,
) -> response.Response(ResponseBody)

Sets up the connection for Server-Sent Events.

on_init function is called once process that handles SSE connection is initialized. The argument is subject that can be used to send messages to the client. It must return initial state.

handler function is called for every subject’s message received. It must return instruction on how SSE connection should proceed.

on_close function is called when SSE process is going to be stopped.

pub fn sse_continue(
  user_state: user_state,
) -> SSENext(user_state)

Instructs Server-Sent Events connection to continue processing.

pub fn sse_stop() -> SSENext(user_state)

Instructs Server-Sent Events connection to stop.

pub fn sse_stop_abnormal(reason: String) -> SSENext(user_state)

Instructs Server-Sent Events connection to stop with abnormal reason.

pub fn start(
  builder: Builder,
) -> Result(
  actor.Started(static_supervisor.Supervisor),
  actor.StartError,
)

Starts the server with the provided configuration.

pub fn stream_body(
  req: request.Request(Connection),
) -> Result(fn(Int) -> Result(Stream, BodyError), BodyError)

Returns a consumer for streaming the request body in chunks.

pub fn supervised(
  builder: Builder,
) -> supervision.ChildSpecification(static_supervisor.Supervisor)

Returns a child specification for use in a supervision tree.

pub fn upgrade_websocket(
  req: request.Request(Connection),
  on_init on_init: fn(
    WebsocketConnection,
    process.Selector(user_message),
  ) -> #(user_state, process.Selector(user_message)),
  handler handler: fn(
    WebsocketConnection,
    user_state,
    WebsocketMessage(user_message),
  ) -> WebsocketNext(user_state, user_message),
  on_close on_close: fn(WebsocketConnection, user_state) -> Nil,
) -> response.Response(ResponseBody)

Upgrade request to a WebSocket connection. If the initial request is not valid for WebSocket upgrade, 400 response is sent.

on_init function is called once process that handles WebSocket connection is initialized. It must return a tuple with initial state and selector for custom messages. If there is no custom messages, user can pass the same selector from the argument

handler function is called for every WebSocket message received. It must return instruction on how WebSocket connection should proceed.

on_close function is called when WebSocket process is going to be stopped.

pub fn websocket_continue(
  user_state: user_state,
) -> WebsocketNext(user_state, user_message)

Instructs WebSocket connection to continue processing.

pub fn websocket_continue_with_selector(
  user_state: user_state,
  selector: process.Selector(user_message),
) -> WebsocketNext(user_state, user_message)

Instructs WebSocket connection to continue processing, including selector for custom messages.

pub fn websocket_stop() -> WebsocketNext(user_state, user_message)

Instructs WebSocket connection to stop.

pub fn websocket_stop_abnormal(
  reason: String,
) -> WebsocketNext(user_state, user_message)

Instructs WebSocket connection to stop with abnormal reason.

pub fn with_name(
  builder: Builder,
  name: process.Name(@internal Message),
) -> Builder

Sets a custom listener process name. This name is required when calling ewe.get_server_info to retrieve the server’s bound address and port.

Search Document