[SEND][ACK]

Quickstart

Publish an event, receive it live and on a webhook, read it back, see a delivery fail and go again, and run a chat on a topic. Steps 1 to 6 are the same in Rust, TypeScript and Python; step 7 is TypeScript. The code below is copied from docs/samples/, and every sample runs in its SDK's tests against that SDK's fake server, so it is the code that works. The calls are in each SDK's README (TypeScript, Python, Rust: crates/client) and the routes in api.md.

1. Get a token and connect

A local server started without --harpora-issuer is open: pass no token, and skip to the code. A server that checks tokens (central, https://sendack.lunaor.com) wants a Harpora access token whose audience is the API's. Your service gets one the way Astropause's and Rankine's CLIs do, with a key pair of its own (private_key_jwt, RFC 7523): only the public half is ever registered, so no secret moves.

# 1. a key pair: deployer.key stays with you (mode 600), deployer.jwks.json is the public half
sendack-proto keygen --out ./sendack-key

# 2. send deployer.jwks.json to whoever runs your Harpora realm, to register as a client (its id is CLIENT below)
#    with the scopes this quickstart needs:
#    sendack:topic:orders:publish, sendack:topic:orders:subscribe, sendack:webhooks:create  (api.md#auth)

# 3. a token, on stdout (`--out FILE` writes it, mode 600; `--resource URL` for a server other than central)
sendack-proto token --issuer https://auth.lunaor.com/lunaor --client CLIENT --key-file ./sendack-key/deployer.key

The token lasts minutes: for a service, pass a function that runs step 3's request again (the SDKs ask it again after unauthenticated) rather than a pasted string. A refusal says what to fix: a 401 carries the verifier's reason (expired, wrong audience, bad signature) and a 403 names the scope the call needed. GET /.well-known/oauth-protected-resource on the server names its issuer and the scopes it understands. An empty token (an unset variable) is an error in every SDK, never a call sent without one.

Rust

use sendack_client::Client;

// `token` is the Harpora access token from step 1. Use `with_token_fn` instead to fetch a fresh one before each call.
pub fn connect(url: &str, token: &str) -> Client {
    Client::new(url).with_token(token)
}

TypeScript

import { Sendack } from "@sendack/client";

// `token` is the Harpora access token from step 1, or a function that returns a fresh one.
export const connect = (url, token) => new Sendack(url, { token });

Python

from sendack import Sendack


# `token` is the Harpora access token from step 1, or a callable(refresh) that returns a fresh one.
def connect(url, token):
    return Sendack(url, token=token)

2. Publish an event

An event has a topic, an id you choose and bytes of data. The id is what makes a retry safe: the same id with the same data answers duplicate and delivers nothing again; the same id with other data is already_exists.

Rust

use sendack_client::{Client, Error, Published};

pub async fn publish(sendack: &Client) -> Result<(Published, Published), Error> {
    // The id makes a retry safe: the same id with the same data is found, not delivered twice.
    let first = sendack.publish("orders", "order-1001", r#"{"total":42}"#).await?;
    let retry = sendack.publish("orders", "order-1001", r#"{"total":42}"#).await?;
    println!("{:?} {} {}", first.pos, first.duplicate, retry.duplicate); // Some("7.0") false true
    Ok((first, retry))
}

TypeScript

import { jsonBytes } from "@sendack/client";

export async function publish(sendack) {
  // The id makes a retry safe: the same id with the same data is found, not delivered twice.
  const first = await sendack.publish("orders", "order-1001", jsonBytes({ total: 42 }));
  const retry = await sendack.publish("orders", "order-1001", jsonBytes({ total: 42 }));
  console.log(first.pos, first.duplicate, retry.duplicate); // 7.0 false true
  return [first, retry];
}

Python

import json


def publish(sendack):
    # The id makes a retry safe: the same id with the same data is found, not delivered twice.
    data = json.dumps({"total": 42}).encode()
    first = sendack.publish("orders", "order-1001", data)
    retry = sendack.publish("orders", "order-1001", data)
    print(first.pos, first.duplicate, retry.duplicate)  # 7.0 False True
    return first, retry

3. Subscribe live

Start this first, then publish again from another terminal. A live subscription resumes by itself after a dropped connection or an expired token, from the last position it saw, with no gap and no repeat.

Rust

use futures::StreamExt;
use sendack_client::{Client, Error, Event, SubscribeOptions};

pub async fn subscribe(sendack: &Client) -> Result<Event, Error> {
    // Live from now; it resumes by itself after a drop, with no gap and no repeat.
    let mut live = sendack.subscribe("orders", SubscribeOptions::default());
    // A service loops `while let Some(ev) = live.next().await`; this takes the first event and stops.
    let ev = live.next().await.expect("a live subscription ends only when dropped")?;
    println!("{} {} {}", ev.pos, ev.id, ev.text().unwrap_or(""));
    Ok(ev)
}

TypeScript

import { json } from "@sendack/client";

export async function subscribe(sendack) {
  // Live from now; it resumes by itself after a drop, with no gap and no repeat.
  for await (const ev of sendack.subscribe("orders")) {
    console.log(ev.pos, ev.id, json(ev.data));
    return ev; // a service keeps looping; this takes the first event and stops
  }
}

Python

def subscribe(sendack):
    # Live from now; it resumes by itself after a drop, with no gap and no repeat.
    live = sendack.subscribe("orders")
    for ev in live:
        print(ev.pos, ev.id, ev.json())
        live.close()
        return ev  # a service keeps looping; this takes the first event and stops

4. Create a webhook and verify a delivery

Sendack posts each event on the topic to the URL, signed. Verify the body as it arrived, never JSON you parsed and re-serialised, and answer 2xx only after it verifies. Details and errors: Verifying webhooks.

Rust

use sendack_client::{verify_webhook, Client, Error, WebhookError, WEBHOOK_TOLERANCE};

pub async fn create_webhook(sendack: &Client) -> Result<String, Error> {
    // The secret (whsec_...) is answered once: keep it.
    sendack.create_webhook("orders-hook", "orders", "https://example.com/hooks/sendack").await
}

// In your HTTP handler: the headers, and the body as raw bytes, exactly as they arrived.
pub fn verify_delivery(secret: &str, headers: &[(&str, &str)], body: &[u8]) -> Result<serde_json::Value, WebhookError> {
    let event = verify_webhook(&[secret], headers.iter().copied(), body, WEBHOOK_TOLERANCE)?;
    println!("{} {} {}", event["topic"], event["id"], event["pos"]);
    Ok(event) // answer 2xx only now
}

TypeScript

import { verifyWebhook } from "@sendack/client";

export async function createWebhook(sendack) {
  // The secret (whsec_...) is answered once: keep it.
  return sendack.createWebhook("orders-hook", "orders", "https://example.com/hooks/sendack");
}

// In your HTTP handler: the headers, and the body as raw bytes, exactly as they arrived.
export async function verifyDelivery(secret, headers, rawBody) {
  const event = await verifyWebhook(secret, headers, rawBody); // throws WebhookVerificationError, with a .kind
  console.log(event.topic, event.id, event.pos);
  return event; // answer 2xx only now
}

Python

from sendack import verify_webhook


def create_webhook(sendack):
    # The secret (whsec_...) is answered once: keep it.
    return sendack.create_webhook("orders-hook", "orders", "https://example.com/hooks/sendack")


# In your HTTP handler: the headers, and the body as raw bytes, exactly as they arrived.
def verify_delivery(secret, headers, raw_body):
    event = verify_webhook(secret, headers, raw_body)  # raises WebhookVerificationError, with a .kind
    print(event["topic"], event["id"], event["pos"])
    return event  # answer 2xx only now

5. Read a topic's events by page

A page is oldest first. next_after is set when the page was full and is the position to ask after; a short page is the end, as of now. It never waits for new events: step 3 does that. Each SDK also has an iterator that pages for you (all_events, allEvents, iter_events).

Rust

use sendack_client::{Client, Error, Event};

pub async fn read_pages(sendack: &Client, page_size: u32) -> Result<Vec<Event>, Error> {
    let mut all = Vec::new();
    let mut after = None; // None: from the beginning
    loop {
        let page = sendack.events("orders", after.as_deref(), Some(page_size)).await?;
        all.extend(page.events);
        match page.next_after {
            Some(next) => after = Some(next),
            None => return Ok(all), // a short page is the end, as of now
        }
    }
}

TypeScript

export async function readPages(sendack, limit = 100) {
  const all = [];
  let after = ""; // from the beginning
  for (;;) {
    const page = await sendack.events("orders", { after, limit });
    all.push(...page.events);
    if (page.nextAfter === null) return all; // a short page is the end, as of now
    after = page.nextAfter;
  }
}

Python

def read_pages(sendack, limit=100):
    events = []
    after = ""  # from the beginning
    while True:
        page = sendack.events("orders", after=after, limit=limit)
        events.extend(page.events)
        if page.next_after is None:  # a short page is the end, as of now
            return events
        after = page.next_after

6. See failures and redeliver

A webhook keeps its recent delivery attempts, newest first: the position, whether it succeeded and the receiver's status (or timeout, dns, ...). Redelivery sends one event again, signed, and answers the attempt it made. It is limited per webhook, and past the limit the call fails with resource_exhausted (api.md).

Rust

use sendack_client::{Client, DeliveryAttempt, Error};

pub async fn failures(sendack: &Client) -> Result<Option<DeliveryAttempt>, Error> {
    let page = sendack.webhook_deliveries("orders-hook", None, Some(20)).await?; // newest first
    for d in &page.deliveries {
        println!("{} {} {}", d.pos, if d.ok { "ok" } else { "failed" }, d.status);
    }
    let Some(failed) = page.deliveries.iter().find(|d| !d.ok) else { return Ok(None) };
    // Sends that event again, signed, and answers the attempt it made.
    Ok(Some(sendack.webhook_redeliver("orders-hook", &failed.pos).await?))
}

TypeScript

export async function failures(sendack) {
  const { deliveries } = await sendack.webhookDeliveries("orders-hook", { limit: 20 }); // newest first
  for (const d of deliveries) console.log(d.pos, d.ok ? "ok" : "failed", d.status);
  const failed = deliveries.find((d) => !d.ok);
  if (!failed) return null;
  // Sends that event again, signed, and answers the attempt it made.
  return sendack.webhookRedeliver("orders-hook", failed.pos);
}

Python

def failures(sendack):
    page = sendack.webhook_deliveries("orders-hook", limit=20)  # newest first
    for d in page.deliveries:
        print(d.pos, "ok" if d.ok else "failed", d.status)
    failed = next((d for d in page.deliveries if not d.ok), None)
    if failed is None:
        return None
    # Sends that event again, signed, and answers the attempt it made.
    return sendack.webhook_redeliver("orders-hook", failed.pos)

7. Chat on a topic

A chat is a topic: a message is an event, a reply is an event published with replyTo (a thread is one level), a reaction is an emoji on an event, and read state is your last-read position per topic and per thread, with the unread count after it (at most 99). Follow it live with ?reactions=1 on the socket to get a frame for each reaction change too (Reactions); the SDK's subscribe of step 3 carries events only. This one is TypeScript, on Node 22+ for the global WebSocket.

import { jsonBytes } from "@sendack/client";

// Needs Node 22+ for the global WebSocket. `token` is as in step 1 (omit it on an open server).
export async function chat(sendack, url, token) {
  const topic = "chat.general";

  // Follow the topic live, reactions too: `?reactions=1` adds a {"reaction": {id, emoji, by, on}} frame for every change.
  // (subscribe() in step 3 is events only.) A socket from a browser-style client sends its token as the first frame.
  const socket = new WebSocket(`${url.replace(/^http/, "ws")}/live/${topic}?reactions=1`);
  const frames = [];
  let wake;
  socket.onmessage = ({ data }) => (frames.push(JSON.parse(data)), wake?.());
  socket.onopen = () => token && socket.send(JSON.stringify({ token }));
  const until = async (match) => {
    for (;;) {
      const i = frames.findIndex(match);
      if (i >= 0) return frames.splice(i, 1)[0];
      await new Promise((resolve) => (wake = resolve));
    }
  };
  await until((f) => "hello" in f); // live from here on

  // Publish, reply in the message's thread, react.
  await sendack.publish(topic, "m1", jsonBytes({ text: "Lunch?" }));
  const reply = await sendack.publish(topic, "m1-r1", jsonBytes({ text: "Noon works" }), { replyTo: "m1" });
  await sendack.react(topic, "m1", "๐Ÿ‘");
  const change = (await until((f) => f.reaction)).reaction;
  console.log(change.id, change.emoji, change.on); // m1 ๐Ÿ‘ true

  // Read state: unread events in the topic, unread replies per thread, and the counts a page of a chat shows.
  const { unread } = await sendack.readState(topic);
  const { m1 } = await sendack.threadCounts(topic, ["m1"]);
  const { reactions } = (await sendack.reactions(topic, ["m1"])).m1;
  console.log(unread, m1.replies, m1.unread, reactions[0].count); // 2 1 1 1

  // Read it all up to your own newest event, whose position publish answered: the topic's position and the thread's are separate, so move both.
  const { pos } = reply;
  await sendack.markRead(topic, pos);
  await sendack.markThreadRead(topic, "m1", pos);
  socket.close();
  return { unread, replies: m1.replies, threadUnread: m1.unread, reactions };
}