Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion coverage/api.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
30 changes: 29 additions & 1 deletion src-ts/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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<OmapPage> { return this.#native.getOmap(oid, options.startAfter ?? "", options.prefix ?? "", options.maxReturn ?? 1024n); }
setOmap(oid: string, values: Record<string, Buffer>) { 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<ObjectEntry> {
const list = this.#native.openObjectList();
Expand Down Expand Up @@ -124,6 +125,33 @@ export class IoContext {
async [Symbol.asyncDispose](): Promise<void> { 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<void>) {}
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<string, Buffer>) { this.#steps.push({type: "setOmap", values}); return this; }
removeOmapKeys(keys: string[]) { this.#steps.push({type: "removeOmapKeys", keys}); return this; }
operate(): Promise<void> { return this.run([...this.#steps]); }
}

export class RbdPool {
constructor(readonly nativeHandle: NativeRbdPool) {}
list(): Promise<ImageSpec[]> { return this.nativeHandle.list(); }
Expand Down
3 changes: 2 additions & 1 deletion src-ts/native.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -20,6 +20,7 @@ export interface NativeIoContext {
read(oid: string, length: bigint, offset: bigint): Promise<Buffer>; remove(oid: string): Promise<void>; truncate(oid: string, size: bigint): Promise<void>; stat(oid: string): Promise<ObjectStat>;
setXattr(oid: string, name: string, value: Buffer): Promise<void>; getXattr(oid: string, name: string): Promise<Buffer>; removeXattr(oid: string, name: string): Promise<void>; getXattrs(oid: string): Promise<Record<string, Buffer>>;
getOmap(oid: string, start: string, prefix: string, max: bigint): Promise<OmapPage>; setOmap(oid: string, values: Record<string, Buffer>): Promise<void>; removeOmapKeys(oid: string, keys: string[]): Promise<void>;
writeOp(oid: string, steps: WriteStep[]): Promise<void>;
openObjectList(): NativeObjectList; notify(oid: string, payload: Buffer, timeout: bigint): Promise<Buffer>; flush(): Promise<void>;
lockExclusive(oid: string, name: string, cookie: string, description: string, duration: bigint, flags: number): Promise<void>;
lockShared(oid: string, name: string, cookie: string, tag: string, description: string, duration: bigint, flags: number): Promise<void>;
Expand Down
18 changes: 18 additions & 0 deletions src-ts/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, Buffer>}
| {type: "removeOmapKeys"; keys: string[]};

export interface OmapPage {
entries: Record<string, Buffer>;
more: boolean;
Expand Down
130 changes: 130 additions & 0 deletions src/io_context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string> 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<Napi::Buffer<uint8_t>>();
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<Napi::String>().Utf8Value();
}

std::vector<WriteStep> write_steps(const Napi::Value& value) {
if (!value.IsArray()) throw Napi::TypeError::New(value.Env(), "steps must be an array");
static const std::map<std::string, WriteStep::Kind> 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<std::string, int> 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<Napi::Array>();
std::vector<WriteStep> 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<Napi::Object>();
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<Napi::String>().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<Napi::Object>();
auto names = values.GetPropertyNames();
for (uint32_t n = 0; n < names.Length(); ++n) {
auto key = names.Get(n).As<Napi::String>().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<Napi::Array>();
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<const char*>(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<uint8_t>(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<const char*> kp, vp; std::vector<size_t> kl, vl;
for (const auto& [key, value] : step.entries) { kp.push_back(key.data()); kl.push_back(key.size()); vp.push_back(reinterpret_cast<const char*>(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<const char*> kp; std::vector<size_t> 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)
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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<const char*> kp; std::vector<size_t> 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_);
Expand Down
1 change: 1 addition & 0 deletions src/io_context.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class IoContextWrap : public Napi::ObjectWrap<IoContextWrap> {
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);
Expand Down
Loading
Loading