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

Amazon Glacier: Retry Multipart Completion

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.

Uses fixed 8 MiB parts, at most 10,000 parts (78.125 GiB), and buffers one part at a time. The API also allows other power-of-two MiB sizes up to 4 GiB; this portable example deliberately fixes the size. The last part may be smaller. Use a nonempty, immutable file and one writer per upload. Create qa_output first. Byte offsets and archive sizes stay exact in languages with 32-bit integers.

The private checkpoint stores the upload ID, region, vault, file path, size, part size, and full-file tree hash. Preserve it across failures. It contains no AWS credentials. A separate completion receipt records the archive ID. A lost initiation response requires inspecting List Multipart Uploads; starting a new upload is not a retry of the old one. Inactive uploads can expire after 24 hours. Do not abort automatically on transient errors.

Use only after all parts were uploaded and a previous completion response was lost. Sends the identical upload ID, total size, and complete tree hash from the checkpoint, without listing parts or re-uploading bytes. AWS permits idempotent completion for a short period and returns the same archive ID. After completion, List Parts and List Multipart Uploads no longer expose the upload. This example deliberately does not require the local source file. A later 404 cannot prove whether the archive was completed; preserve the checkpoint and investigate your archive catalog/inventory.

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 B4X Downloads

B4X
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim success As Boolean = False
'  Private configuration, not a file in public web content or source control.
'  Load current IAM credentials authorized for the Glacier operation.
Dim credentials As ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/glacier.json")
If success <> True Then
    Log("Could not load private AWS credentials.")
    Return
End If

If (credentials.JsonTypeOf("access_key") <> 1) Or (credentials.StringOf("access_key") = "") Then
    Log("Missing or invalid access_key.")
    Return
End If

If (credentials.JsonTypeOf("secret_key") <> 1) Or (credentials.StringOf("secret_key") = "") Then
    Log("Missing or invalid secret_key.")
    Return
End If

