@celljs/ta-gateway 4.19.0 → 4.21.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.
Files changed (39) hide show
  1. package/esm/node/docker-engine.d.ts +14 -0
  2. package/esm/node/docker-engine.js +21 -2
  3. package/esm/node/docker-sandbox.d.ts +22 -4
  4. package/esm/node/docker-sandbox.js +104 -9
  5. package/esm/node/environments.d.ts +25 -2
  6. package/esm/node/environments.js +106 -13
  7. package/esm/node/gateway-files.d.ts +18 -0
  8. package/esm/node/gateway-files.js +36 -0
  9. package/esm/node/gateway-policy.d.ts +5 -1
  10. package/esm/node/gateway-policy.js +9 -0
  11. package/esm/node/gateway-server.d.ts +5 -11
  12. package/esm/node/gateway-server.js +22 -27
  13. package/esm/node/gateway-service-util.js +12 -0
  14. package/esm/node/gateway-service.d.ts +8 -1
  15. package/esm/node/gateway-service.js +37 -2
  16. package/esm/node/sandbox-provider.d.ts +24 -0
  17. package/esm/node/sandbox-updates.d.ts +56 -0
  18. package/esm/node/sandbox-updates.js +104 -0
  19. package/esm/node/tenant-store.d.ts +2 -0
  20. package/lib/node/docker-engine.d.ts +14 -0
  21. package/lib/node/docker-engine.js +21 -2
  22. package/lib/node/docker-sandbox.d.ts +22 -4
  23. package/lib/node/docker-sandbox.js +104 -9
  24. package/lib/node/environments.d.ts +25 -2
  25. package/lib/node/environments.js +106 -13
  26. package/lib/node/gateway-files.d.ts +18 -0
  27. package/lib/node/gateway-files.js +36 -0
  28. package/lib/node/gateway-policy.d.ts +5 -1
  29. package/lib/node/gateway-policy.js +9 -0
  30. package/lib/node/gateway-server.d.ts +5 -11
  31. package/lib/node/gateway-server.js +22 -27
  32. package/lib/node/gateway-service-util.js +12 -0
  33. package/lib/node/gateway-service.d.ts +8 -1
  34. package/lib/node/gateway-service.js +37 -2
  35. package/lib/node/sandbox-provider.d.ts +24 -0
  36. package/lib/node/sandbox-updates.d.ts +57 -0
  37. package/lib/node/sandbox-updates.js +108 -0
  38. package/lib/node/tenant-store.d.ts +2 -0
  39. package/package.json +5 -5
@@ -43,6 +43,11 @@ 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
+ rename(name: string, to: string): Promise<void>;
47
+ /** An image by its name or id; undefined when it is not here. */
48
+ image(image: string): Promise<DockerImage | undefined>;
49
+ /** Pulled again from its registry, for a newer one under the same name. */
50
+ pull(image: string, timeoutMs?: number): Promise<void>;
46
51
  /** Removed, its volumes kept; nothing when it is not there. */
47
52
  remove(name: string): Promise<void>;
48
53
  /**
@@ -55,6 +60,9 @@ export declare class DockerEngine {
55
60
  }
56
61
  export interface DockerContainer {
57
62
  Id: string;
63
+ /** The id of its image. */
64
+ Image?: string;
65
+ Created?: string;
58
66
  Config?: {
59
67
  Env?: string[];
60
68
  Labels?: Record<string, string>;
@@ -70,6 +78,12 @@ export interface DockerContainer {
70
78
  }[] | null>;
71
79
  };
72
80
  }
81
+ export interface DockerImage {
82
+ Id: string;
83
+ Config?: {
84
+ Labels?: Record<string, string> | null;
85
+ };
86
+ }
73
87
  /** As far as the console reads `/containers/<name>/stats`. */
74
88
  export interface DockerStats {
75
89
  cpu_stats?: {
@@ -132,6 +132,26 @@ export class DockerEngine {
132
132
  throw error;
133
133
  }
134
134
  }
135
+ async rename(name, to) {
136
+ await this.call('POST', `/containers/${encodeURIComponent(name)}/rename?name=${encodeURIComponent(to)}`);
137
+ }
138
+ /** An image by its name or id; undefined when it is not here. */
139
+ async image(image) {
140
+ try {
141
+ return (await this.call('GET', `/images/${encodeURIComponent(image)}/json`)).body;
142
+ }
143
+ catch (error) {
144
+ if (error instanceof DockerError && error.status === 404) {
145
+ return undefined;
146
+ }
147
+ throw error;
148
+ }
149
+ }
150
+ /** Pulled again from its registry, for a newer one under the same name. */
151
+ async pull(image, timeoutMs = 10 * 60 * 1000) {
152
+ const [repository, tag = 'latest'] = DockerEngineUtil.splitImage(image);
153
+ await this.call('POST', `/images/create?fromImage=${encodeURIComponent(repository)}&tag=${encodeURIComponent(tag)}`, undefined, timeoutMs);
154
+ }
135
155
  /** Removed, its volumes kept; nothing when it is not there. */
136
156
  async remove(name) {
137
157
  try {
@@ -174,8 +194,7 @@ export class DockerEngine {
174
194
  throw error;
175
195
  }
176
196
  }
177
- const [repository, tag = 'latest'] = DockerEngineUtil.splitImage(image);
178
- await this.call('POST', `/images/create?fromImage=${encodeURIComponent(repository)}&tag=${encodeURIComponent(tag)}`, undefined, 30 * 60 * 1000);
197
+ await this.pull(image, 30 * 60 * 1000);
179
198
  }
180
199
  }
