mirror of
https://github.com/Start9Labs/start-os.git
synced 2026-03-31 12:33:40 +00:00
* docs: update preferred external port design in TODO * docs: add user-controlled public/private and port forward mapping to design * docs: overhaul interfaces page design with view/manage split and per-address controls * docs: move address enable/disable to overflow menu, add SSL indicator, defer UI placement decisions * chore: remove tor from startos core Tor is being moved from a built-in OS feature to a service. This removes the Arti-based Tor client, onion address management, hidden service creation, and all related code from the core backend, frontend, and SDK. - Delete core/src/net/tor/ module (~2060 lines) - Remove OnionAddress, TorSecretKey, TorController from all consumers - Remove HostnameInfo::Onion and HostAddress::Onion variants - Remove onion CRUD RPC endpoints and tor subcommand - Remove tor key handling from account and backup/restore - Remove ~12 tor-related Cargo dependencies (arti-client, torut, etc.) - Remove tor UI components, API methods, mock data, and routes - Remove OnionHostname and tor patterns/regexes from SDK - Add v0_4_0_alpha_20 database migration to strip onion data - Bump version to 0.4.0-alpha.20 * chore: flatten HostnameInfo from enum to struct HostnameInfo only had one variant (Ip) after removing Tor. Flatten it into a plain struct with fields gateway, public, hostname. Remove all kind === 'ip' type guards and narrowing across SDK, frontend, and container runtime. Update DB migration to strip the kind field. * chore: format RPCSpec.md markdown table * docs: update TODO.md with DerivedAddressInfo design, remove completed tor task * feat: implement preferred port allocation and per-address enable/disable - Add AvailablePorts::try_alloc() with SSL tracking (BTreeMap<u16, bool>) - Add DerivedAddressInfo on BindInfo with private_disabled/public_enabled/possible sets - Add Bindings wrapper with Map impl for patchdb indexed access - Flatten HostAddress from single-variant enum to struct - Replace set-gateway-enabled RPC with set-address-enabled - Remove hostname_info from Host; computed addresses now in BindInfo.addresses.possible - Compute possible addresses inline in NetServiceData::update() - Update DB migration, SDK types, frontend, and container-runtime * feat: replace InterfaceFilter with ForwardRequirements, add WildcardListener, complete alpha.20 bump - Replace DynInterfaceFilter with ForwardRequirements for per-IP forward precision with source-subnet iptables filtering for private forwards - Add WildcardListener (binds [::]:port) to replace the per-gateway NetworkInterfaceListener/SelfContainedNetworkInterfaceListener/ UpgradableListener infrastructure - Update forward-port script with src_subnet and excluded_src env vars - Remove unused filter types and listener infrastructure from gateway.rs - Add availablePorts migration (IdPool -> BTreeMap<u16, bool>) to alpha.20 - Complete version bump to 0.4.0-alpha.20 in SDK and web * outbound gateway support (#3120) * Multiple (#3111) * fix alerts i18n, fix status display, better, remove usb media, hide shutdown for install complete * trigger chnage detection for localize pipe and round out implementing localize pipe for consistency even though not needed * Fix PackageInfoShort to handle LocaleString on releaseNotes (#3112) * Fix PackageInfoShort to handle LocaleString on releaseNotes * fix: filter by target_version in get_matching_models and pass otherVersions from install * chore: add exver documentation for ai agents * frontend plus some be types --------- Co-authored-by: Aiden McClelland <3732071+dr-bonez@users.noreply.github.com> * feat: replace SourceFilter with IpNet, add policy routing, remove MASQUERADE * build ts types and fix i18n * fix license display in marketplace * wip refactor * chore: update ts bindings for preferred port design * feat: refactor NetService to watch DB and reconcile network state - NetService sync task now uses PatchDB DbWatch instead of being called directly after DB mutations - Read gateways from DB instead of network interface context when updating host addresses - gateway sync updates all host addresses in the DB - Add Watch<u64> channel for callers to wait on sync completion - Fix ts-rs codegen bug with #[ts(skip)] on flattened Plugin field - Update SDK getServiceInterface.ts for new HostnameInfo shape - Remove unnecessary HTTPS redirect in static_server.rs - Fix tunnel/api.rs to filter for WAN IPv4 address * re-arrange (#3123) * new service interfacee page * feat: add mdns hostname metadata variant and fix vhost routing - Add HostnameMetadata::Mdns variant to distinguish mDNS from private domains - Mark mDNS addresses as private (public: false) since mDNS is local-only - Fall back to null SNI entry when hostname not found in vhost mapping - Simplify public detection in ProxyTarget filter - Pass hostname to update_addresses for mDNS domain name generation * looking good * feat: add port_forwards field to Host for tracking gateway forwarding rules * update bindings for API types, add ARCHITECTURE (#3124) * update binding for API types, add ARCHITECTURE * translations * fix: add CONNMARK restore-mark to mangle OUTPUT chain The CONNMARK --restore-mark rule was only in PREROUTING, which handles forwarded packets. Locally-bound listeners (e.g. vhost) generate replies through the OUTPUT chain, where the fwmark was never restored. This caused response packets to route via the default table instead of back through the originating interface. * chore: reserialize db on equal version, update bindings and docs - Run de/ser roundtrip in pre_init even when db version matches, ensuring all #[serde(default)] fields are populated before any typed access - Add patchdb.md documentation for TypedDbWatch patterns - Update TS bindings for CheckPortParams, CheckPortRes, ifconfigUrl - Update CLAUDE.md docs with patchdb and component-level references * fix: include public gateways for IP-based addresses in vhost targets The server hostname vhost construction only collected private IPs, always setting public to empty. Public IP addresses (Ipv4/Ipv6 metadata with public=true) were never added to the vhost target's public gateway set, causing the vhost filter to reject public traffic for IP-based addresses. * fix: add TLS handshake timeout and fix accept loop deadlock Two issues in TlsListener::poll_accept: 1. No timeout on TLS handshakes: LazyConfigAcceptor waits indefinitely for ClientHello. Attackers that complete TCP handshake but never send TLS data create zombie futures in `in_progress` that never complete. Fix: wrap the entire handshake in tokio::time::timeout(15s). 2. Missing waker on new-connection pending path: when a TCP connection is accepted and the TLS handshake is pending, poll_accept returned Pending without calling wake_by_ref(). Since the TcpListener returned Ready (not Pending), no waker was registered for it. With edge- triggered epoll and no other wakeup source, the task sleeps forever and remaining connections in the kernel accept queue are never drained. Fix: add cx.waker().wake_by_ref() so the task immediately re-polls and continues draining the accept queue. * fix: switch BackgroundJobRunner from Vec to FuturesUnordered BackgroundJobRunner stored active jobs in a Vec<BoxFuture> and polled ALL of them on every wakeup — O(n) per poll. Since this runs in the same tokio::select! as the WebServer accept loop, polling overhead from active connections directly delayed acceptance of new connections. FuturesUnordered only polls woken futures — O(woken) instead of O(n). * chore: update bindings and use typed params for outbound gateway API * feat: per-service and default outbound gateway routing Add set-outbound-gateway RPC for packages and set-default-outbound RPC for the server, with policy routing enforcement via ip rules. Fix connmark restore to skip packets with existing fwmarks, add bridge subnet routes to per-interface tables, and fix squashfs path in update-image-local.sh. * refactor: manifest wraps PackageMetadata, move dependency_metadata to PackageVersionInfo Manifest now embeds PackageMetadata via #[serde(flatten)] instead of duplicating ~14 fields. icon and dependency_metadata moved from PackageMetadata to PackageVersionInfo since they are registry-enrichment data loaded from the S9PK archive. merge_with now returns errors on metadata/icon/dependency_metadata mismatches instead of silently ignoring them. * fix: replace .status() with .invoke() for iptables/ip commands Using .status() leaks stderr directly to system logs, causing noisy iptables error messages. Switch all networking CLI invocations to use .invoke() which captures stderr properly. For check-then-act patterns (iptables -C), use .invoke().await.is_err() instead of .status().await.map_or(false, |s| s.success()). * feat: add check-dns gateway endpoint and fix per-interface routing tables Add a `check-dns` RPC endpoint that verifies whether a gateway's DNS is properly configured for private domain resolution. Uses a three-tier check: direct match (DNS == server IP), TXT challenge probe (DNS on LAN), or failure (DNS off-subnet). Fix per-interface routing tables to clone all non-default routes from the main table instead of only the interface's own subnets. This preserves LAN reachability when the priority-75 catch-all overrides default routing. Filter out status-only flags (linkdown, dead) that are invalid for `ip route add`. * refactor: rename manifest metadata fields and improve error display Rename wrapperRepo→packageRepo, marketingSite→marketingUrl, docsUrl→docsUrls (array), remove supportSite. Add display_src/display_dbg helpers to Error. Fix DepInfo description type to LocaleString. Update web UI, SDK bindings, tests, and fixtures to match. Clean up cli_attach error handling and remove dead commented code. * chore: bump sdk version to 0.4.0-beta.49 * chore: add createTask decoupling TODO * chore: add TODO to clear service error state on install/update * round out dns check, dns server check, port forward check, and gateway port forwards * chore: add TODOs for URL plugins, NAT hairpinning, and start-tunnel OTA updates * version instead of os query param * interface row clickable again, bu now with a chevron! * feat: implement URL plugins with table/row actions and prefill support - Add URL plugin effects (register, export_url, clear_urls) in core - Add PluginHostnameInfo, HostnameMetadata::Plugin, and plugin registration types - Implement plugin URL table in web UI with tableAction button and rowAction overflow menus - Thread urlPluginMetadata (packageId, hostId, interfaceId, internalPort) as prefill to actions - Add prefill support to PackageActionData so metadata passes through form dialogs - Add i18n translations for plugin error messages - Clean up plugin URLs on package uninstall * feat: split row_actions into remove_action and overflow_actions for URL plugins * touch up URL plugins table * show table even when no addresses * feat: NAT hairpinning, DNS static servers, clear service error on install - Add POSTROUTING MASQUERADE rules for container and host hairpin NAT - Allow bridge subnet containers to reach private forwards via LAN IPs - Pass bridge_subnet env var from forward.rs to forward-port script - Use DB-configured static DNS servers in resolver with DB watcher - Fall back to resolv.conf servers when no static servers configured - Clear service error state when install/update completes successfully - Remove completed TODO items * feat: builder-style InputSpec API, prefill plumbing, and port forward fix - Add addKey() and add() builder methods to InputSpec with InputSpecTools - Move OuterType to last generic param on Value, List, and all dynamic methods - Plumb prefill through getActionInput end-to-end (core → container-runtime → SDK) - Filter port_forwards to enabled addresses only - Bump SDK to 0.4.0-beta.50 * fix: propagate host locale into LXC containers and write locale.conf * chore: remove completed URL plugins TODO * feat: OTA updates for start-tunnel via apt repository (untested) - Add apt repo publish script (build/apt/publish-deb.sh) for S3-hosted repo - Add apt source config and GPG key placeholder (apt/) - Add tunnel.update.check and tunnel.update.apply RPC endpoints - Wire up update API in tunnel frontend (api service + mock) - Uses systemd-run --scope to survive service restart during update * fix: publish script dpkg-name, s3cfg fallback, and --reinstall for apply * chore: replace OTA updates TODO with UI TODO for MattDHill * feat: add getOutboundGateway effect and simplify VersionGraph init/uninit Add getOutboundGateway effect across core, container-runtime, and SDK to let services query their effective outbound gateway with callback support. Remove preInstall/uninstall hooks from VersionGraph as they are no longer needed. * frontend start-tunnel updates * chore: remove completed TODO * feat: tor hidden service key migration * chore: migrate from ts-matches to zod across all TypeScript packages * feat(core): allow setting server hostname * send prefill for tasks and hide operations to hidden fields * fix(core): preserve plugin URLs across binding updates BindInfo::update was replacing addresses with a new DerivedAddressInfo that cleared the available set, wiping plugin-exported URLs whenever bind() was called. Also simplify update_addresses plugin preservation to use retain in place rather than collecting into a separate set. * minor cleanup from patch-db audit * clean up prefill flow * frontend support for setting and changing hostname * feat(core): refactor hostname to ServerHostnameInfo with name/hostname pair - Rename Hostname to ServerHostnameInfo, add name + hostname fields - Add set_hostname_rpc for changing hostname at runtime - Migrate alpha_20: generate serverInfo.name from hostname, delete ui.name - Extract gateway.rs helpers to fix rustfmt nesting depth issue - Add i18n key for hostname validation error - Update SDK bindings * add comments to everything potentially consumer facing (#3127) * add comments to everything potentially consumer facing * rework smtp --------- Co-authored-by: Aiden McClelland <3732071+dr-bonez@users.noreply.github.com> * implement server name * setup changes * clean up copy around addresses table * feat: add zod-deep-partial, partialValidator on InputSpec, and z.deepPartial re-export * fix: header color in zoom (#3128) * fix: merge version ranges when adding existing package signer (#3125) * fix: merge version ranges when adding existing package signer Previously, add_package_signer unconditionally inserted the new version range, overwriting any existing authorization for that signer. Now it OR-merges the new range with the existing one, so running signer add multiple times accumulates permissions rather than replacing them. * add --merge flag to registry package signer add Default behavior remains overwrite. When --merge is passed, the new version range is OR-merged with the existing one, allowing admins to accumulate permissions incrementally. * add missing attribute to TS type * make merge optional * upsert instead of insert * VersionRange::None on upsert * fix: header color in zoom --------- Co-authored-by: Dominion5254 <musashidisciple@proton.me> * update snake and add about this server to system general * chore: bump sdk to beta.53, wrap z.deepPartial with passthrough * reset instead of reset defaults * action failure show dialog * chore: bump sdk to beta.54, add device-info RPC, improve SDK abort handling and InputSpec filtering - Bump SDK version to 0.4.0-beta.54 - Add `server.device-info` RPC endpoint and `s9pk select` CLI command - Extract `HardwareRequirements::is_compatible()` method, reuse in registry filtering - Add `AbortedError` class with `muteUnhandled` flag, replace generic abort errors - Handle unhandled promise rejections in container-runtime with mute support - Improve `InputSpec.filter()` with `keepByDefault` param and boolean filter values - Accept readonly tuples in `CommandType` and `splitCommand` - Remove `sync_host` calls from host API handlers (binding/address changes) - Filter mDNS hostnames by secure gateway availability - Derive mDNS enabled state from LAN IPs in web UI - Add "Open UI" action to address table, disable mDNS toggle - Hide debug details in service error component - Update rpc-toolkit docs for no-params handlers * fix: add --no-nvram to efi grub-install to preserve built-in boot order * update snake * diable actions when in error state * chore: split out nvidia variant * misc bugfixes * create manage-release script (untested) * fix: preserve z namespace types for sdk consumers * sdk version bump * new checkPort types * multiple bugs and better port forward ux * fix link * chore: todos and formatting * fix build --------- Co-authored-by: Matt Hill <MattDHill@users.noreply.github.com> Co-authored-by: Matt Hill <mattnine@protonmail.com> Co-authored-by: Alex Inkin <alexander@inkin.ru> Co-authored-by: Dominion5254 <musashidisciple@proton.me>
991 lines
37 KiB
TypeScript
991 lines
37 KiB
TypeScript
import { Value } from '../../base/lib/actions/input/builder/value'
|
|
import { InputSpec } from '../../base/lib/actions/input/builder/inputSpec'
|
|
import { Variants } from '../../base/lib/actions/input/builder/variants'
|
|
import {
|
|
Action,
|
|
ActionInfo,
|
|
Actions,
|
|
} from '../../base/lib/actions/setupActions'
|
|
import { ServiceInterfaceType, Effects } from '../../base/lib/types'
|
|
import * as patterns from '../../base/lib/util/patterns'
|
|
import { Backups } from './backup/Backups'
|
|
import {
|
|
smtpInputSpec,
|
|
systemSmtpSpec,
|
|
customSmtp,
|
|
smtpProviderVariants,
|
|
} from '../../base/lib/actions/input/inputSpecConstants'
|
|
import { Daemon, Daemons } from './mainFn/Daemons'
|
|
import { checkPortListening } from './health/checkFns/checkPortListening'
|
|
import { checkWebUrl, runHealthScript } from './health/checkFns'
|
|
import { List } from '../../base/lib/actions/input/builder/list'
|
|
import { SetupBackupsParams, setupBackups } from './backup/setupBackups'
|
|
import { setupMain } from './mainFn'
|
|
import { defaultTrigger } from './trigger/defaultTrigger'
|
|
import { changeOnFirstSuccess, cooldownTrigger } from './trigger'
|
|
import { setupServiceInterfaces } from '../../base/lib/interfaces/setupInterfaces'
|
|
import { setupExportedUrls } from '../../base/lib/interfaces/setupExportedUrls'
|
|
import { successFailure } from './trigger/successFailure'
|
|
import { MultiHost, Scheme } from '../../base/lib/interfaces/Host'
|
|
import { ServiceInterfaceBuilder } from '../../base/lib/interfaces/ServiceInterfaceBuilder'
|
|
import { GetOutboundGateway, GetSystemSmtp } from './util'
|
|
import { nullIfEmpty } from './util'
|
|
import { getServiceInterface, getServiceInterfaces } from './util'
|
|
import {
|
|
CommandOptions,
|
|
ExitError,
|
|
SubContainer,
|
|
SubContainerOwned,
|
|
} from './util/SubContainer'
|
|
import { splitCommand } from './util'
|
|
import { Mounts } from './mainFn/Mounts'
|
|
import { setupDependencies } from '../../base/lib/dependencies/setupDependencies'
|
|
import * as T from '../../base/lib/types'
|
|
import { testTypeVersion } from '../../base/lib/exver'
|
|
import {
|
|
CheckDependencies,
|
|
checkDependencies,
|
|
} from '../../base/lib/dependencies/dependencies'
|
|
import { GetSslCertificate, getServiceManifest } from './util'
|
|
import { getDataVersion, setDataVersion } from './version'
|
|
import { MaybeFn } from '../../base/lib/actions/setupActions'
|
|
import { GetInput } from '../../base/lib/actions/setupActions'
|
|
import { Run } from '../../base/lib/actions/setupActions'
|
|
import * as actions from '../../base/lib/actions'
|
|
import * as fs from 'node:fs/promises'
|
|
import {
|
|
setupInit,
|
|
setupUninit,
|
|
setupOnInit,
|
|
setupOnUninit,
|
|
} from '../../base/lib/inits'
|
|
import { DropGenerator } from '../../base/lib/util/Drop'
|
|
import {
|
|
getOwnServiceInterface,
|
|
ServiceInterfaceFilled,
|
|
} from '../../base/lib/util/getServiceInterface'
|
|
import { getOwnServiceInterfaces } from '../../base/lib/util/getServiceInterfaces'
|
|
import { Volumes, createVolumes } from './util/Volume'
|
|
|
|
/** The minimum StartOS version required by this SDK release */
|
|
export const OSVersion = testTypeVersion('0.4.0-alpha.20')
|
|
|
|
// prettier-ignore
|
|
type AnyNeverCond<T extends any[], Then, Else> =
|
|
T extends [] ? Else :
|
|
T extends [never, ...Array<any>] ? Then :
|
|
T extends [any, ...infer U] ? AnyNeverCond<U,Then, Else> :
|
|
never
|
|
|
|
/**
|
|
* The top-level SDK facade for building StartOS service packages.
|
|
*
|
|
* Use `StartSdk.of()` to create an uninitialized instance, then call `.withManifest()`
|
|
* to bind it to a manifest, and finally `.build()` to obtain the full toolkit of helpers
|
|
* for actions, daemons, backups, interfaces, health checks, and more.
|
|
*
|
|
* @typeParam Manifest - The service manifest type; starts as `never` until `.withManifest()` is called.
|
|
*/
|
|
export class StartSdk<Manifest extends T.SDKManifest> {
|
|
private constructor(readonly manifest: Manifest) {}
|
|
/**
|
|
* Create an uninitialized StartSdk instance. Call `.withManifest()` next.
|
|
* @returns A new StartSdk with no manifest bound.
|
|
*/
|
|
static of() {
|
|
return new StartSdk<never>(null as never)
|
|
}
|
|
/**
|
|
* Bind a manifest to the SDK, producing a typed SDK instance.
|
|
* @param manifest - The service manifest definition
|
|
* @returns A new StartSdk instance parameterized by the given manifest type
|
|
*/
|
|
withManifest<Manifest extends T.SDKManifest = never>(manifest: Manifest) {
|
|
return new StartSdk<Manifest>(manifest)
|
|
}
|
|
|
|
private ifPluginEnabled<P extends T.PluginId, T>(
|
|
plugin: P,
|
|
value: T,
|
|
): Manifest extends { plugins: P[] } ? T : null {
|
|
if (this.manifest.plugins?.includes(plugin)) return value as any
|
|
return null as any
|
|
}
|
|
|
|
/**
|
|
* Finalize the SDK and return the full set of helpers for building a StartOS service.
|
|
*
|
|
* This method is only callable after `.withManifest()` has been called (enforced at the type level).
|
|
*
|
|
* @param isReady - Type-level gate; resolves to `true` only when a manifest is bound.
|
|
* @returns An object containing all SDK utilities: actions, daemons, backups, interfaces, health checks, volumes, triggers, and more.
|
|
*/
|
|
build(isReady: AnyNeverCond<[Manifest], 'Build not ready', true>) {
|
|
type NestedEffects = 'subcontainer' | 'store' | 'action' | 'plugin'
|
|
type InterfaceEffects =
|
|
| 'getServiceInterface'
|
|
| 'listServiceInterfaces'
|
|
| 'exportServiceInterface'
|
|
| 'clearServiceInterfaces'
|
|
| 'bind'
|
|
| 'getHostInfo'
|
|
type MainUsedEffects = 'setMainStatus'
|
|
type CallbackEffects =
|
|
| 'child'
|
|
| 'constRetry'
|
|
| 'isInContext'
|
|
| 'onLeaveContext'
|
|
| 'clearCallbacks'
|
|
type AlreadyExposed =
|
|
| 'getSslCertificate'
|
|
| 'getSystemSmtp'
|
|
| 'getOutboundGateway'
|
|
| 'getContainerIp'
|
|
| 'getDataVersion'
|
|
| 'setDataVersion'
|
|
| 'getServiceManifest'
|
|
|
|
// prettier-ignore
|
|
type StartSdkEffectWrapper = {
|
|
[K in keyof Omit<Effects, "eventId" | NestedEffects | InterfaceEffects | MainUsedEffects | CallbackEffects | AlreadyExposed>]: (effects: Effects, ...args: Parameters<Effects[K]>) => ReturnType<Effects[K]>
|
|
}
|
|
const startSdkEffectWrapper: StartSdkEffectWrapper = {
|
|
restart: (effects, ...args) => effects.restart(...args),
|
|
setDependencies: (effects, ...args) => effects.setDependencies(...args),
|
|
checkDependencies: (effects, ...args) =>
|
|
effects.checkDependencies(...args),
|
|
mount: (effects, ...args) => effects.mount(...args),
|
|
getInstalledPackages: (effects, ...args) =>
|
|
effects.getInstalledPackages(...args),
|
|
getServicePortForward: (effects, ...args) =>
|
|
effects.getServicePortForward(...args),
|
|
clearBindings: (effects, ...args) => effects.clearBindings(...args),
|
|
getOsIp: (effects, ...args) => effects.getOsIp(...args),
|
|
getSslKey: (effects, ...args) => effects.getSslKey(...args),
|
|
shutdown: (effects, ...args) => effects.shutdown(...args),
|
|
getDependencies: (effects, ...args) => effects.getDependencies(...args),
|
|
getStatus: (effects, ...args) => effects.getStatus(...args),
|
|
setHealth: (effects, ...args) => effects.setHealth(...args),
|
|
}
|
|
|
|
return {
|
|
/** The bound service manifest */
|
|
manifest: this.manifest,
|
|
/** Volume path helpers derived from the manifest volume definitions */
|
|
volumes: createVolumes(this.manifest),
|
|
...startSdkEffectWrapper,
|
|
/** Persist the current data version to the StartOS effect system */
|
|
setDataVersion,
|
|
/** Retrieve the current data version from the StartOS effect system */
|
|
getDataVersion,
|
|
action: {
|
|
/** Execute an action by its ID, optionally providing input */
|
|
run: actions.runAction,
|
|
/** Create a task notification for a specific package's action */
|
|
createTask: <T extends ActionInfo<T.ActionId, any>>(
|
|
effects: T.Effects,
|
|
packageId: T.PackageId,
|
|
action: T,
|
|
severity: T.TaskSeverity,
|
|
options?: actions.TaskOptions<T>,
|
|
) =>
|
|
actions.createTask({
|
|
effects,
|
|
packageId,
|
|
action,
|
|
severity,
|
|
options: options,
|
|
}),
|
|
/** Create a task notification for this service's own action (uses manifest.id automatically) */
|
|
createOwnTask: <T extends ActionInfo<T.ActionId, any>>(
|
|
effects: T.Effects,
|
|
action: T,
|
|
severity: T.TaskSeverity,
|
|
options?: actions.TaskOptions<T>,
|
|
) =>
|
|
actions.createTask({
|
|
effects,
|
|
packageId: this.manifest.id,
|
|
action,
|
|
severity,
|
|
options: options,
|
|
}),
|
|
/**
|
|
* Clear one or more task notifications by their replay IDs
|
|
* @param effects - The effects context
|
|
* @param replayIds - One or more replay IDs of the tasks to clear
|
|
*/
|
|
clearTask: (effects: T.Effects, ...replayIds: string[]) =>
|
|
effects.action.clearTasks({ only: replayIds }),
|
|
},
|
|
/**
|
|
* Check whether the specified (or all) dependencies are satisfied.
|
|
* @param effects - The effects context
|
|
* @param packageIds - Optional subset of dependency IDs to check; defaults to all
|
|
* @returns An object describing which dependencies are satisfied and which are not
|
|
*/
|
|
checkDependencies: checkDependencies as <
|
|
DependencyId extends keyof Manifest['dependencies'] &
|
|
T.PackageId = keyof Manifest['dependencies'] & T.PackageId,
|
|
>(
|
|
effects: Effects,
|
|
packageIds?: DependencyId[],
|
|
) => Promise<CheckDependencies<DependencyId>>,
|
|
serviceInterface: {
|
|
/** Retrieve a single service interface belonging to this package by its ID */
|
|
getOwn: getOwnServiceInterface,
|
|
/** Retrieve a single service interface from any package */
|
|
get: getServiceInterface,
|
|
/** Retrieve all service interfaces belonging to this package */
|
|
getAllOwn: getOwnServiceInterfaces,
|
|
/** Retrieve all service interfaces, optionally filtering by package */
|
|
getAll: getServiceInterfaces,
|
|
},
|
|
/**
|
|
* Get the container IP address with reactive subscription support.
|
|
*
|
|
* Returns an object with multiple read strategies: `const()` for a value
|
|
* that retries on change, `once()` for a single read, `watch()` for an async
|
|
* generator, `onChange()` for a callback, and `waitFor()` to block until a predicate is met.
|
|
*
|
|
* @param effects - The effects context
|
|
* @param options - Optional filtering options (e.g. `containerId`)
|
|
*/
|
|
getContainerIp: (
|
|
effects: T.Effects,
|
|
options: Omit<
|
|
Parameters<T.Effects['getContainerIp']>[0],
|
|
'callback'
|
|
> = {},
|
|
) => {
|
|
async function* watch(abort?: AbortSignal) {
|
|
const resolveCell = { resolve: () => {} }
|
|
effects.onLeaveContext(() => {
|
|
resolveCell.resolve()
|
|
})
|
|
abort?.addEventListener('abort', () => resolveCell.resolve())
|
|
while (effects.isInContext && !abort?.aborted) {
|
|
let callback: () => void = () => {}
|
|
const waitForNext = new Promise<void>((resolve) => {
|
|
callback = resolve
|
|
resolveCell.resolve = resolve
|
|
})
|
|
yield await effects.getContainerIp({ ...options, callback })
|
|
await waitForNext
|
|
}
|
|
}
|
|
return {
|
|
const: () =>
|
|
effects.getContainerIp({
|
|
...options,
|
|
callback:
|
|
effects.constRetry &&
|
|
(() => effects.constRetry && effects.constRetry()),
|
|
}),
|
|
once: () => effects.getContainerIp(options),
|
|
watch: (abort?: AbortSignal) => {
|
|
const ctrl = new AbortController()
|
|
abort?.addEventListener('abort', () => ctrl.abort())
|
|
return DropGenerator.of(watch(ctrl.signal), () => ctrl.abort())
|
|
},
|
|
onChange: (
|
|
callback: (
|
|
value: string | null,
|
|
error?: Error,
|
|
) => { cancel: boolean } | Promise<{ cancel: boolean }>,
|
|
) => {
|
|
;(async () => {
|
|
const ctrl = new AbortController()
|
|
for await (const value of watch(ctrl.signal)) {
|
|
try {
|
|
const res = await callback(value)
|
|
if (res.cancel) {
|
|
ctrl.abort()
|
|
break
|
|
}
|
|
} catch (e) {
|
|
console.error(
|
|
'callback function threw an error @ getContainerIp.onChange',
|
|
e,
|
|
)
|
|
}
|
|
}
|
|
})()
|
|
.catch((e) => callback(null, e))
|
|
.catch((e) =>
|
|
console.error(
|
|
'callback function threw an error @ getContainerIp.onChange',
|
|
e,
|
|
),
|
|
)
|
|
},
|
|
waitFor: async (pred: (value: string | null) => boolean) => {
|
|
const resolveCell = { resolve: () => {} }
|
|
effects.onLeaveContext(() => {
|
|
resolveCell.resolve()
|
|
})
|
|
while (effects.isInContext) {
|
|
let callback: () => void = () => {}
|
|
const waitForNext = new Promise<void>((resolve) => {
|
|
callback = resolve
|
|
resolveCell.resolve = resolve
|
|
})
|
|
const res = await effects.getContainerIp({ ...options, callback })
|
|
if (pred(res)) {
|
|
resolveCell.resolve()
|
|
return res
|
|
}
|
|
await waitForNext
|
|
}
|
|
return null
|
|
},
|
|
}
|
|
},
|
|
|
|
MultiHost: {
|
|
/**
|
|
* Create a new MultiHost instance for binding ports and exporting interfaces.
|
|
* @param effects - The effects context
|
|
* @param id - A unique identifier for this multi-host group
|
|
*/
|
|
of: (effects: Effects, id: string) => new MultiHost({ id, effects }),
|
|
},
|
|
/**
|
|
* Return `null` if the given string is empty, otherwise return the string unchanged.
|
|
* Useful for converting empty user input into explicit null values.
|
|
*/
|
|
nullIfEmpty,
|
|
/**
|
|
* Indicate that a daemon should use the container image's configured entrypoint.
|
|
* @param overrideCmd - Optional command arguments to append after the entrypoint
|
|
*/
|
|
useEntrypoint: (overrideCmd?: string[]) =>
|
|
new T.UseEntrypoint(overrideCmd),
|
|
/**
|
|
* @description Use this class to create an Action. By convention, each Action should receive its own file.
|
|
*
|
|
*/
|
|
Action: {
|
|
/**
|
|
* @description Use this function to create an action that accepts form input
|
|
* @param id - a unique ID for this action
|
|
* @param metadata - information describing the action and its availability
|
|
* @param inputSpec - define the form input using the InputSpec and Value classes
|
|
* @param prefillFn - optionally fetch data from the file system to pre-fill the input form. Must returns a deep partial of the input spec
|
|
* @param executionFn - execute the action. Optionally return data for the user to view. Must be in the structure of an ActionResult, version "1"
|
|
* @example
|
|
* In this example, we create an action for a user to provide their name.
|
|
* We prefill the input form with their existing name from the service's yaml file.
|
|
* The new name is saved to the yaml file, and we return nothing to the user, which
|
|
* means they will receive a generic success message.
|
|
*
|
|
* ```
|
|
import { sdk } from '../sdk'
|
|
import { yamlFile } from '../file-models/config.yml'
|
|
|
|
const { InputSpec, Value } = sdk
|
|
|
|
export const inputSpec = InputSpec.of({
|
|
name: Value.text({
|
|
name: 'Name',
|
|
description:
|
|
'When you launch the Hello World UI, it will display "Hello [Name]"',
|
|
required: true,
|
|
default: 'World',
|
|
}),
|
|
})
|
|
|
|
export const setName = sdk.Action.withInput(
|
|
// id
|
|
'set-name',
|
|
|
|
// metadata
|
|
async ({ effects }) => ({
|
|
name: 'Set Name',
|
|
description: 'Set your name so Hello World can say hello to you',
|
|
warning: null,
|
|
allowedStatuses: 'any',
|
|
group: null,
|
|
visibility: 'enabled',
|
|
}),
|
|
|
|
// form input specification
|
|
inputSpec,
|
|
|
|
// optionally pre-fill the input form
|
|
async ({ effects }) => {
|
|
const name = await yamlFile.read.const(effects)?.name
|
|
return { name }
|
|
},
|
|
|
|
// the execution function
|
|
async ({ effects, input }) => yamlFile.merge(input)
|
|
)
|
|
* ```
|
|
*/
|
|
withInput: Action.withInput,
|
|
/**
|
|
* @description Use this function to create an action that does not accept form input
|
|
* @param id - a unique ID for this action
|
|
* @param metadata - information describing the action and its availability
|
|
* @param executionFn - execute the action. Optionally return data for the user to view. Must be in the structure of an ActionResult, version "1"
|
|
* @example
|
|
* In this example, we create an action that returns a secret phrase for the user to see.
|
|
*
|
|
* ```
|
|
import { store } from '../file-models/store.json'
|
|
import { sdk } from '../sdk'
|
|
|
|
export const showSecretPhrase = sdk.Action.withoutInput(
|
|
// id
|
|
'show-secret-phrase',
|
|
|
|
// metadata
|
|
async ({ effects }) => ({
|
|
name: 'Show Secret Phrase',
|
|
description: 'Reveal the secret phrase for Hello World',
|
|
warning: null,
|
|
allowedStatuses: 'any',
|
|
group: null,
|
|
visibility: 'enabled',
|
|
}),
|
|
|
|
// the execution function
|
|
async ({ effects }) => ({
|
|
version: '1',
|
|
title: 'Secret Phrase',
|
|
message:
|
|
'Below is your secret phrase. Use it to gain access to extraordinary places',
|
|
result: {
|
|
type: 'single',
|
|
value: (await store.read.once())?.secretPhrase,
|
|
copyable: true,
|
|
qr: true,
|
|
masked: true,
|
|
},
|
|
}),
|
|
)
|
|
* ```
|
|
*/
|
|
withoutInput: <Id extends T.ActionId>(
|
|
id: Id,
|
|
metadata: MaybeFn<Omit<T.ActionMetadata, 'hasInput'>>,
|
|
run: Run<{}>,
|
|
) => Action.withoutInput(id, metadata, run),
|
|
},
|
|
inputSpecConstants: {
|
|
smtpInputSpec,
|
|
systemSmtpSpec,
|
|
customSmtp,
|
|
smtpProviderVariants,
|
|
},
|
|
/**
|
|
* @description Use this function to create a service interface.
|
|
* @param effects
|
|
* @param options
|
|
* @example
|
|
* In this example, we create a standard web UI
|
|
*
|
|
* ```
|
|
const ui = sdk.createInterface(effects, {
|
|
name: 'Web UI',
|
|
id: 'ui',
|
|
description: 'The primary web app for this service.',
|
|
type: 'ui',
|
|
masked: false,
|
|
schemeOverride: null,
|
|
username: null,
|
|
path: '',
|
|
query: {},
|
|
})
|
|
* ```
|
|
*/
|
|
createInterface: (
|
|
effects: Effects,
|
|
options: {
|
|
/** The human readable name of this service interface. */
|
|
name: string
|
|
/** A unique ID for this service interface. */
|
|
id: string
|
|
/** The human readable description. */
|
|
description: string
|
|
/** Affects how the interface appears to the user. One of: 'ui', 'api', 'p2p'. If 'ui', the user will see an option to open the UI in a new tab */
|
|
type: ServiceInterfaceType
|
|
/** (optional) prepends the provided username to all URLs. */
|
|
username: null | string
|
|
/** (optional) appends the provided path to all URLs. */
|
|
path: string
|
|
/** (optional) appends the provided query params to all URLs. */
|
|
query: Record<string, string>
|
|
/** (optional) overrides the protocol prefix provided by the bind function.
|
|
*
|
|
* @example `{ ssl: 'ftps', noSsl: 'ftp' }`
|
|
*/
|
|
schemeOverride: { ssl: Scheme; noSsl: Scheme } | null
|
|
/** mask the url (recommended if it contains credentials such as an API key or password) */
|
|
masked: boolean
|
|
},
|
|
) => new ServiceInterfaceBuilder({ ...options, effects }),
|
|
/**
|
|
* Get the system SMTP configuration with reactive subscription support.
|
|
* @param effects - The effects context
|
|
*/
|
|
getSystemSmtp: <E extends Effects>(effects: E) =>
|
|
new GetSystemSmtp(effects),
|
|
/**
|
|
* Get the outbound network gateway address with reactive subscription support.
|
|
* @param effects - The effects context
|
|
*/
|
|
getOutboundGateway: <E extends Effects>(effects: E) =>
|
|
new GetOutboundGateway(effects),
|
|
/**
|
|
* Get an SSL certificate for the given hostnames with reactive subscription support.
|
|
* @param effects - The effects context
|
|
* @param hostnames - The hostnames to obtain a certificate for
|
|
* @param algorithm - Optional algorithm preference (e.g. Ed25519)
|
|
*/
|
|
getSslCertificate: <E extends Effects>(
|
|
effects: E,
|
|
hostnames: string[],
|
|
algorithm?: T.Algorithm,
|
|
) => new GetSslCertificate(effects, hostnames, algorithm),
|
|
/** Retrieve the manifest of any installed service package by its ID */
|
|
getServiceManifest,
|
|
healthCheck: {
|
|
checkPortListening,
|
|
checkWebUrl,
|
|
runHealthScript,
|
|
},
|
|
/** Common utility patterns (e.g. hostname regex, port validators) */
|
|
patterns,
|
|
/**
|
|
* @description Use this function to list every Action offered by the service. Actions will be displayed in the provided order.
|
|
*
|
|
* By convention, each Action should receive its own file in the "actions" directory.
|
|
* @example
|
|
*
|
|
* ```
|
|
import { sdk } from '../sdk'
|
|
import { config } from './config'
|
|
import { nameToLogs } from './nameToLogs'
|
|
|
|
export const actions = sdk.Actions.of().addAction(config).addAction(nameToLogs)
|
|
* ```
|
|
*/
|
|
Actions: Actions<{}>,
|
|
/**
|
|
* @description Use this function to determine which volumes are backed up when a user creates a backup, including advanced options.
|
|
* @example
|
|
* In this example, we back up the entire "main" volume and nothing else.
|
|
*
|
|
* ```
|
|
import { sdk } from './sdk'
|
|
|
|
export const { createBackup, restoreBackup } = sdk.setupBackups(
|
|
async ({ effects }) => sdk.Backups.volumes('main'),
|
|
)
|
|
* ```
|
|
* @example
|
|
* In this example, we back up the "main" volume, but exclude hypothetical directory "excludedDir".
|
|
*
|
|
* ```
|
|
import { sdk } from './sdk'
|
|
|
|
export const { createBackup, restoreBackup } = sdk.setupBackups(async () =>
|
|
sdk.Backups.volumes('main').setOptions({
|
|
exclude: ['excludedDir'],
|
|
}),
|
|
)
|
|
* ```
|
|
*/
|
|
setupBackups: (options: SetupBackupsParams<Manifest>) =>
|
|
setupBackups<Manifest>(options),
|
|
/**
|
|
* @description Use this function to set dependency information.
|
|
* @example
|
|
* In this example, we create a dependency on Hello World >=1.0.0:0, where Hello World must be running and passing its "primary" health check.
|
|
*
|
|
* ```
|
|
export const setDependencies = sdk.setupDependencies(
|
|
async ({ effects }) => {
|
|
return {
|
|
'hello-world': {
|
|
kind: 'running',
|
|
versionRange: '>=1.0.0',
|
|
healthChecks: ['primary'],
|
|
},
|
|
}
|
|
},
|
|
)
|
|
* ```
|
|
*/
|
|
setupDependencies: setupDependencies<Manifest>,
|
|
/**
|
|
* @description Use this function to create an InitScript that runs every time the service initializes (install, update, restore, rebuild, and server bootup)
|
|
*/
|
|
setupOnInit,
|
|
/**
|
|
* @description Use this function to create an UninitScript that runs every time the service uninitializes (update, uninstall, and server shutdown)
|
|
*/
|
|
setupOnUninit,
|
|
/**
|
|
* @description Use this function to setup what happens when the service initializes.
|
|
*
|
|
* This happens when the server boots, or a service is installed, updated, or restored
|
|
*
|
|
* Not every init script does something on every initialization. For example, versions only does something on install or update
|
|
*
|
|
* These scripts are run in the order they are supplied
|
|
* @example
|
|
*
|
|
* ```
|
|
export const init = sdk.setupInit(
|
|
restoreInit,
|
|
versions,
|
|
setDependencies,
|
|
setInterfaces,
|
|
actions,
|
|
postInstall,
|
|
)
|
|
* ```
|
|
*/
|
|
setupInit: setupInit,
|
|
/**
|
|
* @description Use this function to setup what happens when the service uninitializes.
|
|
*
|
|
* This happens when the server shuts down, or a service is uninstalled or updated
|
|
*
|
|
* Not every uninit script does something on every uninitialization. For example, versions only does something on uninstall or update
|
|
*
|
|
* These scripts are run in the order they are supplied
|
|
* @example
|
|
*
|
|
* ```
|
|
export const uninit = sdk.setupUninit(
|
|
versions,
|
|
)
|
|
* ```
|
|
*/
|
|
setupUninit: setupUninit,
|
|
/**
|
|
* @description Use this function to determine how this service will be hosted and served. The function executes on service install, service update, and inputSpec save.
|
|
* @param inputSpec - The inputSpec spec of this service as exported from /inputSpec/spec.
|
|
* @param fn - an async function that returns an array of interface receipts. The function always has access to `effects`; it has access to `input` only after inputSpec save, otherwise `input` will be null.
|
|
* @example
|
|
* In this example, we create two UIs from one multi-host, and one API from another multi-host.
|
|
*
|
|
* ```
|
|
export const setInterfaces = sdk.setupInterfaces(
|
|
async ({ effects }) => {
|
|
// ** UI multi-host **
|
|
const uiMulti = sdk.MultiHost.of(effects, 'ui-multi')
|
|
const uiMultiOrigin = await uiMulti.bindPort(80, {
|
|
protocol: 'http',
|
|
})
|
|
// Primary UI
|
|
const primaryUi = sdk.createInterface(effects, {
|
|
name: 'Primary UI',
|
|
id: 'primary-ui',
|
|
description: 'The primary web app for this service.',
|
|
type: 'ui',
|
|
masked: false,
|
|
schemeOverride: null,
|
|
username: null,
|
|
path: '',
|
|
query: {},
|
|
})
|
|
// Admin UI
|
|
const adminUi = sdk.createInterface(effects, {
|
|
name: 'Admin UI',
|
|
id: 'admin-ui',
|
|
description: 'The admin web app for this service.',
|
|
type: 'ui',
|
|
masked: false,
|
|
schemeOverride: null,
|
|
username: null,
|
|
path: '/admin',
|
|
query: {},
|
|
})
|
|
// UI receipt
|
|
const uiReceipt = await uiMultiOrigin.export([primaryUi, adminUi])
|
|
|
|
// ** API multi-host **
|
|
const apiMulti = sdk.MultiHost.of(effects, 'api-multi')
|
|
const apiMultiOrigin = await apiMulti.bindPort(5959, {
|
|
protocol: 'http',
|
|
})
|
|
// API
|
|
const api = sdk.createInterface(effects, {
|
|
name: 'Admin API',
|
|
id: 'api',
|
|
description: 'The advanced API for this service.',
|
|
type: 'api',
|
|
masked: false,
|
|
schemeOverride: null,
|
|
username: null,
|
|
path: '',
|
|
query: {},
|
|
})
|
|
// API receipt
|
|
const apiReceipt = await apiMultiOrigin.export([api])
|
|
|
|
// ** Return receipts **
|
|
return [uiReceipt, apiReceipt]
|
|
},
|
|
)
|
|
* ```
|
|
*/
|
|
setupInterfaces: setupServiceInterfaces,
|
|
/**
|
|
* Define the main entrypoint for the service. The provided function should
|
|
* configure and return a `Daemons` instance describing all long-running processes.
|
|
* @param fn - Async function that receives `effects` and returns a `Daemons` instance
|
|
*/
|
|
setupMain: (
|
|
fn: (o: { effects: Effects }) => Promise<Daemons<Manifest, any>>,
|
|
) => setupMain<Manifest>(fn),
|
|
/** Built-in trigger strategies for controlling health-check polling intervals */
|
|
trigger: {
|
|
/** Default trigger: polls at a fixed interval */
|
|
defaultTrigger,
|
|
/** Trigger with a cooldown period between checks */
|
|
cooldownTrigger,
|
|
/** Switches to a different interval after the first successful check */
|
|
changeOnFirstSuccess,
|
|
/** Uses different intervals based on success vs failure results */
|
|
successFailure,
|
|
},
|
|
Mounts: {
|
|
/**
|
|
* Create an empty Mounts builder for declaring volume, asset, dependency, and backup mounts.
|
|
* @returns A new Mounts instance with no mounts configured
|
|
*/
|
|
of: Mounts.of<Manifest>,
|
|
},
|
|
Backups: {
|
|
/**
|
|
* Create a Backups configuration that backs up entire volumes by name.
|
|
* @param volumeNames - Volume IDs from the manifest to include in backups
|
|
*/
|
|
ofVolumes: Backups.ofVolumes<Manifest>,
|
|
/**
|
|
* Create a Backups configuration from explicit sync path pairs.
|
|
* @param syncs - Array of `{ dataPath, backupPath }` objects
|
|
*/
|
|
ofSyncs: Backups.ofSyncs<Manifest>,
|
|
/**
|
|
* Create a Backups configuration with custom rsync options (e.g. exclude patterns).
|
|
* @param options - Partial sync options to override defaults
|
|
*/
|
|
withOptions: Backups.withOptions<Manifest>,
|
|
},
|
|
InputSpec: {
|
|
/**
|
|
* @description Use this function to define the inputSpec specification that will ultimately present to the user as validated form inputs.
|
|
*
|
|
* Most form controls are supported, including text, textarea, number, toggle, select, multiselect, list, color, datetime, object (sub form), and union (conditional sub form).
|
|
* @example
|
|
* In this example, we define a inputSpec form with two value: name and makePublic.
|
|
*
|
|
* ```
|
|
import { sdk } from '../sdk'
|
|
const { InputSpec, Value } = sdk
|
|
|
|
export const inputSpecSpec = InputSpec.of({
|
|
name: Value.text({
|
|
name: 'Name',
|
|
description:
|
|
'When you launch the Hello World UI, it will display "Hello [Name]"',
|
|
required: true,
|
|
default: 'World'
|
|
}),
|
|
makePublic: Value.toggle({
|
|
name: 'Make Public',
|
|
description: 'Whether or not to expose the service to the network',
|
|
default: false,
|
|
}),
|
|
})
|
|
* ```
|
|
*/
|
|
of: <Spec extends Record<string, Value<any>>>(spec: Spec) =>
|
|
InputSpec.of<Spec>(spec),
|
|
},
|
|
Daemon: {
|
|
/**
|
|
* Create a single Daemon that wraps a long-running process with automatic restart logic.
|
|
* Returns a curried function: call with `(effects, subcontainer, exec)`.
|
|
*/
|
|
get of() {
|
|
return Daemon.of<Manifest>()
|
|
},
|
|
},
|
|
Daemons: {
|
|
/**
|
|
* Create a new Daemons builder for defining the service's daemon topology.
|
|
* Chain `.addDaemon()` calls to register each long-running process.
|
|
* @param effects - The effects context
|
|
*/
|
|
of(effects: Effects) {
|
|
return Daemons.of<Manifest>({ effects })
|
|
},
|
|
},
|
|
SubContainer: {
|
|
/**
|
|
* @description Create a new SubContainer
|
|
* @param effects
|
|
* @param image - what container image to use
|
|
* @param mounts - what to mount to the subcontainer
|
|
* @param name - a name to use to refer to the subcontainer for debugging purposes
|
|
*/
|
|
of(
|
|
effects: Effects,
|
|
image: {
|
|
imageId: T.ImageId & keyof Manifest['images']
|
|
sharedRun?: boolean
|
|
},
|
|
mounts: Mounts<Manifest> | null,
|
|
name: string,
|
|
) {
|
|
return SubContainerOwned.of<Manifest, Effects>(
|
|
effects,
|
|
image,
|
|
mounts,
|
|
name,
|
|
).then((subc) => subc.rc())
|
|
},
|
|
/**
|
|
* @description Run a function with a temporary SubContainer
|
|
* @param effects
|
|
* @param image - what container image to use
|
|
* @param mounts - what to mount to the subcontainer
|
|
* @param name - a name to use to refer to the ephemeral subcontainer for debugging purposes
|
|
*/
|
|
withTemp<T>(
|
|
effects: T.Effects,
|
|
image: {
|
|
imageId: T.ImageId & keyof Manifest['images']
|
|
sharedRun?: boolean
|
|
},
|
|
mounts: Mounts<Manifest> | null,
|
|
name: string,
|
|
fn: (subContainer: SubContainer<Manifest>) => Promise<T>,
|
|
): Promise<T> {
|
|
return SubContainerOwned.withTemp(effects, image, mounts, name, fn)
|
|
},
|
|
},
|
|
List,
|
|
Value,
|
|
Variants,
|
|
plugin: {
|
|
url: this.ifPluginEnabled('url-v0' as const, {
|
|
register: (
|
|
effects: T.Effects,
|
|
options: {
|
|
tableAction: ActionInfo<
|
|
T.ActionId,
|
|
{
|
|
urlPluginMetadata: {
|
|
packageId: T.PackageId
|
|
interfaceId: T.ServiceInterfaceId
|
|
hostId: T.HostId
|
|
internalPort: number
|
|
}
|
|
}
|
|
>
|
|
},
|
|
) =>
|
|
effects.plugin.url.register({
|
|
tableAction: options.tableAction.id,
|
|
}),
|
|
exportUrl: (
|
|
effects: T.Effects,
|
|
options: {
|
|
hostnameInfo: T.PluginHostnameInfo
|
|
removeAction: ActionInfo<
|
|
T.ActionId,
|
|
{
|
|
urlPluginMetadata: T.PluginHostnameInfo & {
|
|
interfaceId: T.ServiceInterfaceId
|
|
}
|
|
}
|
|
> | null
|
|
overflowActions: ActionInfo<
|
|
T.ActionId,
|
|
{
|
|
urlPluginMetadata: T.PluginHostnameInfo & {
|
|
interfaceId: T.ServiceInterfaceId
|
|
}
|
|
}
|
|
>[]
|
|
},
|
|
) =>
|
|
effects.plugin.url.exportUrl({
|
|
hostnameInfo: options.hostnameInfo,
|
|
removeAction: options.removeAction?.id ?? null,
|
|
overflowActions: options.overflowActions.map((a) => a.id),
|
|
}),
|
|
setupExportedUrls, // similar to setupInterfaces
|
|
}),
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Run a one-shot command inside a temporary subcontainer.
|
|
*
|
|
* Creates a subcontainer, executes the command, and destroys the subcontainer when finished.
|
|
* Throws an {@link ExitError} if the command exits with a non-zero code or signal.
|
|
*
|
|
* @param effects - The effects context
|
|
* @param image - The container image to use
|
|
* @param command - The command to execute (string array or UseEntrypoint)
|
|
* @param options - Mount and command options
|
|
* @param name - Optional human-readable name for debugging
|
|
* @returns The stdout and stderr output of the command
|
|
*/
|
|
export async function runCommand<Manifest extends T.SDKManifest>(
|
|
effects: Effects,
|
|
image: { imageId: keyof Manifest['images'] & T.ImageId; sharedRun?: boolean },
|
|
command: T.CommandType,
|
|
options: CommandOptions & {
|
|
mounts: Mounts<Manifest> | null
|
|
},
|
|
name?: string,
|
|
): Promise<{ stdout: string | Buffer; stderr: string | Buffer }> {
|
|
let commands: string[]
|
|
if (T.isUseEntrypoint(command)) {
|
|
const imageMeta: T.ImageMetadata = await fs
|
|
.readFile(`/media/startos/images/${image.imageId}.json`, {
|
|
encoding: 'utf8',
|
|
})
|
|
.catch(() => '{}')
|
|
.then(JSON.parse)
|
|
commands = imageMeta.entrypoint ?? []
|
|
commands = commands.concat(...(command.overridCmd ?? imageMeta.cmd ?? []))
|
|
} else commands = splitCommand(command)
|
|
return SubContainerOwned.withTemp(
|
|
effects,
|
|
image,
|
|
options.mounts,
|
|
name ||
|
|
commands
|
|
.map((c) => {
|
|
if (c.includes(' ')) {
|
|
return `"${c.replace(/"/g, `\"`)}"`
|
|
} else {
|
|
return c
|
|
}
|
|
})
|
|
.join(' '),
|
|
async (subcontainer) => {
|
|
const res = await subcontainer.exec(commands)
|
|
if (res.exitCode || res.exitSignal) {
|
|
throw new ExitError(commands[0], res)
|
|
} else {
|
|
return res
|
|
}
|
|
},
|
|
)
|
|
}
|