Docs · Services

Services.

Tools Canner runs for your project so your app does not have to bundle them. Included with Live and above: a virus scan, media processing with ffmpeg, document rendering to PDF and a cache. Each service is a switch on the project’s Services tab.

Turn one on

Services on the project, then Turn on, then redeploy. Your app gets one variable per service.

Virus scan

Scan a file in your own code before you encrypt it, store it or pass it on. The variable is CANNER_SCAN_SOCKET: a unix socket that speaks the standard ClamAV protocol, so any ClamAV client library works when you point it at that path. Send the bytes; the scanner never sees your file system.

Node.js

import net from "node:net";

export function scan(buffer) {
  return new Promise((resolve, reject) => {
    const socket = net.connect(process.env.CANNER_SCAN_SOCKET);
    const out = [];
    socket.on("data", (d) => out.push(d));
    socket.on("error", reject);
    socket.on("close", () => {
      const verdict = Buffer.concat(out).toString().replace(/\0$/, "").trim();
      if (verdict === "stream: OK") return resolve({ clean: true });
      const found = verdict.match(/^stream: (.+) FOUND$/);
      if (found) return resolve({ clean: false, signature: found[1] });
      reject(new Error(verdict || "scan failed")); // not scanned: do not treat as clean
    });
    socket.write("zINSTREAM\0");
    for (let i = 0; i < buffer.length; i += 65536) {
      const part = buffer.subarray(i, i + 65536);
      const size = Buffer.alloc(4);
      size.writeUInt32BE(part.length);
      socket.write(size);
      socket.write(part);
    }
    socket.end(Buffer.alloc(4)); // a zero-length chunk ends the stream
  });
}

Python

import os, socket, struct

def scan(data: bytes):
    s = socket.socket(socket.AF_UNIX)
    s.connect(os.environ["CANNER_SCAN_SOCKET"])
    s.sendall(b"zINSTREAM\0")
    for i in range(0, len(data), 65536):
        part = data[i:i + 65536]
        s.sendall(struct.pack(">I", len(part)) + part)
    s.sendall(struct.pack(">I", 0))  # a zero-length chunk ends the stream
    verdict = s.recv(4096).rstrip(b"\0\n").decode()
    if verdict == "stream: OK":
        return None
    if verdict.endswith(" FOUND"):
        return verdict[len("stream: "):-len(" FOUND")]
    raise RuntimeError(verdict or "scan failed")  # not scanned: do not treat as clean

What comes back

stream: OK                               clean
stream: Eicar-Test-Signature FOUND       a signature matched
INSTREAM size limit exceeded. ERROR      over 100 MB
INSTREAM: too many scans at once ERROR   slow down
INSTREAM: scanner unavailable ERROR      try again

Anything other than stream: OK or FOUND means the file was not scanned. Reject it or retry; do not treat it as clean.

Limits

  • 100 MB per file.
  • 3 scans at once and 120 a minute, per project.
  • Only INSTREAM, PING and VERSION are accepted.

Media processing (ffmpeg)

Convert audio and video without bundling ffmpeg. The variable is CANNER_FFMPEG_SOCKET. Send one JSON line, then the file; the reply is one JSON line, then the result. You choose a preset and a few numbers; you cannot pass ffmpeg arguments.

Node.js

import net from "node:net";

export function run(input, preset, params = {}) {
  return new Promise((resolve, reject) => {
    const socket = net.connect(process.env.CANNER_FFMPEG_SOCKET);
    const chunks = [];
    socket.on("data", (d) => chunks.push(d));
    socket.on("error", reject);
    socket.on("close", () => {
      const reply = Buffer.concat(chunks);
      const end = reply.indexOf(10); // the header line ends at the first newline
      if (end < 0) return reject(new Error("no reply"));
      const head = JSON.parse(reply.subarray(0, end).toString());
      if (!head.ok) return reject(new Error(`${head.code}: ${head.error}`));
      resolve({ ...head, data: reply.subarray(end + 1, end + 1 + head.size) });
    });
    socket.write(JSON.stringify({ preset, size: input.length, params }) + "\n");
    socket.end(input);
  });
}

// const { data } = await run(fs.readFileSync("clip.mov"), "mp4", { height: 720 });

Python

import json, os, socket

def run(data: bytes, preset: str, **params) -> bytes:
    s = socket.socket(socket.AF_UNIX)
    s.connect(os.environ["CANNER_FFMPEG_SOCKET"])
    s.sendall(json.dumps({"preset": preset, "size": len(data), "params": params}).encode() + b"\n")
    s.sendall(data)
    f = s.makefile("rb")
    head = json.loads(f.readline())
    if not head["ok"]:
        raise RuntimeError(f'{head["code"]}: {head["error"]}')
    return f.read(head["size"])

# mp4 = run(open("clip.mov", "rb").read(), "mp4", height=720)

Presets

preset     parameters (default)                                   output
mp4        height 144-1080 (720), crf 18-35 (28)                  video/mp4, H.264 + AAC
webm       height 144-1080 (720), crf 20-45 (34)                  video/webm, VP9 + Opus
mp3        kbps 48-320 (128)                                      audio/mpeg
m4a        kbps 48-320 (128)                                      audio/mp4
wav        channels 1-2 (1), rate 8000-48000 (16000)              audio/wav
thumbnail  at seconds (1), width 16-1920 (640), quality 2-31 (5)  image/jpeg
gif        at (0), seconds 0.5-15 (3), width 16-800 (480), fps 1-20 (12)  image/gif
info       none                                                   application/json: streams, duration

