From 25deeec162748b8066ff6783eb480acf573ab210 Mon Sep 17 00:00:00 2001 From: Mikko Ahlroth Date: Thu, 4 Jul 2024 22:58:03 +0300 Subject: [PATCH] Working, living actor --- backend/src/aurinko/updater.gleam | 50 +++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/backend/src/aurinko/updater.gleam b/backend/src/aurinko/updater.gleam index 13038c0..2f4ad3b 100644 --- a/backend/src/aurinko/updater.gleam +++ b/backend/src/aurinko/updater.gleam @@ -5,6 +5,8 @@ import birl/duration import biscotto import gleam/dict import gleam/dynamic +import gleam/erlang/process +import gleam/io import gleam/list import gleam/option import gleam/order @@ -12,10 +14,13 @@ import gleam/otp/actor import gleam/result import gleamy/red_black_tree_set.{type Set} +const update_interval = 10_000 + const login_cookie_expiry = 86_400 pub type Message { Update + PeriodicUpdate } pub type ProductionInfo = @@ -65,6 +70,7 @@ pub type State { credentials: Credentials, inner: InnerState, error: option.Option(UpdateError), + self_subject: process.Subject(Message), ) } @@ -74,17 +80,49 @@ pub type UpdateError { } pub fn start(username: String, password: String) { - actor.start( - State(Credentials(username, password), Pending, option.None), - handle_message, - ) + let spec = + actor.Spec( + init: fn() { + let self_subject = process.new_subject() + let selector = + process.new_selector() |> process.selecting(self_subject, fn(a) { a }) + + process.send_after(self_subject, update_interval, PeriodicUpdate) + + actor.Ready( + state: State( + Credentials(username, password), + Pending, + option.None, + self_subject, + ), + selector: selector, + ) + }, + init_timeout: 5000, + loop: handle_message, + ) + + actor.start_spec(spec) } fn handle_message(message: Message, state: State) -> actor.Next(Message, State) { let next = with_initialised_state(state, fn(credentials, inner_state) { case message { - Update -> { + PeriodicUpdate -> { + process.send_after( + state.self_subject, + update_interval, + PeriodicUpdate, + ) + Nil + } + Update -> Nil + } + + case message { + Update | PeriodicUpdate -> { use new_state <- result.try(update(credentials, inner_state)) Ok(actor.continue(State(..state, inner: Initialised(new_state)))) @@ -92,6 +130,8 @@ fn handle_message(message: Message, state: State) -> actor.Next(Message, State) } }) + io.debug(#("Next state", next)) + case next { Ok(next) -> next Error(err) -> {