| 215 | } |
| 216 | |
| 217 | function doRead(stream: GridFSBucketReadStream): void { |
| 218 | if (stream.destroyed) return; |
| 219 | if (!stream.s.cursor) return; |
| 220 | if (!stream.s.file) return; |
| 221 | |
| 222 | const handleReadResult = (doc: Document | null) => { |
| 223 | if (stream.destroyed) return; |
| 224 | |
| 225 | if (!doc) { |
| 226 | stream.push(null); |
| 227 | |
| 228 | stream.s.cursor?.close().then(undefined, error => stream.destroy(error)); |
| 229 | return; |
| 230 | } |
| 231 | |
| 232 | if (!stream.s.file) return; |
| 233 | |
| 234 | const bytesRemaining = stream.s.file.length - stream.s.bytesRead; |
| 235 | const expectedN = stream.s.expected++; |
| 236 | const expectedLength = Math.min(stream.s.file.chunkSize, bytesRemaining); |
| 237 | if (doc.n > expectedN) { |
| 238 | return stream.destroy( |
| 239 | new MongoGridFSChunkError( |
| 240 | `ChunkIsMissing: Got unexpected n: ${doc.n}, expected: ${expectedN}` |
| 241 | ) |
| 242 | ); |
| 243 | } |
| 244 | |
| 245 | if (doc.n < expectedN) { |
| 246 | return stream.destroy( |
| 247 | new MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${doc.n}, expected: ${expectedN}`) |
| 248 | ); |
| 249 | } |
| 250 | |
| 251 | let buf = ByteUtils.isUint8Array(doc.data) ? doc.data : doc.data.buffer; |
| 252 | |
| 253 | if (buf.byteLength !== expectedLength) { |
| 254 | if (bytesRemaining <= 0) { |
| 255 | return stream.destroy( |
| 256 | new MongoGridFSChunkError( |
| 257 | `ExtraChunk: Got unexpected n: ${doc.n}, expected file length ${stream.s.file.length} bytes but already read ${stream.s.bytesRead} bytes` |
| 258 | ) |
| 259 | ); |
| 260 | } |
| 261 | |
| 262 | return stream.destroy( |
| 263 | new MongoGridFSChunkError( |
| 264 | `ChunkIsWrongSize: Got unexpected length: ${buf.byteLength}, expected: ${expectedLength}` |
| 265 | ) |
| 266 | ); |
| 267 | } |
| 268 | |
| 269 | stream.s.bytesRead += buf.byteLength; |
| 270 | |
| 271 | if (buf.byteLength === 0) { |
| 272 | return stream.push(null); |
| 273 | } |
| 274 | |