It turns out that you cannot fine-grained control of the range header in the current Java SDK implementation.
You can set the starting position by ReadChannel#seek(offset)
, but not the ending position.
Inside of the Java SDK, it will set the range header as Rrange:$offset-$(offset+bufferSize)
.
https://github.com/googleapis/java-storage/blob/master/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/v1/HttpStorageRpc.java#L732
A workaround is wrapping the ReadChannel
by yourself, and close the connection while it reaches the expected ending position. Code snipplet:
class GSBlobInputStream extends InputStream {
private final ReadChannel channel;
private long start = 0;
private long end = -1;
private InputStream delegate;
public GSBlobInputStream(ReadChannel channel) {
this.channel = channel;
}
public GSBlobInputStream(ReadChannel channel, long start, long end) {
this.channel = channel;
this.start = start;
this.end = end;
}
@Override
public int read() throws IOException {
init();
return delegate.read();
}
@Override
public int read(byte[] b) throws IOException {
init();
return delegate.read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
init();
return delegate.read(b, off, len);
}
/**
* Closes this input stream and releases any system resources associated with the stream.
*
* @throws IOException if an I/O error occurs.
*/
@Override
public void close() throws IOException {
if (delegate != null) {
delegate.close();
}
}
private void init() throws IOException {
if (delegate != null) {
return;
}
channel.seek(start);
delegate = Channels.newInputStream(channel);
if (end != -1) {
delegate = ByteStreams.limit(delegate, end - start + 1);
}
}
}
Note that in this approach, your will have 15MiB - 1 byte overhead in the worst case, since the default buffer size is 15MiB.