PluginsBuild a plugin

Outbound HTTP

Call other services from a Rustrak plugin with ctx.fetch: read an API and store the result, the hosts it may call, hosts the admin adds, redirects, timeouts and size limits.

A plugin calls other services over HTTP with ctx.fetch: read an API and keep what it answers in the plugin’s database, or send it data. It reaches only the hosts it names in rustrak.config.ts. A plugin that names none has no network at all.

The plugin’s config names them:

// rustrak.config.ts
export default defineConfig({
  name: 'Rates',
  rustrak: '>=0.37.0',
  network: { allowedHosts: ['api.example.com'] },
});
TypeScript

This route reads exchange rates from an API, stores them and answers with what it got:

// src/server/routes/rates.rs
use rustrak_plugin::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct Rate {
    pub currency: String,
    pub value: f64,
}

#[post("/rates/refresh", instance)]
fn refresh(ctx: &Ctx) -> Result<Json<Vec<Rate>>> {
    let rates: Vec<Rate> = ctx
        .fetch("GET", "https://api.example.com/rates")
        .send()?
        .json()?;
    for rate in &rates {
        ctx.db().execute(
            "INSERT OR REPLACE INTO rates (currency, value) VALUES (?1, ?2)",
            params![rate.currency, rate.value],
        )?;
    }
    Ok(Json(rates))
}
Rust

Where to call from

ctx.fetch works the same in routes, scheduled tasks and background jobs. Pick by who is waiting:

Call fromWhen
A routeSomeone waits for the answer, and the other service answers well inside the route’s 2 seconds
A jobThe call is slow, or it should be retried if the service is down. The route queues the job and answers at once
A taskNobody asks for it: pull new data every hour

In a job

This job sends a report to the API. A route queues it with ctx.enqueue("send_report", &report) and answers without waiting:

// src/server/jobs/report.rs
use rustrak_plugin::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct Report {
    pub errors: u32,
}

#[job]
fn send_report(ctx: &Ctx, report: Json<Report>) -> Result<()> {
    let response = ctx
        .fetch("POST", "https://api.example.com/reports")
        .json(&report.0)
        .send()?;
    if response.status >= 400 {
        return Err(Error::Internal(format!("the API answered {}", response.status)));
    }
    Ok(())
}
Rust

Returning an Error makes Rustrak try the job again, 1 minute and then 4 minutes later. A 4xx or 5xx is still a response, so the job checks status itself.

In a task

This task refreshes the rates every hour, with nobody asking:

// src/server/tasks/rates.rs
use rustrak_plugin::prelude::*;
use std::time::Duration;

use crate::routes::rates::Rate;

#[task("0 * * * *")]
fn refresh_rates(ctx: &Ctx) -> Result<()> {
    let rates: Vec<Rate> = ctx
        .fetch("GET", "https://api.example.com/rates")
        .timeout(Duration::from_secs(10))
        .send()?
        .json()?;
    // store them, as the route does
    Ok(())
}
Rust

Tasks and jobs take turns, one at a time across every plugin, so give a task’s requests a timeout.

Which hosts

Each entry of allowedHosts is one of these:

EntryAllows
api.example.comThat host only. example.com is a different host
*.example.comEvery subdomain of example.com, at any depth: a.example.com, a.b.example.com. Not example.com itself
*Any host
127.0.0.1That IPv4 address
{ setting: 'key' }The hosts the admin writes in that setting. See Hosts the admin sets

A host matches in any case, on any port, over http or https. An entry with a scheme, a port or a path is refused when the plugin is installed:

capabilities.allowed_hosts "https://api.example.com" must be a host, *.domain or *: no scheme, port or path

An IPv6 address cannot be named. Only * reaches one.

Rustrak checks the host by its name, before it connects, and does not look at the address the name resolves to. It does not block private networks either: a plugin allowed *, or 10.0.0.5, reaches your internal services.

Installing a plugin grants its hosts, with no prompt. Once it is installed, its page in Settings → Plugins lists them under Access, as Calls out to. Uninstall a plugin whose list you do not want.

