Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a3327cdd98 | |||
| 432a5c2264 | |||
| f36d20b8dd | |||
| baba892353 | |||
| d2c1bed82c | |||
| 3e68e875ac | |||
| a30260e336 |
@@ -4,6 +4,33 @@
|
||||
|
||||
|
||||
|
||||
## 2026-05-25 - 2.1.1
|
||||
|
||||
### Fixes
|
||||
|
||||
- disable dees-catalog build scripts in workspace config (pnpm-workspace)
|
||||
- Adds @design.estate/dees-catalog to pnpm allowBuilds with a false value to explicitly prevent its build scripts from running.
|
||||
|
||||
## 2026-05-25 - 2.1.0
|
||||
|
||||
### Features
|
||||
|
||||
- add App Store upgrade progress tracking and interactive workspace processes (appstore,workspace)
|
||||
- Track App Store upgrade operations with async start/list requests and streamed progress updates.
|
||||
- Show running and failed upgrade status in App Store and service detail views while preventing duplicate upgrade actions.
|
||||
- Route App Store upgrades through the shared service update flow to restore service routes before gateway sync.
|
||||
- Add backend workspace shell discovery plus interactive process start/input/kill/output/exit APIs backed by Docker exec streams.
|
||||
- Bump Docker and workspace UI dependencies for interactive stdin streaming and shell selection support.
|
||||
|
||||
## 2026-05-25 - 2.0.0
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- switch Onebox App Store resolution to the shared appstore client
|
||||
- Uses `@serve.zone/appstore` and `@serve.zone/interfaces` for App Store metadata, parsing, and Docker digest resolution
|
||||
- Renames App Store typed request methods to `getAppStoreTemplates`, `getAppStoreConfig`, `installAppStoreApp`, and `getUpgradeableAppStoreServices`
|
||||
- Removes local duplicated App Store DTO and resolver code while preserving Onebox install and upgrade behavior
|
||||
|
||||
## 2026-05-25 - 1.31.0
|
||||
|
||||
### Features
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@serve.zone/onebox",
|
||||
"version": "1.31.0",
|
||||
"version": "2.1.1",
|
||||
"exports": "./mod.ts",
|
||||
"tasks": {
|
||||
"test": "deno test --allow-all test/",
|
||||
@@ -15,7 +15,7 @@
|
||||
"@std/assert": "jsr:@std/assert@^1.0.19",
|
||||
"@std/encoding": "jsr:@std/encoding@^1.0.10",
|
||||
"@db/sqlite": "jsr:@db/sqlite@0.13.0",
|
||||
"@apiclient.xyz/docker": "npm:@apiclient.xyz/docker@^5.1.4",
|
||||
"@apiclient.xyz/docker": "npm:@apiclient.xyz/docker@^5.1.5",
|
||||
"@apiclient.xyz/cloudflare": "npm:@apiclient.xyz/cloudflare@7.1.0",
|
||||
"@push.rocks/smartacme": "npm:@push.rocks/smartacme@^9.5.0",
|
||||
"@push.rocks/smartregistry": "npm:@push.rocks/smartregistry@^2.9.2",
|
||||
@@ -27,7 +27,9 @@
|
||||
"@push.rocks/smartguard": "npm:@push.rocks/smartguard@^3.1.0",
|
||||
"@push.rocks/smartjwt": "npm:@push.rocks/smartjwt@^2.2.2",
|
||||
"@api.global/typedsocket": "npm:@api.global/typedsocket@^4.1.3",
|
||||
"@serve.zone/containerarchive": "npm:@serve.zone/containerarchive@^0.1.3"
|
||||
"@serve.zone/containerarchive": "npm:@serve.zone/containerarchive@^0.1.3",
|
||||
"@serve.zone/interfaces": "npm:@serve.zone/interfaces@^6.0.0",
|
||||
"@serve.zone/appstore": "npm:@serve.zone/appstore@^0.2.0"
|
||||
},
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
|
||||
+5
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@serve.zone/onebox",
|
||||
"version": "1.31.0",
|
||||
"version": "2.1.1",
|
||||
"description": "Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers",
|
||||
"main": "mod.ts",
|
||||
"type": "module",
|
||||
@@ -56,9 +56,11 @@
|
||||
"dependencies": {
|
||||
"@api.global/typedrequest-interfaces": "^3.0.19",
|
||||
"@api.global/typedsocket": "^4.1.3",
|
||||
"@design.estate/dees-catalog": "^3.81.0",
|
||||
"@design.estate/dees-catalog": "^3.82.0",
|
||||
"@design.estate/dees-element": "^2.2.4",
|
||||
"@serve.zone/catalog": "^2.12.6"
|
||||
"@serve.zone/appstore": "^0.2.0",
|
||||
"@serve.zone/catalog": "^2.12.6",
|
||||
"@serve.zone/interfaces": "^6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbundle": "^2.10.4",
|
||||
|
||||
Generated
+64
-3
@@ -15,14 +15,20 @@ importers:
|
||||
specifier: ^4.1.3
|
||||
version: 4.1.3(@push.rocks/smartserve@2.0.4)
|
||||
'@design.estate/dees-catalog':
|
||||
specifier: ^3.81.0
|
||||
version: 3.81.0(@tiptap/pm@2.27.2)
|
||||
specifier: ^3.82.0
|
||||
version: 3.82.0(@tiptap/pm@2.27.2)
|
||||
'@design.estate/dees-element':
|
||||
specifier: ^2.2.4
|
||||
version: 2.2.4
|
||||
'@serve.zone/appstore':
|
||||
specifier: ^0.2.0
|
||||
version: 0.2.0
|
||||
'@serve.zone/catalog':
|
||||
specifier: ^2.12.6
|
||||
version: 2.12.6(@tiptap/pm@2.27.2)
|
||||
'@serve.zone/interfaces':
|
||||
specifier: ^6.0.0
|
||||
version: 6.0.0
|
||||
devDependencies:
|
||||
'@git.zone/tsbundle':
|
||||
specifier: ^2.10.4
|
||||
@@ -75,6 +81,9 @@ packages:
|
||||
'@design.estate/dees-catalog@3.81.0':
|
||||
resolution: {integrity: sha512-N7ocwSKVdjDQWmVV2XWiyg3dotGEuxP4/jhyB6duH8zJ3k63wmGm8+FeoP+LzRc8/U0Bl8w7UZrewlkIEMstUA==}
|
||||
|
||||
'@design.estate/dees-catalog@3.82.0':
|
||||
resolution: {integrity: sha512-OvPglDHI8J8K8+hmtxHyvVLzKMr8rQSFXVxf6xT60q/om3QoQacwS8cPI/RmnEKT+mzvDk/vnNpt9/Tw0cTmWA==}
|
||||
|
||||
'@design.estate/dees-comms@1.0.30':
|
||||
resolution: {integrity: sha512-KchMlklJfKAjQiJiR0xmofXtQ27VgZtBIxcMwPE9d+h3jJRv+lPZxzBQVOM0eyM0uS44S5vJMZ11IeV4uDXSHg==}
|
||||
|
||||
@@ -977,9 +986,15 @@ packages:
|
||||
'@sec-ant/readable-stream@0.4.1':
|
||||
resolution: {integrity: sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==}
|
||||
|
||||
'@serve.zone/appstore@0.2.0':
|
||||
resolution: {integrity: sha512-qt2LVaRpzfJdUywllm+F0njwnN3aHc2aZHEcjc9REn1VDT47UuUEGaKkfNiosGK0GJqb1hPI/GwyuGMe4H4q7w==}
|
||||
|
||||
'@serve.zone/catalog@2.12.6':
|
||||
resolution: {integrity: sha512-FjieZNCHTCHufMre8OSP8bFP9L4DPL9yNtd7UMwD1yQ8wublgAq6eWrx6Tfb+3k8Hyof33BBt4rbFyrvIEBk+A==}
|
||||
|
||||
'@serve.zone/interfaces@6.0.0':
|
||||
resolution: {integrity: sha512-nCidhOH0XlX+7e6xaJDq6fwnwaWasB/4w2LHkV7A96G+m+7EXZqbbaKSboUlaiGDly0dWNajk2FrYFo64ZucPA==}
|
||||
|
||||
'@tempfix/lenis@1.3.20':
|
||||
resolution: {integrity: sha512-ypeB0FuHLHOCQXW4d0RQ69txPJJH+1CHcpsZIUdcv2t1vR0IVyQr2vHihtde9UOXhjzqEnUphWon/UcJNsa0YA==}
|
||||
peerDependencies:
|
||||
@@ -2534,6 +2549,42 @@ snapshots:
|
||||
- supports-color
|
||||
- vue
|
||||
|
||||
'@design.estate/dees-catalog@3.82.0(@tiptap/pm@2.27.2)':
|
||||
dependencies:
|
||||
'@design.estate/dees-domtools': 2.5.6
|
||||
'@design.estate/dees-element': 2.2.4
|
||||
'@design.estate/dees-wcctools': 3.9.0
|
||||
'@fortawesome/fontawesome-svg-core': 7.2.0
|
||||
'@fortawesome/free-brands-svg-icons': 7.2.0
|
||||
'@fortawesome/free-regular-svg-icons': 7.2.0
|
||||
'@fortawesome/free-solid-svg-icons': 7.2.0
|
||||
'@push.rocks/smarti18n': 1.1.0
|
||||
'@push.rocks/smartpromise': 4.2.4
|
||||
'@push.rocks/smartstring': 4.1.1
|
||||
'@tempfix/webcontainer__api': 1.6.1
|
||||
'@tiptap/core': 2.27.2(@tiptap/pm@2.27.2)
|
||||
'@tiptap/extension-link': 2.27.2(@tiptap/core@2.27.2(@tiptap/pm@2.27.2))(@tiptap/pm@2.27.2)
|
||||
'@tiptap/extension-text-align': 2.27.2(@tiptap/core@2.27.2(@tiptap/pm@2.27.2))
|
||||
'@tiptap/extension-typography': 2.27.2(@tiptap/core@2.27.2(@tiptap/pm@2.27.2))
|
||||
'@tiptap/extension-underline': 2.27.2(@tiptap/core@2.27.2(@tiptap/pm@2.27.2))
|
||||
'@tiptap/starter-kit': 2.27.2
|
||||
'@tsclass/tsclass': 9.5.1
|
||||
echarts: 5.6.0
|
||||
highlight.js: 11.11.1
|
||||
ibantools: 4.5.4
|
||||
lightweight-charts: 5.2.0
|
||||
lucide: 1.14.0
|
||||
monaco-editor: 0.55.1
|
||||
pdfjs-dist: 4.10.38
|
||||
xterm: 5.3.0
|
||||
xterm-addon-fit: 0.8.0(xterm@5.3.0)
|
||||
transitivePeerDependencies:
|
||||
- '@nuxt/kit'
|
||||
- '@tiptap/pm'
|
||||
- react
|
||||
- supports-color
|
||||
- vue
|
||||
|
||||
'@design.estate/dees-comms@1.0.30':
|
||||
dependencies:
|
||||
'@api.global/typedrequest': 3.3.0
|
||||
@@ -2543,7 +2594,7 @@ snapshots:
|
||||
|
||||
'@design.estate/dees-domtools@2.5.6':
|
||||
dependencies:
|
||||
'@api.global/typedrequest': 3.3.0
|
||||
'@api.global/typedrequest': 3.3.1
|
||||
'@design.estate/dees-comms': 1.0.30
|
||||
'@push.rocks/lik': 6.4.1
|
||||
'@push.rocks/smartdelay': 3.1.0
|
||||
@@ -3572,6 +3623,10 @@ snapshots:
|
||||
|
||||
'@sec-ant/readable-stream@0.4.1': {}
|
||||
|
||||
'@serve.zone/appstore@0.2.0':
|
||||
dependencies:
|
||||
'@serve.zone/interfaces': 6.0.0
|
||||
|
||||
'@serve.zone/catalog@2.12.6(@tiptap/pm@2.27.2)':
|
||||
dependencies:
|
||||
'@design.estate/dees-catalog': 3.81.0(@tiptap/pm@2.27.2)
|
||||
@@ -3585,6 +3640,12 @@ snapshots:
|
||||
- supports-color
|
||||
- vue
|
||||
|
||||
'@serve.zone/interfaces@6.0.0':
|
||||
dependencies:
|
||||
'@api.global/typedrequest-interfaces': 3.0.19
|
||||
'@push.rocks/smartlog-interfaces': 3.0.2
|
||||
'@tsclass/tsclass': 9.5.1
|
||||
|
||||
'@tempfix/lenis@1.3.20': {}
|
||||
|
||||
'@tempfix/webcontainer__api@1.6.1': {}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
allowBuilds:
|
||||
'@design.estate/dees-catalog': false
|
||||
esbuild: true
|
||||
ignoredBuiltDependencies:
|
||||
- '@design.estate/dees-catalog'
|
||||
|
||||
@@ -183,7 +183,7 @@ onebox config set cloudflareZoneId zone-id
|
||||
|
||||
## App Store
|
||||
|
||||
The App Store manager fetches catalog data from `serve.zone/appstore-apptemplates` and caches it briefly. Templates can declare platform requirements, so installing an app can automatically provision MongoDB, S3-compatible storage, ClickHouse, Redis, or MariaDB resources and inject the resulting credentials as environment variables.
|
||||
The App Store manager fetches metadata from `serve.zone/appstore` through `@serve.zone/appstore` and caches it briefly. Templates can declare platform requirements, so installing an app can automatically provision MongoDB, S3-compatible storage, ClickHouse, Redis, or MariaDB resources and inject the resulting credentials as environment variables.
|
||||
|
||||
```bash
|
||||
onebox appstore list
|
||||
|
||||
@@ -2,12 +2,14 @@ import { assertEquals, assertThrows } from '@std/assert';
|
||||
|
||||
import { AppStoreManager } from '../ts/classes/appstore.ts';
|
||||
import { OneboxDockerManager } from '../ts/classes/docker.ts';
|
||||
import type { IAppVersionConfig } from '../ts/classes/appstore-types.ts';
|
||||
import type * as servezoneInterfaces from '@serve.zone/interfaces';
|
||||
import type { IService } from '../ts/types.ts';
|
||||
|
||||
type IAppStoreVersionConfig = servezoneInterfaces.appstore.IAppStoreVersionConfig;
|
||||
|
||||
const createAppStore = () => new AppStoreManager({} as any);
|
||||
|
||||
const baseConfig: IAppVersionConfig = {
|
||||
const baseConfig: IAppStoreVersionConfig = {
|
||||
image: 'example/app:1.0.0',
|
||||
port: 3000,
|
||||
envVars: [
|
||||
@@ -82,19 +84,19 @@ Deno.test('appstore rejects invalid template ports and volumes', () => {
|
||||
});
|
||||
|
||||
Deno.test('appstore resolves repo manifests and docker digest-tracked latest images', async () => {
|
||||
const catalogBaseUrl = 'https://catalog.example.test';
|
||||
const manifestUrl = 'https://code.example.test/cloudly/servezone.catalog.json';
|
||||
const appStoreBaseUrl = 'https://appstore.example.test';
|
||||
const manifestUrl = 'https://code.example.test/cloudly/servezone.appstore.json';
|
||||
const digest = 'sha256:1234567890abcdef';
|
||||
|
||||
const fakeFetch: typeof fetch = async (input, init) => {
|
||||
const url = input instanceof Request ? input.url : input.toString();
|
||||
const method = init?.method || 'GET';
|
||||
|
||||
if (url === `${catalogBaseUrl}/catalog.resolved.json`) {
|
||||
if (url === `${appStoreBaseUrl}/appstore.resolved.json`) {
|
||||
return new Response('not found', { status: 404 });
|
||||
}
|
||||
|
||||
if (url === `${catalogBaseUrl}/catalog.json`) {
|
||||
if (url === `${appStoreBaseUrl}/appstore.json`) {
|
||||
return Response.json({
|
||||
schemaVersion: 1,
|
||||
updatedAt: '2026-05-24T00:00:00Z',
|
||||
@@ -152,14 +154,14 @@ Deno.test('appstore resolves repo manifests and docker digest-tracked latest ima
|
||||
};
|
||||
|
||||
const appStore = new AppStoreManager({} as any, {
|
||||
repoBaseUrl: catalogBaseUrl,
|
||||
baseUrl: appStoreBaseUrl,
|
||||
fetch: fakeFetch,
|
||||
});
|
||||
|
||||
const catalog = await appStore.getCatalog();
|
||||
assertEquals(catalog.apps[0].latestVersion, `latest@${digest}`);
|
||||
assertEquals(catalog.apps[0].resolvedSource?.manifestHash?.length, 64);
|
||||
assertEquals(catalog.apps[0].upgradeStrategy, 'dockerDigest');
|
||||
const appStoreIndex = await appStore.getAppStore();
|
||||
assertEquals(appStoreIndex.apps[0].latestVersion, `latest@${digest}`);
|
||||
assertEquals(appStoreIndex.apps[0].resolvedSource?.manifestHash?.length, 64);
|
||||
assertEquals(appStoreIndex.apps[0].upgradeStrategy, 'dockerDigest');
|
||||
|
||||
const appMeta = await appStore.getAppMeta('cloudly');
|
||||
assertEquals(appMeta.latestVersion, `latest@${digest}`);
|
||||
@@ -167,7 +169,7 @@ Deno.test('appstore resolves repo manifests and docker digest-tracked latest ima
|
||||
|
||||
const config = await appStore.getAppVersionConfig('cloudly', appMeta.latestVersion);
|
||||
assertEquals(config.image, 'registry.example.test/serve.zone/cloudly:latest');
|
||||
assertEquals(config.catalogVersion, `latest@${digest}`);
|
||||
assertEquals(config.appStoreVersion, `latest@${digest}`);
|
||||
assertEquals(config.resolvedImageDigest, digest);
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@serve.zone/onebox',
|
||||
version: '1.31.0',
|
||||
version: '2.1.1',
|
||||
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
|
||||
}
|
||||
|
||||
@@ -1,202 +0,0 @@
|
||||
/**
|
||||
* App Store type definitions
|
||||
*/
|
||||
|
||||
export interface ICatalog {
|
||||
schemaVersion: number;
|
||||
updatedAt: string;
|
||||
apps: ICatalogApp[];
|
||||
resolvedAt?: string;
|
||||
}
|
||||
|
||||
export type TAppCatalogSourceType = 'inline' | 'repoManifest' | 'dockerImage';
|
||||
export type TAppCatalogTrackingMode = 'tag' | 'digest';
|
||||
export type TAppUpgradeStrategy = 'semver' | 'branch' | 'dockerDigest';
|
||||
|
||||
export interface IAppCatalogInlineSource {
|
||||
type: 'inline';
|
||||
}
|
||||
|
||||
export interface IAppCatalogRepoManifestSource {
|
||||
type: 'repoManifest';
|
||||
url: string;
|
||||
ref?: string;
|
||||
}
|
||||
|
||||
export interface IAppCatalogDockerImageSource {
|
||||
type: 'dockerImage';
|
||||
image: string;
|
||||
tracking?: TAppCatalogTrackingMode;
|
||||
}
|
||||
|
||||
export type TAppCatalogSource =
|
||||
| IAppCatalogInlineSource
|
||||
| IAppCatalogRepoManifestSource
|
||||
| IAppCatalogDockerImageSource;
|
||||
|
||||
export interface IResolvedCatalogSource {
|
||||
type: TAppCatalogSourceType;
|
||||
url?: string;
|
||||
ref?: string;
|
||||
image?: string;
|
||||
manifestHash?: string;
|
||||
imageDigest?: string;
|
||||
resolvedAt: string;
|
||||
}
|
||||
|
||||
export interface ICatalogApp {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
category: string;
|
||||
iconName?: string;
|
||||
iconUrl?: string;
|
||||
latestVersion: string;
|
||||
versions?: string[];
|
||||
tags?: string[];
|
||||
source?: TAppCatalogSource;
|
||||
runtime?: IAppVersionConfig;
|
||||
channel?: string;
|
||||
upgradeStrategy?: TAppUpgradeStrategy;
|
||||
resolvedSource?: IResolvedCatalogSource;
|
||||
}
|
||||
|
||||
export interface IAppCatalogVolume {
|
||||
name?: string;
|
||||
source?: string;
|
||||
mountPath: string;
|
||||
driver?: string;
|
||||
readOnly?: boolean;
|
||||
backup?: boolean;
|
||||
options?: Record<string, string>;
|
||||
}
|
||||
|
||||
export type TAppCatalogVolumeSpec = string | IAppCatalogVolume;
|
||||
|
||||
export interface IAppCatalogPublishedPort {
|
||||
targetPort: number;
|
||||
targetPortEnd?: number;
|
||||
publishedPort?: number;
|
||||
publishedPortEnd?: number;
|
||||
protocol?: 'tcp' | 'udp';
|
||||
hostIp?: string;
|
||||
}
|
||||
|
||||
export interface IAppMeta {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
category: string;
|
||||
iconName?: string;
|
||||
latestVersion: string;
|
||||
versions: string[];
|
||||
maintainer?: string;
|
||||
links?: Record<string, string>;
|
||||
tags?: string[];
|
||||
source?: TAppCatalogSource;
|
||||
resolvedSource?: IResolvedCatalogSource;
|
||||
}
|
||||
|
||||
export interface IAppVersionConfig {
|
||||
image: string;
|
||||
port: number;
|
||||
envVars?: Array<{ key: string; value: string; description: string; required?: boolean }>;
|
||||
volumes?: TAppCatalogVolumeSpec[];
|
||||
publishedPorts?: IAppCatalogPublishedPort[];
|
||||
platformRequirements?: {
|
||||
mongodb?: boolean;
|
||||
s3?: boolean;
|
||||
clickhouse?: boolean;
|
||||
redis?: boolean;
|
||||
mariadb?: boolean;
|
||||
};
|
||||
minOneboxVersion?: string;
|
||||
catalogVersion?: string;
|
||||
upgradeStrategy?: TAppUpgradeStrategy;
|
||||
source?: TAppCatalogSource;
|
||||
resolvedSource?: IResolvedCatalogSource;
|
||||
resolvedImageDigest?: string;
|
||||
changelog?: string;
|
||||
breaking?: boolean;
|
||||
requiresManualReview?: boolean;
|
||||
migrationRequired?: boolean;
|
||||
backupBeforeUpgrade?: boolean;
|
||||
requiresFeatures?: string[];
|
||||
healthCheck?: {
|
||||
path?: string;
|
||||
port?: number;
|
||||
expectedStatus?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IServezoneCatalogAppInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
category: string;
|
||||
iconName?: string;
|
||||
iconUrl?: string;
|
||||
tags?: string[];
|
||||
maintainer?: string;
|
||||
links?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface IServezoneCatalogVersion extends IAppVersionConfig {
|
||||
version: string;
|
||||
}
|
||||
|
||||
export interface IServezoneCatalogManifest {
|
||||
schemaVersion: number;
|
||||
app: IServezoneCatalogAppInfo;
|
||||
latestVersion?: string;
|
||||
channel?: string;
|
||||
channels?: Record<string, string>;
|
||||
source?: TAppCatalogSource;
|
||||
runtime?: IAppVersionConfig;
|
||||
versions?: IServezoneCatalogVersion[];
|
||||
policy?: {
|
||||
allowMutableImage?: boolean;
|
||||
defaultChannel?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IAppInstallOptions {
|
||||
appId: string;
|
||||
version?: string;
|
||||
serviceName: string;
|
||||
domain?: string;
|
||||
port?: number;
|
||||
publishedPorts?: IAppCatalogPublishedPort[];
|
||||
envVars?: Record<string, string>;
|
||||
autoDNS?: boolean;
|
||||
}
|
||||
|
||||
export interface IMigrationContext {
|
||||
service: {
|
||||
name: string;
|
||||
image: string;
|
||||
envVars: Record<string, string>;
|
||||
port: number;
|
||||
};
|
||||
fromVersion: string;
|
||||
toVersion: string;
|
||||
}
|
||||
|
||||
export interface IMigrationResult {
|
||||
success: boolean;
|
||||
envVars?: Record<string, string>;
|
||||
image?: string;
|
||||
imageDigest?: string;
|
||||
port?: number;
|
||||
volumes?: IAppCatalogVolume[];
|
||||
publishedPorts?: IAppCatalogPublishedPort[];
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export interface IUpgradeableService {
|
||||
serviceName: string;
|
||||
appTemplateId: string;
|
||||
currentVersion: string;
|
||||
latestVersion: string;
|
||||
hasMigration: boolean;
|
||||
}
|
||||
+162
-764
File diff suppressed because it is too large
Load Diff
+31
-7
@@ -14,6 +14,12 @@ type TExpandedPublishedPort = Required<Pick<
|
||||
'targetPort' | 'publishedPort' | 'protocol' | 'hostIp'
|
||||
>>;
|
||||
|
||||
export interface IInteractiveContainerExec {
|
||||
stream: plugins.nodeStream.Duplex;
|
||||
close: () => Promise<void>;
|
||||
inspect: () => Promise<{ ExitCode?: number | null; Running?: boolean }>;
|
||||
}
|
||||
|
||||
export class OneboxDockerManager {
|
||||
private dockerClient: InstanceType<typeof plugins.docker.Docker> | null = null;
|
||||
private networkName = 'onebox-network';
|
||||
@@ -1128,16 +1134,12 @@ export class OneboxDockerManager {
|
||||
/**
|
||||
* Execute a command in a running container
|
||||
*/
|
||||
async execInContainer(
|
||||
containerID: string,
|
||||
cmd: string[]
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
try {
|
||||
private async resolveContainer(containerID: string): Promise<any> {
|
||||
let container: any = null;
|
||||
try {
|
||||
container = await this.dockerClient!.getContainerById(containerID);
|
||||
} catch {
|
||||
// Not a direct container ID — try Swarm service lookup
|
||||
// Not a direct container ID — try Swarm service lookup.
|
||||
}
|
||||
|
||||
if (!container) {
|
||||
@@ -1146,7 +1148,7 @@ export class OneboxDockerManager {
|
||||
try {
|
||||
container = await this.dockerClient!.getContainerById(serviceContainerId);
|
||||
} catch {
|
||||
// Service container also not found
|
||||
// Service container also not found.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1154,6 +1156,15 @@ export class OneboxDockerManager {
|
||||
if (!container) {
|
||||
throw new Error(`Container not found: ${containerID}`);
|
||||
}
|
||||
return container;
|
||||
}
|
||||
|
||||
async execInContainer(
|
||||
containerID: string,
|
||||
cmd: string[]
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
try {
|
||||
const container = await this.resolveContainer(containerID);
|
||||
|
||||
const { stream, inspect } = await container.exec(cmd, {
|
||||
attachStdout: true,
|
||||
@@ -1190,6 +1201,19 @@ export class OneboxDockerManager {
|
||||
}
|
||||
}
|
||||
|
||||
async startInteractiveExecInContainer(
|
||||
containerID: string,
|
||||
cmd: string[],
|
||||
): Promise<IInteractiveContainerExec> {
|
||||
const container = await this.resolveContainer(containerID);
|
||||
return await container.exec(cmd, {
|
||||
tty: true,
|
||||
attachStdin: true,
|
||||
attachStdout: true,
|
||||
attachStderr: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a platform service container (MongoDB, MinIO, etc.)
|
||||
* Platform containers are long-running infrastructure services
|
||||
|
||||
+48
-1
@@ -11,6 +11,26 @@ import { OneboxDatabase } from './database.ts';
|
||||
import { OneboxDockerManager } from './docker.ts';
|
||||
import type { PlatformServicesManager } from './platform-services/index.ts';
|
||||
|
||||
export type TServiceUpdateProgressStep =
|
||||
| 'stopping'
|
||||
| 'pulling-image'
|
||||
| 'updating-record'
|
||||
| 'removing-container'
|
||||
| 'creating-container'
|
||||
| 'starting'
|
||||
| 'restoring-route'
|
||||
| 'syncing-gateway'
|
||||
| 'complete';
|
||||
|
||||
export interface IServiceUpdateProgress {
|
||||
step: TServiceUpdateProgressStep;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface IServiceUpdateOptions {
|
||||
onProgress?: (progressArg: IServiceUpdateProgress) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export class OneboxServicesManager {
|
||||
private oneboxRef: any; // Will be Onebox instance
|
||||
private database: OneboxDatabase;
|
||||
@@ -583,9 +603,15 @@ export class OneboxServicesManager {
|
||||
envVars?: Record<string, string>;
|
||||
volumes?: IService['volumes'];
|
||||
publishedPorts?: IService['publishedPorts'];
|
||||
}
|
||||
imageDigest?: string;
|
||||
appTemplateVersion?: string;
|
||||
},
|
||||
optionsArg: IServiceUpdateOptions = {},
|
||||
): Promise<IService> {
|
||||
try {
|
||||
const emitProgress = async (step: TServiceUpdateProgressStep, message: string) => {
|
||||
await optionsArg.onProgress?.({ step, message });
|
||||
};
|
||||
const service = this.database.getServiceByName(name);
|
||||
if (!service) {
|
||||
throw new Error(`Service not found: ${name}`);
|
||||
@@ -599,6 +625,7 @@ export class OneboxServicesManager {
|
||||
// Stop the container if running
|
||||
if (wasRunning && oldContainerID) {
|
||||
logger.info(`Stopping service ${name} for updates...`);
|
||||
await emitProgress('stopping', `Stopping ${name} before updating its container`);
|
||||
try {
|
||||
await this.docker.stopContainer(oldContainerID);
|
||||
} catch (error) {
|
||||
@@ -609,10 +636,12 @@ export class OneboxServicesManager {
|
||||
// Pull new image if changed
|
||||
if (updates.image && updates.image !== service.image) {
|
||||
logger.info(`Pulling new image: ${updates.image}`);
|
||||
await emitProgress('pulling-image', `Pulling image ${updates.image}`);
|
||||
await this.docker.pullImage(updates.image, updates.registry || service.registry);
|
||||
}
|
||||
|
||||
// Update service in database
|
||||
await emitProgress('updating-record', `Updating service record for ${name}`);
|
||||
const updateData: any = {
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
@@ -623,6 +652,8 @@ export class OneboxServicesManager {
|
||||
if (updates.envVars !== undefined) updateData.envVars = updates.envVars;
|
||||
if (updates.volumes !== undefined) updateData.volumes = updates.volumes;
|
||||
if (updates.publishedPorts !== undefined) updateData.publishedPorts = updates.publishedPorts;
|
||||
if (updates.imageDigest !== undefined) updateData.imageDigest = updates.imageDigest;
|
||||
if (updates.appTemplateVersion !== undefined) updateData.appTemplateVersion = updates.appTemplateVersion;
|
||||
|
||||
this.database.updateService(service.id!, updateData);
|
||||
|
||||
@@ -631,6 +662,7 @@ export class OneboxServicesManager {
|
||||
|
||||
// Remove old container
|
||||
if (oldContainerID) {
|
||||
await emitProgress('removing-container', `Removing old container for ${name}`);
|
||||
try {
|
||||
await this.docker.removeContainer(oldContainerID, true);
|
||||
logger.info(`Removed old container for ${name}`);
|
||||
@@ -641,6 +673,7 @@ export class OneboxServicesManager {
|
||||
|
||||
// Create new container with updated config
|
||||
logger.info(`Creating new container for ${name}...`);
|
||||
await emitProgress('creating-container', `Creating replacement container for ${name}`);
|
||||
const containerID = await this.docker.createContainer(updatedService);
|
||||
this.database.updateService(service.id!, { containerID });
|
||||
|
||||
@@ -674,6 +707,7 @@ export class OneboxServicesManager {
|
||||
// Restart the container if it was running
|
||||
if (wasRunning) {
|
||||
logger.info(`Starting updated service ${name}...`);
|
||||
await emitProgress('starting', `Starting updated service ${name}`);
|
||||
this.database.updateService(service.id!, { status: 'starting' });
|
||||
await this.docker.startContainer(containerID);
|
||||
this.database.updateService(service.id!, { status: 'running' });
|
||||
@@ -685,8 +719,21 @@ export class OneboxServicesManager {
|
||||
|
||||
const refreshedService = this.database.getServiceByName(name)!;
|
||||
if (refreshedService.domain && refreshedService.status === 'running') {
|
||||
await emitProgress('restoring-route', `Restoring route ${refreshedService.domain} -> ${refreshedService.port}`);
|
||||
try {
|
||||
await this.oneboxRef.reverseProxy.addRoute(
|
||||
refreshedService.id!,
|
||||
refreshedService.domain,
|
||||
refreshedService.port,
|
||||
);
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to restore reverse proxy route for ${refreshedService.domain}: ${getErrorMessage(error)}`);
|
||||
throw error;
|
||||
}
|
||||
await emitProgress('syncing-gateway', `Syncing external gateway route for ${refreshedService.domain}`);
|
||||
await this.syncExternalGatewayRoute(refreshedService);
|
||||
}
|
||||
await emitProgress('complete', `Service ${name} update completed`);
|
||||
await this.broadcastServiceUpdate(name, 'updated');
|
||||
return refreshedService;
|
||||
} catch (error) {
|
||||
|
||||
@@ -9,7 +9,9 @@ import { Onebox } from './classes/onebox.ts';
|
||||
import { OneboxDaemon } from './classes/daemon.ts';
|
||||
import { OneboxSystemd } from './classes/systemd.ts';
|
||||
import { OneboxUpdateManager } from './classes/update-manager.ts';
|
||||
import type { IAppVersionConfig } from './classes/appstore-types.ts';
|
||||
import type * as servezoneInterfaces from '@serve.zone/interfaces';
|
||||
|
||||
type IAppStoreVersionConfig = servezoneInterfaces.appstore.IAppStoreVersionConfig;
|
||||
|
||||
export async function runCli(): Promise<void> {
|
||||
const args = Deno.args;
|
||||
@@ -591,7 +593,7 @@ function parseEnvArgs(args: string[]): Record<string, string> {
|
||||
}
|
||||
|
||||
function getAppStoreEnvVars(
|
||||
configArg: IAppVersionConfig,
|
||||
configArg: IAppStoreVersionConfig,
|
||||
overridesArg: Record<string, string>,
|
||||
): Record<string, string> {
|
||||
const envVars: Record<string, string> = {};
|
||||
|
||||
@@ -3,20 +3,209 @@ import { logger } from '../../logging.ts';
|
||||
import type { OpsServer } from '../classes.opsserver.ts';
|
||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
import { requireAdminIdentity } from '../helpers/guards.ts';
|
||||
import { getErrorMessage } from '../../utils/error.ts';
|
||||
|
||||
type IAppStoreUpgradeOperation = interfaces.requests.IAppStoreUpgradeOperation;
|
||||
type TAppStoreUpgradeStep = interfaces.requests.TAppStoreUpgradeStep;
|
||||
|
||||
export class AppStoreHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
private upgradeOperations = new Map<string, IAppStoreUpgradeOperation>();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private getUpgradeOperations(): IAppStoreUpgradeOperation[] {
|
||||
return Array.from(this.upgradeOperations.values())
|
||||
.sort((a, b) => b.startedAt - a.startedAt)
|
||||
.slice(0, 25);
|
||||
}
|
||||
|
||||
private getRunningUpgrade(serviceNameArg: string): IAppStoreUpgradeOperation | null {
|
||||
for (const operation of this.upgradeOperations.values()) {
|
||||
if (operation.serviceName === serviceNameArg && operation.status === 'running') {
|
||||
return operation;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async createUpgradeOperation(
|
||||
serviceNameArg: string,
|
||||
targetVersionArg: string,
|
||||
): Promise<IAppStoreUpgradeOperation> {
|
||||
const existingRunning = this.getRunningUpgrade(serviceNameArg);
|
||||
if (existingRunning) {
|
||||
throw new plugins.typedrequest.TypedResponseError(
|
||||
`An upgrade is already running for ${serviceNameArg}`,
|
||||
);
|
||||
}
|
||||
|
||||
const existingService = this.opsServerRef.oneboxRef.database.getServiceByName(serviceNameArg);
|
||||
if (!existingService) {
|
||||
throw new plugins.typedrequest.TypedResponseError(`Service not found: ${serviceNameArg}`);
|
||||
}
|
||||
if (!existingService.appTemplateId) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Service was not deployed from an app template');
|
||||
}
|
||||
if (!existingService.appTemplateVersion) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Service has no tracked template version');
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const operation: IAppStoreUpgradeOperation = {
|
||||
id: crypto.randomUUID(),
|
||||
serviceName: existingService.name,
|
||||
appTemplateId: existingService.appTemplateId,
|
||||
fromVersion: existingService.appTemplateVersion,
|
||||
targetVersion: targetVersionArg,
|
||||
status: 'running',
|
||||
step: 'queued',
|
||||
progressLines: [`Queued upgrade ${existingService.appTemplateVersion} -> ${targetVersionArg}`],
|
||||
warnings: [],
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.upgradeOperations.set(operation.id, operation);
|
||||
await this.pushUpgradeProgress(operation);
|
||||
return operation;
|
||||
}
|
||||
|
||||
private async updateUpgradeOperation(
|
||||
operationIdArg: string,
|
||||
stepArg: TAppStoreUpgradeStep,
|
||||
messageArg: string,
|
||||
updatesArg: Partial<IAppStoreUpgradeOperation> = {},
|
||||
): Promise<IAppStoreUpgradeOperation> {
|
||||
const existing = this.upgradeOperations.get(operationIdArg);
|
||||
if (!existing) {
|
||||
throw new Error(`Upgrade operation not found: ${operationIdArg}`);
|
||||
}
|
||||
|
||||
const nextOperation: IAppStoreUpgradeOperation = {
|
||||
...existing,
|
||||
...updatesArg,
|
||||
step: stepArg,
|
||||
updatedAt: Date.now(),
|
||||
progressLines: [...existing.progressLines, messageArg].slice(-200),
|
||||
};
|
||||
this.upgradeOperations.set(operationIdArg, nextOperation);
|
||||
await this.pushUpgradeProgress(nextOperation);
|
||||
return nextOperation;
|
||||
}
|
||||
|
||||
private async pushUpgradeProgress(operationArg: IAppStoreUpgradeOperation): Promise<void> {
|
||||
await this.opsServerRef.pushDashboardEvent('pushAppStoreUpgradeProgress', {
|
||||
operation: operationArg,
|
||||
});
|
||||
}
|
||||
|
||||
private async performUpgrade(operationIdArg: string): Promise<interfaces.data.IService> {
|
||||
let operation = this.upgradeOperations.get(operationIdArg);
|
||||
if (!operation) {
|
||||
throw new Error(`Upgrade operation not found: ${operationIdArg}`);
|
||||
}
|
||||
|
||||
try {
|
||||
operation = await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'validating',
|
||||
`Validating ${operation.serviceName} for App Store upgrade`,
|
||||
);
|
||||
|
||||
const existingService = this.opsServerRef.oneboxRef.database.getServiceByName(operation.serviceName);
|
||||
if (!existingService) {
|
||||
throw new Error(`Service not found: ${operation.serviceName}`);
|
||||
}
|
||||
if (!existingService.appTemplateId || !existingService.appTemplateVersion) {
|
||||
throw new Error('Service is missing App Store template metadata');
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`Upgrading service '${operation.serviceName}' from v${operation.fromVersion} to v${operation.targetVersion}`,
|
||||
);
|
||||
|
||||
await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'migration',
|
||||
`Resolving migration for ${operation.appTemplateId} ${operation.fromVersion} -> ${operation.targetVersion}`,
|
||||
);
|
||||
|
||||
const migrationResult = await this.opsServerRef.oneboxRef.appStore.executeMigration(
|
||||
existingService,
|
||||
operation.fromVersion,
|
||||
operation.targetVersion,
|
||||
);
|
||||
|
||||
if (!migrationResult.success) {
|
||||
throw new Error(`Migration failed: ${migrationResult.warnings.join('; ')}`);
|
||||
}
|
||||
|
||||
if (migrationResult.warnings.length > 0) {
|
||||
operation = await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'migration',
|
||||
`Migration completed with ${migrationResult.warnings.length} warning(s)`,
|
||||
{ warnings: migrationResult.warnings },
|
||||
);
|
||||
}
|
||||
|
||||
await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'applying',
|
||||
`Applying upgrade to ${operation.serviceName}`,
|
||||
);
|
||||
|
||||
const updatedService = await this.opsServerRef.oneboxRef.appStore.applyUpgrade(
|
||||
operation.serviceName,
|
||||
migrationResult,
|
||||
operation.targetVersion,
|
||||
{
|
||||
onProgress: async (progressArg) => {
|
||||
await this.updateUpgradeOperation(
|
||||
operation!.id,
|
||||
progressArg.step as TAppStoreUpgradeStep,
|
||||
progressArg.message,
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'complete',
|
||||
`Upgrade completed for ${operation.serviceName}`,
|
||||
{
|
||||
status: 'success',
|
||||
completedAt: Date.now(),
|
||||
service: updatedService,
|
||||
warnings: migrationResult.warnings,
|
||||
},
|
||||
);
|
||||
|
||||
return updatedService;
|
||||
} catch (error) {
|
||||
await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'failed',
|
||||
`Upgrade failed: ${getErrorMessage(error)}`,
|
||||
{
|
||||
status: 'failed',
|
||||
completedAt: Date.now(),
|
||||
error: getErrorMessage(error),
|
||||
},
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
// Get app templates (catalog)
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppTemplates>(
|
||||
'getAppTemplates',
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppStoreTemplates>(
|
||||
'getAppStoreTemplates',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const apps = await this.opsServerRef.oneboxRef.appStore.getApps();
|
||||
@@ -25,10 +214,9 @@ export class AppStoreHandler {
|
||||
),
|
||||
);
|
||||
|
||||
// Get app config for a specific version
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppConfig>(
|
||||
'getAppConfig',
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppStoreConfig>(
|
||||
'getAppStoreConfig',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const config = await this.opsServerRef.oneboxRef.appStore.getAppVersionConfig(
|
||||
@@ -42,8 +230,8 @@ export class AppStoreHandler {
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_InstallAppTemplate>(
|
||||
'installAppTemplate',
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_InstallAppStoreApp>(
|
||||
'installAppStoreApp',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const service = await this.opsServerRef.oneboxRef.appStore.installApp(dataArg.install);
|
||||
@@ -52,64 +240,54 @@ export class AppStoreHandler {
|
||||
),
|
||||
);
|
||||
|
||||
// Get services with available upgrades
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetUpgradeableServices>(
|
||||
'getUpgradeableServices',
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetUpgradeableAppStoreServices>(
|
||||
'getUpgradeableAppStoreServices',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const services = await this.opsServerRef.oneboxRef.appStore.getUpgradeableServices();
|
||||
const services = await this.opsServerRef.oneboxRef.appStore.getUpgradeableAppStoreServices();
|
||||
return { services };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Upgrade a service to a new template version
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpgradeService>(
|
||||
'upgradeService',
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpgradeAppStoreService>(
|
||||
'upgradeAppStoreService',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
|
||||
const existingService = this.opsServerRef.oneboxRef.database.getServiceByName(dataArg.serviceName);
|
||||
if (!existingService) {
|
||||
throw new plugins.typedrequest.TypedResponseError(`Service not found: ${dataArg.serviceName}`);
|
||||
}
|
||||
if (!existingService.appTemplateId) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Service was not deployed from an app template');
|
||||
}
|
||||
if (!existingService.appTemplateVersion) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Service has no tracked template version');
|
||||
}
|
||||
|
||||
logger.info(`Upgrading service '${dataArg.serviceName}' from v${existingService.appTemplateVersion} to v${dataArg.targetVersion}`);
|
||||
|
||||
// Execute migration
|
||||
const migrationResult = await this.opsServerRef.oneboxRef.appStore.executeMigration(
|
||||
existingService,
|
||||
existingService.appTemplateVersion,
|
||||
dataArg.targetVersion,
|
||||
);
|
||||
|
||||
if (!migrationResult.success) {
|
||||
throw new plugins.typedrequest.TypedResponseError(
|
||||
`Migration failed: ${migrationResult.warnings.join('; ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Apply the upgrade
|
||||
const updatedService = await this.opsServerRef.oneboxRef.appStore.applyUpgrade(
|
||||
dataArg.serviceName,
|
||||
migrationResult,
|
||||
dataArg.targetVersion,
|
||||
);
|
||||
const operation = await this.createUpgradeOperation(dataArg.serviceName, dataArg.targetVersion);
|
||||
const updatedService = await this.performUpgrade(operation.id);
|
||||
const completedOperation = this.upgradeOperations.get(operation.id)!;
|
||||
|
||||
return {
|
||||
service: updatedService,
|
||||
warnings: migrationResult.warnings,
|
||||
warnings: completedOperation.warnings,
|
||||
};
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_StartAppStoreServiceUpgrade>(
|
||||
'startAppStoreServiceUpgrade',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const operation = await this.createUpgradeOperation(dataArg.serviceName, dataArg.targetVersion);
|
||||
void this.performUpgrade(operation.id).catch(() => {});
|
||||
return { operation };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppStoreUpgradeOperations>(
|
||||
'getAppStoreUpgradeOperations',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
return { operations: this.getUpgradeOperations() };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,8 +5,21 @@ import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
import { requireAdminIdentity } from '../helpers/guards.ts';
|
||||
import { getErrorMessage } from '../../utils/error.ts';
|
||||
|
||||
interface IWorkspaceProcessSession {
|
||||
processId: string;
|
||||
serviceName: string;
|
||||
userId: string;
|
||||
stream: plugins.nodeStream.Duplex;
|
||||
close: () => Promise<void>;
|
||||
inspect: () => Promise<{ ExitCode?: number | null; Running?: boolean }>;
|
||||
finalized: boolean;
|
||||
}
|
||||
|
||||
const getWorkspaceProcessTag = (processIdArg: string) => `workspaceProcess:${processIdArg}`;
|
||||
|
||||
export class WorkspaceHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
private workspaceProcesses = new Map<string, IWorkspaceProcessSession>();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
@@ -24,6 +37,111 @@ export class WorkspaceHandler {
|
||||
return service.containerID;
|
||||
}
|
||||
|
||||
private validateProcessId(processIdArg: string): void {
|
||||
if (!/^[a-zA-Z0-9_-]{8,80}$/.test(processIdArg)) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Invalid workspace process id');
|
||||
}
|
||||
}
|
||||
|
||||
private async getShellCommandForContainer(
|
||||
containerIdArg: string,
|
||||
): Promise<interfaces.requests.IWorkspaceShellCommand> {
|
||||
const candidates: interfaces.requests.IWorkspaceShellCommand[] = [
|
||||
{ command: '/bin/bash', args: ['-il'], label: 'bash', prompt: '# ' },
|
||||
{ command: 'bash', args: ['-il'], label: 'bash', prompt: '# ' },
|
||||
{ command: '/bin/sh', args: ['-i'], label: 'sh', prompt: '# ' },
|
||||
{ command: 'sh', args: ['-i'], label: 'sh', prompt: '# ' },
|
||||
{ command: '/bin/ash', args: ['-i'], label: 'ash', prompt: '# ' },
|
||||
{ command: 'ash', args: ['-i'], label: 'ash', prompt: '# ' },
|
||||
{ command: '/usr/bin/zsh', args: ['-il'], label: 'zsh', prompt: '# ' },
|
||||
{ command: 'zsh', args: ['-il'], label: 'zsh', prompt: '# ' },
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const result = await this.opsServerRef.oneboxRef.docker.execInContainer(
|
||||
containerIdArg,
|
||||
[candidate.command, '-c', 'printf onebox-shell'],
|
||||
);
|
||||
if (result.exitCode === 0 && result.stdout.includes('onebox-shell')) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
throw new plugins.typedrequest.TypedResponseError(
|
||||
'No supported interactive shell found in the target container',
|
||||
);
|
||||
}
|
||||
|
||||
private async getProcessSession(
|
||||
dataArg: { identity: interfaces.data.IIdentity; processId: string },
|
||||
): Promise<IWorkspaceProcessSession> {
|
||||
const identity = await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
this.validateProcessId(dataArg.processId);
|
||||
const session = this.workspaceProcesses.get(dataArg.processId);
|
||||
if (!session) {
|
||||
throw new plugins.typedrequest.TypedResponseError(`Workspace process not found: ${dataArg.processId}`);
|
||||
}
|
||||
if (session.userId !== identity.userId) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Workspace process belongs to another session');
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
private async pushWorkspaceProcessOutput(processIdArg: string, outputArg: string): Promise<void> {
|
||||
const typedsocket = (this.opsServerRef.server as any)?.typedserver?.typedsocket;
|
||||
if (!typedsocket) return;
|
||||
|
||||
const connections = await typedsocket.findAllTargetConnectionsByTag(getWorkspaceProcessTag(processIdArg));
|
||||
await Promise.allSettled(
|
||||
connections.map((connection: any) => typedsocket
|
||||
.createTypedRequest(
|
||||
'pushWorkspaceProcessOutput',
|
||||
connection,
|
||||
)
|
||||
.fire({ processId: processIdArg, output: outputArg })),
|
||||
);
|
||||
}
|
||||
|
||||
private async pushWorkspaceProcessExit(processIdArg: string, exitCodeArg: number): Promise<void> {
|
||||
const typedsocket = (this.opsServerRef.server as any)?.typedserver?.typedsocket;
|
||||
if (!typedsocket) return;
|
||||
|
||||
const connections = await typedsocket.findAllTargetConnectionsByTag(getWorkspaceProcessTag(processIdArg));
|
||||
await Promise.allSettled(
|
||||
connections.map((connection: any) => typedsocket
|
||||
.createTypedRequest(
|
||||
'pushWorkspaceProcessExit',
|
||||
connection,
|
||||
)
|
||||
.fire({ processId: processIdArg, exitCode: exitCodeArg })),
|
||||
);
|
||||
}
|
||||
|
||||
private async finalizeWorkspaceProcess(processIdArg: string, fallbackExitCodeArg = -1): Promise<void> {
|
||||
const session = this.workspaceProcesses.get(processIdArg);
|
||||
if (!session || session.finalized) return;
|
||||
session.finalized = true;
|
||||
|
||||
let exitCode = fallbackExitCodeArg;
|
||||
try {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
const inspectResult = await session.inspect();
|
||||
if (typeof inspectResult.ExitCode === 'number') {
|
||||
exitCode = inspectResult.ExitCode;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.debug(`Failed to inspect workspace process ${processIdArg}: ${getErrorMessage(error)}`);
|
||||
}
|
||||
|
||||
this.workspaceProcesses.delete(processIdArg);
|
||||
await this.pushWorkspaceProcessExit(processIdArg, exitCode);
|
||||
try {
|
||||
await session.close();
|
||||
} catch {
|
||||
// The hijacked connection may already be closed by Docker.
|
||||
}
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
// Read file from container
|
||||
this.typedrouter.addTypedHandler(
|
||||
@@ -176,6 +294,108 @@ export class WorkspaceHandler {
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceGetShellCommand>(
|
||||
'workspaceGetShellCommand',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const containerId = await this.resolveContainerId(dataArg.serviceName);
|
||||
const shellCommand = await this.getShellCommandForContainer(containerId);
|
||||
return { shellCommand };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceStartProcess>(
|
||||
'workspaceStartProcess',
|
||||
async (dataArg) => {
|
||||
const identity = await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
this.validateProcessId(dataArg.processId);
|
||||
if (this.workspaceProcesses.has(dataArg.processId)) {
|
||||
throw new plugins.typedrequest.TypedResponseError(`Workspace process already exists: ${dataArg.processId}`);
|
||||
}
|
||||
|
||||
const containerId = await this.resolveContainerId(dataArg.serviceName);
|
||||
const command = dataArg.args ? [dataArg.command, ...dataArg.args] : [dataArg.command];
|
||||
const interactiveExec = await this.opsServerRef.oneboxRef.docker.startInteractiveExecInContainer(
|
||||
containerId,
|
||||
command,
|
||||
);
|
||||
|
||||
const session: IWorkspaceProcessSession = {
|
||||
processId: dataArg.processId,
|
||||
serviceName: dataArg.serviceName,
|
||||
userId: identity.userId,
|
||||
stream: interactiveExec.stream,
|
||||
close: interactiveExec.close,
|
||||
inspect: interactiveExec.inspect,
|
||||
finalized: false,
|
||||
};
|
||||
this.workspaceProcesses.set(dataArg.processId, session);
|
||||
|
||||
interactiveExec.stream.on('data', (chunk: Uint8Array | string) => {
|
||||
const output = typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk);
|
||||
void this.pushWorkspaceProcessOutput(dataArg.processId, output);
|
||||
});
|
||||
interactiveExec.stream.on('error', (error: Error) => {
|
||||
void this.pushWorkspaceProcessOutput(
|
||||
dataArg.processId,
|
||||
`\r\n[workspace process error: ${getErrorMessage(error)}]\r\n`,
|
||||
);
|
||||
void this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||
});
|
||||
interactiveExec.stream.on('end', () => {
|
||||
void this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||
});
|
||||
interactiveExec.stream.on('close', () => {
|
||||
void this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||
});
|
||||
|
||||
return { processId: dataArg.processId };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceProcessInput>(
|
||||
'workspaceProcessInput',
|
||||
async (dataArg) => {
|
||||
const session = await this.getProcessSession(dataArg);
|
||||
if (session.finalized || session.stream.writableEnded) {
|
||||
return {};
|
||||
}
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
session.stream.write(dataArg.input, (error?: Error | null) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
return {};
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceKillProcess>(
|
||||
'workspaceKillProcess',
|
||||
async (dataArg) => {
|
||||
const session = await this.getProcessSession(dataArg);
|
||||
session.stream.destroy();
|
||||
try {
|
||||
await session.close();
|
||||
} catch {
|
||||
// The stream may already be closed.
|
||||
}
|
||||
await this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||
return {};
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
logger.info('Workspace handler registered');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +82,11 @@ export { smartguard, smartjwt };
|
||||
import { ContainerArchive } from '@serve.zone/containerarchive';
|
||||
export { ContainerArchive };
|
||||
|
||||
// serve.zone App Store contracts and resolver
|
||||
import * as servezoneInterfaces from '@serve.zone/interfaces';
|
||||
import * as servezoneAppstore from '@serve.zone/appstore';
|
||||
export { servezoneInterfaces, servezoneAppstore };
|
||||
|
||||
// Node.js compat for streaming
|
||||
import * as nodeFs from 'node:fs';
|
||||
import * as nodeStream from 'node:stream';
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,125 +1,112 @@
|
||||
import type * as servezoneInterfaces from '@serve.zone/interfaces';
|
||||
import * as plugins from '../plugins.ts';
|
||||
import * as data from '../data/index.ts';
|
||||
|
||||
export interface ICatalogApp {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
category: string;
|
||||
iconName?: string;
|
||||
iconUrl?: string;
|
||||
latestVersion: string;
|
||||
tags?: string[];
|
||||
}
|
||||
export type IAppStoreApp = servezoneInterfaces.appstore.IAppStoreApp;
|
||||
export type IAppStoreVersionConfig = servezoneInterfaces.appstore.IAppStoreVersionConfig;
|
||||
export type IAppStoreAppMeta = servezoneInterfaces.appstore.IAppStoreAppMeta;
|
||||
export type IUpgradeableAppStoreService = servezoneInterfaces.appstore.IUpgradeableAppStoreService;
|
||||
|
||||
export interface IAppVersionConfig {
|
||||
image: string;
|
||||
port: number;
|
||||
envVars?: Array<{ key: string; value: string; description: string; required?: boolean }>;
|
||||
volumes?: Array<string | data.IServiceVolume>;
|
||||
publishedPorts?: data.IServicePublishedPort[];
|
||||
platformRequirements?: {
|
||||
mongodb?: boolean;
|
||||
s3?: boolean;
|
||||
clickhouse?: boolean;
|
||||
redis?: boolean;
|
||||
mariadb?: boolean;
|
||||
};
|
||||
minOneboxVersion?: string;
|
||||
}
|
||||
|
||||
export interface IAppInstallOptions {
|
||||
appId: string;
|
||||
version?: string;
|
||||
serviceName: string;
|
||||
domain?: string;
|
||||
port?: number;
|
||||
publishedPorts?: data.IServicePublishedPort[];
|
||||
envVars?: Record<string, string>;
|
||||
export interface IAppStoreInstallOptions extends servezoneInterfaces.appstore.IAppStoreInstallRequest {
|
||||
autoDNS?: boolean;
|
||||
}
|
||||
|
||||
export interface IAppMeta {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
category: string;
|
||||
iconName?: string;
|
||||
latestVersion: string;
|
||||
versions: string[];
|
||||
maintainer?: string;
|
||||
links?: Record<string, string>;
|
||||
}
|
||||
export type TAppStoreUpgradeStatus = 'running' | 'success' | 'failed';
|
||||
|
||||
export interface IUpgradeableService {
|
||||
export type TAppStoreUpgradeStep =
|
||||
| 'queued'
|
||||
| 'validating'
|
||||
| 'migration'
|
||||
| 'applying'
|
||||
| 'stopping'
|
||||
| 'pulling-image'
|
||||
| 'updating-record'
|
||||
| 'removing-container'
|
||||
| 'creating-container'
|
||||
| 'starting'
|
||||
| 'restoring-route'
|
||||
| 'syncing-gateway'
|
||||
| 'complete'
|
||||
| 'failed';
|
||||
|
||||
export interface IAppStoreUpgradeOperation {
|
||||
id: string;
|
||||
serviceName: string;
|
||||
appTemplateId: string;
|
||||
currentVersion: string;
|
||||
latestVersion: string;
|
||||
hasMigration: boolean;
|
||||
fromVersion: string;
|
||||
targetVersion: string;
|
||||
status: TAppStoreUpgradeStatus;
|
||||
step: TAppStoreUpgradeStep;
|
||||
progressLines: string[];
|
||||
warnings: string[];
|
||||
error?: string;
|
||||
startedAt: number;
|
||||
updatedAt: number;
|
||||
completedAt?: number;
|
||||
service?: data.IService;
|
||||
}
|
||||
|
||||
export interface IReq_GetAppTemplates extends plugins.typedrequestInterfaces.implementsTR<
|
||||
export interface IReq_GetAppStoreTemplates extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetAppTemplates
|
||||
IReq_GetAppStoreTemplates
|
||||
> {
|
||||
method: 'getAppTemplates';
|
||||
method: 'getAppStoreTemplates';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
};
|
||||
response: {
|
||||
apps: ICatalogApp[];
|
||||
apps: IAppStoreApp[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_GetAppConfig extends plugins.typedrequestInterfaces.implementsTR<
|
||||
export interface IReq_GetAppStoreConfig extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetAppConfig
|
||||
IReq_GetAppStoreConfig
|
||||
> {
|
||||
method: 'getAppConfig';
|
||||
method: 'getAppStoreConfig';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
appId: string;
|
||||
version: string;
|
||||
};
|
||||
response: {
|
||||
config: IAppVersionConfig;
|
||||
appMeta: IAppMeta;
|
||||
config: IAppStoreVersionConfig;
|
||||
appMeta: IAppStoreAppMeta;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_InstallAppTemplate extends plugins.typedrequestInterfaces.implementsTR<
|
||||
export interface IReq_InstallAppStoreApp extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_InstallAppTemplate
|
||||
IReq_InstallAppStoreApp
|
||||
> {
|
||||
method: 'installAppTemplate';
|
||||
method: 'installAppStoreApp';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
install: IAppInstallOptions;
|
||||
install: IAppStoreInstallOptions;
|
||||
};
|
||||
response: {
|
||||
service: data.IService;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_GetUpgradeableServices extends plugins.typedrequestInterfaces.implementsTR<
|
||||
export interface IReq_GetUpgradeableAppStoreServices extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetUpgradeableServices
|
||||
IReq_GetUpgradeableAppStoreServices
|
||||
> {
|
||||
method: 'getUpgradeableServices';
|
||||
method: 'getUpgradeableAppStoreServices';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
};
|
||||
response: {
|
||||
services: IUpgradeableService[];
|
||||
services: IUpgradeableAppStoreService[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_UpgradeService extends plugins.typedrequestInterfaces.implementsTR<
|
||||
export interface IReq_UpgradeAppStoreService extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_UpgradeService
|
||||
IReq_UpgradeAppStoreService
|
||||
> {
|
||||
method: 'upgradeService';
|
||||
method: 'upgradeAppStoreService';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
serviceName: string;
|
||||
@@ -130,3 +117,42 @@ export interface IReq_UpgradeService extends plugins.typedrequestInterfaces.impl
|
||||
warnings: string[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_StartAppStoreServiceUpgrade extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_StartAppStoreServiceUpgrade
|
||||
> {
|
||||
method: 'startAppStoreServiceUpgrade';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
serviceName: string;
|
||||
targetVersion: string;
|
||||
};
|
||||
response: {
|
||||
operation: IAppStoreUpgradeOperation;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_GetAppStoreUpgradeOperations extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetAppStoreUpgradeOperations
|
||||
> {
|
||||
method: 'getAppStoreUpgradeOperations';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
};
|
||||
response: {
|
||||
operations: IAppStoreUpgradeOperation[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_PushAppStoreUpgradeProgress extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_PushAppStoreUpgradeProgress
|
||||
> {
|
||||
method: 'pushAppStoreUpgradeProgress';
|
||||
request: {
|
||||
operation: IAppStoreUpgradeOperation;
|
||||
};
|
||||
response: {};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import * as plugins from '../plugins.ts';
|
||||
import * as data from '../data/index.ts';
|
||||
|
||||
export interface IWorkspaceShellCommand {
|
||||
command: string;
|
||||
args?: string[];
|
||||
label?: string;
|
||||
prompt?: string;
|
||||
}
|
||||
|
||||
export interface IReq_WorkspaceReadFile extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_WorkspaceReadFile
|
||||
@@ -104,3 +111,83 @@ export interface IReq_WorkspaceExec extends plugins.typedrequestInterfaces.imple
|
||||
exitCode: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_WorkspaceGetShellCommand extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_WorkspaceGetShellCommand
|
||||
> {
|
||||
method: 'workspaceGetShellCommand';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
serviceName: string;
|
||||
};
|
||||
response: {
|
||||
shellCommand: IWorkspaceShellCommand;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_WorkspaceStartProcess extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_WorkspaceStartProcess
|
||||
> {
|
||||
method: 'workspaceStartProcess';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
serviceName: string;
|
||||
processId: string;
|
||||
command: string;
|
||||
args?: string[];
|
||||
};
|
||||
response: {
|
||||
processId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_WorkspaceProcessInput extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_WorkspaceProcessInput
|
||||
> {
|
||||
method: 'workspaceProcessInput';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
processId: string;
|
||||
input: string;
|
||||
};
|
||||
response: {};
|
||||
}
|
||||
|
||||
export interface IReq_WorkspaceKillProcess extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_WorkspaceKillProcess
|
||||
> {
|
||||
method: 'workspaceKillProcess';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
processId: string;
|
||||
};
|
||||
response: {};
|
||||
}
|
||||
|
||||
export interface IReq_PushWorkspaceProcessOutput extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_PushWorkspaceProcessOutput
|
||||
> {
|
||||
method: 'pushWorkspaceProcessOutput';
|
||||
request: {
|
||||
processId: string;
|
||||
output: string;
|
||||
};
|
||||
response: {};
|
||||
}
|
||||
|
||||
export interface IReq_PushWorkspaceProcessExit extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_PushWorkspaceProcessExit
|
||||
> {
|
||||
method: 'pushWorkspaceProcessExit';
|
||||
request: {
|
||||
processId: string;
|
||||
exitCode: number;
|
||||
};
|
||||
response: {};
|
||||
}
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@serve.zone/onebox',
|
||||
version: '1.31.0',
|
||||
version: '2.1.1',
|
||||
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
|
||||
}
|
||||
|
||||
+75
-18
@@ -58,8 +58,9 @@ export interface ISettingsState {
|
||||
}
|
||||
|
||||
export interface IAppStoreState {
|
||||
apps: interfaces.requests.ICatalogApp[];
|
||||
upgradeableServices: interfaces.requests.IUpgradeableService[];
|
||||
apps: interfaces.requests.IAppStoreApp[];
|
||||
upgradeableServices: interfaces.requests.IUpgradeableAppStoreService[];
|
||||
upgradeOperations: interfaces.requests.IAppStoreUpgradeOperation[];
|
||||
}
|
||||
|
||||
export interface IUiState {
|
||||
@@ -154,6 +155,7 @@ export const appStoreStatePart = await appState.getStatePart<IAppStoreState>(
|
||||
{
|
||||
apps: [],
|
||||
upgradeableServices: [],
|
||||
upgradeOperations: [],
|
||||
},
|
||||
'soft',
|
||||
);
|
||||
@@ -1101,6 +1103,19 @@ const upsertService = (
|
||||
return updatedServices;
|
||||
};
|
||||
|
||||
const upsertUpgradeOperation = (
|
||||
operations: interfaces.requests.IAppStoreUpgradeOperation[],
|
||||
operation: interfaces.requests.IAppStoreUpgradeOperation,
|
||||
): interfaces.requests.IAppStoreUpgradeOperation[] => {
|
||||
const existingIndex = operations.findIndex((item) => item.id === operation.id);
|
||||
const updatedOperations = existingIndex === -1
|
||||
? [operation, ...operations]
|
||||
: operations.map((item) => item.id === operation.id ? operation : item);
|
||||
return updatedOperations
|
||||
.sort((a, b) => b.startedAt - a.startedAt)
|
||||
.slice(0, 25);
|
||||
};
|
||||
|
||||
socketRouter.addTypedHandler(
|
||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushServiceUpdate>(
|
||||
'pushServiceUpdate',
|
||||
@@ -1137,6 +1152,33 @@ socketRouter.addTypedHandler(
|
||||
),
|
||||
);
|
||||
|
||||
socketRouter.addTypedHandler(
|
||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushAppStoreUpgradeProgress>(
|
||||
'pushAppStoreUpgradeProgress',
|
||||
async (dataArg) => {
|
||||
const state = appStoreStatePart.getState();
|
||||
appStoreStatePart.setState({
|
||||
...state,
|
||||
upgradeOperations: upsertUpgradeOperation(state.upgradeOperations, dataArg.operation),
|
||||
upgradeableServices: dataArg.operation.status === 'success'
|
||||
? state.upgradeableServices.filter((service) => service.serviceName !== dataArg.operation.serviceName)
|
||||
: state.upgradeableServices,
|
||||
});
|
||||
if (dataArg.operation.service) {
|
||||
const servicesState = servicesStatePart.getState();
|
||||
servicesStatePart.setState({
|
||||
...servicesState,
|
||||
services: upsertService(servicesState.services, dataArg.operation.service),
|
||||
currentService: servicesState.currentService?.name === dataArg.operation.service.name
|
||||
? dataArg.operation.service
|
||||
: servicesState.currentService,
|
||||
});
|
||||
}
|
||||
return {};
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Handle server-pushed platform service log entries
|
||||
socketRouter.addTypedHandler(
|
||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushPlatformServiceLog>(
|
||||
@@ -1226,13 +1268,13 @@ async function disconnectSocket() {
|
||||
// App Store Actions
|
||||
// ============================================================================
|
||||
|
||||
export const fetchAppTemplatesAction = appStoreStatePart.createAction(
|
||||
export const fetchAppStoreTemplatesAction = appStoreStatePart.createAction(
|
||||
async (statePartArg) => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetAppTemplates
|
||||
>('/typedrequest', 'getAppTemplates');
|
||||
interfaces.requests.IReq_GetAppStoreTemplates
|
||||
>('/typedrequest', 'getAppStoreTemplates');
|
||||
const response = await typedRequest.fire({ identity: context.identity! });
|
||||
return { ...statePartArg.getState(), apps: response.apps };
|
||||
} catch (err) {
|
||||
@@ -1242,13 +1284,13 @@ export const fetchAppTemplatesAction = appStoreStatePart.createAction(
|
||||
},
|
||||
);
|
||||
|
||||
export const fetchUpgradeableServicesAction = appStoreStatePart.createAction(
|
||||
export const fetchUpgradeableAppStoreServicesAction = appStoreStatePart.createAction(
|
||||
async (statePartArg) => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetUpgradeableServices
|
||||
>('/typedrequest', 'getUpgradeableServices');
|
||||
interfaces.requests.IReq_GetUpgradeableAppStoreServices
|
||||
>('/typedrequest', 'getUpgradeableAppStoreServices');
|
||||
const response = await typedRequest.fire({ identity: context.identity! });
|
||||
return { ...statePartArg.getState(), upgradeableServices: response.services };
|
||||
} catch (err) {
|
||||
@@ -1258,26 +1300,41 @@ export const fetchUpgradeableServicesAction = appStoreStatePart.createAction(
|
||||
},
|
||||
);
|
||||
|
||||
export const upgradeServiceAction = appStoreStatePart.createAction<{
|
||||
export const fetchAppStoreUpgradeOperationsAction = appStoreStatePart.createAction(
|
||||
async (statePartArg) => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetAppStoreUpgradeOperations
|
||||
>('/typedrequest', 'getAppStoreUpgradeOperations');
|
||||
const response = await typedRequest.fire({ identity: context.identity! });
|
||||
return { ...statePartArg.getState(), upgradeOperations: response.operations };
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch upgrade operations:', err);
|
||||
return statePartArg.getState();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const upgradeAppStoreServiceAction = appStoreStatePart.createAction<{
|
||||
serviceName: string;
|
||||
targetVersion: string;
|
||||
}>(async (statePartArg, dataArg) => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_UpgradeService
|
||||
>('/typedrequest', 'upgradeService');
|
||||
await typedRequest.fire({
|
||||
interfaces.requests.IReq_StartAppStoreServiceUpgrade
|
||||
>('/typedrequest', 'startAppStoreServiceUpgrade');
|
||||
const response = await typedRequest.fire({
|
||||
identity: context.identity!,
|
||||
serviceName: dataArg.serviceName,
|
||||
targetVersion: dataArg.targetVersion,
|
||||
});
|
||||
// Re-fetch upgradeable services and services list
|
||||
const upgradeReq = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetUpgradeableServices
|
||||
>('/typedrequest', 'getUpgradeableServices');
|
||||
const upgradeResp = await upgradeReq.fire({ identity: context.identity! });
|
||||
return { ...statePartArg.getState(), upgradeableServices: upgradeResp.services };
|
||||
const state = statePartArg.getState();
|
||||
return {
|
||||
...state,
|
||||
upgradeOperations: upsertUpgradeOperation(state.upgradeOperations, response.operation),
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('Failed to upgrade service:', err);
|
||||
return statePartArg.getState();
|
||||
|
||||
@@ -19,19 +19,20 @@ export class ObViewAppStore extends DeesElement {
|
||||
accessor appStoreState: appstate.IAppStoreState = {
|
||||
apps: [],
|
||||
upgradeableServices: [],
|
||||
upgradeOperations: [],
|
||||
};
|
||||
|
||||
@state()
|
||||
accessor currentView: 'grid' | 'detail' = 'grid';
|
||||
|
||||
@state()
|
||||
accessor selectedApp: interfaces.requests.ICatalogApp | null = null;
|
||||
accessor selectedApp: interfaces.requests.IAppStoreApp | null = null;
|
||||
|
||||
@state()
|
||||
accessor selectedAppMeta: interfaces.requests.IAppMeta | null = null;
|
||||
accessor selectedAppMeta: interfaces.requests.IAppStoreAppMeta | null = null;
|
||||
|
||||
@state()
|
||||
accessor selectedAppConfig: interfaces.requests.IAppVersionConfig | null = null;
|
||||
accessor selectedAppConfig: interfaces.requests.IAppStoreVersionConfig | null = null;
|
||||
|
||||
@state()
|
||||
accessor selectedVersion: string = '';
|
||||
@@ -331,7 +332,10 @@ export class ObViewAppStore extends DeesElement {
|
||||
|
||||
async connectedCallback() {
|
||||
super.connectedCallback();
|
||||
await appstate.appStoreStatePart.dispatchAction(appstate.fetchAppTemplatesAction, null);
|
||||
await Promise.all([
|
||||
appstate.appStoreStatePart.dispatchAction(appstate.fetchAppStoreTemplatesAction, null),
|
||||
appstate.appStoreStatePart.dispatchAction(appstate.fetchAppStoreUpgradeOperationsAction, null),
|
||||
]);
|
||||
}
|
||||
|
||||
public render(): TemplateResult {
|
||||
@@ -357,6 +361,7 @@ export class ObViewAppStore extends DeesElement {
|
||||
|
||||
return html`
|
||||
<ob-sectionheading>App Store</ob-sectionheading>
|
||||
${this.renderUpgradeOperations()}
|
||||
${appTemplates.length === 0
|
||||
? html`<div class="loading-spinner">Loading app templates...</div>`
|
||||
: html`
|
||||
@@ -369,6 +374,27 @@ export class ObViewAppStore extends DeesElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private renderUpgradeOperations(): TemplateResult | '' {
|
||||
const visibleOperations = this.appStoreState.upgradeOperations
|
||||
.filter((operation) => operation.status === 'running' || operation.status === 'failed')
|
||||
.slice(0, 3);
|
||||
if (visibleOperations.length === 0) return '';
|
||||
|
||||
return html`
|
||||
<div class="detail-card">
|
||||
<div class="section-label">Recent Upgrade Operations</div>
|
||||
<div class="footprint-list">
|
||||
${visibleOperations.map((operation) => html`
|
||||
<div class="footprint-item">
|
||||
<span>${operation.serviceName}: ${operation.fromVersion} → ${operation.targetVersion}</span>
|
||||
<span class="footprint-meta">${operation.status} / ${operation.step}</span>
|
||||
</div>
|
||||
`)}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderDetailView(): TemplateResult {
|
||||
if (this.loading) {
|
||||
return html`
|
||||
@@ -541,7 +567,7 @@ export class ObViewAppStore extends DeesElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private renderDeploymentFootprint(config: interfaces.requests.IAppVersionConfig): TemplateResult | '' {
|
||||
private renderDeploymentFootprint(config: interfaces.requests.IAppStoreVersionConfig): TemplateResult | '' {
|
||||
const volumes = this.getConfigVolumes(config);
|
||||
const publishedPorts = config.publishedPorts || [];
|
||||
|
||||
@@ -577,7 +603,7 @@ export class ObViewAppStore extends DeesElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private renderDeployConfirmation(config: interfaces.requests.IAppVersionConfig): TemplateResult | '' {
|
||||
private renderDeployConfirmation(config: interfaces.requests.IAppStoreVersionConfig): TemplateResult | '' {
|
||||
const volumes = this.getConfigVolumes(config);
|
||||
const publishedPorts = config.publishedPorts || [];
|
||||
if (volumes.length === 0 && publishedPorts.length === 0) return '';
|
||||
@@ -590,7 +616,7 @@ export class ObViewAppStore extends DeesElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private getConfigVolumes(config: interfaces.requests.IAppVersionConfig): interfaces.data.IServiceVolume[] {
|
||||
private getConfigVolumes(config: interfaces.requests.IAppStoreVersionConfig): interfaces.data.IServiceVolume[] {
|
||||
return (config.volumes || []).map((volume) => {
|
||||
if (typeof volume === 'string') {
|
||||
return { mountPath: volume };
|
||||
@@ -658,8 +684,8 @@ export class ObViewAppStore extends DeesElement {
|
||||
if (!identity) return;
|
||||
|
||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetAppConfig
|
||||
>('/typedrequest', 'getAppConfig');
|
||||
interfaces.requests.IReq_GetAppStoreConfig
|
||||
>('/typedrequest', 'getAppStoreConfig');
|
||||
|
||||
const response = await typedRequest.fire({ identity, appId, version });
|
||||
|
||||
@@ -728,8 +754,8 @@ export class ObViewAppStore extends DeesElement {
|
||||
const identity = appstate.loginStatePart.getState().identity;
|
||||
if (!identity) return;
|
||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_InstallAppTemplate
|
||||
>('/typedrequest', 'installAppTemplate');
|
||||
interfaces.requests.IReq_InstallAppStoreApp
|
||||
>('/typedrequest', 'installAppStoreApp');
|
||||
await typedRequest.fire({
|
||||
identity,
|
||||
install: {
|
||||
|
||||
@@ -146,6 +146,7 @@ export class ObViewServices extends DeesElement {
|
||||
accessor appStoreState: appstate.IAppStoreState = {
|
||||
apps: [],
|
||||
upgradeableServices: [],
|
||||
upgradeOperations: [],
|
||||
};
|
||||
|
||||
constructor() {
|
||||
@@ -226,7 +227,8 @@ export class ObViewServices extends DeesElement {
|
||||
await Promise.all([
|
||||
appstate.servicesStatePart.dispatchAction(appstate.fetchServicesAction, null),
|
||||
appstate.servicesStatePart.dispatchAction(appstate.fetchPlatformServicesAction, null),
|
||||
appstate.appStoreStatePart.dispatchAction(appstate.fetchUpgradeableServicesAction, null),
|
||||
appstate.appStoreStatePart.dispatchAction(appstate.fetchUpgradeableAppStoreServicesAction, null),
|
||||
appstate.appStoreStatePart.dispatchAction(appstate.fetchAppStoreUpgradeOperationsAction, null),
|
||||
]);
|
||||
|
||||
// If a platform service was selected from the dashboard, navigate to its detail
|
||||
@@ -471,9 +473,21 @@ export class ObViewServices extends DeesElement {
|
||||
const upgradeInfo = service
|
||||
? this.appStoreState.upgradeableServices.find((u) => u.serviceName === service.name)
|
||||
: null;
|
||||
const upgradeOperation = service
|
||||
? this.appStoreState.upgradeOperations.find((operation) => {
|
||||
return operation.serviceName === service.name && operation.status === 'running';
|
||||
})
|
||||
: null;
|
||||
const latestUpgradeOperation = service
|
||||
? this.appStoreState.upgradeOperations.find((operation) => operation.serviceName === service.name)
|
||||
: null;
|
||||
|
||||
return html`
|
||||
<ob-sectionheading>Service Details</ob-sectionheading>
|
||||
${upgradeOperation ? this.renderUpgradeOperation(upgradeOperation) : ''}
|
||||
${!upgradeOperation && latestUpgradeOperation?.status === 'failed'
|
||||
? this.renderUpgradeOperation(latestUpgradeOperation)
|
||||
: ''}
|
||||
${upgradeInfo ? html`
|
||||
<div style="
|
||||
background: linear-gradient(135deg, rgba(59, 130, 246, 0.1), rgba(139, 92, 246, 0.1));
|
||||
@@ -496,18 +510,14 @@ export class ObViewServices extends DeesElement {
|
||||
<button
|
||||
class="deploy-button"
|
||||
style="padding: 8px 16px; font-size: 13px;"
|
||||
?disabled=${Boolean(upgradeOperation)}
|
||||
@click=${async () => {
|
||||
await appstate.appStoreStatePart.dispatchAction(appstate.upgradeServiceAction, {
|
||||
await appstate.appStoreStatePart.dispatchAction(appstate.upgradeAppStoreServiceAction, {
|
||||
serviceName: upgradeInfo.serviceName,
|
||||
targetVersion: upgradeInfo.latestVersion,
|
||||
});
|
||||
// Refresh service data
|
||||
appstate.servicesStatePart.dispatchAction(appstate.fetchServiceAction, {
|
||||
name: upgradeInfo.serviceName,
|
||||
});
|
||||
appstate.servicesStatePart.dispatchAction(appstate.fetchServicesAction, null);
|
||||
}}
|
||||
>Upgrade</button>
|
||||
>${upgradeOperation ? 'Upgrading...' : 'Upgrade'}</button>
|
||||
</div>
|
||||
` : ''}
|
||||
<sz-service-detail-view
|
||||
@@ -544,6 +554,53 @@ export class ObViewServices extends DeesElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private renderUpgradeOperation(
|
||||
operationArg: interfaces.requests.IAppStoreUpgradeOperation,
|
||||
): TemplateResult {
|
||||
const color = operationArg.status === 'failed' ? '#f87171' : '#60a5fa';
|
||||
return html`
|
||||
<div style="
|
||||
background: var(--ci-shade-1, #09090b);
|
||||
border: 1px solid ${color};
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin-bottom: 16px;
|
||||
">
|
||||
<div style="display: flex; justify-content: space-between; gap: 16px; align-items: flex-start;">
|
||||
<div>
|
||||
<div style="font-size: 14px; font-weight: 600; color: var(--ci-shade-7, #e4e4e7);">
|
||||
Upgrade ${operationArg.fromVersion} → ${operationArg.targetVersion}: ${operationArg.step}
|
||||
</div>
|
||||
<div style="font-size: 12px; color: var(--ci-shade-4, #71717a); margin-top: 4px;">
|
||||
${operationArg.status === 'running' ? 'Operation is running in the background.' : operationArg.error || 'Operation finished.'}
|
||||
</div>
|
||||
</div>
|
||||
<span style="font-size: 12px; color: ${color}; text-transform: uppercase; letter-spacing: 0.04em;">
|
||||
${operationArg.status}
|
||||
</span>
|
||||
</div>
|
||||
<div style="
|
||||
margin-top: 12px;
|
||||
padding: 10px 12px;
|
||||
background: var(--ci-shade-0, #030305);
|
||||
border-radius: 6px;
|
||||
color: var(--ci-shade-5, #a1a1aa);
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
max-height: 130px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
">${operationArg.progressLines.slice(-8).join('\n')}</div>
|
||||
${operationArg.warnings.length > 0 ? html`
|
||||
<div style="margin-top: 10px; color: #fbbf24; font-size: 12px;">
|
||||
${operationArg.warnings.join(' | ')}
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderBackupsView(): TemplateResult {
|
||||
return html`
|
||||
<ob-sectionheading>Backups</ob-sectionheading>
|
||||
|
||||
@@ -12,19 +12,30 @@ type IExecutionEnvironment = import('@design.estate/dees-catalog').IExecutionEnv
|
||||
type IFileEntry = import('@design.estate/dees-catalog').IFileEntry;
|
||||
type IFileWatcher = import('@design.estate/dees-catalog').IFileWatcher;
|
||||
type IProcessHandle = import('@design.estate/dees-catalog').IProcessHandle;
|
||||
type IWorkspaceShellCommand = interfaces.requests.IWorkspaceShellCommand;
|
||||
|
||||
const domtools = plugins.deesElement.domtools;
|
||||
|
||||
interface IWorkspaceProcessState {
|
||||
outputController: ReadableStreamDefaultController<string>;
|
||||
resolveExit: (exitCodeArg: number) => void;
|
||||
}
|
||||
|
||||
export class BackendExecutionEnvironment implements IExecutionEnvironment {
|
||||
readonly type = 'backend' as const;
|
||||
private _ready = false;
|
||||
private identity: interfaces.data.IIdentity;
|
||||
private processRouter = new plugins.domtools.plugins.typedrequest.TypedRouter();
|
||||
private processSocket: InstanceType<typeof plugins.typedsocket.TypedSocket> | null = null;
|
||||
private processSocketPromise: Promise<InstanceType<typeof plugins.typedsocket.TypedSocket>> | null = null;
|
||||
private processStates = new Map<string, IWorkspaceProcessState>();
|
||||
|
||||
constructor(
|
||||
private serviceName: string,
|
||||
identity: interfaces.data.IIdentity,
|
||||
) {
|
||||
this.identity = identity;
|
||||
this.registerProcessSocketHandlers();
|
||||
}
|
||||
|
||||
get ready(): boolean {
|
||||
@@ -44,6 +55,12 @@ export class BackendExecutionEnvironment implements IExecutionEnvironment {
|
||||
}
|
||||
|
||||
async destroy(): Promise<void> {
|
||||
for (const processId of Array.from(this.processStates.keys())) {
|
||||
await this.killProcess(processId).catch(() => {});
|
||||
}
|
||||
await this.processSocket?.stop().catch(() => {});
|
||||
this.processSocket = null;
|
||||
this.processSocketPromise = null;
|
||||
this._ready = false;
|
||||
}
|
||||
|
||||
@@ -103,38 +120,142 @@ export class BackendExecutionEnvironment implements IExecutionEnvironment {
|
||||
}
|
||||
|
||||
async spawn(command: string, args?: string[]): Promise<IProcessHandle> {
|
||||
// For interactive shell: execute the command via the workspace exec API
|
||||
// and return a process handle that bridges stdin/stdout
|
||||
const cmd = args ? [command, ...args] : [command];
|
||||
const fullCommand = cmd.join(' ');
|
||||
const socket = await this.ensureProcessSocket();
|
||||
const processId = crypto.randomUUID();
|
||||
await socket.setTag(`workspaceProcess:${processId}`, true);
|
||||
|
||||
// Use a non-interactive exec for now — full interactive shell would need
|
||||
// TypedSocket bidirectional streaming (to be implemented)
|
||||
const result = await this.fireRequest<interfaces.requests.IReq_WorkspaceExec>(
|
||||
'workspaceExec',
|
||||
{ command: cmd[0], args: cmd.slice(1) },
|
||||
);
|
||||
|
||||
// Create a ReadableStream from the exec output
|
||||
let resolveExit: (exitCodeArg: number) => void = () => {};
|
||||
const exit = new Promise<number>((resolve) => {
|
||||
resolveExit = resolve;
|
||||
});
|
||||
const output = new ReadableStream<string>({
|
||||
start(controller) {
|
||||
if (result.stdout) controller.enqueue(result.stdout);
|
||||
if (result.stderr) controller.enqueue(result.stderr);
|
||||
controller.close();
|
||||
start: (controller) => {
|
||||
this.processStates.set(processId, {
|
||||
outputController: controller,
|
||||
resolveExit,
|
||||
});
|
||||
},
|
||||
cancel: async () => {
|
||||
await this.killProcess(processId).catch(() => {});
|
||||
},
|
||||
});
|
||||
|
||||
// Create a writable stream (no-op for non-interactive)
|
||||
const inputStream = new WritableStream<string>();
|
||||
try {
|
||||
await socket.createTypedRequest<interfaces.requests.IReq_WorkspaceStartProcess>(
|
||||
'workspaceStartProcess',
|
||||
).fire({
|
||||
identity: this.identity,
|
||||
serviceName: this.serviceName,
|
||||
processId,
|
||||
command,
|
||||
args,
|
||||
});
|
||||
} catch (error) {
|
||||
const processState = this.processStates.get(processId);
|
||||
this.processStates.delete(processId);
|
||||
await socket.removeTag(`workspaceProcess:${processId}`).catch(() => {});
|
||||
try {
|
||||
processState?.outputController.error(error);
|
||||
} catch {
|
||||
// The stream may already have been cancelled by the terminal.
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const input = new WritableStream<string>({
|
||||
write: async (chunkArg) => {
|
||||
await socket.createTypedRequest<interfaces.requests.IReq_WorkspaceProcessInput>(
|
||||
'workspaceProcessInput',
|
||||
).fire({
|
||||
identity: this.identity,
|
||||
processId,
|
||||
input: chunkArg,
|
||||
});
|
||||
},
|
||||
abort: async () => {
|
||||
await this.killProcess(processId).catch(() => {});
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
output,
|
||||
input: inputStream,
|
||||
exit: Promise.resolve(result.exitCode),
|
||||
kill: () => {},
|
||||
input,
|
||||
exit,
|
||||
kill: () => {
|
||||
void this.killProcess(processId);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getShellCommand(): Promise<IWorkspaceShellCommand> {
|
||||
const result = await this.fireRequest<interfaces.requests.IReq_WorkspaceGetShellCommand>(
|
||||
'workspaceGetShellCommand',
|
||||
{},
|
||||
);
|
||||
return result.shellCommand;
|
||||
}
|
||||
|
||||
private registerProcessSocketHandlers(): void {
|
||||
this.processRouter.addTypedHandler(
|
||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushWorkspaceProcessOutput>(
|
||||
'pushWorkspaceProcessOutput',
|
||||
async (dataArg: interfaces.requests.IReq_PushWorkspaceProcessOutput['request']) => {
|
||||
this.processStates.get(dataArg.processId)?.outputController.enqueue(dataArg.output);
|
||||
return {};
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.processRouter.addTypedHandler(
|
||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushWorkspaceProcessExit>(
|
||||
'pushWorkspaceProcessExit',
|
||||
async (dataArg: interfaces.requests.IReq_PushWorkspaceProcessExit['request']) => {
|
||||
this.completeProcessState(dataArg.processId, dataArg.exitCode);
|
||||
await this.processSocket?.removeTag(`workspaceProcess:${dataArg.processId}`).catch(() => {});
|
||||
return {};
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private async ensureProcessSocket(): Promise<InstanceType<typeof plugins.typedsocket.TypedSocket>> {
|
||||
if (this.processSocket) return this.processSocket;
|
||||
if (!this.processSocketPromise) {
|
||||
this.processSocketPromise = plugins.typedsocket.TypedSocket.createClient(
|
||||
this.processRouter,
|
||||
plugins.typedsocket.TypedSocket.useWindowLocationOriginUrl(),
|
||||
{ autoReconnect: true },
|
||||
);
|
||||
}
|
||||
this.processSocket = await this.processSocketPromise;
|
||||
return this.processSocket;
|
||||
}
|
||||
|
||||
private completeProcessState(processIdArg: string, exitCodeArg: number): void {
|
||||
const processState = this.processStates.get(processIdArg);
|
||||
if (!processState) return;
|
||||
try {
|
||||
processState.outputController.close();
|
||||
} catch {
|
||||
// The terminal may already have cancelled the stream.
|
||||
}
|
||||
processState.resolveExit(exitCodeArg);
|
||||
this.processStates.delete(processIdArg);
|
||||
}
|
||||
|
||||
private async killProcess(processIdArg: string): Promise<void> {
|
||||
const socket = this.processSocket;
|
||||
if (!socket) return;
|
||||
await socket.createTypedRequest<interfaces.requests.IReq_WorkspaceKillProcess>(
|
||||
'workspaceKillProcess',
|
||||
).fire({
|
||||
identity: this.identity,
|
||||
processId: processIdArg,
|
||||
}).catch(() => {});
|
||||
this.completeProcessState(processIdArg, -1);
|
||||
await socket.removeTag(`workspaceProcess:${processIdArg}`).catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to fire TypedRequests to the workspace API
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user