mission-control-server

    The Mission Control server: instance folders, ports, folder paths and project rules

    mission-control
    server
    instance
    Download zip
    Author
    Version
    0.5.0
    License
    Apache-2.0
    Last updated
    2 hours ago
    Downloads
    4

    #moonrockz/mission-control-server

    The Mission Control server. Each running copy of Mission Control is an instance. This module holds the rules that every part of Mission Control shares: where an instance keeps its files, which port it uses, which projects it lists, who can use its server, and how another program finds the server. The commands for users are in Web UI and projects.

    moon add moonrockz/mission-control-server

    #moonrockz/mission-control-server

    The root package is the server process. It gives the UI to a browser or a desktop window, and does the commands of moonrockz/mission-control-contracts/app. It listens on 127.0.0.1 only. The package builds on native and wasm only, because it uses moonbitlang/async/fs.

    #Run a server

    async fn main {
    @async.with_task_group(reads => {
    @server.serve(options, reads~, running => {
    @stdio.stdout.write("\{running.address()}\n") catch { _ => () }
    })
    @env.exit(0)
    })
    }

    • serve returns after a stop. A view, a control request or a cancellation, such as Ctrl+C, stops the server. The open calls have 5 seconds to finish.
    • End the process with @env.exit when serve returns or raises. A read of a network share that is off can continue for 40 seconds, and nothing can cancel it. reads is the task group of these reads. It waits for them, and so does the end of main.
    • ServeOptions has the folder of the instance, the port and the version.
    • A port is in use when a program accepts connections to it on 127.0.0.1, also when that program listens on all addresses. Then Fixed raises NotStarted(PortInUse(port)), and Preferred takes a free port.
    • AlreadyRunning says that another server has the lock of the instance. NotStarted has the reason of a failed start, which is also in server.json. Ended says that the system gave no new connection for a minute.
    • The server writes its log to the standard error. The log never has a request, because an address can have a secret.
    • With MISSION_CONTROL_BACKGROUND=1 in the environment, only SIGTERM cancels the program.

    Refusal is the error of a command that the server does not do. Its text is for people, such as /code/notes.txt is not a folder. Show it as it is.

    #Find, start, call and stop a server

    let server = @server.find_or_start(folder, {
    program: "/usr/local/bin/mission-control",
    args: ["serve", "--instance", "stable"],
    })
    let added = server.call(@app.add_project, { path: "/code/docs" })
    println(server.link(Browser, Some(added.project.id)))

    • find gives the server of an instance, and find_all gives all servers in the order of their names. A server runs when a process has the lock of the instance. None says that no server runs. FoundServer says what the server does:

      CaseThe server
      Answers(server)The program on the port of server.json says that it is this instance.
      Silent(name)It does not answer for 1 to 2 seconds, or it does not end in 10 seconds after a stop.
      NewerFormat(name, format)It is from a newer version, and this version cannot read its server.json.

    • FoundServer::server gives the server, or NotReachable with a text for the other two cases.
    • find_all raises FindError when it cannot read the folder of the instances. A folder that does not exist has no servers.
    • find_or_start starts the server in the background if none runs. Starter has the full path of the program that calls serve. The server has no window and no file of the starter, and it continues when the starter and its terminal end. Its outputs go to server.log.
    • When two programs start a server at the same time, one of them starts it and the other one waits. A lock on server.log says who starts.
    • wait_for waits for a server that another program starts.
    • Starter::background_command gives the command for another program that continues when the terminal ends, such as the desktop app. On Linux and macOS that program ignores the signals of the terminal.
    • existing_folder gives the real path of a folder, or the Refusal that add_project has for it. Call it before you start another program with the folder.
    • StartError is PortInUse, or Failed with the reason, the last 20 lines of the log and the path of the log. The error comes at once when the server writes its reason or ends, and when a server of a newer version runs. In each other case it comes after 10 seconds.
    • call does a command of the contract, and call_json does a command by its name. ServerCallError has texts for people: Refused, NotReachable and BadReply.
    • stop returns when the server has ended. Another program can start a new server of the instance at once, and stop does not wait for that one.

    #Addresses

    The server refuses each request with another Host, or with the Origin of another site.

    RequestLoginReply
    GET /?access_token=<token>the token of a linkA page that keeps the cookie and the view key, and then shows the UI.
    GET /, GET /app.jscookieThe page of the UI and its script.
    GET /sessioncookie, and view key in Authorization: Bearer204, or 403 when the session does not exist.
    /hub, /hub/negotiatecookie, and view key in Authorization: Bearer or access_tokenThe SignalR hub, with the commands and the events. A message has 32768 bytes and 64 levels of JSON at most.
    GET /control/statussecret{"app":"mission-control","instance":…,"version":…,"views":…}
    POST /control/link?surface=&project=secret{"url":…}. surface is browser or desktop. project can be absent.
    POST /control/call?command=&request=secret200 with the reply of the command, or 422 with the text of a refusal.
    POST /control/stopsecret202, and then the server stops.

    These are the default limits of SignalR. A view with a larger or deeper message loses its connection, and the other views keep theirs. The request of a command can have 16 levels. With more, the view gets an error and keeps its connection.

    The secret is in server.json, and goes in the header X-Mission-Control-Secret. A control request has no body. Each failure has the body {"error":…}. After the stop starts, a page and a control request get 503, except POST /control/stop, and a view gets a refusal for each new call except stop_app.

    #moonrockz/mission-control-server/core

    This package is pure. It does no I/O, and it builds on wasm, wasm-gc, js and native. The caller reads the environment, the clock, the files and the random bytes, and gives them to the package.

    #Folders and ports

    • BaseFolder::of_env(platform, env) finds the base folder. MISSION_CONTROL_HOME wins over all other variables. Then Windows uses LOCALAPPDATA, macOS uses HOME, and Linux uses XDG_DATA_HOME or HOME. A variable with an empty value counts as not set. A relative XDG_DATA_HOME is ignored. Another variable that holds a path that is not absolute raises NotAbsolute. A missing variable raises MissingVariable.
    • BaseFolder::instance(name) gives the InstanceFolder. Its files are server.lock, server.json, server.log and projects.json.
    • BaseFolder::desktop(name) gives the folder of the desktop app that is installed for an instance, and desktop_program(folder) gives the path of its program. desktop_candidates(base, name, channel, env) gives the programs that can be the app of an instance, in the order of the search: the variable MISSION_CONTROL_DESKTOP, the instance and the channel. It ignores a variable with a path that is not absolute.
    • Port::Port(value) accepts 1 to 65535. PortChoice::for_command(name) gives the fixed port of stable (3090), insiders (3091), nightly (3092) and dev (3093), and Free for each other name. PortChoice::for_desktop(name) gives Preferred in place of Fixed.
    • FolderPath::FolderPath(text, platform) parses an absolute path and removes ., .. and repeated or trailing separators. On Windows it reads drive paths (C:\a, C:/a), \\?\ paths and UNC paths, and writes the drive letter in upper case. One pair of double quotes around a Windows path is permitted, because "Copy as path" gives it. FolderPath::resolve(text, base) reads a relative path from a base folder. same_folder and contains compare paths. Windows ignores the case of letters. Linux and macOS compare the exact text.

    #Project list

    • ProjectList holds the folders that the user added, in that order. A folder is in the list one time. add, open and remove give a new list and do not change the old one. The list does not use the ID of a removed project again.
    • describe gives the projects for the UI. A project shows the name of its parent folder while another project has the same name.
    • ProjectRef::ProjectRef(text, current) reads what a person types: an ID (3), a path (./docs) or a name (docs). find gives the one project that matches, or raises NoMatch or Ambiguous.
    • nearest_project gives the deepest project that contains a folder. last_opened gives the project that the user opened last.
    • to_file_text and of_file_text write and read projects.json. A file that this version cannot read raises Damaged or NewerFormat.

    #Login rules

    • Secret::of_bytes(bytes) makes a secret from 32 random bytes or more. Its debug text is always <secret>. Only to_text gives the text.
    • Links holds the links that the server gave. A link works for 10 minutes, and it can work more than one time. redeem gives the kind of view and the project of the link.
    • Sessions holds two secrets for each session: a cookie value and a view key. A browser sends the cookie to each port of the machine, so another local server can read it. The browser keeps the view key for the origin of the server only.
    • Sessions::find needs only the cookie. Use it for the static page and its script, and for nothing else. Sessions::find_view needs the cookie and the view key of one session. Use it for the hub and for the session check.
    • CookieName contains the instance name and the port, such as mc_stable_3090. set_cookie gives the header value for the cookie. Do not put the view key in a cookie.
    • site_decision(port, host~, origin~) checks the Host and the Origin of a request. The host must be 127.0.0.1:<port>. The origin must be absent or http://127.0.0.1:<port>.

    #Server record

    • ServerRecord is the content of server.json. Running has the port, the version and the secret of the server. Failed has the time and the reason why the server did not start.
    • to_text and of_text write and read the file. The text of Running contains the secret, so write it only to the private file of the instance.
    • of_text raises Damaged or NewerFormat. These errors never contain a text from the file, because that text can be the secret.
    • server.json and projects.json have the same rule for the format number. It is a JSON number, and a whole number of 1 or more. A number above 1 raises NewerFormat. A number above 2147483647 has the value 2147483647 in the error.

    FindError

    pub(all) suberror FindError {
    NotReadable(path~ : String, reason~ : String)
    } derive(Eq,
    Debug
    )

    Raised when the instances cannot be found.

    Refusal

    pub(all) suberror Refusal {
    Refusal(String)
    } derive(Eq,
    Debug
    )

    A call that the app does not do. The text is for people, and a client shows it as it is.

    Refusal::equal

    fn Refusal::equal(Refusal, Refusal) -> Bool
    automatically derived

    Refusal::not_equal

    fn Refusal::not_equal(x : Refusal, y : Refusal) -> Bool
    automatically derived

    Refusal::to_repr

    automatically derived

    ServeError

    pub(all) suberror ServeError {
    AlreadyRunning
    NotStarted(
    StartFailure
    )
    Ended(String)
    } derive(Eq,
    Debug
    )

    The reason why a server ended when nobody stopped it.

    ServeError::equal

    fn ServeError::equal(ServeError, ServeError) -> Bool
    automatically derived

    ServeError::not_equal

    fn ServeError::not_equal(x : ServeError, y : ServeError) -> Bool
    automatically derived

    ServeError::to_repr

    automatically derived

    ServerCallError

    pub(all) suberror ServerCallError {
    Refused(String)
    NotReachable(String)
    BadReply(String)
    } derive(Eq,
    Debug
    )

    Raised when a control request to a server has no success. The text is for people.

    ServerCallError::equal

    automatically derived

    ServerCallError::not_equal

    fn ServerCallError::not_equal(x : ServerCallError, y : ServerCallError) -> Bool
    automatically derived

    ServerCallError::to_repr

    automatically derived

    StartError

    pub(all) suberror StartError {
    PortInUse(
    Port
    )
    Failed(reason~ : String, log_tail~ : ReadOnlyArray[String], log~ : String)
    } derive(Eq,
    Debug
    )

    The reason why there is no server of the instance.

    StartError::equal

    fn StartError::equal(StartError, StartError) -> Bool
    automatically derived

    StartError::not_equal

    fn StartError::not_equal(x : StartError, y : StartError) -> Bool
    automatically derived

    StartError::to_repr

    automatically derived

    FoundServer

    A server that has the lock of its instance.

    FoundServer::server

    The server, if it answers. Raises NotReachable in each other case. The text says why this program cannot use the server.

    RunningServer

    pub struct RunningServer {
    // private fields
    }

    A server that runs, as another program or the server itself knows it.

    RunningServer::address

    fn RunningServer::address(self : RunningServer) -> String

    The address of the server, such as http://127.0.0.1:3090.

    RunningServer::call

    Does a command of the contract, such as @app.add_project, and gives its reply.

    RunningServer::call_json

    Does a command of the server and gives its reply. The name is the name in the contract, such as add_project.

    RunningServer::instance

    The instance of the server.

    Asks for a link that opens the UI, with the project when there is one. The link gives access to the server for 10 minutes, so show it only to the user.

    RunningServer::port

    The port of 127.0.0.1 on which the server listens.

    RunningServer::stop

    async fn RunningServer::stop(self : RunningServer) -> Unit raise ServerCallError

    Stops the server, and returns when it has ended. A new server of the instance can then start on the same port, and this function does not wait for that one.

    This needs 10 seconds at most, and raises NotReachable when the server did not end. A server that ended before is no failure.

    RunningServer::version

    The version of the server. It can be another version than this program has.

    RunningServer::views

    async fn RunningServer::views(self : RunningServer) -> Int raise ServerCallError

    The number of views that are connected to the server.

    ServeOptions

    How to run a server.

    ServeOptions::equal

    automatically derived

    ServeOptions::not_equal

    fn ServeOptions::not_equal(x : ServeOptions, y : ServeOptions) -> Bool
    automatically derived

    ServeOptions::to_repr

    automatically derived

    Starter

    pub(all) struct Starter {
    program : String
    args : ReadOnlyArray[String]
    } derive(Eq,
    Debug
    )

    The program that runs the server of an instance: the CLI or the desktop app, with the arguments of serve. A start fails when the program ends, so a program that starts another one must wait for it.

    Starter::background_command

    fn Starter::background_command(self : Starter) -> (String, Array[String])

    The command that runs a starter in the background: a program with its full path, and its arguments.

    On Linux and macOS, the new process is in the process group of this program. A terminal that closes, Ctrl+C and Ctrl+Z send a signal to the group, when for example ssh -t or a script ran this program. sh ignores these signals and then becomes the program, with the same process ID. A program inherits the signals that it ignores.

    On Windows, the new process has its own console without a window.

    Starter::equal

    fn Starter::equal(Starter, Starter) -> Bool
    automatically derived

    Starter::not_equal

    fn Starter::not_equal(x : Starter, y : Starter) -> Bool
    automatically derived

    Starter::to_repr

    automatically derived

    existing_folder

    The real path of a folder that exists. Raises the refusal that add_project gives for the folder, such as /code/nope does not exist, so a program can check a folder before it starts another one.

    It can need a long time for a folder on a network share that is off.

    find

    Finds the server of an instance. None says that no server runs.

    A server runs when a process has the lock of the instance. It answers when the program on the port of server.json says that it is this instance. So the file of a server that died, or another program on its port, is no server.

    The function waits for the end of a server that stops, 10 seconds at most, and for a server that does not answer, 1 to 2 seconds. It changes no file.

    find_all

    Finds the servers of all instances, in the order of their names. There are none when the folder of all instances does not exist.

    find_or_start

    Finds the server of an instance, or starts one in the background and waits until it answers. The server continues when this program and its terminal end.

    When two programs do this at the same time, one of them starts a server, and the other one waits for it. Both get the same server.

    This needs about 20 seconds at most: 10 seconds for a server that stops or for another start, and 10 seconds for the new server to answer. The error comes at once when the new server ends or writes the reason of its failure. A server that does not answer in time continues to run, so a later command can find it.

    The server gets the folder of the instance as its working directory, MISSION_CONTROL_BACKGROUND=1, no input, and server.log for both outputs. It has no other file or pipe of this program, so a program that reads the output of this one does not wait for the server.

    real_folder

    The path that the project list has for a folder that a user names, such as a link.

    When the folder is gone, the result is the real path of the nearest folder above it that exists, with the other names. So a user can still name a project whose folder is gone. When the system gives no answer in a second, such as for a network share that is off, the result is the path of the user.

    The read then continues in the group reads, and nothing can cancel it. So the program must end with @env.exit, as after serve.

    serve

    async fn[X] serve(options : ServeOptions, ready : async (RunningServer) -> Unit noraise, reads~ :
    TaskGroup
    [X]) -> Unit raise ServeError

    Runs the server of an instance, and returns after its stop. A view, a control request or a cancellation, such as Ctrl+C, stops the server. The open calls have 5 seconds to finish. Then the server releases its port, removes server.json and releases its lock.

    ready gets the server when it answers requests. The stop cancels ready.

    reads is the task group of the folder reads. The system can need 40 seconds for a folder on a network share that is off, and nothing can cancel the read. serve does not wait for it, but the group does, and so does the end of main. So the caller ends the process with @env.exit when serve returns:

    @async.with_task_group(reads => {
    serve(options, reads~, running => {
    @stdio.stdout.write("\{running.address()}\n") catch { _ => () }
    })
    @env.exit(0)
    })

    Do not use println in ready. A native program keeps its text while the output is a file or a pipe.

    With MISSION_CONTROL_BACKGROUND=1 in the environment, only SIGTERM cancels the program. find_or_start starts it so that it ignores the signals of a terminal. If another signal comes, the system ends the process at once, as in a crash, and the next start removes the old files.

    wait_for

    Waits until the server of an instance answers, for 10 seconds at most. Another program starts the server, such as the desktop app. since is a time before that start: the reason of an older failure does not count.