mirror of
https://github.com/vercel/workflow.git
synced 2026-09-14 19:59:43 +08:00
4ca9a3edbd
build durable, resilient, and observable workflows. Co-authored-by: Nathan Rajlich <n@n8.io> Co-authored-by: Pranay Prakash <pranay.gp@gmail.com> Co-authored-by: Adrian <me@adriandlam.com> Co-authored-by: JJ Kasper <jj@jjsweb.site> Co-authored-by: Vercel Release Bot <88769842+vercel-release-bot@users.noreply.github.com> Co-authored-by: Peter Wielander <mittgfu@gmail.com> Co-authored-by: Hayden Bleasel <hello@haydenbleasel.com> Co-authored-by: Gal Schlezinger <gal@spitfire.co.il> Co-authored-by: Manuel Muñoz Solera <mamuso@mamuso.net> Co-authored-by: Garrett <garrett.tolbert@vercel.com> Co-authored-by: Lars Grammel <lars.grammel@gmail.com> Co-authored-by: Pooya Parsa <pyapar@gmail.com> Co-authored-by: Tom Dale <tom@tomdale.net> Co-authored-by: Vishal Yathish <135551666+visyat@users.noreply.github.com> Co-authored-by: josh <144584931+dancer@users.noreply.github.com>
59 lines
1.5 KiB
TypeScript
59 lines
1.5 KiB
TypeScript
export async function genStream(): Promise<ReadableStream<Uint8Array>> {
|
|
'use step';
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
async start(controller) {
|
|
const encoder = new TextEncoder();
|
|
for (let i = 0; i < 30; i++) {
|
|
const chunk = encoder.encode(`${i}\n`);
|
|
controller.enqueue(chunk);
|
|
console.log(`Enqueued number: ${i}`);
|
|
await new Promise((resolve) => setTimeout(resolve, 2500));
|
|
}
|
|
controller.close();
|
|
},
|
|
});
|
|
return stream;
|
|
}
|
|
|
|
export async function consumeStreams(
|
|
...streams: ReadableStream<Uint8Array>[]
|
|
): Promise<string> {
|
|
'use step';
|
|
const parts: Uint8Array[] = [];
|
|
|
|
console.log('Consuming streams', streams);
|
|
|
|
await Promise.all(
|
|
streams.map(async (s, i) => {
|
|
const reader = s.getReader();
|
|
while (true) {
|
|
const result = await reader.read();
|
|
if (result.done) break;
|
|
console.log(
|
|
`Received ${result.value.length} bytes from stream ${i}: ${JSON.stringify(new TextDecoder().decode(result.value))}`
|
|
);
|
|
parts.push(result.value);
|
|
}
|
|
})
|
|
);
|
|
|
|
return Buffer.concat(parts).toString('utf8');
|
|
}
|
|
|
|
export async function streams() {
|
|
'use workflow';
|
|
|
|
console.log('Streams workflow started');
|
|
|
|
const [s1, s2] = await Promise.all([genStream(), genStream()]);
|
|
const result = await consumeStreams(s1, s2);
|
|
|
|
console.log(`Streams workflow completed. Result: ${result.slice(0, 100)}`);
|
|
|
|
return {
|
|
message: 'Streams processed successfully',
|
|
dataLength: result.length,
|
|
preview: result.slice(0, 100),
|
|
};
|
|
}
|