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

stream

Declare an append-only log in a luna, read and roll it up with ctx.streams, and follow another luna's stream with ctx.subscribe.

stream declares an append-only log of typed entries that a luna keeps in its own database, under the luna type’s streams option.

import { defineLuna, stream, t } from "luna";

export const Room = defineLuna({
  name: "Room",
  key: { id: t.string() },
  streams: {
    messages: stream(t.object({ from: t.string(), text: t.string() }), { retention: { maxCount: 1000 } }),
  },
  handlers: (h) => ({
    say: h({ args: { from: t.string(), text: t.string() } }, (ctx, m) => ctx.streams.messages.append(m)),
    history: h({ args: { from: t.int() }, query: true }, (ctx, { from }) => ctx.streams.messages.read({ from, limit: 50 })),
  }),
});

Reference

stream(type, options)

PropType
typeTy<T>

Each entry's type, built with `t`.

TypeTy<T>
options.retention?Retention

Which entries are kept, and with no limit set, every entry is kept for good.

TypeRetention
Default{}
options.rollups?Record<string, Rollup>

Time-series aggregates kept up to date with every append.

TypeRecord<string, Rollup>
options.live?boolean

Each append is kept and readable at once, on its own, rather than when the handler commits.

Typeboolean
Defaultfalse

Retention

An entry is dropped once it passes any limit you set.

PropType
maxAge?string | number

Drops entries older than this, as a duration such as `"7d"` or milliseconds.

Typestring | number
maxCount?number

Keeps at most this many entries, the newest.

Typenumber
maxBytes?number

Keeps at most this many bytes of entries as JSON, oldest dropped first, and the newest always stays.

Typenumber

Rollup

PropType
everystring | number

The length of each bucket, from 1 second to 1 year.

Typestring | number
keep?string | number

How long buckets are kept, at least one bucket long, and with none set, for good.

Typestring | number
by?string

A dotted path into each entry: buckets are kept per value found there.

Typestring
fieldsRecord<string, Aggregate>

The aggregates of each bucket, made with `agg`, at most 32.

TypeRecord<string, Aggregate>

A stream has at most 16 rollups. An aggregate’s name is letters, digits and _, at most 64 characters, and is never at, by or count.

agg

Each takes a dotted path into an entry’s data, such as "ms" or "req.route".

PropType
count(path?)?Aggregate

Entries in the bucket, or with a path, those where it holds a value.

TypeAggregate
sum(path)?Aggregate

The sum of the values.

TypeAggregate
min(path)?Aggregate

The smallest value.

TypeAggregate
max(path)?Aggregate

The largest value.

TypeAggregate
avg(path)?Aggregate

The mean of the values.

TypeAggregate
first(path)?Aggregate

The value of the bucket's first entry.

TypeAggregate
last(path)?Aggregate

The value of the bucket's last entry.

TypeAggregate

Stream

A handler reaches each stream as ctx.streams.<name>.

PropType
namestring

The stream's name.

Typestring
append(data)number

Appends an entry and returns its offset.

Typenumber
appendMany(data[])number

Appends entries in order and returns the first one's offset.

Typenumber
read(opts?)StreamPage<T>

Up to `limit` entries from offset `from` on, with `from` 0 and `limit` 100 by default, and 1,000 at most.

TypeStreamPage<T>
rollup(name, opts?)RollupRow[]

A rollup's buckets, oldest first, from `from` up to before `to`, only group `by` if given, at most `limit` and 1,000.

TypeRollupRow[]

from and to of rollup are milliseconds since the epoch.

StreamEntry and StreamPage

PropType
offsetnumber

The entry's place in the stream, from 0, kept for good.

Typenumber
atnumber

When it was appended, in milliseconds since the epoch.

Typenumber
dataT

The entry.

TypeT

A StreamPage<T> holds a page of entries.

PropType
entriesStreamEntry<T>[]

The entries read.

TypeStreamEntry<T>[]
firstnumber

The oldest offset still kept.

Typenumber
nextnumber

Where to read on from.

Typenumber
endnumber

The offset the next append gets.

Typenumber

RollupRow

PropType
atnumber

When the bucket starts, in milliseconds since the epoch.

