Files
qb/database/metric.go

401 lines
9.3 KiB
Go
Raw Normal View History

2026-02-10 14:02:11 +00:00
package database
import (
2026-06-09 08:16:16 +03:00
"io"
bin "gordenko.dev/dima/bin/little"
2026-05-14 16:06:37 +03:00
"gordenko.dev/dima/qb"
2026-06-10 06:18:45 +03:00
"gordenko.dev/dima/qb/storage"
2026-02-10 14:02:11 +00:00
)
// METRIC
2026-06-07 21:27:18 +03:00
const minBufferSize = 1024
2026-06-09 08:16:16 +03:00
var (
indexRecordSize = 8
)
2026-05-31 20:01:28 +00:00
2026-02-10 14:02:11 +00:00
type _metric struct {
2026-06-09 08:16:16 +03:00
metricType qb.MetricType
fracDigits byte
lastPageNo uint32
//SinceValue float64
//Since uint32
lastValue float64
//Until uint32
buffer []byte
timestamps qb.TimestampCompressor
values qb.ValueCompressor
2026-06-05 19:43:01 +00:00
XLock bool
RLocks int
WaitQueue []any
2026-06-10 06:18:45 +03:00
indexLevelTails []storage.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
2026-06-10 06:18:45 +03:00
// func (s *_metric) startAppendMeasures(req tryAppendMeasuresReq, sendToStorage func(storage.AppendedMeasures)) {
2026-06-11 14:27:38 +00:00
func (s *_metric) StartAppendMeasures(req tryAppendMeasuresReq, tmp []byte, sendToStorage func(any)) {
2026-05-31 20:01:28 +00:00
var (
2026-06-09 08:16:16 +03:00
timestamps = s.timestamps
values = s.values
2026-05-31 20:01:28 +00:00
2026-06-10 06:18:45 +03:00
dataPages []storage.DataPayload
2026-05-31 20:01:28 +00:00
2026-06-11 14:27:38 +00:00
// офсети на head сторінці
timestampsOffset int
valuesOffset int
2026-05-31 20:01:28 +00:00
//written int
//resultCode byte
)
2026-06-09 08:16:16 +03:00
s.values.CaptureState()
s.timestamps.CaptureState()
2026-05-31 20:01:28 +00:00
for idx, measure := range req.Measures {
2026-06-09 08:16:16 +03:00
// FIX - у випадку помилки треба в транзакції зберегти що помилка, але також зафіксувати скільки елементів збережено.
2026-06-10 06:18:45 +03:00
// якщо idx == 0 - одразу знімаю блокування і нічого не відправляю в storage
2026-06-09 08:16:16 +03:00
if measure.Timestamp <= s.timestamps.LastTimestamp() {
if idx == 0 {
s.values.ForgetCapturedState()
s.timestamps.ForgetCapturedState()
req.ResultCh <- tryAppendMeasuresResult{
ResultCode: ExpiredMeasure,
2026-05-31 20:01:28 +00:00
}
2026-06-09 08:16:16 +03:00
return
2026-05-31 20:01:28 +00:00
}
2026-06-09 08:16:16 +03:00
//resultCode = ExpiredMeasure
//written = idx
break
}
if s.metricType == qb.Cumulative && measure.Value < s.lastValue {
if idx == 0 {
s.values.ForgetCapturedState()
s.timestamps.ForgetCapturedState()
2026-05-31 20:01:28 +00:00
2026-06-09 08:16:16 +03:00
req.ResultCh <- tryAppendMeasuresResult{
ResultCode: NonMonotonicValue,
2026-05-31 20:01:28 +00:00
}
2026-06-09 08:16:16 +03:00
return
2026-05-31 20:01:28 +00:00
}
2026-06-09 08:16:16 +03:00
//resultCode = NonMonotonicValue
//written = idx
break
2026-05-31 20:01:28 +00:00
}
2026-06-09 08:16:16 +03:00
//}
2026-05-31 20:01:28 +00:00
// fix - 1 + 8 bytes
2026-06-11 14:27:38 +00:00
tReport := timestamps.Evaluate(tmp, measure.Timestamp)
vReport := values.Evaluate(tmp, measure.Value)
2026-06-07 21:27:18 +03:00
2026-06-11 14:27:38 +00:00
totalRequiredSpace := tReport.TotalSpace + vReport.TotalSpace
2026-05-31 20:01:28 +00:00
2026-06-09 08:16:16 +03:00
if totalRequiredSpace <= len(s.buffer) {
2026-06-11 14:27:38 +00:00
// якщо на сторінці є місце
if idx == 0 {
timestampsOffset = tReport.Offset
valuesOffset = vReport.Offset
}
2026-05-31 20:01:28 +00:00
} else {
2026-06-11 14:27:38 +00:00
if len(s.buffer) < storage.DataPageSize {
// allocate bigger buffer
buf, databuf := growBuffers(growBuffersIn{
databuf: s.buffer,
tSize: timestamps.Size(),
vSize: values.Size(),
requiredSpace: totalRequiredSpace,
})
s.buffer = buf
// replace buffer in timestamps and values
timestamps.Rotate(databuf) // fix pos
values.Rotate(databuf) // fix pos
} else {
// сторінка заповнена
since := s.timestamps.ReplaceSinceWithUntil()
if len(dataPages) == 0 {
// head page FIX
// timestampsPayload =
// valuesPayload =
}
2026-06-09 08:16:16 +03:00
2026-06-11 14:27:38 +00:00
dataPages = append(dataPages, storage.DataPayload{
Since: since,
Content: s.buffer,
TimestampsSize: timestamps.Size(),
ValuesSize: values.Size(),
})
2026-06-09 08:16:16 +03:00
2026-06-11 14:27:38 +00:00
buffer := make([]byte, minBufferSize)
2026-05-31 20:01:28 +00:00
2026-06-11 14:27:38 +00:00
timestamps.Rotate(buffer)
values.Rotate(buffer)
2026-06-07 21:27:18 +03:00
2026-06-11 14:27:38 +00:00
// renew
s.buffer = buffer
}
2026-05-31 20:01:28 +00:00
}
2026-06-11 14:27:38 +00:00
timestamps.Append(tReport.Offset, tmp[:tReport.ChangeSize], measure.Timestamp)
values.Append(vReport.Offset, tmp[7:7+vReport.ChangeSize], measure.Value, vReport.Delta)
2026-06-09 08:16:16 +03:00
//
s.lastValue = measure.Value
2026-05-31 20:01:28 +00:00
}
// виділити змінені байти.
// скопіювати. Причому можна скопіювати зрізи chunks
if len(dataPages) > 0 {
2026-06-10 06:18:45 +03:00
// пишу в storage довгим шляхом через redo файл і запис в data файл
sendToStorage(storage.AppendedMeasures{
2026-06-05 19:43:01 +00:00
MetricID: req.MetricID,
2026-06-09 08:16:16 +03:00
LastPageNo: s.lastPageNo,
2026-06-11 14:27:38 +00:00
TimestampsOffset: timestampsOffset,
ValuesOffset: valuesOffset,
2026-06-05 19:43:01 +00:00
//Payload: s.payload, // fix - timestamps + values ? or timestamps and values (for WAL)
2026-06-09 08:16:16 +03:00
IndexLevelTails: s.indexLevelTails,
2026-06-05 19:43:01 +00:00
DataPages: dataPages,
Timestamps: nil,
Values: nil,
//ResultCode: resultCode,
//WrittenCount: wri,
ResultCh: nil,
})
2026-05-31 20:01:28 +00:00
} else {
2026-06-10 06:18:45 +03:00
// короткий шлях - запис лише в storage
2026-06-11 14:27:38 +00:00
sendToStorage(storage.AppendedMeasures{
MetricID: req.MetricID,
TimestampsOffset: timestampsOffset,
ValuesOffset: valuesOffset,
Timestamps: nil, // pos - offset
Values: nil,
//ResultCode: resultCode,
//WrittenCount: wri,
ResultCh: nil,
})
2026-05-31 20:01:28 +00:00
}
}
2026-06-10 06:18:45 +03:00
func (s *_metric) FinAppendMeasures(rec storage.AppendMeasuresSummary) {
2026-05-31 20:01:28 +00:00
// Видаляю state. Оригінальні Timestamps і Values вже мають останню версію
2026-06-09 08:16:16 +03:00
s.values.ForgetCapturedState()
s.timestamps.ForgetCapturedState()
2026-05-31 20:01:28 +00:00
if rec.LastPageNo > 0 {
2026-06-09 08:16:16 +03:00
s.lastPageNo = rec.LastPageNo
2026-05-31 20:01:28 +00:00
}
2026-06-10 06:18:45 +03:00
// В storage я передав повний індекс. У нього додали елементи (можливо нові рівні).
2026-05-31 20:01:28 +00:00
// Тому проста заміна
2026-06-09 08:16:16 +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) {
2026-06-09 08:16:16 +03:00
// if s.Since == 0 {
// req.ResultCh <- fullScanResult{
// ResultCode: QueryDone,
// }
// return
// }
2026-05-31 20:01:28 +00:00
2026-06-09 08:16:16 +03:00
// timestampDecompressor := s.Timestamps.CreateDecompressor()
// valueDecompressor := s.Values.CreateDecompressor()
2026-05-31 20:01:28 +00:00
2026-06-09 08:16:16 +03:00
// 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,
// }
// }
}
2026-05-31 20:01:28 +00:00
2026-06-09 08:16:16 +03:00
// індекси
// Metric encode format:
// metricID - 4b
// metricType - 1b
// fracDigits - 1b
// lastPageNo - 4b
// timestamps size - 2b
// values size - 2b
2026-06-09 16:42:17 +00:00
// timestams payload - Nb
2026-06-09 08:16:16 +03:00
// values payload - Nb
// index levels count - varsize
// [
// records qty - varsize
// records - Nb
// ]
func (s *_metric) WriteTo(w io.Writer) (err error) {
_, err = w.Write([]byte{
byte(s.metricType),
s.fracDigits,
})
if err != nil {
return
}
err = bin.WriteUint32(w, s.lastPageNo)
if err != nil {
return
}
2026-06-09 16:42:17 +00:00
err = bin.WriteUint16(w, uint16(s.timestamps.Size()))
2026-06-09 08:16:16 +03:00
if err != nil {
return
}
2026-06-09 16:42:17 +00:00
err = bin.WriteUint16(w, uint16(s.values.Size()))
if err != nil {
return
}
// timestamps payload
2026-06-09 08:16:16 +03:00
err = s.timestamps.WritePayloadTo(w)
if err != nil {
return
}
2026-06-09 16:42:17 +00:00
// values payload
2026-06-09 08:16:16 +03:00
err = s.values.WritePayloadTo(w)
if err != nil {
return
}
// indexes
_, err = bin.WriteVarSize(w, len(s.indexLevelTails))
if err != nil {
return
}
for _, level := range s.indexLevelTails {
_, err = bin.WriteVarSize(w, level.RecordsCount)
if err != nil {
return
2026-05-31 20:01:28 +00:00
}
2026-06-09 08:16:16 +03:00
_, err = w.Write(level.Buffer)
if err != nil {
return
2026-05-31 20:01:28 +00:00
}
}
2026-06-09 08:16:16 +03:00
return
2026-05-31 20:01:28 +00:00
}
2026-06-09 08:16:16 +03:00
// since - 4b
// sinceValue - 8b -
// untilValue - 8b