///|
/// The reason why a server ended when nobody stopped it.
#derive(Eq, Debug)
pub(all) suberror ServeError {
  /// Another server of the instance runs. It did not change.
  AlreadyRunning
  /// The server did not start. `server.json` has the same reason, if the server
  /// could write it.
  NotStarted(@core.StartFailure)
  /// The server ran, and then the system gave no new connection for a minute. The
  /// text is the reason of the system.
  Ended(String)
}

///|
/// How to run a server.
#derive(Eq, Debug)
pub(all) struct ServeOptions {
  folder : @core.InstanceFolder
  port : @core.PortChoice
  version : @contracts.Version
}

///|
/// What a server gets from the machine, and its limits.
priv struct Machine {
  states : FolderStates
  now : () -> @app.UnixMillis
  /// Writes a line of the log.
  log : async (String) -> Unit noraise
  /// How long a start waits for the lock of the instance.
  lock_limit : Duration
  /// How long a stop waits for the open calls.
  drain_limit : Duration
}

///|
/// How long a stop waits for the last replies to control requests. The HTTP server
/// does not say when a reply went out, and its end cuts a reply that did not.
let reply_limit : Duration = Duration(100)

///|
/// 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:
///
/// ```mbt nocheck
/// @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.
pub async fn[X] serve(
  options : ServeOptions,
  ready : async (RunningServer) -> Unit noraise,
  reads~ : @async.TaskGroup[X],
) -> Unit raise ServeError {
  if @env.get_env_var("MISSION_CONTROL_BACKGROUND") == Some("1") {
    @signal.set_global_cancellation_signals([SIGTERM])
  }
  let machine = {
    states: FolderStates(reads),
    now: system_time,
    log: write_log,
    lock_limit: Duration(1000),
    drain_limit: Duration(5000),
  }
  serve_with(options, machine, ready)
}

///|
/// The time of the system.
fn system_time() -> @app.UnixMillis {
  @app.UnixMillis::UnixMillis(@env.now().reinterpret_as_int64()) catch {
    _ => abort("the clock is before 1970")
  }
}

///|
/// Writes a line to the standard error. The system has it at once, also when the
/// process ends without a stop. `println` keeps its text for a time when the output
/// is a file, so the last lines of `server.log` would not be there.
async fn write_log(text : String) -> Unit noraise {
  @stdio.stderr.write("\{text}\n") catch {
    // There is no other place to write to.
    _ => ()
  }
}

///|
/// Runs a server on a machine.
async fn serve_with(
  options : ServeOptions,
  machine : Machine,
  ready : async (RunningServer) -> Unit noraise,
) -> Unit raise ServeError {
  // After a cancellation, `handle_cancellation` gives `None`, so this function
  // returns, and the caller can end the process.
  (@async.handle_cancellation(() => serve_instance(options, machine, ready))
  |> ignore) catch {
    AlreadyRunning => raise AlreadyRunning
    NotStarted(failure) => raise NotStarted(failure)
    Ended(reason) => raise Ended(reason)
    error => raise NotStarted(Other(reason_of(error)))
  }
}

///|
async fn serve_instance(
  options : ServeOptions,
  machine : Machine,
  ready : async (RunningServer) -> Unit noraise,
) -> Unit {
  let folder = options.folder
  make_private_folder(folder.path())
  let lock = take_lock(folder, machine.lock_limit)
  defer lock.close()
  let (site, hub) = open_server(options, machine) catch {
    error => raise record_failure(folder, machine, error)
  }
  defer @async.protect_from_cancel(() => remove_record(folder, machine.log))
  let running = {
    folder,
    version: options.version,
    port: hub.port,
    secret: site.login.secret,
  }
  @async.with_task_group(group => {
    // Only the stop ends this task. The group waits for it, also when the group is
    // cancelled.
    group.spawn_bg(() => {
      @async.protect_from_cancel(() => {
        run_until_stop(site, hub, machine.drain_limit)
      })
    })
    group.spawn_bg(no_wait=true, () => {
      // A cancellation ends the wait and then asks for the stop.
      defer site.stop.request()
      site.stop.wait()
    })
    group.spawn_bg(no_wait=true, () => ready(running))
  })
}

///|
/// Writes the failure of a start to the record, and gives it as the error of
/// `serve`. A program that waits for the server then knows the reason at once.
async fn record_failure(
  folder : @core.InstanceFolder,
  machine : Machine,
  error : Error,
) -> ServeError noraise {
  let failure : @core.StartFailure = match error {
    NotStarted(failure) => failure
    InUse(port) => PortInUse(port)
    NoBind(reason) => Other(reason)
    error => Other(reason_of(error))
  }
  let record : @core.ServerRecord = Failed(at=(machine.now)(), failure~)
  write_private(folder.record(), record.to_text()) catch {
    error =>
      (machine.log)("\{folder.record()} is not written: \{reason_of(error)}")
  }
  NotStarted(failure)
}

