VictoriaMetrics/lib/logstorage/pipe_head.go

81 lines
1.9 KiB
Go
Raw Normal View History

2024-04-29 01:44:54 +00:00
package logstorage
import (
"fmt"
"sync/atomic"
)
2024-04-30 23:19:22 +00:00
// pipeHead implements '| head ...' pipe.
//
// See https://docs.victoriametrics.com/victorialogs/logsql/#limiters
2024-04-29 01:44:54 +00:00
type pipeHead struct {
n uint64
}
func (ph *pipeHead) String() string {
return fmt.Sprintf("head %d", ph.n)
}
func (ph *pipeHead) newPipeProcessor(_ int, _ <-chan struct{}, cancel func(), ppBase pipeProcessor) pipeProcessor {
if ph.n == 0 {
// Special case - notify the caller to stop writing data to the returned pipeHeadProcessor
cancel()
}
return &pipeHeadProcessor{
ph: ph,
cancel: cancel,
ppBase: ppBase,
}
}
type pipeHeadProcessor struct {
ph *pipeHead
cancel func()
ppBase pipeProcessor
rowsProcessed atomic.Uint64
}
2024-04-30 23:19:22 +00:00
func (php *pipeHeadProcessor) writeBlock(workerID uint, br *blockResult) {
rowsProcessed := php.rowsProcessed.Add(uint64(len(br.timestamps)))
if rowsProcessed <= php.ph.n {
2024-04-29 01:44:54 +00:00
// Fast path - write all the rows to ppBase.
2024-04-30 23:19:22 +00:00
php.ppBase.writeBlock(workerID, br)
2024-04-29 01:44:54 +00:00
return
}
// Slow path - overflow. Write the remaining rows if needed.
2024-04-30 21:03:34 +00:00
rowsProcessed -= uint64(len(br.timestamps))
2024-04-30 23:19:22 +00:00
if rowsProcessed >= php.ph.n {
2024-04-29 01:44:54 +00:00
// Nothing to write. There is no need in cancel() call, since it has been called by another goroutine.
return
}
// Write remaining rows.
2024-04-30 23:19:22 +00:00
keepRows := php.ph.n - rowsProcessed
2024-04-30 21:03:34 +00:00
br.truncateRows(int(keepRows))
2024-04-30 23:19:22 +00:00
php.ppBase.writeBlock(workerID, br)
2024-04-29 01:44:54 +00:00
// Notify the caller that it should stop passing more data to writeBlock().
2024-04-30 23:19:22 +00:00
php.cancel()
2024-04-29 01:44:54 +00:00
}
2024-04-30 23:19:22 +00:00
func (php *pipeHeadProcessor) flush() error {
2024-04-29 01:44:54 +00:00
return nil
}
func parsePipeHead(lex *lexer) (*pipeHead, error) {
if !lex.mustNextToken() {
return nil, fmt.Errorf("missing the number of head rows to return")
}
n, err := parseUint(lex.token)
if err != nil {
return nil, fmt.Errorf("cannot parse the number of head rows to return %q: %w", lex.token, err)
}
lex.nextToken()
ph := &pipeHead{
n: n,
}
return ph, nil
}