Files
qb/worker/metric.go

404 lines
9.8 KiB
Go
Raw Normal View History

2026-06-13 22:43:17 +00:00
package worker
2026-02-10 14:02:11 +00:00
import (
2026-06-13 22:43:17 +00:00
"errors"
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-14 07:57:01 +03:00
"gordenko.dev/dima/qb/inbox"
2026-06-10 06:18:45 +03:00
"gordenko.dev/dima/qb/storage"
2026-02-10 14:02:11 +00:00
)
// METRIC
2026-06-13 22:43:17 +00:00
var ErrNoValueBug = errors.New("has timestamp but no value")
2026-05-31 20:01:28 +00:00
2026-06-13 08:01:42 +03:00
type CapturedState struct {
LastTimestamp uint32
LastValue float64
}
2026-06-13 22:43:17 +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-06-12 00:29:02 +03:00
capturedState *CapturedState
2026-02-10 14:02:11 +00:00
}
2026-06-14 07:57:01 +03:00
func (s *Metric) MetricType() qb.MetricType {
return s.metricType
}
func (s *Metric) FracDigits() byte {
return s.fracDigits
}
2026-06-13 22:43:17 +00:00
func (s *Metric) LastValue() float64 {
2026-06-13 08:01:42 +03:00
if s.capturedState != nil {
return s.capturedState.LastValue
}
return s.lastValue
}
2026-02-10 14:02:11 +00:00
2026-06-13 22:43:17 +00:00
func (s *Metric) LastTimestamp() uint32 {
2026-06-13 08:01:42 +03:00
if s.capturedState != nil {
return s.capturedState.LastTimestamp
}
return s.timestamps.LastTimestamp()
}
2026-02-10 14:02:11 +00:00
2026-06-13 22:43:17 +00:00
func (s *Metric) OnMeasuresDeleteCommited(rec storage.MeasuresDeleteCommited) {
2026-06-13 07:13:03 +00:00
//s.timestamps.Reset()
//s.values.Reset()
s.XLock = false
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
2026-06-13 07:13:03 +00:00
s.indexLevelTails = nil
s.lastPageNo = 0
s.lastValue = 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-14 07:57:01 +03:00
func (s *Metric) StartAppendMeasures(req AppendMeasuresReq, tmp []byte, storageInbox *inbox.Inbox) {
2026-06-12 00:29:02 +03:00
if s.capturedState != nil {
s.WaitQueue = append(s.WaitQueue, req)
}
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-11 14:27:38 +00:00
// офсети на head сторінці
2026-06-12 14:21:14 +00:00
timestampsOffset int
timestampsRewindOffset int
valuesOffset int
valuesRewindOffset int
2026-06-11 14:27:38 +00:00
2026-06-12 06:11:57 +00:00
headTimestamps []byte
headValues []byte
2026-06-12 14:21:14 +00:00
pages []storage.DataPayload
2026-06-12 00:29:02 +03:00
written int
resultCode byte
2026-05-31 20:01:28 +00:00
)
2026-06-12 00:29:02 +03:00
s.capturedState = &CapturedState{
2026-06-12 14:21:14 +00:00
LastTimestamp: timestamps.LastTimestamp(),
LastValue: s.lastValue,
2026-06-12 00:29:02 +03:00
}
2026-05-31 20:01:28 +00:00
2026-06-12 06:11:57 +00:00
s.timestamps.CaptureState()
s.values.CaptureState()
2026-05-31 20:01:28 +00:00
for idx, measure := range req.Measures {
2026-06-09 08:16:16 +03:00
if measure.Timestamp <= s.timestamps.LastTimestamp() {
2026-06-12 00:29:02 +03:00
resultCode = ExpiredMeasure
2026-06-09 08:16:16 +03:00
break
}
if s.metricType == qb.Cumulative && measure.Value < s.lastValue {
2026-06-12 00:29:02 +03:00
resultCode = NonMonotonicValue
2026-06-09 08:16:16 +03:00
break
2026-05-31 20:01:28 +00:00
}
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
// якщо на сторінці є місце
2026-06-12 14:21:14 +00:00
timestamps.Append(tReport.RewindOffset, tmp[:tReport.ChangeSize], measure.Timestamp)
values.Append(vReport.RewindOffset, tmp[7:7+vReport.ChangeSize], measure.Value, vReport.Delta)
2026-06-11 14:27:38 +00:00
if idx == 0 {
timestampsOffset = tReport.Offset
2026-06-12 14:21:14 +00:00
timestampsRewindOffset = tReport.RewindOffset
2026-06-11 14:27:38 +00:00
valuesOffset = vReport.Offset
2026-06-12 14:21:14 +00:00
valuesRewindOffset = vReport.RewindOffset
2026-06-11 14:27:38 +00:00
}
2026-05-31 20:01:28 +00:00
} else {
2026-06-12 06:11:57 +00:00
// сторінка заповнена
since := s.timestamps.ReplaceSinceWithUntil()
2026-06-13 08:01:42 +03:00
if len(pages) == 0 && idx > 0 {
// idx > 0 required because page may overflows without append any data
2026-06-12 06:11:57 +00:00
headTimestamps = timestamps.Tail(timestampsOffset)
headValues = values.Tail(valuesOffset)
2026-06-11 14:27:38 +00:00
}
2026-06-12 06:11:57 +00:00
2026-06-12 14:21:14 +00:00
pages = append(pages, storage.DataPayload{
2026-06-12 06:11:57 +00:00
Since: since,
Content: s.buffer,
TimestampsSize: timestamps.Size(),
ValuesSize: values.Size(),
})
buf := make([]byte, storage.DataPageSize)
databuf := buf[:storage.DataPagePayloadSize]
timestamps.ReplaceBuffer(databuf)
values.ReplaceBuffer(databuf)
// renew
s.buffer = buf
2026-06-12 14:21:14 +00:00
timestamps.Append(tReport.RewindOffset, tmp[:tReport.ChangeSize], measure.Timestamp)
values.Append(vReport.RewindOffset, tmp[7:7+vReport.ChangeSize], measure.Value, vReport.Delta)
2026-05-31 20:01:28 +00:00
}
2026-06-09 08:16:16 +03:00
//
s.lastValue = measure.Value
2026-06-12 00:29:02 +03:00
written++
}
if written == 0 {
s.capturedState = nil
2026-06-13 22:43:17 +00:00
req.ResultCh <- AppendMeasuresResult{
2026-06-12 00:29:02 +03:00
ResultCode: resultCode,
}
return
2026-05-31 20:01:28 +00:00
}
// виділити змінені байти.
// скопіювати. Причому можна скопіювати зрізи chunks
2026-06-12 14:21:14 +00:00
if len(pages) > 0 {
2026-06-10 06:18:45 +03:00
// пишу в storage довгим шляхом через redo файл і запис в data файл
2026-06-14 07:57:01 +03:00
storageInbox.Push(storage.MeasuresAppendWithGrow{
2026-06-13 08:01:42 +03:00
MetricID: req.MetricID,
LastPageNo: s.lastPageNo,
TimestampsRewindOffset: timestampsRewindOffset,
Timestamps: headTimestamps,
ValuesRewindOffset: valuesRewindOffset,
Values: headValues,
IndexLevelTails: s.indexLevelTails,
DataPages: pages,
TailTimestamps: timestamps.Tail(0), // payload
TailValues: values.Tail(0),
ResultCode: resultCode,
WrittenCount: written,
//ResultCh: req.ResultCh,
2026-06-05 19:43:01 +00:00
})
2026-05-31 20:01:28 +00:00
} else {
2026-06-10 06:18:45 +03:00
// короткий шлях - запис лише в storage
2026-06-14 07:57:01 +03:00
storageInbox.Push(storage.MeasuresAppend{
2026-06-13 08:01:42 +03:00
MetricID: req.MetricID,
TimestampsRewindOffset: timestampsRewindOffset,
ValuesRewindOffset: valuesRewindOffset,
Timestamps: timestamps.Tail(timestampsOffset),
Values: values.Tail(valuesOffset),
ResultCode: resultCode,
WrittenCount: written,
//ResultCh: req.ResultCh,
2026-06-11 14:27:38 +00:00
})
2026-05-31 20:01:28 +00:00
}
2026-06-13 07:13:03 +00:00
}
2026-05-31 20:01:28 +00:00
2026-06-13 22:43:17 +00:00
func (s *Metric) OnMeasuresAppendCommited(rec storage.MeasuresAppendCommited) {
2026-06-13 07:13:03 +00:00
// Видаляю state. Оригінальні Timestamps і Values вже мають останню версію
s.capturedState = nil
s.timestamps.ForgetCapturedState()
s.values.ForgetCapturedState()
2026-05-31 20:01:28 +00:00
}
2026-06-13 22:43:17 +00:00
func (s *Metric) OnMeasuresAppendWithGrowCommited(rec storage.MeasuresAppendWithGrowCommited) {
2026-05-31 20:01:28 +00:00
// Видаляю state. Оригінальні Timestamps і Values вже мають останню версію
2026-06-12 00:29:02 +03:00
s.capturedState = nil
2026-06-13 07:13:03 +00:00
s.timestamps.ForgetCapturedState()
s.values.ForgetCapturedState()
2026-06-09 08:16:16 +03:00
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
2026-06-13 22:43:17 +00:00
func (s *Metric) StartRangeScan(req RangeScanReq) {
2026-06-13 08:01:42 +03:00
// if s.Since == 0 {
// req.ResultCh <- rangeScanResult{
// ResultCode: QueryDone,
// }
// return
// }
2026-06-07 21:27:18 +03:00
2026-06-13 08:01:42 +03:00
// if req.Since > s.Until {
// req.ResultCh <- rangeScanResult{
// ResultCode: QueryDone,
// }
// return
// }
2026-06-07 21:27:18 +03:00
2026-06-13 08:01:42 +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-06-07 21:27:18 +03:00
2026-06-13 08:01:42 +03:00
// timestampDecompressor := s.timestamps.CreateDecompressor()
// valueDecompressor := s.values.CreateDecompressor(s.metricType, s.fracDigits)
2026-05-31 20:01:28 +00:00
2026-06-13 08:01:42 +03:00
// 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
// }
// }
// }
// 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
}
2026-06-13 22:43:17 +00:00
func (s *Metric) StartFullScan(req FullScanReq) {
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-12 14:21:14 +00:00
timestampDecompressor := s.timestamps.CreateDecompressor()
valueDecompressor := s.values.CreateDecompressor(s.metricType, s.fracDigits)
2026-05-31 20:01:28 +00:00
2026-06-12 14:21:14 +00: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)
}
2026-06-09 08:16:16 +03:00
2026-06-12 14:21:14 +00:00
if s.lastPageNo > 0 {
2026-06-13 22:43:17 +00:00
req.ResultCh <- FullScanResult{
2026-06-12 14:21:14 +00:00
ResultCode: UntilFound,
LastPageNo: s.lastPageNo,
FracDigits: s.fracDigits,
}
s.RLocks++
} else {
2026-06-13 22:43:17 +00:00
req.ResultCh <- FullScanResult{
2026-06-12 14:21:14 +00:00
ResultCode: QueryDone,
}
}
2026-06-09 08:16:16 +03:00
}
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
// ]
2026-06-13 22:43:17 +00:00
func (s *Metric) WriteTo(w io.Writer) (err error) {
2026-06-09 08:16:16 +03:00
_, 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-12 14:21:14 +00:00
err = bin.WriteUint16(w, uint16(s.timestamps.StoredSize()))
2026-06-09 08:16:16 +03:00
if err != nil {
return
}
2026-06-12 14:21:14 +00:00
err = bin.WriteUint16(w, uint16(s.values.StoredSize()))
2026-06-09 16:42:17 +00:00
if err != nil {
return
}
// timestamps payload
2026-06-12 14:21:14 +00:00
err = s.timestamps.WriteStoredTo(w)
2026-06-09 08:16:16 +03:00
if err != nil {
return
}
2026-06-09 16:42:17 +00:00
// values payload
2026-06-12 14:21:14 +00:00
err = s.values.WriteStoredTo(w)
2026-06-09 08:16:16 +03:00
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
}