Working, living actor

This commit is contained in:
Mikko Ahlroth 2024-07-04 22:58:03 +03:00
parent 3e809e360b
commit 25deeec162

View file

@ -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) -> {