Supra_App/src/routes/api/sheet/stream/+server.ts

93 lines
2.6 KiB
TypeScript
Raw Normal View History

import { logger } from '$lib/core/utils/logger';
2026-06-09 10:50:59 +07:00
import { json } from '@sveltejs/kit';
// In-memory store for streamed catalog data
// Format: { batchId: { chunks: [...], status: 'collecting'|'complete'|'error' } }
const streamCache = new Map<string, any>();
export async function POST({ request }) {
try {
const data = await request.json();
const { batch_id, msg, content, current_chunk, total_chunks } = data.payload;
// Initialize or update batch
if (!streamCache.has(batch_id)) {
streamCache.set(batch_id, {
chunks: [],
status: 'collecting',
total_chunks,
createdAt: Date.now()
});
}
const batch = streamCache.get(batch_id);
// Handle different message types
if (msg === 'start') {
logger.info(`[API] Stream started for batch ${batch_id}`);
2026-06-09 10:50:59 +07:00
} else if (msg === 'chunk') {
batch.chunks.push(content);
logger.info(`[API] Received chunk ${current_chunk}/${total_chunks} for batch ${batch_id}`);
2026-06-09 10:50:59 +07:00
} else if (msg === 'end') {
batch.status = 'complete';
logger.info(`[API] Stream complete for batch ${batch_id}, total chunks: ${batch.chunks.length}`);
2026-06-09 10:50:59 +07:00
} else if (msg === 'error') {
batch.status = 'error';
batch.error = content;
logger.info(`[API] Stream error for batch ${batch_id}:`, content);
2026-06-09 10:50:59 +07:00
}
return json({ status: 'received', batch_id });
} catch (error) {
logger.error('[API] Error processing stream:', error);
2026-06-09 10:50:59 +07:00
return json({ status: 'error', message: String(error) }, { status: 500 });
}
}
export function GET({ url }) {
const batchId = url.searchParams.get('batch_id');
// Clean up old cache entries (older than 5 minutes)
const now = Date.now();
for (const [key, value] of streamCache.entries()) {
if (now - value.createdAt > 5 * 60 * 1000) {
streamCache.delete(key);
}
}
// If batch_id specified, return that specific batch
if (batchId) {
const batch = streamCache.get(batchId);
if (!batch) {
return json({ status: 'not_found' }, { status: 404 });
}
return json({
batch_id: batchId,
status: batch.status,
chunks: batch.chunks,
total_chunks: batch.total_chunks,
error: batch.error || null,
createdAt: new Date(batch.createdAt).toISOString()
});
}
// Otherwise return list of all recent batches
const batches = Array.from(streamCache.entries()).map(([batchId, batch]) => ({
batch_id: batchId,
status: batch.status,
chunks_count: batch.chunks.length,
total_chunks: batch.total_chunks,
error: batch.error || null,
createdAt: new Date(batch.createdAt).toISOString()
}));
return json({
status: 'success',
batches: batches.sort(
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
)
});
}