Hosts the admin sets

When the hosts depend on the install (a self-hosted service, the sites an uptime check watches), let the admin write them. Put { setting: 'key' } in allowedHosts, naming a text setting of the instance:

// rustrak.config.ts
export default defineConfig({
  name: 'Uptime',
  rustrak: '>=0.37.0',
  network: { allowedHosts: [{ setting: 'monitoredHosts' }] },
  settings: {
    monitoredHosts: { type: 'text' },
  },
});
TypeScript

The admin fills it in the plugin’s settings form, separating hosts with commas, spaces or new lines:

status.example.com, *.example.org
api.internal.example

Rustrak checks each host when the form is saved and refuses the value, on that field, if one is not a host: https://status.example.com is not a host, *.domain or *: no scheme, port or path. It reads the setting at every request, so a host added or removed applies from the plugin’s next call.

The setting must be a text setting with scope: 'instance', the default. A project setting or another type is refused when the plugin is installed. Fixed hosts and settings can go in the same list: allowedHosts: ['api.example.com', { setting: 'extraHosts' }].

Until the admin writes a host, every request of a plugin with no fixed hosts fails with no hosts are set yet in this plugin's settings.

The request

ctx.fetch(method, url) starts a request. Build it, then send it:

MethodSets
.header(name, value)A request header. Call it once per header
.body(bytes)The body: a String, a Vec<u8> or a &str
.json(&value)The body as JSON, with content-type: application/json
.timeout(duration)How long to wait for the whole response
.send()Sends it and reads the whole response

The URL must be http or https. Rustrak sends no cookies, credentials or user-agent of its own: set the headers the other service expects, such as an API key.

The response

send returns Result<Response, FetchError>. Any status is a response: a server that answers 500 gives Ok, with status 500.

On ResponseGives
statusThe status code, a u16
headersEvery header, as (name, value) pairs
bodyThe body, as bytes
header(name)The first header with that name, in any case
text()The body as a String. Invalid UTF-8 is replaced
json::<T>()The body parsed as T. A body that does not parse is an Error

Rustrak follows up to 10 redirects. Each one is checked like the first request, so a server cannot send the plugin to a host it does not allow. If api.example.com redirects to cdn.example.net and only the first is allowed, the request ends in an error.

Errors

A request that gets no response returns a FetchError. Its message says why:

MessageWhen
<host> is not among the hosts this plugin allowsThe host, or a redirect’s, is not allowed. Rustrak never connected to it
this plugin declares no hosts it may callThe config has no network
the request timed outThe timeout, or the call’s own time, ran out
the response is over 5 MBThe body is larger than 5 MB
The URL, method or header, and what is wrong with itThe request is not a valid one
The reasonNo connection: DNS, TLS or a reset

is_timeout() and is_connection() tell the cases apart in code. With ?, a FetchError becomes a 500, and its message goes to Rustrak’s log, not to the caller. Match on it when the failure is what you are measuring, as an uptime check does:

let outcome = match ctx.fetch("GET", url).timeout(Duration::from_secs(10)).send() {
    Ok(r) if r.status < 400 => "up".to_string(),
    Ok(r) => format!("down: {}", r.status),
    Err(e) => format!("down: {e}"),
};
Rust

Time

A request never outlives the call that makes it. Without .timeout, it can take what the call has left: 2 seconds in a route, 30 seconds in a task or a job. A .timeout longer than that is cut to it. The time a request waits counts against the call’s own, so a route that spends 1.5 seconds on a request has half a second for the rest.

Tasks and jobs run one at a time across every plugin. A task waiting on a slow server holds up the others, so give its requests a timeout.

Limits

WhatLimit
Schemeshttp, https
Response body5 MB
Redirects10
TimeWhat is left of the call: 2 seconds in a route, 30 in a task or job

Outbound HTTP needs Rustrak 0.37.0 or later, like scheduled tasks and background jobs.

Esc

Type to search guides, configuration and the API.