CrawlClick docs
Menu and search

CrawlClick partner reference client (TypeScript, Python)

The reference client asks /v1/decide with a short timeout, shows the answer with or without a placement, logs the serve, and confirms it with a signed receipt, retrying only on 503, 429 and transport failures.

Status: Coming. This page has one complete partner client in TypeScript and the same client in Python. Each runs the whole flow: request a placement, show the answer, write a serve log, and confirm the placement with an Ed25519 receipt. The decision API is built and tested but not yet open to partners; when it opens, CrawlClick issues your ccp_… key and the base URL, and these clients run against it unchanged.

What does the reference client do, step by step?

  1. Decide with a deadline. It posts the question and topics to /v1/decide with a 400 ms timeout. If the call is slow, fails, or answers anything other than 200, it logs the failure and returns no placement. It never retries /v1/decide: a retry would only make your answer later.
  2. Show. It renders your answer, and, when there is a fill, disclosure.passage as its own paragraph below it, unchanged. See Show the disclosure.
  3. Log the serve. It appends a line to crawlclick-serves.jsonl recording what it showed.
  4. Confirm. After the answer is out, it signs crawlclick-receipt-v1, a newline and the decision_id, and posts the receipt to /v1/decide/receipts. See Sign a receipt.
  5. Retry only what can succeed. On 503, 429 or a transport failure it waits and sends the same receipt again, with exponential backoff from one second, honouring Retry-After, and stops 30 seconds before expires_at. It never retries 400, 401, 403 or 410.

What configuration does the client read?

Four environment variables, all server-side:

Variable Holds
CRAWLCLICK_DECISION_URL The decision service base URL CrawlClick issues with your key.
CRAWLCLICK_PARTNER_KEY Your ccp_… key, with the decide and receipts scopes.
CRAWLCLICK_RECEIPT_KEY Your Ed25519 private key as its 32-byte seed in unpadded base64url.
CRAWLCLICK_RECEIPT_KEY_ID The key id you registered the matching public key under.

Sign a receipt shows how to generate the key pair and what to send CrawlClick to register the public key.

How do I run the TypeScript client?

The file uses fetch and node:crypto and has no dependencies. Node 22.18 or later runs a .ts file directly; on an earlier Node 22, add --experimental-strip-types, or compile it with tsc.

node crawlclick-partner.ts "best crm for a two-person startup"
// crawlclick-partner.ts: reference code for the CrawlClick decision API. Not a published package.
// Node 22 or later. No dependencies: fetch and node:crypto only.
import { createPrivateKey, sign, type KeyObject } from 'node:crypto';
import { appendFileSync } from 'node:fs';

