35 lines
1.4 KiB
JavaScript
35 lines
1.4 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { Readable } from 'node:stream';
|
|
import { createSseBillingTransform } from './sse-billing.mjs';
|
|
|
|
function collectFinishEvents(payload) {
|
|
return new Promise((resolve, reject) => {
|
|
const finishes = [];
|
|
const transform = createSseBillingTransform({
|
|
onFinish: async (event) => {
|
|
finishes.push(event);
|
|
},
|
|
});
|
|
const chunks = [];
|
|
transform.on('data', (chunk) => chunks.push(chunk));
|
|
transform.on('error', reject);
|
|
transform.on('finish', () => resolve({ finishes, output: Buffer.concat(chunks).toString('utf8') }));
|
|
Readable.from([payload]).pipe(transform);
|
|
});
|
|
}
|
|
|
|
test('createSseBillingTransform bills each Finish only once per stream', async () => {
|
|
const frame =
|
|
'data: {"type":"Finish","request_id":"req-1","token_state":{"accumulatedInputTokens":100,"accumulatedOutputTokens":20}}\n\n';
|
|
const { finishes, output } = await collectFinishEvents(frame);
|
|
assert.equal(finishes.length, 1);
|
|
assert.equal(output, frame);
|
|
});
|
|
|
|
test('createSseBillingTransform dedupes Finish replayed in flush buffer', async () => {
|
|
const partial = 'data: {"type":"Finish","request_id":"req-2","token_state":{"accumulatedInputTokens":50,"accumulatedOutputTokens":5}}';
|
|
const { finishes } = await collectFinishEvents(partial);
|
|
assert.equal(finishes.length, 1);
|
|
});
|