Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions src/content/docs/durable-objects/examples/readable-stream.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
---
type: example
summary: Stream ReadableStream from Durable Objects.
pcx_content_type: example
title: Use ReadableStream with Durable Object and Workers
sidebar:
order: 3
description: Stream ReadableStream from Durable Objects.
---

import { GlossaryTooltip, WranglerConfig } from "~/components";

This example demonstrates:

- A Worker receives a request, and forwards it to a Durable Object `my-id`.
- The Durable Object streams an incrementing number every second, until it receives `AbortSignal`.
- The Worker reads and logs the values from the stream.
- The Worker then cancels the stream after 5 values.

```ts
import { DurableObject } from 'cloudflare:workers';

async function* dataSource(signal: AbortSignal) {
let counter = 0;
while (!signal.aborted) {
yield counter++;
await new Promise((resolve) => setTimeout(resolve, 1_000));
}

console.log('Data source cancelled');
}

export class MyDurableObject extends DurableObject<Env> {
async fetch(request: Request): Promise<Response> {
const abortController = new AbortController();

const stream = new ReadableStream({
start(controller) {
if (request.signal.aborted) {
controller.close();
return;
}

(async () => {
for await (const value of dataSource(AbortSignal.any([request.signal, abortController.signal]))) {
controller.enqueue(new TextEncoder().encode(String(value)));
}
})();
},
cancel() {
console.log('Stream cancelled');
abortController.abort();
},
});

const headers = new Headers({
'Content-Type': 'application/octet-stream',
});

return new Response(stream, { headers });
}
}

export default {
async fetch(request, env, ctx): Promise<Response> {
const id: DurableObjectId = env.MY_DURABLE_OBJECT.idFromName('my-id');
const stub = env.MY_DURABLE_OBJECT.get(id);
const response = await stub.fetch(request);
if (!response.ok || !response.body) {
return new Response('Invalid response', { status: 500 });
}

const reader = response.body.getReader();

// Cancel the stream after 5 messages
let i = 0;
while (true) {
if (i > 5) {
reader.cancel();
break;
}
const { value, done } = await reader.read();
console.log(`Got value ${new TextDecoder().decode(value)}`);
if (done) {
break;
}
i++;
}

return new Response('Done', { status: 200 });
},
} satisfies ExportedHandler<Env>;
```

:::note

In a setup where a Durable Object returns a readable stream to a Worker, if the Worker cancels the Durable Object's readable stream, the cancellation propagates to the Durable Object.

:::
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,6 @@ let reader = readable.getReader({ mode: 'byob' });

* When `true`, errors in the source `ReadableStream` will no longer abort the destination `WritableStream`. `pipeTo` will return a rejected promise with the error from the source or any error that occurred while aborting the destination.



***

## Related resources
Expand Down
Loading