pellest/src/ws.ml

49 lines
1.5 KiB
OCaml
Raw Normal View History

2022-12-11 18:58:56 +01:00
open Lwt.Syntax
open Shared
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 ->
(* 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* () =
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
| None ->
(* TODO: backup everything to database *)
Dream.close_websocket client
2022-12-11 18:58:56 +01:00
| Some s ->
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
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
| Error msg as e ->
Dream.log "check_action error: %s" msg;
e
2022-12-26 02:06:13 +01:00
| Ok action' ->
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 ()