Skip to content
c89systemsPublic

About

liblockdc is a C89 client library for lockd, providing persistent state, ordered collections, leases, queues, attachments, queries, and built-in implicit XA transactions with coordinated commit, rollback, and recovery. It also includes Pouch, an embedded storage engine that makes these capabilities available directly inside your application

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

liblockdc

liblockdc is a C89/C90 SDK for leased state, attachments, queues, streamed queries, and transactions. Connect to a remote lockd server over HTTP/1.1, HTTP/2, or a Unix socket, or embed Pouch for local storage in the same process. Pouch also provides ordered collections, transactional inbox/outbox, and the journal for the built-in XA coordinator. An optional PostgreSQL provider can participate in that coordinator. C++98-compatible headers and a Lua facade are available.

Choose When you need
Remote lockd A separate server for networked clients. Supply its endpoint and, for mTLS, a combined PEM bundle.
Embedded Pouch A local file managed by your application. Use a pouch:// endpoint and the same client and lease APIs.

Install and link the C SDK

Extract the target SDK archive and its matching cpkt, libpslog, lonejson, and liblql SDKs. Each prefix should contain the archive's include/ and lib/ directories. Use a compiler and runtime compatible with the target SDK. For GNU shared builds, the supplied dependencies require glibc 2.43 or later.

Save the C program in the next section as quickstart.c alongside this CMakeLists.txt.

cmake_minimum_required(VERSION 3.24)
project(lockdc_quickstart LANGUAGES C)

find_package(lockdc CONFIG REQUIRED COMPONENTS static)
add_executable(quickstart quickstart.c)
set_target_properties(quickstart PROPERTIES
    C_STANDARD 90 C_STANDARD_REQUIRED YES C_EXTENSIONS NO)
target_link_libraries(quickstart PRIVATE lockdc::static)

Set the prefix list to your extracted SDK paths. For a cross build, select the target compiler or CMake toolchain on the first configure. Toolchains that restrict package discovery to specific roots need the SDK prefixes in their CMake package search roots.

sdk=/absolute/path/to/sdk-prefixes
cmake -S . -B build -DCMAKE_PREFIX_PATH="$sdk/lockdc;$sdk/cpkt;$sdk/pslog;$sdk/lonejson;$sdk/liblql"
cmake --build build

For shared linkage, request the shared component and link to lockdc::shared. The v0.32.0 core shared library uses ABI 10. Rebuild applications and native modules that used ABI 9 with the matching SDK. See ABI compatibility and the SDK archive guide.

From a source checkout, make build prepares the pinned dependencies and builds the native Debug SDK and examples. Run make test for the Debug suite. See development for prerequisites, clangd setup, local services, and the release matrix.

C example: write and read leased state

This program opens a client, acquires a lease, updates a JSON document, streams the current state to stdout, and releases the lease. The source and sink are borrowed by each operation and closed by the caller.

#include <lc/lc.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    const char document[] = "{\"status\":\"ready\"}";
    const char *endpoints[1];
    lc_client_config config;
    lc_pouch_settings settings;
    lc_acquire_req request;
    lc_update_opts update;
    lc_get_res result = {0};
    lc_client *client = NULL;
    lc_lease *lease = NULL;
    lc_source *credentials = NULL;
    lc_source *body = NULL;
    lc_sink *output = NULL;
    lc_error error;
    int rc;

    if (argc != 2 && argc != 3) {
        fprintf(stderr, "usage: %s ENDPOINT [CLIENT_BUNDLE.pem]\n", argv[0]);
        return 1;
    }

    lc_error_init(&error);
    lc_client_config_init(&config);
    lc_acquire_req_init(&request);
    lc_update_opts_init(&update);
    endpoints[0] = argv[1];
    config.endpoints = endpoints;
    config.endpoint_count = 1;
    config.default_namespace = "default";

    if (argc == 3) {
        rc = lc_source_from_file(argv[2], &credentials, &error);
        if (rc != LC_OK)
            goto done;
        config.client_bundle_source = credentials;
    } else {
        lc_pouch_settings_init(&settings);
        settings.set_mask = LC_POUCH_SETTING_DURABLE_SYNC;
        settings.durable_sync = 1;
        config.pouch_settings = &settings;
    }

    rc = lc_client_open(&config, &client, &error);
    lc_source_close(credentials);
    credentials = NULL;
    if (rc != LC_OK)
        goto done;

    request.key = "quickstart";
    request.owner = "quickstart-client";
    request.ttl_seconds = 30;
    rc = client->acquire(client, &request, &lease, &error);
    if (rc != LC_OK)
        goto done;

    update.content_type = "application/json";
    rc = lc_source_from_memory(document, sizeof(document) - 1, &body, &error);
    if (rc == LC_OK)
        rc = lease->update(lease, body, &update, &error);
    if (rc == LC_OK)
        rc = lc_sink_to_fd(1, &output, &error);
    if (rc == LC_OK)
        rc = lease->get(lease, output, NULL, &result, &error);
    if (rc == LC_OK) {
        rc = lease->release(lease, NULL, &error);
        if (rc == LC_OK) {
            lease = NULL;
            puts("");
        }
    }

done:
    if (rc != LC_OK)
        fprintf(stderr, "%d: %s\n", rc,
                error.message ? error.message : "liblockdc operation failed");
    lc_get_res_cleanup(&result);
    lc_sink_close(output);
    lc_source_close(body);
    lc_source_close(credentials);
    lc_lease_close(lease);
    lc_client_close(client);
    lc_error_cleanup(&error);
    return rc == LC_OK ? 0 : 1;
}

Run it with a fresh Pouch file. The second invocation reopens the same store. For ordinary local usage, keep the file in a directory writable by the application.

work=$(mktemp -d)
./build/quickstart "pouch://$work/store"
./build/quickstart "pouch://$work/store"

