Pack: Stop retrying copyAsIs when the output stream fails

When the client disconnects (e.g. Jetty EofException), isHeaderWritten
stays false and the IOException is wrapped as
StoredObjectRepresentationNotAvailableException. PackWriter then sees
otp.getOffset() == out.length() and retries with a new
representation, looping forever since the client is now gone.

Set the flag before each writeHeader call instead of after. A write
failure then happens as a plain IOException, ending the upload-pack.
Read failures before the first write still produce
StoredObjectRepresentationNotAvailableException so the concurrent
repack recovery from e682a023 is preserved.

Bug: jgit-162
Change-Id: I4bd59b9ca627968ad77afca23668b7bcf71c860d
diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java
index ad2c891..d729862 100644
--- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java
+++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java
@@ -16,6 +16,7 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.mockito.ArgumentMatchers.any;
@@ -28,6 +29,7 @@
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.time.Duration;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -928,6 +930,58 @@ private static PackIndex writePack(FileRepository repo, RevWalk walk,
 		}
 	}
 
+	// An output-stream failure during copyAsIs2 must occur as a plain
+	// IOException, not as StoredObjectRepresentationNotAvailableException.
+	// This will prevent the PackWriter to retry forever if the client is gone.
+	// The test timeout guards against that infinite loop in case of a regression.
+	@Test(timeout = 10_000)
+	public void testCopyAsIsWriteFailureThrowsIOException()
+			throws Exception {
+		FileRepository repo = createBareRepository();
+		try (TestRepository<FileRepository> testRepo = new TestRepository<>(
+				repo)) {
+			testRepo.branch("refs/heads/master").commit()
+					.add("file", "content").create();
+			testRepo.packAndPrune();
+
+			Set<ObjectId> wants = new HashSet<>();
+			for (Ref r : repo.getRefDatabase().getRefs()) {
+				wants.add(r.getObjectId());
+			}
+
+			// Let the 12-byte pack header through, then fail on
+			// the first object write inside copyAsIs2.
+			OutputStream failingStream = new OutputStream() {
+				private int remaining = 12;
+
+				@Override
+				public void write(int b) throws IOException {
+					if (--remaining < 0) {
+						throw new IOException(
+								"simulated client disconnect");
+					}
+				}
+
+				@Override
+				public void write(byte[] b, int off, int len)
+						throws IOException {
+					remaining -= len;
+					if (remaining < 0) {
+						throw new IOException(
+								"simulated client disconnect");
+					}
+				}
+			};
+
+			try (PackWriter pw = new PackWriter(repo)) {
+				NullProgressMonitor m = NullProgressMonitor.INSTANCE;
+				pw.preparePack(m, wants, NONE);
+				assertThrows(IOException.class,
+						() -> pw.writePack(m, m, failingStream));
+			}
+		}
+	}
+
 	// TODO: testWritePackDeltasCycle()
 	// TODO: testWritePackDeltasDepth()
 
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/Pack.java b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/Pack.java
index bf574ec..77d8994 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/Pack.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/Pack.java
@@ -434,7 +434,10 @@ private void copyAsIs2(PackOutputStream out, LocalObjectToPack src,
 		final CRC32 crc2 = validate ? new CRC32() : null;
 		final byte[] buf = out.getCopyBuffer();
 
-		boolean isHeaderWritten = false;
+		// Set before the first write to out.
+		// A failure after this point is an output-stream error,
+		// not a missing object, and must not be retried.
+		boolean isWriteStarted = false;
 		// Rip apart the header so we can discover the size.
 		//
 		try {
@@ -567,8 +570,8 @@ private void copyAsIs2(PackOutputStream out, LocalObjectToPack src,
 				// The entire object fits into a single byte array window slice,
 				// and we have it pinned.  Write this out without copying.
 				//
+				isWriteStarted = true;
 				out.writeHeader(src, inflatedLength);
-				isHeaderWritten = true;
 				quickCopy.write(out, dataOffset, (int) dataLength);
 
 			} else if (dataLength <= buf.length) {
@@ -585,8 +588,8 @@ private void copyAsIs2(PackOutputStream out, LocalObjectToPack src,
 						cnt -= n;
 					}
 				}
+				isWriteStarted = true;
 				out.writeHeader(src, inflatedLength);
-				isHeaderWritten = true;
 				out.write(buf, 0, (int) dataLength);
 			} else {
 				// Now we are committed to sending the object. As we spool it out,
@@ -603,15 +606,15 @@ private void copyAsIs2(PackOutputStream out, LocalObjectToPack src,
 						crc2.update(buf, 0, n);
 					}
 					cnt -= n;
-					if (!isHeaderWritten) {
+					if (!isWriteStarted) {
 						if (invalid && cnt > 0) {
 							// Since this is not the last iteration and the packfile is invalid,
 							// better to assume the iterations will not all complete here while
 							// it is still likely recoverable.
 							throw new StoredObjectRepresentationNotAvailableException(invalidatingCause);
 						}
+						isWriteStarted = true;
 						out.writeHeader(src, inflatedLength);
-						isHeaderWritten = true;
 					}
 					out.write(buf, 0, n);
 					pos += n;
@@ -626,7 +629,7 @@ private void copyAsIs2(PackOutputStream out, LocalObjectToPack src,
 				}
 			}
 		} catch (IOException ioError) {
-			if (!isHeaderWritten) {
+			if (!isWriteStarted) {
 				throw new StoredObjectRepresentationNotAvailableException(ioError);
 			}
 			throw ioError;