Typenumber
by?string

The bucket's group, for a rollup with `by`.

Typestring
countnumber

How many entries the bucket holds.

Typenumber
[field]?any

Each aggregate, under the name it was declared with.

Typeany

ctx.subscribe, ctx.unsubscribe and ctx.subscriptions

PropType
subscribe(luna, key, stream, opts)string

Follows a luna's stream: each entry runs the handler `opts.handler` here, and it returns the subscription's id.

Typestring
unsubscribe(id)boolean

Stops following, and returns `false` if there was no such subscription.

Typeboolean
subscriptions()SubscriptionInfo[]

The streams this luna follows.

TypeSubscriptionInfo[]

opts.from is the offset to start at. By default a subscription starts at the next append.

StreamDelivery

What the subscribed handler receives for each entry. Declare these args on it.

PropType
subscriptionstring

The subscription's id.

Typestring
streamstring

The stream's name.

Typestring
offsetnumber

The entry's offset.

Typenumber
atnumber

When it was appended, in milliseconds since the epoch.

Typenumber
dataT

The entry.

TypeT

SubscriptionInfo

PropType
idstring

The subscription's id.

Typestring
lunaTypestring

The followed luna's type.

Typestring
keyRecord<string, unknown>

The followed luna's key.

TypeRecord<string, unknown>
streamstring

The followed stream.

Typestring
handlerstring

The handler each entry runs.

Typestring
nextnumber

The next offset it expects, and everything before it is handled.

Typenumber
createdMsnumber

When it was made, in milliseconds since the epoch.

Typenumber

Good to know

  • An append is kept once the handler commits, and a handler that fails leaves nothing behind. On a live stream, each append is kept at once and stays if the handler fails.
  • A stream is live or not for good, so its offsets stay in order.
  • Luna checks each entry against the stream’s type. An entry of another type fails the call.
  • Retention drops the oldest entries. Offsets never move, so first grows as entries go.
  • Rollups are kept apart from the entries. A bucket outlives the entries it counted.
  • A subscription delivers entries durably, in order and at least once.
  • A retention limit must be above zero.

Examples

Roll up messages per hour

import { agg, defineLuna, stream, t } from "luna";

export const Room = defineLuna({
  name: "Room",
  key: { id: t.string() },
  streams: {
    messages: stream(t.object({ from: t.string(), text: t.string() }), {
      retention: { maxCount: 1000 },
      rollups: { hourly: { every: "1h", keep: "30d", by: "from", fields: { sent: agg.count() } } },
    }),
  },
  handlers: (h) => ({
    busiest: h({ query: true }, (ctx) => ctx.streams.messages.rollup("hourly", { from: ctx.now() - 86_400_000 })),
  }),
});

Follow another luna’s stream

import { defineLuna, type StreamDelivery, t, table } from "luna";
import { Room } from "./room.ts";

export const Follower = defineLuna({
  name: "Follower",
  key: { id: t.string() },
  schema: { seen: table({ offset: t.int(), text: t.string() }, { primaryKey: ["offset"] }) },
  handlers: (h) => ({
    follow: h({ args: { room: t.string() } }, (ctx, { room }) =>
      ctx.subscribe(Room, { id: room }, "messages", { handler: "onMessage" }),
    ),
    onMessage: h(
      { args: { subscription: t.string(), stream: t.string(), offset: t.int(), at: t.int(), data: t.json() } },
      (ctx, delivery) => {
        const d = delivery as StreamDelivery<{ from: string; text: string }>;
        ctx.db.seen.upsert({ offset: d.offset, text: d.data.text });
      },
    ),
    leave: h({}, (ctx) => {
      for (const s of ctx.subscriptions()) ctx.unsubscribe(s.id);
    }),
  }),
});

Report progress while a handler runs

streams: {
  progress: stream(t.int(), { live: true, retention: { maxAge: "1d" } }),
},
work: h({}, async (ctx) => {
  for (let step = 1; step <= 10; step++) {
    await new Promise((r) => setTimeout(r, 100));
    ctx.streams.progress.append(step * 10);
  }
}),

Apps follow a live stream as it grows. See LunaHandle.

Was this page helpful?