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.
triggers:
onReady:
type: system
active: true
options:
name: READYexport 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:
wss://api.example.com/api/firehoseMessages in both directions are JSON objects with a name and data:
{"name": "chat:message", "data": {"room": "general", "text": "Hi!"}}triggers:
onConnection:
type: firehose
active: true
options:
event: "**"
onChatMessage:
type: firehose
active: true
options:
event: chat:messageevent | Fires on |
|---|---|
* | Every message. |
** | Connection events: connection and close. |
connection, close | A client connected or disconnected. |
| Any other name | Messages with that name. |
The handler receives the client and the pool of all clients, plus the message:
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});
}| Object | Members |
|---|---|
socket | id, remoteAddress, send(name, data), close() |
pool | size, send(name, data) to every connected client |
message | name, data |
// 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).
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:
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:
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
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| Option | Description |
|---|---|
url | Required. amqp:// or amqps:// URL. Connection parameters such as heartbeat can be added as query parameters. |
socketOptions | TLS and socket options: ca, cert, key, passphrase, servername, rejectUnauthorized, timeout, clientProperties. |
exchange | Exchange to declare and bind the queue to: name, type (direct, fanout, topic, headers or a plugin type) and options. |
queue | Queue to declare and consume: name (empty lets the broker choose), durable, exclusive and other options. |
bindings | Extra bindings of the queue to existing exchanges, with routing key patterns. |
exchangeBindings | Bindings between exchanges. |
prefetch, prefetchGlobal | How many unacknowledged messages the broker delivers at once. |
consume | Consumer options such as consumerTag, exclusive and priority. |
noAck | Default true: messages count as acknowledged on delivery. Set false to acknowledge from your code. |
The handler receives the message and a channel:
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 method | Description |
|---|---|
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
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| Option | Description |
|---|---|
connection | hostname, port (default 5552), vhost, username, password and protocol settings. |
stream | name of the stream to declare and consume, and optional arguments such as retention. |
consumer.offset | Where to start: type is first, last, next, offset (with a numeric value) or timestamp (with an ISO date or epoch milliseconds). |
consumer.consumerRef | Name under which the broker stores this consumer's offset. Required for storeOffset and for resuming after a restart. |
consumer.singleActive | Only 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:
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.