@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
@@ -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
@@ -92,6 +92,17 @@ export var GatewayServerUtil;
92
92
  return given;
93
93
  }
94
94
  GatewayServerUtil.deploymentEnv = deploymentEnv;
95
+ /**
96
+ * What makes a sandbox a Ta in the cloud of its account (TaAccountService.cloud): where it reaches this gateway's
97
+ * accounts, and the address devices know the gateway by, the only account it joins.
98
+ */
99
+ function accountEnv(env, url) {
100
+ var _a;
101
+ var _b;
102
+ const service = (_a = ((_b = env.TA_GATEWAY_URL) !== null && _b !== void 0 ? _b : env.TA_PUBLIC_URL)) === null || _a === void 0 ? void 0 : _a.trim().replace(/\/+$/, '');
103
+ return { TA_ACCOUNT_KIND: 'cloud', TA_ACCOUNT_URL: url, ...(service ? { TA_ACCOUNT_SERVICE: service } : {}) };
104
+ }
105
+ GatewayServerUtil.accountEnv = accountEnv;
95
106
  /** Where another Ta reaches the exec server of its account's sandbox. */
96
107
  GatewayServerUtil.EXEC_PATH = '/api/exec';
97
108
  /** 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. */
@@ -122,25 +133,6 @@ export var GatewayServerUtil;
122
133
  return join(root, 'index.html');
123
134
  }
124
135
  GatewayServerUtil.file = file;
125
- /**
126
- * Where a request of `/api/files` goes in the Ta of its tenant: undefined for one whose path, once its dots
127
- * are resolved (`/api/files/../../x`, `%2e%2e`), is not of `/api/files` there, which would reach any
128
- * path of that address, and of any address a tenant names as its own Ta service.
129
- */
130
- function filesTarget(requestUrl, endpoint) {
131
- const target = new URL(requestUrl, endpoint);
132
- return target.origin === new URL(endpoint).origin && target.pathname.startsWith(`${TA_FILES_PATH}/`) ? target : undefined;
133
- }
134
- GatewayServerUtil.filesTarget = filesTarget;
135
- /**
136
- * The headers of an answer of the Ta of a tenant, as the browser gets them: without cookies, which a Ta
137
- * service of the user's (or what runs in a sandbox) would otherwise set on the gateway's origin.
138
- */
139
- function filesHeaders(headers) {
140
- const { 'set-cookie': _cookies, ...rest } = headers;
141
- return rest;
142
- }
143
- GatewayServerUtil.filesHeaders = filesHeaders;
144
136
  })(GatewayServerUtil || (GatewayServerUtil = {}));