///|
/// Removes the record of a server that ended.
async fn remove_record(
  folder : @core.InstanceFolder,
  log : async (String) -> Unit noraise,
) -> Unit noraise {
  remove_made(folder.record()) catch {
    error => log("\{folder.record()} is not removed: \{reason_of(error)}")
  }
}

///|
/// Takes the lock of an instance. The system releases it when the file closes, and
/// also after a crash. A server that stops needs a moment, so a start waits for it. It
/// does not wait for a server that answers: a second start would then become the server
/// when the user stops the first one.
async fn take_lock(folder : @core.InstanceFolder, limit : Duration) -> @fs.File {
  let file = @fs.open(
    folder.lock(),
    mode=ReadWrite,
    create_mode=OpenOrCreate,
    permission=private_file_mode,
  )
  errdefer file.close()
  let end = limit.after(@async.now())
  while !file.try_lock(Exclusive) {
    // A look can need a second, and the server can end in that time. So the loop tries
    // the lock after each look, also when the time is over.
    guard @async.now() < end && !(look_at(folder) is Found(Answers(_))) else {
      raise AlreadyRunning
    }
    @async.sleep(look_delay.millis())
  }
  file
}

///|
/// Reads the files of the instance, listens on the port, and writes the record. The
/// caller has the lock.
async fn open_server(
  options : ServeOptions,
  machine : Machine,
) -> (Site, HubServer) {
  let folder = options.folder
  remove_left_files(folder, machine.log)
  // The record of the last server is not correct now.
  remove_made(folder.record())
  let projects = read_projects(folder)
  let secret = new_secret()
  let views = Views()
  let stop = StopRequest()
  let app = App(
    folder,
    options.version,
    projects,
    states=machine.states,
    publish=(name, payload) => views.publish(name, payload),
    has_view=surface => views.has(surface),
    stop=() => stop.request(),
    now=machine.now,
  )
  let site : Ref[Site?] = Ref(None)
  let hub = listen(options.port, port => {
    HubServer::bind(port, views~, commands=app.operation_names(), handlers=port => {
      let made = Site::{
        app,
        login: Login(folder.name(), port~, secret~, now=machine.now),
        views,
        stop,
        log: machine.log,
        calls: 0,
        idle: Cond(),
      }
      site.val = Some(made)
      made.handlers()
    })
  })
  errdefer @async.protect_from_cancel(() => hub.stop(Duration(0)))
  let record : @core.ServerRecord = Running(
    port=hub.port,
    version=options.version,
    secret~,
  )
  write_private(folder.record(), record.to_text())
  (site.val.unwrap(), hub)
}

///|
/// Listens on the port that the options choose.
async fn listen(
  choice : @core.PortChoice,
  bind : async (@core.Port?) -> HubServer,
) -> HubServer {
  match choice {
    Free => bind(None)
    Fixed(port) => bind(Some(port))
    Preferred(port) =>
      bind(Some(port)) catch {
        InUse(_) | NoBind(_) => bind(None)
        error => raise error
      }
  }
}

///|
/// Reads the project file. The list is empty when there is no file. This function
/// never changes the file.
async fn read_projects(folder : @core.InstanceFolder) -> @core.ProjectList {
  let path = folder.projects()
  let bad = message => ServeError::NotStarted(BadProjectFile(path~, message~))
  let text = @fs.read_file(path).text() catch {
    @os_error.OSError(_) as error if error.is_ENOENT() =>
      return @core.ProjectList::empty()
    @os_error.OSError(_) as error => raise bad(reason_of(error))
    _ => raise bad("The file is not UTF-8 text.")
  }
  @core.ProjectList::of_file_text(text, folder.platform()) catch {
    Damaged(reason) => raise bad("The file is damaged: \{reason}")
    NewerFormat(format) =>
      raise bad(
        "The file has the format \{format}, which this version does not know.",
      )
  }
}

///|
/// Handles requests until the stop. Then it lets the open calls finish, and closes
/// the server.
async fn run_until_stop(
  site : Site,
  hub : HubServer,
  drain_limit : Duration,
) -> Unit {
  let failure : Ref[Error?] = Ref(None)
  @async.with_task_group(group => {
    group.spawn_bg(() => {
      hub.run(site.log) catch {
        error => failure.val = Some(error)
      }
      site.stop.request()
    })
    site.stop.wait()
    if failure.val is Some(error) {
      raise Ended(reason_of(error))
    }
    let end = drain_limit.after(@async.now())
    site.finish_calls(drain_limit)
    @async.sleep(reply_limit.millis())
    hub.stop(Duration::between(@async.now(), end))
  })
}

///|
pub extend ServeError with Eq::{not_equal, equal}

///|
pub extend ServeError with @debug.Debug::{to_repr}

///|
pub extend ServeOptions with Eq::{not_equal, equal}

///|
pub extend ServeOptions with @debug.Debug::{to_repr}