Sagas & Monitoring

Sagas

A saga is a sequence of steps over a state, each with an execute and maybe a compensate. When a step fails, the saga’s failure handler decides by the failure: undo the completed steps in reverse, do nothing, or recover its own way.

import Saga.Saga

data Trip = Trip { booked :: [String] }

booking :: String -> SagaStep Trip
booking what = step what (\t -> Right t { booked = L.append t.booked [what] }) (\t -> ())

refusing :: String -> SagaStep Trip
refusing what = stepOnly what (\t -> Left (Fault "SoldOut" what))

onFailure :: Fault -> OnFailure Trip
onFailure f = case f of
  Fault "SoldOut" detail -> CompensateInReverse
  _                      -> NoCompensation

runSaga (saga "trip" [Single (booking "flight"), Single (booking "hotel")] onFailure) (Trip [])
-- Right (Trip ["flight", "hotel"])
runSaga (saga "trip" [Single (booking "flight"), Single (refusing "hotel")] onFailure) (Trip [])
-- Left (Fault "SoldOut" "hotel"), the flight's compensate run
Piece Meaning
step name execute compensate A step that can be undone
stepOnly name execute A step with nothing to undo
Single step A stage of one step
Together steps merge Steps run in parallel; their states merged by merge
CompensateInReverse Undo every completed step, last first
NoCompensation Leave what was done
Recover handler Run your own recovery with the fault

Decorators

retryWithBackoff 3 100 step                       -- up to 3 tries, waiting 100 ms, then 200 ms
circuitBreaker (breakerCells ()) 5 30000 step     -- refused after 5 failures in a row, for 30 s

A breaker’s counts live in transactional cells (breakerCells ()), so they outlast one run of the saga; share the cells between runs that call the same dependency.

Metrics

Monitoring.Metrics keeps counters, gauges and histograms by name and labels in an actor, and renders them in the Prometheus text format:

import Monitoring.Metrics

case metricsRegistry system of
  m -> case incrementCounter m "orders_total" [("kind", "express")] 1 of
    _ -> case setGauge m "queue_depth" [] 12 of
      _ -> case observeMicros m "order_duration_seconds" [] 1800 of     -- a histogram, in microseconds
        _ -> valueOf m "orders_total" [("kind", "express")]            -- 1

prometheusText m renders every series for a /metrics endpoint.

An actor can be measured as a whole: @Mon.instrumented(metrics, "console") on a behaviour counts mlambda_actor_messages_total, times mlambda_actor_message_duration_seconds, and counts mlambda_actor_errors_total by failure kind.

Tracing

Monitoring.Tracing records spans: a trace, an id, a parent, a name, tags, a start and an end, and whether it failed. A tracer actor keeps the finished ones and renders them as Zipkin JSON, which Jaeger reads.

import Monitoring.Tracing

case tracer system of
  tr -> case rootSpan "checkout" [("order", "o-17")] of
    root -> case childSpan root "charge" [] of
      charge -> case finish tr (ended False [] charge) of
        _ -> case finish tr (ended False [] root) of
          _ -> zipkinJson "orders-service" (finishedSpans tr)

ended failed tags span closes a span, marking it failed or not and adding tags.

runInstrumented tracer metrics saga state runs a saga with a saga.execute span and one saga.step.execute child per step, and records mlambda_saga_total, mlambda_saga_steps_total and mlambda_saga_duration_seconds.

Diagnostics

Diagnostic.Diagnostic collects what happened to a request, by request id, and reports it:

import Diagnostic.Diagnostic

case diagnostics system of
  d -> case record d "req-1" (info "Route" "dispatched to satellite-1") of
    _ -> case record d "req-1" (errorEvent "Worker" "no answer" "Timeout") of
      _ -> reportAnalysis (report d "req-1")
-- "FAILED -- 1 error(s): Timeout: no answer"

info category message and errorEvent category message kind make the events; a report has the count, the errors, the flow and the analysis (OK -- 3 events across [Route, Worker] when nothing failed).

Sequencing effects

The examples bind each effect with case … of, which runs it before what follows. Effects passed as sibling arguments to one function run in no promised order, and a let may be moved to where its name is used; use case or >> when order matters.