space-data-module-sdk 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,6 +16,12 @@
16
16
  //
17
17
  // auto get = sdm_piv::call("http.request", "HttpParams", http, {sdm_piv::raw("url", url)});
18
18
  // std::string_view body = get.raw("body");
19
+ //
20
+ // const sdm_piv::Config config = sdm_piv::get_config(); // plugin.getConfig: one ModuleConfig (MCFG), read in place
21
+ // if (!config.ok()) { config.error_message(); }
22
+ // double lead = config.number("nwp_max_lead", 72);
23
+ // std::string_view provider = config.string("targets.0.provider_id");
24
+ // sdm_piv::Span<double> index = config.numbers("index");
19
25
  #ifndef SDM_PIV_HOSTCALL_HPP
20
26
  #define SDM_PIV_HOSTCALL_HPP
21
27
 
@@ -29,6 +35,7 @@
29
35
 
30
36
  #include "sds/PIV/main_generated.h"
31
37
  #include "HostOps_aligned.h"
38
+ #include "ModuleConfig_generated.h"
32
39
 
33
40
  extern "C" {
34
41
  #if defined(__wasm__)
@@ -196,6 +203,282 @@ inline Response call(const char* op, const char* params_type, const Params& para
196
203
  /// Call an operation without a "params" record (clock.now, plugin.getConfig, filesystem.readFile with raw "path", ...).
197
204
  inline Response call(const char* op, std::initializer_list<Frame> frames = {}) { return call_frames(op, std::vector<Frame>(frames)); }
198
205
 
206
+ // ---- plugin.getConfig: the module's config as one ModuleConfig FlatBuffer (schemas/runtime/ModuleConfig.fbs, MCFG) --
207
+
208
+ /// A read-only run of T in place (C++17 has no std::span).
209
+ template <typename T>
210
+ class Span {
211
+ public:
212
+ Span() = default;
213
+ Span(const T* data, size_t size) : data_(data), size_(size) {}
214
+ const T* data() const { return data_; }
215
+ size_t size() const { return size_; }
216
+ bool empty() const { return size_ == 0; }
217
+ const T& operator[](size_t i) const { return data_[i]; }
218
+ const T* begin() const { return data_; }
219
+ const T* end() const { return data_ + size_; }
220
+
221
+ private:
222
+ const T* data_ = nullptr;
223
+ size_t size_ = 0;
224
+ };
225
+
226
+ using ConfigEntries = flatbuffers::Vector<flatbuffers::Offset<sdn::runtime::ConfigEntry>>;
227
+
228
+ /// A table of config entries (the ModuleConfig root, or one nested ConfigTable of a TableList), sorted by KEY.
229
+ ///
230
+ /// Every lookup takes a key or a dotted path into nested tables and lists, the way the old flattened entries were
231
+ /// named: "targets.0.provider_id" (table 0 of TableList "targets", then its "provider_id"), "targets.provider_id"
232
+ /// (a TableList holding one table - a nested object - needs no index), "widths.1" (item 1 of a NumberList or
233
+ /// StringList). A key that itself contains dots is found too: the longest key that matches is taken first.
234
+ /// A missing key, or a value of another kind, answers the default (or an empty list / table).
235
+ class ConfigTable {
236
+ public:
237
+ ConfigTable() = default;
238
+ explicit ConfigTable(const ConfigEntries* entries) : entries_(entries) {}
239
+
240
+ explicit operator bool() const { return entries_ != nullptr; }
241
+ /// The entries, in place (nullptr for an empty table).
242
+ const ConfigEntries* entries() const { return entries_; }
243
+ size_t size() const { return entries_ ? entries_->size() : 0; }
244
+
245
+ /// The entry a key or dotted path names (nullptr when there is none; a path ending in a list index names the
246
+ /// list's entry - use the typed lookups to read the item).
247
+ const sdn::runtime::ConfigEntry* entry(std::string_view key) const { return find(key).entry; }
248
+ bool has(std::string_view key) const { return find(key).entry != nullptr; }
249
+ /// The value's kind, or `fallback` when the key is missing.
250
+ sdn::runtime::configValueKind kind(std::string_view key, sdn::runtime::configValueKind fallback = sdn::runtime::configValueKind_String) const {
251
+ const Found f = find(key);
252
+ return f.entry ? f.entry->KIND() : fallback;
253
+ }
254
+
255
+ /// A String (or an item of a StringList: "names.2"); the view lives as long as the Config.
256
+ std::string_view string(std::string_view key, std::string_view def = {}) const {
257
+ const Found f = find(key);
258
+ if (!f.entry) return def;
259
+ if (f.index < 0 && f.entry->KIND() == sdn::runtime::configValueKind_String) return view(f.entry->STRING_VALUE());
260
+ if (f.index >= 0 && f.entry->KIND() == sdn::runtime::configValueKind_StringList && f.entry->STRINGS() &&
261
+ static_cast<size_t>(f.index) < f.entry->STRINGS()->size()) {
262
+ return view(f.entry->STRINGS()->Get(static_cast<flatbuffers::uoffset_t>(f.index)));
263
+ }
264
+ return def;
265
+ }
266
+ /// A Number (or an item of a NumberList: "widths.1").
267
+ double number(std::string_view key, double def = 0) const {
268
+ const Found f = find(key);
269
+ if (!f.entry) return def;
270
+ if (f.index < 0 && f.entry->KIND() == sdn::runtime::configValueKind_Number) return f.entry->NUMBER_VALUE();
271
+ if (f.index >= 0 && f.entry->KIND() == sdn::runtime::configValueKind_NumberList && f.entry->NUMBERS() &&
272
+ static_cast<size_t>(f.index) < f.entry->NUMBERS()->size()) {
273
+ return f.entry->NUMBERS()->Get(static_cast<flatbuffers::uoffset_t>(f.index));
274
+ }
275
+ return def;
276
+ }
277
+ bool boolean(std::string_view key, bool def = false) const {
278
+ const Found f = find(key);
279
+ return f.entry && f.index < 0 && f.entry->KIND() == sdn::runtime::configValueKind_Bool ? f.entry->BOOL_VALUE() : def;
280
+ }
281
+ /// A NumberList in place, no copy (empty when missing or another kind).
282
+ Span<double> numbers(std::string_view key) const {
283
+ const Found f = find(key);
284
+ if (!f.entry || f.index >= 0 || f.entry->KIND() != sdn::runtime::configValueKind_NumberList || !f.entry->NUMBERS()) return {};
285
+ return {f.entry->NUMBERS()->data(), f.entry->NUMBERS()->size()};
286
+ }
287
+ /// A StringList's items (views into the config; empty when missing or another kind).
288
+ std::vector<std::string_view> strings(std::string_view key) const {
289
+ std::vector<std::string_view> out;
290
+ const Found f = find(key);
291
+ if (!f.entry || f.index >= 0 || f.entry->KIND() != sdn::runtime::configValueKind_StringList || !f.entry->STRINGS()) return out;
292
+ out.reserve(f.entry->STRINGS()->size());
293
+ for (const auto* s : *f.entry->STRINGS()) out.push_back(view(s));
294
+ return out;
295
+ }
296
+ /// How many tables a TableList holds (0 when missing or another kind).
297
+ size_t tables(std::string_view key) const {
298
+ const Found f = find(key);
299
+ return f.entry && f.index < 0 && f.entry->KIND() == sdn::runtime::configValueKind_TableList && f.entry->TABLES() ? f.entry->TABLES()->size() : 0;
300
+ }
301
+ /// Table `i` of a TableList ("targets", 2), or the table a path names ("targets.2"; "settings" for a nested object).
302
+ ConfigTable table(std::string_view key, size_t i) const {
303
+ const Found f = find(key);
304
+ if (!f.entry || f.index >= 0 || f.entry->KIND() != sdn::runtime::configValueKind_TableList || !f.entry->TABLES() || i >= f.entry->TABLES()->size()) return {};
305
+ return ConfigTable(f.entry->TABLES()->Get(static_cast<flatbuffers::uoffset_t>(i))->ENTRIES());
306
+ }
307
+ ConfigTable table(std::string_view key) const {
308
+ const Found f = find(key);
309
+ if (!f.entry || f.entry->KIND() != sdn::runtime::configValueKind_TableList || !f.entry->TABLES()) return {};
310
+ const size_t i = f.index >= 0 ? static_cast<size_t>(f.index) : 0;
311
+ if (i >= f.entry->TABLES()->size() || (f.index < 0 && f.entry->TABLES()->size() != 1)) return {};
312
+ return ConfigTable(f.entry->TABLES()->Get(static_cast<flatbuffers::uoffset_t>(i))->ENTRIES());
313
+ }
314
+
315
+ private:
316
+ struct Found {
317
+ const sdn::runtime::ConfigEntry* entry = nullptr;
318
+ int64_t index = -1; // an item of a list, when the path ends in an index
319
+ };
320
+ static std::string_view view(const flatbuffers::String* s) { return s ? std::string_view(s->c_str(), s->size()) : std::string_view(); }
321
+ static bool index_of(std::string_view s, int64_t& out) {
322
+ if (s.empty() || s.size() > 18) return false;
323
+ int64_t v = 0;
324
+ for (char c : s) { if (c < '0' || c > '9') return false; v = v * 10 + (c - '0'); }
325
+ out = v;
326
+ return true;
327
+ }
328
+ /// The entry with exactly this key: a binary search (the entries are sorted by KEY), then a scan in case a writer
329
+ /// sorted by another collation.
330
+ static const sdn::runtime::ConfigEntry* lookup(const ConfigEntries* entries, std::string_view key) {
331
+ if (!entries) return nullptr;
332
+ size_t lo = 0, hi = entries->size();
333
+ while (lo < hi) {
334
+ const size_t mid = lo + (hi - lo) / 2;
335
+ const auto* e = entries->Get(static_cast<flatbuffers::uoffset_t>(mid));
336
+ const int c = view(e->KEY()).compare(key);
337
+ if (c == 0) return e;
338
+ if (c < 0) lo = mid + 1; else hi = mid;
339
+ }
340
+ for (const auto* e : *entries) if (view(e->KEY()) == key) return e;
341
+ return nullptr;
342
+ }
343
+ static Found resolve(const ConfigEntries* entries, std::string_view path, int depth) {
344
+ if (!entries || path.empty() || depth > 64) return {};
345
+ if (const auto* e = lookup(entries, path)) return {e, -1};
346
+ // the longest key before a dot first, so keys that contain dots win over nesting
347
+ for (size_t dot = path.rfind('.'); dot != std::string_view::npos && dot > 0; dot = path.rfind('.', dot - 1)) {
348
+ const auto* e = lookup(entries, path.substr(0, dot));
349
+ if (!e) continue;
350
+ std::string_view rest = path.substr(dot + 1);
351
+ const size_t next = rest.find('.');
352
+ const std::string_view head = rest.substr(0, next);
353
+ int64_t index = -1;
354
+ const bool indexed = index_of(head, index);
355
+ switch (e->KIND()) {
356
+ case sdn::runtime::configValueKind_NumberList:
357
+ case sdn::runtime::configValueKind_StringList:
358
+ if (indexed && next == std::string_view::npos) return {e, index};
359
+ return {};
360
+ case sdn::runtime::configValueKind_TableList: {
361
+ const auto* tables = e->TABLES();
362
+ if (!tables) return {};
363
+ if (indexed) {
364
+ if (static_cast<uint64_t>(index) >= tables->size()) return {};
365
+ if (next == std::string_view::npos) return {e, index}; // "targets.0": the table itself
366
+ return resolve(tables->Get(static_cast<flatbuffers::uoffset_t>(index))->ENTRIES(), rest.substr(next + 1), depth + 1);
367
+ }
368
+ if (tables->size() != 1) return {};
369
+ return resolve(tables->Get(0)->ENTRIES(), rest, depth + 1); // a nested object: one table, no index
370
+ }
371
+ default:
372
+ return {};
373
+ }
374
+ }
375
+ return {};
376
+ }
377
+ Found find(std::string_view key) const { return resolve(entries_, key, 0); }
378
+
379
+ const ConfigEntries* entries_ = nullptr;
380
+ };
381
+
382
+ /// The module's config, as plugin.getConfig answers it: the host's $PIV response kept whole and its raw "config"
383
+ /// frame - one ModuleConfig FlatBuffer (MCFG) - verified and read in place. Lookups are ConfigTable's. Move-only
384
+ /// (the views point into the kept bytes).
385
+ class Config : public ConfigTable {
386
+ public:
387
+ explicit Config(Response response) : response_(std::move(response)) {
388
+ if (!response_.ok()) { error_ = response_.error_message(); code_ = response_.error_code(); return; }
389
+ std::string_view frame = response_.raw("config");
390
+ if (frame.empty()) { fail("plugin.getConfig answered without a \"config\" frame"); return; }
391
+ const uint8_t* data = reinterpret_cast<const uint8_t*>(frame.data());
392
+ if (reinterpret_cast<uintptr_t>(data) % 8) { // the invoke arena aligns frames to 8; copy only if a host did not
393
+ aligned_.resize((frame.size() + 7) / 8);
394
+ std::memcpy(aligned_.data(), frame.data(), frame.size());
395
+ data = reinterpret_cast<const uint8_t*>(aligned_.data());
396
+ }
397
+ flatbuffers::Verifier::Options options;
398
+ options.max_tables = 100000000; // TableList-heavy configs: the buffer size bounds the work anyway
399
+ flatbuffers::Verifier verifier(data, frame.size(), options);
400
+ if (!sdn::runtime::VerifyModuleConfigBuffer(verifier)) { fail("plugin.getConfig: \"config\" is not a ModuleConfig (MCFG) FlatBuffer"); return; }
401
+ root_ = sdn::runtime::GetModuleConfig(data);
402
+ size_ = frame.size();
403
+ static_cast<ConfigTable&>(*this) = ConfigTable(root_->ENTRIES());
404
+ }
405
+ Config(Config&&) = default;
406
+ Config& operator=(Config&&) = default;
407
+ Config(const Config&) = delete;
408
+ Config& operator=(const Config&) = delete;
409
+
410
+ bool ok() const { return root_ != nullptr; }
411
+ std::string error_code() const { return code_; }
412
+ std::string error_message() const { return error_; }
413
+ /// The verified ModuleConfig root (nullptr when the call failed).
414
+ const sdn::runtime::ModuleConfig* root() const { return root_; }
415
+ /// The ModuleConfig bytes' length.
416
+ size_t byte_size() const { return size_; }
417
+
418
+ private:
419
+ void fail(const char* message) { error_ = message; code_ = "failed"; }
420
+ Response response_;
421
+ std::vector<uint64_t> aligned_;
422
+ const sdn::runtime::ModuleConfig* root_ = nullptr;
423
+ size_t size_ = 0;
424
+ std::string error_;
425
+ std::string code_;
426
+ };
427
+
428
+ /// plugin.getConfig: the module's config (no capability needed).
429
+ inline Config get_config() { return Config(call("plugin.getConfig")); }
430
+
431
+ /// SQL values (raw "params" of storage.flatsql_query_stream / query_sandboxed / flatsql_cache_key, raw "cells" of a
432
+ /// query_sandboxed rows answer) in FlatSQL's tagged parameter encoding: value after value, a u8 tag, a u32
433
+ /// little-endian payload length, the payload. Text and bytes of any length.
434
+ /// sdm_piv::SqlValues p; p.i64(25544).str("ISS (ZARYA)").bytes(key, 32);
435
+ /// sdm_piv::call("storage.flatsql_query_stream", "SqlStreamParams", s, {sdm_piv::raw("sql", sql), p.frame()});
436
+ enum SqlTag : uint8_t { kSqlNull = 0, kSqlBool = 1, kSqlI64 = 2, kSqlF64 = 3, kSqlStr = 4, kSqlBytes = 5 };
437
+ class SqlValues {
438
+ public:
439
+ SqlValues& null() { return put(kSqlNull, nullptr, 0); }
440
+ SqlValues& boolean(bool v) { const uint8_t b = v ? 1 : 0; return put(kSqlBool, &b, 1); }
441
+ SqlValues& i64(int64_t v) { uint8_t b[8]; for (int i = 0; i < 8; ++i) b[i] = static_cast<uint8_t>(static_cast<uint64_t>(v) >> (8 * i)); return put(kSqlI64, b, 8); }
442
+ SqlValues& f64(double v) { uint64_t u; std::memcpy(&u, &v, 8); return i64_bits(kSqlF64, u); }
443
+ SqlValues& str(std::string_view v) { return put(kSqlStr, reinterpret_cast<const uint8_t*>(v.data()), v.size()); }
444
+ SqlValues& bytes(const uint8_t* data, size_t size) { return put(kSqlBytes, data, size); }
445
+ std::string_view view() const { return bytes_; }
446
+ /// The raw frame (default port "params"); the values must outlive the call.
447
+ Frame frame(const char* port = "params") const { return raw(port, bytes_); }
448
+
449
+ private:
450
+ SqlValues& i64_bits(uint8_t tag, uint64_t u) { uint8_t b[8]; for (int i = 0; i < 8; ++i) b[i] = static_cast<uint8_t>(u >> (8 * i)); return put(tag, b, 8); }
451
+ SqlValues& put(uint8_t tag, const uint8_t* data, size_t size) {
452
+ bytes_.push_back(static_cast<char>(tag));
453
+ for (int i = 0; i < 4; ++i) bytes_.push_back(static_cast<char>((static_cast<uint32_t>(size) >> (8 * i)) & 0xff));
454
+ if (size) bytes_.append(reinterpret_cast<const char*>(data), size);
455
+ return *this;
456
+ }
457
+ std::string bytes_;
458
+ };
459
+ /// One decoded SQL value: its tag and payload (in place).
460
+ struct SqlValue {
461
+ uint8_t tag;
462
+ std::string_view payload;
463
+ bool as_bool() const { return !payload.empty() && payload[0] != 0; }
464
+ int64_t as_i64() const { uint64_t u = 0; for (size_t i = 0; i < 8 && i < payload.size(); ++i) u |= static_cast<uint64_t>(static_cast<uint8_t>(payload[i])) << (8 * i); return static_cast<int64_t>(u); }
465
+ double as_f64() const { const uint64_t u = static_cast<uint64_t>(as_i64()); double d; std::memcpy(&d, &u, 8); return d; }
466
+ };
467
+ /// The values of a tagged SQL value run; false when it is malformed.
468
+ inline bool read_sql_values(std::string_view bytes, std::vector<SqlValue>& out) {
469
+ out.clear();
470
+ size_t at = 0;
471
+ while (at < bytes.size()) {
472
+ if (bytes.size() - at < 5) return false;
473
+ uint32_t size = 0;
474
+ for (int i = 0; i < 4; ++i) size |= static_cast<uint32_t>(static_cast<uint8_t>(bytes[at + 1 + i])) << (8 * i);
475
+ if (bytes.size() - at - 5 < size) return false;
476
+ out.push_back({static_cast<uint8_t>(bytes[at]), bytes.substr(at + 5, size)});
477
+ at += 5 + size;
478
+ }
479
+ return true;
480
+ }
481
+
199
482
  } // namespace sdm_piv
200
483
 
201
484
  #endif // SDM_PIV_HOSTCALL_HPP