const SERVE_LOG = 'crawlclick-serves.jsonl';
const DECIDE_TIMEOUT_MS = 400; // your latency budget for an ad; tune it to your answer path
const RECEIPT_TIMEOUT_MS = 5_000;
const RECEIPT_MARGIN_S = 30; // stop retrying this long before expires_at

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is not set`);
  return value.trim();
}

const BASE_URL = env('CRAWLCLICK_DECISION_URL').replace(/\/+$/, '');
const PARTNER_KEY = env('CRAWLCLICK_PARTNER_KEY');
const RECEIPT_KEY_ID = env('CRAWLCLICK_RECEIPT_KEY_ID');
const RECEIPT_KEY = loadReceiptKey(env('CRAWLCLICK_RECEIPT_KEY'));

export type DecideRequest = { query?: string; topics?: string[]; url?: string; safe?: boolean };

export type Fill = {
  filled: true;
  decision_id: string;
  expires_at: number;
  sponsored: true;
  disclosure: { format: 'inline_prefix'; label: string; passage: string; advertiser: string };
  campaign_id: string;
  creative_id: string;
  landing_url: string;
  price_micros: number;
  marker: string;
};

type ReceiptOutcome = 'recorded' | 'duplicate' | 'budget_exhausted' | 'expired' | 'refused' | 'gave_up';

/** The receipt key is the unpadded base64url 32-byte Ed25519 seed. */
function loadReceiptKey(seedB64url: string): KeyObject {
  const seed = Buffer.from(seedB64url, 'base64url');
  if (seed.length !== 32) throw new Error('CRAWLCLICK_RECEIPT_KEY must be a 32-byte seed in base64url');
  // RFC 8410 PKCS#8 wrapper for an Ed25519 private key, followed by the seed.
  const pkcs8 = Buffer.concat([Buffer.from('302e020100300506032b657004220420', 'hex'), seed]);
  return createPrivateKey({ key: pkcs8, format: 'der', type: 'pkcs8' });
}

function serveLog(entry: Record<string, unknown>): void {
  appendFileSync(SERVE_LOG, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n');
}

function headers(): Record<string, string> {
  return { authorization: `Bearer ${PARTNER_KEY}`, 'content-type': 'application/json' };
}

/** Ask for a placement. Returns null on no fill, on any error, and when the budget runs out. */
export async function decide(request: DecideRequest): Promise<Fill | null> {
  try {
    const response = await fetch(`${BASE_URL}/v1/decide`, {
      method: 'POST',
      headers: headers(),
      body: JSON.stringify(request),
      signal: AbortSignal.timeout(DECIDE_TIMEOUT_MS),
    });
    if (response.status !== 200) {
      // 401, 429, 400 and 5xx: answer without a placement. Never retry inside the answer path.
      serveLog({ event: 'decide_failed', status: response.status, body: await response.text() });
      return null;
    }
    const body = await response.json();
    return body.filled === true ? (body as Fill) : null;
  } catch (error) {
    serveLog({ event: 'decide_failed', error: String(error) });
    return null;
  }
}

/** Put the placement under the answer, exactly as CrawlClick wrote it. */
export function render(answer: string, fill: Fill | null): string {
  if (!fill) return answer;
  return `${answer}\n\n${fill.disclosure.passage}`;
}

export function receiptSignature(decisionId: string): string {
  const message = Buffer.from(`crawlclick-receipt-v1\n${decisionId}`, 'utf8');
  return sign(null, message, RECEIPT_KEY).toString('base64url');
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/** Confirm a placement you showed. Call it after the answer has gone out, never before. */
export async function confirm(fill: Fill): Promise<ReceiptOutcome> {
  const body = JSON.stringify({
    decision_id: fill.decision_id,
    key_id: RECEIPT_KEY_ID,
    signature: receiptSignature(fill.decision_id),
  });
  let delayMs = 1_000;
  for (let attempt = 1; ; attempt++) {
    let status = 0;
    let retryAfterS = 0;
    let text = '';
    try {
      const response = await fetch(`${BASE_URL}/v1/decide/receipts`, {
        method: 'POST',
        headers: headers(),
        body,
        signal: AbortSignal.timeout(RECEIPT_TIMEOUT_MS),
      });
      status = response.status;
      retryAfterS = Number(response.headers.get('retry-after')) || 0;
      text = await response.text();
    } catch (error) {
      text = String(error); // the request may not have arrived: the same receipt is safe to resend
    }
    serveLog({ event: 'receipt_attempt', decision_id: fill.decision_id, attempt, status, body: text });

    if (status === 200 || status === 202) {
      const result = JSON.parse(text);
      if (result.recorded === true) return 'recorded';
      if (result.duplicate === true) return 'duplicate';
      if (result.code === 'budget_exhausted') return 'budget_exhausted';
      return 'refused';
    }
    if (status === 410) return 'expired';
    if (status !== 0 && status !== 429 && status !== 503) {
      // 400, 401 and 403 will fail the same way every time. Fix the cause; do not resend.
      return 'refused';
    }
    const waitMs = Math.max(delayMs, retryAfterS * 1_000);
    if (Date.now() + waitMs > (fill.expires_at - RECEIPT_MARGIN_S) * 1_000) return 'gave_up';
    await sleep(waitMs);
    delayMs = Math.min(delayMs * 2, 60_000);
  }
}

// One complete turn: decide, show, confirm.
async function main(): Promise<void> {
  const question = process.argv[2] ?? 'best crm for a two-person startup';
  const answer = 'For two people, pick a CRM with a free tier and a shared inbox.'; // your own answer
  const fill = await decide({ query: question, topics: ['crm'], safe: true });
  console.log(render(answer, fill)); // this is where your product shows the answer
  if (!fill) return;
  serveLog({
    event: 'shown',
    decision_id: fill.decision_id,
    campaign_id: fill.campaign_id,
    creative_id: fill.creative_id,
    advertiser: fill.disclosure.advertiser,
    price_micros: fill.price_micros,
    expires_at: fill.expires_at,
  });
  const outcome = await confirm(fill);
  serveLog({ event: 'receipt_outcome', decision_id: fill.decision_id, outcome });
}

if (import.meta.url === `file://${process.argv[1]}`) {
  main().catch((error) => {
    console.error(error);
    process.exitCode = 1;
  });
}

