lukemin89 commented on a change in pull request #11397: [BEAM-9743] Fix 
TFRecordCodec to try harder to read/write
URL: https://github.com/apache/beam/pull/11397#discussion_r407041552
 
 

 ##########
 File path: sdks/java/core/src/main/java/org/apache/beam/sdk/io/TFRecordIO.java
 ##########
 @@ -717,14 +715,38 @@ public void write(WritableByteChannel outChannel, byte[] 
data) throws IOExceptio
       header.clear();
       header.putLong(data.length).putInt(maskedCrc32OfLength);
       header.rewind();
-      outChannel.write(header);
+      writeFully(outChannel, header);
 
-      outChannel.write(ByteBuffer.wrap(data));
+      writeFully(outChannel, ByteBuffer.wrap(data));
 
       footer.clear();
       footer.putInt(maskedCrc32OfData);
       footer.rewind();
-      outChannel.write(footer);
+      writeFully(outChannel, footer);
+    }
+
+    @VisibleForTesting
+    static void readFully(ReadableByteChannel in, ByteBuffer bb) throws 
IOException {
+      int expected = bb.remaining();
+      int actual = read(in, bb);
+      if (expected != actual) {
+        throw new IOException(String.format("expected %d, but got %d", 
expected, expected));
+      }
+    }
+
+    private static int read(ReadableByteChannel in, ByteBuffer bb) throws 
IOException {
+      int n, read = 0;
+      while (bb.hasRemaining() && (n = in.read(bb)) >= 0) {
+        read += n;
+      }
+      return read;
+    }
+
+    @VisibleForTesting
+    static void writeFully(WritableByteChannel channel, ByteBuffer buffer) 
throws IOException {
+      while (buffer.hasRemaining()) {
+        channel.write(buffer);
+      }
 
 Review comment:
   I'm not sure if I can/should make these better.
   If the channel does follow Javadoc description and keeps returning 0 without 
throwing,
   it might have an infinite loop.
   That might be channel's problem, but not sure if I have to add something 
like `retry` or hard limit.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to