We are going to design a durable upload pipeline that supports:
Resumable uploads: Allow large files to be uploaded in parts and resumed from the last successful part.
Checksums: Verify the integrity of each part and the whole file.
Lifecycle: Manage the lifecycle of uploads (e.g., cleanup of incomplete uploads after a certain time).
We'll break down the system into components:
Client: Uploads the file in parts, and can resume.
Server: Handles the upload requests, stores parts, and assembles the final file.
Storage: Stores the uploaded parts and the final file.
Metadata Store: Keeps track of upload sessions, parts, and checksums.
Steps:
Initiate an upload:
Client requests to upload a file (with metadata: file name, size, etc.)
Server generates a unique upload ID and returns it to the client.
Server stores an upload session record in the metadata store (with status: "in-progress", file info, and expiration time).
Upload parts:
Client uploads each part (e.g., 5MB each) with:
upload_id
part_number
data
checksum of the part (e.g., MD5 or SHA256)
Server:
Verifies the checksum of the received part.
Stores the part in a temporary storage (with a name that includes upload_id and part_number).
Records the part in the metadata store (with part number, checksum, and storage location).
Complete the upload:
After all parts are uploaded, client sends a complete request with:
upload_id
list of part numbers (in order)
optional: overall file checksum (e.g., of the entire file) for final verification.
Server:
Verifies that all parts are present and their checksums match (from the metadata store).
Assembles the parts in order into the final file in the permanent storage.
Computes the overall checksum of the assembled file and compares with the client-provided one (if provided).
Updates the upload session status to "completed" and records the final file location.
Deletes the temporary parts (or marks them for deletion).
Resuming an upload:
If the client loses connection, it can resume by:
Requesting the status of an upload (by upload_id) to get the list of already uploaded parts.
Then continue uploading the missing parts.
Lifecycle management:
We need a background process that periodically checks for upload sessions that have been in-progress for too long (e.g., 24 hours) and aborts them.
When aborting, we delete the temporary parts and remove the session record.
Abort an upload:
Client can also explicitly abort an upload by sending an abort request with the upload_id.
Server then deletes the temporary parts and marks the session as aborted.
Implementation considerations:
Storage: We can use a distributed file system (like HDFS, S3) for storing parts and final files. Or we can use a database with BLOBs for small parts, but for large files we need file storage.
Metadata Store: Use a database (SQL or NoSQL) to store:
upload_sessions: (upload_id, file_name, file_size, status, created_at, updated_at, expires_at, final_file_location)
upload_parts: (upload_id, part_number, checksum, storage_location, uploaded_at)
For checksums, we can use MD5 for parts (but note: MD5 is broken for cryptographic security, but for integrity it's still widely used and fast). For the whole file, we might want a stronger one (like SHA256) but it depends on the use case.
For resumable uploads, we need to ensure that the same part is not uploaded twice (or if it is, we can skip if checksum matches). We can design the server to accept a part only if it hasn't been uploaded yet, or if it's uploaded again and the checksum matches, we can ignore the duplicate.
We must handle concurrent uploads of the same part? We can use versioning or just overwrite? But note: if two clients are resuming the same upload (which shouldn't happen because upload_id should be secret) then we have a problem. So we assume that only one client has the upload_id.
Security: The upload_id should be long and random to avoid guessing. Also, we might want to authenticate the client for each request (but for simplicity, we assume the upload_id is secret).
Performance: Storing each part as a separate file might lead to too many small files. We can combine small parts? But that complicates resumability. Alternatively, we can have a limit on part size (minimum 5MB) and then for the last part it can be smaller.
GET /upload/status?upload_id=uuid
Response: { "status": "in-progress", "uploaded_parts": [1,3,4] } // list of part numbers already uploaded
POST /upload/abort?upload_id=uuid
Response: { "status": "aborted" }
(Background) Lifecycle cleanup: runs periodically and aborts old in-progress uploads.
Now, let's think about the server logic for each endpoint:
Initiate:
Generate a UUID for upload_id.
Calculate the number of parts: ceil(file_size / part_size)
Store in upload_sessions: (upload_id, file_name, file_size, part_size, status='in-progress', created_at=now, expires_at=now+24h)
Return upload_id and part_size.
Upload part:
Check if the upload session exists and is in-progress.
Check if the part number is between 1 and total_parts (we can store total_parts in the session? or calculate from file_size and part_size).
Calculate the checksum of the uploaded part.
Store the part in a temporary directory (or object storage) with a key: {upload_id}/{part_number}
Record in upload_parts: (upload_id, part_number, checksum, storage_location, uploaded_at=now)
Return the checksum.
Complete:
Check if the upload session exists and is in-progress.
Check that the list of part_numbers matches the expected parts (and in order? we assume the client sends in order, but we can sort?).
For each part_number in the list, check that we have a record in upload_parts and the checksum matches (we already stored it when uploaded, but we can recompute to be safe? or trust our stored checksum?).
If any part is missing or checksum mismatch, return error.
If the client provided a file_checksum, then after assembling the file, compute the checksum and compare.
Assemble the parts: read each part in order and write to the final file location.
Update the upload session: status='completed', final_file_location=..., updated_at=now.
Delete the temporary parts (or mark for deletion, and let a separate process clean up? but we want to free space immediately).
Status:
Return the list of part_numbers that have been uploaded for this upload_id.
Abort:
Mark the session as aborted and delete all the temporary parts.
Lifecycle cleanup:
Query for sessions with status='in-progress' and expires_at < now, then for each:
Delete all parts for that upload_id from storage.
Update session status to 'aborted' (or delete the session record?).
Additional considerations:
We must handle the case where the client sends the same part multiple times (due to retries). We can check if the part already exists and if the checksum matches, then we can return success without storing again.
For the complete step, we need to be cautious about the assembly. We can read the parts in parallel? But the parts are stored separately and we need to write in order. So we might read sequentially and write to the final file.
If the file is very large, we might not want to assemble on the server (because it requires a lot of disk space and I/O). Alternatively, we can have the final file stored as a concatenation of parts in object storage (like S3 multipart upload) and then just create a manifest. But if we are using a file system, we have to copy.
If we are using object storage (like S3), we can use their multipart upload API and then just complete it. But then we are relying on S3's durability and resumability. However, the requirement is to build our own pipeline, so we assume we are storing parts in our own storage.
We must also consider that the client might send parts out of order. Our design does not require order for uploading, but for completion we require the list of part numbers in order? Actually, the client can send the parts in any order, and then when completing, we require the list of all part numbers in sorted order? Or we can accept the parts in any order and then when completing, we sort the list? But note: the client must know the total number of parts and the part numbers. We can return the total number of parts in the initiate response? Alternatively, we can compute from file_size and part_size.
Let's change the initiate response to also include the total number of parts.
Then when completing, the client must provide a list of all part numbers from 1 to total_parts? Or at least the parts that were uploaded? But we want to ensure no missing parts.
We can change the complete request to not require the list of part numbers? Instead, we can look up all parts for this upload_id and then check if we have all from 1 to total_parts. But then the client could just say "I'm done" and we check we have all parts. However, the client might have uploaded only some parts and then wants to complete? That would be an error.
So in the complete request, we don't need the list of part numbers? We can just have the client say "I have uploaded all parts" and then we check we have all parts from 1 to total_parts. But what if the client missed a part? Then we would be missing that part. So we can:
Option 1: Client sends the list of part numbers they uploaded (which must be exactly the set of 1..total_parts). We verify that the set is complete and then assemble.
Option 2: Server has the list of parts that were successfully uploaded (from the upload_parts table) and then we check that we have all parts from 1 to total_parts.
I think Option 2 is simpler for the client. But then the client must ensure they uploaded all parts. If they missed one, then the complete will fail because we don't have that part in our table.
So in the complete request, we only need the upload_id and optionally the file_checksum.
However, what if the client uploaded a part twice? Then we might have duplicate part numbers? We should not allow duplicate part numbers for the same upload_id. So when uploading a part, if we already have that part number and the checksum matches, we can return success and not store again. If the checksum doesn't match, then we have a problem (maybe the client sent a different version of the same part). We can reject the part if the checksum doesn't match the stored one? Or we can overwrite? But if we overwrite, then the previously stored part is lost and we break the consistency. So we should not allow overwriting a part with a different checksum. We should reject the upload of the same part number with a different checksum.
So in the upload part endpoint, if the part number already exists in the upload_parts for that upload_id, we compare the checksum. If same, return success. If different, return error.
Then in the complete, we just check that we have all part numbers from 1 to total_parts.
But wait: what if the client uploaded extra parts (part numbers beyond total_parts)? That should not happen because the client knows total_parts from the initiate response. We can ignore any part beyond total_parts? Or reject? We can reject during upload if the part_number > total_parts.
So we must store total_parts in the session.
Steps for complete:
Look up the upload session by upload_id. If not found or not in-progress, error.
Check that we have exactly total_parts parts in the upload_parts table for this upload_id? Actually, we must have all from 1 to total_parts. We can query for part_numbers where upload_id = ? and then check that the set is {1,2,...,total_parts}.
If any part is missing, error.
Then assemble the parts in order (1 to total_parts) to the final file.
If file_checksum is provided, compute the checksum of the final file and compare.
Update the session to completed and store the final file location.
Delete the temporary parts.
However, note: the client might have uploaded a part with a wrong checksum? But we already checked the checksum when uploading each part. So we trust the stored checksums? But what if the stored part got corrupted? We can recompute the checksum of each stored part during assembly and compare with the stored checksum. That would be safer.
So during assembly, for each part we read from storage, we compute the checksum and compare with the stored one. If any mismatch, we abort the assembly and return error.
Alternatively, we can do:
For each part in order:
Read the part from storage.
Compute its checksum.
Compare with the stored checksum (from upload_parts). If mismatch, error.
Write the part to the final file.
Then after writing all parts, if file_checksum is provided, compute the final file's checksum and compare.
This way we verify every part again during assembly.
But note: if the storage is reliable (like a distributed file system with checksums) then we might skip per-part verification? But it's better to be safe.
Now, about the part storage:
We are storing each part as a separate file. The storage location in the upload_parts table can be the path or key.
We must ensure that the storage for parts is on a disk that has enough space and that we clean up after completion or abortion.
Table: upload_parts
id (PK, auto increment)
upload_id (FK to upload_sessions.upload_id)
part_number
checksum (the checksum of the part, e.g., MD5)
storage_location (the path to the part file)
uploaded_at
We create an index on upload_parts(upload_id, part_number) to quickly check for existing parts.
Now, the code structure for the server:
We assume we have a storage service (like a local file system or S3) and a database.
We'll have:
class UploadService:
def init(self, db, storage):
self.db = db
self.storage = storage
code
def initiate_upload(self, file_name, file_size, part_size=None):
# generate upload_id
# calculate total_parts = ceil(file_size / part_size)
# store in upload_sessions
# return upload_id, part_size, total_parts
def upload_part(self, upload_id, part_number, data):
# check session exists and is in-progress
# check part_number is between 1 and total_parts (from session)
# compute checksum of data
# check if part already exists for this upload_id and part_number
# if exists and checksum matches, return success (without storing again)
# if exists and checksum mismatch, return error
# else, store the part in storage (with key: f"{upload_id}/{part_number}")
# record in upload_parts
# return checksum
def complete_upload(self, upload_id, file_checksum=None):
# get session
# check status is in-progress
# get all parts for this upload_id from upload_parts
# check that we have exactly total_parts parts and they are numbered 1..total_parts
# for part_number in 1..total_parts:
# get part record
# read part from storage using storage_location
# compute checksum of the read data
# if not equal to stored checksum, raise error
# write the part to the final file (in order)
# after writing all parts, if file_checksum is provided, compute final file checksum and compare
# update session to completed and set final_file_location
# delete all parts (from storage and from upload_parts table? or just delete the storage and then delete the records? We can delete the records because we don't need them anymore)
# return final file location
def get_upload_status(self, upload_id):
# return the list of part_numbers that are uploaded (from upload_parts) and the session status.
def abort_upload(self, upload_id):
# delete all parts from storage (for this upload_id)
# delete all upload_parts records for this upload_id
# update session to aborted
Then we have a background job:
code
def cleanup_old_uploads():
# find sessions with status in-progress and expires_at < now
# for each, call abort_upload
But note: when we abort, we delete the parts and the records. So the abort_upload function should do:
- Delete the storage for each part (using the storage_location from upload_parts)
- Delete the upload_parts records for that upload_id
- Update the session to aborted.
However, in the complete_upload, we are deleting the parts and the records as well? Yes, because after successful completion we don't need the parts anymore.
So in complete_upload, after assembling the file, we delete the parts and the records. Then we update the session.
But wait: if the assembly fails in the middle, we should not delete the parts? We should leave them so that we can retry? So we must be cautious.
In complete_upload, we are reading each part and verifying its checksum. If any part fails, we raise an error and do not delete the parts. The client can then retry the complete? But if the part is corrupted, then the client must re-upload that part? Actually, the client cannot re-upload the same part because we already have that part number and the checksum mismatch? But the client can upload the same part number again with the correct data? But our upload_part endpoint will reject if the part number already exists with a different checksum? Actually, we allow re-uploading the same part only if the checksum matches? That doesn't help if the stored part is corrupted.
So we have two options:
Option 1: In the upload_part endpoint, if the part already exists and the checksum mismatch, we allow overwriting? But then we break the previous part? But if the stored part is corrupted, we want to replace it. However, what if the client sends a different version of the same part? That would be a mistake. But the client should not re-upload a part that they already uploaded successfully. So we can allow overwriting only if the part is already present and the checksum is different? That would mean the client is trying to fix a corrupted upload? But the client doesn't know the stored checksum? The client only knows the checksum of the data they are sending.
Actually, the client sends the checksum of the part. So if the client sends the same part again, the checksum will be the same. If the stored part is corrupted (so the stored checksum is different from the original) then the client would send the same part (same checksum) and we would see that the stored part has a different checksum? But we stored the checksum when the part was first uploaded. If the storage corrupted the part, then the stored checksum (which we computed at upload time) is the correct one, but the actual data is corrupted? That's a problem because we computed the checksum on the data we received and stored it. Then if the storage corrupts the data, the checksum we stored is still the original one, but the data is different. So when we read the part during assembly, we compute the checksum of the corrupted data and it won't match the stored checksum. So we catch the corruption.
But then the client cannot fix it because they cannot re-upload the same part? Because when they try to upload the same part (with the same checksum) we will see that the part already exists and the stored checksum (which is the original) matches the one they are sending? But wait, the stored checksum is the original one, and the client is sending the original part (same checksum) so we would think it's the same and not overwrite? But the stored data is corrupted. So we need to overwrite the corrupted part with the correct one.
How can we allow that? We can change the upload_part to:
code
If the part already exists:
If the stored checksum == the new checksum, then do nothing (return success).
Else (stored checksum != new checksum), then overwrite the storage and update the checksum in the database.
But then we are allowing the client to overwrite a part with a different checksum. That is dangerous because maybe the client made a mistake and is sending a different part? But the client is resuming and they think they are sending the same part? They have the same part number and the same data, so the checksum should be the same. If the checksum is different, then the client is sending a different part. That might be an error.
Alternatively, we can have a version number for each part? Or we can have the client send a part only once? But then if the part gets corrupted in storage, we cannot fix it.
Given the complexity, maybe we assume that the storage is reliable and we don't expect corruption. So we don't allow overwriting. Then if a part gets corrupted, the entire upload is doomed and the client must start over.
But in reality, storage can fail. So we need a way to recover.
Another idea: when the client resumes, they get the list of uploaded parts and their checksums (from the server). Then if the client wants to re-upload a part, they can only do so if the server's stored checksum does not match the one the client has? But the client doesn't have the stored checksum? They only have the checksum of the data they have.
Actually, in the status response, we can return the checksums of the uploaded parts. Then the client can compare. If the client has a part with a different checksum than what the server has, then the client can re-upload that part? But then we are allowing the client to overwrite with a different checksum? That's the same issue.
Alternatively, we can have a rule: the client can only upload a part if the server does not have that part number, or if the server has that part number but the checksum matches (then skip). If the server has that part number and the checksum doesn't match, then we consider that part as missing (because the stored part is corrupted) and allow the client to upload again? But then we are overwriting with a different checksum.
Given the trade-offs, I think we should allow overwriting if the checksum is different. Because if the stored part is corrupted, we want to replace it. And if the client accidentally sends a different part (with a different checksum) then they are fixing a mistake? But wait, the client should not change the part. So if the client changes the part, then the file is different. But the client is the one who knows the original file. So if they change a part, then the final file will be different. So we must trust the client to upload the correct parts.
So we can allow overwriting. But then we must also update the stored checksum.
So in upload_part:
code
existing_part = db.get_part(upload_id, part_number)
if existing_part:
if existing_part.checksum == new_checksum:
return # already have the same part
else:
# overwrite: delete the old part from storage, store the new part, update the checksum in the database.
else:
# store new part and record.
Then during complete, we verify each part's checksum again (by reading from storage) and if any part's stored checksum doesn't match the data we read, then we have a problem (corruption after upload). But then we cannot fix because the client doesn't have the part anymore? Actually, the client might have the part and can re-upload? But the complete is the last step. So if we find a corruption during complete, we should abort the complete and let the client retry the complete? But the client doesn't have the part? They do because they just uploaded it.
Wait, the corruption could happen after the upload. So the client uploaded the part, we stored it, and then the storage corrupted it. Then when we read it during complete, the checksum doesn't match. Then we should tell the client that part X is corrupted and they need to re-upload it? But the client doesn't know which part is corrupted? We can return which part failed.
Alternatively, we can re-verify each part during complete and if one fails, we abort the complete and return an error with the part number. Then the client can re-upload that part and then complete again.
So in complete_upload:
code
for part_number in 1..total_parts:
part_record = db.get_part(upload_id, part_number)
if not part_record:
error: missing part
data = storage.read(part_record.storage_location)
computed_checksum = checksum(data)
if computed_checksum != part_record.checksum:
error: part corrupted, please re-upload part part_number
write to final file.
Then if any part is corrupted, we abort the complete and the client must re-upload that part and then complete again.
But note: the client might have uploaded the part correctly, but the storage corrupted it. So we need a way to recover. So we must allow the client to re-upload a part even if we already have it (with a different checksum). But in the upload_part endpoint, we already allow overwriting if the checksum is different. So the client can re-upload the same part (with the same data, same checksum) and we will see that the stored checksum is different (because the stored data is corrupted and we stored the original checksum) and then we overwrite.
But wait: when we first uploaded the part, we stored the checksum of the data we received. If the storage corrupts the data, then the stored checksum (in the database) is still the original one, but the data is different. So when the client re-uploads the same part (with the same checksum) we will see that the stored checksum (original) matches the new checksum (same as original) and then we would not overwrite? Because we check: if existing_part.checksum == new_checksum then skip. But the stored checksum is the original, and the new checksum is the same as the original, so we skip and don't overwrite. Then we still have the corrupted data.
So we have a problem: we cannot distinguish between a part that was stored correctly and a part that was stored and then corrupted? Because the stored checksum is the same as the original.
Therefore, we must not trust the stored checksum for the integrity of the stored data. We must recompute the checksum of the stored data when we read it.
So in the upload_part endpoint, when we store the part, we compute the checksum of the data we received and store that checksum. But then we don't verify the storage at that time. So if the storage corrupts the data immediately, we won't know until complete.
Then during complete, we read the data and compute the checksum. If it doesn't match the stored checksum, we know the stored data is corrupted. Then we can tell the client to re-upload that part.
But then the client will re-upload the same part (with the same checksum) and we will see that the stored checksum (which is the original) matches the new checksum? Yes, so we will skip overwriting? Because we check: if existing_part.checksum == new_checksum, then we skip. But we want to overwrite because the stored data is corrupted.
So we need to change the logic in upload_part:
code
We don't trust the stored checksum to indicate that the stored data is correct. We only trust the stored checksum as the expected checksum for that part.
When a part is uploaded:
Compute the checksum of the uploaded data (C1).
Check if we already have a part with the same part_number for this upload_id.
If we do:
If the stored checksum == C1, then the stored data is expected to be correct? Not necessarily, because the stored data might be corrupted but the stored checksum is still C1. So we cannot skip.
So we must always store the new data and update the checksum? But then we are overwriting even if the stored data is correct? That's wasteful.
Alternatively, we can read the stored data and compute its checksum to see if it's still correct? But that would be expensive.
Given the complexity, maybe we assume that the storage is reliable and we don't expect corruption. Then we can trust the stored checksum and skip re-uploading if the checksum matches.
But if we want to be safe against storage corruption, we need to verify the stored data when we read it (during complete) and if it's corrupted, then we must allow the client to re-upload that part even if the stored checksum matches the client's checksum.
So in upload_part, we should not skip based on the stored checksum. Instead, we should always store the new data and update the checksum? But then we are overwriting even if the stored data is correct. That might be acceptable if we want to ensure that the stored data is exactly what the client last sent. But then if the client sends the same part twice (with the same checksum) we are overwriting with the same data? That's inefficient.
Alternatively, we can change the logic:
code
When a part is uploaded:
Compute the checksum of the uploaded data (C1).
If we already have a part with the same part_number:
Read the stored data and compute its checksum (C2).
If C2 == C1, then the stored data is correct and the same as the new data, so skip.
Else, overwrite the stored data with the new data and update the stored checksum to C1.
Else:
Store the data and record the checksum C1.
This way, we verify the stored data's integrity at the time of re-upload. But this requires reading the stored data for every re-upload, which is expensive.
Given the trade-offs, and since we expect that re-uploads are rare (only when resuming after a failure), we can do:
code
If the part already exists:
If the stored checksum == new_checksum, then assume the stored data is correct and skip.
Else, overwrite.
But then we are vulnerable to the scenario where the stored data is corrupted but the stored checksum is still the same as the original? Actually, if the stored data is corrupted, then the stored checksum (which was computed on the original data) is not the same as the corrupted data's checksum. But we are comparing the stored checksum (original) with the new checksum (which is the same as the original). So they match, and we skip, even though the stored data is corrupted.
So the only way to detect corruption is to read the stored data and compute its checksum. But we don't do that in the upload_part endpoint because we assume that if the stored checksum matches the new checksum, then the stored data is the same as the original? Not necessarily, because two different data can have the same checksum? But we are using a cryptographic hash (like SHA256) so it's very unlikely. But if the storage corrupts the data, it's unlikely to have the same SHA256.
However, if the storage corrupts the data in a way that changes the bits but the SHA256 remains the same? That's a hash collision, which is extremely unlikely for SHA256.
So we can rely on the stored checksum to be a fingerprint of the original data. If the stored data is corrupted, the chance that the corrupted data has the same SHA256 is negligible.
Therefore, we can skip re-uploading if the stored checksum matches the new checksum.
So the logic in upload_part becomes:
code
existing = db.get_part(upload_id, part_number)
if existing:
if existing.checksum == new_checksum:
return # already have the same part, skip storage
else:
# overwrite
storage.delete(existing.storage_location)
storage.store(new_data, new_key)
db.update_part(upload_id, part_number, new_checksum, new_key)
else:
storage.store(new_data, new_key)
db.create_part(upload_id, part_number, new_checksum, new_key)
And during complete, we read each part and compute the checksum. If it doesn't match the stored checksum, then we have a corruption that happened after upload. Then we return an error for that part.
But note: if the corruption happened during the initial upload (so we stored a corrupted part but with the correct checksum? That's impossible because we computed the checksum on the received data. If the data was corrupted during the upload (network corruption) then the checksum would be different and we would have rejected the upload? Actually, we compute the checksum on the received data. If the network corrupted the data, then the received data is corrupted and the checksum we compute is for the corrupted data. Then we store that corrupted data and the corrupted checksum. Then during complete, we read the corrupted data and compute the same corrupted checksum (if the storage doesn't corrupt it further) and it matches the stored checksum. So we accept it. But that's because the client sent corrupted data. We cannot protect against that.
So the checksum only protects against corruption in storage after upload, not during the upload.
To protect against corruption during upload, we need the client to compute the checksum of the original file and send it, and then we compute the checksum of the assembled file and compare. That will catch if any part was corrupted during upload (because the assembled file's checksum won't match).
So we should require the client to provide the overall file checksum (of the original file) and then after assembling, we compute the checksum and compare. That will catch if any part was corrupted during upload (or if the client uploaded a wrong part).
Therefore, we change the complete request to require the file_checksum? Or make it optional? If provided, we verify. If not provided, we don't.
But then if the client doesn't provide the overall checksum, we cannot verify the entire file.
So we should make it required? But what if the client cannot compute the checksum (e.g., streaming from a source that doesn't allow seeking to compute)? Then we can skip.
We can make it optional and warn if not provided.
But for durability, we want to verify the entire file.
So let's change the initiate request to optionally accept the overall file checksum? Or the client can send it at complete time.
We'll do:
code
complete_upload(upload_id, file_checksum=None)
If file_checksum is provided, we compute the checksum of the assembled file and compare.
Now, about the assembly:
code
We read each part in order and write to the final file. We also compute the checksum of the final file as we write (streaming). Then at the end, compare with file_checksum.
But note: if the file is very large, we don't want to read it twice (once for assembly and once for checksum). So we can compute the checksum while writing.
Steps for assembly with checksum:
code
open final_file for writing
for part_number in 1..total_parts:
part_record = get_part(upload_id, part_number)
data = storage.read(part_record.storage_location)
computed_part_checksum = checksum(data)
if computed_part_checksum != part_record.checksum:
raise PartCorruptedError(part_number)
final_file.write(data)
# update overall_checksum with data
final_file.close()
if file_checksum:
overall_checksum = final_file_checksum (computed during writing)
if overall_checksum != file_checksum:
raise FileChecksumMismatchError
Alternatively, we can compute the overall checksum by reading the entire final file after assembly? But that would read the file twice. So we compute as we write.
Now, what about the storage for the final file? We can store it in the same storage as the parts? Or a different location.
We'll assume the storage service has a method to store a file and return a location.
We'll also need to handle the case where the final file is very large and we are writing it sequentially. We can stream the parts and write to the final file without loading the entire file in memory.
Now, let's write the code for the endpoints.
We'll use Flask for example, but the design is framework agnostic.
We assume we have a database and storage service.
We'll also need to handle errors and rollback if the complete fails.
In complete_upload, if any part fails (missing or checksum mismatch) we abort and don't delete the parts. If the file_checksum fails, we also abort and don't delete the parts? But we already wrote the final file? We should delete the final file if we fail? Or we can write to a temporary file and then rename on success.
Steps for complete_upload:
code
session = db.get_session(upload_id)
if not session or session.status != 'in-progress':
return error
total_parts = session.total_parts
# Check we have all parts
parts = db.get_parts(upload_id) # returns list of part records
if len(parts) != total_parts:
return error: missing parts
# Check part numbers are 1..total_parts
part_numbers = set(p.part_number for p in parts)
if part_numbers != set(range(1, total_parts+1)):
return error: missing or extra parts
# Create a temporary file for the final file
temp_final_path = storage.get_temp_path()
try:
with open(temp_final_path, 'wb') as final_file:
overall_hasher = hashlib.sha256() # or whatever algorithm
for part_number in range(1, total_parts+1):
part_record = db.get_part(upload_id, part_number)
data = storage.read(part_record.storage_location)
# Verify part checksum
part_hasher = hashlib.sha256()
part_hasher.update(data)
if part_hasher.hexdigest() != part_record.checksum:
raise PartCorruptedError(part_number)
final_file.write(data)
overall_hasher.update(data)
if file_checksum:
if overall_hasher.hexdigest() != file_checksum:
raise FileChecksumMismatchError
# Success: move the temporary file to the final location
final_location = storage.get_final_location(session.file_name)
storage.move(temp_final_path, final_location)
# Update session
session.status = 'completed'
session.final_file_location = final_location
session.updated_at = now
db.update_session(session)
# Delete parts
for part in parts:
storage.delete(part.storage_location)
db.delete_parts(upload_id)
return final_location
except Exception as e:
# If any error, delete the temporary file and reraise
storage.delete(temp_final_path)
raise
But note: we are reading each part into memory? That might be too much for large parts. We should stream the part from storage and write to the final file in chunks.
We change:
code
with open(temp_final_path, 'wb') as final_file:
overall_hasher = hashlib.sha256()
for part_number in range(1, total_parts+1):
part_record = db.get_part(upload_id, part_number)
# Stream the part from storage
with storage.read_stream(part_record.storage_location) as part_stream:
part_hasher = hashlib.sha256()
while True:
chunk = part_stream.read(8192)
if not chunk:
break
part_hasher.update(chunk)
final_file.write(chunk)
overall_hasher.update(chunk)
if part_hasher.hexdigest() != part_record.checksum:
raise PartCorruptedError(part_number)
This way we don't load the entire part in memory.
Now, about the storage service:
code
We assume it has:
store(key, data) # for storing a part (data is bytes or a file-like object)
read(key) -> bytes # for reading a part (if the part is small) or we can use read_stream
read_stream(key) -> context manager that yields a file-like object
delete(key)
get_temp_path() -> a path for a temporary file (if we are using file system) or we can use a temporary file in the same storage? We are using the storage service for both parts and final file? We can use the same storage.
But if we are using object storage (like S3) then we cannot create a temporary file on the local disk? We can write the final file to a temporary key and then copy to the final key? Or we can use multipart upload for the final file? But we are assembling from parts that are already stored.
Alternatively, we can assemble by downloading each part and uploading the final file? That would be network intensive.
If we are using the same storage (like a file system) then we can write to a temporary file and then rename.
If we are using object storage (like S3) then we might not have a temporary file. We can:
Option 1: Download each part to the server, assemble in memory or on local disk, then upload the final file. But that requires the server to have enough disk space.
Option 2: Use the storage's multipart upload to assemble the parts without downloading. But then we are limited by the storage's own multipart upload limits (like max parts, etc.)
Since we are building our own pipeline, we assume we have control over the storage and we can read and write arbitrarily.
Given the complexity, let's assume we are using a file system for storage and we have enough disk space.
Now, the background job for cleanup:
code
We run a periodic task (every hour) that:
sessions = db.get_sessions_with_status_and_expiry('in-progress', now - 24h)
for session in sessions:
# abort the session (delete parts and update status)
parts = db.get_parts(session.upload_id)
for part in parts:
storage.delete(part.storage_location)
db.delete_parts(session.upload_id)
session.status = 'aborted'
session.updated_at = now
db.update_session(session)
But note: we already have an abort_upload function. We can reuse that.
So:
code
def cleanup_old_uploads():
old_sessions = db.get_in_progress_sessions_expired_before(now - timedelta(hours=24))
for session in old_sessions:
try:
abort_upload(session.upload_id)
except Exception as e:
log error and continue
Now, we must also consider that the client might abandon an upload and we want to clean up. The expires_at is set to now+24h in the initiate. We update the expires_at on every upload_part? Or on every successful part upload? We can update the expires_at to now+24h on every successful part upload? That way, as long as the client is actively uploading, the session doesn't expire.
So in upload_part, after successfully storing a part, we update the session's expires_at to now+24h.
Similarly, in get_upload_status, we can also update the expires_at? Maybe not, because just checking status doesn't mean the client is active. We only update on upload_part and complete? And maybe on initiate? But initiate is the first request.
Alternatively, we can set a fixed expiration from the initiate time (24 hours) and not update. Then if the client takes more than 24 hours, we abort. That might be acceptable.
But if the client is actively uploading, we want to extend the lifetime. So we update the expires_at on every successful part upload.
So in upload_part:
code
after storing the part and updating the db for the part, also update the session's expires_at to now+24h.
Now, what about the complete request? We don't update the expires_at because the upload is about to complete.
Now, let's write the code for the endpoints.
We'll use Flask and SQLAlchemy for example.
But note: the question asks for a design, not full code. So we can write pseudocode.
However, the question says "Build a durable upload pipeline", so we need to provide a design and maybe some code structure.
POST /upload/abort?upload_id=uuid
Response: { "status": "aborted" }
And the background cleanup job.
Now, we must also consider:
Authentication and authorization: We assume the upload_id is secret and the client must present it to perform operations. We might also want to associate the upload with a user.
Rate limiting: To prevent abuse.
Monitoring: We should log uploads and failures.
Scalability: The metadata store and storage must scale. We can shard by upload_id? Or use a distributed database.
Idempotency: The upload_part endpoint should be idempotent (same part uploaded multiple times with same checksum should be safe).
We are using checksums for integrity, but we are not using TLS? We assume the transport is secure? If not, we should use HTTPS.
That's the design.
Now, let's write some code structure in Python (using Flask and SQLAlchemy) to illustrate:
We assume we have:
code
db = SQLAlchemy()
storage = StorageService() # abstract class with methods: store, read, read_stream, delete, get_temp_path, move
def cleanup_old_uploads():
with app.app_context():
cutoff = datetime.utcnow() - timedelta(hours=24)
old_sessions = UploadSession.query.filter(
UploadSession.status == 'in-progress',
UploadSession.expires_at < cutoff
).all()
for session in old_sessions:
try:
upload_service.abort_upload(session.upload_id)
except Exception as e:
app.logger.error(f'Failed to abort upload {session.upload_id}: {e}')
We can schedule this job with a cron or a background thread.
This is a basic design. We might need to handle:
Concurrency: multiple clients trying to upload the same part? We use database constraints to prevent duplicate part numbers for the same upload_id? But we allow overwriting. So we don't have a unique constraint on (upload_id, part_number) because we want to update the same part. But then we cannot have two concurrent uploads of the same part? We can use a lock? Or we can rely on the database update to be atomic? We are using SQLAlchemy and we are updating the part if it exists. But two concurrent requests might both read the existing part, then both try to update? One will succeed and the other will fail due to the unique constraint? We have a unique constraint on (upload_id, part_number). So if two requests try to update the same part, one will succeed and the other will get an integrity error. Then we can catch that and retry? Or we can use SELECT FOR UPDATE.
Alternatively, we can remove the unique constraint and allow multiple records for the same part_number? That would be bad because we only want one part per number.
So we keep the unique constraint. Then in upload_part, we do:
code
existing_part = UploadPart.query.filter_by(upload_id=upload_id, part_number=part_number).first()
if existing_part:
if existing_part.checksum == checksum:
... skip ...
else:
... delete old and insert new ...
else:
... insert new ...
But if two requests come at the same time for the same part_number, both might read that there is no existing part (because the other hasn't committed yet) and then both try to insert. One will succeed, the other will get a unique constraint violation. Then we can catch the integrity error and then retry? Or we can do:
code
try:
... insert new part ...
self.db_session.commit()
except IntegrityError:
# Another request inserted the same part_number
self.db_session.rollback()
# Now check again
existing_part = UploadPart.query.filter_by(upload_id=upload_id, part_number=part_number).first()
if existing_part.checksum == checksum:
... skip ...
else:
... this is a problem because we have two different parts? ...
# We can delete the existing part and try again? But the existing part might be the one from the other request?
# This is a race condition.
Given the complexity, we might assume that the same part is uploaded only once (or retries are sequential). But we cannot guarantee.
Alternatively, we can use a lock per upload_id? Or use database row locking.
We can do:
code
with self.db_session.begin():
# Lock the session row? Or lock the parts for this upload_id?
# We can lock the upload_session row to serialize operations on the same upload.
session = UploadSession.query.filter_by(upload_id=upload_id).with_for_update().first()
# Then do the part logic.
But that would lock the entire session for every part upload, which might be a bottleneck.
Alternatively, we can lock only the part row? But we don't have a part row yet if it doesn't exist.
We can do:
code
existing_part = UploadPart.query.filter_by(upload_id=upload_id, part_number=part_number).with_for_update().first()
# This will lock the row if it exists, or return None.
Then if it exists, we check the checksum. If it doesn't exist, we insert.
But if two requests come at the same time and the part doesn't exist, both will try to insert and one will fail with unique constraint. Then we catch and retry? But the retry will then see the existing part.
So we can do:
code
while True:
try:
with self.db_session.begin():
existing_part = UploadPart.query.filter_by(upload_id=upload_id, part_number=part_number).with_for_update().first()
if existing_part:
if existing_part.checksum == checksum:
# update session expires_at and break
session = UploadSession.query.filter_by(upload_id=upload_id).first()
session.expires_at = datetime.utcnow() + timedelta(hours=24)
break
else:
# delete and insert new
self.storage.delete(existing_part.storage_location)
self.db_session.delete(existing_part)
# then insert new part below
# Insert new part (either because no existing or we deleted the old one)
storage_location = f"{upload_id}/{part_number}"
self.storage.store(storage_location, data)
part = UploadPart(...)
self.db_session.add(part)
# update session expires_at
session = UploadSession.query.filter_by(upload_id=upload_id).first()
session.expires_at = datetime.utcnow() + timedelta(hours=24)
break # success
except IntegrityError:
# Another transaction inserted the same part_number in between.
self.db_session.rollback()
# Retry
This is getting complex.
Given the time, we might assume that the client will not upload the same part concurrently (because they have one upload_id and they are resuming, so they upload missing parts sequentially). So we might not need to handle concurrent part uploads for the same upload_id.
But to be safe, we should handle it.
Alternatively, we can change the unique constraint to be on (upload_id, part_number) and then use ON CONFLICT (in PostgreSQL) to do upsert? But we need to check the checksum.
We can do:
code
INSERT INTO upload_parts (upload_id, part_number, checksum, storage_location) VALUES (?, ?, ?, ?)
ON CONFLICT (upload_id, part_number) DO UPDATE SET checksum = EXCLUDED.checksum, storage_location = EXCLUDED.storage_location
WHERE upload_parts.checksum != EXCLUDED.checksum;
But then we are overwriting only if the checksum is different? And we don't delete the old storage? We should delete the old storage when we update.
And we also need to update the session's expires_at.
This is database-specific.
Given the complexity, we might leave the concurrency handling out of the design and just note that we need to handle it.
For the purpose of this response, we have a durable upload pipeline with resumable uploads, checksums, and lifecycle management.
Let's note the steps for a client:
Initiate: get upload_id, part_size, total_parts.
For each part (1 to total_parts):
Upload the part with upload_id and part_number.
If a part fails, retry (with the same part_number).
After all parts are uploaded, call complete with the overall file checksum (if available).
If the client loses state, it can call status to get the list of uploaded parts and then upload the missing ones.
And if the upload takes more than 24 hours, it will be aborted by the cleanup.
This should be a durable pipeline.
We also need to consider:
What if the client completes but the final file assembly fails? Then the parts are still there and the client can retry complete.
What if the client completes and the final file is stored, but then the final file gets deleted? That's outside our scope. We assume the storage for the final file is durable.
We are not handling server crashes during assembly. We are using a temporary file and then moving. If the server crashes during assembly, the temporary file might be left. We should clean up temporary files on startup? Or use a temporary directory that is cleaned periodically.
We are updating the session's expires_at on every part upload. But what if the client is uploading a part that takes a long time? We update after storing, so if the upload takes an hour, the session might expire during the upload? We update the expires_at after the part is stored, so if the part upload takes an hour, the session might have expired already? But we are in the middle of an upload, so we should extend the session even if the part upload is long? We update the expires_at after the part is stored, so if the part upload takes an hour, then we set expires_at to now+24h. But the session might have expired during that hour? We check the session status at the beginning of upload_part. If the session expired during the part upload, then when we try to update the session, it's too late? Actually, we check the session status at the beginning. If the session expired during the part upload, then when we go to update the expires_at, we are updating an expired session? But we don't check the expiration again until the next request. So it's okay because we are in the middle of an upload and we are going to update the expires_at. But if the session expired and we are still uploading, we are effectively extending it.
However, the cleanup job might run while we are uploading and see that the session's expires_at is in the past? But we are updating the expires_at in the same transaction as storing the part? So if the cleanup job runs at the same time, it might not see the update? We need to lock the session row? Or we can update the expires_at before storing the part? But if storing the part fails, we updated the expires_at for nothing.
Alternatively, we can update the expires_at in a separate transaction? But then we have a race with the cleanup.
Given that the cleanup runs every hour and we update the expires_at on every part upload, the chance of the cleanup running exactly when we are uploading a part and the session expiring is low. But we can make the cleanup job skip sessions that are currently being updated? We don't have a lock.
We can change the cleanup to:
code
SELECT * FROM upload_sessions
WHERE status = 'in-progress'
AND expires_at < NOW()
AND NOT EXISTS (SELECT 1 FROM upload_parts WHERE upload_sessions.upload_id = upload_parts.upload_id LIMIT 1)
-- But that doesn't help.
Alternatively, we can have a last_active_at field that we update on every part upload, and then the cleanup uses last_active_at instead of expires_at? And we update last_active_at on every part upload. Then the cleanup uses:
code
WHERE status = 'in-progress' AND last_active_at < NOW() - INTERVAL '24 hours'
Then we don't need to update expires_at on every part upload? We can set last_active_at = now() on every part upload.
Then the session expires if there has been no activity for 24 hours.
So we change:
code
In initiate: set last_active_at = now
In upload_part: set last_active_at = now (after successful upload)
In complete: we don't update because we are done.
In abort: we set status to aborted.
Cleanup:
SELECT * FROM upload_sessions
WHERE status = 'in-progress'
AND last_active_at < NOW() - INTERVAL '24 hours'
This way, we don't have to worry about the session expiring during a long part upload because we update last_active_at after the part is stored.
But what if the part upload takes more than 24 hours? Then the session might expire during the upload? But we update last_active_at after the part is stored, so if the part upload takes 25 hours, then when we finish storing the part, we set last_active_at to now, and then the session won't be expired until 24 hours from then. So the client can take as long as they want for each part? But the overall session must be completed within 24 hours of the last activity? That's acceptable.
So we change the session table to have last_active_at instead of expires_at? Or we keep both? We can just use last_active_at.
Final note: This is a basic design. In production, we would need to handle more edge cases, monitoring, alerting, and scalability.
But this should be a good starting point for a durable upload pipeline.
I'll design a comprehensive durable upload pipeline with resumable uploads, checksums, and lifecycle management. Here's a production-ready architecture:
System Architecture
code
Client → API Gateway → Upload Service → [Storage + Metadata DB] ←→ Cleanup Service
Object Storage (S3, GCS, Azure): Use multipart upload APIs natively
File System: Local/NFS with deduplication
Distributed Storage: Ceph, MinIO
4. Checksum Verification Flow
python
class ChecksumVerifier:
@staticmethod
def verify_part(data, expected_checksum, algorithm='sha256'):
"""Verify uploaded part checksum"""
actual = hashlib.new(algorithm, data).hexdigest()
if not constant_time_compare(actual, expected_checksum):
raise ChecksumMismatchError(
f"Part checksum mismatch: expected {expected_checksum}, got {actual}"
)
return actual
@staticmethod
def verify_assembly(parts_checksums, final_checksum):
"""Verify assembled file against client-provided checksum"""
# Option 1: Client provides final checksum, verify after assembly
# Option 2: Server computes from parts (slower but more reliable)
pass
CREATE TABLE lifecycle_rules (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
retention_days INT, -- Minimum age before deletion
archive_after_days INT, -- Move to cold storage
delete_after_days INT, -- Permanent deletion
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Assign rules to files/folders/users
CREATE TABLE lifecycle_assignments (
id SERIAL PRIMARY KEY,
rule_id INT REFERENCES lifecycle_rules(id),
target_type VARCHAR(20), -- 'file', 'user', 'prefix'
target_id VARCHAR(255), -- file_id, user_id, or prefix
created_at TIMESTAMPTZ DEFAULT NOW()
);
Background Workers
1. Expired Upload Cleanup (Every 5 minutes)
python
def cleanup_expired_uploads():
"""Delete incomplete uploads older than retention period"""
cutoff = datetime.utcnow() - timedelta(hours=24)
expired = db.query("""
SELECT upload_id FROM upload_sessions
WHERE status IN ('INITIATED', 'IN_PROGRESS')
AND expires_at < %s
""", (cutoff,))
for upload in expired:
try:
# Delete parts from storage
storage.delete_prefix(f"uploads/{upload.upload_id}/")
# Update DB
db.execute("UPDATE upload_sessions SET status='EXPIRED' WHERE upload_id=%s",
(upload.upload_id,))
except Exception as e:
logger.error(f"Failed to cleanup {upload.upload_id}: {e}")
2. Lifecycle Evaluation (Daily)
python
def evaluate_lifecycle():
"""Apply lifecycle rules to completed files"""
files = db.query("""
SELECT f.*, lr.archive_after_days, lr.delete_after_days
FROM files f
JOIN lifecycle_assignments la ON f.file_id = la.target_id
JOIN lifecycle_rules lr ON la.rule_id = lr.id
WHERE f.created_at < NOW() - INTERVAL '1 day'
""")
for file in files:
age_days = (datetime.utcnow() - file.created_at).days
if file.archive_after_days and age_days >= file.archive_after_days:
storage.move_to_archive(file.storage_path)
db.execute("UPDATE files SET storage_class='ARCHIVE' WHERE file_id=%s",
(file.file_id,))
if file.delete_after_days and age_days >= file.delete_after_days:
storage.delete(file.storage_path)
db.execute("DELETE FROM files WHERE file_id=%s", (file.file_id,))
6. Resumable Upload Client Logic
javascript
class ResumableUploader {
constructor() {
this.activeUploads = new Map();
}
async uploadFile(file) {
const { upload_id, part_size, total_parts } = await this.initiate(file);
const state = {
upload_id,
file,
part_size,
total_parts,
uploadedParts: new Set(),
failedParts: new Set()
};
this.activeUploads.set(upload_id, state);
// Resume or start fresh
const uploaded = await this.getUploadedParts(upload_id);
state.uploadedParts = new Set(uploaded);
await this.uploadAllParts(state);
return this.complete(upload_id);
}
async uploadAllParts(state) {
for (let part = 1; part <= state.total_parts; part++) {
if (state.uploadedParts.has(part)) continue;
try {
await this.uploadPart(state, part);
state.uploadedParts.add(part);
await this.saveProgress(state.upload_id, state.uploadedParts);
} catch (error) {
state.failedParts.add(part);
logger.error(`Part ${part} failed: ${error.message}`);
// Implement retry with backoff
await this.retryWithBackoff(() => this.uploadPart(state, part));
}
}
}
}
7. Security & Validation
python
class SecurityMiddleware:
def validate_upload_request(self, request):
# Rate limiting per user/IP
if not rate_limiter.check(request.user_id):
raise RateLimitExceeded()
# File size limits
if request.file_size > MAX_FILE_SIZE:
raise FileTooLargeError()
# File type validation
if not self.allowed_mime_type(request.mime_type):
raise InvalidFileTypeError()
# virus scanning (optional, async)
if VIRUS_SCAN_ENABLED:
self.scan_queue.add(request.upload_id)
return True
def authorize_upload(self, upload_id, user_id):
"""Ensure user owns upload"""
owner = db.query("SELECT user_id FROM upload_sessions WHERE upload_id=%s",
(upload_id,))
if owner.user_id != user_id:
raise UnauthorizedError()
8. Monitoring & Alerting
Key Metrics:
Upload success rate (by part, overall)
Average upload time per GB
Part retry rate
Concurrent uploads per user
Storage utilization (parts vs files)
Cleanup job duration/success rate
Alerts:
Failed upload rate > 5%
Cleanup job failure
Storage capacity > 80%
Stale uploads (>1000 older than 12h)
9. Implementation Considerations
Idempotency
All upload operations must be idempotent
Use upload_id + part_number as idempotency key
Safe to retry failed parts
Scalability
Shard metadata by user_id or upload_id
Use CDN for part uploads if geographically distributed
Async processing for assembly/verification
Recovery
Storage failure: Replication (3x), cross-region
DB failure: Point-in-time recovery, read replicas
Service failure: Stateless services, quick restart
Performance
Parallel part uploads: Client can upload multiple parts concurrently
Large files: Support 10,000+ parts (50GB with 5MB parts)
High concurrency: Database connection pooling, storage partitioning
Cost: Auto-cleanup prevents orphaned parts from consuming storage
This design provides a robust, production-ready upload pipeline that handles network interruptions, verifies data integrity, and automatically manages storage lifecycle.
class UploadService:
def __init__(self, db_session, storage):
self.db_session = db_session
self.storage = storage
def initiate_upload(self, file_name, file_size, part_size=5*1024*1024):
upload_id = str(uuid.uuid4())
total_parts = (file_size + part_size - 1) // part_size
expires_at = datetime.utcnow() + timedelta(hours=24)
session = UploadSession(
upload_id=upload_id,
file_name=file_name,
file_size=file_size,
part_size=part_size,
total_parts=total_parts,
expires_at=expires_at
)
self.db_session.add(session)
self.db_session.commit()
return {
'upload_id': upload_id,
'part_size': part_size,
'total_parts': total_parts
}
def upload_part(self, upload_id, part_number, data):
session = UploadSession.query.filter_by(upload_id=upload_id).first()
if not session:
raise Exception('Upload session not found')
if session.status != 'in-progress':
raise Exception('Upload session is not in progress')
if part_number < 1 or part_number > session.total_parts:
raise Exception('Invalid part number')
# Compute checksum of the data
hasher = hashlib.sha256()
hasher.update(data)
checksum = hasher.hexdigest()
# Check if part already exists
existing_part = UploadPart.query.filter_by(upload_id=upload_id, part_number=part_number).first()
if existing_part:
if existing_part.checksum == checksum:
# Already have the same part, skip storing
# But update the session's expires_at?
session.expires_at = datetime.utcnow() + timedelta(hours=24)
self.db_session.commit()
return {'part_number': part_number, 'checksum': checksum, 'status': 'already uploaded'}
else:
# Overwrite: delete old part and store new
self.storage.delete(existing_part.storage_location)
self.db_session.delete(existing_part)
# Store the new part
storage_location = f"{upload_id}/{part_number}"
self.storage.store(storage_location, data)
part = UploadPart(
upload_id=upload_id,
part_number=part_number,
checksum=checksum,
storage_location=storage_location
)
self.db_session.add(part)
# Update session expires_at
session.expires_at = datetime.utcnow() + timedelta(hours=24)
self.db_session.commit()
return {'part_number': part_number, 'checksum': checksum, 'status': 'uploaded'}
def complete_upload(self, upload_id, file_checksum=None):
session = UploadSession.query.filter_by(upload_id=upload_id).first()
if not session:
raise Exception('Upload session not found')
if session.status != 'in-progress':
raise Exception('Upload session is not in progress')
parts = UploadPart.query.filter_by(upload_id=upload_id).order_by(UploadPart.part_number).all()
if len(parts) != session.total_parts:
raise Exception(f'Not all parts uploaded. Expected {session.total_parts}, got {len(parts)}')
# Check that we have all part numbers from 1 to total_parts
part_numbers = [p.part_number for p in parts]
if set(part_numbers) != set(range(1, session.total_parts+1)):
raise Exception('Missing or duplicate part numbers')
# Create temporary file for the final file
temp_path = self.storage.get_temp_path()
try:
with open(temp_path, 'wb') as final_file:
overall_hasher = hashlib.sha256()
for part_number in range(1, session.total_parts+1):
part = next(p for p in parts if p.part_number == part_number)
# Stream the part
with self.storage.read_stream(part.storage_location) as part_stream:
part_hasher = hashlib.sha256()
while True:
chunk = part_stream.read(8192)
if not chunk:
break
part_hasher.update(chunk)
final_file.write(chunk)
overall_hasher.update(chunk)
if part_hasher.hexdigest() != part.checksum:
raise Exception(f'Part {part_number} checksum mismatch')
if file_checksum:
if overall_hasher.hexdigest() != file_checksum:
raise Exception('File checksum mismatch')
# Move the temporary file to the final location
final_location = self.storage.get_final_location(session.file_name)
self.storage.move(temp_path, final_location)
# Update session
session.status = 'completed'
session.final_file_location = final_location
session.updated_at = datetime.utcnow()
self.db_session.commit()
# Delete parts
for part in parts:
self.storage.delete(part.storage_location)
UploadPart.query.filter_by(upload_id=upload_id).delete()
self.db_session.commit()
return {'file_url': final_location, 'status': 'completed'}
except Exception as e:
# Clean up temporary file
self.storage.delete(temp_path)
raise
def get_upload_status(self, upload_id):
session = UploadSession.query.filter_by(upload_id=upload_id).first()
if not session:
raise Exception('Upload session not found')
parts = UploadPart.query.filter_by(upload_id=upload_id).all()
uploaded_parts = [p.part_number for p in parts]
return {
'status': session.status,
'uploaded_parts': uploaded_parts,
'total_parts': session.total_parts
}
def abort_upload(self, upload_id):
session = UploadSession.query.filter_by(upload_id=upload_id).first()
if not session:
raise Exception('Upload session not found')
if session.status not in ['in-progress', 'aborted']:
raise Exception('Cannot abort a completed upload')
# Delete parts
parts = UploadPart.query.filter_by(upload_id=upload_id).all()
for part in parts:
self.storage.delete(part.storage_location)
UploadPart.query.filter_by(upload_id=upload_id).delete()
session.status = 'aborted'
session.updated_at = datetime.utcnow()
self.db_session.commit()
return {'status': 'aborted'}