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