Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.6.0+

S3 Http: Resume and Recover a Multipart Upload

See more S3 - HTTP Examples

Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.

Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.

Uses explicit signed Http requests to preserve query parameters, conditional headers, and full responses. The included SigV4 block signs the exact path, sorted encoded query and headers used by this example; it is not a general-purpose HTTP signing library. Keep the clock accurate and do not change signed data after signing. Code requires Chilkat 11.6.0 or later; locally tested with 11.8.0.

Uses a private checkpoint directory for one upload and an immutable source file. Run one process per checkpoint; never run upload/resume concurrently with abort. The fixed 8 MiB part size limits this demonstration to nonempty files of at most 10,000 parts (78.125 GiB). It does not impose that limit on S3 itself; choose larger valid part sizes for larger objects.

Uses SHA-256 COMPOSITE multipart checksums, validates part checksums, and verifies the returned composite checksum. ETags are retained for completion but never treated as MD5. Completion can return an error inside HTTP 200; the XML result is checked. Source identity is SHA-256, not just filename/length. The checkpoint contains no AWS credentials.

Requires s3:PutObject, s3:ListMultipartUploadParts for resume, and s3:GetObject for uncertain-completion recovery, plus relevant KMS permissions if bucket defaults use KMS. Incomplete parts incur storage charges until completed or aborted. Configure a suitable incomplete-multipart lifecycle rule as an operational safeguard. Timeout during initiation may leave an upload without a checkpoint; list uploads and investigate before initiating another.

Lists all uploaded parts and reuses only parts whose SHA-256 and byte count match the local source; mismatched parts are replaced. If ListParts returns NoSuchUpload after a recorded completion attempt, a checksum-enabled HEAD must match the unique upload token, source hash, composite checksum and size before recovery is reported. A missing upload alone is never treated as completion. If another write has replaced the current object, inspect version history manually.

AWS reference

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

local stringCompare = chilkat.StringBuilder.new()
-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
-- Load private credentials; never put access keys or session tokens in source.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
local success = credentials:load_file("qa_data/aws/s3.json")
if not success then
    print("Could not load private S3 credentials.")
    return
end

stringCompare:set_string(credentials:string_of("access_key"))
local stringMatch1 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (stringMatch1) then
    print("Missing or invalid access_key.")
    return
end

stringCompare:set_string(credentials:string_of("secret_key"))
local stringMatch2 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (stringMatch2) then
    print("Missing or invalid secret_key.")
    return
end

local http = chilkat.Http.new()
http.aws_access_key = credentials:string_of("access_key")
http.aws_secret_key = credentials:string_of("secret_key")
if credentials:has_member("session_token") then
    stringCompare:set_string(credentials:string_of("session_token"))
    local stringMatch3 = stringCompare:contents_equal("", true)
    if (credentials:json_type_of("session_token") ~= 1) or (stringMatch3) then
        print("session_token must be a nonempty string when supplied.")
        return
    end

    http.aws_session_token = credentials:string_of("session_token")
end

-- Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
-- Set the actual bucket region, not the caller's location.
local region = "us-west-2"
http.aws_region = region
local endpoint = chilkat.StringBuilder.new()
endpoint:append("s3.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
http.aws_endpoint = endpoint:get_as_string()
http.require_ssl_cert_verify = true
http.follow_redirects = false
-- A region redirect is not success. Correct the endpoint and signing region.
local bucketName = "your-bucket-name"
local objectKey = "examples/archive.bin"
local response = chilkat.HttpResponse.new()
local signer = chilkat.Crypt2.new()
signer.charset = "utf-8"
signer.hash_algorithm = "sha256"
signer.encoding_mode = "hexlower"
signer.mac_algorithm = "hmac"
local now = chilkat.DateTime.new()
local timestamp = chilkat.StringBuilder.new()
local canonical = chilkat.StringBuilder.new()
local canonicalHeaders = chilkat.StringBuilder.new()
local signedHeaders = chilkat.StringBuilder.new()
local scope = chilkat.StringBuilder.new()
local stringToSign = chilkat.StringBuilder.new()
local signingKey = chilkat.StringBuilder.new()
local authorization = chilkat.StringBuilder.new()
local url = chilkat.StringBuilder.new()
local query = chilkat.StringBuilder.new()
local number = chilkat.StringBuilder.new()
local host = chilkat.StringBuilder.new()
local uri = chilkat.StringBuilder.new()
local xml = chilkat.Xml.new()
local amzDate = ""
local dateStamp = ""
local payloadHash = ""
local canonicalHash = ""
local derivedKey = ""
local signature = ""
host:append(bucketName)
host:append(".")
host:append(endpoint:get_as_string())
-- Encode the original key exactly once, preserving S3 path separators.
uri:set_string(http:url_encode(objectKey))
local replaceCount = uri:replace_no_case("%2f", "/")
if (uri:starts_with("/", true)) or ((uri:contains("/../", true)) or (uri:contains("/./", true))) then
    print("Use a key without a leading slash or dot path segments for these examples.")
    return
end

uri:prepend("/")
local files = chilkat.FileAccess.new()
local filePath = "qa_data/bin/archive.bin"
local fileSize = files:file_size_str(filePath)
if not files.last_method_success then
    print("Could not read source file size.")
    return
end

local digest = chilkat.Crypt2.new()
digest.hash_algorithm = "sha256"
digest.encoding_mode = "hexlower"
local sourceHash = digest:hash_file_enc(filePath)
if not digest.last_method_success then
    print("Could not hash source file.")
    return
end

digest.encoding_mode = "base64"
local sourceChecksum = digest:hash_file_enc(filePath)
if not digest.last_method_success then
    print("Could not compute checksum.")
    return
end

local statePath = "qa_output/s3-multipart/state.json"
local pendingPath = "qa_output/s3-multipart/completion.json"
local receiptPath = "qa_output/s3-multipart/completed.json"
local state = chilkat.JsonObject.new()
state.strict = true
local pending = chilkat.JsonObject.new()
pending.strict = true
local compositeChecksum = ""
success = files:open_for_read(filePath)
if not success then
    print("Could not open immutable source file.")
    return
end

local partSize = 8388608
local numParts = files:get_num_blocks(partSize)
if (numParts < 1) or (numParts > 10000) then
    print("Use a nonempty source of at most 10,000 fixed 8 MiB parts.")
    return
end

local remoteEtags = chilkat.Hashtable.new()
local remoteSizes = chilkat.Hashtable.new()
local remoteChecksums = chilkat.Hashtable.new()
local partNumbers = chilkat.Hashtable.new()
local partNumberText = chilkat.StringBuilder.new()
success = state:load_file(statePath)
if not success then
    print("Could not load multipart checkpoint.")
    return
end

stringCompare:set_string(state:string_of("schema"))
local stringMatch4 = stringCompare:contents_equal("1", true)
if not stringMatch4 then
    print("Checkpoint/source identity differs. Do not resume another file or destination.")
    return
end

stringCompare:set_string(state:string_of("bucket"))
local stringMatch5 = stringCompare:contents_equal(bucketName, true)
if not stringMatch5 then
    print("Checkpoint/source identity differs. Do not resume another file or destination.")
    return
end

stringCompare:set_string(state:string_of("key"))
local stringMatch6 = stringCompare:contents_equal(objectKey, true)
if not stringMatch6 then
    print("Checkpoint/source identity differs. Do not resume another file or destination.")
    return
end

stringCompare:set_string(state:string_of("region"))
local stringMatch7 = stringCompare:contents_equal(region, true)
if not stringMatch7 then
    print("Checkpoint/source identity differs. Do not resume another file or destination.")
    return
end

stringCompare:set_string(state:string_of("filePath"))
local stringMatch8 = stringCompare:contents_equal(filePath, true)
if not stringMatch8 then
    print("Checkpoint/source identity differs. Do not resume another file or destination.")
    return
end

stringCompare:set_string(state:string_of("fileSize"))
local stringMatch9 = stringCompare:contents_equal(fileSize, true)
if not stringMatch9 then
    print("Checkpoint/source identity differs. Do not resume another file or destination.")
    return
end

stringCompare:set_string(state:string_of("sourceHash"))
local stringMatch10 = stringCompare:contents_equal(sourceHash, true)
if not stringMatch10 then
    print("Checkpoint/source identity differs. Do not resume another file or destination.")
    return
end

stringCompare:set_string(state:string_of("partSize"))
local stringMatch11 = stringCompare:contents_equal("8388608", true)
if not stringMatch11 then
    print("Checkpoint/source identity differs. Do not resume another file or destination.")
    return
end

local uploadId = state:string_of("uploadId")
local uploadToken = state:string_of("uploadToken")
stringCompare:set_string(uploadId)
local stringMatch12 = stringCompare:contents_equal("", true)
stringCompare:set_string(uploadToken)
local stringMatch13 = stringCompare:contents_equal("", true)
if (stringMatch12) or ((stringMatch13) or ((state:json_type_of("uploadId") ~= 1) or (state:json_type_of("uploadToken") ~= 1))) then
    print("Checkpoint has no upload identity.")
    return
end

if files:file_exists(receiptPath) then
    success = pending:load_file(receiptPath)
    if not success then
        print("Invalid completion receipt.")
        return
    end

    stringCompare:set_string(pending:string_of("uploadId"))
    local stringMatch14 = stringCompare:contents_equal(uploadId, true)
    stringCompare:set_string(pending:string_of("sourceHash"))
    local stringMatch15 = stringCompare:contents_equal(sourceHash, true)
    if (not stringMatch14) or (not stringMatch15) then
        print("Completion receipt belongs to another upload.")
        return
    end

    print("Multipart upload already completed; receipt retained.")
    return
end

local seen = chilkat.Hashtable.new()
local more = true
local page = 0
local marker = ""
local truncated = ""
local item = ""
while more do
    if page == 10000 then
        print("Page bound reached; results are incomplete.")
        return
    end

    page = page + 1
    query:clear()
    if query.length > 0 then
        query:append("&")
    end

    query:append("max-parts=")
    query:append(http:url_encode("1000"))
    stringCompare:set_string(marker)
    local stringMatch16 = stringCompare:contents_equal("", true)
    if not stringMatch16 then
        if query.length > 0 then
            query:append("&")
        end

        query:append("part-number-marker=")
        query:append(http:url_encode(marker))
    end

    if query.length > 0 then
        query:append("&")
    end

    query:append("uploadId=")
    query:append(http:url_encode(uploadId))
    http:clear_headers()
    success = now:set_from_current_system_time()
    if not success then
        print("Could not read system time.")
        return
    end

    timestamp:set_string(now:get_as_timestamp(false))
    replaceCount = timestamp:replace("-", "")
    replaceCount = timestamp:replace(":", "")
    amzDate = timestamp:get_as_string()
    dateStamp = timestamp:get_range(0, 8, false)
    payloadHash = signer:hash_string_enc("")
    if not signer.last_method_success then
        print("Could not hash payload.")
        return
    end

    canonicalHeaders:clear()
    signedHeaders:clear()
    if signedHeaders.length > 0 then
        signedHeaders:append(";")
    end

    signedHeaders:append("host")
    canonicalHeaders:append("host:")
    canonicalHeaders:append(host:get_as_string())
    canonicalHeaders:append("\n")
    http:set_request_header("host", host:get_as_string())
    if signedHeaders.length > 0 then
        signedHeaders:append(";")
    end

    signedHeaders:append("x-amz-content-sha256")
    canonicalHeaders:append("x-amz-content-sha256:")
    canonicalHeaders:append(payloadHash)
    canonicalHeaders:append("\n")
    http:set_request_header("x-amz-content-sha256", payloadHash)
    if signedHeaders.length > 0 then
        signedHeaders:append(";")
    end

    signedHeaders:append("x-amz-date")
    canonicalHeaders:append("x-amz-date:")
    canonicalHeaders:append(amzDate)
    canonicalHeaders:append("\n")
    http:set_request_header("x-amz-date", amzDate)
    if credentials:has_member("session_token") then
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("x-amz-security-token")
        canonicalHeaders:append("x-amz-security-token:")
        canonicalHeaders:append(credentials:string_of("session_token"))
        canonicalHeaders:append("\n")
        http:set_request_header("x-amz-security-token", credentials:string_of("session_token"))
    end

    canonical:clear()
    canonical:append("GET\n")
    canonical:append(uri:get_as_string())
    canonical:append("\n")
    canonical:append(query:get_as_string())
    canonical:append("\n")
    canonical:append(canonicalHeaders:get_as_string())
    canonical:append("\n")
    canonical:append(signedHeaders:get_as_string())
    canonical:append("\n")
    canonical:append(payloadHash)
    canonicalHash = signer:hash_string_enc(canonical:get_as_string())
    if not signer.last_method_success then
        print("Could not hash canonical request.")
        return
    end

    scope:clear()
    scope:append(dateStamp)
    scope:append("/")
    scope:append(region)
    scope:append("/s3/aws4_request")
    stringToSign:clear()
    stringToSign:append("AWS4-HMAC-SHA256\n")
    stringToSign:append(amzDate)
    stringToSign:append("\n")
    stringToSign:append(scope:get_as_string())
    stringToSign:append("\n")
    stringToSign:append(canonicalHash)
    signingKey:set_string("AWS4")
    signingKey:append(credentials:string_of("secret_key"))
    success = signer:set_mac_key_string(signingKey:get_as_string())
    if not success then
        print("Could not set signing key.")
        return
    end

    derivedKey = signer:mac_string_enc(dateStamp)
    if not signer.last_method_success then
        print("Could not derive signing key.")
        return
    end

    success = signer:set_mac_key_encoded(derivedKey, "hex")
    if not success then
        print("Could not set signing key.")
        return
    end

    derivedKey = signer:mac_string_enc(region)
    if not signer.last_method_success then
        print("Could not derive signing key.")
        return
    end

    success = signer:set_mac_key_encoded(derivedKey, "hex")
    if not success then
        print("Could not set signing key.")
        return
    end

    derivedKey = signer:mac_string_enc("s3")
    if not signer.last_method_success then
        print("Could not derive signing key.")
        return
    end

    success = signer:set_mac_key_encoded(derivedKey, "hex")
    if not success then
        print("Could not set signing key.")
        return
    end

    derivedKey = signer:mac_string_enc("aws4_request")
    if not signer.last_method_success then
        print("Could not derive signing key.")
        return
    end

    success = signer:set_mac_key_encoded(derivedKey, "hex")
    if not success then
        print("Could not set signing key.")
        return
    end

    signature = signer:mac_string_enc(stringToSign:get_as_string())
    if not signer.last_method_success then
        print("Could not sign request.")
        return
    end

    authorization:clear()
    authorization:append("AWS4-HMAC-SHA256 Credential=")
    authorization:append(credentials:string_of("access_key"))
    authorization:append("/")
    authorization:append(scope:get_as_string())
    authorization:append(", SignedHeaders=")
    authorization:append(signedHeaders:get_as_string())
    authorization:append(", Signature=")
    authorization:append(signature)
    http:set_request_header("Authorization", authorization:get_as_string())
    url:set_string("https://")
    url:append(host:get_as_string())
    url:append(uri:get_as_string())
    if query.length > 0 then
        url:append("?")
        url:append(query:get_as_string())
    end

    success = http:http_no_body("GET", url:get_as_string(), response)
    if response.status_code == 404 then
        success = xml:load_xml(response.body_str)
        if not success then
            print("Could not parse missing-upload response.")
            return
        end

        stringCompare:set_string(xml:get_child_content("Code"))
        local stringMatch17 = stringCompare:contents_equal("NoSuchUpload", true)
        if not stringMatch17 then
            print("404 was not NoSuchUpload; inspect target bucket/key.")
            return
        end

        success = pending:load_file(pendingPath)
        if not success then
            print("Upload no longer exists. No valid pending completion record; inspect object state manually.")
            return
        end

        stringCompare:set_string(pending:string_of("uploadId"))
        local stringMatch18 = stringCompare:contents_equal(uploadId, true)
        if not stringMatch18 then
            print("Pending completion does not match this upload.")
            return
        end

        stringCompare:set_string(pending:string_of("sourceHash"))
        local stringMatch19 = stringCompare:contents_equal(sourceHash, true)
        if not stringMatch19 then
            print("Pending completion does not match this upload.")
            return
        end

        stringCompare:set_string(pending:string_of("uploadToken"))
        local stringMatch20 = stringCompare:contents_equal(uploadToken, true)
        if not stringMatch20 then
            print("Pending completion does not match this upload.")
            return
        end

        compositeChecksum = pending:string_of("checksum")
        stringCompare:set_string(compositeChecksum)
        local stringMatch21 = stringCompare:contents_equal("", true)
        if (not pending.last_method_success) or (stringMatch21) then
            print("Missing pending checksum.")
            return
        end

        query:clear()
        http:clear_headers()
        success = now:set_from_current_system_time()
        if not success then
            print("Could not read system time.")
            return
        end

        timestamp:set_string(now:get_as_timestamp(false))
        replaceCount = timestamp:replace("-", "")
        replaceCount = timestamp:replace(":", "")
        amzDate = timestamp:get_as_string()
        dateStamp = timestamp:get_range(0, 8, false)
        payloadHash = signer:hash_string_enc("")
        if not signer.last_method_success then
            print("Could not hash payload.")
            return
        end

        canonicalHeaders:clear()
        signedHeaders:clear()
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("host")
        canonicalHeaders:append("host:")
        canonicalHeaders:append(host:get_as_string())
        canonicalHeaders:append("\n")
        http:set_request_header("host", host:get_as_string())
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("x-amz-checksum-mode")
        canonicalHeaders:append("x-amz-checksum-mode:")
        canonicalHeaders:append("ENABLED")
        canonicalHeaders:append("\n")
        http:set_request_header("x-amz-checksum-mode", "ENABLED")
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("x-amz-content-sha256")
        canonicalHeaders:append("x-amz-content-sha256:")
        canonicalHeaders:append(payloadHash)
        canonicalHeaders:append("\n")
        http:set_request_header("x-amz-content-sha256", payloadHash)
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("x-amz-date")
        canonicalHeaders:append("x-amz-date:")
        canonicalHeaders:append(amzDate)
        canonicalHeaders:append("\n")
        http:set_request_header("x-amz-date", amzDate)
        if credentials:has_member("session_token") then
            if signedHeaders.length > 0 then
                signedHeaders:append(";")
            end

            signedHeaders:append("x-amz-security-token")
            canonicalHeaders:append("x-amz-security-token:")
            canonicalHeaders:append(credentials:string_of("session_token"))
            canonicalHeaders:append("\n")
            http:set_request_header("x-amz-security-token", credentials:string_of("session_token"))
        end

        canonical:clear()
        canonical:append("HEAD\n")
        canonical:append(uri:get_as_string())
        canonical:append("\n")
        canonical:append(query:get_as_string())
        canonical:append("\n")
        canonical:append(canonicalHeaders:get_as_string())
        canonical:append("\n")
        canonical:append(signedHeaders:get_as_string())
        canonical:append("\n")
        canonical:append(payloadHash)
        canonicalHash = signer:hash_string_enc(canonical:get_as_string())
        if not signer.last_method_success then
            print("Could not hash canonical request.")
            return
        end

        scope:clear()
        scope:append(dateStamp)
        scope:append("/")
        scope:append(region)
        scope:append("/s3/aws4_request")
        stringToSign:clear()
        stringToSign:append("AWS4-HMAC-SHA256\n")
        stringToSign:append(amzDate)
        stringToSign:append("\n")
        stringToSign:append(scope:get_as_string())
        stringToSign:append("\n")
        stringToSign:append(canonicalHash)
        signingKey:set_string("AWS4")
        signingKey:append(credentials:string_of("secret_key"))
        success = signer:set_mac_key_string(signingKey:get_as_string())
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc(dateStamp)
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc(region)
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc("s3")
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc("aws4_request")
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        signature = signer:mac_string_enc(stringToSign:get_as_string())
        if not signer.last_method_success then
            print("Could not sign request.")
            return
        end

        authorization:clear()
        authorization:append("AWS4-HMAC-SHA256 Credential=")
        authorization:append(credentials:string_of("access_key"))
        authorization:append("/")
        authorization:append(scope:get_as_string())
        authorization:append(", SignedHeaders=")
        authorization:append(signedHeaders:get_as_string())
        authorization:append(", Signature=")
        authorization:append(signature)
        http:set_request_header("Authorization", authorization:get_as_string())
        url:set_string("https://")
        url:append(host:get_as_string())
        url:append(uri:get_as_string())
        if query.length > 0 then
            url:append("?")
            url:append(query:get_as_string())
        end

        success = http:http_no_body("HEAD", url:get_as_string(), response)
        if (not success) or (response.status_code ~= 200) then
            print("Request failed or returned unexpected HTTP status: " .. response.status_code)
            -- Preserve progress. Inspect full diagnostics privately; do not log secrets.
            return
        end

        stringCompare:set_string(response:get_header_field("x-amz-meta-upload-token"))
        local stringMatch22 = stringCompare:contents_equal(uploadToken, true)
        if not stringMatch22 then
            print("Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.")
            return
        end

        stringCompare:set_string(response:get_header_field("x-amz-meta-source-sha256"))
        local stringMatch23 = stringCompare:contents_equal(sourceHash, true)
        if not stringMatch23 then
            print("Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.")
            return
        end

        stringCompare:set_string(response:get_header_field("x-amz-checksum-sha256"))
        local stringMatch24 = stringCompare:contents_equal(compositeChecksum, true)
        if not stringMatch24 then
            print("Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.")
            return
        end

        stringCompare:set_string(response:get_header_field("x-amz-checksum-type"))
        local stringMatch25 = stringCompare:contents_equal("COMPOSITE", true)
        if not stringMatch25 then
            print("Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.")
            return
        end

        stringCompare:set_string(response:get_header_field("Content-Length"))
        local stringMatch26 = stringCompare:contents_equal(fileSize, true)
        if not stringMatch26 then
            print("Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.")
            return
        end

        success = state:update_string("compositeChecksum", compositeChecksum)
        if not success then
            print("Could not save compositeChecksum.")
            return
        end

        success = state:write_file("qa_output/s3-multipart/completed.json.tmp")
        if not success then
            print("Completion succeeded but receipt could not be saved; preserve the checkpoint.")
            return
        end

        success = files:file_rename("qa_output/s3-multipart/completed.json.tmp", receiptPath)
        if not success then
            print("Completion receipt remains at its temporary path.")
            return
        end

        print("Multipart upload completed and verified.")
        return
    end

    if (not success) or (response.status_code ~= 200) then
        print("Request failed or returned unexpected HTTP status: " .. response.status_code)
        -- Preserve progress. Inspect full diagnostics privately; do not log secrets.
        return
    end

    success = xml:load_xml(response.body_str)
    if not success then
        print("Invalid XML response.")
        return
    end

    stringCompare:set_string(xml.tag)
    local stringMatch27 = stringCompare:contents_equal("ListPartsResult", true)
    if not stringMatch27 then
        print("Unexpected XML result, possibly an embedded S3 error. Inspect privately.")
        return
    end

    local i = 0
    while i < xml:num_children_having_tag("Part") do
        xml.i = i
        local remoteNumber = xml:get_child_int_value("Part[i]|PartNumber")
        if (not xml.last_method_success) or ((remoteNumber < 1) or (remoteNumber > numParts)) then
            print("Unexpected remote part number.")
            return
        end

        partNumberText:clear()
        partNumberText:append_int(remoteNumber)
        if partNumbers:contains(partNumberText:get_as_string()) then
            print("Duplicate remote part number.")
            return
        end

        success = partNumbers:add_str(partNumberText:get_as_string(), "seen")
        if not success then
            print("Could not track remote part.")
            return
        end

        item = xml:get_child_content("Part[i]|ETag")
        stringCompare:set_string(item)
        local stringMatch28 = stringCompare:contents_equal("", true)
        if (not xml.last_method_success) or (stringMatch28) then
            print("Missing required Part[i]|ETag.")
            return
        end

        success = remoteEtags:add_str(partNumberText:get_as_string(), item)
        if not success then
            print("Could not retain part ETag.")
            return
        end

        item = xml:get_child_content("Part[i]|Size")
        stringCompare:set_string(item)
        local stringMatch29 = stringCompare:contents_equal("", true)
        if (not xml.last_method_success) or (stringMatch29) then
            print("Missing required Part[i]|Size.")
            return
        end

        success = remoteSizes:add_str(partNumberText:get_as_string(), item)
        if not success then
            print("Could not retain part size.")
            return
        end

        item = xml:get_child_content("Part[i]|ChecksumSHA256")
        if xml.last_method_success then
            success = remoteChecksums:add_str(partNumberText:get_as_string(), item)
            if not success then
                print("Could not retain part checksum.")
                return
            end
        end

        i = i + 1
    end

    truncated = xml:get_child_content("IsTruncated")
    stringCompare:set_string(truncated)
    local stringMatch30 = stringCompare:contents_equal("", true)
    if (not xml.last_method_success) or (stringMatch30) then
        print("Missing required IsTruncated.")
        return
    end

    stringCompare:set_string(truncated)
    local stringMatch31 = stringCompare:contents_equal("true", true)
    stringCompare:set_string(truncated)
    local stringMatch32 = stringCompare:contents_equal("false", true)
    if (not stringMatch31) and (not stringMatch32) then
        print("Invalid IsTruncated; results are incomplete.")
        return
    end

    more = false
    stringCompare:set_string(truncated)
    local stringMatch33 = stringCompare:contents_equal("true", true)
    if stringMatch33 then
        marker = xml:get_child_content("NextPartNumberMarker")
        stringCompare:set_string(marker)
        local stringMatch34 = stringCompare:contents_equal("", true)
        if (not xml.last_method_success) or (stringMatch34) then
            print("Missing required NextPartNumberMarker.")
            return
        end

        if seen:contains(marker) then
            print("Repeated pagination marker; results are incomplete.")
            return
        end

        success = seen:add_str(marker, "seen")
        if not success then
            print("Could not track marker.")
            return
        end

        more = true
    end
end

local part = chilkat.BinData.new()
local concatenatedDigests = chilkat.BinData.new()
local completion = chilkat.Xml.new()
completion.tag = "CompleteMultipartUpload"
completion:add_attribute("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/")
local partIndex = 0
local partChecksum = ""
local partEtag = ""
local partHash = ""
local confirmed = ""
local sizeText = ""
while partIndex < numParts do
    part:clear()
    success = files:read_block_bd(partIndex, partSize, part)
    if not success then
        print("Could not read source part; preserve checkpoint.")
        return
    end

    if (part.num_bytes == 0) or ((partIndex < numParts - 1) and (part.num_bytes ~= partSize)) then
        print("Source changed or part read was incomplete.")
        return
    end

    partChecksum = digest:hash_bd_enc(part)
    if not digest.last_method_success then
        print("Could not checksum part.")
        return
    end

    partHash = signer:hash_bd_enc(part)
    if not signer.last_method_success then
        print("Could not hash part.")
        return
    end

    success = concatenatedDigests:append_encoded(partChecksum, "base64")
    if not success then
        print("Could not accumulate part digests.")
        return
    end

    partNumberText:clear()
    partNumberText:append_int(partIndex + 1)
    number:clear()
    number:append_int(part.num_bytes)
    sizeText = number:get_as_string()
    local partNumberKey = partNumberText:get_as_string()
    local reuse = false
    partEtag = ""
    if remoteChecksums:contains(partNumberKey) then
        stringCompare:set_string(remoteChecksums:lookup_str(partNumberKey))
        local stringMatch35 = stringCompare:contents_equal(partChecksum, true)
        stringCompare:set_string(remoteSizes:lookup_str(partNumberKey))
        local stringMatch36 = stringCompare:contents_equal(sizeText, true)
        if (stringMatch35) and (stringMatch36) then
            partEtag = remoteEtags:lookup_str(partNumberKey)
            stringCompare:set_string(partEtag)
            local stringMatch37 = stringCompare:contents_equal("", true)
            if (remoteEtags.last_method_success) and (not stringMatch37) then
                reuse = true
            end
        end
    end

    if not reuse then
        query:clear()
        if query.length > 0 then
            query:append("&")
        end

        query:append("partNumber=")
        query:append(http:url_encode(partNumberText:get_as_string()))
        if query.length > 0 then
            query:append("&")
        end

        query:append("uploadId=")
        query:append(http:url_encode(uploadId))
        http:clear_headers()
        success = now:set_from_current_system_time()
        if not success then
            print("Could not read system time.")
            return
        end

        timestamp:set_string(now:get_as_timestamp(false))
        replaceCount = timestamp:replace("-", "")
        replaceCount = timestamp:replace(":", "")
        amzDate = timestamp:get_as_string()
        dateStamp = timestamp:get_range(0, 8, false)
        payloadHash = partHash
        canonicalHeaders:clear()
        signedHeaders:clear()
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("host")
        canonicalHeaders:append("host:")
        canonicalHeaders:append(host:get_as_string())
        canonicalHeaders:append("\n")
        http:set_request_header("host", host:get_as_string())
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("x-amz-checksum-sha256")
        canonicalHeaders:append("x-amz-checksum-sha256:")
        canonicalHeaders:append(partChecksum)
        canonicalHeaders:append("\n")
        http:set_request_header("x-amz-checksum-sha256", partChecksum)
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("x-amz-content-sha256")
        canonicalHeaders:append("x-amz-content-sha256:")
        canonicalHeaders:append(payloadHash)
        canonicalHeaders:append("\n")
        http:set_request_header("x-amz-content-sha256", payloadHash)
        if signedHeaders.length > 0 then
            signedHeaders:append(";")
        end

        signedHeaders:append("x-amz-date")
        canonicalHeaders:append("x-amz-date:")
        canonicalHeaders:append(amzDate)
        canonicalHeaders:append("\n")
        http:set_request_header("x-amz-date", amzDate)
        if credentials:has_member("session_token") then
            if signedHeaders.length > 0 then
                signedHeaders:append(";")
            end

            signedHeaders:append("x-amz-security-token")
            canonicalHeaders:append("x-amz-security-token:")
            canonicalHeaders:append(credentials:string_of("session_token"))
            canonicalHeaders:append("\n")
            http:set_request_header("x-amz-security-token", credentials:string_of("session_token"))
        end

        canonical:clear()
        canonical:append("PUT\n")
        canonical:append(uri:get_as_string())
        canonical:append("\n")
        canonical:append(query:get_as_string())
        canonical:append("\n")
        canonical:append(canonicalHeaders:get_as_string())
        canonical:append("\n")
        canonical:append(signedHeaders:get_as_string())
        canonical:append("\n")
        canonical:append(payloadHash)
        canonicalHash = signer:hash_string_enc(canonical:get_as_string())
        if not signer.last_method_success then
            print("Could not hash canonical request.")
            return
        end

        scope:clear()
        scope:append(dateStamp)
        scope:append("/")
        scope:append(region)
        scope:append("/s3/aws4_request")
        stringToSign:clear()
        stringToSign:append("AWS4-HMAC-SHA256\n")
        stringToSign:append(amzDate)
        stringToSign:append("\n")
        stringToSign:append(scope:get_as_string())
        stringToSign:append("\n")
        stringToSign:append(canonicalHash)
        signingKey:set_string("AWS4")
        signingKey:append(credentials:string_of("secret_key"))
        success = signer:set_mac_key_string(signingKey:get_as_string())
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc(dateStamp)
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc(region)
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc("s3")
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        derivedKey = signer:mac_string_enc("aws4_request")
        if not signer.last_method_success then
            print("Could not derive signing key.")
            return
        end

        success = signer:set_mac_key_encoded(derivedKey, "hex")
        if not success then
            print("Could not set signing key.")
            return
        end

        signature = signer:mac_string_enc(stringToSign:get_as_string())
        if not signer.last_method_success then
            print("Could not sign request.")
            return
        end

        authorization:clear()
        authorization:append("AWS4-HMAC-SHA256 Credential=")
        authorization:append(credentials:string_of("access_key"))
        authorization:append("/")
        authorization:append(scope:get_as_string())
        authorization:append(", SignedHeaders=")
        authorization:append(signedHeaders:get_as_string())
        authorization:append(", Signature=")
        authorization:append(signature)
        http:set_request_header("Authorization", authorization:get_as_string())
        url:set_string("https://")
        url:append(host:get_as_string())
        url:append(uri:get_as_string())
        if query.length > 0 then
            url:append("?")
            url:append(query:get_as_string())
        end

        success = http:http_bd("PUT", url:get_as_string(), part, "application/octet-stream", response)
        if (not success) or (response.status_code ~= 200) then
            print("Request failed or returned unexpected HTTP status: " .. response.status_code)
            -- Preserve progress. Inspect full diagnostics privately; do not log secrets.
            return
        end

        confirmed = response:get_header_field("x-amz-checksum-sha256")
        stringCompare:set_string(confirmed)
        local stringMatch38 = stringCompare:contents_equal("", true)
        if (not response.last_method_success) or (stringMatch38) then
            print("Missing required response header x-amz-checksum-sha256.")
            return
        end

        stringCompare:set_string(confirmed)
        local stringMatch39 = stringCompare:contents_equal(partChecksum, true)
        if not stringMatch39 then
            print("Part checksum mismatch; preserve checkpoint.")
            return
        end

        partEtag = response:get_header_field("ETag")
        stringCompare:set_string(partEtag)
        local stringMatch40 = stringCompare:contents_equal("", true)
        if (not response.last_method_success) or (stringMatch40) then
            print("Missing required response header ETag.")
            return
        end
    else
        print("Reusing verified remote part: " .. partNumberText:get_as_string())
    end

    completion.i = partIndex
    completion:update_child_content("Part[i]|PartNumber", partNumberText:get_as_string())
    completion:update_child_content("Part[i]|ETag", partEtag)
    completion:update_child_content("Part[i]|ChecksumSHA256", partChecksum)
    partIndex = partIndex + 1
end

files:file_close()
-- Recheck the entire immutable source before committing its parts.
local finalSourceHash = signer:hash_file_enc(filePath)
stringCompare:set_string(finalSourceHash)
local stringMatch41 = stringCompare:contents_equal(sourceHash, true)
if (not signer.last_method_success) or (not stringMatch41) then
    print("Source changed; completion was not sent.")
    return
end

compositeChecksum = digest:hash_bd_enc(concatenatedDigests)
if not digest.last_method_success then
    print("Could not compute composite checksum.")
    return
end

number:set_string(compositeChecksum)
number:append("-")
number:append_int(numParts)
compositeChecksum = number:get_as_string()
success = pending:update_string("uploadId", uploadId)
if not success then
    print("Could not save uploadId.")
    return
end

success = pending:update_string("sourceHash", sourceHash)
if not success then
    print("Could not save sourceHash.")
    return
end

success = pending:update_string("uploadToken", uploadToken)
if not success then
    print("Could not save uploadToken.")
    return
end

success = pending:update_string("checksum", compositeChecksum)
if not success then
    print("Could not save checksum.")
    return
end

success = pending:write_file(pendingPath)
if not success then
    print("Could not save completion recovery record.")
    return
end

local requestBody = completion:get_xml()
query:clear()
if query.length > 0 then
    query:append("&")
end

query:append("uploadId=")
query:append(http:url_encode(uploadId))
http:clear_headers()
success = now:set_from_current_system_time()
if not success then
    print("Could not read system time.")
    return
end

timestamp:set_string(now:get_as_timestamp(false))
replaceCount = timestamp:replace("-", "")
replaceCount = timestamp:replace(":", "")
amzDate = timestamp:get_as_string()
dateStamp = timestamp:get_range(0, 8, false)
payloadHash = signer:hash_string_enc(requestBody)
if not signer.last_method_success then
    print("Could not hash payload.")
    return
end

canonicalHeaders:clear()
signedHeaders:clear()
if signedHeaders.length > 0 then
    signedHeaders:append(";")
end

signedHeaders:append("host")
canonicalHeaders:append("host:")
canonicalHeaders:append(host:get_as_string())
canonicalHeaders:append("\n")
http:set_request_header("host", host:get_as_string())
if signedHeaders.length > 0 then
    signedHeaders:append(";")
end

signedHeaders:append("x-amz-checksum-type")
canonicalHeaders:append("x-amz-checksum-type:")
canonicalHeaders:append("COMPOSITE")
canonicalHeaders:append("\n")
http:set_request_header("x-amz-checksum-type", "COMPOSITE")
if signedHeaders.length > 0 then
    signedHeaders:append(";")
end

signedHeaders:append("x-amz-content-sha256")
canonicalHeaders:append("x-amz-content-sha256:")
canonicalHeaders:append(payloadHash)
canonicalHeaders:append("\n")
http:set_request_header("x-amz-content-sha256", payloadHash)
if signedHeaders.length > 0 then
    signedHeaders:append(";")
end

signedHeaders:append("x-amz-date")
canonicalHeaders:append("x-amz-date:")
canonicalHeaders:append(amzDate)
canonicalHeaders:append("\n")
http:set_request_header("x-amz-date", amzDate)
if credentials:has_member("session_token") then
    if signedHeaders.length > 0 then
        signedHeaders:append(";")
    end

    signedHeaders:append("x-amz-security-token")
    canonicalHeaders:append("x-amz-security-token:")
    canonicalHeaders:append(credentials:string_of("session_token"))
    canonicalHeaders:append("\n")
    http:set_request_header("x-amz-security-token", credentials:string_of("session_token"))
end

canonical:clear()
canonical:append("POST\n")
canonical:append(uri:get_as_string())
canonical:append("\n")
canonical:append(query:get_as_string())
canonical:append("\n")
canonical:append(canonicalHeaders:get_as_string())
canonical:append("\n")
canonical:append(signedHeaders:get_as_string())
canonical:append("\n")
canonical:append(payloadHash)
canonicalHash = signer:hash_string_enc(canonical:get_as_string())
if not signer.last_method_success then
    print("Could not hash canonical request.")
    return
end

scope:clear()
scope:append(dateStamp)
scope:append("/")
scope:append(region)
scope:append("/s3/aws4_request")
stringToSign:clear()
stringToSign:append("AWS4-HMAC-SHA256\n")
stringToSign:append(amzDate)
stringToSign:append("\n")
stringToSign:append(scope:get_as_string())
stringToSign:append("\n")
stringToSign:append(canonicalHash)
signingKey:set_string("AWS4")
signingKey:append(credentials:string_of("secret_key"))
success = signer:set_mac_key_string(signingKey:get_as_string())
if not success then
    print("Could not set signing key.")
    return
end

derivedKey = signer:mac_string_enc(dateStamp)
if not signer.last_method_success then
    print("Could not derive signing key.")
    return
end

success = signer:set_mac_key_encoded(derivedKey, "hex")
if not success then
    print("Could not set signing key.")
    return
end

derivedKey = signer:mac_string_enc(region)
if not signer.last_method_success then
    print("Could not derive signing key.")
    return
end

success = signer:set_mac_key_encoded(derivedKey, "hex")
if not success then
    print("Could not set signing key.")
    return
end

derivedKey = signer:mac_string_enc("s3")
if not signer.last_method_success then
    print("Could not derive signing key.")
    return
end

success = signer:set_mac_key_encoded(derivedKey, "hex")
if not success then
    print("Could not set signing key.")
    return
end

derivedKey = signer:mac_string_enc("aws4_request")
if not signer.last_method_success then
    print("Could not derive signing key.")
    return
end

success = signer:set_mac_key_encoded(derivedKey, "hex")
if not success then
    print("Could not set signing key.")
    return
end

signature = signer:mac_string_enc(stringToSign:get_as_string())
if not signer.last_method_success then
    print("Could not sign request.")
    return
end

authorization:clear()
authorization:append("AWS4-HMAC-SHA256 Credential=")
authorization:append(credentials:string_of("access_key"))
authorization:append("/")
authorization:append(scope:get_as_string())
authorization:append(", SignedHeaders=")
authorization:append(signedHeaders:get_as_string())
authorization:append(", Signature=")
authorization:append(signature)
http:set_request_header("Authorization", authorization:get_as_string())
url:set_string("https://")
url:append(host:get_as_string())
url:append(uri:get_as_string())
if query.length > 0 then
    url:append("?")
    url:append(query:get_as_string())
end

success = http:http_str("POST", url:get_as_string(), requestBody, "utf-8", "application/xml", response)
if (not success) or (response.status_code ~= 200) then
    print("Request failed or returned unexpected HTTP status: " .. response.status_code)
    -- Preserve progress. Inspect full diagnostics privately; do not log secrets.
    return
end

success = xml:load_xml(response.body_str)
if not success then
    print("Invalid XML response.")
    return
end

stringCompare:set_string(xml.tag)
local stringMatch42 = stringCompare:contents_equal("CompleteMultipartUploadResult", true)
if not stringMatch42 then
    print("Unexpected XML result, possibly an embedded S3 error. Inspect privately.")
    return
end

confirmed = xml:get_child_content("ChecksumSHA256")
stringCompare:set_string(confirmed)
local stringMatch43 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch43) then
    print("Missing required ChecksumSHA256.")
    return
end

stringCompare:set_string(confirmed)
local stringMatch44 = stringCompare:contents_equal(compositeChecksum, true)
if not stringMatch44 then
    print("Completion checksum differs; preserve checkpoint and inspect object.")
    return
end

success = state:update_string("compositeChecksum", compositeChecksum)
if not success then
    print("Could not save compositeChecksum.")
    return
end

success = state:write_file("qa_output/s3-multipart/completed.json.tmp")
if not success then
    print("Completion succeeded but receipt could not be saved; preserve the checkpoint.")
    return
end

success = files:file_rename("qa_output/s3-multipart/completed.json.tmp", receiptPath)
if not success then
    print("Completion receipt remains at its temporary path.")
    return
end

print("Multipart upload completed and verified.")