daemon/fetch.bend

cswap-bend-cli@0.1.0.0 · 60 lines · 10 definitions

1import Base
2import cswap-bend-cli@0.1.0.0/act.bend as Act
3import cswap-bend-cli@0.1.0.0/store/base.bend as SBase
4import cswap-bend-cli@0.1.0.0/collect.bend as Collect
5import cswap-bend-cli@0.1.0.0/collectrun.bend as CRun
6import cswap-bend-cli@0.1.0.0/view.bend as View
7import cswap-bend-cli@0.1.0.0/policy/types.bend as T
8import cswap-bend-cli@0.1.0.0/daemon/config.bend as Cfg
9import cswap-bend-cli@0.1.0.0/daemon/gather.bend as G
10
11# Fetch the accounts a tick decided to poll and merge each outcome into
12# cache/usage.json. This is the CLI's collector (collectrun.collect): it leases
13# the rows, fetches (gated refresh for inactive accounts), plans the next poll
14# with the proved policy and writes under cache/.usage.lock. There is no second
15# usage store.
16
17def ActM(-A: Type) -> Type:
18  Act.of(A)
19
20def ActM.pure(-A: Type, x: A) -> Act.of(A):
21  Act.pure(A, x)
22
23def ActM.bind(-A: Type, -B: Type, m: Act.of(A), f: A -> Act.of(B)) -> Act.of(B):
24  Act.bind(A, B, m, f)
25
26def disabled_of(+a: T.Account) -> Bool:
27  match a:
28    case T.Account{n, e, k, d}:
29      d
30
31def is_active(+slot: String, +active: Maybe<&2, String>) -> Bool:
32  match active:
33    case Some{a}:
34      String.eq(slot, a)
35    case None{}:
36      False{}
37
38def info_of(+e: G.Ent, +active: Maybe<&2, String>) -> Collect.Info:
39  match e:
40    case G.Ent{+slot, email, org, creds, acct}:
41      Collect.Info{Maybe.default(&2, U32, U32.read(slot), 0), email, "", org, "", disabled_of(acct), is_active(slot, active), creds}
42
43def infos(+es: List<&2, G.Ent>, +active: Maybe<&2, String>) -> List<&2, Collect.Info>:
44  match es:
45    case Nil{}:
46      []
47    case Con{e, t}:
48      info_of(e, active) <> infos(t, active)
49
50# The threshold in tenths of a percent, as the collector wants it.
51def tenths(+cfg: Cfg.Cfg) -> U32:
52  (Cfg.cfg_threshold(cfg) / 10 : U32)
53
54def discard(+rs: List<&2, View.Acct>) -> Act.of(Unit):
55  Act.pure(Unit, Unit{})
56
57def fetch_all(+ctx: SBase.Ctx, +cfg: Cfg.Cfg, +es: List<&2, G.Ent>, +active: Maybe<&2, String>, +now: U32) -> Act.of(Unit):
58  do ActM<Unit>:
59    rs : List<&2, View.Acct> <- CRun.collect(ctx, infos(es, active), now, Cfg.cfg_models(cfg), tenths(cfg), U32.to_nat(now))
60    discard(rs)