Inputs: MP4/MOV, WebM/MKV, AVI, WAV, MP3, AAC, OGG, FLAC, FLV and MPEG-TS. The type is read from the file itself, not its name. The reply header is {"ok": true, "size", "type", "ms", "minutes_left"} or {"ok": false, "code", "error"} with one of:

not_enabled  bad_request  too_large  unsupported_input
busy  rate  allowance  timeout  failed

Limits and job minutes

  • 500 MB in, 1 GB out, 15 minutes a job.
  • One job at a time per project, 20 a minute.
  • 300 job minutes a month are included, shared by your organization’s projects, and reset on the 1st (UTC). A job minute is a minute of ffmpeg running, not a minute of video. A job stops when the allowance runs out. The Services tab shows what is left. The Media add-on adds 600 job minutes a month for $9; it stacks.

Document rendering (PDF)

Turn HTML into a PDF or a PNG, or convert Word, Excel, PowerPoint, OpenDocument and RTF files to PDF, without bundling a browser or LibreOffice. The variable is CANNER_RENDER_SOCKET. The protocol is the same as media processing: one JSON line, then the document; one JSON line, then the result.

Node.js

import net from "node:net";

export function render(input, preset, params = {}) {
  return new Promise((resolve, reject) => {
    const socket = net.connect(process.env.CANNER_RENDER_SOCKET);
    const chunks = [];
    socket.on("data", (d) => chunks.push(d));
    socket.on("error", reject);
    socket.on("close", () => {
      const reply = Buffer.concat(chunks);
      const end = reply.indexOf(10); // the header line ends at the first newline
      if (end < 0) return reject(new Error("no reply"));
      const head = JSON.parse(reply.subarray(0, end).toString());
      if (!head.ok) return reject(new Error(`${head.code}: ${head.error}`));
      resolve({ ...head, data: reply.subarray(end + 1, end + 1 + head.size) });
    });
    socket.write(JSON.stringify({ preset, size: input.length, params }) + "\n");
    socket.end(input);
  });
}

// const { data } = await render(Buffer.from(html), "pdf", { paper: "letter" });
// const { data } = await render(fs.readFileSync("quote.docx"), "convert");

Python

import json, os, socket

def render(data: bytes, preset: str, **params) -> bytes:
    s = socket.socket(socket.AF_UNIX)
    s.connect(os.environ["CANNER_RENDER_SOCKET"])
    s.sendall(json.dumps({"preset": preset, "size": len(data), "params": params}).encode() + b"\n")
    s.sendall(data)
    f = s.makefile("rb")
    head = json.loads(f.readline())
    if not head["ok"]:
        raise RuntimeError(f'{head["code"]}: {head["error"]}')
    return f.read(head["size"])

# pdf = render(html.encode(), "pdf", paper="a4", landscape=True)
# pdf = render(open("quote.docx", "rb").read(), "convert")

Presets

preset      input                              parameters (default)                                       output
pdf         HTML                               paper a3|a4|a5|letter|legal (a4), landscape (false),       application/pdf
                                               margin_mm 0-50 (10), background (true)
screenshot  HTML                               width 100-3000 (1280), height 100-3000 (800), scale 1-3    image/png
convert     docx xlsx pptx odt ods odp rtf     none                                                       application/pdf
            doc xls ppt
  • The HTML must be self-contained: inline CSS, and data: URIs for images and fonts. The renderer has no network, so links to outside stylesheets, fonts or images do not load. Scripts run.
  • The input’s type is read from the file itself. Replies and error codes are the same as for media processing.
  • 50 MB in, 200 MB out, 2 minutes a job, one job at a time per project, 20 a minute.
  • It uses the same monthly job minutes as media processing: 300 included, shared by your organization’s projects.

Cache

A Redis-compatible store for your project (Redis 7.0), saved to disk. The variable is CANNER_CACHE_SOCKET: a unix socket that only your app can open. There is no TCP port, so a redis://host:port URL does not apply; give your client the socket path.

Node.js (ioredis)

import Redis from "ioredis";

const redis = new Redis({ path: process.env.CANNER_CACHE_SOCKET });
await redis.set("greeting", "hello", "EX", 3600);
console.log(await redis.get("greeting"));

Node.js (redis)

import { createClient } from "redis";

const client = createClient({ socket: { path: process.env.CANNER_CACHE_SOCKET } });
await client.connect();
await client.set("greeting", "hello", { EX: 3600 });
console.log(await client.get("greeting"));

Python

import os
import redis

r = redis.Redis(unix_socket_path=os.environ["CANNER_CACHE_SOCKET"], decode_responses=True)
r.set("greeting", "hello", ex=3600)
print(r.get("greeting"))

Size, persistence and what is not available

  • 64 MB included; Cache 256 MB ($4 a month) and Cache 1 GB ($9) are add-ons. When it is full, writes fail and reads keep working:
OOM command not allowed when used memory > 'maxmemory'.
  • Nothing is evicted to make room, so give keys an expiry or delete what you no longer need.
  • Every write is saved to disk within a second. After a crash or a restart the data is back; the last second of writes can be lost.
  • CONFIG, DEBUG, MODULE, REPLICAOF, SLAVEOF, FAILOVER, MIGRATE, SYNC and ACL are not available.
  • Turning the cache off stops it and keeps its data for 7 days. Turn it back on within that time and the data is there; after that it is deleted.

Good to know

  • Files you upload to Files are already scanned by Canner. This service is for files your app handles itself, such as before it encrypts them.
  • The scanner runs on the same servers as your app, in Canada. Nothing is stored or sent anywhere. Canner counts scans and bytes per project and never records a file name or content.
  • Signatures update daily. A scan lowers the risk; it does not remove it.
  • Turning the service off, or leaving Live, stops it within a minute.