Skip to content

@ogygia/postrender

Custom adapters

Write your own store for a database postrender doesn't ship, or your own edge for another CDN. A store is four async methods plus evictByTag, and an edge is a name, a headers function and two purge calls.

On this page

The built-in stores and edges cover the common cases. For anything else, such as a database you already run or a CDN with its own purge API, write an adapter. Neither needs a base class: a store is any object that matches PostrenderStore, and an edge is any object that matches EdgeAdapter. Both types come from @ogygia/postrender.

Pass yours to postrender.handle() like a built-in one. In the example, kv is your own key-value client, wrapped to match the Kv interface below.

import { sequence } from '@sveltejs/kit/hooks';
import * as ogygia from 'ogygia/server';
import { postrender } from '@ogygia/postrender';
import { KvPageStore } from '$lib/server/page-store';
import { myCdn } from '$lib/server/my-cdn';
import { kv } from '$lib/server/kv';
import { CDN_TOKEN } from '$env/static/private';

export const handle = sequence(
  postrender.handle({
    store: new KvPageStore(kv),
    edge: [
      myCdn({
        site: 'https://www.example.com',
        token: CDN_TOKEN
      })
    ]
  }),
  ogygia.handle()
);

Store adapters

A store keeps entries by key. The keys are page paths, and an entry is a plain object you can pass to JSON.stringify, so most stores keep the JSON string under the key. The interface:

Each method has a rule to keep:

  • get returns what put was given for that key, or null. Don’t change the entry.
  • put should expire the entry after ttl seconds, so old pages stop taking room. Postrender also checks each page’s age against its created time when it reads it, so a store with no expiry still never serves a page past its TTL.
  • put gets a ttl of ten years for one key. Postrender keeps a record of the last build under a key that starts with a NUL character (\0), so not every key is a path, and that record has to outlive any page. Don’t cap ttl at a day.
  • evict removes one key.
  • evictWhere gets a prefix that starts with / and has no trailing slash, except / itself. Remove the key equal to the prefix and every key under prefix + '/', never a sibling: /fr removes /fr, /fr/ and /fr/about, not /fresh. / removes every page, and should leave the NUL-prefixed record.
  • evictByTag removes every key whose put carried the tag in tags, and returns those keys, which postrender then purges at every edge. Every page carries a tag for the build that stored it and one per data source it read. Without evictByTag, a clear by source logs postrender_store_no_evict_by_tag and clears nothing. The same warning comes on the first request after each new build, since the deploy can’t clear the old build’s pages early (they’re still never served), and on each federation thaw notice.

A method may throw. A get that throws is a miss, a put that throws is skipped, and a failed evict is logged; see When a store or edge fails.

An example store

This store runs on any key-value client that can expire a key and list keys by prefix. Pages go under page:<path>, and each tag is a set of marker keys, tag:<tag> and the path, so clearing a tag is one listing:

What an entry holds

PostrenderEntry is one of two shapes. A store doesn’t need to read them, only keep them:

  • A page: { kind: 'page', html, headers, created, build?, head_end?, stitch? }. headers are the ones every hit is sent with, created is when it was stored (milliseconds since 1970), build is the build that stored it, head_end is where </head> is in html, and stitch marks a page with a stitch: 'serve' hole.
  • A permanent redirect: { kind: 'redirect', status: 301 | 308, location, created, build? }.

An entry with no build, or one from another build, is a miss. So is one whose created isn’t a number.

interface PostrenderStore {
  get(key: string): Promise<PostrenderEntry | null>;
  put(
    key: string,
    entry: PostrenderEntry,
    options: { ttl: number; tags?: string[] }
  ): Promise<void>;
  evict(key: string): Promise<void>;
  evictWhere(filter: { prefix: string }): Promise<void>;
  evictByTag?(tag: string): Promise<string[]>; // optional, but clearing by source and deploys need it
  size?(): Promise<number>; // optional, for tests and tooling
}
import type {
  PostrenderEntry,
  PostrenderPutOptions,
  PostrenderStore
} from '@ogygia/postrender';

