Reminders
RFC 5545 recurrence and reminders, expanded in TypeScript and delivered through notifications.
reminders stores a recurrence rule, a reminder (who, how, how long before) and one delivery row per occurrence. Expansion runs in the app with expandRule, on Temporal.ZonedDateTime, so a local time stays put across a daylight-saving change. list_reminder_schedule returns each reminder with its rule. planReminderDeliveries expands a horizon and returns one delayed job per occurrence, with a dedupe key of reminder id and occurrence. deliverReminder calls mark_reminder_sent, which records reminder.sent, then your notify function.
better-supabase add remindersThe block's entity is reminder (the reminders table). It isn't registered as a subject. Rename it with blocks.reminders.names.
import {
createReminders,
planReminderDeliveries,
} from "better-supabase/blocks/reminders";options.ruleFormat is rrule (the default) or columns. The columns format maps frequency, interval_count, week_days, month_day, month_weekday and month_ordinal.
reminders.upsert(subject, offsetMinutes) sets a reminder for the caller (or upsert(subject, { at }) for one time), reminders.list(subject) returns the caller's reminders on that subject, reminders.listForCaller() returns every reminder the caller set in the tenant with the subject of each, and reminders.remove(id) deletes one with its delivery history. All four need reminders.manage. The subject is a RecordRef, such as { type: "task", id: taskId }, and upsert and list act in the block's tenant, an organization id or a function that returns the current one. createBlocks and createBlockClient pass the request's tenant; a call without one fails with invalid_request and the hint TENANT_REQUIRED. The calendar block mirrors each event into a rule, so reminders on a calendar_event fire.
One-time reminders and subject times
A reminder fires before each occurrence of its subject's rule, before the
time in a column of the subject's row, or once at a time you give it.
upsert takes { at } in place of the offset for a one-time reminder:
await db.reminders
.upsert(
{ type: "task", id: taskId },
{ at: Temporal.Instant.from("2030-03-06T07:30:00Z") },
)
.orThrow();The time lands in the reminder's remind_at column, and list returns it as
remindAt. Map columns.reminders.remindAt to null on a table without
the column; upsert then takes offsets only.
A subject without a recurrence rule, such as a task with a due date, names
the column that holds its time in on.<type>.at. Its reminders fire
offsetMinutes before that time, and a subject with no time set gets none:
reminders: {
on: { task: { table: "public.tasks", at: "due_at" } },
},upsert checks the subject. With on set, a subject type that on doesn't
list is refused with REMINDER_SUBJECT_UNSUPPORTED. A subject of a type in
on, or in config.recordTypes when on is unset,
must exist in the organization and be readable by the caller, or upsert
fails with REMINDER_SUBJECT_NOT_FOUND. Other types pass unchecked. The
service role skips both checks.
expandRule covers FREQ, INTERVAL, COUNT, UNTIL, BYDAY with ordinals, BYMONTHDAY, BYMONTH, BYSETPOS and WKST. The pin is SPEC_PINS.rfc5545.
Delivery
reminders.deliver(payload) marks one occurrence sent and, when this call
recorded it, calls notifyDelivery, which defaults to sending the
notification type through the notifier port. It returns ok(true) for the first
delivery and ok(false) for a replay, which records no second
reminder.sent and sends nothing. The payload's occurrenceAt is a
Temporal.Instant, as are the ones planReminderDeliveries returns and the
one reminders.markSent(id, occurrenceAt) takes. In a queued job it travels as
ISO text, and the handler reads it back into an Instant; the notification's
data.occurrenceAt stays ISO text. reminders.job is the same call as a job
handler, for the reminders.deliver queue (REMINDER_DELIVERY_QUEUE):
Server code calls the reminders instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useReminders } = defineDataHooks(
"reminders",
(db: AppDb) => db.reminders,
);const rows = await db.reminders.list({ limit: 50 }).orThrow();"use client";
import { useReminders } from "@/lib/supabase/hooks";
const rows = useReminders({ limit: 50 });Before it records the occurrence, deliver checks the reminder's user with
audience, a SubscriberPolicy. A user it leaves out still has the
occurrence recorded but gets no notification, and a throw fails the call
with the hint REMINDER_AUDIENCE_FAILED so the job retries. Without the
option it uses authorization.delivery.audience; with authorization and
no such policy, it uses subjectReaders, so a user who lost read access to
the subject stops getting its reminders:
createReminders({ ...context, authorization: bsb.authorization });Scheduling deliveries
reminders.schedule() plans the deliveries on the server. It reads
list_reminder_schedule as the service role, expands each reminder's rule,
and enqueues one reminders.deliver job per occurrence due in the next day
on jobs, keyed by reminder id and occurrence. Running it again enqueues
nothing new, and deliver still records each occurrence once, so the two
dedupes together send every reminder once. A delivery that fell due in the
last 15 minutes still goes out, so a late run catches up.
The block declares the timer reminders.schedule (every five minutes) in its
manifest, so blockSchedules creates it with the
other block timers:
export const jobs = createQueue({
sql: postgres.admin,
queues: {
[BLOCK_TICKS_QUEUE]: blockTickSchema,
[REMINDER_DELIVERY_QUEUE]: reminderJobSchema,
},
});
const { reminders } = createBlocks(
{ transport, service },
{
notifications: notificationsBlock,
reminders: remindersBlock.with({ jobs }),
},
);
export const ticks = blockTickHandler({
"reminders.schedule": () => reminders.schedule(),
});| Option | Default | Does |
|---|---|---|
horizonMinutes | 1440 | How far ahead to enqueue deliveries |
lookbackMinutes | 15 | How far back a missed delivery is still enqueued |
now | now | The instant the window starts from, for tests |
It returns { planned, enqueued, duplicates, skipped }. Rules kept in
columns (ruleFormat: "columns") are counted in skipped: expand those with
planReminderDeliveries from your own rule reader. Without jobs,
schedule fails with the hint REMINDER_JOBS_MISSING.
reminder.sent carries organizationId, id, subjectType, subjectId
and userId, so a watcher sink can
route it like any other subject event.
Your own fields
Columns you add to reminders with alter table in your own schema files are fields of the block (details). upsert writes them (its last argument) from fields,
and upsert return them in fields. Pass a Standard Schema as fields
to type them: writes are validated before they reach the database (a
validation error), and reads are parsed. hooks refuses, rewrites or
observes any method; see extending blocks.
alter table "better_supabase"."reminders" add column "channel" text;const client = createReminders({
transport,
tenant: organizationId,
fields: v.object({ channel: v.optional(v.picklist(["email", "push"])) }),
});
await client.upsert({ type: "task", id: taskId }, 30, { channel: "push" });Over your own tables
To run over tables you already have, map tables.rules, tables.reminders and tables.deliveries. Collection-level defaults, such as agenda_collection_notification_reminders, are reminders whose subject is the collection.
Without the client
db.reminders is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
const { reminders } = createBlocks(
{ transport, service },
{
notifications: notificationsBlock,
reminders: remindersBlock.with({ notification: "reminder.due" }),
},
);
export const GET = jobs.drainRoute({
secret: process.env.CRON_SECRET,
handlers: { [REMINDER_DELIVERY_QUEUE]: reminders.job },
});Paging reminders
page pages the caller's own reminders, so every row belongs to the signed-in user. Sorts are offsetMinutes and subjectType. Filters are subjectType, subjectId and method, facets are method and subjectType. facets and count read under the same filters, and get(reminderId) returns one reminder or a not_found error. The SQL functions are page_my_reminders and get_my_reminder.
const mine = await reminders.page({ filters: { method: ["email"] } }).orThrow();Last updated on