1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE QuasiQuotes #-}

module OpenlabTools where

import Builder
import Control.Category qualified as Cat
import Control.Concurrent.STM hiding (atomically, readTVarIO)
import Control.DeepSeq (NFData, deepseq)
import Control.Monad.Except (runExcept, throwError)
import Control.Monad.Logger qualified as Logger
import Control.Monad.Logger.CallStack
import Control.Monad.Reader
import Data.Attoparsec.ByteString qualified as Atto
import Data.CaseInsensitive qualified as CaseInsensitive
import Data.Either (partitionEithers)
import Data.Error.Tree
import Data.Functor (($>))
import Data.HashMap.Strict qualified as HashMap
import Data.List qualified as List
import Data.List.NonEmpty qualified as NonEmpty
import Data.Maybe (listToMaybe, maybeToList)
import Data.Monoid qualified as Monoid
import Data.Text qualified as Text
import Data.Time (NominalDiffTime, UTCTime (utctDayTime), diffUTCTime, getCurrentTime)
import Data.Time qualified as Time
import Data.Time.Clock (addUTCTime)
import Data.Time.Format qualified as Time.Format
import Debug.Trace
import FieldParser (FieldParser' (..))
import FieldParser qualified as Field
import GHC.Stack qualified
import IHP.HSX.QQ (hsx)
import Label
import MyLabel
import MyPrelude
import Network.HTTP.Client.Conduit qualified as Http
import Network.HTTP.Simple qualified as Http
import Network.HTTP.Types qualified as Http
import Network.Wai qualified as Wai
import Network.Wai.Handler.Warp qualified as Warp
import OpenTelemetry.Trace qualified as Otel hiding (getTracer, inSpan, inSpan')
import OpenTelemetry.Trace.Core qualified as Otel hiding (inSpan, inSpan')
import OpenTelemetry.Trace.Monad qualified as Otel
import Parse (Parse, mkParseNoContext, mkParsePushContext)
import Parse qualified
import System.Environment qualified as Env
import System.IO qualified as IO
import Text.Blaze.Html.Renderer.Pretty qualified as Html.Pretty
import Text.Blaze.Html.Renderer.Utf8 qualified as Html
import Text.Blaze.Html5 qualified as Html
import Text.HTML.TagSoup qualified as Soup
import Text.HTML.TagSoup.Tree qualified as SoupTree
import Text.StringLike qualified as Soup
import UnliftIO hiding (Handler, newTVarIO)
import Prelude hiding (span, until)

-- | Link to the https://mapall.space heatmap for the OpenLab Augsburg
mapallSpaceOla :: Text
mapallSpaceOla = "https://mapall.space/heatmap/show.php?id=OpenLab+Augsburg"

-- | Link to the OpenLab Augsburg wiki page containing the calendar html
openlabWikiCalendar :: Text
openlabWikiCalendar = "https://wiki.openlab-augsburg.de"

mainPage :: Html.Html
mainPage =
  Html.docTypeHtml
    [hsx|
          <head>
            <title>Openlab Augsburg Tools</title>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
          </head>

          <body>
            <p>Welcome to the OpenLab Augsburg tools thingy. The idea is to provide some services that can be embedded into our other pages.</p>

            <h2>Whats there</h2>
            <ul>
              <li>
                A <a href="snips/table-opening-hours-last-week">table displaying the opening hours last week</a>, courtesy of <a href={mapallSpaceOla}>mapall.space</a>.
              </li>
              <li>
                An <a href="events/openlab-augsburg-recurring-events.ics"><code>.ical</code> calendar file</a> for recurring events in the OpenLab, generated from the <code>&lt;span&gt;</code>s on the <a href="https://wiki.openlab-augsburg.de/">frontpage of our Wiki</a>. (Something wrong with the ical file? Check out the <a href="events/debug.html">debug section</a>.)
              </li>
            </ul>


            <h2>Show me the code/how to contribute</h2>

            <p>The source code can be found <a href="https://code.tvl.fyi/tree/users/Profpatsch/openlab-tools">in my user dir in the tvl repo</a>.</p>

            <p>To build the server, clone the repository from <a href="https://code.tvl.fyi/depot.git">https://code.tvl.fyi/depot.git</a>.
            Then <code>cd</code> into <code>users/Profpatsch</code>, run <code>nix-shell</code>.
            </p>

            <p>You can now run the server with <code>cabal repl openlab-tools/`</code> by executing the <code>main</code> function inside the GHC repl. It starts on port <code>9099</code>.
            <br>
            To try out changes to the code, stop the server with <kbd><kbd>Ctrl</kbd>+<kbd>c</kbd></kbd> and type <code>:reload</code>, then <code>main</code> again.
            <br>
            Finally, from within <code>users/Profpatsch</code> you can start a working development environment by installing <var>vscode</var> or <var>vscodium</var> and the <var>Haskell</var> extension. Then run <code>code .</code> from within the directory.
            </p>

            <p>Once you have a patch, <a href="https://matrix.to/#/@profpatsch:augsburg.one">contact me on Matrix</a> or DM me at <code>irc/libera</code>, nick <code>Profpatsch</code>.
            </p>
          </body>
        |]

debug :: Bool
debug = False

-- | Run the given application; can be used to test functions that return 'AppT'.
mainWith :: AppT IO a -> IO a
mainWith appT = withTracer $ \tracer -> do
  runReaderT appT.unAppT Context {..}

-- Run the app.
main :: IO ()
main = mainWith $ do
  let runApplication ::
        (MonadUnliftIO m, MonadLogger m) =>
        ( Wai.Request ->
          (Wai.Response -> m Wai.ResponseReceived) ->
          m Wai.ResponseReceived
        ) ->
        m ()
      runApplication app = do
        withRunInIO $ \runInIO -> Warp.run 9099 $ \req respond -> do
          let catchAppException act =
                try act >>= \case
                  Right a -> pure a
                  Left (AppException err) -> do
                    runInIO (logError err)
                    respond (Wai.responseLBS Http.status500 [] "")
          liftIO $ catchAppException (runInIO $ app req (\resp -> liftIO $ respond resp))

  runHandlers
    runApplication
    appHandlers

-- | App handlers
appHandlers :: [Handler (AppT IO)]
appHandlers = do
  [ Handler
      { path = "",
        body =
          Body
            (pure ())
            (\((), _) -> pure $ ok200Html [] (renderHtml mainPage))
      },
    Handler
      { path = "snips/table-opening-hours-last-week",
        body =
          Body
            ((label @"ifModifiedSince" <$> parseIfModifiedSince))
            ( \(req', cache) -> do
                now <- liftIO getCurrentTime <&> mkSecondTime
                new <- updateCacheIfNewer now cache heatmap
                let cacheToHeaders =
                      [ ("Last-Modified", new.lastModified & formatHeaderTime),
                        ("Expires", new.until & formatHeaderTime),
                        ( "Cache-Control",
                          let maxAge = new.until `diffSecondTime` now
                           in [fmt|max-age={maxAge & floor @NominalDiffTime @Int  & show}, immutable|]
                        )
                      ]
                if
                  -- If the last cache update is newer or equal to the requested version, we can tell the browser it’s fine
                  | Just modifiedSince <- req'.ifModifiedSince,
                    modifiedSince >= new.lastModified ->
                      pure $ Wai.responseLBS Http.status304 cacheToHeaders ""
                  | otherwise ->
                      pure $ ok200Html cacheToHeaders (new.result & toLazyBytes)
            )
      },
    Handler
      { path = "events/openlab-augsburg-recurring-events.ics",
        body =
          Body
            (pure ())
            ( \(_req', _cache) -> do
                cal <- readOpenlabWikiCalendar
                pure $
                  Wai.responseLBS
                    Http.status200
                    [("Content-Type", "text/calendar")]
                    (cal.ical & textToBytesUtf8 & toLazyBytes)
            )
      },
    Handler
      { path = "events/debug.html",
        body =
          Body
            (pure ())
            ( \(_req', _cache) -> do
                cal <- readOpenlabWikiCalendar
                let html =
                      [hsx|
                      <!DOCTYPE html>
                      <head>
                        <title>Openlab Events Ical Debugging</title>
                        <meta charset="utf-8">
                      </head>
                      <body>
                        <h1>Ical error debugging</h1>
                        <p><a href="openlab-augsburg-recurring-events.ics"> Kalenderlink</a></p>
                        <p>Ich habe gerade versucht, das <code>.ical</code> aus dem Wiki zu generieren, und die folgenden Events warfen Fehler:</p>
                        <pre>
                          {cal.err & prettyErrorTree}
                        </pre>

                        <p>Aber nicht alles ist verloren! Die folgenden Events konnten geparsed werden und ein Subset funktioniert eventuell, so sieht die <code>.ical</code> aus:</p>

                        <pre>
                          {cal.ical}
                        </pre>
                      </body>
                   |]
                pure $
                  Wai.responseLBS
                    Http.status200
                    [("Content-Type", "text/html")]
                    (html & Html.renderHtml)
            )
      }
    ]
  where
    renderHtml =
      if debug
        then Html.Pretty.renderHtml >>> stringToText >>> textToBytesUtf8 >>> toLazyBytes
        else Html.renderHtml

    ok200Html extra res = Wai.responseLBS Http.ok200 (("Content-Type", "text/html") : extra) res

    -- "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified#syntax"
    headerFormat = "%a, %d %b %0Y %T GMT"
    formatHeaderTime (SecondTime t) =
      t
        & Time.Format.formatTime
          @UTCTime
          Time.Format.defaultTimeLocale
          headerFormat
        & stringToText
        & textToBytesUtf8
    parseHeaderTime =
      Field.utf8
        >>> ( FieldParser $ \t ->
                t
                  & textToString
                  & Time.Format.parseTimeM
                    @Maybe
                    @UTCTime
                    {-no leading whitespace -} False
                    Time.Format.defaultTimeLocale
                    headerFormat
                  & annotate [fmt|Cannot parse header timestamp "{t}"|]
            )
    parseIfModifiedSince :: Parse Wai.Request (Maybe SecondTime)
    parseIfModifiedSince =
      lmap
        ( (.requestHeaders)
            >>> findMaybe
              ( \(h, v) ->
                  if "If-Modified-Since" == CaseInsensitive.mk h then Just v else Nothing
              )
        )
        (Parse.maybe $ Parse.fieldParser parseHeaderTime)
        & rmap (fmap mkSecondTime)

-- | Extract the heatmap from https://mapall.space
heatmap :: AppT IO ByteString
heatmap = do
  Http.httpBS [fmt|GET {mapallSpaceOla}|]
    <&> (.responseBody)
    <&> Soup.parseTags
    <&> Soup.canonicalizeTags
    <&> findHeatmap
    <&> fromMaybe (htmlToTags [hsx|<p>Uh oh! could not fetch the table from <a href={mapallSpaceOla}>{mapallSpaceOla}</a></p>|])
    <&> Soup.renderTags
  where
    firstSection f t = t & Soup.sections f & listToMaybe
    match :: Soup.Tag ByteString -> Soup.Tag ByteString -> Bool
    match x (t :: Soup.Tag ByteString) = (Soup.~==) @ByteString t x
    findHeatmap t =
      t
        & firstSection (match (Soup.TagOpen ("") [("class", "heatmap")]))
        >>= firstSection (match (Soup.TagOpen "table" []))
          <&> getTable
          <&> (<> htmlToTags [hsx|<figcaption>source: <a href={mapallSpaceOla} target="_blank">mapall.space</a></figcaption>|])
          <&> wrapTagStream (T2 (label @"el" "figure") (label @"attrs" []))

    -- get the table from opening tag to closing tag (allowing nested tables)
    getTable = go 0
      where
        go _ [] = []
        go d (el : els)
          | match (Soup.TagOpen "table" []) el = el : go (d + 1) els
          | match (Soup.TagClose "table") el = if d <= 1 then [el] else el : go (traceShowId $ d - 1) els
          | otherwise = el : go d els

    htmlToTags :: Html.Html -> [Soup.Tag ByteString]
    htmlToTags h = h & Html.renderHtml & toStrictBytes & Soup.parseTags

    -- TODO: this is dog-slow because of the whole list recreation!
    wrapTagStream ::
      T2 "el" ByteString "attrs" [Soup.Attribute ByteString] ->
      [Soup.Tag ByteString] ->
      [Soup.Tag ByteString]
    wrapTagStream tag inner = (Soup.TagOpen (tag.el) tag.attrs : inner) <> [Soup.TagClose tag.el]

-- | Read the OpenLab wiki calendar from the wiki page and parse it into a list of events.
readOpenlabWikiCalendar :: AppT IO (T2 "err" ErrorTree "ical" Text)
readOpenlabWikiCalendar =
  Http.httpBS @(AppT IO)
    ( [fmt|GET {openlabWikiCalendar}|]
        & Http.setRequestHeader "User-Agent" ["curl/8.11.1"]
        & Http.setRequestHeader "Accept" ["text/html"]
    )
    <&> (.responseBody)
    <&> Soup.parseTags
    <&> Soup.canonicalizeTags
    <&> findCalendarEntries
    <&> map
      ( \calendarEntry -> do
          let getAttr attrName = mkParsePushContext attrName $
                \as -> as & List.lookup (attrName & textToBytesUtf8) & annotate [fmt|Missing span attribute {attrName}|]
          let getAttrs attrName = mkParsePushContext attrName $
                \as -> as & mapMaybe (\(k, v) -> v & guarded (textToBytesUtf8 attrName == k)) & pure

          let attrs = Parse.name "<span> attributes" $ do
                dataSince <- getAttr "data-since" >>> Parse.fieldParser (Field.utf8 >>> Field.hyphenatedDay)
                dataStableId <- getAttr "data-stable-id" >>> Parse.fieldParser Field.utf8
                dataAdditional <- getAttrs "data-additional" >>> Parse.multiple (Parse.fieldParser (Field.utf8 >>> Field.hyphenatedDay))
                dataExcept <- getAttrs "data-except" >>> Parse.multiple (Parse.fieldParser (Field.utf8 >>> Field.hyphenatedDay))
                pure (t3 #since dataSince #stableId dataStableId #excepts (t2 #additional dataAdditional #excepts dataExcept))

          let dateSpec = Parse.name "<span> date spec" $ Parse.withFrom $ \spec ->
                Parse.fieldParser $ attoparsecBytes' [fmt|error parsing dateSpec from: {spec & bytesToTextUtf8Lenient}|] parseDateSpec

          let headerText =
                ( (findTagOneOf ["h1", "h2", "h3", "h4", "h5", "h6"] <&> toList)
                    >>>
                    -- ignore the toc-anchor tag
                    firstDirectTagText
                      ( \case
                          SoupTree.TagBranch _ attrs' _ -> not $ classContains "toc-anchor" attrs'
                          _ -> True
                      )
                )

          let parser = do
                span <- Parse.name "datespec <span>" $ do
                  attrs' <- lmap (.attrsSet) attrs
                  dateSpec' <- lmap (.spanText) dateSpec
                  pure $ t2 #attrs attrs' #dateSpec dateSpec'
                heading <- lmap (.sectionTags) $ Parse.name "section heading" headerText
                body <- lmap (.sectionTags) identity <&> skipTag
                pure $
                  OpenlabWikiCalendarIcal
                    { since = span.attrs.since,
                      stableId = span.attrs.stableId,
                      dateSpec = span.dateSpec,
                      additional = span.attrs.excepts.additional,
                      excepts = span.attrs.excepts.excepts,
                      heading,
                      body
                    }

          Parse.runParse "Parse error when getting span tag" parser calendarEntry
            & first
              ( \err ->
                  nestedMultiError
                    "Cannot parse calendar event"
                    $ err
                      :| [ nestedError
                             "The calender section we tried to parse was"
                             ( calendarEntry.sectionTags
                                 & Soup.renderTags
                                 & bytesToTextUtf8Lenient
                                 & newError
                                 & singleError
                             )
                         ]
              )
      )
    <&> partitionEithers
    <&> \(errs, events) ->
      t2
        #err
        ( case errs of
            IsEmpty -> "No errors! :)"
            IsNonEmpty e -> nestedMultiError "Errors when parsing these events from the wiki" e
        )
        #ical
        (mkOpenlabWikiCalendarIcal events)

-- | Whether the class is in the class attribute
classContains :: Text -> [Soup.Attribute ByteString] -> Bool
classContains className attrs =
  attrs
    & List.lookup "class"
    <&> (\val -> className `Text.isInfixOf` (val & bytesToTextUtf8Lenient))
    & fromMaybe False

-- | Skip a single tag (forward until its closing tag), ignore nested tags of the same kind
--
-- TODO: unify with the <table> find above
skipTag :: forall str. (Soup.StringLike str) => [Soup.Tag str] -> [Soup.Tag str]
skipTag [] = []
skipTag (Soup.TagOpen name _ : more) = go name 0 more
  where
    go :: str -> Int -> [Soup.Tag str] -> [Soup.Tag str]
    go _ _ [] = []
    go n d (el : els)
      | match (Soup.TagOpen n []) el = go n (d + 1) els
      | match (Soup.TagClose n) el = if d <= 1 then els else go n (traceShowId $ d - 1) els
      | otherwise = go n d els
    match :: Soup.Tag str -> Soup.Tag str -> Bool
    match x (t :: Soup.Tag str) = (Soup.~==) @str t x
skipTag ts = ts

-- | Get the first TagText content in the given subtree.
--
-- The @useSubtree@ filter can be used to filter out unwanted subtags.
firstDirectTagText :: (SoupTree.TagTree ByteString -> Bool) -> Parse [Soup.Tag ByteString] Text
firstDirectTagText useSubtree =
  mkParseNoContext $
    ( \ts -> runExcept $ do
        ts
          & SoupTree.tagTree
          -- We should be in a surrounding element now
          & ( \case
                [] -> throwError [fmt|Cannot find a subtree|]
                (SoupTree.TagBranch _ _ children : _) -> pure children
                _ -> throwError [fmt|Cannot find a subtree|]
            )
          <&> List.filter useSubtree
          >>= \case
            IsEmpty -> throwError [fmt|Cannot find tags to extract text|]
            IsNonEmpty ts' ->
              ts'
                & toList
                -- flatten again, find the first tag text
                & SoupTree.flattenTree
                & mapMaybe Soup.maybeTagText
                <&> bytesToTextUtf8Lenient
                -- ignore all only-whitespace text
                <&> Text.strip
                & List.filter ("" /=)
                & \case
                  IsEmpty -> throwError [fmt|Cannot find any plain text element|]
                  IsNonEmpty a -> pure (NonEmpty.head a)
    )

-- | Find the first tag content that is one of the list of given tag names.
-- Includes the opening and closing element.
findTagOneOf :: [Text] -> Parse [Soup.Tag ByteString] (NonEmpty (Soup.Tag ByteString))
findTagOneOf names =
  Parse.mkParsePushContext [fmt|findTag[{names & Text.intercalate ","}]|] $ \tags -> runExcept $ do
    let namesB = names & map textToBytesUtf8
    tags
      & \case
        IsEmpty -> throwError [fmt|Empty list of tags|]
        IsNonEmpty t -> pure t
      <&> NonEmpty.tails1
      <&> findMaybe
        ( \hs ->
            if
              | (Soup.TagOpen name' _) <- NonEmpty.head hs,
                name' `List.elem` namesB ->
                  Just $ t2 #tagName name' #tags hs
              | otherwise -> Nothing
        )
      >>= maybe (throwError [fmt|No tag found that are any of "{names & Text.intercalate ", "}"|]) pure
      >>= ( \sect -> do
              sect.tags
                & NonEmpty.break
                  (Soup.isTagCloseName sect.tagName)
                & \case
                  (inner, IsNonEmpty (end :| _)) -> pure $ NonEmpty.prependList inner $ singleton end
                  -- no closing tag found
                  (_inner, IsEmpty) -> throwError [fmt|No closing tag found for "{sect.tagName}"|]
          )

-- | Find all calendar entries by their <span> tag in the wiki page, and their corresponding section tags.
findCalendarEntries ::
  [Soup.Tag ByteString] ->
  [T3 "attrsSet" [Soup.Attribute ByteString] "spanText" ByteString "sectionTags" [Soup.Tag ByteString]]
findCalendarEntries tags =
  tags
    & headerSections
    -- get everything till the end of this heading
    & mapMaybe (\sect -> getFirstTagName sect <&> \name -> onlyThisHead name sect)
    -- find the datespec
    & mapMaybe
      ( \sect ->
          sect
            & overNonEmpty findDatespecSpan
            <&> ( \t ->
                    t3
                      #attrsSet
                      t.attrsSet
                      #spanText
                      t.spanText
                      #sectionTags
                      sect
                )
      )
  where
    isHeader t =
      any
        ($ t)
        [ Soup.isTagOpenName "h1",
          Soup.isTagOpenName "h2",
          Soup.isTagOpenName "h3",
          Soup.isTagOpenName "h4",
          Soup.isTagOpenName "h5",
          Soup.isTagOpenName "h6"
        ]
    -- all sections that start with a header tag
    headerSections = Soup.sections isHeader

    -- everything until the next header that matches the given tag
    onlyThisHead headerName ts =
      ts
        & Soup.partitions
          -- break on any header that is on the same level or bigger
          -- (e.g. if we are a h2, break on h2 and h1)
          (\t -> any (\h -> Soup.isTagOpenName h t) (upperHeaders headerName))
        & headMay
        & maybeToList
        & join

    -- headers that have a bigger powerlevel than the given header
    upperHeaders h = ["h6", "h5", "h4", "h3", "h2", "h1"] & List.dropWhile (/= h)

    getFirstTagName =
      findMaybe
        ( \case
            (Soup.TagOpen name _) -> Just name
            _ -> Nothing
        )

    -- find a <span>-tag like <span data-since="2025-01-01">Th[1] 19:00+</span>
    findDatespecSpan ::
      NonEmpty (Soup.Tag ByteString) ->
      Maybe
        (T2 "attrsSet" [Soup.Attribute ByteString] "spanText" ByteString)
    findDatespecSpan ts =
      ts
        -- We need the info whether there is another header before the span
        -- But ignore the first element since it’s always a header
        & (\(t :| ts') -> t2 #acc mempty #dat t :| zipWithFold (Monoid.Any . isHeader) ts')
        -- Get the first datespec span tag in this section
        & NonEmpty.tails1
        & findMaybe
          ( \ts'' -> do
              let h = NonEmpty.head ts''
              let headerTag = h.dat
              let leadingHeader = h.acc
              if
                -- if we find another header before the datespec, this is not a datespec header section (prevents duplicates)
                | Monoid.Any True <- leadingHeader -> Nothing
                | Soup.TagOpen name attrsSet <- headerTag,
                  name == "span",
                  Just _ <- List.lookup "data-datespec" attrsSet ->
                    Just $
                      t2
                        #attrsSet
                        attrsSet
                        #tags
                        (headerTag :| NonEmpty.tail (ts'' <&> (.dat)))
                | otherwise -> Nothing
          )
        <&> ( \sect ->
                t2
                  #attrsSet
                  sect.attrsSet
                  #spanText
                  ( sect.tags
                      & NonEmpty.tail
                      & List.takeWhile (not . Soup.isTagCloseName "span")
                      & Soup.innerText
                  )
            )

    -- \| Zip the given accumulation over the list along with the original list items
    zipWithFold :: (Monoid m) => (a -> m) -> [a] -> [T2 "acc" m "dat" a]
    zipWithFold f as =
      zipWith
        (\m a -> t2 #acc m #dat a)
        (List.scanl' (\b a -> f a <> b) mempty as)
        as

-- | Parse a dateSpec, which accepts a (very) small subset of the OpenStreetMap `opening_hours` tag,
-- see https://wiki.openstreetmap.org/wiki/Key:opening_hours
parseDateSpec :: Atto.Parser DateSpec
parseDateSpec = dayTime
  where
    -- wd weekday, available: Mo · Tu · We · Th · Fr · Sa · Su Fr 08:30-20:00
    -- hh hour, always two digits number in 24 hour basis (no am/pm), in the format "hh:mm" · Fr 08:30-20:00
    -- mm minute, always two digits number in the format "hh:mm" Fr 08:30-20:00
    -- mo month, available: Jan · Feb · Mar · Apr · May · Jun · Jul · Aug · Sep · Oct · Nov · Dec · "mo md" Dec 25
    -- md monthday, always two digits number in the format · "mo md" Dec 25
    -- we week number, always a two digit number in range 01-53, in the format "week we" week 25 Mo 08:30-20:00
    n = flip (Atto.<?>)
    charLit c = Atto.word8 (charToWordUnsafe c) <|> fail [fmt|required char '{c}'|]
    oneOfErr :: [(a, Text)] -> Atto.Parser a
    oneOfErr ps =
      Atto.choice (ps <&> (\(a, t) -> a <$ (Atto.string $ textToBytesUtf8 t)))
        <|> fail [fmt|Must be one of {ps <&> snd & show}|]
    weekday = n "weekday" $ oneOfErr $ (\t -> (t, t)) <$> ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]
    optionalMonthOffset = n "optionalMonthOffset" $ do
      starts <- Atto.option False (charLit '[' $> True)
      if starts
        then
          Just <$> do
            isNeg <- Atto.option False (True <$ charLit '-')
            offset <-
              Atto.choice $
                ( [1 .. 6 :: Int] <&> \i -> do
                    Atto.string (buildBytes intDecimalB i)
                    pure i
                )
                  <|> fail "Must be between [-6] and [+6] (excluding 0)"
            charLit ']'
            pure $ if isNeg then -offset else offset
        else pure Nothing
    oneOfIntPadTwo ints = oneOfErr $ (\i -> (i, buildText (padPrefixT 2 '0' naturalDecimalT) i)) <$> ints
    hour = n "hour" $ oneOfIntPadTwo [0 .. 23]
    minute = n "minute" $ oneOfIntPadTwo [0 .. 59]

    hhMm = n "hh:mm" $ do
      h <- hour
      Atto.word8 (charToWordUnsafe ':')
      m <- minute
      pure $ HhMm {hour = h, minute = m}

    hhMmMinusHhMm = n "hh:mm-hh:mm" $ do
      start <- hhMm
      Atto.word8 (charToWordUnsafe '-')
      end <- hhMm
      pure (start, end)

    startTime =
      n "startTime" $
        (n "startTimeEoD" $ StartTimeEoD <$> (hhMm <* charLit '+'))
          <|> (StartTimeEndTime <$> hhMmMinusHhMm)
          <|> fail "Must be in the format hh:mm-hh:mm or hh:mm+ (from time until end of day)"

    dayTime :: Atto.Parser DateSpec
    dayTime = n "dayTime" $ do
      w <- weekday
      offset <- optionalMonthOffset
      charLit ' '
      hhmm <- startTime
      pure $ DateSpec {weekday = w, offset = offset, startTime = hhmm}

data DateSpec = DateSpec
  { -- | The weekday this events happens, @Mo@, @Tu@, @We@, @Th@, @Fr@, @Sa@, @Su@
    weekday :: Text,
    -- | If this is not set, the event happens every week; if set, it happens once per month in the given week (1 = first week, -1 = last week, 3 = third week, etc.)
    offset :: Maybe Int,
    -- | The start time of the event in the given day
    startTime :: StartTime
  }
  deriving stock (Show, Eq)

-- | The start time of the event in the given day
data StartTime
  = -- | has a start and end hour, formatted as @hh:mm-hh:mm@
    StartTimeEndTime (HhMm, HhMm)
  | -- | has a start hour and ends at the end of the day, formatted as @hh:mm@
    StartTimeEoD HhMm
  deriving stock (Show, Eq)

-- | Some examples of datespecs that should parse.
testParseDateSpec :: IO ()
testParseDateSpec = do
  let specs =
        [ "Mo[1] 19:00-23:00",
          "Mo[-1] 19:00+",
          "Mo 15:00"
        ]
  for_ specs $ \dateSpec -> do
    let result = Field.runFieldParser (attoparsecBytes' [fmt|error parsing dateSpec from: {dateSpec & bytesToTextUtf8Lenient}|] parseDateSpec) dateSpec
    print result

-- | Turn Attoparsec parser into FieldParser, and keep the attoparsec error message.
attoparsecBytes' :: Text -> Atto.Parser a -> FieldParser' Error ByteString a
attoparsecBytes' err parser =
  let parseAll = Atto.parseOnly (parser <* Atto.endOfInput)
   in FieldParser $ \bytes -> case parseAll bytes of
        Left attoErr -> Left $ attoErr & stringToText & newError & errorContext err
        Right a -> Right a

-- | Ical data for one of our recurring events
data OpenlabWikiCalendarIcal = OpenlabWikiCalendarIcal
  { since :: Time.Day,
    stableId :: Text,
    dateSpec :: DateSpec,
    excepts :: [Time.Day],
    additional :: [Time.Day],
    heading :: Text,
    body :: [Soup.Tag ByteString]
  }

-- | Generate an iCal file from the given list of events.
mkOpenlabWikiCalendarIcal ::
  [OpenlabWikiCalendarIcal] ->
  Text
mkOpenlabWikiCalendarIcal dat =
  [fmt|{openlabWikiCalendarIcalHeader :: Text}
{icalEvents :: Text}
END:VCALENDAR
|]
  where
    icalEvents =
      dat
        & concatMap icalEvent
        & Text.intercalate "\n"
    icalEvent (d :: OpenlabWikiCalendarIcal) = do
      let mkStarttime day = case d.dateSpec.startTime of
            StartTimeEndTime (start, _) -> mkIcalDateTime day start
            StartTimeEoD start -> mkIcalDateTime day start
      let mkEndtime day = case d.dateSpec.startTime of
            StartTimeEndTime (_, end) -> mkIcalDateTime day end
            StartTimeEoD _ -> mkIcalDateTime day (HhMm {hour = 23, minute = 59})
      let since = d.since & Time.showGregorian
      let rrule = case d.dateSpec.offset of
            -- every week per month
            Nothing -> Just [fmt|FREQ=WEEKLY;BYDAY={d.dateSpec.weekday & Text.toUpper}|]
            -- once per month on the offset week
            Just offset -> Just [fmt|FREQ=MONTHLY;BYDAY={d.dateSpec.weekday & Text.toUpper};BYSETPOS={offset & buildText intDecimalT}|]

      let summary = d.heading
      -- We create a unique recurring event for the combination of identifier & since date
      let uid = [fmt|{d.stableId :: Text}-since-{since}|]
      let descriptionText = d.body & Soup.innerText & bytesToTextUtf8Lenient
      let descriptionHtml =
            d.body
              & Soup.renderTags
              & bytesToTextUtf8Lenient
      let mkDtstamp day = mkIcalDateTime day hhMmZero

      mkIcalEvent
        <$> concat
          [ pure $
              IcalEvent
                { summary,
                  uid,
                  descriptionText,
                  descriptionHtml,
                  -- we use a DTSTAMP that corresponds to midnight of `since`, so clients should update if that changes? Although our UID also includes `since`, so unsure.
                  dtstamp = mkDtstamp d.since,
                  starttime = mkStarttime d.since,
                  recurrenceId = Nothing,
                  endtime = mkEndtime d.since,
                  rrule,
                  -- here we remove events in the chain that should not happen (has to be the exact start date & time of each event, so we use mkStarttime)
                  excepts = d.excepts <&> \e -> mkStarttime e
                },
            -- for each additional event we want to add to the chain, add a single event that references the original
            d.additional
              <&> \day ->
                IcalEvent
                  { summary,
                    -- same uid as the event chain
                    uid,
                    descriptionText,
                    descriptionHtml,
                    dtstamp = mkDtstamp day,
                    starttime = mkStarttime day,
                    -- \| We set the recurrence to the starttime of the original event
                    recurrenceId = Just (mkStarttime d.since),
                    endtime = mkEndtime day,
                    rrule = Nothing,
                    excepts = []
                  }
          ]

-- | An hour/minute timestamp
data HhMm = HhMm
  { hour :: Natural,
    minute :: Natural
  }
  deriving stock (Show, Eq)

hhMmZero :: HhMm
hhMmZero = HhMm {hour = 0, minute = 0}

-- | Create an iCal date time in the format @yyyymmddThhmmss@
mkIcalDateTime :: Time.Day -> HhMm -> Text
mkIcalDateTime day hhmm =
  day & Time.toGregorian & \(y, m, d) ->
    [fmt|{y}{pad2 m}{pad2 d}T{hhmm & hhMmToIcalTime}|]
  where
    pad2 = buildText (padPrefixT 2 '0' intDecimalT)

-- | Convert a HhMm to the iCal time format @hhmmss@
hhMmToIcalTime :: HhMm -> Text
hhMmToIcalTime (HhMm h m) = do
  let pad2 = buildText (padPrefixT 2 '0' naturalDecimalT)
  [fmt|{h & pad2}{m & pad2}00|]

-- | escapes an ical TEXT value, also strips leading/trailing whitespace
escapeIcalText :: Text -> Text
escapeIcalText =
  Text.strip
    >>> Text.replace "\\" "\\\\"
    >>> Text.replace ";" "\\;"
    >>> Text.replace "," "\\,"
    >>> Text.replace "\n" "\\n"

-- | A standard VCALENDAR header for our calendar file, including the timezone definition.
openlabWikiCalendarIcalHeader :: Text
openlabWikiCalendarIcalHeader =
  [fmt|BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//openlab.augsburg.de/recurring-events//de-DE
NAME:Openlab Augsburg Wiederkehrende Events
X-WR-CALNAME:Openlab Augsburg Wiederkehrende Events
CALSCALE:GREGORIAN
X-WR-TIMEZONE:Europe/Berlin
X-PUBLISHED-TTL:P1H
BEGIN:VTIMEZONE
TZID:Europe/Berlin
X-LIC-LOCATION:Europe/Berlin
BEGIN:STANDARD
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
TZNAME:CET
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
BEGIN:DAYLIGHT
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
TZNAME:CEST
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
END:VTIMEZONE|]

-- | Data to create a single iCal event
data IcalEvent = IcalEvent
  { summary :: Text,
    uid :: Text,
    descriptionText :: Text,
    descriptionHtml :: Text,
    dtstamp :: Text,
    starttime :: Text,
    -- | If this event is an override to a recurring event, this is the original start-time of the event in the series, see https://icalendar.org/iCalendar-RFC-5545/3-8-4-4-recurrence-id.html
    recurrenceId :: Maybe Text,
    endtime :: Text,
    -- | if the event should repeat, and how
    rrule :: Maybe Text,
    -- | Dates when the (recurring) event should not happen
    excepts :: [Text]
  }
  deriving stock (Show, Eq)

{-
BEGIN:VEVENT
UID:project-deadline-20240105@example.com
SUMMARY:Project Deadline
DTSTART;TZID=Europe/Berlin:20240105T235900
DTEND;TZID=Europe/Berlin:20240106T000000
DESCRIPTION:Final deadline for project submission
RRULE:FREQ=MONTHLY;BYMONTHDAY=5
END:VEVENT
-}
exampleIcalEvent :: Text
exampleIcalEvent =
  mkIcalEvent $
    IcalEvent
      { summary = "Project Deadline",
        uid = "project-deadline-20240105@example.com",
        descriptionText = "Final deadline for project submission",
        descriptionHtml = "<p>Final deadline for project submission",
        dtstamp = "20240105T000000",
        starttime = "20240105T235900",
        recurrenceId = Nothing,
        endtime = "20240106T000000",
        rrule = Just "FREQ=MONTHLY;BYMONTHDAY=5",
        excepts = []
      }

-- | Create an iCal event from the given data.
mkIcalEvent ::
  IcalEvent ->
  Text
mkIcalEvent dat =
  [fmt|BEGIN:VEVENT
UID:{dat.uid :: Text}
SUMMARY:{escapeIcalText dat.summary :: Text}
DTSTAMP:{dat.dtstamp :: Text}
DTSTART;TZID=Europe/Berlin:{dat.starttime :: Text}
DTEND;TZID=Europe/Berlin:{dat.endtime :: Text}
DESCRIPTION:{escapeIcalText dat.descriptionText :: Text}
{optionalRules :: Text }
END:VEVENT|]
  where
    optionalRules =
      mintersperse ("\n" :: Text) $
        join $
          [ dat.rrule & ifExists (\rrule -> [fmt|RRULE:{rrule :: Text}|] :: Text),
            dat.excepts <&> \e -> [fmt|EXDATE;TZID=Europe/Berlin:{e :: Text}|],
            dat.recurrenceId & ifExists (\recId -> [fmt|RECURRENCE-ID;TZID=Europe/Berlin:{recId :: Text}|])
          ]

-- X-ALT-DESC:{escapeIcalText dat.descriptionHtml :: Text}

data Handler m = Handler
  { path :: Text,
    body :: Body m
  }

-- | A request Body is a parser for the request object and a function that receives a parsed request
-- and a cache with potentially previously cached results.
data Body m
  = forall a.
    Body
      (Parse Wai.Request a)
      ((a, TVar (Cache ByteString)) -> m Wai.Response)

-- | Turn a list of handlers into something that slots into a "Network.Wai" Application.
runHandlers ::
  (Otel.MonadTracer m, MonadUnliftIO m, MonadThrow m) =>
  ( (Wai.Request -> (Wai.Response -> m a) -> m a) ->
    m ()
  ) ->
  [Handler m] ->
  m ()
runHandlers runApplication handlers = do
  withCaches ::
    [ T2
        "handler"
        (Handler m)
        "cache"
        (TVar (Cache ByteString))
    ] <-
    handlers
      & traverse
        ( \h -> do
            cache <- liftIO $ newCache h.path "nothing yet"
            pure $ T2 (label @"handler" h) (label @"cache" cache)
        )
  runApplication $ \req respond -> do
    let mHandler =
          withCaches
            & List.find
              ( \h ->
                  (h.handler.path)
                    == (req & Wai.pathInfo & Text.intercalate "/")
              )
    case mHandler of
      Nothing -> respond $ Wai.responseLBS Http.status404 [] "nothing here (yet)"
      Just handler -> do
        inSpan' "TODO" $ \span -> do
          case handler.handler.body of
            Body parse runHandler -> do
              req' <- req & parseRequest span parse
              resp <- runHandler (req', handler.cache)
              respond resp
  where
    parseRequest :: (MonadThrow f) => Otel.Span -> Parse from a -> from -> f a
    parseRequest span parser req =
      Parse.runParse "Unable to parse the HTTP request" parser req
        & assertM span id

inSpan :: (MonadUnliftIO m, Otel.MonadTracer m) => Text -> m a -> m a
inSpan name = Otel.inSpan name Otel.defaultSpanArguments

inSpan' :: Text -> (Otel.Span -> m a) -> m a
-- inSpan' name = Otel.inSpan' name Otel.defaultSpanArguments
inSpan' _name act = act (error "todo telemetry disabled")

-- | Assert the given function returns Right, and throw the error if it fails.
assertM :: (MonadThrow f) => Otel.Span -> (t -> Either ErrorTree a) -> t -> f a
assertM span f v = case f v of
  Right a -> pure a
  Left err -> appThrowTree span err

-- | UTC time that is only specific to the second
newtype SecondTime = SecondTime {unSecondTime :: UTCTime}
  deriving newtype (Show, Eq, Ord)

mkSecondTime :: UTCTime -> SecondTime
mkSecondTime utcTime = SecondTime utcTime {utctDayTime = Time.secondsToDiffTime $ floor utcTime.utctDayTime}

diffSecondTime :: SecondTime -> SecondTime -> NominalDiffTime
diffSecondTime (SecondTime a) (SecondTime b) = diffUTCTime a b

-- | A cache entry that contains the name of the cache,
-- the time until it is valid, the last modified time, and the cached result.
data Cache a = Cache
  { name :: !Text,
    until :: !SecondTime,
    lastModified :: !SecondTime,
    result :: !a
  }
  deriving stock (Show)

-- | Create cache from a name and an initial result.
newCache :: Text -> a -> IO (TVar (Cache a))
newCache name result = do
  let until = mkSecondTime $ Time.UTCTime {utctDay = Time.ModifiedJulianDay 1, utctDayTime = 1}
  let lastModified = until
  newTVarIO $ Cache {..}

-- | Update the cache with a new result, unconditionally.
updateCache :: (NFData a, Eq a) => SecondTime -> TVar (Cache a) -> a -> STM (Cache a)
updateCache now cache result' = do
  -- make sure we don’t hold onto the world by deepseq-ing and evaluating to WHNF
  let !result = deepseq result' result'
  let until = mkSecondTime $ (5 * 60) `addUTCTime` now.unSecondTime
  !toWrite <- do
    old <- readTVar cache
    let name = old.name
    -- only update the lastModified time iff the content changed (this is helpful for HTTP caching with If-Modified-Since)
    if old.result == result
      then do
        let lastModified = old.lastModified
        pure $ Cache {..}
      else do
        let lastModified = now
        pure $ Cache {..}
  _ <- writeTVar cache $! toWrite
  pure toWrite

-- | Run the given action iff the cache is stale, otherwise just return the item from the cache.
updateCacheIfNewer :: (MonadUnliftIO m, NFData b, Eq b) => SecondTime -> TVar (Cache b) -> m b -> m (Cache b)
updateCacheIfNewer now cache act = withRunInIO $ \runInIO -> do
  old <- readTVarIO cache
  if old.until < now
    then do
      res <- runInIO act
      atomically $ updateCache now cache res
    else pure old

-- | Setup the otel tracer
withTracer :: (Otel.Tracer -> IO c) -> IO c
withTracer f = do
  setDefaultEnv "OTEL_SERVICE_NAME" "whatcd-resolver"
  bracket
    -- Install the SDK, pulling configuration from the environment
    Otel.initializeGlobalTracerProvider
    -- Ensure that any spans that haven't been exported yet are flushed
    Otel.shutdownTracerProvider
    -- Get a tracer so you can create spans
    (\tracerProvider -> f $ Otel.makeTracer tracerProvider "whatcd-resolver" Otel.tracerOptions)
  where
    setDefaultEnv :: String -> String -> IO ()
    setDefaultEnv envName defaultValue = do
      Env.lookupEnv envName >>= \case
        Just _env -> pure ()
        Nothing -> Env.setEnv envName defaultValue

-- | App environment
data Context = Context
  { tracer :: Otel.Tracer
  }

-- | A wrapper around our context environment
newtype AppT m a = AppT {unAppT :: ReaderT Context m a}
  deriving newtype (Functor, Applicative, Monad, MonadIO, MonadUnliftIO, MonadThrow)

-- | Application exception, thrown by the @appThrow*@ functions
data AppException = AppException Text
  deriving stock (Show)
  deriving anyclass (Exception)

-- | A specialized variant of @addEvent@ that records attributes conforming to
-- the OpenTelemetry specification's
-- <https://github.com/open-telemetry/opentelemetry-specification/blob/49c2f56f3c0468ceb2b69518bcadadd96e0a5a8b/specification/trace/semantic_conventions/exceptions.md semantic conventions>
--
-- @since 0.0.1.0
recordException ::
  ( MonadIO m,
    HasField "message" r Text,
    HasField "type_" r Text
  ) =>
  Otel.Span ->
  r ->
  m ()
recordException span dat = liftIO $ do
  callStack <- GHC.Stack.whoCreated dat.message
  newEventTimestamp <- Just <$> Otel.getTimestamp
  Otel.addEvent span $
    Otel.NewEvent
      { newEventName = "exception",
        newEventAttributes =
          HashMap.fromList
            [ ("exception.type", Otel.toAttribute @Text dat.type_),
              ("exception.message", Otel.toAttribute @Text dat.message),
              ("exception.stacktrace", Otel.toAttribute @Text $ Text.unlines $ map stringToText callStack)
            ],
        ..
      }

-- | Throw the given error tree as app exception, and record it in the span
appThrowTree :: (MonadThrow m) => Otel.Span -> ErrorTree -> m a
appThrowTree _span exc = do
  let msg = prettyErrorTree exc
  -- recordException
  --   span
  --   ( T2
  --       (label @"type_" "AppException")
  --       (label @"message" msg)
  --   )
  throwM $ AppException msg

-- | If Left, throw the given error tree as app exception, and record it in the span
orAppThrowTree :: (MonadThrow m) => Otel.Span -> Either ErrorTree a -> m a
orAppThrowTree span = \case
  Left err -> appThrowTree span err
  Right a -> pure a

instance (MonadIO m) => MonadLogger (AppT m) where
  monadLoggerLog loc src lvl msg = liftIO $ Logger.defaultOutput IO.stderr loc src lvl (Logger.toLogStr msg)

instance (Monad m) => Otel.MonadTracer (AppT m) where
  getTracer = AppT $ asks (.tracer)