class Agent(T)

Defined in:

agent.cr

Constant Summary

DefaultTimeout = 5.seconds
SubmittedInst = Submitted.new
TimeoutExceptionInst = TimeoutException.new
TimeoutInst = Timeout.new

Constructors

Instance Method Summary

Constructor Detail

def self.new(state : T) #

Creates an Agent wrapping @state.

Agents are fiber-based, i.e. each Agent runs a fiber and serialises access and update requests over a channel. This guarantees thread-safety and data consistency within Agent's operations.


[View source]

Instance Method Detail

def get(max_time = DefaultTimeout) : T | Result #

Fetches the state of the Agent.

This is equivalent to get(max_time, &id), where id is the identity function.


[View source]
def get(max_time = DefaultTimeout, &fn : T -> Q) : Q | Result forall Q #

Fetches the state of the Agent and applies the given function to it.

This is equivalent to calling Agent#get_and_update, where fn does not update the current state. the current state.


[View source]
def get!(max_time = DefaultTimeout) : T #

Fetches the state of the Agent.

Analogous Agent#get, but an exception is raised in case of timeout.

NOTE the compile-time type of the returned value is T, rather than T | Agent::Result.


[View source]
def get!(max_time = DefaultTimeout, &fn : T -> Q) : Q forall Q #

Fetches the state of the Agent and applies the given function to it.

Analogous Agent#get, but an exception is raised in case of timeout or if an exception is raised within the block.

NOTE the compile-time type of the returned value is Q, rather than Q | Agent::Result.


[View source]
def get_and_update(max_time = DefaultTimeout, &fn : T -> Tuple(Q, T)) : Q | Result forall Q #

Fetches the state of the Agent, updates it and returns the first projection of fn.call(state).

If the #get_and_update request is not handled by the Agent's fiber within max_time, then an Agent::Result::Timeout is returned. If an error is raised during the execution of the block, then an Agent::Result::Error is returned. Otherwise, the transformed state fn.call(state).first, and the state is updated to fn.call(state).last.


[View source]
def get_and_update!(max_time = DefaultTimeout, &fn : T -> Tuple(Q, T)) : Q forall Q #

Fetches the state of the Agent, updates it and returns the first projection of fn.call(state).

Analogous Agent#get_and_update, but an exception is raised in case of timeout or if an exception is raised within the block.

NOTE the compile-time type of the returned value is Q, rather than Q | Agent::Result.


[View source]
def update(max_time = DefaultTimeout, &fn : T -> T) : Result #

Updates the state of the Agent.

Returns Agent::Result::Submitted, if the update operation was accepted. Returns Agent::Result::Timeout, if a timeout is triggered before the operation is accepted by the Agent's fiber.

NOTE #update does not wait for fn to be applied to the Agent's state before returning.


[View source]