diff --git a/README.md b/README.md index c9b5918..5945e0a 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,21 @@ An operation uses the namespace, locator key and read snapshot of its `IoContext Data is not copied on its way to or from Ceph. A `Buffer` passed to `write()`, `writeFull()`, `append()` or `RbdImage.write()` is used in place until the returned promise settles, so like with `fs.write()` it must not be changed before then. A read returns a `Buffer` over the memory librados read into. +A compound write applies all of its steps to one object atomically, or none of them. Checks such as an exclusive create or an xattr comparison make it conditional: + +```ts +await io.writeOp("payload") + .create({exclusive: true}) + .writeFull(data) + .setXattr("checksum", checksum) + .operate(); + +await io.writeOp("payload") + .compareXattr("state", "eq", Buffer.from("pending")) + .setXattr("state", Buffer.from("done")) + .operate(); +``` + Administrative commands are deliberately marked unsafe because their JSON schema and authorization are controlled by the connected Ceph release: ```ts diff --git a/coverage/api.json b/coverage/api.json index 915f34a..dd053ef 100644 --- a/coverage/api.json +++ b/coverage/api.json @@ -8,7 +8,7 @@ "rados_ioctx_pool_required_alignment2", "rados_write", "rados_write_full", "rados_append", "rados_read", "rados_remove", "rados_trunc", "rados_stat", "rados_setxattr", "rados_getxattr", "rados_rmxattr", "rados_getxattrs", "rados_getxattrs_next", "rados_getxattrs_end", "rados_create_read_op", "rados_read_op_omap_get_vals2", "rados_read_op_operate", "rados_omap_get_next2", "rados_omap_get_end", "rados_release_read_op", - "rados_create_write_op", "rados_write_op_omap_set2", "rados_write_op_omap_rm_keys2", "rados_write_op_operate", "rados_release_write_op", + "rados_create_write_op", "rados_write_op_omap_set2", "rados_write_op_assert_exists", "rados_write_op_assert_version", "rados_write_op_cmpxattr", "rados_write_op_create", "rados_write_op_write", "rados_write_op_write_full", "rados_write_op_append", "rados_write_op_truncate", "rados_write_op_zero", "rados_write_op_remove", "rados_write_op_setxattr", "rados_write_op_rmxattr", "rados_write_op_omap_rm_keys2", "rados_write_op_operate", "rados_release_write_op", "rados_nobjects_list_open", "rados_nobjects_list_next2", "rados_nobjects_list_close", "rados_notify2", "rados_notify_ack", "rados_watch3", "rados_unwatch2", "rados_watch_flush", "rados_aio_flush", "rados_lock_exclusive", "rados_lock_shared", "rados_unlock", "rados_break_lock", "rados_mon_command", "rados_mon_command_target", "rados_mgr_command", "rados_mgr_command_target", "rados_osd_command", "rados_pg_command", diff --git a/src-ts/index.ts b/src-ts/index.ts index bdb2488..abdde98 100644 --- a/src-ts/index.ts +++ b/src-ts/index.ts @@ -1,7 +1,7 @@ import {CephConfirmationError} from "./errors"; import {EventEmitter} from "node:events"; import {native, type NativeCluster, type NativeImageUpdateWatch, type NativeIoContext, type NativeMonitorLog, type NativeObjectWatch, type NativeRbdImage, type NativeRbdPool} from "./native"; -import type {ClusterOptions, CommandResult, CommandTarget, Confirmation, ForceConfirmation, ImageSpec, ImageStat, MonitorLogEntry, ObjectEntry, ObjectNotification, ObjectStat, OmapPage, RbdPoolStats, SnapshotInfo} from "./types"; +import type {ClusterOptions, CommandResult, CommandTarget, Confirmation, ForceConfirmation, ImageSpec, ImageStat, MonitorLogEntry, ObjectEntry, ObjectNotification, ObjectStat, OmapPage, RbdPoolStats, SnapshotInfo, WriteStep, XattrComparison} from "./types"; export * from "./errors"; export * from "./types"; @@ -93,6 +93,7 @@ export class IoContext { setXattr(oid: string, name: string, value: Buffer) { return this.#native.setXattr(oid, name, value); } getXattr(oid: string, name: string) { return this.#native.getXattr(oid, name); } removeXattr(oid: string, name: string) { return this.#native.removeXattr(oid, name); } getXattrs(oid: string) { return this.#native.getXattrs(oid); } getOmap(oid: string, options: {startAfter?: string; prefix?: string; maxReturn?: bigint} = {}): Promise { return this.#native.getOmap(oid, options.startAfter ?? "", options.prefix ?? "", options.maxReturn ?? 1024n); } setOmap(oid: string, values: Record) { return this.#native.setOmap(oid, values); } removeOmapKeys(oid: string, keys: string[]) { return this.#native.removeOmapKeys(oid, keys); } + writeOp(oid: string): WriteOperation { return new WriteOperation(steps => this.#native.writeOp(oid, steps)); } /** Lists the objects a page at a time, so a pool of any size can be listed without holding it in memory */ async *objects(options: {pageSize?: number} = {}): AsyncGenerator { const list = this.#native.openObjectList(); @@ -124,6 +125,33 @@ export class IoContext { async [Symbol.asyncDispose](): Promise { await this.close(); } } +/** + * Steps applied to one object atomically by a single OSD operation: every step takes effect, or none does. + * A failed check fails the whole operation before anything is written: assertExists() with ENOENT, + * assertVersion() with ERANGE when the object is newer and EOVERFLOW when it is older, compareXattr() with + * ECANCELED, and create({exclusive: true}) with EEXIST + */ +export class WriteOperation { + readonly #steps: WriteStep[] = []; + constructor(private readonly run: (steps: WriteStep[]) => Promise) {} + assertExists() { this.#steps.push({type: "assertExists"}); return this; } + assertVersion(version: bigint) { this.#steps.push({type: "assertVersion", version}); return this; } + /** Passes when the stored xattr compares to value as given, e.g. "gt" when it is greater. Values compare as strings */ + compareXattr(name: string, comparison: XattrComparison, value: Buffer) { this.#steps.push({type: "compareXattr", name, comparison, value}); return this; } + create(options: {exclusive?: boolean} = {}) { this.#steps.push({type: "create", exclusive: options.exclusive ?? true}); return this; } + write(data: Buffer, offset = 0n) { this.#steps.push({type: "write", data, offset}); return this; } + writeFull(data: Buffer) { this.#steps.push({type: "writeFull", data}); return this; } + append(data: Buffer) { this.#steps.push({type: "append", data}); return this; } + truncate(size: bigint) { this.#steps.push({type: "truncate", size}); return this; } + zero(offset: bigint, length: bigint) { this.#steps.push({type: "zero", offset, length}); return this; } + remove() { this.#steps.push({type: "remove"}); return this; } + setXattr(name: string, value: Buffer) { this.#steps.push({type: "setXattr", name, value}); return this; } + removeXattr(name: string) { this.#steps.push({type: "removeXattr", name}); return this; } + setOmap(values: Record) { this.#steps.push({type: "setOmap", values}); return this; } + removeOmapKeys(keys: string[]) { this.#steps.push({type: "removeOmapKeys", keys}); return this; } + operate(): Promise { return this.run([...this.#steps]); } +} + export class RbdPool { constructor(readonly nativeHandle: NativeRbdPool) {} list(): Promise { return this.nativeHandle.list(); } diff --git a/src-ts/native.ts b/src-ts/native.ts index 72e492e..b96e917 100644 --- a/src-ts/native.ts +++ b/src-ts/native.ts @@ -1,4 +1,4 @@ -import type {Capabilities, ClusterStats, CommandResult, ImageSpec, ImageStat, ObjectEntry, ObjectStat, OmapPage, RbdPoolStats, SnapshotInfo, Versions} from "./types"; +import type {Capabilities, ClusterStats, CommandResult, ImageSpec, ImageStat, ObjectEntry, ObjectStat, OmapPage, RbdPoolStats, SnapshotInfo, Versions, WriteStep} from "./types"; export interface NativeCluster { closed: boolean; readonly instanceId: bigint; @@ -20,6 +20,7 @@ export interface NativeIoContext { read(oid: string, length: bigint, offset: bigint): Promise; remove(oid: string): Promise; truncate(oid: string, size: bigint): Promise; stat(oid: string): Promise; setXattr(oid: string, name: string, value: Buffer): Promise; getXattr(oid: string, name: string): Promise; removeXattr(oid: string, name: string): Promise; getXattrs(oid: string): Promise>; getOmap(oid: string, start: string, prefix: string, max: bigint): Promise; setOmap(oid: string, values: Record): Promise; removeOmapKeys(oid: string, keys: string[]): Promise; + writeOp(oid: string, steps: WriteStep[]): Promise; openObjectList(): NativeObjectList; notify(oid: string, payload: Buffer, timeout: bigint): Promise; flush(): Promise; lockExclusive(oid: string, name: string, cookie: string, description: string, duration: bigint, flags: number): Promise; lockShared(oid: string, name: string, cookie: string, tag: string, description: string, duration: bigint, flags: number): Promise; diff --git a/src-ts/types.ts b/src-ts/types.ts index 3a22a94..485a096 100644 --- a/src-ts/types.ts +++ b/src-ts/types.ts @@ -53,6 +53,24 @@ export interface ObjectEntry { namespace: string; } +export type XattrComparison = "eq" | "ne" | "gt" | "gte" | "lt" | "lte"; + +export type WriteStep = + | {type: "assertExists"} + | {type: "assertVersion"; version: bigint} + | {type: "compareXattr"; name: string; comparison: XattrComparison; value: Buffer} + | {type: "create"; exclusive: boolean} + | {type: "write"; data: Buffer; offset: bigint} + | {type: "writeFull"; data: Buffer} + | {type: "append"; data: Buffer} + | {type: "truncate"; size: bigint} + | {type: "zero"; offset: bigint; length: bigint} + | {type: "remove"} + | {type: "setXattr"; name: string; value: Buffer} + | {type: "removeXattr"; name: string} + | {type: "setOmap"; values: Record} + | {type: "removeOmapKeys"; keys: string[]}; + export interface OmapPage { entries: Record; more: boolean; diff --git a/src/io_context.cpp b/src/io_context.cpp index c95ff7a..5fb7072 100644 --- a/src/io_context.cpp +++ b/src/io_context.cpp @@ -24,6 +24,122 @@ Bytes buffer_arg(const Napi::CallbackInfo& info, size_t index, const char* name) return {value.Data(), value.Data() + value.Length()}; } +// One step of a compound write operation, converted from JavaScript on the main thread +struct WriteStep { + enum Kind { AssertExists, AssertVersion, CompareXattr, Create, Write, WriteFull, Append, Truncate, Zero, Remove, SetXattr, RemoveXattr, SetOmap, RemoveOmapKeys }; + Kind kind{}; + std::string name; + Bytes data; + uint64_t offset{}; + uint64_t length{}; + int flag{}; + ByteMap entries; + std::vector keys; +}; + +Bytes buffer_value(const Napi::Value& value, const char* name) { + if (!value.IsBuffer()) throw Napi::TypeError::New(value.Env(), std::string(name) + " must be a Buffer"); + auto buffer = value.As>(); + return {buffer.Data(), buffer.Data() + buffer.Length()}; +} + +std::string string_value(const Napi::Value& value, const char* name) { + if (!value.IsString()) throw Napi::TypeError::New(value.Env(), std::string(name) + " must be a string"); + return value.As().Utf8Value(); +} + +std::vector write_steps(const Napi::Value& value) { + if (!value.IsArray()) throw Napi::TypeError::New(value.Env(), "steps must be an array"); + static const std::map kinds = { + {"assertExists", WriteStep::AssertExists}, {"assertVersion", WriteStep::AssertVersion}, {"compareXattr", WriteStep::CompareXattr}, + {"create", WriteStep::Create}, {"write", WriteStep::Write}, {"writeFull", WriteStep::WriteFull}, {"append", WriteStep::Append}, + {"truncate", WriteStep::Truncate}, {"zero", WriteStep::Zero}, {"remove", WriteStep::Remove}, {"setXattr", WriteStep::SetXattr}, + {"removeXattr", WriteStep::RemoveXattr}, {"setOmap", WriteStep::SetOmap}, {"removeOmapKeys", WriteStep::RemoveOmapKeys}}; + // compareXattr(name, "gt", value) passes when the stored xattr is greater than value. The OSD evaluates + // "value OP stored", so the ordering operators are mirrored here + static const std::map comparisons = { + {"eq", LIBRADOS_CMPXATTR_OP_EQ}, {"ne", LIBRADOS_CMPXATTR_OP_NE}, {"gt", LIBRADOS_CMPXATTR_OP_LT}, + {"gte", LIBRADOS_CMPXATTR_OP_LTE}, {"lt", LIBRADOS_CMPXATTR_OP_GT}, {"lte", LIBRADOS_CMPXATTR_OP_GTE}}; + auto array = value.As(); + std::vector steps; + for (uint32_t i = 0; i < array.Length(); ++i) { + if (!array.Get(i).IsObject()) throw Napi::TypeError::New(value.Env(), "steps must be objects"); + auto item = array.Get(i).As(); + auto kind = kinds.find(string_value(item.Get("type"), "step type")); + if (kind == kinds.end()) throw Napi::TypeError::New(value.Env(), "unknown write step " + item.Get("type").As().Utf8Value()); + WriteStep step; + step.kind = kind->second; + switch (step.kind) { + case WriteStep::AssertExists: case WriteStep::Remove: break; + case WriteStep::AssertVersion: step.offset = uint64_arg(item.Get("version"), "version"); break; + case WriteStep::CompareXattr: { + step.name = string_value(item.Get("name"), "name"); + auto comparison = comparisons.find(string_value(item.Get("comparison"), "comparison")); + if (comparison == comparisons.end()) throw Napi::TypeError::New(value.Env(), "comparison must be one of eq, ne, gt, gte, lt, lte"); + step.flag = comparison->second; + step.data = buffer_value(item.Get("value"), "value"); + break; + } + case WriteStep::Create: step.flag = item.Get("exclusive").ToBoolean() ? LIBRADOS_CREATE_EXCLUSIVE : LIBRADOS_CREATE_IDEMPOTENT; break; + case WriteStep::Write: step.data = buffer_value(item.Get("data"), "data"); step.offset = uint64_arg(item.Get("offset"), "offset"); break; + case WriteStep::WriteFull: case WriteStep::Append: step.data = buffer_value(item.Get("data"), "data"); break; + case WriteStep::Truncate: step.offset = uint64_arg(item.Get("size"), "size"); break; + case WriteStep::Zero: step.offset = uint64_arg(item.Get("offset"), "offset"); step.length = uint64_arg(item.Get("length"), "length"); break; + case WriteStep::SetXattr: step.name = string_value(item.Get("name"), "name"); step.data = buffer_value(item.Get("value"), "value"); break; + case WriteStep::RemoveXattr: step.name = string_value(item.Get("name"), "name"); break; + case WriteStep::SetOmap: { + if (!item.Get("values").IsObject()) throw Napi::TypeError::New(value.Env(), "values must be an object"); + auto values = item.Get("values").As(); + auto names = values.GetPropertyNames(); + for (uint32_t n = 0; n < names.Length(); ++n) { + auto key = names.Get(n).As().Utf8Value(); + step.entries.emplace_back(key, buffer_value(values.Get(key), "omap values")); + } + break; + } + case WriteStep::RemoveOmapKeys: { + if (!item.Get("keys").IsArray()) throw Napi::TypeError::New(value.Env(), "keys must be an array"); + auto keys = item.Get("keys").As(); + for (uint32_t n = 0; n < keys.Length(); ++n) step.keys.push_back(string_value(keys.Get(n), "keys")); + break; + } + } + steps.push_back(std::move(step)); + } + return steps; +} + +// Adds a step to a write operation. librados copies buffers and strings into the operation here +void add_step(rados_write_op_t op, const WriteStep& step) { + const char* data = reinterpret_cast(step.data.data()); + switch (step.kind) { + case WriteStep::AssertExists: rados_write_op_assert_exists(op); break; + case WriteStep::AssertVersion: rados_write_op_assert_version(op, step.offset); break; + case WriteStep::CompareXattr: rados_write_op_cmpxattr(op, step.name.c_str(), static_cast(step.flag), data, step.data.size()); break; + case WriteStep::Create: rados_write_op_create(op, step.flag, nullptr); break; + case WriteStep::Write: rados_write_op_write(op, data, step.data.size(), step.offset); break; + case WriteStep::WriteFull: rados_write_op_write_full(op, data, step.data.size()); break; + case WriteStep::Append: rados_write_op_append(op, data, step.data.size()); break; + case WriteStep::Truncate: rados_write_op_truncate(op, step.offset); break; + case WriteStep::Zero: rados_write_op_zero(op, step.offset, step.length); break; + case WriteStep::Remove: rados_write_op_remove(op); break; + case WriteStep::SetXattr: rados_write_op_setxattr(op, step.name.c_str(), data, step.data.size()); break; + case WriteStep::RemoveXattr: rados_write_op_rmxattr(op, step.name.c_str()); break; + case WriteStep::SetOmap: { + std::vector kp, vp; std::vector kl, vl; + for (const auto& [key, value] : step.entries) { kp.push_back(key.data()); kl.push_back(key.size()); vp.push_back(reinterpret_cast(value.data())); vl.push_back(value.size()); } + rados_write_op_omap_set2(op, kp.data(), vp.data(), kl.data(), vl.data(), kp.size()); + break; + } + case WriteStep::RemoveOmapKeys: { + std::vector kp; std::vector kl; + for (const auto& key : step.keys) { kp.push_back(key.data()); kl.push_back(key.size()); } + rados_write_op_omap_rm_keys2(op, kp.data(), kl.data(), kp.size()); + break; + } + } +} + Napi::Object byte_map_to_js(Napi::Env env, const ByteMap& values) { auto out = Napi::Object::New(env); for (const auto& [key, value] : values) @@ -58,6 +174,7 @@ void IoContextWrap::Init(Napi::Env env, Napi::Object exports) { InstanceMethod("getOmap", &IoContextWrap::GetOmap), InstanceMethod("setOmap", &IoContextWrap::SetOmap), InstanceMethod("removeOmapKeys", &IoContextWrap::RemoveOmapKeys), + InstanceMethod("writeOp", &IoContextWrap::WriteOp), InstanceMethod("openObjectList", &IoContextWrap::OpenObjectList), InstanceMethod("notify", &IoContextWrap::Notify), InstanceMethod("flush", &IoContextWrap::Flush), @@ -184,6 +301,19 @@ Napi::Value IoContextWrap::RemoveOmapKeys(const Napi::CallbackInfo& info) { return async_void(info.Env(), "rados_write_op_omap_rm_keys2", oid, [state, oid, keys] { return state->use([&](rados_ioctx_t h) { std::vector kp; std::vector kl; for (const auto& key : keys) { kp.push_back(key.data()); kl.push_back(key.size()); } auto op = rados_create_write_op(); rados_write_op_omap_rm_keys2(op, kp.data(), kl.data(), keys.size()); int rc = rados_write_op_operate(op, h, oid.c_str(), nullptr, 0); rados_release_write_op(op); return rc; }); }); } +Napi::Value IoContextWrap::WriteOp(const Napi::CallbackInfo& info) { + auto oid = string_arg(info, 0, "oid"); auto steps = write_steps(info[1]); auto state = in_flight(state_); + return async_void(info.Env(), "rados_write_op_operate", oid, [state, oid, steps] { + return state->use([&](rados_ioctx_t h) { + rados_write_op_t op = rados_create_write_op(); + for (const auto& step : steps) add_step(op, step); + int rc = rados_write_op_operate(op, h, oid.c_str(), nullptr, 0); + rados_release_write_op(op); + return rc; + }); + }); +} + Napi::Value IoContextWrap::OpenObjectList(const Napi::CallbackInfo& info) { return ObjectListWrap::Create(info.Env(), state_, pool_); } Napi::Value IoContextWrap::Notify(const Napi::CallbackInfo& info) { auto oid = string_arg(info, 0, "oid"); auto payload = buffer_arg(info, 1, "payload"); uint64_t timeout = uint64_arg(info[2], "timeoutMs"); auto state = in_flight(state_); diff --git a/src/io_context.h b/src/io_context.h index 0e9cf93..1162855 100644 --- a/src/io_context.h +++ b/src/io_context.h @@ -42,6 +42,7 @@ class IoContextWrap : public Napi::ObjectWrap { Napi::Value GetOmap(const Napi::CallbackInfo& info); Napi::Value SetOmap(const Napi::CallbackInfo& info); Napi::Value RemoveOmapKeys(const Napi::CallbackInfo& info); + Napi::Value WriteOp(const Napi::CallbackInfo& info); Napi::Value OpenObjectList(const Napi::CallbackInfo& info); Napi::Value ListWatchers(const Napi::CallbackInfo& info); Napi::Value Notify(const Napi::CallbackInfo& info); diff --git a/tests/integration/rados-rbd.test.ts b/tests/integration/rados-rbd.test.ts index edfe7c3..5772784 100644 --- a/tests/integration/rados-rbd.test.ts +++ b/tests/integration/rados-rbd.test.ts @@ -92,6 +92,54 @@ test("large writes and reads, and reads past the end", {skip: !enabled}, async ( await io.remove("zero-copy"); }); +test("compound write operations apply all steps or none", {skip: !enabled}, async () => { + await using io = cluster.ioContext(pool); + const failsWith = (errno: number) => (error: unknown) => error instanceof CephError && error.errno === errno; + await io.writeOp("op").create({exclusive: true}).writeFull(Buffer.from("first")).setXattr("state", Buffer.from("ready")).operate(); + assert.equal((await io.read("op", 16n)).toString(), "first"); + assert.equal((await io.getXattr("op", "state")).toString(), "ready"); + + await assert.rejects(io.writeOp("op").create({exclusive: true}).writeFull(Buffer.from("second")).operate(), failsWith(17)); + await assert.rejects(io.writeOp("op").compareXattr("state", "eq", Buffer.from("other")).writeFull(Buffer.from("second")).removeXattr("state").operate(), failsWith(125)); + assert.equal((await io.read("op", 16n)).toString(), "first"); + assert.equal((await io.getXattr("op", "state")).toString(), "ready"); + + await io.writeOp("op").compareXattr("state", "eq", Buffer.from("ready")).writeFull(Buffer.from("second")).setXattr("state", Buffer.from("done")).operate(); + assert.equal((await io.read("op", 16n)).toString(), "second"); + assert.equal((await io.getXattr("op", "state")).toString(), "done"); + + await assert.rejects(io.writeOp("op-missing").assertExists().writeFull(Buffer.from("x")).operate(), failsWith(2)); + await assert.rejects(io.stat("op-missing"), failsWith(2)); + await io.writeOp("op").remove().operate(); + await assert.rejects(io.stat("op"), failsWith(2)); +}); + +test("compound write checks compare the stored value and the version", {skip: !enabled}, async () => { + await using io = cluster.ioContext(pool); + const failsWith = (errno: number) => (error: unknown) => error instanceof CephError && error.errno === errno; + await io.writeFull("checked", Buffer.from("x")); + await io.setXattr("checked", "v", Buffer.from("m")); + for (const [comparison, value, passes] of [ + ["eq", "m", true], ["ne", "m", false], ["gt", "a", true], ["gt", "z", false], ["gte", "m", true], + ["lt", "z", true], ["lt", "a", false], ["lte", "m", true], + ] as const) { + const op = io.writeOp("checked").compareXattr("v", comparison, Buffer.from(value)).operate(); + if (passes) await op; else await assert.rejects(op, failsWith(125), `${comparison} ${value}`); + } + + await io.writeFull("checked", Buffer.from("v1")); + const version = io.lastVersion; + await assert.rejects(io.writeOp("checked").assertVersion(version + 1n).writeFull(Buffer.from("v2")).operate(), failsWith(75)); + await io.writeOp("checked").assertVersion(version).writeFull(Buffer.from("v2")).operate(); + await assert.rejects(io.writeOp("checked").assertVersion(version).writeFull(Buffer.from("v3")).operate(), failsWith(34)); + assert.equal((await io.read("checked", 16n)).toString(), "v2"); + + const ops = Array.from({length: 8}, () => io.writeOp("checked").append(Buffer.from("!")).operate()); + assert.throws(() => io.setNamespace("elsewhere"), failsWith(16)); + await Promise.all(ops); + await io.remove("checked"); +}); + test("RBD image, I/O, metadata, snapshots, resize, and trash", {skip: !enabled}, async () => { await using io = cluster.ioContext(pool); const rbd = io.rbd();