Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

defineEvent

Declare a typed event that any luna emits with ctx.emit and any luna type hears through its on option.

defineEvent declares a typed event. Any luna emits it with ctx.emit, and any luna type hears it through its on option.

import { defineEvent, t } from "luna";

export const CardDone = defineEvent("cards.done", t.object({ card: t.int(), owner: t.string() }));

Reference

defineEvent(name, type, options)

PropType
namestring

The event's name: letters, digits, `_`, `.` and `-`, at most 128 characters.

Typestring
typeTy<T>

The payload's type, built with `t`.

TypeTy<T>
options.retention?EventRetention

How long each emitting luna keeps the events it emitted, for listeners that come later.

TypeEventRetention
Default{ maxAge: "7d" }

It returns an EventDef.

PropType
namestring

The name it was declared with.

Typestring
typeTy<T>

The payload's type.

TypeTy<T>
map(fn: (e: T, from: Record<string, any>) => R) => Source<R, T>

A source that sends each listener only the fields `fn` names.

Type(fn: (e: T, from: Record<string, any>) => R) => Source<R, T>

EventRetention

An event leaves the emitter’s keeping once it passes any limit you set. Leave out retention to keep events for 7 days. Pass {} to set no limit.

PropType
maxAge?string | number

Drops events older than this, as a duration such as `"30d"` or milliseconds.

Typestring | number
maxCount?number

Keeps at most this many events, the newest.

Typenumber
maxBytes?number

Keeps at most this many bytes of events, the newest.

Typenumber

ctx.emit(event, payload)

PropType
eventEventDef

The event to emit.

TypeEventDef
payloadEventOf<E>

The payload, of the event's type.

TypeEventOf<E>

It returns a number: the event’s place in this luna’s log of that event. The ctx page covers the rest of ctx.

The on option and listen

A luna type lists what it hears in on. The function receives listen and returns a list of its results: on: (listen) => [listen(source, options, handler)].

PropType
sourceEventDef | Source | TableChanges

An event, a mapped event, or a luna type's table changes.

TypeEventDef | Source | TableChanges
options.key?(item, from) => unknown

Names which luna of this type hears each item, and is left out on a type with no key.

Type(item, from) => unknown
handler(ctx, item, from: From) => void | Promise<void>

Runs for each event or change, with this type's `ctx`.

Type(ctx, item, from: From) => void | Promise<void>

The key function only names values. It may return a field of the payload or row, a key field of the emitting luna from from, a constant, day(field) or hash(n). A type with several key fields returns an object with each of them.

The handler’s third argument is a From, the emitting luna:

PropType
typestring

The emitting luna's type.

Typestring
keyRecord<string, unknown>

The emitting luna's key.

TypeRecord<string, unknown>

day(field) and hash(n)

PropType
day(field)?never

The UTC day, as `YYYY-MM-DD`, of a field that holds milliseconds since the epoch.

Typenever
hash(n)?never

A bucket from 0 to `n - 1`, picked by a hash of the emitting luna's key. `n` is 1 to 1024.

Typenever

Both are imported from "luna" and used only inside a key function, such as key: (e) => day(e.at).

TableChanges

Every luna type has changes, with one TableChanges for each of its tables, such as Card.changes.notes.

PropType
where(w: Record<string, unknown>) => TableChanges

Only rows that match, with a value or `eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `in` and `isNull`.

Type(w: Record<string, unknown>) => TableChanges
map(fn: (row, from) => M) => TableChanges

Sends each listener only the fields `fn` names, from the row and the emitting luna's key.

Type(fn: (row, from) => M) => TableChanges

TableChange

What a listener’s handler receives for each change of a table’s row.

PropType
op"upsert" | "delete" | "clear"

What happened to the row.

Type"upsert" | "delete" | "clear"
key?unknown[]

The row's primary key values, set for `upsert` and `delete`.

Typeunknown[]
row?R

The row as it is now, set for `upsert`.

TypeR

clear means everything from that emitting luna goes. It comes when the luna was destroyed, or before it sends all its rows again, such as after a deploy changes the listen.

Good to know

  • An emit is a write. It goes out once the handler commits, and a handler that fails takes it back, as does a ctx.transaction that throws.
  • Luna checks each payload against the event’s type. A payload of another type, or one over 1 MiB as JSON, fails the call.
  • A listener hears one emitting luna’s events and changes in order. Luna delivers each batch at least once and skips a batch the listener already ran, so the handler runs once for each item.
  • Items come in batches, each in one transaction. A batch that fails is tried again.
  • Each event reaches one luna per listen: the one its key names. There is no broadcast to every luna of a type.
  • A listen added by a later deploy catches up. It hears the events each emitter still keeps, and every row of a table that matches its where.
  • A row that stops matching the where, or whose key now names another luna, reaches the luna that had it as a delete.
  • A key function that computes a value, such as a template string, throws when the type is defined. It may only name fields.
  • A listen can fill key fields of type string, int, uuid and enum.
  • in in a where takes at most 100 values.
  • Every event your app’s modules define is part of its deploy, whether or not a type listens to it.

Examples

Emit an event

import { defineLuna, t, table } from "luna";
import { CardDone } from "./events.ts";

export const Card = defineLuna({
  name: "Card",
  key: { board: t.string(), card: t.int() },
  schema: { notes: table({ id: t.id(), text: t.string(), done: t.bool().default(false) }) },
  handlers: (h) => ({
    finish: h({ args: { owner: t.string() } }, (ctx, { owner }) => {
      ctx.emit(CardDone, { card: ctx.key.card, owner });
    }),
  }),
});

Hear an event in the luna it names

import { defineLuna, t, table } from "luna";
import { CardDone } from "./events.ts";

export const User = defineLuna({
  name: "User",
  key: { id: t.string() },
  schema: { done: table({ id: t.id(), card: t.int(), board: t.string() }) },
  on: (listen) => [
    listen(CardDone, { key: (e) => e.owner }, (ctx, e, from) => {
      ctx.db.done.insert({ card: e.card, board: String(from.key.board) });
    }),
  ],
  handlers: (h) => ({
    done: h({ query: true }, (ctx) => ctx.db.done.find({ orderBy: "id" })),
  }),
});

Keep a copy of another type’s rows

Each Board keeps the open notes of its cards. The key comes from the emitting card’s own key.

import { defineLuna, t, table } from "luna";
import { Card } from "./card.ts";

export const Board = defineLuna({
  name: "Board",
  key: { id: t.string() },
  schema: {
    open: table({ card: t.int(), note: t.int(), text: t.string() }, { primaryKey: ["card", "note"] }),
  },
  on: (listen) => [
    listen(Card.changes.notes.where({ done: false }), { key: (_row, from) => from.board }, (ctx, change, from) => {
      const card = Number(from.key.card);
      if (change.op === "upsert") ctx.db.open.upsert({ card, note: change.row!.id, text: change.row!.text });
      else if (change.op === "delete") ctx.db.open.delete({ where: { card, note: Number(change.key![0]) } });
      else ctx.db.open.delete({ where: { card } });
    }),
  ],
  handlers: (h) => ({
    open: h({ query: true }, (ctx) => ctx.db.open.find({ orderBy: "card" })),
  }),
});

Keep events for longer

export const CardMoved = defineEvent("cards.moved", t.object({ card: t.int(), to: t.string() }), {
  retention: { maxAge: "30d", maxCount: 10_000 },
});

Version history

Version Change
0.0.9 defineEvent, ctx.emit and listens added.

Was this page helpful?