181
200
  export var DockerEngineUtil;
@@ -1,5 +1,5 @@
1
- import { type DockerContainer, DockerEngine } from './docker-engine.js';
2
- import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage } from './sandbox-provider.js';
1
+ import { type DockerContainer, DockerEngine, type DockerImage } from './docker-engine.js';
2
+ import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage, type SandboxVersion, type SandboxVersions } from './sandbox-provider.js';
3
3
  export declare namespace DockerSandboxUtil {
4
4
  /** The label of a container that tells the environment the gateway gave it. */
5
5
  const ENV_LABEL = "cell.ta.env";
@@ -12,6 +12,12 @@ export declare namespace DockerSandboxUtil {
12
12
  function sameEnv(config: DockerContainer['Config'], want: Record<string, string> | undefined): boolean;
13
13
  /** Whether a container has each variable of `env` as it is. */
14
14
  function hasEnv(have: string[] | undefined, want: Record<string, string> | undefined): boolean;
15
+ /** What a container of a tenant is named while it is kept to go back to, after an update. */
16
+ const PREVIOUS = "-previous";
17
+ /** A version of Ta, as an image of it tells: its id, and the OCI labels the Dockerfile writes. */
18
+ function version(image: DockerImage | undefined, id?: string | undefined): SandboxVersion | undefined;
19
+ /** Whether an image is of a registry (`ghcr.io/me/ta`, `localhost:5000/ta`), a newer one of the same name to be pulled; `ta:latest` is built here. */
20
+ function remote(image: string): boolean;
15
21
  /** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
16
22
  function hostname(account: string): string;
17
23
  }
@@ -46,14 +52,26 @@ export declare class DockerSandbox implements SandboxProvider {
46
52
  readonly name: string;
47
53
  readonly gatewayUrl?: string;
48
54
  protected readonly engine: DockerEngine;
55
+ protected latestRead?: {
56
+ at: number;
57
+ image: Promise<DockerImage | undefined>;
58
+ };
59
+ protected pulledAt: number;
49
60
  static options(config: SandboxProviderConfig): DockerSandboxOptions;
50
61
  constructor(id: string, config: SandboxProviderConfig, options?: DockerSandboxOptions, engine?: DockerEngine);
51
62
  start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
63
+ versions(tenant: SandboxTenant, refresh?: boolean): Promise<SandboxVersions>;
64
+ rollback(tenant: SandboxTenant): Promise<string | undefined>;
65
+ forget(tenant: SandboxTenant): Promise<void>;
66
+ /** The image a new sandbox runs, read again after a few seconds. */
67
+ protected latest(): Promise<DockerImage | undefined>;
68
+ /** Made again on the latest, its volume kept; the one before is kept stopped, in place of one kept before it. */
69
+ protected renew(name: string, tenant: SandboxTenant): Promise<void>;
52
70
  stop(tenant: SandboxTenant): Promise<void>;
53
71
  state(tenant: SandboxTenant): Promise<SandboxState>;
54
72
  usage(tenant: SandboxTenant): Promise<SandboxUsage | undefined>;
55
73
  logs(tenant: SandboxTenant, lines: number): Promise<string>;
56
- /** What `docker run` would be given. */
57
- spec(tenant: SandboxTenant): object;
74
+ /** What `docker run` would be given: of `image` (an id) for one kept on a version, else of the latest. */
75
+ spec(tenant: SandboxTenant, image?: string): object;
58
76
  protected containerName(tenant: SandboxTenant): string;
59
77
  }
@@ -27,6 +27,27 @@ export var DockerSandboxUtil;
27
27
  return Object.entries(want !== null && want !== void 0 ? want : {}).every(([key, value]) => set.has(`${key}=${value}`));
28
28
  }
29
29
  DockerSandboxUtil.hasEnv = hasEnv;
30
+ /** What a container of a tenant is named while it is kept to go back to, after an update. */
31
+ DockerSandboxUtil.PREVIOUS = '-previous';
32
+ /** A version of Ta, as an image of it tells: its id, and the OCI labels the Dockerfile writes. */
33
+ function version(image, id = image === null || image === void 0 ? void 0 : image.Id) {
34
+ var _a;
35
+ var _b;
36
+ if (!id) {
37
+ return undefined;
38
+ }
39
+ const labels = (_b = (_a = image === null || image === void 0 ? void 0 : image.Config) === null || _a === void 0 ? void 0 : _a.Labels) !== null && _b !== void 0 ? _b : {};
40
+ const version = labels['org.opencontainers.image.version'] || undefined;
41
+ const revision = labels['org.opencontainers.image.revision'] || undefined;
42
+ return { id, ...(version ? { version } : {}), ...(revision ? { revision } : {}) };
43
+ }
44
+ DockerSandboxUtil.version = version;
45
+ /** Whether an image is of a registry (`ghcr.io/me/ta`, `localhost:5000/ta`), a newer one of the same name to be pulled; `ta:latest` is built here. */
46
+ function remote(image) {
47
+ const first = image.split('/')[0];
48
+ return image.includes('/') && (first.includes('.') || first.includes(':') || first === 'localhost');
49
+ }
50
+ DockerSandboxUtil.remote = remote;
30
51
  /** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
31
52
  function hostname(account) {
32
53
  const name = account
@@ -43,6 +64,10 @@ export var DockerSandboxUtil;
43
64
  })(DockerSandboxUtil || (DockerSandboxUtil = {}));
44
65
  /** The port of ta serve in the image (its Dockerfile). */
