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