///|
/// How long a server has to say its status. A server answers at once, and a program
/// that does not know the request possibly never.
let status_limit : Duration = Duration(1000)

///|
/// How long `find` waits for a server that stops.
let find_limit : Duration = Duration(10_000)

///|
/// How long `find` looks again at a server that has the lock and does not answer. A
/// server has the lock for a moment before it writes its record, and after it removes
/// it.
let silent_limit : Duration = Duration(1000)

///|
/// A server that has the lock of its instance.
pub(all) enum FoundServer {
  /// The server answers.
  Answers(RunningServer)
  /// The server of the instance does not answer, or it did not end in 10 seconds after
  /// a stop.
  Silent(@app.InstanceName)
  /// The record of the server has this format, which only a newer version knows.
  NewerFormat(@app.InstanceName, Int32)
}

///|
/// The server, if it answers. Raises `NotReachable` in each other case. The text says
/// why this program cannot use the server.
pub fn FoundServer::server(
  self : FoundServer,
) -> RunningServer raise ServerCallError {
  match self {
    Answers(server) => server
    Silent(name) =>
      raise NotReachable(
        "A server of the instance \{name.to_string()} runs, but it does not answer.",
      )
    NewerFormat(name, format) =>
      raise NotReachable(newer_format_text(name, format))
  }
}

///|
/// The text for a server that only a newer version can use.
fn newer_format_text(name : @app.InstanceName, format : Int32) -> String {
  "The server of the instance \{name.to_string()} is from a newer version of Mission Control. Its server.json has the format \{format}, which this version does not know."
}

///|
/// Raised when the instances cannot be found.
#derive(Eq, Debug)
pub(all) suberror FindError {
  /// The folder of all instances cannot be read. The reason is text for people.
  NotReadable(path~ : String, reason~ : String)
}

///|
/// 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.
pub async fn find(folder : @core.InstanceFolder) -> FoundServer? noraise {
  find_in(folder, find_limit)
}

///|
/// Finds the servers of all instances, in the order of their names. There are none when
/// the folder of all instances does not exist.
pub async fn find_all(
  base : @core.BaseFolder,
) -> Array[FoundServer] raise FindError {
  let path = base.instances()
  let names = @fs.readdir(path) catch {
    @os_error.OSError(_) as error if error.is_ENOENT() => []
    error => raise NotReadable(path~, reason=reason_of(error))
  }
  // The order of `String` puts a short name before a long one.
  names.sort_by((a, b) => a.lexical_compare(b))
  let found = @async.all(
    names.filter_map(name => {
      let name = Some(@app.InstanceName::InstanceName(name)) catch { _ => None }
      name.map(name => () => find(base.instance(name)))
    }),
  ) catch {
    // `find` raises nothing, so this is a cancellation, and nothing gets the result.
    _ => []
  }
  found.filter_map(server => server)
}

///|
/// Finds the server of an instance, and waits for a server that stops in a limited
/// time.
async fn find_in(
  folder : @core.InstanceFolder,
  limit : Duration,
) -> FoundServer? noraise {
  let end = limit.after(@async.now())
  // When the first look ended that saw a silent server. A look can need a second, and
  // the server can end in that time. So one silent look is never sufficient.
  let mut silent_since : Int64? = None
  // Each look reads the record again. Another program can start a new server at once
  // after an end, and then no look sees a free lock.
  for ;; {
    let look = look_at(folder)
    let now = @async.now()
    let found = match look {
      NoServer => return None
      Found(Answers(_) as found) => return Some(found)
      Found(found) => {
        let since = silent_since.unwrap_or(now)
        guard now < silent_limit.after(since) else { return Some(found) }
        silent_since = Some(since)
        found
      }
      Stops => {
        silent_since = None
        Silent(folder.name())
      }
    }
    guard now < end else { return Some(found) }
    @async.sleep(look_delay.millis())
  }
}

///|
/// What one look at an instance says.
priv enum Look {
  /// No process has the lock.
  NoServer
  /// The server answers, but it accepts no new work.
  Stops
  /// A process has the lock. `Silent` can be for a moment only.
  Found(FoundServer)
}

///|
/// Looks one time at the server of an instance. This is the only place that says if a
/// server runs.
async fn look_at(folder : @core.InstanceFolder) -> Look noraise {
  let record = read_record(folder)
  let is_free = lock_is_free(folder) catch {
    // Then only the answer says if the server runs.
    _ => false
  }
  if is_free {
    return NoServer
  }
  match record {
    Known(Running(port~, version~, secret~)) =>
      RunningServer::{ folder, version, port, secret, }.look()
    Newer(format) => Found(NewerFormat(folder.name(), format))
    Known(Failed(..)) | NoRecord => Found(Silent(folder.name()))
  }
}

///|
/// Asks a server that has the lock what it does.
async fn RunningServer::look(self : RunningServer) -> Look noraise {
  let silent = Look::Found(Silent(self.instance()))
  let answer = self.send(Get, "/control/status", status_limit) catch {
    _ => return silent
  }
  if answer.status == 503 {
    return Stops
  }
  try self.views_of(answer) catch {
    // Another program answers.
    _ => silent
  } noraise {
    _ => Found(Answers(self))
  }
}

///|
/// The record of an instance, as a program finds it.
priv enum Record {
  Known(@core.ServerRecord)
  /// The record has this format, which this version does not know.
  Newer(Int32)
  /// The file is absent, damaged or not readable.
  NoRecord
}

///|
/// Reads the record of an instance.
async fn read_record(folder : @core.InstanceFolder) -> Record noraise {
  try {
    let text = retry_in_use(() => @fs.read_file(folder.record()).text())
    @core.ServerRecord::of_text(text)
  } catch {
    @core.ServerRecordError::NewerFormat(format) => Newer(format)
    _ => NoRecord
  } noraise {
    record => Known(record)
  }
}

///|
/// True when no server of the instance runs. It takes the lock for a moment. A start
/// tries the lock for a second, so this does not disturb it.
async fn lock_is_free(folder : @core.InstanceFolder) -> Bool {
  let file = retry_in_use(() => @fs.open(folder.lock(), mode=ReadOnly)) catch {
    error if is_missing(error) => return true
    error => raise error
  }
  defer file.close()
  let is_free = file.try_lock(Shared)
  if is_free {
    file.unlock()
  }
  is_free
}