145
137
  /**
146
138
  * `ta gateway`: one sign-in for many people, each with a Ta of their own. An account that signs in is a
@@ -172,7 +164,11 @@ export class GatewayServer {
172
164
  this.flow = new SignInFlow(SignInProviders.fromEnv(env), new AccessStore(join(options.dir, 'access.json'), allowed), SignInProviders.publicUrl(env), SignInProviders.polled(env));
173
165
  this.tenants = new TenantStore(options.dir);
174
166
  // The devices of each account (docs/design/ta-account.md 3), its tokens those of this gateway's sign-in.
175
- this.accounts = new RelayServerAccounts(options.dir, { authenticate: async (token) => GatewayServerUtil.accountOf(this.caller(token)) });
167
+ this.accounts = new RelayServerAccounts(options.dir, {
168
+ authenticate: async (token) => GatewayServerUtil.accountOf(this.caller(token)),
169
+ // A computer the user scanned joins their account with a sign-in of its own (docs/design/ta-me.md 4).
170
+ issue: async (account) => this.flow.store.signIn({ id: account.id, name: account.name }, 'A computer of the account'),
171
+ });
176
172
  this.links = new SignInLinks(options.dir);
177
173
  this.environments = new Environments(providers, this.tenants, {
178
174
  default: config.default,
@@ -195,13 +191,10 @@ export class GatewayServer {
195
191
  this.quotas.egressOf = tenant => (this.egress.enabled ? this.egress.refused(tenant.id) : undefined);
196
192
  this.environments.envOf = (tenant, provider, fresh) => {
197
193
  var _a, _b, _c;
198
- const deployment = GatewayServerUtil.deploymentEnv(env);
199
- if (!this.models.enabled && !this.egress.enabled) {
200
- return Object.keys(deployment).length ? deployment : undefined;
201
- }
202
194
  const base = (_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, SandboxProviders.publicBase(env));
203
195
  const url = base.replace(/\/+$/, '');
204
- const given = { ...deployment };
196
+ // The sandbox is a device of its account (docs/design/ta-me.md 2): the accounts of this gateway, from within.
197
+ const given = { ...GatewayServerUtil.deploymentEnv(env), ...GatewayServerUtil.accountEnv(env, url) };
205
198
  if (this.models.enabled) {
206
199
  Object.assign(given, { TA_MODEL_PROXY_URL: url, TA_MODEL_PROXY_KEY: this.tenants.modelKey(tenant.id) });
207
200
  }
@@ -276,6 +269,7 @@ export class GatewayServer {
276
269
  this.server = server;
277
270
  this.ticker = setInterval(() => void this.tick().catch(error => console.warn(`ta gateway: counting minutes failed: ${error.message}`)), TICK_MS);
278
271
  (_b = (_a = this.ticker).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
272
+ this.service.updates.start();
279
273
  return new Promise((resolve, reject) => {
280
274
  var _a, _b;
281
275
  server.once('error', reject);
@@ -288,6 +282,7 @@ export class GatewayServer {
288
282
  }
289
283
  async close() {
290
284
  clearInterval(this.ticker);
285
+ this.service.updates.dispose();
291
286
  this.flow.stopPolling();
292
287
  await this.tick().catch(() => undefined);
293
288
  for (const socket of this.sockets) {
@@ -465,12 +460,12 @@ export class GatewayServer {
465
460
  return;
466
461
  }
467
462
  const endpoint = await this.environments.ensure(caller.tenant);
468
- const target = GatewayServerUtil.filesTarget((_b = request.url) !== null && _b !== void 0 ? _b : '/', endpoint.url);
463
+ const target = GatewayFiles.target((_b = request.url) !== null && _b !== void 0 ? _b : '/', endpoint.url);
469
464
  if (!target) {
470
465
  SignInPageUtil.end(response, 404);
471
466
  return;
472
467
  }
473
- await GatewayFiles.forward(request, response, target, GatewayServerUtil.filesHeaders);
468
+ await GatewayFiles.forward(request, response, target, GatewayFiles.headers);
474
469
  }
475
470
  page(request, response, path) {
476
471
  var _a;
@@ -22,6 +22,7 @@ export var GatewayServiceUtil;
22
22
  getGateway: 'anyone',
23
23
  setEnvironment: 'anyone',
24
24
  restartEnvironment: 'anyone',
25
+ updateEnvironment: 'anyone',
25
26
  listTenants: 'admin',
26
27
  getConsole: 'admin',
27
28
  getTenantAgents: 'admin',
@@ -33,6 +34,10 @@ export var GatewayServiceUtil;
33
34
  startTenant: 'admin',
34
35
  stopTenant: 'admin',
35
36
  restartTenant: 'admin',
37
+ updateTenant: 'admin',
38
+ updateTenants: 'admin',
39
+ rollbackTenant: 'admin',
40
+ checkUpdates: 'admin',
36
41
  createSignInLink: 'admin',
37
42
  setTenantLimits: 'admin',
38
43
  grantMinutes: 'admin',
@@ -40,6 +45,7 @@ export var GatewayServiceUtil;
40
45
  setDefaultLimits: 'owner',
41
46
  setRole: 'owner',
42
47
  setEgressHosts: 'owner',
48
+ setUpdatePolicy: 'owner',
43
49
  createAccessToken: 'anyone',
44
50
  },
45
51
  TaAccessServer: {
@@ -56,6 +62,10 @@ export var GatewayServiceUtil;
56
62
  'startTenant',
57
63
  'stopTenant',
58
64
  'restartTenant',
65
+ 'updateTenant',
66
+ 'updateTenants',
67
+ 'rollbackTenant',
68
+ 'setUpdatePolicy',
59
69
  'getTenantLogs',
60
70
  'getAgentActivity',
61
71
  'createSignInLink',
@@ -167,6 +177,8 @@ export var GatewayServiceUtil;
167
177
  return second ? 'suspended' : 'let go';
168
178
  case 'setRole':
169
179
  return String(second);
180
+ case 'setUpdatePolicy':
181
+ return String(params[0]);
170
182
  case 'setEgressHosts':
171
183
  return Array.isArray(params[0]) ? params[0].join(', ') || 'any public host' : undefined;
172
184
  default:
@@ -7,6 +7,7 @@ import { type GatewayPolicy } from './gateway-policy.js';
7
7
  import type { GatewayQuotas } from './gateway-quotas.js';
8
8
  import { type GatewayUsage } from './gateway-usage.js';
9
9
  import { type ModelProxy } from './model-proxy.js';
10
+ import { SandboxUpdates } from './sandbox-updates.js';
10
11
  import type { SignInLinks } from './sign-in-links.js';
11
12
  import type { Tenant, TenantStore } from './tenant-store.js';
12
13
  /** Who calls: the browser signed in as `account`, with the token `token`, and what that account is on the gateway. */
