@celljs/ta-gateway 4.15.2 → 4.16.0
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 +1 -0
- package/esm/node/command-sandbox.js +10 -1
- package/esm/node/docker-engine.d.ts +5 -0
- package/esm/node/docker-engine.js +11 -0
- package/esm/node/docker-sandbox.d.ts +3 -0
- package/esm/node/docker-sandbox.js +17 -3
- package/esm/node/environments.d.ts +2 -0
- package/esm/node/environments.js +5 -3
- package/esm/node/gateway-exec.d.ts +19 -0
- package/esm/node/gateway-exec.js +65 -0
- package/esm/node/gateway-policy.d.ts +1 -0
- package/esm/node/gateway-policy.js +2 -1
- package/esm/node/gateway-quotas.d.ts +9 -1
- package/esm/node/gateway-quotas.js +34 -3
- package/esm/node/gateway-server.d.ts +12 -1
- package/esm/node/gateway-server.js +55 -4
- package/esm/node/gateway-service.d.ts +8 -0
- package/esm/node/gateway-service.js +23 -4
- package/esm/node/local-sandbox.d.ts +1 -0
- package/esm/node/local-sandbox.js +2 -1
- package/esm/node/model-proxy.d.ts +105 -0
- package/esm/node/model-proxy.js +435 -0
- package/esm/node/sandbox-provider.d.ts +7 -0
- package/esm/node/tenant-store.d.ts +7 -0
- package/esm/node/tenant-store.js +10 -0
- package/lib/node/command-sandbox.d.ts +1 -0
- package/lib/node/command-sandbox.js +10 -1
- package/lib/node/docker-engine.d.ts +5 -0
- package/lib/node/docker-engine.js +11 -0
- package/lib/node/docker-sandbox.d.ts +3 -0
- package/lib/node/docker-sandbox.js +17 -3
- package/lib/node/environments.d.ts +2 -0
- package/lib/node/environments.js +5 -3
- package/lib/node/gateway-exec.d.ts +20 -0
- package/lib/node/gateway-exec.js +69 -0
- package/lib/node/gateway-policy.d.ts +1 -0
- package/lib/node/gateway-policy.js +2 -1
- package/lib/node/gateway-quotas.d.ts +9 -1
- package/lib/node/gateway-quotas.js +34 -3
- package/lib/node/gateway-server.d.ts +12 -1
- package/lib/node/gateway-server.js +55 -4
- package/lib/node/gateway-service.d.ts +8 -0
- package/lib/node/gateway-service.js +23 -4
- package/lib/node/local-sandbox.d.ts +1 -0
- package/lib/node/local-sandbox.js +2 -1
- package/lib/node/model-proxy.d.ts +106 -0
- package/lib/node/model-proxy.js +440 -0
- package/lib/node/sandbox-provider.d.ts +7 -0
- package/lib/node/tenant-store.d.ts +7 -0
- package/lib/node/tenant-store.js +10 -0
- package/package.json +4 -4
|
@@ -5,6 +5,9 @@ export interface TenantMeter {
|
|
|
5
5
|
month: string;
|
|
6
6
|
runMs: number;
|
|
7
7
|
bonusMinutes: number;
|
|
8
|
+
/** Tokens and dollars of calls of models through the gateway. */
|
|
9
|
+
tokens?: number;
|
|
10
|
+
cost?: number;
|
|
8
11
|
}
|
|
9
12
|
/** A tenant: an account and its Ta, wherever it runs. */
|
|
10
13
|
export interface Tenant {
|
|
@@ -22,6 +25,8 @@ export interface Tenant {
|
|
|
22
25
|
limits?: TaGatewayLimits;
|
|
23
26
|
suspended?: boolean;
|
|
24
27
|
meter?: TenantMeter;
|
|
28
|
+
/** What its sandbox calls the models of the gateway with: it reaches no key of a provider. */
|
|
29
|
+
modelKey?: string;
|
|
25
30
|
}
|
|
26
31
|
/** Files written whole or not at all, readable by this user only. */
|
|
27
32
|
export declare function writePrivate(file: string, data: unknown): void;
|
|
@@ -42,6 +47,8 @@ export declare class TenantStore {
|
|
|
42
47
|
avatar?: string;
|
|
43
48
|
}, now?: number): Tenant;
|
|
44
49
|
update(id: string, change: Partial<Omit<Tenant, 'id' | 'account' | 'token'>>): Tenant;
|
|
50
|
+
/** Its model key, made for a tenant of before. */
|
|
51
|
+
modelKey(id: string): string;
|
|
45
52
|
list(): Tenant[];
|
|
46
53
|
protected save(tenant: Tenant): void;
|
|
47
54
|
}
|
package/esm/node/tenant-store.js
CHANGED
|
@@ -55,6 +55,7 @@ export class TenantStore {
|
|
|
55
55
|
name: account.name,
|
|
56
56
|
avatar: account.avatar,
|
|
57
57
|
token: randomBytes(32).toString('base64url'),
|
|
58
|
+
modelKey: `tam-${randomBytes(24).toString('base64url')}`,
|
|
58
59
|
createdAt: now,
|
|
59
60
|
};
|
|
60
61
|
this.save(tenant);
|
|
@@ -69,6 +70,15 @@ export class TenantStore {
|
|
|
69
70
|
this.save(next);
|
|
70
71
|
return next;
|
|
71
72
|
}
|
|
73
|
+
/** Its model key, made for a tenant of before. */
|
|
74
|
+
modelKey(id) {
|
|
75
|
+
var _a;
|
|
76
|
+
const tenant = this.get(id);
|
|
77
|
+
if (!tenant) {
|
|
78
|
+
throw new Error(`No tenant ${id}`);
|
|
79
|
+
}
|
|
80
|
+
return (_a = tenant.modelKey) !== null && _a !== void 0 ? _a : this.update(id, { modelKey: `tam-${randomBytes(24).toString('base64url')}` }).modelKey;
|
|
81
|
+
}
|
|
72
82
|
list() {
|
|
73
83
|
return readdirSync(this.dir)
|
|
74
84
|
.filter(name => /^[0-9a-f]{16}\.json$/.test(name))
|
|
@@ -30,6 +30,7 @@ class CommandSandbox {
|
|
|
30
30
|
this.id = id;
|
|
31
31
|
this.type = 'command';
|
|
32
32
|
this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', id);
|
|
33
|
+
this.gatewayUrl = sandbox_provider_1.SandboxProviders.string(config, 'gatewayUrl');
|
|
33
34
|
const start = sandbox_provider_1.SandboxProviders.string(config, 'start');
|
|
34
35
|
if (!start) {
|
|
35
36
|
throw new Error(`The provider "${id}" of the type command needs "start", a command that prints the address of the Ta service.`);
|
|
@@ -72,7 +73,15 @@ class CommandSandbox {
|
|
|
72
73
|
run(command, tenant, extra = {}) {
|
|
73
74
|
return new Promise((resolve, reject) => {
|
|
74
75
|
const child = (0, node_child_process_1.spawn)('sh', ['-c', command], {
|
|
75
|
-
env: {
|
|
76
|
+
env: {
|
|
77
|
+
...process.env,
|
|
78
|
+
...this.env,
|
|
79
|
+
...tenant.env,
|
|
80
|
+
TA_TENANT_ID: tenant.id,
|
|
81
|
+
TA_TENANT_ACCOUNT: tenant.account,
|
|
82
|
+
TA_SERVE_TOKEN: tenant.token,
|
|
83
|
+
...extra,
|
|
84
|
+
},
|
|
76
85
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
77
86
|
});
|
|
78
87
|
let stdout = '';
|
|
@@ -43,6 +43,8 @@ export declare class DockerEngine {
|
|
|
43
43
|
} | undefined>;
|
|
44
44
|
/** The last `lines` of what a container wrote, its output and errors in their order; empty for one that is not there. */
|
|
45
45
|
logs(name: string, lines: number): Promise<string>;
|
|
46
|
+
/** Removed, its volumes kept; nothing when it is not there. */
|
|
47
|
+
remove(name: string): Promise<void>;
|
|
46
48
|
/** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
|
|
47
49
|
ensureNetwork(name: string, isolated: boolean): Promise<void>;
|
|
48
50
|
/** Pulled when it is not here; one built here (ta:latest) is. */
|
|
@@ -50,6 +52,9 @@ export declare class DockerEngine {
|
|
|
50
52
|
}
|
|
51
53
|
export interface DockerContainer {
|
|
52
54
|
Id: string;
|
|
55
|
+
Config?: {
|
|
56
|
+
Env?: string[];
|
|
57
|
+
};
|
|
53
58
|
State: {
|
|
54
59
|
Running: boolean;
|
|
55
60
|
Status: string;
|
|
@@ -136,6 +136,17 @@ class DockerEngine {
|
|
|
136
136
|
throw error;
|
|
137
137
|
}
|
|
138
138
|
}
|
|
139
|
+
/** Removed, its volumes kept; nothing when it is not there. */
|
|
140
|
+
async remove(name) {
|
|
141
|
+
try {
|
|
142
|
+
await this.call('DELETE', `/containers/${encodeURIComponent(name)}?force=true`);
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (!(error instanceof DockerError && error.status === 404)) {
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
139
150
|
/** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
|
|
140
151
|
async ensureNetwork(name, isolated) {
|
|
141
152
|
try {
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { DockerEngine } from './docker-engine';
|
|
2
2
|
import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage } from './sandbox-provider';
|
|
3
3
|
export declare namespace DockerSandboxUtil {
|
|
4
|
+
/** Whether a container has each variable of `env` as it is. */
|
|
5
|
+
function hasEnv(have: string[] | undefined, want: Record<string, string> | undefined): boolean;
|
|
4
6
|
/** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
|
|
5
7
|
function hostname(account: string): string;
|
|
6
8
|
}
|
|
@@ -33,6 +35,7 @@ export declare class DockerSandbox implements SandboxProvider {
|
|
|
33
35
|
protected readonly options: DockerSandboxOptions;
|
|
34
36
|
readonly type = "docker";
|
|
35
37
|
readonly name: string;
|
|
38
|
+
readonly gatewayUrl?: string;
|
|
36
39
|
protected readonly engine: DockerEngine;
|
|
37
40
|
static options(config: SandboxProviderConfig): DockerSandboxOptions;
|
|
38
41
|
constructor(id: string, config: SandboxProviderConfig, options?: DockerSandboxOptions, engine?: DockerEngine);
|
|
@@ -5,6 +5,12 @@ const docker_engine_1 = require("./docker-engine");
|
|
|
5
5
|
const sandbox_provider_1 = require("./sandbox-provider");
|
|
6
6
|
var DockerSandboxUtil;
|
|
7
7
|
(function (DockerSandboxUtil) {
|
|
8
|
+
/** Whether a container has each variable of `env` as it is. */
|
|
9
|
+
function hasEnv(have, want) {
|
|
10
|
+
const set = new Set(have !== null && have !== void 0 ? have : []);
|
|
11
|
+
return Object.entries(want !== null && want !== void 0 ? want : {}).every(([key, value]) => set.has(`${key}=${value}`));
|
|
12
|
+
}
|
|
13
|
+
DockerSandboxUtil.hasEnv = hasEnv;
|
|
8
14
|
/** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
|
|
9
15
|
function hostname(account) {
|
|
10
16
|
const name = account
|
|
@@ -55,12 +61,18 @@ class DockerSandbox {
|
|
|
55
61
|
this.options = options;
|
|
56
62
|
this.type = 'docker';
|
|
57
63
|
this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', 'Docker');
|
|
64
|
+
this.gatewayUrl = sandbox_provider_1.SandboxProviders.string(config, 'gatewayUrl');
|
|
58
65
|
this.engine = engine !== null && engine !== void 0 ? engine : new docker_engine_1.DockerEngine({ host: options.host });
|
|
59
66
|
}
|
|
60
67
|
async start(tenant) {
|
|
61
|
-
var _a, _b, _c;
|
|
68
|
+
var _a, _b, _c, _d;
|
|
62
69
|
const name = this.containerName(tenant);
|
|
63
70
|
let container = await this.engine.inspect(name);
|
|
71
|
+
if (container && !DockerSandboxUtil.hasEnv((_a = container.Config) === null || _a === void 0 ? void 0 : _a.Env, tenant.env)) {
|
|
72
|
+
// Made before the gateway gave it this environment (the models of the gateway): made again, its volume kept.
|
|
73
|
+
await this.engine.remove(name);
|
|
74
|
+
container = undefined;
|
|
75
|
+
}
|
|
64
76
|
if (!container) {
|
|
65
77
|
await this.engine.ensureImage(this.options.image);
|
|
66
78
|
await this.engine.ensureNetwork(this.options.network, true);
|
|
@@ -71,7 +83,7 @@ class DockerSandbox {
|
|
|
71
83
|
await this.engine.start(name);
|
|
72
84
|
container = await this.engine.inspect(name);
|
|
73
85
|
}
|
|
74
|
-
const port = (
|
|
86
|
+
const port = (_d = (_c = (_b = container === null || container === void 0 ? void 0 : container.NetworkSettings.Ports) === null || _b === void 0 ? void 0 : _b[PORT]) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.HostPort;
|
|
75
87
|
if (!port) {
|
|
76
88
|
throw new Error(`The container ${name} publishes no port for ${PORT}.`);
|
|
77
89
|
}
|
|
@@ -97,11 +109,13 @@ class DockerSandbox {
|
|
|
97
109
|
Image: this.options.image,
|
|
98
110
|
// What the Ta of the tenant tells its clients its machine is, as the list of computers of the phone shows it.
|
|
99
111
|
Hostname: DockerSandboxUtil.hostname(tenant.account),
|
|
100
|
-
Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries(this.options.env).map(([key, value]) => `${key}=${value}`)],
|
|
112
|
+
Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries({ ...this.options.env, ...tenant.env }).map(([key, value]) => `${key}=${value}`)],
|
|
101
113
|
Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account },
|
|
102
114
|
ExposedPorts: { [PORT]: {} },
|
|
103
115
|
HostConfig: {
|
|
104
116
|
PortBindings: { [PORT]: [{ HostIp: this.options.bind, HostPort: '' }] },
|
|
117
|
+
// The gateway, for the models it gives (TA_MODEL_PROXY_URL): the host, on Linux too.
|
|
118
|
+
ExtraHosts: ['host.docker.internal:host-gateway'],
|
|
105
119
|
Mounts: [{ Type: 'volume', Source: name, Target: '/home/ta' }],
|
|
106
120
|
NetworkMode: this.options.network,
|
|
107
121
|
Memory: this.options.memory,
|
|
@@ -48,6 +48,8 @@ export declare class Environments {
|
|
|
48
48
|
protected readonly running: Map<string, Running>;
|
|
49
49
|
/** Why the tenant's Ta may not start now (suspended, its free minutes used), checked before each start. */
|
|
50
50
|
guard?: (tenant: Tenant) => string | undefined;
|
|
51
|
+
/** More of the environment of a sandbox the gateway starts: what reaches the models of the gateway. */
|
|
52
|
+
envOf?: (tenant: Tenant, provider: SandboxProvider) => Record<string, string> | undefined;
|
|
51
53
|
constructor(providers: SandboxProvider[], tenants: TenantStore, settings: {
|
|
52
54
|
default?: string;
|
|
53
55
|
own: boolean;
|
package/lib/node/environments.js
CHANGED
|
@@ -312,9 +312,11 @@ class Environments {
|
|
|
312
312
|
running.error = undefined;
|
|
313
313
|
const starting = (async () => {
|
|
314
314
|
var _a;
|
|
315
|
-
|
|
316
|
-
const
|
|
317
|
-
|
|
315
|
+
var _b;
|
|
316
|
+
const { provider, own } = this.provider(tenant);
|
|
317
|
+
const env = own ? undefined : (_a = this.envOf) === null || _a === void 0 ? void 0 : _a.call(this, tenant, provider);
|
|
318
|
+
const endpoint = await provider.start({ ...EnvironmentsUtil.sandboxTenant(tenant), ...(env ? { env } : {}) });
|
|
319
|
+
await EnvironmentsUtil.waitReady(endpoint.url, (_b = this.settings.readyTimeoutMs) !== null && _b !== void 0 ? _b : provider.readyTimeoutMs);
|
|
318
320
|
return endpoint;
|
|
319
321
|
})();
|
|
320
322
|
running.starting = starting;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
|
|
2
|
+
import type { SandboxEndpoint } from './sandbox-provider';
|
|
3
|
+
/**
|
|
4
|
+
* A connection of another Ta to the exec server of its account's sandbox (`/api/exec`): what it sends goes to the
|
|
5
|
+
* sandbox once it answers, and back, unread. The account's own token is checked by the gateway; the sandbox's by it.
|
|
6
|
+
*/
|
|
7
|
+
export declare class GatewayExecProxy {
|
|
8
|
+
protected readonly outer: WebSocketConnection;
|
|
9
|
+
protected readonly release: () => void;
|
|
10
|
+
protected inner?: WebSocket;
|
|
11
|
+
protected readonly queued: string[];
|
|
12
|
+
protected queuedBytes: number;
|
|
13
|
+
protected closed: boolean;
|
|
14
|
+
constructor(outer: WebSocketConnection, endpoint: Promise<SandboxEndpoint>, release: () => void);
|
|
15
|
+
protected open(endpoint: SandboxEndpoint): void;
|
|
16
|
+
protected send(text: string): void;
|
|
17
|
+
close(code: number, reason: string): void;
|
|
18
|
+
protected dispose(): void;
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=gateway-exec.d.ts.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GatewayExecProxy = void 0;
|
|
4
|
+
/** What waits for the sandbox at most, as GatewaySocket. */
|
|
5
|
+
const MAX_QUEUED_BYTES = 16 * 1024 * 1024;
|
|
6
|
+
/**
|
|
7
|
+
* A connection of another Ta to the exec server of its account's sandbox (`/api/exec`): what it sends goes to the
|
|
8
|
+
* sandbox once it answers, and back, unread. The account's own token is checked by the gateway; the sandbox's by it.
|
|
9
|
+
*/
|
|
10
|
+
class GatewayExecProxy {
|
|
11
|
+
constructor(outer, endpoint, release) {
|
|
12
|
+
this.outer = outer;
|
|
13
|
+
this.release = release;
|
|
14
|
+
this.queued = [];
|
|
15
|
+
this.queuedBytes = 0;
|
|
16
|
+
this.closed = false;
|
|
17
|
+
outer.onMessage(text => this.send(text));
|
|
18
|
+
outer.onClose(() => this.dispose());
|
|
19
|
+
endpoint.then(found => this.open(found), (error) => this.close(1011, `Your environment did not start: ${error.message}`.slice(0, 120)));
|
|
20
|
+
}
|
|
21
|
+
open(endpoint) {
|
|
22
|
+
if (this.closed) {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const url = new URL(`${endpoint.url.replace(/^http/, 'ws')}/api/exec`);
|
|
26
|
+
url.searchParams.set('token', endpoint.token);
|
|
27
|
+
const inner = new WebSocket(url);
|
|
28
|
+
this.inner = inner;
|
|
29
|
+
inner.onopen = () => {
|
|
30
|
+
for (const text of this.queued.splice(0)) {
|
|
31
|
+
inner.send(text);
|
|
32
|
+
}
|
|
33
|
+
this.queuedBytes = 0;
|
|
34
|
+
};
|
|
35
|
+
inner.onmessage = message => this.outer.open && this.outer.send(String(message.data));
|
|
36
|
+
inner.onclose = event => this.close(event.code === 1000 || event.code === 1001 ? 1001 : 1011, 'The sandbox closed the connection.');
|
|
37
|
+
inner.onerror = () => undefined;
|
|
38
|
+
}
|
|
39
|
+
send(text) {
|
|
40
|
+
var _a;
|
|
41
|
+
if (((_a = this.inner) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
|
|
42
|
+
this.inner.send(text);
|
|
43
|
+
}
|
|
44
|
+
else if (this.queuedBytes + text.length <= MAX_QUEUED_BYTES) {
|
|
45
|
+
this.queued.push(text);
|
|
46
|
+
this.queuedBytes += text.length;
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
this.close(1013, 'The environment is still starting.');
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
close(code, reason) {
|
|
53
|
+
if (this.outer.open) {
|
|
54
|
+
this.outer.close(code, reason);
|
|
55
|
+
}
|
|
56
|
+
this.dispose();
|
|
57
|
+
}
|
|
58
|
+
dispose() {
|
|
59
|
+
var _a;
|
|
60
|
+
if (this.closed) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
this.closed = true;
|
|
64
|
+
this.release();
|
|
65
|
+
(_a = this.inner) === null || _a === void 0 ? void 0 : _a.close();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
exports.GatewayExecProxy = GatewayExecProxy;
|
|
69
|
+
//# sourceMappingURL=gateway-exec.js.map
|
|
@@ -7,6 +7,7 @@ interface StoredPolicy {
|
|
|
7
7
|
/** The limits of a member once the defaults and their own are taken together: none where a value is missing. */
|
|
8
8
|
export interface ResolvedLimits {
|
|
9
9
|
freeMinutes?: number;
|
|
10
|
+
monthlyTokens?: number;
|
|
10
11
|
promptsPerMinute?: number;
|
|
11
12
|
connections?: number;
|
|
12
13
|
providers?: string[];
|
|
@@ -10,7 +10,7 @@ class PolicyError extends Error {
|
|
|
10
10
|
exports.PolicyError = PolicyError;
|
|
11
11
|
var GatewayPolicyUtil;
|
|
12
12
|
(function (GatewayPolicyUtil) {
|
|
13
|
-
const NUMBERS = ['freeMinutes', 'promptsPerMinute', 'connections'];
|
|
13
|
+
const NUMBERS = ['freeMinutes', 'monthlyTokens', 'promptsPerMinute', 'connections'];
|
|
14
14
|
const RANK = { member: 0, admin: 1, owner: 2 };
|
|
15
15
|
function rank(role) {
|
|
16
16
|
return RANK[role];
|
|
@@ -87,6 +87,7 @@ var GatewayPolicyUtil;
|
|
|
87
87
|
const own_ = pick('own');
|
|
88
88
|
return {
|
|
89
89
|
freeMinutes: number('freeMinutes'),
|
|
90
|
+
monthlyTokens: number('monthlyTokens'),
|
|
90
91
|
promptsPerMinute: number('promptsPerMinute'),
|
|
91
92
|
connections: number('connections'),
|
|
92
93
|
providers: Array.isArray(providers) ? providers : undefined,
|
|
@@ -11,16 +11,24 @@ export declare class GatewayQuotas {
|
|
|
11
11
|
protected readonly tenants: TenantStore;
|
|
12
12
|
protected readonly usage: GatewayUsage;
|
|
13
13
|
protected readonly ownAllowed: () => boolean;
|
|
14
|
+
/** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
|
|
15
|
+
protected readonly metered: () => boolean;
|
|
14
16
|
protected lastTick: number;
|
|
15
17
|
/** By tenant: the times of its messages within the last minute. */
|
|
16
18
|
protected readonly prompts: Map<string, number[]>;
|
|
17
|
-
constructor(policy: GatewayPolicy, tenants: TenantStore, usage: GatewayUsage, ownAllowed: () => boolean
|
|
19
|
+
constructor(policy: GatewayPolicy, tenants: TenantStore, usage: GatewayUsage, ownAllowed: () => boolean,
|
|
20
|
+
/** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
|
|
21
|
+
metered?: () => boolean);
|
|
18
22
|
role(tenant: Tenant): TaGatewayRole;
|
|
19
23
|
limits(tenant: Tenant): ResolvedLimits;
|
|
20
24
|
/** That of this month: a meter of a month before starts again. */
|
|
21
25
|
meter(tenant: Tenant, now?: number): TenantMeter;
|
|
22
26
|
blocked(tenant: Tenant, now?: number): TaQuotaBlock | undefined;
|
|
23
27
|
state(tenant: Tenant, now?: number): TaQuotaState;
|
|
28
|
+
/** Why a call of a model of the gateway is refused now; owners have no limit. */
|
|
29
|
+
refuseModels(tenant: Tenant, now?: number): string | undefined;
|
|
30
|
+
/** What a call of a model took, to the month of the tenant. */
|
|
31
|
+
addTokens(tenantId: string, tokens: number, cost: number, now?: number): void;
|
|
24
32
|
/** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
|
|
25
33
|
takePrompt(tenant: Tenant, now?: number): boolean;
|
|
26
34
|
/** When the next message may go: the oldest of the minute leaves it. */
|
|
@@ -11,11 +11,14 @@ const MAX_TICK_MS = 2 * MINUTE;
|
|
|
11
11
|
* gateway as it sees them run, and the messages a minute they send their agents. Owners have no limits.
|
|
12
12
|
*/
|
|
13
13
|
class GatewayQuotas {
|
|
14
|
-
constructor(policy, tenants, usage, ownAllowed
|
|
14
|
+
constructor(policy, tenants, usage, ownAllowed,
|
|
15
|
+
/** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
|
|
16
|
+
metered = () => false) {
|
|
15
17
|
this.policy = policy;
|
|
16
18
|
this.tenants = tenants;
|
|
17
19
|
this.usage = usage;
|
|
18
20
|
this.ownAllowed = ownAllowed;
|
|
21
|
+
this.metered = metered;
|
|
19
22
|
this.lastTick = Date.now();
|
|
20
23
|
/** By tenant: the times of its messages within the last minute. */
|
|
21
24
|
this.prompts = new Map();
|
|
@@ -44,20 +47,48 @@ class GatewayQuotas {
|
|
|
44
47
|
return freeMinutes !== undefined && meter.runMs >= (freeMinutes + meter.bonusMinutes) * MINUTE ? 'minutes' : undefined;
|
|
45
48
|
}
|
|
46
49
|
state(tenant, now = Date.now()) {
|
|
50
|
+
var _a, _b;
|
|
47
51
|
const { key, next } = gateway_usage_1.GatewayUsageUtil.month(now);
|
|
48
52
|
const meter = this.meter(tenant, now);
|
|
49
53
|
const limits = this.limits(tenant);
|
|
50
|
-
const
|
|
54
|
+
const metered = this.metered();
|
|
55
|
+
const month = metered ? { tokens: (_a = meter.tokens) !== null && _a !== void 0 ? _a : 0, cost: (_b = meter.cost) !== null && _b !== void 0 ? _b : 0 } : this.usage.month(tenant.id, now);
|
|
51
56
|
return {
|
|
52
57
|
month: key,
|
|
53
58
|
resetsAt: next,
|
|
54
59
|
minutes: { used: Math.floor(meter.runMs / MINUTE), limit: limits.freeMinutes, bonus: meter.bonusMinutes },
|
|
55
|
-
tokens: { used: month.tokens, cost: month.cost },
|
|
60
|
+
tokens: { used: month.tokens, cost: month.cost, limit: metered ? limits.monthlyTokens : undefined, metered },
|
|
56
61
|
promptsPerMinute: limits.promptsPerMinute,
|
|
57
62
|
connections: limits.connections,
|
|
58
63
|
blocked: this.blocked(tenant, now),
|
|
59
64
|
};
|
|
60
65
|
}
|
|
66
|
+
/** Why a call of a model of the gateway is refused now; owners have no limit. */
|
|
67
|
+
refuseModels(tenant, now = Date.now()) {
|
|
68
|
+
var _a;
|
|
69
|
+
if (this.role(tenant) === 'owner') {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
if (tenant.suspended) {
|
|
73
|
+
return 'Your account is suspended by an administrator of the gateway.';
|
|
74
|
+
}
|
|
75
|
+
const limit = this.limits(tenant).monthlyTokens;
|
|
76
|
+
const used = (_a = this.meter(tenant, now).tokens) !== null && _a !== void 0 ? _a : 0;
|
|
77
|
+
// The words pi does not retry on: the month is over, not a moment of load.
|
|
78
|
+
return limit !== undefined && used >= limit
|
|
79
|
+
? `Monthly usage limit reached: ${used} of ${limit} tokens this month; it starts again next month, or ask an administrator.`
|
|
80
|
+
: undefined;
|
|
81
|
+
}
|
|
82
|
+
/** What a call of a model took, to the month of the tenant. */
|
|
83
|
+
addTokens(tenantId, tokens, cost, now = Date.now()) {
|
|
84
|
+
var _a, _b;
|
|
85
|
+
const tenant = this.tenants.get(tenantId);
|
|
86
|
+
if (!tenant) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const meter = this.meter(tenant, now);
|
|
90
|
+
this.tenants.update(tenantId, { meter: { ...meter, tokens: ((_a = meter.tokens) !== null && _a !== void 0 ? _a : 0) + tokens, cost: ((_b = meter.cost) !== null && _b !== void 0 ? _b : 0) + cost } });
|
|
91
|
+
}
|
|
61
92
|
/** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
|
|
62
93
|
takePrompt(tenant, now = Date.now()) {
|
|
63
94
|
var _a;
|
|
@@ -10,6 +10,7 @@ import { GatewayQuotas } from './gateway-quotas';
|
|
|
10
10
|
import { type GatewayCaller, GatewayService } from './gateway-service';
|
|
11
11
|
import { GatewaySocket } from './gateway-socket';
|
|
12
12
|
import { GatewayUsage } from './gateway-usage';
|
|
13
|
+
import { type GatewayModelsConfig, ModelProxy } from './model-proxy';
|
|
13
14
|
import { type SandboxProviderFactory, SandboxProviders } from './sandbox-provider';
|
|
14
15
|
import { SignInLinks } from './sign-in-links';
|
|
15
16
|
import { TenantStore } from './tenant-store';
|
|
@@ -28,6 +29,13 @@ export interface GatewayServerOptions {
|
|
|
28
29
|
version?: string;
|
|
29
30
|
}
|
|
30
31
|
export declare namespace GatewayServerUtil {
|
|
32
|
+
/**
|
|
33
|
+
* Where a sandbox reaches the gateway, by the type of its provider: a container the host (host.docker.internal,
|
|
34
|
+
* mapped on Linux too), a process of this machine 127.0.0.1, another the public address.
|
|
35
|
+
*/
|
|
36
|
+
function reach(type: string, port: number, publicUrl: string | undefined): string;
|
|
37
|
+
/** Where another Ta reaches the exec server of its account's sandbox. */
|
|
38
|
+
const EXEC_PATH = "/api/exec";
|
|
31
39
|
/** What a page is told when its Ta does not start for its account's limits; TaGatewayInfo.quota says it in the page's words. */
|
|
32
40
|
function blockedReason(block: TaQuotaBlock | undefined): string | undefined;
|
|
33
41
|
/** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
|
|
@@ -63,10 +71,13 @@ export declare class GatewayServer {
|
|
|
63
71
|
readonly quotas: GatewayQuotas;
|
|
64
72
|
readonly usage: GatewayUsage;
|
|
65
73
|
readonly audit: GatewayAudit;
|
|
74
|
+
readonly models: ModelProxy;
|
|
75
|
+
/** The port it listens on, once it does. */
|
|
76
|
+
protected port?: number;
|
|
66
77
|
protected server?: Server;
|
|
67
78
|
protected ticker?: ReturnType<typeof setInterval>;
|
|
68
79
|
static create(options: GatewayServerOptions): Promise<GatewayServer>;
|
|
69
|
-
protected constructor(options: GatewayServerOptions, providers: Awaited<ReturnType<typeof SandboxProviders.create>>, config: ReturnType<typeof SandboxProviders.read
|
|
80
|
+
protected constructor(options: GatewayServerOptions, providers: Awaited<ReturnType<typeof SandboxProviders.create>>, config: ReturnType<typeof SandboxProviders.read>, models?: GatewayModelsConfig);
|
|
70
81
|
isAdmin(account: string): boolean;
|
|
71
82
|
/** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
|
|
72
83
|
tick(now?: number): Promise<void>;
|
|
@@ -16,12 +16,14 @@ const command_sandbox_1 = require("./command-sandbox");
|
|
|
16
16
|
const docker_sandbox_1 = require("./docker-sandbox");
|
|
17
17
|
const environments_1 = require("./environments");
|
|
18
18
|
const gateway_audit_1 = require("./gateway-audit");
|
|
19
|
+
const gateway_exec_1 = require("./gateway-exec");
|
|
19
20
|
const gateway_policy_1 = require("./gateway-policy");
|
|
20
21
|
const gateway_quotas_1 = require("./gateway-quotas");
|
|
21
22
|
const gateway_service_1 = require("./gateway-service");
|
|
22
23
|
const gateway_socket_1 = require("./gateway-socket");
|
|
23
24
|
const gateway_usage_1 = require("./gateway-usage");
|
|
24
25
|
const local_sandbox_1 = require("./local-sandbox");
|
|
26
|
+
const model_proxy_1 = require("./model-proxy");
|
|
25
27
|
const sandbox_provider_1 = require("./sandbox-provider");
|
|
26
28
|
const sign_in_links_1 = require("./sign-in-links");
|
|
27
29
|
const ta_sandbox_1 = require("./ta-sandbox");
|
|
@@ -53,6 +55,22 @@ exports.SANDBOX_TYPES = {
|
|
|
53
55
|
};
|
|
54
56
|
var GatewayServerUtil;
|
|
55
57
|
(function (GatewayServerUtil) {
|
|
58
|
+
/**
|
|
59
|
+
* Where a sandbox reaches the gateway, by the type of its provider: a container the host (host.docker.internal,
|
|
60
|
+
* mapped on Linux too), a process of this machine 127.0.0.1, another the public address.
|
|
61
|
+
*/
|
|
62
|
+
function reach(type, port, publicUrl) {
|
|
63
|
+
if (type === 'docker') {
|
|
64
|
+
return `http://host.docker.internal:${port}`;
|
|
65
|
+
}
|
|
66
|
+
if (type === 'local' || !publicUrl) {
|
|
67
|
+
return `http://127.0.0.1:${port}`;
|
|
68
|
+
}
|
|
69
|
+
return publicUrl;
|
|
70
|
+
}
|
|
71
|
+
GatewayServerUtil.reach = reach;
|
|
72
|
+
/** Where another Ta reaches the exec server of its account's sandbox. */
|
|
73
|
+
GatewayServerUtil.EXEC_PATH = '/api/exec';
|
|
56
74
|
/** What a page is told when its Ta does not start for its account's limits; TaGatewayInfo.quota says it in the page's words. */
|
|
57
75
|
function blockedReason(block) {
|
|
58
76
|
switch (block) {
|
|
@@ -110,13 +128,14 @@ var GatewayServerUtil;
|
|
|
110
128
|
*/
|
|
111
129
|
class GatewayServer {
|
|
112
130
|
static async create(options) {
|
|
131
|
+
const models = model_proxy_1.ModelProxyUtil.read(options.dir);
|
|
113
132
|
(0, node_fs_1.mkdirSync)(options.dir, { recursive: true, mode: 0o700 });
|
|
114
133
|
const config = sandbox_provider_1.SandboxProviders.read(options.dir);
|
|
115
134
|
const context = { dir: options.dir, taCommand: options.taCommand };
|
|
116
135
|
const providers = await sandbox_provider_1.SandboxProviders.create(config, context, exports.SANDBOX_TYPES);
|
|
117
|
-
return new GatewayServer(options, providers, config);
|
|
136
|
+
return new GatewayServer(options, providers, config, models);
|
|
118
137
|
}
|
|
119
|
-
constructor(options, providers, config) {
|
|
138
|
+
constructor(options, providers, config, models = {}) {
|
|
120
139
|
var _a, _b;
|
|
121
140
|
this.options = options;
|
|
122
141
|
this.sockets = new Set();
|
|
@@ -134,8 +153,24 @@ class GatewayServer {
|
|
|
134
153
|
});
|
|
135
154
|
this.usage = new gateway_usage_1.GatewayUsage(options.dir);
|
|
136
155
|
this.audit = new gateway_audit_1.GatewayAudit(options.dir);
|
|
137
|
-
this.quotas = new gateway_quotas_1.GatewayQuotas(this.policy, this.tenants, this.usage, () => this.environments.settings.own);
|
|
156
|
+
this.quotas = new gateway_quotas_1.GatewayQuotas(this.policy, this.tenants, this.usage, () => this.environments.settings.own, () => this.models.enabled);
|
|
138
157
|
this.environments.guard = tenant => GatewayServerUtil.blockedReason(this.quotas.blocked(tenant));
|
|
158
|
+
this.models = new model_proxy_1.ModelProxy(models, {
|
|
159
|
+
tenantOfKey: key => this.tenants.list().find(tenant => tenant.modelKey && model_proxy_1.ModelProxyUtil.sameKey(key, tenant.modelKey)),
|
|
160
|
+
refuse: id => {
|
|
161
|
+
const tenant = this.tenants.get(id);
|
|
162
|
+
return tenant ? this.quotas.refuseModels(tenant) : 'No such account.';
|
|
163
|
+
},
|
|
164
|
+
record: (id, usage, cost) => this.quotas.addTokens(id, model_proxy_1.ModelProxyUtil.total(usage), cost),
|
|
165
|
+
}, env);
|
|
166
|
+
this.environments.envOf = (tenant, provider) => {
|
|
167
|
+
var _a, _b, _c;
|
|
168
|
+
if (!this.models.enabled) {
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
const url = (_a = provider.gatewayUrl) !== null && _a !== void 0 ? _a : GatewayServerUtil.reach(provider.type, (_c = (_b = this.port) !== null && _b !== void 0 ? _b : options.port) !== null && _c !== void 0 ? _c : 4100, sandbox_provider_1.SandboxProviders.publicBase(env));
|
|
172
|
+
return { TA_MODEL_PROXY_URL: url.replace(/\/+$/, ''), TA_MODEL_PROXY_KEY: this.tenants.modelKey(tenant.id) };
|
|
173
|
+
};
|
|
139
174
|
this.service = new gateway_service_1.GatewayService({
|
|
140
175
|
flow: this.flow,
|
|
141
176
|
tenants: this.tenants,
|
|
@@ -145,6 +180,7 @@ class GatewayServer {
|
|
|
145
180
|
usage: this.usage,
|
|
146
181
|
audit: this.audit,
|
|
147
182
|
hooks: { cutOff: () => this.cutOff(), reset: id => this.reset(id) },
|
|
183
|
+
models: this.models,
|
|
148
184
|
meta: { links: this.links, startedAt: Date.now(), version: options.version, publicUrl: sandbox_provider_1.SandboxProviders.publicBase(env) },
|
|
149
185
|
});
|
|
150
186
|
}
|
|
@@ -171,6 +207,7 @@ class GatewayServer {
|
|
|
171
207
|
server.once('error', reject);
|
|
172
208
|
server.listen((_a = this.options.port) !== null && _a !== void 0 ? _a : 4100, (_b = this.options.host) !== null && _b !== void 0 ? _b : '127.0.0.1', () => {
|
|
173
209
|
const { address, port } = server.address();
|
|
210
|
+
this.port = port;
|
|
174
211
|
resolve(`http://${address.includes(':') ? `[${address}]` : address}:${port}`);
|
|
175
212
|
});
|
|
176
213
|
});
|
|
@@ -227,6 +264,9 @@ class GatewayServer {
|
|
|
227
264
|
onSignedIn: (res, token, account, origin) => this.signedIn(res, token, account, origin),
|
|
228
265
|
});
|
|
229
266
|
}
|
|
267
|
+
else if (path === model_proxy_1.ModelProxyUtil.PATH || path.startsWith(`${model_proxy_1.ModelProxyUtil.PATH}/`)) {
|
|
268
|
+
await this.models.handle(request, response);
|
|
269
|
+
}
|
|
230
270
|
else if (path.startsWith(`${ta_protocol_1.TA_FILES_PATH}/`)) {
|
|
231
271
|
await this.files(request, response);
|
|
232
272
|
}
|
|
@@ -340,7 +380,7 @@ class GatewayServer {
|
|
|
340
380
|
upgrade(request, socket, head) {
|
|
341
381
|
var _a, _b;
|
|
342
382
|
const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://gateway');
|
|
343
|
-
if (url.pathname !== ta_protocol_1.TA_WEBSOCKET_PATH) {
|
|
383
|
+
if (url.pathname !== ta_protocol_1.TA_WEBSOCKET_PATH && url.pathname !== GatewayServerUtil.EXEC_PATH) {
|
|
344
384
|
socket.destroy();
|
|
345
385
|
return;
|
|
346
386
|
}
|
|
@@ -362,6 +402,17 @@ class GatewayServer {
|
|
|
362
402
|
return;
|
|
363
403
|
}
|
|
364
404
|
this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
|
|
405
|
+
if (url.pathname === GatewayServerUtil.EXEC_PATH) {
|
|
406
|
+
// Another Ta works in this account's sandbox: it counts as a page connected, and keeps the sandbox running.
|
|
407
|
+
const blocked = GatewayServerUtil.blockedReason(this.quotas.blocked(caller.tenant));
|
|
408
|
+
if (blocked) {
|
|
409
|
+
websocket_connection_1.WebSocketConnection.refuse(socket, 403, blocked);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
const exec = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 64 * 1024 * 1024, heartbeat: 30000 });
|
|
413
|
+
new gateway_exec_1.GatewayExecProxy(exec, this.environments.ensure(caller.tenant), this.environments.connect(caller.tenant.id));
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
365
416
|
const connection = websocket_connection_1.WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
|
|
366
417
|
const gatewaySocket = new gateway_socket_1.GatewaySocket(connection, caller, this.environments, this.service, this.quotas);
|
|
367
418
|
this.sockets.add(gatewaySocket);
|
|
@@ -5,6 +5,7 @@ import type { GatewayAudit } from './gateway-audit';
|
|
|
5
5
|
import { type GatewayPolicy } from './gateway-policy';
|
|
6
6
|
import type { GatewayQuotas } from './gateway-quotas';
|
|
7
7
|
import { type GatewayUsage } from './gateway-usage';
|
|
8
|
+
import { type ModelProxy } from './model-proxy';
|
|
8
9
|
import type { SignInLinks } from './sign-in-links';
|
|
9
10
|
import type { Tenant, TenantStore } from './tenant-store';
|
|
10
11
|
/** Who calls: the browser signed in as `account`, with the token `token`, and what that account is on the gateway. */
|
|
@@ -42,6 +43,7 @@ export interface GatewayParts {
|
|
|
42
43
|
reset(tenantId: string): void;
|
|
43
44
|
};
|
|
44
45
|
meta: GatewayMeta;
|
|
46
|
+
models?: ModelProxy;
|
|
45
47
|
}
|
|
46
48
|
type Need = TaGatewayRole | 'anyone';
|
|
47
49
|
export declare namespace GatewayServiceUtil {
|
|
@@ -92,6 +94,7 @@ export declare class GatewayService {
|
|
|
92
94
|
protected readonly audit: GatewayAudit;
|
|
93
95
|
protected readonly hooks: GatewayParts['hooks'];
|
|
94
96
|
protected readonly meta: GatewayMeta;
|
|
97
|
+
protected readonly models?: ModelProxy;
|
|
95
98
|
constructor(parts: GatewayParts);
|
|
96
99
|
call(caller: GatewayCaller, method: string, params: unknown[]): Promise<unknown>;
|
|
97
100
|
protected handle(caller: GatewayCaller, service: string, name: string, params: unknown[]): Promise<unknown>;
|
|
@@ -119,6 +122,11 @@ export declare class GatewayService {
|
|
|
119
122
|
protected setSuspended(caller: GatewayCaller, id: unknown, suspended: unknown): Promise<void>;
|
|
120
123
|
protected setDefaultLimits(value: unknown): TaGatewayPolicy;
|
|
121
124
|
protected setRole(caller: GatewayCaller, account: unknown, role: unknown): TaGatewayPolicy;
|
|
125
|
+
/** A sign-in of the caller's own account, named for where it is used. */
|
|
126
|
+
protected accessToken(caller: GatewayCaller, label: unknown): {
|
|
127
|
+
token: string;
|
|
128
|
+
url?: string;
|
|
129
|
+
};
|
|
122
130
|
protected access(caller: GatewayCaller): TaAccessInfo;
|
|
123
131
|
protected allow(account: unknown, name: unknown): void;
|
|
124
132
|
/** The browsers of the account are cut off, and what reaches its Ta otherwise (paired phones) goes with its sandbox. */
|