Files
qb/worker/metric.go

484 lines
12 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-14 23:12:03 +03:00
"fmt"
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 {
2026-06-15 10:47:24 +00:00
LastValue float64
2026-06-13 08:01:42 +03:00
}
2026-06-13 22:43:17 +00:00
type Metric struct {
2026-06-15 10:47:24 +00:00
metricType qb.MetricType
fracDigits byte
lastPageNo uint32
lastValue float64
2026-06-09 08:16:16 +03:00
buffer []byte
timestamps qb.TimestampCompressor
values qb.ValueCompressor
2026-06-14 23:12:03 +03:00
xLock bool
rLocks int
2026-06-15 05:32:15 +03:00
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-15 05:32:15 +03:00
// індекси
// Metric encode format:
// metricID - 4b
// metricType - 1b
// fracDigits - 1b
// lastPageNo - 4b
// timestamps size - 2b
// values size - 2b
// timestams payload - Nb
// 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
}
err = bin.WriteUint16(w, uint16(s.timestamps.CommitedSize()))
if err != nil {
return
}
err = bin.WriteUint16(w, uint16(s.values.CommitedSize()))
if err != nil {
return
}
// timestamps payload
err = s.timestamps.WriteCommitedTo(w)
if err != nil {
return
}
// values payload
err = s.values.WriteCommitedTo(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
}
_, err = w.Write(level.Buffer[:level.RecordsCount*storage.IndexRecordSize])
if err != nil {
return
}
}
return
}
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-15 10:47:24 +00:00
// REQUESTS
func (s *Metric) ReleaseRLock() {
s.rLocks--
if s.rLocks == 0 {
if len(s.waitQueue) > 0 {
s.ProcessQueue()
}
2026-06-13 08:01:42 +03:00
}
}
2026-02-10 14:02:11 +00:00
2026-06-15 10:47:24 +00:00
// суть у тому що треба запускати запити, пока не зустріну XLock
func (s *Metric) ProcessQueue(metricID uint32, tmp []byte) {
if len(s.waitQueue) == 0 {
return
}
for _, untyped := range s.waitQueue {
switch req := untyped.(type) {
case RangeScanReq:
s.StartRangeScan(req)
case FullScanReq:
s.StartFullScan(req)
case GetMetricReq:
s.GetMetric(req)
case AppendMeasuresReq:
metric.AppendMeasures(req, tmp, s.storageInbox)
case DeleteMetricReq:
s.DeleteMetric(req)
case DeleteMeasuresReq:
metric.DeleteMeasures(req)
default:
qb.Abort(qb.UnknownMetricWaitQueueItemBug,
fmt.Errorf("bug: unknown metric wait queue item type %T", req))
}
}
}
2026-05-31 20:01:28 +00:00
2026-06-14 23:12:03 +03:00
func (s *Metric) AppendMeasures(req AppendMeasuresReq, tmp []byte, storageInbox *inbox.Inbox) {
2026-06-15 05:32:15 +03:00
if s.xLock || s.capturedState != nil {
s.waitQueue = append(s.waitQueue, req)
return
2026-06-12 00:29:02 +03:00
}
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
2026-06-14 23:12:03 +03:00
resultCode byte = Succeed
2026-05-31 20:01:28 +00:00
)
2026-06-12 00:29:02 +03:00
s.capturedState = &CapturedState{
2026-06-15 10:47:24 +00:00
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-15 10:47:24 +00:00
if measure.Timestamp <= s.timestamps.Until() {
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-14 23:12:03 +03:00
tReport := timestamps.Evaluate(tmp[:7], measure.Timestamp)
2026-06-15 01:20:30 +03:00
//fmt.Printf("tReport: %#v\n", tReport)
2026-06-14 23:12:03 +03:00
vReport := values.Evaluate(tmp[7:], measure.Value)
2026-06-15 01:20:30 +03:00
//fmt.Printf("vReport: %#v\n", vReport)
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-15 01:20:30 +03:00
fmt.Println("PAGE FILLED")
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
2026-06-15 01:20:30 +03:00
tReport = timestamps.Evaluate(tmp[:7], measure.Timestamp)
//fmt.Printf("tReport: %#v\n", tReport)
vReport = values.Evaluate(tmp[7:], measure.Value)
//fmt.Printf("vReport: %#v\n", vReport)
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-14 23:12:03 +03:00
req.ResultCh <- storage.MeasuresAppendResult{
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,
2026-06-14 23:12:03 +03:00
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,
2026-06-14 23:12:03 +03:00
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-15 05:32:15 +03:00
func (s *Metric) DeleteMeasures(req DeleteMeasuresReq) {
2026-06-15 10:47:24 +00:00
// if s.xLock || s.capturedState != nil {
// s.waitQueue = append(s.waitQueue, req)
// return
// }
// since := s.timestamps.FirstTimestamp()
// until := s.timestamps.LastTimestamp()
// if since == 0 || (req.Since > 0 && until < req.Since) {
// req.ResultCh <- NoMeasuresToDelete
// }
2026-06-15 05:32:15 +03:00
// if s.RootPageNo > 0 {
// req.ResultCh <- tryDeleteMeasuresResult{
// ResultCode: DeleteFromAtreeRequired,
// RootPageNo: metric.RootPageNo,
// }
// } else {
// req.ResultCh <- tryDeleteMeasuresResult{
// ResultCode: DeleteFromAtreeNotNeeded,
// }
// }
2026-05-31 20:01:28 +00:00
}
2026-06-13 22:43:17 +00:00
func (s *Metric) StartRangeScan(req RangeScanReq) {
2026-06-15 05:32:15 +03:00
if s.xLock {
s.waitQueue = append(s.waitQueue, req)
return
}
2026-06-15 10:47:24 +00:00
since := s.timestamps.CommitedSince()
if since == 0 {
req.ResultCh <- RangeScanResult{
ResultCode: QueryDone,
}
return
}
// range after
if req.Since > s.timestamps.CommitedUntil() {
req.ResultCh <- RangeScanResult{
ResultCode: QueryDone,
}
return
}
// range before
if req.Until < since {
if len(s.indexLevelTails) > 0 {
pageNo, isDataPage := storage.FindPageOnIndexLevelTails(s.indexLevelTails, req.Until)
if pageNo > 0 {
req.ResultCh <- RangeScanResult{
ResultCode: UntilNotFound,
FracDigits: s.fracDigits,
LastPageNo: pageNo,
IsDataPage: isDataPage,
}
s.rLocks++
return
} else {
// range until before 1st measure timestamp
req.ResultCh <- RangeScanResult{
ResultCode: QueryDone,
}
return
}
} else {
req.ResultCh <- RangeScanResult{
ResultCode: QueryDone,
}
return
}
}
2026-06-07 21:27:18 +03:00
2026-06-15 05:32:15 +03:00
timestampDecompressor := s.timestamps.CreateDecompressor()
valueDecompressor := s.values.CreateDecompressor(s.metricType, s.fracDigits)
2026-05-31 20:01:28 +00:00
2026-06-15 05:32:15 +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-15 05:32:15 +03:00
if s.xLock {
s.waitQueue = append(s.waitQueue, req)
return
}
if s.timestamps.CommitedSize() == 0 {
req.ResultCh <- FullScanResult{
ResultCode: QueryDone,
}
return
}
2026-06-12 14:21:14 +00:00
timestampDecompressor := s.timestamps.CreateDecompressor()
valueDecompressor := s.values.CreateDecompressor(s.metricType, s.fracDigits)
for {
timestamp, done := timestampDecompressor.NextValue()
if done {
break
}
2026-06-15 01:20:30 +03:00
//fmt.Println("ts:", timestamp)
2026-06-12 14:21:14 +00:00
value, done := valueDecompressor.NextValue()
if done {
qb.Abort(qb.HasTimestampNoValueBug, ErrNoValueBug)
}
2026-06-15 01:20:30 +03:00
//fmt.Println("value:", value)
2026-06-12 14:21:14 +00:00
req.ResponseWriter.FeedNoSend(timestamp, value)
}
2026-06-09 08:16:16 +03:00
2026-06-15 05:32:15 +03:00
if s.lastPageNo > 0 {
req.ResultCh <- FullScanResult{
ResultCode: UntilFound,
LastPageNo: s.lastPageNo,
FracDigits: s.fracDigits,
}
s.rLocks++
} else {
req.ResultCh <- FullScanResult{
ResultCode: QueryDone,
}
2026-06-12 14:21:14 +00:00
}
2026-06-09 08:16:16 +03:00
}
2026-05-31 20:01:28 +00:00
2026-06-15 05:32:15 +03:00
// COMMITS
2026-06-09 08:16:16 +03:00
2026-06-15 05:32:15 +03:00
func (s *Metric) OnMeasuresAppendCommited(rec storage.MeasuresAppendCommited) {
// Видаляю state. Оригінальні Timestamps і Values вже мають останню версію
s.capturedState = nil
s.timestamps.ForgetCapturedState()
s.values.ForgetCapturedState()
rec.ResultCh <- storage.MeasuresAppendResult{
ResultCode: rec.ResultCode,
WrittenCount: rec.WrittenCount,
2026-06-09 08:16:16 +03:00
}
2026-06-15 05:32:15 +03:00
}
func (s *Metric) OnMeasuresAppendWithGrowCommited(rec storage.MeasuresAppendWithGrowCommited) {
// Видаляю state. Оригінальні Timestamps і Values вже мають останню версію
s.capturedState = nil
s.timestamps.ForgetCapturedState()
s.values.ForgetCapturedState()
if rec.LastPageNo > 0 {
s.lastPageNo = rec.LastPageNo
2026-06-09 08:16:16 +03:00
}
2026-06-15 05:32:15 +03:00
// В storage я передав повний індекс. У нього додали елементи (можливо нові рівні).
// Тому проста заміна
s.indexLevelTails = rec.Index
rec.ResultCh <- storage.MeasuresAppendResult{
ResultCode: rec.ResultCode,
WrittenCount: rec.WrittenCount,
2026-05-31 20:01:28 +00:00
}
2026-06-15 05:32:15 +03:00
}
func (s *Metric) OnMeasuresDeleteCommited(rec storage.MeasuresDeleteCommited) {
//s.timestamps.Reset()
//s.values.Reset()
s.xLock = false
// s.Timestamps.Renew()
// s.Values.Renew()
s.indexLevelTails = nil
s.lastPageNo = 0
s.lastValue = 0
2026-05-31 20:01:28 +00:00
}