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

Amazon Glacier: Resume a Multipart Upload

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.

Verifies the local file against its checkpoint, reads every List Parts page, and compares each exact range and tree hash. Matching parts are skipped; missing or mismatched parts are uploaded. Unexpected server ranges prevent completion. Keep the upload exclusive to this process. A missing upload may be completed, aborted, or expired: do not automatically start over. For an uncertain completion use retry completion.

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 Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
credentials: HCkJsonObject;
region: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
connection: HCkSocket;
body: HCkJsonObject;
result: HCkJsonObject;
error: HCkJsonObject;
requestBody: HCkStringBuilder;
responseBody: HCkStringBuilder;
files: HCkFileAccess;
statePath: PWideChar;
receiptPath: PWideChar;
state: HCkJsonObject;
saved: HCkStringBuilder;
uploadId: PWideChar;
filePath: PWideChar;
fileSize: PWideChar;
crypt: HCkCrypt2;
treeHash: PWideChar;
remoteParts: HCkHashtable;
seenMarkers: HCkHashtable;
marker: PWideChar;
more: Boolean;
page: Integer;
i: Integer;
remoteRange: PWideChar;
partSize: Integer;
numParts: Integer;
byteHigh: Integer;
byteLow: Integer;
endHigh: Integer;
endLow: Integer;
range: HCkStringBuilder;
digits: HCkStringBuilder;
part: HCkBinData;
partIndex: Integer;
matchedRemoteParts: Integer;
rangeKey: PWideChar;
partHash: PWideChar;
sendPart: Boolean;
linearHash: PWideChar;
confirmedHash: PWideChar;
archiveId: PWideChar;
location: PWideChar;
returnedHash: PWideChar;
receipt: HCkJsonObject;

