]> git.giacomolli.uk - onechat/blob - view.go
8877462f6b028c80f54fc23a5d6a5f621545b1fe
[onechat] / view.go
1 package main
2
3 import (
4 "fmt"
5 "math"
6 "math/bits"
7 "strconv"
8 "strings"
9 )
10
11 const (
12 // viewChatHigh and viewChatLow are the limits of the chat view in
13 // bytes.
14 viewChatHigh = 128000
15 viewChatLow = 64000
16
17 // viewCompactionHigh and viewCompactionLow are the limits of the
18 // compaction view in bytes.
19 viewCompactionHigh = 32000
20 viewCompactionLow = 16000
21
22 // viewPending is the text of a line that is not built yet.
23 viewPending = "(not summarized yet: zoom it)"
24 )
25
26 // View is a list of tree nodes that covers messages 0 to end-1 without a gap,
27 // oldest first. Each new message appends its leaf as a line. Once the size of
28 // the view goes above high, one batch merges the most due sibling pairs until
29 // the size is at most low. A batch merges only pairs whose parent is built. If
30 // the batch cannot get to low, it continues at each new message until it does.
31 //
32 // The view keeps the nodes of its built lines in memory, so its size and its
33 // text need no read of the tree. The size of a line is the size of its node
34 // text, or the size of the pending text when the node is not built.
35 //
36 // For the sibling pair (l, i) and (l, i+1), due is (T - last) / 2^l, with T the
37 // number of messages and last the ID of the last message of the pair. That is
38 // how long ago the pair ended, measured in its own line size. With a budget of
39 // the length of the rollback push list of the reference design, this order
40 // makes the same merges as the push. The oldest pair wins a tie.
41 type View struct {
42 high int
43 low int
44 lines []NodeKey
45 nodes map[NodeKey]Node
46 end int
47 merging bool
48 }
49
50 // ViewState is the saved form of a View. The limits are not part of it.
51 type ViewState struct {
52 Lines [][2]int `json:"lines"`
53 Merging bool `json:"merging"`
54 }
55
56 // ViewNodeReader gives the built nodes of a tree.
57 type ViewNodeReader interface {
58 Built(level, index int) (bool, error)
59 Node(level, index int) (Node, bool, error)
60 }
61
62 // newView returns an empty view with the limits high and low.
63 func newView(high, low int) *View {
64 return &View{
65 high: high,
66 low: low,
67 nodes: make(map[NodeKey]Node),
68 }
69 }
70
71 // State returns the saved form of the view.
72 func (v *View) State() ViewState {
73 state := ViewState{
74 Lines: make([][2]int, len(v.lines)),
75 Merging: v.merging,
76 }
77
78 for n, line := range v.lines {
79 state.Lines[n] = [2]int{line.level, line.index}
80 }
81
82 return state
83 }
84
85 // Append adds the leaf of the next message as a line and merges when the view
86 // is too large. It tells if a merge changed the view.
87 func (v *View) Append(tree ViewNodeReader) (bool, error) {
88 line := NodeKey{0, v.end}
89 _, err := v.load(tree, line)
90 if err != nil {
91 return false, fmt.Errorf("load appended leaf: %w", err)
92 }
93
94 v.lines = append(v.lines, line)
95 v.end++
96
97 return v.fit(tree)
98 }
99
100 // load keeps the node of line when it is built, and tells if it is.
101 func (v *View) load(tree ViewNodeReader, line NodeKey) (bool, error) {
102 node, built, err := tree.Node(line.level, line.index)
103 if err != nil || !built {
104 return false, err
105 }
106
107 v.nodes[line] = node
108
109 return true, nil
110 }
111
112 // fit merges the most due pairs while a batch runs, and tells if a merge
113 // changed the view.
114 func (v *View) fit(tree ViewNodeReader) (bool, error) {
115 size := v.Size()
116 if size > v.high {
117 v.merging = true
118 }
119
120 merged := false
121 for v.merging && size > v.low {
122 best, err := v.mostDue(tree)
123 if err != nil || best < 0 {
124 if err != nil {
125 return merged, fmt.Errorf("choose merge candidate: %w", err)
126 }
127
128 return merged, nil
129 }
130
131 left, right := v.lines[best], v.lines[best+1]
132 parent := NodeKey{left.level + 1, left.index / 2}
133 _, err = v.load(tree, parent)
134 if err != nil {
135 return merged, fmt.Errorf("load merged parent: %w", err)
136 }
137
138 size += v.lineSize(parent) - v.lineSize(left) - v.lineSize(right)
139 delete(v.nodes, left)
140 delete(v.nodes, right)
141
142 v.lines[best] = parent
143 v.lines = append(v.lines[:best+1], v.lines[best+2:]...)
144 merged = true
145 }
146
147 v.merging = false
148
149 return merged, nil
150 }
151
152 // Size returns the sum of the line sizes.
153 func (v *View) Size() int {
154 size := 0
155 for _, line := range v.lines {
156 size += v.lineSize(line)
157 }
158
159 return size
160 }
161
162 // mostDue returns the position of the left line of the most due sibling pair
163 // whose parent is built, or -1 when there is no such pair.
164 func (v *View) mostDue(tree ViewNodeReader) (int, error) {
165 best := -1
166 bestDue := 0.0
167 for n := 0; n+1 < len(v.lines); n++ {
168 left, right := v.lines[n], v.lines[n+1]
169 if left.index%2 != 0 || right.level != left.level || right.index != left.index+1 {
170 continue
171 }
172
173 last := nodeEnd(right.level, right.index) - 1
174 due := math.Ldexp(float64(v.end-last), -left.level)
175 if best >= 0 && due <= bestDue {
176 continue
177 }
178
179 built, err := tree.Built(left.level+1, left.index/2)
180 if err != nil {
181 return -1, fmt.Errorf("check parent node: %w", err)
182 }
183
184 if built {
185 best = n
186 bestDue = due
187 }
188 }
189
190 return best, nil
191 }
192
193 // lineSize returns the size of a view line.
194 func (v *View) lineSize(line NodeKey) int {
195 node, built := v.nodes[line]
196 if !built {
197 return len(viewPending)
198 }
199
200 return node.Size
201 }
202
203 // Coarsen takes each merge of other, a view of the same messages, and then
204 // merges in one batch until the size is at most low. Each line of the result is
205 // the coarser of the two lines that start at its first message. Dyadic ranges
206 // either nest or do not overlap, so the result covers the messages without a
207 // gap.
208 func (v *View) Coarsen(other *View, tree ViewNodeReader) error {
209 lines := make([]NodeKey, 0, len(v.lines))
210 nodes := make(map[NodeKey]Node, len(v.nodes))
211 mine, theirs := 0, 0
212 for start := 0; start < v.end; {
213 line := v.lines[mine]
214 node, built := v.nodes[line]
215 if other.lines[theirs].level > line.level {
216 line = other.lines[theirs]
217 node, built = other.nodes[line]
218 }
219
220 lines = append(lines, line)
221 if built {
222 nodes[line] = node
223 }
224
225 start = nodeEnd(line.level, line.index)
226 for mine < len(v.lines) && v.lines[mine].index<<v.lines[mine].level < start {
227 mine++
228 }
229
230 for theirs < len(other.lines) && other.lines[theirs].index<<other.lines[theirs].level < start {
231 theirs++
232 }
233 }
234
235 v.lines = lines
236 v.nodes = nodes
237 v.merging = true
238 _, err := v.fit(tree)
239
240 return err
241 }
242
243 // Refresh keeps node when it is the node of a pending line.
244 func (v *View) Refresh(node Node) {
245 key := NodeKey{node.Level, node.Index}
246 for n := len(v.lines) - 1; n >= 0; n-- {
247 line := v.lines[n]
248 if line == key {
249 v.nodes[key] = node
250 return
251 }
252
253 if line.index<<line.level <= key.index<<key.level {
254 return
255 }
256 }
257 }
258
259 // Pending tells if a line of the view is not built yet.
260 func (v *View) Pending() bool {
261 for _, line := range v.lines {
262 _, built := v.nodes[line]
263 if !built {
264 return true
265 }
266 }
267
268 return false
269 }
270
271 // Render returns the view as the model reads it: one line "id+n|text" for each
272 // node inside <chat> tags, with the newlines of the text as spaces.
273 func (v *View) Render() string {
274 return "<chat>\n" + strings.Join(v.LinesWithout(nil), "") + "</chat>"
275 }
276
277 // LinesWithout returns the lines of the view as the model reads them, each with
278 // its newline, without the leaf lines of the messages in skip. A line that
279 // merges such a message with others stays.
280 func (v *View) LinesWithout(skip map[int]bool) []string {
281 lines := make([]string, 0, len(v.lines))
282 for _, line := range v.lines {
283 if line.level == 0 && skip[line.index] {
284 continue
285 }
286
287 var text strings.Builder
288
289 v.renderLine(&text, line)
290
291 lines = append(lines, text.String())
292 }
293
294 return lines
295 }
296
297 // renderLine writes one view line, "id+n|text", and a newline.
298 func (v *View) renderLine(text *strings.Builder, line NodeKey) {
299 body := viewPending
300 node, built := v.nodes[line]
301 if built {
302 body = strings.ReplaceAll(node.Text, "\n", " ")
303 }
304
305 text.WriteString(strconv.Itoa(line.index << line.level))
306 text.WriteByte('+')
307 text.WriteString(strconv.Itoa(1 << line.level))
308 text.WriteByte('|')
309 text.WriteString(body)
310 text.WriteByte('\n')
311 }
312
313 // Context returns the lines of the view before message end as the model reads
314 // them. It stops at the first line that is not built, so a compaction never
315 // sees a pending mark or a part of a message.
316 func (v *View) Context(end int) string {
317 var text strings.Builder
318
319 text.WriteString("<chat>\n")
320
321 for _, line := range v.lines {
322 _, built := v.nodes[line]
323 if !built || nodeEnd(line.level, line.index) > end {
324 break
325 }
326
327 v.renderLine(&text, line)
328 }
329
330 text.WriteString("</chat>")
331
332 return text.String()
333 }
334
335 // restoreView returns the view of state with the limits high and low. Each line
336 // must continue the one before it, and each line above level 0 must be built.
337 func restoreView(state ViewState, high, low int, tree ViewNodeReader) (*View, error) {
338 v := newView(high, low)
339 v.merging = state.Merging
340 for _, pair := range state.Lines {
341 line := NodeKey{pair[0], pair[1]}
342 if line.level < 0 || line.level >= bits.UintSize-2 || line.index < 0 || line.index<<line.level != v.end {
343 return nil, fmt.Errorf("view line (%d, %d) does not start at message %d", line.level, line.index, v.end)
344 }
345
346 built, err := v.load(tree, line)
347 if err != nil {
348 return nil, fmt.Errorf("load restored view node: %w", err)
349 }
350
351 if line.level > 0 && !built {
352 return nil, fmt.Errorf("view line (%d, %d) is not built", line.level, line.index)
353 }
354
355 v.lines = append(v.lines, line)
356 v.end = nodeEnd(line.level, line.index)
357 }
358
359 return v, nil
360 }