Each run prints {"status":"ready"}. With a running mTLS-enabled lockd and a bundle containing the CA, client certificate and private key, use the same executable with the server endpoint and bundle.

./build/quickstart https://lockd.example.com:19441 /absolute/path/to/client.pem

For a collection example, run this from a source checkout after make build. The complete collection program demonstrates idempotent appends, streaming reads, resume cursors and retention.

work=$(mktemp -d)
./build/debug/examples/lc_example_collection_journal "pouch://$work/journal"

Lua example: encrypted local Pouch

Install the matching C SDK and Lua rocks as described in the Lua guide. Save this as quickstart.lua and run it with the interpreter that has those rocks installed.

local lockdc = require("lockdc")
local root = assert(arg[1], "supply an absolute Pouch file path")
assert(root:sub(1, 1) == "/", "Pouch requires an absolute path")

local function check(value, err)
  if value == nil then
    error(err.message, 2)
  end
  return value
end

local client = check(lockdc.open({
  endpoints = { "pouch://" .. root },
  default_namespace = "default",
  pouch = {
    durable_sync = true,
    compression = "zlib",
    crypto_key_file = root .. ".key",
    crypto_generate_key_file = true,
  },
}))

local lease = check(client:acquire({
  key = "quickstart",
  owner = "lua-quickstart",
  ttl_seconds = 30,
}))
check(lease:update_json({ status = "ready" }))
check(lease:release())
local value = check(client:read_json({ key = "quickstart" }))
print(value.status)
client:close()
work=$(mktemp -d)
lua quickstart.lua "$work/store"
lua quickstart.lua "$work/store"

The program prints ready and reuses the key file on the second open. The key file is separate from the encrypted store. Keep it available when backing up or moving the store.

How single-file Pouch works

  • One file per root. The container holds namespace records, collection streams, indexes, transaction decisions, and storage metadata. It starts at 10 MiB and grows in 1 MiB increments. The engine streams large bodies through bounded buffers and reuses space inside the file after safe reclamation.
  • Staging and NFSv4. One empty lockfile beside the store serializes creation, migration, and restore at that pathname. Reads, writes, and application guards use locks on the store itself. On Linux NFSv4 mounts, use server-backed byte-range locks (local_lock=none). See NFSv4 coordination.
  • Journal and checkpoints. The journal records changes and checksummed checkpoints bound replay. Recovery validates complete records before admitting writers. Query indexes can be rebuilt from canonical records.
  • Ownership and durability. One writer owns the root by default. Set single_writer=false explicitly for shared writers. NoSync is the default. Set durable_sync=true to wait for the durable journal boundary before a mutation is acknowledged. Recovery and maintenance can require their own syncs. Single-file Pouch requires fsync_batch_max_ops=0.
  • Upgrade in place. Opening an eligible legacy multifile directory through pouch:// takes exclusive ownership, streams its data and retained history into a verified container, atomically switches the original path, and then removes the legacy files. Close existing clients and keep the legacy key available before upgrading. Set disable_migration=true to reject legacy roots. The optional LOCKDC_ENABLE_POUCH_MULTIFILE=ON build also exposes the writable directory receiver at pouch+multifile://.

See storage and recovery, upgrade and opening settings, and container internals.

Back up and restore a root

The C client exposes pouch_backup() and pouch_restore() for single-file Pouch roots. Backup captures one consistent root checkpoint and streams it into one compact archive file. Writers can continue while the archive is written. Copy the archive on its own and leave the empty lockfile at the output path. Restore builds a private candidate, verifies it, and switches the root pathname atomically. Connected clients follow the restored root through their existing lc_client handles on their next root operation. Queue watches, managed consumers, and outbox dispatchers resume on the restored data. Leases and delivery claims acquired before the cutover remain fenced.

cmake --build --preset debug --target \
  lc_example_collection_journal lc_example_pouch_archive

work=$(mktemp -d)
./build/debug/examples/lc_example_collection_journal "pouch://$work/store"
./build/debug/examples/lc_example_pouch_archive backup \
  "pouch://$work/store" "$work/app.pouch-backup"
./build/debug/examples/lc_example_pouch_archive restore \
  "pouch://$work/restored" "$work/app.pouch-backup"

Restore merges by default. Matching keys and collections come from the backup, and destination-only data survives. Use --replace-existing to make the archive authoritative for the whole root. The example accepts root and archive key files through POUCH_ROOT_KEY_FILE and POUCH_ARCHIVE_KEY_FILE. See backup and restore for key selection, history, prepared XA work, and retry behavior.

Supported targets

Platform Architectures Libraries
Linux, GNU or musl x86_64, aarch64, armhf Static .a and shared .so
macOS 15 or later, built with osxcross arm64 Static .a and shared .dylib

The current tree uses core shared-library ABI 10. The optional PostgreSQL provider has ABI 0. See ABI and storage compatibility and the release notes before upgrading.

Guides and examples

Topic Guide
C handles, ownership and streaming C API, public header, C examples
Lua installation, usage and embedding Lua SDK, Lua examples
Pouch options, migration and codecs Opening Pouch, compression
Online checkpoints and root recovery Backup and restore
Application session coordination Pouch guards
Ordered journals and streamed appends Collections, append writers, leases, atomic edits
Per-object expiry State retention
Transactional messaging Inbox/outbox, dispatcher
XA and PostgreSQL XA contract, provider
Builds, local services and releases Development, releases, benchmarks

See LICENSE.

About

liblockdc is a C89 client library for lockd, providing persistent state, ordered collections, leases, queues, attachments, queries, and built-in implicit XA transactions with coordinated commit, rollback, and recovery. It also includes Pouch, an embedded storage engine that makes these capabilities available directly inside your application

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages