@celljs/ta-gateway 4.15.0 → 4.15.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.
- package/esm/node/command-sandbox.d.ts +5 -2
- package/esm/node/command-sandbox.js +17 -4
- package/esm/node/docker-engine.d.ts +45 -0
- package/esm/node/docker-engine.js +87 -11
- package/esm/node/docker-sandbox.d.ts +3 -1
- package/esm/node/docker-sandbox.js +6 -0
- package/esm/node/environments.d.ts +34 -2
- package/esm/node/environments.js +187 -11
- package/esm/node/gateway-audit.d.ts +12 -0
- package/esm/node/gateway-audit.js +47 -0
- package/esm/node/gateway-cli.d.ts +2 -0
- package/esm/node/gateway-cli.js +1 -0
- package/esm/node/gateway-policy.d.ts +46 -0
- package/esm/node/gateway-policy.js +151 -0
- package/esm/node/gateway-quotas.d.ts +32 -0
- package/esm/node/gateway-quotas.js +104 -0
- package/esm/node/gateway-server.d.ts +16 -1
- package/esm/node/gateway-server.js +58 -6
- package/esm/node/gateway-service.d.ts +91 -16
- package/esm/node/gateway-service.js +366 -45
- package/esm/node/gateway-socket.d.ts +7 -1
- package/esm/node/gateway-socket.js +40 -1
- package/esm/node/gateway-usage.d.ts +37 -0
- package/esm/node/gateway-usage.js +137 -0
- package/esm/node/local-sandbox.d.ts +12 -0
- package/esm/node/local-sandbox.js +36 -1
- package/esm/node/sandbox-provider.d.ts +10 -0
- package/esm/node/tenant-store.d.ts +12 -1
- package/lib/node/command-sandbox.d.ts +5 -2
- package/lib/node/command-sandbox.js +17 -4
- package/lib/node/docker-engine.d.ts +45 -0
- package/lib/node/docker-engine.js +87 -11
- package/lib/node/docker-sandbox.d.ts +3 -1
- package/lib/node/docker-sandbox.js +6 -0
- package/lib/node/environments.d.ts +34 -2
- package/lib/node/environments.js +186 -10
- package/lib/node/gateway-audit.d.ts +13 -0
- package/lib/node/gateway-audit.js +51 -0
- package/lib/node/gateway-cli.d.ts +2 -0
- package/lib/node/gateway-cli.js +1 -0
- package/lib/node/gateway-policy.d.ts +47 -0
- package/lib/node/gateway-policy.js +156 -0
- package/lib/node/gateway-quotas.d.ts +33 -0
- package/lib/node/gateway-quotas.js +108 -0
- package/lib/node/gateway-server.d.ts +16 -1
- package/lib/node/gateway-server.js +58 -6
- package/lib/node/gateway-service.d.ts +91 -16
- package/lib/node/gateway-service.js +365 -44
- package/lib/node/gateway-socket.d.ts +7 -1
- package/lib/node/gateway-socket.js +40 -1
- package/lib/node/gateway-usage.d.ts +38 -0
- package/lib/node/gateway-usage.js +141 -0
- package/lib/node/local-sandbox.d.ts +12 -0
- package/lib/node/local-sandbox.js +38 -2
- package/lib/node/sandbox-provider.d.ts +10 -0
- package/lib/node/tenant-store.d.ts +12 -1
- package/package.json +4 -4
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { writePrivate } from './tenant-store.js';
|
|
4
|
+
const HOUR = 3600000;
|
|
5
|
+
const DAY = 24 * HOUR;
|
|
6
|
+
/** Kept of each tenant: a month, whatever day of it. */
|
|
7
|
+
const KEPT_DAYS = 32;
|
|
8
|
+
/** A tenant's usage is asked again at most this often. */
|
|
9
|
+
const FRESH_MS = 60000;
|
|
10
|
+
export var GatewayUsageUtil;
|
|
11
|
+
(function (GatewayUsageUtil) {
|
|
12
|
+
GatewayUsageUtil.KEEP_MS = KEPT_DAYS * DAY;
|
|
13
|
+
/** The start of the month of UTC of `now`, and of the next. */
|
|
14
|
+
function month(now) {
|
|
15
|
+
const date = new Date(now);
|
|
16
|
+
const start = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1);
|
|
17
|
+
const next = Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1);
|
|
18
|
+
return { key: new Date(start).toISOString().slice(0, 7), start, next };
|
|
19
|
+
}
|
|
20
|
+
GatewayUsageUtil.month = month;
|
|
21
|
+
function tokens(bucket) {
|
|
22
|
+
return bucket.input + bucket.output + bucket.cacheRead + bucket.cacheWrite;
|
|
23
|
+
}
|
|
24
|
+
GatewayUsageUtil.tokens = tokens;
|
|
25
|
+
/** The buckets of tenants since `since`: by hour, by model and by tenant. */
|
|
26
|
+
function trend(byTenant, since, stale, now) {
|
|
27
|
+
var _a, _b;
|
|
28
|
+
const hours = new Map();
|
|
29
|
+
const models = new Map();
|
|
30
|
+
const tenants = [];
|
|
31
|
+
for (const [tenantId, buckets] of byTenant) {
|
|
32
|
+
const share = { tenantId, tokens: 0, cost: 0, turns: 0 };
|
|
33
|
+
for (const bucket of buckets) {
|
|
34
|
+
if (bucket.at + HOUR <= since) {
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const count = tokens(bucket);
|
|
38
|
+
const hour = (_a = hours.get(bucket.at)) !== null && _a !== void 0 ? _a : { at: bucket.at, input: 0, output: 0, tokens: 0, cost: 0, turns: 0 };
|
|
39
|
+
hour.input += bucket.input;
|
|
40
|
+
hour.output += bucket.output;
|
|
41
|
+
hour.tokens += count;
|
|
42
|
+
hour.cost += bucket.cost;
|
|
43
|
+
hour.turns += bucket.turns;
|
|
44
|
+
hours.set(bucket.at, hour);
|
|
45
|
+
const model = (_b = models.get(bucket.model)) !== null && _b !== void 0 ? _b : { model: bucket.model, tokens: 0, cost: 0, turns: 0 };
|
|
46
|
+
model.tokens += count;
|
|
47
|
+
model.cost += bucket.cost;
|
|
48
|
+
model.turns += bucket.turns;
|
|
49
|
+
models.set(bucket.model, model);
|
|
50
|
+
share.tokens += count;
|
|
51
|
+
share.cost += bucket.cost;
|
|
52
|
+
share.turns += bucket.turns;
|
|
53
|
+
}
|
|
54
|
+
if (share.turns > 0) {
|
|
55
|
+
tenants.push(share);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
since,
|
|
60
|
+
hours: [...hours.values()].sort((a, b) => a.at - b.at),
|
|
61
|
+
byModel: [...models.values()].sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
|
|
62
|
+
byTenant: tenants.sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
|
|
63
|
+
stale,
|
|
64
|
+
readAt: now,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
GatewayUsageUtil.trend = trend;
|
|
68
|
+
})(GatewayUsageUtil || (GatewayUsageUtil = {}));
|
|
69
|
+
/**
|
|
70
|
+
* What the agents of each tenant took, by hour, as its Ta said last (TaUsageServer): asked of a running sandbox
|
|
71
|
+
* at most once a minute, kept in `usage/<tenant>.json` so that one stopped still counts.
|
|
72
|
+
*/
|
|
73
|
+
export class GatewayUsage {
|
|
74
|
+
constructor(root) {
|
|
75
|
+
this.kept = new Map();
|
|
76
|
+
this.reading = new Map();
|
|
77
|
+
this.dir = join(root, 'usage');
|
|
78
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
79
|
+
}
|
|
80
|
+
/** What is kept of the tenant. */
|
|
81
|
+
get(tenantId) {
|
|
82
|
+
let kept = this.kept.get(tenantId);
|
|
83
|
+
if (!kept && /^[0-9a-f]{16}$/.test(tenantId)) {
|
|
84
|
+
try {
|
|
85
|
+
kept = JSON.parse(readFileSync(join(this.dir, `${tenantId}.json`), 'utf8'));
|
|
86
|
+
this.kept.set(tenantId, kept);
|
|
87
|
+
}
|
|
88
|
+
catch (_a) {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return kept;
|
|
93
|
+
}
|
|
94
|
+
/** Asks the tenant's Ta again, unless it was asked within `maxAge` (a minute); `read` undefined: it does not run. */
|
|
95
|
+
async refresh(tenantId, read, now = Date.now(), maxAge = FRESH_MS) {
|
|
96
|
+
const kept = this.get(tenantId);
|
|
97
|
+
if (!read) {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
if (kept && now - kept.readAt < maxAge) {
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
let reading = this.reading.get(tenantId);
|
|
104
|
+
if (!reading) {
|
|
105
|
+
reading = read(now - GatewayUsageUtil.KEEP_MS).then(buckets => {
|
|
106
|
+
const next = { readAt: now, buckets };
|
|
107
|
+
this.kept.set(tenantId, next);
|
|
108
|
+
writePrivate(join(this.dir, `${tenantId}.json`), next);
|
|
109
|
+
});
|
|
110
|
+
this.reading.set(tenantId, reading);
|
|
111
|
+
void reading.finally(() => this.reading.delete(tenantId)).catch(() => undefined);
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
await reading;
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
catch (_a) {
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** Tokens and dollars of the month of `now`. */
|
|
122
|
+
month(tenantId, now = Date.now()) {
|
|
123
|
+
var _a;
|
|
124
|
+
var _b;
|
|
125
|
+
const { start } = GatewayUsageUtil.month(now);
|
|
126
|
+
let tokens = 0;
|
|
127
|
+
let cost = 0;
|
|
128
|
+
for (const bucket of (_b = (_a = this.get(tenantId)) === null || _a === void 0 ? void 0 : _a.buckets) !== null && _b !== void 0 ? _b : []) {
|
|
129
|
+
if (bucket.at >= start) {
|
|
130
|
+
tokens += GatewayUsageUtil.tokens(bucket);
|
|
131
|
+
cost += bucket.cost;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return { tokens, cost };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=gateway-usage.js.map
|
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
import { type ChildProcess } from 'node:child_process';
|
|
2
2
|
import type { SandboxContext, SandboxEndpoint, SandboxProvider, SandboxProviderConfig, SandboxState, SandboxTenant } from './sandbox-provider.js';
|
|
3
|
+
/** The last lines written to it, whole lines only but the one being written. */
|
|
4
|
+
export declare class LineTail {
|
|
5
|
+
protected readonly max: number;
|
|
6
|
+
protected readonly lines: string[];
|
|
7
|
+
protected partial: string;
|
|
8
|
+
constructor(max?: number);
|
|
9
|
+
write(chunk: string): void;
|
|
10
|
+
last(count: number): string;
|
|
11
|
+
}
|
|
3
12
|
/**
|
|
4
13
|
* `local`: a `ta serve` process per tenant on the machine of the gateway, its agent directory and workspace
|
|
5
14
|
* under `<gateway>/local/<tenant>`. Not a sandbox: every tenant runs as the user of the gateway and can read
|
|
@@ -14,10 +23,13 @@ export declare class LocalSandbox implements SandboxProvider {
|
|
|
14
23
|
child: ChildProcess;
|
|
15
24
|
url: string;
|
|
16
25
|
}>;
|
|
26
|
+
/** Kept past a stop, so that the console shows why one ended. */
|
|
27
|
+
protected readonly output: Map<string, LineTail>;
|
|
17
28
|
constructor(id: string, config: SandboxProviderConfig, context: SandboxContext);
|
|
18
29
|
start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
|
|
19
30
|
stop(tenant: SandboxTenant): Promise<void>;
|
|
20
31
|
state(tenant: SandboxTenant): Promise<SandboxState>;
|
|
32
|
+
logs(tenant: SandboxTenant, lines: number): Promise<string>;
|
|
21
33
|
dispose(): Promise<void>;
|
|
22
34
|
static freePort(): Promise<number>;
|
|
23
35
|
}
|
|
@@ -5,6 +5,29 @@ import { join } from 'node:path';
|
|
|
5
5
|
import { SandboxProviders } from './sandbox-provider.js';
|
|
6
6
|
/** How long a ta serve has to end on SIGTERM before it is killed. */
|
|
7
7
|
const STOP_TIMEOUT_MS = 10000;
|
|
8
|
+
/** The lines of output of each tenant's ta serve kept for the console. */
|
|
9
|
+
const KEPT_LINES = 2000;
|
|
10
|
+
/** The last lines written to it, whole lines only but the one being written. */
|
|
11
|
+
export class LineTail {
|
|
12
|
+
constructor(max = KEPT_LINES) {
|
|
13
|
+
this.max = max;
|
|
14
|
+
this.lines = [];
|
|
15
|
+
this.partial = '';
|
|
16
|
+
}
|
|
17
|
+
write(chunk) {
|
|
18
|
+
var _a;
|
|
19
|
+
const parts = (this.partial + chunk).split('\n');
|
|
20
|
+
this.partial = (_a = parts.pop()) !== null && _a !== void 0 ? _a : '';
|
|
21
|
+
this.lines.push(...parts);
|
|
22
|
+
if (this.lines.length > this.max) {
|
|
23
|
+
this.lines.splice(0, this.lines.length - this.max);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
last(count) {
|
|
27
|
+
const lines = this.partial ? [...this.lines, this.partial] : this.lines;
|
|
28
|
+
return lines.slice(-count).join('\n');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
8
31
|
/**
|
|
9
32
|
* `local`: a `ta serve` process per tenant on the machine of the gateway, its agent directory and workspace
|
|
10
33
|
* under `<gateway>/local/<tenant>`. Not a sandbox: every tenant runs as the user of the gateway and can read
|
|
@@ -16,9 +39,12 @@ export class LocalSandbox {
|
|
|
16
39
|
this.context = context;
|
|
17
40
|
this.type = 'local';
|
|
18
41
|
this.running = new Map();
|
|
42
|
+
/** Kept past a stop, so that the console shows why one ended. */
|
|
43
|
+
this.output = new Map();
|
|
19
44
|
this.name = SandboxProviders.string(config, 'name', 'Local');
|
|
20
45
|
}
|
|
21
46
|
async start(tenant) {
|
|
47
|
+
var _a, _b;
|
|
22
48
|
const running = this.running.get(tenant.id);
|
|
23
49
|
if (running && running.child.exitCode === null) {
|
|
24
50
|
return { url: running.url, token: tenant.token };
|
|
@@ -33,8 +59,12 @@ export class LocalSandbox {
|
|
|
33
59
|
const child = spawn(command, [...args, 'serve', '--port', String(port)], {
|
|
34
60
|
cwd,
|
|
35
61
|
env: { ...process.env, TA_CODING_AGENT_DIR: agentDir, TA_SERVE_TOKEN: tenant.token, CELL_SERVER__HOST: '127.0.0.1' },
|
|
36
|
-
stdio: 'ignore',
|
|
62
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
37
63
|
});
|
|
64
|
+
const tail = new LineTail();
|
|
65
|
+
this.output.set(tenant.id, tail);
|
|
66
|
+
(_a = child.stdout) === null || _a === void 0 ? void 0 : _a.setEncoding('utf8').on('data', (data) => tail.write(data));
|
|
67
|
+
(_b = child.stderr) === null || _b === void 0 ? void 0 : _b.setEncoding('utf8').on('data', (data) => tail.write(data));
|
|
38
68
|
const url = `http://127.0.0.1:${port}`;
|
|
39
69
|
// A command that cannot start fails this tenant's start (nothing answers), not the gateway.
|
|
40
70
|
const gone = () => {
|
|
@@ -69,6 +99,11 @@ export class LocalSandbox {
|
|
|
69
99
|
async state(tenant) {
|
|
70
100
|
return this.running.has(tenant.id) ? 'running' : 'stopped';
|
|
71
101
|
}
|
|
102
|
+
async logs(tenant, lines) {
|
|
103
|
+
var _a;
|
|
104
|
+
var _b;
|
|
105
|
+
return (_b = (_a = this.output.get(tenant.id)) === null || _a === void 0 ? void 0 : _a.last(lines)) !== null && _b !== void 0 ? _b : '';
|
|
106
|
+
}
|
|
72
107
|
async dispose() {
|
|
73
108
|
await Promise.all([...this.running.keys()].map(id => this.stop({ id, account: '', token: '' })));
|
|
74
109
|
}
|
|
@@ -10,6 +10,12 @@ export interface SandboxEndpoint {
|
|
|
10
10
|
token: string;
|
|
11
11
|
}
|
|
12
12
|
export type SandboxState = 'running' | 'stopped' | 'missing';
|
|
13
|
+
/** What a running sandbox takes: CPU in percent of one CPU, memory in bytes. */
|
|
14
|
+
export interface SandboxUsage {
|
|
15
|
+
cpu?: number;
|
|
16
|
+
memory?: number;
|
|
17
|
+
memoryLimit?: number;
|
|
18
|
+
}
|
|
13
19
|
/**
|
|
14
20
|
* Makes and runs the sandboxes of tenants, one each: a container, a process, a machine of a cloud. As a model
|
|
15
21
|
* provider of pi is to models, built in (`docker`, `command`, `local`, `ta`) or a module of the operator's
|
|
@@ -30,6 +36,10 @@ export interface SandboxProvider {
|
|
|
30
36
|
/** Stops it, keeping what it holds, to start again later. */
|
|
31
37
|
stop(tenant: SandboxTenant): Promise<void>;
|
|
32
38
|
state(tenant: SandboxTenant): Promise<SandboxState>;
|
|
39
|
+
/** What its sandbox takes now, for the console; undefined when it does not run. */
|
|
40
|
+
usage?(tenant: SandboxTenant): Promise<SandboxUsage | undefined>;
|
|
41
|
+
/** The last `lines` its sandbox wrote (its Ta service's output), for the console. */
|
|
42
|
+
logs?(tenant: SandboxTenant, lines: number): Promise<string>;
|
|
33
43
|
/** The gateway stops: what runs in this process ends (`local`). */
|
|
34
44
|
dispose?(): Promise<void>;
|
|
35
45
|
}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import type { TaEnvironmentChoice } from '@celljs/ta-protocol';
|
|
1
|
+
import type { TaEnvironmentChoice, TaGatewayLimits } from '@celljs/ta-protocol';
|
|
2
|
+
/** The minutes a tenant's sandbox ran in a month (of UTC), and those given on top of its limit. */
|
|
3
|
+
export interface TenantMeter {
|
|
4
|
+
/** `YYYY-MM`. */
|
|
5
|
+
month: string;
|
|
6
|
+
runMs: number;
|
|
7
|
+
bonusMinutes: number;
|
|
8
|
+
}
|
|
2
9
|
/** A tenant: an account and its Ta, wherever it runs. */
|
|
3
10
|
export interface Tenant {
|
|
4
11
|
id: string;
|
|
@@ -11,6 +18,10 @@ export interface Tenant {
|
|
|
11
18
|
environment?: TaEnvironmentChoice;
|
|
12
19
|
createdAt: number;
|
|
13
20
|
lastActiveAt?: number;
|
|
21
|
+
/** Its own limits over the gateway's defaults. */
|
|
22
|
+
limits?: TaGatewayLimits;
|
|
23
|
+
suspended?: boolean;
|
|
24
|
+
meter?: TenantMeter;
|
|
14
25
|
}
|
|
15
26
|
/** Files written whole or not at all, readable by this user only. */
|
|
16
27
|
export declare function writePrivate(file: string, data: unknown): void;
|
|
@@ -8,7 +8,8 @@ export declare namespace CommandSandboxUtil {
|
|
|
8
8
|
* by shell commands, as pi's models.json takes an endpoint it has no provider for. Each runs with
|
|
9
9
|
* TA_TENANT_ID, TA_TENANT_ACCOUNT and TA_SERVE_TOKEN in its environment: `start` makes or starts the sandbox
|
|
10
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
|
|
11
|
+
* `state` prints running, stopped or missing; `logs`, when there is one, prints the last TA_LOG_LINES lines
|
|
12
|
+
* the sandbox wrote, for the console.
|
|
12
13
|
*/
|
|
13
14
|
export declare class CommandSandbox implements SandboxProvider {
|
|
14
15
|
readonly id: string;
|
|
@@ -18,12 +19,14 @@ export declare class CommandSandbox implements SandboxProvider {
|
|
|
18
19
|
start: string;
|
|
19
20
|
stop?: string;
|
|
20
21
|
state?: string;
|
|
22
|
+
logs?: string;
|
|
21
23
|
};
|
|
22
24
|
protected readonly env: Record<string, string>;
|
|
23
25
|
constructor(id: string, config: SandboxProviderConfig);
|
|
26
|
+
logs?(tenant: SandboxTenant, lines: number): Promise<string>;
|
|
24
27
|
start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
|
|
25
28
|
stop(tenant: SandboxTenant): Promise<void>;
|
|
26
29
|
state(tenant: SandboxTenant): Promise<SandboxState>;
|
|
27
|
-
protected run(command: string, tenant: SandboxTenant): Promise<string>;
|
|
30
|
+
protected run(command: string, tenant: SandboxTenant, extra?: Record<string, string>): Promise<string>;
|
|
28
31
|
}
|
|
29
32
|
//# sourceMappingURL=command-sandbox.d.ts.map
|
|
@@ -22,7 +22,8 @@ var CommandSandboxUtil;
|
|
|
22
22
|
* by shell commands, as pi's models.json takes an endpoint it has no provider for. Each runs with
|
|
23
23
|
* TA_TENANT_ID, TA_TENANT_ACCOUNT and TA_SERVE_TOKEN in its environment: `start` makes or starts the sandbox
|
|
24
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
|
|
25
|
+
* `state` prints running, stopped or missing; `logs`, when there is one, prints the last TA_LOG_LINES lines
|
|
26
|
+
* the sandbox wrote, for the console.
|
|
26
27
|
*/
|
|
27
28
|
class CommandSandbox {
|
|
28
29
|
constructor(id, config) {
|
|
@@ -33,8 +34,20 @@ class CommandSandbox {
|
|
|
33
34
|
if (!start) {
|
|
34
35
|
throw new Error(`The provider "${id}" of the type command needs "start", a command that prints the address of the Ta service.`);
|
|
35
36
|
}
|
|
36
|
-
this.commands = {
|
|
37
|
+
this.commands = {
|
|
38
|
+
start,
|
|
39
|
+
stop: sandbox_provider_1.SandboxProviders.string(config, 'stop'),
|
|
40
|
+
state: sandbox_provider_1.SandboxProviders.string(config, 'state'),
|
|
41
|
+
logs: sandbox_provider_1.SandboxProviders.string(config, 'logs'),
|
|
42
|
+
};
|
|
37
43
|
this.env = sandbox_provider_1.SandboxProviders.env(config);
|
|
44
|
+
if (!this.commands.logs) {
|
|
45
|
+
// The console asks a provider whether it has logs by the method.
|
|
46
|
+
this.logs = undefined;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
logs(tenant, lines) {
|
|
50
|
+
return this.run(this.commands.logs, tenant, { TA_LOG_LINES: String(lines) });
|
|
38
51
|
}
|
|
39
52
|
async start(tenant) {
|
|
40
53
|
const stdout = await this.run(this.commands.start, tenant);
|
|
@@ -56,10 +69,10 @@ class CommandSandbox {
|
|
|
56
69
|
const word = (await this.run(this.commands.state, tenant)).trim().split(/\s+/).pop();
|
|
57
70
|
return word === 'running' || word === 'stopped' ? word : 'missing';
|
|
58
71
|
}
|
|
59
|
-
run(command, tenant) {
|
|
72
|
+
run(command, tenant, extra = {}) {
|
|
60
73
|
return new Promise((resolve, reject) => {
|
|
61
74
|
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 },
|
|
75
|
+
env: { ...process.env, ...this.env, TA_TENANT_ID: tenant.id, TA_TENANT_ACCOUNT: tenant.account, TA_SERVE_TOKEN: tenant.token, ...extra },
|
|
63
76
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
64
77
|
});
|
|
65
78
|
let stdout = '';
|
|
@@ -23,6 +23,11 @@ export declare class DockerEngine {
|
|
|
23
23
|
status: number;
|
|
24
24
|
body: T;
|
|
25
25
|
}>;
|
|
26
|
+
/** The answer of the Engine as it came, for the streams of logs, which are not text; a status of 400 and above throws. */
|
|
27
|
+
raw(method: string, path: string, body?: unknown, timeoutMs?: number): Promise<{
|
|
28
|
+
status: number;
|
|
29
|
+
body: Buffer;
|
|
30
|
+
}>;
|
|
26
31
|
/** undefined for a container that is not there. */
|
|
27
32
|
inspect(name: string): Promise<DockerContainer | undefined>;
|
|
28
33
|
create(name: string, spec: object): Promise<void>;
|
|
@@ -30,6 +35,14 @@ export declare class DockerEngine {
|
|
|
30
35
|
start(name: string): Promise<void>;
|
|
31
36
|
/** Stopped, already stopped (304) or not there (404). */
|
|
32
37
|
stop(name: string, seconds?: number): Promise<void>;
|
|
38
|
+
/** What a running container takes: one sample of its CPU over a second or so, and its memory; undefined for one that does not run. */
|
|
39
|
+
stats(name: string): Promise<{
|
|
40
|
+
cpu?: number;
|
|
41
|
+
memory?: number;
|
|
42
|
+
memoryLimit?: number;
|
|
43
|
+
} | undefined>;
|
|
44
|
+
/** The last `lines` of what a container wrote, its output and errors in their order; empty for one that is not there. */
|
|
45
|
+
logs(name: string, lines: number): Promise<string>;
|
|
33
46
|
/** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
|
|
34
47
|
ensureNetwork(name: string, isolated: boolean): Promise<void>;
|
|
35
48
|
/** Pulled when it is not here; one built here (ta:latest) is. */
|
|
@@ -48,7 +61,39 @@ export interface DockerContainer {
|
|
|
48
61
|
}[] | null>;
|
|
49
62
|
};
|
|
50
63
|
}
|
|
64
|
+
/** As far as the console reads `/containers/<name>/stats`. */
|
|
65
|
+
export interface DockerStats {
|
|
66
|
+
cpu_stats?: {
|
|
67
|
+
cpu_usage?: {
|
|
68
|
+
total_usage?: number;
|
|
69
|
+
};
|
|
70
|
+
system_cpu_usage?: number;
|
|
71
|
+
online_cpus?: number;
|
|
72
|
+
};
|
|
73
|
+
precpu_stats?: {
|
|
74
|
+
cpu_usage?: {
|
|
75
|
+
total_usage?: number;
|
|
76
|
+
};
|
|
77
|
+
system_cpu_usage?: number;
|
|
78
|
+
};
|
|
79
|
+
memory_stats?: {
|
|
80
|
+
usage?: number;
|
|
81
|
+
limit?: number;
|
|
82
|
+
stats?: Record<string, number>;
|
|
83
|
+
};
|
|
84
|
+
}
|
|
51
85
|
export declare namespace DockerEngineUtil {
|
|
86
|
+
/** As `docker stats` reckons: CPU in percent of one CPU, memory without the page cache. */
|
|
87
|
+
function usage(stats: DockerStats | undefined): {
|
|
88
|
+
cpu?: number;
|
|
89
|
+
memory?: number;
|
|
90
|
+
memoryLimit?: number;
|
|
91
|
+
} | undefined;
|
|
92
|
+
/**
|
|
93
|
+
* The text of the logs of a container without a terminal: frames of a header of 8 bytes (the stream, three
|
|
94
|
+
* zeroes, the length) and their bytes. One with a terminal sends its text as it is.
|
|
95
|
+
*/
|
|
96
|
+
function demux(buffer: Buffer): string;
|
|
52
97
|
/** `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
98
|
function splitImage(image: string): [string, string?];
|
|
54
99
|
/** `512m`, `4g`, a number of bytes: Docker's `--memory`. */
|
|
@@ -28,7 +28,20 @@ class DockerEngine {
|
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
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) {
|
|
31
|
+
async call(method, path, body, timeoutMs = 120000) {
|
|
32
|
+
const answer = await this.raw(method, path, body, timeoutMs);
|
|
33
|
+
const text = answer.body.toString('utf8');
|
|
34
|
+
let parsed = text;
|
|
35
|
+
try {
|
|
36
|
+
parsed = text ? JSON.parse(text) : undefined;
|
|
37
|
+
}
|
|
38
|
+
catch (_a) {
|
|
39
|
+
// Streams of progress (a pull) are lines of JSON: kept as text.
|
|
40
|
+
}
|
|
41
|
+
return { status: answer.status, body: parsed };
|
|
42
|
+
}
|
|
43
|
+
/** The answer of the Engine as it came, for the streams of logs, which are not text; a status of 400 and above throws. */
|
|
44
|
+
raw(method, path, body, timeoutMs = 120000) {
|
|
32
45
|
return new Promise((resolve, reject) => {
|
|
33
46
|
const payload = body === undefined ? undefined : JSON.stringify(body);
|
|
34
47
|
const req = (0, node_http_1.request)({
|
|
@@ -42,21 +55,21 @@ class DockerEngine {
|
|
|
42
55
|
res.on('data', chunk => chunks.push(chunk));
|
|
43
56
|
res.on('end', () => {
|
|
44
57
|
var _a, _b;
|
|
45
|
-
const
|
|
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
|
-
}
|
|
58
|
+
const buffer = Buffer.concat(chunks);
|
|
53
59
|
const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
|
|
54
60
|
if (status >= 400) {
|
|
55
|
-
const
|
|
61
|
+
const text = buffer.toString('utf8');
|
|
62
|
+
let message = text;
|
|
63
|
+
try {
|
|
64
|
+
message = (_b = JSON.parse(text).message) !== null && _b !== void 0 ? _b : text;
|
|
65
|
+
}
|
|
66
|
+
catch (_c) {
|
|
67
|
+
// Not JSON: the text as it is.
|
|
68
|
+
}
|
|
56
69
|
reject(new DockerError(`Docker: ${method} ${path.split('?')[0]} answered ${status}: ${message}`, status));
|
|
57
70
|
}
|
|
58
71
|
else {
|
|
59
|
-
resolve({ status, body:
|
|
72
|
+
resolve({ status, body: buffer });
|
|
60
73
|
}
|
|
61
74
|
});
|
|
62
75
|
});
|
|
@@ -97,6 +110,32 @@ class DockerEngine {
|
|
|
97
110
|
}
|
|
98
111
|
}
|
|
99
112
|
}
|
|
113
|
+
/** What a running container takes: one sample of its CPU over a second or so, and its memory; undefined for one that does not run. */
|
|
114
|
+
async stats(name) {
|
|
115
|
+
try {
|
|
116
|
+
const { body } = await this.call('GET', `/containers/${encodeURIComponent(name)}/stats?stream=false`, undefined, 15000);
|
|
117
|
+
return DockerEngineUtil.usage(body);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (error instanceof DockerError && (error.status === 404 || error.status === 409)) {
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** The last `lines` of what a container wrote, its output and errors in their order; empty for one that is not there. */
|
|
127
|
+
async logs(name, lines) {
|
|
128
|
+
try {
|
|
129
|
+
const { body } = await this.raw('GET', `/containers/${encodeURIComponent(name)}/logs?stdout=1&stderr=1&tail=${lines}`, undefined, 15000);
|
|
130
|
+
return DockerEngineUtil.demux(body);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
if (error instanceof DockerError && error.status === 404) {
|
|
134
|
+
return '';
|
|
135
|
+
}
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
100
139
|
/** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
|
|
101
140
|
async ensureNetwork(name, isolated) {
|
|
102
141
|
try {
|
|
@@ -129,6 +168,43 @@ class DockerEngine {
|
|
|
129
168
|
exports.DockerEngine = DockerEngine;
|
|
130
169
|
var DockerEngineUtil;
|
|
131
170
|
(function (DockerEngineUtil) {
|
|
171
|
+
/** As `docker stats` reckons: CPU in percent of one CPU, memory without the page cache. */
|
|
172
|
+
function usage(stats) {
|
|
173
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
|
|
174
|
+
var _r, _s, _t, _u, _v, _w;
|
|
175
|
+
if (!((_a = stats === null || stats === void 0 ? void 0 : stats.memory_stats) === null || _a === void 0 ? void 0 : _a.usage) && !((_b = stats === null || stats === void 0 ? void 0 : stats.cpu_stats) === null || _b === void 0 ? void 0 : _b.system_cpu_usage)) {
|
|
176
|
+
// A container that does not run answers with zeroes.
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
const cpuDelta = ((_r = (_d = (_c = stats.cpu_stats) === null || _c === void 0 ? void 0 : _c.cpu_usage) === null || _d === void 0 ? void 0 : _d.total_usage) !== null && _r !== void 0 ? _r : 0) - ((_s = (_f = (_e = stats.precpu_stats) === null || _e === void 0 ? void 0 : _e.cpu_usage) === null || _f === void 0 ? void 0 : _f.total_usage) !== null && _s !== void 0 ? _s : 0);
|
|
180
|
+
const systemDelta = ((_t = (_g = stats.cpu_stats) === null || _g === void 0 ? void 0 : _g.system_cpu_usage) !== null && _t !== void 0 ? _t : 0) - ((_u = (_h = stats.precpu_stats) === null || _h === void 0 ? void 0 : _h.system_cpu_usage) !== null && _u !== void 0 ? _u : 0);
|
|
181
|
+
const cpus = ((_j = stats.cpu_stats) === null || _j === void 0 ? void 0 : _j.online_cpus) || 1;
|
|
182
|
+
const cpu = systemDelta > 0 && cpuDelta >= 0 ? Math.round((cpuDelta / systemDelta) * cpus * 1000) / 10 : undefined;
|
|
183
|
+
const memory = (_k = stats.memory_stats) === null || _k === void 0 ? void 0 : _k.usage;
|
|
184
|
+
// cgroup v2 says inactive_file, v1 cache: what `docker stats` takes away.
|
|
185
|
+
const cache = (_w = (_v = (_m = (_l = stats.memory_stats) === null || _l === void 0 ? void 0 : _l.stats) === null || _m === void 0 ? void 0 : _m.inactive_file) !== null && _v !== void 0 ? _v : (_p = (_o = stats.memory_stats) === null || _o === void 0 ? void 0 : _o.stats) === null || _p === void 0 ? void 0 : _p.cache) !== null && _w !== void 0 ? _w : 0;
|
|
186
|
+
return { cpu, memory: memory === undefined ? undefined : Math.max(0, memory - cache), memoryLimit: (_q = stats.memory_stats) === null || _q === void 0 ? void 0 : _q.limit };
|
|
187
|
+
}
|
|
188
|
+
DockerEngineUtil.usage = usage;
|
|
189
|
+
/**
|
|
190
|
+
* The text of the logs of a container without a terminal: frames of a header of 8 bytes (the stream, three
|
|
191
|
+
* zeroes, the length) and their bytes. One with a terminal sends its text as it is.
|
|
192
|
+
*/
|
|
193
|
+
function demux(buffer) {
|
|
194
|
+
const parts = [];
|
|
195
|
+
let offset = 0;
|
|
196
|
+
while (offset + 8 <= buffer.length) {
|
|
197
|
+
const stream = buffer[offset];
|
|
198
|
+
const size = buffer.readUInt32BE(offset + 4);
|
|
199
|
+
if (stream > 2 || buffer[offset + 1] !== 0 || buffer[offset + 2] !== 0 || buffer[offset + 3] !== 0 || offset + 8 + size > buffer.length) {
|
|
200
|
+
return buffer.toString('utf8');
|
|
201
|
+
}
|
|
202
|
+
parts.push(buffer.subarray(offset + 8, offset + 8 + size));
|
|
203
|
+
offset += 8 + size;
|
|
204
|
+
}
|
|
205
|
+
return offset === buffer.length ? Buffer.concat(parts).toString('utf8') : buffer.toString('utf8');
|
|
206
|
+
}
|
|
207
|
+
DockerEngineUtil.demux = demux;
|
|
132
208
|
/** `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
209
|
function splitImage(image) {
|
|
134
210
|
const slash = image.lastIndexOf('/');
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DockerEngine } from './docker-engine';
|
|
2
|
-
import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant } from './sandbox-provider';
|
|
2
|
+
import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage } from './sandbox-provider';
|
|
3
3
|
export declare namespace DockerSandboxUtil {
|
|
4
4
|
/** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
|
|
5
5
|
function hostname(account: string): string;
|
|
@@ -39,6 +39,8 @@ export declare class DockerSandbox implements SandboxProvider {
|
|
|
39
39
|
start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
|
|
40
40
|
stop(tenant: SandboxTenant): Promise<void>;
|
|
41
41
|
state(tenant: SandboxTenant): Promise<SandboxState>;
|
|
42
|
+
usage(tenant: SandboxTenant): Promise<SandboxUsage | undefined>;
|
|
43
|
+
logs(tenant: SandboxTenant, lines: number): Promise<string>;
|
|
42
44
|
/** What `docker run` would be given. */
|
|
43
45
|
spec(tenant: SandboxTenant): object;
|
|
44
46
|
protected containerName(tenant: SandboxTenant): string;
|
|
@@ -84,6 +84,12 @@ class DockerSandbox {
|
|
|
84
84
|
const container = await this.engine.inspect(this.containerName(tenant));
|
|
85
85
|
return !container ? 'missing' : container.State.Running ? 'running' : 'stopped';
|
|
86
86
|
}
|
|
87
|
+
usage(tenant) {
|
|
88
|
+
return this.engine.stats(this.containerName(tenant));
|
|
89
|
+
}
|
|
90
|
+
logs(tenant, lines) {
|
|
91
|
+
return this.engine.logs(this.containerName(tenant), lines);
|
|
92
|
+
}
|
|
87
93
|
/** What `docker run` would be given. */
|
|
88
94
|
spec(tenant) {
|
|
89
95
|
const name = this.containerName(tenant);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type TaEnvironmentChoice, type TaEnvironmentInfo, type TaEnvironmentOption, type TaEnvironmentStatus } from '@celljs/ta-protocol';
|
|
2
|
-
import type { SandboxEndpoint, SandboxProvider, SandboxTenant } from './sandbox-provider';
|
|
1
|
+
import { type TaAgentActivity, type TaAgentCounts, type TaAgentSession, type TaAgentStats, type TaEnvironmentChoice, type TaEnvironmentInfo, type TaEnvironmentOption, type TaEnvironmentStatus, type TaSessionInfo, type TaTenantAgents, type TaUsageBucket } from '@celljs/ta-protocol';
|
|
2
|
+
import type { SandboxEndpoint, SandboxProvider, SandboxTenant, SandboxUsage } from './sandbox-provider';
|
|
3
3
|
import type { Tenant, TenantStore } from './tenant-store';
|
|
4
4
|
interface Running {
|
|
5
5
|
status: TaEnvironmentStatus;
|
|
@@ -16,6 +16,20 @@ export declare namespace EnvironmentsUtil {
|
|
|
16
16
|
function waitReady(url: string, timeoutMs?: number, fetcher?: typeof fetch): Promise<void>;
|
|
17
17
|
/** One call of the Ta service at `endpoint` over a WebSocket of its own: the gateway's, not a browser's. */
|
|
18
18
|
function call<T>(endpoint: SandboxEndpoint, method: string, params?: unknown[], timeoutMs?: number): Promise<T>;
|
|
19
|
+
/**
|
|
20
|
+
* Calls of the Ta service at `endpoint` over one WebSocket of the gateway's, in their order: the answers, or
|
|
21
|
+
* the error of each that failed. Throws when the service is not reached, or all took too long.
|
|
22
|
+
*/
|
|
23
|
+
function calls<T extends unknown[]>(endpoint: SandboxEndpoint, list: [string, unknown[]][], timeoutMs?: number): Promise<{
|
|
24
|
+
[K in keyof T]: T[K];
|
|
25
|
+
}>;
|
|
26
|
+
/** What the console says an agent does: a dialog waiting for the user first, then a turn, then a question left. */
|
|
27
|
+
function status(session: TaSessionInfo): TaAgentSession['status'];
|
|
28
|
+
function summary(sessions: TaSessionInfo[]): TaAgentCounts;
|
|
29
|
+
/** Of pi's statistics of a session, what the console shows; undefined for what is not them (an error). */
|
|
30
|
+
function stats(value: unknown): TaAgentStats | undefined;
|
|
31
|
+
/** A session as an administrator sees it: never what was said in it. */
|
|
32
|
+
function agentSession(session: TaSessionInfo, stats?: TaAgentStats): TaAgentSession;
|
|
19
33
|
function sandboxTenant(tenant: Tenant): SandboxTenant;
|
|
20
34
|
}
|
|
21
35
|
/**
|
|
@@ -32,6 +46,8 @@ export declare class Environments {
|
|
|
32
46
|
readyTimeoutMs?: number;
|
|
33
47
|
};
|
|
34
48
|
protected readonly running: Map<string, Running>;
|
|
49
|
+
/** Why the tenant's Ta may not start now (suspended, its free minutes used), checked before each start. */
|
|
50
|
+
guard?: (tenant: Tenant) => string | undefined;
|
|
35
51
|
constructor(providers: SandboxProvider[], tenants: TenantStore, settings: {
|
|
36
52
|
default?: string;
|
|
37
53
|
own: boolean;
|
|
@@ -46,6 +62,22 @@ export declare class Environments {
|
|
|
46
62
|
own: boolean;
|
|
47
63
|
};
|
|
48
64
|
info(tenant: Tenant): TaEnvironmentInfo;
|
|
65
|
+
/** What the sandbox of a running tenant takes, when its provider tells; a provider that fails to tell leaves it out. */
|
|
66
|
+
usage(tenant: Tenant): Promise<SandboxUsage | undefined>;
|
|
67
|
+
/** The last lines its sandbox wrote; a Ta service of the user's, or a provider without logs, has none for the gateway. */
|
|
68
|
+
logs(tenant: Tenant, lines: number): Promise<string>;
|
|
69
|
+
/** Where the Ta of a tenant answers, while it runs in a sandbox of the gateway's; a Ta service of the user's is theirs to watch. */
|
|
70
|
+
protected watched(tenant: Tenant): SandboxEndpoint | undefined;
|
|
71
|
+
/** The tenants whose sandbox of the gateway's runs now: those whose minutes count. */
|
|
72
|
+
runningIds(): string[];
|
|
73
|
+
/** How the gateway asks its Ta what its agents took; undefined while it does not run. */
|
|
74
|
+
usageReader(tenant: Tenant): ((since: number) => Promise<TaUsageBucket[]>) | undefined;
|
|
75
|
+
/** The latest of what an agent of its Ta did. */
|
|
76
|
+
activity(tenant: Tenant, sessionId: string): Promise<TaAgentActivity[]>;
|
|
77
|
+
/** How many conversations its Ta has open and how many work or wait; undefined when it does not run, or does not answer soon. */
|
|
78
|
+
agentSummary(tenant: Tenant, timeoutMs?: number): Promise<TaAgentCounts | undefined>;
|
|
79
|
+
/** The conversations open in its Ta, each with pi's statistics of it, over one connection. */
|
|
80
|
+
agents(tenant: Tenant, now?: number): Promise<TaTenantAgents>;
|
|
49
81
|
connections(tenantId: string): number;
|
|
50
82
|
/** Where the Ta of the tenant answers, started when it does not run. */
|
|
51
83
|
ensure(tenant: Tenant): Promise<SandboxEndpoint>;
|