Author SHA1 Message Date
MasseR 5f8b3cbe00 Refactor to a more arrows style syntax 2026-10-24 00:18:04 +03:00
MasseR 078f24e4b9 Fix tests and add tests for kitchen lights 2026-10-23 23:57:05 +03:00
MasseR 15e50322c4 Making the controllers more linear
Basically, the idea of `(oneBranch <> secondBranch)` instead of

```
do
x <- foo
case x of
  ...
```
2026-10-23 22:55:06 +03:00
MasseR 617bd255ff Diagrams 2026-10-23 16:00:19 +03:00
MasseR 022342af32 Make the type variable 2026-10-22 12:17:58 +03:00
MasseR 6caa2acafb Merge pull request 'Statistics page' (#7) from statistics-page into main
Reviewed-on: #7
2026-10-12 16:06:16 +03:00
MasseR 7d5103ac90 Pretty 2026-10-12 16:05:32 +03:00
MasseR 3a6fe26d0c List of ranges 2026-10-12 15:17:07 +03:00
MasseR 45277e02da htmx flags 2026-10-12 14:55:30 +03:00
MasseR 87dda96e7e Simple HTML responses 2026-10-12 13:28:54 +03:00
MasseR 55855db55b Try a separate holdKnown primitive 2026-10-12 11:11:37 +03:00
MasseR 8a4a5aef33 Filter setup 2026-10-09 14:50:15 +03:00
MasseR d33c2cf268 Reads better 2026-10-08 13:45:12 +03:00
MasseR 7bd0a652cb Clean hlint and cabal warnings 2026-10-02 15:42:12 +03:00
MasseR 449f404464 Review notes docs tweaks 2026-10-02 15:13:54 +03:00
MasseR 0e5d76901d Bound note header parsing 2026-10-02 15:13:04 +03:00
MasseR 773f3b550f Review notes docs 2026-10-02 14:47:46 +03:00
MasseR 4664e71493 Review note push 2026-10-02 14:45:17 +03:00
MasseR e7adb3e88b Latest review note 2026-10-02 14:41:26 +03:00
MasseR 2e2960c159 Review note script 2026-10-02 14:36:46 +03:00
MasseR 627f813859 Spec: verification wording matches scan-based latest 2026-10-02 14:31:49 +03:00
MasseR e750e0e687 Spec: latest scans notes by branch and round 2026-10-02 14:29:56 +03:00
MasseR 63210afc7b Track superpowers specs, ignore plans 2026-10-02 14:23:40 +03:00
MasseR 7ec491d383 Review notes protocol design 2026-10-02 14:22:24 +03:00
MasseR 4f1277aa45 Worktrees 2026-10-02 12:29:56 +03:00
MasseR 3908d5a3a6 REVIEW guidelines 2026-10-02 12:28:23 +03:00
MasseR 5416e9b708 Safer default 2026-10-01 21:57:47 +03:00
MasseR 38d575d716 I don't need these log lines anymore 2026-10-01 21:16:23 +03:00
MasseR 6bcab1a0d8 Update tests 2026-09-30 15:01:17 +03:00
MasseR cceddad037 Capped based on light level 2026-09-30 14:27:50 +03:00
MasseR c75fc1a7b9 Logging and really not working light restoration 2026-09-30 13:46:16 +03:00
MasseR 1098be227d Push to journalctl 2026-09-30 12:33:31 +03:00
MasseR a427acd6ed Fix warnings 2026-09-30 09:05:48 +03:00
MasseR aee34f4e14 Make flag-decision tests fail fast and assert the outbound metric 2026-09-30 08:57:40 +03:00
MasseR 526710ef71 Simplify channelHassEval now that the writer owns the flag decision 2026-09-30 08:56:07 +03:00
MasseR c2425e8fb0 Move handler flag check from bus to writer with skip logging 2026-09-30 08:06:59 +03:00
MasseR a7a11e96b7 Complete rename vocabulary (childrenBedroomButton, toIkeaRemoteAction) 2026-09-30 00:21:24 +03:00
MasseR adce7c8427 Split Controller.hs into vertical submodules behind umbrella re-export 2026-09-30 00:07:31 +03:00
MasseR 9e00aeb6a2 Rename entity-list and snapshot helpers for consistency 2026-09-29 23:52:46 +03:00
MasseR b643fe55b1 Rename switch to switchService to avoid AFRP name conflict 2026-09-29 23:47:58 +03:00
MasseR 138b62c54a Rename IkeaController to IkeaRemoteAction, fix brightness typo 2026-09-29 23:44:56 +03:00
MasseR 889091d321 Regenerate default.nix (data-default was missing from the derivation) 2026-09-29 23:40:20 +03:00
MasseR c2426dec3d Unify per-room Lights enums into shared LightingMode 2026-09-29 23:38:43 +03:00
MasseR ad023a1ba2 Rename light observation layer (LightStatus, lightSignal, brightness, temperature) 2026-09-29 23:19:34 +03:00
MasseR 7ce994e814 Rename light command layer (Light, LightSettings, BrightnessSettings) 2026-09-29 23:14:07 +03:00
MasseR fefeae6301 Store a custom snapshot of lights 2026-09-29 22:51:37 +03:00
MasseR fcaccfdeb0 Faster transition 2026-09-29 20:42:14 +03:00
MasseR 73d4255fd7 Update tests 2026-09-29 20:01:03 +03:00
MasseR 7ad36d8ccb More transition stuff 2026-09-29 19:48:16 +03:00
MasseR f4c82df968 Scene transitions 2026-09-29 18:05:51 +03:00
MasseR 219f75c0e4 Remove the debug line
I thought I already had..?
2026-09-29 11:35:24 +03:00
MasseR 7ed846d0fc Fix the ambience mode 2026-09-29 11:33:56 +03:00
MasseR 53c36a81de Trial age 2026-09-25 13:55:29 +03:00
MasseR 1bf2258167 Merge branch 'runtime-flags': runtime handler toggling 2026-09-25 13:17:08 +03:00
MasseR 4d8cb8dc36 Log and return 500 when handler flag persistence fails 2026-09-25 13:14:25 +03:00
MasseR 1697d55ad5 Drop build-time controller flag, run all controllers, consolidate paths 2026-09-25 13:10:26 +03:00
MasseR bd1402ab3a Add REST endpoints for handler flags 2026-09-25 13:09:25 +03:00
MasseR c412435172 Gate CallService by handler flags on the Bus 2026-09-25 13:07:40 +03:00
MasseR 3b08988e30 Route Flags load warnings to stderr 2026-09-25 13:02:14 +03:00
MasseR 44497173de Add Flags module for runtime handler toggling 2026-09-25 13:01:44 +03:00
MasseR 894d8f8436 Add requestHandler field to Request 2026-09-25 12:59:14 +03:00
MasseR bd5f97f96e Merge pull request 'Replace scotty with servant' (#4) from servant into main
Reviewed-on: #4
2026-09-25 12:10:58 +03:00
MasseR d6f785662b Logging in http 2026-09-25 12:10:24 +03:00
MasseR 5d16bf4ade Move http to separate module 2026-09-25 11:54:36 +03:00
MasseR 05bd609c7e Replace scotty with servant 2026-09-25 11:48:42 +03:00
MasseR 4ea75beb7b Merge pull request 'Plant lights' (#3) from plant-light into main
Reviewed-on: #3
2026-09-25 10:37:26 +03:00
MasseR 96d3482af8 Merge pull request 'Use scenes instead of stateful applications of adaptive sleep mode' (#2) from bedroom-sleep-mode-via-scenes into main
Reviewed-on: #2
2026-09-25 10:37:20 +03:00
MasseR 7fc07c1883 Plant lights 2026-09-25 10:31:06 +03:00
MasseR a7becaf2d4 Use scenes instead of stateful applications of adaptive sleep mode 2026-09-25 09:55:48 +03:00
MasseR 9c47bbcb42 More 2026-09-24 20:27:11 +03:00
MasseR 6063aafe8b Toggle adaptive mode 2026-09-24 20:21:33 +03:00
MasseR fafc7111bb The center button also disables sleep mode 2026-09-24 10:07:02 +03:00
MasseR 69cac934ec Fix tests 2026-09-24 10:06:20 +03:00
MasseR b2a74cbee4 Sleep mode in the bedroom 2026-09-24 09:48:35 +03:00
MasseR 769ab43fd2 Untested three-state for dinner table 2026-09-24 08:17:22 +03:00
MasseR 15f3fe7c9e Hups 2026-09-21 18:59:32 +03:00
MasseR 416a9484a5 Listen on 0.0.0.0 to be usable by tailscale 2026-09-21 08:11:49 +03:00
MasseR e3bc25ce54 Quick buttons 2026-09-17 11:48:22 +03:00
MasseR 036473ab81 Don't catch async exceptions 2026-09-17 11:05:27 +03:00
MasseR 27f271691c Hallway lights automation 2026-09-17 09:57:12 +03:00
MasseR 73d546395b Fix the bad use of async
Propagate errors with `mapConcurrently_`
2026-09-16 14:54:36 +03:00
MasseR a969730de1 Update tests 2026-09-16 14:52:39 +03:00
MasseR 213f9d5d2a More graphs 2026-09-16 14:42:31 +03:00
MasseR 2cb8035ef4 Increase the backoff 2026-09-16 12:51:58 +03:00
MasseR 1ec8c7211f Render ratelimiter 2026-09-16 12:32:32 +03:00
MasseR 3d7f6cb3c6 Fix supervisor and proper rate limiting 2026-09-16 12:28:48 +03:00
MasseR 64561718a5 Bedroom spec and partially fix writing
LLM had done "rate limiting" via deduplicating outbound calls. But the
ordering matters..
2026-09-16 10:52:10 +03:00
MasseR 7570711768 Enable bedroom presence controller 2026-09-16 09:56:12 +03:00
MasseR 7c2cfde814 Livingroom lights 2026-09-16 09:47:49 +03:00
MasseR 9fda48f589 runtime: reject out-of-range HA_METRICS_PORT values 2026-09-15 22:27:20 +03:00
MasseR 319104641b runtime: start the metrics graph server worker 2026-09-15 22:09:45 +03:00
MasseR 9861266c1e graphing: serve rrdtool graphs over http 2026-09-15 22:06:25 +03:00
MasseR 0893862f3a graphing: add pure graph table, ranges, and argv builders 2026-09-15 22:01:13 +03:00
MasseR 6078a64d00 Merge branch 'feature/trigger-service-metrics' 2026-09-15 17:31:06 +03:00
MasseR 7d08acec9d runtime: count only trigger event frames and harden metrics tests 2026-09-15 17:25:31 +03:00
MasseR 2a477b4977 runtime: increment trigger/service counters on the bus 2026-09-15 16:34:35 +03:00
MasseR 09479b5c48 metrics: register inbound-trigger and outbound-service counters 2026-09-15 16:26:09 +03:00
MasseR a19e5afd5e metrics: detect rrd schema mismatch and recreate with backup 2026-09-15 16:20:37 +03:00
MasseR af46776bb0 Enable bedroom buttons 2026-09-15 16:03:28 +03:00
MasseR d1bdd2eb67 Dinner presence 2026-09-15 10:49:12 +03:00
MasseR 9108ba9c8f Merge pull request 'Control the kitchen lights' (#1) from kitchen-lights into main
Reviewed-on: #1
2026-09-14 14:47:18 +03:00
MasseR 0f7c6ff98a Control the kitchen lights 2026-09-14 14:45:45 +03:00
MasseR aaba917a9b Test the SerializeUTCTime property 2026-09-12 20:25:24 +03:00
MasseR a3dd63f26c Update tests 2026-09-12 20:18:13 +03:00
MasseR b20320c779 Explicit state 2026-09-12 20:09:42 +03:00
MasseR e16010bf2f Backport serializable arrow 2026-09-12 16:27:12 +03:00
MasseR 1f786815e6 Laws 2026-09-12 12:25:02 +03:00
MasseR 54ef6b5cc3 Merge branch 'mem-leak' 2026-09-08 08:00:13 +03:00
MasseR 1edb2ac5a2 Fix memory memory leak
- Tuple to strict pair
- Self-recursive loops with more knot tying <- this was the thing
2026-09-08 07:58:50 +03:00
MasseR d3518e8ff2 Fix: rrdtool DS names must be <= 19 chars
sanitizeName now keeps the first 15 chars plus a 3-hex hash suffix
for names longer than 19 chars (rrdtool's hard limit on DS name
length). The previous replace-dots-only version produced names up to
31 chars, which rrdtool rejected with 'invalid DS format'.
2026-09-07 23:09:42 +03:00
MasseR e30a28c9ef Merge feat/ekg-rrd-metrics: ekg-core RTS metrics -> rrd export 2026-09-07 21:44:56 +03:00
MasseR f7849ac889 defaultMain: wire metricsAction worker and enable -with-rtsopts=-T 2026-09-07 21:37:17 +03:00
MasseR 0a4b7dbb01 Add metricsAction: supervised loop sampling ekg store to rrd via rrdtool 2026-09-07 21:34:15 +03:00
MasseR 88af6a3139 Add Metrics module: pure rrdtool argv builders for ekg samples 2026-09-07 21:30:42 +03:00
MasseR 055c02d0f2 flake: add rrdtool to devShell and wrap the shipped binary with HA_RRDTOOL 2026-09-07 21:24:42 +03:00
MasseR 7b6b529120 Merge feat/outbound-rate-limiting: drop excess outbound calls 2026-08-25 19:46:13 +03:00
MasseR ef4811f89b Drop redundant UUID import from ConnectionSpec 2026-08-25 19:39:40 +03:00
MasseR 9fadbae777 writerAction: drain, dedupe, and rate-limit outbound calls 2026-08-25 19:37:57 +03:00
MasseR 3f5aa4735c Add dedupeBatch: collapse outbound calls per target 2026-08-25 19:33:44 +03:00
MasseR 6bb96833e1 A lot of internals as I tried to do a switch based logic 2026-08-25 19:05:52 +03:00
MasseR 2730657952 Triggers instead of full state events 2026-08-25 13:13:50 +03:00
MasseR 771d702abd Test the bedroom spec 2026-08-25 12:41:42 +03:00
MasseR 7051eaf244 Test rest of the AFRP 2026-08-25 11:41:12 +03:00
MasseR 7a9f30e1be Tests with timers 2026-08-25 11:36:13 +03:00
MasseR aa8ea07249 Tests 2026-08-25 11:27:18 +03:00
MasseR 2664ca67c0 Debounce instead of delay 2026-08-25 10:47:38 +03:00
MasseR d341270ed1 rollup, sliding and fixed windows 2026-08-25 10:11:44 +03:00
MasseR dc55834507 Outdated comment 2026-08-21 16:21:08 +03:00
MasseR 50c82393ed Clean tests 2026-08-21 16:01:15 +03:00
MasseR 96d4fb4c8d HUmidifier logic with some extra new primitives 2026-08-21 15:46:31 +03:00
MasseR 8ea013c94a Fix debug ordering 2026-08-21 15:46:18 +03:00
MasseR c60508fd0c Severity level 2026-08-21 13:55:22 +03:00
59 changed files with 5211 additions and 636 deletions

No files matched your search

+7 -1
View File
@@ -4,4 +4,10 @@ dist-newstyle
.worktrees/ .worktrees/
docs/superpowers docs/superpowers/plans
*.hp
*.eventlog
*.eventlog.html
*.rrd
*.rrd.*bak*
+5 -1
View File
@@ -1,3 +1,7 @@
creation_rules: creation_rules:
- path_regex: "secrets.yaml" - path_regex: "secrets.yaml"
pgp: "95DBE64C2EA64D6B0E0C8C2F9DE6E04ED1918118" age:
# usb-c yubikey
- "age1yubikey1qw7m7rad6malegqypgntr7qmu97xrxxurp0c00s23263nuxnpek6w0jye60"
# usb-a yubikey
- "age1yubikey1qdnx7jum6k4fzenkqj8y5met9hyq6lqxrpzrl2788wr0q445vhupzuqtpk0"
+11
View File
@@ -5,11 +5,17 @@
A sidecar for Home Assistant that runs automations using arrowized functional A sidecar for Home Assistant that runs automations using arrowized functional
reactive programming (AFRP). Haskell, built with cabal. reactive programming (AFRP). Haskell, built with cabal.
## Working style
- When doing any non-trivial work, always work in a worktree on a feature branch
- Feature branches should be named as the topic of the change
## Code style ## Code style
- Vertical modules: split by feature/concept, not by layer. - Vertical modules: split by feature/concept, not by layer.
- Comments are minimal. They describe the contract, not the implementation, - Comments are minimal. They describe the contract, not the implementation,
and should stay stable as the implementation changes. and should stay stable as the implementation changes.
- Never ever log directly to stdout via `putStr` and friends. Always use proper logging functions
## Build ## Build
@@ -24,3 +30,8 @@ reactive programming (AFRP). Haskell, built with cabal.
- hspec for unit tests, hedgehog for property tests. - hspec for unit tests, hedgehog for property tests.
- Run with `nix develop -c cabal test`. - Run with `nix develop -c cabal test`.
## Reviewing
Reviews are recorded in git notes under `refs/notes/review`; read the latest
note before reviewing. See [[REVIEW.md]].
+49
View File
@@ -0,0 +1,49 @@
# Code Review Guidelines
- Each MR should be focused, changing only one concept at a time
- Keep MRs small - aim for under 500 lines of diff. There can be some wiggle room for cases that are hard to split
- When reviewing code, check for test coverage and suggest tests if missing
- Go through tests and think hard to see if any unit tests or group of unit tests can be replaced with a property test
- When suggesting a property test, consider cases that the property needs to falsify and whether it needs its own generator
- Business logic stays pure
## Comments
- Less is more
- If there's comments for a function, verify they're proper haddock style
- If there's comments for a function, they must only be about the contract and use instructions
- If there's comments for implementation, they should only be for exceptional cases, cases where the reader would question why something is implemented like that
- Comment style should follow minimalistic writing style
## Recording reviews
Reviews are stored as git notes under `refs/notes/review`, one note per
reviewed commit. The note header carries `branch`, `round`, `verdict`
(`approve` or `request-changes`), `previous` (sha of the last reviewed tip),
and a findings list with stable IDs (`F1`, `F2`, ...) whose `status` is
`open`, `resolved`, or `wontfix`. The body is free markdown prose.
Protocol:
1. Fetch prior results:
`git fetch origin "refs/notes/review:refs/notes/review"`
Ignore the failure on the first-ever review (origin has no notes ref yet);
if the fetch is rejected as non-fast-forward, your local notes are ahead —
push instead.
2. Read the latest verdict and open findings for the branch:
`scripts/review-note latest [branch]`
3. Review the branch tip per this document.
4. Write the note (header + markdown) to a file and attach it to the tip:
`scripts/review-note write <file>`. Use `--force` only to replace a note
on the same commit deliberately.
5. Publish: `scripts/review-note push` (plain `git push` does not push
notes).
On a re-review after fixes: new tip, new note, `round`+1, `previous` set to
the last reviewed sha, open findings carried forward by ID, resolved ones
marked `resolved`.
On a branch rename: update the note's `branch:` header to the new name and
mention the old name in the body, so `latest <new-name>` chains and history
stays findable.
-1
View File
@@ -4,5 +4,4 @@ import qualified HomeAssistant.Runtime (defaultMain)
main :: IO () main :: IO ()
main = do main = do
putStrLn "Hello, Haskell!"
HomeAssistant.Runtime.defaultMain HomeAssistant.Runtime.defaultMain
+15 -6
View File
@@ -1,6 +1,10 @@
{ mkDerivation, aeson, annotated-exception, async, base, bytestring { mkDerivation, aeson, annotated-exception, async, base, bytestring
, hedgehog, hspec, hspec-hedgehog, katip, lens, lens-aeson, lib , cereal, cereal-conduit, cereal-text, conduit, containers
, network, stm, text, time, uuid, websockets , data-default, directory, ekg-core, exceptions, filepath, hedgehog
, hspec, hspec-hedgehog, http-media, http-types, katip, lens
, lens-aeson, lib, libsystemd-journal, lucid2, network, process
, retry, servant, servant-server, stm, temporary, text, time
, unliftio, unordered-containers, uuid, wai, warp, websockets
}: }:
mkDerivation { mkDerivation {
pname = "home-assistant-controller"; pname = "home-assistant-controller";
@@ -9,13 +13,18 @@ mkDerivation {
isLibrary = true; isLibrary = true;
isExecutable = true; isExecutable = true;
libraryHaskellDepends = [ libraryHaskellDepends = [
aeson annotated-exception async base bytestring katip lens aeson annotated-exception async base bytestring cereal
lens-aeson network stm text time uuid websockets cereal-conduit cereal-text conduit containers data-default
directory ekg-core exceptions filepath http-media http-types katip
lens lens-aeson libsystemd-journal lucid2 network process retry
servant servant-server stm text time unliftio unordered-containers
uuid wai warp websockets
]; ];
executableHaskellDepends = [ base ]; executableHaskellDepends = [ base ];
testHaskellDepends = [ testHaskellDepends = [
aeson annotated-exception async base hedgehog hspec hspec-hedgehog aeson annotated-exception async base bytestring cereal containers
stm text time data-default directory ekg-core hedgehog hspec hspec-hedgehog katip
process servant stm temporary text time unordered-containers uuid
]; ];
license = lib.meta.getLicenseFromSpdxId "BSD-3-Clause"; license = lib.meta.getLicenseFromSpdxId "BSD-3-Clause";
mainProgram = "home-assistant-controller"; mainProgram = "home-assistant-controller";
@@ -0,0 +1,113 @@
# Review notes protocol
Date: 2026-10-02
Status: approved
## Purpose
Record code-review results as git notes under `refs/notes/review` so that the
next reviewer — human or AI — can read the current verdict, see open findings
with stable IDs, and continue from where the last review stopped. This
replaces a CI reviewer: reviews happen locally, results travel with the
commits they judged.
## Storage model
- One note per reviewed commit, in the `review` notes ref.
- The tip of a reviewed branch always carries the latest verdict.
- Re-reviewing after fixes writes a **new** note on the **new** tip commit.
Old notes stay attached to old commits as history.
- Each note links to the previously reviewed commit via `previous`, forming a
walkable chain of review rounds per branch.
- Merging to main needs no special handling: the `approve` note on the final
tip is the record.
## Note format
Line-based header, then a blank line, then free markdown body:
branch: <branch name>
round: <integer, starting at 1>
verdict: approve | request-changes
previous: none | <sha of previously reviewed tip>
findings:
- id: F<N>
severity: blocker | major | minor
file: <path>:<line>
title: <one line>
status: open | resolved | wontfix
## Details
<markdown prose>
Rules:
- Finding IDs are unique within a note and carry forward across rounds: a
finding resolved since the last note keeps its ID and moves to
`status: resolved`; an unfixed finding keeps its ID and `status: open`.
New findings get fresh IDs that do not collide with carried-forward ones.
- The body is free markdown; the `## Details` heading in the example is
illustrative, not required.
- Headers are plain `key: value` lines so the helper script can parse them
with sed/awk.
## Helper script: `scripts/review-note`
Bash, git plumbing only. Subcommands:
- `review-note show [commit]` — print the note for a commit (default: current
tip). Exit 1 with a message on stderr if there is no note.
- `review-note write <file>` — attach the note in `<file>` to the current tip
commit. Refuses to replace an existing note unless `--force` is given; a
proper re-review targets a new commit, so overwriting is always deliberate.
Validates that `branch`, `round`, and `verdict` are present and that
`verdict` uses the vocabulary above. No other validation.
- `review-note latest [branch]` — print the note with the highest `round` for
a branch (default: current branch), scanning the notes ref and matching
notes on their `branch:` header. Exit 1 if there is no note for the branch.
(A `previous`-chain walk cannot bootstrap from an unreviewed tip, so the
scan uses the `branch:` header as the index instead.)
- `review-note push` — `git push origin refs/notes/review`. Plain `git push`
ignores notes, so this is the only way results travel.
`push` pushes without force; if the remote rejects, report the failure and let
the user decide.
## Lifecycle
1. Reviewer reads `review-note latest <branch>` (exit 1 means first review).
2. Reviewer reviews the branch tip per `REVIEW.md`.
3. Reviewer writes the note with `review-note write` and runs
`review-note push`.
4. If the verdict is `request-changes`, the author pushes fixes as new
commits. The next review round starts at the new tip with `round`+1,
`previous` set to the last reviewed tip, and carried-forward findings.
5. When the verdict is `approve` and the branch merges, the notes remain on
the branch commits as the review record.
## Documentation integration
- `REVIEW.md` gains a "Recording reviews" section describing the protocol and
the four script commands. This is the single source of truth for the
protocol.
- `AGENTS.md` "Reviewing" section gains one line pointing at the section, so
any AI session picks up the flow automatically.
## Seeding the experiment
The failing review of `home_assistant_controller_cleanup` (commit `ba6e0e8`)
becomes note round 1, with these findings:
- F1 (blocker, src/AFRP.hs:273): hlint's `\_ -> x` → `const x` rewrites break
the rank-2 `Mealy` type; library does not compile.
- F2 (blocker, test/AFRPLawsSpec.hs:98): seven law tests reduced to
tautologies by hlint rewrites; see :103, :212, :221, :228, :235, :256.
- F3 (minor, test/AFRPLawsSpec.hs:241): the interchange and composition laws
were reshaped to `<$>` forms; fold them into the same hlint suppression.
## Verification
The script is verified by round-trip checks in a throwaway temp clone: write,
show, latest (two rounds, branch filtering), force-overwrite refusal and
acceptance, and push. No Haskell or cabal changes, so no
cabal2nix regeneration.
+11 -1
View File
@@ -20,7 +20,15 @@
}); });
}); });
in rec { in rec {
packages.home-assistant-controller = pkgs.haskell.lib.justStaticExecutables hp.home-assistant-controller; packages.home-assistant-controller = pkgs.symlinkJoin {
name = "home-assistant-controller";
paths = [ (pkgs.haskell.lib.justStaticExecutables hp.home-assistant-controller) ];
nativeBuildInputs = [ pkgs.makeWrapper ];
postBuild = ''
wrapProgram $out/bin/home-assistant-controller \
--set HA_RRDTOOL ${pkgs.lib.getBin pkgs.rrdtool}/bin/rrdtool
'';
};
defaultPackage = packages.home-assistant-controller; defaultPackage = packages.home-assistant-controller;
devShell = hp.shellFor { devShell = hp.shellFor {
packages = h: [h.home-assistant-controller]; packages = h: [h.home-assistant-controller];
@@ -34,6 +42,8 @@
hp.graphmod hp.graphmod
hp.haskell-language-server hp.haskell-language-server
rrdtool
]; ];
}; };
} }
+75 -8
View File
@@ -52,7 +52,7 @@ extra-doc-files: CHANGELOG.md
-- extra-source-files: -- extra-source-files:
common warnings common warnings
ghc-options: -Wall ghc-options: -Wall -Werror
library library
-- Import common warning flags. -- Import common warning flags.
@@ -60,12 +60,35 @@ library
-- Modules exported by the library. -- Modules exported by the library.
exposed-modules: AFRP exposed-modules: AFRP
, AFRP.Diagram
, HomeAssistant.Controller , HomeAssistant.Controller
, HomeAssistant.Controller.Bedroom , HomeAssistant.Controller.Bedroom
, HomeAssistant.Controller.Children
, HomeAssistant.Controller.Door
, HomeAssistant.Controller.Effect
, HomeAssistant.Controller.Entity
, HomeAssistant.Controller.Hallway
, HomeAssistant.Controller.Ikea
, HomeAssistant.Controller.Kitchen
, HomeAssistant.Controller.Light.Command
, HomeAssistant.Controller.Light.Mode
, HomeAssistant.Controller.Light.Observation
, HomeAssistant.Controller.Livingroom
, HomeAssistant.Controller.Presence
, HomeAssistant.Controller.Ruuvi
, HomeAssistant.Controller.Scene
, HomeAssistant.Controller.Service
, HomeAssistant.Controller.Switch
, HomeAssistant.Runtime , HomeAssistant.Runtime
, HomeAssistant.Runtime.Bus , HomeAssistant.Runtime.Bus
, HomeAssistant.Runtime.Connection , HomeAssistant.Runtime.Connection
, HomeAssistant.Runtime.Flags
, HomeAssistant.Runtime.Graphing
, HomeAssistant.Runtime.Metrics
, HomeAssistant.Runtime.Supervisor , HomeAssistant.Runtime.Supervisor
, HomeAssistant.Runtime.RateLimit
, HttpServer
, Katip.Scribes.Journal
-- Modules included in this library but not exported. -- Modules included in this library but not exported.
-- other-modules: -- other-modules:
@@ -76,10 +99,13 @@ library
-- Other library packages from which modules are imported. -- Other library packages from which modules are imported.
build-depends: base ^>=4.20.2.0 build-depends: base ^>=4.20.2.0
, websockets , websockets
, http-media
, aeson , aeson
, lens-aeson , lens-aeson
, lens , lens
, exceptions
, text , text
, unliftio
, network , network
, bytestring , bytestring
, time , time
@@ -88,6 +114,27 @@ library
, annotated-exception , annotated-exception
, uuid , uuid
, katip , katip
, containers
, ekg-core
, unordered-containers
, process
, directory
, cereal
, cereal-text
, containers
, data-default
, filepath
, conduit
, cereal-conduit
, servant
, servant-server
, http-types
, warp
, wai
, retry
, libsystemd-journal
, lucid2
, http-api-data
-- Directories containing source files. -- Directories containing source files.
hs-source-dirs: src hs-source-dirs: src
@@ -118,7 +165,7 @@ executable home-assistant-controller
-- Base language which the package is written in. -- Base language which the package is written in.
default-language: GHC2024 default-language: GHC2024
ghc-options: -threaded ghc-options: -threaded -with-rtsopts=-T
test-suite home-assistant-controller-test test-suite home-assistant-controller-test
-- Import common warning flags. -- Import common warning flags.
@@ -128,11 +175,20 @@ test-suite home-assistant-controller-test
default-language: GHC2024 default-language: GHC2024
-- Modules included in this executable, other than Main. -- Modules included in this executable, other than Main.
other-modules: BusSpec other-modules: AFRPLawsSpec
, ConnectionSpec , AFRPSpec
, RuntimeSpec , BedroomSpec
, SupervisorSpec , BusSpec
, BackoffProp , ConnectionSpec
, FlagsSpec
, GraphingSpec
, HttpServerSpec
, KitchenSpec
, LivingroomSpec
, MetricsSpec
, RuntimeSpec
, Support
, ControllerSpec
-- LANGUAGE extensions used by modules in this package. -- LANGUAGE extensions used by modules in this package.
-- other-extensions: -- other-extensions:
@@ -150,9 +206,13 @@ test-suite home-assistant-controller-test
build-depends: build-depends:
base ^>=4.20.2.0, base ^>=4.20.2.0,
home-assistant-controller, home-assistant-controller,
bytestring,
data-default,
hspec, hspec,
stm, stm,
servant,
aeson, aeson,
cereal,
text, text,
async, async,
hedgehog, hedgehog,
@@ -160,4 +220,11 @@ test-suite home-assistant-controller-test
annotated-exception, annotated-exception,
time, time,
uuid, uuid,
katip katip,
containers,
ekg-core,
unordered-containers,
process,
directory,
temporary,
lucid2
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env bash
# review-note: manage code-review notes under refs/notes/review.
# The protocol lives in REVIEW.md.
set -euo pipefail
NOTES_REF=refs/notes/review
REMOTE=origin
die() { echo "review-note: $*" >&2; exit 1; }
usage() {
cat >&2 <<'EOF'
usage:
review-note show [commit]
review-note write <file> [--force]
review-note latest [branch]
review-note push
EOF
exit 1
}
validate() {
local file="$1"
grep -q '^branch: .\+' "$file" || die "missing or empty 'branch:' header"
grep -Eq '^round: [0-9]+$' "$file" || die "missing or invalid 'round:' header"
grep -Eq '^verdict: (approve|request-changes)$' "$file" \
|| die "verdict must be 'approve' or 'request-changes'"
}
cmd_show() {
local commit="${1:-HEAD}"
git notes --ref="$NOTES_REF" show "$commit" 2>/dev/null \
|| die "no review note for $commit"
}
cmd_write() {
local force="" file=""
local arg
for arg in "$@"; do
case "$arg" in
--force) force=1 ;;
*) file="$arg" ;;
esac
done
[ -n "$file" ] || usage
[ -f "$file" ] || die "no such file: $file"
local tip
tip=$(git rev-parse HEAD)
if [ -z "$force" ] && git notes --ref="$NOTES_REF" show "$tip" >/dev/null 2>&1; then
die "tip $tip already has a review note; pass --force to replace"
fi
validate "$file"
if [ -n "$force" ]; then
git notes --ref="$NOTES_REF" add -f -F "$file" "$tip"
else
git notes --ref="$NOTES_REF" add -F "$file" "$tip"
fi
}
cmd_latest() {
local branch="${1:-$(git branch --show-current)}"
local blob obj note br rnd best="" best_round=-1
while read -r blob obj; do
note=$(git notes --ref="$NOTES_REF" show "$obj") || continue
br=$(sed -n '/^$/q; s/^branch: //p' <<<"$note")
[ "$br" = "$branch" ] || continue
rnd=$(sed -n '/^$/q; s/^round: //p' <<<"$note")
[[ "$rnd" =~ ^[0-9]+$ ]] || continue
if [ "$rnd" -gt "$best_round" ]; then
best_round=$rnd
best=$note
fi
done < <(git notes --ref="$NOTES_REF" list)
[ -n "$best" ] || die "no review notes for branch: $branch"
printf '%s\n' "$best"
}
cmd_push() {
git rev-parse -q --verify "$NOTES_REF" >/dev/null || die "no review notes to push"
git push "$REMOTE" "$NOTES_REF"
}
main() {
local cmd="${1:-}"
if [ $# -gt 0 ]; then shift; fi
case "$cmd" in
show) cmd_show "$@" ;;
write) cmd_write "$@" ;;
latest) cmd_latest "$@" ;;
push) cmd_push "$@" ;;
*) usage ;;
esac
}
main "$@"
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# Round-trip checks for scripts/review-note, in a throwaway temp repo.
set -euo pipefail
root=$(cd "$(dirname "$0")/.." && pwd -P)
rn="$root/scripts/review-note"
fail() { echo "FAIL: $*" >&2; exit 1; }
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
git init -q --bare "$tmp/remote.git"
git init -q -b main "$tmp/repo"
cd "$tmp/repo"
git config user.email test@example.com
git config user.name test
echo one > a.txt && git add a.txt && git commit -qm one
echo two > b.txt && git add b.txt && git commit -qm two
note="$tmp/note1"
cat > "$note" <<'EOF'
branch: main
round: 1
verdict: request-changes
previous: none
findings:
- id: F1
severity: blocker
file: a.txt:1
title: fix me
status: open
## Details
Fix it.
EOF
if "$rn" show >/dev/null 2>&1; then fail "show should exit 1 without a note"; fi
sed '/^verdict:/d' "$note" > "$tmp/no-verdict"
if "$rn" write "$tmp/no-verdict" >/dev/null 2>&1; then fail "write should refuse a missing verdict"; fi
sed 's/^verdict: request-changes/verdict: maybe/' "$note" > "$tmp/bad-verdict"
if "$rn" write "$tmp/bad-verdict" >/dev/null 2>&1; then fail "write should refuse a bad verdict"; fi
"$rn" write "$note"
"$rn" show | grep -q '^verdict: request-changes$' || fail "show should print the note"
if "$rn" write "$note" >/dev/null 2>&1; then fail "write should refuse an existing note"; fi
sed 's/^verdict: request-changes/verdict: approve/' "$note" > "$tmp/note1b"
"$rn" write "$tmp/note1b" --force
"$rn" show | grep -q '^verdict: approve$' || fail "show should print the replaced note"
"$rn" show | diff -u "$tmp/note1b" - || fail "show should print the note verbatim"
# latest finds the note by branch, even from a newer unreviewed tip
echo three > c.txt && git add c.txt && git commit -qm three
"$rn" latest main | grep -q '^verdict: approve$' || fail "latest should find the round 1 note"
# a note for another branch must not leak into the result
sed -e 's/^branch: main/branch: other/' -e 's/^round: 1/round: 9/' "$tmp/note1b" > "$tmp/other"
"$rn" write "$tmp/other"
"$rn" latest main | grep -q '^verdict: approve$' || fail "latest should ignore other branches"
# round 2 on the new tip wins and carries previous (replaces the
# other-branch note on the same commit, so --force)
PREV=$(git rev-parse HEAD~1)
sed -e 's/^round: 1/round: 2/' -e "s/^previous: none/previous: $PREV/" "$tmp/note1b" > "$tmp/note2"
"$rn" write "$tmp/note2" --force
"$rn" latest main | grep -q '^round: 2$' || fail "latest should pick the highest round"
"$rn" latest main | grep -q "^previous: $PREV$" || fail "round 2 should carry previous"
if "$rn" latest nosuch >/dev/null 2>&1; then fail "latest should exit 1 for an unknown branch"; fi
# push publishes notes to origin; a fresh clone picks them up
git remote add origin "$tmp/remote.git"
git push -q origin main
"$rn" push
git clone -q "$tmp/remote.git" "$tmp/clone"
cd "$tmp/clone"
git fetch -q origin "refs/notes/review:refs/notes/review"
"$rn" latest main | grep -q '^round: 2$' || fail "clone should see the round 2 note"
echo "ok: show/write/latest/push"
+21 -21
View File
@@ -1,28 +1,28 @@
HA_TOKEN: ENC[AES256_GCM,data:zs9nTT2EV/OhBiH9alUuupUvYURXj40lxe7IKKWXdExW+BW98yEDHcQr/KNsQ0Iu9+U2GrsA8WpODeM351kI3Owj3rl082tObBJ2jwF1iyYcXhoH3xvbHb+HN802SBOTIO32m+ZwGvIVPjF8W+67eGKTrIUcqnKj7Ab/TchG+mYPLdil0mYjITY+DCUi0mW1nElCaTTexovj4PHlUdA1xIsCYF+XnTypQv8o+Zy8MsMZtdzNQKJG,iv:Lmxmp5y15sqhQvEO7liVk6x3Y26qtoL39TT2MSqZdok=,tag:1Xvs6YUilP/XH0UxYngTIg==,type:str] HA_TOKEN: ENC[AES256_GCM,data:zs9nTT2EV/OhBiH9alUuupUvYURXj40lxe7IKKWXdExW+BW98yEDHcQr/KNsQ0Iu9+U2GrsA8WpODeM351kI3Owj3rl082tObBJ2jwF1iyYcXhoH3xvbHb+HN802SBOTIO32m+ZwGvIVPjF8W+67eGKTrIUcqnKj7Ab/TchG+mYPLdil0mYjITY+DCUi0mW1nElCaTTexovj4PHlUdA1xIsCYF+XnTypQv8o+Zy8MsMZtdzNQKJG,iv:Lmxmp5y15sqhQvEO7liVk6x3Y26qtoL39TT2MSqZdok=,tag:1Xvs6YUilP/XH0UxYngTIg==,type:str]
HA_HOST: ENC[AES256_GCM,data:MfA+RReJHnKP31bD4YAoZrc=,iv:Z9xDtzPsUER4jQ12BbM2EtnLNggZhOWzCb7VAL2I02g=,tag:/Eogbd2kT7phdhaR/vGNDA==,type:str] HA_HOST: ENC[AES256_GCM,data:MfA+RReJHnKP31bD4YAoZrc=,iv:Z9xDtzPsUER4jQ12BbM2EtnLNggZhOWzCb7VAL2I02g=,tag:/Eogbd2kT7phdhaR/vGNDA==,type:str]
sops: sops:
age:
- enc: |
-----BEGIN AGE ENCRYPTED FILE-----
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHBpdi1wMjU2IHJKaXRSQSBBeEpPRXVT
NDY2ZUxZRDB5a21waDFoUXJsQkdsbFhQRjhobFBGVDlaZmlpSApGNEpKS1JzUStw
eWFJcUkxbWRtWURLQm0rWWtURXVNVEwvVlRLa3prNFZRCi0tLSBJWjhiL2RLV3ZO
NStpUlVSRHlSTEJWa2ZkenI3T292RnMwaHB6cnJRSW1NCt3zpORUDB2m9V+IK9UI
Z94uFopKZsRxzbxbZWklNykYoryjKfVCTO7sFDxapzr1UlG3UjVp2kgBJeDCEBVt
SwQ=
-----END AGE ENCRYPTED FILE-----
recipient: age1yubikey1qw7m7rad6malegqypgntr7qmu97xrxxurp0c00s23263nuxnpek6w0jye60
- enc: |
-----BEGIN AGE ENCRYPTED FILE-----
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHBpdi1wMjU2IFVnM21GQSBBNFYvaEM2
MFoyR3NhcDc4eklaTHJaUVZRWlJzT2dkclBOaExLYWZDb05DaQpidVcrRklydWJZ
WUhxQUR1c281R1RtdGlxNy9uMmJPODE1YXQ1K2g3bnFJCi0tLSAwblViWnhPMUNC
dTRoelphM1djcW9DK0NkWE44TSsvYmE5aEtIMW5RVG9vCqO5SqZ73i4wRn9qWyXA
8bW5XLeTN4qCIeMFEKloiAKDUKFWutHt/9SedYUsqMuRmQ9btmWg5TdkHV4S/6iR
qDU=
-----END AGE ENCRYPTED FILE-----
recipient: age1yubikey1qdnx7jum6k4fzenkqj8y5met9hyq6lqxrpzrl2788wr0q445vhupzuqtpk0
lastmodified: "2026-08-21T10:17:59Z" lastmodified: "2026-08-21T10:17:59Z"
mac: ENC[AES256_GCM,data:GuNyo/3flhR30e6kds1iXcDGmq0Xq2hqvBmAvYtakKwzUzMocP9vImfxs+MfVNiMGirlkwbihrX5mFSbfORjES/FDTs6p0100H1tkBqPTecW88PC6/66Js9umVevGYbgToCNBjV9mUBu7o7SyU+NYLnZ/8X4xdx0y6/MKnuvjUA=,iv:/nL5AIL80iV3sutjMTmHyF62SRezmX9XyJJ6+o9TdkQ=,tag:SNMu17rgMIhdzZVsGmXyfg==,type:str] mac: ENC[AES256_GCM,data:GuNyo/3flhR30e6kds1iXcDGmq0Xq2hqvBmAvYtakKwzUzMocP9vImfxs+MfVNiMGirlkwbihrX5mFSbfORjES/FDTs6p0100H1tkBqPTecW88PC6/66Js9umVevGYbgToCNBjV9mUBu7o7SyU+NYLnZ/8X4xdx0y6/MKnuvjUA=,iv:/nL5AIL80iV3sutjMTmHyF62SRezmX9XyJJ6+o9TdkQ=,tag:SNMu17rgMIhdzZVsGmXyfg==,type:str]
pgp:
- created_at: "2026-08-20T05:39:51Z"
enc: |-
-----BEGIN PGP MESSAGE-----
hQIMA5Urps8/GyTEAQ//ZQeXRy2SHcR2/hVqleE8V9/3u150TWX7GpDPVdjK7pxu
zK1JZSw/FSpNrUPFHXk6rWDm6lv1k/GCx34egHwgumlO1/192nQLMxwNHXhDeJmc
k6y44pb3Z1m/upVp62fIif2/f7X2BIQqGI0nZBaCM6sD5FE8HqXCk+jYw4YMvNZp
I6dtxxnYwW5wK5Gfv86hTHkn2ibDqARMgd0QsB8fv9fpE9iHWTeeSHqkCBVnb5Kn
s0Xk1DeED/ylLAlHfY0p0LVIjeCK5KCQCbIHXh4yb8ioxUxg9LQp8glXbjqbfaBx
FadLksLDxBuO0CWxAB4bVk4G/MKCL1nN3KzZBWfy96aknHHGQre0DCe7IxfmSYjd
f5UhfeFCVrWQTOtaoq3Oimw6CFeoGe04FKogQmZOWK1zmJmHxjCRGn4n5vzEZB1g
Cq+fzDLl2+Krr91Wq/xGwatoWaPl+SDzw1i7CnfGhWJn50BtO/YI1229yLSyANhs
M2R9JXxiWFst8xur0nJBKkzH+EZpaVOOLT7FgFpf/vWOO/se1kVPaMAhg6fQ3IwJ
JphPD+FTkTDY4GBefVP/qOhOnibcIjhwTiDWP6ppcaOxgVjyDyLsqS96jYSwfyKQ
puDyzrD4BlLv1lc2lULCtgMwZj428Vpd7YI1SjnxxKnKhIQ1IZx0ddneHn9fSivS
XgE6NpQKQ110FFYse8P1fb2yNaYb2ZRbLh0cUOe2qcTATTvK5OdDVlgCjNsO8Fgl
OO8hwmsk+1QziCwO4Md8NPdyNn4Kup1iRojMyAh23CT5LyYXoccakWvF/awLvz8=
=nX50
-----END PGP MESSAGE-----
fp: 95DBE64C2EA64D6B0E0C8C2F9DE6E04ED1918118
unencrypted_suffix: _unencrypted unencrypted_suffix: _unencrypted
version: 3.13.3 version: 3.13.3
+560 -70
View File
@@ -1,12 +1,18 @@
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE LambdaCase #-}
{-# LANGUAGE Arrows #-}
{-# LANGUAGE TypeOperators #-}
module AFRP module AFRP
( Mealy(..) ( Mealy(..)
, Auto(..)
, DecodedAuto(..)
, eff , eff
, named
, Event(..) , Event(..)
, hold , hold
, holdKnown
, events , events
, switch -- , switch
, preMapAccum , preMapAccum
, preMapAccumRequest , preMapAccumRequest
, mapAccum , mapAccum
@@ -14,123 +20,466 @@ module AFRP
, changes , changes
, whenA , whenA
, filterA , filterA
, filterEvent
, thenA , thenA
, (>>|) , (>>|)
, (>>||)
, toEvent , toEvent
, lMerge , lMerge
, Pair(..)
, Request(..) , Request(..)
, SerializeUTCTime(..)
, SerializeLocalTime(..)
, edge
, waitFor
, duration
, tag
, isEvent
, delayEvent
, sample
, rollup
, sliding
, debounce
, currentTime
, onEvent
, save
, load
, stepAuto
, stepAutoSerializing
, snapshot
) where ) where
import Control.Category (Category(..), (>>>)) import Control.Category (Category(..), (>>>))
import Prelude hiding ((.), id) import Prelude hiding ((.), id)
import Control.Arrow (Arrow(..), ArrowChoice(..), ArrowLoop(..)) import Control.Arrow (Arrow(..), ArrowChoice(..))
import Data.Time (UTCTime) import Data.Time (UTCTime (UTCTime), NominalDiffTime, diffUTCTime, addUTCTime, TimeZone, LocalTime (LocalTime), utcToLocalTime, Day (..), diffTimeToPicoseconds, picosecondsToDiffTime, TimeOfDay (TimeOfDay), diffLocalTime)
import Control.Monad.Fix (MonadFix (mfix))
import Data.Either (fromLeft) import Data.Either (fromLeft)
import Data.Bool (bool) import Data.Bool (bool)
import Data.UUID (UUID) import Data.UUID (UUID)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Serialize (Get, Putter, Serialize (put), runGet, get)
import qualified Data.ByteString as B
import Control.Exception (IOException)
import System.IO.Error (isDoesNotExistError)
import GHC.Generics (Generic)
import Data.Sequence (Seq, (|>))
import qualified Data.Foldable as F
import Control.Monad.IO.Class (MonadIO, liftIO)
import Conduit (ConduitT, (.|))
import qualified Data.Conduit.Cereal as CC
import qualified Conduit as C
import Control.Monad.Catch (MonadCatch, handle)
import Control.Exception.Annotated (throw)
import AFRP.Diagram
import Data.Text (Text)
data Codec s = Codec { getter :: !(Get s), putter :: !(Putter s) }
data State s = State {state :: !s, dirty :: !Bool}
deriving Functor
instance Semigroup s => Semigroup (State s) where
s1 <> s2 = State (state s1 <> state s2) (dirty s1 || dirty s2)
instance Monoid s => Monoid (State s) where
mempty = State mempty False
instance Applicative State where
pure a = State a False
s1 <*> s2 = State
{ state =
let a = state s2
f = state s1
in f a
, dirty = dirty s1 || dirty s2
}
mergeState :: State s1 -> State s2 -> State (s1, s2)
mergeState s1 s2 = (,) <$> s1 <*> s2
mergeCodec :: Codec s -> Codec s1 -> Codec (s, s1)
mergeCodec (Codec agetter aputter) (Codec bgetter bputter) = Codec (mergeGet agetter bgetter) (mergePut aputter bputter)
where
mergePut :: Putter s -> Putter s1 -> Putter (s, s1)
mergePut p1 p2 (s, s1) = p1 s >> p2 s1
mergeGet :: Get s -> Get s' -> Get (s, s')
mergeGet g1 g2 = (,) <$> g1 <*> g2
data Pair a b = Pair !a !b
data Request = Request data Request = Request
{ requestTime :: !UTCTime { requestTime :: !UTCTime
, requestTraceId :: !UUID , requestTimeZone :: !TimeZone
} , requestTraceId :: !UUID
deriving Show , requestHandler :: !T.Text
} deriving (Show, Eq)
newtype Mealy eff a b = Mealy
{ runMealy :: forall m. MonadFix m => (forall x. eff x -> m x) -> Request -> a -> m (b, Mealy eff a b) } data Auto m a b
= Fun (Request -> a -> b) -- Stateless variant, needed at least for 'id'
| forall s. Stateful !(Codec s) !(State s) !(State s -> Request -> a -> m (b, State s)) -- State is explicitly part of it
instance Monad m => Functor (Auto m a) where
fmap f = \case
Fun x -> Fun $ \req -> f . x req
Stateful codec s x -> Stateful codec s $ \s' req a -> do
(a',s'') <- x s' req a
pure (f a', s'')
instance Monad m => Applicative (Auto m a) where
pure a = Fun (\_req -> const a)
fa <*> fb =
case (fa,fb) of
(Fun af, Fun bf) -> Fun $ \req -> af req <*> bf req
(Stateful codec s af, Fun bf) -> Stateful codec s
(\s' req x -> do
let a = bf req x
(h, s'') <- af s' req x
pure (h a, s'')
)
(Fun af, Stateful codec s bf) -> Stateful codec s
(\s' req x -> do
(a, s'') <- bf s' req x
let h = af req x
pure (h a, s'')
)
(Stateful acodec as af, Stateful bcodec bs bf) -> Stateful (mergeCodec acodec bcodec) (mergeState as bs)
(\s' req x -> do
(a, as') <- bf (snd <$> s') req x
(h, bs') <- af (fst <$> s') req x
pure (h a, mergeState bs' as')
)
instance (Monad m, Semigroup b) => Semigroup (Auto m a b) where
fa <> fb =
case (fa,fb) of
(Fun af, Fun bf) -> Fun (af <> bf)
(Stateful codec s af, Fun bf) -> Stateful codec s
(\s' req a -> do
(ab, s'') <- af s' req a
let bb = bf req a
pure (ab <> bb, s'')
)
(Fun af, Stateful codec s bf) -> Stateful codec s
(\s' req a -> do
let ab = af req a
(bb, s'') <- bf s' req a
pure (ab <> bb, s'')
)
(Stateful acodec as af , Stateful bcodec bs bf) -> Stateful (mergeCodec acodec bcodec) (mergeState as bs)
(\s req a -> do
(ab, as'') <- af (fst <$> s) req a
(bb, bs'') <- bf (snd <$> s) req a
pure (ab <> bb, mergeState as'' bs'')
)
instance (Monad m, Monoid b) => Monoid (Auto m a b) where
mempty = Fun $ \_req _ -> mempty
instance Monad m => Category (Auto m) where
id = Fun $ const id
af . ag =
case (af, ag) of
(Fun f, Fun g) -> Fun (\req -> f req . g req)
(Stateful codec s f, Fun g) -> Stateful codec s (\s' req -> f s' req . g req)
(Fun f, Stateful codec s g) -> Stateful codec s (\s' req -> fmap (first (f req)) . g s' req)
(Stateful fcodec fs f , Stateful gcodec gs g) ->
Stateful (mergeCodec fcodec gcodec) (mergeState fs gs) (\s req a -> do
(b, s') <- g (snd <$> s) req a
(c, s'') <- f (fst <$> s) req b
pure (c, mergeState s'' s'))
instance Monad m => Arrow (Auto m) where
arr f = Fun $ const f
first = \case
Fun f -> Fun $ \req -> first (f req)
Stateful codec s f -> Stateful codec s $ \s' req (b,d) -> do
(c, s'') <- f s' req b
pure ((c,d), s'')
instance Monad m => ArrowChoice (Auto m) where
left = \case
Fun f -> Fun $ \req ->
\case
Left b -> Left $ f req b
Right d -> Right d
Stateful codec s f -> Stateful codec s $ \s' req -> \case
Right d -> pure (Right d, s')
Left b -> do
(c, s'') <- f s' req b
pure (Left c, s'')
serialize :: Monad m => Auto eff a b -> ConduitT i B.ByteString m ()
serialize = \case
Fun _ -> CC.sourcePut (put ())
Stateful Codec{putter} s _ -> CC.sourcePut (putter (state s))
data DecodedAuto m a b
= Decoded (Auto m a b) -- decoded from serialized state
| FailDecode String (Auto m a b) -- gives back the original + errmsg
deserialize :: B.ByteString -> Auto m a b -> DecodedAuto m a b
deserialize bs = \case
Fun f -> Decoded (Fun f) -- no state to decode, success by default
Stateful codec s f ->
either
(\err -> FailDecode err (Stateful codec s f))
(\s' -> Decoded $ Stateful codec (pure s') f)
$ runGet (getter codec) bs
save :: FilePath -> Auto m a b -> IO (Auto m a b)
save path s
| isDirty s = do
-- Using conduit machinery as it handles the exception handling for me
() <- C.runResourceT $ C.runConduit (serialize s .| C.sinkFileCautious path)
pure $ cleanDirty s
| otherwise = pure s
where
cleanDirty :: Auto m a b -> Auto m a b
cleanDirty (Stateful codec s' f) = Stateful codec s'{dirty=False} f
cleanDirty a = a
isDirty :: Auto m a b -> Bool
isDirty (Stateful _ s' _) = dirty s'
isDirty _ = False
load :: forall eff a b m. (MonadCatch m, MonadIO m) => FilePath -> Auto eff a b -> m (DecodedAuto eff a b)
load path a = handle defaultOnMissingFile (flip deserialize a <$> liftIO (B.readFile path))
where
defaultOnMissingFile :: IOException -> m (DecodedAuto eff a b)
defaultOnMissingFile e
| isDoesNotExistError e = pure $ FailDecode "State doesn't exist yet" a
| otherwise = throw e
-- | The set of entity ids an arrow subscribes to. Static: it does not
-- change as the machine steps, so the runtime can read it once to build
-- trigger subscriptions.
data Mealy eff a b = Mealy
{ entities :: S.Set T.Text
, runDiagramC :: forall x. (DiagramF x -> x) -> x
, runMealy :: forall m. Monad m => (forall x. eff x -> m x) -> Auto m a b
}
-- Provide a name
named :: Text -> Mealy eff a b -> Mealy eff a b
named n f = f{runDiagramC = \run -> run (Step n (runDiagramC f run))}
instance Semigroup b => Semigroup (Mealy eff a b) where
Mealy ast ad af <> Mealy bst bd bf = Mealy (ast <> bst) (combineDiagram Merge ad bd) $ \nt -> af nt <> bf nt
instance Monoid b => Monoid (Mealy eff a b) where
mempty = Mealy mempty emptyDiagram $ \_nt -> mempty
eff :: (Request -> a -> eff b) -> Mealy eff a b eff :: (Request -> a -> eff b) -> Mealy eff a b
eff f = Mealy $ \nt req x -> eff f = Mealy mempty emptyDiagram $ \nt -> do
nt (f req x) >>= \b -> pure (b, eff f) Stateful (Codec get put) (State () False) $ \s req a -> do
b <- nt (f req a)
pure (b, s)
instance Category (Mealy eff) where instance Category (Mealy eff) where
id = Mealy (\_ _ x -> pure (x, id)) {- HLINT ignore "Use const" -}
(Mealy f) . (Mealy g) = Mealy $ \nt t a -> do id = Mealy mempty emptyDiagram $ \_nt -> id
(b, g') <- g nt t a (Mealy ast ad f) . (Mealy bst bd g) = Mealy (ast <> bst) (combineDiagram Then bd ad) $ \nt -> do
(c, f') <- f nt t b f nt . g nt
pure (c, f' . g')
instance Arrow (Mealy eff) where instance Arrow (Mealy eff) where
arr f = Mealy $ \_ _ b -> pure (f b, arr f) arr f = Mealy mempty emptyDiagram $ \_nt -> arr f
first (Mealy f) = Mealy $ \nt t (b,d) -> do first (Mealy st d f) = Mealy st d $ \nt -> first (f nt)
(c, f') <- f nt t b (Mealy ast ad f) &&& (Mealy bst bd g) = Mealy (ast <> bst) (combineDiagram Both ad bd) $ \nt -> do
pure ((c, d), first f') f nt &&& g nt
instance ArrowChoice (Mealy eff) where instance ArrowChoice (Mealy eff) where
left (Mealy f) = Mealy $ \nt t -> \case left (Mealy st d f) = Mealy st d $ \nt -> left (f nt)
Left b -> do (Mealy ast ad f) +++ (Mealy bst bd g) = Mealy (ast <> bst) (combineDiagram Branch ad bd) $ \nt -> do
(c, f') <- f nt t b f nt +++ g nt
pure (Left c, left f')
Right d -> pure (Right d, left (Mealy f))
instance ArrowLoop (Mealy eff) where
loop (Mealy f) = Mealy $ \nt t b -> do
((c,_), f') <- mfix $ \((_,d), _) -> f nt t (b,d)
pure (c, loop f')
instance Functor (Mealy eff a) where instance Functor (Mealy eff a) where
fmap f (Mealy g) = Mealy $ \nt t a -> do fmap f (Mealy st d g) = Mealy st d $ \nt -> fmap f (g nt)
(b, g') <- g nt t a
pure (f b, fmap f g')
instance Applicative (Mealy eff a) where instance Applicative (Mealy eff a) where
pure b = Mealy $ \_ _ _ -> pure (b, pure b) pure b = Mealy mempty emptyDiagram $ \_ -> pure b
Mealy f <*> Mealy x = Mealy $ \nt t a -> do Mealy ast ad f <*> Mealy bst bd x = Mealy (ast <> bst) (combineDiagram Compose ad bd) $ \nt ->
(f', fNext) <- f nt t a f nt <*> x nt
(x', xNext) <- x nt t a
pure (f' x', fNext <*> xNext)
data Event a data Event a
= Tick = Tick
| Event a | Event a
deriving (Show, Functor, Foldable, Traversable) deriving (Show, Eq, Functor, Foldable, Traversable, Generic)
hold :: a -> Mealy eff (Event a) a instance Serialize a => Serialize (Event a)
hold a = Mealy $ \_ _ -> \case
Tick -> pure (a, hold a) instance Semigroup (Event a) where
Event a' -> pure (a', hold a') (<>) = lMerge
instance Monoid (Event a) where
mempty = Tick
hold :: (Serialize a, Eq a) => a -> Mealy m (Event a) a
hold def = mapAccum step def id
where
step prev = \case
Tick -> prev
Event new -> new
-- A variant of 'hold' which makes it explicit whether we have a previous value
holdKnown :: (Serialize a, Eq a) => Mealy m (Event a) (Maybe a)
holdKnown = arr (fmap Just) >>> hold Nothing
snapshot :: (Serialize a, Eq a) => a -> Mealy m (Event x, a) a
snapshot def = mapAccum step def id
where
step prev (Tick, _) = prev
step _prev (Event _, a) = a
events :: Mealy eff (Event a) (Either () a) events :: Mealy eff (Event a) (Either () a)
events = arr $ \case events = arr $ \case
Tick -> Left () Tick -> Left ()
Event a -> Right a Event a -> Right a
switch :: Mealy eff a (b, Event c) -> (c -> Mealy eff a b) -> Mealy eff a b isEvent :: Event a -> Bool
switch (Mealy f) s = Mealy $ \nt t a -> do isEvent Tick = False
((b, ev), f') <- f nt t a isEvent _ = True
case ev of
Tick -> pure (b, switch f' s)
Event x -> runMealy (s x) nt t a
preMapAccum :: (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b tag :: b -> Event a -> Event b
preMapAccum f x extract = go x tag b ev = b <$ ev
-- switch :: Mealy eff a (b, Event c) -> (c -> Mealy eff a b) -> Mealy eff a b
-- switch (Mealy st f) s = Mealy st $ \nt t a -> do
-- Pair (b, ev) f' <- f nt t a
-- case ev of
-- Tick -> pure (Pair b (switch f' s))
-- Event x -> runMealy (s x) nt t a
sample :: Mealy eff (a, Event b) (Event a)
sample = arr (uncurry tag)
preMapAccum' :: forall m x a b. (Monad m, Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Auto m a b
preMapAccum' f x extract = Stateful (Codec get put) (pure x) (\s _req a -> pure $ step s a)
where where
go b = Mealy $ \_ _ a -> step :: State x -> a -> (b, State x)
let next = f b a step s a = let s' = f (state s) a in (extract (state s), State s' (dirty s || state s /= s'))
in pure (extract b, go next)
preMapAccumRequest :: (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
preMapAccumRequest f x extract = go x mapAccum :: (Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
mapAccum step x extract = Mealy mempty emptyDiagram $ \_nt -> mapAccum' step x extract
preMapAccum :: (Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
preMapAccum step x extract = Mealy mempty emptyDiagram $ \_nt -> preMapAccum' step x extract
mapAccum' :: forall m x a b. (Monad m, Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Auto m a b
mapAccum' f x extract = Stateful (Codec get put) (pure x) (\s _req a -> pure $ step s a)
where where
go b = Mealy $ \_ t a -> step :: State x -> a -> (b, State x)
let next = f t b a step s a = let s' = f (state s) a in (extract s', State s' (dirty s || state s /= s'))
in pure (extract b, go next)
mapAccum :: (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b preMapAccumRequest :: (Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
mapAccum f x extract = go x preMapAccumRequest step x extract = Mealy mempty emptyDiagram $ \_ -> preMapAccumRequest' step x extract
preMapAccumRequest' :: forall m x a b. (Serialize x, Eq x, Monad m) => (Request -> x -> a -> x) -> x -> (x -> b) -> Auto m a b
preMapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
where where
go b = Mealy $ \_ _ a -> step :: State x -> Request -> a -> (b, State x)
let next = f b a step s req a = let s' = f req (state s) a in (extract (state s), State s' (dirty s || state s /= s'))
in pure (extract next, go next)
mapAccumRequest :: (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b mapAccumRequest :: (Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
mapAccumRequest f x extract = go x mapAccumRequest step x extract = Mealy mempty emptyDiagram $ \_ -> mapAccumRequest' step x extract
mapAccumRequest' :: forall m x a b. (Monad m, Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Auto m a b
mapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
where where
go b = Mealy $ \_ t a -> step :: State x -> Request -> a -> (b, State x)
let next = f t b a step s req a = let s' = f req (state s) a in (extract s', State s' (dirty s || state s /= s'))
in pure (extract next, go next)
changes :: Eq a => Mealy eff a (Event a) data DelayState x a = DelayState
{ pending :: x
, output :: !(Event a)
}
deriving (Generic, Eq)
instance (Serialize x, Serialize a) => Serialize (DelayState x a)
newtype SerializeUTCTime = SerializeUTCTime UTCTime
deriving (Eq, Show)
instance Serialize SerializeUTCTime where
put (SerializeUTCTime (UTCTime day time)) = do
put (toModifiedJulianDay day)
put (diffTimeToPicoseconds time)
get = do
day <- ModifiedJulianDay <$> get
time <- picosecondsToDiffTime <$> get
pure $ SerializeUTCTime (UTCTime day time)
newtype SerializeLocalTime = SerializeLocalTime LocalTime
deriving (Eq, Show)
instance Serialize SerializeLocalTime where
put (SerializeLocalTime (LocalTime day time)) = do
put (toModifiedJulianDay day)
let TimeOfDay h m s = time
put (h,m, toRational s)
get = do
day <- ModifiedJulianDay <$> get
(h,m,s) <- get
pure $ SerializeLocalTime (LocalTime day (TimeOfDay h m (fromRational s)))
delayEvent :: (Eq a, Serialize a) => NominalDiffTime -> Mealy eff (Event a) (Event a)
delayEvent delay =
mapAccumRequest step initial output
where
initial = DelayState [] Tick
step req st input =
let now = requestTime req
queued =
case input of
Tick -> pending st
Event x -> pending st ++ [(SerializeUTCTime $ delay `addUTCTime` now, x)]
in case queued of
(SerializeUTCTime due, x) : rest
| due <= now ->
DelayState rest (Event x)
_ ->
DelayState queued Tick
debounce :: (Serialize a, Eq a) => NominalDiffTime -> Mealy eff (Event a) (Event a)
debounce delay =
mapAccumRequest step initial output
where
initial = DelayState Nothing Tick
step req st input =
let now = requestTime req
held = case input of
Tick -> pending st
Event x -> Just (SerializeUTCTime $ delay `addUTCTime` now, x)
in case held of
Just (SerializeUTCTime due, x)
| due <= now -> DelayState Nothing (Event x)
_ -> DelayState held Tick
changes :: (Serialize a, Eq a) => Mealy eff a (Event a)
changes = mapAccum go Nothing (maybe Tick snd) changes = mapAccum go Nothing (maybe Tick snd)
where where
go :: Eq a => Maybe (a, Event a) -> a -> Maybe (a, Event a) go :: Eq a => Maybe (a, Event a) -> a -> Maybe (a, Event a)
@@ -145,6 +494,13 @@ whenA predicate auto = arr (\a -> if predicate a then Left a else Right ()) >>>
filterA :: (a -> Bool) -> Mealy eff a (Either () a) filterA :: (a -> Bool) -> Mealy eff a (Either () a)
filterA f = arr $ \a -> bool (Left ()) (Right a) (f a) filterA f = arr $ \a -> bool (Left ()) (Right a) (f a)
-- filters events through if they match the predicate
filterEvent :: (ArrowChoice cat, Arrow cat) => (a -> Bool) -> Event a `cat` Event a
filterEvent predicate = proc ev -> do
case ev of
Event a | predicate a -> id -< ev
_ -> arr (const Tick) -< ()
thenA :: (ArrowChoice cat, Arrow cat) => cat a (Either b1 c) -> cat c (Either b1 b2) -> cat a (Either b1 b2) thenA :: (ArrowChoice cat, Arrow cat) => cat a (Either b1 c) -> cat c (Either b1 b2) -> cat a (Either b1 b2)
thenA f g = f >>> arr Left ||| g thenA f g = f >>> arr Left ||| g
@@ -153,6 +509,15 @@ thenA f g = f >>> arr Left ||| g
infixl 2 >>| infixl 2 >>|
(>>||) :: (ArrowChoice cat, Arrow cat) => cat a (Event b) -> cat b c -> cat a (Event c)
f >>|| g = proc x -> do
e <- f -< x
case e of
Event e' -> g >>> arr Event -< e'
Tick -> arr (const Tick) -< ()
infixr 1 >>||
toEvent :: Mealy eff (Either () a) (Event a) toEvent :: Mealy eff (Either () a) (Event a)
toEvent = arr (either (const Tick) Event) toEvent = arr (either (const Tick) Event)
@@ -161,3 +526,128 @@ lMerge :: Event a -> Event a -> Event a
lMerge Tick Tick = Tick lMerge Tick Tick = Tick
lMerge (Event a) _ = Event a lMerge (Event a) _ = Event a
lMerge Tick (Event a) = Event a lMerge Tick (Event a) = Event a
edge :: Mealy eff Bool (Event ())
edge =
mapAccum
(\(_, current) new -> (current, new))
(False, False)
(\(old, current) ->
if not old && current
then Event ()
else Tick)
data WaitingFor
= Waiting
| Pending { waitingForStart :: SerializeLocalTime, waitingForCurrent :: SerializeLocalTime }
deriving (Show, Eq, Generic)
instance Serialize WaitingFor
waitFor :: NominalDiffTime -> Mealy eff Bool (Event ())
waitFor delta =
mapAccumRequest step Waiting extract >>> edge
where
extract :: WaitingFor -> Bool
extract Waiting = False
extract Pending{waitingForStart=SerializeLocalTime s, waitingForCurrent=SerializeLocalTime e} =
e `diffLocalTime` s >= delta
step :: Request -> WaitingFor -> Bool -> WaitingFor
step _req _prev False = Waiting
step req prev True =
let now = SerializeLocalTime $ requestLocalTime req
in case prev of
Waiting -> Pending now now
pending -> pending{waitingForCurrent = now}
duration :: forall eff a. Mealy eff a NominalDiffTime
duration = mapAccumRequest go (Nothing @(SerializeUTCTime, SerializeUTCTime)) (maybe 0 delta)
where
delta :: (SerializeUTCTime, SerializeUTCTime) -> NominalDiffTime
delta (SerializeUTCTime start, SerializeUTCTime end) = end `diffUTCTime` start
go :: Request -> Maybe (SerializeUTCTime, SerializeUTCTime) -> a -> Maybe (SerializeUTCTime, SerializeUTCTime)
go req Nothing _ = Just (SerializeUTCTime $ requestTime req, SerializeUTCTime $ requestTime req)
go req (Just (startTime, _)) _ = Just (startTime, SerializeUTCTime $ requestTime req)
-- | Rollup, hold back bursty messages
--
-- Consider a case where you have a bursty set of data. You care to get an immediate response,
-- but don't want to spam the output.
rollup
:: (Serialize a, Eq a)
=> Int -- ^ How many items to pass through before burst protection
-> Int -- ^ How many seconds to collect the bursty data
-> Mealy eff (Event a) (Event [a])
rollup limit seconds =
mapAccumRequest
go
(Left Tick)
(either id (\(_, _, _, ev) -> ev))
where
go
:: Request
-> Either (Event [a]) (SerializeUTCTime, Int, Seq a, Event [a])
-> Event a
-> Either (Event [a]) (SerializeUTCTime, Int, Seq a, Event [a])
go _ (Left _) Tick =
Left Tick
go req (Left _) (Event a) =
Right
( SerializeUTCTime $ addUTCTime (fromIntegral seconds) (requestTime req)
, 1
, mempty
, Event [a]
)
go req (Right (SerializeUTCTime end, n, acc, _)) Tick
| requestTime req >= end =
Left (Event $ F.toList acc)
| otherwise =
Right (SerializeUTCTime end, n, acc, Tick)
go req (Right (SerializeUTCTime end, n, acc, _)) (Event a)
| requestTime req >= end =
Left (Event $ F.toList (acc |> a))
| n < limit =
Right (SerializeUTCTime end, n + 1, acc, Event [a])
| otherwise =
Right (SerializeUTCTime end, n + 1, acc |> a, Tick)
-- Sliding window into the events
sliding :: (Serialize a, Eq a) => Int -> Mealy eff (Event a) [a]
sliding size = mapAccum go [] id
where
go :: [a] -> Event a -> [a]
go acc Tick = acc
go acc (Event a) = let xs = acc ++ [a] in drop (max 0 (length xs - size)) xs
requestLocalTime :: Request -> LocalTime
requestLocalTime Request{requestTime, requestTimeZone} = utcToLocalTime requestTimeZone requestTime
currentTime :: Mealy eff a LocalTime
currentTime = Mealy mempty emptyDiagram $ \_nt -> Fun $ \req _ ->
requestLocalTime req
stepAuto :: Monad m => Auto m a b -> Request -> a -> m (b, Auto m a b)
stepAuto (Fun f) req a = pure (f req a, Fun f)
stepAuto (Stateful codec s f) req a = do
(b, s') <- f s req a
pure (b, Stateful codec s' f)
stepAutoSerializing :: MonadIO m => FilePath -> Auto m a b -> Request -> a -> m (b, Auto m a b)
stepAutoSerializing path f req a = do
(b,x) <- stepAuto f req a
y <- liftIO $ save path x
pure (b,y)
onEvent :: Mealy eff a () -> Mealy eff (Event a) ()
onEvent f = events >>> (arr (const ()) ||| f)
+49
View File
@@ -0,0 +1,49 @@
{-# LANGUAGE OverloadedStrings #-}
module AFRP.Diagram where
import Data.Text (Text)
import qualified Text.Printf as Text
import qualified Data.Text as T
-- For rendering the arrows
data DiagramF f
= Empty
| Step Text f -- Named step
| Then f f -- >>>
| Both f f -- &&&
| Branch f f -- |||
| Merge f f -- <>
| Compose f f -- <*>
type DiagramAlgebra a = DiagramF a -> a
type DiagramC= forall a. DiagramAlgebra a -> a
combineDiagram :: (forall a. a -> a -> DiagramF a) -> DiagramC -> DiagramC -> DiagramC
combineDiagram constructor a b r = r (constructor (a r) (b r))
emptyDiagram :: DiagramC
emptyDiagram r = r Empty
renderF :: DiagramF (Maybe T.Text) -> Maybe T.Text
renderF = \case
Empty -> Nothing
Step n x -> Just $ n <> T.pack (maybe "" (Text.printf "( %s )") x)
Then (Just a) (Just b) -> Just $ a <> " -> " <> b
Then (Just a) _ -> Just a
Then _ b -> b
Both (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s, %s)" a b
Both (Just a) _ -> Just a
Both _ b -> b
Branch (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s || %s)" a b
-- I'm leaving this here. This would be technically more correct (showing
-- the empty branch, ie. the full if-then-else, but often we care about a
-- more simplistic `when` style structure
-- Branch (Just a) Nothing -> Just $ T.pack $ Text.printf "(%s || <skip>)" a
Branch (Just a) Nothing -> Just $ T.pack $ Text.printf "%s" a
Branch _ b -> b
Merge (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s, %s)" a b
Merge (Just a) _ -> Just a
Merge _ b -> b
Compose (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s, %s)" a b
Compose (Just a) _ -> Just a
Compose _ b -> b
+12 -155
View File
@@ -1,158 +1,15 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE GADTs #-}
module HomeAssistant.Controller module HomeAssistant.Controller
( Service(..) ( module Export
, HASSEff(..)
, HASS
, callService
, entityChangeEvent
, entityChangeEvent'
, entityRead
, entityRead'
, entityBool
, entityBool'
, Ruuvi(..)
, ruuvi
, ruuviTemperatures
, ruuviPressures
, DoorState(..)
, door
, light
, lightController
, Presence(..)
, presence
, debug
, traceEvent
, switch
, Target(..)
) where ) where
import AFRP (Mealy (..), eff, Event(..), hold, events, changes, filterA, (>>|), toEvent, Request) import HomeAssistant.Controller.Service as Export
import Control.Arrow (Arrow(..), returnA) import HomeAssistant.Controller.Effect as Export
import Control.Category ((>>>)) import HomeAssistant.Controller.Entity as Export
import Data.Aeson (Value) import HomeAssistant.Controller.Presence as Export
import qualified Data.Text as T import HomeAssistant.Controller.Door as Export
import Control.Lens (has, only, (^?), to) import HomeAssistant.Controller.Switch as Export
import Data.Aeson.Lens (key, _String) import HomeAssistant.Controller.Scene as Export
import qualified Data.Text.Lens as TL import HomeAssistant.Controller.Ikea as Export
import Data.Bool (bool) import HomeAssistant.Controller.Light.Command as Export
import HomeAssistant.Controller.Light.Observation as Export
data Target = EntityId !T.Text | AreaId !T.Text import HomeAssistant.Controller.Light.Mode as Export
deriving (Show,Eq)
data Service = Service
{ serviceDomain :: T.Text
, serviceName :: T.Text
, serviceData :: Maybe Value
, serviceTarget :: [Target]
}
deriving (Show, Eq)
data HASSEff a where
CallService :: Request -> Service -> HASSEff ()
Debug :: Show a => a -> HASSEff ()
Trace :: Show a => Request -> a -> HASSEff ()
type HASS a b = Mealy HASSEff a b
callService :: Service -> HASS a ()
callService service = eff (\req _ -> CallService req service)
debug :: Show a => HASS a a
debug = proc x -> do
eff (const Debug) -< x
returnA -< x
traceEvent :: Show a => HASS (Event a) (Event a)
traceEvent = Mealy $ \nt req -> \case
Event a -> nt (Trace req a) >>= \() -> pure (Event a, traceEvent)
Tick -> pure (Tick, traceEvent)
ruuviTemperatures :: Mealy eff (Event Value) Double
ruuviTemperatures = entityRead @Double "sensor.ruuvitag_b168_temperature" >>> hold 0
ruuviPressures :: Mealy eff (Event Value) Double
ruuviPressures = entityRead "sensor.ruuvitag_b168_pressure" >>> hold 0
data Ruuvi = Ruuvi { ruuviTemperature :: Double, ruuviPressure :: Double }
deriving (Show, Eq)
ruuvi :: Mealy eff (Event Value) (Event Ruuvi)
ruuvi = (Ruuvi <$> ruuviTemperatures <*> ruuviPressures) >>> changes
data DoorState = Open | Closed
deriving (Show, Eq)
data Presence = Occupied | Unoccupied
deriving (Show, Eq)
presence :: T.Text -> HASS (Event Value) (Event Presence)
presence entityId =entityBool entityId
>>> arr (fmap (bool Unoccupied Occupied))
door :: HASS (Event Value) (Event DoorState)
door = entityBool "binary_sensor.makuuhuone_ovi_contact"
>>> arr (fmap (bool Closed Open))
>>> hold Open
>>> changes
-- Turn off lights when door is closed
light :: [Target] -> Bool -> Service
light targets b = Service
{ serviceDomain="light"
, serviceName= bool "turn_off" "turn_on" b
, serviceData=Nothing
, serviceTarget=targets
}
-- Name conflict with AFRP
switch :: [Target] -> Bool -> Service
switch targets b = Service
{ serviceDomain="switch"
, serviceName= bool "turn_off" "turn_on" b
, serviceData=Nothing
, serviceTarget=targets
}
lightController :: HASS (Event Value) (Event DoorState)
lightController = proc ev -> do
doorState <- door -< ev
case doorState of
Event Open -> callService (light [EntityId "light.bedroom_masse"] False) -< ()
Event Closed -> callService (light [EntityId "light.bedroom_masse"] True) -< ()
_ -> returnA -< ()
returnA -< doorState
entityChangeEvent :: T.Text -> Mealy eff (Event Value) (Event Value)
entityChangeEvent entityId = entityChangeEvent' entityId >>> toEvent
entityChangeEvent' :: T.Text -> Mealy eff (Event Value) (Either () Value)
entityChangeEvent' entityId = events >>| filterA isEntity
where
isEntity :: Value -> Bool
isEntity = has (key "event" . key "data" . key "entity_id" . _String . only entityId)
entityRead' :: (Read a) => T.Text -> Mealy eff (Event Value) (Either () a)
entityRead' entityId = entityChangeEvent' entityId >>| (arr state >>> arr (maybe (Left ()) Right))
where
state v = v ^? key "event" . key "data" . key "new_state" . key "state" . _String . TL.unpacked . to read
entityBool' :: T.Text -> Mealy eff (Event Value) (Either () Bool)
entityBool' entityId = entityChangeEvent' entityId >>| (arr state >>> arr (maybe (Left ()) Right))
where
state v = v ^? key "event" . key "data" . key "new_state" . key "state" . _String . TL.unpacked . to toBool
toBool = \case
"on" -> True
"off" -> False
_ -> False
entityRead :: (Read a) => T.Text -> Mealy eff (Event Value) (Event a)
entityRead entityId = entityRead' entityId >>> toEvent
entityBool :: T.Text -> Mealy eff (Event Value) (Event Bool)
entityBool entityId = entityBool' entityId >>> toEvent
+117 -63
View File
@@ -1,20 +1,26 @@
{-# LANGUAGE Arrows #-} {-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DerivingVia #-}
module HomeAssistant.Controller.Bedroom where module HomeAssistant.Controller.Bedroom where
import HomeAssistant.Controller import HomeAssistant.Controller
import qualified Data.Text as T import qualified Data.Text as T
import AFRP (Event (..), (>>|), toEvent, lMerge) import AFRP (Event (..), lMerge, duration, edge, filterEvent, named, (>>||))
import Data.Aeson (Value, object, (.=)) import Data.Aeson (Value, object, (.=))
import Control.Arrow ((>>>), returnA, arr, Arrow (..)) import Control.Arrow ((>>>), returnA, arr, Arrow (..))
import Control.Lens ((^?), to, traversed)
import Data.Aeson.Lens (key, _String)
import Data.Bool (bool) import Data.Bool (bool)
import Data.Time (NominalDiffTime)
import qualified AFRP
import Data.Map (Map)
import qualified Data.Map.Strict as M
import Data.Serialize.Text ()
import Data.Default (def)
import Data.Serialize (Serialize)
bedroomLights :: [Target] bedroomLightTargets :: [Target]
bedroomLights = map EntityId ["light.bedroom_masse","light.bedroom_jemina","light.bedroom_ceiling","light.bedroom_led_switch"] bedroomLightTargets = map EntityId ["light.bedroom_masse","light.bedroom_jemina","light.bedroom_ceiling","light.bedroom_led_switch"]
createBedroomScene :: Service createBedroomScene :: Service
createBedroomScene = Service createBedroomScene = Service
@@ -22,88 +28,103 @@ createBedroomScene = Service
, serviceName= "create" , serviceName= "create"
, serviceData= Just $ object , serviceData= Just $ object
[ "scene_id" .= ("makuuhuone_lights_snapshot" :: T.Text) [ "scene_id" .= ("makuuhuone_lights_snapshot" :: T.Text)
, "snapshot_entities" .= [l | EntityId l <- bedroomLights] , "snapshot_entities" .= [l | EntityId l <- bedroomLightTargets]
] ]
, serviceTarget= [] , serviceTarget= []
} }
activateScene :: T.Text -> Service
activateScene sceneId = Service
{ serviceDomain="scene"
, serviceName= "turn_on"
, serviceTarget= [EntityId sceneId]
, serviceData = Nothing
}
-- Bedroom presence -- Bedroom presence
bedroomPresence :: HASS (Event Value) (Event Presence) bedroomPresence :: HASS (Event Value) (Event Presence)
bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy" bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy"
presenceLightEvents :: HASS (Event Value) (Event LightingMode)
presenceLightEvents =
bedroomPresence >>> AFRP.hold Unoccupied
>>> arr lightWanted
>>> (sleepEvent &&& offEvent &&& onEvent)
>>> arr (\(s,(o,n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
where
lightWanted o = o == Occupied
sleepEvent = arr not >>> AFRP.edge >>> arr (AFRP.tag LightingSleep)
onEvent = AFRP.edge >>> arr (AFRP.tag LightingOn)
offEvent = arr not >>> AFRP.waitFor 300 >>> arr (AFRP.tag LightingOff)
bedroomLightStatus :: HASS (Event Value) (Map T.Text LightObservation)
bedroomLightStatus = M.fromList <$> traverse (\e -> (e,) <$> observedLight e) [e | EntityId e <- bedroomLightTargets]
newtype Snapshot = Snapshot { getSnapshot :: Map T.Text LightObservation }
deriving (Show, Eq)
deriving Serialize via (Map T.Text LightObservation)
lightLevel :: HASS (Event Value) Int
lightLevel = entityRead "sensor.presence_sensor_bedroom_light_level" >>> AFRP.hold 1
bedroomPresenceController :: HASS (Event Value) () bedroomPresenceController :: HASS (Event Value) ()
bedroomPresenceController = proc x -> do bedroomPresenceController = proc x -> do
p <- bedroomPresence -< x p <- presenceLightEvents >>> traceEvent -< x
capped <- lightLevel >>> arr (< 4) -< x
snap <- (doSnapshot &&& bedroomLightStatus) >>> AFRP.snapshot M.empty >>> arr Snapshot -< x
-- This line is just for debugging
_ <- AFRP.changes >>> traceEvent -< snap
case p of case p of
Event Unoccupied -> callService createBedroomScene >>> callService (light bedroomLights False) -< () Event LightingOff -> do
Event Occupied -> callService (activateScene "makuuhuone_lights_snapshot") -< () callService "Turn off lights" (light bedroomLightTargets Off) -< ()
Event LightingOn -> do
callServicesDyn "Turn on lights (capped)" (\(c,xs) -> concatMap (uncurry (toLight c)) xs) -< (capped, M.toList (getSnapshot snap))
returnA -< ()
Event LightingSleep -> do
callService "Turn on sleep" (activateScene "scene.makuuhuone_lepotila") -< ()
_ -> returnA -< () _ -> returnA -< ()
data IkeaGesture
= ShortClick
| ShortRelease
| DoubleClick
| LongClick
deriving Show
data IkeaButton a = OnButton !a | OffButton !a
deriving Show
toIkeaQuickButton :: T.Text -> Maybe (IkeaButton IkeaGesture)
toIkeaQuickButton = \case
-- 1 is on, 2 is off side of the button
"1_initial_press" -> Just $ OnButton ShortClick
"1_short_release" -> Just $ OnButton ShortRelease
"1_double_press" -> Just $ OnButton DoubleClick
"1_long_press" -> Just $ OnButton LongClick
"2_initial_press" -> Just $ OffButton ShortClick
"2_short_release" -> Just $ OffButton ShortRelease
"2_double_press" -> Just $ OffButton DoubleClick
"2_long_press" -> Just $ OffButton LongClick
_ -> Nothing
ikeaQuickButton :: T.Text -> HASS (Event Value) (Event (IkeaButton IkeaGesture))
ikeaQuickButton entityId =
entityChangeEvent' entityId
>>| arr (maybe (Left ()) Right . eventType)
>>> toEvent
where where
eventType v = v ^? key "event" . key "data" . key "new_state" . key "attributes" . key "event_type" . _String . to toIkeaQuickButton . traversed toLight :: Bool -> T.Text -> LightObservation -> [Service]
toLight _ entityId LightObservation{observedOn=False} = [light [EntityId entityId] Off]
toLight capped entityId LightObservation{observedOn=True, observedTemperature=t, observedBrightness=b} =
[ light [EntityId entityId] (On def
{lightBrightness = fmap (\b' -> BrightnessAbsolute $ if capped then 140 `min` b' else b') b
, lightColorTemperature = t
})
]
doSnapshot = presenceLightEvents
>>> arr (\ev -> if ev == Event LightingSleep then Event () else Tick)
data BedroomControls data BedroomControls
= Masse (IkeaButton IkeaGesture) = Masse (IkeaButton IkeaGesture)
| Enishen (IkeaButton IkeaGesture) | Enishen (IkeaButton IkeaGesture)
| Central IkeaRemoteAction
deriving Show deriving Show
bedroomButton :: HASS (Event Value) (Event BedroomControls) bedroomButton :: HASS (Event Value) (Event BedroomControls)
bedroomButton = (masseButton &&& enishenButton) >>> arr (uncurry lMerge) bedroomButton = (masseButton &&& enishenButton &&& centralButton)
>>> arr (\(a,(b,c)) -> a <> b <> c)
where where
masseButton = fmap Masse <$> ikeaQuickButton "event.bedroom_quick_remote_masse_action" masseButton = fmap Masse <$> ikeaQuickButton "event.bedroom_quick_remote_masse_action"
enishenButton = fmap Enishen <$> ikeaQuickButton "event.bedroom_quick_jemina_action" enishenButton = fmap Enishen <$> ikeaQuickButton "event.bedroom_quick_jemina_action"
centralButton = fmap Central <$> ikeaBoxRemote "event.bedroom_remote_action"
bedroomButtonController :: HASS (Event Value) () bedroomButtonController :: HASS (Event Value) ()
bedroomButtonController = proc x -> do bedroomButtonController = proc x -> do
ev <- bedroomButton >>> traceEvent -< x ev <- bedroomButton >>> traceEvent -< x
-- Any event will cause the sleep mode to be turned off
case ev of case ev of
Event (Masse (OnButton ShortRelease)) -> callService (activateScene "scene.makuuhuone_masse") -< () -- this should be on release Event (Masse (OnButton ShortRelease)) -> do
Event (Masse (OnButton DoubleClick)) -> callService (activateScene "scene.makuuhuone_keski") -< () callService "scene.makuuhuone_masse" (activateScene "scene.makuuhuone_masse") -< ()
Event (Masse (OnButton LongClick)) -> callService (activateScene "scene.makuuhuone_kirkas") -< () Event (Masse (OnButton DoubleClick)) -> do
Event (Masse (OffButton _)) -> callService (light [AreaId "makuuhuone"] False) -< () callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< ()
Event (Enishen (OnButton ShortRelease)) -> callService (activateScene "scene.makuuhuone_jemina") -< () Event (Masse (OnButton LongClick)) -> do
Event (Enishen (OnButton DoubleClick)) -> callService (activateScene "scene.makuuhuone_keski") -< () callService "scene.makuuhuone_kirkas" (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Enishen (OnButton LongClick)) -> callService (activateScene "scene.makuuhuone_kirkas") -< () Event (Masse (OffButton _)) -> do
Event (Enishen (OffButton _)) -> callService (light [AreaId "makuuhuone"] False) -< () callService "Lights off" (light [AreaId "makuuhuone"] Off) -< ()
Event (Enishen (OnButton ShortRelease)) -> do
callService "scene.makuuhuone_jemina" (activateScene "scene.makuuhuone_jemina") -< ()
Event (Enishen (OnButton DoubleClick)) -> do
callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< ()
Event (Enishen (OnButton LongClick)) -> do
callService "scene.makuuhuone_kirkas" (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Enishen (OffButton _)) -> do
callService "Lights off" (light [AreaId "makuuhuone"] Off) -< ()
_ -> returnA -< () _ -> returnA -< ()
@@ -113,11 +134,44 @@ drawer = entityBool "binary_sensor.bedroom_nightstand_drawer_sensor_masse_contac
>>> arr (fmap (bool Closed Open)) >>> arr (fmap (bool Closed Open))
bedroomDrawerController :: HASS (Event Value) () bedroomDrawerController :: HASS (Event Value) ()
bedroomDrawerController = proc x -> do bedroomDrawerController =
st <- drawer >>> traceEvent -< x drawer >>>
case st of (named "Drawer opened" lightOn <> named "Drawer closed" lightOff)
Event Open -> callService (switch [entity] True) -< () >>> arr (const ())
Event Closed -> callService (switch [entity] False) -< ()
_ -> returnA -< ()
where where
entity = EntityId "switch.bedroom_drawer_light_masse" entity = EntityId "switch.bedroom_drawer_light_masse"
lightOff = filterEvent (== Closed)
>>|| callService "drawer light off" (switchService [entity] False)
lightOn = filterEvent (== Open)
>>|| callService "drawer light on" (switchService [entity] True)
door :: HASS (Event Value) (Event DoorState)
door = entityBool "binary_sensor.makuuhuone_ovi_contact"
>>> arr (fmap (bool Closed Open))
waitFor :: NominalDiffTime -> HASS a (Event ())
waitFor n = duration >>> arr (> n) >>> edge
delayedDoor :: HASS (Event Value) (Event DoorState)
delayedDoor = door
>>> AFRP.debounce 15
>>> AFRP.hold Open
>>> AFRP.changes
humidifierController :: HASS (Event Value) ()
humidifierController = proc x -> do
st <- delayedDoor -< x
case st of
-- Turn the humidifier on when the door is closed
-- the humidifier is low-powered, no point in losing all the humidity
Event Open -> callService "Humidifier off" (humidifier False) -< ()
Event Closed -> callService "Humidifier on" (humidifier True) -< ()
_ -> returnA -< ()
where
humidifier state = Service
{ serviceDomain="humidifier"
, serviceName= bool "turn_off" "turn_on" state
, serviceData= Nothing
, serviceTarget= [EntityId "humidifier.makuuhuone_ilmankostutin"]
}
+165
View File
@@ -0,0 +1,165 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DerivingVia #-}
module HomeAssistant.Controller.Children where
import HomeAssistant.Controller (HASS, callService, light, LightCommand(..), ikeaQuickButton, IkeaGesture (..), IkeaButton (..), traceEvent, activateScene, LightAttributes (..), Brightness (..), entityRead, entityChangeEvent)
import AFRP (Event (..))
import qualified AFRP
import Control.Arrow (Arrow(..), (>>>), returnA)
import Data.Time (Day, TimeOfDay (..), localDay, LocalTime (..))
import Data.Time.Calendar.OrdinalDate (WeekOfYear, mondayStartWeek)
import Data.Functor.Contravariant (Predicate (..), (>$<))
import Data.Aeson (Value, object, (.=))
import Data.Default (Default(..))
import Data.Serialize (Serialize)
import Data.Serialize.Text ()
import GHC.Generics (Generic)
import HomeAssistant.Controller.Service (Service(..), Target(..))
import Data.Aeson.Types (ToJSON (..))
import Data.Aeson.Lens (key, _String)
import Control.Lens ((^?), to)
import Data.Text (Text)
import Control.Monad (join)
-- Let's see building some reasonable interface for utctime
dow :: Day -> (WeekOfYear, Int)
dow = mondayStartWeek
weekday :: Predicate Day
weekday = Predicate (betweenInclusive 1 5 . snd . dow)
where
betweenInclusive a b c = c >= a && c <= b
time :: (Int, Int) -> Predicate TimeOfDay
time (h,m) = mconcat
[ Predicate (equals h . todHour)
, Predicate (equals m . todMin)
]
where
equals a b = a == b
atTime :: Predicate LocalTime -> HASS a (Event ())
atTime p = AFRP.currentTime
>>> arr (getPredicate p)
>>> AFRP.edge
-- I don't have any proper presence sensors in their bedroom
-- and they are notoriously bad at changing clothes in complete darkness
-- So I have set up an automation that attempts to turn on the lights sometime
-- before they leave for school and turns them off a bit later
-- Don't mconcat these predicates they have && behavior
-- if you mconcat the actual arrows, they combine the behaviors of the separate branches
-- essentially becoming || behavior
timersOff :: [Predicate LocalTime]
timersOff =
[ day 1 <> at (08,15)
, day 2 <> at (09,15)
, day 3 <> at (08,15)
, day 4 <> at (08,15)
, day 5 <> at (08,15)
]
where
dayOfWeek = snd . mondayStartWeek . localDay
at (h,m) = localTimeOfDay >$< Predicate (\TimeOfDay{todHour, todMin} -> todHour == h && todMin == m)
day n = dayOfWeek >$< Predicate (== n)
timersOn :: [Predicate LocalTime]
timersOn =
[ day 1 <> at (07,30)
, day 2 <> at (08,30)
, day 3 <> at (07,30)
, day 4 <> at (07,30)
, day 5 <> at (07,30)
]
where
dayOfWeek = snd . mondayStartWeek . localDay
at (h,m) = localTimeOfDay >$< Predicate (\TimeOfDay{todHour, todMin} -> todHour == h && todMin == m)
day n = dayOfWeek >$< Predicate (== n)
schoolLightController :: HASS a ()
schoolLightController = lightsOn <> lightsOff
lightsOn :: HASS a ()
lightsOn = foldMap atTime timersOn
>>> AFRP.onEvent (callService "Lights on" (light [AreaId "lasten_makuuhuone"] (On def{lightBrightness=Just $ BrightnessPercent 100} )))
lightsOff :: HASS a ()
lightsOff = foldMap atTime timersOff
>>> AFRP.onEvent (callService "Lights off" (light [AreaId "lasten_makuuhuone"] Off))
childrenBedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
childrenBedroomButton = ikeaQuickButton "event.children_quick_remote_action"
childrenBedroomButtonController :: HASS (Event Value) ()
childrenBedroomButtonController = proc x -> do
ev <- childrenBedroomButton >>> traceEvent -< x
case ev of
Event (OnButton ShortRelease) -> callService "scene.lasten_nukkuvalmistelu" (activateScene "scene.lasten_nukkuvalmistelu") -< ()
Event (OnButton DoubleClick) -> callService "scene.lasten_luku" (activateScene "scene.lasten_luku") -< ()
Event (OnButton LongClick) -> callService "scene.lasten_kirkas" (activateScene "scene.lasten_kirkas") -< ()
Event (OffButton _) -> callService "Lights off" (light [AreaId "lasten_makuuhuone"] Off) -< ()
_ -> returnA -< ()
newtype PM25 = PM25 Float
deriving (Serialize, Eq, Ord) via Float
deriving Show
data PM25Level = PM25High | PM25Low
deriving (Eq, Generic, Show)
instance Serialize PM25Level
pm25 :: HASS (Event Value) PM25
pm25 = fmap PM25 (entityRead "sensor.children_temp_pm25" >>> AFRP.hold 0)
pm25Level :: HASS PM25 PM25Level
pm25Level = (tagHigh &&& tagLow) >>> arr (uncurry AFRP.lMerge) >>> AFRP.hold PM25Low
where
-- Band between 8 and 12 to avoid oscillation near the ~10 mark
tagHigh = arr (> PM25 12) >>> AFRP.edge >>> arr (AFRP.tag PM25High)
tagLow = arr (< PM25 8) >>> AFRP.edge >>> arr (AFRP.tag PM25Low)
data HumidifierAction
= Idle
| Humidifying
| Other Text
deriving (Show, Eq, Generic)
instance Serialize HumidifierAction
-- what is the humidifer doing right now?
humidifierOperatingState :: HASS (Event Value) (Event (Maybe HumidifierAction))
humidifierOperatingState = entityChangeEvent "humidifier.lapset_ilmankostutin"
>>> arr (fmap entityAction)
where
entityAction v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "action" . _String . to humidifierAction
humidifierAction = \case
"idle" -> Idle
"humidifying" -> Humidifying
other -> Other other
-- TODO: There's some other percentages elsewhere that could be replaced with this
newtype Percentage = Percentage Int
instance ToJSON Percentage where
toJSON (Percentage p) = object ["percentage" .= p]
childrenAirFilterController :: HASS (Event Value) ()
childrenAirFilterController = proc ev -> do
level <- pm25 >>> pm25Level >>> AFRP.changes >>> traceEvent -< ev
humidifier <- humidifierOperatingState >>> AFRP.holdKnown >>> arr join -< ev
case level of
Event PM25High ->
AFRP.whenA (== Just Idle) (callService "Fan strong" (fanOnTo (Percentage 80))) -< humidifier
Event PM25Low -> callService "Fan low" (fanOnTo (Percentage 20)) -< ()
_ -> returnA -< ()
where
fanOnTo percentage = Service
{ serviceDomain = "fan"
, serviceName = "set_percentage"
, serviceTarget = [EntityId "fan.children_fan"]
, serviceData = Just $ toJSON percentage
}
+9
View File
@@ -0,0 +1,9 @@
module HomeAssistant.Controller.Door (DoorState(..)) where
import GHC.Generics (Generic)
import Data.Serialize (Serialize)
data DoorState = Open | Closed
deriving (Show, Eq, Generic)
instance Serialize DoorState
+60
View File
@@ -0,0 +1,60 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Effect
( HASSEff(..)
, HASS
, callService
, callServices
, callServiceDyn
, callServicesDyn
, debug
, traceEvent
, traceValue
) where
import AFRP (Mealy, eff, Event (..), Request, named)
import Control.Arrow (returnA)
import HomeAssistant.Controller.Service (Service (..))
import qualified Data.Text as T
data HASSEff a where
CallService :: Request -> Service -> HASSEff ()
CallServices :: Request -> [Service] -> HASSEff ()
Debug :: Show a => a -> HASSEff ()
Trace :: Show a => Request -> a -> HASSEff ()
type HASS a b = Mealy HASSEff a b
serviceLabel :: T.Text -> HASS a b -> HASS a b
serviceLabel lbl = named ("Service: " <> lbl)
callService :: T.Text -> Service -> HASS a ()
callService lbl service = serviceLabel lbl $ eff (\req _ -> CallService req service)
callServices :: T.Text -> [Service] -> HASS a ()
callServices lbl service = serviceLabel lbl $ eff (\req _ -> CallServices req service)
callServiceDyn :: T.Text -> (a -> Service) -> HASS a ()
callServiceDyn lbl mkService = serviceLabel lbl $ eff (\req a -> CallService req (mkService a))
callServicesDyn :: T.Text -> (a -> [Service]) -> HASS a ()
callServicesDyn lbl mkService = serviceLabel lbl $ eff (\req a -> CallServices req (mkService a))
debug :: Show a => HASS a a
debug = proc x -> do
eff (const Debug) -< x
returnA -< x
traceEvent :: Show a => HASS (Event a) (Event a)
traceEvent = proc ev -> do
case ev of
Event a -> eff Trace -< a
Tick -> returnA -< ()
returnA -< ev
traceValue :: Show a => HASS a a
traceValue = proc x -> do
eff Trace -< x
returnA -< x
+51
View File
@@ -0,0 +1,51 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Entity
( entityChangeEvent
, entityChangeEvent'
, entityRead
, entityRead'
, entityBool
, entityBool'
) where
import AFRP (Mealy (..), Event, events, filterA, (>>|), toEvent, named)
import Control.Arrow (arr)
import Control.Category ((>>>))
import Data.Aeson (Value)
import Data.Aeson.Lens (key, _String)
import qualified Data.Text as T
import qualified Data.Set as S
import Control.Lens (has, only, (^?), to)
import qualified Data.Text.Lens as TL
import AFRP.Diagram (emptyDiagram)
entityChangeEvent :: T.Text -> Mealy eff (Event Value) (Event Value)
entityChangeEvent entityId = entityChangeEvent' entityId >>> toEvent
entityChangeEvent' :: T.Text -> Mealy eff (Event Value) (Either () Value)
entityChangeEvent' entityId = named entityId $ Mealy (S.singleton entityId) emptyDiagram $ runMealy (events >>| filterA isEntity)
where
isEntity :: Value -> Bool
isEntity = has (key "event" . key "variables" . key "trigger" . key "entity_id" . _String . only entityId)
entityRead' :: (Read a) => T.Text -> Mealy eff (Event Value) (Either () a)
entityRead' entityId = entityChangeEvent' entityId >>| (arr state >>> arr (maybe (Left ()) Right))
where
state v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "state" . _String . TL.unpacked . to read
entityBool' :: T.Text -> Mealy eff (Event Value) (Either () Bool)
entityBool' entityId = entityChangeEvent' entityId >>| (arr state >>> arr (maybe (Left ()) Right))
where
state v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "state" . _String . TL.unpacked . to toBool
toBool = \case
"on" -> True
"off" -> False
_ -> False
entityRead :: (Read a) => T.Text -> Mealy eff (Event Value) (Event a)
entityRead entityId = entityRead' entityId >>> toEvent
entityBool :: T.Text -> Mealy eff (Event Value) (Event Bool)
entityBool entityId = entityBool' entityId >>> toEvent
+31
View File
@@ -0,0 +1,31 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Arrows #-}
module HomeAssistant.Controller.Hallway where
import HomeAssistant.Controller (Presence, HASS, motion, motionToPresence, traceEvent, callServiceDyn, light, Target (..), LightCommand (..))
import HomeAssistant.Controller.Light.Mode (LightingMode (..), lightingModeEvents)
import AFRP (Event (..))
import qualified AFRP
import Data.Aeson (Value)
import Control.Arrow ((>>>), returnA)
import Data.Time (LocalTime(..), TimeOfDay (..))
import Data.Default (def)
hallwayPresence :: HASS (Event Value) Presence
hallwayPresence = motion "binary_sensor.hallway_movement_occupancy" >>> motionToPresence 500
hallwayLightsController :: HASS (Event Value) ()
hallwayLightsController = proc x -> do
now <- AFRP.currentTime -< ()
p <- hallwayPresence -< x
ev <- lightingModeEvents -< p
traceEvent -< ev
case ev of
-- The lights entity is a "group of lights" in hass
Event LightingOn | lightsAllowed now -> callServiceDyn "Lights on" (light [EntityId "light.hallway_lights"]) -< On def
Event LightingOff -> callServiceDyn "Lights off" (light [EntityId "light.hallway_lights"]) -< Off
_ -> returnA -< ()
where
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
+80
View File
@@ -0,0 +1,80 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Ikea
( IkeaGesture(..)
, IkeaButton(..)
, IkeaRemoteAction(..)
, ikeaQuickButton
, ikeaBoxRemote
) where
import AFRP (Event, toEvent, (>>|))
import Control.Arrow (arr)
import Control.Category ((>>>))
import Control.Lens ((^?), to, traversed)
import Data.Aeson (Value)
import Data.Aeson.Lens (key, _String)
import qualified Data.Text as T
import HomeAssistant.Controller.Entity (entityChangeEvent')
import HomeAssistant.Controller.Effect (HASS)
data IkeaGesture
= ShortClick
| ShortRelease
| DoubleClick
| LongClick
deriving Show
data IkeaButton a = OnButton !a | OffButton !a
deriving Show
toIkeaQuickButton :: T.Text -> Maybe (IkeaButton IkeaGesture)
toIkeaQuickButton = \case
-- 1 is on, 2 is off side of the button
"1_initial_press" -> Just $ OnButton ShortClick
"1_short_release" -> Just $ OnButton ShortRelease
"1_double_press" -> Just $ OnButton DoubleClick
"1_long_press" -> Just $ OnButton LongClick
"2_initial_press" -> Just $ OffButton ShortClick
"2_short_release" -> Just $ OffButton ShortRelease
"2_double_press" -> Just $ OffButton DoubleClick
"2_long_press" -> Just $ OffButton LongClick
_ -> Nothing
ikeaQuickButton :: T.Text -> HASS (Event Value) (Event (IkeaButton IkeaGesture))
ikeaQuickButton entityId =
entityChangeEvent' entityId
>>| arr (maybe (Left ()) Right . eventType)
>>> toEvent
where
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaQuickButton . traversed
data IkeaRemoteAction
= RemoteOn -- Short press on
| RemoteOff -- Short press off
| RemoteBrightnessUp -- Turn brightness up
| RemoteBrightnessDown -- Turn brightness down
| RemoteArrowRight -- Arrow right
| RemoteArrowLeft -- Arrow left
| RemoteBrightnessStop
deriving Show
toIkeaRemoteAction :: T.Text -> Maybe IkeaRemoteAction
toIkeaRemoteAction = \case
"on" -> Just RemoteOn
"off" -> Just RemoteOff
"brightness_move_up" -> Just RemoteBrightnessUp
"brightness_move_down" -> Just RemoteBrightnessDown
"brightness_stop" -> Just RemoteBrightnessStop
"arrow_right_click" -> Just RemoteArrowRight
"arrow_left_click" -> Just RemoteArrowLeft
_ -> Nothing
ikeaBoxRemote :: T.Text -> HASS (Event Value) (Event IkeaRemoteAction)
ikeaBoxRemote entityId = entityChangeEvent' entityId
>>| arr (maybe (Left ()) Right . eventType)
>>> toEvent
where
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaRemoteAction . traversed
+74
View File
@@ -0,0 +1,74 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Arrows #-}
module HomeAssistant.Controller.Kitchen where
import HomeAssistant.Controller
import AFRP (Event (..), (>>||))
import qualified AFRP
import Data.Aeson (Value)
import Control.Arrow ((>>>), Arrow (..), returnA)
import Prelude hiding (id)
import Data.Time (LocalTime(..), TimeOfDay (..))
import Data.Default (def)
-- Kitchen has two "presence" sensors. One IKEA motion sensor and one SwitchBot presence sensor
kitchenPresence :: HASS (Event Value) Presence
kitchenPresence = motion "binary_sensor.kitchen_movement_occupancy" >>> motionToPresence 500
kitchenCeilingController :: HASS (Event Value) ()
kitchenCeilingController = proc x -> do
now <- AFRP.currentTime -< ()
p <- kitchenPresence -< x
ev <- lightingModeEvents -< p
traceEvent -< ev
case ev of
Event LightingOn | lightsAllowed now -> callServiceDyn "light.kitchen_ceiling on" (light [EntityId "light.kitchen_ceiling"]) -< On def
Event LightingOff -> callServiceDyn "light.kitchen_ceiling off" (light [EntityId "light.kitchen_ceiling"]) -< Off
_ -> returnA -< ()
where
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
dinnerLightLevel :: HASS (Event Value) Int
dinnerLightLevel = entityRead "sensor.sijainti_keittio_light_level" >>> AFRP.hold 0
dinnerPresence :: HASS (Event Value) Presence
dinnerPresence = presence "binary_sensor.sijainti_keittio_occupancy" >>> AFRP.hold Unoccupied
dinnerTableController :: HASS (Event Value) ()
dinnerTableController =
((,) <$> dinnerLightLevel <*> dinnerPresence)
>>> arr lightWanted
-- These are done "in parallel", there is a chance that two services are called in one go
>>> mconcat
[ AFRP.named "Lights on" lightsOn
, AFRP.named "Lights sleep" lightsSleep
, AFRP.named "Lights off" lightsOff ]
>>> arr (const ()) -- I don't like this extra arr here
where
lightWanted (lightLevel, occ) = occ == Occupied && lightLevel < 13
lightsOn =
AFRP.edge
>>|| sleep "sleep off" False
>>> callService "Dining light on" (light [EntityId "light.kitchen_dining_large"] $ On def)
lightsSleep =
arr not
>>> AFRP.edge
>>|| sleep "sleep on" True
lightsOff =
arr not
>>> AFRP.waitFor 300
>>|| sleep "sleep off" False
>>> callService "Dining light on" (light [EntityId "light.kitchen_dining_large"] Off)
sleep lbl b = callService lbl (switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] b)
kitchenMotionController :: HASS (Event Value) ()
kitchenMotionController = kitchenCeilingController <> dinnerTableController
@@ -0,0 +1,62 @@
{-# LANGUAGE MonadComprehensions #-}
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Light.Command
( LightCommand(..)
, LightAttributes(..)
, Brightness(..)
, light
, formatLightAttributes
) where
import Data.Aeson (Value, object, (.=))
import Data.Aeson.Types (Pair)
import Data.Default (Default)
import Data.Maybe (catMaybes)
import GHC.Generics (Generic)
import HomeAssistant.Controller.Service (Service (..), Target)
data Brightness = BrightnessPercent Double | BrightnessAbsolute Int
deriving (Show, Generic)
instance Default Brightness where
data LightAttributes = LightAttributes
{ lightBrightness :: Maybe Brightness
, lightColorTemperature :: Maybe Int
, lightTransition :: Maybe Double
}
deriving (Show, Generic)
instance Default LightAttributes where
formatLightAttributes :: LightAttributes -> Maybe Value
formatLightAttributes s = toObject $ catMaybes
[ ["transition" .= x | x <- lightTransition s]
, ["color_temp_kelvin" .= k | k <- lightColorTemperature s]
, ["brightness" .= b | BrightnessAbsolute b <- lightBrightness s]
, ["brightness_pct" .= b | BrightnessPercent b <- lightBrightness s]
]
where
toObject :: [Pair] -> Maybe Value
toObject [] = Nothing
toObject xs = Just $ object xs
data LightCommand
= Off
| On LightAttributes
light :: [Target] -> LightCommand -> Service
light targets (On settings) = Service
{ serviceDomain="light"
, serviceName= "turn_on"
, serviceData= formatLightAttributes settings
, serviceTarget=targets
}
light targets Off = Service
{ serviceDomain="light"
, serviceName= "turn_off"
, serviceData=Nothing
, serviceTarget=targets
}
@@ -0,0 +1,23 @@
module HomeAssistant.Controller.Light.Mode
( LightingMode(..)
, toLightingMode
, lightingModeEvents
) where
import HomeAssistant.Controller.Effect (HASS)
import HomeAssistant.Controller.Presence (Presence (..))
import qualified AFRP
import Control.Arrow (Arrow(..), (>>>))
import GHC.Generics (Generic)
import Data.Serialize (Serialize)
data LightingMode = LightingOn | LightingOff | LightingSleep
deriving (Eq, Show, Generic)
instance Serialize LightingMode
toLightingMode :: Presence -> LightingMode
toLightingMode Occupied = LightingOn
toLightingMode Unoccupied = LightingOff
lightingModeEvents :: HASS Presence (AFRP.Event LightingMode)
lightingModeEvents = AFRP.changes >>> arr (fmap toLightingMode)
@@ -0,0 +1,52 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StrictData #-}
module HomeAssistant.Controller.Light.Observation
( LightObservation(..)
, observedLight
, lightBrightnessEvent
, lightTemperatureEvent
) where
import AFRP (Event, hold)
import Control.Arrow (arr, returnA)
import Control.Category ((>>>), (.))
import Control.Lens ((^?))
import Data.Aeson (Value)
import Data.Aeson.Lens (key, _Integral)
import qualified Data.Text as T
import GHC.Generics (Generic)
import Data.Serialize (Serialize)
import HomeAssistant.Controller.Entity (entityBool, entityChangeEvent)
import HomeAssistant.Controller.Effect (HASS)
import Prelude hiding ((.))
lightBrightnessEvent :: T.Text -> HASS (Event Value) (Event (Maybe Int))
lightBrightnessEvent entityId =
entityChangeEvent entityId
>>> arr (fmap eventBrightness)
where
eventBrightness v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "brightness" . _Integral
lightTemperatureEvent :: T.Text -> HASS (Event Value) (Event (Maybe Int))
lightTemperatureEvent entityId =
entityChangeEvent entityId
>>> arr (fmap eventTemperature)
where
eventTemperature v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "color_temp_kelvin" . _Integral
data LightObservation = LightObservation
{ observedOn :: Bool
, observedBrightness :: Maybe Int
, observedTemperature :: Maybe Int
}
deriving (Show, Generic, Eq)
instance Serialize LightObservation
observedLight :: T.Text -> HASS (Event Value) LightObservation
observedLight entityId = proc ev -> do
e <- hold False . entityBool entityId -< ev
b <- hold Nothing . lightBrightnessEvent entityId -< ev
t <- hold Nothing . lightTemperatureEvent entityId -< ev
returnA -< LightObservation e b t
@@ -0,0 +1,93 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Arrows #-}
module HomeAssistant.Controller.Livingroom where
import HomeAssistant.Controller (HASS, Presence (..), Target (..), presence, callServiceDyn, light, LightCommand (..), traceEvent, callService, activateScene)
import HomeAssistant.Controller.Light.Mode (LightingMode (..), lightingModeEvents)
import qualified AFRP
import Control.Arrow ((>>>), Arrow (..), returnA)
import Data.Aeson (Value)
import Prelude hiding ((.))
import Control.Category ((.))
import Data.Time (LocalTime(..), toGregorian, TimeOfDay (..))
import Data.Default (def)
livingroomPresence :: HASS (AFRP.Event Value) Presence
livingroomPresence = presence "binary_sensor.occupancy_olohuone_derived" >>> AFRP.hold Unoccupied
-- There's a small race condition / corner case bug in the og implementation
-- I have a couple of lights in the Livingroom
--
-- - Ceiling ilght
-- - "Sofa light", a small reading nook light
-- - A few strong lights at a plant corner
--
-- The plant corner lights are not started by the automation. They are started by a separate schedule
-- But, they are turned off by the automation
-- So their status gets messed if their schedule turns on while there is nobody in the room
--
--
-- With that in mind, I'll be explicitly controlling the two lights, without any scene shenanigans
livingroomLightTargets :: [Target]
livingroomLightTargets = [EntityId "light.livingroom_ceiling", EntityId "light.livingroom_sofa"]
livingroomPresenceController :: HASS (AFRP.Event Value) ()
livingroomPresenceController = proc x -> do
ev <- lightingModeEvents . livingroomPresence -< x
traceEvent -< ev
case ev of
AFRP.Event LightingOn -> callServiceDyn "Lights on" (light livingroomLightTargets) -< On def
AFRP.Event LightingOff -> callServiceDyn "Lights off" (light livingroomLightTargets) -< Off
_ -> returnA -< ()
returnA -< ()
data Season = Summer | Fall | Winter | Spring
deriving Show
season :: HASS a Season
season = AFRP.currentTime >>> arr toSeason
where
toSeason t =
case toGregorian (localDay t) of
(_, m, _)
| m >= 12 || m <= 2 -> Winter
| m <= 5 -> Spring
| m <= 8 -> Summer
| otherwise -> Fall
tod :: HASS a TimeOfDay
tod = AFRP.currentTime >>> arr localTimeOfDay
data PlantLightMode = Growth | Ambience
deriving Show
plantLightMode :: HASS (Season, TimeOfDay) (AFRP.Event PlantLightMode)
plantLightMode =
(lightMode &&& ambienceMode) >>> arr (uncurry AFRP.lMerge)
where
lightMode = arr (uncurry lightWanted) >>> AFRP.edge >>> arr (AFRP.tag Growth)
ambienceMode = arr (uncurry ambienceWanted) >>> AFRP.edge >>> arr (AFRP.tag Ambience)
-- Full brightness during daytime only non-summer
lightWanted :: Season -> TimeOfDay -> Bool
lightWanted Summer _ = False
lightWanted _ TimeOfDay{todHour=10,todMin=00} = True
lightWanted _ _ = False
-- Ambience mode is always
ambienceWanted :: Season -> TimeOfDay -> Bool
ambienceWanted _ TimeOfDay{todHour=20,todMin=0} = True
ambienceWanted _ _ = False
livingroomPlantLights :: HASS (AFRP.Event a) ()
livingroomPlantLights = (season &&& tod)
>>> plantLightMode
>>> setLights
where
setLights = proc mode -> do
case mode of
AFRP.Event Growth -> callService "scene.olohuoneen_kasvivalo" (activateScene "scene.olohuoneen_kasvivalo") -< ()
AFRP.Event Ambience -> callService "scene.kasvivalo_iltatila" (activateScene "scene.kasvivalo_iltatila") -< ()
_ -> returnA -< ()
+55
View File
@@ -0,0 +1,55 @@
module HomeAssistant.Controller.Presence
( Presence(..)
, presence
, Motion(..)
, motion
, motionToPresence
) where
import AFRP (Event, hold, lMerge, waitFor, tag, edge)
import Control.Arrow (arr, (&&&))
import Control.Category ((>>>))
import Data.Aeson (Value)
import qualified Data.Text as T
import Data.Bool (bool)
import Data.Serialize (Serialize)
import GHC.Generics (Generic)
import Data.Time (NominalDiffTime)
import HomeAssistant.Controller.Entity (entityBool)
import HomeAssistant.Controller.Effect (HASS)
data Presence = Occupied | Unoccupied
deriving (Show, Eq, Generic)
instance Serialize Presence
presence :: T.Text -> HASS (Event Value) (Event Presence)
presence entityId = entityBool entityId
>>> arr (fmap (bool Unoccupied Occupied))
data Motion = MotionDetected | MotionNotDetected | MotionUnknown
deriving (Show, Eq, Generic)
motion :: T.Text -> HASS (Event Value) Motion
motion entityId = entityBool entityId
>>> arr (fmap (bool MotionNotDetected MotionDetected))
>>> hold MotionUnknown
-- Convert a motion status into a simulated presence
--
-- A motion tracker detects _motion_, but if you are still, it can't detect you.
-- A simple and cheap heuristic is to assume the person is a bit longer there
motionToPresence :: NominalDiffTime -> HASS Motion Presence
motionToPresence delay = (eventOccupied &&& eventUnoccupied)
>>> arr (uncurry lMerge)
>>> AFRP.hold Unoccupied
where
eventOccupied :: HASS Motion (Event Presence)
eventOccupied = arr (== MotionDetected) >>> edge >>> arr (fmap (const Occupied))
eventUnoccupied :: HASS Motion (Event Presence)
eventUnoccupied = arr (== MotionNotDetected) >>> waitFor delay >>> arr (tag Unoccupied)
instance Serialize Motion
+34
View File
@@ -0,0 +1,34 @@
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Ruuvi
( Ruuvi(..)
, ruuvi
, ruuviTemperatures
, ruuviPressures
, ruuviController
) where
import AFRP (Mealy, Event, hold, changes, rollup)
import Control.Category ((>>>))
import Data.Aeson (Value)
import HomeAssistant.Controller (entityRead, traceEvent, HASS)
import Control.Arrow (Arrow(..))
import GHC.Generics (Generic)
import Data.Serialize (Serialize)
ruuviTemperatures :: Mealy eff (Event Value) Double
ruuviTemperatures = entityRead @Double "sensor.ruuvitag_b168_temperature" >>> hold 0
ruuviPressures :: Mealy eff (Event Value) Double
ruuviPressures = entityRead "sensor.ruuvitag_b168_pressure" >>> hold 0
data Ruuvi = Ruuvi { ruuviTemperature :: Double, ruuviPressure :: Double }
deriving (Show, Eq, Generic)
instance Serialize Ruuvi
ruuvi :: Mealy eff (Event Value) (Event Ruuvi)
ruuvi = (Ruuvi <$> ruuviTemperatures <*> ruuviPressures) >>> changes
ruuviController :: HASS (Event Value) ()
ruuviController = ruuvi >>> rollup 1 30 >>> traceEvent >>> arr (const ())
+21
View File
@@ -0,0 +1,21 @@
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Scene
( activateScene
, activateSceneWith
) where
import Data.Aeson (Value)
import qualified Data.Text as T
import HomeAssistant.Controller.Service (Service (..), Target (..))
activateScene :: T.Text -> Service
activateScene sceneId = activateSceneWith sceneId Nothing
activateSceneWith :: T.Text -> Maybe Value -> Service
activateSceneWith sceneId d = Service
{ serviceDomain="scene"
, serviceName= "turn_on"
, serviceTarget= [EntityId sceneId]
, serviceData = d
}
+18
View File
@@ -0,0 +1,18 @@
module HomeAssistant.Controller.Service
( Service(..)
, Target(..)
) where
import Data.Aeson (Value)
import qualified Data.Text as T
data Target = EntityId !T.Text | AreaId !T.Text
deriving (Show,Eq,Ord)
data Service = Service
{ serviceDomain :: T.Text
, serviceName :: T.Text
, serviceData :: Maybe Value
, serviceTarget :: [Target]
}
deriving (Show, Eq)
+14
View File
@@ -0,0 +1,14 @@
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Switch (switchService) where
import Data.Bool (bool)
import HomeAssistant.Controller.Service (Service (..), Target)
switchService :: [Target] -> Bool -> Service
switchService targets b = Service
{ serviceDomain="switch"
, serviceName= bool "turn_off" "turn_on" b
, serviceData=Nothing
, serviceTarget=targets
}
+115 -48
View File
@@ -4,81 +4,148 @@
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Runtime module HomeAssistant.Runtime
( defaultMain ( defaultMain,
, step step,
, CallIdGen CallIdGen,
, mkCallIdGen mkCallIdGen,
, dryRunHassEval dryRunHassEval,
, Controller(..) Controller (..),
, runController runController,
) where )
where
import AFRP (Event (..), Mealy (..), Request (..)) import AFRP (Auto, DecodedAuto (..), Event (..), Mealy (..), Request (..), load, stepAutoSerializing)
import Control.Concurrent.Async (async, waitAny)
import Control.Concurrent.STM (atomically, dupTChan, readTChan) import Control.Concurrent.STM (atomically, dupTChan, readTChan)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Aeson (Value) import Data.Aeson (Value)
import qualified Data.Text as T import Data.Foldable (forM_)
import Data.Time (getCurrentTime) import Data.Maybe (fromMaybe)
import Data.Void (Void, absurd) import Data.Text qualified as T
import Data.Time (getCurrentTime, getCurrentTimeZone)
import Data.UUID (UUID, toText)
import Data.UUID.V4 qualified as UUID.V4
import Data.Void (Void)
import GHC.Stack (HasCallStack)
import HomeAssistant.Controller (HASS, HASSEff (..)) import HomeAssistant.Controller (HASS, HASSEff (..))
import HomeAssistant.Controller.Bedroom (bedroomButtonController, bedroomDrawerController, bedroomPresenceController, humidifierController)
import HomeAssistant.Controller.Children (childrenBedroomButtonController, schoolLightController, childrenAirFilterController)
import HomeAssistant.Controller.Hallway (hallwayLightsController)
import HomeAssistant.Controller.Kitchen (kitchenMotionController)
import HomeAssistant.Controller.Livingroom (livingroomPlantLights, livingroomPresenceController)
import HomeAssistant.Runtime.Bus import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Connection (readerAction, writerAction) import HomeAssistant.Runtime.Connection (readerAction, writerAction)
import HomeAssistant.Runtime.Supervisor (defaultBackoff, supervised) import HomeAssistant.Runtime.Flags (loadFlags)
import HomeAssistant.Runtime.Metrics qualified
import HomeAssistant.Runtime.RateLimit (registerRateLimitMetrics, slidingWindowLimiter)
import HomeAssistant.Runtime.Supervisor (supervised)
import HttpServer qualified
import Katip (KatipContext, Namespace (Namespace), Severity (..), logF, logLocM, ls, runKatipContextT, runKatipT, sl, katipAddNamespace)
import Network.Socket (withSocketsDo) import Network.Socket (withSocketsDo)
import System.Environment (getEnv) import System.Environment (getEnv, lookupEnv)
import HomeAssistant.Controller.Bedroom (bedroomPresenceController, bedroomButtonController, bedroomDrawerController) import System.FilePath ((</>))
import Data.UUID (UUID, toText) import System.Metrics qualified
import qualified Data.UUID.V4 as UUID.V4 import Text.Read (readMaybe)
import Katip (runKatipT, logF, sl, Severity (..), ls, Namespace (Namespace), runKatipContextT) import UnliftIO.Async
import Control.Monad.IO.Class (liftIO, MonadIO) import Control.Monad.Catch (MonadCatch)
import Control.Monad.Fix (MonadFix) import Control.Exception.Annotated (checkpoint, Annotation (..))
import AFRP.Diagram (renderF)
step :: (MonadFix m, MonadIO m) => (forall x. eff x -> m x) -> UUID -> Mealy eff a b -> a -> m (b, Mealy eff a b) step :: (MonadIO m) => FilePath -> T.Text -> UUID -> Auto m a b -> a -> m (b, Auto m a b)
step nt trace (Mealy f) a = do step path name trace st a = do
now <- liftIO getCurrentTime now <- liftIO getCurrentTime
f nt (Request now trace) a tz <- liftIO getCurrentTimeZone
let req = Request now tz trace name
stepAutoSerializing path st req a
data Controller = forall b. Controller T.Text (HASS (Event Value) b) Bool data Controller = forall b. Controller T.Text (HASS (Event Value) b)
controllers :: [Controller] controllers :: [Controller]
controllers = controllers =
[ Controller "bedroom-presence" bedroomPresenceController False [ Controller "bedroom-presence" bedroomPresenceController,
, Controller "bedroom-button" bedroomButtonController False -- This works but leaving for vacation Controller "bedroom-button" bedroomButtonController,
, Controller "bedroom-drawer" bedroomDrawerController True Controller "bedroom-drawer" bedroomDrawerController,
Controller "bedroom-humidifier" humidifierController,
Controller "school-light-controller" schoolLightController,
Controller "kitchen-motion-controller" kitchenMotionController,
Controller "livingroom-presence" livingroomPresenceController,
Controller "hallway-motion-controller" hallwayLightsController,
Controller "children-button" childrenBedroomButtonController,
Controller "livingroom-plants" livingroomPlantLights,
Controller "children-filter" childrenAirFilterController
] ]
-- | Steps the machine for every inbound message; service calls go to the -- | Steps the machine for every inbound message; service calls go to the
-- bus. A restart re-dups the inbound channel and starts from the machine's -- bus. A restart re-dups the inbound channel and starts from the machine's
-- initial state; messages broadcast during the restart window are lost. -- initial state; messages broadcast during the restart window are lost.
runController :: Bus -> Controller -> IO Void runController :: forall m. (HasCallStack, MonadCatch m, KatipContext m, MonadIO m) => FilePath -> Bus -> Controller -> m Void
runController bus (Controller name machine _enabled) = do runController rootDir bus (Controller name machine) = checkpoint (Annotation name) $ katipAddNamespace ns $ do
inbound <- atomically (dupTChan (busInbound bus)) inbound <- liftIO $ atomically (dupTChan (busInbound bus))
go inbound machine let workerDefinition = runMealy machine (channelHassEval @m bus)
let path = rootDir </> T.unpack name
worker <-
load path workerDefinition >>= \case
Decoded a -> pure a
FailDecode err a -> a <$ logLocM WarningS (ls ("Failed to load (" <> T.unpack name <> "): " <> err))
go path inbound worker
where where
go inbound f = do ns = Namespace [name]
msg <- atomically (readTChan inbound) go path inbound f = do
uuid <- UUID.V4.nextRandom msg <- liftIO $ atomically (readTChan inbound)
let ns = Namespace [name] uuid <- liftIO UUID.V4.nextRandom
(_, f') <- step (runKatipContextT (busLogEnv bus) () ns . channelHassEval bus) uuid f (Event msg) (_, next) <- step path name uuid f msg
go inbound f' go path inbound next
lookupPort :: (MonadFail m, MonadIO m) => m Int
lookupPort = do
m <- liftIO (lookupEnv "HA_METRICS_PORT")
case m of
Nothing -> pure 8124
Just s -> case readMaybe s of
Just p | p >= 1 && p <= 65535 -> pure p
_ -> fail ("HA_METRICS_PORT must be a port in 1..65535: " <> s)
defaultMain :: IO () defaultMain :: IO ()
defaultMain = withSocketsDo $ withBus $ \bus -> do defaultMain =
token <- getEnv "HA_TOKEN" withSocketsDo $
host <- getEnv "HA_HOST" getSeverity >>= \s -> withLogEnv s $ \le -> runKatipContextT le () mempty $ do
let workers = logLocM InfoS "Hello world"
[ ("reader", readerAction host 8123 token bus) store <- liftIO System.Metrics.newStore
, ("writer", writerAction bus) liftIO $ System.Metrics.registerGcMetrics store
] ++ [ (name, runController bus c) | c@(Controller name _ True) <- controllers ] appMetrics <- liftIO $ HomeAssistant.Runtime.Metrics.registerAppMetrics store
as <- mapM (\(name, act) -> async (supervised name defaultBackoff act)) workers rateLimitMetrics <- registerRateLimitMetrics store
(_, v) <- waitAny as rootPath <- fromMaybe "/tmp/" <$> liftIO (lookupEnv "HA_LIB_DIR")
absurd v let allNames = map (\(Controller n _) -> n) controllers
flags <- loadFlags rootPath allNames
withBus le appMetrics flags $ \bus -> do
token <- liftIO $ getEnv "HA_TOKEN"
host <- liftIO $ getEnv "HA_HOST"
let rrdPath = rootPath </> "hass-controller.rrd"
rrdtool <- fromMaybe "rrdtool" <$> liftIO (lookupEnv "HA_RRDTOOL")
metricsPort <- lookupPort
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
forM_ controllers $ \(Controller n m) ->
logLocM InfoS $ ls $ n <> ": " <> fromMaybe "" (runDiagramC m renderF)
let ents = foldMap (\(Controller _ m) -> entities m) controllers
workers =
[ ("reader", readerAction host 8123 token ents bus),
("writer", writerAction writerLimiter bus),
("metrics", HomeAssistant.Runtime.Metrics.metricsAction store rrdPath rrdtool),
("metrics-http", HttpServer.runHttpServer (busLogEnv bus) rrdPath rrdtool (busFlags bus) metricsPort)
]
++ [(name, runController rootPath bus c) | c@(Controller name _) <- controllers]
runKatipContextT (busLogEnv bus) () mempty $
mapConcurrently_ (uncurry supervised) workers
where
getSeverity = maybe InfoS (const DebugS) <$> lookupEnv "HA_DEBUG"
dryRunHassEval :: Namespace -> Bus -> HASSEff a -> IO a dryRunHassEval :: Namespace -> Bus -> HASSEff a -> IO a
dryRunHassEval ns bus = \case dryRunHassEval ns bus = \case
CallService req x -> runKatipT (busLogEnv bus) $ do CallService req x -> runKatipT (busLogEnv bus) $ do
callId <- liftIO $ generateCallId (busGen bus) callId <- liftIO $ generateCallId (busGen bus)
logF (sl "traceId" (toText (requestTraceId req))) ns DebugS (ls $ show (callId, x)) logF (sl "traceId" (toText (requestTraceId req))) ns DebugS (ls $ show (callId, x))
CallServices req xs -> runKatipT (busLogEnv bus) $ forM_ xs $ \x -> do
callId <- liftIO $ generateCallId (busGen bus)
logF (sl "traceId" (toText (requestTraceId req))) ns DebugS (ls $ show (callId, x))
Debug x -> runKatipT (busLogEnv bus) $ do Debug x -> runKatipT (busLogEnv bus) $ do
logF () ns DebugS (ls $ show x) logF () ns DebugS (ls $ show x)
Trace req x -> runKatipT (busLogEnv bus) $ do Trace req x -> runKatipT (busLogEnv bus) $ do
+54 -18
View File
@@ -1,12 +1,16 @@
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module HomeAssistant.Runtime.Bus module HomeAssistant.Runtime.Bus
( Bus(..) ( Bus(..)
, CallIdGen(..) , CallIdGen(..)
, mkCallIdGen , mkCallIdGen
, withBus , withBus
, recordInbound
, recordOutbound
, channelHassEval , channelHassEval
, withLogEnv
) where ) where
import Control.Concurrent.STM import Control.Concurrent.STM
@@ -21,47 +25,79 @@ import Control.Concurrent.STM
import Data.Aeson (Value) import Data.Aeson (Value)
import Data.IORef (atomicModifyIORef', newIORef) import Data.IORef (atomicModifyIORef', newIORef)
import HomeAssistant.Controller (HASSEff (..), Service) import HomeAssistant.Controller (HASSEff (..), Service)
import HomeAssistant.Runtime.Metrics (AppMetrics (..))
import Network.WebSockets (Connection) import Network.WebSockets (Connection)
import Katip (LogEnv, closeScribes, mkHandleScribe, ColorStrategy (..), permitItem, Severity (..), Verbosity (V2), registerScribe, defaultScribeSettings, initLogEnv, ls, sl, logFM, katipAddContext, KatipContext) import Katip (LogEnv, closeScribes, mkHandleScribe, ColorStrategy (..), permitItem, Severity (..), Verbosity (V2), registerScribe, defaultScribeSettings, initLogEnv, ls, sl, logFM, katipAddContext, KatipContext)
import Control.Exception (bracket) import Control.Exception (bracket)
import System.IO (stdout) import System.IO (stdout)
import System.Metrics.Counter (inc)
import Data.UUID (toText) import Data.UUID (toText)
import AFRP (Request(..)) import AFRP (Request(..), Event(..))
import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.IO.Class (MonadIO, liftIO)
import HomeAssistant.Runtime.Flags (Flags)
import Katip.Scribes.Journal (mkJournalScribe)
import System.Environment (lookupEnv)
import Data.Maybe (isJust)
-- | Shared runtime state: inbound is a broadcast channel (controllers -- | Shared runtime state: inbound is a broadcast channel (controllers
-- read from 'dupTChan' copies), outbound queues service calls for the -- read from 'dupTChan' copies), outbound queues service calls for the
-- writer, conn holds the current websocket (Nothing before first connect). -- writer, conn holds the current websocket (Nothing before first connect).
data Bus = Bus data Bus = Bus
{ busInbound :: TChan Value { busInbound :: TChan (Event Value)
, busOutbound :: TChan (Request, Service) , busOutbound :: TChan (Request, Service)
, busConn :: TVar (Maybe Connection) , busConn :: TVar (Maybe Connection)
, busGen :: CallIdGen , busGen :: CallIdGen
, busLogEnv :: LogEnv , busLogEnv :: LogEnv
, busMetrics :: AppMetrics
, busFlags :: Flags
} }
withBus :: (Bus -> IO a) -> IO a withLogEnv :: Severity -> (LogEnv -> IO a) -> IO a
withBus callback = do withLogEnv severity f = do
handleScribe <- mkHandleScribe ColorIfTerminal stdout (permitItem DebugS) V2 let makeLogEnv = registerJournalScribe =<< registerHandleScribe =<< initLogEnv "hass-controller" "production"
let makeLogEnv = registerScribe "stdout" handleScribe defaultScribeSettings =<< initLogEnv "hass-controller" "production"
-- closeScribes will stop accepting new logs, flush existing ones and clean up resources -- closeScribes will stop accepting new logs, flush existing ones and clean up resources
bracket makeLogEnv closeScribes $ \le -> do bracket makeLogEnv closeScribes $ \le -> f le
bus <- Bus where
<$> newBroadcastTChanIO registerJournalScribe :: LogEnv -> IO LogEnv
<*> newTChanIO registerJournalScribe le = do
<*> newTVarIO Nothing journalScribe <- mkJournalScribe (permitItem severity) V2
<*> mkCallIdGen 0 registerScribe "journalctl" journalScribe defaultScribeSettings le
<*> pure le registerHandleScribe le = do
callback bus systemdUnit <- isJust <$> lookupEnv "HA_CONTROLLER_SYSTEMD"
if systemdUnit
then pure le -- ignore stdout when running in systemd
else do
handleScribe <- mkHandleScribe ColorIfTerminal stdout (permitItem severity) V2
registerScribe "stdout" handleScribe defaultScribeSettings le
channelHassEval :: (MonadIO m, KatipContext m) => Bus -> HASSEff a -> m a withBus :: MonadIO m => LogEnv -> AppMetrics -> Flags -> (Bus -> m a) -> m a
withBus le metrics flags callback = do
bus <- Bus
<$> liftIO newBroadcastTChanIO
<*> liftIO newTChanIO
<*> liftIO (newTVarIO Nothing)
<*> liftIO (mkCallIdGen 0)
<*> pure le
<*> pure metrics
<*> pure flags
callback bus
recordInbound :: Bus -> IO ()
recordInbound bus = inc (amTriggersIn (busMetrics bus))
recordOutbound :: Bus -> IO ()
recordOutbound bus = inc (amServicesOut (busMetrics bus))
channelHassEval :: forall m a. (MonadIO m, KatipContext m) => Bus -> HASSEff a -> m a
channelHassEval bus = \case channelHassEval bus = \case
CallService req svc -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $ do CallService req svc -> emit req svc
logFM DebugS (ls $ show svc) CallServices req svcs -> mapM_ (emit req) svcs
liftIO $ atomically $ writeTChan (busOutbound bus) (req, svc)
Debug x -> logFM DebugS (ls $ show x) Debug x -> logFM DebugS (ls $ show x)
Trace req x -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $ Trace req x -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $
logFM InfoS (ls $ show x) logFM InfoS (ls $ show x)
where
emit :: Request -> Service -> m ()
emit req svc = liftIO $ atomically $ writeTChan (busOutbound bus) (req, svc)
newtype CallIdGen = CallIdGen { generateCallId :: IO Int } newtype CallIdGen = CallIdGen { generateCallId :: IO Int }
+78 -34
View File
@@ -4,7 +4,9 @@
module HomeAssistant.Runtime.Connection module HomeAssistant.Runtime.Connection
( readerAction ( readerAction
, writerAction , writerAction
, dispatchService
, encodeService , encodeService
, isTriggerEvent
) where ) where
import Control.Concurrent.STM import Control.Concurrent.STM
@@ -15,35 +17,41 @@ import Control.Concurrent.STM
, writeTChan , writeTChan
, writeTVar , writeTVar
) )
import Control.Exception (onException) import Control.Concurrent (threadDelay)
import Control.Exception.Annotated (throw) import Control.Exception.Annotated (throw)
import Control.Lens ((^?)) import Control.Lens ((^?))
import Control.Monad (forever) import Control.Monad (forever, forM_, when)
import Data.Aeson (Value, eitherDecode, encode, object, (.=)) import Data.Aeson (Value, eitherDecode, encode, object, (.=))
import Data.Aeson.Lens (key, _String) import Data.Aeson.Lens (key, _String)
import qualified Data.ByteString.Lazy as BL import qualified Data.Set as S
import qualified Data.Text as T import qualified Data.Text as T
import Data.Void (Void) import Data.Void (Void)
import HomeAssistant.Controller (Service (..), Target (..)) import HomeAssistant.Controller (Service (..), Target (..))
import HomeAssistant.Runtime.Bus import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Flags (isEnabled)
import HomeAssistant.Runtime.Supervisor (Fatal (..)) import HomeAssistant.Runtime.Supervisor (Fatal (..))
import qualified Network.WebSockets as WS import qualified Network.WebSockets as WS
import Katip (runKatipContextT, sl, logFM, Severity (..), ls) import Katip (sl, logFM, Severity (..), ls, Namespace (Namespace), KatipContext, katipAddNamespace, katipAddContext, logLocM)
import Data.UUID (toText) import Data.UUID (toText)
import AFRP (Request(..)) import AFRP (Request(..), Event(..))
import Control.Monad.IO.Class (liftIO, MonadIO)
import HomeAssistant.Runtime.RateLimit (RateLimited, RateLimiter, runRateLimited)
import GHC.Stack (HasCallStack)
import UnliftIO (MonadUnliftIO, race, withRunInIO)
import Control.Monad.Catch (MonadCatch, onException)
-- | Connect, authenticate, subscribe, then receive and broadcast forever. -- | Connect, authenticate, subscribe, then receive and broadcast forever.
-- Restarting this action reconnects. All setup sends happen before the -- Restarting this action reconnects. All setup sends happen before the
-- connection is published in the bus, so only the writer sends afterwards. -- connection is published in the bus, so only the writer sends afterwards.
readerAction :: String -> Int -> String -> Bus -> IO Void readerAction :: (MonadCatch m, HasCallStack, KatipContext m, MonadUnliftIO m, MonadIO m) => String -> Int -> String -> S.Set T.Text -> Bus -> m Void
readerAction host port token bus = readerAction host port token ents bus = katipAddNamespace "receiver" $ withRunInIO $ \rio ->
WS.runClient host port "/api/websocket" $ \conn -> do WS.runClient host port "/api/websocket" $ \conn -> rio $ do
handshake conn token liftIO $ handshake conn token
subscribe bus conn subscribe bus conn ents
atomically $ writeTVar (busConn bus) (Just conn) liftIO $ atomically $ writeTVar (busConn bus) (Just conn)
putStrLn "[reader] connected" logLocM InfoS "connected"
-- Unpublish on exit so the writer blocks and the backlog survives the outage. -- Unpublish on exit so the writer blocks and the backlog survives the outage.
receiveLoop bus conn `onException` atomically (writeTVar (busConn bus) Nothing) receiveLoop bus conn `onException` liftIO (atomically (writeTVar (busConn bus) Nothing))
handshake :: WS.Connection -> String -> IO () handshake :: WS.Connection -> String -> IO ()
handshake conn token = do handshake conn token = do
@@ -62,23 +70,39 @@ expectType expected msg =
Just t | t == expected -> pure () Just t | t == expected -> pure ()
_ -> throw (Fatal $ "expected " <> expected <> ", got: " <> T.pack (show msg)) _ -> throw (Fatal $ "expected " <> expected <> ", got: " <> T.pack (show msg))
subscribe :: Bus -> WS.Connection -> IO () isTriggerEvent :: Value -> Bool
subscribe bus conn = do isTriggerEvent v = v ^? key "type" . _String == Just "event"
sid <- generateCallId (busGen bus)
WS.sendTextData conn $ encode $ object subscribe :: HasCallStack => KatipContext m => Bus -> WS.Connection -> S.Set T.Text -> m ()
[ "id" .= sid subscribe bus conn ents =
, "type" .= ("subscribe_events" :: T.Text) forM_ (S.toList ents) $ \entityId -> do
, "event_type" .= ("state_changed" :: T.Text) logLocM InfoS $ ls entityId
] sid <- liftIO $ generateCallId (busGen bus)
liftIO $ WS.sendTextData conn $ encode $ object
[ "id" .= sid
, "type" .= ("subscribe_trigger" :: T.Text)
, "trigger" .= object
[ "platform" .= ("state" :: T.Text)
, "entity_id" .= entityId
]
]
-- | Undecodable messages are skipped: reconnecting cannot fix a decode -- | Undecodable messages are skipped: reconnecting cannot fix a decode
-- problem, so crashing here would only produce a hot restart loop. -- problem, so crashing here would only produce a hot restart loop.
receiveLoop :: Bus -> WS.Connection -> IO Void --
-- Each read races a one-second timeout: a timeout broadcasts 'Tick' so
-- time-based primitives (debounce, rollup, fixed, ...) keep advancing
-- even when no state changes arrive.
receiveLoop :: (HasCallStack, MonadUnliftIO m, KatipContext m) => Bus -> WS.Connection -> m Void
receiveLoop bus conn = forever $ do receiveLoop bus conn = forever $ do
msg <- WS.receiveData conn :: IO BL.ByteString winner <- race (liftIO $ threadDelay 1_000_000) (liftIO $ WS.receiveData conn)
case eitherDecode msg of case winner of
Left err -> putStrLn $ "[reader] skipping undecodable message: " <> err Left () -> liftIO $ atomically $ writeTChan (busInbound bus) Tick
Right v -> atomically $ writeTChan (busInbound bus) v Right msg -> case eitherDecode msg of
Left err -> logLocM WarningS $ ls $ "skipping undecodable message: " <> err
Right v -> liftIO $ do
when (isTriggerEvent v) (recordInbound bus)
atomically $ writeTChan (busInbound bus) (Event v)
receiveJSON :: WS.Connection -> IO Value receiveJSON :: WS.Connection -> IO Value
receiveJSON conn = do receiveJSON conn = do
@@ -87,15 +111,34 @@ receiveJSON conn = do
Left err -> throw (Fatal $ "Invalid JSON from Home Assistant: " <> T.pack err) Left err -> throw (Fatal $ "Invalid JSON from Home Assistant: " <> T.pack err)
Right x -> pure x Right x -> pure x
writerAction :: Bus -> IO Void
writerAction bus = forever $ do
(request, svc) <- atomically $ readTChan (busOutbound bus) sendWithId :: (MonadIO m, KatipContext m) => Bus -> WS.Connection -> Service -> RateLimited m ()
conn <- atomically $ readTVar (busConn bus) >>= maybe retry pure sendWithId bus conn svc = katipAddNamespace "connection" $ do
callId <- generateCallId (busGen bus) callId <- liftIO $ generateCallId (busGen bus)
let textData = encode $ encodeService callId svc let textData = encode $ encodeService callId svc
runKatipContextT (busLogEnv bus) (sl "traceId" (toText (requestTraceId request))) "connection" $ logFM DebugS (ls textData)
logFM DebugS (ls textData) liftIO $ recordOutbound bus
WS.sendTextData conn textData liftIO $ WS.sendTextData conn textData
writerAction :: (MonadIO m, KatipContext m, MonadCatch m) => RateLimiter -> Bus -> m Void
writerAction rateLimiter bus = forever $ do
(request, svc) <- liftIO $ atomically $ readTChan (busOutbound bus)
katipAddContext (sl "traceId" (toText (requestTraceId request))) $
katipAddNamespace (Namespace [requestHandler request]) $
dispatchService rateLimiter bus request svc
-- | Sends the service call, or logs and drops it when its handler is disabled.
dispatchService
:: (MonadIO m, KatipContext m, MonadCatch m)
=> RateLimiter -> Bus -> Request -> Service -> m ()
dispatchService rateLimiter bus request svc = do
enabled <- isEnabled (busFlags bus) (requestHandler request)
let logPrefix = if enabled then "Calling: " else "Skipping: "
logFM InfoS (ls $ logPrefix <> show svc)
when enabled $ do
conn <- liftIO $ atomically $ readTVar (busConn bus) >>= maybe retry pure
runRateLimited rateLimiter $ sendWithId bus conn svc
encodeService :: Int -> Service -> Value encodeService :: Int -> Service -> Value
encodeService callId Service{..} = object $ encodeService callId Service{..} = object $
@@ -106,6 +149,7 @@ encodeService callId Service{..} = object $
, "target" .= targetObject serviceTarget , "target" .= targetObject serviceTarget
] <> maybe [] (\d -> ["service_data" .= d]) serviceData ] <> maybe [] (\d -> ["service_data" .= d]) serviceData
-- | A single target encodes as a scalar; multiple encode as a list. Empty -- | A single target encodes as a scalar; multiple encode as a list. Empty
-- lists are omitted so Home Assistant receives only populated keys. -- lists are omitted so Home Assistant receives only populated keys.
targetObject :: [Target] -> Value targetObject :: [Target] -> Value
+93
View File
@@ -0,0 +1,93 @@
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Runtime.Flags
( Name
, Flags(..)
, loadFlags
, isEnabled
, setEnabled
, allFlags
, validNames
) where
import Control.Concurrent.MVar (MVar, newMVar, withMVar)
import Control.Concurrent.STM (TVar, atomically, newTVarIO, readTVarIO, stateTVar)
import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Conduit as C
import Conduit ((.|))
import Data.Aeson (decodeFileStrict', encode)
import qualified Data.ByteString.Lazy as BL
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Set (Set)
import qualified Data.Set as S
import Data.Text (Text)
import System.FilePath ((</>))
import System.IO.Error (isDoesNotExistError)
import GHC.Stack (HasCallStack)
import Katip (KatipContext, logLocM, Severity (..), ls)
import Control.Monad.Catch (MonadCatch, handle)
import Control.Exception (IOException)
import Data.Maybe (fromMaybe)
type Name = Text
data Flags = Flags
{ flagsState :: TVar (Map Name Bool)
, flagsLock :: MVar ()
, flagsPath :: FilePath
, flagsValidNames :: Set Text
}
loadFlags :: (KatipContext m, MonadCatch m, MonadIO m) => FilePath -> [Name] -> m Flags
loadFlags rootPath allNames = do
let path = rootPath </> "handlers.json"
fileMap <- readFlagsFile path
let defaults = M.fromList [(n, True) | n <- allNames]
initial = M.unionWith const fileMap defaults
tv <- liftIO $ newTVarIO initial
lock <- liftIO $ newMVar ()
pure Flags
{ flagsState = tv
, flagsLock = lock
, flagsPath = path
, flagsValidNames = S.fromList allNames
}
readFlagsFile :: forall m. (HasCallStack, KatipContext m, MonadCatch m) => FilePath -> m (Map Name Bool)
readFlagsFile path =
handle onMissingOrUnreadable $ do
decoded <- liftIO $ decodeFileStrict' path
case decoded of
Nothing -> do
logLocM WarningS $ ls ("handlers.json is unparseable; treating all handlers as enabled: " <> path)
pure mempty
Just m -> pure (fromMaybe mempty m)
where
onMissingOrUnreadable :: HasCallStack => IOException -> m (Map Name Bool)
onMissingOrUnreadable e
| isDoesNotExistError e = pure mempty
| otherwise = do
logLocM WarningS $ ls ("could not read handlers.json (" <> show e <> "); treating all handlers as enabled")
pure mempty
isEnabled :: MonadIO m => Flags -> Name -> m Bool
isEnabled flags name = liftIO $
M.findWithDefault True name <$> readTVarIO (flagsState flags)
allFlags :: MonadIO m => Flags -> m (Map Name Bool)
allFlags flags = liftIO $ readTVarIO (flagsState flags)
setEnabled :: MonadIO m => Flags -> Name -> Bool -> m ()
setEnabled Flags{flagsState, flagsLock, flagsPath} name val =
liftIO $ withMVar flagsLock $ \_ -> do
m <- atomically $ stateTVar flagsState $ \cur ->
let next = M.insert name val cur in (next, next)
safeWrite flagsPath m
validNames :: Flags -> Set Text
validNames = flagsValidNames
safeWrite :: FilePath -> Map Name Bool -> IO ()
safeWrite path m = C.runResourceT $ C.runConduit $
C.yieldMany [BL.toStrict (encode m)] .| C.sinkFileCautious path
+282
View File
@@ -0,0 +1,282 @@
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Runtime.Graphing
( Range (..)
, parseRange
, rangeStart
, Series (..)
, GraphSpec (..)
, graphs
, lookupGraph
, parseNameParam
, buildGraphArgs
, readProcessBytes
, Graph(..)
, renderGraph
, rangeSuffix
) where
import Control.Exception (evaluate)
import Control.Monad.IO.Class (liftIO, MonadIO)
import qualified Data.ByteString as BS
import Data.Text (Text)
import qualified Data.Text as T
import System.Exit (ExitCode (..))
import System.IO (hGetContents)
import System.Process (CreateProcess (..), StdStream (..), proc, waitForProcess, withCreateProcess)
import Servant.API (FromHttpApiData (..), ToHttpApiData (..))
data Range = TenMinutes | OneHour | OneDay | OneWeek | OneMonth
deriving (Eq, Show, Bounded, Enum)
rangeSuffix :: Range -> String
rangeSuffix TenMinutes = "10m"
rangeSuffix OneHour = "1h"
rangeSuffix OneDay = "24h"
rangeSuffix OneWeek = "7d"
rangeSuffix OneMonth = "30d"
parseRange :: Text -> Maybe Range
parseRange t = lookup t [(T.pack (rangeSuffix r), r) | r <- [minBound .. maxBound]]
instance ToHttpApiData Range where
toQueryParam = T.pack . rangeSuffix
instance FromHttpApiData Range where
parseQueryParam x = maybe (Left ("Could not parse '" <> x <> "' as Range")) Right $ parseRange x
rangeStart :: Range -> String
rangeStart r = "end-" ++ rangeSuffix r
data CF = Average | Minimum | Maximum | Last
deriving (Eq, Show)
data Source = Source
{ srcDs :: String
, srcCF :: CF
}
deriving (Eq, Show)
data Transform
= Identity
| Multiply Double
deriving (Eq, Show)
data Series = Series
{ serSource :: Source
, serTransform :: Transform
, serAlias :: String
, serColor :: String
, serLabel :: String
}
deriving (Eq, Show)
data Plot
= Line Int Series
| Area Series
deriving (Eq, Show)
data GraphSpec = GraphSpec
{ gsName :: Text
, gsTitle :: String
, gsPlots :: [Plot]
, gsIdentifier :: Graph
}
deriving (Eq, Show)
average :: String -> Source
average ds = Source ds Average
maximumCF :: String -> Source
maximumCF ds = Source ds Maximum
line :: String -> String -> Source -> Plot
line alias color source =
Line 2 Series
{ serSource = source
, serTransform = Identity
, serAlias = alias
, serColor = color
, serLabel = alias
}
area :: String -> String -> Source -> Plot
area alias color source =
Area Series
{ serSource = source
, serTransform = Identity
, serAlias = alias
, serColor = color
, serLabel = alias
}
ratelimitGraph :: GraphSpec
ratelimitGraph =
GraphSpec
{ gsName = "ratelimit"
, gsTitle = "Rate limiting"
, gsPlots =
[ Line 2 Series
{ serSource = Source "ratelimit_retry" Average
, serTransform = Multiply 60
, serAlias = "retry"
, serColor = "#0066cc"
, serLabel = "Requests retried/min"
}
, Line 2 Series
{ serSource = Source "ratelimit_exhausted" Average
, serTransform = Multiply 60
, serAlias = "exhaust"
, serColor = "#cc0000"
, serLabel = "Requests exhausted/min"
}
]
, gsIdentifier = RateLimit
}
trafficGraph :: GraphSpec
trafficGraph =
GraphSpec
{ gsName = "traffic"
, gsTitle = "Hass triggers in / services out"
, gsPlots =
[ Line 2 Series
{ serSource = Source "hass_trigger_in" Average
, serTransform = Multiply 60
, serAlias = "in"
, serColor = "#0066cc"
, serLabel = "Triggers in/min"
}
, Line 2 Series
{ serSource = Source "hass_service_out" Average
, serTransform = Multiply 60
, serAlias = "out"
, serColor = "#cc0000"
, serLabel = "Service calls out/min"
}
]
, gsIdentifier = Traffic
}
memoryGraph :: GraphSpec
memoryGraph =
GraphSpec
"memory"
"Memory use"
[ area "live" "#99ccff" (average "rts_gc_current__a7a")
, line "peak" "#cc0000" (maximumCF "rts_gc_current__a7a")
]
Memory
graphs :: [GraphSpec]
graphs = [memoryGraph, ratelimitGraph, trafficGraph]
-- XXX: Proper lookup..?
lookupGraph :: [GraphSpec] -> Graph -> Maybe GraphSpec
lookupGraph specs graphMode = case [g | g <- specs, gsIdentifier g == graphMode] of
(g : _) -> Just g
[] -> Nothing
parseNameParam :: [GraphSpec] -> Text -> Maybe GraphSpec
parseNameParam specs t = rightToMaybe (parseQueryParam t) >>= lookupGraph specs
where
rightToMaybe = either (const Nothing) Just
cfName :: CF -> String
cfName = \case
Average -> "AVERAGE"
Minimum -> "MIN"
Maximum -> "MAX"
Last -> "LAST"
defArgs :: FilePath -> Series -> [String]
defArgs rrdPath series =
( "DEF:" ++ rawF ++ "=" ++ rrdPath ++ ":"
++ srcDs source ++ ":" ++ cfName (srcCF source)
)
: transformArgs
where
source = serSource series
alias = serAlias series
rawF = alias ++ "_raw"
transformArgs = case serTransform series of
Identity ->
[ "CDEF:" ++ alias ++ "=" ++ rawF ]
Multiply factor ->
[ "CDEF:" ++ alias ++ "=" ++ rawF
++ "," ++ show factor ++ ",*"
]
plotArg :: Plot -> String
plotArg = \case
Line width series ->
"LINE" ++ show width ++ ":" ++ serAlias series
++ serColor series ++ ":" ++ serLabel series
Area series ->
"AREA:" ++ serAlias series
++ serColor series ++ ":" ++ serLabel series
plotSeries :: Plot -> Series
plotSeries = \case
Line _ series -> series
Area series -> series
buildGraphArgs :: FilePath -> GraphSpec -> Range -> [String]
buildGraphArgs rrdPath spec range =
[ "graph"
, "-"
, "--start", rangeStart range
, "--title", gsTitle spec
, "--width", "800"
, "--height", "250"
, "--imgformat", "PNG"
]
++ concatMap (defArgs rrdPath . plotSeries) (gsPlots spec)
++ map plotArg (gsPlots spec)
readProcessBytes :: FilePath -> [String] -> IO (ExitCode, BS.ByteString, String)
readProcessBytes cmd args =
withCreateProcess (proc cmd args) { std_out = CreatePipe, std_err = CreatePipe } $
\_ mout merr ph ->
case (mout, merr) of
(Just hout, Just herr) -> do
out <- BS.hGetContents hout
err <- hGetContents herr
code <- waitForProcess ph
_ <- evaluate (length err)
pure (code, out, err)
_ -> pure (ExitFailure 1, BS.empty, "failed to create pipes")
renderGraph :: MonadIO m => FilePath -> FilePath -> GraphSpec -> Range -> m (Either Text BS.ByteString)
renderGraph rrdPath rrdtool spec range = do
(code, out, err) <- liftIO (readProcessBytes rrdtool (buildGraphArgs rrdPath spec range))
case code of
ExitSuccess
| not (BS.null out) -> pure $ Right out
| otherwise -> pure $ Left "empty graph"
_ -> pure $ Left (T.pack $ take 200 err)
data Graph
= Memory
| Traffic
| RateLimit
deriving (Show, Eq, Enum, Bounded)
instance ToHttpApiData Graph where
toQueryParam Memory = "memory.png"
toQueryParam Traffic = "traffic.png"
toQueryParam RateLimit = "ratelimit.png"
instance FromHttpApiData Graph where
parseQueryParam "memory.png" = Right Memory
parseQueryParam "traffic.png" = Right Traffic
parseQueryParam "ratelimit.png" = Right RateLimit
parseQueryParam x = Left ("Can't parse '" <> x <> "' as Graph")
+182
View File
@@ -0,0 +1,182 @@
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Runtime.Metrics
( DsType (..)
, DsSpec (..)
, dsTypeOf
, sanitizeName
, buildSchema
, buildCreateArgs
, buildUpdateArgs
, parseInfoDs
, schemaMatches
, AppMetrics (..)
, registerAppMetrics
, ensureRrd
, sampleAndUpdate
, metricsAction
) where
import Control.Concurrent (threadDelay)
import Control.Monad (forever, unless)
import Data.Char (ord)
import Data.Int (Int64)
import Data.List (intercalate, sort, sortBy, stripPrefix)
import Data.Maybe (mapMaybe)
import Data.Ord (comparing)
import Data.Text (Text)
import Data.Time (defaultTimeLocale, formatTime, getCurrentTime)
import Data.Void (Void)
import Numeric (showHex)
import qualified Data.Text as T
import qualified Data.HashMap.Strict as HM
import qualified System.Metrics as M (Value (..), Sample, Store, createCounter, sampleAll)
import System.Metrics.Counter (Counter)
import System.Directory (doesFileExist, renameFile)
import System.Exit (ExitCode (..))
import System.Process (callProcess, readProcessWithExitCode)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Exception.Annotated (checkpointCallStack)
import Control.Monad.Catch (MonadCatch)
data DsType = Derive | Gauge
deriving (Eq, Ord, Show)
data DsSpec = DsSpec
{ dsEkgName :: Text
, dsName :: String
, dsType :: DsType
}
deriving (Eq, Show)
dsTypeOf :: M.Value -> Maybe DsType
dsTypeOf (M.Counter _) = Just Derive
dsTypeOf (M.Gauge _) = Just Gauge
dsTypeOf _ = Nothing
-- | Maps an ekg metric label to a valid rrd DS name (≤19 chars, [A-Za-z0-9_]).
-- Long names keep the first 15 chars plus a 3-hex hash suffix for uniqueness.
sanitizeName :: Text -> String
sanitizeName name
| length sanitized <= 19 = sanitized
| otherwise = take 15 sanitized ++ "_" ++ paddedHash
where
sanitized = T.unpack (T.replace "." "_" name)
paddedHash = let h = showHex (sum (map ord sanitized) `mod` 4096) ""
in replicate (3 - length h) '0' ++ h
buildSchema :: M.Sample -> [DsSpec]
buildSchema sample =
sortBy (comparing dsName)
[ DsSpec ekgName (sanitizeName ekgName) dt
| (ekgName, val) <- HM.toList sample
, Just dt <- [dsTypeOf val]
]
data AppMetrics = AppMetrics
{ amTriggersIn :: Counter
, amServicesOut :: Counter
}
registerAppMetrics :: M.Store -> IO AppMetrics
registerAppMetrics store =
AppMetrics
<$> M.createCounter "hass.trigger.in" store
<*> M.createCounter "hass.service.out" store
buildCreateArgs :: FilePath -> Int -> [(String, DsType)] -> [String]
buildCreateArgs path step specs =
["create", path, "--step", show step]
++ concatMap dsArg specs
++ rras
where
dsArg (name, Derive) = ["DS:" ++ name ++ ":DERIVE:20:0:U"]
dsArg (name, Gauge) = ["DS:" ++ name ++ ":GAUGE:20:0:U"]
rras =
[ "RRA:AVERAGE:0.5:1:6000"
, "RRA:MAX:0.5:1:6000"
, "RRA:AVERAGE:0.5:360:1680"
, "RRA:MAX:0.5:360:1680"
]
buildUpdateArgs :: FilePath -> [String] -> [Maybe Int64] -> [String]
buildUpdateArgs path names values =
[ "update"
, path
, "--template"
, intercalate ":" names
, "N:" ++ intercalate ":" (map renderValue values)
]
where
renderValue Nothing = "U"
renderValue (Just n) = show n
dsTypeFromString :: String -> Maybe DsType
dsTypeFromString "DERIVE" = Just Derive
dsTypeFromString "GAUGE" = Just Gauge
dsTypeFromString _ = Nothing
parseInfoDs :: String -> [(String, DsType)]
parseInfoDs = mapMaybe parseLine . lines
where
parseLine line = do
rest0 <- stripPrefix "ds[" line
let (name, rest1) = break (== ']') rest0
rest2 <- stripPrefix "].type = \"" rest1
let (ty, _) = break (== '"') rest2
dt <- dsTypeFromString ty
pure (name, dt)
schemaMatches :: [DsSpec] -> [(String, DsType)] -> Bool
schemaMatches schema existing =
sort (map (\s -> (dsName s, dsType s)) schema) == sort existing
lookupValue :: M.Sample -> Text -> Maybe Int64
lookupValue sample name = case HM.lookup name sample of
Just (M.Counter n) -> Just n
Just (M.Gauge n) -> Just n
_ -> Nothing
readExistingDs :: (MonadCatch m, MonadIO m) => FilePath -> FilePath -> m [(String, DsType)]
readExistingDs rrdtool rrdPath = checkpointCallStack $ do
(code, out, _) <- liftIO $ readProcessWithExitCode rrdtool ["info", rrdPath] ""
pure $ case code of
ExitSuccess -> parseInfoDs out
_ -> []
backupPath :: MonadIO m => FilePath -> m FilePath
backupPath path = liftIO $ do
now <- getCurrentTime
pure $ path ++ ".bak-" ++ formatTime defaultTimeLocale "%Y%m%dT%H%M%S" now
ensureRrd :: (MonadCatch m, MonadIO m) => FilePath -> FilePath -> [DsSpec] -> m ()
ensureRrd rrdtool rrdPath schema = checkpointCallStack $ do
exists <- liftIO $ doesFileExist rrdPath
if not exists
then create
else do
current <- readExistingDs rrdtool rrdPath
unless (schemaMatches schema current) $ do
backup <- backupPath rrdPath
liftIO $ renameFile rrdPath backup
create
where
create = liftIO $ callProcess rrdtool (buildCreateArgs rrdPath 10 (map toPair schema))
toPair s = (dsName s, dsType s)
sampleAndUpdate :: (MonadCatch m, MonadIO m) => M.Store -> FilePath -> FilePath -> [DsSpec] -> m ()
sampleAndUpdate store rrdtool rrdPath schema = checkpointCallStack $ do
sample <- liftIO $ M.sampleAll store
let names = map dsName schema
values = map (lookupValue sample . dsEkgName) schema
liftIO $ callProcess rrdtool (buildUpdateArgs rrdPath names values)
metricsAction :: (MonadCatch m, MonadIO m) => M.Store -> FilePath -> FilePath -> m Void
metricsAction store rrdPath rrdtool = checkpointCallStack $ do
schema <- buildSchema <$> liftIO (M.sampleAll store)
ensureRrd rrdtool rrdPath schema
forever $ do
sampleAndUpdate store rrdtool rrdPath schema
liftIO $ threadDelay 10000000
+75
View File
@@ -0,0 +1,75 @@
{-# Language DerivingVia #-}
{-# Language OverloadedStrings #-}
module HomeAssistant.Runtime.RateLimit where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Time (NominalDiffTime)
import Control.Concurrent.STM (newTVarIO, atomically, readTVar, writeTVar)
import Data.Time.Clock.POSIX (getPOSIXTime)
import Katip.Monadic (KatipContext(..))
import Control.Retry (fullJitterBackoff, limitRetries, retrying, RetryStatus (..))
import Data.Maybe (isNothing)
import Control.Exception.Annotated (Exception, checkpointCallStack, throw)
import Control.Monad.Catch (MonadCatch)
import Katip (Katip, Severity (WarningS), logFM, ls)
import Control.Monad (when)
import System.Metrics.Counter (Counter)
import qualified System.Metrics.Counter as Counter
import System.Metrics (Store, createCounter)
data RateLimitMetrics = RateLimitMetrics
{ rlRetries :: Counter
, rlRejects :: Counter
}
registerRateLimitMetrics :: MonadIO m => Store -> m RateLimitMetrics
registerRateLimitMetrics store = liftIO $ RateLimitMetrics
<$> createCounter "ratelimit.retry" store
<*> createCounter "ratelimit.exhausted" store
newtype RateLimited m a = RateLimited (m a)
deriving (Functor, Applicative, Monad, MonadIO, KatipContext, Katip) via m
data RateLimiter = RateLimiter
{ metrics :: RateLimitMetrics
, limiter :: forall m a. (KatipContext m, MonadIO m) => RateLimited m a -> m (Maybe a)
}
slidingWindowLimiter
:: MonadIO m
=> RateLimitMetrics
-> NominalDiffTime -- ^ Within how many seconds
-> Int -- ^ How many requests we can make
-> m RateLimiter
slidingWindowLimiter metrics timeWindow size = do
window <- liftIO $ newTVarIO []
return $ RateLimiter metrics $ \(RateLimited action) -> do
now <- liftIO getPOSIXTime
allowed <- liftIO $ atomically $ do
elements <- takeWhile (\x -> x > now - timeWindow) <$> readTVar window
if length elements >= size
then pure False
else True <$ writeTVar window (now : elements)
if allowed
then Just <$> action
else pure Nothing
data RateLimitException = RateLimitExhausted
deriving Show
instance Exception RateLimitException
runRateLimited :: (MonadIO m, KatipContext m, MonadCatch m) => RateLimiter -> RateLimited m a -> m a
runRateLimited (RateLimiter metrics run) action = checkpointCallStack $ do
x <- retrying retryPolicy (const $ pure . isNothing) $ \RetryStatus{rsIterNumber} -> do
when (rsIterNumber > 0) $ do
logFM WarningS $ ls $ "Rate limited, attempt no. " <> show rsIterNumber
incRetry
run action
maybe (incReject >> throw RateLimitExhausted) pure x
where
retryPolicy = fullJitterBackoff 500_000 <> limitRetries 5
incRetry = liftIO $ Counter.inc (rlRetries metrics)
incReject = liftIO $ Counter.inc (rlRejects metrics)
+19 -47
View File
@@ -2,26 +2,23 @@
module HomeAssistant.Runtime.Supervisor module HomeAssistant.Runtime.Supervisor
( supervised ( supervised
, Backoff(..)
, defaultBackoff
, backoffDelay
, nextAttempt
, Fatal(..) , Fatal(..)
) where ) where
import Control.Concurrent (threadDelay)
import Control.Exception.Annotated import Control.Exception.Annotated
( Exception ( Exception
, Handler (..) , Handler (..)
, SomeException , SomeException
, catches , checkpoint, Annotation (..)
, displayException
, throw
) )
import Data.Text (Text) import Data.Text (Text)
import qualified Data.Text as T
import Data.Time (NominalDiffTime, diffUTCTime, getCurrentTime)
import Data.Void (Void) import Data.Void (Void)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Catch (MonadCatch, MonadMask)
import Katip (KatipContext, logFM, ls)
import Control.Retry (RetryStatus(..), recovering, fullJitterBackoff, capDelay, skipAsyncExceptions)
import Control.Monad (when)
import Katip.Core (Severity(..))
-- | A failure that cannot be fixed by restarting; propagates out of -- | A failure that cannot be fixed by restarting; propagates out of
-- 'supervised' and terminates the process. -- 'supervised' and terminates the process.
@@ -30,28 +27,11 @@ newtype Fatal = Fatal Text
instance Exception Fatal instance Exception Fatal
data Backoff = Backoff
{ backoffBase :: NominalDiffTime -- ^ Delay before the first restart
, backoffCap :: NominalDiffTime -- ^ Maximum delay between restarts
, backoffQuiet :: NominalDiffTime -- ^ Uptime after which the delay resets
}
deriving (Eq, Show)
defaultBackoff :: Backoff data SupervisorException = RetriesExhausted
defaultBackoff = Backoff 0.1 30 30 deriving Show
-- | Delay before the @attempt@-th restart: doubles from base, clamped at cap. instance Exception SupervisorException
backoffDelay :: Backoff -> Int -> NominalDiffTime
backoffDelay (Backoff base cap _) attempt = go (max 0 (attempt - 1)) base
where
go 0 d = d
go n d = go (n - 1) (min cap (d * 2))
-- | Attempt number to use after a crash that ran for the given uptime.
nextAttempt :: Backoff -> NominalDiffTime -> Int -> Int
nextAttempt (Backoff _ _ quiet) uptime attempt
| uptime >= quiet = 1
| otherwise = attempt + 1
-- | Runs the action forever, restarting it with backoff after synchronous -- | Runs the action forever, restarting it with backoff after synchronous
-- exceptions; async exceptions propagate. 'Fatal' is rethrown (crashing the -- exceptions; async exceptions propagate. 'Fatal' is rethrown (crashing the
@@ -59,22 +39,14 @@ nextAttempt (Backoff _ _ quiet) uptime attempt
-- must not be wrapped in checkpoints around 'Fatal'-throwing code: a -- must not be wrapped in checkpoints around 'Fatal'-throwing code: a
-- doubly-wrapped 'Fatal' is indistinguishable from a crash and would be -- doubly-wrapped 'Fatal' is indistinguishable from a crash and would be
-- restarted instead of escalated. -- restarted instead of escalated.
supervised :: Text -> Backoff -> IO Void -> IO Void supervised :: (MonadIO m, MonadCatch m, KatipContext m, MonadMask m) => Text -> m Void -> m Void
supervised name backoff action = go 1 supervised name action = checkpoint (Annotation name) $ do
recovering retryPolicy (skipAsyncExceptions ++ handlers) $ \RetryStatus{rsIterNumber} -> do
when (rsIterNumber > 0) $ logFM WarningS $ ls $ "Child crashed, retry no " <> show rsIterNumber
action
where where
go attempt = do handlers =
start <- getCurrentTime [ \_retryStatus -> Handler $ \(_ :: Fatal) -> pure False
outcome <- (action >> pure (Nothing :: Maybe (Either Fatal SomeException))) `catches` , \_retryStatus -> Handler $ \(_ :: SomeException) -> pure True
[ Handler $ \(f :: Fatal) -> pure (Just (Left f))
, Handler $ \(e :: SomeException) -> pure (Just (Right e))
] ]
end <- getCurrentTime retryPolicy = capDelay (15 * 1_000_000) (fullJitterBackoff 50_000)
case outcome of
Nothing -> error "unreachable: supervised action returned"
Just (Left f) -> throw f
Just (Right e) -> do
putStrLn $ "[" <> T.unpack name <> "] attempt " <> show attempt <> " crashed: " <> displayException e
let delay = backoffDelay backoff attempt
putStrLn $ "[" <> T.unpack name <> "] restarting in " <> show delay
threadDelay (round (realToFrac delay * 1000000 :: Double))
go (nextAttempt backoff (diffUTCTime end start) attempt)
+242
View File
@@ -0,0 +1,242 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DerivingVia #-}
module HttpServer where
import Control.Monad (forever)
import Control.Monad.IO.Class (liftIO, MonadIO)
import qualified Data.ByteString as BS
import Data.Void (Void)
import Network.Wai.Handler.Warp (run)
import Servant.API ((:>), Capture, Get, QueryParam, (:-), MimeRender (..), Accept (..), NamedRoutes, JSON, ReqBody, Put, Post, FormUrlEncoded, Header)
import Data.ByteString (ByteString)
import GHC.Generics (Generic)
import Servant (Handler, err404, fieldLink, toUrlPiece)
import Control.Monad.Catch (throwM, catch, MonadCatch, MonadThrow, SomeException)
import Servant.Server (err500, ServerT)
import Data.Maybe (fromMaybe)
import Data.Map.Strict (Map)
import qualified Data.Set as S
import Data.Text (Text)
import HomeAssistant.Runtime.Flags (Flags, allFlags, setEnabled, validNames, isEnabled)
import Control.Exception.Annotated (checkpoint, Annotation (Annotation))
import Servant.Server.Generic (genericServeT)
import Network.Wai (Application)
import Network.HTTP.Media ((//))
import HomeAssistant.Runtime.Graphing (Graph (..), Range (..), lookupGraph, graphs, renderGraph, rangeSuffix)
import Katip (KatipContextT, Katip, runKatipContextT, LogEnv, KatipContext, ls, Severity (..), logFM, katipAddContext, sl)
import Data.Aeson (ToJSON (toJSON), FromJSON, object, (.=))
import Lucid (ToHtml, toHtml, renderBS, toHtmlRaw, HtmlT, Attributes)
import qualified Lucid.Html5 as H5
import qualified Data.Map.Strict as M
import Data.Foldable (for_)
import qualified Data.Text as T
import Web.FormUrlEncoded (FromForm, fromForm, parseUnique)
import Lucid.Base (makeAttributes)
import Data.Aeson.Key (fromText)
data ImagePng
instance MimeRender ImagePng GraphPng where
mimeRender _ (GraphPng bs) = BS.fromStrict bs
instance Accept ImagePng where
contentType _ = "image" // "png"
-- `servant-lucid` package would provide this and the instance for the original lucid(1) package
-- but we have lucid2
data HTML
instance Accept HTML where
contentType _ = "text" // "html"
instance ToHtml a => MimeRender HTML a where
mimeRender _ = renderBS . toHtml
newtype StatsPage = StatsPage (forall m. Monad m => HtmlT m ())
instance ToHtml StatsPage where
toHtml (StatsPage inner) = inner
toHtmlRaw = toHtml
page_ :: Monad m => HtmlT m () -> HtmlT m ()
page_ inner = H5.doctypehtml_ $ do
H5.head_ $ do
H5.script_
[ H5.src_ "https://cdn.jsdelivr.net/npm/htmx.org@2.0.11/dist/htmx.min.js"
, H5.integrity_ "sha384-2OatzQy1H+Zd/IIrjr1TcuDGqLXeHhbooAyJY1KdQMKnr4LZ22k31GBLdYKHmVjg"
, H5.crossorigin_ "anonymous"
]
("" :: Text)
H5.style_ css
H5.body_ inner
css :: Text
css = T.unlines
[ "body { font-family: system-ui, sans-serif; margin: 1rem auto; max-width: 40rem; padding: 0 1rem; }"
, "table { border-collapse: collapse; }"
, "th, td { padding: 0.4rem 0.75rem; border-bottom: 1px solid #ddd; text-align: left; }"
, "input[type=submit] { padding: 0.25rem 0.75rem; cursor: pointer; }"
, "img { max-width: 100%; }"
]
type HxRequest = Header "HX-Request" Bool
data API mode = API
{ getMetrics :: mode :- "metrics" :> Capture "graph" Graph :> QueryParam "range" Range :> Get '[ImagePng] GraphPng
, getStats :: mode :- "stats" :> HxRequest :> QueryParam "range" Range :> Get '[HTML] StatsPage
, getFlags :: mode :- "flags" :> Get '[JSON, HTML] FlagsResponse
, putFlag :: mode :- "flags" :> Capture "name" Text :> ReqBody '[JSON, FormUrlEncoded] FlagValue :> Put '[HTML, JSON] FlagResponse
, postFlag :: mode :- "flags" :> Capture "name" Text :> ReqBody '[JSON, FormUrlEncoded] FlagValue :> Post '[JSON, HTML] FlagResponse
}
deriving Generic
newtype GraphPng = GraphPng ByteString
newtype FlagValue = FlagValue Bool
deriving FromJSON via Bool
instance FromForm FlagValue where
fromForm f = FlagValue <$> parseUnique "flag-value" f
newtype FlagsResponse = FlagsResponse (Map Text Bool)
deriving (ToJSON) via (Map Text Bool)
data FlagResponse = FlagResponse Text Bool
instance ToHtml FlagResponse where
toHtml (FlagResponse name value) = flagRow name value
toHtmlRaw = toHtml
instance ToJSON FlagResponse where
toJSON (FlagResponse k v) = object [fromText k .= v]
flagsPage :: Monad m => FlagsResponse -> HtmlT m ()
flagsPage (FlagsResponse f) = page_ $
H5.table_ $ do
H5.tr_ $ do
H5.th_ "Name"
H5.th_ "Value"
H5.th_ ""
for_ (M.toList f) $ uncurry flagRow
flagRow :: Monad m => Text -> Bool -> HtmlT m ()
flagRow name value = H5.tr_ [H5.id_ (rowId name)] $ do
H5.td_ (toHtml name)
H5.td_ (toHtml (if value then "on" else "off" :: Text))
H5.td_ (toggle name value)
where
toggle :: Monad m => Text -> Bool -> HtmlT m ()
toggle key current = H5.form_ [H5.method_ "post", H5.action_ (postFlagsLink key)] $ do
H5.input_ [H5.name_ "flag-value", H5.type_ "hidden", H5.value_ (T.pack (show (not current)))]
H5.input_
[ H5.type_ "submit"
, H5.value_ (if current then "Disable" else "Enable")
, hxTrigger "click"
, hxTarget ("#" <> rowId key)
, hxPut (postFlagsLink key)
, hxSwap "outerHTML"
]
postFlagsLink k = "/" <> toUrlPiece (fieldLink putFlag k)
rowId :: Text -> Text
rowId = ("status-" <>)
hxTrigger :: Text -> Attributes
hxTrigger = makeAttributes "hx-trigger"
hxTarget :: Text -> Attributes
hxTarget = makeAttributes "hx-target"
hxPut :: Text -> Attributes
hxPut = makeAttributes "hx-put"
hxGet :: Text -> Attributes
hxGet = makeAttributes "hx-get"
hxPushUrl :: Text -> Attributes
hxPushUrl = makeAttributes "hx-push-url"
hxSwap :: Text -> Attributes
hxSwap = makeAttributes "hx-swap"
instance ToHtml FlagsResponse where
toHtml = flagsPage
toHtmlRaw = toHtml
getFlagsHandler :: Flags -> LoggingHandler FlagsResponse
getFlagsHandler = fmap FlagsResponse . allFlags
putFlagHandler :: Flags -> Text -> FlagValue -> LoggingHandler FlagResponse
putFlagHandler flags name (FlagValue val)
| name `S.notMember` validNames flags = throwM err404
| otherwise = checkpoint (Annotation (name, val)) $ katipAddContext (sl "flag" (name, val)) $ do
setEnabled flags name val `catch` \e -> do
logFM ErrorS (ls ("failed to persist handler flag: " <> show (e :: SomeException)))
throwM err500
FlagResponse name <$> isEnabled flags name
getMetricsHandler :: FilePath -> FilePath -> Graph -> Maybe Range -> LoggingHandler GraphPng
getMetricsHandler rrdPath rrdtool graphMode mRange = checkpoint (Annotation (graphMode, mRange)) $ do
case lookupGraph graphs graphMode of
Nothing -> throwM err404
Just spec -> do
let range = fromMaybe OneDay mRange
g <- renderGraph rrdPath rrdtool spec range
either (\e -> logFM ErrorS (ls e) >> throwM err500) (pure . GraphPng) g
-- server :: FilePath -> FilePath -> API AsServer
server :: FilePath -> FilePath -> Flags -> ServerT (NamedRoutes API) LoggingHandler
server rrdPath rrdtool flags = API
{ getMetrics = getMetricsHandler rrdPath rrdtool
, getStats = getStatsHandler
, getFlags = getFlagsHandler flags
, putFlag = putFlagHandler flags
, postFlag = putFlagHandler flags -- This exists only for html forms
}
statsPage :: Maybe Bool -> Maybe Range -> StatsPage
statsPage hx r = StatsPage $
if hx == Just True
then statsContent r
else page_ (statsContent r)
statsContent :: Monad m => Maybe Range -> HtmlT m ()
statsContent r = H5.div_ [H5.id_ "stats"] $ do
H5.ul_ $ for_ [minBound..maxBound] $ \range ->
H5.li_ $ H5.a_ (link range) $ toHtml $ rangeSuffix range
H5.h2_ "Traffic"
H5.img_ [H5.src_ (src Traffic)]
H5.h2_ "Memory"
H5.img_ [H5.src_ (src Memory)]
H5.h2_ "Ratelimit"
H5.img_ [H5.src_ (src RateLimit)]
where
src m = "/" <> toUrlPiece (fieldLink getMetrics m r)
link range =
let url = "/" <> toUrlPiece (fieldLink getStats (Just range))
in [ H5.href_ url
, hxGet url
, hxTarget "#stats"
, hxSwap "outerHTML"
, hxPushUrl "true"
]
getStatsHandler :: Maybe Bool -> Maybe Range -> LoggingHandler StatsPage
getStatsHandler hx r = pure (statsPage hx r)
servantApp :: LogEnv -> FilePath -> FilePath -> Flags -> Application
servantApp le rrdPath rrdtool flags = genericServeT (toHandler le) (server rrdPath rrdtool flags)
runHttpServer :: MonadIO m => LogEnv -> FilePath -> FilePath -> Flags -> Int -> m Void
runHttpServer le rrdPath rrdtool flags port = liftIO $ forever $ run port (servantApp le rrdPath rrdtool flags)
newtype LoggingHandler a = LoggingHandler (KatipContextT Handler a)
deriving (Functor, Applicative, Monad, MonadIO, Katip, KatipContext, MonadCatch, MonadThrow) via (KatipContextT Handler)
toHandler :: LogEnv -> (forall a. LoggingHandler a -> Handler a)
toHandler le (LoggingHandler k) = runKatipContextT le () "http" k
+70
View File
@@ -0,0 +1,70 @@
{-# LANGUAGE OverloadedStrings #-}
module Katip.Scribes.Journal where
import Data.Text.Lazy qualified as TL
import Data.Text.Lazy.Builder qualified as Builder
import Katip (Item (..), LogStr (..), PermitFunc, Scribe (..), Verbosity (..), permitItem, Severity (..), registerScribe, defaultScribeSettings, initLogEnv, closeScribes, runKatipContextT, logLocM, LogItem, Namespace (..), getThreadIdText, payloadObject, katipAddContext, sl, getEnvironment)
import Systemd.Journal qualified as J
import Control.Exception (bracket)
import GHC.Stack (HasCallStack)
import qualified Data.Text as T
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text.Encoding as TE
import qualified Data.Aeson as A
import qualified Data.ByteString.Lazy as BL
import qualified Data.Aeson.KeyMap as KeyMap
import qualified Data.Aeson.Key as Key
import qualified Data.ByteString as B
mkJournalScribe :: PermitFunc -> Verbosity -> IO Scribe
mkJournalScribe permitFunc verbosity =
pure $
Scribe
{ liPush = \i ->
J.sendMessageWith (TL.toStrict $ Builder.toLazyText $ unLogStr $ _itemMessage i) (itemToJournalFields verbosity i),
scribeFinalizer = pure (), -- no cleanup?
scribePermitItem = permitFunc
}
itemToJournalFields :: forall a. LogItem a => Verbosity -> Item a -> J.JournalFields
itemToJournalFields verbosity item = mconcat
[ J.syslogIdentifier (unNS item)
, J.priority (mapPriority item)
, thread item
, payload item
, environment item
]
where
mapPriority i =
case _itemSeverity i of
DebugS -> J.Debug
InfoS -> J.Info
NoticeS -> J.Notice
WarningS -> J.Warning
ErrorS -> J.Error
CriticalS -> J.Critical
AlertS -> J.Alert
EmergencyS -> J.Emergency
unNS = T.intercalate "." . unNamespace . _itemNamespace
thread i = HashMap.singleton (katipField "thread") (TE.encodeUtf8 $ getThreadIdText $ _itemThread i)
environment i = HashMap.singleton (katipField "environment") (TE.encodeUtf8 $ getEnvironment $ _itemEnv i)
payload :: Item a -> J.JournalFields
payload i = -- HashMap.singleton (J.mkJournalField "payload") (BL.toStrict $ A.encode $ payloadObject verbosity $ _itemPayload i)
HashMap.fromList $ map (\(k,v) -> (katipField (Key.toText k), encodeValue v)) $ KeyMap.toList $ payloadObject verbosity $ _itemPayload i
-- The upstream doesn't handle '-'
katipField = J.mkJournalField . T.replace "-" "_" . ("KATIP_" <>)
encodeValue :: A.Value -> B.ByteString
encodeValue = \case
-- Handle simple scalar values as is
A.String t -> TE.encodeUtf8 t
x -> BL.toStrict $ A.encode x
test :: HasCallStack => IO ()
test = do
scribe <- mkJournalScribe (permitItem InfoS) V2
let makeLogEnv = registerScribe "journald" scribe defaultScribeSettings =<< initLogEnv "hass-controller" "dev"
bracket makeLogEnv closeScribes $ \le -> do
runKatipContextT le () "findme-context" $
katipAddContext (sl "trace-id" ("abcdefg" :: String)) $
logLocM InfoS "Hello world"
pure ()
+260
View File
@@ -0,0 +1,260 @@
module AFRPLawsSpec (spec) where
import AFRP
import Control.Arrow (arr, first, left, (***), (+++))
import Control.Category ((>>>))
import qualified Control.Category as Cat (id)
import Data.Functor.Identity (Identity (..))
import Hedgehog (Gen, PropertyT)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Support (fakeRequest)
import Test.Hspec (Spec, describe, it)
import Test.Hspec.Hedgehog (forAll, forAllWith, hedgehog, (===))
-- We are testing laws -> hlint warns about not using laws
{-# ANN module "Hlint: ignore" #-}
-- | Law tests for the Mealy instances. Two machines count as equal when
-- they emit equal outputs on every input sequence, so each law runs both
-- sides on generated inputs.
runPure :: Mealy Identity a b -> [a] -> [b]
runPure m = go (runMealy m id)
where
go _ [] = []
go w (a : as) = case runIdentity (stepAuto w fakeRequest a) of
(b, w') -> b : go w' as
-- | Machines wrap functions and have no Show; name them for forAll instead.
forAllMealy :: Gen (Mealy Identity a b) -> PropertyT IO (Mealy Identity a b)
forAllMealy = forAllWith (const "<mealy>")
intGen :: Gen Int
intGen = Gen.int (Range.linear (-5) 5)
ints :: Gen [Int]
ints = Gen.list (Range.linear 0 30) intGen
intPairs :: Gen [(Int, Int)]
intPairs = Gen.list (Range.linear 0 30) ((,) <$> intGen <*> intGen)
intEithers :: Gen [Either Int Int]
intEithers = Gen.list (Range.linear 0 30) $
Gen.choice [Left <$> intGen, Right <$> intGen]
nestedPairs :: Gen [((Int, Int), Int)]
nestedPairs = Gen.list (Range.linear 0 30) ((,) <$> ((,) <$> intGen <*> intGen) <*> intGen)
nestedEithers :: Gen [Either (Either Int Int) Int]
nestedEithers = Gen.list (Range.linear 0 30) $
Gen.choice
[ Left <$> Gen.choice [Left <$> intGen, Right <$> intGen]
, Right <$> intGen
]
-- | Stateful Int machines: the arrow variables of the laws.
statefulGen :: Gen (Mealy Identity Int Int)
statefulGen = Gen.choice
[ (\k -> mapAccum (+) k id) <$> intGen
, (\k -> preMapAccum (+) k id) <$> intGen
, (\k -> mapAccum (*) 1 (+ k)) <$> intGen
]
eventArrowGen :: Gen (Mealy Identity Int (Event Int))
eventArrowGen = Gen.choice
[ pure changes
, (\k -> mapAccum (+) k Event) <$> intGen
, (\k -> preMapAccum (+) k (Event . (* 2))) <$> intGen
]
funArrowGen :: Gen (Mealy Identity Int (Int -> Int))
funArrowGen = Gen.choice
[ (\k -> mapAccum (+) k (*)) <$> intGen
, pure (preMapAccum (*) 1 (+))
]
spec :: Spec
spec = describe "Mealy laws" $ do
semigroupSpec
monoidSpec
categorySpec
arrowSpec
arrowChoiceSpec
functorSpec
applicativeSpec
semigroupSpec :: Spec
semigroupSpec = describe "Semigroup (<>)" $ do
it "(a <> b) <> c = a <> (b <> c)" $ hedgehog $ do
a <- forAllMealy eventArrowGen
b <- forAllMealy eventArrowGen
c <- forAllMealy eventArrowGen
xs <- forAll ints
runPure ((a <> b) <> c) xs === runPure (a <> (b <> c)) xs
monoidSpec :: Spec
monoidSpec = describe "Monoid" $ do
it "mempty <> a = a" $ hedgehog $ do
a <- forAllMealy eventArrowGen
xs <- forAll ints
runPure (mempty <> a) xs === runPure a xs
it "a <> mempty = a" $ hedgehog $ do
a <- forAllMealy eventArrowGen
xs <- forAll ints
runPure (a <> mempty) xs === runPure a xs
categorySpec :: Spec
categorySpec = describe "Category" $ do
it "id >>> f = f" $ hedgehog $ do
f <- forAllMealy statefulGen
xs <- forAll ints
runPure (Cat.id >>> f) xs === runPure f xs
it "f >>> id = f" $ hedgehog $ do
f <- forAllMealy statefulGen
xs <- forAll ints
runPure (f >>> Cat.id) xs === runPure f xs
it "(f >>> g) >>> h = f >>> (g >>> h)" $ hedgehog $ do
f <- forAllMealy statefulGen
g <- forAllMealy statefulGen
h <- forAllMealy statefulGen
xs <- forAll ints
runPure ((f >>> g) >>> h) xs === runPure (f >>> (g >>> h)) xs
arrowSpec :: Spec
arrowSpec = describe "Arrow" $ do
it "arr id = id" $ hedgehog $ do
xs <- forAll ints
runPure (arr id :: Mealy Identity Int Int) xs === runPure Cat.id xs
it "arr (f >>> g) = arr f >>> arr g" $ hedgehog $ do
p <- forAll intGen
q <- forAll intGen
xs <- forAll ints
let f = (+ p)
g = (* q)
runPure (arr (f >>> g)) xs === runPure (arr f >>> arr g) xs
it "first (arr f) = arr (first f)" $ hedgehog $ do
p <- forAll intGen
ps <- forAll intPairs
let f = (+ p)
runPure (first (arr f)) ps === runPure (arr (first f)) ps
it "first (f >>> g) = first f >>> first g" $ hedgehog $ do
f <- forAllMealy statefulGen
g <- forAllMealy statefulGen
ps <- forAll intPairs
runPure (first (f >>> g)) ps === runPure (first f >>> first g) ps
it "first f >>> arr fst = arr fst >>> f" $ hedgehog $ do
f <- forAllMealy statefulGen
ps <- forAll intPairs
runPure (first f >>> arr fst) ps === runPure (arr fst >>> f) ps
it "first f >>> arr (id *** g) = arr (id *** g) >>> first f" $ hedgehog $ do
f <- forAllMealy statefulGen
p <- forAll intGen
ps <- forAll intPairs
let g = (* p)
runPure (first f >>> arr (id *** g)) ps
=== runPure (arr (id *** g) >>> first f) ps
it "first (first f) >>> arr assoc = arr assoc >>> first f" $ hedgehog $ do
f <- forAllMealy statefulGen
ts <- forAll nestedPairs
let assoc ((a, b), c) = (a, (b, c))
runPure (first (first f) >>> arr assoc) ts
=== runPure (arr assoc >>> first f) ts
arrowChoiceSpec :: Spec
arrowChoiceSpec = describe "ArrowChoice" $ do
it "left (arr f) = arr (left f)" $ hedgehog $ do
p <- forAll intGen
es <- forAll intEithers
let f = (+ p)
runPure (left (arr f)) es === runPure (arr (left f)) es
it "left (f >>> g) = left f >>> left g" $ hedgehog $ do
f <- forAllMealy statefulGen
g <- forAllMealy statefulGen
es <- forAll intEithers
runPure (left (f >>> g)) es === runPure (left f >>> left g) es
it "f >>> arr Left = arr Left >>> left f" $ hedgehog $ do
f <- forAllMealy statefulGen
xs <- forAll ints
runPure (f >>> arr (Left @Int @Int)) xs
=== runPure (arr (Left @Int @Int) >>> left f) xs
it "left f >>> arr (id +++ g) = arr (id +++ g) >>> left f" $ hedgehog $ do
f <- forAllMealy statefulGen
p <- forAll intGen
es <- forAll intEithers
let g = (* p)
runPure (left f >>> arr (id +++ g)) es
=== runPure (arr (id +++ g) >>> left f) es
it "left (left f) >>> arr assocsum = arr assocsum >>> left f" $ hedgehog $ do
f <- forAllMealy statefulGen
es <- forAll nestedEithers
let assocsum (Left (Left x)) = Left x
assocsum (Left (Right y)) = Right (Left y)
assocsum (Right z) = Right (Right z)
runPure (left (left f) >>> arr assocsum) es
=== runPure (arr assocsum >>> left f) es
functorSpec :: Spec
functorSpec = describe "Functor" $ do
it "fmap id = id" $ hedgehog $ do
m <- forAllMealy statefulGen
xs <- forAll ints
runPure (fmap id m) xs === runPure m xs
it "fmap (f . g) = fmap f . fmap g" $ hedgehog $ do
m <- forAllMealy statefulGen
p <- forAll intGen
q <- forAll intGen
xs <- forAll ints
let f = (+ p)
g = (* q)
runPure (fmap (f . g) m) xs === runPure (fmap f (fmap g m)) xs
applicativeSpec :: Spec
applicativeSpec = describe "Applicative" $ do
it "pure id <*> v = v" $ hedgehog $ do
v <- forAllMealy statefulGen
xs <- forAll ints
runPure (pure id <*> v) xs === runPure v xs
it "pure f <*> pure x = pure (f x)" $ hedgehog $ do
p <- forAll intGen
x <- forAll intGen
xs <- forAll ints
let f = (+ p)
runPure (pure f <*> pure x) xs === runPure (pure (f x)) xs
it "u <*> pure y = pure ($ y) <*> u" $ hedgehog $ do
u <- forAllMealy funArrowGen
y <- forAll intGen
xs <- forAll ints
runPure (u <*> pure y) xs === runPure (pure ($ y) <*> u) xs
it "pure (.) <*> u <*> v <*> w = u <*> (v <*> w)" $ hedgehog $ do
u <- forAllMealy funArrowGen
v <- forAllMealy funArrowGen
w <- forAllMealy statefulGen
xs <- forAll ints
runPure (pure (.) <*> u <*> v <*> w) xs
=== runPure (u <*> (v <*> w)) xs
it "fmap f x = pure f <*> x" $ hedgehog $ do
x <- forAllMealy statefulGen
p <- forAll intGen
xs <- forAll ints
let f = (+ p)
runPure (fmap f x) xs === runPure (pure f <*> x) xs
+589
View File
@@ -0,0 +1,589 @@
{-# LANGUAGE OverloadedStrings #-}
module AFRPSpec (spec) where
import Control.Arrow (arr, (&&&), first, left)
import Control.Category ((>>>))
import Control.Monad.Fix (MonadFix (..))
import Data.Foldable (for_)
import AFRP
import Data.Functor.Identity (Identity (..))
import Data.List (sort)
import Data.Serialize (get, put, runGet, runPut)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Time (Day (..), NominalDiffTime, LocalTime(..), TimeOfDay(..), UTCTime (..), picosecondsToDiffTime, utc)
import Data.UUID (nil)
import Hedgehog
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Test.Hspec
import Test.Hspec.Hedgehog
import Data.Maybe (listToMaybe)
import AFRP.Diagram (emptyDiagram)
fakeRequest :: Request
fakeRequest = Request (sec 0) utc nil "test"
sec :: Integer -> UTCTime
sec n = UTCTime (toEnum 0) (fromIntegral n)
untime :: SerializeUTCTime -> UTCTime
untime (SerializeUTCTime t) = t
runPure :: Mealy Identity a b -> [a] -> [b]
runPure m = go (runMealy m id)
where
go _ [] = []
go w (a : as) = case runIdentity (stepAuto w fakeRequest a) of
(b, w') -> b : go w' as
-- | Run a Mealy with a per-step wall clock (seconds since the day-0 epoch).
runTimed :: Mealy Identity a b -> [(Integer, a)] -> [b]
runTimed m = go (runMealy m id)
where
go _ [] = []
go w ((s, a) : as) =
case runIdentity (stepAuto w (Request (sec s) utc nil "test") a) of
(b, w') -> b : go w' as
-- | A minimal State monad for observing effectful arrows (e.g. whenA gating).
newtype St a = St { unSt :: Int -> (a, Int) }
instance Functor St where
fmap f (St g) = St $ \s -> let (a, s') = g s in (f a, s')
instance Applicative St where
pure a = St (a,)
St f <*> St x = St $ \s -> let (f', s') = f s; (a, s'') = x s' in (f' a, s'')
instance Monad St where
St m >>= k = St $ \s -> let (a, s') = m s; (b, s'') = unSt (k a) s' in (b, s'')
instance MonadFix St where
mfix f = St $ \s -> let (a, s') = unSt (f a) s in (a, s')
runStEff :: Mealy St a b -> Int -> [a] -> ([b], Int)
runStEff m = go (runMealy m id)
where
go _ s [] = ([], s)
go w s (a : rest) = case unSt (stepAuto w fakeRequest a) s of
((b, w'), s') -> let (bs, s'') = go w' s' rest in (b : bs, s'')
spec :: Spec
spec = describe "AFRP" $ do
entitiesSpec
holdSpec
eventsSpec
isEventSpec
tagSpec
toEventSpec
lMergeSpec
changesSpec
edgeSpec
filterASpec
slidingSpec
mapAccumSpec
preMapAccumSpec
durationSpec
delayEventSpec
debounceSpec
rollupSpec
serializeSpec
effSpec
mapAccumRequestSpec
preMapAccumRequestSpec
whenASpec
thenASpec
sampleSpec
holdSpec :: Spec
holdSpec = describe "hold" $ do
it "holds initial value until an Event arrives" $
runPure (hold 'a') [Tick, Event 'b', Tick, Event 'c']
`shouldBe` ['a', 'b', 'b', 'c']
it "never changes on Tick" $
runPure (hold (0 :: Int)) (replicate 5 Tick) `shouldBe` replicate 5 (0 :: Int)
eventsSpec :: Spec
eventsSpec = describe "events" $ do
it "converts Tick to Left () and Event a to Right a" $
runPure events [Tick, Event 'a', Tick, Event 'b']
`shouldBe` [Left (), Right 'a', Left (), Right 'b']
isEventSpec :: Spec
isEventSpec = describe "isEvent" $ do
it "returns False for Tick" $
isEvent Tick `shouldBe` False
it "returns True for Event x" $
isEvent (Event ()) `shouldBe` True
tagSpec :: Spec
tagSpec = describe "tag" $ do
it "replaces value preserving structure" $ do
tag 'b' Tick `shouldBe` Tick
tag 'b' (Event 'a') `shouldBe` Event 'b'
toEventSpec :: Spec
toEventSpec = describe "toEvent" $ do
it "round-trips through events" $
runPure toEvent [Left (), Right 'a', Left ()]
`shouldBe` [Tick, Event 'a', Tick]
it "is inverse of events modulo Event/Either" $
runPure (events >>> toEvent) [Tick, Event 'a', Event 'b']
`shouldBe` [Tick, Event 'a', Event 'b']
lMergeSpec :: Spec
lMergeSpec = describe "lMerge" $ do
it "both Tick gives Tick" $
lMerge (Tick :: Event Int) (Tick :: Event Int) `shouldBe` Tick
it "prefers left Event" $
lMerge (Event (1 :: Int)) (Event (2 :: Int)) `shouldBe` Event (1 :: Int)
it "prefers right Event if left is Tick" $
lMerge Tick (Event (2 :: Int)) `shouldBe` Event (2 :: Int)
it "Tick is a left identity" $
hedgehog $ do
e <- forAll eventGen
lMerge Tick e === e
it "Tick is a right identity" $
hedgehog $ do
e <- forAll eventGen
lMerge e Tick === e
it "is associative" $
hedgehog $ do
a <- forAll eventGen
b <- forAll eventGen
c <- forAll eventGen
lMerge a (lMerge b c) === lMerge (lMerge a b) c
changesSpec :: Spec
changesSpec = describe "changes" $ do
it "first output is always Tick" $
listToMaybe (runPure changes "hello") `shouldBe` Just Tick
it "outputs Event only on value change" $
runPure changes "aaaabbbcca"
`shouldBe` [Tick, Tick, Tick, Tick
, Event 'b', Tick, Tick
, Event 'c', Tick
, Event 'a'
]
it "first output is Tick, subsequent outputs are Event iff value changed" $
hedgehog $ do
xs <- forAll $ Gen.list (Range.linear 0 100) Gen.alpha
let out = runPure changes xs
length out === length xs
case out of
[] -> pure ()
(Tick : rest) -> do
let triples = zip3 xs (drop 1 xs) rest
for_ triples $ \(prev, curr, o) ->
if prev /= curr
then o === Event curr
else o === Tick
_ -> failure
edgeSpec :: Spec
edgeSpec = describe "edge" $ do
it "emits Event () only on rising edge" $
runPure edge [False, True, True, False, True]
`shouldBe` [Tick, Event (), Tick, Tick, Event ()]
it "starts from False, so first True is a rising edge" $
runPure edge [True, False, True]
`shouldBe` [Event (), Tick, Event ()]
it "Event () only on False -> True transition" $
hedgehog $ do
bs <- forAll $ Gen.list (Range.linear 0 50) Gen.bool
let out = runPure edge bs
length out === length bs
case (bs, out) of
([], []) -> pure ()
(b : _, o : _) -> do
if b then o === Event () else o === Tick
let triples = zip3 bs (drop 1 bs) (drop 1 out)
for_ triples $ \(prev, curr, o') ->
if not prev && curr
then o' === Event ()
else o' === Tick
_ -> failure
filterASpec :: Spec
filterASpec = describe "filterA" $ do
it "lets through values matching predicate" $
runPure (filterA (even @Int)) [1, 2, 3, 4]
`shouldBe` [Left (), Right 2, Left (), Right 4]
it "output is Right a iff predicate holds" $
hedgehog $ do
threshold <- forAll $ Gen.int (Range.linear (-10) 10)
let p = (> threshold)
xs <- forAll $ Gen.list (Range.linear 0 50) (Gen.int (Range.linear (-20) 20))
let out = runPure (filterA p) xs
length out === length xs
for_ (zip xs out) $ \(x, o) ->
if p x
then o === Right x
else o === Left ()
slidingSpec :: Spec
slidingSpec = describe "sliding" $ do
it "accumulates events up to the window size" $
runPure (sliding (3 :: Int)) [Event (1 :: Int), Event 2, Event 3, Event 4]
`shouldBe` [[1], [1, 2], [1, 2, 3], [2, 3, 4]]
it "Ticks don't change the accumulator" $
runPure (sliding 2) [Event (1 :: Int), Tick, Event 2]
`shouldBe` [[1], [1], [1, 2]]
it "empty list stays empty" $
runPure (sliding (5 :: Int)) ([] :: [Event Int]) `shouldBe` []
it "output length never exceeds window size" $
hedgehog $ do
n <- forAll $ Gen.int (Range.constant 1 10)
evs <- forAll $ Gen.list (Range.linear 0 20) (Gen.frequency
[(3, Event <$> Gen.alpha), (1, pure Tick)])
let out = runPure (sliding n) evs
for_ out $ \xs -> assert (length xs <= n)
mapAccumSpec :: Spec
mapAccumSpec = describe "mapAccum" $ do
it "running sum" $
runPure (mapAccum (+) (0 :: Int) id) [1, 2, 3]
`shouldBe` [1, 3, 6]
it "post-state extraction: output uses state after applying f" $
runPure (mapAccum (\s x -> s ++ [x]) ([] :: [Int]) id) [1, 2, 3]
`shouldBe` [[1], [1, 2], [1, 2, 3]]
it "output equals running sum of all inputs so far" $
hedgehog $ do
xs <- forAll $ Gen.list (Range.linear 0 50) (Gen.int (Range.linear (-100) 100))
let out = runPure (mapAccum (+) (0 :: Int) id) xs
length out === length xs
for_ (zip3 [0 ..] xs out) $ \(i, _x, cur) ->
cur === sum (take (i + 1) xs)
preMapAccumSpec :: Spec
preMapAccumSpec = describe "preMapAccum" $ do
it "running sum with pre-state extraction" $
runPure (preMapAccum (+) (0 :: Int) id) [1, 2, 3]
`shouldBe` [0, 1, 3]
it "pre-state extraction: output uses state before applying f" $
runPure (preMapAccum (\s x -> s ++ [x]) ([] :: [Int]) id) [1, 2, 3]
`shouldBe` [[], [1], [1, 2]]
it "output equals running sum before current input" $
hedgehog $ do
xs <- forAll $ Gen.list (Range.linear 0 50) (Gen.int (Range.linear (-100) 100))
let out = runPure (preMapAccum (+) (0 :: Int) id) xs
length out === length xs
for_ (zip3 [0 ..] xs out) $ \(i, _x, cur) ->
cur === sum (take i xs)
durationSpec :: Spec
durationSpec = describe "duration" $ do
it "first sample is 0, then elapsed time since first sample" $
runTimed duration [(0, 'a'), (5, 'b'), (10, 'c')]
`shouldBe` [0, 5, 10]
it "measures from the first observation, not the most recent" $
runTimed duration [(2, 'a'), (3, 'b'), (7, 'c')]
`shouldBe` [0, 1, 5]
it "output i equals times[i] - times[0]" $
hedgehog $ do
secs <- forAll $ Gen.list (Range.linear 0 50) (Gen.int (Range.linear 0 1000))
let out = runTimed duration [(fromIntegral s, ()) | s <- secs]
length out === length secs
case secs of
[] -> pure ()
(t0 : _) -> for_ (zip secs out) $ \(s, d) ->
d === fromIntegral (s - t0)
delayEventSpec :: Spec
delayEventSpec = describe "delayEvent" $ do
let delay = 5 :: NominalDiffTime
it "emits a queued event once the delay has elapsed" $
runTimed (delayEvent delay)
[(0, Event 'a'), (3, Tick), (6, Tick)]
`shouldBe` [Tick, Tick, Event 'a']
it "preserves order when multiple events are queued" $
runTimed (delayEvent delay)
[(0, Event 'a'), (1, Event 'b'), (10, Tick), (12, Tick)]
`shouldBe` [Tick, Tick, Event 'a', Event 'b']
it "emits nothing on pure Tick input" $
runTimed (delayEvent delay) [(0, Tick :: Event Char), (10, Tick)]
`shouldBe` [Tick, Tick]
it "emits exactly one output Event per input Event" $
hedgehog $ do
evs <- forAll $ Gen.list (Range.linear 0 30) eventGen
let evs' = evs ++ replicate 3 Tick
n = length [() | Event _ <- evs]
out = runTimed (delayEvent (1 :: NominalDiffTime))
(zip [0, 2 ..] evs')
length [() | Event _ <- out] === n
debounceSpec :: Spec
debounceSpec = describe "debounce" $ do
let delay = 5 :: NominalDiffTime
it "fires the last event after the quiet period" $
runTimed (debounce delay)
[(0, Event 'a'), (3, Tick), (6, Tick)]
`shouldBe` [Tick, Tick, Event 'a']
it "a newer event before firing resets the timer" $
runTimed (debounce delay)
[(0, Event 'a'), (3, Event 'b'), (6, Tick), (8, Tick)]
`shouldBe` [Tick, Tick, Tick, Event 'b']
it "collapses a burst into a single emission" $
runTimed (debounce delay)
[(0, Event 'a'), (1, Event 'b'), (2, Event 'c'), (10, Tick)]
`shouldBe` [Tick, Tick, Tick, Event 'c']
it "emits no more output Events than input Events" $
hedgehog $ do
evs <- forAll $ Gen.list (Range.linear 0 30) eventGen
let nIn = length [() | Event _ <- evs]
out = runTimed (debounce (1 :: NominalDiffTime))
(zip [0, 2 ..] evs)
nOut = length [() | Event _ <- out]
assert (nOut <= nIn)
rollupSpec :: Spec
rollupSpec = describe "rollup" $ do
it "passes the first `limit` events through immediately, then bursts" $
runTimed (rollup 2 10)
[ (0, Event 'a'), (1, Event 'b')
, (2, Event 'c'), (3, Event 'd')
, (12, Tick)
]
`shouldBe` [ Event ['a'], Event ['b']
, Tick, Tick
, Event ['c', 'd']
]
it "flushes the accumulator when the window ends on a Tick" $
runTimed (rollup 1 10)
[(0, Event 'a'), (1, Event 'b'), (2, Tick), (12, Tick)]
`shouldBe` [Event ['a'], Tick, Tick, Event ['b']]
it "is idle (Tick) until the first Event" $
runTimed (rollup 2 10) [(0, Tick :: Event Char), (1, Tick)]
`shouldBe` [Tick, Tick]
it "every input Event appears exactly once across the outputs" $
hedgehog $ do
limit <- forAll $ Gen.int (Range.constant 1 5)
evs <- forAll $ Gen.list (Range.linear 0 30) eventGen
let evs' = evs ++ replicate 10 Tick
times = [0 ..]
out = runTimed (rollup limit 5) (zip times evs')
emitted = concat [xs | Event xs <- out]
sort emitted === sort [x | Event x <- evs]
eventGen :: Gen (Event Char)
eventGen = Gen.frequency
[ (3, Event <$> Gen.alpha)
, (1, pure Tick)
]
timeGen :: Gen SerializeUTCTime
timeGen = do
day <- ModifiedJulianDay . fromIntegral <$> Gen.int (Range.linear 0 100000)
pico <- picosecondsToDiffTime . fromIntegral
<$> Gen.int (Range.linear 0 (86400 * 10 ^ (12 :: Int) - 1))
pure $ SerializeUTCTime (UTCTime day pico)
localTimeGen :: Gen SerializeLocalTime
localTimeGen = do
day <- ModifiedJulianDay . fromIntegral <$> genInt 0 100000
tod <- TimeOfDay <$> genInt 0 23 <*> genInt 0 59 <*> (fromIntegral <$> genInt 0 60)
pure $ SerializeLocalTime (LocalTime day tod)
where
genInt a b = Gen.int (Range.linear a b)
serializeSpec :: Spec
serializeSpec = do
describe "SerializeUTCTime" $ do
it "get (put x) == pure x" $
hedgehog $ do
x <- forAll timeGen
tripping x (runPut . put) (runGet get)
describe "SerializeLocalTime" $ do
it "get (put x) == pure x" $
hedgehog $ do
x <- forAll localTimeGen
tripping x (runPut . put) (runGet get)
effSpec :: Spec
effSpec = describe "eff" $ do
it "lifts a pure effect function into a stateless Mealy" $
runPure (eff (\_ x -> Identity (x + 1))) [1, 2, 3]
`shouldBe` [2 :: Int, 3, 4]
it "output equals f(input) for every step" $
hedgehog $ do
xs <- forAll $ Gen.list (Range.linear 0 50) (Gen.int (Range.linear (-100) 100))
let out = runPure (eff (\_ x -> Identity (x * 2))) xs
out === map (* 2) xs
mapAccumRequestSpec :: Spec
mapAccumRequestSpec = describe "mapAccumRequest" $ do
it "accumulates request times, post-state extraction" $
runTimed (mapAccumRequest (\req s _ -> s ++ [SerializeUTCTime (requestTime req)]) [] (map untime))
[(0, 'a'), (5, 'b'), (10, 'c')]
`shouldBe` [ [sec 0], [sec 0, sec 5], [sec 0, sec 5, sec 10] ]
it "output i is every request time seen so far" $
hedgehog $ do
secs' <- forAll $ Gen.list (Range.linear 0 30) (Gen.int (Range.linear 0 100))
let out = runTimed (mapAccumRequest (\req s _ -> s ++ [SerializeUTCTime (requestTime req)]) [] (map untime))
[(fromIntegral s, ()) | s <- secs']
expected = [ map (sec . fromIntegral) (take (i + 1) secs') | i <- [0 .. length secs' - 1] ]
out === expected
preMapAccumRequestSpec :: Spec
preMapAccumRequestSpec = describe "preMapAccumRequest" $ do
it "accumulates request times, pre-state extraction" $
runTimed (preMapAccumRequest (\req s _ -> s ++ [SerializeUTCTime (requestTime req)]) [] (map untime))
[(0, 'a'), (5, 'b'), (10, 'c')]
`shouldBe` [ [], [sec 0], [sec 0, sec 5] ]
it "output i is every request time before the current step" $
hedgehog $ do
secs' <- forAll $ Gen.list (Range.linear 0 30) (Gen.int (Range.linear 0 100))
let out = runTimed (preMapAccumRequest (\req s _ -> s ++ [SerializeUTCTime (requestTime req)]) [] (map untime))
[(fromIntegral s, ()) | s <- secs']
expected = [ map (sec . fromIntegral) (take i secs') | i <- [0 .. length secs' - 1] ]
out === expected
whenASpec :: Spec
whenASpec = describe "whenA" $ do
let counter = eff (\_ (_ :: Int) -> St (\s -> ((), s + 1)))
it "output is always () regardless of the predicate" $
fst (runStEff (whenA (> 5) counter) 0 [1, 6, 2, 7])
`shouldBe` [(), (), (), ()]
it "runs the inner arrow only when the predicate holds" $
snd (runStEff (whenA (> 5) counter) 0 [1, 6, 2, 7])
`shouldBe` 2
it "never runs the inner arrow when the predicate is always false" $
snd (runStEff (whenA (const False) counter) 0 [1, 6, 2, 7])
`shouldBe` 0
it "runs the inner arrow on every input when the predicate is always true" $
snd (runStEff (whenA (const True) counter) 0 [1, 6, 2, 7])
`shouldBe` 4
thenASpec :: Spec
thenASpec = describe "thenA" $ do
it "short-circuits on Left and continues on Right" $
runPure (filterA (even @Int) `thenA` filterA (> 3)) [1..6]
`shouldBe` [Left (), Left (), Left (), Right 4, Left (), Right 6]
it "(>>|) is an infix alias for thenA" $
runPure (filterA (even @Int) >>| filterA (> 3)) [1..6]
`shouldBe` [Left (), Left (), Left (), Right 4, Left (), Right 6]
it "second stage runs only when the first produces Right" $
hedgehog $ do
xs <- forAll $ Gen.list (Range.linear 0 30) (Gen.int (Range.linear (-20) 20))
let out = runPure (filterA (even @Int) >>| filterA (> 0)) xs
expected =
[ if odd x then Left ()
else if x > 0 then Right x
else Left ()
| x <- xs ]
out === expected
sampleSpec :: Spec
sampleSpec = describe "sample" $ do
it "tags the current value onto the Event structure" $
runPure sample [(1, Tick), (2, Event 'a'), (3, Tick)]
`shouldBe` [Tick, Event @Int 2, Tick]
it "output is Event a iff the input event is present" $
hedgehog $ do
vals <- forAll $ Gen.list (Range.linear 0 30) (Gen.int (Range.linear 0 100))
evs <- forAll $ Gen.list (Range.linear 0 30) eventGen
let n = min (length vals) (length evs)
ps = take n $ zip vals evs
out = runPure sample ps
for_ (zip ps out) $ \((v, ev), o) ->
o === tag v ev
-- | A stateless arrow carrying a fixed entity set, for testing propagation.
subscribed :: S.Set T.Text -> Mealy Identity Int Int
subscribed ents = Mealy ents emptyDiagram $ \_ -> Fun $ \_ a -> a
-- | Same as 'subscribed' but yields a function, for testing '<*>'.
subscribedF :: S.Set T.Text -> Mealy Identity Int (Int -> Int)
subscribedF ents = Mealy ents emptyDiagram $ \_ -> Fun $ \_ a -> (a +)
entitiesSpec :: Spec
entitiesSpec = describe "entities" $ do
it "id carries no entities" $
entities (arr id :: Mealy Identity Int Int) `shouldBe` S.empty
it "arr carries no entities" $
entities (arr (+ 1) :: Mealy Identity Int Int) `shouldBe` S.empty
it "eff carries no entities" $
entities (eff (\_ x -> Identity (x + 1 :: Int))) `shouldBe` S.empty
it "primitive combinators carry no entities" $ do
entities (hold 'a') `shouldBe` S.empty
entities (changes @Int) `shouldBe` S.empty
entities edge `shouldBe` S.empty
entities (sliding (3 :: Int) :: Mealy Identity (Event Int) [Int]) `shouldBe` S.empty
it "Category (.) unions entity sets" $
entities (subscribed (S.singleton "a") >>> subscribed (S.singleton "b"))
`shouldBe` S.fromList ["a", "b"]
it "Applicative (<*>) unions entity sets" $
entities (subscribedF (S.singleton "a") <*> subscribed (S.singleton "b"))
`shouldBe` S.fromList ["a", "b"]
it "Arrow (&&&) unions entity sets" $
entities (subscribed (S.singleton "a") &&& subscribed (S.singleton "b"))
`shouldBe` S.fromList ["a", "b"]
it "(>>>) unions entity sets" $
entities (subscribed (S.singleton "a") >>> arr id >>> subscribed (S.singleton "b"))
`shouldBe` S.fromList ["a", "b"]
it "left preserves the entity set" $
entities (left (subscribed (S.singleton "a")) :: Mealy Identity (Either Int Int) (Either Int Int))
`shouldBe` S.singleton "a"
it "first preserves the entity set" $
entities (first (subscribed (S.singleton "a")) :: Mealy Identity (Int, Int) (Int, Int))
`shouldBe` S.singleton "a"
it "fmap preserves the entity set" $
entities (fmap (+ 1) (subscribed (S.singleton "a")))
`shouldBe` S.singleton "a"
-21
View File
@@ -1,21 +0,0 @@
module BackoffProp (spec) where
import Data.Maybe (listToMaybe)
import Data.Time (NominalDiffTime)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import HomeAssistant.Runtime.Supervisor (Backoff (..), backoffDelay)
import Test.Hspec (Spec, describe, it)
import Test.Hspec.Hedgehog (hedgehog, forAll, (===))
spec :: Spec
spec = describe "backoffDelay" $
it "doubles from base, clamped at cap" $ hedgehog $ do
baseD <- forAll $ Gen.double (Range.constant 0.0001 10)
ratio <- forAll $ Gen.double (Range.constant 1 100)
let base = realToFrac baseD :: NominalDiffTime
cap = realToFrac (baseD * ratio) :: NominalDiffTime
backoff = Backoff base cap 1
delays = map (backoffDelay backoff) [1 .. 100 :: Int]
listToMaybe delays === Just (min cap base)
mapM_ (\(a, b) -> b === min cap (a * 2)) (zip delays (drop 1 delays))
+135
View File
@@ -0,0 +1,135 @@
{-# LANGUAGE OverloadedStrings #-}
module BedroomSpec (spec) where
import AFRP (Event (..), entities)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Aeson (Value)
import HomeAssistant.Controller
import HomeAssistant.Controller.Bedroom
import Support
import Test.Hspec
masseButton :: T.Text -> Event Value
masseButton = Event . buttonEvent "event.bedroom_quick_remote_masse_action"
enishenButton :: T.Text -> Event Value
enishenButton = Event . buttonEvent "event.bedroom_quick_jemina_action"
drawerState :: T.Text -> Event Value
drawerState = Event . stateEvent "binary_sensor.bedroom_nightstand_drawer_sensor_masse_contact"
spec :: Spec
spec = describe "Bedroom" $ do
entitySpec
drawerSpec
buttonSpec
entitySpec :: Spec
entitySpec = describe "entities" $ do
it "entityChangeEvent' registers its entity id" $
entities (entityChangeEvent' "sensor.foo")
`shouldBe` S.singleton "sensor.foo"
it "entityRead / entityBool inherit the entity id" $ do
entities (entityRead @Double "sensor.bar") `shouldBe` S.singleton "sensor.bar"
entities (entityBool "binary_sensor.baz") `shouldBe` S.singleton "binary_sensor.baz"
it "bedroomDrawerController subscribes to the drawer sensor" $
entities bedroomDrawerController
`shouldBe` S.singleton "binary_sensor.bedroom_nightstand_drawer_sensor_masse_contact"
it "bedroomButtonController subscribes to both remote event entities" $
entities bedroomButtonController
`shouldBe` S.fromList
[ "event.bedroom_quick_remote_masse_action"
, "event.bedroom_quick_jemina_action"
, "event.bedroom_remote_action"
]
it "bedroomPresenceController subscribes to the presence sensor" $
S.toList (entities bedroomPresenceController)
`shouldContain` [ "binary_sensor.presence_sensor_bedroom_occupancy" ]
it "humidifierController subscribes to the door sensor" $
entities humidifierController
`shouldBe` S.singleton "binary_sensor.makuuhuone_ovi_contact"
drawerSpec :: Spec
drawerSpec = describe "bedroomDrawerController" $ do
let entity = EntityId "switch.bedroom_drawer_light_masse"
it "turns the drawer light on when the drawer opens" $
services (runHASS bedroomDrawerController [drawerState "on"])
`shouldBe` [[switchService [entity] True]]
it "turns the drawer light off when the drawer closes" $
services (runHASS bedroomDrawerController [drawerState "off"])
`shouldBe` [[switchService [entity] False]]
it "toggles the light as the drawer opens and closes" $
services (runHASS bedroomDrawerController
[ drawerState "on", drawerState "off", drawerState "on" ])
`shouldBe` [ [switchService [entity] True]
, [switchService [entity] False]
, [switchService [entity] True]
]
it "ignores state events for other entities" $
services (runHASS bedroomDrawerController
[Event (stateEvent "binary_sensor.some_other_contact" "on")])
`shouldBe` [[]]
it "does nothing on Tick" $
services (runHASS bedroomDrawerController [Tick])
`shouldBe` [[]]
buttonSpec :: Spec
buttonSpec = describe "bedroomButtonController" $ do
let area = AreaId "makuuhuone"
it "Masse single click turns on his nightstand scene (lowest)" $
concat (services (runHASS bedroomButtonController [masseButton "1_short_release"]))
`shouldContain` [activateScene "scene.makuuhuone_masse"]
it "Masse double click turns on the middle scene" $
concat (services (runHASS bedroomButtonController [masseButton "1_double_press"]))
`shouldContain` [activateScene "scene.makuuhuone_keski"]
it "Masse long click turns on the bright scene" $
concat (services (runHASS bedroomButtonController [masseButton "1_long_press"]))
`shouldContain` [activateScene "scene.makuuhuone_kirkas"]
it "Masse off click turns the bedroom lights off" $
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
`shouldContain` [light [area] Off]
it "Enishen single click turns on her nightstand scene (lowest)" $
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
`shouldContain` [activateScene "scene.makuuhuone_jemina"]
it "Enishen double click turns on the middle scene" $
concat (services (runHASS bedroomButtonController [enishenButton "1_double_press"]))
`shouldContain` [activateScene "scene.makuuhuone_keski"]
it "Enishen long click turns on the bright scene" $
concat (services (runHASS bedroomButtonController [enishenButton "1_long_press"]))
`shouldContain` [activateScene "scene.makuuhuone_kirkas"]
it "Enishen off click turns the bedroom lights off" $
concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"]))
`shouldContain` [light [area] Off]
it "ignores the initial press (scene only fires on release)" $
services (runHASS bedroomButtonController [masseButton "1_initial_press"])
`shouldBe` [[]]
it "ignores button events for other entities" $
services (runHASS bedroomButtonController
[Event (buttonEvent "event.some_other_action" "1_short_release")])
`shouldBe` [[]]
it "does nothing on Tick" $
services (runHASS bedroomButtonController [Tick])
`shouldBe` [[]]
+61 -9
View File
@@ -2,44 +2,96 @@
module BusSpec (spec) where module BusSpec (spec) where
import AFRP (Request (..)) import AFRP (Request (..), Event (..))
import Control.Concurrent.STM import Control.Concurrent.STM
( atomically ( atomically
, dupTChan , dupTChan
, readTChan , readTChan
, writeTChan , writeTChan
) )
import Data.Aeson (Value (..)) import Data.Aeson (Value (..))
import Data.Time (UTCTime (..)) import qualified Data.HashMap.Strict as HM
import Data.Time (UTCTime (..), utc)
import Data.UUID (nil) import Data.UUID (nil)
import HomeAssistant.Controller (HASSEff (..), Service (..), Target(..)) import HomeAssistant.Controller (HASSEff (..), Service (..), Target(..))
import HomeAssistant.Runtime.Bus import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Flags (loadFlags, setEnabled)
import HomeAssistant.Runtime.Metrics (registerAppMetrics)
import Katip (Namespace (Namespace), runKatipContextT) import Katip (Namespace (Namespace), runKatipContextT)
import Katip.Monadic (runNoLoggingT)
import Support (withTestLogEnv)
import qualified System.Metrics as Metrics
import System.IO.Temp (withTempDirectory)
import System.Timeout (timeout)
import Test.Hspec import Test.Hspec
spec :: Spec spec :: Spec
spec = describe "Bus" $ do spec = describe "Bus" $ do
it "broadcasts inbound messages to every dup'd channel in order" $ withBus $ \bus -> do it "broadcasts inbound messages to every dup'd channel in order" $ withTestBus $ \bus -> do
p1 <- atomically $ dupTChan (busInbound bus) p1 <- atomically $ dupTChan (busInbound bus)
p2 <- atomically $ dupTChan (busInbound bus) p2 <- atomically $ dupTChan (busInbound bus)
atomically $ writeTChan (busInbound bus) (Number 1) atomically $ writeTChan (busInbound bus) (Event (Number 1))
atomically $ writeTChan (busInbound bus) (Number 2) atomically $ writeTChan (busInbound bus) (Event (Number 2))
r1 <- atomically $ (,) <$> readTChan p1 <*> readTChan p1 r1 <- atomically $ (,) <$> readTChan p1 <*> readTChan p1
r2 <- atomically $ (,) <$> readTChan p2 <*> readTChan p2 r2 <- atomically $ (,) <$> readTChan p2 <*> readTChan p2
r1 `shouldBe` (Number 1, Number 2) r1 `shouldBe` (Event (Number 1), Event (Number 2))
r2 `shouldBe` (Number 1, Number 2) r2 `shouldBe` (Event (Number 1), Event (Number 2))
it "channelHassEval writes CallService to the outbound channel" $ withBus $ \bus -> do it "channelHassEval writes CallService to the outbound channel" $ withTestBus $ \bus -> do
let req = Request (UTCTime (toEnum 0) 0) nil let req = Request (UTCTime (toEnum 0) 0) utc nil "test"
svc = Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"] svc = Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"]
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $ runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
channelHassEval bus (CallService req svc) channelHassEval bus (CallService req svc)
(_, svc') <- atomically $ readTChan (busOutbound bus) (_, svc') <- atomically $ readTChan (busOutbound bus)
svc' `shouldBe` svc svc' `shouldBe` svc
it "channelHassEval writes CallService to the outbound channel even when the handler is disabled" $
withTestFlagsBus $ \bus -> do
setEnabled (busFlags bus) "test-handler" False
let req = Request (UTCTime (toEnum 0) 0) utc nil "test-handler"
svc = Service "light" "turn_on" Nothing [EntityId "light.test"]
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
channelHassEval bus (CallService req svc)
result <- timeout 1000000 $ atomically $ readTChan (busOutbound bus)
case result of
Nothing -> expectationFailure "expected a write to the outbound channel"
Just (_, svc') -> svc' `shouldBe` svc
it "generates unique sequential call ids" $ do it "generates unique sequential call ids" $ do
gen <- mkCallIdGen 0 gen <- mkCallIdGen 0
a <- generateCallId gen a <- generateCallId gen
b <- generateCallId gen b <- generateCallId gen
(a, b) `shouldBe` (1, 2) (a, b) `shouldBe` (1, 2)
describe "recordInbound / recordOutbound" $ do
it "increments the trigger and service counters" $ do
store <- Metrics.newStore
m <- registerAppMetrics store
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir [])
withTestLogEnv $ \le -> withBus le m flags $ \bus -> do
recordInbound bus
recordInbound bus
recordOutbound bus
sample <- Metrics.sampleAll store
HM.lookup "hass.trigger.in" sample `shouldBe` Just (Metrics.Counter 2)
HM.lookup "hass.service.out" sample `shouldBe` Just (Metrics.Counter 1)
withTestBus :: (Bus -> IO a) -> IO a
withTestBus action = do
store <- Metrics.newStore
m <- registerAppMetrics store
withTestLogEnv $ \le ->
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir [])
withBus le m flags action
withTestFlagsBus :: (Bus -> IO a) -> IO a
withTestFlagsBus action = do
store <- Metrics.newStore
m <- registerAppMetrics store
withTestLogEnv $ \le ->
withTempDirectory "/tmp" "bus-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir ["test-handler"])
withBus le m flags action
+73 -21
View File
@@ -2,31 +2,83 @@
module ConnectionSpec (spec) where module ConnectionSpec (spec) where
import AFRP (Request(..))
import Data.Aeson (object, (.=)) import Data.Aeson (object, (.=))
import qualified Data.HashMap.Strict as HM
import Data.Maybe (fromJust)
import Data.Text (Text) import Data.Text (Text)
import Data.Time (UTCTime (..), utc)
import Data.UUID (fromString)
import HomeAssistant.Controller (Service (..), Target(..)) import HomeAssistant.Controller (Service (..), Target(..))
import HomeAssistant.Runtime.Connection (encodeService) import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Flags (loadFlags, setEnabled)
import HomeAssistant.Runtime.Metrics (registerAppMetrics)
import HomeAssistant.Runtime.RateLimit (registerRateLimitMetrics, slidingWindowLimiter)
import HomeAssistant.Runtime.Connection (dispatchService, encodeService, isTriggerEvent)
import Katip (Namespace (Namespace), runKatipContextT)
import Katip.Monadic (runNoLoggingT)
import Support (withTestLogEnv)
import System.IO.Temp (withTempDirectory)
import qualified System.Metrics as Metrics
import System.Timeout (timeout)
import Test.Hspec import Test.Hspec
spec :: Spec spec :: Spec
spec = describe "encodeService" $ do spec = do
it "encodes a call_service message" $ describe "encodeService" $ do
encodeService 7 (Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"]) it "encodes a call_service message" $
`shouldBe` object encodeService 7 (Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"])
[ "id" .= (7 :: Int) `shouldBe` object
, "type" .= ("call_service" :: Text) [ "id" .= (7 :: Int)
, "domain" .= ("light" :: Text) , "type" .= ("call_service" :: Text)
, "service" .= ("turn_on" :: Text) , "domain" .= ("light" :: Text)
, "target" .= object ["entity_id" .= ("light.bedroom_masse" :: Text)] , "service" .= ("turn_on" :: Text)
] , "target" .= object ["entity_id" .= ("light.bedroom_masse" :: Text)]
]
it "includes service_data when present" $
encodeService 8 (Service "light" "turn_on" (Just (object ["brightness" .= (200 :: Int)])) [EntityId "light.bedroom_masse"])
`shouldBe` object
[ "id" .= (8 :: Int)
, "type" .= ("call_service" :: Text)
, "domain" .= ("light" :: Text)
, "service" .= ("turn_on" :: Text)
, "target" .= object ["entity_id" .= ("light.bedroom_masse" :: Text)]
, "service_data" .= object ["brightness" .= (200 :: Int)]
]
describe "isTriggerEvent" $ do
it "is true for event frames" $
isTriggerEvent (object ["type" .= ("event" :: Text)]) `shouldBe` True
it "is false for result frames" $
isTriggerEvent (object ["type" .= ("result" :: Text)]) `shouldBe` False
it "is false when there is no type" $
isTriggerEvent (object ["id" .= (1 :: Int)]) `shouldBe` False
describe "dispatchService" $ do
it "skips disabled handlers without consuming a call id" $ do
store <- Metrics.newStore
m <- registerAppMetrics store
rlMetrics <- registerRateLimitMetrics store
limiter <- slidingWindowLimiter rlMetrics 10 20
withTempDirectory "/tmp" "connection-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir ["test"])
setEnabled flags "test" False
withTestLogEnv $ \le -> withBus le m flags $ \bus -> do
timeout 1000000 (do
runKatipContextT (busLogEnv bus) () (Namespace ["connection"]) $
dispatchService limiter bus (req 1) (lightOn [EntityId "light.test"])
generateCallId (busGen bus)) `shouldReturn` Just 1
sample <- Metrics.sampleAll store
HM.lookup "hass.service.out" sample `shouldBe` Just (Metrics.Counter 0)
req :: Int -> Request
req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc
(fromJust (fromString uuid)) "test"
where
pad i = replicate (12 - length (show i)) '0' <> show i
uuid = "00000000-0000-0000-0000-" <> pad n
lightOn :: [Target] -> Service
lightOn = Service "light" "turn_on" Nothing
it "includes service_data when present" $
encodeService 8 (Service "light" "turn_on" (Just (object ["brightness" .= (200 :: Int)])) [EntityId "light.bedroom_masse"])
`shouldBe` object
[ "id" .= (8 :: Int)
, "type" .= ("call_service" :: Text)
, "domain" .= ("light" :: Text)
, "service" .= ("turn_on" :: Text)
, "target" .= object ["entity_id" .= ("light.bedroom_masse" :: Text)]
, "service_data" .= object ["brightness" .= (200 :: Int)]
]
+28
View File
@@ -0,0 +1,28 @@
{-# LANGUAGE OverloadedStrings #-}
module ControllerSpec where
import Test.Hspec
import Data.Default (def)
import HomeAssistant.Controller (Brightness(..), formatLightAttributes, LightAttributes(..))
import Data.Aeson (object, (.=))
spec :: Spec
spec = describe "Generic controller" $
describe "Light settings" $ do
it "formats the default as empty" $
formatLightAttributes def `shouldBe` Nothing
it "formats the transition" $
formatLightAttributes def{lightTransition=Just 5} `shouldBe`
Just (object ["transition" .= (5 :: Int)])
it "formats the temperature" $
formatLightAttributes def{lightColorTemperature=Just 5} `shouldBe`
Just (object ["color_temp_kelvin" .= (5 :: Int)])
it "formats the brightness as percentage" $
formatLightAttributes def{lightBrightness=Just (BrightnessPercent 100)} `shouldBe`
Just (object ["brightness_pct" .= (100 :: Int)])
it "formats the brightness as absolute" $
formatLightAttributes def{lightBrightness=Just (BrightnessAbsolute 200)} `shouldBe`
Just (object ["brightness" .= (200 :: Int)])
it "formats multiple values" $
formatLightAttributes def{lightTransition = Just 5, lightBrightness=Just (BrightnessAbsolute 200)} `shouldBe`
Just (object ["brightness" .= (200 :: Int), "transition" .= (5 :: Int)])
+76
View File
@@ -0,0 +1,76 @@
{-# LANGUAGE OverloadedStrings #-}
module FlagsSpec (spec) where
import Control.Concurrent.Async (mapConcurrently_)
import Control.Monad.IO.Class (liftIO)
import Data.Aeson (decodeFileStrict)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Katip.Monadic (runNoLoggingT)
import System.IO.Temp (withTempDirectory)
import Test.Hspec
import Test.Hspec.Hedgehog
import HomeAssistant.Runtime.Flags
spec :: Spec
spec = describe "Flags" $ do
describe "loadFlags" $ do
it "defaults all names to True when the file is missing (opt-out)" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir ["a", "b"])
m <- allFlags flags
m `shouldBe` M.fromList [("a" :: Text, True), ("b", True)]
it "lets the file override the True default, missing keys stay True" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
let path = dir <> "/handlers.json"
writeFile path "{\"b\": false}"
flags <- runNoLoggingT (loadFlags dir ["a", "b"])
m <- allFlags flags
m `shouldBe` M.fromList [("a" :: Text, True), ("b" :: Text, False)]
it "treats a corrupt file as empty (all-enabled) without throwing" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
let path = dir <> "/handlers.json"
writeFile path "not json at all"
flags <- runNoLoggingT (loadFlags dir ["a"])
m <- allFlags flags
m `shouldBe` M.fromList [("a" :: Text, True)]
describe "isEnabled" $ do
it "returns the stored value" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
let path = dir <> "/handlers.json"
writeFile path "{\"a\": false}"
flags <- runNoLoggingT (loadFlags dir ["a"])
isEnabled flags "a" `shouldReturn` False
it "defaults unknown names to True" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir [])
isEnabled flags "unknown" `shouldReturn` True
describe "setEnabled" $ do
it "updates the in-memory map and persists to disk" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir ["a"])
setEnabled flags "a" False
isEnabled flags "a" `shouldReturn` False
-- reload from disk to confirm persistence
flags' <- runNoLoggingT (loadFlags dir ["a"])
isEnabled flags' "a" `shouldReturn` False
it "concurrent writes leave the file consistent with the TVar" $
hedgehog $ do
n <- forAll $ Gen.int (Range.linear 1 50)
liftIO $ withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir ["x"])
mapConcurrently_ (setEnabled flags "x" . even) [1 .. n]
m <- allFlags flags
decoded <- decodeFileStrict (dir <> "/handlers.json")
(decoded :: Maybe (Map Text Bool)) `shouldBe` Just m
+144
View File
@@ -0,0 +1,144 @@
{-# LANGUAGE OverloadedStrings #-}
module GraphingSpec (spec) where
import Control.Exception (SomeException, finally, try)
import qualified Data.ByteString as BS
import HomeAssistant.Runtime.Graphing
( GraphSpec (..)
, Range (..)
, Graph(..)
, buildGraphArgs
, graphs
, lookupGraph
, parseNameParam
, parseRange
, rangeStart
, readProcessBytes
)
import qualified HomeAssistant.Runtime.Metrics as Metrics
import System.Directory (findExecutable, getTemporaryDirectory, removeFile)
import System.Exit (ExitCode (..))
import System.Process (readProcessWithExitCode)
import Test.Hspec
import Servant.API (FromHttpApiData(..), ToHttpApiData (..))
traffic :: GraphSpec
traffic = case lookupGraph graphs Traffic of
Just s -> s
Nothing -> error "traffic graph is missing from the table"
spec :: Spec
spec = do
describe "Graph HttpApiData" $ do
-- There's an enumerable amount of graphs, we can just enumerate through them all
it "satisfies roundtrip property" $ do
let modes = [minBound..maxBound]
let got = map (parseQueryParam . toQueryParam @Graph) modes
let wanted = map Right modes
got `shouldBe` wanted
describe "parseRange" $ do
-- Fully enumerable
it "the http-api-data satisfies roundtrip property" $ do
let rs = [minBound..maxBound]
let got = map (parseQueryParam . toQueryParam @Range) rs
let wanted = map Right rs
got `shouldBe` wanted
it "accepts every suffix in the closed set" $
map parseRange ["10m", "1h", "24h", "7d", "30d"]
`shouldBe` [ Just TenMinutes
, Just OneHour
, Just OneDay
, Just OneWeek
, Just OneMonth
]
it "rejects everything outside the closed set" $
map parseRange
[ ""
, "1h "
, " 1h"
, "1h; rm -rf /"
, "end-1h"
, "../../etc/passwd"
, "1y"
, "30m"
, "1H"
]
`shouldBe` replicate 9 Nothing
describe "rangeStart" $ do
it "renders rrdtool end- relative starts" $
map rangeStart [TenMinutes, OneHour, OneDay, OneWeek, OneMonth]
`shouldBe` ["end-10m", "end-1h", "end-24h", "end-7d", "end-30d"]
describe "parseNameParam" $ do
it "resolves the traffic graph only with a .png suffix" $ do
fmap gsName (parseNameParam graphs "traffic.png") `shouldBe` Just "traffic"
parseNameParam graphs "traffic" `shouldBe` Nothing
it "rejects unknown, malformed, and traversing names" $
map (parseNameParam graphs)
[ "unknown.png"
, "../traffic.png"
, "traffic.png.png"
, ""
, "nope"
]
`shouldBe` replicate 5 Nothing
describe "buildGraphArgs" $ do
it "builds the traffic argv for a range" $
buildGraphArgs "hass-controller.rrd" traffic OneHour
`shouldBe`
[ "graph"
, "-"
, "--start", "end-1h"
, "--title", "Hass triggers in / services out"
, "--width", "800"
, "--height", "250"
, "--imgformat", "PNG"
, "DEF:in_raw=hass-controller.rrd:hass_trigger_in:AVERAGE"
, "CDEF:in=in_raw,60.0,*"
, "DEF:out_raw=hass-controller.rrd:hass_service_out:AVERAGE"
, "CDEF:out=out_raw,60.0,*"
, "LINE2:in#0066cc:Triggers in/min"
, "LINE2:out#cc0000:Service calls out/min"
]
describe "end-to-end (rrdtool-gated)" $ do
it "renders a PNG for the traffic graph" $ do
mRrdtool <- findExecutable "rrdtool"
case mRrdtool of
Nothing -> pendingWith "rrdtool not on PATH"
Just rrdtool -> do
tmp <- getTemporaryDirectory
let rrdPath = tmp ++ "/hass-controller-graph-test.rrd"
cleanup = try (removeFile rrdPath) :: IO (Either SomeException ())
schema =
[ ("hass_trigger_in", Metrics.Derive)
, ("hass_service_out", Metrics.Derive)
]
pngMagic = BS.pack [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
_ <- cleanup
( do
(createCode, _, _) <-
readProcessWithExitCode rrdtool (Metrics.buildCreateArgs rrdPath 10 schema) ""
createCode `shouldBe` ExitSuccess
(updateCode, _, _) <-
readProcessWithExitCode
rrdtool
(Metrics.buildUpdateArgs
rrdPath
["hass_trigger_in", "hass_service_out"]
[Just 5, Just 3])
""
updateCode `shouldBe` ExitSuccess
(code, out, _) <- readProcessBytes rrdtool (buildGraphArgs rrdPath traffic OneHour)
code `shouldBe` ExitSuccess
out `shouldSatisfy` BS.isPrefixOf pngMagic
)
`finally` cleanup
+64
View File
@@ -0,0 +1,64 @@
{-# LANGUAGE OverloadedStrings #-}
module HttpServerSpec (spec) where
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Lazy.Encoding (decodeUtf8)
import qualified Data.Text.Lazy as TL
import Lucid (Html, renderBS, toHtml)
import Test.Hspec
import HomeAssistant.Runtime.Graphing (Range (..))
import HttpServer
render :: Html () -> String
render = TL.unpack . decodeUtf8 . renderBS
spec :: Spec
spec = describe "HttpServer" $ do
describe "flagRow" $ do
it "renders the whole row so htmx can outerHTML-swap it" $
render (flagRow "tea" True) `shouldContain` "<tr id=\"status-tea\">"
it "requests an outerHTML swap (htmx casing)" $
render (flagRow "tea" True) `shouldContain` "hx-swap=\"outerHTML\""
it "displays on with a Disable button when enabled" $ do
let html = render (flagRow "tea" True)
html `shouldContain` "<td>on</td>"
html `shouldContain` "value=\"Disable\""
it "displays off with an Enable button when disabled" $ do
let html = render (flagRow "tea" False)
html `shouldContain` "<td>off</td>"
html `shouldContain` "value=\"Enable\""
describe "flagsPage" $ do
let page = flagsPage (FlagsResponse (M.fromList [("tea" :: Text, True)]))
it "uses the shared page shell with a style block" $
render page `shouldContain` "<style"
it "has a header row" $ do
let html = render page
html `shouldContain` "<th>Name</th>"
html `shouldContain` "<th>Value</th>"
it "carries each row id exactly once" $
T.count "id=\"status-tea\"" (T.pack (render page)) `shouldBe` 1
describe "statsPage" $ do
it "uses the shared page shell with a style block (full page)" $
render (toHtml (statsPage Nothing Nothing)) `shouldContain` "<style"
it "serves a bare fragment for htmx requests" $ do
let html = render (toHtml (statsPage (Just True) (Just OneDay)))
html `shouldNotContain` "DOCTYPE"
html `shouldContain` "<div id=\"stats\">"
it "range links swap the stats fragment in place" $ do
let html = render (toHtml (statsPage Nothing (Just OneDay)))
html `shouldContain` "hx-get=\"/stats?range=24h\""
html `shouldContain` "hx-target=\"#stats\""
html `shouldContain` "hx-push-url=\"true\""
+53
View File
@@ -0,0 +1,53 @@
{-# LANGUAGE OverloadedStrings #-}
module KitchenSpec (spec) where
import AFRP (Event (..), entities)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Aeson (Value)
import HomeAssistant.Controller
import HomeAssistant.Controller.Kitchen
import Support
import Test.Hspec
import Data.Default (def)
import Data.Time (getCurrentTime, addUTCTime)
-- Helper functions for creating test events
testDinnerLightLevel :: Int -> Event Value
testDinnerLightLevel level = Event (stateEvent "sensor.sijainti_keittio_light_level" (T.pack $ show level))
testDinnerPresence :: T.Text -> Event Value
testDinnerPresence state = Event (stateEvent "binary_sensor.sijainti_keittio_occupancy" state)
spec :: Spec
spec = describe "Kitchen" $ do
dinnerTableSpec
dinnerTableSpec :: Spec
dinnerTableSpec = describe "dinnerTableController" $ do
it "subscribes to the light level sensor" $ do
entities dinnerTableController
`shouldBe` S.fromList ["sensor.sijainti_keittio_light_level", "binary_sensor.sijainti_keittio_occupancy"]
it "subscribes to the presence sensor" $ do
entities dinnerTableController
`shouldBe` S.fromList ["sensor.sijainti_keittio_light_level", "binary_sensor.sijainti_keittio_occupancy"]
it "turns lights on when presence is occupied and light level is low" $ do
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "on"])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], [switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] False, light [EntityId "light.kitchen_dining_large"] (On def)]]
it "turns lights to sleep when presence is unoccupied" $ do
now <- getCurrentTime
services (runHASSTimed dinnerTableController [(now, testDinnerLightLevel 10), (now, testDinnerPresence "off")])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], []]
it "turns lights off when no presence for 300 seconds" $ do
now <- getCurrentTime
let later = 305 `addUTCTime` now
services (runHASSTimed dinnerTableController [(now, testDinnerLightLevel 10), (now, testDinnerPresence "off"), (later, Tick)])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], [], [switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] False, light [EntityId "light.kitchen_dining_large"] Off]]
it "does nothing on Tick" $ do
services (runHASS dinnerTableController [Tick])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True]]
+43
View File
@@ -0,0 +1,43 @@
{-# LANGUAGE OverloadedStrings #-}
module LivingroomSpec (spec) where
import AFRP (Event (..))
import Data.Time (UTCTime (..), fromGregorian)
import HomeAssistant.Controller
import HomeAssistant.Controller.Livingroom
import Support
import Test.Hspec
-- | A UTCTime at a given hour on March 15, 2025 (Spring).
springAt :: Int -> UTCTime
springAt h = UTCTime (fromGregorian 2025 3 15) (fromIntegral (h * 3600))
-- | A UTCTime at a given hour on July 15, 2025 (Summer).
summerAt :: Int -> UTCTime
summerAt h = UTCTime (fromGregorian 2025 7 15) (fromIntegral (h * 3600))
spec :: Spec
spec = describe "livingroomPlantLights" $ do
it "activates the Growth scene at 10:00 in Spring" $ do
let result = runHASSTimed livingroomPlantLights
[ (springAt 9, Tick)
, (springAt 10, Tick)
]
services result
`shouldBe` [ [], [activateScene "scene.olohuoneen_kasvivalo"] ]
it "activates the Ambience scene at 20:00 in Spring" $ do
let result = runHASSTimed livingroomPlantLights
[ (springAt 19, Tick)
, (springAt 20, Tick)
]
services result
`shouldBe` [ [], [activateScene "scene.kasvivalo_iltatila"] ]
it "does not activate Growth in Summer" $ do
let result = runHASSTimed livingroomPlantLights
[ (summerAt 9, Tick)
, (summerAt 10, Tick)
]
services result `shouldBe` [ [], [] ]
+20 -4
View File
@@ -1,16 +1,32 @@
module Main (main) where module Main (main) where
import Test.Hspec (hspec) import Test.Hspec (hspec)
import qualified BackoffProp import qualified AFRPLawsSpec
import qualified AFRPSpec
import qualified BedroomSpec
import qualified BusSpec import qualified BusSpec
import qualified ConnectionSpec import qualified ConnectionSpec
import qualified FlagsSpec
import qualified GraphingSpec
import qualified HttpServerSpec
import qualified KitchenSpec
import qualified LivingroomSpec
import qualified MetricsSpec
import qualified RuntimeSpec import qualified RuntimeSpec
import qualified SupervisorSpec import qualified ControllerSpec
main :: IO () main :: IO ()
main = hspec $ do main = hspec $ do
AFRPLawsSpec.spec
AFRPSpec.spec
BedroomSpec.spec
BusSpec.spec BusSpec.spec
ConnectionSpec.spec ConnectionSpec.spec
FlagsSpec.spec
GraphingSpec.spec
HttpServerSpec.spec
KitchenSpec.spec
LivingroomSpec.spec
MetricsSpec.spec
RuntimeSpec.spec RuntimeSpec.spec
SupervisorSpec.spec ControllerSpec.spec
BackoffProp.spec
+226
View File
@@ -0,0 +1,226 @@
{-# LANGUAGE OverloadedStrings #-}
module MetricsSpec (spec) where
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
import Data.List (isPrefixOf)
import Data.Text (Text)
import qualified Data.Text as T
import HomeAssistant.Runtime.Metrics
( DsType (..)
, DsSpec (..)
, dsTypeOf
, sanitizeName
, buildSchema
, buildCreateArgs
, buildUpdateArgs
, ensureRrd
, sampleAndUpdate
, parseInfoDs
, schemaMatches
, AppMetrics (..)
, registerAppMetrics
)
import qualified System.Metrics as M (Value (..))
import Test.Hspec
import Control.Exception (try, SomeException, finally)
import Control.Monad (forM_)
import System.Directory (findExecutable, getTemporaryDirectory, listDirectory, removeFile)
import System.Exit (ExitCode (ExitSuccess))
import System.Process (readProcessWithExitCode)
import qualified System.Metrics as Metrics
import qualified System.Metrics.Counter as Counter
import qualified System.Metrics.Gauge as Gauge
spec :: Spec
spec = do
describe "dsTypeOf" $ do
it "maps Counter to Derive" $
dsTypeOf (M.Counter 1000) `shouldBe` Just Derive
it "maps Gauge to Gauge" $
dsTypeOf (M.Gauge 500) `shouldBe` Just Gauge
it "maps Label to Nothing" $
dsTypeOf (M.Label "hello") `shouldBe` Nothing
describe "sanitizeName" $ do
it "replaces dots with underscores for short names" $
sanitizeName ("rts.gc.cpu_ms" :: Text) `shouldBe` "rts_gc_cpu_ms"
it "shortens names longer than 19 chars to 15 chars + _ + 3 hex" $ do
let result = sanitizeName ("rts.gc.par_balanced_bytes_copied" :: Text)
length result `shouldBe` 19
take 15 result `shouldBe` "rts_gc_par_bala"
drop 15 result `shouldBe` "_" ++ drop 16 result
it "is deterministic (same input -> same output)" $
sanitizeName ("rts.gc.peak_megabytes_allocated" :: Text)
`shouldBe` sanitizeName ("rts.gc.peak_megabytes_allocated" :: Text)
describe "buildSchema" $ do
it "builds sorted DsSpecs from counters and gauges, skipping labels" $
let sample :: HashMap Text M.Value
sample = HM.fromList
[ ("x.allocated", M.Counter 1000)
, ("a.bytes_used", M.Gauge 500)
, ("c.label_thing", M.Label "irrelevant")
]
in buildSchema sample `shouldBe`
[ DsSpec "a.bytes_used" "a_bytes_used" Gauge
, DsSpec "x.allocated" "x_allocated" Derive
]
it "produces dsName <= 19 chars for long ekg GC metric names" $
let sample :: HashMap Text M.Value
sample = HM.fromList
[ ("rts.gc.par_balanced_bytes_copied", M.Gauge 1)
, ("rts.gc.peak_megabytes_allocated", M.Gauge 2)
, ("rts.gc.cumulative_bytes_used", M.Counter 3)
]
in map (length . dsName) (buildSchema sample) `shouldSatisfy` all (<= 19)
describe "buildCreateArgs" $ do
it "builds create argv with mixed DERIVE and GAUGE DSes and RRAs" $
buildCreateArgs "test.rrd" 10
[ ("ds1", Derive)
, ("ds2", Gauge)
]
`shouldBe`
[ "create"
, "test.rrd"
, "--step"
, "10"
, "DS:ds1:DERIVE:20:0:U"
, "DS:ds2:GAUGE:20:0:U"
, "RRA:AVERAGE:0.5:1:6000"
, "RRA:MAX:0.5:1:6000"
, "RRA:AVERAGE:0.5:360:1680"
, "RRA:MAX:0.5:360:1680"
]
describe "buildUpdateArgs" $ do
it "builds update argv with numeric values" $
buildUpdateArgs "test.rrd" ["ds1", "ds2"] [Just 100, Just 200]
`shouldBe`
[ "update"
, "test.rrd"
, "--template"
, "ds1:ds2"
, "N:100:200"
]
it "renders Nothing as U (unknown)" $
buildUpdateArgs "test.rrd" ["ds1", "ds2"] [Just 100, Nothing]
`shouldBe`
[ "update"
, "test.rrd"
, "--template"
, "ds1:ds2"
, "N:100:U"
]
it "renders all-Nothing as all-U" $
buildUpdateArgs "test.rrd" ["ds1"] [Nothing]
`shouldBe`
[ "update"
, "test.rrd"
, "--template"
, "ds1"
, "N:U"
]
describe "parseInfoDs" $ do
it "extracts DS names and types from rrdtool info output" $
let info = unlines
[ "filename = \"test.rrd\""
, "step = 10"
, "ds[foo].index = 0"
, "ds[foo].type = \"DERIVE\""
, "ds[bar].type = \"GAUGE\""
, "rra[0].cf = \"AVERAGE\""
]
in parseInfoDs info `shouldBe` [("foo", Derive), ("bar", Gauge)]
it "ignores lines that are not ds type declarations" $
parseInfoDs "step = 10\nrra[0].cf = \"AVERAGE\"\n" `shouldBe` []
describe "schemaMatches" $ do
let ds name = DsSpec (T.pack name) name
it "is true for identical schemas regardless of order" $
schemaMatches [ds "b" Gauge, ds "a" Derive] [("a", Derive), ("b", Gauge)]
`shouldBe` True
it "is false when the derived schema has an added DS" $
schemaMatches [ds "a" Derive, ds "b" Gauge] [("a", Derive)]
`shouldBe` False
it "is false when the derived schema has a removed DS" $
schemaMatches [ds "a" Derive] [("a", Derive), ("b", Gauge)]
`shouldBe` False
it "is false when a DS type changed" $
schemaMatches [ds "a" Derive] [("a", Gauge)]
`shouldBe` False
describe "registerAppMetrics" $ do
it "registers both counters with the store" $ do
store <- Metrics.newStore
m <- registerAppMetrics store
Counter.inc (amTriggersIn m)
Counter.inc (amServicesOut m)
sample <- Metrics.sampleAll store
HM.lookup "hass.trigger.in" sample `shouldBe` Just (M.Counter 1)
HM.lookup "hass.service.out" sample `shouldBe` Just (M.Counter 1)
describe "end-to-end (rrdtool-gated)" $ do
it "creates an rrd, samples, and updates it" $ do
mRrdtool <- findExecutable "rrdtool"
case mRrdtool of
Nothing -> pendingWith "rrdtool not on PATH"
Just rrdtool -> do
store <- Metrics.newStore
c <- Metrics.createCounter "test.counter" store
g <- Metrics.createGauge "test.gauge" store
Counter.inc c
Gauge.set g 42
tmp <- getTemporaryDirectory
let rrdPath = tmp ++ "/hass-controller-metrics-test.rrd"
_ <- try (removeFile rrdPath) :: IO (Either SomeException ())
schema <- buildSchema <$> Metrics.sampleAll store
ensureRrd rrdtool rrdPath schema
sampleAndUpdate store rrdtool rrdPath schema
(rc, out, _) <- readProcessWithExitCode rrdtool ["fetch", rrdPath, "AVERAGE"] ""
rc `shouldBe` ExitSuccess
length out `shouldSatisfy` (> 0)
_ <- try (removeFile rrdPath) :: IO (Either SomeException ())
return ()
it "backs up and recreates the rrd when the schema changes" $ do
mRrdtool <- findExecutable "rrdtool"
case mRrdtool of
Nothing -> pendingWith "rrdtool not on PATH"
Just rrdtool -> do
tmp <- getTemporaryDirectory
let rrdPath = tmp ++ "/hass-controller-schema-change-test.rrd"
bakPrefix = "hass-controller-schema-change-test.rrd.bak-"
base = [ DsSpec "a" "a" Derive, DsSpec "b" "b" Gauge ]
expanded = base ++ [ DsSpec "c" "c" Derive ]
clean = do
stale <- filter (isPrefixOf bakPrefix) <$> listDirectory tmp
forM_ (rrdPath : map (\f -> tmp ++ "/" ++ f) stale) $ \f ->
try (removeFile f) :: IO (Either SomeException ())
clean
( do
ensureRrd rrdtool rrdPath base
ensureRrd rrdtool rrdPath base
noBackups <- filter (isPrefixOf bakPrefix) <$> listDirectory tmp
noBackups `shouldBe` []
ensureRrd rrdtool rrdPath expanded
backups <- filter (isPrefixOf bakPrefix) <$> listDirectory tmp
length backups `shouldBe` 1
(rc, out, _) <- readProcessWithExitCode rrdtool ["info", rrdPath] ""
rc `shouldBe` ExitSuccess
out `shouldContain` "ds[c].type"
) `finally` clean
+57 -34
View File
@@ -1,42 +1,65 @@
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedStrings #-}
module RuntimeSpec (spec) where module RuntimeSpec (spec) where
import Control.Concurrent (threadDelay) import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (async, race) import Control.Concurrent.Async (async, cancel, race, waitCatch)
import Control.Concurrent.STM (atomically, isEmptyTChan, readTChan, writeTChan) import Control.Exception (bracket)
import Data.Aeson (Value, object, (.=)) import Control.Monad (forever)
import Data.Text (Text) import Control.Monad.IO.Class (liftIO)
import HomeAssistant.Controller (light, lightController, Target (..)) import HomeAssistant.Runtime.Supervisor (supervised)
import HomeAssistant.Runtime (Controller (..), runController) import Katip (LogEnv, closeScribes, initLogEnv, runKatipContextT)
import HomeAssistant.Runtime.Bus
import Test.Hspec import Test.Hspec
spec :: Spec spec :: Spec
spec = describe "runController" $ do spec = describe "supervised" $ do
it "feeds inbound events through the machine and forwards service calls" $ withBus $ \bus -> do it "propagates ThreadKilled instead of retrying" $
_ <- async (runController bus (Controller "test" lightController True)) withTestLogEnv $ \le -> do
putStrLn "Before the delay" worker <- async $ runKatipContextT le () mempty $
threadDelay 100000 -- let the controller dup its inbound channel supervised "test" (liftIO (forever (threadDelay 100000)))
putStrLn "After the delay" threadDelay 200000
atomically $ writeTChan (busInbound bus) (doorEvent "on") -- initial value: no change event cancel worker
atomically $ writeTChan (busInbound bus) (doorEvent "off") -- door closes: lights on result <- race (threadDelay 5000000) (waitCatch worker)
atomically $ writeTChan (busInbound bus) (doorEvent "on") -- door opens: lights off case result of
putStrLn "After the writes" Left () -> expectationFailure
Right (_, svc1) <- boundedRead (busOutbound bus) "supervised retried on ThreadKilled (process would hang)"
Right (_, svc2) <- boundedRead (busOutbound bus) Right _ -> pure ()
putStrLn "After the reads"
svc1 `shouldBe` light [EntityId "light.bedroom_masse"] True
svc2 `shouldBe` light [EntityId "light.bedroom_masse"] False
atomically (isEmptyTChan (busOutbound bus)) `shouldReturn` True
where
boundedRead channel = race (threadDelay 10000) (atomically (readTChan channel))
doorEvent :: Text -> Value withTestLogEnv :: (LogEnv -> IO a) -> IO a
doorEvent state = object withTestLogEnv = bracket (initLogEnv "test" "test") closeScribes
[ "event" .= object
[ "data" .= object -- I'm commenting out the test as that specific controller
[ "entity_id" .= ("binary_sensor.makuuhuone_ovi_contact" :: Text) -- was just a dummy for seeing how the data flows (dead code)
, "new_state" .= object ["state" .= state] -- But leaving it commented as it retains some code sample on how and what to test
] --
] -- spec :: Spec
] -- spec = describe "runController" $ do
-- it "feeds inbound events through the machine and forwards service calls" $ withBus severity appMetrics $ \bus -> do
-- _ <- async (runController bus (Controller "test" lightController True))
-- putStrLn "Before the delay"
-- threadDelay 100000 -- let the controller dup its inbound channel
-- putStrLn "After the delay"
-- atomically $ writeTChan (busInbound bus) (Event (doorEvent "on")) -- initial value: no change event
-- atomically $ writeTChan (busInbound bus) (Event (doorEvent "off")) -- door closes: lights on
-- atomically $ writeTChan (busInbound bus) (Event (doorEvent "on")) -- door opens: lights off
-- putStrLn "After the writes"
-- Right (_, svc1) <- boundedRead (busOutbound bus)
-- Right (_, svc2) <- boundedRead (busOutbound bus)
-- putStrLn "After the reads"
-- svc1 `shouldBe` light [EntityId "light.bedroom_masse"] True
-- svc2 `shouldBe` light [EntityId "light.bedroom_masse"] False
-- atomically (isEmptyTChan (busOutbound bus)) `shouldReturn` True
-- where
-- boundedRead channel = race (threadDelay 10000) (atomically (readTChan channel))
--
-- doorEvent :: Text -> Value
-- doorEvent state = object
-- [ "event" .= object
-- [ "variables" .= object
-- [ "trigger" .= object
-- [ "entity_id" .= ("binary_sensor.makuuhuone_ovi_contact" :: Text)
-- , "to_state" .= object ["state" .= state]
-- ]
-- ]
-- ]
-- ]
-73
View File
@@ -1,73 +0,0 @@
{-# LANGUAGE OverloadedStrings #-}
module SupervisorSpec (spec) where
import Control.Concurrent (newEmptyMVar, putMVar, readMVar, threadDelay)
import Control.Concurrent.Async (async, cancel, poll, waitCatch)
import Control.Exception (fromException)
import Control.Exception.Annotated (AnnotatedException (..), throw)
import Control.Monad (forever)
import Data.IORef (atomicModifyIORef', newIORef, readIORef)
import Data.Maybe (isJust, isNothing)
import HomeAssistant.Runtime.Supervisor
import Test.Hspec
tinyBackoff :: Backoff
tinyBackoff = Backoff 0.001 0.002 0.001
spec :: Spec
spec = describe "supervised" $ do
it "restarts a crashing action until it stays up" $ do
counter <- newIORef (0 :: Int)
up <- newEmptyMVar
let action = do
n <- atomicModifyIORef' counter (\c -> (c + 1, c + 1))
if n < 3
then ioError (userError "boom")
else do putMVar up (); forever (threadDelay 1000000)
sup <- async (supervised "test" tinyBackoff action)
readMVar up
threadDelay 50000
status <- poll sup
isNothing status `shouldBe` True
readIORef counter `shouldReturn` 3
cancel sup
it "rethrows Fatal instead of restarting" $ do
counter <- newIORef (0 :: Int)
let action = do
_ <- atomicModifyIORef' counter (\c -> (c + 1, c + 1))
throw (Fatal "auth_invalid")
sup <- async (supervised "test" tinyBackoff action)
res <- waitCatch sup
case res of
Left se -> case fromException se :: Maybe (AnnotatedException Fatal) of
Just _ -> pure ()
Nothing -> expectationFailure "expected Fatal to propagate"
Right _ -> expectationFailure "supervised returned"
threadDelay 50000
readIORef counter `shouldReturn` 1
it "does not restart on async exceptions" $ do
counter <- newIORef (0 :: Int)
let action = do
_ <- atomicModifyIORef' counter (\c -> (c + 1, c + 1))
forever (threadDelay 1000000)
sup <- async (supervised "test" tinyBackoff action)
threadDelay 100000
cancel sup
threadDelay 100000
readIORef counter `shouldReturn` 1
status <- poll sup
isJust status `shouldBe` True
describe "nextAttempt" $ do
it "resets after a quiet period" $
nextAttempt tinyBackoff 0.001 5 `shouldBe` 1
it "increments otherwise" $
nextAttempt tinyBackoff 0.0005 5 `shouldBe` 6
describe "backoffDelay" $ do
it "starts at base" $ backoffDelay tinyBackoff 1 `shouldBe` 0.001
it "doubles" $ backoffDelay tinyBackoff 2 `shouldBe` 0.002
it "clamps at cap" $ backoffDelay tinyBackoff 3 `shouldBe` 0.002
+108
View File
@@ -0,0 +1,108 @@
{-# LANGUAGE OverloadedStrings #-}
module Support
( Acc(..)
, interp
, runHASS
, runHASSTimed
, services
, fakeRequest
, sec
, stateEvent
, buttonEvent
, withTestLogEnv
) where
import Control.Exception (bracket)
import Control.Monad.Fix (MonadFix (..))
import Data.Aeson (Value, object, (.=))
import Katip (LogEnv, closeScribes, initLogEnv)
import qualified Data.Text as T
import Data.Time (UTCTime (..), utc)
import Data.UUID (nil)
import AFRP (Mealy (..), Request (..), stepAuto, Event (..))
import HomeAssistant.Controller (HASSEff (..), Service)
fakeRequest :: Request
fakeRequest = Request (sec 0) utc nil "test"
sec :: Integer -> UTCTime
sec n = UTCTime (toEnum 0) (fromIntegral n)
-- | A pure Writer-like monad accumulating `Service` calls per step.
newtype Acc a = Acc { runAcc :: [Service] -> (a, [Service]) }
instance Functor Acc where
fmap f (Acc g) = Acc $ \s -> let (a, s') = g s in (f a, s')
instance Applicative Acc where
pure a = Acc (a,)
Acc f <*> Acc x = Acc $ \s -> let (f', s') = f s; (a, s'') = x s' in (f' a, s'')
instance Monad Acc where
Acc m >>= k = Acc $ \s -> let (a, s') = m s; (b, s'') = runAcc (k a) s' in (b, s'')
instance MonadFix Acc where
mfix f = Acc $ \s -> let (a, s') = runAcc (f a) s in (a, s')
-- | A silent LogEnv: no scribes registered, so nothing is written anywhere.
withTestLogEnv :: (LogEnv -> IO a) -> IO a
withTestLogEnv = bracket (initLogEnv "test" "test") closeScribes
-- | Interpret `HASSEff` in `Acc`: record `CallService`, drop tracing/debug.
interp :: HASSEff a -> Acc a
interp (CallService _ svc) = Acc $ \s -> ((), s ++ [svc])
interp (CallServices _ svc) = Acc $ \s -> ((), s ++ svc)
interp (Debug _) = pure ()
interp (Trace _ _) = pure ()
-- | Run a HASS arrow over a list of inputs, collecting per-step emitted services.
runHASS :: Mealy HASSEff a b -> [a] -> [(b, [Service])]
runHASS m = go (runMealy m interp)
where
go _ [] = []
go w (a : as) =
case runAcc (stepAuto w fakeRequest a) [] of
((b, w'), svcs) -> (b, svcs) : go w' as
-- | Run a HASS arrow over a list of (time, input) pairs, collecting per-step
-- emitted services. Each step uses a fresh Request with the given UTCTime.
runHASSTimed :: Mealy HASSEff (Event a) b -> [(UTCTime, Event a)] -> [(b, [Service])]
runHASSTimed m = go (runMealy m interp)
where
go _ [] = []
go w ((t, a) : as) =
case runAcc (stepAuto w (Request t utc nil "test") a) [] of
((b, w'), svcs) -> (b, svcs) : go w' as
services :: [(b, [Service])] -> [[Service]]
services = map snd
-- | Build a state-trigger payload matching `entityChangeEvent'` / `entityBool'`
-- lenses. The subscribe_trigger websocket event wraps the trigger datum under
-- `event.variables.trigger`, with `entity_id` and `to_state.state` fields.
stateEvent :: T.Text -> T.Text -> Value
stateEvent entityId state = object
[ "event" .= object
[ "variables" .= object
[ "trigger" .= object
[ "entity_id" .= entityId
, "to_state" .= object [ "state" .= state ]
]
]
]
]
-- | Build an Ikea button trigger payload matching `ikeaQuickButton` lenses.
buttonEvent :: T.Text -> T.Text -> Value
buttonEvent entityId eventType = object
[ "event" .= object
[ "variables" .= object
[ "trigger" .= object
[ "entity_id" .= entityId
, "to_state" .= object
[ "attributes" .= object [ "event_type" .= eventType ] ]
]
]
]
]