Skip to content

Commit c267c85

Browse files
committed
PHPLIB-241: Delete orphan chunks if GridFS upload fails
1 parent 6676e7e commit c267c85

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

src/GridFS/WritableStream.php

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use MongoDB\BSON\Binary;
66
use MongoDB\BSON\ObjectId;
77
use MongoDB\BSON\UTCDateTime;
8+
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
89
use MongoDB\Exception\InvalidArgumentException;
910
use MongoDB\Exception\RuntimeException;
1011

@@ -175,7 +176,12 @@ public function writeBytes($data)
175176

176177
private function abort()
177178
{
178-
$this->collectionWrapper->deleteChunksByFilesId($this->file['_id']);
179+
try {
180+
$this->collectionWrapper->deleteChunksByFilesId($this->file['_id']);
181+
} catch (DriverRuntimeException $e) {
182+
// We are already handling an error if abort() is called, so suppress this
183+
}
184+
179185
$this->isClosed = true;
180186
}
181187

@@ -191,7 +197,13 @@ private function fileCollectionInsert()
191197
$this->file['length'] = $this->length;
192198
$this->file['md5'] = $md5;
193199

194-
$this->collectionWrapper->insertFile($this->file);
200+
try {
201+
$this->collectionWrapper->insertFile($this->file);
202+
} catch (DriverRuntimeException $e) {
203+
$this->abort();
204+
205+
throw $e;
206+
}
195207

196208
return $this->file['_id'];
197209
}
@@ -218,7 +230,14 @@ private function insertChunkFromBuffer()
218230

219231
hash_update($this->ctx, $data);
220232

221-
$this->collectionWrapper->insertChunk($chunk);
233+
try {
234+
$this->collectionWrapper->insertChunk($chunk);
235+
} catch (DriverRuntimeException $e) {
236+
$this->abort();
237+
238+
throw $e;
239+
}
240+
222241
$this->length += strlen($data);
223242
$this->chunkOffset++;
224243
}

0 commit comments

Comments
 (0)