aboutsummaryrefslogtreecommitdiff
path: root/refstore/reftable/lookup.go
blob: 24f9adb597327f9142b3b688a77ae5ad2538606d (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package reftable

import (
	"encoding/binary"
	"fmt"
	"strings"

	"codeberg.org/lindenii/furgit/objectid"
)

// resolveRecord resolves one ref name inside a single table file.
func (table *tableFile) resolveRecord(name string) (recordValue, bool, error) {
	if table.refIndexPos != 0 {
		pos, ok, err := table.resolveRefBlockPosFromIndex(name, int(table.refIndexPos))
		if err != nil {
			return recordValue{}, false, err
		}
		if !ok {
			return recordValue{}, false, nil
		}
		return table.lookupInRefBlock(name, pos)
	}

	// Without a ref index, fall back to scanning ref blocks in order.
	pos := table.headerLen
	for pos < table.refEnd {
		for pos < table.refEnd && table.data[pos] == 0 {
			pos++
		}
		if pos >= table.refEnd {
			break
		}
		if table.data[pos] != blockTypeRef {
			return recordValue{}, false, fmt.Errorf("refstore/reftable: table %q: unexpected block type %q in ref section", table.name, table.data[pos])
		}
		block, blockEnd, err := table.readBlockAt(pos)
		if err != nil {
			return recordValue{}, false, err
		}
		found, done, rec, err := lookupRecordInRefBlock(table, block, name)
		if err != nil {
			return recordValue{}, false, err
		}
		if found {
			return rec, true, nil
		}
		if done {
			return recordValue{}, false, nil
		}
		pos = table.nextBlockPos(blockEnd)
	}
	return recordValue{}, false, nil
}

// resolveRefBlockPosFromIndex resolves a candidate ref block position via index blocks.
func (table *tableFile) resolveRefBlockPosFromIndex(name string, indexPos int) (int, bool, error) {
	block, _, err := table.readBlockAt(indexPos)
	if err != nil {
		return 0, false, err
	}
	if block.blockType != blockTypeIndex {
		return 0, false, fmt.Errorf("refstore/reftable: table %q: ref index root is not index block", table.name)
	}
	childPos, ok, err := lookupChildPosInIndexBlock(block, name)
	if err != nil {
		return 0, false, err
	}
	if !ok {
		return 0, false, nil
	}
	if childPos < 0 || childPos >= len(table.data) {
		return 0, false, fmt.Errorf("refstore/reftable: table %q: index child position out of range", table.name)
	}

	childType := table.data[childPos]
	switch childType {
	case blockTypeRef:
		return childPos, true, nil
	case blockTypeIndex:
		return table.resolveRefBlockPosFromIndex(name, childPos)
	default:
		return 0, false, fmt.Errorf("refstore/reftable: table %q: unexpected child block type %q", table.name, childType)
	}
}

// lookupInRefBlock searches one ref block by full ref name.
func (table *tableFile) lookupInRefBlock(name string, pos int) (recordValue, bool, error) {
	block, _, err := table.readBlockAt(pos)
	if err != nil {
		return recordValue{}, false, err
	}
	if block.blockType != blockTypeRef {
		return recordValue{}, false, fmt.Errorf("refstore/reftable: table %q: expected ref block at %d", table.name, pos)
	}
	found, _, rec, err := lookupRecordInRefBlock(table, block, name)
	if err != nil {
		return recordValue{}, false, err
	}
	return rec, found, nil
}

// forEachRecord iterates all ref records in this table in lexical order.
func (table *tableFile) forEachRecord(fn func(name string, rec recordValue) error) error {
	pos := table.headerLen
	prevLast := ""
	for pos < table.refEnd {
		for pos < table.refEnd && table.data[pos] == 0 {
			pos++
		}
		if pos >= table.refEnd {
			break
		}
		if table.data[pos] != blockTypeRef {
			return fmt.Errorf("refstore/reftable: table %q: unexpected block type %q in ref section", table.name, table.data[pos])
		}

		block, blockEnd, err := table.readBlockAt(pos)
		if err != nil {
			return err
		}
		var first, last string
		err = forEachRecordInRefBlock(table, block, func(name string, rec recordValue) error {
			if first == "" {
				first = name
			}
			last = name
			return fn(name, rec)
		})
		if err != nil {
			return err
		}
		if prevLast != "" && first != "" && strings.Compare(first, prevLast) <= 0 {
			return fmt.Errorf("refstore/reftable: table %q: ref blocks are not strictly ordered", table.name)
		}
		if last != "" {
			prevLast = last
		}
		pos = table.nextBlockPos(blockEnd)
	}
	return nil
}

// blockView is one decoded block boundary within the mapped table bytes.
type blockView struct {
	blockType byte
	start     int
	end       int
	first     bool
	payload   []byte
}

// readBlockAt validates and returns a block view starting at pos.
func (table *tableFile) readBlockAt(pos int) (blockView, int, error) {
	if pos < 0 || pos+4 > len(table.data) {
		return blockView{}, 0, fmt.Errorf("refstore/reftable: table %q: block header out of range", table.name)
	}
	blockLen := int(readUint24(table.data[pos+1 : pos+4]))
	effectiveLen := blockLen
	if pos == table.headerLen {
		if blockLen < table.headerLen {
			return blockView{}, 0, fmt.Errorf("refstore/reftable: table %q: invalid first block length", table.name)
		}
		effectiveLen = blockLen - table.headerLen
	}
	if effectiveLen < 4 {
		return blockView{}, 0, fmt.Errorf("refstore/reftable: table %q: invalid block length", table.name)
	}
	end := pos + effectiveLen
	if end > len(table.data) {
		return blockView{}, 0, fmt.Errorf("refstore/reftable: table %q: block out of range", table.name)
	}
	view := blockView{blockType: table.data[pos], start: pos, end: end, first: pos == table.headerLen, payload: table.data[pos:end]}
	return view, end, nil
}

// nextBlockPos computes the next block start from current block end.
func (table *tableFile) nextBlockPos(blockEnd int) int {
	if table.blockSize > 0 {
		return alignUp(blockEnd, table.blockSize)
	}
	return blockEnd
}

// lookupChildPosInIndexBlock selects a child block position for key.
func lookupChildPosInIndexBlock(block blockView, key string) (int, bool, error) {
	off, recordsEnd, restarts, err := parseBlockLayout(block)
	if err != nil {
		return 0, false, err
	}
	if err := validateRestarts(block, restarts, off, recordsEnd, true); err != nil {
		return 0, false, err
	}
	prev := ""
	for off < recordsEnd {
		name, v, nextOff, err := parseKeyedRecord(block.payload, off, recordsEnd, prev)
		if err != nil {
			return 0, false, err
		}
		if (v & 0x7) != 0 {
			return 0, false, fmt.Errorf("index value_type must be 0")
		}
		childPos, nextOff, err := readVarint(block.payload, nextOff, recordsEnd)
		if err != nil {
			return 0, false, err
		}
		if strings.Compare(key, name) <= 0 {
			if childPos > uint64(int(^uint(0)>>1)) {
				return 0, false, fmt.Errorf("index child position overflows int")
			}
			return int(childPos), true, nil
		}
		prev = name
		off = nextOff
	}
	if off != recordsEnd {
		return 0, false, fmt.Errorf("malformed index block")
	}
	return 0, false, nil
}

// lookupRecordInRefBlock searches one ref block and may short-circuit by sort order.
func lookupRecordInRefBlock(table *tableFile, block blockView, key string) (found bool, done bool, rec recordValue, err error) {
	off, recordsEnd, restarts, err := parseBlockLayout(block)
	if err != nil {
		return false, false, recordValue{}, err
	}
	if err := validateRestarts(block, restarts, off, recordsEnd, true); err != nil {
		return false, false, recordValue{}, err
	}
	prev := ""
	for off < recordsEnd {
		name, v, nextOff, err := parseKeyedRecord(block.payload, off, recordsEnd, prev)
		if err != nil {
			return false, false, recordValue{}, err
		}
		typeBits := byte(v & 0x7)
		_, nextOff, err = readVarint(block.payload, nextOff, recordsEnd)
		if err != nil {
			return false, false, recordValue{}, err
		}
		recVal, nextOff, err := parseRefValue(block.payload, nextOff, recordsEnd, table.algo, typeBits)
		if err != nil {
			return false, false, recordValue{}, err
		}
		cmp := strings.Compare(name, key)
		if cmp == 0 {
			return true, true, recVal, nil
		}
		if cmp > 0 {
			return false, true, recordValue{}, nil
		}
		prev = name
		off = nextOff
	}
	if off != recordsEnd {
		return false, false, recordValue{}, fmt.Errorf("malformed ref block")
	}
	return false, false, recordValue{}, nil
}

// forEachRecordInRefBlock iterates all records in one ref block.
func forEachRecordInRefBlock(table *tableFile, block blockView, fn func(name string, rec recordValue) error) error {
	off, recordsEnd, restarts, err := parseBlockLayout(block)
	if err != nil {
		return err
	}
	if err := validateRestarts(block, restarts, off, recordsEnd, true); err != nil {
		return err
	}
	prev := ""
	for off < recordsEnd {
		name, v, nextOff, err := parseKeyedRecord(block.payload, off, recordsEnd, prev)
		if err != nil {
			return err
		}
		typeBits := byte(v & 0x7)
		_, nextOff, err = readVarint(block.payload, nextOff, recordsEnd)
		if err != nil {
			return err
		}
		recVal, nextOff, err := parseRefValue(block.payload, nextOff, recordsEnd, table.algo, typeBits)
		if err != nil {
			return err
		}
		if err := fn(name, recVal); err != nil {
			return err
		}
		prev = name
		off = nextOff
	}
	if off != recordsEnd {
		return fmt.Errorf("malformed ref block")
	}
	return nil
}

// parseBlockLayout parses common record/restart regions for ref and index blocks.
func parseBlockLayout(block blockView) (recordsStart int, recordsEnd int, restarts []int, err error) {
	if len(block.payload) < 6 {
		return 0, 0, nil, fmt.Errorf("short block")
	}
	restartCount := int(binary.BigEndian.Uint16(block.payload[len(block.payload)-2:]))
	if restartCount <= 0 {
		return 0, 0, nil, fmt.Errorf("invalid restart count")
	}
	restarts = make([]int, restartCount)
	restartBytes := restartCount * 3
	restartsStart := len(block.payload) - 2 - restartBytes
	if restartsStart < 4 {
		return 0, 0, nil, fmt.Errorf("invalid restart table")
	}
	for i := 0; i < restartCount; i++ {
		off := restartsStart + i*3
		rel := int(readUint24(block.payload[off : off+3]))
		base := block.start
		if block.first {
			// In the first block, restart offsets are relative to file start.
			base = 0
		}
		abs := base + rel
		restarts[i] = abs - block.start
	}
	return 4, restartsStart, restarts, nil
}

// validateRestarts validates restart monotonicity, bounds and record-prefix invariants.
func validateRestarts(block blockView, restarts []int, recordsStart, recordsEnd int, requirePrefixZero bool) error {
	prev := -1
	for _, off := range restarts {
		if off < recordsStart || off >= recordsEnd {
			return fmt.Errorf("restart offset out of range")
		}
		if off <= prev {
			return fmt.Errorf("restart offsets not strictly increasing")
		}
		prev = off
		if requirePrefixZero {
			prefix, _, err := readVarint(block.payload, off, recordsEnd)
			if err != nil {
				return err
			}
			if prefix != 0 {
				return fmt.Errorf("restart record prefix length must be zero")
			}
		}
	}
	return nil
}

// parseKeyedRecord parses one prefix-compressed key record header.
func parseKeyedRecord(buf []byte, off, end int, prev string) (name string, rawType uint64, next int, err error) {
	prefixLen, next, err := readVarint(buf, off, end)
	if err != nil {
		return "", 0, 0, err
	}
	suffixAndType, next, err := readVarint(buf, next, end)
	if err != nil {
		return "", 0, 0, err
	}
	suffixLen := int(suffixAndType >> 3)
	if suffixLen < 0 || next+suffixLen > end {
		return "", 0, 0, fmt.Errorf("invalid suffix length")
	}
	if int(prefixLen) > len(prev) {
		return "", 0, 0, fmt.Errorf("invalid prefix length")
	}
	name = prev[:prefixLen] + string(buf[next:next+suffixLen])
	next += suffixLen
	if prev != "" && strings.Compare(name, prev) <= 0 {
		return "", 0, 0, fmt.Errorf("keys not strictly increasing")
	}
	return name, suffixAndType, next, nil
}

// parseRefValue parses one ref-record value payload according to value_type.
func parseRefValue(buf []byte, off, end int, algo objectid.Algorithm, valueType byte) (recordValue, int, error) {
	switch valueType {
	case 0x0:
		return recordValue{deleted: true}, off, nil
	case 0x1:
		id, next, err := readObjectID(buf, off, end, algo)
		if err != nil {
			return recordValue{}, 0, err
		}
		return recordValue{detachedID: id, hasDetached: true}, next, nil
	case 0x2:
		id, next, err := readObjectID(buf, off, end, algo)
		if err != nil {
			return recordValue{}, 0, err
		}
		peeled, next, err := readObjectID(buf, next, end, algo)
		if err != nil {
			return recordValue{}, 0, err
		}
		peeledCopy := peeled
		return recordValue{detachedID: id, hasDetached: true, peeled: &peeledCopy}, next, nil
	case 0x3:
		targetLen, next, err := readVarint(buf, off, end)
		if err != nil {
			return recordValue{}, 0, err
		}
		if targetLen > uint64(end-next) {
			return recordValue{}, 0, fmt.Errorf("invalid symref target length")
		}
		target := string(buf[next : next+int(targetLen)])
		next += int(targetLen)
		return recordValue{symbolicTarget: target}, next, nil
	default:
		return recordValue{}, 0, fmt.Errorf("unsupported ref value type %d", valueType)
	}
}

// readObjectID reads one object ID using the table algorithm width.
func readObjectID(buf []byte, off, end int, algo objectid.Algorithm) (objectid.ObjectID, int, error) {
	sz := algo.Size()
	if off < 0 || sz < 0 || off+sz > end {
		return objectid.ObjectID{}, 0, fmt.Errorf("truncated object id")
	}
	id, err := objectid.FromBytes(algo, buf[off:off+sz])
	if err != nil {
		return objectid.ObjectID{}, 0, err
	}
	return id, off + sz, nil
}