// The HTTP server and the hub for the views. No other file of the server names
// SignalR (design CON-1): this file has the start and the stop of the HTTP server,
// and gives each request and each call to `Handlers`.

///|
/// The path of the hub.
let hub_path : String = "/hub"

///|
/// The number of calls of one view that run at the same time. With one, a folder
/// that does not answer stops the other calls of the view, and its stop too.
let calls_of_a_view : Int32 = 8

///|
/// What the rest of the server does with requests and calls.
priv struct Handlers {
  /// Whether a request comes to the address of the server, and not from another
  /// site. This is the first question for each request.
  is_same_site : (Request) -> Bool
  /// Whether a request for the hub has the login of a view.
  is_view : (Request) -> Bool
  /// The kind of the view with a view key, after `is_view` accepted the request.
  surface_of : (String) -> @app.Surface?
  /// The event that only this new view gets: its name in the contract and its payload.
  greeting : (@app.Surface) -> (String, Json)?
  /// Answers a request for a path that is not of the hub.
  answer : async (Request) -> Reply
  /// Does a command. The name is the name in the contract.
  call : async (String, Json) -> Json
}

///|
/// A view that is connected to the hub.
priv struct ConnectedView {
  surface : @app.Surface
  connection : @signalr_server.Connection
}

///|
/// The views that are connected to the hub.
priv struct Views {
  /// The keys are the connection IDs.
  connections : Map[String, ConnectedView]
}

///|
/// No views.
fn Views::Views() -> Views {
  { connections: Map([]), }
}

///|
/// The number of views.
fn Views::count(self : Views) -> Int32 {
  self.connections.length()
}

///|
/// Whether a view of this kind is connected.
fn Views::has(self : Views, surface : @app.Surface) -> Bool {
  self.connections.values().any(view => view.surface == surface)
}

///|
/// Sends an event of the contract to each view.
fn Views::publish(self : Views, name : String, payload : Json) -> Unit {
  // A copy, because a connection that ends leaves the map.
  for view in self.connections.values().collect() {
    view.send(name, payload)
  }
}

///|
/// Sends an event of the contract. It does not wait: a view that does not read its
/// events loses its connection, and the other views do not.
fn ConnectedView::send(
  self : ConnectedView,
  name : String,
  payload : Json,
) -> Unit {
  let (name, payload) = (
    @signalr.MethodName::parse(@app.wire_name(name)),
    @signalr.HubValue::from_json(payload),
  ) catch {
    // The names and the types of the contract are always correct.
    error => abort("the event \{name} is not correct: \{error}")
  }
  self.connection.send(name, [payload])
}

///|
/// The identity that SignalR keeps with the connection of a view of this kind. It is
/// the only way to bring the kind from the request to the connection.
fn identity_of(surface : @app.Surface) -> @signalr.Identity raise {
  @signalr.Identity::user(
    @signalr.UserId::parse(
      match surface {
        Browser => "browser"
        Desktop => "desktop"
      },
    ),
  )
}

///|
/// The view of a new connection.
fn ConnectedView::ConnectedView(
  connection : @signalr_server.Connection,
) -> ConnectedView raise {
  let is_window = connection.identity() == identity_of(Desktop)
  { surface: if is_window { Desktop } else { Browser }, connection, }
}

///|
/// The reason why the server does not listen.
priv suberror BindFailure {
  /// Another program uses the port.
  InUse(@core.Port)
  /// A reason of the system, as text to show.
  NoBind(String)
}

///|
/// How long a view can be silent before the server ends its connection, in seconds. A
/// view sends a ping each 15 seconds, but a browser runs the timers of a hidden page
/// only about one time each minute. The time is more than 2 such minutes. The end of a
/// view closes its socket, so the server does not wait for this limit then.
let silent_view_seconds : Int32 = 150

///|
/// An HTTP server with a hub that listens on `127.0.0.1`.
priv struct HubServer {
  server : @signalr_server.Server
  port : @core.Port
  /// The reasons why the system gave no new connection.
  problems : @aqueue.Queue[String]
}

