2022-12-11 18:58:56 +01:00
|
|
|
open Lwt.Syntax
|
|
|
|
|
open Shared
|
|
|
|
|
|
2023-01-08 04:10:15 +01:00
|
|
|
let get_state_unsafe user_id =
|
|
|
|
|
match User.get_state user_id with
|
|
|
|
|
| Error _e -> assert false
|
|
|
|
|
| Ok state -> state
|
|
|
|
|
|
2022-12-11 18:58:56 +01:00
|
|
|
let handle_client request client =
|
|
|
|
|
match Dream.session "user_id" request with
|
|
|
|
|
| None -> Dream.log "User does not exists" |> Lwt.return
|
|
|
|
|
| Some user_id ->
|
2023-01-08 04:10:15 +01:00
|
|
|
(* send user island state for the first time *)
|
|
|
|
|
let state = get_state_unsafe user_id in
|
2022-12-26 02:06:13 +01:00
|
|
|
let* () =
|
2023-01-08 04:10:15 +01:00
|
|
|
Dream.send ~text_or_binary:`Text client
|
|
|
|
|
(Network.marshal (Network.Full_state state))
|
2022-12-26 02:06:13 +01:00
|
|
|
in
|
2022-12-11 18:58:56 +01:00
|
|
|
|
2023-01-07 23:15:03 +01:00
|
|
|
let rec loop () =
|
2022-12-11 18:58:56 +01:00
|
|
|
match%lwt Dream.receive client with
|
2023-01-08 04:10:15 +01:00
|
|
|
| None ->
|
|
|
|
|
(* TODO: backup everything to database *)
|
|
|
|
|
Dream.close_websocket client
|
2022-12-11 18:58:56 +01:00
|
|
|
| Some s ->
|
2023-01-08 04:10:15 +01:00
|
|
|
let state = get_state_unsafe user_id in
|
2022-12-26 02:06:13 +01:00
|
|
|
let (Network.Action_msg action : Network.client_message) =
|
|
|
|
|
Network.unmarshal s
|
|
|
|
|
in
|
2023-01-08 04:10:15 +01:00
|
|
|
Dream.log "checking action %a" State.pp_action action;
|
|
|
|
|
Dream.log "current state %a" State.pp state;
|
2023-01-07 23:15:03 +01:00
|
|
|
let res =
|
2022-12-26 02:06:13 +01:00
|
|
|
match State.check_action state action with
|
2023-01-08 04:10:15 +01:00
|
|
|
| Error msg as e ->
|
|
|
|
|
Dream.log "check_action error: %s" msg;
|
|
|
|
|
e
|
2022-12-26 02:06:13 +01:00
|
|
|
| Ok action' ->
|
2023-01-08 04:10:15 +01:00
|
|
|
Dream.log "check_action ok: %a" State.pp_action' action';
|
2022-12-26 02:06:13 +01:00
|
|
|
let state = State.perform_action state action' in
|
|
|
|
|
User.set_state user_id state;
|
2023-01-07 23:15:03 +01:00
|
|
|
Ok action'
|
2022-12-26 02:06:13 +01:00
|
|
|
in
|
|
|
|
|
let* () =
|
|
|
|
|
Dream.send client (Network.marshal (Network.Update_result res))
|
|
|
|
|
in
|
2023-01-07 23:15:03 +01:00
|
|
|
loop ()
|
2022-12-11 18:58:56 +01:00
|
|
|
in
|
2023-01-07 23:15:03 +01:00
|
|
|
loop ()
|