File size: 4,837 Bytes
9e4583c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/**
 * Stream Tracker — Unified SSE stream monitoring
 *
 * Tracks token counts, latency, and errors during streaming responses.
 * Emits periodic progress callbacks for real-time monitoring.
 *
 * @module shared/utils/streamTracker
 */

export interface StreamMetrics {
  startTime: number;
  firstTokenTime: number;
  totalTokens: number;
  totalChunks: number;
  elapsedMs: number;
  tokensPerSecond: number;
  complete: boolean;
  error: string | null;
  finishReason: string | null;
}

interface StreamTrackerOptions {
  onProgress?: (metrics: StreamMetrics) => void;
  progressIntervalMs?: number;
}

export class StreamTracker {
  private _onProgress: ((metrics: StreamMetrics) => void) | null;
  private _progressIntervalMs: number;
  private _startTime: number;
  private _firstTokenTime: number;
  private _totalTokens: number;
  private _totalChunks: number;
  private _complete: boolean;
  private _error: string | null;
  private _finishReason: string | null;
  private _lastProgressAt: number;
  private _buffer: string;

  constructor(options: StreamTrackerOptions = {}) {
    this._onProgress = options.onProgress || null;
    this._progressIntervalMs = options.progressIntervalMs || 500;

    this._startTime = Date.now();
    this._firstTokenTime = 0;
    this._totalTokens = 0;
    this._totalChunks = 0;
    this._complete = false;
    this._error = null;
    this._finishReason = null;
    this._lastProgressAt = 0;
    this._buffer = "";
  }

  /**
   * Record an incoming SSE chunk.
   * @param {string|Object} chunk - Raw SSE text or parsed data
   */
  onChunk(chunk) {
    this._totalChunks++;

    if (this._totalChunks === 1) {
      this._firstTokenTime = Date.now() - this._startTime;
    }

    // Try to extract token count from chunk
    let data = chunk;
    if (typeof chunk === "string") {
      // Parse SSE if formatted
      if (chunk.startsWith("data: ")) {
        const payload = chunk.slice(6).trim();
        if (payload === "[DONE]") {
          this._complete = true;
          this._emitProgress();
          return;
        }
        try {
          data = JSON.parse(payload);
        } catch {
          data = null;
        }
      }
    }

    if (data && typeof data === "object") {
      // OpenAI format: choices[0].delta.content
      const content = data.choices?.[0]?.delta?.content;
      if (content) {
        // Rough token estimate (~4 chars per token)
        this._totalTokens += Math.ceil(content.length / 4);
      }

      // Check for finish reason
      const reason = data.choices?.[0]?.finish_reason;
      if (reason) {
        this._finishReason = reason;
      }

      // Usage in final chunk (OpenAI includes this)
      if (data.usage?.completion_tokens) {
        this._totalTokens = data.usage.completion_tokens;
      }
    }

    this._maybeEmitProgress();
  }

  /**
   * Mark stream as errored.
   * @param {string|Error} error
   */
  onError(error) {
    this._error = typeof error === "string" ? error : error.message;
    this._complete = true;
    this._emitProgress();
  }

  /** Mark stream as complete. */
  onComplete() {
    this._complete = true;
    this._emitProgress();
  }

  /** @returns {StreamMetrics} Current metrics */
  getMetrics() {
    const elapsedMs = Date.now() - this._startTime;
    const tokensPerSecond = elapsedMs > 0 ? this._totalTokens / (elapsedMs / 1000) : 0;

    return {
      startTime: this._startTime,
      firstTokenTime: this._firstTokenTime,
      totalTokens: this._totalTokens,
      totalChunks: this._totalChunks,
      elapsedMs,
      tokensPerSecond: Math.round(tokensPerSecond * 10) / 10,
      complete: this._complete,
      error: this._error,
      finishReason: this._finishReason,
    };
  }

  /** @private */
  _maybeEmitProgress() {
    const now = Date.now();
    if (now - this._lastProgressAt >= this._progressIntervalMs) {
      this._emitProgress();
    }
  }

  /** @private */
  _emitProgress() {
    this._lastProgressAt = Date.now();
    if (this._onProgress) {
      this._onProgress(this.getMetrics());
    }
  }
}

/**
 * Create a TransformStream that tracks SSE progress.
 *
 * @param {{ onProgress?: (metrics: StreamMetrics) => void }} [options={}]
 * @returns {{ stream: TransformStream, tracker: StreamTracker }}
 */
export function createStreamTracker(options = {}) {
  const tracker = new StreamTracker(options);

  const stream = new TransformStream({
    transform(chunk, controller) {
      const text = typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk);
      const lines = text.split("\n");

      for (const line of lines) {
        if (line.startsWith("data: ")) {
          tracker.onChunk(line);
        }
      }

      controller.enqueue(chunk);
    },
    flush() {
      tracker.onComplete();
    },
  });

  return { stream, tracker };
}