///|
/// Listens on a port, or on a free port. `handlers` gets the port. The server
/// handles requests when `run` runs.
///
/// A port with a program that accepts connections is in use, also when the system
/// permits the bind. Windows lets a program listen on `127.0.0.1:3090` while another
/// one listens on `0.0.0.0:3090` or `[::]:3090`. The server would then take the local
/// connections of the other program.
async fn HubServer::bind(
  port : @core.Port?,
  views~ : Views,
  commands~ : Array[String],
  handlers~ : (@core.Port) -> Handlers,
) -> HubServer {
  if port is Some(port) && accepts_connections(port) {
    raise InUse(port)
  }
  let problems = @aqueue.Queue(kind=DiscardOldest(8))
  let bound : Ref[Handlers?] = Ref(None)
  // No request comes before `run`, and then the handlers are there.
  let get_handlers = () => bound.val.unwrap()
  let endpoint = @signalr.EndpointPath::parse(hub_path)
  let paths = [hub_path, endpoint.negotiate()]
  let options = @signalr_server.ServerOptions::new(
    endpoint,
    parallel_calls=@signalr.CountLimit::of(calls_of_a_view),
    client_timeout=@signalr.TimeLimit::seconds(silent_view_seconds),
    admit=seen => {
      let handlers = get_handlers()
      let request = request_of(seen)
      if !(handlers.is_same_site)(request) {
        Deny("another site")
      } else if paths.contains(request.path) && !(handlers.is_view)(request) {
        Deny("no session")
      } else {
        Admit
      }
    },
    authenticate=credentials => {
      // `admit` accepted the same key before.
      guard credentials.token is Some(key) &&
        (get_handlers().surface_of)(key.expose()) is Some(surface) else {
        raise @signalr.AuthRejected("no session")
      }
      identity_of(surface)
    },
    fallback=seen => {
      let reply = (get_handlers().answer)(request_of(seen))
      @signalr_server.HttpReply::new(
        reply.status.to_int(),
        headers=reply.headers,
        body=reply.body,
      )
    },
    on_event=event => {
      if event is AcceptFailed(reason) {
        ignore(problems.try_put(reason)) catch {
          // Nothing closes the queue.
          _ => ()
        }
      }
    },
  )
  let service = hub_service(
    views,
    commands,
    greeting=surface => (get_handlers().greeting)(surface),
    call=(name, request) => (get_handlers().call)(name, request),
  )
  let number = match port {
    Some(port) => port.to_int()
    None => 0
  }
  let address = @signalr_server.BindAddress::parse("127.0.0.1:\{number}")
  let server = @signalr_server.Server::bind(address, options, service) catch {
    error =>
      match port {
        Some(port) if is_port_in_use(port) => raise InUse(port)
        _ => raise NoBind(error.message())
      }
  }
  let port = @core.Port::Port(@socket.Addr::parse(server.address()).port())
  bound.val = Some(handlers(port))
  { server, port, problems, }
}

///|
/// How long a start waits for a program that can have the port. Windows needs 2
/// seconds to refuse a local connection, and a program that listens accepts at once.
let connect_limit : Duration = Duration(300)

///|
/// True when a program accepts a connection to the port of `127.0.0.1`. The old
/// connections of a server that ended accept nothing.
async fn accepts_connections(port : @core.Port) -> Bool {
  let address = @core_socket.Addr::parse("127.0.0.1:\{port.to_int()}")
  let found = @async.with_timeout_opt(connect_limit.millis(), () => {
    let tcp = @core_socket.Tcp::connect(address)
    defer tcp.close()
    // Linux can connect a socket to itself when it gives it the same port.
    tcp.local_addr() != address
  }) catch {
    _ => None
  }
  found is Some(true)
}

///|
/// True when a program has the port, or when Windows does not give the port
/// to programs. The failure of `Server::bind` has only a text, so this function
/// tries the port again.
async fn is_port_in_use(port : @core.Port) -> Bool {
  let address = @socket.Addr::parse("127.0.0.1:\{port.to_int()}")
  try @socket.TcpServer(address, reuse_addr=true) catch {
    @os_error.OSError(code, ..) =>
      match @async.platform {
        Linux => code == 98
        MacOS => code == 48
        // WSAEADDRINUSE and WSAEACCES.
        Windows => code is (10048 | 10013)
      }
    _ => false
  } noraise {
    probe => {
      probe.close()
      false
    }
  }
}