'  Set this once to the region containing the vault.
Dim region As String = "us-west-2"
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("glacier.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As ChilkatAuthAws
aws.Initialize
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "glacier"
aws.SignatureVersion = 4
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
success = rest.SetAuthAws(aws)
If success <> True Then
    Log("Could not configure AWS signing.")
    Return
End If

'  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.
If credentials.HasMember("session_token") = True Then
    If credentials.JsonTypeOf("session_token") <> 1 Then
        Log("session_token must be a string.")
        Return
    End If

    If credentials.StringOf("session_token") <> "" Then
        success = rest.AddQueryParam("X-Amz-Security-Token", credentials.StringOf("session_token"))
        If success <> True Then
            Log("Could not set the session-token parameter.")
            Return
        End If

    End If

End If

'  Supply a Socket to explicitly enable TLS certificate verification.
Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
    Log("TLS connection failed; inspect diagnostics privately.")
    Return
End If

success = rest.UseConnection(connection, True)
If success <> True Then
    Log("Could not attach the TLS connection.")
    Return
End If

success = rest.AddHeader("x-amz-glacier-version", "2012-06-01")
If success <> True Then
    Log("Could not set x-amz-glacier-version.")
    Return
End If

'  A hyphen selects the account belonging to the signing credentials.
'  Use the original, URL-safe vault name and IDs returned by Glacier.
success = rest.AddPathParam("{vault}", "chilkat")
If success <> True Then
    Log("Could not set vault name.")
    Return
End If


Dim body As ChilkatJsonObject
body.Initialize
Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
Dim error As ChilkatJsonObject
error.Initialize
error.Strict = True
Dim requestBody As ChilkatStringBuilder
requestBody.Initialize
Dim responseBody As ChilkatStringBuilder
responseBody.Initialize
Dim files As ChilkatFileAccess
files.Initialize
Dim statePath As String = "qa_output/glacier-multipart.json"
Dim receiptPath As String = "qa_output/glacier-multipart-completed.json"
Dim state As ChilkatJsonObject
state.Initialize
state.Strict = True
Dim saved As ChilkatStringBuilder
saved.Initialize
success = state.LoadFile(statePath)
If success <> True Then
    Log("Could not load the private multipart checkpoint.")
    Return
End If

If state.JsonTypeOf("UploadId") <> 1 Then
    Log("Missing or invalid UploadId.")
    Return
End If

If state.StringOf("UploadId") = "" Then
    Log("Empty UploadId.")
    Return
End If

If state.JsonTypeOf("Region") <> 1 Then
    Log("Missing or invalid Region.")
    Return
End If

If state.StringOf("Region") = "" Then
    Log("Empty Region.")
    Return
End If

If state.JsonTypeOf("VaultName") <> 1 Then
    Log("Missing or invalid VaultName.")
    Return
End If

If state.StringOf("VaultName") = "" Then
    Log("Empty VaultName.")
    Return
End If

If state.JsonTypeOf("FilePath") <> 1 Then
    Log("Missing or invalid FilePath.")
    Return
End If

If state.StringOf("FilePath") = "" Then
    Log("Empty FilePath.")
    Return
End If

If state.JsonTypeOf("ArchiveSize") <> 1 Then
    Log("Missing or invalid ArchiveSize.")
    Return
End If

If state.StringOf("ArchiveSize") = "" Then
    Log("Empty ArchiveSize.")
    Return
End If

If state.JsonTypeOf("TreeHash") <> 1 Then
    Log("Missing or invalid TreeHash.")
    Return
End If

If state.StringOf("TreeHash") = "" Then
    Log("Empty TreeHash.")
    Return
End If

If state.JsonTypeOf("PartSize") <> 1 Then
    Log("Missing or invalid PartSize.")
    Return
End If

If state.StringOf("PartSize") = "" Then
    Log("Empty PartSize.")
    Return
End If

If (state.StringOf("Region") <> region) Or (state.StringOf("VaultName") <> "chilkat") Then
    Log("Checkpoint region/vault differs from this example configuration.")
    Return
End If

If state.StringOf("PartSize") <> "8388608" Then
    Log("This workflow requires the original 8 MiB part size.")
    Return
End If

Dim uploadId As String = state.StringOf("UploadId")
success = rest.AddPathParam("{upload}", uploadId)
If success <> True Then
    Log("Could not set upload ID.")
    Return
End If

If files.FileExists(receiptPath) = True Then
    Log("A completion receipt already exists; read its archive ID.")
    Return
End If

success = rest.AddHeader("x-amz-sha256-tree-hash", state.StringOf("TreeHash"))
If success <> True Then
    Log("Could not set x-amz-sha256-tree-hash.")
    Return
End If

success = rest.AddHeader("x-amz-archive-size", state.StringOf("ArchiveSize"))
If success <> True Then
    Log("Could not set x-amz-archive-size.")
    Return
End If

'  Completion has NO body: never reuse a part's precomputed payload hash.
aws.PrecomputedSha256 = ""
success = rest.SetAuthAws(aws)
If success <> True Then
    Log("Could not reset signing.")
    Return
End If

success = rest.RemoveHeader("x-amz-content-sha256")
If success <> True Then
    Log("Could not clear part payload hash.")
    Return
End If

success = rest.RemoveHeader("Content-Range")
If success <> True Then
    Log("Could not clear part range.")
    Return
End If

success = rest.RemoveHeader("Content-Type")
If success <> True Then
    Log("Could not clear content type.")
    Return
End If

success = rest.FullRequestNoBodySb("POST", "/-/vaults/{vault}/multipart-uploads/{upload}", responseBody)
If success <> True Then
    Log("Request did not complete; inspect diagnostics privately. Check state before retrying a change.")
    Return
End If

If rest.ResponseStatusCode <> 201 Then
    Log("Glacier HTTP status: " & rest.ResponseStatusCode)
    success = error.LoadSb(responseBody)
    If success = True Then
        If error.JsonTypeOf("code") = 1 Then
            Log("AWS error code: " & error.StringOf("code"))
        End If

    End If

    Log("AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId"))
    '  Inspect full errors privately. An HTTP error is not a successful operation.
    Return
End If

Dim archiveId As String = rest.ResponseHdrByName("x-amz-archive-id")
If (rest.LastMethodSuccess <> True) Or (archiveId = "") Then
    Log("Completion response has no archive ID. Preserve the checkpoint and retry identical completion promptly.")
    Return
End If

Log("Archive ID: " & archiveId)
Dim location As String = rest.ResponseHdrByName("Location")
Log("Location: " & location)
Dim returnedHash As String = rest.ResponseHdrByName("x-amz-sha256-tree-hash")
If (rest.LastMethodSuccess = True) And (returnedHash <> state.StringOf("TreeHash")) Then
    Log("Completion checksum mismatch; preserve the printed archive ID and investigate.")
    Return
End If

Dim receipt As ChilkatJsonObject
receipt.Initialize
success = receipt.UpdateString("UploadId", uploadId)
If success <> True Then
    Log("Could not set UploadId.")
    Return
End If

success = receipt.UpdateString("ArchiveId", archiveId)
If success <> True Then
    Log("Could not set ArchiveId.")
    Return
End If

success = receipt.UpdateString("Location", location)
If success <> True Then
    Log("Could not set Location.")
    Return
End If

success = receipt.UpdateString("TreeHash", state.StringOf("TreeHash"))
If success <> True Then
    Log("Could not set TreeHash.")
    Return
End If

saved.Clear
success = receipt.EmitSb(saved)
If success <> True Then
    Log("Could not serialize receipt; preserve the printed archive ID.")
    Return
End If

success = saved.WriteFile(receiptPath, "utf-8", False)
If success <> True Then
    Log("Could not save receipt; preserve the printed archive ID.")
    Return
End If

Log("Completion receipt saved. Keep it in your archive catalog.")