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)
typeTy<T>
Each entry's type, built with `t`.
Ty<T>options.retention?Retention
Which entries are kept, and with no limit set, every entry is kept for good.
Retention{}options.rollups?Record<string, Rollup>
Time-series aggregates kept up to date with every append.
Record<string, Rollup>options.live?boolean
Each append is kept and readable at once, on its own, rather than when the handler commits.
booleanfalseRetention
An entry is dropped once it passes any limit you set.
maxAge?string | number
Drops entries older than this, as a duration such as `"7d"` or milliseconds.
string | numbermaxCount?number
Keeps at most this many entries, the newest.
numbermaxBytes?number
Keeps at most this many bytes of entries as JSON, oldest dropped first, and the newest always stays.
numberRollup
everystring | number
The length of each bucket, from 1 second to 1 year.
string | numberkeep?string | number
How long buckets are kept, at least one bucket long, and with none set, for good.
string | numberby?string
A dotted path into each entry: buckets are kept per value found there.
stringfieldsRecord<string, Aggregate>
The aggregates of each bucket, made with `agg`, at most 32.
Record<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".
count(path?)?Aggregate
Entries in the bucket, or with a path, those where it holds a value.
Aggregatesum(path)?Aggregate
The sum of the values.
Aggregatemin(path)?Aggregate
The smallest value.
Aggregatemax(path)?Aggregate
The largest value.
Aggregateavg(path)?Aggregate
The mean of the values.
Aggregatefirst(path)?Aggregate
The value of the bucket's first entry.
Aggregatelast(path)?Aggregate
The value of the bucket's last entry.
AggregateStream
A handler reaches each stream as ctx.streams.<name>.
namestring
The stream's name.
stringappend(data)number
Appends an entry and returns its offset.
numberappendMany(data[])number
Appends entries in order and returns the first one's offset.
numberread(opts?)StreamPage<T>
Up to `limit` entries from offset `from` on, with `from` 0 and `limit` 100 by default, and 1,000 at most.
StreamPage<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.
RollupRow[]from and to of rollup are milliseconds since the epoch.
StreamEntry and StreamPage
offsetnumber
The entry's place in the stream, from 0, kept for good.
numberatnumber
When it was appended, in milliseconds since the epoch.
numberdataT
The entry.
TA StreamPage<T> holds a page of entries.
entriesStreamEntry<T>[]
The entries read.
StreamEntry<T>[]firstnumber
The oldest offset still kept.
numbernextnumber
Where to read on from.
numberendnumber
The offset the next append gets.
numberRollupRow
atnumber
When the bucket starts, in milliseconds since the epoch.
numberby?string
The bucket's group, for a rollup with `by`.
stringcountnumber
How many entries the bucket holds.
number[field]?any
Each aggregate, under the name it was declared with.
anyctx.subscribe, ctx.unsubscribe and ctx.subscriptions
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.
stringunsubscribe(id)boolean
Stops following, and returns `false` if there was no such subscription.
booleansubscriptions()SubscriptionInfo[]
The streams this luna follows.
SubscriptionInfo[]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.
subscriptionstring
The subscription's id.
stringstreamstring
The stream's name.
stringoffsetnumber
The entry's offset.
numberatnumber
When it was appended, in milliseconds since the epoch.
numberdataT
The entry.
TSubscriptionInfo
idstring
The subscription's id.
stringlunaTypestring
The followed luna's type.
stringkeyRecord<string, unknown>
The followed luna's key.
Record<string, unknown>streamstring
The followed stream.
stringhandlerstring
The handler each entry runs.
stringnextnumber
The next offset it expects, and everything before it is handled.
numbercreatedMsnumber
When it was made, in milliseconds since the epoch.
numberGood to know
- An append is kept once the handler commits, and a handler that fails leaves nothing behind. On a
livestream, 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
firstgrows 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.