CCF
Loading...
Searching...
No Matches
kv_module_loader.h
Go to the documentation of this file.
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the Apache 2.0 License.
3#pragma once
4
7#include "ccf/tx.h"
8
9#include <string>
10
11namespace ccf::js::modules
12{
14 {
15 protected:
16 ccf::Modules::ReadOnlyHandle* modules_handle;
17
18 public:
19 KvModuleLoader(ccf::Modules::ReadOnlyHandle* mh) : modules_handle(mh) {}
20
21 virtual std::optional<js::core::JSWrappedValue> get_module(
22 std::string_view module_name, js::core::Context& ctx) override
23 {
24 std::string module_name_kv(module_name);
25 if (module_name_kv[0] != '/')
26 {
27 module_name_kv.insert(0, "/");
28 }
29
30 CCF_APP_TRACE("Looking for module '{}' in KV", module_name_kv);
31
32 auto module_str = modules_handle->get(module_name_kv);
33 if (!module_str.has_value())
34 {
35 CCF_APP_TRACE("Module '{}' not found", module_name_kv);
36 return std::nullopt;
37 }
38
39 auto module_name_quickjs = module_name_kv.c_str() + 1;
40 const char* buf = module_str->c_str();
41 size_t buf_len = module_str->size();
42 auto parsed_module = ctx.eval(
43 buf,
44 buf_len,
45 module_name_quickjs,
46 JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
47 if (parsed_module.is_exception())
48 {
49 auto [reason, trace] = ctx.error_message();
50
51 auto& rt = ctx.runtime();
52 if (rt.log_exception_details)
53 {
54 CCF_APP_FAIL("{}: {}", reason, trace.value_or("<no trace>"));
55 }
56
57 throw std::runtime_error(fmt::format(
58 "Failed to compile module '{}': {}", module_name, reason));
59 }
60
62 "Module '{}' found in KV (table: {})",
63 module_name_kv,
64 modules_handle->get_name_of_map());
65 return parsed_module;
66 }
67 };
68}
Definition context.h:46
JSWrappedValue eval(const char *input, size_t input_len, const char *filename, int eval_flags) const
Definition context.cpp:422
std::pair< std::string, std::optional< std::string > > error_message()
Definition context.cpp:187
Runtime & runtime()
Definition context.h:79
Definition kv_module_loader.h:14
virtual std::optional< js::core::JSWrappedValue > get_module(std::string_view module_name, js::core::Context &ctx) override
Definition kv_module_loader.h:21
ccf::Modules::ReadOnlyHandle * modules_handle
Definition kv_module_loader.h:16
KvModuleLoader(ccf::Modules::ReadOnlyHandle *mh)
Definition kv_module_loader.h:19
Definition module_loader_interface.h:21
#define CCF_APP_TRACE
Definition logger.h:383
#define CCF_APP_FAIL
Definition logger.h:400
Definition module_loader_interface.h:19