API reference
- Every public function and type in the C and C++ headers, with the rules it follows.
Karu has a C interface in karu.h and a header-only C++23 layer in karu.hpp. Both reach the same engine. This page describes the public functions and types in the order a program uses them, and states the rules each one follows.
A complete program
A program builds a configuration, freezes it into a client, resolves an object, submits reads and drains their completions. The example reads two ranges of one object and reports any failure.
#include <karu/karu.h>
#include <stdio.h>
int main(void) {
karu_config* config = NULL;
karu_client* client = NULL;
karu_locator* object = NULL;
karu_batch* batch = NULL;
static unsigned char head[4096], tile[65536];
int failed = 1;
if (karu_config_create(&config) != KARU_OK ||
karu_client_create(config, &client) != KARU_OK ||
karu_resolve("s3://bucket/scene.tif", &object) != KARU_OK) {
fprintf(stderr, "setup failed: %s\n", karu_last_error());
goto cleanup;
}
karu_req reads[] = {
{.locator = object, .offset = 0, .length = sizeof head, .buffer = head, .tag = head},
{.locator = object, .offset = 1048576, .length = sizeof tile, .buffer = tile, .tag = tile},
};
if (karu_client_submit(client, reads, 2, &batch) != KARU_OK) {
fprintf(stderr, "submit failed: %s\n", karu_last_error());
goto cleanup;
}
failed = 0;
karu_done done;
karu_status step;
while ((step = karu_batch_next(batch, &done, -1)) == KARU_OK) {
if (done.status != KARU_OK) {
fprintf(stderr, "%s: %s\n", karu_status_string(done.status), karu_last_error());
failed = 1;
}
}
if (step != KARU_END) {
fprintf(stderr, "next failed: %s\n", karu_last_error());
failed = 1;
}
cleanup:
karu_batch_free(batch);
karu_locator_free(object);
karu_client_free(client);
karu_config_free(config);
return failed;
}
The completions arrive in the order the reads finish, and the tag identifies each one. The loop ends with KARU_END once every completion has been returned. Destination buffers must stay valid until karu_batch_free returns.
Handles and ownership
Every Karu object is an opaque handle with one function that creates it and one that releases it. Each release function accepts NULL.
| Handle | Created by | Released by | Sharing |
|---|---|---|---|
karu_config* | karu_config_create, karu_config_create_empty | karu_config_free | mutable, needs external locking |
karu_client* | karu_client_create | karu_client_free | shared across threads |
karu_locator* | karu_resolve | karu_locator_free | immutable |
karu_batch* | karu_client_submit, karu_client_submit_with | karu_batch_free | drained by any number of threads |
| a buffer Karu allocated | a request with buffer = NULL | karu_free | owned by the caller once returned |
A client copies its configuration, and a submitted batch copies its requests, locators and ETags and keeps the engine alive. The configuration, the client and the locators can therefore be freed while a batch is still draining. Only the destination buffers have to outlive the batch. karu_batch_free releases any buffer Karu allocated that was never drained, and a drained one belongs to the caller whatever its status.
Creating functions write NULL to *out only after their pointer arguments pass the null check, so handles should be initialized to NULL before the call.
Configuration and clients
A configuration is a mutable builder. A client freezes a validated copy of it and owns the engine that serves every read.
| Function | Behaviour |
|---|---|
karu_config_create | Creates a builder that starts from the environment and enables default credential discovery. |
karu_config_create_empty | Creates a builder that starts from nothing, for hermetic clients and tests. |
karu_config_set_option | Sets an option for the whole client, or removes it when the value is NULL. An unknown name fails with KARU_ERR_CONFIG. |
karu_config_set_path_option | Sets or removes an option for one path prefix. KARU_* options are refused with KARU_ERR_CONFIG. |
karu_config_set_credentials_provider | Installs one credential callback per provider kind. Passing NULL for the provider, the user data and the release function, a karu_credentials_provider_free, removes it. User data or a release function without a provider fails with KARU_ERR_CONFIG. |
karu_client_create | Checks the syntax and range of every option and freezes a copy, and the builder may be freed afterwards. A malformed value fails here with KARU_ERR_CONFIG. Endpoints, headers and other values that depend on the request are checked when a request is built, and fail that read with KARU_ERR_CONFIG. |
karu_client_matches_config | Reports whether a builder would produce the client's frozen configuration, without any I/O. Callbacks compare by registration, so installing the same function again does not match. |
karu_client_concurrency, karu_client_coalesce_gap, karu_client_max_attempts | Return frozen values, or 0 for a NULL client. |
A client should be created once and shared. Its threads, connection pools, credential cache and learned S3 regions start on the first call that reads, whether a submit, a fetch, a probe or a download, and serve every later read. The configuration reference lists the options, what each builder reads and which value a request uses when an option is set at several levels.
Locators
A locator names one object and, optionally, a window inside it. karu_resolve only parses the string. It touches neither the network nor credentials.
| Backend | URI | Path form |
|---|---|---|
| Local file | /data/a.bin, data/a.bin, file:///data/a.bin | |
| HTTP | https://host/x | /vsicurl/https://host/x |
| S3 and compatible stores | s3://bucket/key | /vsis3/bucket/key |
| Google Cloud Storage | gs://bucket/key | /vsigs/bucket/key |
| Azure Blob | az://container/blob | /vsiaz/container/blob |
| Azure Data Lake Gen2 | abfs://container/path | /vsiadls/container/path |
| Hugging Face | hf://owner/name/path, or with datasets/ or spaces/ after hf://, and an optional @revision after the name that defaults to main | /vsihf/... |
| Source Cooperative | source://account/product/key | /vsisource/account/product/key |
Bucket, container and account names cannot contain spaces, control characters or any of / ? # @ : % \ [ ], and Hugging Face owner and repository names follow the Hub's rules; otherwise karu_resolve fails with KARU_ERR_URI. Other provider naming rules are left to the provider. A / in a revision is written %2F, as in @refs%2Fpr%2F1. A file:// URI takes an empty or localhost authority, and its path is percent-decoded.
A window limits a locator to part of an object, written as /vsisubfile/OFFSET_LENGTH,<path> or as #bytes=FIRST-LAST after a URI. Without a length or a last byte, the window runs to the end of the object. Read offsets are then relative to the window. Archives such as /vsizip/ are refused with KARU_ERR_UNSUPPORTED.
| Function | Returns |
|---|---|
karu_resolve | A new locator, or KARU_ERR_URI or KARU_ERR_UNSUPPORTED with a message. |
karu_locator_uri | The canonical identity, for example /vsis3/bucket/key for s3://bucket/key. |
karu_locator_is_remote | Nonzero for everything except local files. |
karu_locator_window_offset, karu_locator_window_length | The window, with a length of KARU_TO_END when it is unbounded. |
Configuration rules, credential scopes and merging are all keyed on the canonical identity, so s3://b/k and /vsis3/b/k are the same object. The identity of an HTTP locator is the URL itself, without /vsicurl/, and a local path keeps its spelling, so data/a.bin and /abs/data/a.bin are different identities. A window is not part of the identity, and reads through different windows of one object can share a request.
Requests, batches and completions
A batch is an array of karu_req. Karu returns one karu_done per request, in the order the reads finish.
typedef struct {
const karu_locator* locator;
uint64_t offset; // relative to the locator's window
uint64_t length; // nonzero and finite
void* buffer; // length bytes, or NULL to let Karu allocate
void* tag; // returned unchanged
const char* if_match; // optional ETag, copied at submit
} karu_req;
typedef struct {
void* tag;
karu_status status;
uint64_t got; // valid prefix of buffer
void* buffer; // the request's buffer, or the one Karu allocated
} karu_done;
| Function | Behaviour |
|---|---|
karu_client_submit | Copies the requests and returns a batch at once. A batch of zero requests reports KARU_END immediately. |
karu_client_submit_with | The same, with planner settings for this batch only. |
karu_batch_next | Returns KARU_OK with one completion, KARU_END when every completion has been returned, or KARU_TIMEOUT when nothing is ready. A timeout of -1 waits, 0 polls and a positive value waits that many milliseconds. |
karu_batch_free | Cancels pending work, including requests already on the network, and waits until no worker still touches the buffers. |
karu_batch_get_stats | Fills a karu_batch_stats with transfer, byte, retry, connection and refresh counters. The fields are transfers, transfers_finished, requested_bytes, received_bytes, retries, throttled, new_connections, resumed and credential_refreshes. They can be read while the batch runs, though not while karu_batch_free runs, and they are not an atomic snapshot. |
karu_client_fetch, karu_client_fetch_with | Submit, drain and free in one blocking call. Every request needs a buffer. The call returns the status of the first failure, and after a failure every destination is unspecified. |
A request without a locator, with a zero or unbounded length, or with a line break in if_match fails the whole submit with KARU_ERR_INVALID. Problems that depend on the object do not. A read that leaves its window, or an ETag on a local file, comes back as a failed completion while the rest of the batch continues. Overlapping and duplicate requests are valid, and each destination receives its own copy.
got equals the requested length on success. It is normally 0 on failure, except that KARU_ERR_RANGE reports the valid prefix when the object ends inside the request. Bytes past got are unspecified. Several threads may call karu_batch_next on one batch, and each completion goes to exactly one of them. karu_batch_free must not run while another thread is inside karu_batch_next on the same batch.
Planner settings for one batch
karu_submit_options options = KARU_SUBMIT_OPTIONS_INIT; // every field KARU_INHERIT
options.coalesce_gap = 0; // no merging in this batch
karu_status status = karu_client_fetch_with(client, reads, count, &options);
| Field | Meaning |
|---|---|
struct_size | sizeof(karu_submit_options), which must at least cover coalesce_gap |
coalesce_gap | largest hole merged, in bytes, where 0 disables merging |
coalesce_limit | largest merged request, at least 1 |
coalesce_parts | most reads in one request, at least 1 |
coalesce_amplification | most bytes fetched per requested byte, at least 1 |
A field left at KARU_INHERIT keeps the client's value. Concurrency, retries and timeouts belong to the client and cannot change per batch. How Karu reads explains how these limits shape a plan.
Sizes, versions and downloads
Four blocking calls work on a whole object rather than on a batch of ranges.
| Function | Behaviour |
|---|---|
karu_client_size | The size visible through the locator. A bounded window answers without I/O, a local file asks the file system, and a remote object costs one GET of byte 0. The result is never cached. |
karu_client_stat | The size and the strong ETag in a karu_object_info. Unlike size, it probes a bounded remote window too, to obtain the ETag. |
karu_client_read_ends | The first and last bytes of an object together, with the size and ETag. Each buffer receives the smaller of its length and the size, so on a short object the two overlap. Sizes or ETags that disagree fail with KARU_ERR_PRECONDITION. |
karu_client_download | Copies the object into a local file. A first read of up to 1 MiB learns the size and the ETag, and the rest follows in parallel ranges, 8 MiB each and eight at once by default. When the source returns a strong ETag, every range is pinned to it. The destination appears only after every range succeeds. |
The ETag in karu_object_info keeps its quotes and can be passed straight to if_match. It is empty for local files and for missing, weak, invalid or overlong tags. Structures with a struct_size field are initialized with their macros, KARU_OBJECT_INFO_INIT, KARU_DOWNLOAD_OPTIONS_INIT, KARU_DOWNLOAD_RESULT_INIT, KARU_SUBMIT_OPTIONS_INIT and KARU_BATCH_STATS_INIT, so a program compiled against an older header keeps working.
karu_download_options options = KARU_DOWNLOAD_OPTIONS_INIT; // 8 MiB chunks, 8 in parallel
options.overwrite = 1; // replace an existing file
karu_download_result result = KARU_DOWNLOAD_RESULT_INIT;
karu_status status = karu_client_download(client, object, "scene.tif", &options, &result);
karu_download_options sets chunk_size, parallelism, overwrite and a progress callback. overwrite must be 0 or 1, and without it an existing destination fails with KARU_ERR_IO. karu_download_result reports the size, the bytes downloaded and received, retries, throttled responses, new connections, resumes, credential refreshes and the ETag used. Either pointer may be NULL. Servers used for downloads of more than one chunk must honour Range beyond KARU_RANGE_FALLBACK_LIMIT.
The download progress callback, a karu_download_progress, runs on the calling thread after bytes reach the temporary file, and returning zero cancels the download with KARU_ERR_CANCELLED. On failure or cancellation the temporary file is removed.
Credential callbacks
A callback replaces Karu's own credential discovery for one provider kind, unless the matching *_NO_SIGN_REQUEST option is set. It receives the canonical path and fills a karu_credentials.
typedef karu_status (*karu_credentials_provider)(void* user_data, karu_credentials_kind kind,
const char* canonical_path,
karu_credentials* out);
| Kind | Fields Karu uses |
|---|---|
KARU_CREDENTIALS_AWS | access_key_id, secret_access_key and optionally session_token |
KARU_CREDENTIALS_SOURCE | the same fields as AWS |
KARU_CREDENTIALS_GCS | bearer_token, or access_key_id and secret_access_key as HMAC keys |
KARU_CREDENTIALS_AZURE | sas_token, bearer_token, or account_name with a base64 secret_access_key, where an empty field falls back to the AZURE_STORAGE_* options |
For submitted reads and downloads the callback runs on Karu's credential workers, possibly for several paths at once. For size and stat it runs on the calling thread, and read_ends may call it from a helper thread. It must be thread safe, must not call back into the same client, and must bound its own I/O, because Karu cannot interrupt it. The returned strings must outlive the callback, because Karu copies them right after it returns. The release function runs once no builder, client or batch still holds the callback.
The callback returns KARU_OK or a failure. A negative status passes through, and any other value becomes KARU_ERR_CREDENTIALS. expires_at is Unix time in seconds, or 0 for credentials that do not expire. Credentials that have already expired are rejected. cache_prefix is optional, and when it is set it must contain the requested path, or the lookup fails with KARU_ERR_CREDENTIALS. How Karu reuses and refreshes the answer is described in the configuration reference.
Statuses and error text
Every fallible call returns a karu_status. Success is 0, and failures are negative except KARU_TIMEOUT.
| Status | Value | Typical cause |
|---|---|---|
KARU_OK | 0 | success |
KARU_END | 1 | every completion of a batch has been returned |
KARU_TIMEOUT | 2 | nothing ready in karu_batch_next, or a read that ran out of KARU_REQUEST_TIMEOUT |
KARU_ERR_URI | -1 | a malformed path or URI |
KARU_ERR_UNSUPPORTED | -2 | an archive handler such as /vsizip/, or an ETag on a local file |
KARU_ERR_INVALID | -3 | a null argument, an empty or unbounded request, bad submit or download options, a batch used after fork |
KARU_ERR_NOMEM | -4 | an allocation failed |
KARU_ERR_IO | -5 | a local file could not be opened or read, or a download could not write its output |
KARU_ERR_NETWORK | -6 | a DNS, connection or TLS failure, or a truncated body |
KARU_ERR_HTTP | -7 | another HTTP status, a bad Content-Range, an ignored range above the fallback limit, a refused redirect |
KARU_ERR_RANGE | -8 | a read past the end of the object, or outside its window |
KARU_ERR_AUTH | -9 | HTTP 401 or 403 |
KARU_ERR_CANCELLED | -10 | a download whose progress callback returned zero |
KARU_ERR_CONFIG | -11 | an unknown option, an invalid value or a bad endpoint |
KARU_ERR_CREDENTIALS | -12 | credentials missing or a lookup failed |
KARU_ERR_NOT_FOUND | -13 | HTTP 404 |
KARU_ERR_PRECONDITION | -14 | the object no longer matches if_match |
karu_status_string gives the short name of a status. karu_last_error gives the message of the last failure on the calling thread, truncated to 511 bytes. In messages about HTTP requests, query strings and user information in the URL are replaced by <redacted>. Every function that returns a status clears the message on entry, so it has to be copied before the next call on the same thread. After karu_batch_next returns a failed completion, the message belongs to that completion. karu_clear_error clears it explicitly.
Threads and fork
One client runs one engine, made of the I/O threads, four credential workers and four file workers. They start on first use and stop when the client and all its batches are freed.
Every call on a client may come from many threads at once. size and stat run their whole probe on the calling thread, credential lookup included, and read_ends reads the head from a helper thread. Submitted reads and downloads use the workers. System DNS lookups run on a resolver thread that cannot be cancelled and may briefly outlive the engine.
A client used in a child process after fork notices the new process, leaves the inherited engine alone and builds a fresh one, so a client may be created before worker processes are forked. Batches do not cross a fork. In the child, karu_batch_next and karu_batch_get_stats return KARU_ERR_INVALID, and karu_batch_free leaves the inherited batch allocated until the process exits.
Language bindings should release their interpreter lock around every call that can wait, which means karu_batch_next with a nonzero timeout, the fetch, size, stat, read_ends and download calls, and karu_batch_free. Memory owned by the host language can serve as buffer as long as it stays pinned until karu_batch_free returns.
C++
karu.hpp wraps the C interface in move-only classes that release their handles automatically. Every fallible member returns karu::Result<T>, a std::expected whose error carries the status and a copy of the message.
#include <karu/karu.hpp>
#include <iostream>
int main() {
auto config = karu::Config::from_environment();
if (!config) return 1;
auto client = karu::Client::create(*config);
auto object = karu::Object::parse("s3://bucket/scene.tif");
if (!client || !object) return 1;
auto head = client->read(*object, 0, 4096); // Result<std::vector<std::byte>>
if (!head) {
std::cerr << karu_status_string(head.error().status) << ": " << head.error().message << '\n';
return 1;
}
}
| Class | Wraps | Main members |
|---|---|---|
karu::Config | karu_config | from_environment, empty, set, unset, set_path, unset_path, set_credentials_provider, clear_credentials_provider |
karu::Object | karu_locator | parse, uri, is_remote, window_offset, window_length |
karu::Client | karu_client | create, matches, size, stat, read_ends, download, read, read_into, fetch, submit, concurrency, coalesce_gap, max_attempts |
karu::Batch | karu_batch | next, stats |
karu::Read | karu_req | object, offset, destination, tag, if_match |
karu::SubmitOptions | karu_submit_options | optional planner overrides, unset ones inherit |
karu::BatchEvent | karu_done | state, a BatchState, and tag, status, bytes_read, message |
karu::Error | karu_status and karu_last_error | status, message |
karu::ObjectInfo, DownloadOptions, DownloadResult, BatchStats | the matching C structures | the same fields, without struct_size |
Config, Object and Client also expose native_handle for mixing with C calls. The C++ layer never lets Karu allocate. A Read takes its length from the size of its destination span, and an empty span fails submit or fetch with KARU_ERR_INVALID without setting karu_last_error. read and read_into with an empty destination succeed without any I/O. Batch::next fails only when the call itself fails. A read that failed arrives as a ready event with its own status and message. Destroying a Batch cancels its work and waits for the workers, so it must not happen while another thread is inside next.
Versions and linking
Karu builds as a static C++23 library. A C program links against it with a C++ linker, so its project enables both languages.
project(reader C CXX)
find_package(karu CONFIG REQUIRED)
add_executable(reader reader.c)
set_target_properties(reader PROPERTIES LINKER_LANGUAGE CXX)
target_link_libraries(reader PRIVATE karu::karu)
The CMake target brings libcurl 7.83 or newer, OpenSSL 3 and the platform thread library with it. karu_api_version returns KARU_API_VERSION, currently 1, karu_version_string returns the release, and karu_http_backend returns the libcurl version string. No C++ type or exception crosses the C interface, which keeps bindings for other languages simple.