@@ -59,13 +60,16 @@ export declare class GatewayService {
59
60
  protected readonly meta: GatewayMeta;
60
61
  protected readonly models?: ModelProxy;
61
62
  protected readonly egress?: EgressProxy;
63
+ /** Moving the sandboxes to a newer version of Ta: started with the gateway (GatewayServer.listen). */
64
+ readonly updates: SandboxUpdates;
62
65
  constructor(parts: GatewayParts);
63
66
  call(caller: GatewayCaller, method: string, params: unknown[]): Promise<unknown>;
64
67
  protected handle(caller: GatewayCaller, service: string, name: string, params: unknown[]): Promise<unknown>;
65
68
  protected record(caller: GatewayCaller, action: string, params: unknown[]): void;
66
69
  info(caller: GatewayCaller): TaGatewayInfo;
67
70
  protected setEnvironment(caller: GatewayCaller, value: unknown): Promise<TaGatewayInfo>;
68
- protected restart(caller: GatewayCaller): Promise<TaGatewayInfo>;
71
+ /** `update`: it starts on the latest version as one connects again, even one it went back from. */
72
+ protected restart(caller: GatewayCaller, update?: boolean): Promise<TaGatewayInfo>;
69
73
  protected tenantInfo(tenant: Tenant): TaGatewayTenant;
70
74
  /** The tenants with what their sandboxes take and their agents do, read together: a slow one holds the console a second, not a second each. */
71
75
  protected console(caller: GatewayCaller): Promise<TaGatewayConsole>;
@@ -77,6 +81,9 @@ export declare class GatewayService {
77
81
  protected startTenant(caller: GatewayCaller, id: unknown): Promise<void>;
78
82
  protected stopTenant(caller: GatewayCaller, id: unknown): Promise<void>;
79
83
  protected restartTenant(caller: GatewayCaller, id: unknown): Promise<void>;
84
+ protected updateTenant(caller: GatewayCaller, id: unknown): Promise<void>;
85
+ protected rollbackTenant(caller: GatewayCaller, id: unknown): Promise<void>;
86
+ protected setUpdatePolicy(mode: unknown): TaGatewayPolicy;
80
87
  /** What its sandbox wrote, its secrets hidden: tokens and keys printed by what ran there do not reach the page. */
81
88
  protected logs(id: unknown, lines: unknown): Promise<string>;
82
89
  protected activity(id: unknown, sessionId: unknown): Promise<TaAgentActivity[]>;
@@ -6,6 +6,7 @@ import { GatewayPolicyUtil, PolicyError } from './gateway-policy.js';
6
6
  import { GatewayCallError, GatewayServiceUtil } from './gateway-service-util.js';
7
7
  import { GatewayUsageUtil } from './gateway-usage.js';
8
8
  import { ModelProxyUtil } from './model-proxy.js';
9
+ import { SandboxUpdates } from './sandbox-updates.js';
9
10
  const DAY = 24 * 3600000;
10
11
  /**
11
12
  * The calls the gateway answers on the WebSocket of a browser: TaGatewayServer, and TaAccessServer, whose
@@ -25,6 +26,7 @@ export class GatewayService {
25
26
  this.audit = parts.audit;
26
27
  this.hooks = parts.hooks;
27
28
  this.meta = parts.meta;
29
+ this.updates = new SandboxUpdates({ ...parts, reset: id => parts.hooks.reset(id) });
28
30
  }
29
31
  async call(caller, method, params) {
30
32
  const [service, name] = method.split('/');
@@ -47,9 +49,10 @@ export class GatewayService {
47
49
  const [first, second] = params;
48
50
  const handlers = service === 'TaGatewayServer'
49
51
  ? {
50
- getGateway: () => this.info(caller),
52
+ getGateway: () => this.environments.readVersions(caller.tenant).then(() => this.info(caller)),
51
53
  setEnvironment: () => this.setEnvironment(caller, first),
52
54
  restartEnvironment: () => this.restart(caller),
55
+ updateEnvironment: () => this.restart(caller, true),
53
56
  listTenants: () => this.tenants.list().map(tenant => this.tenantInfo(tenant)),
54
57
  getConsole: () => this.console(caller),
55
58
  getTenantAgents: () => this.environments.agents(this.tenant(first)),
@@ -61,6 +64,11 @@ export class GatewayService {
61
64
  startTenant: () => this.startTenant(caller, first),
62
65
  stopTenant: () => this.stopTenant(caller, first),
63
66
  restartTenant: () => this.restartTenant(caller, first),
67
+ updateTenant: () => this.updateTenant(caller, first),
68
+ updateTenants: () => this.updates.check().then(behind => this.updates.updateAll(behind)),
69
+ rollbackTenant: () => this.rollbackTenant(caller, first),
70
+ checkUpdates: () => this.updates.check(true).then(behind => behind.length),
71
+ setUpdatePolicy: () => this.setUpdatePolicy(first),
64
72
  createSignInLink: () => this.signInLink(first, second),
65
73
  setTenantLimits: () => this.setTenantLimits(caller, first, second),
66
74
  grantMinutes: () => this.grantMinutes(caller, first, second),
@@ -107,6 +115,7 @@ export class GatewayService {
107
115
  admin: caller.admin,
108
116
  role: caller.role,
109
117
  quota: this.quotas.state(tenant),
118
+ updates: this.policy.updates,
110
119
  };
111
120
  }
112
121
  async setEnvironment(caller, value) {
@@ -120,7 +129,11 @@ export class GatewayService {
120
129
  this.hooks.reset(next.id);
121
130
  return this.info(caller);
122
131
  }
123
- async restart(caller) {
132
+ /** `update`: it starts on the latest version as one connects again, even one it went back from. */
133
+ async restart(caller, update = false) {
134
+ if (update) {
135
+ caller.tenant = this.tenants.update(caller.tenant.id, { skipVersion: undefined });
136
+ }
124
137
  await this.environments.stop(caller.tenant.id).catch(() => undefined);
125
138
  this.hooks.reset(caller.tenant.id);
126
139
  return this.info(caller);
@@ -149,6 +162,7 @@ export class GatewayService {
149
162
  const [usages, agents] = await Promise.all([
150
163
  Promise.all(tenants.map(tenant => this.environments.usage(tenant).catch(() => undefined))),
151
164
  Promise.all(tenants.map(tenant => this.environments.agentSummary(tenant).catch(() => undefined))),
165
+ this.updates.check(),
152
166
  ]);
153
167
  const counts = new Map();
154
168
  for (const tenant of tenants) {
@@ -182,6 +196,7 @@ export class GatewayService {
182
196
  api: provider.api,
183
197
  models: provider.models.length,
184
198
  })),
199
+ ...(this.updates.progress ? { updating: { ...this.updates.progress } } : {}),
185
200
  };
186
201
  }
187
202
  policyView() {
@@ -229,6 +244,26 @@ export class GatewayService {
229
244
  this.hooks.reset(tenant.id);
230
245
  await this.environments.ensure(tenant);
231
246
  }
247
+ async updateTenant(caller, id) {
248
+ const wentBack = await this.updates.update(this.manage(caller, id));
249
+ if (wentBack) {
250
+ throw new GatewayCallError(wentBack, TaErrorCode.COMMAND_FAILED, 'Its log tells why the newer version did not start.');
251
+ }
252
+ }
253
+ async rollbackTenant(caller, id) {
254
+ var _a;
255
+ const tenant = this.manage(caller, id);
256
+ await this.environments.rollback(tenant);
257
+ this.hooks.reset(tenant.id);
258
+ await this.environments.ensure((_a = this.tenants.get(tenant.id)) !== null && _a !== void 0 ? _a : tenant);
259
+ }
260
+ setUpdatePolicy(mode) {
261
+ if (mode !== 'idle' && mode !== 'manual') {
262
+ throw new GatewayCallError('Updates are idle or manual.', TaErrorCode.INVALID_ARGUMENT, 'idle: once nothing works in a sandbox; manual: when told to.');
263
+ }
264
+ this.policy.setUpdates(mode);
265
+ return this.policyView();
266
+ }
232
267
  /** What its sandbox wrote, its secrets hidden: tokens and keys printed by what ran there do not reach the page. */
233
268
  async logs(id, lines) {
234
269
  return new Redactor().text(await this.environments.logs(this.tenant(id), GatewayServiceUtil.lines(lines)));
@@ -1,3 +1,4 @@
1
+ import type { TaSandboxVersion } from '@celljs/ta-protocol';
1
2
  import type { EgressConfig } from './egress-proxy.js';
2
3
  /** A tenant, as a provider of sandboxes sees it: `token` is the one its Ta service must take (TA_SERVE_TOKEN). */
3
4
  export interface SandboxTenant {
@@ -10,11 +11,24 @@ export interface SandboxTenant {
10
11
  * gateway. A provider that makes a sandbox once remakes it when they change.
11
12
  */
12
13
  env?: Record<string, string>;
14
+ /** The id of a version not to move to on its own: the one the sandbox was moved back from. */
15
+ skip?: string;
13
16
  }
14
17
  /** Where the Ta service of a tenant answers: `url` is its http(s) address, the gateway connects to `/api/ws` there. */
15
18
  export interface SandboxEndpoint {
16
19
  url: string;
17
20
  token: string;
21
+ /** Made again on the latest version just now, the one before kept: moved back when it does not answer. */
22
+ updated?: boolean;
23
+ }
24
+ export type SandboxVersion = TaSandboxVersion;
25
+ /** The versions of Ta of a tenant's sandbox: what a new one runs, what it runs, and what it ran before (since its update). */
26
+ export interface SandboxVersions {
27
+ latest?: SandboxVersion;
28
+ current?: SandboxVersion;
29
+ previous?: SandboxVersion & {
30
+ since: number;
31
+ };
18
32
  }
19
33
  export type SandboxState = 'running' | 'stopped' | 'missing';
20
34
  /** What a running sandbox takes: CPU in percent of one CPU, memory in bytes. */
@@ -49,6 +63,16 @@ export interface SandboxProvider {
49
63
  usage?(tenant: SandboxTenant): Promise<SandboxUsage | undefined>;
50
64
  /** The last `lines` its sandbox wrote (its Ta service's output), for the console. */
51
65
  logs?(tenant: SandboxTenant, lines: number): Promise<string>;
66
+ /**
67
+ * Its versions, for a provider whose sandboxes move to a newer version of Ta (docs/design/ta-sandbox-update.md):
68
+ * `start` makes a stopped one on an older version again on the latest, unless that is `skip`, keeping the one
69
+ * before, and says so (`updated`). `refresh`: look for a newer one where it is published (a registry).
70
+ */
71
+ versions?(tenant: SandboxTenant, refresh?: boolean): Promise<SandboxVersions>;
72
+ /** Back to the one it ran before its update, stopped: the id of the version it leaves. Throws when there is none. */
73
+ rollback?(tenant: SandboxTenant): Promise<string | undefined>;
74
+ /** The one it ran before is dropped. */
75
+ forget?(tenant: SandboxTenant): Promise<void>;
52
76
  /** The gateway stops: what runs in this process ends (`local`). */
53
77
  dispose?(): Promise<void>;
54
78
  }
@@ -0,0 +1,56 @@
1
+ import type { TaSessionInfo } from '@celljs/ta-protocol';
2
+ import { type Environments } from './environments.js';
3
+ import type { GatewayAudit } from './gateway-audit.js';
4
+ import type { GatewayPolicy } from './gateway-policy.js';
5
+ import type { Tenant, TenantStore } from './tenant-store.js';
6
+ export declare namespace SandboxUpdatesUtil {
7
+ /** How often the gateway looks for a newer version and the sandboxes that may move to it. */
8
+ const EVERY_MS: number;
9
+ /** How long nothing is to have happened in a Ta for it to be idle. */
10
+ const QUIET_MS: number;
11
+ /** Who the audit says did what the gateway did on its own. */
12
+ const ACTOR = "ta gateway";
13
+ /**
14
+ * Whether nothing works in a Ta: no turn, no dialog or question waiting, and no conversation touched for a while.
15
+ * Connections do not count: a phone stays connected all day.
16
+ */
17
+ function idle(sessions: TaSessionInfo[] | undefined, now: number): boolean;
18
+ }
19
+ export interface SandboxUpdatesParts {
20
+ environments: Environments;
21
+ tenants: TenantStore;
22
+ policy: GatewayPolicy;
23
+ audit: GatewayAudit;
24
+ /** The connections of the tenant close, to connect again to its sandbox. */
25
+ reset(tenantId: string): void;
26
+ }
27
+ /**
28
+ * Moving the sandboxes of tenants to a newer version of Ta (docs/design/ta-sandbox-update.md): a stopped one does as it
29
+ * starts (its provider); a running one when told to, or once nothing works in it (`idle` of the policy), one after
30
+ * another, the gateway stopping at the first that went back to its version before.
31
+ */
32
+ export declare class SandboxUpdates {
33
+ protected readonly parts: SandboxUpdatesParts;
34
+ /** While sandboxes move one after another. */
35
+ progress?: {
36
+ done: number;
37
+ total: number;
38
+ current?: string;
39
+ };
40
+ protected timer?: ReturnType<typeof setInterval>;
41
+ constructor(parts: SandboxUpdatesParts);
42
+ start(): void;
43
+ dispose(): void;
44
+ /** The versions of every sandbox read again (`refresh`: a newer one pulled); those running an older one. */
45
+ check(refresh?: boolean): Promise<Tenant[]>;
46
+ /**
47
+ * Its sandbox stops (what runs in it is paused, to go on after) and starts on the latest version, even one it went
48
+ * back from: why it went back to the one before when it did, else undefined.
49
+ */
50
+ update(tenant: Tenant): Promise<string | undefined>;
51
+ /** Each running sandbox on an older version moves, one after another, in the background: how many. */
52
+ updateAll(tenants: Tenant[], auto?: boolean): number;
53
+ /** Every few minutes: what was kept for a week is dropped; idle sandboxes move, when the policy says so. */
54
+ tick(now?: number): Promise<void>;
55
+ protected record(tenant: Tenant, action: string, detail: string): void;
56
+ }
@@ -0,0 +1,104 @@
1
+ import { EnvironmentsUtil } from './environments.js';
2
+ export var SandboxUpdatesUtil;
3
+ (function (SandboxUpdatesUtil) {
4
+ /** How often the gateway looks for a newer version and the sandboxes that may move to it. */
5
+ SandboxUpdatesUtil.EVERY_MS = 10 * 60000;
6
+ /** How long nothing is to have happened in a Ta for it to be idle. */
7
+ SandboxUpdatesUtil.QUIET_MS = 10 * 60000;
8
+ /** Who the audit says did what the gateway did on its own. */
9
+ SandboxUpdatesUtil.ACTOR = 'ta gateway';
10
+ /**
11
+ * Whether nothing works in a Ta: no turn, no dialog or question waiting, and no conversation touched for a while.
12
+ * Connections do not count: a phone stays connected all day.
13
+ */
14
+ function idle(sessions, now) {
15
+ return (sessions === null || sessions === void 0 ? void 0 : sessions.every(session => !session.isStreaming && !session.waiting && !session.asking && now - session.updatedAt > SandboxUpdatesUtil.QUIET_MS)) === true;
16
+ }
17
+ SandboxUpdatesUtil.idle = idle;
18
+ })(SandboxUpdatesUtil || (SandboxUpdatesUtil = {}));
19
+ /**
20
+ * Moving the sandboxes of tenants to a newer version of Ta (docs/design/ta-sandbox-update.md): a stopped one does as it
21
+ * starts (its provider); a running one when told to, or once nothing works in it (`idle` of the policy), one after
22
+ * another, the gateway stopping at the first that went back to its version before.
23
+ */
24
+ export class SandboxUpdates {
25
+ constructor(parts) {
26
+ this.parts = parts;
27
+ parts.environments.rolledBack = (tenant, from, reason) => this.record(tenant, 'rollbackTenant', `${EnvironmentsUtil.label(from ? { id: from } : undefined)}: ${reason}`);
28
+ }
29
+ start() {
30
+ var _a, _b;
31
+ this.timer = setInterval(() => void this.tick().catch(error => console.warn(`ta gateway: updating sandboxes failed: ${error.message}`)), SandboxUpdatesUtil.EVERY_MS);
32
+ (_b = (_a = this.timer).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
33
+ }
34
+ dispose() {
35
+ clearInterval(this.timer);
36
+ }
37
+ /** The versions of every sandbox read again (`refresh`: a newer one pulled); those running an older one. */
38
+ async check(refresh = false) {
39
+ const { environments, tenants } = this.parts;
40
+ const list = tenants.list();
41
+ await Promise.all(list.map(tenant => environments.readVersions(tenant, refresh).catch(() => undefined)));
42
+ return list.filter(tenant => environments.info(tenant).latest !== undefined);
43
+ }
44
+ /**
45
+ * Its sandbox stops (what runs in it is paused, to go on after) and starts on the latest version, even one it went
46
+ * back from: why it went back to the one before when it did, else undefined.
47
+ */
48
+ async update(tenant) {
49
+ const { environments, tenants } = this.parts;
50
+ const next = tenants.update(tenant.id, { skipVersion: undefined });
51
+ await environments.stop(tenant.id).catch(() => undefined);
52
+ this.parts.reset(tenant.id);
53
+ await environments.ensure(next);
54
+ return environments.info(next).error;
55
+ }
56
+ /** Each running sandbox on an older version moves, one after another, in the background: how many. */
57
+ updateAll(tenants, auto = false) {
58
+ const list = tenants.filter(tenant => this.parts.environments.info(tenant).status === 'running');
59
+ if (this.progress || list.length === 0) {
60
+ return this.progress ? this.progress.total - this.progress.done : 0;
61
+ }
62
+ const progress = { done: 0, total: list.length };
63
+ this.progress = progress;
64
+ void (async () => {
65
+ for (const tenant of list) {
66
+ progress.current = tenant.account;
67
+ const from = this.parts.environments.info(tenant);
68
+ const wentBack = await this.update(tenant).catch((error) => error.message);
69
+ progress.done++;
70
+ if (auto) {
71
+ this.record(tenant, 'updateTenant', `${EnvironmentsUtil.label(from.version)} → ${EnvironmentsUtil.label(from.latest)}`);
72
+ }
73
+ if (wentBack) {
74
+ console.warn(`ta gateway: ${tenant.account} did not move to the latest version, the others wait: ${wentBack}`);
75
+ break;
76
+ }
77
+ }
78
+ })().finally(() => {
79
+ this.progress = undefined;
80
+ });
81
+ return list.length;
82
+ }
83
+ /** Every few minutes: what was kept for a week is dropped; idle sandboxes move, when the policy says so. */
84
+ async tick(now = Date.now()) {
85
+ await this.parts.environments.forgetPrevious(now);
86
+ if (this.parts.policy.updates !== 'idle' || this.progress) {
87
+ return;
88
+ }
89
+ const found = await this.check(true);
90
+ await Promise.all(found.map(tenant => this.parts.environments.adopt(tenant)));
91
+ const behind = found.filter(tenant => this.parts.environments.info(tenant).status === 'running');
92
+ const sessions = await Promise.all(behind.map(tenant => this.parts.environments.sessions(tenant)));
93
+ this.updateAll(behind.filter((_, index) => SandboxUpdatesUtil.idle(sessions[index], now)), true);
94
+ }
95
+ record(tenant, action, detail) {
96
+ try {
97
+ this.parts.audit.add({ actor: SandboxUpdatesUtil.ACTOR, action, target: tenant.account, detail });
98
+ }
99
+ catch (error) {
100
+ console.warn(`ta gateway: the audit could not be written: ${error.message}`);
101
+ }
102
+ }
103
+ }
104
+ //# sourceMappingURL=sandbox-updates.js.map
@@ -37,6 +37,8 @@ export interface Tenant {
37
37
  epoch: number;
38
38
  secret: string;
39
39
  };
40
+ /** The version of Ta its sandbox went back from: it does not move to it again on its own (docs/design/ta-sandbox-update.md). */
41
+ skipVersion?: string;
40
42
  }
41
43
  /** Files written whole or not at all, readable by this user only. */
42
44
  export declare function writePrivate(file: string, data: unknown): void;
@@ -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?: {
@@ -136,6 +136,26 @@ class DockerEngine {
136
136
  throw error;
137
137
  }
138
138
  }
139
+ async rename(name, to) {
140
+ await this.call('POST', `/containers/${encodeURIComponent(name)}/rename?name=${encodeURIComponent(to)}`);
141
+ }
142
+ /** An image by its name or id; undefined when it is not here. */
143
+ async image(image) {
144
+ try {
145
+ return (await this.call('GET', `/images/${encodeURIComponent(image)}/json`)).body;
146
+ }
147
+ catch (error) {
148
+ if (error instanceof DockerError && error.status === 404) {
149
+ return undefined;
150
+ }
151
+ throw error;
152
+ }
153
+ }
154
+ /** Pulled again from its registry, for a newer one under the same name. */
155
+ async pull(image, timeoutMs = 10 * 60 * 1000) {
156
+ const [repository, tag = 'latest'] = DockerEngineUtil.splitImage(image);
157
+ await this.call('POST', `/images/create?fromImage=${encodeURIComponent(repository)}&tag=${encodeURIComponent(tag)}`, undefined, timeoutMs);
158
+ }
139
159
  /** Removed, its volumes kept; nothing when it is not there. */
140
160
  async remove(name) {
141
161
  try {
@@ -178,8 +198,7 @@ class DockerEngine {
178
198
  throw error;
179
199
  }
180
200
  }
181
- const [repository, tag = 'latest'] = DockerEngineUtil.splitImage(image);
182
- await this.call('POST', `/images/create?fromImage=${encodeURIComponent(repository)}&tag=${encodeURIComponent(tag)}`, undefined, 30 * 60 * 1000);
201
+ await this.pull(image, 30 * 60 * 1000);
183
202
  }
184
203
  }
185
204
  exports.DockerEngine = DockerEngine;
@@ -1,5 +1,5 @@
1
- import { type DockerContainer, DockerEngine } from './docker-engine';
2
- import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage } from './sandbox-provider';
1
+ import { type DockerContainer, DockerEngine, type DockerImage } from './docker-engine';
2
+ import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage, type SandboxVersion, type SandboxVersions } from './sandbox-provider';
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,15 +52,27 @@ 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
  }
60
78
  //# sourceMappingURL=docker-sandbox.d.ts.map