@celljs/ta-gateway 0.0.0-stage → 4.9.1
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.
- package/README.en.md +80 -0
- package/README.md +79 -2
- package/esm/node/command-sandbox.d.ts +28 -0
- package/esm/node/command-sandbox.js +83 -0
- package/esm/node/docker-engine.d.ts +56 -0
- package/esm/node/docker-engine.js +151 -0
- package/esm/node/docker-sandbox.d.ts +45 -0
- package/esm/node/docker-sandbox.js +110 -0
- package/esm/node/environments.d.ts +68 -0
- package/esm/node/environments.js +237 -0
- package/esm/node/gateway-cli.d.ts +9 -0
- package/esm/node/gateway-cli.js +99 -0
- package/esm/node/gateway-server.d.ts +67 -0
- package/esm/node/gateway-server.js +288 -0
- package/esm/node/gateway-service.d.ts +58 -0
- package/esm/node/gateway-service.js +187 -0
- package/esm/node/gateway-socket.d.ts +33 -0
- package/esm/node/gateway-socket.js +143 -0
- package/esm/node/index.d.ts +13 -0
- package/esm/node/index.js +14 -0
- package/esm/node/local-sandbox.d.ts +23 -0
- package/esm/node/local-sandbox.js +73 -0
- package/esm/node/sandbox-provider.d.ts +72 -0
- package/esm/node/sandbox-provider.js +83 -0
- package/esm/node/sign-in-links.d.ts +25 -0
- package/esm/node/sign-in-links.js +44 -0
- package/esm/node/ta-sandbox.d.ts +23 -0
- package/esm/node/ta-sandbox.js +47 -0
- package/esm/node/tenant-store.d.ts +36 -0
- package/esm/node/tenant-store.js +83 -0
- package/esm/package.json +3 -0
- package/lib/node/command-sandbox.d.ts +29 -0
- package/lib/node/command-sandbox.js +87 -0
- package/lib/node/docker-engine.d.ts +57 -0
- package/lib/node/docker-engine.js +156 -0
- package/lib/node/docker-sandbox.d.ts +46 -0
- package/lib/node/docker-sandbox.js +114 -0
- package/lib/node/environments.d.ts +69 -0
- package/lib/node/environments.js +242 -0
- package/lib/node/gateway-cli.d.ts +10 -0
- package/lib/node/gateway-cli.js +102 -0
- package/lib/node/gateway-server.d.ts +68 -0
- package/lib/node/gateway-server.js +292 -0
- package/lib/node/gateway-service.d.ts +59 -0
- package/lib/node/gateway-service.js +192 -0
- package/lib/node/gateway-socket.d.ts +34 -0
- package/lib/node/gateway-socket.js +147 -0
- package/lib/node/index.d.ts +14 -0
- package/lib/node/index.js +30 -0
- package/lib/node/local-sandbox.d.ts +24 -0
- package/lib/node/local-sandbox.js +77 -0
- package/lib/node/sandbox-provider.d.ts +73 -0
- package/lib/node/sandbox-provider.js +87 -0
- package/lib/node/sign-in-links.d.ts +26 -0
- package/lib/node/sign-in-links.js +48 -0
- package/lib/node/ta-sandbox.d.ts +24 -0
- package/lib/node/ta-sandbox.js +51 -0
- package/lib/node/tenant-store.d.ts +37 -0
- package/lib/node/tenant-store.js +88 -0
- package/package.json +57 -4
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { chmodSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
/** Files written whole or not at all, readable by this user only. */
|
|
5
|
+
export function writePrivate(file, data) {
|
|
6
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
7
|
+
writeFileSync(temporary, JSON.stringify(data, undefined, 2), { mode: 0o600 });
|
|
8
|
+
chmodSync(temporary, 0o600);
|
|
9
|
+
renameSync(temporary, file);
|
|
10
|
+
}
|
|
11
|
+
export var TenantUtil;
|
|
12
|
+
(function (TenantUtil) {
|
|
13
|
+
/** Stable, and fit for the names of containers and volumes. */
|
|
14
|
+
function id(account) {
|
|
15
|
+
return createHash('sha256').update(account).digest('hex').slice(0, 16);
|
|
16
|
+
}
|
|
17
|
+
TenantUtil.id = id;
|
|
18
|
+
})(TenantUtil || (TenantUtil = {}));
|
|
19
|
+
/** `<gateway>/tenants/<id>.json`, one per account, made on its first sign-in. */
|
|
20
|
+
export class TenantStore {
|
|
21
|
+
constructor(root) {
|
|
22
|
+
this.cache = new Map();
|
|
23
|
+
this.dir = join(root, 'tenants');
|
|
24
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
25
|
+
}
|
|
26
|
+
get(id) {
|
|
27
|
+
if (!/^[0-9a-f]{16}$/.test(id)) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
let tenant = this.cache.get(id);
|
|
31
|
+
if (!tenant) {
|
|
32
|
+
try {
|
|
33
|
+
tenant = JSON.parse(readFileSync(join(this.dir, `${id}.json`), 'utf8'));
|
|
34
|
+
this.cache.set(id, tenant);
|
|
35
|
+
}
|
|
36
|
+
catch (_a) {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return tenant;
|
|
41
|
+
}
|
|
42
|
+
/** The tenant of the account, made when it has none. */
|
|
43
|
+
ensure(account, now = Date.now()) {
|
|
44
|
+
const id = TenantUtil.id(account.id);
|
|
45
|
+
const known = this.get(id);
|
|
46
|
+
if (known) {
|
|
47
|
+
if (account.name && (known.name !== account.name || known.avatar !== account.avatar)) {
|
|
48
|
+
return this.update(id, { name: account.name, avatar: account.avatar });
|
|
49
|
+
}
|
|
50
|
+
return known;
|
|
51
|
+
}
|
|
52
|
+
const tenant = {
|
|
53
|
+
id,
|
|
54
|
+
account: account.id,
|
|
55
|
+
name: account.name,
|
|
56
|
+
avatar: account.avatar,
|
|
57
|
+
token: randomBytes(32).toString('base64url'),
|
|
58
|
+
createdAt: now,
|
|
59
|
+
};
|
|
60
|
+
this.save(tenant);
|
|
61
|
+
return tenant;
|
|
62
|
+
}
|
|
63
|
+
update(id, change) {
|
|
64
|
+
const tenant = this.get(id);
|
|
65
|
+
if (!tenant) {
|
|
66
|
+
throw new Error(`No tenant ${id}`);
|
|
67
|
+
}
|
|
68
|
+
const next = { ...tenant, ...change };
|
|
69
|
+
this.save(next);
|
|
70
|
+
return next;
|
|
71
|
+
}
|
|
72
|
+
list() {
|
|
73
|
+
return readdirSync(this.dir)
|
|
74
|
+
.filter(name => /^[0-9a-f]{16}\.json$/.test(name))
|
|
75
|
+
.map(name => this.get(name.slice(0, -5)))
|
|
76
|
+
.filter((tenant) => tenant !== undefined);
|
|
77
|
+
}
|
|
78
|
+
save(tenant) {
|
|
79
|
+
writePrivate(join(this.dir, `${tenant.id}.json`), tenant);
|
|
80
|
+
this.cache.set(tenant.id, tenant);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=tenant-store.js.map
|
package/esm/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant } from './sandbox-provider';
|
|
2
|
+
export declare namespace CommandSandboxUtil {
|
|
3
|
+
/** The last line of what `start` printed that is an address. */
|
|
4
|
+
function url(stdout: string): string | undefined;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* `command`: the sandboxes of a platform the gateway has no type for (Kubernetes, a cloud's CLI, a script),
|
|
8
|
+
* by shell commands, as pi's models.json takes an endpoint it has no provider for. Each runs with
|
|
9
|
+
* TA_TENANT_ID, TA_TENANT_ACCOUNT and TA_SERVE_TOKEN in its environment: `start` makes or starts the sandbox
|
|
10
|
+
* of the tenant, whose Ta service takes TA_SERVE_TOKEN, and prints its address last; `stop` stops it;
|
|
11
|
+
* `state` prints running, stopped or missing.
|
|
12
|
+
*/
|
|
13
|
+
export declare class CommandSandbox implements SandboxProvider {
|
|
14
|
+
readonly id: string;
|
|
15
|
+
readonly type = "command";
|
|
16
|
+
readonly name: string;
|
|
17
|
+
protected readonly commands: {
|
|
18
|
+
start: string;
|
|
19
|
+
stop?: string;
|
|
20
|
+
state?: string;
|
|
21
|
+
};
|
|
22
|
+
protected readonly env: Record<string, string>;
|
|
23
|
+
constructor(id: string, config: SandboxProviderConfig);
|
|
24
|
+
start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
|
|
25
|
+
stop(tenant: SandboxTenant): Promise<void>;
|
|
26
|
+
state(tenant: SandboxTenant): Promise<SandboxState>;
|
|
27
|
+
protected run(command: string, tenant: SandboxTenant): Promise<string>;
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=command-sandbox.d.ts.map
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CommandSandbox = exports.CommandSandboxUtil = void 0;
|
|
4
|
+
const node_child_process_1 = require("node:child_process");
|
|
5
|
+
const sandbox_provider_1 = require("./sandbox-provider");
|
|
6
|
+
const TIMEOUT_MS = 10 * 60 * 1000;
|
|
7
|
+
var CommandSandboxUtil;
|
|
8
|
+
(function (CommandSandboxUtil) {
|
|
9
|
+
/** The last line of what `start` printed that is an address. */
|
|
10
|
+
function url(stdout) {
|
|
11
|
+
var _a;
|
|
12
|
+
return (_a = stdout
|
|
13
|
+
.split('\n')
|
|
14
|
+
.map(line => line.trim())
|
|
15
|
+
.reverse()
|
|
16
|
+
.find(line => /^https?:\/\/\S+$/.test(line))) === null || _a === void 0 ? void 0 : _a.replace(/\/+$/, '');
|
|
17
|
+
}
|
|
18
|
+
CommandSandboxUtil.url = url;
|
|
19
|
+
})(CommandSandboxUtil || (exports.CommandSandboxUtil = CommandSandboxUtil = {}));
|
|
20
|
+
/**
|
|
21
|
+
* `command`: the sandboxes of a platform the gateway has no type for (Kubernetes, a cloud's CLI, a script),
|
|
22
|
+
* by shell commands, as pi's models.json takes an endpoint it has no provider for. Each runs with
|
|
23
|
+
* TA_TENANT_ID, TA_TENANT_ACCOUNT and TA_SERVE_TOKEN in its environment: `start` makes or starts the sandbox
|
|
24
|
+
* of the tenant, whose Ta service takes TA_SERVE_TOKEN, and prints its address last; `stop` stops it;
|
|
25
|
+
* `state` prints running, stopped or missing.
|
|
26
|
+
*/
|
|
27
|
+
class CommandSandbox {
|
|
28
|
+
constructor(id, config) {
|
|
29
|
+
this.id = id;
|
|
30
|
+
this.type = 'command';
|
|
31
|
+
this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', id);
|
|
32
|
+
const start = sandbox_provider_1.SandboxProviders.string(config, 'start');
|
|
33
|
+
if (!start) {
|
|
34
|
+
throw new Error(`The provider "${id}" of the type command needs "start", a command that prints the address of the Ta service.`);
|
|
35
|
+
}
|
|
36
|
+
this.commands = { start, stop: sandbox_provider_1.SandboxProviders.string(config, 'stop'), state: sandbox_provider_1.SandboxProviders.string(config, 'state') };
|
|
37
|
+
this.env = sandbox_provider_1.SandboxProviders.env(config);
|
|
38
|
+
}
|
|
39
|
+
async start(tenant) {
|
|
40
|
+
const stdout = await this.run(this.commands.start, tenant);
|
|
41
|
+
const url = CommandSandboxUtil.url(stdout);
|
|
42
|
+
if (!url) {
|
|
43
|
+
throw new Error(`"start" of the provider "${this.id}" printed no address (http:// or https://) last.`);
|
|
44
|
+
}
|
|
45
|
+
return { url, token: tenant.token };
|
|
46
|
+
}
|
|
47
|
+
async stop(tenant) {
|
|
48
|
+
if (this.commands.stop) {
|
|
49
|
+
await this.run(this.commands.stop, tenant);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async state(tenant) {
|
|
53
|
+
if (!this.commands.state) {
|
|
54
|
+
return 'missing';
|
|
55
|
+
}
|
|
56
|
+
const word = (await this.run(this.commands.state, tenant)).trim().split(/\s+/).pop();
|
|
57
|
+
return word === 'running' || word === 'stopped' ? word : 'missing';
|
|
58
|
+
}
|
|
59
|
+
run(command, tenant) {
|
|
60
|
+
return new Promise((resolve, reject) => {
|
|
61
|
+
const child = (0, node_child_process_1.spawn)('sh', ['-c', command], {
|
|
62
|
+
env: { ...process.env, ...this.env, TA_TENANT_ID: tenant.id, TA_TENANT_ACCOUNT: tenant.account, TA_SERVE_TOKEN: tenant.token },
|
|
63
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
64
|
+
});
|
|
65
|
+
let stdout = '';
|
|
66
|
+
let stderr = '';
|
|
67
|
+
child.stdout.on('data', data => (stdout += data));
|
|
68
|
+
child.stderr.on('data', data => (stderr += data));
|
|
69
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), TIMEOUT_MS);
|
|
70
|
+
child.on('error', error => {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
reject(error);
|
|
73
|
+
});
|
|
74
|
+
child.on('close', code => {
|
|
75
|
+
clearTimeout(timer);
|
|
76
|
+
if (code === 0) {
|
|
77
|
+
resolve(stdout);
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
reject(new Error(`"${command.split(/\s+/)[0]}…" of the provider "${this.id}" exited with ${code}: ${stderr.trim().slice(-300)}`));
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
exports.CommandSandbox = CommandSandbox;
|
|
87
|
+
//# sourceMappingURL=command-sandbox.js.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export declare class DockerError extends Error {
|
|
2
|
+
readonly status: number;
|
|
3
|
+
constructor(message: string, status: number);
|
|
4
|
+
}
|
|
5
|
+
export interface DockerEngineOptions {
|
|
6
|
+
/** `unix:///var/run/docker.sock` or `tcp://host:2375`: DOCKER_HOST's form; default that of DOCKER_HOST, else the socket. */
|
|
7
|
+
host?: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The Docker Engine API, as far as sandboxes need it, over its socket: no Docker CLI in the image of the
|
|
11
|
+
* gateway, nothing to install.
|
|
12
|
+
*/
|
|
13
|
+
export declare class DockerEngine {
|
|
14
|
+
protected readonly target: {
|
|
15
|
+
socketPath: string;
|
|
16
|
+
} | {
|
|
17
|
+
host: string;
|
|
18
|
+
port: number;
|
|
19
|
+
};
|
|
20
|
+
constructor(options?: DockerEngineOptions);
|
|
21
|
+
/** The answer of the Engine, parsed when it is JSON; a status of 400 and above throws. */
|
|
22
|
+
call<T = unknown>(method: string, path: string, body?: unknown, timeoutMs?: number): Promise<{
|
|
23
|
+
status: number;
|
|
24
|
+
body: T;
|
|
25
|
+
}>;
|
|
26
|
+
/** undefined for a container that is not there. */
|
|
27
|
+
inspect(name: string): Promise<DockerContainer | undefined>;
|
|
28
|
+
create(name: string, spec: object): Promise<void>;
|
|
29
|
+
/** Started, or already running (304). */
|
|
30
|
+
start(name: string): Promise<void>;
|
|
31
|
+
/** Stopped, already stopped (304) or not there (404). */
|
|
32
|
+
stop(name: string, seconds?: number): Promise<void>;
|
|
33
|
+
/** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
|
|
34
|
+
ensureNetwork(name: string, isolated: boolean): Promise<void>;
|
|
35
|
+
/** Pulled when it is not here; one built here (ta:latest) is. */
|
|
36
|
+
ensureImage(image: string): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
export interface DockerContainer {
|
|
39
|
+
Id: string;
|
|
40
|
+
State: {
|
|
41
|
+
Running: boolean;
|
|
42
|
+
Status: string;
|
|
43
|
+
};
|
|
44
|
+
NetworkSettings: {
|
|
45
|
+
Ports?: Record<string, {
|
|
46
|
+
HostIp: string;
|
|
47
|
+
HostPort: string;
|
|
48
|
+
}[] | null>;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export declare namespace DockerEngineUtil {
|
|
52
|
+
/** `ghcr.io:443/me/ta:1.0` → `ghcr.io:443/me/ta`, `1.0`: the tag after the last `:` that is past the last `/`. */
|
|
53
|
+
function splitImage(image: string): [string, string?];
|
|
54
|
+
/** `512m`, `4g`, a number of bytes: Docker's `--memory`. */
|
|
55
|
+
function bytes(value: string | number | undefined): number | undefined;
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=docker-engine.d.ts.map
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DockerEngineUtil = exports.DockerEngine = exports.DockerError = void 0;
|
|
4
|
+
const node_http_1 = require("node:http");
|
|
5
|
+
class DockerError extends Error {
|
|
6
|
+
constructor(message, status) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.status = status;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
exports.DockerError = DockerError;
|
|
12
|
+
/**
|
|
13
|
+
* The Docker Engine API, as far as sandboxes need it, over its socket: no Docker CLI in the image of the
|
|
14
|
+
* gateway, nothing to install.
|
|
15
|
+
*/
|
|
16
|
+
class DockerEngine {
|
|
17
|
+
constructor(options = {}) {
|
|
18
|
+
const host = options.host || process.env.DOCKER_HOST || 'unix:///var/run/docker.sock';
|
|
19
|
+
if (host.startsWith('unix://')) {
|
|
20
|
+
this.target = { socketPath: host.slice('unix://'.length) };
|
|
21
|
+
}
|
|
22
|
+
else if (host.startsWith('tcp://')) {
|
|
23
|
+
const url = new URL(`http://${host.slice('tcp://'.length)}`);
|
|
24
|
+
this.target = { host: url.hostname, port: Number(url.port || 2375) };
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
throw new DockerError(`${host} is not a Docker host: write unix://<socket> or tcp://<host>:<port>.`, 0);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** The answer of the Engine, parsed when it is JSON; a status of 400 and above throws. */
|
|
31
|
+
call(method, path, body, timeoutMs = 120000) {
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
const payload = body === undefined ? undefined : JSON.stringify(body);
|
|
34
|
+
const req = (0, node_http_1.request)({
|
|
35
|
+
...this.target,
|
|
36
|
+
method,
|
|
37
|
+
path,
|
|
38
|
+
headers: payload ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {},
|
|
39
|
+
timeout: timeoutMs,
|
|
40
|
+
}, res => {
|
|
41
|
+
const chunks = [];
|
|
42
|
+
res.on('data', chunk => chunks.push(chunk));
|
|
43
|
+
res.on('end', () => {
|
|
44
|
+
var _a, _b;
|
|
45
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
46
|
+
let parsed = text;
|
|
47
|
+
try {
|
|
48
|
+
parsed = text ? JSON.parse(text) : undefined;
|
|
49
|
+
}
|
|
50
|
+
catch (_c) {
|
|
51
|
+
// Streams of progress (a pull) are lines of JSON: kept as text.
|
|
52
|
+
}
|
|
53
|
+
const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
|
|
54
|
+
if (status >= 400) {
|
|
55
|
+
const message = (_b = parsed === null || parsed === void 0 ? void 0 : parsed.message) !== null && _b !== void 0 ? _b : text;
|
|
56
|
+
reject(new DockerError(`Docker: ${method} ${path.split('?')[0]} answered ${status}: ${message}`, status));
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
resolve({ status, body: parsed });
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
req.on('timeout', () => req.destroy(new DockerError(`Docker: ${method} ${path} took too long`, 0)));
|
|
64
|
+
req.on('error', error => reject(error instanceof DockerError
|
|
65
|
+
? error
|
|
66
|
+
: new DockerError(`Docker is not reachable (${'socketPath' in this.target ? this.target.socketPath : this.target.host}): ${error.message}`, 0)));
|
|
67
|
+
req.end(payload);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/** undefined for a container that is not there. */
|
|
71
|
+
async inspect(name) {
|
|
72
|
+
try {
|
|
73
|
+
return (await this.call('GET', `/containers/${encodeURIComponent(name)}/json`)).body;
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
if (error instanceof DockerError && error.status === 404) {
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async create(name, spec) {
|
|
83
|
+
await this.call('POST', `/containers/create?name=${encodeURIComponent(name)}`, spec);
|
|
84
|
+
}
|
|
85
|
+
/** Started, or already running (304). */
|
|
86
|
+
async start(name) {
|
|
87
|
+
await this.call('POST', `/containers/${encodeURIComponent(name)}/start`);
|
|
88
|
+
}
|
|
89
|
+
/** Stopped, already stopped (304) or not there (404). */
|
|
90
|
+
async stop(name, seconds = 10) {
|
|
91
|
+
try {
|
|
92
|
+
await this.call('POST', `/containers/${encodeURIComponent(name)}/stop?t=${seconds}`, undefined, (seconds + 30) * 1000);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (!(error instanceof DockerError && error.status === 404)) {
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
|
|
101
|
+
async ensureNetwork(name, isolated) {
|
|
102
|
+
try {
|
|
103
|
+
await this.call('GET', `/networks/${encodeURIComponent(name)}`);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
if (!(error instanceof DockerError && error.status === 404)) {
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const options = isolated ? { 'com.docker.network.bridge.enable_icc': 'false' } : {};
|
|
112
|
+
await this.call('POST', '/networks/create', { Name: name, Driver: 'bridge', Options: options, Labels: { 'cell.ta.gateway': '1' } });
|
|
113
|
+
}
|
|
114
|
+
/** Pulled when it is not here; one built here (ta:latest) is. */
|
|
115
|
+
async ensureImage(image) {
|
|
116
|
+
try {
|
|
117
|
+
await this.call('GET', `/images/${encodeURIComponent(image)}/json`);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (!(error instanceof DockerError && error.status === 404)) {
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const [repository, tag = 'latest'] = DockerEngineUtil.splitImage(image);
|
|
126
|
+
await this.call('POST', `/images/create?fromImage=${encodeURIComponent(repository)}&tag=${encodeURIComponent(tag)}`, undefined, 30 * 60 * 1000);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
exports.DockerEngine = DockerEngine;
|
|
130
|
+
var DockerEngineUtil;
|
|
131
|
+
(function (DockerEngineUtil) {
|
|
132
|
+
/** `ghcr.io:443/me/ta:1.0` → `ghcr.io:443/me/ta`, `1.0`: the tag after the last `:` that is past the last `/`. */
|
|
133
|
+
function splitImage(image) {
|
|
134
|
+
const slash = image.lastIndexOf('/');
|
|
135
|
+
const colon = image.lastIndexOf(':');
|
|
136
|
+
return colon > slash ? [image.slice(0, colon), image.slice(colon + 1)] : [image];
|
|
137
|
+
}
|
|
138
|
+
DockerEngineUtil.splitImage = splitImage;
|
|
139
|
+
/** `512m`, `4g`, a number of bytes: Docker's `--memory`. */
|
|
140
|
+
function bytes(value) {
|
|
141
|
+
if (value === undefined || value === '') {
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
if (typeof value === 'number') {
|
|
145
|
+
return value;
|
|
146
|
+
}
|
|
147
|
+
const match = /^(\d+(?:\.\d+)?)\s*([kmg]?)b?$/i.exec(value.trim());
|
|
148
|
+
if (!match) {
|
|
149
|
+
throw new DockerError(`${value} is not an amount of memory: write 512m or 4g.`, 0);
|
|
150
|
+
}
|
|
151
|
+
const unit = { '': 1, k: 1024, m: 1024 ** 2, g: 1024 ** 3 }[match[2].toLowerCase()];
|
|
152
|
+
return Math.round(Number(match[1]) * unit);
|
|
153
|
+
}
|
|
154
|
+
DockerEngineUtil.bytes = bytes;
|
|
155
|
+
})(DockerEngineUtil || (exports.DockerEngineUtil = DockerEngineUtil = {}));
|
|
156
|
+
//# sourceMappingURL=docker-engine.js.map
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { DockerEngine } from './docker-engine';
|
|
2
|
+
import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant } from './sandbox-provider';
|
|
3
|
+
export declare namespace DockerSandboxUtil {
|
|
4
|
+
/** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
|
|
5
|
+
function hostname(account: string): string;
|
|
6
|
+
}
|
|
7
|
+
export interface DockerSandboxOptions {
|
|
8
|
+
/** The image of Ta: default `ta:latest`, built from apps/ta/Dockerfile. */
|
|
9
|
+
image: string;
|
|
10
|
+
/** DOCKER_HOST's form; default DOCKER_HOST, else /var/run/docker.sock. */
|
|
11
|
+
host?: string;
|
|
12
|
+
/** Each sandbox at most: `--memory`, `--cpus`, `--pids-limit`. */
|
|
13
|
+
memory?: number;
|
|
14
|
+
cpus?: number;
|
|
15
|
+
pids?: number;
|
|
16
|
+
/** A network of the sandboxes, whose containers cannot reach each other. */
|
|
17
|
+
network: string;
|
|
18
|
+
/** Where the port of each sandbox is published, and where the gateway reaches it. */
|
|
19
|
+
bind: string;
|
|
20
|
+
address: string;
|
|
21
|
+
/** Names of containers and volumes: `<prefix><tenant>`. */
|
|
22
|
+
prefix: string;
|
|
23
|
+
/** More of the environment of every sandbox, such as a proxy. */
|
|
24
|
+
env: Record<string, string>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* `docker`: a container per tenant, its home (sessions, model accounts, workspace) in a volume of its own,
|
|
28
|
+
* with limits of memory, CPU and processes, in a network where sandboxes cannot reach each other. Its port is
|
|
29
|
+
* published on `bind` only (127.0.0.1): the gateway is the way in.
|
|
30
|
+
*/
|
|
31
|
+
export declare class DockerSandbox implements SandboxProvider {
|
|
32
|
+
readonly id: string;
|
|
33
|
+
protected readonly options: DockerSandboxOptions;
|
|
34
|
+
readonly type = "docker";
|
|
35
|
+
readonly name: string;
|
|
36
|
+
protected readonly engine: DockerEngine;
|
|
37
|
+
static options(config: SandboxProviderConfig): DockerSandboxOptions;
|
|
38
|
+
constructor(id: string, config: SandboxProviderConfig, options?: DockerSandboxOptions, engine?: DockerEngine);
|
|
39
|
+
start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
|
|
40
|
+
stop(tenant: SandboxTenant): Promise<void>;
|
|
41
|
+
state(tenant: SandboxTenant): Promise<SandboxState>;
|
|
42
|
+
/** What `docker run` would be given. */
|
|
43
|
+
spec(tenant: SandboxTenant): object;
|
|
44
|
+
protected containerName(tenant: SandboxTenant): string;
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=docker-sandbox.d.ts.map
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DockerSandbox = exports.DockerSandboxUtil = void 0;
|
|
4
|
+
const docker_engine_1 = require("./docker-engine");
|
|
5
|
+
const sandbox_provider_1 = require("./sandbox-provider");
|
|
6
|
+
var DockerSandboxUtil;
|
|
7
|
+
(function (DockerSandboxUtil) {
|
|
8
|
+
/** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
|
|
9
|
+
function hostname(account) {
|
|
10
|
+
const name = account
|
|
11
|
+
.slice(account.indexOf(':') + 1)
|
|
12
|
+
.split('@')[0]
|
|
13
|
+
.toLowerCase()
|
|
14
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
15
|
+
.replace(/^-+|-+$/g, '')
|
|
16
|
+
.slice(0, 48)
|
|
17
|
+
.replace(/-+$/, '');
|
|
18
|
+
return name || 'ta';
|
|
19
|
+
}
|
|
20
|
+
DockerSandboxUtil.hostname = hostname;
|
|
21
|
+
})(DockerSandboxUtil || (exports.DockerSandboxUtil = DockerSandboxUtil = {}));
|
|
22
|
+
/** The port of ta serve in the image (its Dockerfile). */
|
|
23
|
+
const PORT = '4100/tcp';
|
|
24
|
+
/**
|
|
25
|
+
* `docker`: a container per tenant, its home (sessions, model accounts, workspace) in a volume of its own,
|
|
26
|
+
* with limits of memory, CPU and processes, in a network where sandboxes cannot reach each other. Its port is
|
|
27
|
+
* published on `bind` only (127.0.0.1): the gateway is the way in.
|
|
28
|
+
*/
|
|
29
|
+
class DockerSandbox {
|
|
30
|
+
static options(config) {
|
|
31
|
+
var _a;
|
|
32
|
+
const number = (key, fallback) => {
|
|
33
|
+
var _a;
|
|
34
|
+
const value = (_a = config[key]) !== null && _a !== void 0 ? _a : fallback;
|
|
35
|
+
if (typeof value !== 'number' || value < 0) {
|
|
36
|
+
throw new Error(`"${key}" of a provider of the type docker is a number.`);
|
|
37
|
+
}
|
|
38
|
+
return value || undefined;
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
image: sandbox_provider_1.SandboxProviders.string(config, 'image', 'ta:latest'),
|
|
42
|
+
host: sandbox_provider_1.SandboxProviders.string(config, 'host'),
|
|
43
|
+
memory: docker_engine_1.DockerEngineUtil.bytes((_a = config.memory) !== null && _a !== void 0 ? _a : '4g'),
|
|
44
|
+
cpus: number('cpus', 2),
|
|
45
|
+
pids: number('pids', 1024),
|
|
46
|
+
network: sandbox_provider_1.SandboxProviders.string(config, 'network', 'ta-sandbox'),
|
|
47
|
+
bind: sandbox_provider_1.SandboxProviders.string(config, 'bind', '127.0.0.1'),
|
|
48
|
+
address: sandbox_provider_1.SandboxProviders.string(config, 'address', '127.0.0.1'),
|
|
49
|
+
prefix: sandbox_provider_1.SandboxProviders.string(config, 'prefix', 'ta-'),
|
|
50
|
+
env: sandbox_provider_1.SandboxProviders.env(config),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
constructor(id, config, options = DockerSandbox.options(config), engine) {
|
|
54
|
+
this.id = id;
|
|
55
|
+
this.options = options;
|
|
56
|
+
this.type = 'docker';
|
|
57
|
+
this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', 'Docker');
|
|
58
|
+
this.engine = engine !== null && engine !== void 0 ? engine : new docker_engine_1.DockerEngine({ host: options.host });
|
|
59
|
+
}
|
|
60
|
+
async start(tenant) {
|
|
61
|
+
var _a, _b, _c;
|
|
62
|
+
const name = this.containerName(tenant);
|
|
63
|
+
let container = await this.engine.inspect(name);
|
|
64
|
+
if (!container) {
|
|
65
|
+
await this.engine.ensureImage(this.options.image);
|
|
66
|
+
await this.engine.ensureNetwork(this.options.network, true);
|
|
67
|
+
await this.engine.create(name, this.spec(tenant));
|
|
68
|
+
container = await this.engine.inspect(name);
|
|
69
|
+
}
|
|
70
|
+
if (!(container === null || container === void 0 ? void 0 : container.State.Running)) {
|
|
71
|
+
await this.engine.start(name);
|
|
72
|
+
container = await this.engine.inspect(name);
|
|
73
|
+
}
|
|
74
|
+
const port = (_c = (_b = (_a = container === null || container === void 0 ? void 0 : container.NetworkSettings.Ports) === null || _a === void 0 ? void 0 : _a[PORT]) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.HostPort;
|
|
75
|
+
if (!port) {
|
|
76
|
+
throw new Error(`The container ${name} publishes no port for ${PORT}.`);
|
|
77
|
+
}
|
|
78
|
+
return { url: `http://${this.options.address}:${port}`, token: tenant.token };
|
|
79
|
+
}
|
|
80
|
+
async stop(tenant) {
|
|
81
|
+
await this.engine.stop(this.containerName(tenant));
|
|
82
|
+
}
|
|
83
|
+
async state(tenant) {
|
|
84
|
+
const container = await this.engine.inspect(this.containerName(tenant));
|
|
85
|
+
return !container ? 'missing' : container.State.Running ? 'running' : 'stopped';
|
|
86
|
+
}
|
|
87
|
+
/** What `docker run` would be given. */
|
|
88
|
+
spec(tenant) {
|
|
89
|
+
const name = this.containerName(tenant);
|
|
90
|
+
return {
|
|
91
|
+
Image: this.options.image,
|
|
92
|
+
// What the Ta of the tenant tells its clients its machine is, as the list of computers of the phone shows it.
|
|
93
|
+
Hostname: DockerSandboxUtil.hostname(tenant.account),
|
|
94
|
+
Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries(this.options.env).map(([key, value]) => `${key}=${value}`)],
|
|
95
|
+
Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account },
|
|
96
|
+
ExposedPorts: { [PORT]: {} },
|
|
97
|
+
HostConfig: {
|
|
98
|
+
PortBindings: { [PORT]: [{ HostIp: this.options.bind, HostPort: '' }] },
|
|
99
|
+
Mounts: [{ Type: 'volume', Source: name, Target: '/home/ta' }],
|
|
100
|
+
NetworkMode: this.options.network,
|
|
101
|
+
Memory: this.options.memory,
|
|
102
|
+
NanoCpus: this.options.cpus ? Math.round(this.options.cpus * 1e9) : undefined,
|
|
103
|
+
PidsLimit: this.options.pids,
|
|
104
|
+
RestartPolicy: { Name: 'unless-stopped' },
|
|
105
|
+
Init: false,
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
containerName(tenant) {
|
|
110
|
+
return `${this.options.prefix}${tenant.id}`;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
exports.DockerSandbox = DockerSandbox;
|
|
114
|
+
//# sourceMappingURL=docker-sandbox.js.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { type TaEnvironmentChoice, type TaEnvironmentInfo, type TaEnvironmentOption, type TaEnvironmentStatus } from '@celljs/ta-protocol';
|
|
2
|
+
import type { SandboxEndpoint, SandboxProvider, SandboxTenant } from './sandbox-provider';
|
|
3
|
+
import type { Tenant, TenantStore } from './tenant-store';
|
|
4
|
+
interface Running {
|
|
5
|
+
status: TaEnvironmentStatus;
|
|
6
|
+
error?: string;
|
|
7
|
+
endpoint?: SandboxEndpoint;
|
|
8
|
+
starting?: Promise<SandboxEndpoint>;
|
|
9
|
+
connections: number;
|
|
10
|
+
idle?: ReturnType<typeof setTimeout>;
|
|
11
|
+
}
|
|
12
|
+
export declare class EnvironmentError extends Error {
|
|
13
|
+
}
|
|
14
|
+
export declare namespace EnvironmentsUtil {
|
|
15
|
+
/** Whether a Ta service answers at `url`, whatever it answers. */
|
|
16
|
+
function waitReady(url: string, timeoutMs?: number, fetcher?: typeof fetch): Promise<void>;
|
|
17
|
+
/** One call of the Ta service at `endpoint` over a WebSocket of its own: the gateway's, not a browser's. */
|
|
18
|
+
function call<T>(endpoint: SandboxEndpoint, method: string, params?: unknown[], timeoutMs?: number): Promise<T>;
|
|
19
|
+
function sandboxTenant(tenant: Tenant): SandboxTenant;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The environments of the tenants: which provider runs each, starting it on its first connection (once,
|
|
23
|
+
* whoever asks meanwhile), and stopping it when nobody has been connected for `idleMinutes`.
|
|
24
|
+
*/
|
|
25
|
+
export declare class Environments {
|
|
26
|
+
readonly providers: SandboxProvider[];
|
|
27
|
+
protected readonly tenants: TenantStore;
|
|
28
|
+
readonly settings: {
|
|
29
|
+
default?: string;
|
|
30
|
+
own: boolean;
|
|
31
|
+
idleMinutes: number;
|
|
32
|
+
readyTimeoutMs?: number;
|
|
33
|
+
};
|
|
34
|
+
protected readonly running: Map<string, Running>;
|
|
35
|
+
constructor(providers: SandboxProvider[], tenants: TenantStore, settings: {
|
|
36
|
+
default?: string;
|
|
37
|
+
own: boolean;
|
|
38
|
+
idleMinutes: number;
|
|
39
|
+
readyTimeoutMs?: number;
|
|
40
|
+
});
|
|
41
|
+
/** The providers one may pick. */
|
|
42
|
+
choices(): TaEnvironmentOption[];
|
|
43
|
+
/** The provider of a tenant: its own Ta service, the one it picked, or the default. */
|
|
44
|
+
provider(tenant: Tenant): {
|
|
45
|
+
provider: SandboxProvider;
|
|
46
|
+
own: boolean;
|
|
47
|
+
};
|
|
48
|
+
info(tenant: Tenant): TaEnvironmentInfo;
|
|
49
|
+
connections(tenantId: string): number;
|
|
50
|
+
/** Where the Ta of the tenant answers, started when it does not run. */
|
|
51
|
+
ensure(tenant: Tenant): Promise<SandboxEndpoint>;
|
|
52
|
+
/** The sandbox of the tenant answered no more (its connection dropped): looked for again on the next. */
|
|
53
|
+
lost(tenantId: string): void;
|
|
54
|
+
connect(tenantId: string): () => void;
|
|
55
|
+
/** Its connections are the caller's to close: they would only find the sandbox gone. */
|
|
56
|
+
stop(tenantId: string): Promise<void>;
|
|
57
|
+
/**
|
|
58
|
+
* The account of the tenant is no longer let in: the devices paired with its Ta (`ta pair`, which reach it
|
|
59
|
+
* through a relay, not the gateway) are unpaired, and its sandbox is stopped. A Ta service of the user's
|
|
60
|
+
* is theirs: left as it is.
|
|
61
|
+
*/
|
|
62
|
+
revoke(tenant: Tenant): Promise<number>;
|
|
63
|
+
/** Another environment for the tenant: the one before is stopped (a service of the user's is left as it is); its connections are the caller's to close. */
|
|
64
|
+
change(tenant: Tenant, choice: TaEnvironmentChoice | undefined): Promise<Tenant>;
|
|
65
|
+
dispose(): Promise<void>;
|
|
66
|
+
protected state(tenantId: string): Running;
|
|
67
|
+
}
|
|
68
|
+
export {};
|
|
69
|
+
//# sourceMappingURL=environments.d.ts.map
|