/** Any key-value client with expiry and listing by prefix. */
export interface Kv {
  get(key: string): Promise<string | null>;
  set(
    key: string,
    value: string,
    ttlSeconds: number
  ): Promise<void>;
  delete(keys: string[]): Promise<void>;
  list(prefix: string): Promise<string[]>;
}

const PAGE = 'page:';
const TAG = 'tag:';
const mark = (tag: string, key: string) =>
  `${TAG}${tag}\n${key}`;

export class KvPageStore implements PostrenderStore {
  #kv: Kv;

  constructor(kv: Kv) {
    this.#kv = kv;
  }

  async get(key: string): Promise<PostrenderEntry | null> {
    const raw = await this.#kv.get(PAGE + key);
    return raw === null
      ? null
      : (JSON.parse(raw) as PostrenderEntry);
  }

  async put(
    key: string,
    entry: PostrenderEntry,
    { ttl, tags = [] }: PostrenderPutOptions
  ): Promise<void> {
    await this.#kv.set(PAGE + key, JSON.stringify(entry), ttl);
    for (const tag of tags)
      await this.#kv.set(mark(tag, key), '', ttl);
  }

  async evict(key: string): Promise<void> {
    await this.#kv.delete([PAGE + key]);
  }

  async evictWhere({
    prefix
  }: {
    prefix: string;
  }): Promise<void> {
    const under = prefix === '/' ? '/' : `${prefix}/`;
    await this.#kv.delete([
      PAGE + prefix,
      ...(await this.#kv.list(PAGE + under))
    ]);
  }

  async evictByTag(tag: string): Promise<string[]> {
    const marks = await this.#kv.list(mark(tag, ''));
    const keys = marks.map((m) =>
      m.slice(mark(tag, '').length)
    );
    await this.#kv.delete([
      ...keys.map((key) => PAGE + key),
      ...marks
    ]);
    return keys;
  }
}

Edge adapters

An edge is a name and three functions. The example below purges a CDN with a JSON API:

  • name names the edge in log messages.
  • headers({ url, ttl }) returns headers to add to a page as it’s stored: cache tags, a cache-control of its own. They’re added after postrender’s own, so they can replace its cache-control. It’s called once per stored page, never for a page with a stitch: 'serve' hole (it isn’t cached at the edge), and one that throws is skipped.
  • purgeUrl(path) gets the decoded pathname, the store’s key (/café, not /caf%C3%A9, and %2F decoded to /; see One copy per path). Your CDN caches the encoded URL, so encode it with encodeURI(path) before you make it absolute.
  • purgeWhere({ prefix }) gets the same prefix a store’s evictWhere does.

Postrender calls every edge at once and waits for all of them. A purge that rejects is logged (postrender_fanout_failed) and never fails the clear, so throw on a failed purge rather than ignoring it. Edges aren’t called when a post clears its own page. After a deploy, purgeUrl is called once for each page the old build stored.

import type { EdgeAdapter } from '@ogygia/postrender';

export function myCdn(opts: {
  site: string;
  token: string;
}): EdgeAdapter {
  const purge = async (body: unknown): Promise<void> => {
    const res = await fetch(
      'https://api.cdn.example.com/purge',
      {
        method: 'POST',
        headers: {
          authorization: `Bearer ${opts.token}`,
          'content-type': 'application/json'
        },
        body: JSON.stringify(body)
      }
    );
    if (!res.ok) throw new Error(`purge failed: ${res.status}`);
  };

  return {
    name: 'my-cdn',
    headers: ({ ttl }) => ({
      'cache-control': `public, s-maxage=${ttl}`
    }),
    purgeUrl: (path) =>
      purge({ urls: [opts.site + encodeURI(path)] }),
    purgeWhere: ({ prefix }) =>
      purge({ prefix: opts.site + encodeURI(prefix) })
  };
}