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

Amazon Glacier: Resume an Archive Download with Verified Chunks

See more Amazon Glacier Examples

For existing Amazon Glacier vault customers. The standalone vault service is closed to new customers. These examples use its REST API version 2012-06-01, not the S3 bucket APIs used by S3 Glacier storage classes. See AWS service guidance.

Downloads a completed full-archive retrieval job in fixed 8 MiB ranges. Set the job ID, cache directory, and final path. Start with an empty, private cache directory on the same filesystem as the final output, then rerun with exactly the same settings to resume. Only one process may use the directory. No new retrieval job is initiated, even if the old job expires.

A saved identity binds progress to region, vault, job, archive ID, size, tree hash, chunk size, and final path. Every cached chunk is rehashed and its length and range checked before reuse. New chunks require HTTP 206, exact Content-Range and Content-Length, actual length, and a matching response tree hash before their temporary file is committed. An interrupted chunk is downloaded again; already verified chunks are retained. A damaged checkpoint or cached chunk stops with an explanation. Local cache files and receipts must be protected from other writers.

After downloading, the example assembles one chunk at a time and checks the entire file's byte count and archive tree hash before renaming it. Interrupted assembly is rebuilt from the cache. Existing final output is accepted only if it matches; other files are not overwritten. Chunks remain for inspection or manual cleanup. Allow disk space for both the complete chunk cache and assembled archive, plus one temporary chunk. A disk-full, network, or checksum failure is not success.

Uses decimal strings and bounded 32-bit arithmetic for archive offsets through the 40 TiB archive limit, including beyond 2 GiB. This produces up to 5,242,880 chunk files plus receipts at that limit; larger power-of-two chunks are more practical for very large archives, but require adapting the arithmetic and checkpoint schema. Empty archives use the single-download example. For partial retrieval jobs use range output download instead.

Requires glacier:DescribeJob and glacier:GetJobOutput. Resume promptly while output is retained (at least 24 hours after successful completion). If it has expired, initiate a new retrieval deliberately and use a new cache directory; cached chunks are not automatically transferred to a different job.

Uses AWS Signature Version 4 with service glacier. Set the region once; the example builds the commercial AWS endpoint. Other partitions require the appropriate endpoint suffix. /-/ selects the signing account; change the vault name and IDs to your own resources. Load private qa_data/aws/glacier.json with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles or refresh credentials. TLS certificate verification is enabled explicitly.

Checks transport completion, the operation-specific HTTP status, and parsed data separately. Inspect full diagnostics privately. Renew expired credentials; use bounded backoff with jitter for retryable reads. Uploads and job initiation can succeed before a connection fails, so do not blindly resubmit them. Configure IAM permissions for only the required operations and vault resources.

AWS reference

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoCredentials
    String sRegion
    Handle hoEndpoint
    Variant vAws
    Handle hoAws
    Handle hoRest
    Variant vConnection
    Handle hoConnection
    Handle hoResult
    Handle hoError
    Variant vResponseBody
    Handle hoResponseBody
    String sJobId
    String sExpectedSize
    String sExpectedHash
    Integer iChunkSize
    Integer iChunkCount
    Integer iRemainder
    Integer iPosition
    Handle hoSizeText
    Handle hoDecimalDigits
    Handle hoDigit
    String sCacheDir
    String sFinalPath
    Handle hoFiles
    Handle hoPath
    String sManifestPath
    Handle hoManifest
    Handle hoIdentity
    Handle hoCacheContents
    Handle hoCrypt
    String sFinalSize
    String sFinalHash
Header    Handle hoRangeHeader
    Handle hoContentRange
    Handle hoByteCount
    Handle hoReceipt
    Integer iChunkIndex
    Integer iByteHigh
    Integer iByteLow
    Integer iEndHigh
    Integer iEndLow
    Handle hoRange
