System, firehose, gRPC and RabbitMQ triggers

Run functions when the API starts, exchange low-latency messages over WebSocket, serve gRPC methods and consume RabbitMQ queues and streams.

System

The system trigger runs when the API reaches a lifecycle event. READY fires once the API has started, which is the right moment to seed data or warm caches.

YAML
triggers:
  onReady:
    type: system
    active: true
    options:
      name: READY
JavaScript
export async function onReady() {
  console.info("Spica is ready");
}

With several API replicas, READY fires on every replica. Make the handler idempotent.

Firehose

The firehose is a WebSocket endpoint for low-latency, bidirectional messaging, such as presence, typing indicators and games. Clients connect to:

Text
wss://api.example.com/api/firehose

Messages in both directions are JSON objects with a name and data:

JSON
{"name": "chat:message", "data": {"room": "general", "text": "Hi!"}}
YAML
triggers:
  onConnection:
    type: firehose
    active: true
    options:
      event: "**"
  onChatMessage:
    type: firehose
    active: true
    options:
      event: chat:message
eventFires on
*Every message.
**Connection events: connection and close.
connection, closeA client connected or disconnected.
Any other nameMessages with that name.

The handler receives the client and the pool of all clients, plus the message:

JavaScript
export function onConnection({socket, pool}, message) {
  if (message.name == "connection") {
    pool.send("presence", {online: pool.size});
  }
}

export function onChatMessage({socket, pool}, message) {
  if (!message.data?.text) {
    return socket.send("error", {message: "text is required"});
  }
  pool.send("chat:message", {from: socket.id, text: message.data.text});
}
ObjectMembers
socketid, remoteAddress, send(name, data), close()
poolsize, send(name, data) to every connected client
messagename, data
JavaScript
// Browser
const socket = new WebSocket("wss://api.example.com/api/firehose");
socket.onmessage = event => console.log(JSON.parse(event.data));
socket.onopen = () => socket.send(JSON.stringify({name: "chat:message", data: {text: "Hi!"}}));

gRPC

The grpc trigger exposes a handler as a unary gRPC method. The gRPC server listens on --grpc-function-port (default 50051).

YAML
triggers:
  GetQuote:
    type: grpc
    active: true
    options:
      requestParams:
        - {name: symbol, type: string}
      responseParams:
        - {name: symbol, type: string}
        - {name: price, type: double}

Parameter types: string, int32, int64, float, double, bool, bytes.

Spica generates the service definition from the function and handler names. For a function named quotes, the trigger above becomes:

Text
syntax = "proto3";

package quotes;

service quotes {
  rpc GetQuote (GetQuoteRequest) returns (GetQuoteResponse);
}

message GetQuoteRequest {
  string symbol = 1;
}

message GetQuoteResponse {
  string symbol = 1;
  double price = 2;
}

The handler receives the request message as an object and returns the response object:

JavaScript
export async function GetQuote(request) {
  const price = await lookupPrice(request.symbol);
  return {symbol: request.symbol, price};
}

A thrown error is returned to the client with status code 13 (INTERNAL). The maximum message size is --function-grpc-max-message-size-bytes (25 MiB by default).

RabbitMQ

The rabbitmq trigger consumes messages from RabbitMQ, either from a queue over AMQP 0.9.1 (mode: queue, the default) or from a stream over the RabbitMQ Stream protocol (mode: stream).

Queue mode

YAML
triggers:
  processOrder:
    type: rabbitmq
    active: true
    options:
      mode: queue
      url: ${SECRET.RABBITMQ_URL}
      exchange:
        name: orders
        type: topic
      queue:
        name: spica-orders
        durable: true
      bindings: []
      prefetch: 10
      noAck: false
OptionDescription
urlRequired. amqp:// or amqps:// URL. Connection parameters such as heartbeat can be added as query parameters.
socketOptionsTLS and socket options: ca, cert, key, passphrase, servername, rejectUnauthorized, timeout, clientProperties.
exchangeExchange to declare and bind the queue to: name, type (direct, fanout, topic, headers or a plugin type) and options.
queueQueue to declare and consume: name (empty lets the broker choose), durable, exclusive and other options.
bindingsExtra bindings of the queue to existing exchanges, with routing key patterns.
exchangeBindingsBindings between exchanges.
prefetch, prefetchGlobalHow many unacknowledged messages the broker delivers at once.
consumeConsumer options such as consumerTag, exclusive and priority.
noAckDefault true: messages count as acknowledged on delivery. Set false to acknowledge from your code.

The handler receives the message and a channel:

JavaScript
export async function processOrder(message, channel) {
  const order = JSON.parse(message.content.toString());
  try {
    await fulfil(order);
    await channel.ack(message);
  } catch (error) {
    console.error("Order failed", order.id, error);
    await channel.nack(message, false, true);
  }
}
Channel methodDescription
ack(message, allUpTo?)Acknowledge a message.
nack(message, allUpTo?, requeue?)Reject a message, requeued by default.
reject(message, requeue?)Reject a single message.
ackAll(), nackAll(requeue?)Settle every outstanding message.

message has content (a Buffer), fields and properties.

Stream mode

YAML
options:
  mode: stream
  connection:
    hostname: rabbitmq.internal
    port: 5552
    username: ${SECRET.RABBITMQ_USER}
    password: ${SECRET.RABBITMQ_PASSWORD}
  stream:
    name: orders
  consumer:
    offset:
      type: first
    consumerRef: spica-orders
OptionDescription
connectionhostname, port (default 5552), vhost, username, password and protocol settings.
streamname of the stream to declare and consume, and optional arguments such as retention.
consumer.offsetWhere to start: type is first, last, next, offset (with a numeric value) or timestamp (with an ISO date or epoch milliseconds).
consumer.consumerRefName under which the broker stores this consumer's offset. Required for storeOffset and for resuming after a restart.
consumer.singleActiveOnly one consumer with the same consumerRef receives messages at a time.

The broker must have the rabbitmq_stream plugin enabled. Behind Docker, NAT or a load balancer, set stream.advertised_host and stream.advertised_port on the broker so clients can reach it. The handler receives the message, including its offset, and a consumer that can store offsets:

JavaScript
export async function onOrderEvent(message, consumer) {
  console.info("offset", message.offset, message.content.toString());
  await consumer.storeOffset();
}

Keep connection details in secrets and reference them with ${SECRET.NAME} placeholders as shown above.