chore: Update the start-sdk to use dependencies

This commit is contained in:
BluJ
2023-04-17 13:39:09 -06:00
parent 78076387ef
commit 4b74906ada
6 changed files with 73 additions and 110 deletions

View File

@@ -0,0 +1,15 @@
import { Dependency, PackageId } from "../types";
export function exists(id: PackageId) {
return {
id,
kind: "exists",
} as Dependency;
}
export function running(id: PackageId) {
return {
id,
kind: "running",
} as Dependency;
}

View File

@@ -2,3 +2,4 @@ export * as configBuilder from "./builder";
export { setupConfigExports } from "./setupConfigExports"; export { setupConfigExports } from "./setupConfigExports";
export { specToBuilder, specToBuilderFile } from "./specToBuilder"; export { specToBuilder, specToBuilderFile } from "./specToBuilder";
export * as dependencies from './dependencies'

View File

@@ -1,5 +1,5 @@
import { Config } from "./builder"; import { Config } from "./builder";
import { DeepPartial, DependsOn, Effects, ExpectedExports } from "../types"; import { DeepPartial, Dependencies, DependsOn, Effects, ExpectedExports } from "../types";
import { InputSpec } from "./configTypes"; import { InputSpec } from "./configTypes";
import { nullIfEmpty } from "../util"; import { nullIfEmpty } from "../util";
import { TypeFromProps } from "../util/propertiesMatcher"; import { TypeFromProps } from "../util/propertiesMatcher";
@@ -13,15 +13,8 @@ import { TypeFromProps } from "../util/propertiesMatcher";
*/ */
export function setupConfigExports<A extends InputSpec, ConfigType>(options: { export function setupConfigExports<A extends InputSpec, ConfigType>(options: {
spec: Config<A>; spec: Config<A>;
dependsOn: DependsOn; write(options: { effects: Effects; input: TypeFromProps<A> }): Promise<[ConfigType, Dependencies]>;
write(options: { read(options: { effects: Effects; config: ConfigType }): Promise<null | DeepPartial<TypeFromProps<A>>>;
effects: Effects;
input: TypeFromProps<A>;
}): Promise<ConfigType>;
read(options: {
effects: Effects;
config: ConfigType;
}): Promise<null | DeepPartial<TypeFromProps<A>>>;
}) { }) {
const validator = options.spec.validator(); const validator = options.spec.validator();
return { return {
@@ -30,17 +23,15 @@ export function setupConfigExports<A extends InputSpec, ConfigType>(options: {
await effects.error(String(validator.errorMessage(input))); await effects.error(String(validator.errorMessage(input)));
return { error: "Set config type error for config" }; return { error: "Set config type error for config" };
} }
const output = await options.write({ input, effects }); const [output, dependencies] = await options.write({ input, effects });
if (output) {
await effects.setWrapperData({ path: "config", value: output }); await effects.setDependencies(dependencies);
} await effects.setWrapperData({ path: "config", value: output });
}) as ExpectedExports.setConfig, }) as ExpectedExports.setConfig,
getConfig: (async ({ effects, config }) => { getConfig: (async ({ effects, config }) => {
return { return {
spec: options.spec.build(), spec: options.spec.build(),
config: nullIfEmpty( config: nullIfEmpty(await options.read({ effects, config: config as ConfigType })),
await options.read({ effects, config: config as ConfigType })
),
}; };
}) as ExpectedExports.getConfig, }) as ExpectedExports.getConfig,
}; };

View File

@@ -4,10 +4,12 @@ import { LocalBinding } from "./LocalBinding";
export class LocalPort { export class LocalPort {
constructor(readonly effects: Effects, readonly id: string) {} constructor(readonly effects: Effects, readonly id: string) {}
async bindLan(internalPort: number) { async bindLan(internalPort: number) {
const [localAddress, ipAddress] = await this.effects.bindLan({ const port = await this.effects.bindLan({
internalPort, internalPort,
name: this.id, name: this.id,
}); });
const localAddress = `${await this.effects.getLocalHostname()}:${port}`;
const ipAddress = `${await this.effects.getIPHostname()}:${port}`;
return new LocalBinding(localAddress, ipAddress); return new LocalBinding(localAddress, ipAddress);
} }
} }