s    Handle hoDigits
    Integer iChunkBytes
    String sRangeKey
    String sChunkPath
    String sReceiptPath
    String sTemporaryPath
    String sCachedHash
    Integer iHttpStatus
    String sResponseRange
    String sResponseLength
    String sResponseHash
    Variant vOutput
    Handle hoOutput
    String sActualSize
    String sActualHash
    String sAssembledPath
    Handle hoAssembled
    Variant vData
    Handle hoData
    String sAssembledSize
    String sAssembledHash
    String sTemp1
    String sTemp2
    String sTemp3
    String sTemp4
    Integer iTemp1
    Integer iTemp2
    Boolean bTemp1

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    Move False To iSuccess
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials authorized for the Glacier operation.
    Get Create (RefClass(cComChilkatJsonObject)) To hoCredentials
    If (Not(IsComObjectCreated(hoCredentials))) Begin
        Send CreateComObject of hoCredentials
    End
    Set ComStrict Of hoCredentials To True
    Get ComLoadFile Of hoCredentials "qa_data/aws/glacier.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not load private AWS credentials."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoCredentials "access_key" To iTemp1
    Get ComStringOf Of hoCredentials "access_key" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid access_key."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoCredentials "secret_key" To iTemp1
    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid secret_key."
        Procedure_Return
    End

    //  Set this once to the region containing the vault.
    Move "us-west-2" To sRegion
    Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
    If (Not(IsComObjectCreated(hoEndpoint))) Begin
        Send CreateComObject of hoEndpoint
    End
    Get ComAppend Of hoEndpoint "glacier." To iSuccess
    Get ComAppend Of hoEndpoint sRegion To iSuccess
    Get ComAppend Of hoEndpoint ".amazonaws.com" To iSuccess
    Get Create (RefClass(cComChilkatAuthAws)) To hoAws
    If (Not(IsComObjectCreated(hoAws))) Begin
        Send CreateComObject of hoAws
    End
    Get ComStringOf Of hoCredentials "access_key" To sTemp1
    Set ComAccessKey Of hoAws To sTemp1
    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    Set ComSecretKey Of hoAws To sTemp1
    Set ComRegion Of hoAws To sRegion
    Set ComServiceName Of hoAws To "glacier"
    Set ComSignatureVersion Of hoAws To 4
    Get Create (RefClass(cComChilkatRest)) To hoRest
    If (Not(IsComObjectCreated(hoRest))) Begin
        Send CreateComObject of hoRest
    End
    Set ComConnectTimeoutMs Of hoRest To 20000
    Set ComIdleTimeoutMs Of hoRest To 60000
    Get pvComObject of hoAws to vAws
    Get ComSetAuthAws Of hoRest vAws To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not configure AWS signing."
        Procedure_Return
    End

    //  Temporary IAM/STS credentials require their session token on every signed request.
    //  Include the token in the signed query. Keep request URLs and diagnostics private.
    //  Leave session_token absent or empty only for credentials that do not have one.
    Get ComHasMember Of hoCredentials "session_token" To bTemp1
    If (bTemp1 = True) Begin
        Get ComJsonTypeOf Of hoCredentials "session_token" To iTemp1
        If (iTemp1 <> 1) Begin
            Showln "session_token must be a string."
            Procedure_Return
        End

        Get ComStringOf Of hoCredentials "session_token" To sTemp1
        If (sTemp1 <> "") Begin
            Get ComStringOf Of hoCredentials "session_token" To sTemp1
            Get ComAddQueryParam Of hoRest "X-Amz-Security-Token" sTemp1 To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not set the session-token parameter."
                Procedure_Return
            End

        End

    End

    //  Supply a Socket to explicitly enable TLS certificate verification.
    Get Create (RefClass(cComChilkatSocket)) To hoConnection
    If (Not(IsComObjectCreated(hoConnection))) Begin
        Send CreateComObject of hoConnection
    End
    Set ComRequireSslCertVerify Of hoConnection To True
    Set ComMaxReadIdleMs Of hoConnection To 60000
    Set ComMaxSendIdleMs Of hoConnection To 60000
    Get ComGetAsString Of hoEndpoint To sTemp1
    Get ComConnect Of hoConnection sTemp1 443 True 20000 To iSuccess
    If (iSuccess <> True) Begin
        Showln "TLS connection failed; inspect diagnostics privately."
        Procedure_Return
    End

    Get pvComObject of hoConnection to vConnection
    Get ComUseConnection Of hoRest vConnection True To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not attach the TLS connection."
        Procedure_Return
    End

    Get ComAddHeader Of hoRest "x-amz-glacier-version" "2012-06-01" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set x-amz-glacier-version."
        Procedure_Return
    End

    //  A hyphen selects the account belonging to the signing credentials.
    //  Use the original, URL-safe vault name and IDs returned by Glacier.
    Get ComAddPathParam Of hoRest "{vault}" "chilkat" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set vault name."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoResult
    If (Not(IsComObjectCreated(hoResult))) Begin
        Send CreateComObject of hoResult
    End
    Set ComStrict Of hoResult To True
    Get Create (RefClass(cComChilkatJsonObject)) To hoError
    If (Not(IsComObjectCreated(hoError))) Begin
        Send CreateComObject of hoError
    End
    Set ComStrict Of hoError To True
    Get Create (RefClass(cComChilkatStringBuilder)) To hoResponseBody
    If (Not(IsComObjectCreated(hoResponseBody))) Begin
        Send CreateComObject of hoResponseBody
    End
    Move "YOUR_JOB_ID" To sJobId
    Get ComAddPathParam Of hoRest "{job}" sJobId To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set job ID."
        Procedure_Return
    End

    Get pvComObject of hoResponseBody to vResponseBody
    Get ComFullRequestNoBodySb Of hoRest "GET" "/-/vaults/{vault}/jobs/{job}" vResponseBody To iSuccess
    If (iSuccess <> True) Begin
        Showln "Request did not complete; inspect diagnostics privately. Check state before retrying a change."
        Procedure_Return
    End

    Get ComResponseStatusCode Of hoRest To iTemp1
    If (iTemp1 <> 200) Begin
        Get ComResponseStatusCode Of hoRest To iTemp1
        Showln "Glacier HTTP status: " iTemp1
        Get pvComObject of hoResponseBody to vResponseBody
        Get ComLoadSb Of hoError vResponseBody To iSuccess
        If (iSuccess = True) Begin
            Get ComJsonTypeOf Of hoError "code" To iTemp1
            If (iTemp1 = 1) Begin
                Get ComStringOf Of hoError "code" To sTemp1
                Showln "AWS error code: " sTemp1
            End

        End

        Get ComResponseHdrByName Of hoRest "x-amzn-RequestId" To sTemp1
        Showln "AWS request ID: " sTemp1
        //  Inspect full errors privately. An HTTP error is not a successful operation.
        Procedure_Return
    End

    Get pvComObject of hoResponseBody to vResponseBody
    Get ComLoadSb Of hoResult vResponseBody To iSuccess
    If (iSuccess <> True) Begin
        Showln "Expected valid JSON response."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "Completed" To iTemp1
    If (iTemp1 <> 5) Begin
        Showln "Missing or invalid Completed."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "StatusCode" To iTemp1
    If (iTemp1 <> 1) Begin
        Showln "Missing or invalid StatusCode."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "StatusCode" To sTemp1
    If (sTemp1 = "") Begin
        Showln "Empty StatusCode."
        Procedure_Return
    End

    Get ComBoolOf Of hoResult "Completed" To bTemp1
    Get ComStringOf Of hoResult "StatusCode" To sTemp1
    If ((bTemp1 <> True) Or (sTemp1 <> "Succeeded")) Begin
        Showln "Job is not successfully complete. Resume later only if InProgress."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "Action" To sTemp1
    If (sTemp1 <> "ArchiveRetrieval") Begin
        Showln "Wrong job type."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "SHA256TreeHash" To iTemp1
    If (iTemp1 <> 1) Begin
        Showln "Missing or invalid SHA256TreeHash."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "SHA256TreeHash" To sTemp1
    If (sTemp1 = "") Begin
        Showln "Empty SHA256TreeHash."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "ArchiveSizeInBytes" To iTemp1
    If (iTemp1 <> 2) Begin
        Showln "Missing or invalid ArchiveSizeInBytes."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "ArchiveId" To iTemp1
    If (iTemp1 <> 1) Begin
        Showln "Missing or invalid ArchiveId."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "ArchiveId" To sTemp1
    If (sTemp1 = "") Begin
        Showln "Empty ArchiveId."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoResult "ArchiveSHA256TreeHash" To iTemp1
    If (iTemp1 <> 1) Begin
        Showln "Missing or invalid ArchiveSHA256TreeHash."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "ArchiveSHA256TreeHash" To sTemp1
    If (sTemp1 = "") Begin
        Showln "Empty ArchiveSHA256TreeHash."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "ArchiveSizeInBytes" To sExpectedSize
    Get ComStringOf Of hoResult "ArchiveSHA256TreeHash" To sExpectedHash
    Get ComStringOf Of hoResult "SHA256TreeHash" To sTemp1
    If (sTemp1 <> sExpectedHash) Begin
        Showln "Use a full-archive retrieval job for this resumable example."
        Procedure_Return
    End

    //  Fixed 8 MiB chunks are power-of-two and tree-hash aligned.
    //  Decimal long division avoids 32-bit overflow in every generated language.
    Move 8388608 To iChunkSize
    Move 0 To iChunkCount
    Move 0 To iRemainder
    Move 0 To iPosition
    Get Create (RefClass(cComChilkatStringBuilder)) To hoSizeText
    If (Not(IsComObjectCreated(hoSizeText))) Begin
        Send CreateComObject of hoSizeText
    End
    Get Create (RefClass(cComChilkatStringBuilder)) To hoDecimalDigits
    If (Not(IsComObjectCreated(hoDecimalDigits))) Begin
        Send CreateComObject of hoDecimalDigits
    End
    Get Create (RefClass(cComChilkatStringBuilder)) To hoDigit
    If (Not(IsComObjectCreated(hoDigit))) Begin
        Send CreateComObject of hoDigit
    End
    Get ComAppend Of hoSizeText sExpectedSize To iSuccess
    Get ComAppend Of hoDecimalDigits "0123456789" To iSuccess
    Get ComLength Of hoSizeText To iTemp1
    Get ComLength Of hoSizeText To iTemp2
    If ((iTemp1 = 0) Or (iTemp2 > 14)) Begin
        Showln "Invalid archive size."
        Procedure_Return
    End

    While (iPosition < (ComLength(hoSizeText)))
        Get ComGetRange Of hoSizeText iPosition 1 False To sTemp1
        Get ComSetString Of hoDigit sTemp1 To iSuccess
        Get ComContains Of hoDecimalDigits (ComGetAsString(hoDigit)) True To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Invalid decimal archive size."
            Procedure_Return
        End

        Get ComIntValue Of hoDigit To iTemp1
        Move (iRemainder * 10 + iTemp1) To iRemainder
        //  At most nine subtractions per digit; avoids language-specific division.
        Move (iChunkCount * 10) To iChunkCount
        While (iRemainder >= iChunkSize)
            Move (iChunkCount + 1) To iChunkCount
            Move (iRemainder - iChunkSize) To iRemainder
        Loop

        Move (iPosition + 1) To iPosition
    Loop

    If ((iChunkCount > 5242880) Or ((iChunkCount = 5242880) And (iRemainder <> 0))) Begin
        Showln "Archive exceeds the 40 TiB service limit."
        Procedure_Return
    End

    If ((iChunkCount = 0) And (iRemainder = 0)) Begin
        Showln "Use the single-download example for an empty archive."
        Procedure_Return
    End

    If (iRemainder <> 0) Begin
        Move (iChunkCount + 1) To iChunkCount
    End

    //  This dedicated directory belongs to ONE job. Use a new empty directory
    //  when selecting another job. Run only one process against it at a time.
    Move "qa_output/glacier-download" To sCacheDir
    Move "qa_output/archive-resumed.dat" To sFinalPath
    Get Create (RefClass(cComCkFileAccess)) To hoFiles
    If (Not(IsComObjectCreated(hoFiles))) Begin
        Send CreateComObject of hoFiles
    End
    Get ComDirEnsureExists Of hoFiles sCacheDir To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not create private download directory."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatStringBuilder)) To hoPath
    If (Not(IsComObjectCreated(hoPath))) Begin
        Send CreateComObject of hoPath
    End
    Get ComAppend Of hoPath sCacheDir To iSuccess
    Get ComAppend Of hoPath "/manifest.json" To iSuccess
    Get ComGetAsString Of hoPath To sManifestPath
    Get Create (RefClass(cComChilkatJsonObject)) To hoManifest
    If (Not(IsComObjectCreated(hoManifest))) Begin
        Send CreateComObject of hoManifest
    End
    Set ComStrict Of hoManifest To True
    Get Create (RefClass(cComChilkatJsonObject)) To hoIdentity
    If (Not(IsComObjectCreated(hoIdentity))) Begin
        Send CreateComObject of hoIdentity
    End
    Get ComUpdateString Of hoIdentity "version" "1" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set version."
        Procedure_Return
    End

    Get ComUpdateString Of hoIdentity "region" sRegion To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set region."
        Procedure_Return
    End

    Get ComUpdateString Of hoIdentity "vault" "chilkat" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set vault."
        Procedure_Return
    End

    Get ComUpdateString Of hoIdentity "jobId" sJobId To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set jobId."
        Procedure_Return
    End

    Get ComStringOf Of hoResult "ArchiveId" To sTemp1
    Get ComUpdateString Of hoIdentity "archiveId" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set archiveId."
        Procedure_Return
    End

    Get ComUpdateString Of hoIdentity "size" sExpectedSize To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set size."
        Procedure_Return
    End

    Get ComUpdateString Of hoIdentity "treeHash" sExpectedHash To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set treeHash."
        Procedure_Return
    End

    Get ComUpdateString Of hoIdentity "chunkSize" "8388608" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set chunkSize."
        Procedure_Return
    End

    Get ComUpdateString Of hoIdentity "finalPath" sFinalPath To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set finalPath."
        Procedure_Return
    End

    Get ComFileExists Of hoFiles sManifestPath To bTemp1
    If (bTemp1 = True) Begin
        Get ComLoadFile Of hoManifest sManifestPath To iSuccess
        If (iSuccess <> True) Begin
            Showln "Invalid checkpoint. Preserve the cache and inspect it before restarting."
            Procedure_Return
        End

        Get ComStringOf Of hoManifest "version" To sTemp1
        Get ComStringOf Of hoIdentity "version" To sTemp2
        If (sTemp1 <> sTemp2) Begin
            Showln "Checkpoint belongs to different download settings. Use a new empty cache directory."
            Procedure_Return
        End

        Get ComStringOf Of hoManifest "region" To sTemp1
        Get ComStringOf Of hoIdentity "region" To sTemp2
        If (sTemp1 <> sTemp2) Begin
            Showln "Checkpoint belongs to different download settings. Use a new empty cache directory."
            Procedure_Return
        End

        Get ComStringOf Of hoManifest "vault" To sTemp1
        Get ComStringOf Of hoIdentity "vault" To sTemp2
        If (sTemp1 <> sTemp2) Begin
            Showln "Checkpoint belongs to different download settings. Use a new empty cache directory."
            Procedure_Return
        End

        Get ComStringOf Of hoManifest "jobId" To sTemp1
        Get ComStringOf Of hoIdentity "jobId" To sTemp2
        If (sTemp1 <> sTemp2) Begin
            Showln "Checkpoint belongs to different download settings. Use a new empty cache directory."
            Procedure_Return
        End

        Get ComStringOf Of hoManifest "archiveId" To sTemp1
        Get ComStringOf Of hoIdentity "archiveId" To sTemp2
        If (sTemp1 <> sTemp2) Begin
            Showln "Checkpoint belongs to different download settings. Use a new empty cache directory."
            Procedure_Return
        End

        Get ComStringOf Of hoManifest "size" To sTemp1
        Get ComStringOf Of hoIdentity "size" To sTemp2
        If (sTemp1 <> sTemp2) Begin
            Showln "Checkpoint belongs to different download settings. Use a new empty cache directory."
            Procedure_Return
        End

        Get ComStringOf Of hoManifest "treeHash" To sTemp1
        Get ComStringOf Of hoIdentity "treeHash" To sTemp2
        If (sTemp1 <> sTemp2) Begin
            Showln "Checkpoint belongs to different download settings. Use a new empty cache directory."
            Procedure_Return
        End

        Get ComStringOf Of hoManifest "chunkSize" To sTemp1
        Get ComStringOf Of hoIdentity "chunkSize" To sTemp2
        If (sTemp1 <> sTemp2) Begin
            Showln "Checkpoint belongs to different download settings. Use a new empty cache directory."
            Procedure_Return
        End

        Get ComStringOf Of hoManifest "finalPath" To sTemp1
        Get ComStringOf Of hoIdentity "finalPath" To sTemp2
        If (sTemp1 <> sTemp2) Begin
            Showln "Checkpoint belongs to different download settings. Use a new empty cache directory."
            Procedure_Return
        End

    End
    Else Begin
        Get Create (RefClass(cComChilkatDirTree)) To hoCacheContents
        If (Not(IsComObjectCreated(hoCacheContents))) Begin
            Send CreateComObject of hoCacheContents
        End
        Set ComBaseDir Of hoCacheContents To sCacheDir
        Set ComRecurse Of hoCacheContents To False
        Get ComBeginIterate Of hoCacheContents To iSuccess
        Get ComDoneIterating Of hoCacheContents To bTemp1
        If ((iSuccess = True) Or (bTemp1 <> True)) Begin
            Showln "First run requires an empty, readable cache directory."
            Procedure_Return
        End

        Get ComWriteFile Of hoIdentity sManifestPath To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not save download identity."
            Procedure_Return
        End

    End

    Get Create (RefClass(cComChilkatCrypt2)) To hoCrypt
    If (Not(IsComObjectCreated(hoCrypt))) Begin
        Send CreateComObject of hoCrypt
    End
    Set ComHashAlgorithm Of hoCrypt To "sha256-tree-hash"
    Set ComEncodingMode Of hoCrypt To "hexlower"
    Get ComFileExists Of hoFiles sFinalPath To bTemp1
    If (bTemp1 = True) Begin
        Get ComFileSizeStr Of hoFiles sFinalPath To sFinalSize
        Get ComHashFileENC Of hoCrypt sFinalPath To sFinalHash
        Get ComLastMethodSuccess Of hoCrypt To bTemp1
        If ((bTemp1 <> True) Or (sFinalSize <> sExpectedSize) Or (sFinalHash <> sExpectedHash)) Begin
            Showln "Existing final file differs; choose another final output path."
            Procedure_Return
        End

        Showln "Archive already downloaded and verified."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatStringBuilder)) To hoRangeHeader
    If (Not(IsComObjectCreated(hoRangeHeader))) Begin
        Send CreateComObject of hoRangeHeader
    End
    Get Create (RefClass(cComChilkatStringBuilder)) To hoContentRange
    If (Not(IsComObjectCreated(hoContentRange))) Begin
        Send CreateComObject of hoContentRange
    End
    Get Create (RefClass(cComChilkatStringBuilder)) To hoByteCount
    If (Not(IsComObjectCreated(hoByteCount))) Begin
        Send CreateComObject of hoByteCount
    End
    Get Create (RefClass(cComChilkatJsonObject)) To hoReceipt
    If (Not(IsComObjectCreated(hoReceipt))) Begin
        Send CreateComObject of hoReceipt
    End
    Set ComStrict Of hoReceipt To True
    Move 0 To iChunkIndex
    Move 0 To iByteHigh
    Move 0 To iByteLow

    Get Create (RefClass(cComChilkatStringBuilder)) To hoRange
    If (Not(IsComObjectCreated(hoRange))) Begin
        Send CreateComObject of hoRange
    End
    Get Create (RefClass(cComChilkatStringBuilder)) To hoDigits
    If (Not(IsComObjectCreated(hoDigits))) Begin
        Send CreateComObject of hoDigits
    End
    While (iChunkIndex < iChunkCount)
        Move iChunkSize To iChunkBytes
        If ((iChunkIndex = iChunkCount - 1) And (iRemainder <> 0)) Begin
            Move iRemainder To iChunkBytes
        End

        Send ComClear To hoRange
        Send ComClear To hoDigits
        Get ComAppendInt Of hoDigits iByteLow To iSuccess
        If (iByteHigh > 0) Begin
            While ((ComLength(hoDigits)) < 9)
                Get ComPrepend Of hoDigits "0" To iSuccess
            Loop

            Get ComAppendInt Of hoRange iByteHigh To iSuccess
        End

        Get ComGetAsString Of hoDigits To sTemp1
        Get ComAppend Of hoRange sTemp1 To iSuccess
        Get ComAppend Of hoRange "-" To iSuccess
        Move iByteHigh To iEndHigh
        Move (iByteLow + iChunkBytes - 1) To iEndLow
        If (iEndLow >= 1000000000) Begin
            Move (iEndLow - 1000000000) To iEndLow
            Move (iEndHigh + 1) To iEndHigh
        End

        Send ComClear To hoDigits
        Get ComAppendInt Of hoDigits iEndLow To iSuccess
        If (iEndHigh > 0) Begin
            While ((ComLength(hoDigits)) < 9)
                Get ComPrepend Of hoDigits "0" To iSuccess
            Loop

            Get ComAppendInt Of hoRange iEndHigh To iSuccess
        End

        Get ComGetAsString Of hoDigits To sTemp1
        Get ComAppend Of hoRange sTemp1 To iSuccess
        Get ComGetAsString Of hoRange To sRangeKey
        Get ComSetString Of hoRangeHeader "bytes=" To iSuccess
        Get ComAppend Of hoRangeHeader sRangeKey To iSuccess
        Get ComSetString Of hoContentRange "bytes " To iSuccess
        Get ComAppend Of hoContentRange sRangeKey To iSuccess
        Get ComAppend Of hoContentRange "/" To iSuccess
        Get ComAppend Of hoContentRange sExpectedSize To iSuccess
        Send ComClear To hoByteCount
        Get ComAppendInt Of hoByteCount iChunkBytes To iSuccess
        Get ComSetString Of hoPath sCacheDir To iSuccess
        Get ComAppend Of hoPath "/chunk-" To iSuccess
        Get ComAppendInt Of hoPath iChunkIndex To iSuccess
        Get ComGetAsString Of hoPath To sChunkPath
        Get ComAppend Of hoPath ".json" To iSuccess
        Get ComGetAsString Of hoPath To sReceiptPath
        Get ComSetString Of hoPath sChunkPath To iSuccess
        Get ComAppend Of hoPath ".part" To iSuccess
        Get ComGetAsString Of hoPath To sTemporaryPath
        Get ComFileExists Of hoFiles sChunkPath To bTemp1
        If (bTemp1 = True) Begin
            Get ComLoadFile Of hoReceipt sReceiptPath To iSuccess
            If (iSuccess <> True) Begin
                Showln "Cached chunk lacks a valid receipt. Preserve the cache and inspect it."
                Procedure_Return
            End

            Get ComHashFileENC Of hoCrypt sChunkPath To sCachedHash
            Get ComLastMethodSuccess Of hoCrypt To bTemp1
            Get ComStringOf Of hoReceipt "treeHash" To sTemp1
            Get ComStringOf Of hoReceipt "range" To sTemp2
            Get ComFileSizeStr Of hoFiles sChunkPath To sTemp3
            Get ComGetAsString Of hoByteCount To sTemp4
            If ((bTemp1 <> True) Or (sCachedHash <> sTemp1) Or (sTemp2 <> sRangeKey) Or (sTemp3 <> sTemp4)) Begin
                Showln "Cached chunk failed verification. Remove only that chunk and its receipt, then rerun."
                Procedure_Return
            End

            Showln "Reusing verified chunk: " iChunkIndex
        End
        Else Begin
            Get ComGetAsString Of hoRangeHeader To sTemp1
            Get ComAddHeader Of hoRest "Range" sTemp1 To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not set Range."
                Procedure_Return
            End

            Get ComSendReqNoBody Of hoRest "GET" "/-/vaults/{vault}/jobs/{job}/output" To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not send range request. Rerun to resume."
                Procedure_Return
            End

            Get ComReadResponseHeader Of hoRest To iHttpStatus
            If (iHttpStatus <> 206) Begin
                Showln "Expected HTTP 206 for range download. Job may have expired; no new retrieval was started."
                Procedure_Return
            End

            Get ComResponseHdrByName Of hoRest "Content-Range" To sResponseRange
            Get ComLastMethodSuccess Of hoRest To bTemp1
            Get ComGetAsString Of hoContentRange To sTemp1
            If ((bTemp1 <> True) Or (sResponseRange <> sTemp1)) Begin
                Showln "Unexpected Content-Range; refusing download."
                Procedure_Return
            End

            Get ComResponseHdrByName Of hoRest "Content-Length" To sResponseLength
            Get ComLastMethodSuccess Of hoRest To bTemp1
            Get ComGetAsString Of hoByteCount To sTemp1
            If ((bTemp1 <> True) Or (sResponseLength <> sTemp1)) Begin
                Showln "Unexpected Content-Length; refusing download."
                Procedure_Return
            End

            Get ComResponseHdrByName Of hoRest "x-amz-sha256-tree-hash" To sResponseHash
            Get ComLastMethodSuccess Of hoRest To bTemp1
            If ((bTemp1 <> True) Or (sResponseHash = "")) Begin
                Showln "Missing range tree hash. Require a tree-hash-aligned retrieval and download range."
                Procedure_Return
            End

            Get Create (RefClass(cComChilkatStream)) To hoOutput
            If (Not(IsComObjectCreated(hoOutput))) Begin
                Send CreateComObject of hoOutput
            End
            Set ComSinkFile Of hoOutput To sTemporaryPath
            Get pvComObject of hoOutput to vOutput
            Get ComReadRespBodyStream Of hoRest vOutput True To iSuccess
            If (iSuccess <> True) Begin
                Showln "Download interrupted; rerun to resume. Temporary bytes are not trusted."
                Procedure_Return
            End

            Get ComFileSizeStr Of hoFiles sTemporaryPath To sActualSize
            Get ComLastMethodSuccess Of hoFiles To bTemp1
            Get ComGetAsString Of hoByteCount To sTemp1
            If ((bTemp1 <> True) Or (sActualSize <> sTemp1)) Begin
                Showln "Downloaded size mismatch."
                Procedure_Return
            End

            Get ComHashFileENC Of hoCrypt sTemporaryPath To sActualHash
            Get ComLastMethodSuccess Of hoCrypt To bTemp1
            If ((bTemp1 <> True) Or (sActualHash <> sResponseHash)) Begin
                Showln "Downloaded tree hash mismatch."
                Procedure_Return
            End

            Get ComUpdateString Of hoReceipt "range" sRangeKey To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not set range."
                Procedure_Return
            End

            Get ComUpdateString Of hoReceipt "treeHash" sActualHash To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not set treeHash."
                Procedure_Return
            End

            Get ComWriteFile Of hoReceipt sReceiptPath To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not save chunk checksum; temporary bytes remain uncommitted."
                Procedure_Return
            End

            Get ComFileRename Of hoFiles sTemporaryPath sChunkPath To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not commit verified chunk."
                Procedure_Return
            End

            Showln "Downloaded verified chunk: " iChunkIndex
        End

        Move iEndHigh To iByteHigh
        Move (iEndLow + 1) To iByteLow
        If (iByteLow = 1000000000) Begin
            Move 0 To iByteLow
            Move (iByteHigh + 1) To iByteHigh
        End

        Move (iChunkIndex + 1) To iChunkIndex
    Loop

    //  Full-archive size plus hash protects against a partial retrieval job too.
    //  Assemble from verified chunks; interrupted assembly is rebuilt on rerun.
    Get ComSetString Of hoPath sCacheDir To iSuccess
    Get ComAppend Of hoPath "/assembled.part" To iSuccess
    Get ComGetAsString Of hoPath To sAssembledPath
    Get Create (RefClass(cComCkFileAccess)) To hoAssembled
    If (Not(IsComObjectCreated(hoAssembled))) Begin
        Send CreateComObject of hoAssembled
    End
    Get ComOpenForWrite Of hoAssembled sAssembledPath To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not open assembly file."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatBinData)) To hoData
    If (Not(IsComObjectCreated(hoData))) Begin
        Send CreateComObject of hoData
    End
    Move 0 To iChunkIndex
    While (iChunkIndex < iChunkCount)
        Get ComSetString Of hoPath sCacheDir To iSuccess
        Get ComAppend Of hoPath "/chunk-" To iSuccess
        Get ComAppendInt Of hoPath iChunkIndex To iSuccess
        Get ComClear Of hoData To iSuccess
        Get ComGetAsString Of hoPath To sTemp1
        Get ComLoadFile Of hoData sTemp1 To iSuccess
        If (iSuccess = True) Begin
            Get pvComObject of hoData to vData
            Get ComFileWriteBd Of hoAssembled vData 0 0 To iSuccess
        End

        If (iSuccess <> True) Begin
            Send ComFileClose To hoAssembled
            Showln "Assembly failed. Verified chunks are retained for resume."
            Procedure_Return
        End

        Move (iChunkIndex + 1) To iChunkIndex
    Loop

    Send ComFileClose To hoAssembled
    Get ComFileSizeStr Of hoFiles sAssembledPath To sAssembledSize
    Get ComHashFileENC Of hoCrypt sAssembledPath To sAssembledHash
    Get ComLastMethodSuccess Of hoCrypt To bTemp1
    If ((bTemp1 <> True) Or (sAssembledSize <> sExpectedSize) Or (sAssembledHash <> sExpectedHash)) Begin
        Showln "Assembled archive failed verification; final output was not created."
        Procedure_Return
    End

    Get ComFileRename Of hoFiles sAssembledPath sFinalPath To iSuccess
    If (iSuccess <> True) Begin
        Showln "Verified assembly could not be renamed; keep the cache."
        Procedure_Return
    End

    Showln "Archive downloaded and verified. Retained chunks can now be removed manually."


End_Procedure