cloudflare-docs icon indicating copy to clipboard operation
cloudflare-docs copied to clipboard

R2 worker example does not send `content-range` response header for range requests

Open milot-mirdita opened this issue 3 years ago • 2 comments

Which Cloudflare product does this pertain to?

R2

Existing documentation URL(s)

https://developers.cloudflare.com/r2/examples/demo-worker/

Section that requires update

Using R2 in a Worker

What needs to change?

Demo worker code does not work for range requests with aria2c. aria2c expects a content-range header in the HTTP response.

How should it change?

The following changes add the correct content-range response header:

function parseRange(encoded) {
...
  return {
    offset: Number(parts[0]),
+    end:    Number(parts[1]),
    length: Number(parts[1]) + 1 - Number(parts[0]),
  }
    headers.set("etag", object.httpEtag);
+    if (range) {
+      headers.set("content-range", `bytes ${range.offset}-${range.end}/${object.size}`)
+   }
    const status = object.body ? (range ? 206 : 200) : 304

Additional information

No response

milot-mirdita avatar Jul 09 '22 06:07 milot-mirdita

/lgtm

Nice fix, it can works with aria2c

iakisme avatar Jul 11 '22 16:07 iakisme

Hi @milot-mirdita , thank you for this catch, could you please PR this? I'm happy to review and merge after you do.

deadlypants1973 avatar Jul 28 '22 13:07 deadlypants1973

I found another issue. wget Sends range: START_OFFSET-, without an end. This results in an error. I fixed this by issuing a HEAD request to find out the real end position:

      let range = parseRange(request.headers.get('range'));
      if (range && range.end == 0) {
        const object = await env.MY_BUCKET.head(key);
        range.end = object.size - 1;
        range.length = range.end + 1 - range.offset;
      }

With these ~~two~~ changes wget --continue works correctly.

EDIT: Fixed this breaking aria2c again, This version should now be correct.

milot-mirdita avatar Oct 27 '22 15:10 milot-mirdita