begin
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the Glacier operation.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/glacier.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private AWS credentials.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (CkJsonObject__stringOf(credentials,'access_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (CkJsonObject__stringOf(credentials,'secret_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
//  Set this once to the region containing the vault.
region := 'us-west-2';
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'glacier.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'glacier');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not configure AWS signing.');
    Exit;
  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.
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    if (CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) then
      begin
        Memo1.Lines.Add('session_token must be a string.');
        Exit;
      end;
    if (CkJsonObject__stringOf(credentials,'session_token') <> '') then
      begin
        success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set the session-token parameter.');
            Exit;
          end;
      end;
  end;
//  Supply a Socket to explicitly enable TLS certificate verification.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
  begin
    Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
    Exit;
  end;
success := CkRest_UseConnection(rest,connection,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach the TLS connection.');
    Exit;
  end;
success := CkRest_AddHeader(rest,'x-amz-glacier-version','2012-06-01');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set x-amz-glacier-version.');
    Exit;
  end;
//  A hyphen selects the account belonging to the signing credentials.
//  Use the original, URL-safe vault name and IDs returned by Glacier.
success := CkRest_AddPathParam(rest,'{vault}','chilkat');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set vault name.');
    Exit;
  end;

body := CkJsonObject_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
error := CkJsonObject_Create();
CkJsonObject_putStrict(error,True);
requestBody := CkStringBuilder_Create();
responseBody := CkStringBuilder_Create();
files := CkFileAccess_Create();
statePath := 'qa_output/glacier-multipart.json';
receiptPath := 'qa_output/glacier-multipart-completed.json';
state := CkJsonObject_Create();
CkJsonObject_putStrict(state,True);
saved := CkStringBuilder_Create();
success := CkJsonObject_LoadFile(state,statePath);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load the private multipart checkpoint.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(state,'UploadId') <> 1) then
  begin
    Memo1.Lines.Add('Missing or invalid UploadId.');
    Exit;
  end;
if (CkJsonObject__stringOf(state,'UploadId') = '') then
  begin
    Memo1.Lines.Add('Empty UploadId.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(state,'Region') <> 1) then
  begin
    Memo1.Lines.Add('Missing or invalid Region.');
    Exit;
  end;
if (CkJsonObject__stringOf(state,'Region') = '') then
  begin
    Memo1.Lines.Add('Empty Region.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(state,'VaultName') <> 1) then
  begin
    Memo1.Lines.Add('Missing or invalid VaultName.');
    Exit;
  end;
if (CkJsonObject__stringOf(state,'VaultName') = '') then
  begin
    Memo1.Lines.Add('Empty VaultName.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(state,'FilePath') <> 1) then
  begin
    Memo1.Lines.Add('Missing or invalid FilePath.');
    Exit;
  end;
if (CkJsonObject__stringOf(state,'FilePath') = '') then
  begin
    Memo1.Lines.Add('Empty FilePath.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(state,'ArchiveSize') <> 1) then
  begin
    Memo1.Lines.Add('Missing or invalid ArchiveSize.');
    Exit;
  end;
if (CkJsonObject__stringOf(state,'ArchiveSize') = '') then
  begin
    Memo1.Lines.Add('Empty ArchiveSize.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(state,'TreeHash') <> 1) then
  begin
    Memo1.Lines.Add('Missing or invalid TreeHash.');
    Exit;
  end;
if (CkJsonObject__stringOf(state,'TreeHash') = '') then
  begin
    Memo1.Lines.Add('Empty TreeHash.');
    Exit;
  end;
if (CkJsonObject_JsonTypeOf(state,'PartSize') <> 1) then
  begin
    Memo1.Lines.Add('Missing or invalid PartSize.');
    Exit;
  end;
if (CkJsonObject__stringOf(state,'PartSize') = '') then
  begin
    Memo1.Lines.Add('Empty PartSize.');
    Exit;
  end;
if ((CkJsonObject__stringOf(state,'Region') <> region) or (CkJsonObject__stringOf(state,'VaultName') <> 'chilkat')) then
  begin
    Memo1.Lines.Add('Checkpoint region/vault differs from this example configuration.');
    Exit;
  end;
if (CkJsonObject__stringOf(state,'PartSize') <> '8388608') then
  begin
    Memo1.Lines.Add('This workflow requires the original 8 MiB part size.');
    Exit;
  end;
uploadId := CkJsonObject__stringOf(state,'UploadId');
success := CkRest_AddPathParam(rest,'{upload}',uploadId);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set upload ID.');
    Exit;
  end;
if (CkFileAccess_FileExists(files,receiptPath) = True) then
  begin
    Memo1.Lines.Add('A completion receipt already exists; this upload has finished.');
    Exit;
  end;
filePath := CkJsonObject__stringOf(state,'FilePath');
fileSize := CkFileAccess__fileSizeStr(files,filePath);
if ((CkFileAccess_getLastMethodSuccess(files) <> True) or (fileSize <> CkJsonObject__stringOf(state,'ArchiveSize'))) then
  begin
    Memo1.Lines.Add('Local file size differs from the checkpoint.');
    Exit;
  end;
crypt := CkCrypt2_Create();
CkCrypt2_putHashAlgorithm(crypt,'sha256-tree-hash');
CkCrypt2_putEncodingMode(crypt,'hexlower');
treeHash := CkCrypt2__hashFileENC(crypt,filePath);
if ((CkCrypt2_getLastMethodSuccess(crypt) <> True) or (treeHash <> CkJsonObject__stringOf(state,'TreeHash'))) then
  begin
    Memo1.Lines.Add('Local file checksum differs from the checkpoint; do not resume with a different file.');
    Exit;
  end;
remoteParts := CkHashtable_Create();
success := CkRest_AddQueryParam(rest,'limit','50');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set page limit.');
    Exit;
  end;
seenMarkers := CkHashtable_Create();
marker := '';
more := True;
page := 0;
while (more = True) do
  begin
    if (page = 1000) then
      begin
        Memo1.Lines.Add('Page limit reached; listing is incomplete.');
        Exit;
      end;
    page := page + 1;
    if (marker <> '') then
      begin
        success := CkRest_AddQueryParam(rest,'marker',marker);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set marker.');
            Exit;
          end;
      end;
    success := CkRest_FullRequestNoBodySb(rest,'GET','/-/vaults/{vault}/multipart-uploads/{upload}',responseBody);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Request did not complete; inspect diagnostics privately. Check state before retrying a change.');
        Exit;
      end;
    if (CkRest_getResponseStatusCode(rest) <> 200) then
      begin
        Memo1.Lines.Add('Glacier HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
        success := CkJsonObject_LoadSb(error,responseBody);
        if (success = True) then
          begin
            if (CkJsonObject_JsonTypeOf(error,'code') = 1) then
              begin
                Memo1.Lines.Add('AWS error code: ' + CkJsonObject__stringOf(error,'code'));
              end;
          end;
        Memo1.Lines.Add('AWS request ID: ' + CkRest__responseHdrByName(rest,'x-amzn-RequestId'));
        //  Inspect full errors privately. An HTTP error is not a successful operation.
        Exit;
      end;
    success := CkJsonObject_LoadSb(result,responseBody);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Expected valid JSON response.');
        Exit;
      end;
    if (CkJsonObject_JsonTypeOf(result,'MultipartUploadId') <> 1) then
      begin
        Memo1.Lines.Add('Missing or invalid MultipartUploadId.');
        Exit;
      end;
    if (CkJsonObject__stringOf(result,'MultipartUploadId') = '') then
      begin
        Memo1.Lines.Add('Empty MultipartUploadId.');
        Exit;
      end;
    if (CkJsonObject_JsonTypeOf(result,'PartSizeInBytes') <> 2) then
      begin
        Memo1.Lines.Add('Missing or invalid PartSizeInBytes.');
        Exit;
      end;
    if ((CkJsonObject__stringOf(result,'MultipartUploadId') <> uploadId) or (CkJsonObject__stringOf(result,'PartSizeInBytes') <> CkJsonObject__stringOf(state,'PartSize'))) then
      begin
        Memo1.Lines.Add('Server upload identity or part size differs from checkpoint.');
        Exit;
      end;
    if (CkJsonObject_JsonTypeOf(result,'Parts') <> 4) then
      begin
        Memo1.Lines.Add('Missing or invalid Parts.');
        Exit;
      end;
    i := 0;
    while (i < CkJsonObject_SizeOfArray(result,'Parts')) do
      begin
        CkJsonObject_putI(result,i);
        if (CkJsonObject_JsonTypeOf(result,'Parts[i].RangeInBytes') <> 1) then
          begin
            Memo1.Lines.Add('Missing or invalid Parts[i].RangeInBytes.');
            Exit;
          end;
        if (CkJsonObject__stringOf(result,'Parts[i].RangeInBytes') = '') then
          begin
            Memo1.Lines.Add('Empty Parts[i].RangeInBytes.');
            Exit;
          end;
        if (CkJsonObject_JsonTypeOf(result,'Parts[i].SHA256TreeHash') <> 1) then
          begin
            Memo1.Lines.Add('Missing or invalid Parts[i].SHA256TreeHash.');
            Exit;
          end;
        if (CkJsonObject__stringOf(result,'Parts[i].SHA256TreeHash') = '') then
          begin
            Memo1.Lines.Add('Empty Parts[i].SHA256TreeHash.');
            Exit;
          end;
        remoteRange := CkJsonObject__stringOf(result,'Parts[i].RangeInBytes');
        if (CkHashtable_Contains(remoteParts,remoteRange) = True) then
          begin
            Memo1.Lines.Add('Duplicate server range; listing is inconsistent.');
            Exit;
          end;
        success := CkHashtable_AddStr(remoteParts,remoteRange,CkJsonObject__stringOf(result,'Parts[i].SHA256TreeHash'));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not record server part.');
            Exit;
          end;
        i := i + 1;
      end;

    more := False;
    if (CkJsonObject_JsonTypeOf(result,'Marker') = 1) then
      begin
        marker := CkJsonObject__stringOf(result,'Marker');
        if (marker = '') then
          begin
            Memo1.Lines.Add('Empty marker; listing is incomplete.');
            Exit;
          end;
        if (CkHashtable_Contains(seenMarkers,marker) = True) then
          begin
            Memo1.Lines.Add('Repeated marker; listing is incomplete.');
            Exit;
          end;
        success := CkHashtable_AddStr(seenMarkers,marker,'seen');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not track pagination.');
            Exit;
          end;
        more := True;
      end
    else
      begin
        if (CkJsonObject_JsonTypeOf(result,'Marker') <> 6) then
          begin
            Memo1.Lines.Add('Missing or invalid Marker; listing is incomplete.');
            Exit;
          end;
      end;
  end;

success := CkRest_RemoveQueryParam(rest,'limit');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not clear limit.');
    Exit;
  end;
if (marker <> '') then
  begin
    success := CkRest_RemoveQueryParam(rest,'marker');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not clear marker.');
        Exit;
      end;
  end;
success := CkFileAccess_OpenForRead(files,filePath);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not open the immutable source file.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
partSize := 8388608;
numParts := CkFileAccess_GetNumBlocks(files,partSize);
if ((numParts < 1) or (numParts > 10000)) then
  begin
    Memo1.Lines.Add('This 8 MiB example supports nonempty files of at most 10,000 parts.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
//  Two base-1,000,000,000 components avoid 32-bit overflow in COM languages.
byteHigh := 0;
byteLow := 0;

range := CkStringBuilder_Create();
digits := CkStringBuilder_Create();
part := CkBinData_Create();
partIndex := 0;
matchedRemoteParts := 0;
while (partIndex < numParts) do
  begin
    success := CkBinData_Clear(part);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not clear part buffer.');
        CkFileAccess_FileClose(files);
        Exit;
      end;
    success := CkFileAccess_ReadBlockBd(files,partIndex,partSize,part);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not read the source part.');
        CkFileAccess_FileClose(files);
        Exit;
      end;
    if ((CkBinData_getNumBytes(part) = 0) or ((partIndex < numParts - 1) and (CkBinData_getNumBytes(part) <> partSize))) then
      begin
        Memo1.Lines.Add('Source file changed or a part was read incompletely.');
        CkFileAccess_FileClose(files);
        Exit;
      end;
    CkStringBuilder_Clear(range);
    CkStringBuilder_Clear(digits);
    CkStringBuilder_AppendInt(digits,byteLow);
    if (byteHigh > 0) then
      begin
        while (CkStringBuilder_getLength(digits) < 9) do
          begin
            CkStringBuilder_Prepend(digits,'0');
          end;

        CkStringBuilder_AppendInt(range,byteHigh);
      end;
    CkStringBuilder_Append(range,CkStringBuilder__getAsString(digits));
    CkStringBuilder_Append(range,'-');
    endHigh := byteHigh;
    endLow := byteLow + CkBinData_getNumBytes(part) - 1;
    if (endLow >= 1000000000) then
      begin
        endLow := endLow - 1000000000;
        endHigh := endHigh + 1;
      end;
    CkStringBuilder_Clear(digits);
    CkStringBuilder_AppendInt(digits,endLow);
    if (endHigh > 0) then
      begin
        while (CkStringBuilder_getLength(digits) < 9) do
          begin
            CkStringBuilder_Prepend(digits,'0');
          end;

        CkStringBuilder_AppendInt(range,endHigh);
      end;
    CkStringBuilder_Append(range,CkStringBuilder__getAsString(digits));
    rangeKey := CkStringBuilder__getAsString(range);
    CkCrypt2_putHashAlgorithm(crypt,'sha256-tree-hash');
    partHash := CkCrypt2__hashBdENC(crypt,part);
    if (CkCrypt2_getLastMethodSuccess(crypt) <> True) then
      begin
        Memo1.Lines.Add('Could not hash source part.');
        CkFileAccess_FileClose(files);
        Exit;
      end;
    sendPart := True;
    if (CkHashtable_Contains(remoteParts,rangeKey) = True) then
      begin
        matchedRemoteParts := matchedRemoteParts + 1;
        if (CkHashtable__lookupStr(remoteParts,rangeKey) = partHash) then
          begin
            sendPart := False;
            Memo1.Lines.Add('Verified existing part: ' + rangeKey);
          end;
      end;
    if (sendPart = True) then
      begin
        CkCrypt2_putHashAlgorithm(crypt,'sha256');
        linearHash := CkCrypt2__hashBdENC(crypt,part);
        if (CkCrypt2_getLastMethodSuccess(crypt) <> True) then
          begin
            Memo1.Lines.Add('Could not hash the part payload.');
            CkFileAccess_FileClose(files);
            Exit;
          end;
        CkAuthAws_putPrecomputedSha256(aws,linearHash);
        success := CkRest_SetAuthAws(rest,aws);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not configure part signing.');
            CkFileAccess_FileClose(files);
            Exit;
          end;
        success := CkRest_AddHeader(rest,'x-amz-content-sha256',linearHash);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set x-amz-content-sha256.');
            CkFileAccess_FileClose(files);
            Exit;
          end;
        success := CkRest_AddHeader(rest,'x-amz-sha256-tree-hash',partHash);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set x-amz-sha256-tree-hash.');
            CkFileAccess_FileClose(files);
            Exit;
          end;
        CkStringBuilder_Prepend(range,'bytes ');
        CkStringBuilder_Append(range,'/*');
        success := CkRest_AddHeader(rest,'Content-Range',CkStringBuilder__getAsString(range));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set Content-Range.');
            CkFileAccess_FileClose(files);
            Exit;
          end;
        success := CkRest_AddHeader(rest,'Content-Type','application/octet-stream');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set Content-Type.');
            CkFileAccess_FileClose(files);
            Exit;
          end;
        success := CkRest_FullRequestBd(rest,'PUT','/-/vaults/{vault}/multipart-uploads/{upload}',part,responseBody);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Part request did not complete. Keep the checkpoint and run the resume example.');
            CkFileAccess_FileClose(files);
            Exit;
          end;
        if (CkRest_getResponseStatusCode(rest) <> 204) then
          begin
            Memo1.Lines.Add('Glacier HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
            success := CkJsonObject_LoadSb(error,responseBody);
            if (success = True) then
              begin
                if (CkJsonObject_JsonTypeOf(error,'code') = 1) then
                  begin
                    Memo1.Lines.Add('AWS error code: ' + CkJsonObject__stringOf(error,'code'));
                  end;
              end;
            Memo1.Lines.Add('AWS request ID: ' + CkRest__responseHdrByName(rest,'x-amzn-RequestId'));
            //  Inspect full errors privately. An HTTP error is not a successful operation.
            CkFileAccess_FileClose(files);
            Exit;
          end;
        confirmedHash := CkRest__responseHdrByName(rest,'x-amz-sha256-tree-hash');
        if (confirmedHash <> partHash) then
          begin
            Memo1.Lines.Add('Part response checksum mismatch. Keep the checkpoint and inspect List Parts.');
            CkFileAccess_FileClose(files);
            Exit;
          end;
        Memo1.Lines.Add('Uploaded part: ' + rangeKey);
      end;
    byteLow := byteLow + CkBinData_getNumBytes(part);
    if (byteLow >= 1000000000) then
      begin
        byteLow := byteLow - 1000000000;
        byteHigh := byteHigh + 1;
      end;
    partIndex := partIndex + 1;
  end;

CkFileAccess_FileClose(files);
if (matchedRemoteParts <> CkHashtable_getCount(remoteParts)) then
  begin
    Memo1.Lines.Add('Server contains unexpected ranges. Do not complete; inspect the upload and source.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
//  Recheck the source before completion. Keep the file immutable throughout.
fileSize := CkFileAccess__fileSizeStr(files,filePath);
if ((CkFileAccess_getLastMethodSuccess(files) <> True) or (fileSize <> CkJsonObject__stringOf(state,'ArchiveSize'))) then
  begin
    Memo1.Lines.Add('Source size changed during upload; do not complete.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
CkCrypt2_putHashAlgorithm(crypt,'sha256-tree-hash');
treeHash := CkCrypt2__hashFileENC(crypt,filePath);
if ((CkCrypt2_getLastMethodSuccess(crypt) <> True) or (treeHash <> CkJsonObject__stringOf(state,'TreeHash'))) then
  begin
    Memo1.Lines.Add('Source checksum changed during upload; do not complete.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
success := CkRest_AddHeader(rest,'x-amz-sha256-tree-hash',CkJsonObject__stringOf(state,'TreeHash'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set x-amz-sha256-tree-hash.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
success := CkRest_AddHeader(rest,'x-amz-archive-size',CkJsonObject__stringOf(state,'ArchiveSize'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set x-amz-archive-size.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
//  Completion has NO body: never reuse a part's precomputed payload hash.
CkAuthAws_putPrecomputedSha256(aws,'');
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not reset signing.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
success := CkRest_RemoveHeader(rest,'x-amz-content-sha256');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not clear part payload hash.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
success := CkRest_RemoveHeader(rest,'Content-Range');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not clear part range.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
success := CkRest_RemoveHeader(rest,'Content-Type');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not clear content type.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
success := CkRest_FullRequestNoBodySb(rest,'POST','/-/vaults/{vault}/multipart-uploads/{upload}',responseBody);
if (success <> True) then
  begin
    Memo1.Lines.Add('Request did not complete; inspect diagnostics privately. Check state before retrying a change.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
if (CkRest_getResponseStatusCode(rest) <> 201) then
  begin
    Memo1.Lines.Add('Glacier HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
    success := CkJsonObject_LoadSb(error,responseBody);
    if (success = True) then
      begin
        if (CkJsonObject_JsonTypeOf(error,'code') = 1) then
          begin
            Memo1.Lines.Add('AWS error code: ' + CkJsonObject__stringOf(error,'code'));
          end;
      end;
    Memo1.Lines.Add('AWS request ID: ' + CkRest__responseHdrByName(rest,'x-amzn-RequestId'));
    //  Inspect full errors privately. An HTTP error is not a successful operation.
    CkFileAccess_FileClose(files);
    Exit;
  end;
archiveId := CkRest__responseHdrByName(rest,'x-amz-archive-id');
if ((CkRest_getLastMethodSuccess(rest) <> True) or (archiveId = '')) then
  begin
    Memo1.Lines.Add('Completion response has no archive ID. Preserve the checkpoint and retry identical completion promptly.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
Memo1.Lines.Add('Archive ID: ' + archiveId);
location := CkRest__responseHdrByName(rest,'Location');
Memo1.Lines.Add('Location: ' + location);
returnedHash := CkRest__responseHdrByName(rest,'x-amz-sha256-tree-hash');
if ((CkRest_getLastMethodSuccess(rest) = True) and (returnedHash <> CkJsonObject__stringOf(state,'TreeHash'))) then
  begin
    Memo1.Lines.Add('Completion checksum mismatch; preserve the printed archive ID and investigate.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
receipt := CkJsonObject_Create();
success := CkJsonObject_UpdateString(receipt,'UploadId',uploadId);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set UploadId.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
success := CkJsonObject_UpdateString(receipt,'ArchiveId',archiveId);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set ArchiveId.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
success := CkJsonObject_UpdateString(receipt,'Location',location);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Location.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
success := CkJsonObject_UpdateString(receipt,'TreeHash',CkJsonObject__stringOf(state,'TreeHash'));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set TreeHash.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
CkStringBuilder_Clear(saved);
success := CkJsonObject_EmitSb(receipt,saved);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not serialize receipt; preserve the printed archive ID.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
success := CkStringBuilder_WriteFile(saved,receiptPath,'utf-8',False);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not save receipt; preserve the printed archive ID.');
    CkFileAccess_FileClose(files);
    Exit;
  end;
Memo1.Lines.Add('Completion receipt saved. Keep it in your archive catalog.');

CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkJsonObject_Dispose(body);
CkJsonObject_Dispose(result);
CkJsonObject_Dispose(error);
CkStringBuilder_Dispose(requestBody);
CkStringBuilder_Dispose(responseBody);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(state);
CkStringBuilder_Dispose(saved);
CkCrypt2_Dispose(crypt);
CkHashtable_Dispose(remoteParts);
CkHashtable_Dispose(seenMarkers);
CkStringBuilder_Dispose(range);
CkStringBuilder_Dispose(digits);
CkBinData_Dispose(part);
CkJsonObject_Dispose(receipt);