Files
qb/database/metric.go

326 lines
8.4 KiB
Go
Raw Normal View History

2026-02-10 14:02:11 +00:00
package database
import (
2026-05-14 16:06:37 +03:00
"gordenko.dev/dima/qb"
2026-05-31 20:01:28 +00:00
"gordenko.dev/dima/qb/atree"
"gordenko.dev/dima/qb/txlog"
2026-02-10 14:02:11 +00:00
)
// METRIC
2026-06-07 21:27:18 +03:00
const minBufferSize = 1024
2026-06-05 19:43:01 +00:00
type IndexLevelTail struct {
Payload []byte
RecordsCount int
2026-05-31 20:01:28 +00:00
}
2026-02-10 14:02:11 +00:00
type _metric struct {
2026-06-05 19:43:01 +00:00
MetricType qb.MetricType
FracDigits byte
LastPageNo uint32
SinceValue float64
Since uint32
UntilValue float64
Until uint32
2026-06-07 21:27:18 +03:00
Buffer []byte
2026-06-05 19:43:01 +00:00
Timestamps qb.TimestampCompressor
Values qb.ValueCompressor
XLock bool
RLocks int
WaitQueue []any
2026-06-07 21:27:18 +03:00
IndexLevelTails []txlog.IndexLevelTail // root - last element
2026-02-10 14:02:11 +00:00
}
2026-06-05 19:43:01 +00:00
//IndexLevels [][]IndexRec // root - last element
2026-06-07 21:27:18 +03:00
// func (s *_metric) ReinitBy(timestamp uint32, value float64) {
// s.Timestamps.Renew()
// s.Values.Renew()
2026-02-10 14:02:11 +00:00
2026-06-07 21:27:18 +03:00
// s.Timestamps.Append(timestamp)
// s.Values.Append(value)
2026-02-10 14:02:11 +00:00
2026-06-07 21:27:18 +03:00
// s.Since = timestamp
// s.SinceValue = value
// s.Until = timestamp
// s.UntilValue = value
// }
2026-02-10 14:02:11 +00:00
func (s *_metric) DeleteMeasures() {
2026-06-07 21:27:18 +03:00
// s.Timestamps.Renew()
// s.Values.Renew()
// s.LastPageNo = 0
// s.Since = 0
// s.SinceValue = 0
// s.Until = 0
// s.UntilValue = 0
2026-02-10 14:02:11 +00:00
}
2026-05-31 20:01:28 +00:00
// func (s *_metric) startAppendMeasures(req tryAppendMeasuresReq, sendToStorage func(txlog.AppendedMeasures)) {
func (s *_metric) StartAppendMeasures(req tryAppendMeasuresReq, sendToStorage func(any)) {
var (
// AppendedMeasures struct {
// MetricID uint32
// TimestampsOffset int // (заповнені одразу)
// ValuesOffset int // (заповнені одразу)
// Timestamps [][]byte
// TimestampsSize int
// Values [][]byte
// ValuesSize int
// IndexLevels []*atree.IndexLevel
// DataPages []*atree.DataPage // fix - prevPageNo for the 1st data page
// }
timestamps = s.Timestamps
values = s.Values
2026-06-07 21:27:18 +03:00
indexLevels []txlog.IndexLevelTail
dataPages []txlog.DataPayload
2026-05-31 20:01:28 +00:00
//written int
//resultCode byte
)
2026-06-07 21:27:18 +03:00
s.Values.CaptureState()
s.Timestamps.CaptureState()
2026-05-31 20:01:28 +00:00
for idx, measure := range req.Measures {
if s.Since == 0 {
s.Since = measure.Timestamp
} else {
// FIX - у випадку помилки треба в транзакції зберегти що помилка, але також зафіксувати скільки елементів збережено.
// якщо idx == 0 - одразу знімаю блокування і нічого не відправляю в txlog
if measure.Timestamp <= s.Until {
if idx == 0 {
2026-06-07 21:27:18 +03:00
s.Values.ForgetCapturedState()
s.Timestamps.ForgetCapturedState()
2026-05-31 20:01:28 +00:00
req.ResultCh <- tryAppendMeasuresResult{
ResultCode: ExpiredMeasure,
}
return
}
//resultCode = ExpiredMeasure
//written = idx
break
}
if s.MetricType == qb.Cumulative && measure.Value < s.UntilValue {
if idx == 0 {
2026-06-07 21:27:18 +03:00
s.Values.ForgetCapturedState()
s.Timestamps.ForgetCapturedState()
2026-05-31 20:01:28 +00:00
req.ResultCh <- tryAppendMeasuresResult{
ResultCode: NonMonotonicValue,
}
return
}
//resultCode = NonMonotonicValue
//written = idx
break
}
}
// fix - 1 + 8 bytes
2026-06-07 21:27:18 +03:00
timestampCompressionWay, timestampRequiredSpace := timestamps.Evaluate(measure.Timestamp)
valueCompressionWay, valueRequiredSpace := values.Evaluate(measure.Value)
totalSpace := timestampRequiredSpace + valueRequiredSpace
2026-05-31 20:01:28 +00:00
if totalSpace <= atree.DataPagePayloadSize {
// накопичую
2026-06-07 21:27:18 +03:00
timestamps.Compress(timestampCompressionWay, measure.Timestamp)
values.Compress(valueCompressionWay, measure.Value)
2026-05-31 20:01:28 +00:00
} else {
// сторінка заповнена
2026-06-07 21:27:18 +03:00
buffer := make([]byte, minBufferSize)
timestampsSize := timestamps.Rotate(buffer)
valuesSize := values.Rotate(buffer)
2026-05-31 20:01:28 +00:00
// prevPageNo - виставляю в txlog, коли забираю номер сторінки із freeList або генерую новий
2026-06-07 21:27:18 +03:00
dataPages = append(dataPages, txlog.DataPayload{
2026-06-05 19:43:01 +00:00
Since: s.Since,
2026-06-07 21:27:18 +03:00
Content: s.Buffer,
TimestampsSize: timestampsSize,
ValuesSize: valuesSize,
2026-05-31 20:01:28 +00:00
})
2026-06-07 21:27:18 +03:00
// renew
s.Buffer = buffer
2026-05-31 20:01:28 +00:00
2026-06-07 21:27:18 +03:00
timestampCompressionWay, _ = timestamps.Evaluate(measure.Timestamp)
valueCompressionWay, _ = values.Evaluate(measure.Value)
timestamps.Compress(timestampCompressionWay, measure.Timestamp)
values.Compress(valueCompressionWay, measure.Value)
2026-05-31 20:01:28 +00:00
s.Since = measure.Timestamp
}
s.Until = measure.Timestamp
s.UntilValue = measure.Value
}
// виділити змінені байти.
// скопіювати. Причому можна скопіювати зрізи chunks
if len(dataPages) > 0 {
// пишу в txlog довгим шляхом через redo файл і запис в data файл
2026-06-05 19:43:01 +00:00
for _, tail := range s.IndexLevelTails {
2026-06-07 21:27:18 +03:00
indexLevels = append(indexLevels, txlog.IndexLevelTail{
Records: tail.Records,
2026-06-05 19:43:01 +00:00
RecordsCount: tail.RecordsCount,
2026-05-31 20:01:28 +00:00
})
}
2026-06-05 19:43:01 +00:00
sendToStorage(txlog.AppendedMeasures{
MetricID: req.MetricID,
LastPageNo: s.LastPageNo,
TimestampsOffset: timestamps.Offset(), // state.Pos() з якої позиції дописувати дані на сторінку 0 (при відновленні)
ValuesOffset: values.Offset(), // state.Pos()
//Payload: s.payload, // fix - timestamps + values ? or timestamps and values (for WAL)
IndexLevelTails: indexLevels,
DataPages: dataPages,
Timestamps: nil,
Values: nil,
//ResultCode: resultCode,
//WrittenCount: wri,
ResultCh: nil,
})
2026-05-31 20:01:28 +00:00
} else {
// короткий шлях - запис лише в txlog
}
}
func (s *_metric) FinAppendMeasures(rec txlog.AppendMeasuresSummary) {
// Видаляю state. Оригінальні Timestamps і Values вже мають останню версію
2026-06-07 21:27:18 +03:00
s.Values.ForgetCapturedState()
s.Timestamps.ForgetCapturedState()
2026-05-31 20:01:28 +00:00
// fix write index levels
// update prev pageNo
// if len(rec.DataPages) > 0 {
// s.LastPageNo = rec.DataPages[len(rec.DataPages)-1].PageNo
// }
if rec.LastPageNo > 0 {
s.LastPageNo = rec.LastPageNo
}
// В txlog я передав повний індекс. У нього додали елементи (можливо нові рівні).
// Тому проста заміна
2026-06-07 21:27:18 +03:00
s.IndexLevelTails = rec.Index
2026-05-31 20:01:28 +00:00
}
// READ
func (s *_metric) StartRangeScan(req tryRangeScanReq) {
2026-06-07 21:27:18 +03:00
// if s.Since == 0 {
// req.ResultCh <- rangeScanResult{
// ResultCode: QueryDone,
// }
// return
// }
2026-05-31 20:01:28 +00:00
2026-06-07 21:27:18 +03:00
// if req.Since > s.Until {
// req.ResultCh <- rangeScanResult{
// ResultCode: QueryDone,
// }
// return
// }
2026-05-31 20:01:28 +00:00
2026-06-07 21:27:18 +03:00
// if req.Until < s.Since {
// if s.RootPageNo > 0 {
// req.ResultCh <- rangeScanResult{
// ResultCode: UntilNotFound,
// RootPageNo: s.RootPageNo,
// FracDigits: s.FracDigits,
// }
// s.RLocks++
// return
// } else {
// req.ResultCh <- rangeScanResult{
// ResultCode: QueryDone,
// }
// return
// }
// }
2026-05-31 20:01:28 +00:00
2026-06-07 21:27:18 +03:00
// timestampDecompressor := s.Timestamps.CreateDecompressor()
// valueDecompressor := s.Values.CreateDecompressor(s.FracDigits)
// for {
// timestamp, done := timestampDecompressor.NextValue()
// if done {
// break
// }
// value, done := valueDecompressor.NextValue()
// if done {
// qb.Abort(qb.HasTimestampNoValueBug, ErrNoValueBug)
// }
// if timestamp <= req.Until {
// req.ResponseWriter.FeedNoSend(timestamp, value)
// if timestamp < req.Since {
// req.ResultCh <- rangeScanResult{
// ResultCode: QueryDone,
// }
// return
// }
// }
// }
2026-05-31 20:01:28 +00:00
2026-06-07 21:27:18 +03:00
// if s.LastPageNo > 0 {
// req.ResultCh <- rangeScanResult{
// ResultCode: UntilFound,
// LastPageNo: s.LastPageNo,
// FracDigits: s.FracDigits,
// }
// s.RLocks++
// } else {
// req.ResultCh <- rangeScanResult{
// ResultCode: QueryDone,
// }
// }
2026-05-31 20:01:28 +00:00
}
func (s *_metric) StartFullScan(req tryFullScanReq) {
if s.Since == 0 {
req.ResultCh <- fullScanResult{
ResultCode: QueryDone,
}
return
}
timestampDecompressor := s.Timestamps.CreateDecompressor()
valueDecompressor := s.Values.CreateDecompressor(s.FracDigits)
for {
timestamp, done := timestampDecompressor.NextValue()
if done {
break
}
value, done := valueDecompressor.NextValue()
if done {
qb.Abort(qb.HasTimestampNoValueBug, ErrNoValueBug)
}
req.ResponseWriter.FeedNoSend(timestamp, value)
}
if s.LastPageNo > 0 {
req.ResultCh <- fullScanResult{
ResultCode: UntilFound,
LastPageNo: s.LastPageNo,
FracDigits: s.FracDigits,
}
s.RLocks++
} else {
req.ResultCh <- fullScanResult{
ResultCode: QueryDone,
}
}
}