cerevox
Version:
TypeScript SDK for browser automation and secure command execution in highly available and scalable micro computer environments
157 lines • 5.96 kB
JavaScript
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Sandbox = exports.ADMIN_HOST = void 0;
exports.createSandbox = createSandbox;
exports.connectSandbox = connectSandbox;
const base_1 = require("./base");
const constants_1 = require("../utils/constants");
exports.ADMIN_HOST = 'sd2mfo025ni4n75n9r5p0.apigateway-cn-beijing.volceapi.com';
let Sandbox = class Sandbox extends base_1.BaseClass {
constructor(token, logger, timeout = 60, keepAliveMS = 5000, metadata) {
super(logger.level);
this.token = token;
this.timeout = timeout;
this.keepAliveMS = keepAliveMS;
this.metadata = metadata;
this.id = null;
this.host = 'sd2lum427399ulo39js70.apigateway-cn-beijing.volceapi.com';
this.headers = {};
}
get workspace() {
return this.token.slice(3, 19);
}
async connect(sandboxId) {
this.id = sandboxId;
const isRunning = await this.isRunning();
if (!isRunning) {
// await this.init(); // create new
throw new Error(`Sandbox ${sandboxId} is not running`);
}
}
async init() {
const adminUrl = `https://${exports.ADMIN_HOST}/create`;
// eslint-disable-next-line custom/no-fetch-in-src
const res = await fetch(adminUrl, {
method: 'POST',
body: JSON.stringify({
timeout: this.timeout,
token: this.token,
metadata: this.metadata,
}),
});
if (res.status !== 200) {
throw new Error(`Failed to create sandbox: ${await res.text()}`);
}
const data = await res.json();
if (data.SandboxId) {
this.id = data.SandboxId;
this.logger.info(`Sandbox created: ${this.id}`);
return this.id;
}
throw new Error(`Failed to create sandbox: ${JSON.stringify(data)}`);
}
get sandboxId() {
return this.id;
}
async request(url, options = {}) {
if (url.startsWith('http')) {
const urlObj = new URL(url);
if (urlObj.hostname !== this.host) {
throw new Error(`Hostname must be ${this.host}`);
}
url = urlObj.pathname;
}
const opts = {
...options,
headers: {
...this.headers,
...options.headers,
'x-faas-instance-name': this.id,
'x-workspace': this.workspace,
},
};
this.logger.debug(`Request: https://${this.host}${url} ${JSON.stringify(opts)}`);
// eslint-disable-next-line custom/no-fetch-in-src
return fetch(`https://${this.host}${url}`, opts);
}
getUrl(path = '/') {
const url = new URL(path, `https://${this.host}`);
url.searchParams.append('faasInstanceName', this.id);
return url.toString();
}
getProxyHost(port, proxyDomain = 'cerevox.run') {
const sandbox_id = this.id.replace(/vefaas-.*?-/, '').replace(/-sandbox$/, '');
return `${port}-${sandbox_id}.${proxyDomain}`;
}
async isRunning() {
if (!this.id) {
return false;
}
try {
const res = await this.request(`/health`);
return res.ok;
}
catch (error) {
return false;
}
}
async kill() {
if (!this.id) {
return;
}
const adminUrl = `https://${exports.ADMIN_HOST}/delete`;
// eslint-disable-next-line custom/no-fetch-in-src
const res = await fetch(adminUrl, {
method: 'POST',
body: JSON.stringify({
token: this.token,
sandboxId: this.id,
}),
});
if (res.status !== 200) {
throw new Error(`Failed to kill sandbox: ${await res.text()}`);
}
this.logger.info(`Sandbox killed: ${this.id}`);
}
async setTimeout(timeout) {
this.timeout = timeout;
const adminUrl = `https://${exports.ADMIN_HOST}/timeout`;
// eslint-disable-next-line custom/no-fetch-in-src
const res = await fetch(adminUrl, {
method: 'POST',
body: JSON.stringify({
token: this.token,
sandboxId: this.id,
timeout,
}),
});
if (res.status !== 200) {
throw new Error(`Failed to set timeout: ${await res.text()}`);
}
}
};
exports.Sandbox = Sandbox;
exports.Sandbox = Sandbox = __decorate([
(0, base_1.Logger)({ VERSION: constants_1.VERSION }),
__metadata("design:paramtypes", [String, Object, Number, Number, Object])
], Sandbox);
async function createSandbox(token, logger, timeout = 20, keepAliveMS = 5000, metadata) {
const sandbox = new Sandbox(token, logger, timeout, keepAliveMS, metadata);
await sandbox.init();
return sandbox;
}
async function connectSandbox(token, logger, sandboxId, keepAliveMS = 5000) {
const sandbox = new Sandbox(token, logger, 0, keepAliveMS);
await sandbox.connect(sandboxId);
return sandbox;
}
//# sourceMappingURL=sandbox.js.map