How do I run the Python client?

The Python client uses urllib from the standard library for HTTP, so the one dependency is cryptography for Ed25519. It needs Python 3.10 or later.

pip install cryptography
python crawlclick_partner.py "best crm for a two-person startup"
"""crawlclick_partner.py: reference code for the CrawlClick decision API. Not a published package.

Python 3.10 or later. Standard library plus `cryptography` (pip install cryptography).
"""
from __future__ import annotations

import base64
import datetime
import json
import os
import sys
import time
import urllib.error
import urllib.request

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

SERVE_LOG = "crawlclick-serves.jsonl"
DECIDE_TIMEOUT_S = 0.4  # your latency budget for an ad; tune it to your answer path
RECEIPT_TIMEOUT_S = 5.0
RECEIPT_MARGIN_S = 30  # stop retrying this long before expires_at


def env(name: str) -> str:
    value = os.environ.get(name, "").strip()
    if not value:
        raise RuntimeError(f"{name} is not set")
    return value


def b64url_decode(text: str) -> bytes:
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))


def b64url_encode(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


BASE_URL = env("CRAWLCLICK_DECISION_URL").rstrip("/")
PARTNER_KEY = env("CRAWLCLICK_PARTNER_KEY")
RECEIPT_KEY_ID = env("CRAWLCLICK_RECEIPT_KEY_ID")
# The receipt key is the unpadded base64url 32-byte Ed25519 seed.
RECEIPT_KEY = Ed25519PrivateKey.from_private_bytes(b64url_decode(env("CRAWLCLICK_RECEIPT_KEY")))


def serve_log(**entry) -> None:
    entry = {"ts": datetime.datetime.now(datetime.timezone.utc).isoformat(), **entry}
    with open(SERVE_LOG, "a", encoding="utf-8") as f:
        f.write(json.dumps(entry) + "\n")


def post(path: str, payload: dict, timeout: float) -> tuple[int, dict[str, str], str]:
    """POST JSON. Returns (status, headers, body). Raises only on transport failure."""
    request = urllib.request.Request(
        BASE_URL + path,
        data=json.dumps(payload).encode("utf-8"),
        method="POST",
        headers={"Authorization": "Bearer " + PARTNER_KEY, "Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            return response.status, dict(response.headers), response.read().decode("utf-8")
    except urllib.error.HTTPError as error:  # 4xx and 5xx arrive here with a body
        return error.code, dict(error.headers), error.read().decode("utf-8")


def decide(query: str | None = None, topics: list[str] | None = None,
           url: str | None = None, safe: bool = True) -> dict | None:
    """Ask for a placement. Returns None on no fill, on any error, and when the budget runs out."""
    payload = {"query": query, "topics": topics or [], "url": url, "safe": safe}
    payload = {k: v for k, v in payload.items() if v is not None}
    try:
        status, _, body = post("/v1/decide", payload, DECIDE_TIMEOUT_S)
    except (OSError, urllib.error.URLError) as error:  # includes timeouts
        serve_log(event="decide_failed", error=repr(error))
        return None
    if status != 200:
        # 401, 429, 400 and 5xx: answer without a placement. Never retry inside the answer path.
        serve_log(event="decide_failed", status=status, body=body)
        return None
    result = json.loads(body)
    return result if result.get("filled") is True else None


def render(answer: str, fill: dict | None) -> str:
    """Put the placement under the answer, exactly as CrawlClick wrote it."""
    if fill is None:
        return answer
    return f"{answer}\n\n{fill['disclosure']['passage']}"


def receipt_signature(decision_id: str) -> str:
    message = ("crawlclick-receipt-v1\n" + decision_id).encode("utf-8")
    return b64url_encode(RECEIPT_KEY.sign(message))


def confirm(fill: dict) -> str:
    """Confirm a placement you showed. Call it after the answer has gone out, never before."""
    payload = {
        "decision_id": fill["decision_id"],
        "key_id": RECEIPT_KEY_ID,
        "signature": receipt_signature(fill["decision_id"]),
    }
    delay = 1.0
    attempt = 0
    while True:
        attempt += 1
        status, headers, body, retry_after = 0, {}, "", 0.0
        try:
            status, headers, body = post("/v1/decide/receipts", payload, RECEIPT_TIMEOUT_S)
            retry_after = float(headers.get("Retry-After") or 0)
        except (OSError, urllib.error.URLError) as error:
            body = repr(error)  # the request may not have arrived: the same receipt is safe to resend
        serve_log(event="receipt_attempt", decision_id=fill["decision_id"],
                  attempt=attempt, status=status, body=body)

        if status in (200, 202):
            result = json.loads(body)
            if result.get("recorded") is True:
                return "recorded"
            if result.get("duplicate") is True:
                return "duplicate"
            if result.get("code") == "budget_exhausted":
                return "budget_exhausted"
            return "refused"
        if status == 410:
            return "expired"
        if status not in (0, 429, 503):
            # 400, 401 and 403 will fail the same way every time. Fix the cause; do not resend.
            return "refused"
        wait = max(delay, retry_after)
        if time.time() + wait > fill["expires_at"] - RECEIPT_MARGIN_S:
            return "gave_up"
        time.sleep(wait)
        delay = min(delay * 2, 60.0)


def main() -> None:
    question = sys.argv[1] if len(sys.argv) > 1 else "best crm for a two-person startup"
    answer = "For two people, pick a CRM with a free tier and a shared inbox."  # your own answer
    fill = decide(query=question, topics=["crm"], safe=True)
    print(render(answer, fill))  # this is where your product shows the answer
    if fill is None:
        return
    serve_log(event="shown", decision_id=fill["decision_id"], campaign_id=fill["campaign_id"],
              creative_id=fill["creative_id"], advertiser=fill["disclosure"]["advertiser"],
              price_micros=fill["price_micros"], expires_at=fill["expires_at"])
    outcome = confirm(fill)
    serve_log(event="receipt_outcome", decision_id=fill["decision_id"], outcome=outcome)


if __name__ == "__main__":
    main()

What does the serve log record?

Each line of crawlclick-serves.jsonl is one JSON object with a timestamp and an event:

  • shown: a placement went out with your answer, with its decision_id, campaign, creative, advertiser, price_micros and expires_at.
  • receipt_attempt: one call to /v1/decide/receipts, with the attempt number, the HTTP status (0 for a transport failure) and the response body.
  • receipt_outcome: the final result for that decision: recorded, duplicate, budget_exhausted, expired, refused or gave_up.
  • decide_failed: a decision that failed or timed out, so the answer went out without a placement.

The log is your side of reconciliation. CrawlClick’s console shows confirmed serves paid and refused per day, and CrawlClick compares those counts with your own record of what you showed. Keep the log for as long as you keep your billing records. In production, write it to your own durable store rather than a local file.

Why does the client retry some responses and not others?

Response Client action Reason
202 recorded Stop The serve is evidence and will be billed.
200 duplicate Stop The decision was already confirmed.
202 budget_exhausted Stop The campaign ran out of budget; the serve is not billed.
503 Retry the same receipt The receipt was not written, or the service was busy.
429 Retry the same receipt Your per-minute receipt limit refills continuously.
No response Retry the same receipt The request may not have arrived.
400, 401, 403 Stop and alert The same request fails the same way every time.
410 Stop The decision expired; it costs and earns nothing.

Retrying a receipt is safe because the body is identical each time and CrawlClick records a decision once. Retrying /v1/decide is not worth it: a placement that arrives after your answer is no use, and every fill counts towards your daily cap.

What should I change before using it in production?

  • Send the receipt from a background job or queue, not from the request handler, so the reader never waits on it. The sample calls it inline to keep the flow in one place.
  • Persist pending receipts, so a restart between showing and confirming does not lose them. A decision has 15 minutes.
  • Tune DECIDE_TIMEOUT_MS (DECIDE_TIMEOUT_S in Python) to your answer path. The value here is an example, not a CrawlClick figure.
  • Load the private key from your secret manager at start-up, and alert on 401 bad_receipt_signature, which usually means the key id and key do not match what CrawlClick registered.

The routes are described in full on Request a placement and Sign a receipt, and every refusal is on the errors reference.