Re: [whatwg/streams] Discussion: How should streams handle Explicit Resource Management (Issue #1307)

I agree that readers and writers should be sync-disposable. Conceptually, the "resource" they're holding is the lock on the stream, so when you dispose them, they should release that resource through `releaseLock()`. This also shows up in other languages, e.g. a Rust [`MutexGuard`](https://doc.rust-lang.org/std/sync/struct.MutexGuard.html) releases its lock on the parent `Mutex` when dropped.

Personally, I would expect readable and writable streams to be async-disposable.
* Async-disposing a `ReadableStream` should `await readable.cancel()`.
* Async-disposing a `WritableStream` should `await writable.close()`. This aligns closer to [the proposal for Node.js Writable](https://github.com/tc39/proposal-explicit-resource-management/blob/06e6070442b7a2bd3bc18730dc78cb7ee9a88130/README.md#nodejs-streams) to use `writable.end()`.

This does mean that anything you do with that stream needs to be *inside* the block with the `await using`:
* If you acquire a reader/writer, you should release it within that block. This should be easy with `using reader = readable.getReader()`.
* If you async-iterate the stream, you should either `await using iterator = readable.values()` so the iterator will properly release its lock when done, or just use `for await (const chunk of readable)` to do that automatically.

Piping is really tricky though. You're almost *required* to `await` every `pipeTo()`, otherwise the stream will still be locked at the end of the `await using` block. I don't even know what we'd do with `pipeThrough()`... :confused:

Oh, and then there's `tee()` which keeps the original stream *locked forever*, so you can never dispose it... 😅 

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/streams/issues/1307#issuecomment-1968665901
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/streams/issues/1307/1968665901@github.com>

Received on Wednesday, 28 February 2024 10:19:49 UTC