Re: [whatwg/streams] Is when pull() is called on an underlying source deterministic? (#1155)

> > make the final consumer ... manually close() the chunk when it (eventually) receives it.
> 
> [w3c/mediacapture-transform#56](https://github.com/w3c/mediacapture-transform/issues/56) is about that not working with `tee()`.

I see... For Fetch, we use ["tee a readable stream"](https://streams.spec.whatwg.org/#readablestream-tee) which calls `ReadableStreamTee` with `cloneForBranch2 = true`. Thus, all chunks are [structurally cloned](https://streams.spec.whatwg.org/#abstract-opdef-structuredclone) before enqueuing them to the second branch.

Unfortunately, this mechanism is not exposed to web authors. `ReadableStream.prototype.tee()` always uses `cloneForBranch2 = false`. A naive solution would be to pipe `branch2` through a `TransformStream` that manually `clone()`s each frame:
```javascript
function teeWithClone(readable) {
  let [branch1, branch2] = readable.tee();
  branch2 = branch2.pipeThrough(new TransformStream({
    transform(frame, controller) {
      controller.enqueue(frame.clone());
    }
  }));
  return [branch1, branch2];
}
```

But this has a nasty problem. If the consumer of `branch1` modifies or closes the frame before `branch2` had a chance to clone it, then `branch2` will have modified or even unusable frames. So to do this "correctly", you'd have to clone *first*:
```javascript
function teeWithClone(readable) {
  readable = readable.pipeThrough(new TransformStream({
    transform(frame, controller) {
      controller.enqueue([frame, frame.clone()]);
    }
  }));
  let [branch1, branch2] = readable.tee();
  branch1 = branch1.pipeThrough(new TransformStream({
    transform([frame, clonedFrame], controller) {
      controller.enqueue(frame);
    }
  }));
  branch2 = branch2.pipeThrough(new TransformStream({
    transform([frame, clonedFrame], controller) {
      controller.enqueue(clonedFrame);
    }
  }));
  return [branch1, branch2];
}
```
...which looks very, very weird. 😛 

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

Received on Tuesday, 3 August 2021 21:40:51 UTC