View File

@@ -5,29 +5,17 @@ import { ActionReceipt } from "./init";
export namespace ExpectedExports { export namespace ExpectedExports {
version: 1; version: 1;
/** Set configuration is called after we have modified and saved the configuration in the embassy ui. Use this to make a file for the docker to read from for configuration. */ /** Set configuration is called after we have modified and saved the configuration in the embassy ui. Use this to make a file for the docker to read from for configuration. */
export type setConfig = (options: { export type setConfig = (options: { effects: Effects; input: Record<string, unknown> }) => Promise<void>;
effects: Effects;
input: Record<string, unknown>;
}) => Promise<unknown>;
/** Get configuration returns a shape that describes the format that the embassy ui will generate, and later send to the set config */ /** Get configuration returns a shape that describes the format that the embassy ui will generate, and later send to the set config */
export type getConfig = (options: { export type getConfig = (options: { effects: Effects; config: unknown }) => Promise<ConfigRes>;
effects: Effects;
config: unknown;
}) => Promise<ConfigRes>;
// /** These are how we make sure the our dependency configurations are valid and if not how to fix them. */ // /** These are how we make sure the our dependency configurations are valid and if not how to fix them. */
// export type dependencies = Dependencies; // export type dependencies = Dependencies;
/** For backing up service data though the embassyOS UI */ /** For backing up service data though the embassyOS UI */
export type createBackup = (options: { export type createBackup = (options: { effects: Effects }) => Promise<unknown>;
effects: Effects;
}) => Promise<unknown>;
/** For restoring service data that was previously backed up using the embassyOS UI create backup flow. Backup restores are also triggered via the embassyOS UI, or doing a system restore flow during setup. */ /** For restoring service data that was previously backed up using the embassyOS UI create backup flow. Backup restores are also triggered via the embassyOS UI, or doing a system restore flow during setup. */
export type restoreBackup = (options: { export type restoreBackup = (options: { effects: Effects }) => Promise<unknown>;
effects: Effects;
}) => Promise<unknown>;
/** Properties are used to get values from the docker, like a username + password, what ports we are hosting from */ /** Properties are used to get values from the docker, like a username + password, what ports we are hosting from */
export type properties = (options: { export type properties = (options: { effects: Effects }) => Promise<Properties | null | undefined | void>;
effects: Effects;
}) => Promise<Properties | null | undefined | void>;
// /** Health checks are used to determine if the service is working properly after starting // /** Health checks are used to determine if the service is working properly after starting
// * A good use case is if we are using a web server, seeing if we can get to the web server. // * A good use case is if we are using a web server, seeing if we can get to the web server.
@@ -43,43 +31,35 @@ export namespace ExpectedExports {
* service starting, and that file would indicate that it would rescan all the data. * service starting, and that file would indicate that it would rescan all the data.
*/ */
export type action = { export type action = {
[id: string]: (options: { [id: string]: (options: { effects: Effects; input?: Record<string, unknown> }) => Promise<ActionResult>;
effects: Effects;
input?: Record<string, unknown>;
}) => Promise<ActionResult>;
}; };
/** /**
* This is the entrypoint for the main container. Used to start up something like the service that the * This is the entrypoint for the main container. Used to start up something like the service that the
* package represents, like running a bitcoind in a bitcoind-wrapper. * package represents, like running a bitcoind in a bitcoind-wrapper.
*/ */
export type main = (options: { export type main = (options: { effects: Effects; started(onTerm: () => void): null }) => Promise<unknown>;
effects: Effects;
started(onTerm: () => void): null; /**
}) => Promise<unknown>; * After a shutdown, if we wanted to do any operations to clean up things, like
* set the action as unavailable or something.
*/
export type afterShutdown = (options: { effects: Effects }) => Promise<unknown>;
/** /**
* Every time a package completes an install, this function is called before the main. * Every time a package completes an install, this function is called before the main.
* Can be used to do migration like things. * Can be used to do migration like things.
*/ */
export type init = (options: { export type init = (options: { effects: Effects; previousVersion: null | string }) => Promise<unknown>;
effects: Effects;
previousVersion: null | string;
}) => Promise<unknown>;
/** This will be ran during any time a package is uninstalled, for example during a update /** This will be ran during any time a package is uninstalled, for example during a update
* this will be called. * this will be called.
*/ */
export type uninit = (options: { export type uninit = (options: { effects: Effects; nextVersion: null | string }) => Promise<unknown>;
effects: Effects;
nextVersion: null | string;
}) => Promise<unknown>;
} }
export type TimeMs = number; export type TimeMs = number;
export type VersionString = string; export type VersionString = string;
export type ValidIfNoStupidEscape<A> = A extends export type ValidIfNoStupidEscape<A> = A extends `${string}'"'"'${string}` | `${string}\\"${string}`
| `${string}'"'"'${string}`
| `${string}\\"${string}`
? never ? never
: "" extends A & "" : "" extends A & ""
? never ? never
@@ -104,9 +84,7 @@ export type Daemon = {
export type HealthStatus = "passing" | "warning" | "failing" | "disabled"; export type HealthStatus = "passing" | "warning" | "failing" | "disabled";
export type CommandType<A extends string> = export type CommandType<A extends string> = ValidIfNoStupidEscape<A> | [string, ...string[]];
| ValidIfNoStupidEscape<A>
| [string, ...string[]];
export type DaemonReturned = { export type DaemonReturned = {
wait(): Promise<string>; wait(): Promise<string>;
@@ -116,11 +94,7 @@ export type DaemonReturned = {
/** Used to reach out from the pure js runtime */ /** Used to reach out from the pure js runtime */
export type Effects = { export type Effects = {
/** Usable when not sandboxed */ /** Usable when not sandboxed */
writeFile(input: { writeFile(input: { path: string; volumeId: string; toWrite: string }): Promise<void>;
path: string;
volumeId: string;
toWrite: string;
}): Promise<void>;
readFile(input: { volumeId: string; path: string }): Promise<string>; readFile(input: { volumeId: string; path: string }): Promise<string>;
metadata(input: { volumeId: string; path: string }): Promise<Metadata>; metadata(input: { volumeId: string; path: string }): Promise<Metadata>;
/** Create a directory. Usable when not sandboxed */ /** Create a directory. Usable when not sandboxed */
@@ -132,17 +106,10 @@ export type Effects = {
removeFile(input: { volumeId: string; path: string }): Promise<void>; removeFile(input: { volumeId: string; path: string }): Promise<void>;
/** Write a json file into an object. Usable when not sandboxed */ /** Write a json file into an object. Usable when not sandboxed */
writeJsonFile(input: { writeJsonFile(input: { volumeId: string; path: string; toWrite: Record<string, unknown> }): Promise<void>;
volumeId: string;
path: string;
toWrite: Record<string, unknown>;
}): Promise<void>;
/** Read a json file into an object */ /** Read a json file into an object */
readJsonFile(input: { readJsonFile(input: { volumeId: string; path: string }): Promise<Record<string, unknown>>;
volumeId: string;
path: string;
}): Promise<Record<string, unknown>>;
runCommand<A extends string>( runCommand<A extends string>(
command: ValidIfNoStupidEscape<A> | [string, ...string[]], command: ValidIfNoStupidEscape<A> | [string, ...string[]],
@@ -154,9 +121,7 @@ export type Effects = {
wait(): Promise<string>; wait(): Promise<string>;
term(): Promise<void>; term(): Promise<void>;
}; };
runDaemon<A extends string>( runDaemon<A extends string>(command: ValidIfNoStupidEscape<A> | [string, ...string[]]): DaemonReturned;
command: ValidIfNoStupidEscape<A> | [string, ...string[]]
): DaemonReturned;
/** Uses the chown on the system */ /** Uses the chown on the system */
chown(input: { volumeId: string; path: string; uid: string }): Promise<null>; chown(input: { volumeId: string; path: string; uid: string }): Promise<null>;
@@ -181,14 +146,12 @@ export type Effects = {
/** Check that a file exists or not */ /** Check that a file exists or not */
exists(input: { volumeId: string; path: string }): Promise<boolean>; exists(input: { volumeId: string; path: string }): Promise<boolean>;
/** Declaring that we are opening a interface on some protocal for local network */ /** Declaring that we are opening a interface on some protocal for local network
bindLan(options: { internalPort: number; name: string }): Promise<string[]>; * Returns the port exposed
*/
bindLan(options: { internalPort: number; name: string }): Promise<number>;
/** Declaring that we are opening a interface on some protocal for tor network */ /** Declaring that we are opening a interface on some protocal for tor network */
bindTor(options: { bindTor(options: { internalPort: number; name: string; externalPort: number }): Promise<string>;
internalPort: number;
name: string;
externalPort: number;
}): Promise<string>;
/** Similar to the fetch api via the mdn, this is simplified but the point is /** Similar to the fetch api via the mdn, this is simplified but the point is
* to get something from some website, and return the response. * to get something from some website, and return the response.
@@ -248,17 +211,11 @@ export type Effects = {
getLocalHostname(): Promise<string>; getLocalHostname(): Promise<string>;
getIPHostname(): Promise<string>; getIPHostname(): Promise<string>;
/** Get the address for another service for tor interfaces */ /** Get the address for another service for tor interfaces */
getServiceTorHostname( getServiceTorHostname(interfaceId: string, packageId?: string): Promise<string>;
interfaceId: string,
packageId?: string
): Promise<string>;
/** /**
* Get the port address for another service * Get the port address for another service
*/ */
getServicePortForward( getServicePortForward(internalPort: number, packageId?: string): Promise<number>;
internalPort: number,
packageId?: string
): Promise<number>;
/** When we want to create a link in the front end interfaces, and example is /** When we want to create a link in the front end interfaces, and example is
* exposing a url to view a web service * exposing a url to view a web service
@@ -328,21 +285,20 @@ export type Effects = {
* *
* @returns PEM encoded fullchain (ecdsa) * @returns PEM encoded fullchain (ecdsa)
*/ */
getSslCertificate: ( getSslCertificate: (packageId: string, algorithm?: "ecdsa" | "ed25519") => [string, string, string];
packageId: string,
algorithm?: "ecdsa" | "ed25519"
) => [string, string, string];
/** /**
* @returns PEM encoded ssl key (ecdsa) * @returns PEM encoded ssl key (ecdsa)
*/ */
getSslKey: (packageId: string, algorithm?: "ecdsa" | "ed25519") => string; getSslKey: (packageId: string, algorithm?: "ecdsa" | "ed25519") => string;
setHealth(o: { setHealth(o: { name: string; status: HealthStatus; message?: string }): Promise<void>;
name: string;
status: HealthStatus;
message?: string;
}): Promise<void>;
/** Set the dependencies of what the service needs, usually ran during the set config as a best practice */
setDependencies(dependencies: Dependencies): Promise<void>;
/** Exists could be useful during the runtime to know if some service exists, option dep */
exists(packageId: PackageId): Promise<boolean>;
/** Exists could be useful during the runtime to know if some service is running, option dep */
running(packageId: PackageId): Promise<boolean>;
restart(): void; restart(): void;
shutdown(): void; shutdown(): void;
}; };
@@ -423,6 +379,10 @@ export type SetResult = {
"depends-on": DependsOn; "depends-on": DependsOn;
}; };
export type PackageId = string;
export type Message = string;
export type DependencyKind = "running" | "exists";
export type DependsOn = { export type DependsOn = {
[packageId: string]: string[]; [packageId: string]: string[];
}; };
@@ -463,16 +423,10 @@ export type Properties = {
data: PackagePropertiesV2; data: PackagePropertiesV2;
}; };
export type Dependencies = { export type Dependency = {
/** Id is the id of the package, should be the same as the manifest */ id: PackageId;
[id: string]: { kind: DependencyKind;
/** Checks are called to make sure that our dependency is in the correct shape. If a known error is returned we know that the dependency needs modification */
check(effects: Effects, input: InputSpec): Promise<void | null>;
/** This is called after we know that the dependency package needs a new configuration, this would be a transform for defaults */
autoConfigure(effects: Effects, input: InputSpec): Promise<InputSpec>;
};
}; };
export type Dependencies = Array<Dependency>;
export type DeepPartial<T> = T extends {} export type DeepPartial<T> = T extends {} ? { [P in keyof T]?: DeepPartial<T[P]> } : T;
? { [P in keyof T]?: DeepPartial<T[P]> }
: T;