Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 7 additions & 76 deletions pkg/seqproxyapi/v1/marshaler.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ import (
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"

"github.com/ozontech/seq-db/query/encoding"
"github.com/ozontech/seq-db/seq"
)

var (
Expand Down Expand Up @@ -62,11 +59,7 @@ type rawValueBucket struct {

// MarshalJSON overrides "value" field to encode math.NaN and math.Inf as string.
func (b *Aggregation_Bucket) MarshalJSON() ([]byte, error) {
val := json.RawMessage(strconv.FormatFloat(b.Value, 'f', -1, 64))
// Convert math.NaN and math.Inf to quoted string.
if math.IsNaN(b.Value) || math.IsInf(b.Value, 0) {
val = json.RawMessage(strconv.Quote(string(val)))
}
val := marshalFloat64(b.Value)

bucket := rawValueBucket{
TestAggBucket: (*TestAggBucket)(b),
Expand Down Expand Up @@ -267,73 +260,11 @@ func (i *AsyncSearchesListItem) MarshalJSON() ([]byte, error) {
return pbMarshaller.Marshal(i)
}

// streamSearchDocColumns is the number of columns carried by a document record
// produced by StreamSearch: [id, time, data].
const streamSearchDocColumns = 3

// streamSearchAggColumns is the number of columns carried by an aggregation
// record: [key, value, ts, quantiles, not_exists].
const streamSearchAggColumns = 5

// MarshalJSON formats a StreamSearch record into a human-readable JSON array.
// The record kind is distinguished by the column count:
//
// - documents (3 cells): [id, time(nanoseconds, little-endian uint64), data]
// - aggregation buckets (5 cells): [key, value(little-endian float64),
// ts(nanoseconds, little-endian uint64), quantiles(little-endian float64
// array), not_exists(little-endian uint64)]
//
// For any other layout the raw cells are emitted as-is (base64 for bytes).
func (r *Record) MarshalJSON() ([]byte, error) {
cells := r.GetRawData()
switch len(cells) {
case streamSearchDocColumns:
// cells[1] is a little-endian uint64 storing the document MID (nanoseconds).
var ts time.Time
if len(cells[1]) == 8 {
ts = seq.MID(encoding.Uint64FromBytes(cells[1])).Time()
}
return json.Marshal([]any{
string(cells[0]), // id
ts.UTC().Format(time.RFC3339Nano),
json.RawMessage(cells[2]), // data, inlined as JSON
})
case streamSearchAggColumns:
return marshalAggRecord(cells)
default:
return json.Marshal(cells)
}
}

// marshalAggRecord renders an aggregation record: [key, value, ts, quantiles, not_exists].
func marshalAggRecord(cells [][]byte) ([]byte, error) {
// cells[1] is a little-endian float64 storing the aggregation value.
var value float64
if len(cells[1]) == 8 {
value = encoding.Float64FromBytes(cells[1])
}
val := json.RawMessage(strconv.FormatFloat(value, 'f', -1, 64))
if math.IsNaN(value) || math.IsInf(value, 0) {
val = json.RawMessage(strconv.Quote(string(val)))
}
// cells[2] is a little-endian uint64 storing the bucket MID (nanoseconds).
// A zero MID (no timestamp) is rendered as an empty string.
formattedTime := ""
if len(cells[2]) == 8 {
if ns := encoding.Uint64FromBytes(cells[2]); ns != 0 {
formattedTime = time.Unix(0, int64(ns)).UTC().Format(time.RFC3339Nano)
}
}
// cells[4] is a little-endian uint64 storing the not_exists count.
var notExists uint64
if len(cells[4]) == 8 {
notExists = encoding.Uint64FromBytes(cells[4])
// marshalFloat64 renders a float64 as a JSON number, quoting math.NaN and math.Inf as strings.
func marshalFloat64(v float64) json.RawMessage {
val := json.RawMessage(strconv.FormatFloat(v, 'f', -1, 64))
if math.IsNaN(v) || math.IsInf(v, 0) {
return json.RawMessage(strconv.Quote(string(val)))
}
return json.Marshal([]any{
string(cells[0]), // key
val, // value
formattedTime, // ts
encoding.Float64ArrayFromBytes(cells[3]), // quantiles
notExists, // not_exists
})
return val
}
77 changes: 5 additions & 72 deletions pkg/seqproxyapi/v1/marshaler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import (
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"

"github.com/ozontech/seq-db/query/encoding"
)

func TestAggregationBucketMarshalJSON(t *testing.T) {
Expand Down Expand Up @@ -152,74 +150,9 @@ func TestFetchAsyncSearchResultResponseMarshalJSON(t *testing.T) {
func TestRecordMarshalJSON(t *testing.T) {
r := require.New(t)

t.Run("documents", func(t *testing.T) {
ns := time.Date(2025, 7, 8, 10, 19, 8, 742000000, time.UTC).UnixNano()
rec := &Record{RawData: [][]byte{
[]byte("46e48be997010000-e70163d0fa7582e4"),
encoding.Uint64ToBytes(uint64(ns)),
[]byte(`{"message":"some_message","level":3}`),
}}

raw, err := json.Marshal(rec)
r.NoError(err)
r.Equal(
`["46e48be997010000-e70163d0fa7582e4","2025-07-08T10:19:08.742Z",{"message":"some_message","level":3}]`,
string(raw),
)
})

t.Run("aggregation buckets", func(t *testing.T) {
tsNs := time.Date(2025, 7, 8, 10, 19, 8, 742000000, time.UTC).UnixNano()
rec := &Record{RawData: [][]byte{
[]byte("service-a"),
encoding.Float64ToBytes(42.5),
encoding.Uint64ToBytes(uint64(tsNs)),
encoding.Float64ArrayToBytes(nil), // no quantiles
encoding.Uint64ToBytes(7),
}}

raw, err := json.Marshal(rec)
r.NoError(err)
r.Equal(`["service-a",42.5,"2025-07-08T10:19:08.742Z",[],7]`, string(raw))
})

t.Run("aggregation bucket with quantiles", func(t *testing.T) {
tsNs := time.Date(2025, 7, 8, 10, 19, 8, 742000000, time.UTC).UnixNano()
rec := &Record{RawData: [][]byte{
[]byte("service-a"),
encoding.Float64ToBytes(42.5),
encoding.Uint64ToBytes(uint64(tsNs)),
encoding.Float64ArrayToBytes([]float64{5.5, 9.1}),
encoding.Uint64ToBytes(0),
}}

raw, err := json.Marshal(rec)
r.NoError(err)
r.Equal(`["service-a",42.5,"2025-07-08T10:19:08.742Z",[5.5,9.1],0]`, string(raw))
})

t.Run("aggregation bucket with NaN", func(t *testing.T) {
rec := &Record{RawData: [][]byte{
[]byte("service-a"),
encoding.Float64ToBytes(math.NaN()),
make([]byte, 8),
encoding.Float64ArrayToBytes(nil),
make([]byte, 8),
}}

raw, err := json.Marshal(rec)
r.NoError(err)
r.Equal(`["service-a","NaN","",[],0]`, string(raw))
})

t.Run("unknown layout falls back to raw bytes", func(t *testing.T) {
// 4 cells used to be the aggregation layout; now it is an unknown one.
rec := &Record{RawData: [][]byte{[]byte("only"), []byte("two"), []byte("three"), []byte("four")}}
raw, err := json.Marshal(rec)
r.NoError(err)
// encoding/json marshals [][]byte as an array of base64 strings.
var decoded [][]byte
r.NoError(json.Unmarshal(raw, &decoded))
r.Equal(rec.RawData, decoded)
})
// Without a schema from the stream header, a record renders as raw cells with base64-encoded bytes.
rec := &Record{RawData: [][]byte{[]byte("only"), []byte("two")}}
raw, err := json.Marshal(rec)
r.NoError(err)
r.Equal(`{"raw_data":["b25seQ==","dHdv"]}`, string(raw))
}
170 changes: 170 additions & 0 deletions pkg/seqproxyapi/v1/stream_render.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package seqproxyapi

import (
"context"
"encoding/json"
"fmt"
"sync"
"time"

"google.golang.org/protobuf/proto"

"github.com/ozontech/seq-db/query/encoding"
)

func NewStreamSearchRewriter() func(ctx context.Context, resp proto.Message) (any, error) {
var (
mu sync.RWMutex
schemas = make(map[context.Context]*rowSchema) // key per stream
)

return func(ctx context.Context, resp proto.Message) (any, error) {
res, ok := resp.(*StreamSearchResponse)
if !ok {
return resp, nil
}

switch {
case res.GetHeader() != nil:
mu.Lock()
schemas[ctx] = newRowSchema(res.GetHeader().GetTyping())
for c := range schemas {
// clean up streams aborted mid way
if c.Err() != nil {
delete(schemas, c)
}
}
mu.Unlock()
case res.GetData() != nil:
mu.RLock()
schema := schemas[ctx]
mu.RUnlock()
if schema != nil {
return &renderedData{schema: schema, batch: res.GetData().GetBatch()}, nil
}
case res.GetSummary() != nil:
// delete the entry for completed stream
mu.Lock()
delete(schemas, ctx)
mu.Unlock()
}

return res, nil
}
}

type renderedData struct {
schema *rowSchema
batch *RecordsBatch
}

func (d *renderedData) MarshalJSON() ([]byte, error) {
records := make([]json.RawMessage, len(d.batch.GetRecords()))
for i, rec := range d.batch.GetRecords() {
raw, err := d.schema.renderRecord(rec.GetRawData())
if err != nil {
// schema mismatch, return raw base64 instead of failing the whole stream.
if raw, err = json.Marshal(rec.GetRawData()); err != nil {
return nil, err
}
}
records[i] = raw
}
return json.Marshal(renderedResponseTypeJSON{
ResponseType: renderedDataJSON{
Data: renderedDataBodyJSON{
Batch: renderedBatchJSON{Records: records},
},
},
})
}

type renderedResponseTypeJSON struct {
ResponseType renderedDataJSON `json:"ResponseType,omitempty"`
}

type renderedDataJSON struct {
Data renderedDataBodyJSON `json:"Data,omitempty"`
}

type renderedDataBodyJSON struct {
Batch renderedBatchJSON `json:"batch,omitempty"`
}

type renderedBatchJSON struct {
Records []json.RawMessage `json:"records,omitempty"`
}

// rowSchema renders raw data of StreamSearch records as human readable values according to the Typing from header.
type rowSchema []*Typing

func newRowSchema(typing []*Typing) *rowSchema {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: why not just return rowSchema and make all functions below on struct? (e.g. func (s rowSchema) render)

so there will be no need to dereference any pointers

s := rowSchema(typing)
return &s
}

func (s *rowSchema) renderRecord(cells [][]byte) (json.RawMessage, error) {
row, err := s.render(cells)
if err != nil {
return nil, err
}
return json.Marshal(row)
}

func (s *rowSchema) render(cells [][]byte) ([]any, error) {
if len(cells) != len(*s) {
return nil, fmt.Errorf("record has %d cells, schema declares %d columns", len(cells), len(*s))
}
row := make([]any, len(cells))
for i, cell := range cells {
row[i] = (*s)[i].renderCell(cell)
}
return row, nil
}

// timestampTitles holds uint64 column titles that carry time as nanoseconds since epoch;
// so timestamp rendering is keyed on the column title instead of the type alone.
var timestampTitles = map[string]struct{}{
"time": {},
"ts": {},
}

func (t *Typing) renderCell(cell []byte) any {
switch t.Type {
case DataType_DATA_TYPE_SEQ_ID, DataType_DATA_TYPE_STRING:
return string(cell)
case DataType_DATA_TYPE_BYTES:
return cell
case DataType_DATA_TYPE_RAW_DOCUMENT:
return json.RawMessage(cell)
case DataType_DATA_TYPE_UINT32:
return encoding.Uint32FromBytes(cell)
case DataType_DATA_TYPE_UINT64:
if _, ok := timestampTitles[t.Title]; ok {
return renderTimestamp(cell)
}
return encoding.Uint64FromBytes(cell)
case DataType_DATA_TYPE_INT32:
return encoding.Int32FromBytes(cell)
case DataType_DATA_TYPE_INT64:
return encoding.Int64FromBytes(cell)
case DataType_DATA_TYPE_FLOAT64:
return marshalFloat64(encoding.Float64FromBytes(cell))
case DataType_DATA_TYPE_FLOAT64_ARRAY:
return encoding.Float64ArrayFromBytes(cell)
case DataType_DATA_TYPE_STRING_ARRAY:
return encoding.StringArrayFromBytes(cell)
default:
return cell
}
}

func renderTimestamp(cell []byte) string {
if len(cell) != 8 {
return ""
}
if ns := encoding.Uint64FromBytes(cell); ns != 0 {
return time.Unix(0, int64(ns)).UTC().Format(time.RFC3339Nano)
}
return ""
}
Loading
Loading