Study · Advanced · HTTP/1.1
Resume a large file upload
Upload a 12 MiB file in requests of 4 MiB each. After a disconnect, ask the server how far it got and resume there.
SDK 2.3.0 allows a configured maximum of 8 MiB per request body. This exercise splits the file into independent parts using an application protocol over HTTP.
Choose a server and run the example
Choose one server and save its files in a fresh directory, then choose a client below. All servers use the same HTTP API and SHA-256 checks.
C / C++ · SDK 2.3.0
Install the official package. Save all 6 files in one directory. server.c registers routes and receives requests through the C ABI. Both programs share store.cpp for part storage and SHA-256.
Install the SHA-256 library for the example
sudo apt install libssl-devbrew install openssl@3Shared files
cmake_minimum_required(VERSION 3.24)
project(coakka_resumable_upload LANGUAGES C CXX)
find_package(CoAkkaHttpHost 2.3.0 EXACT CONFIG REQUIRED)
find_package(OpenSSL 3 REQUIRED COMPONENTS Crypto)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_library(resume-handler STATIC server.c store.cpp)
target_link_libraries(resume-handler PUBLIC CoAkkaHttp::host PRIVATE OpenSSL::Crypto)
add_executable(resume-c main.c)
add_executable(resume-cpp main.cpp)
target_link_libraries(resume-c PRIVATE resume-handler)
target_link_libraries(resume-cpp PRIVATE resume-handler)
foreach(target IN ITEMS resume-handler resume-c resume-cpp)
target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic -Werror)
endforeach()
#ifndef COAKKA_PORTAL_RESUME_UPLOAD_H
#define COAKKA_PORTAL_RESUME_UPLOAD_H
#include <coakka/http/host.h>
#ifdef __cplusplus
extern "C" {
#endif
enum {
LAB_PART_SIZE = 4 * 1024 * 1024,
LAB_CREATE = 1,
LAB_STATUS,
LAB_PUT,
LAB_FINISH,
LAB_DELETE,
LAB_ROUTE_COUNT = LAB_DELETE
};
typedef struct {
unsigned status;
char body[512];
} lab_reply_t;
/* The handler uses request views only while the caller owns the event lease. */
lab_reply_t lab_dispatch(const coakka_http_host_request_event_t *request);
int run_resume_server(void);
#ifdef __cplusplus
}
#endif
#endif
#define _POSIX_C_SOURCE 200809L
#include "upload.h"
#include <errno.h>
#include <poll.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static coakka_http_host_bytes_t bytes(const char *value) {
return (coakka_http_host_bytes_t){(const uint8_t *)value, strlen(value)};
}
static bool check(coakka_http_host_status_t status, const char *step) {
if (status == COAKKA_HTTP_HOST_OK) {
return true;
}
fprintf(stderr, "%s: %s\n", step, coakka_http_host_status_name(status));
return false;
}
static bool take_request(coakka_http_host_service_t *service) {
coakka_http_host_request_event_t event;
coakka_http_host_request_event_init(&event);
const coakka_http_host_status_t received =
coakka_http_host_take_request(service, 500U, &event);
if (received == COAKKA_HTTP_HOST_TIMEOUT) {
return true;
}
if (!check(received, "read request")) {
return false;
}
const coakka_http_host_exchange_t exchange = event.exchange;
lab_reply_t reply = {0};
if (event.kind == COAKKA_HTTP_HOST_REQUEST) {
reply = lab_dispatch(&event);
}
// Only the copied response survives the Core-owned request lease.
if (!check(coakka_http_host_release_request(service, &event),
"release event")) {
return false;
}
if (reply.status != 0U) {
const coakka_http_host_header_t header = {
.name = bytes("content-type"),
.value = bytes("application/json"),
};
coakka_http_host_response_t response;
coakka_http_host_response_init(&response);
response.status_code = reply.status;
response.headers = &header;
response.header_count = 1U;
response.body = bytes(reply.body);
// A missing reply never rolls back a part that was already committed.
(void)check(coakka_http_host_respond(service, exchange, &response),
"respond");
}
return true;
}
static bool drain(coakka_http_host_service_t *service) {
if (!check(coakka_http_host_service_begin_drain(service), "begin drain")) {
return false;
}
for (;;) {
coakka_http_host_drain_state_t state = COAKKA_HTTP_HOST_DRAIN_NOT_STARTED;
const coakka_http_host_status_t status =
coakka_http_host_service_wait_drained(service, 0U, &state);
if (status != COAKKA_HTTP_HOST_TIMEOUT ||
state != COAKKA_HTTP_HOST_DRAIN_PENDING) {
return check(status, "finish drain");
}
if (!take_request(service)) {
return false;
}
}
}
int run_resume_server(void) {
// The lab runs as one process and one application request reader.
umask(0077);
if (mkdir("upload-lab-data", 0700) != 0 && errno != EEXIST) {
perror("create upload-lab-data");
return EXIT_FAILURE;
}
coakka_http_host_configuration_t config;
coakka_http_host_configuration_init(&config);
config.bind_address = bytes("127.0.0.1");
config.port = 8080U;
config.limits.max_request_body_bytes = LAB_PART_SIZE;
config.limits.drain_timeout_ms = 2000U;
config.limits.stop_timeout_ms = 4000U;
const char *methods[] = {"POST", "GET", "PUT", "POST", "DELETE"};
const char *patterns[] = {
"/uploads", "/uploads/{upload_id}", "/uploads/{upload_id}/parts/{offset}",
"/uploads/{upload_id}/finish", "/uploads/{upload_id}"};
coakka_http_host_route_t routes[LAB_ROUTE_COUNT];
for (size_t index = 0; index < LAB_ROUTE_COUNT; ++index) {
coakka_http_host_route_init(&routes[index]);
routes[index].route_id = index + 1U;
routes[index].handler_binding_id = index + 1U;
routes[index].method = bytes(methods[index]);
routes[index].encoded_path_pattern = bytes(patterns[index]);
}
coakka_http_host_service_t *service = NULL;
uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
if (!check(coakka_http_host_service_create(&config, routes, LAB_ROUTE_COUNT,
&service, &failed_route),
"create")) {
return EXIT_FAILURE;
}
coakka_http_host_issue_t issue;
coakka_http_host_issue_init(&issue);
bool running =
check(coakka_http_host_service_start(service, &issue), "start");
if (running) {
puts("Listening on http://127.0.0.1:8080; press Enter to stop.");
fflush(stdout);
struct pollfd input = {.fd = STDIN_FILENO, .events = POLLIN};
while (running) {
const int ready = poll(&input, 1U, 0);
if (ready > 0) {
break;
}
if (ready < 0 && errno != EINTR) {
perror("read stop input");
running = false;
break;
}
running = take_request(service);
}
if (running) {
running = drain(service);
}
}
const bool stopped = check(coakka_http_host_service_stop(service), "stop");
const bool closed =
check(coakka_http_host_service_destroy(&service), "destroy");
return running && stopped && closed ? EXIT_SUCCESS : EXIT_FAILURE;
}
#include "upload.h"
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <algorithm>
#include <array>
#include <charconv>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <strings.h>
namespace {
namespace fs = std::filesystem;
constexpr std::size_t max_file = 32U * 1024U * 1024U;
constexpr std::size_t max_sessions = 4U;
constexpr std::size_t part_size = LAB_PART_SIZE;
const fs::path root{"upload-lab-data"};
struct Session {
std::string id;
fs::path directory;
std::size_t length = 0;
std::string sha256;
std::size_t next = 0;
bool complete = false;
};
struct Temporary {
fs::path path;
~Temporary() {
std::error_code ignored;
fs::remove(path, ignored);
}
};
std::string_view text(coakka_http_host_bytes_t value) {
if (!value.size) {
return {};
}
return {reinterpret_cast<const char *>(value.data), value.size};
}
std::string_view header(const coakka_http_host_request_event_t *request,
std::string_view name) {
for (uint32_t index = 0;
index < coakka_http_host_request_header_count(request); ++index) {
coakka_http_host_header_t field{};
if (coakka_http_host_request_header(request, index, &field) &&
field.name.size == name.size() &&
strncasecmp(reinterpret_cast<const char *>(field.name.data),
name.data(), name.size()) == 0) {
return text(field.value);
}
}
return {};
}
std::string_view capture(const coakka_http_host_request_event_t *request,
uint32_t index) {
coakka_http_host_path_parameter_t field{};
if (!coakka_http_host_request_path_parameter(request, index, &field)) {
return {};
}
return text(field.encoded_value);
}
bool is_hex(std::string_view value, std::size_t length) {
return value.size() == length &&
value.find_first_not_of("0123456789abcdef") == std::string_view::npos;
}
std::optional<std::size_t> number(std::string_view value) {
if (value.empty() || value.size() > 10U) {
return std::nullopt;
}
std::size_t result{};
const char *end = value.data() + value.size();
const auto parsed = std::from_chars(value.data(), end, result);
return parsed.ec == std::errc{} && parsed.ptr == end
? std::optional<std::size_t>{result}
: std::nullopt;
}
std::string hex(const unsigned char *bytes, std::size_t size) {
constexpr std::string_view digits = "0123456789abcdef";
std::string result;
result.reserve(2U * size);
for (std::size_t index = 0; index < size; ++index) {
result.push_back(digits[bytes[index] >> 4U]);
result.push_back(digits[bytes[index] & 15U]);
}
return result;
}
class Sha256 {
public:
Sha256() : context_(EVP_MD_CTX_new(), &EVP_MD_CTX_free) {
if (!context_ ||
EVP_DigestInit_ex(context_.get(), EVP_sha256(), nullptr) != 1) {
throw std::runtime_error("cannot start SHA-256");
}
}
void update(const void *data, std::size_t size) {
if (EVP_DigestUpdate(context_.get(), data, size) != 1) {
throw std::runtime_error("cannot update SHA-256");
}
}
std::string finish() {
std::array<unsigned char, 32> digest{};
unsigned length{};
if (EVP_DigestFinal_ex(context_.get(), digest.data(), &length) != 1 ||
length != digest.size()) {
throw std::runtime_error("cannot finish SHA-256");
}
return hex(digest.data(), length);
}
private:
std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> context_;
};
lab_reply_t reply(unsigned status, const std::string &json) {
lab_reply_t result{};
if (json.size() >= sizeof(result.body)) {
throw std::runtime_error("lab response exceeded its buffer");
}
result.status = status;
std::memcpy(result.body, json.data(), json.size());
return result;
}
// Errors are fixed literals; IDs and checksums are validated hexadecimal.
lab_reply_t reject(unsigned status, const std::string &message,
std::optional<std::size_t> next = std::nullopt) {
return reply(status,
"{\"error\":\"" + message + "\"" +
(next ? ",\"next_offset\":" + std::to_string(*next) : "") +
"}");
}
lab_reply_t describe(unsigned status, const Session &state) {
return reply(status,
"{\"upload_id\":\"" + state.id +
"\",\"length\":" + std::to_string(state.length) +
",\"sha256\":\"" + state.sha256 +
"\",\"next_offset\":" + std::to_string(state.next) +
",\"part_size\":" + std::to_string(part_size) +
",\"complete\":" + (state.complete ? "true}" : "false}"));
}
fs::path part(const fs::path &directory, std::size_t offset) {
char name[32];
std::snprintf(name, sizeof(name), "part-%08zu.bin", offset);
return directory / name;
}
void atomic_write(const fs::path &path, std::string_view data) {
Temporary temporary{path.parent_path() / "incoming.tmp"};
std::ofstream output(temporary.path, std::ios::binary | std::ios::trunc);
output.exceptions(std::ios::failbit | std::ios::badbit);
output.write(data.data(), static_cast<std::streamsize>(data.size()));
output.close();
fs::rename(temporary.path, path);
}
lab_reply_t create(const coakka_http_host_request_event_t *request) {
const auto length = number(header(request, "upload-length"));
const std::string digest(header(request, "upload-sha256"));
if (coakka_http_host_request_body(request).size || !length ||
!is_hex(digest, 64U)) {
return reject(400, "invalid upload metadata");
}
if (*length == 0 || *length > max_file) {
return reject(413, "file length must be between 1 byte and 32 MiB");
}
std::size_t entries = 0;
for (const auto &entry : fs::directory_iterator(root)) {
(void)entry;
if (++entries >= max_sessions) {
return reject(503, "all upload slots are in use");
}
}
std::array<unsigned char, 16> random{};
if (RAND_bytes(random.data(), static_cast<int>(random.size())) != 1) {
throw std::runtime_error("cannot generate upload ID");
}
const std::string id = hex(random.data(), random.size());
const fs::path directory = root / id;
if (!fs::create_directory(directory)) {
throw std::runtime_error("cannot create a new upload directory");
}
try {
atomic_write(directory / "manifest.txt",
std::to_string(*length) + "\n" + digest + "\n");
} catch (...) {
fs::remove(directory);
throw;
}
return describe(201, Session{id, directory, *length, digest});
}
std::optional<Session> load(std::string_view id) {
if (!is_hex(id, 32U)) {
return std::nullopt;
}
Session state{};
state.id = id;
state.directory = root / state.id;
const fs::path manifest = state.directory / "manifest.txt";
if (!fs::is_regular_file(manifest)) {
return std::nullopt;
}
std::ifstream source(manifest);
if (!(source >> state.length >> state.sha256) || state.length == 0 ||
state.length > max_file || !is_hex(state.sha256, 64U)) {
throw std::runtime_error("invalid upload manifest");
}
const fs::path target = state.directory / "complete.bin";
state.complete = fs::is_regular_file(target);
if (state.complete) {
if (fs::file_size(target) != state.length) {
throw std::runtime_error("invalid published length");
}
state.next = state.length;
}
// Derive progress from contiguous committed files.
while (state.next < state.length) {
const fs::path path = part(state.directory, state.next);
if (!fs::is_regular_file(path)) {
break;
}
const std::size_t size = std::min(part_size, state.length - state.next);
if (fs::file_size(path) != size) {
throw std::runtime_error("invalid committed part length");
}
state.next += size;
}
return state;
}
std::size_t hash_part(const fs::path &path, Sha256 &hash, std::ostream *output,
std::size_t limit) {
std::ifstream source(path, std::ios::binary);
if (!source) {
throw std::runtime_error("cannot open committed part");
}
std::array<char, 64 * 1024> buffer{};
std::size_t size = 0;
while (source.read(buffer.data(), buffer.size()) || source.gcount()) {
const auto count = static_cast<std::size_t>(source.gcount());
if (count > limit - size) {
throw std::runtime_error("committed part exceeds declared length");
}
hash.update(buffer.data(), count);
if (output) {
output->write(buffer.data(), static_cast<std::streamsize>(count));
}
size += count;
}
if (!source.eof() || source.bad()) {
throw std::runtime_error("cannot read committed part");
}
return size;
}
bool binary_body(std::string_view value) {
value = value.substr(0, value.find(';'));
const auto start = value.find_first_not_of(" \t");
if (start == std::string_view::npos) {
return false;
}
value = value.substr(start, value.find_last_not_of(" \t") - start + 1);
constexpr std::string_view media = "application/octet-stream";
return value.size() == media.size() &&
strncasecmp(value.data(), media.data(), media.size()) == 0;
}
lab_reply_t put(const coakka_http_host_request_event_t *request,
Session &state) {
const auto offset = number(capture(request, 1));
if (!offset) {
return reject(400, "invalid part offset");
}
if (state.complete || *offset >= state.length || *offset % part_size ||
*offset > state.next) {
return reject(409, "wrong part offset or completed upload", state.next);
}
if (!binary_body(header(request, "content-type"))) {
return reject(415, "send application/octet-stream");
}
const auto body = coakka_http_host_request_body(request);
if (body.size != std::min(part_size, state.length - *offset)) {
return reject(400, "incorrect part length", state.next);
}
const auto digest = header(request, "part-sha256");
if (!is_hex(digest, 64U)) {
return reject(400, "invalid part checksum");
}
Sha256 incoming;
incoming.update(body.data, body.size);
if (incoming.finish() != digest) {
return reject(422, "part checksum does not match", state.next);
}
const fs::path path = part(state.directory, *offset);
if (*offset < state.next) {
Sha256 committed;
hash_part(path, committed, nullptr, body.size);
if (committed.finish() != digest) {
return reject(409, "committed part differs", state.next);
}
return describe(200, state);
}
atomic_write(path, text(body));
state.next += body.size;
return describe(200, state);
}
lab_reply_t finish(const coakka_http_host_request_event_t *request,
Session &state) {
if (coakka_http_host_request_body(request).size) {
return reject(400, "finish does not accept a body");
}
if (state.complete) {
return describe(200, state);
}
if (state.next != state.length) {
return reject(409, "upload is incomplete", state.next);
}
Temporary temporary{state.directory / "assemble.tmp"};
Sha256 hash;
std::ofstream output(temporary.path, std::ios::binary | std::ios::trunc);
output.exceptions(std::ios::failbit | std::ios::badbit);
std::size_t size = 0;
for (std::size_t offset = 0; offset < state.length; offset += part_size) {
size += hash_part(part(state.directory, offset), hash, &output,
state.length - size);
}
output.close();
if (size != state.length || hash.finish() != state.sha256) {
return reject(422, "assembled file checksum or length does not match");
}
fs::rename(temporary.path, state.directory / "complete.bin");
for (std::size_t offset = 0; offset < state.length; offset += part_size) {
std::error_code error;
fs::remove(part(state.directory, offset), error);
if (error) {
std::fputs("Could not remove a committed part\n", stderr);
}
}
state.complete = true;
return describe(201, state);
}
} // namespace
extern "C" lab_reply_t
lab_dispatch(const coakka_http_host_request_event_t *request) {
try {
if (request->handler_binding_id == LAB_CREATE) {
return create(request);
}
auto state = load(capture(request, 0));
if (!state) {
return reject(404, "upload not found");
}
switch (request->handler_binding_id) {
case LAB_STATUS:
return describe(200, *state);
case LAB_PUT:
return put(request, *state);
case LAB_FINISH:
return finish(request, *state);
case LAB_DELETE:
fs::remove_all(state->directory);
return reply(200, "{\"deleted\":\"" + state->id + "\"}");
default:
return reject(404, "route not found");
}
} catch (const std::exception &error) {
std::fprintf(stderr, "Upload store: %s\n", error.what());
return {500, "{\"error\":\"upload store failed\"}"};
} catch (...) {
return {500, "{\"error\":\"upload store failed\"}"};
}
}
C · main.c
#include "upload.h"
int main(void) { return run_resume_server(); }
C++ · main.cpp
#include "upload.h"
int main() { return run_resume_server(); }
cmake -S . -B build -DCMAKE_PREFIX_PATH="$COAKKA_HTTP_SDK"
cmake --build buildIf CMake on macOS cannot find OpenSSL, add -DOPENSSL_ROOT_DIR="$(brew --prefix openssl@3)" to the configure command.
./build/resume-c./build/resume-cppGo · 2.3.2
Install the official package. Save the code as server.go.
server.go
package main
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
http "github.com/phuong-tran/coakka-http-runtime-go/v2"
)
const (
partSize = 4 * 1024 * 1024
maxFile = 32 * 1024 * 1024
maxSessions = 4
root = "upload-lab-data"
)
var (
uploadID = regexp.MustCompile("^[0-9a-f]{32}$")
checksum = regexp.MustCompile("^[0-9a-f]{64}$")
number = regexp.MustCompile("^[0-9]{1,10}$")
)
type session struct {
ID string `json:"upload_id"`
NextOffset int64 `json:"next_offset"`
Length int64 `json:"length"`
PartSize int `json:"part_size"`
SHA256 string `json:"sha256"`
Complete bool `json:"complete"`
}
type lab struct {
mu sync.Mutex
}
func reply(status uint32, value any) (http.Response, error) {
data, err := json.Marshal(value)
if err != nil {
return http.Response{}, err
}
headers, err := http.NewHeaders(http.Header{Name: "content-type", Value: "application/json"})
if err != nil {
return http.Response{}, err
}
return http.NewResponse(status, headers, data)
}
func reject(status uint32, message string, offsets ...int64) (http.Response, error) {
fields := map[string]any{"error": message}
if len(offsets) > 0 {
fields["next_offset"] = offsets[0]
}
return reply(status, fields)
}
func (app *lab) handler(action http.Handler) http.Handler {
return func(request *http.Request) (http.Response, error) {
// The app serializes changes to its small disk store.
app.mu.Lock()
defer app.mu.Unlock()
response, err := action(request)
if err != nil {
log.Print(err)
return reject(500, "upload store failed")
}
return response, nil
}
}
func atomicWrite(destination string, body []byte) error {
temp := filepath.Join(filepath.Dir(destination), "incoming.tmp")
defer os.Remove(temp)
if err := os.WriteFile(temp, body, 0600); err != nil {
return err
}
return os.Rename(temp, destination)
}
func create(request *http.Request) (http.Response, error) {
lengthText, _ := request.Headers.Get("upload-length")
digest, _ := request.Headers.Get("upload-sha256")
if len(request.Bytes()) != 0 || !number.MatchString(lengthText) || !checksum.MatchString(digest) {
return reject(400, "invalid upload metadata")
}
length, _ := strconv.ParseInt(lengthText, 10, 64)
if length < 1 || length > maxFile {
return reject(413, "file length must be between 1 byte and 32 MiB")
}
entries, err := os.ReadDir(root)
if err != nil {
return http.Response{}, err
}
if len(entries) >= maxSessions {
return reject(503, "all upload slots are in use")
}
var id [16]byte
if _, err := rand.Read(id[:]); err != nil {
return http.Response{}, err
}
state := session{ID: hex.EncodeToString(id[:]), Length: length, PartSize: partSize, SHA256: digest}
dir := filepath.Join(root, state.ID)
if err := os.Mkdir(dir, 0700); err != nil {
return http.Response{}, err
}
metadata, err := json.Marshal(state)
if err == nil {
err = atomicWrite(filepath.Join(dir, "manifest.json"), metadata)
}
if err != nil {
_ = os.Remove(dir)
return http.Response{}, err
}
return reply(201, state)
}
func partPath(dir string, offset int64) string {
return filepath.Join(dir, fmt.Sprintf("part-%08d.bin", offset))
}
func load(request *http.Request) (string, session, error) {
id := request.PathParameters[0].EncodedValue
var state session
if !uploadID.MatchString(id) {
return "", state, os.ErrNotExist
}
dir := filepath.Join(root, id)
metadata, err := os.ReadFile(filepath.Join(dir, "manifest.json"))
if err != nil {
return "", state, err
}
if err := json.Unmarshal(metadata, &state); err != nil {
return "", state, err
}
if state.ID != id || state.Length < 1 || state.Length > maxFile || !checksum.MatchString(state.SHA256) {
return "", state, errors.New("invalid upload manifest")
}
state.NextOffset, state.Complete, state.PartSize = 0, false, partSize
final, err := os.Stat(filepath.Join(dir, "complete.bin"))
if err == nil {
if final.Size() != state.Length {
return "", state, errors.New("invalid published length")
}
state.NextOffset, state.Complete = state.Length, true
return dir, state, nil
}
if !os.IsNotExist(err) {
return "", state, err
}
// Committed files are the checkpoint; no independent counter to update.
for state.NextOffset < state.Length {
info, err := os.Stat(partPath(dir, state.NextOffset))
if os.IsNotExist(err) {
break
}
if err != nil {
return "", state, err
}
size := min(int64(partSize), state.Length-state.NextOffset)
if info.Size() != size {
return "", state, errors.New("invalid committed part length")
}
state.NextOffset += size
}
return dir, state, nil
}
func lookup(action func(*http.Request, string, session) (http.Response, error)) http.Handler {
return func(request *http.Request) (http.Response, error) {
dir, state, err := load(request)
if os.IsNotExist(err) {
return reject(404, "upload not found")
}
if err != nil {
return http.Response{}, err
}
return action(request, dir, state)
}
}
func put(request *http.Request, dir string, state session) (http.Response, error) {
value := request.PathParameters[1].EncodedValue
if !number.MatchString(value) {
return reject(400, "invalid part offset")
}
offset, _ := strconv.ParseInt(value, 10, 64)
if state.Complete || offset >= state.Length || offset%partSize != 0 || offset > state.NextOffset {
return reject(409, "wrong part offset or completed upload", state.NextOffset)
}
media, _ := request.Headers.Get("content-type")
kind, _, _ := strings.Cut(media, ";")
if !strings.EqualFold(strings.TrimSpace(kind), "application/octet-stream") {
return reject(415, "send application/octet-stream")
}
body := request.Bytes()
if int64(len(body)) != min(int64(partSize), state.Length-offset) {
return reject(400, "incorrect part length", state.NextOffset)
}
digest, _ := request.Headers.Get("part-sha256")
if !checksum.MatchString(digest) {
return reject(400, "invalid part checksum")
}
actual := sha256.Sum256(body)
if hex.EncodeToString(actual[:]) != digest {
return reject(422, "part checksum does not match", state.NextOffset)
}
path := partPath(dir, offset)
if offset < state.NextOffset {
existing, err := os.ReadFile(path)
if err != nil {
return http.Response{}, err
}
if sha256.Sum256(existing) != actual {
return reject(409, "committed part differs", state.NextOffset)
}
return reply(200, state)
}
if err := atomicWrite(path, body); err != nil {
return http.Response{}, err
}
state.NextOffset += int64(len(body))
return reply(200, state)
}
func assemble(dir string, length int64) (int64, string, error) {
file, err := os.OpenFile(filepath.Join(dir, "assemble.tmp"), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
return 0, "", err
}
hash := sha256.New()
target := io.MultiWriter(file, hash)
var size int64
for offset := int64(0); offset < length; offset += partSize {
part, err := os.Open(partPath(dir, offset))
if err != nil {
_ = file.Close()
return 0, "", err
}
expected := min(int64(partSize), length-offset)
count, readErr := io.CopyN(target, part, expected)
var extra [1]byte
if readErr == nil {
n, err := part.Read(extra[:])
if n != 0 || err != io.EOF {
readErr = errors.New("committed part exceeds its declared length")
}
}
size += count
if err := errors.Join(readErr, part.Close()); err != nil {
_ = file.Close()
return size, "", err
}
}
return size, hex.EncodeToString(hash.Sum(nil)), file.Close()
}
func finish(request *http.Request, dir string, state session) (http.Response, error) {
if len(request.Bytes()) != 0 {
return reject(400, "finish does not accept a body")
}
if state.Complete {
return reply(200, state)
}
if state.NextOffset != state.Length {
return reject(409, "upload is incomplete", state.NextOffset)
}
temp := filepath.Join(dir, "assemble.tmp")
defer os.Remove(temp)
size, digest, err := assemble(dir, state.Length)
if err != nil {
return http.Response{}, err
}
if size != state.Length || digest != state.SHA256 {
return reject(422, "assembled file checksum or length does not match")
}
if err := os.Rename(temp, filepath.Join(dir, "complete.bin")); err != nil {
return http.Response{}, err
}
for offset := int64(0); offset < state.Length; offset += partSize {
if err := os.Remove(partPath(dir, offset)); err != nil {
log.Print(err)
}
}
state.Complete = true
return reply(201, state)
}
func run() (err error) {
if err := os.MkdirAll(root, 0700); err != nil {
return err
}
app := &lab{}
limits := http.DefaultLimits()
limits.MaxRequestBodyBytes = partSize
server, err := http.NewBuilder().
Listen("127.0.0.1", 8080).
Limits(limits).
Post("/uploads", app.handler(create)).
Get("/uploads/{upload_id}", app.handler(lookup(func(_ *http.Request, _ string, state session) (http.Response, error) {
return reply(200, state)
}))).
Put("/uploads/{upload_id}/parts/{offset}", app.handler(lookup(put))).
Post("/uploads/{upload_id}/finish", app.handler(lookup(finish))).
Delete("/uploads/{upload_id}", app.handler(lookup(func(_ *http.Request, dir string, state session) (http.Response, error) {
if err := os.RemoveAll(dir); err != nil {
return http.Response{}, err
}
return reply(200, map[string]string{"deleted": state.ID})
}))).
Start()
if err != nil {
return err
}
defer func() { err = errors.Join(err, server.Close()) }()
log.Print("Listening on http://127.0.0.1:8080; press Enter to stop.")
_, _ = os.Stdin.Read(make([]byte, 1))
return nil
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
go mod init example.com/coakka-resume
go get github.com/phuong-tran/coakka-http-runtime-go/[email protected]
export CGO_CFLAGS="-I$COAKKA_HTTP_SDK/include"
export CGO_LDFLAGS="-L$COAKKA_HTTP_SDK/lib -Wl,-rpath,$COAKKA_HTTP_SDK/lib"
go run server.goJava / Kotlin · JVM 2.3.2
Install the official package. Use JDK 17 or newer and save the files at the paths shown. Both entry points share UploadStore.java. The Pi commands select linux-aarch64; on macOS ARM64 omit that option.
Shared upload store
package study;
import coakka.http.Handler;
import coakka.http.Header;
import coakka.http.Headers;
import coakka.http.Request;
import coakka.http.Response;
import coakka.http.Responses;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
final class UploadStore {
static final int PART_SIZE = 4 * 1024 * 1024;
private static final int MAX_FILE = 32 * 1024 * 1024;
private static final int MAX_SESSIONS = 4;
private static final Path ROOT = Path.of("upload-lab-data");
private static final Headers JSON = new Headers(List.of(new Header("content-type", "application/json")));
UploadStore() throws IOException {
Files.createDirectories(ROOT);
}
@FunctionalInterface
interface Action {
Response apply(Request request) throws IOException;
}
Handler handler(Action action) {
return request -> {
// Mutations of this small local store run one at a time.
synchronized (this) {
try {
return action.apply(request);
} catch (IOException | IllegalArgumentException error) {
System.err.println("Upload store: " + error);
return reject(500, "upload store failed");
}
}
};
}
private record State(String id, Path directory, long length, String sha256, long next, boolean complete) {
Response reply(int status) {
return Responses.text(
String.format(Locale.ROOT,
"{\"upload_id\":\"%s\",\"length\":%d,\"sha256\":\"%s\",\"next_offset\":%d,",
id, length, sha256, next)
+ "\"part_size\":" + PART_SIZE + ",\"complete\":" + complete + "}",
status, JSON);
}
State advance(long nextOffset, boolean finished) {
return new State(id, directory, length, sha256, nextOffset, finished);
}
}
// Messages are fixed literals; IDs and checksums use lowercase hex.
private static Response reject(int status, String message) {
return Responses.text("{\"error\":\"" + message + "\"}", status, JSON);
}
private static Response reject(int status, String message, long offset) {
return Responses.text("{\"error\":\"" + message + "\",\"next_offset\":" + offset + "}", status, JSON);
}
private static String header(Request request, String name) {
String value = request.getHeaders().get(name);
return value == null ? "" : value;
}
private static String capture(Request request, int index) {
return new String(request.getPathParameters().get(index).encodedValue(), StandardCharsets.US_ASCII);
}
private static boolean checksum(String value) {
return value.matches("[0-9a-f]{64}");
}
private static MessageDigest sha256() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException error) {
throw new IllegalStateException("JDK must support SHA-256", error);
}
}
private static Path part(Path directory, long offset) {
return directory.resolve(String.format(Locale.ROOT, "part-%08d.bin", offset));
}
private static void publish(Path from, Path to) throws IOException {
Files.move(from, to, StandardCopyOption.ATOMIC_MOVE);
}
private static void writePart(Path path, byte[] body) throws IOException {
Path temporary = path.resolveSibling("incoming.tmp");
try {
Files.write(temporary, body);
publish(temporary, path);
} finally {
Files.deleteIfExists(temporary);
}
}
Response create(Request request) throws IOException {
String lengthText = header(request, "upload-length");
String digest = header(request, "upload-sha256");
if (request.bytes().length != 0 || !lengthText.matches("[0-9]{1,10}") || !checksum(digest)) {
return reject(400, "invalid upload metadata");
}
long length = Long.parseLong(lengthText);
if (length < 1 || length > MAX_FILE) {
return reject(413, "file length must be between 1 byte and 32 MiB");
}
try (var entries = Files.list(ROOT)) {
if (entries.limit(MAX_SESSIONS).count() >= MAX_SESSIONS) {
return reject(503, "all upload slots are in use");
}
}
String id = UUID.randomUUID().toString().replace("-", "");
Path directory = Files.createDirectory(ROOT.resolve(id));
try {
writePart(directory.resolve("manifest.txt"), (length + "\n" + digest + "\n").getBytes(StandardCharsets.US_ASCII));
} catch (IOException error) {
Files.deleteIfExists(directory);
throw error;
}
return new State(id, directory, length, digest, 0, false).reply(201);
}
private State load(Request request) throws IOException {
String id = capture(request, 0);
if (!id.matches("[0-9a-f]{32}")) {
return null;
}
Path directory = ROOT.resolve(id);
Path manifest = directory.resolve("manifest.txt");
if (!Files.isRegularFile(manifest)) {
return null;
}
List<String> values = Files.readAllLines(manifest, StandardCharsets.US_ASCII);
if (values.size() != 2 || !checksum(values.get(1))) {
throw new IOException("invalid upload manifest");
}
long length = Long.parseLong(values.get(0));
if (length < 1 || length > MAX_FILE) {
throw new IOException("invalid manifest length");
}
Path finalFile = directory.resolve("complete.bin");
boolean complete = Files.isRegularFile(finalFile);
if (complete && Files.size(finalFile) != length) {
throw new IOException("invalid published length");
}
long next = complete ? length : 0;
// The committed files are the checkpoint, including after a restart.
while (next < length && Files.isRegularFile(part(directory, next))) {
long count = Math.min(PART_SIZE, length - next);
if (Files.size(part(directory, next)) != count) {
throw new IOException("invalid committed part length");
}
next += count;
}
return new State(id, directory, length, values.get(1), next, complete);
}
Response status(Request request) throws IOException {
State state = load(request);
return state == null ? reject(404, "upload not found") : state.reply(200);
}
Response put(Request request) throws IOException {
State state = load(request);
if (state == null) {
return reject(404, "upload not found");
}
String value = capture(request, 1);
if (!value.matches("[0-9]{1,10}")) {
return reject(400, "invalid part offset");
}
long offset = Long.parseLong(value);
if (state.complete || offset >= state.length || offset % PART_SIZE != 0 || offset > state.next) {
return reject(409, "wrong part offset or completed upload", state.next);
}
String media = header(request, "content-type").split(";", 2)[0].trim();
if (!media.equalsIgnoreCase("application/octet-stream")) {
return reject(415, "send application/octet-stream");
}
byte[] body = request.bytes();
if (body.length != Math.min(PART_SIZE, state.length - offset)) {
return reject(400, "incorrect part length", state.next);
}
String digest = header(request, "part-sha256");
if (!checksum(digest)) {
return reject(400, "invalid part checksum");
}
if (!HexFormat.of().formatHex(sha256().digest(body)).equals(digest)) {
return reject(422, "part checksum does not match", state.next);
}
Path path = part(state.directory, offset);
if (offset < state.next) {
if (!HexFormat.of().formatHex(sha256().digest(Files.readAllBytes(path))).equals(digest)) {
return reject(409, "committed part differs", state.next);
}
return state.reply(200);
}
writePart(path, body);
return state.advance(state.next + body.length, false).reply(200);
}
Response finish(Request request) throws IOException {
State state = load(request);
if (state == null) {
return reject(404, "upload not found");
}
if (request.bytes().length != 0) {
return reject(400, "finish does not accept a body");
}
if (state.complete) {
return state.reply(200);
}
if (state.next != state.length) {
return reject(409, "upload is incomplete", state.next);
}
Path temporary = state.directory.resolve("assemble.tmp");
try {
MessageDigest hash = sha256();
long size = 0;
byte[] buffer = new byte[64 * 1024];
try (OutputStream output = Files.newOutputStream(temporary)) {
for (long offset = 0; offset < state.length; offset += PART_SIZE) {
try (InputStream input = Files.newInputStream(part(state.directory, offset))) {
int count;
while ((count = input.read(buffer)) != -1) {
if (count > state.length - size) {
throw new IOException("assembled file exceeds declared length");
}
output.write(buffer, 0, count);
hash.update(buffer, 0, count);
size += count;
}
}
}
}
if (size != state.length || !HexFormat.of().formatHex(hash.digest()).equals(state.sha256)) {
return reject(422, "assembled file checksum or length does not match");
}
publish(temporary, state.directory.resolve("complete.bin"));
} finally {
Files.deleteIfExists(temporary);
}
for (long offset = 0; offset < state.length; offset += PART_SIZE) {
try {
Files.deleteIfExists(part(state.directory, offset));
} catch (IOException error) {
System.err.println("Remove committed part: " + error);
}
}
return state.advance(state.length, true).reply(201);
}
Response delete(Request request) throws IOException {
State state = load(request);
if (state == null) {
return reject(404, "upload not found");
}
try (var paths = Files.walk(state.directory)) {
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(path);
}
}
return Responses.text("{\"deleted\":\"" + state.id + "\"}", 200, JSON);
}
}
Java
package study;
import coakka.http.Limits;
import coakka.http.Service;
import coakka.http.ServiceBuilder;
public final class JavaResumeUpload {
private JavaResumeUpload() {}
public static void main(String[] args) throws Exception {
UploadStore store = new UploadStore();
// The fifth parameter caps one request body; zero keeps other defaults.
Limits limits = new Limits(0, 0, 0, 0, UploadStore.PART_SIZE);
Service server = new ServiceBuilder()
.listen("127.0.0.1", 8080)
.limits(limits)
.post("/uploads", store.handler(store::create))
.get("/uploads/{upload_id}", store.handler(store::status))
.put("/uploads/{upload_id}/parts/{offset}", store.handler(store::put))
.post("/uploads/{upload_id}/finish", store.handler(store::finish))
.delete("/uploads/{upload_id}", store.handler(store::delete))
.start();
try {
System.out.println("Listening on http://127.0.0.1:8080; press Enter to stop.");
System.in.read();
} finally {
server.close();
}
}
}
Kotlin
package study
import coakka.http.Limits
import coakka.http.ServiceBuilder
fun main() {
val store = UploadStore()
val server = ServiceBuilder()
.listen(host = "127.0.0.1", port = 8080)
.limits(limits = Limits(maxRequestBodyBytes = UploadStore.PART_SIZE.toLong()))
.post(pattern = "/uploads", handler = store.handler(store::create))
.get(pattern = "/uploads/{upload_id}", handler = store.handler(store::status))
.put(pattern = "/uploads/{upload_id}/parts/{offset}", handler = store.handler(store::put))
.post(pattern = "/uploads/{upload_id}/finish", handler = store.handler(store::finish))
.delete(pattern = "/uploads/{upload_id}", handler = store.handler(store::delete))
.start()
try {
println("Listening on http://127.0.0.1:8080; press Enter to stop.")
readlnOrNull()
} finally {
server.close()
}
}
Maven
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>example.coakka</groupId>
<artifactId>coakka-http-resumable-upload-lab</artifactId>
<version>1.0.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>17</maven.compiler.release>
<kotlin.version>2.3.10</kotlin.version>
<coakka.version>2.3.2</coakka.version>
<coakka.target>macos-aarch64</coakka.target>
</properties>
<dependencies>
<dependency>
<groupId>io.github.phuong-tran.coakka</groupId>
<artifactId>coakka-http-runtime-jvm</artifactId>
<version>${coakka.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile-kotlin</id>
<phase>process-sources</phase>
<goals><goal>compile</goal></goals>
<configuration>
<jvmTarget>17</jvmTarget>
<args><arg>-Werror</arg><arg>-Xjdk-release=17</arg></args>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
<configuration>
<release>17</release>
<showWarnings>true</showWarnings>
<compilerArgs><arg>-Xlint:all</arg><arg>-Werror</arg></compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.8.1</version>
<executions>
<execution>
<id>unpack-coakka-native</id>
<phase>process-resources</phase>
<goals><goal>unpack</goal></goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>io.github.phuong-tran.coakka</groupId>
<artifactId>coakka-http-runtime-jvm</artifactId>
<version>${coakka.version}</version>
<classifier>${coakka.target}</classifier>
<type>zip</type>
<outputDirectory>${project.build.directory}/coakka-native</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
mvn -q -Dcoakka.target=linux-aarch64 compile dependency:build-classpath -Dmdep.outputFile=target/classpath.txtjava -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.JavaResumeUploadjava -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.KotlinResumeUploadKtGradle
plugins {
kotlin("jvm") version "2.3.10"
}
repositories {
mavenCentral()
}
val coakkaTarget = providers.gradleProperty("coakkaTarget")
.orElse("macos-aarch64")
val coakkaNative by configurations.creating
dependencies {
implementation("io.github.phuong-tran.coakka:coakka-http-runtime-jvm:2.3.2")
coakkaNative("io.github.phuong-tran.coakka:coakka-http-runtime-jvm:2.3.2:${coakkaTarget.get()}@zip")
}
val unpackCoakkaNative by tasks.registering(Sync::class) {
from(coakkaNative.map(::zipTree))
into(layout.buildDirectory.dir("coakka-native"))
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
freeCompilerArgs.add("-Xjdk-release=17")
allWarningsAsErrors.set(true)
}
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
tasks.withType<JavaCompile>().configureEach {
options.release.set(17)
options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror"))
}
tasks.register<JavaExec>("runJavaResumeUpload") {
dependsOn(unpackCoakkaNative)
classpath = sourceSets["main"].runtimeClasspath
mainClass.set("study.JavaResumeUpload")
standardInput = System.`in`
jvmArgs("-Djava.library.path=${layout.buildDirectory.dir("coakka-native/native").get().asFile}")
}
tasks.register<JavaExec>("runKotlinResumeUpload") {
dependsOn(unpackCoakkaNative)
classpath = sourceSets["main"].runtimeClasspath
mainClass.set("study.KotlinResumeUploadKt")
standardInput = System.`in`
jvmArgs("-Djava.library.path=${layout.buildDirectory.dir("coakka-native/native").get().asFile}")
}
rootProject.name = "coakka-http-resumable-upload-lab"
gradle -PcoakkaTarget=linux-aarch64 runJavaResumeUploadgradle -PcoakkaTarget=linux-aarch64 runKotlinResumeUploadPython · 2.3.2
Install the official package. Save the code as server.py.
server.py
"""An application-owned upload session on a local CoAkka HTTP Runtime listener."""
import hashlib
import json
import os
import re
import shutil
import threading
import uuid
from pathlib import Path
from coakka_http import Builder, Header, Headers, Limits, Request, Response
PART_SIZE = 4 * 1024 * 1024
MAX_FILE = 32 * 1024 * 1024
MAX_SESSIONS = 4
ROOT = Path("upload-lab-data")
ID = re.compile(r"[0-9a-f]{32}")
SHA256 = re.compile(r"[0-9a-f]{64}")
NUMBER = re.compile(r"[0-9]{1,10}")
LOCK = threading.Lock()
def reply(value: dict, status: int = 200) -> Response:
return Response(
status=status,
headers=Headers([Header("content-type", "application/json")]),
body=json.dumps(value).encode("utf-8") + b"\n",
)
class UploadError(Exception):
def __init__(self, status: int, message: str, **fields):
super().__init__(message)
self.status = status
self.result = {"error": message, **fields}
def handler(action):
def dispatch(request: Request) -> Response:
# Serialize mutations of this small local store. Core still owns HTTP
# admission, request delivery and cancellation.
with LOCK:
try:
return action(request)
except UploadError as error:
return reply(error.result, error.status)
except (OSError, ValueError) as error:
print(f"Upload store: {error}", flush=True)
return reply({"error": "upload store failed"}, 500)
return dispatch
def header(request: Request, name: str, pattern: re.Pattern) -> str:
value = request.headers.get(name) or ""
if not pattern.fullmatch(value):
raise UploadError(400, f"invalid {name}")
return value
def write_file(destination: Path, data: bytes) -> None:
temporary = destination.parent / "incoming.tmp"
try:
with temporary.open("wb") as output:
if output.write(data) != len(data):
raise OSError("short file write")
os.replace(temporary, destination)
finally:
temporary.unlink(missing_ok=True)
def create(request: Request) -> Response:
if request.body:
raise UploadError(400, "send upload metadata in the headers")
length = int(header(request, "Upload-Length", NUMBER))
digest = header(request, "Upload-SHA256", SHA256)
if not 0 < length <= MAX_FILE:
raise UploadError(413, "file length must be between 1 byte and 32 MiB")
if sum(1 for _ in ROOT.iterdir()) >= MAX_SESSIONS:
raise UploadError(503, "all upload slots are in use")
directory = ROOT / uuid.uuid4().hex
directory.mkdir(mode=0o700)
try:
write_file(directory / "manifest.json", json.dumps({"length": length, "sha256": digest}).encode())
except OSError:
directory.rmdir()
raise
return reply(describe(directory, length, digest), 201)
def load(request: Request) -> tuple[Path, int, str]:
upload_id = request.path_parameters[0].encoded_value
if not ID.fullmatch(upload_id):
raise UploadError(404, "upload not found")
directory = ROOT / upload_id
manifest = directory / "manifest.json"
if not manifest.is_file():
raise UploadError(404, "upload not found")
value = json.loads(manifest.read_text(encoding="utf-8"))
length, digest = value["length"], value["sha256"]
if type(length) is not int or not 0 < length <= MAX_FILE or not isinstance(digest, str) or not SHA256.fullmatch(digest):
raise OSError("invalid upload manifest")
return directory, length, digest
def part_path(directory: Path, offset: int) -> Path:
return directory / f"part-{offset:08d}.bin"
def describe(directory: Path, length: int, digest: str) -> dict:
final = directory / "complete.bin"
complete = final.is_file()
next_offset = length if complete else 0
if complete and final.stat().st_size != length:
raise OSError("published file length is invalid")
if not complete:
# The contiguous, committed part files are the checkpoint. There is
# no separate offset to update after committing a part.
while next_offset < length:
part = part_path(directory, next_offset)
if not part.is_file():
break
expected = min(PART_SIZE, length - next_offset)
if part.stat().st_size != expected:
raise OSError("committed part length is invalid")
next_offset += expected
return {
"upload_id": directory.name,
"next_offset": next_offset,
"length": length,
"part_size": PART_SIZE,
"sha256": digest,
"complete": complete,
}
def status(request: Request) -> Response:
return reply(describe(*load(request)))
def put_part(request: Request) -> Response:
directory, length, digest = load(request)
state = describe(directory, length, digest)
value = request.path_parameters[1].encoded_value
if not NUMBER.fullmatch(value):
raise UploadError(400, "invalid part offset")
offset = int(value)
if offset >= length or offset % PART_SIZE != 0:
raise UploadError(409, "offset is not a part boundary", next_offset=state["next_offset"])
if state["complete"]:
raise UploadError(409, "upload is already complete", next_offset=length)
if offset > state["next_offset"]:
raise UploadError(409, "a prior part is missing", next_offset=state["next_offset"])
media_type = (request.headers.get("content-type") or "").split(";", 1)[0].strip().lower()
if media_type != "application/octet-stream":
raise UploadError(415, "send application/octet-stream")
if len(request.body) != min(PART_SIZE, length - offset):
raise UploadError(400, "incorrect part length", next_offset=state["next_offset"])
part_digest = header(request, "Part-SHA256", SHA256)
if hashlib.sha256(request.body).hexdigest() != part_digest:
raise UploadError(422, "part checksum does not match", next_offset=state["next_offset"])
destination = part_path(directory, offset)
if offset < state["next_offset"]:
with destination.open("rb") as existing:
if hashlib.file_digest(existing, "sha256").hexdigest() != part_digest:
raise UploadError(409, "committed part differs", next_offset=state["next_offset"])
return reply(state) # Retrying the same part never appends it twice.
# This buffered route is invoked only after Core receives the full body.
write_file(destination, request.body)
return reply(describe(directory, length, digest))
def finish(request: Request) -> Response:
if request.body:
raise UploadError(400, "finish does not accept a request body")
directory, length, digest = load(request)
state = describe(directory, length, digest)
if state["complete"]:
return reply(state)
if state["next_offset"] != length:
raise UploadError(409, "upload is incomplete", next_offset=state["next_offset"])
temporary = directory / "assemble.tmp"
actual = hashlib.sha256()
size = 0
try:
with temporary.open("wb") as output:
for offset in range(0, length, PART_SIZE):
with part_path(directory, offset).open("rb") as source:
while data := source.read(64 * 1024):
size += len(data)
if size > length or output.write(data) != len(data):
raise OSError("cannot assemble bounded output")
actual.update(data)
if size != length or actual.hexdigest() != digest:
raise UploadError(422, "assembled file checksum or length does not match")
os.replace(temporary, directory / "complete.bin")
finally:
temporary.unlink(missing_ok=True)
for offset in range(0, length, PART_SIZE):
try:
part_path(directory, offset).unlink()
except OSError as error:
print(f"Remove committed part: {error}", flush=True)
return reply(describe(directory, length, digest), 201)
def remove(request: Request) -> Response:
directory, _, _ = load(request)
shutil.rmtree(directory)
return reply({"deleted": directory.name})
def main() -> None:
ROOT.mkdir(mode=0o700, exist_ok=True)
service = (
Builder()
.listen("127.0.0.1", 8080)
.limits(Limits(max_request_body_bytes=PART_SIZE))
.post("/uploads", handler(create))
.get("/uploads/{upload_id}", handler(status))
.put("/uploads/{upload_id}/parts/{offset}", handler(put_part))
.post("/uploads/{upload_id}/finish", handler(finish))
.delete("/uploads/{upload_id}", handler(remove))
.start()
)
with service:
print("Listening on http://127.0.0.1:8080; press Enter to stop.", flush=True)
input()
if __name__ == "__main__":
main()
python3 -m venv .venv
. .venv/bin/activate
python -m pip install coakka-http-runtime-python==2.3.2
python server.pyNode.js / Bun · 2.3.2
Save the code as server.mjs, then choose the Node.js or Bun package.
server.mjs
import { createHash, randomUUID } from "node:crypto";
import {
closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync,
readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync,
} from "node:fs";
import { join } from "node:path";
const { Builder, Header, Limits, Response } = await import(process.versions.bun
? "coakka-http-runtime-bun"
: "coakka-http-runtime-node");
const PART_SIZE = 4 * 1024 * 1024;
const MAX_FILE = 32 * 1024 * 1024;
const MAX_SESSIONS = 4;
const ROOT = "upload-lab-data";
mkdirSync(ROOT, { recursive: true, mode: 0o700 });
function reply(status, fields) {
return Response.text(JSON.stringify(fields) + "\n", {
status,
headers: [new Header("content-type", "application/json")],
});
}
function reject(status, message, offset) {
return reply(status, { error: message, next_offset: offset });
}
function handler(action) {
return (request) => {
// Synchronous bounded disk work serializes this local example's store.
try {
return action(request);
} catch (error) {
console.error("Upload store:", error);
return reject(500, "upload store failed");
}
};
}
function capture(request, index) {
return Buffer.from(request.pathParameters[index].encodedValue).toString("utf8");
}
function atomicWrite(dir, name, body) {
const temp = join(dir, "incoming.tmp");
try {
writeFileSync(temp, body, { mode: 0o600 });
renameSync(temp, join(dir, name));
} finally {
rmSync(temp, { force: true });
}
}
function create(request) {
const lengthText = request.headers.get("upload-length") ?? "";
const sha256 = request.headers.get("upload-sha256") ?? "";
if (request.bytes().length || !/^[0-9]{1,10}$/.test(lengthText) || !/^[0-9a-f]{64}$/.test(sha256)) {
return reject(400, "invalid upload metadata");
}
const length = Number(lengthText);
if (length < 1 || length > MAX_FILE) return reject(413, "file length must be between 1 byte and 32 MiB");
if (readdirSync(ROOT).length >= MAX_SESSIONS) return reject(503, "all upload slots are in use");
const upload_id = randomUUID().replaceAll("-", "");
const dir = join(ROOT, upload_id);
mkdirSync(dir, { mode: 0o700 });
try {
atomicWrite(dir, "manifest.json", JSON.stringify({ length, sha256 }));
} catch (error) {
rmSync(dir, { recursive: true });
throw error;
}
return reply(201, { upload_id, length, sha256, next_offset: 0, part_size: PART_SIZE, complete: false });
}
function partName(offset) {
return `part-${String(offset).padStart(8, "0")}.bin`;
}
function load(id) {
if (!/^[0-9a-f]{32}$/.test(id)) return null;
const dir = join(ROOT, id);
const manifest = join(dir, "manifest.json");
if (!existsSync(manifest)) return null;
const { length, sha256 } = JSON.parse(readFileSync(manifest, "utf8"));
if (!Number.isSafeInteger(length) || length < 1 || length > MAX_FILE || !/^[0-9a-f]{64}$/.test(sha256)) {
throw new Error("invalid upload manifest");
}
const target = join(dir, "complete.bin");
const complete = existsSync(target);
let next_offset = complete ? length : 0;
if (complete && statSync(target).size !== length) throw new Error("invalid published length");
while (next_offset < length) {
const path = join(dir, partName(next_offset));
if (!existsSync(path)) break;
const size = Math.min(PART_SIZE, length - next_offset);
if (statSync(path).size !== size) throw new Error("invalid committed part length");
next_offset += size;
}
return { dir, state: { upload_id: id, length, sha256, next_offset, part_size: PART_SIZE, complete } };
}
function lookup(action) {
return (request) => {
const upload = load(capture(request, 0));
if (!upload) return reject(404, "upload not found");
return action(request, upload.dir, upload.state);
};
}
function digest(body) {
return createHash("sha256").update(body).digest("hex");
}
function put(request, dir, state) {
const value = capture(request, 1);
if (!/^[0-9]{1,10}$/.test(value)) return reject(400, "invalid part offset");
const offset = Number(value);
if (state.complete || offset >= state.length || offset % PART_SIZE || offset > state.next_offset) {
return reject(409, "wrong part offset or completed upload", state.next_offset);
}
const media = (request.headers.get("content-type") ?? "").split(";", 1)[0].trim().toLowerCase();
if (media !== "application/octet-stream") return reject(415, "send application/octet-stream");
const body = request.bytes();
if (body.length !== Math.min(PART_SIZE, state.length - offset)) {
return reject(400, "incorrect part length", state.next_offset);
}
const checksum = request.headers.get("part-sha256") ?? "";
if (!/^[0-9a-f]{64}$/.test(checksum)) return reject(400, "invalid part checksum");
if (digest(body) !== checksum) return reject(422, "part checksum does not match", state.next_offset);
if (offset < state.next_offset) {
if (digest(readFileSync(join(dir, partName(offset)))) !== checksum) {
return reject(409, "committed part differs", state.next_offset);
}
return reply(200, state);
}
atomicWrite(dir, partName(offset), body);
state.next_offset += body.length;
return reply(200, state);
}
function assemble(dir, size) {
const temp = join(dir, "assemble.tmp");
const output = openSync(temp, "w", 0o600);
const buffer = Buffer.alloc(64 * 1024);
const hash = createHash("sha256");
let total = 0;
try {
for (let offset = 0; offset < size; offset += PART_SIZE) {
const part = openSync(join(dir, partName(offset)), "r");
try {
let count;
while ((count = readSync(part, buffer, 0, buffer.length, null))) {
if (count > size - total) throw new Error("assembled file exceeds the declared length");
hash.update(buffer.subarray(0, count));
for (let written = 0; written < count;) {
const next = writeSync(output, buffer, written, count - written);
if (!next) throw new Error("upload write made no progress");
written += next;
}
total += count;
}
} finally {
closeSync(part);
}
}
} finally {
closeSync(output);
}
return { length: total, sha256: hash.digest("hex") };
}
function finish(request, dir, state) {
if (request.bytes().length) return reject(400, "finish does not accept a body");
if (state.complete) return reply(200, state);
if (state.next_offset !== state.length) return reject(409, "upload is incomplete", state.next_offset);
const temp = join(dir, "assemble.tmp");
try {
const actual = assemble(dir, state.length);
if (actual.length !== state.length || actual.sha256 !== state.sha256) {
return reject(422, "assembled file checksum or length does not match");
}
renameSync(temp, join(dir, "complete.bin"));
} finally {
rmSync(temp, { force: true });
}
for (let offset = 0; offset < state.length; offset += PART_SIZE) {
try {
rmSync(join(dir, partName(offset)));
} catch (error) {
console.error("Remove committed part:", error);
}
}
state.complete = true;
return reply(201, state);
}
const service = new Builder()
.listen("127.0.0.1", 8080)
.limits(new Limits({ maxRequestBodyBytes: PART_SIZE }))
.post("/uploads", handler(create))
.get("/uploads/{upload_id}", handler(lookup((_request, _dir, state) => reply(200, state))))
.put("/uploads/{upload_id}/parts/{offset}", handler(lookup(put)))
.post("/uploads/{upload_id}/finish", handler(lookup(finish)))
.delete("/uploads/{upload_id}", handler(lookup((_request, dir, state) => {
rmSync(dir, { recursive: true });
return reply(200, { deleted: state.upload_id });
})))
.start();
console.log("Listening on http://127.0.0.1:8080; press Enter to stop.");
try {
for await (const chunk of process.stdin) {
if (chunk.length) break;
}
} finally {
await service.close();
}
Node.js
npm install --save-exact [email protected]
node server.mjsBun
bun add --exact [email protected]
bun server.mjsRun one server at a time on 127.0.0.1:8080. Press Enter to stop it. Resume a session against the server and data directory where it was created.
Choose a client
Choose a client independently of the server language. In a second terminal in the server’s working directory, build the client if needed and define upload as shown. The steps below use that command.
C / C++
Save all 5 files in client-native/. The shared code reads JSON and checks SHA-256. C uses fseek; C++ uses seekg to reach next_offset.
Install client libraries
sudo apt install cmake pkg-config libcurl4-openssl-dev libjson-c-dev libssl-devbrew install cmake pkgconf curl json-c openssl@3Shared files
cmake_minimum_required(VERSION 3.24)
project(coakka_upload_clients LANGUAGES C CXX)
find_package(PkgConfig REQUIRED)
find_package(OpenSSL 3 REQUIRED COMPONENTS Crypto)
find_package(CURL REQUIRED)
pkg_check_modules(JSON_C REQUIRED IMPORTED_TARGET json-c)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_library(client-api STATIC client_api.c)
target_link_libraries(client-api PRIVATE CURL::libcurl PkgConfig::JSON_C OpenSSL::Crypto)
add_executable(client-c client.c)
add_executable(client-cpp client.cpp)
target_link_libraries(client-c PRIVATE client-api)
target_link_libraries(client-cpp PRIVATE client-api)
foreach(target IN ITEMS client-api client-c client-cpp)
target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic -Werror)
endforeach()
#ifndef COAKKA_PORTAL_UPLOAD_CLIENT_API_H
#define COAKKA_PORTAL_UPLOAD_CLIENT_API_H
#include <stdbool.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
enum { PART_SIZE = 4 * 1024 * 1024, JSON_LIMIT = 8192 };
typedef struct {
size_t length;
char sha256[65];
} file_info_t;
typedef struct {
char base[48];
} client_t;
typedef struct {
char json[JSON_LIMIT + 1];
size_t size;
long http_status;
} reply_t;
typedef struct {
file_info_t expected;
size_t next_offset;
bool complete;
reply_t reply;
} checkpoint_t;
typedef bool (*resume_fn)(const client_t *, const char *id, const char *file,
size_t stop_after, checkpoint_t *);
bool client_error(const char *message);
bool file_info(const char *path, file_info_t *out);
bool same_file(file_info_t a, file_info_t b);
bool get_checkpoint(const client_t *, const char *id, checkpoint_t *out);
bool put_part(const client_t *, const char *id, size_t offset, const void *data,
size_t size, checkpoint_t *out);
bool resume_checkpoint(const client_t *, const char *id, file_info_t source,
size_t confirmed, checkpoint_t *out);
bool retry_unavailable(const reply_t *, unsigned *retries);
int client_main(int argc, char **argv, resume_fn resume);
#ifdef __cplusplus
}
#endif
#endif
#if !defined(_WIN32) && !defined(_POSIX_C_SOURCE)
#define _POSIX_C_SOURCE 200809L
#endif
#include "client_api.h"
#include <curl/curl.h>
#include <json-c/json.h>
#include <openssl/evp.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <time.h>
#endif
enum { MAX_FILE = 32 * 1024 * 1024 };
bool client_error(const char *message) {
fprintf(stderr, "%s\n", message);
return false;
}
static bool decimal(const char *value, size_t max, size_t *out) {
if (!value || !*value) {
return false;
}
size_t result = 0;
for (; *value; ++value) {
if (*value < '0' || *value > '9' || result > max / 10U) {
return false;
}
const size_t digit = (size_t)(*value - '0');
if (digit > max - result * 10U) {
return false;
}
result = result * 10U + digit;
}
*out = result;
return true;
}
static bool is_hex(const char *value, size_t length) {
return value && strlen(value) == length &&
strspn(value, "0123456789abcdef") == length;
}
static void hex(const unsigned char digest[32], char out[65]) {
static const char digits[] = "0123456789abcdef";
for (size_t index = 0; index < 32U; ++index) {
out[index * 2U] = digits[digest[index] >> 4U];
out[index * 2U + 1U] = digits[digest[index] & 15U];
}
out[64] = '\0';
}
bool file_info(const char *path, file_info_t *out) {
FILE *input = fopen(path, "rb");
if (!input) {
perror(path);
return false;
}
EVP_MD_CTX *context = EVP_MD_CTX_new();
bool ok = context && EVP_DigestInit_ex(context, EVP_sha256(), NULL) == 1;
unsigned char buffer[64 * 1024];
size_t size = 0;
size_t count;
while (ok && (count = fread(buffer, 1U, sizeof(buffer), input)) != 0U) {
if (count > MAX_FILE - size) {
ok = false;
break;
}
size += count;
ok = EVP_DigestUpdate(context, buffer, count) == 1;
}
unsigned char digest[32];
unsigned length = 0;
ok = ok && !ferror(input) && size > 0 &&
EVP_DigestFinal_ex(context, digest, &length) == 1 &&
length == sizeof(digest);
if (fclose(input) != 0) {
ok = false;
}
EVP_MD_CTX_free(context);
if (!ok) {
return client_error(
"cannot hash file, or file size is outside 1 byte–32 MiB");
}
out->length = size;
hex(digest, out->sha256);
return true;
}
bool same_file(file_info_t a, file_info_t b) {
return a.length == b.length && strcmp(a.sha256, b.sha256) == 0;
}
static size_t receive(char *data, size_t width, size_t count, void *context) {
reply_t *reply = context;
if (width && count > (JSON_LIMIT - reply->size) / width) {
return 0;
}
const size_t size = width * count;
memcpy(reply->json + reply->size, data, size);
reply->size += size;
reply->json[reply->size] = '\0';
return size;
}
static bool request(const client_t *client, const char *method,
const char *path, const void *data, size_t size,
const char *first_header, const char *second_header,
reply_t *reply) {
*reply = (reply_t){0};
CURL *curl = curl_easy_init();
if (!curl) {
return client_error("cannot create HTTP client");
}
char url[160];
const int count = snprintf(url, sizeof(url), "%s%s", client->base, path);
bool ok = false;
struct curl_slist *headers = NULL;
const char *fields[] = {"Expect:", first_header, second_header};
if (count < 0 || (size_t)count >= sizeof(url)) {
goto done;
}
for (size_t index = 0; index < sizeof(fields) / sizeof(fields[0]); ++index) {
if (fields[index]) {
struct curl_slist *next = curl_slist_append(headers, fields[index]);
if (!next) {
goto done;
}
headers = next;
}
}
if (curl_easy_setopt(curl, CURLOPT_URL, url) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_PROXY, "") != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15L) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, receive) != CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, reply) != CURLE_OK) {
goto done;
}
if (data || strcmp(method, "POST") == 0) {
if (curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)size) !=
CURLE_OK ||
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data ? data : "") !=
CURLE_OK) {
goto done;
}
}
if (curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method) != CURLE_OK) {
goto done;
}
const CURLcode result = curl_easy_perform(curl);
long status = 0;
if (result != CURLE_OK) {
client_error(curl_easy_strerror(result));
} else if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status) ==
CURLE_OK) {
reply->http_status = status;
if (status >= 200 && status < 300) {
ok = true;
} else {
fprintf(stderr, "HTTP %ld: %s\n", status, reply->json);
}
}
done:
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
return ok;
}
static struct json_object *field(struct json_object *object, const char *name,
enum json_type type) {
struct json_object *value = NULL;
if (!object || !json_object_object_get_ex(object, name, &value) ||
!json_object_is_type(value, type)) {
return NULL;
}
return value;
}
static bool read_checkpoint(const char *id, checkpoint_t *out) {
struct json_object *doc = json_tokener_parse(out->reply.json);
struct json_object *length = field(doc, "length", json_type_int);
struct json_object *offset = field(doc, "next_offset", json_type_int);
struct json_object *part = field(doc, "part_size", json_type_int);
struct json_object *done = field(doc, "complete", json_type_boolean);
struct json_object *hash = field(doc, "sha256", json_type_string);
struct json_object *upload = field(doc, "upload_id", json_type_string);
bool valid = false;
if (length && offset && part && done && hash && upload) {
const int64_t size = json_object_get_int64(length);
const int64_t next = json_object_get_int64(offset);
const char *sha = json_object_get_string(hash);
const bool complete = json_object_get_boolean(done);
if (strcmp(json_object_get_string(upload), id) == 0 && size > 0 &&
size <= MAX_FILE && next >= 0 && next <= size &&
json_object_get_int64(part) == PART_SIZE && is_hex(sha, 64U) &&
(next == size || (!complete && next % PART_SIZE == 0))) {
out->expected.length = (size_t)size;
memcpy(out->expected.sha256, sha, 65U);
out->next_offset = (size_t)next;
out->complete = complete;
valid = true;
}
}
json_object_put(doc);
return valid || client_error("invalid server checkpoint");
}
bool get_checkpoint(const client_t *client, const char *id, checkpoint_t *out) {
char path[48];
snprintf(path, sizeof(path), "/%s", id);
return request(client, "GET", path, NULL, 0U, NULL, NULL, &out->reply) &&
read_checkpoint(id, out);
}
bool put_part(const client_t *client, const char *id, size_t offset,
const void *data, size_t size, checkpoint_t *out) {
out->reply.http_status = 0L;
unsigned char digest[32];
unsigned length = 0;
if (size > PART_SIZE ||
EVP_Digest(data, size, digest, &length, EVP_sha256(), NULL) != 1 ||
length != sizeof(digest)) {
return client_error("cannot hash part");
}
char sha[65];
hex(digest, sha);
char checksum[88], path[80];
snprintf(checksum, sizeof(checksum), "Part-SHA256: %s", sha);
snprintf(path, sizeof(path), "/%s/parts/%zu", id, offset);
if (!request(client, "PUT", path, data, size,
"Content-Type: application/octet-stream", checksum,
&out->reply) ||
!read_checkpoint(id, out)) {
return false;
}
return out->next_offset == offset + size ||
client_error("unexpected offset; check status before retrying");
}
bool resume_checkpoint(const client_t *client, const char *id,
file_info_t source, size_t confirmed, checkpoint_t *out) {
if (!get_checkpoint(client, id, out)) {
return false;
}
if (!same_file(source, out->expected)) {
return client_error("source file no longer matches this upload session");
}
return out->next_offset >= confirmed ||
client_error("server checkpoint moved backward");
}
bool retry_unavailable(const reply_t *reply, unsigned *retries) {
if (reply->http_status != 503L || *retries == 3U) {
return false;
}
const unsigned milliseconds = 100U << *retries;
++*retries;
#ifdef _WIN32
Sleep(milliseconds);
#else
const struct timespec delay = {0, (long)milliseconds * 1000000L};
if (nanosleep(&delay, NULL) != 0) {
return client_error("retry wait interrupted");
}
#endif
return true;
}
static bool verify(const client_t *client, const char *id, const char *source,
const char *assembled) {
checkpoint_t state;
file_info_t original, final;
if (!get_checkpoint(client, id, &state)) {
return false;
}
if (!state.complete) {
return client_error("finish the upload before verifying");
}
if (!file_info(source, &original) || !file_info(assembled, &final)) {
return false;
}
if (!same_file(original, state.expected) ||
!same_file(final, state.expected)) {
return client_error("file length or SHA-256 does not match");
}
struct json_object *doc = json_tokener_parse(state.reply.json);
if (!doc) {
return client_error("invalid verification response");
}
json_object_object_add(doc, "verified", json_object_new_boolean(true));
puts(json_object_to_json_string_ext(doc, JSON_C_TO_STRING_PLAIN));
json_object_put(doc);
return true;
}
static bool run(const client_t *client, int argc, char **argv,
resume_fn resume) {
static const char *usage =
"usage: start FILE | status ID | resume ID FILE [--stop-after N] | "
"finish ID | verify ID FILE ASSEMBLED | delete ID";
if (argc < 3) {
return client_error(usage);
}
const char *action = argv[1], *id = argv[2];
reply_t reply;
bool ok = false;
if (strcmp(action, "start") == 0 && argc == 3) {
file_info_t source;
if (!file_info(id, &source)) {
return false;
}
char length[48], digest[88];
snprintf(length, sizeof(length), "Upload-Length: %zu", source.length);
snprintf(digest, sizeof(digest), "Upload-SHA256: %s", source.sha256);
ok = request(client, "POST", "", NULL, 0U, length, digest, &reply);
} else if (!is_hex(id, 32U)) {
return client_error("invalid upload ID");
} else if (strcmp(action, "status") == 0 && argc == 3) {
checkpoint_t state;
if (!get_checkpoint(client, id, &state)) {
return false;
}
reply = state.reply;
ok = true;
} else if (strcmp(action, "resume") == 0 && (argc == 4 || argc == 6)) {
size_t stop_after = SIZE_MAX;
if (argc == 6 &&
(strcmp(argv[4], "--stop-after") != 0 ||
!decimal(argv[5], 999999999U, &stop_after) || stop_after == 0U)) {
return client_error(usage);
}
checkpoint_t state;
if (!resume(client, id, argv[3], stop_after, &state)) {
return false;
}
reply = state.reply;
ok = true;
} else if (strcmp(action, "verify") == 0 && argc == 5) {
return verify(client, id, argv[3], argv[4]);
} else if (strcmp(action, "finish") == 0 && argc == 3) {
char path[64];
snprintf(path, sizeof(path), "/%s/finish", id);
ok = request(client, "POST", path, NULL, 0U, NULL, NULL, &reply);
} else if (strcmp(action, "delete") == 0 && argc == 3) {
char path[48];
snprintf(path, sizeof(path), "/%s", id);
ok = request(client, "DELETE", path, NULL, 0U, NULL, NULL, &reply);
} else {
return client_error(usage);
}
if (ok) {
puts(reply.json);
}
return ok;
}
int client_main(int argc, char **argv, resume_fn resume) {
const char *value = getenv("COAKKA_UPLOAD_LAB_PORT");
size_t port = 8080U;
if (value && (strlen(value) > 5 || !decimal(value, 65535U, &port) || !port)) {
client_error("invalid local lab port");
return EXIT_FAILURE;
}
client_t client;
snprintf(client.base, sizeof(client.base), "http://127.0.0.1:%zu/uploads",
port);
if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) {
client_error("cannot initialize libcurl");
return EXIT_FAILURE;
}
const bool ok = run(&client, argc, argv, resume);
if (!ok && argc > 1 && strcmp(argv[1], "resume") == 0) {
client_error(
"Check status and run resume again with the same ID and file.");
}
curl_global_cleanup();
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
C · client.c
#include "client_api.h"
#include <stdio.h>
#include <stdlib.h>
static bool resume(const client_t *client, const char *id, const char *path,
size_t stop_after, checkpoint_t *state) {
file_info_t source;
if (!file_info(path, &source)) {
return false;
}
FILE *file = fopen(path, "rb");
if (!file) {
perror(path);
return false;
}
unsigned char *body = malloc(PART_SIZE);
if (!body) {
fclose(file);
return client_error("cannot allocate a part buffer");
}
bool ok;
size_t confirmed = 0;
size_t start_offset = source.length;
unsigned retries = 0;
do {
ok = resume_checkpoint(client, id, source, confirmed, state);
if (ok) {
confirmed = state->next_offset;
if (start_offset == source.length) {
start_offset = confirmed;
}
if (fseek(file, (long)confirmed, SEEK_SET) != 0) {
ok = client_error("cannot seek to the confirmed offset");
break;
}
}
while (ok && confirmed < source.length &&
(confirmed - start_offset) / PART_SIZE < stop_after) {
const size_t remaining = source.length - confirmed;
const size_t count = remaining < PART_SIZE ? remaining : PART_SIZE;
if (fread(body, 1U, count, file) != count) {
ok = client_error("source file ended early");
break;
}
ok = put_part(client, id, confirmed, body, count, state);
if (ok) {
confirmed = state->next_offset;
}
}
// After the wait, read the committed offset before sending again.
} while (!ok && retry_unavailable(&state->reply, &retries));
free(body);
const bool closed = fclose(file) == 0;
return ok && closed;
}
int main(int argc, char **argv) { return client_main(argc, argv, resume); }
C++ · client.cpp
#include "client_api.h"
#include <algorithm>
#include <exception>
#include <fstream>
#include <vector>
static bool resume(const client_t *client, const char *id, const char *path,
std::size_t stop_after, checkpoint_t *state) noexcept {
try {
file_info_t source{};
if (!file_info(path, &source)) {
return false;
}
std::ifstream file(path, std::ios::binary);
std::vector<char> body(PART_SIZE);
bool ok;
std::size_t confirmed = 0;
std::size_t start_offset = source.length;
unsigned retries = 0;
do {
ok = resume_checkpoint(client, id, source, confirmed, state);
if (ok) {
confirmed = state->next_offset;
if (start_offset == source.length) {
start_offset = confirmed;
}
if (!file.seekg(static_cast<std::streamoff>(confirmed))) {
return client_error("cannot seek to the confirmed offset");
}
}
while (ok && confirmed < source.length &&
(confirmed - start_offset) / PART_SIZE < stop_after) {
const std::size_t count = std::min(body.size(), source.length - confirmed);
if (!file.read(body.data(), static_cast<std::streamsize>(count))) {
return client_error("source file ended early");
}
ok = put_part(client, id, confirmed, body.data(), count, state);
if (ok) {
confirmed = state->next_offset;
}
}
// After the wait, read the committed offset before sending again.
} while (!ok && retry_unavailable(&state->reply, &retries));
return ok;
} catch (const std::exception &error) {
return client_error(error.what());
}
}
int main(int argc, char **argv) { return client_main(argc, argv, resume); }
cmake -S client-native -B client-native/build
cmake --build client-native/buildOn macOS, if CMake cannot find the libraries, add -DCMAKE_PREFIX_PATH="$(brew --prefix curl);$(brew --prefix openssl@3)" to the configure command.
Choose one of the following commands to set upload.
upload() { ./client-native/build/client-c "$@"; }upload() { ./client-native/build/client-cpp "$@"; }Go
Save as client.go. The standard-library client uses Seek with next_offset before sending the next part.
client.go
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"regexp"
"strconv"
"time"
)
const partSize = 4 * 1024 * 1024
const maxFile = 32 * 1024 * 1024
var idPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
var shaPattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
var decimal = regexp.MustCompile(`^[0-9]+$`)
var transport = &http.Client{
Timeout: 15 * time.Second,
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
},
}
type httpStatusError struct {
status int
detail string
}
func (err *httpStatusError) Error() string {
return fmt.Sprintf("HTTP %d: %s", err.status, err.detail)
}
func retryUnavailable(err error, retries *int) bool {
var response *httpStatusError
if !errors.As(err, &response) || response.status != http.StatusServiceUnavailable || *retries == 3 {
return false
}
time.Sleep((100 * time.Millisecond) << *retries)
*retries += 1
return true
}
type state struct {
ID string `json:"upload_id"`
Length int64 `json:"length"`
PartSize int64 `json:"part_size"`
NextOffset int64 `json:"next_offset"`
SHA256 string `json:"sha256"`
Complete bool `json:"complete"`
Verified bool `json:"verified,omitempty"`
}
type fingerprint struct {
length int64
sha256 string
}
func baseURL() (string, error) {
value := os.Getenv("COAKKA_UPLOAD_LAB_PORT")
if value == "" {
value = "8080"
}
port, err := strconv.Atoi(value)
if err != nil || !decimal.MatchString(value) || len(value) > 5 || port < 1 || port > 65535 {
return "", errors.New("invalid local lab port")
}
return fmt.Sprintf("http://127.0.0.1:%d/uploads", port), nil
}
func call(method, path string, body []byte, headers map[string]string, result any) error {
base, err := baseURL()
if err != nil {
return err
}
req, err := http.NewRequest(method, base+path, bytes.NewReader(body))
if err != nil {
return err
}
for name, value := range headers {
req.Header.Set(name, value)
}
response, err := transport.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
data, err := io.ReadAll(io.LimitReader(response.Body, 8193))
if err != nil {
return err
}
if len(data) > 8192 {
return errors.New("server response exceeded the lab limit")
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return &httpStatusError{response.StatusCode, string(bytes.TrimSpace(data))}
}
return json.Unmarshal(data, result)
}
func fileInfo(path string) (fingerprint, error) {
file, err := os.Open(path)
if err != nil {
return fingerprint{}, err
}
defer file.Close()
hash := sha256.New()
size, err := io.Copy(hash, io.LimitReader(file, maxFile+1))
if err != nil {
return fingerprint{}, err
}
if size < 1 || size > maxFile {
return fingerprint{}, errors.New("file size must be between 1 byte and 32 MiB")
}
return fingerprint{size, hex.EncodeToString(hash.Sum(nil))}, nil
}
func checkpoint(id string) (state, error) {
var remote state
if err := call("GET", "/"+id, nil, nil, &remote); err != nil {
return state{}, err
}
if remote.ID != id || remote.PartSize != partSize || remote.Length < 1 ||
remote.Length > maxFile || !shaPattern.MatchString(remote.SHA256) ||
remote.NextOffset < 0 || remote.NextOffset > remote.Length ||
(remote.NextOffset != remote.Length && (remote.NextOffset%partSize != 0 || remote.Complete)) {
return state{}, errors.New("invalid server checkpoint")
}
return remote, nil
}
func resume(id, path string, stopAfter int) (state, error) {
source, err := fileInfo(path)
if err != nil {
return state{}, err
}
file, err := os.Open(path)
if err != nil {
return state{}, err
}
defer file.Close()
buffer := make([]byte, partSize)
var confirmed int64
startOffset := int64(-1)
retries := 0
refresh:
for {
remote, err := checkpoint(id)
if err != nil {
if retryUnavailable(err, &retries) {
continue
}
return state{}, err
}
if source != (fingerprint{remote.Length, remote.SHA256}) {
return state{}, errors.New("source file no longer matches this upload session")
}
if remote.NextOffset < confirmed {
return state{}, errors.New("server checkpoint moved backward")
}
confirmed = remote.NextOffset
if startOffset < 0 {
startOffset = confirmed
}
if _, err := file.Seek(confirmed, io.SeekStart); err != nil {
return state{}, err
}
for confirmed < source.length && (stopAfter == 0 || (confirmed-startOffset)/partSize < int64(stopAfter)) {
count := min(int64(partSize), source.length-confirmed)
body := buffer[:count]
if _, err := io.ReadFull(file, body); err != nil {
return state{}, err
}
sum := sha256.Sum256(body)
err := call("PUT", fmt.Sprintf("/%s/parts/%d", id, confirmed), body, map[string]string{
"Content-Type": "application/octet-stream", "Part-SHA256": hex.EncodeToString(sum[:]),
}, &remote)
if err != nil {
if retryUnavailable(err, &retries) {
// The next GET chooses the position before we send again.
continue refresh
}
return state{}, err
}
if remote.NextOffset != confirmed+count {
return state{}, errors.New("unexpected offset; check status before retrying")
}
confirmed = remote.NextOffset
}
return remote, nil
}
}
func verify(id, source, assembled string) (state, error) {
remote, err := checkpoint(id)
if err != nil {
return state{}, err
}
if !remote.Complete {
return state{}, errors.New("finish the upload before verifying")
}
expected := fingerprint{remote.Length, remote.SHA256}
for _, path := range []string{source, assembled} {
actual, err := fileInfo(path)
if err != nil {
return state{}, err
}
if actual != expected {
return state{}, errors.New("file length or SHA-256 does not match")
}
}
remote.Verified = true
return remote, nil
}
func run(args []string) (any, error) {
usage := errors.New("usage: start FILE | status ID | resume ID FILE [--stop-after N] | finish ID | verify ID FILE ASSEMBLED | delete ID")
if len(args) < 2 {
return nil, usage
}
action, id := args[0], args[1]
if action == "start" && len(args) == 2 {
source, err := fileInfo(args[1])
if err != nil {
return nil, err
}
var remote state
err = call("POST", "", nil, map[string]string{
"Upload-Length": strconv.FormatInt(source.length, 10), "Upload-SHA256": source.sha256,
}, &remote)
return remote, err
}
if !idPattern.MatchString(id) {
return nil, errors.New("invalid upload ID")
}
switch {
case action == "status" && len(args) == 2:
return checkpoint(id)
case action == "resume" && (len(args) == 3 || len(args) == 5):
limit := 0
if len(args) == 5 {
n, err := strconv.Atoi(args[4])
if args[3] != "--stop-after" || err != nil || !decimal.MatchString(args[4]) || n < 1 {
return nil, usage
}
limit = n
}
return resume(id, args[2], limit)
case action == "finish" && len(args) == 2:
var remote state
err := call("POST", "/"+id+"/finish", nil, nil, &remote)
return remote, err
case action == "verify" && len(args) == 4:
return verify(id, args[2], args[3])
case action == "delete" && len(args) == 2:
var response map[string]string
err := call("DELETE", "/"+id, nil, nil, &response)
return response, err
default:
return nil, usage
}
}
func main() {
result, err := run(os.Args[1:])
if err == nil {
err = json.NewEncoder(os.Stdout).Encode(result)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
if len(os.Args) > 1 && os.Args[1] == "resume" {
fmt.Fprintln(os.Stderr, "Check status and run resume again with the same ID and file.")
}
os.Exit(1)
}
}
go build -o client-go client.go
upload() { ./client-go "$@"; }Java / Kotlin · JVM
Use JDK 17+ and a separate client-jvm/ directory beside the server. Save the 3 source files at the paths shown. The two clients share HTTP and SHA-256 helpers and each shows how to seek to next_offset with RandomAccessFile.
Shared client API
package study;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.HexFormat;
import java.util.Map;
final class UploadClientApi {
static final int PART_SIZE = 4 * 1024 * 1024;
private static final int MAX_FILE = 32 * 1024 * 1024;
private static final Duration TIMEOUT = Duration.ofSeconds(15);
private static final HttpClient HTTP = HttpClient.newBuilder()
.connectTimeout(TIMEOUT).followRedirects(HttpClient.Redirect.NEVER).build();
private static final String USAGE = "usage: start FILE | status ID | resume ID FILE [--stop-after N]"
+ " | finish ID | verify ID FILE ASSEMBLED | delete ID";
private UploadClientApi() {}
record FileInfo(long length, String sha256) {}
record State(long length, long nextOffset, String sha256, boolean complete, JsonObject json) {}
static final class HttpStatusError extends IOException {
private static final long serialVersionUID = 1L;
private final int status;
HttpStatusError(int status, String detail) {
super("HTTP " + status + ": " + detail);
this.status = status;
}
}
static final class BusyRetry {
private int retries;
boolean waitBeforeRefresh(HttpStatusError error) throws InterruptedException {
if (error.status != 503 || retries == 3) {
return false;
}
Thread.sleep(100L << retries++);
return true;
}
}
@FunctionalInterface
interface ResumeAction {
JsonObject resume(String id, Path file, int stopAfter) throws Exception;
}
private static String baseUrl() {
String value = System.getenv().getOrDefault("COAKKA_UPLOAD_LAB_PORT", "8080");
if (!value.matches("[0-9]{1,5}")) {
throw new IllegalArgumentException("invalid local lab port");
}
int port = Integer.parseInt(value);
if (port < 1 || port > 65535) {
throw new IllegalArgumentException("invalid local lab port");
}
return "http://127.0.0.1:" + port + "/uploads";
}
private static JsonObject call(String method, String path, byte[] data,
Map<String, String> headers) throws IOException, InterruptedException {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(baseUrl() + path)).timeout(TIMEOUT)
.method(method, data == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofByteArray(data));
headers.forEach(builder::header);
HttpResponse<InputStream> response = HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofInputStream());
byte[] result;
try (InputStream body = response.body()) {
result = body.readNBytes(8193);
}
if (result.length > 8192) {
throw new IOException("server response exceeded the lab limit");
}
String text = new String(result, StandardCharsets.UTF_8);
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new HttpStatusError(response.statusCode(), text.trim());
}
return JsonParser.parseString(text).getAsJsonObject();
}
static FileInfo fileInfo(Path file) throws Exception {
MessageDigest hash = MessageDigest.getInstance("SHA-256");
long size = 0;
byte[] buffer = new byte[64 * 1024];
try (InputStream source = Files.newInputStream(file)) {
int count;
while ((count = source.read(buffer)) != -1) {
size += count;
if (size > MAX_FILE) {
throw new IOException("file exceeds 32 MiB");
}
hash.update(buffer, 0, count);
}
}
if (size == 0) {
throw new IOException("file must not be empty");
}
return new FileInfo(size, HexFormat.of().formatHex(hash.digest()));
}
private static State state(String id, JsonObject json) throws IOException {
long length = json.get("length").getAsLong();
long offset = json.get("next_offset").getAsLong();
String hash = json.get("sha256").getAsString();
boolean complete = json.get("complete").getAsBoolean();
if (!id.equals(json.get("upload_id").getAsString()) || json.get("part_size").getAsInt() != PART_SIZE
|| length < 1 || length > MAX_FILE || !hash.matches("[0-9a-f]{64}")
|| offset < 0 || offset > length
|| (offset != length && (complete || offset % PART_SIZE != 0))) {
throw new IOException("invalid server checkpoint");
}
return new State(length, offset, hash, complete, json);
}
static State checkpoint(String id) throws IOException, InterruptedException {
return state(id, call("GET", "/" + id, null, Map.of()));
}
static void checkSource(State remote, FileInfo source, long confirmed) throws IOException {
if (source.length() != remote.length() || !source.sha256().equals(remote.sha256())) {
throw new IOException("source file no longer matches this upload session");
}
if (remote.nextOffset() < confirmed) {
throw new IOException("server checkpoint moved backward");
}
}
static State put(String id, long offset, byte[] body) throws Exception {
String partHash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(body));
State next = state(id, call("PUT", "/" + id + "/parts/" + offset, body, Map.of(
"Content-Type", "application/octet-stream", "Part-SHA256", partHash)));
if (next.nextOffset() != offset + body.length) {
throw new IOException("unexpected offset; check status before retrying");
}
return next;
}
private static JsonObject verify(String id, Path source, Path assembled) throws Exception {
State remote = checkpoint(id);
if (!remote.complete()) {
throw new IOException("finish the upload before verifying");
}
FileInfo expected = new FileInfo(remote.length(), remote.sha256());
if (!fileInfo(source).equals(expected) || !fileInfo(assembled).equals(expected)) {
throw new IOException("file length or SHA-256 does not match");
}
JsonObject result = remote.json();
result.addProperty("verified", true);
return result;
}
private static JsonObject dispatch(String[] args, ResumeAction resume) throws Exception {
if (args.length < 2) {
throw new IllegalArgumentException(USAGE);
}
String action = args[0];
String id = args[1];
if (action.equals("start") && args.length == 2) {
FileInfo info = fileInfo(Path.of(id));
return call("POST", "", null, Map.of(
"Upload-Length", Long.toString(info.length()), "Upload-SHA256", info.sha256()));
}
if (!id.matches("[0-9a-f]{32}")) {
throw new IllegalArgumentException("invalid upload ID");
}
return switch (action) {
case "status" -> {
require(args.length == 2);
yield checkpoint(id).json();
}
case "resume" -> {
require(args.length == 3 || (args.length == 5 && args[3].equals("--stop-after")
&& args[4].matches("[0-9]{1,9}")));
int count = args.length == 5 ? Integer.parseInt(args[4]) : Integer.MAX_VALUE;
require(count > 0);
yield resume.resume(id, Path.of(args[2]), count);
}
case "finish" -> {
require(args.length == 2);
yield call("POST", "/" + id + "/finish", null, Map.of());
}
case "verify" -> {
require(args.length == 4);
yield verify(id, Path.of(args[2]), Path.of(args[3]));
}
case "delete" -> {
require(args.length == 2);
yield call("DELETE", "/" + id, null, Map.of());
}
default -> throw new IllegalArgumentException(USAGE);
};
}
private static void require(boolean valid) {
if (!valid) {
throw new IllegalArgumentException(USAGE);
}
}
static int run(String[] args, ResumeAction resume) {
try {
System.out.println(dispatch(args, resume));
return 0;
} catch (Exception error) {
System.err.println(error.getMessage());
if (args.length > 0 && args[0].equals("resume")) {
System.err.println("Check status and run resume again with the same ID and file.");
}
if (error instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
return 1;
}
}
}
Java
package study;
import com.google.gson.JsonObject;
import java.io.RandomAccessFile;
import java.nio.file.Path;
public final class JavaUploadClient {
private JavaUploadClient() {}
static JsonObject resume(String id, Path path, int stopAfter) throws Exception {
UploadClientApi.FileInfo source = UploadClientApi.fileInfo(path);
UploadClientApi.BusyRetry retry = new UploadClientApi.BusyRetry();
long confirmed = 0;
long startOffset = -1;
try (RandomAccessFile file = new RandomAccessFile(path.toFile(), "r")) {
while (true) {
try {
UploadClientApi.State remote = UploadClientApi.checkpoint(id);
UploadClientApi.checkSource(remote, source, confirmed);
confirmed = remote.nextOffset();
if (startOffset < 0) {
startOffset = confirmed;
}
file.seek(confirmed);
while (confirmed < source.length()
&& (confirmed - startOffset) / UploadClientApi.PART_SIZE < stopAfter) {
byte[] body = new byte[(int) Math.min(UploadClientApi.PART_SIZE, source.length() - confirmed)];
file.readFully(body);
remote = UploadClientApi.put(id, confirmed, body);
confirmed = remote.nextOffset();
}
return remote.json();
} catch (UploadClientApi.HttpStatusError error) {
if (!retry.waitBeforeRefresh(error)) {
throw error;
}
// Read the committed offset again before the next PUT.
}
}
}
}
public static void main(String[] args) {
System.exit(UploadClientApi.run(args, JavaUploadClient::resume));
}
}
Kotlin
package study
import com.google.gson.JsonObject
import java.io.RandomAccessFile
import java.nio.file.Path
import kotlin.system.exitProcess
private fun resume(uploadId: String, path: Path, stopAfter: Int): JsonObject {
val source = UploadClientApi.fileInfo(path)
val retry = UploadClientApi.BusyRetry()
var confirmed = 0L
var startOffset = -1L
RandomAccessFile(path.toFile(), "r").use { file ->
while (true) {
try {
var remote = UploadClientApi.checkpoint(uploadId)
UploadClientApi.checkSource(remote, source, confirmed)
confirmed = remote.nextOffset()
if (startOffset < 0) startOffset = confirmed
file.seek(confirmed)
while (confirmed < source.length() && (confirmed - startOffset) / UploadClientApi.PART_SIZE < stopAfter) {
val count = minOf(UploadClientApi.PART_SIZE.toLong(), source.length() - confirmed).toInt()
val body = ByteArray(size = count)
file.readFully(body)
remote = UploadClientApi.put(uploadId, confirmed, body)
confirmed = remote.nextOffset()
}
return remote.json()
} catch (error: UploadClientApi.HttpStatusError) {
if (!retry.waitBeforeRefresh(error)) throw error
// Read the committed offset again before the next PUT.
}
}
}
}
fun main(args: Array<String>) {
exitProcess(UploadClientApi.run(args, ::resume))
}
Maven
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>example.coakka</groupId>
<artifactId>resumable-upload-client</artifactId>
<version>1.0.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>17</maven.compiler.release>
</properties>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.13.2</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>2.3.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>2.3.10</version>
<executions>
<execution>
<id>compile-kotlin</id>
<phase>process-sources</phase>
<goals><goal>compile</goal></goals>
<configuration>
<jvmTarget>17</jvmTarget>
<args><arg>-Werror</arg><arg>-Xjdk-release=17</arg></args>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
<configuration>
<compilerArgs><arg>-Xlint:all</arg><arg>-Werror</arg></compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.8.1</version>
</plugin>
</plugins>
</build>
</project>
mvn -q -f client-jvm/pom.xml compile dependency:build-classpath -Dmdep.outputFile=target/classpath.txt
CLIENT_CP="client-jvm/target/classes:$(cat client-jvm/target/classpath.txt)"Gradle
plugins {
kotlin("jvm") version "2.3.10"
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.google.code.gson:gson:2.13.2")
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
freeCompilerArgs.add("-Xjdk-release=17")
allWarningsAsErrors.set(true)
}
}
tasks.withType<JavaCompile>().configureEach {
options.release.set(17)
options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror"))
}
tasks.register("writeClientClasspath") {
dependsOn(tasks.classes)
val classpath = sourceSets["main"].runtimeClasspath
val output = layout.buildDirectory.file("client-classpath.txt")
inputs.files(classpath)
outputs.file(output)
doLast {
output.get().asFile.writeText(classpath.asPath)
}
}
rootProject.name = "resumable-upload-client"
gradle -p client-jvm writeClientClasspath
CLIENT_CP=$(cat client-jvm/build/client-classpath.txt)After building with Maven or Gradle, choose one of these commands.
upload() { java -cp "$CLIENT_CP" study.JavaUploadClient "$@"; }upload() { java -cp "$CLIENT_CP" study.KotlinUploadClientKt "$@"; }Python
Save as client.py. Use Python 3.11+; the client needs no connector. source.seek(next_offset) positions the file for the next part.
client.py
"""Start, inspect, resume, finish, verify or remove a local upload."""
import argparse
import hashlib
import json
import os
import re
import sys
import time
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
PART_SIZE = 4 * 1024 * 1024
MAX_FILE = 32 * 1024 * 1024
BUSY_DELAYS = (0.1, 0.2, 0.4)
class HTTPStatusError(RuntimeError):
def __init__(self, status: int, detail: str):
super().__init__(f"HTTP {status}: {detail}")
self.status = status
def base_url() -> str:
value = os.environ.get("COAKKA_UPLOAD_LAB_PORT", "8080")
if not re.fullmatch(r"[0-9]{1,5}", value) or not 1 <= int(value) <= 65535:
raise RuntimeError("invalid local lab port")
return f"http://127.0.0.1:{int(value)}/uploads"
def call(method: str, path: str = "", data: bytes | None = None, headers=None) -> dict:
request = Request(base_url() + path, data=data, headers=headers or {}, method=method)
try:
with urlopen(request, timeout=15) as response:
return json.load(response)
except HTTPError as error:
with error:
detail = error.read().decode(errors="replace").strip()
raise HTTPStatusError(error.code, detail) from error
def source_info(path: Path) -> tuple[int, str]:
with path.open("rb") as source:
return path.stat().st_size, hashlib.file_digest(source, "sha256").hexdigest()
def start(path: Path) -> dict:
length, digest = source_info(path)
return call("POST", data=b"", headers={"Upload-Length": str(length), "Upload-SHA256": digest})
def resume(upload_id: str, path: Path, stop_after: int | None) -> dict:
endpoint = f"/{upload_id}"
length, digest = source_info(path)
delays = iter(BUSY_DELAYS)
start_offset = None
confirmed = 0
with path.open("rb") as source:
while True:
try:
state = call("GET", endpoint)
if (state["length"], state["sha256"]) != (length, digest):
raise RuntimeError("source file no longer matches this upload session")
offset = state["next_offset"]
if (
state["part_size"] != PART_SIZE
or not 0 < length <= MAX_FILE
or not confirmed <= offset <= length
or (offset != length and offset % PART_SIZE)
or (state["complete"] and offset != length)
):
raise RuntimeError("invalid server checkpoint")
if start_offset is None:
start_offset = offset
confirmed = offset
source.seek(offset)
while offset < length and (
stop_after is None or (offset - start_offset) // PART_SIZE < stop_after
):
count = min(PART_SIZE, length - offset)
data = source.read(count)
if len(data) != count:
raise RuntimeError("source file ended early")
state = call(
"PUT",
f"{endpoint}/parts/{offset}",
data=data,
headers={
"Content-Type": "application/octet-stream",
"Part-SHA256": hashlib.sha256(data).hexdigest(),
},
)
if state["next_offset"] != offset + count:
raise RuntimeError("unexpected offset; check status before retrying")
offset = confirmed = state["next_offset"]
return state
except HTTPStatusError as error:
delay = next(delays, None) if error.status == 503 else None
if delay is None:
raise
# After a 503, wait and read the server's checkpoint before sending again.
time.sleep(delay)
def verify(upload_id: str, source: Path, assembled: Path) -> dict:
state = call("GET", f"/{upload_id}")
expected = (state["length"], state["sha256"])
if not state["complete"] or state["next_offset"] != state["length"]:
raise RuntimeError("finish the upload before verifying")
if source_info(source) != expected or source_info(assembled) != expected:
raise RuntimeError("assembled file does not match the source and server SHA-256")
return {**state, "verified": True}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
actions = parser.add_subparsers(dest="action", required=True)
actions.add_parser("start").add_argument("file", type=Path)
for action in ("status", "resume", "finish", "verify", "delete"):
command = actions.add_parser(action)
command.add_argument("id")
if action == "resume":
command.add_argument("file", type=Path)
command.add_argument("--stop-after", type=int, metavar="PARTS")
if action == "verify":
command.add_argument("file", type=Path)
command.add_argument("assembled", type=Path)
args = parser.parse_args()
try:
if args.action == "start":
state = start(args.file)
else:
if not re.fullmatch(r"[0-9a-f]{32}", args.id):
raise RuntimeError("invalid upload ID")
endpoint = f"/{args.id}"
if args.action == "resume":
if args.stop_after is not None and args.stop_after < 1:
raise RuntimeError("--stop-after must be positive")
state = resume(args.id, args.file, args.stop_after)
elif args.action == "finish":
state = call("POST", endpoint + "/finish", data=b"")
elif args.action == "verify":
state = verify(args.id, args.file, args.assembled)
elif args.action == "delete":
state = call("DELETE", endpoint)
else:
state = call("GET", endpoint)
print(json.dumps(state, indent=2))
except (OSError, RuntimeError, URLError) as error:
print(error, file=sys.stderr)
if args.action == "resume":
print("Check status and run resume again with the same ID and file.", file=sys.stderr)
raise SystemExit(1) from error
if __name__ == "__main__":
main()
upload() { python3 client.py "$@"; }Node.js / Bun
Save as client.mjs. No npm package is needed: the client uses fetch, reads at the next_offset position, and hashes with node:crypto.
client.mjs
import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { open } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";
const PART_SIZE = 4 * 1024 * 1024;
const MAX_FILE = 32 * 1024 * 1024;
const BUSY_DELAYS_MS = [100, 200, 400];
class HTTPStatusError extends Error {
constructor(status, detail) {
super(`HTTP ${status}: ${detail}`);
this.status = status;
}
}
function baseURL() {
const value = process.env.COAKKA_UPLOAD_LAB_PORT ?? "8080";
const port = Number(value);
if (!/^[0-9]{1,5}$/.test(value) || port < 1 || port > 65535) {
throw new Error("invalid local lab port");
}
return `http://127.0.0.1:${port}/uploads`;
}
async function call(method, path = "", body, headers = {}) {
const response = await fetch(baseURL() + path, {
method, body, headers, redirect: "error", signal: AbortSignal.timeout(15000),
});
const chunks = [];
let length = 0;
if (response.body) {
const reader = response.body.getReader();
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
length += value.byteLength;
if (length > 8192) {
await reader.cancel();
throw new Error("server response exceeded the lab limit");
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
}
const text = Buffer.concat(chunks, length).toString("utf8");
if (!response.ok) throw new HTTPStatusError(response.status, text.trim());
return JSON.parse(text);
}
async function fileInfo(path) {
const hash = createHash("sha256");
let length = 0;
for await (const chunk of createReadStream(path)) {
length += chunk.length;
if (length > MAX_FILE) throw new Error("file exceeds 32 MiB");
hash.update(chunk);
}
if (length === 0) throw new Error("file must not be empty");
return { length, sha256: hash.digest("hex") };
}
async function checkpoint(id) {
const state = await call("GET", `/${id}`);
const { upload_id, length, next_offset, part_size, sha256, complete } = state;
if (upload_id !== id || part_size !== PART_SIZE || !Number.isSafeInteger(length)
|| length < 1 || length > MAX_FILE || !/^[0-9a-f]{64}$/.test(sha256)
|| !Number.isSafeInteger(next_offset) || next_offset < 0 || next_offset > length
|| typeof complete !== "boolean"
|| (next_offset !== length && (complete || next_offset % PART_SIZE !== 0))) {
throw new Error("invalid server checkpoint");
}
return state;
}
async function readPart(file, offset, count) {
const body = Buffer.alloc(count);
for (let read = 0; read < count;) {
const { bytesRead } = await file.read(body, read, count - read, offset + read);
if (!bytesRead) throw new Error("source file ended early");
read += bytesRead;
}
return body;
}
async function resume(id, path, stopAfter) {
const source = await fileInfo(path);
const file = await open(path, "r");
let retries = 0;
let startOffset;
let confirmed = 0;
try {
for (;;) {
try {
let state = await checkpoint(id);
if (state.length !== source.length || state.sha256 !== source.sha256) {
throw new Error("source file no longer matches this upload session");
}
if (state.next_offset < confirmed) throw new Error("server checkpoint moved backward");
startOffset ??= state.next_offset;
confirmed = state.next_offset;
while (confirmed < source.length && (confirmed - startOffset) / PART_SIZE < stopAfter) {
const offset = state.next_offset;
const count = Math.min(PART_SIZE, source.length - offset);
const body = await readPart(file, offset, count);
state = await call("PUT", `/${id}/parts/${offset}`, body, {
"Content-Type": "application/octet-stream",
"Part-SHA256": createHash("sha256").update(body).digest("hex"),
});
if (state.next_offset !== offset + count) {
throw new Error("unexpected offset; check status before retrying");
}
confirmed = state.next_offset;
}
return state;
} catch (error) {
if (!(error instanceof HTTPStatusError) || error.status !== 503
|| retries === BUSY_DELAYS_MS.length) throw error;
// After a 503, wait and read the server's checkpoint before sending again.
await sleep(BUSY_DELAYS_MS[retries++]);
}
}
} finally {
await file.close();
}
}
async function verify(id, source, assembled) {
const state = await checkpoint(id);
if (!state.complete) throw new Error("finish the upload before verifying");
for (const path of [source, assembled]) {
const actual = await fileInfo(path);
if (actual.length !== state.length || actual.sha256 !== state.sha256) {
throw new Error("file length or SHA-256 does not match");
}
}
return { ...state, verified: true };
}
async function run([action, id, file, option, value, ...rest]) {
const usage = "usage: start FILE | status ID | resume ID FILE [--stop-after N] | finish ID | verify ID FILE ASSEMBLED | delete ID";
if (action === "start" && id && file === undefined) {
const source = await fileInfo(id);
return call("POST", "", undefined, {
"Upload-Length": String(source.length), "Upload-SHA256": source.sha256,
});
}
if (!/^[0-9a-f]{32}$/.test(id ?? "")) throw new Error(usage);
if (action === "status" && file === undefined) return checkpoint(id);
if (action === "finish" && file === undefined) return call("POST", `/${id}/finish`);
if (action === "delete" && file === undefined) return call("DELETE", `/${id}`);
if (action === "verify" && file && option && value === undefined) return verify(id, file, option);
if (action === "resume" && file && !rest.length) {
if (option === undefined) return resume(id, file, Infinity);
if (option === "--stop-after" && /^[0-9]+$/.test(value ?? "")
&& Number.isSafeInteger(Number(value)) && Number(value) > 0) {
return resume(id, file, Number(value));
}
}
throw new Error(usage);
}
try {
console.log(JSON.stringify(await run(process.argv.slice(2)), null, 2));
} catch (error) {
console.error(error.message);
if (process.argv[2] === "resume") {
console.error("Check status and run resume again with the same ID and file.");
}
process.exitCode = 1;
}
upload() { node client.mjs "$@"; }upload() { bun client.mjs "$@"; }Upload one part and stop
Open another terminal in the same directory. Create a fixture and save the upload_id in upload-session.json. Create the session only once for this file.
dd if=/dev/zero of=demo.bin bs=1048576 count=12
upload start demo.bin > upload-session.json
cat upload-session.jsonID=$(python3 -c 'import json; print(json.load(open("upload-session.json"))["upload_id"])')
upload resume "$ID" demo.bin --stop-after 1Expect next_offset: 4194304 and complete: false. The server has committed 4 MiB and has not created the assembled file.
Resume and assemble
After a client exit or network drop, use the same ID and original file. resume reads next_offset from GET /uploads/{id} and starts there. Bytes sent by the client do not establish what the server saved.
- Disconnect mid-part
- The incomplete part was never committed. Resend from the offset returned by the server.
- Reply lost after commit
- The offset has advanced; skip that part. Replaying the same part with identical bytes leaves the offset unchanged and does not duplicate data.
If resume receives HTTP 503, it allows up to 3 retries for the whole command. It waits 100, 200 and 400 ms in order, then reads next_offset before sending again. If the server already committed the part, the client continues from the new offset. If retries run out or the connection drops, run resume again with the same ID and file.
ID=$(python3 -c 'import json; print(json.load(open("upload-session.json"))["upload_id"])')
upload status "$ID"
upload resume "$ID" demo.bin
upload finish "$ID"
upload verify "$ID" demo.bin "upload-lab-data/$ID/complete.bin"
cmp demo.bin "upload-lab-data/$ID/complete.bin"Expect complete: true, length: 12582912, and the same sha256 as at session creation. cmp is silent when the two files match.
verify returns verified: true only when the source and assembled file both match the finished session’s length and SHA-256. The lab reads the assembled file locally.
Compare SHA-256 independently
sha256sum demo.bin "upload-lab-data/$ID/complete.bin"shasum -a 256 demo.bin "upload-lab-data/$ID/complete.bin"Test a real disconnect
To test the server, save check_upload.py next to client.py. It creates its own session, closes a connection halfway through a part, then tests a committed part whose reply was never read. It resumes, verifies the assembled file, and removes its test data.
check_upload.py
"""Exercise a real disconnect, resume, and verify the assembled file."""
import hashlib
import http.client
import json
import socket
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from client import start
HOST = "127.0.0.1"
PORT = 8080
PART_SIZE = 4 * 1024 * 1024
ROOT = Path("upload-lab-data")
def exchange(method, path, expected, body=None, headers=None):
connection = http.client.HTTPConnection(HOST, PORT, timeout=15)
try:
connection.request(method, path, body=body, headers=headers or {})
response = connection.getresponse()
payload = response.read()
assert response.status == expected, (method, path, response.status, payload)
media = response.getheader("Content-Type", "").split(";", 1)[0].strip().lower()
assert media == "application/json", (method, path, media)
return json.loads(payload)
finally:
connection.close()
def digest(data):
return hashlib.sha256(data).hexdigest()
def put(endpoint, offset, data, expected, sha256=None):
return exchange(
"PUT", f"{endpoint}/parts/{offset}", expected, data,
{"Content-Type": "application/octet-stream", "Part-SHA256": sha256 or digest(data)},
)
def check_request_ceiling(endpoint, offset):
connection = http.client.HTTPConnection(HOST, PORT, timeout=8)
try:
connection.putrequest("PUT", f"{endpoint}/parts/{offset}")
connection.putheader("Content-Type", "application/octet-stream")
connection.putheader("Content-Length", str(PART_SIZE + 1))
connection.endheaders()
response = connection.getresponse()
assert response.status == 413, response.status
response.read()
finally:
connection.close()
def send_without_reading(connection, endpoint, offset, data, size):
header = (
f"PUT {endpoint}/parts/{offset} HTTP/1.1\r\n"
f"Host: {HOST}:{PORT}\r\n"
"Content-Type: application/octet-stream\r\n"
f"Content-Length: {len(data)}\r\n"
f"Part-SHA256: {digest(data)}\r\n\r\n"
)
connection.sendall(header.encode("ascii"))
connection.sendall(memoryview(data)[:size])
def check_resume(path):
created = start(path)
upload_id = created["upload_id"]
endpoint = f"/uploads/{upload_id}"
directory = ROOT / upload_id
def status():
return exchange("GET", endpoint, 200)
try:
with path.open("rb") as source:
first = source.read(PART_SIZE)
second = source.read(PART_SIZE)
assert created["next_offset"] == 0
assert put(endpoint, PART_SIZE, second, 409)["next_offset"] == 0
assert put(endpoint, 0, first, 422, "0" * 64)["next_offset"] == 0
assert put(endpoint, 0, first, 200)["next_offset"] == PART_SIZE
check_request_ceiling(endpoint, PART_SIZE)
assert status()["next_offset"] == PART_SIZE
print("A request above 4 MiB returned 413 without advancing the offset.")
assert exchange("POST", endpoint + "/finish", 409)["next_offset"] == PART_SIZE
with socket.create_connection((HOST, PORT), timeout=10) as connection:
send_without_reading(connection, endpoint, PART_SIZE, second, PART_SIZE // 2)
assert status()["next_offset"] == PART_SIZE
assert status()["next_offset"] == PART_SIZE
assert not (directory / f"part-{PART_SIZE:08d}.bin").exists()
assert not list(directory.glob("*.tmp"))
print(f"Disconnected halfway through a part; next_offset stayed {PART_SIZE}.")
with socket.create_connection((HOST, PORT), timeout=10) as connection:
send_without_reading(connection, endpoint, PART_SIZE, second, len(second))
deadline = time.monotonic() + 8
while status()["next_offset"] != 2 * PART_SIZE:
if time.monotonic() >= deadline:
raise RuntimeError("server did not commit the complete part")
time.sleep(0.02)
# Simulate losing the reply: close without reading a response.
assert put(endpoint, PART_SIZE, second, 200)["next_offset"] == 2 * PART_SIZE
changed = b"X" + second[1:]
assert put(endpoint, PART_SIZE, changed, 409)["next_offset"] == 2 * PART_SIZE
print(f"Lost reply after commit; a duplicate kept next_offset at {2 * PART_SIZE}.")
client = Path(__file__).with_name("client.py")
result = json.loads(subprocess.check_output([
sys.executable, client, "resume", upload_id, str(path),
], timeout=35))
assert result["next_offset"] == created["length"] > 8 * 1024 * 1024
finished = exchange("POST", endpoint + "/finish", 201)
assert exchange("POST", endpoint + "/finish", 200) == finished
final = directory / "complete.bin"
assert finished["complete"] and final.stat().st_size == created["length"]
with final.open("rb") as source:
assert hashlib.file_digest(source, "sha256").hexdigest() == created["sha256"]
assert not list(directory.glob("part-*.bin"))
assert not list(directory.glob("*.tmp"))
print(f"Resumed and verified {finished['length']} bytes; SHA-256 {finished['sha256']}.")
finally:
exchange("DELETE", endpoint, 200)
exchange("GET", endpoint, 404)
def check_final_checksum():
created = exchange("POST", "/uploads", 201, headers={
"Upload-Length": "3", "Upload-SHA256": "0" * 64,
})
endpoint = f"/uploads/{created['upload_id']}"
directory = ROOT / created["upload_id"]
try:
assert put(endpoint, 0, b"abc", 200)["next_offset"] == 3
exchange("POST", endpoint + "/finish", 422)
assert not (directory / "complete.bin").exists()
assert not list(directory.glob("*.tmp"))
print("A wrong final checksum left the file unpublished.")
finally:
exchange("DELETE", endpoint, 200)
def main():
with tempfile.TemporaryDirectory(prefix="resume-check-", dir=".") as directory:
source = Path(directory) / "demo.bin"
with source.open("wb") as output:
for value in (17, 44, 193):
output.write(bytes([value]) * PART_SIZE)
output.write(bytes(range(123)))
check_resume(source)
check_final_checksum()
if __name__ == "__main__":
main()
python3 check_upload.pyExpect the offset to remain at 4194304 on a mid-part drop and at 8388608 after replaying a committed part. The final check prints the SHA-256 of the assembled file, which is over 12 MiB.
Interrupt the client while it sends · check_client.py
Save the checker next to the client. This example runs the Go client; replace ./client-go with the command that launches your client. The checker creates a separate session, drops both connections and changes one byte in its own assembled file to test that verify refuses it.
"""Drop a client connection twice, then check resume and SHA-256.
Run a lab server on port 8080 first. Usage: python3 check_client.py -- CLIENT...
"""
import hashlib
import http.client
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import socket
import subprocess
import sys
import tempfile
import threading
PART_SIZE = 4 * 1024 * 1024
class Bridge(ThreadingHTTPServer):
def __init__(self, target_port):
super().__init__(("127.0.0.1", 0), Request)
self.target_port = target_port
self.lock = threading.Lock()
self.mode = None
self.interrupted = []
self.put_offsets = []
def arm(self, mode):
with self.lock:
self.mode = mode
def next_mode(self, method, path):
with self.lock:
if method != "PUT":
return None
self.put_offsets.append(int(path.rsplit("/", 1)[1]))
mode, self.mode = self.mode, None
return mode
class Request(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def setup(self):
super().setup()
self.connection.settimeout(10)
def log_message(self, *_args):
pass
def disconnect(self):
self.close_connection = True
self.connection.shutdown(socket.SHUT_RDWR)
def forward(self):
length = int(self.headers.get("Content-Length", "0"))
if not 0 <= length <= PART_SIZE:
self.send_error(413)
return
mode = self.server.next_mode(self.command, self.path)
connection = http.client.HTTPConnection("127.0.0.1", self.server.target_port, timeout=10)
try:
connection.putrequest(self.command, self.path, skip_host=True, skip_accept_encoding=True)
for name, value in self.headers.items():
if name.lower() not in {"connection", "expect", "host", "transfer-encoding"}:
connection.putheader(name, value)
connection.putheader("Host", f"127.0.0.1:{self.server.target_port}")
connection.endheaders()
remaining = PART_SIZE // 4 if mode == "mid-part" else length
while remaining:
chunk = self.rfile.read(min(remaining, 64 * 1024))
if not chunk:
raise RuntimeError("client ended before the planned interruption")
connection.send(chunk)
remaining -= len(chunk)
if mode == "mid-part":
self.server.interrupted.append(mode)
self.disconnect()
return
response = connection.getresponse()
data = response.read(8193)
if len(data) > 8192:
raise RuntimeError("unexpectedly large API response")
if mode == "lost-reply":
if response.status != 200:
raise RuntimeError("server did not commit the part")
self.server.interrupted.append(mode)
self.disconnect()
return
self.send_response(response.status)
self.send_header("Content-Type", response.getheader("Content-Type", "application/json"))
self.send_header("Content-Length", str(len(data)))
self.send_header("Connection", "close")
self.end_headers()
self.wfile.write(data)
self.close_connection = True
finally:
connection.close()
do_GET = do_POST = do_PUT = do_DELETE = forward
def verify_client(bridge, command, source):
env = {**os.environ, "COAKKA_UPLOAD_LAB_PORT": str(bridge.server_port)}
def cli(*args, fails=False):
result = subprocess.run([*command, *args], env=env, capture_output=True, text=True, timeout=28)
if fails:
assert result.returncode != 0, (args, result.stdout)
return None
assert result.returncode == 0, (args, result.stderr)
return json.loads(result.stdout)
created = cli("start", str(source))
upload_id = created["upload_id"]
size = created["length"]
assert size == 3 * PART_SIZE + 123
try:
with source.open("rb") as file:
expected = hashlib.file_digest(file, "sha256").hexdigest()
assert created["sha256"] == expected
assert cli("resume", upload_id, str(source), "--stop-after", "1")["next_offset"] == PART_SIZE
bridge.arm("mid-part")
cli("resume", upload_id, str(source), fails=True)
assert bridge.interrupted == ["mid-part"]
assert cli("status", upload_id)["next_offset"] == PART_SIZE
print(f"Mid-part disconnect: next_offset stayed {PART_SIZE}.")
bridge.arm("lost-reply")
cli("resume", upload_id, str(source), fails=True)
assert bridge.interrupted == ["mid-part", "lost-reply"]
assert cli("status", upload_id)["next_offset"] == 2 * PART_SIZE
print(f"Lost reply after commit: next_offset advanced to {2 * PART_SIZE}.")
before = len(bridge.put_offsets)
assert cli("resume", upload_id, str(source))["next_offset"] == size
assert bridge.put_offsets[before:] == [2 * PART_SIZE, 3 * PART_SIZE]
state = cli("finish", upload_id)
assert state["complete"] and state["sha256"] == expected
final = Path("upload-lab-data") / upload_id / "complete.bin"
assert cli("verify", upload_id, str(source), str(final))["verified"] is True
# Corrupt this test session's own file. Its length and server metadata
# still match, so only an independent SHA-256 can catch the change.
with final.open("r+b") as file:
byte = file.read(1)[0]
file.seek(0)
file.write(bytes([byte ^ 1]))
cli("verify", upload_id, str(source), str(final), fails=True)
print(f"Resumed without resending committed parts; {size} bytes, SHA-256 {expected}.")
print("Independent verification rejected an assembled file with one byte changed.")
finally:
cli("delete", upload_id)
def main():
command = sys.argv[1:]
if command and command[0] == "--":
command = command[1:]
if not command:
raise SystemExit(__doc__)
port = int(os.environ.get("COAKKA_UPLOAD_LAB_PORT", "8080"))
with tempfile.TemporaryDirectory(prefix="resume-client-check-", dir=".") as directory:
source = Path(directory) / "demo.bin"
with source.open("wb") as file:
for value in (17, 44, 193):
file.write(bytes([value]) * PART_SIZE)
file.write(bytes(range(123)))
with Bridge(port) as bridge:
worker = threading.Thread(target=bridge.serve_forever)
worker.start()
try:
verify_client(bridge, command, source)
finally:
bridge.shutdown()
worker.join()
if __name__ == "__main__":
main()
python3 check_client.py -- ./client-goFor Node.js use python3 check_client.py -- node client.mjs. For Java or Kotlin pass java -cp "$CLIENT_CP" followed by the class name.
Client and server pairs tested on Raspberry Pi
The Mac ARM64 replay used SDK 2.3.0 and connector 2.3.1. All 8 clients resumed against the Python server and checked SHA-256 after both simulated disconnects.
Read each row as the client and each column as the server. Both directions were tested separately. Node.js and Bun have separate entries because they are different JavaScript runtimes. A dash marks the same sample variant at both ends, outside this cross-test.
All 56 pairs passed.
| Client ↓ / Server → | C | C++ | Go | Java | Kotlin | Python | Node.js | Bun |
|---|---|---|---|---|---|---|---|---|
| C | — | Pass | Pass | Pass | Pass | Pass | Pass | Pass |
| C++ | Pass | — | Pass | Pass | Pass | Pass | Pass | Pass |
| Go | Pass | Pass | — | Pass | Pass | Pass | Pass | Pass |
| Java | Pass | Pass | Pass | — | Pass | Pass | Pass | Pass |
| Kotlin | Pass | Pass | Pass | Pass | — | Pass | Pass | Pass |
| Python | Pass | Pass | Pass | Pass | Pass | — | Pass | Pass |
| Node.js | Pass | Pass | Pass | Pass | Pass | Pass | — | Pass |
| Bun | Pass | Pass | Pass | Pass | Pass | Pass | Pass | — |
The pairs ran one at a time over HTTP/1.1 on a single Raspberry Pi 5. The C and C++ servers used CoAkka HTTP Runtime SDK 2.2.0. The other servers used connector 2.2.1.
- Drop the connection mid-part:
next_offsetstays at4194304(4 MiB) because the server did not commit the incomplete part. - Lose the reply after the server commits:
next_offsetis8388608(8 MiB). The client starts there and sends only the 2 remaining parts. - After assembly, the SHA-256 of the 12 MiB + 123 byte file matches the source. Changing 1 byte in the assembled file makes
verifyreport a failure.
Two clients in different languages upload to Python at once
On Raspberry Pi 5, the example server used the default Python connector 2.2.1 settings. The four pairs were C + Go, C++ + Java, Kotlin + Node.js, and Python + Bun. Each pair ran twice with the roles swapped, so each client took a turn being interrupted and continuing the upload.
In all 8 runs, one session lost its connection partway through its second part while the other session was sending its file. The server still returned next_offset: 4194304 (4 MiB) for the interrupted session. The client resumed from there, and all 16 assembled files matched their respective source SHA-256.
Python server returns 503 during 2 concurrent uploads
Python connector 2.2.1 defaults to 8 MiB for requests waiting or running in Python. The limit includes the body and request metadata. Two full 4 MiB parts can exceed it when they overlap, so the connector can reject one request before the server writes that part.
On Pi, the C and C++ clients completed all 16 sessions with the default Python settings, over 8 rounds of 2 concurrent sessions. The server returned 8 responses with status 503. Each time, the client waited and read next_offset again. Each assembled file matched the source SHA-256. To experiment with a larger Python memory budget, add .dispatch_bytes(16 * 1024 * 1024) to Builder() before .start().
Look up the API and errors
| Request | Fields to know | When to use it |
|---|---|---|
POST /uploads | Upload-Length, Upload-SHA256 | Create a session; return its ID and next_offset = 0. |
GET /uploads/{id} | next_offset, complete | Read committed progress; this does not download the file. |
PUT /uploads/{id}/parts/{offset} | Part-SHA256; application/octet-stream | Send one part, up to 4 MiB; the last part may be smaller. |
POST /uploads/{id}/finish | length, sha256 | Assemble in order; publish only if length and SHA-256 match. |
DELETE /uploads/{id} | — | Delete the lab session and its files. |
409- Wrong offset, conflicting replay, or missing parts. Read
next_offsetand check the source file. 413- Over the lab limit of 4 MiB per request or 32 MiB per session.
422- A part or assembled file failed SHA-256 validation. A failed assembly check does not publish the output.
503- The server is out of room for another session or request. For Python, see limits for concurrent uploads.
The local example keeps up to 4 sessions. For a deployment, associate sessions with authenticated users and define expiry, disk quotas and retention.