Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

ring.ts

150 lines4.3 KB

1import type { SessionEvent } from './types'
2​
3/**
4 * A FIFO queue with O(1) push and amortized O(1) shift. A shift moves a head
5 * index. The array is cut only when the dropped half is the bigger half, so
6 * each item is moved at most once per cut.
7 */
8class Queue<T> {
9 private items: Array<T | undefined> = []
10 private head = 0
11​
12 get length() {
13 return this.items.length - this.head
14 }
15​
16 /** The item at `index`, counted from the oldest. */
17 at(index: number) {
18 return this.items[this.head + index] as T
19 }
20​
21 push(item: T) {
22 this.items.push(item)
23 }
24​
25 shift() {
26 if (this.length === 0) return undefined
27 const item = this.items[this.head] as T
28 this.items[this.head] = undefined
29 this.head += 1
30 if (this.head * 2 >= this.items.length) {
31 this.items = this.items.slice(this.head)
32 this.head = 0
33 }
34 return item
35 }
37​
38/** One kept event: the shape of the in-memory tail of the shared log. */
39export interface RingEntry {
40 thread: string
41 entry: SessionEvent
42 /** The byte size of the event (its JSON length). */
43 size: number
45​
46/** The events after a cursor, and whether older events are gone. */
47export interface RingRead {
48 entries: Array<SessionEvent>
49 /**
50 * `true` when the cursor is older than the oldest kept event: the ring
51 * dropped events that the reader did not get. The caller can send a gap.
52 */
53 gap: boolean
55​
56/**
57 * The newest events, up to `maxBytes` of them. A push that goes over the cap
58 * drops the oldest events, but the newest event always stays. Cursors are
59 * numbers that grow with each push. They do not need to be consecutive.
60 *
61 * Push and drop are O(1) (amortized). A read finds its start with a binary
62 * search, and a read of one thread uses the index of that thread, so it does
63 * not walk the events of other threads.
64 */
65export class EventRing {
66 private readonly all = new Queue<RingEntry & { cursor: number }>()
67 /** The kept events of each thread, oldest first. */
68 private readonly threads = new Map<
69 string,
70 Queue<RingEntry & { cursor: number }>
71 >()
72 private total = 0
73 private readonly maxBytes: number
74 /** Every event after this cursor is kept. */
75 private floor: number
76​
77 /**
78 * `from`: the cursor before the first event the ring gets. A read from an
79 * older cursor reports a gap. Default `0`.
80 */
81 constructor(options: { maxBytes: number; from?: number }) {
82 this.maxBytes = options.maxBytes
83 this.floor = options.from ?? 0
84 }
85​
86 /** The sum of the sizes of the kept events. */
87 get bytes() {
88 return this.total
89 }
90​
91 /** The number of kept events. */
92 get length() {
93 return this.all.length
94 }
95​
96 /** Every event after this cursor is kept. An older cursor has a gap. */
97 get from() {
98 return this.floor
99 }
100​
101 /** Keep `item`. Its cursor must be bigger than the cursor of each kept event. */
102 push(item: RingEntry): void {
103 const kept = { ...item, cursor: Number(item.entry.cursor) }
104 this.all.push(kept)
105 let own = this.threads.get(item.thread)
106 if (!own) {
107 own = new Queue()
108 this.threads.set(item.thread, own)
109 }
110 own.push(kept)
111 this.total += item.size
112 while (this.total > this.maxBytes && this.all.length > 1) {
113 // The oldest event of all is also the oldest event of its thread.
114 const dropped = this.all.shift()
115 if (!dropped) break
116 const queue = this.threads.get(dropped.thread)
117 queue?.shift()
118 if (queue?.length === 0) this.threads.delete(dropped.thread)
119 this.total -= dropped.size
120 this.floor = dropped.cursor
121 }
122 }
123​
124 /**
125 * The kept events after `cursor` (exclusive), oldest first. With `thread`,
126 * only the events of that thread.
127 */
128 after(cursor: number, thread?: string): RingRead {
129 const queue = thread === undefined ? this.all : this.threads.get(thread)
130 const entries: Array<SessionEvent> = []
131 if (queue) {
132 for (let i = firstAfter(queue, cursor); i < queue.length; i++) {
133 entries.push(queue.at(i).entry)
134 }
135 }
136 return { entries, gap: cursor < this.floor }
137 }
139​
140/** The index of the first item of `queue` with a cursor after `cursor`. */
141function firstAfter(queue: Queue<{ cursor: number }>, cursor: number) {
142 let low = 0
143 let high = queue.length
144 while (low < high) {
145 const middle = (low + high) >>> 1
146 if (queue.at(middle).cursor <= cursor) low = middle + 1
147 else high = middle
148 }
149 return low