mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-12-05 00:47:15 +08:00
- Unify labels.cascade_id session ID space, separate affinity-only aliases from identity-equivalent groups, align agent envelope parity before FinalizePayloadDoc, and add pre-first-byte 401 same-credential force-refresh retry-once (with Home force_refresh + rejected_aicode_token_sha256 contract) - Align Hub 2.36.0 TPU/502/400 retry rules, 240s multi-signal delay cap, 7 hard-billing reasons + HTTP 402 + daily word-boundary markers, AI_POLICY_REQUIRED diagnostics, and bounded-candidate SSEJSONAssembler - Bump Hub version floor to 2.36.0 (CL 1031268331), 256 MiB stream scanner, continuation leg 2+ parity, budget-exhausted synthetic MAX_TOKENS, usage modality merge, ModelDetails field 48 & THINKING_LEVEL_MAX, single-POST OnboardUser + LRO GET polling, and 2-pass LoadCodeAssist paidTier resolution - Harden AICode strict single-scope gate, shared grant-scoped 1h cooldown with pinned in-flight guard, 403 LOCATION_NOT_ELIGIBLE & §19.3 zero-ErrorInfo 403 fallback, 43-entry strict denial precedence, paidTier gate, FinishReason +1 shift, safetySettings proto normalization, X-Goog-User-Project omission, Home KV capability consumption, and owner/epoch-scoped KV suppression
902 lines
24 KiB
Go
902 lines
24 KiB
Go
package helps
|
|
|
|
import (
|
|
"bytes"
|
|
|
|
"github.com/MoeForge/moego/ojson"
|
|
)
|
|
|
|
const (
|
|
maxRawJSONCandidates = 8
|
|
sseDeferredTrailingEntryOverhead = 24
|
|
)
|
|
|
|
type rawJSONCandidate struct {
|
|
buf []byte
|
|
valid bool
|
|
scanned bool
|
|
state byte
|
|
skippedLines int
|
|
}
|
|
|
|
// SSEJSONAssembler reassembles JSON payloads that may span multiple SSE data
|
|
// lines while isolating malformed events to their own SSE event boundary.
|
|
type SSEJSONAssembler struct {
|
|
pending []byte
|
|
rawCandidates []rawJSONCandidate
|
|
deferredComplete []byte
|
|
deferredCompleteSkipped int
|
|
deferredCompletePrio int
|
|
deferredTrailing [][]byte
|
|
deferredTrailingDataBytes int
|
|
ready [][]byte
|
|
sawBlankAfterRaw bool
|
|
discardUntilBlank bool
|
|
maxBytes int
|
|
}
|
|
|
|
// NewSSEJSONAssembler creates an SSEJSONAssembler bounded by maxBytes.
|
|
// Non-positive limits default to StreamScannerBuffer.
|
|
func NewSSEJSONAssembler(maxBytes int) *SSEJSONAssembler {
|
|
if maxBytes <= 0 {
|
|
maxBytes = StreamScannerBuffer
|
|
}
|
|
return &SSEJSONAssembler{maxBytes: maxBytes}
|
|
}
|
|
|
|
// HasPending reports whether the assembler still holds an incomplete,
|
|
// deferred, queued, or discarded-in-progress SSE event that has not terminated.
|
|
func (a *SSEJSONAssembler) HasPending() bool {
|
|
return a != nil && (len(a.pending) > 0 || len(a.rawCandidates) > 0 || len(a.deferredComplete) > 0 || len(a.ready) > 0 || a.discardUntilBlank)
|
|
}
|
|
|
|
func (a *SSEJSONAssembler) resetActiveState() {
|
|
a.pending = nil
|
|
a.rawCandidates = nil
|
|
a.deferredComplete = nil
|
|
a.deferredCompleteSkipped = 0
|
|
a.deferredCompletePrio = 0
|
|
a.deferredTrailing = nil
|
|
a.deferredTrailingDataBytes = 0
|
|
a.sawBlankAfterRaw = false
|
|
a.discardUntilBlank = false
|
|
}
|
|
|
|
// Reset clears any buffered partial JSON state and queued frames.
|
|
func (a *SSEJSONAssembler) Reset() {
|
|
if a == nil {
|
|
return
|
|
}
|
|
a.resetActiveState()
|
|
a.ready = nil
|
|
}
|
|
|
|
func (a *SSEJSONAssembler) popReady() []byte {
|
|
if len(a.ready) == 0 {
|
|
return nil
|
|
}
|
|
payload := a.ready[0]
|
|
a.ready[0] = nil
|
|
a.ready = a.ready[1:]
|
|
if len(a.ready) == 0 {
|
|
a.ready = nil
|
|
}
|
|
return payload
|
|
}
|
|
|
|
func (a *SSEJSONAssembler) appendDeferredTrailing(line []byte, maxBytes int) {
|
|
if len(a.deferredComplete) == 0 {
|
|
return
|
|
}
|
|
if maxBytes > 0 {
|
|
if len(line) > maxBytes-a.deferredTrailingDataBytes {
|
|
a.flushDeferredAndReplay(line)
|
|
return
|
|
}
|
|
maxCap := (maxBytes - (a.deferredTrailingDataBytes + len(line))) / sseDeferredTrailingEntryOverhead
|
|
if len(a.deferredTrailing) == cap(a.deferredTrailing) {
|
|
if len(a.deferredTrailing)+1 > maxCap {
|
|
a.flushDeferredAndReplay(line)
|
|
return
|
|
}
|
|
newCap := min(max(cap(a.deferredTrailing)*2, 1), maxCap)
|
|
grown := make([][]byte, len(a.deferredTrailing), newCap)
|
|
copy(grown, a.deferredTrailing)
|
|
a.deferredTrailing = grown
|
|
} else if cap(a.deferredTrailing) > maxCap {
|
|
a.flushDeferredAndReplay(line)
|
|
return
|
|
}
|
|
}
|
|
a.deferredTrailing = append(a.deferredTrailing, bytes.Clone(line))
|
|
a.deferredTrailingDataBytes += len(line)
|
|
}
|
|
|
|
func (a *SSEJSONAssembler) replayLineToReady(line []byte) {
|
|
if payload := a.pushLine(line); payload != nil {
|
|
a.ready = append(a.ready, bytes.Clone(payload))
|
|
}
|
|
}
|
|
|
|
func (a *SSEJSONAssembler) flushDeferredAndReplay(currentLine []byte) {
|
|
deferred := a.deferredComplete
|
|
trailing := a.deferredTrailing
|
|
a.resetActiveState()
|
|
a.ready = append(a.ready, deferred)
|
|
for _, tl := range trailing {
|
|
a.replayLineToReady(tl)
|
|
}
|
|
a.replayLineToReady(currentLine)
|
|
}
|
|
|
|
func (a *SSEJSONAssembler) drainDeferredToReady() {
|
|
for len(a.deferredComplete) > 0 {
|
|
deferred := a.deferredComplete
|
|
trailing := a.deferredTrailing
|
|
a.resetActiveState()
|
|
a.ready = append(a.ready, deferred)
|
|
for _, tl := range trailing {
|
|
a.replayLineToReady(tl)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Flush emits the next queued frame or any deferred completed raw-JSON fallback
|
|
// payload (and replayed trailing frames) in FIFO order. Callers using Push can
|
|
// drain all pending frames at stream EOF by calling Flush until it returns nil.
|
|
func (a *SSEJSONAssembler) Flush() []byte {
|
|
if a == nil {
|
|
return nil
|
|
}
|
|
if len(a.ready) > 0 {
|
|
return a.popReady()
|
|
}
|
|
if len(a.deferredComplete) == 0 {
|
|
return nil
|
|
}
|
|
a.drainDeferredToReady()
|
|
return a.popReady()
|
|
}
|
|
|
|
// Drain emits all queued frames followed by any deferred completed raw-JSON
|
|
// fallback payload (and replayed trailing frames) in FIFO order, preserving
|
|
// any incomplete replayed trailing state so HasPending remains accurate at EOF.
|
|
func (a *SSEJSONAssembler) Drain() [][]byte {
|
|
if a == nil || (len(a.ready) == 0 && len(a.deferredComplete) == 0) {
|
|
return nil
|
|
}
|
|
if len(a.deferredComplete) > 0 {
|
|
a.drainDeferredToReady()
|
|
}
|
|
frames := a.ready
|
|
a.ready = nil
|
|
return frames
|
|
}
|
|
|
|
// Push feeds one scanned SSE line and returns the next complete JSON payload
|
|
// in FIFO order, or nil if more lines are needed or the line carries no JSON.
|
|
// When a single line flushes a deferred raw-JSON payload and also completes
|
|
// subsequent frames, the deferred payload is returned first and remaining
|
|
// frames are queued for subsequent Push, Flush, or Drain calls.
|
|
func (a *SSEJSONAssembler) Push(line []byte) []byte {
|
|
if a == nil {
|
|
return sseJSONLinePayload(line)
|
|
}
|
|
payload := a.pushLine(line)
|
|
if len(a.ready) == 0 {
|
|
return payload
|
|
}
|
|
if payload != nil {
|
|
a.ready = append(a.ready, bytes.Clone(payload))
|
|
}
|
|
return a.popReady()
|
|
}
|
|
|
|
// PushFrames feeds one scanned SSE line and returns all complete JSON payloads
|
|
// ready in FIFO order (including any previously queued frames and any deferred
|
|
// raw-JSON frame flushed before trailing and current lines are processed), or
|
|
// nil if no complete payload is ready yet.
|
|
func (a *SSEJSONAssembler) PushFrames(line []byte) [][]byte {
|
|
if a == nil {
|
|
if p := sseJSONLinePayload(line); p != nil {
|
|
return [][]byte{p}
|
|
}
|
|
return nil
|
|
}
|
|
payload := a.pushLine(line)
|
|
if len(a.ready) == 0 {
|
|
if payload == nil {
|
|
return nil
|
|
}
|
|
return [][]byte{payload}
|
|
}
|
|
frames := a.ready
|
|
a.ready = nil
|
|
if payload != nil {
|
|
frames = append(frames, payload)
|
|
}
|
|
return frames
|
|
}
|
|
|
|
func (a *SSEJSONAssembler) pushLine(line []byte) []byte {
|
|
maxBytes := a.maxBytes
|
|
if maxBytes <= 0 {
|
|
maxBytes = StreamScannerBuffer
|
|
}
|
|
|
|
// Only a genuine empty line (after stripping at most one trailing CR)
|
|
// terminates an SSE data event; whitespace-only non-empty lines (including
|
|
// multiple CRs) are ignored fields and must not discard in-progress state.
|
|
// In raw-JSON mode (a.rawCandidates started without an SSE "data:" prefix),
|
|
// internal blank lines are valid JSON whitespace and must be skipped
|
|
// without clearing the pending JSON object or array.
|
|
if len(bytes.TrimSuffix(line, []byte("\r"))) == 0 {
|
|
if len(a.rawCandidates) > 0 {
|
|
a.sawBlankAfterRaw = true
|
|
if len(a.deferredComplete) > 0 {
|
|
a.appendDeferredTrailing(line, maxBytes)
|
|
}
|
|
return nil
|
|
}
|
|
a.resetActiveState()
|
|
return nil
|
|
}
|
|
if a.discardUntilBlank {
|
|
return nil
|
|
}
|
|
|
|
trimmed := bytes.TrimSpace(bytes.TrimPrefix(bytes.TrimSpace(line), []byte{0xef, 0xbb, 0xbf}))
|
|
if len(trimmed) == 0 {
|
|
return nil
|
|
}
|
|
|
|
if len(a.rawCandidates) > 0 {
|
|
// Re-sync when explicit SSE field lines arrive, or handle ":" lines by
|
|
// keeping existing candidates (SSE comment branch) while forking valid
|
|
// JSON colon continuations within maxBytes.
|
|
if bytes.HasPrefix(trimmed, []byte("data:")) || bytes.Equal(trimmed, []byte("data")) {
|
|
if len(a.deferredComplete) > 0 {
|
|
a.flushDeferredAndReplay(line)
|
|
return nil
|
|
}
|
|
a.resetActiveState()
|
|
} else if isSSEFieldLine(trimmed) {
|
|
if len(a.deferredComplete) > 0 {
|
|
a.flushDeferredAndReplay(line)
|
|
return nil
|
|
}
|
|
a.resetActiveState()
|
|
return nil
|
|
} else if trimmed[0] == ':' {
|
|
return a.pushRawColonLine(line, trimmed, maxBytes)
|
|
} else {
|
|
return a.pushRawLine(line, trimmed, maxBytes)
|
|
}
|
|
}
|
|
|
|
return a.pushFreshOrDataLine(line, trimmed, maxBytes)
|
|
}
|
|
|
|
func (a *SSEJSONAssembler) pushFreshOrDataLine(line, trimmed []byte, maxBytes int) []byte {
|
|
if len(a.pending) > 0 {
|
|
if isSSEControlLine(trimmed) || bytes.Equal(trimmed, []byte("data")) || !bytes.HasPrefix(trimmed, []byte("data:")) {
|
|
return nil
|
|
}
|
|
chunk := bytes.TrimSpace(trimmed[len("data:"):])
|
|
if bytes.Equal(chunk, []byte("[DONE]")) {
|
|
a.resetActiveState()
|
|
return nil
|
|
}
|
|
if len(chunk) == 0 {
|
|
return nil
|
|
}
|
|
if len(a.pending)+1+len(chunk) > maxBytes {
|
|
a.resetActiveState()
|
|
a.discardUntilBlank = true
|
|
return nil
|
|
}
|
|
a.pending = append(a.pending, '\n')
|
|
a.pending = append(a.pending, chunk...)
|
|
if !ojson.ValidBytes(a.pending) {
|
|
return nil
|
|
}
|
|
payload := a.pending
|
|
a.resetActiveState()
|
|
return payload
|
|
}
|
|
|
|
payload := sseJSONLinePayload(line)
|
|
if payload == nil {
|
|
return nil
|
|
}
|
|
if ojson.ValidBytes(payload) {
|
|
return payload
|
|
}
|
|
isFromData := bytes.HasPrefix(trimmed, []byte("data:"))
|
|
if len(payload) > maxBytes {
|
|
if isFromData {
|
|
a.discardUntilBlank = true
|
|
}
|
|
return nil
|
|
}
|
|
copied := append([]byte(nil), payload...)
|
|
if isFromData {
|
|
a.pending = copied
|
|
} else {
|
|
a.rawCandidates = []rawJSONCandidate{{buf: copied}}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *SSEJSONAssembler) recordDeferredComplete(payload []byte, skipped int, prio int) bool {
|
|
if len(a.deferredComplete) == 0 ||
|
|
skipped < a.deferredCompleteSkipped ||
|
|
(skipped == a.deferredCompleteSkipped && prio > a.deferredCompletePrio) {
|
|
a.deferredComplete = payload
|
|
a.deferredCompleteSkipped = skipped
|
|
a.deferredCompletePrio = prio
|
|
a.deferredTrailing = nil
|
|
a.deferredTrailingDataBytes = 0
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func minValidCandidateSkipped(candidates []rawJSONCandidate) (int, bool) {
|
|
minSkipped := 0
|
|
hasValid := false
|
|
for _, cand := range candidates {
|
|
if !cand.valid {
|
|
continue
|
|
}
|
|
if !hasValid || cand.skippedLines < minSkipped {
|
|
minSkipped = cand.skippedLines
|
|
hasValid = true
|
|
}
|
|
}
|
|
return minSkipped, hasValid
|
|
}
|
|
|
|
func (a *SSEJSONAssembler) pushRawColonLine(line, trimmed []byte, maxBytes int) []byte {
|
|
anyValid := false
|
|
for i := range a.rawCandidates {
|
|
if !a.rawCandidates[i].scanned {
|
|
a.rawCandidates[i].valid, a.rawCandidates[i].state = scanRawJSONPrefixState(a.rawCandidates[i].buf)
|
|
a.rawCandidates[i].scanned = true
|
|
}
|
|
if a.rawCandidates[i].valid {
|
|
anyValid = true
|
|
}
|
|
}
|
|
if !anyValid && a.sawBlankAfterRaw {
|
|
if len(a.deferredComplete) > 0 {
|
|
a.flushDeferredAndReplay(line)
|
|
return nil
|
|
}
|
|
a.resetActiveState()
|
|
return nil
|
|
}
|
|
|
|
// Branch B (JSON continuation): evaluate candidates expecting ":" whose
|
|
// joined payload stays within maxBytes and remains a valid JSON prefix or frame.
|
|
var forked [maxRawJSONCandidates]rawJSONCandidate
|
|
forkedLen := 0
|
|
var completed []byte
|
|
completedSkipped := 0
|
|
completedPrio := -1
|
|
for _, cand := range a.rawCandidates {
|
|
if !cand.valid || !isRawJSONColonContinuationWithState(cand.state == jsonPrefixExpectColon, trimmed) {
|
|
continue
|
|
}
|
|
joined, ok := joinRawJSONLine(cand.buf, trimmed, maxBytes)
|
|
if !ok {
|
|
continue
|
|
}
|
|
if ojson.ValidBytes(joined) {
|
|
prio := rawJSONCandidatePriority(cand)
|
|
if completed == nil ||
|
|
cand.skippedLines < completedSkipped ||
|
|
(cand.skippedLines == completedSkipped && prio > completedPrio) {
|
|
completed = joined
|
|
completedSkipped = cand.skippedLines
|
|
completedPrio = prio
|
|
}
|
|
continue
|
|
}
|
|
if validJoined, joinedState := scanRawJSONPrefixState(joined); validJoined && forkedLen < len(forked) {
|
|
forked[forkedLen] = rawJSONCandidate{
|
|
buf: joined,
|
|
valid: true,
|
|
scanned: true,
|
|
state: joinedState,
|
|
skippedLines: cand.skippedLines,
|
|
}
|
|
forkedLen++
|
|
}
|
|
}
|
|
|
|
// If no candidate could consume this ":" line as JSON, treat it as an
|
|
// unambiguous SSE comment without penalizing surviving branches.
|
|
if completed == nil && forkedLen == 0 {
|
|
if len(a.deferredComplete) > 0 {
|
|
a.appendDeferredTrailing(line, maxBytes)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Branch A (SSE comment): surviving existing candidates skipped this ":" line.
|
|
for i := range a.rawCandidates {
|
|
a.rawCandidates[i].skippedLines++
|
|
}
|
|
for i := 0; i < forkedLen; i++ {
|
|
a.rawCandidates = addRawJSONCandidate(a.rawCandidates, forked[i])
|
|
}
|
|
consumedCurrentLine := false
|
|
if completed != nil {
|
|
consumedCurrentLine = a.recordDeferredComplete(completed, completedSkipped, completedPrio)
|
|
minSkipped, hasValid := minValidCandidateSkipped(a.rawCandidates)
|
|
if !hasValid || minSkipped >= a.deferredCompleteSkipped {
|
|
if consumedCurrentLine {
|
|
payload := a.deferredComplete
|
|
a.resetActiveState()
|
|
return payload
|
|
}
|
|
a.flushDeferredAndReplay(line)
|
|
return nil
|
|
}
|
|
}
|
|
if len(a.deferredComplete) > 0 && !consumedCurrentLine {
|
|
a.appendDeferredTrailing(line, maxBytes)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *SSEJSONAssembler) pushRawLine(line, trimmed []byte, maxBytes int) []byte {
|
|
a.sawBlankAfterRaw = false
|
|
if bytes.Equal(trimmed, []byte("[DONE]")) {
|
|
if len(a.deferredComplete) > 0 {
|
|
a.flushDeferredAndReplay(line)
|
|
return nil
|
|
}
|
|
a.resetActiveState()
|
|
return nil
|
|
}
|
|
|
|
// Fast O(n) amortized in-place append path for unambiguous single-branch
|
|
// raw JSON accumulation (no ":" fork or deferred fallback active).
|
|
if len(a.rawCandidates) == 1 && len(a.deferredComplete) == 0 {
|
|
buf := a.rawCandidates[0].buf
|
|
if len(buf)+1+len(trimmed) > maxBytes {
|
|
a.resetActiveState()
|
|
return nil
|
|
}
|
|
buf = append(buf, '\n')
|
|
buf = append(buf, trimmed...)
|
|
if ojson.ValidBytes(buf) {
|
|
a.resetActiveState()
|
|
return buf
|
|
}
|
|
a.rawCandidates[0].buf = buf
|
|
a.rawCandidates[0].scanned = false
|
|
return nil
|
|
}
|
|
|
|
var next []rawJSONCandidate
|
|
var fallback []byte
|
|
var completed []byte
|
|
completedSkipped := 0
|
|
completedPrio := -1
|
|
for _, cand := range a.rawCandidates {
|
|
if !cand.scanned {
|
|
cand.valid, cand.state = scanRawJSONPrefixState(cand.buf)
|
|
cand.scanned = true
|
|
}
|
|
joined, ok := joinRawJSONLine(cand.buf, trimmed, maxBytes)
|
|
if !ok {
|
|
continue
|
|
}
|
|
if fallback == nil {
|
|
fallback = joined
|
|
}
|
|
if ojson.ValidBytes(joined) {
|
|
prio := rawJSONCandidatePriority(cand)
|
|
if completed == nil ||
|
|
cand.skippedLines < completedSkipped ||
|
|
(cand.skippedLines == completedSkipped && prio > completedPrio) {
|
|
completed = joined
|
|
completedSkipped = cand.skippedLines
|
|
completedPrio = prio
|
|
}
|
|
continue
|
|
}
|
|
if validJoined, joinedState := scanRawJSONPrefixState(joined); validJoined {
|
|
next = addRawJSONCandidate(next, rawJSONCandidate{
|
|
buf: joined,
|
|
valid: true,
|
|
scanned: true,
|
|
state: joinedState,
|
|
skippedLines: cand.skippedLines,
|
|
})
|
|
}
|
|
}
|
|
consumedCurrentLine := false
|
|
if completed != nil {
|
|
consumedCurrentLine = a.recordDeferredComplete(completed, completedSkipped, completedPrio)
|
|
}
|
|
if len(a.deferredComplete) > 0 {
|
|
minSkipped, hasValid := minValidCandidateSkipped(next)
|
|
if !hasValid || minSkipped >= a.deferredCompleteSkipped {
|
|
if consumedCurrentLine {
|
|
payload := a.deferredComplete
|
|
a.resetActiveState()
|
|
return payload
|
|
}
|
|
a.flushDeferredAndReplay(line)
|
|
return nil
|
|
}
|
|
}
|
|
if len(next) > 0 {
|
|
a.rawCandidates = next
|
|
if len(a.deferredComplete) > 0 && !consumedCurrentLine {
|
|
a.appendDeferredTrailing(line, maxBytes)
|
|
}
|
|
return nil
|
|
}
|
|
if fallback != nil {
|
|
a.rawCandidates = []rawJSONCandidate{{buf: fallback, valid: false, scanned: true}}
|
|
return nil
|
|
}
|
|
a.resetActiveState()
|
|
return nil
|
|
}
|
|
|
|
func rawJSONCandidatePriority(cand rawJSONCandidate) int {
|
|
switch cand.state {
|
|
case jsonPrefixExpectColon, jsonPrefixExpectValue:
|
|
return 3
|
|
case jsonPrefixExpectObjKeyOrEnd, jsonPrefixExpectObjKey, jsonPrefixExpectArrValOrEnd:
|
|
return 2
|
|
case jsonPrefixExpectCommaOrEnd:
|
|
trimmed := bytes.TrimSpace(cand.buf)
|
|
if len(trimmed) > 0 {
|
|
switch trimmed[len(trimmed)-1] {
|
|
case '}', ']', '"':
|
|
return 2
|
|
}
|
|
}
|
|
return 1
|
|
default:
|
|
return 1
|
|
}
|
|
}
|
|
|
|
func addRawJSONCandidate(candidates []rawJSONCandidate, cand rawJSONCandidate) []rawJSONCandidate {
|
|
for i, existing := range candidates {
|
|
if bytes.Equal(existing.buf, cand.buf) {
|
|
if cand.skippedLines < existing.skippedLines {
|
|
candidates[i].skippedLines = cand.skippedLines
|
|
}
|
|
return candidates
|
|
}
|
|
}
|
|
if cand.skippedLines == 0 {
|
|
// Always reserve slot 0 for the full-verbatim (zero-skipped) branch.
|
|
if len(candidates) < maxRawJSONCandidates {
|
|
candidates = append(candidates, rawJSONCandidate{})
|
|
copy(candidates[1:], candidates[:len(candidates)-1])
|
|
candidates[0] = cand
|
|
return candidates
|
|
}
|
|
evictIdx := findWorstRawJSONCandidate(candidates)
|
|
if evictIdx < 0 {
|
|
evictIdx = len(candidates) - 1
|
|
}
|
|
if evictIdx > 0 {
|
|
copy(candidates[1:evictIdx+1], candidates[0:evictIdx])
|
|
}
|
|
candidates[0] = cand
|
|
return candidates
|
|
}
|
|
if len(candidates) < maxRawJSONCandidates {
|
|
return append(candidates, cand)
|
|
}
|
|
evictIdx := findWorstRawJSONCandidate(candidates)
|
|
if evictIdx < 0 {
|
|
return candidates
|
|
}
|
|
worst := candidates[evictIdx]
|
|
newPrio := rawJSONCandidatePriority(cand)
|
|
worstPrio := rawJSONCandidatePriority(worst)
|
|
if worstPrio == 1 {
|
|
if newPrio == 1 && cand.skippedLines > worst.skippedLines {
|
|
return candidates
|
|
}
|
|
} else {
|
|
if newPrio == 1 {
|
|
return candidates
|
|
}
|
|
if cand.skippedLines > worst.skippedLines ||
|
|
(cand.skippedLines == worst.skippedLines && newPrio <= worstPrio) {
|
|
return candidates
|
|
}
|
|
}
|
|
copy(candidates[evictIdx:], candidates[evictIdx+1:])
|
|
candidates[len(candidates)-1] = cand
|
|
return candidates
|
|
}
|
|
|
|
// findWorstRawJSONCandidate returns the index of the most evictable
|
|
// non-verbatim candidate (skippedLines > 0): heartbeat-like scalar branches
|
|
// (priority 1) are evicted before structural branches (priority >= 2), with
|
|
// higher skippedLines (then lower priority, oldest first) evicted first.
|
|
func findWorstRawJSONCandidate(candidates []rawJSONCandidate) int {
|
|
evictIdx := -1
|
|
var worst rawJSONCandidate
|
|
worstPrio := 0
|
|
for i, existing := range candidates {
|
|
if existing.skippedLines == 0 {
|
|
continue
|
|
}
|
|
prio := rawJSONCandidatePriority(existing)
|
|
if evictIdx < 0 || isMoreEvictable(existing, prio, worst, worstPrio) {
|
|
evictIdx = i
|
|
worst = existing
|
|
worstPrio = prio
|
|
}
|
|
}
|
|
return evictIdx
|
|
}
|
|
|
|
func isMoreEvictable(cand rawJSONCandidate, prio int, cur rawJSONCandidate, curPrio int) bool {
|
|
candHeartbeat := prio == 1
|
|
curHeartbeat := curPrio == 1
|
|
if candHeartbeat != curHeartbeat {
|
|
return candHeartbeat
|
|
}
|
|
if cand.skippedLines != cur.skippedLines {
|
|
return cand.skippedLines > cur.skippedLines
|
|
}
|
|
return prio < curPrio
|
|
}
|
|
|
|
// sseJSONLinePayload extracts a JSON object or array fragment from an SSE
|
|
// data line (or raw JSON stream line) while ignoring control lines and [DONE].
|
|
func sseJSONLinePayload(line []byte) []byte {
|
|
trimmed := bytes.TrimSpace(bytes.TrimPrefix(bytes.TrimSpace(line), []byte{0xef, 0xbb, 0xbf}))
|
|
if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("[DONE]")) || isSSEControlLine(trimmed) {
|
|
return nil
|
|
}
|
|
if bytes.HasPrefix(trimmed, []byte("data:")) {
|
|
trimmed = bytes.TrimSpace(trimmed[len("data:"):])
|
|
}
|
|
if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("[DONE]")) {
|
|
return nil
|
|
}
|
|
if trimmed[0] != '{' && trimmed[0] != '[' {
|
|
return nil
|
|
}
|
|
return trimmed
|
|
}
|
|
|
|
func isSSEFieldLine(trimmed []byte) bool {
|
|
return bytes.HasPrefix(trimmed, []byte("event:")) ||
|
|
bytes.HasPrefix(trimmed, []byte("id:")) ||
|
|
bytes.HasPrefix(trimmed, []byte("retry:")) ||
|
|
bytes.Equal(trimmed, []byte("event")) ||
|
|
bytes.Equal(trimmed, []byte("id")) ||
|
|
bytes.Equal(trimmed, []byte("retry"))
|
|
}
|
|
|
|
func isSSEControlLine(trimmed []byte) bool {
|
|
if len(trimmed) == 0 {
|
|
return false
|
|
}
|
|
if trimmed[0] == ':' {
|
|
return true
|
|
}
|
|
return isSSEFieldLine(trimmed)
|
|
}
|
|
|
|
// isRawJSONColonContinuation reports whether colonLine (starting with ':')
|
|
// continues a raw JSON object key-value pair after buf rather than acting as
|
|
// an SSE comment (such as ": keepalive").
|
|
func isRawJSONColonContinuation(buf []byte, colonLine string) bool {
|
|
_, expectColon := scanRawJSONPrefix(buf)
|
|
return isRawJSONColonContinuationWithState(expectColon, []byte(colonLine))
|
|
}
|
|
|
|
func isRawJSONColonContinuationWithState(expectColon bool, colonLine []byte) bool {
|
|
if !expectColon || len(colonLine) == 0 || colonLine[0] != ':' {
|
|
return false
|
|
}
|
|
after := bytes.TrimSpace(colonLine[1:])
|
|
return len(after) == 0 || hasJSONValueStarter(after)
|
|
}
|
|
|
|
var jsonKeywordStarters = [...][]byte{
|
|
[]byte("true"),
|
|
[]byte("false"),
|
|
[]byte("null"),
|
|
}
|
|
|
|
func hasJSONValueStarter(val []byte) bool {
|
|
if len(val) == 0 {
|
|
return false
|
|
}
|
|
switch val[0] {
|
|
case '{', '[', '"':
|
|
return true
|
|
case '-':
|
|
return len(val) > 1 && val[1] >= '0' && val[1] <= '9'
|
|
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
|
return true
|
|
default:
|
|
for _, kw := range jsonKeywordStarters {
|
|
if bytes.HasPrefix(val, kw) {
|
|
if len(val) == len(kw) {
|
|
return true
|
|
}
|
|
switch val[len(kw)] {
|
|
case ' ', '\t', '\r', '\n', ',', '}', ']':
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
}
|
|
|
|
const (
|
|
jsonPrefixExpectValue byte = iota
|
|
jsonPrefixExpectArrValOrEnd
|
|
jsonPrefixExpectObjKeyOrEnd
|
|
jsonPrefixExpectObjKey
|
|
jsonPrefixExpectColon
|
|
jsonPrefixExpectCommaOrEnd
|
|
jsonPrefixExpectEOF
|
|
)
|
|
|
|
// scanRawJSONPrefix reports whether buf is a syntactically valid JSON prefix
|
|
// across line boundaries and whether the next expected token is ':' after a
|
|
// completed JSON object key.
|
|
func scanRawJSONPrefix(buf []byte) (validPrefix bool, expectColon bool) {
|
|
valid, state := scanRawJSONPrefixState(buf)
|
|
return valid, state == jsonPrefixExpectColon
|
|
}
|
|
|
|
func scanRawJSONPrefixState(buf []byte) (validPrefix bool, state byte) {
|
|
var stackBuf [32]byte
|
|
stack := stackBuf[:0]
|
|
state = jsonPrefixExpectValue
|
|
afterValue := func() byte {
|
|
if len(stack) == 0 {
|
|
return jsonPrefixExpectEOF
|
|
}
|
|
return jsonPrefixExpectCommaOrEnd
|
|
}
|
|
|
|
for i := 0; i < len(buf); i++ {
|
|
c := buf[i]
|
|
switch c {
|
|
case ' ', '\t', '\r', '\n':
|
|
continue
|
|
case '{':
|
|
if state != jsonPrefixExpectValue && state != jsonPrefixExpectArrValOrEnd {
|
|
return false, 0
|
|
}
|
|
stack = append(stack, '{')
|
|
state = jsonPrefixExpectObjKeyOrEnd
|
|
case '[':
|
|
if state != jsonPrefixExpectValue && state != jsonPrefixExpectArrValOrEnd {
|
|
return false, 0
|
|
}
|
|
stack = append(stack, '[')
|
|
state = jsonPrefixExpectArrValOrEnd
|
|
case '}':
|
|
if len(stack) == 0 || stack[len(stack)-1] != '{' || (state != jsonPrefixExpectObjKeyOrEnd && state != jsonPrefixExpectCommaOrEnd) {
|
|
return false, 0
|
|
}
|
|
stack = stack[:len(stack)-1]
|
|
state = afterValue()
|
|
case ']':
|
|
if len(stack) == 0 || stack[len(stack)-1] != '[' || (state != jsonPrefixExpectArrValOrEnd && state != jsonPrefixExpectCommaOrEnd) {
|
|
return false, 0
|
|
}
|
|
stack = stack[:len(stack)-1]
|
|
state = afterValue()
|
|
case ':':
|
|
if state != jsonPrefixExpectColon {
|
|
return false, 0
|
|
}
|
|
state = jsonPrefixExpectValue
|
|
case ',':
|
|
if state != jsonPrefixExpectCommaOrEnd || len(stack) == 0 {
|
|
return false, 0
|
|
}
|
|
if stack[len(stack)-1] == '{' {
|
|
state = jsonPrefixExpectObjKey
|
|
} else {
|
|
state = jsonPrefixExpectValue
|
|
}
|
|
case '"':
|
|
if state != jsonPrefixExpectObjKeyOrEnd && state != jsonPrefixExpectObjKey && state != jsonPrefixExpectValue && state != jsonPrefixExpectArrValOrEnd {
|
|
return false, 0
|
|
}
|
|
closed := false
|
|
for i++; i < len(buf); i++ {
|
|
if buf[i] < 0x20 {
|
|
return false, 0
|
|
}
|
|
if buf[i] == '\\' {
|
|
i++
|
|
if i >= len(buf) {
|
|
return false, 0
|
|
}
|
|
switch buf[i] {
|
|
case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
|
|
case 'u':
|
|
for k := 0; k < 4; k++ {
|
|
i++
|
|
if i >= len(buf) || !isASCIIHexDigit(buf[i]) {
|
|
return false, 0
|
|
}
|
|
}
|
|
default:
|
|
return false, 0
|
|
}
|
|
continue
|
|
}
|
|
if buf[i] == '"' {
|
|
closed = true
|
|
break
|
|
}
|
|
}
|
|
if !closed {
|
|
return false, 0
|
|
}
|
|
if state == jsonPrefixExpectObjKeyOrEnd || state == jsonPrefixExpectObjKey {
|
|
state = jsonPrefixExpectColon
|
|
} else {
|
|
state = afterValue()
|
|
}
|
|
default:
|
|
if state != jsonPrefixExpectValue && state != jsonPrefixExpectArrValOrEnd {
|
|
return false, 0
|
|
}
|
|
start := i
|
|
for i+1 < len(buf) {
|
|
next := buf[i+1]
|
|
if next == ' ' || next == '\t' || next == '\r' || next == '\n' ||
|
|
next == '{' || next == '}' || next == '[' || next == ']' ||
|
|
next == ':' || next == ',' || next == '"' {
|
|
break
|
|
}
|
|
i++
|
|
}
|
|
if !ojson.ValidBytes(buf[start : i+1]) {
|
|
return false, 0
|
|
}
|
|
state = afterValue()
|
|
}
|
|
}
|
|
if len(stack) == 0 && state == jsonPrefixExpectValue {
|
|
return false, 0
|
|
}
|
|
return true, state
|
|
}
|
|
|
|
func isASCIIHexDigit(b byte) bool {
|
|
return (b >= '0' && b <= '9') || (b >= 'a' && b <= 'f') || (b >= 'A' && b <= 'F')
|
|
}
|
|
|
|
func joinRawJSONLine(base, line []byte, maxBytes int) ([]byte, bool) {
|
|
if maxBytes > 0 && len(base)+1+len(line) > maxBytes {
|
|
return nil, false
|
|
}
|
|
out := make([]byte, 0, len(base)+1+len(line))
|
|
out = append(out, base...)
|
|
out = append(out, '\n')
|
|
out = append(out, line...)
|
|
return out, true
|
|
}
|