///|
/// A request as the rest of the server sees it.
fn request_of(request : @signalr_server.HttpRequest) -> Request {
  {
    method_: match request.method_() {
      Get => Get
      Post => Post
      _ => Other
    },
    path: request.path(),
    query: name => request.query(name),
    header: name => request.header(name),
  }
}

///|
/// The hub: one method for each command of the contract, with one JSON value in
/// and one out.
fn hub_service(
  views : Views,
  commands : Array[String],
  greeting~ : (@app.Surface) -> (String, Json)?,
  call~ : async (String, Json) -> Json,
) -> @signalr_server.HubService raise {
  let names : Map[@signalr.MethodName, String] = Map([])
  let mut contract = @signalr.HubContract::new(
    @signalr.HubName::parse("mission-control"),
  )
  for command in commands {
    let name = @signalr.MethodName::parse(@app.wire_name(command))
    names[name] = command
    contract = contract.server(
      @signalr.HubMethod::call(
        name,
        @signalr.args1(@signalr.hub_value()),
        @signalr.hub_value(),
      ),
    )
  }
  @signalr_server.HubService::new(
    contract,
    connected=connection => {
      let view = ConnectedView(connection)
      views.connections[connection.connection_id().to_string()] = view
      if greeting(view.surface) is Some((name, payload)) {
        view.send(name, payload)
      }
    },
    disconnected=(connection, _) => {
      views.connections.remove(connection.connection_id().to_string())
    },
    invoke=(_, invocation) => {
      // The contract checked the name and the number of arguments.
      let command = names.get(invocation.target).unwrap()
      let request = invocation.arguments[0]
      if is_deeper(request, levels_of_a_request) {
        raise @signalr.HubError(
          "The request of \{command} is wrong: it has too many levels.",
        )
      }
      // There is no wait between the call and the end of this function, so a reply
      // is not older than an event that a view got before it.
      let reply = call(command, request.to_json()) catch {
        Refusal(text) => raise @signalr.HubError(text)
        BadRequest(text) =>
          raise @signalr.HubError("The request of \{command} is wrong: \{text}")
        error => raise error
      }
      Some(@signalr.HubValue::from_json(reply))
    },
  )
}

///|
/// The levels of arrays and objects that the request of a view can have. The
/// contract needs two. SignalR permits 64 levels in a message, and closes the
/// connection of a view that sends more. This limit gives the view a reply.
let levels_of_a_request : Int32 = 16

///|
/// True when a value has more levels of arrays and objects than `levels`.
fn is_deeper(value : @signalr.HubValue, levels : Int32) -> Bool {
  match value {
    Array(items) =>
      levels == 0 || items.iter().any(item => is_deeper(item, levels - 1))
    Map(map) =>
      levels == 0 || map.iter().any(entry => is_deeper(entry.1, levels - 1))
    _ => false
  }
}

///|
/// Handles requests until `stop`. Raises when the system gives no new connection
/// for a minute. Then the server is closed, and `stop` must not run.
///
/// `log` gets a text each time when the system gives no new connection. It never
/// gets a request, because an address can have a secret.
async fn HubServer::run(
  self : HubServer,
  log : async (String) -> Unit noraise,
) -> Unit {
  @async.with_task_group(group => {
    group.spawn_bg(no_wait=true, () => {
      for ;; {
        log("The server cannot accept a connection: \{self.problems.get()}")
      }
    })
    self.server.run()
  })
}

///|
/// Ends the connection of each view and closes the port. A call of a view that runs
/// has the limit to finish.
async fn HubServer::stop(self : HubServer, limit : Duration) -> Unit {
  // SignalR has no limit of 0.
  let drain_limit = @signalr.TimeLimit::milliseconds(
    limit.millis().max(1).to_int64(),
  )
  self.server.stop(drain_limit~) |> ignore
}