45
66
  const PORT = '4100/tcp';
67
+ /** How long the latest image, as read, holds: the console asks for each tenant at once. */
68
+ const LATEST_MS = 5000;
69
+ /** How often an image of a registry is pulled at most, for a newer one. */
70
+ const PULL_MS = 60000;
46
71
  /**
47
72
  * `docker`: a container per tenant, its home (sessions, model accounts, workspace) in a volume of its own,
48
73
  * with limits of memory, CPU and processes, in a network where sandboxes cannot reach each other. Its port is
@@ -76,34 +101,104 @@ export class DockerSandbox {
76
101
  this.id = id;
77
102
  this.options = options;
78
103
  this.type = 'docker';
104
+ this.pulledAt = 0;
79
105
  this.name = SandboxProviders.string(config, 'name', 'Docker');
80
106
  this.gatewayUrl = SandboxProviders.string(config, 'gatewayUrl');
81
107
  this.engine = engine !== null && engine !== void 0 ? engine : new DockerEngine({ host: options.host });
82
108
  }
83
109
  async start(tenant) {
84
- var _a, _b, _c;
110
+ var _a, _b, _c, _d;
85
111
  const name = this.containerName(tenant);
86
112
  let container = await this.engine.inspect(name);
87
- if (container && !DockerSandboxUtil.sameEnv(container.Config, tenant.env)) {
113
+ let updated = false;
114
+ const latest = container && ((_a = (await this.latest())) === null || _a === void 0 ? void 0 : _a.Id);
115
+ // Kept on the version it was moved back to while the latest is the one it left.
116
+ const kept = latest !== undefined && latest === tenant.skip ? container === null || container === void 0 ? void 0 : container.Image : undefined;
117
+ if (container && !container.State.Running && latest && container.Image !== latest && !kept) {
118
+ // A stopped one on an older version: made again on the latest, the one before kept to go back to.
119
+ await this.renew(name, tenant);
120
+ container = await this.engine.inspect(name);
121
+ updated = true;
122
+ }
123
+ else if (container && !DockerSandboxUtil.sameEnv(container.Config, tenant.env)) {
88
124
  // Made with another environment (the models of the gateway, its way out): made again, its volume kept.
89
125
  await this.engine.remove(name);
90
126
  container = undefined;
91
127
  }
92
128
  if (!container) {
93
- await this.engine.ensureImage(this.options.image);
129
+ await this.engine.ensureImage(kept !== null && kept !== void 0 ? kept : this.options.image);
94
130
  await this.engine.ensureNetwork(this.options.network, true);
95
- await this.engine.create(name, this.spec(tenant));
131
+ await this.engine.create(name, this.spec(tenant, kept));
96
132
  container = await this.engine.inspect(name);
97
133
  }
98
134
  if (!(container === null || container === void 0 ? void 0 : container.State.Running)) {
99
135
  await this.engine.start(name);
100
136
  container = await this.engine.inspect(name);
101
137
  }
102
- 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;
138
+ 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;
103
139
  if (!port) {
104
140
  throw new Error(`The container ${name} publishes no port for ${PORT}.`);
105
141
  }
106
- return { url: `http://${this.options.address}:${port}`, token: tenant.token };
142
+ return { url: `http://${this.options.address}:${port}`, token: tenant.token, ...(updated ? { updated } : {}) };
143
+ }
144
+ async versions(tenant, refresh = false) {
145
+ var _a, _b;
146
+ const image = this.options.image;
147
+ if (refresh && DockerSandboxUtil.remote(image) && Date.now() - this.pulledAt > PULL_MS) {
148
+ this.pulledAt = Date.now();
149
+ this.latestRead = undefined;
150
+ await this.engine.pull(image).catch(error => console.warn(`ta gateway: pulling ${image} failed: ${error.message}`));
151
+ }
152
+ const name = this.containerName(tenant);
153
+ const [latest, container, previous] = await Promise.all([
154
+ this.latest(),
155
+ this.engine.inspect(name),
156
+ this.engine.inspect(`${name}${DockerSandboxUtil.PREVIOUS}`),
157
+ ]);
158
+ const of = async (id) => id === (latest === null || latest === void 0 ? void 0 : latest.Id) ? DockerSandboxUtil.version(latest) : DockerSandboxUtil.version(id ? await this.engine.image(id) : undefined, id);
159
+ const [current, before] = await Promise.all([of(container === null || container === void 0 ? void 0 : container.Image), of(previous === null || previous === void 0 ? void 0 : previous.Image)]);
160
+ return {
161
+ latest: DockerSandboxUtil.version(latest),
162
+ current,
163
+ // Since the one after it was made: when it was left.
164
+ previous: before && { ...before, since: Date.parse((_b = (_a = container === null || container === void 0 ? void 0 : container.Created) !== null && _a !== void 0 ? _a : previous === null || previous === void 0 ? void 0 : previous.Created) !== null && _b !== void 0 ? _b : '') || Date.now() },
165
+ };
166
+ }
167
+ async rollback(tenant) {
168
+ var _a;
169
+ const name = this.containerName(tenant);
170
+ const previous = `${name}${DockerSandboxUtil.PREVIOUS}`;
171
+ if (!(await this.engine.inspect(previous))) {
172
+ throw new Error(`${name} has no version before to go back to.`);
173
+ }
174
+ const left = (_a = (await this.engine.inspect(name))) === null || _a === void 0 ? void 0 : _a.Image;
175
+ await this.engine.remove(name);
176
+ await this.engine.rename(previous, name);
177
+ return left;
178
+ }
179
+ async forget(tenant) {
180
+ await this.engine.remove(`${this.containerName(tenant)}${DockerSandboxUtil.PREVIOUS}`);
181
+ }
182
+ /** The image a new sandbox runs, read again after a few seconds. */
183
+ latest() {
184
+ if (!this.latestRead || Date.now() - this.latestRead.at > LATEST_MS) {
185
+ this.latestRead = { at: Date.now(), image: this.engine.image(this.options.image).catch(() => undefined) };
186
+ }
187
+ return this.latestRead.image;
188
+ }
189
+ /** Made again on the latest, its volume kept; the one before is kept stopped, in place of one kept before it. */
190
+ async renew(name, tenant) {
191
+ const previous = `${name}${DockerSandboxUtil.PREVIOUS}`;
192
+ await this.engine.remove(previous);
193
+ await this.engine.rename(name, previous);
194
+ try {
195
+ await this.engine.ensureNetwork(this.options.network, true);
196
+ await this.engine.create(name, this.spec(tenant));
197
+ }
198
+ catch (error) {
199
+ await this.engine.rename(previous, name).catch(() => undefined);
200
+ throw error;
201
+ }
107
202
  }
108
203
  async stop(tenant) {
109
204
  await this.engine.stop(this.containerName(tenant));
@@ -118,11 +213,11 @@ export class DockerSandbox {
118
213
  logs(tenant, lines) {
119
214
  return this.engine.logs(this.containerName(tenant), lines);
120
215
  }
121
- /** What `docker run` would be given. */
122
- spec(tenant) {
216
+ /** What `docker run` would be given: of `image` (an id) for one kept on a version, else of the latest. */
217
+ spec(tenant, image = this.options.image) {
123
218
  const name = this.containerName(tenant);
124
219
  return {
125
- Image: this.options.image,
220
+ Image: image,
126
221
  // What the Ta of the tenant tells its clients its machine is, as the list of computers of the phone shows it.
127
222
  Hostname: DockerSandboxUtil.hostname(tenant.account),
128
223
  Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries({ ...this.options.env, ...tenant.env }).map(([key, value]) => `${key}=${value}`)],
@@ -1,5 +1,5 @@
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.js';
1
+ import { type TaAgentActivity, type TaAgentCounts, type TaAgentSession, type TaAgentStats, type TaEnvironmentChoice, type TaEnvironmentInfo, type TaEnvironmentOption, type TaEnvironmentStatus, type TaSandboxVersion, type TaSessionInfo, type TaTenantAgents, type TaUsageBucket } from '@celljs/ta-protocol';
2
+ import type { SandboxEndpoint, SandboxProvider, SandboxTenant, SandboxUsage, SandboxVersions } from './sandbox-provider.js';
3
3
  import type { Tenant, TenantStore } from './tenant-store.js';
4
4
  interface Running {
5
5
  status: TaEnvironmentStatus;
@@ -8,6 +8,8 @@ interface Running {
8
8
  starting?: Promise<SandboxEndpoint>;
9
9
  connections: number;
10
10
  idle?: ReturnType<typeof setTimeout>;
11
+ /** What the start of now has to say once it runs: that it went back to the version before. */
12
+ note?: string;
11
13
  }
12
14
  export declare class EnvironmentError extends Error {
13
15
  }
@@ -31,6 +33,10 @@ export declare namespace EnvironmentsUtil {
31
33
  /** A session as an administrator sees it: never what was said in it. */
32
34
  function agentSession(session: TaSessionInfo, stats?: TaAgentStats): TaAgentSession;
33
35
  function sandboxTenant(tenant: Tenant): SandboxTenant;
36
+ /** The newer version a sandbox may move to: none when it runs the latest, has none yet, or was moved back from it. */
37
+ function behind(versions: SandboxVersions | undefined, skip?: string): TaSandboxVersion | undefined;
38
+ /** What a version is, as people read it: `4.18.0`, else the start of its id. */
39
+ function label(version: TaSandboxVersion | undefined): string;
34
40
  }
35
41
  /**
36
42
  * The environments of the tenants: which provider runs each, starting it on its first connection (once,
@@ -46,6 +52,10 @@ export declare class Environments {
46
52
  readyTimeoutMs?: number;
47
53
  };
48
54
  protected readonly running: Map<string, Running>;
55
+ /** The versions of each tenant's sandbox, as last read (readVersions). */
56
+ protected readonly versions: Map<string, SandboxVersions>;
57
+ /** A sandbox made on a newer version did not answer, and went back to the one before: `from`, the version it left. */
58
+ rolledBack?: (tenant: Tenant, from: string | undefined, reason: string) => void;
49
59
  /** Why the tenant's Ta may not start now (suspended, its free minutes used), checked before each start. */
50
60
  guard?: (tenant: Tenant) => string | undefined;
51
61
  /**
@@ -67,6 +77,19 @@ export declare class Environments {
67
77
  own: boolean;
68
78
  };
69
79
  info(tenant: Tenant): TaEnvironmentInfo;
80
+ /** The versions of its sandbox read again, for info; none for a Ta service of the user's, or a provider without versions. */
81
+ readVersions(tenant: Tenant, refresh?: boolean): Promise<SandboxVersions | undefined>;
82
+ /** Its sandbox goes back to the version it ran before its update, stopped, and stays on it; its connections are the caller's to close. */
83
+ rollback(tenant: Tenant): Promise<void>;
84
+ /**
85
+ * A sandbox that runs while the gateway took it for stopped (the gateway started again, nobody connected since)
86
+ * is taken for running: its minutes count, and it may move to a newer version. Nothing is started.
87
+ */
88
+ adopt(tenant: Tenant): Promise<void>;
89
+ /** The versions kept to go back to for longer than a week are dropped. */
90
+ forgetPrevious(now?: number): Promise<void>;
91
+ /** The conversations of its Ta, while it runs in a sandbox of the gateway's; undefined otherwise or when it does not answer soon. */
92
+ sessions(tenant: Tenant, timeoutMs?: number): Promise<TaSessionInfo[] | undefined>;
70
93
  /** What the sandbox of a running tenant takes, when its provider tells; a provider that fails to tell leaves it out. */
71
94
  usage(tenant: Tenant): Promise<SandboxUsage | undefined>;
72
95
  /** The last lines its sandbox wrote; a Ta service of the user's, or a provider without logs, has none for the gateway. */
@@ -2,6 +2,8 @@ import { TA_WEBSOCKET_PATH, } from '@celljs/ta-protocol';
2
2
  import { TaSandbox } from './ta-sandbox.js';
3
3
  /** How long a sandbox has to answer once started: the first start of a container may pull its image first. */
4
4
  const READY_TIMEOUT_MS = 120000;
5
+ /** How long the version a sandbox ran before its update is kept to go back to. */
6
+ const KEEP_PREVIOUS_MS = 7 * 24 * 3600000;
5
7
  export class EnvironmentError extends Error {
6
8
  }
7
9
  export var EnvironmentsUtil;
@@ -148,9 +150,21 @@ export var EnvironmentsUtil;
148
150
  }
149
151
  EnvironmentsUtil.agentSession = agentSession;
150
152
  function sandboxTenant(tenant) {
151
- return { id: tenant.id, account: tenant.account, token: tenant.token };
153
+ return { id: tenant.id, account: tenant.account, token: tenant.token, ...(tenant.skipVersion ? { skip: tenant.skipVersion } : {}) };
152
154
  }
153
155
  EnvironmentsUtil.sandboxTenant = sandboxTenant;
156
+ /** The newer version a sandbox may move to: none when it runs the latest, has none yet, or was moved back from it. */
157
+ function behind(versions, skip) {
158
+ const { latest, current } = versions !== null && versions !== void 0 ? versions : {};
159
+ return latest && current && latest.id !== current.id && latest.id !== skip ? latest : undefined;
160
+ }
161
+ EnvironmentsUtil.behind = behind;
162
+ /** What a version is, as people read it: `4.18.0`, else the start of its id. */
163
+ function label(version) {
164
+ var _a, _b;
165
+ return (_b = (_a = version === null || version === void 0 ? void 0 : version.version) !== null && _a !== void 0 ? _a : version === null || version === void 0 ? void 0 : version.id.replace(/^sha256:/, '').slice(0, 12)) !== null && _b !== void 0 ? _b : 'another version';
166
+ }
167
+ EnvironmentsUtil.label = label;
154
168
  })(EnvironmentsUtil || (EnvironmentsUtil = {}));
155
169
  /**
156
170
  * The environments of the tenants: which provider runs each, starting it on its first connection (once,
@@ -162,6 +176,8 @@ export class Environments {
162
176
  this.tenants = tenants;
163
177
  this.settings = settings;
164
178
  this.running = new Map();
179
+ /** The versions of each tenant's sandbox, as last read (readVersions). */
180
+ this.versions = new Map();
165
181
  }
166
182
  /** The providers one may pick. */
167
183
  choices() {
@@ -186,7 +202,7 @@ export class Environments {
186
202
  return { provider, own: false };
187
203
  }
188
204
  info(tenant) {
189
- var _a;
205
+ var _a, _b;
190
206
  const running = this.running.get(tenant.id);
191
207
  let picked;
192
208
  try {
@@ -196,14 +212,77 @@ export class Environments {
196
212
  return { provider: '', name: '', status: 'failed', error: error.message };
197
213
  }
198
214
  const { provider, own } = picked;
215
+ const versions = own ? undefined : this.versions.get(tenant.id);
216
+ const latest = EnvironmentsUtil.behind(versions, tenant.skipVersion);
217
+ const { since, ...before } = (_a = versions === null || versions === void 0 ? void 0 : versions.previous) !== null && _a !== void 0 ? _a : { since: 0 };
199
218
  return {
200
219
  provider: own ? 'own' : provider.id,
201
220
  name: provider.name,
202
- status: (_a = running === null || running === void 0 ? void 0 : running.status) !== null && _a !== void 0 ? _a : 'stopped',
221
+ status: (_b = running === null || running === void 0 ? void 0 : running.status) !== null && _b !== void 0 ? _b : 'stopped',
203
222
  error: running === null || running === void 0 ? void 0 : running.error,
204
223
  url: own && provider instanceof TaSandbox ? provider.url : undefined,
224
+ ...((versions === null || versions === void 0 ? void 0 : versions.current) ? { version: versions.current } : {}),
225
+ ...(latest ? { latest } : {}),
226
+ ...('id' in before ? { previous: { ...before, until: since + KEEP_PREVIOUS_MS } } : {}),
205
227
  };
206
228
  }
229
+ /** The versions of its sandbox read again, for info; none for a Ta service of the user's, or a provider without versions. */
230
+ async readVersions(tenant, refresh = false) {
231
+ const { provider, own } = this.provider(tenant);
232
+ if (own || !provider.versions) {
233
+ this.versions.delete(tenant.id);
234
+ return undefined;
235
+ }
236
+ const versions = await provider.versions(EnvironmentsUtil.sandboxTenant(tenant), refresh).catch(() => this.versions.get(tenant.id));
237
+ if (versions) {
238
+ this.versions.set(tenant.id, versions);
239
+ }
240
+ return versions;
241
+ }
242
+ /** Its sandbox goes back to the version it ran before its update, stopped, and stays on it; its connections are the caller's to close. */
243
+ async rollback(tenant) {
244
+ var _a;
245
+ const { provider, own } = this.provider(tenant);
246
+ if (own || !provider.rollback) {
247
+ throw new EnvironmentError(`The sandboxes of ${provider.name} keep no version to go back to.`);
248
+ }
249
+ await this.stop(tenant.id);
250
+ const left = await provider.rollback(EnvironmentsUtil.sandboxTenant(tenant));
251
+ this.tenants.update(tenant.id, { skipVersion: left });
252
+ await this.readVersions((_a = this.tenants.get(tenant.id)) !== null && _a !== void 0 ? _a : tenant).catch(() => undefined);
253
+ }
254
+ /**
255
+ * A sandbox that runs while the gateway took it for stopped (the gateway started again, nobody connected since)
256
+ * is taken for running: its minutes count, and it may move to a newer version. Nothing is started.
257
+ */
258
+ async adopt(tenant) {
259
+ const { provider, own } = this.provider(tenant);
260
+ const running = this.running.get(tenant.id);
261
+ if (own || (running === null || running === void 0 ? void 0 : running.status) === 'running' || (running === null || running === void 0 ? void 0 : running.starting)) {
262
+ return;
263
+ }
264
+ if ((await provider.state(EnvironmentsUtil.sandboxTenant(tenant)).catch(() => 'missing')) === 'running') {
265
+ await this.ensure(tenant).catch(() => undefined);
266
+ }
267
+ }
268
+ /** The versions kept to go back to for longer than a week are dropped. */
269
+ async forgetPrevious(now = Date.now()) {
270
+ for (const tenant of this.tenants.list()) {
271
+ const versions = this.versions.get(tenant.id);
272
+ const provider = (versions === null || versions === void 0 ? void 0 : versions.previous) && now - versions.previous.since > KEEP_PREVIOUS_MS ? this.provider(tenant).provider : undefined;
273
+ if (versions && (provider === null || provider === void 0 ? void 0 : provider.forget)) {
274
+ await provider.forget(EnvironmentsUtil.sandboxTenant(tenant)).catch(() => undefined);
275
+ this.versions.set(tenant.id, { ...versions, previous: undefined });
276
+ }
277
+ }
278
+ }
279
+ /** The conversations of its Ta, while it runs in a sandbox of the gateway's; undefined otherwise or when it does not answer soon. */
280
+ sessions(tenant, timeoutMs = 3000) {
281
+ const endpoint = this.watched(tenant);
282
+ return endpoint
283
+ ? EnvironmentsUtil.call(endpoint, 'TaServer/listSessions', [], timeoutMs).catch(() => undefined)
284
+ : Promise.resolve(undefined);
285
+ }
207
286
  /** What the sandbox of a running tenant takes, when its provider tells; a provider that fails to tell leaves it out. */
208
287
  async usage(tenant) {
209
288
  var _a;
@@ -253,11 +332,7 @@ export class Environments {
253
332
  }
254
333
  /** How many conversations its Ta has open and how many work or wait; undefined when it does not run, or does not answer soon. */
255
334
  async agentSummary(tenant, timeoutMs = 3000) {
256
- const endpoint = this.watched(tenant);
257
- if (!endpoint) {
258
- return undefined;
259
- }
260
- const sessions = await EnvironmentsUtil.call(endpoint, 'TaServer/listSessions', [], timeoutMs).catch(() => undefined);
335
+ const sessions = await this.sessions(tenant, timeoutMs);
261
336
  return sessions && EnvironmentsUtil.summary(sessions);
262
337
  }
263
338
  /** The conversations open in its Ta, each with pi's statistics of it, over one connection. */
@@ -307,20 +382,38 @@ export class Environments {
307
382
  running.status = 'starting';
308
383
  running.error = undefined;
309
384
  const starting = (async () => {
310
- var _a;
311
- var _b;
385
+ var _a, _b;
386
+ var _c, _d;
312
387
  const { provider, own } = this.provider(tenant);
313
388
  const sandbox = EnvironmentsUtil.sandboxTenant(tenant);
314
389
  const fresh = !own && this.envOf ? (await provider.state(sandbox).catch(() => 'missing')) === 'missing' : false;
315
390
  const env = own ? undefined : (_a = this.envOf) === null || _a === void 0 ? void 0 : _a.call(this, tenant, provider, fresh);
316
- const endpoint = await provider.start({ ...sandbox, ...(env ? { env } : {}) });
317
- await EnvironmentsUtil.waitReady(endpoint.url, (_b = this.settings.readyTimeoutMs) !== null && _b !== void 0 ? _b : provider.readyTimeoutMs);
391
+ const timeout = (_c = this.settings.readyTimeoutMs) !== null && _c !== void 0 ? _c : provider.readyTimeoutMs;
392
+ let endpoint = await provider.start({ ...sandbox, ...(env ? { env } : {}) });
393
+ try {
394
+ await EnvironmentsUtil.waitReady(endpoint.url, timeout);
395
+ }
396
+ catch (error) {
397
+ if (!endpoint.updated || !provider.rollback) {
398
+ throw error;
399
+ }
400
+ // Made on a newer version that does not answer: back to the one before, which stays.
401
+ const left = await provider.rollback(sandbox);
402
+ this.tenants.update(tenant.id, { skipVersion: left });
403
+ const back = await provider.start({ ...sandbox, skip: left, ...(env ? { env } : {}) });
404
+ await EnvironmentsUtil.waitReady(back.url, timeout);
405
+ const reason = error.message;
406
+ (_b = this.rolledBack) === null || _b === void 0 ? void 0 : _b.call(this, tenant, left, reason);
407
+ running.note = `A newer version did not start, so it went back to the one before: ${reason}`;
408
+ endpoint = back;
409
+ }
410
+ await this.readVersions((_d = this.tenants.get(tenant.id)) !== null && _d !== void 0 ? _d : tenant).catch(() => undefined);
318
411
  return endpoint;
319
412
  })();
320
413
  running.starting = starting;
321
414
  starting.then(endpoint => {
322
415
  if (running.starting === starting) {
323
- Object.assign(running, { status: 'running', endpoint, starting: undefined });
416
+ Object.assign(running, { status: 'running', endpoint, starting: undefined, error: running.note, note: undefined });
324
417
  }
325
418
  }, (error) => {
326
419
  if (running.starting === starting) {
@@ -1,6 +1,24 @@
1
1
  import { type IncomingHttpHeaders, type IncomingMessage, type ServerResponse } from 'node:http';
2
2
  /** `/api/files` of the Ta of a tenant, as the gateway passes a read on to it. */
3
3
  export declare namespace GatewayFiles {
4
+ /**
5
+ * Where a request of `/api/files` goes in the Ta of its tenant: undefined for one whose path, once its dots
6
+ * are resolved (`/api/files/../../x`, `%2e%2e`), is not of `/api/files` there, which would reach any
7
+ * path of that address, and of any address a tenant names as its own Ta service.
8
+ */
9
+ function target(requestUrl: string, endpoint: string): URL | undefined;
10
+ /**
11
+ * What a file read through the gateway may do, whatever the Ta of the tenant said: run its scripts in an origin of
12
+ * its own (as ta serve's WorkspaceFiles has it), never in the gateway's, where the console and its sign-ins are.
13
+ */
14
+ const SANDBOX = "sandbox allow-scripts allow-forms allow-popups allow-modals allow-downloads";
15
+ /**
16
+ * The headers of an answer of the Ta of a tenant, as the browser gets them: without cookies, which a Ta
17
+ * service of the user's (or what runs in a sandbox) would otherwise set on the gateway's origin, and sandboxed by
18
+ * the gateway itself, not trusting what runs there to say so. A PDF alone is left out: browsers do not show one
19
+ * sandboxed, and none runs scripts in the gateway's origin.
20
+ */
21
+ function headers(headers: IncomingMessage['headers']): IncomingMessage['headers'];
4
22
  /** Reads `target` for `request`, its answer to `response` with the headers `answered` lets through. */
5
23
  function forward(request: IncomingMessage, response: ServerResponse, target: URL, answered: (headers: IncomingHttpHeaders) => IncomingHttpHeaders): Promise<void>;
6
24
  }
@@ -1,11 +1,47 @@
1
1
  import { request as httpRequest } from 'node:http';
2
2
  import { request as httpsRequest } from 'node:https';
3
3
  import { pipeline } from 'node:stream';
4
+ import { TA_FILES_PATH } from '@celljs/ta-protocol';
4
5
  /** `/api/files` of the Ta of a tenant, as the gateway passes a read on to it. */
5
6
  export var GatewayFiles;
6
7
  (function (GatewayFiles) {
7
8
  /** What of a read the Ta of the tenant is told: its range and what the browser takes, nothing of who asked. */
8
9
  const PASSED = ['range', 'if-none-match', 'accept', 'accept-encoding', 'user-agent'];
10
+ /**
11
+ * Where a request of `/api/files` goes in the Ta of its tenant: undefined for one whose path, once its dots
12
+ * are resolved (`/api/files/../../x`, `%2e%2e`), is not of `/api/files` there, which would reach any
13
+ * path of that address, and of any address a tenant names as its own Ta service.
14
+ */
15
+ function target(requestUrl, endpoint) {
16
+ const target = new URL(requestUrl, endpoint);
17
+ return target.origin === new URL(endpoint).origin && target.pathname.startsWith(`${TA_FILES_PATH}/`) ? target : undefined;
18
+ }
19
+ GatewayFiles.target = target;
20
+ /**
21
+ * What a file read through the gateway may do, whatever the Ta of the tenant said: run its scripts in an origin of
22
+ * its own (as ta serve's WorkspaceFiles has it), never in the gateway's, where the console and its sign-ins are.
23
+ */
24
+ GatewayFiles.SANDBOX = 'sandbox allow-scripts allow-forms allow-popups allow-modals allow-downloads';
25
+ /**
26
+ * The headers of an answer of the Ta of a tenant, as the browser gets them: without cookies, which a Ta
27
+ * service of the user's (or what runs in a sandbox) would otherwise set on the gateway's origin, and sandboxed by
28
+ * the gateway itself, not trusting what runs there to say so. A PDF alone is left out: browsers do not show one
29
+ * sandboxed, and none runs scripts in the gateway's origin.
30
+ */
31
+ function headers(headers) {
32
+ var _a;
33
+ const { 'set-cookie': _cookies, 'content-security-policy': _policy, 'x-content-type-options': _sniff, ...rest } = headers;
34
+ const type = String((_a = rest['content-type']) !== null && _a !== void 0 ? _a : '')
35
+ .split(';')[0]
36
+ .trim()
37
+ .toLowerCase();
38
+ return {
39
+ ...rest,
40
+ 'x-content-type-options': 'nosniff',
41
+ ...(type === 'application/pdf' ? {} : { 'content-security-policy': GatewayFiles.SANDBOX }),
42
+ };
43
+ }
44
+ GatewayFiles.headers = headers;
9
45
  /** Reads `target` for `request`, its answer to `response` with the headers `answered` lets through. */
10
46
  function forward(request, response, target, answered) {
11
47
  const headers = {};
@@ -1,4 +1,4 @@
1
- import type { TaGatewayLimits, TaGatewayPolicy, TaGatewayRole } from '@celljs/ta-protocol';
1
+ import type { TaGatewayLimits, TaGatewayPolicy, TaGatewayRole, TaUpdateMode } from '@celljs/ta-protocol';
2
2
  import type { EgressSettings } from './egress-proxy.js';
3
3
  interface StoredPolicy {
4
4
  defaults?: TaGatewayLimits;
@@ -6,6 +6,8 @@ interface StoredPolicy {
6
6
  admins?: string[];
7
7
  /** The hosts members' sandboxes may reach through the proxy of the gateway; none: any public host. */
8
8
  egressHosts?: string[];
9
+ /** When running sandboxes move to a newer version of Ta; none: once nothing works in them. */
10
+ updates?: TaUpdateMode;
9
11
  }
10
12
  /** The limits of a member once the defaults and their own are taken together: none where a value is missing. */
11
13
  export interface ResolvedLimits {
@@ -45,6 +47,8 @@ export declare class GatewayPolicy {
45
47
  setDefaults(limits: TaGatewayLimits): void;
46
48
  get egressHosts(): string[];
47
49
  setEgressHosts(hosts: string[]): void;
50
+ get updates(): TaUpdateMode;
51
+ setUpdates(mode: TaUpdateMode): void;
48
52
  setRole(account: string, role: 'admin' | 'member'): void;
49
53
  view(idleMinutes: number, egress?: EgressSettings): TaGatewayPolicy;
50
54
  protected read(): StoredPolicy;
@@ -130,6 +130,14 @@ export class GatewayPolicy {
130
130
  this.stored = { ...this.stored, egressHosts: hosts.length > 0 ? hosts : undefined };
131
131
  writePrivate(this.file, this.stored);
132
132
  }
133
+ get updates() {
134
+ var _a;
135
+ return (_a = this.stored.updates) !== null && _a !== void 0 ? _a : 'idle';
136
+ }
137
+ setUpdates(mode) {
138
+ this.stored = { ...this.stored, updates: mode };
139
+ writePrivate(this.file, this.stored);
140
+ }
133
141
  setRole(account, role) {
134
142
  var _a;
135
143
  const admins = ((_a = this.stored.admins) !== null && _a !== void 0 ? _a : []).filter(other => other !== account);
@@ -146,6 +154,7 @@ export class GatewayPolicy {
146
154
  ],
147
155
  idleMinutes,
148
156
  egress: { enabled: egress.enabled, hosts: this.egressHosts, networks: egress.networks },
157
+ updates: this.updates,
149
158
  };
150
159
  }
151
160
  read() {