Add streaming test case

parent 57ddd363
'use server'
export async function streamData(origin: string) {
const response = await fetch(new URL('/api/stream', origin))
const [body1, body2] = response.body.tee()
const reader = body2.getReader()
;(async () => {
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
console.log('CHUNK', value.byteLength)
}
} finally {
reader.releaseLock()
}
})()
return body1
}
import { setTimeout } from 'timers/promises'
const loremIpsum =
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt.\n'
const totalBytes = 5 * 1024 // 32 KB
const bytesPerChunk = 100 // bytes per chunk
const chunkCount = Math.ceil(totalBytes / bytesPerChunk)
export async function GET() {
const encoder = new TextEncoder()
const stream = new ReadableStream({
async start(controller) {
for (let i = 0; i < chunkCount; i++) {
await setTimeout(10)
controller.enqueue(encoder.encode(`${i} ${loremIpsum}`))
}
controller.close()
},
})
return new Response(stream, { headers: { 'Content-Type': 'text/plain' } })
}
'use client'
import { useState } from 'react'
import { streamData } from './actions'
export default function Page() { export default function Page() {
return <p>hello world</p> const [chunks, setChunks] = useState<string[]>([])
const [isStreaming, setIsStreaming] = useState(false)
const handleClick = async () => {
setChunks([])
setIsStreaming(true)
const stream = await streamData(window.location.origin)
// const response = await fetch('/api/stream')
// const stream = await response.body
const reader = stream.getReader()
const decoder = new TextDecoder()
try {
while (true) {
const { done, value } = await reader.read()
if (done) break
const chunk = decoder.decode(value, { stream: true })
console.log('Received chunk:', chunk)
setChunks((prev) => [...prev, chunk])
}
console.log('Complete')
} finally {
reader.releaseLock()
setIsStreaming(false)
}
}
return (
<div>
<button disabled={isStreaming} onClick={handleClick}>
{isStreaming ? 'Streaming...' : 'Start Stream'}
</button>
<div style={{ marginTop: '20px', whiteSpace: 'pre-wrap' }}>
{chunks.length > 0 && (
<div>
<h3>Received {chunks.length} chunks:</h3>
<div>
{chunks.map((chunk, i) => (
<div key={i}>{chunk}</div>
))}
</div>
</div>
)}
</div>
</div>
)
} }
/** /**
* @type {import('next').NextConfig} * @type {import('next').NextConfig}
*/ */
const nextConfig = {} const nextConfig = {
typescript: {
ignoreBuildErrors: true,
},
experimental: {
taint: true,
},
}
module.exports = nextConfig module.exports = nextConfig
import React from 'react'
let attempts = 1
async function test() {
'use cache'
console.log('attempt %d', attempts++)
throw new Error('bad')
}
export default async function Page() {
await test()
return <p>error page</p>
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment