Repository navigation
refactor(stream search): schema aware grpc gateway marshaler #592
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { | ||
| 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 "" | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
rowSchemaand make all functions below on struct? (e.g.func (s rowSchema) render)so there will be no need to dereference any pointers