@getanthill/datastore
Version:
Event-Sourced Datastore
104 lines (92 loc) • 3.29 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handle = handle;
exports.handleFHE = handleFHE;
exports.thread = thread;
const node_path_1 = __importDefault(require("node:path"));
const worker_threads_1 = require("worker_threads");
async function handle(handler, state, event, modelConfig, fhe) {
if ((modelConfig === null || modelConfig === void 0 ? void 0 : modelConfig.with_fully_homomorphic_encryption) === true &&
fhe !== undefined &&
typeof handler === 'string') {
return handleFHE(handler, state, event, modelConfig, fhe);
}
if (typeof handler === 'function') {
return handler(state, event);
}
const res = await thread(`async function handler(state, event) {
${handler}
}`, state, event);
return res;
}
async function handleFHE(handler, state, event, modelConfig, fhe) {
var _a, _b;
const con = fhe.constructor
.toString()
.replace(/\/\* istanbul ignore next \*\//gm, '')
.replace(/cov_[a-z0-9]+\(\)\.(b|s|f)(\[\d+\])+\+\+/gm, 'null');
const p = node_path_1.default.resolve(__dirname, '../../dist/');
const script = `
const SEAL = require("node-seal");
const _vm = require('vm');
_vm.default = _vm;
const _operatorOverload = require("${p}/services/fhe/operator-overload");
const _utils = require("${p}/utils");
let sealPromise = SEAL();
${con}
async function handler(state, event) {
const fhe = new FullyHomomorphicEncryptionClient({});
await fhe.connect();
const UploadedPublicKey = fhe.seal.PublicKey();
UploadedPublicKey.load(fhe.context, workerData.publicKey);
fhe.keys.public = UploadedPublicKey;
const asyncFn = fhe.compile(
\`async function handler(state, event) {
${handler}
}\`);
const res = await fhe.compute(asyncFn, state, event);
return res;
}`;
const publicKey = (_b = (_a = event === null || event === void 0 ? void 0 : event[modelConfig.fhe_public_key_field]) !== null && _a !== void 0 ? _a : state === null || state === void 0 ? void 0 : state[modelConfig.fhe_public_key_field]) !== null && _b !== void 0 ? _b : modelConfig.fhe_public_key_field;
const res = await thread(script, state, event, {
publicKey,
});
return res;
}
async function thread(script, state, event, extra) {
return new Promise((resolve, reject) => {
let result;
const workerScript = `
const { parentPort, workerData } = require('worker_threads');
${script}
async function main() {
const res = await handler(workerData.state, workerData.event);
parentPort.postMessage(JSON.stringify(res));
}
main().catch((err) => {
throw err;
});
`;
const thread = new worker_threads_1.Worker(workerScript, {
workerData: {
...extra,
state,
event,
},
eval: true,
});
thread.on('error', (err) => {
reject(err);
});
thread.on('exit', () => {
resolve(result);
});
thread.on('message', (msg) => {
result = JSON.parse(msg);
});
});
}
//# sourceMappingURL=handler.js.map