packages feed

eventlog-live 0.4.0.0 → 0.11.0.0

raw patch · 99 files changed

Files

CHANGELOG.md view
@@ -1,3 +1,133 @@+### 0.11.0.0++- Add support for local viewer with `--viewer`.+- Add support for `--viewer-open` with `open-browser`.+- Rename `--control-X` CLI options to `--server-X`, as the server is shared by viewer and control.+- Rename `eventlog-live-otlp` to `eventlog-live`.+- Changed "cap", "capability", and "evCap" attributes to "capNo" for consistency.++### 0.10.0.0++- Add support for `ghc-stack-profiler-0.5.0.0` and drop support for previous versions.++### 0.9.1.0++- Add support for cumulative `Productivity` metric computed by Eventlog Live,+  rather than from `CapabilityUsage` in Grafana.++- Fix bug where `HeapAllocated` metric was erroneously treated as a delta+  metric and aggregated by summation. From this version onwards, it is treated+  as a cumulative metric and aggregated by taking the most recent measurement.++- Add workaround where `CapabilityUsage` metric is exported as a cumulative+  metric, as deltas are not supported by most collectors (Alloy, Prometheus).++### 0.9.0.0++- Add support for the following OTLP exporter configuration options:+  - `OTEL_EXPORTER_OTLP_TIMEOUT` (full support with both `grpc` and `http/protobuf`)+  - `OTEL_EXPORTER_OTLP_COMPRESSION` (full support with both `grpc` and `http/protobuf`)+  - `OTEL_EXPORTER_OTLP_CLIENT_KEY` (not parsed, as mTLS is unsupported)+  - `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE` (not parsed, as mTLS is unsupported)++- Add support for `console` exporter (e.g., via `OTEL_METRICS_EXPORTER=console`).++- Add support for HTTP proxy environment variables (`http_proxy` and `https_proxy`)+  when using HTTP/Protobuf exporter.++- Fix bug where `OTEL_EXPORTER_OTLP_INSECURE` applied to `http/protobuf` exporters.++- Fix bug where `OTEL_EXPORTER_OTLP_ENDPOINT` accepted URLs without scheme for `http/protobuf` exporters.++- Fix bug where `writeLog` shows in the backtraces for error messages.++- Add documentation for OpenTelemetry environment variables to command-line `--help`.++### 0.8.0.0++The version 0.7.0.0 was skipped to avoid confusion with `eventlog-live-otelcol-0.7.0.0`.++- Merge the executable `eventlog-live-otelcol` into this package as `eventlog-live-otlp`.++- Add support for OpenTelemetry Environment Variable Configuration:++  The following SDK configuration options are supported:+  https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration+  - `OTEL_RESOURCE_ATTRIBUTES`+  - `OTEL_SERVICE_NAME`+  - `OTEL_LOG_LEVEL`+  - `OTEL_TRACES_EXPORTER`, `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`, and `OTEL_PROFILES_EXPORTER`++  The following OTLP exporter configuration options are supported:+  https://opentelemetry.io/docs/specs/otel/protocol/exporter/+  - `OTEL_EXPORTER_OTLP_ENDPOINT`+  - `OTEL_EXPORTER_OTLP_INSECURE`+  - `OTEL_EXPORTER_OTLP_CERTIFICATE` (only by `grpc` protocol)+  - `OTEL_EXPORTER_OTLP_CLIENT_KEY` (parsed but ignored)+  - `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE` (parsed but ignored)+  - `OTEL_EXPORTER_OTLP_HEADERS` (only by `http/protobuf` protocol)+  - `OTEL_EXPORTER_OTLP_TIMEOUT` (parsed but ignored, support to be added in next version)+  - `OTEL_EXPORTER_OTLP_PROTOCOL` (only `grpc` and `http/protobuf` protocols are supported)++  All special-specific variants of the above environment variables are supported, e.g., `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT`, and `OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT` are all parsed and used.++  The command-line arguments that controlled these options have been removed:++  ```+  --service-name                   -> OTEL_SERVICE_NAME+  --verbosity                      -> OTEL_LOG_LEVEL+  --otlp-protocol                  -> OTEL_EXPORTER_OTLP_PROTOCOL+  --otlp-endpoint                  -> OTEL_EXPORTER_OTLP_ENDPOINT+  --otlp-grpc-certificate-store    -> OTEL_EXPORTER_OTLP_CERTIFICATE+  --otlp-http-headers              -> OTEL_EXPORTER_OTLP_HEADERS+  ```++- The `--otlp-grpc-ssl-key-log` and `--otlp-grpc-ssl-key-log-from-env` options were removed.++  Support for setting a gRPC SSL keylog was removed. If you relied on this, please open an issue.++- Support was added for _signal-specific exporters_, e.g., if you supply different values for `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` and `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` then traces and metrics are exported to different endpoints.++  You can use signal-specific exporter selection to disable certain signals altogether, e.g., `OTEL_TRACES_EXPORTER=none` causes no traces to be exported.++### 0.6.0.0++- Add support for `ipedb` databases for IPE and cost-centre information.+- **BREAKING**: Refactor profiles processors.+- **BREAKING**: Use `InfoProv`, `CostCentre`, and `SrcLoc` types from `ipedb`.++### 0.5.0.0++- Overhaul documentation for `GHC.Eventlog.Live.Machine.Core`.+- **BREAKING**: Drop `counterBy` and `counterByTick`.+- **BREAKING**: Drop `batchListToTick` and `batchListToTicks`.+- **BREAKING**: Drop `batchToTick` and `batchToTicks`.+- **BREAKING**: Drop `aggregateByTick` and `aggregateByTicks`.+- **BREAKING**: Drop `liftBatch`.+- **BREAKING**: Rename `sortByBatchTick` to `sortByTick`.+- **BREAKING**: Change `batchByTick` and `batchByTicks` to preserve ticks.+- **BREAKING**: Generalise `sortByBatch`, `sortByTick`, and `validateOrder` to work on arbitrary keys.+- **BREAKING**: Rename `between` to `betweenFirst`.+- **BREAKING**: Generalise `betweenFirst` and `delimit` to work on arbitrary items.+- Add `betweenEach`.+- **BREAKING**: Change `liftRouter` to ignore inputs after the child process stops.+- Add `fanoutTick`.+- **BREAKING**: Add implicit `TickInfo` to each `Tick` via `HasTickInfo`.+- **BREAKING**: Change `onlyTick` to yield actual `Tick` values.+- **BREAKING**: Change interval argument for `runWithEventlogSource` and `sourceHandleBatch` to batch in milliseconds.+- **BREAKING**: Add `AttrBoot` to `AttrValue`.+- Add support for user messages and markers.+- **BREAKING**: Replace logging with `co-log-core` contravariant `LogAction`.+- Add support for concurrent `fanoutTickCC` and `mergeWithTickCC`.+- **BREAKING**: Rename `EventlogSource` to `EventlogSourceOptions`.+- **BREAKING**: Rename `GHC.Eventlog.Live.Socket` to `GHC.Eventlog.Live.Source`.+- Add `GHC.Eventlog.Live.Source.Core`.+- **BREAKING**: Move `EventlogSourceOptions` to `GHC.Eventlog.Live.Source.Core`.+- Add `EventlogSourceHandle`.+- **BREAKING**: Rename `runWithEventlogSource` to `runWithEventlogSourceOptions`.+- Add `withEventlogSourceHandle` and `runWithEventlogSourceHandle` to `GHC.Eventlog.Live.Source`.+- **BREAKING**: Rename `sourceHandleBatch` to `eventlogSourceTick`.+ ### 0.4.0.0  - Add parser for `--stats` flag (`statsParser`).
LICENSE view
@@ -1,4 +1,4 @@-Copyright (c) 2021-2025 Well-Typed+Copyright (c) 2021-2026 Well-Typed   Redistribution and use in source and binary forms, with or without
+ README.md view
@@ -0,0 +1,747 @@+![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/well-typed/eventlog-live/ci.yml?style=for-the-badge) ![Hackage Version](https://img.shields.io/hackage/v/eventlog-live?style=for-the-badge) ![License: BSD-3-Clause](https://img.shields.io/badge/license-BSD--3--Clause-blue?style=for-the-badge) ![Stability: Experimental](https://img.shields.io/badge/stability-experimental-yellow?style=for-the-badge)++# ![Eventlog Live](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/social-preview.svg?raw=true)++> ⚠️ **Warning:**+> This package is experimental.+> It is versioned according to the [PVP](https://pvp.haskell.org).+> Breaking changes should be expected and no effort will be made to avoid major version bumps until at least version 1.0.0.0.++Eventlog Live analyses the [eventlog](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/runtime_control.html#rts-eventlog) of any Haskell program and streams the resulting telemetry data to any observability platform that supports the OpenTelemetry protocol, such as [Grafana Cloud](https://grafana.com), [HoneyComb](https://www.honeycomb.io/), or [Prometheus](https://prometheus.io/docs/guides/opentelemetry/).+Eventlog Live also ships with a _local web viewer_, which lets you view your application's telemetry data locally, without the need for an observability platform. See [Eventlog Live – The Local Web Viewer](#eventlog-live--the-local-web-viewer) for details.++The following shows the Grafana Heap Profiles dashboard for [`oddball`](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/examples/oddball/oddball-with-pipe.sh) running with _zero instrumentation_.++![A screen recording of the Grafana Heap Profiles dashboard for the oddball example program.](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/oddball-with-pipe-2026-09-21.gif?raw=true)++Eventlog Live is designed to be _lightweight_, running alongside your application using only in a few megabytes of memory, and _highly configurable_, so that you only send the telemetry data you are interested in. While Eventlog Live works with zero instrumentation, it has support for several Haskell profiling packages that can enable new features.++- **Eventlog Socket – Sockets and Dynamic Control**++  The [`eventlog-socket`](https://github.com/well-typed/eventlog-socket) package adds two features. First, it lets you to stream the eventlog over Unix domain and TCP/IP sockets. Secondly, it lets you control your program from the observability dashboard. The `eventlog-socket` instrumentation has builtin support that lets you toggle RTS features such as heap and stack profiling at runtime, but its control protocol has an easy-to-use plugin mechanism that lets you integrate other actions into your telemetry platform.++  The following shows dynamic control of heap profiling from the Grafana Heap Profiles dashboard for [`oddball`](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/examples/oddball/oddball-with-hT.sh) instrumented with `eventlog-socket`. When the _Stop_ button is pressed, the heap profiling is stopped, and the heap profile flatlines. When the _Start_ button is pressed, heap profiling is restarted.++  ![A screen recording of the Grafana Heap Profiles dashboard for the oddball example program that shows dynamic control of heap profiling.](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/oddball-control-2026-09-21.gif?raw=true)++- **GHC Stack Profiler – Lightweight Call-Stack Profiles**++  The [`ghc-stack-profiler`](https://github.com/well-typed/ghc-stack-profiler) package lets you sample your application's call-stack using a lightweight sampler that can be turned on and off at runtime using `eventlog-socket`'s control protocol.++  The lightweight call-stack sampler has an approximate 5-10% overhead while running with a sampling interval of 10ms, whereas [GHC's builtin cost-centre profiling](https/downloads.haskell.org/ghc/latest/docs/users_guide/profiling.html#time-and-allocation-profiling) has an approximate 50% overhead for the instrumentation alone, i.e., prior to any cost-centres and without sampling.++  The following shows the Grafana Call-Stack Profiles dashboard for [`jumpy-jump`](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/examples/jumpy-jump/jumpy-jump-with-ghc-stack-profiler.sh) instrumented with `ghc-stack-profiler`.++  ![A screen recording of the Grafana Call-Stack Profiles dashboard for the jumpy-jump example program.](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/jumpy-jump-with-ghc-stack-profiler-2026-09-21.gif?raw=true)++## Table of Contents++- [Demos](#demos)+- [Getting Started](#getting-started)+  - [Eventlog Live – The Basic Version](#eventlog-live-the-basic-version)+  - [Eventlog Live with Eventlog Socket](#eventlog-live-with-eventlog-socket)+  - [Eventlog Live with Cost-Centre Stack Profiling](#eventlog-live-with-cost-centre-stack-profiling)+  - [Eventlog Live with Heap Profiling by Info Table](#eventlog-live-with-heap-profiling-by-info-table)+  - [Eventlog Live with GHC Stack Profiler](#eventlog-live-with-ghc-stack-profiler)+  - [Eventlog Live — The Local Web Viewer](#eventlog-live-the-local-web-viewer)+- [Fine-Tuning Eventlog Live](#fine-tuning-eventlog-live)+  - [Configuration Files](#configuration-files)+  - [Restricted Event Classes](#restricted-event-classes)+  - [Info Table and Cost-Centre Databases](#info-table-and-cost-centre-databases)++## Demos++The [`demo`](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/demo/) directory contains a [Docker Compose](https://docs.docker.com/compose/) configuration that runs Grafana and all required data sources and opens an OTLP gRPC receiver on port 4317. This configuration is used in [Getting Started](#getting-started) and by the various scripts under the [`examples`](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/examples/) directory.+You can import the dashboards under [`demo/config/grafana-dashboards`](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/demo/config/grafana-dashboards/) into your Grafana setup, but beware that you'll have to change the variables and visualisations to use your data sources and change the buttons to use your control server.+The dashboards under [`demo-grafana-cloud`](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/demo-grafana-cloud/grafana-dashboards/) were prepared to be shared with other Grafana instances.++The [`demo-grafana-cloud`](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/demo-grafana-cloud/) directory contains an example that runs `jumpy-jump` and Eventlog Live, and sends data directory to Grafana Cloud. This demo shows heap profiles, logs, and cost-centre stack profiles.++The [`demo-nix`](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/demo-nix/) directory contains a [Nix](https://nixos.org) configuration that builds a self-contained virtual machine that runs `oddball`, Eventlog Live, Grafana, and Prometheus. This demo shows heap profiles.++## Getting Started++Let's get Evenlog Live working with your application, which we'll conveniently call `your-application`.++We'll start by getting the basic version of Evenlog Live working and progressively add features.++### Eventlog Live – The Basic Version++For the barebones version, you need three things:++1.  You need Eventlog Live, specifically the `eventlog-live` executable.++    To build Eventlog Live from source, you'll need:+    - GHC version 9.4 up to 9.12 (inclusive).+    - Cabal version 3.12 or later.+    - A recent [Protocol Buffer Compiler](https://protobuf.dev/installation/).++    Run:++    ```sh+    cabal install eventlog-live:eventlog-live \+      --constraint='blockio +serialblockio'   \+      --constraint='grpc-spec -snappy'+    ```++    The `+serialblockio` flag makes `blockio` use serial I/O, as opposed to parallel I/O. If you are on Linux and have [`liburing`](https://github.com/axboe/liburing) installed, you can omit this flag and get slightly faster disk I/O.++    The `-snappy` flag makes `grpc-spec` support snappy compression. If you have [snappy](https://github.com/google/snappy) installed, you can omit this flag and get slightly faster gRPC compression.++2.  You must have _somewhere_ to send the telemetry data.++    Any observability platform that supports OpenTelemetry works. The [demo-grafana-cloud](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/demo-grafana-cloud/) has a guide for setting up [Grafana Cloud](https://grafana.com).+    For the purposes of this guide, you can run the following [Docker Compose](https://docs.docker.com/compose/) from the root of the repository.++    ```sh+    docker compose -f demo/docker-compose-external.yml up --build --detach+    ```++    Eventlog Live supports [OpenTelemetry environment variables](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables). For this guide, we'll assume you used the docker command, which starts an OLTP gRPC receiver on port 4317. If you're using some other endpoint, you'll have to adapt these configuration options.++3.  Your application must be compiled with support for RTS options, the threaded runtime, and the eventlog.++    Add the following to the `executable` section of `your-application.cabal`:++    ```diff+      executable my-app+        ...++    +   ghc-options: -rtsopts+    +   ghc-options: -threaded+    +   if impl(ghc < 9.4)+    +     ghc-options: -eventlog+    ```++    The [`-rtsopts`](https://downloads.haskell.org/ghc/latest/docs/users_guide/phases.html#ghc-flag-rtsopts-none-some-all-ignore-ignoreAll) flag enables the RTS options for your application. This allows us to enable the eventlog at runtime and enable various kinds of profiling. Setting this option may pose a security risk. If this is a concern, you can set all the required RTS options at compile time using [`-with-rtsopts`](https://downloads.haskell.org/ghc/latest/docs/users_guide/phases.html#ghc-flag-with-rtsopts-opts). (See [the next section](#configuring-your-application-for-monitoring) for the necessary RTS options).++    The [`-eventlog`](https://downloads.haskell.org/ghc/latest/docs/users_guide/phases.html#ghc-flag-with-rtsopts-opts) flag builds eventlog support into your application. This is enabled unconditionally since GHC 9.4, but if you're using GHC 9.2 or earlier, you must explicitly pass this flag.++    The [`-threaded`](https://downloads.haskell.org/ghc/latest/docs/users_guide/phases.html#ghc-flag-threaded) flag builds your application with the threaded RTS. This is required because one crucial RTS option, `--eventlog-flush-interval`, is only safe to use with the threaded RTS.++To start monitoring your application, pipe its eventlog to Eventlog Live:++```sh+# OpenTelemetry Configuration+export OTEL_LOG_LEVEL="debug"+export OTEL_SERVICE_NAME="your-application"+export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=$(uuidgen)"+export OTEL_EXPORTER_OTLP_PROTOCOL="grpc"++# Create a pipe for the eventlog+EVENTLOG_PIPE="/tmp/eventlog.pipe"+mkfifo "${EVENTLOG_PIPE}"++# Start your application+your-application                     \+  +RTS                               \+  -l                                 \+  -ol"${EVENTLOG_PIPE}"              \+  -hT                                \+  --eventlog-flush-interval=1        \+  -RTS                               &++# Start eventlog-live+eventlog-live                        \+  --eventlog-file="${EVENTLOG_PIPE}" \+  -hT                                \+  --eventlog-flush-interval=1++# See: examples/oddball/oddball-with-pipe.sh+```++If you run these commands, you should start seeing telemetry show up on your dashboard.++- Navigate to Grafana at <localhost:3000>.+- Log in with username `admin` and password `admin`.+- Select '☰ > Dashboards > Heap Profiles'++  You should be greeted by a dashboard that looks something like this:++  ![A screen recording of the Grafana Heap Profiles dashboard for the oddball example program.](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/oddball-with-pipe-2026-09-21.gif?raw=true)++- Select '☰ > Dashboards > Logs'++  You should be greeted by a dashboard that looks something like this:++  ![A screen capture of the Grafana Logs dashboard for the oddball example program.](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/oddball-with-pipe-logs-2026-09-21.gif?raw=true)++  This dashboard will include a separate tab that shows the logs for `eventlog-live`:++  ![A screen capture of the Grafana Logs dashboard for the eventlog-live program for oddball.](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/eventlog-live-otlp-for-oddball-with-pipe-logs-2026-07-31.png?raw=true)++Let's briefly discuss what this script does:++- **The OpenTelemetry Configuration.**++  The Eventlog Live exporter is configured using the [OpenTelemetry environment variables](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables).+  - `OTEL_LOG_LEVEL` sets Eventlog Live's log level.+  - `OTEL_SERVICE_NAME` sets the service name under which your application's telemetry shows up on your dashboard.+  - `OTEL_RESOURCE_ATTRIBUTES` sets other resource attributes. In this case, it's used to set `service.instance.id` to a unique UUID that identifies the specific instance of your application.+  - `OTEL_EXPORTER_OTLP_PROTOCOL` selects the exporter's protocol. The default is `http/protobuf`, but the docker setup uses gRPC. If the protocol is gRPC, the default endpoint is `http://localhost:4317`, which is what our docker setup uses.++- **The Eventlog.**++  In this example, the eventlog is sent from your application's RTS to Eventlog Live via a named pipe.+  The [`mkfifo`](https://www.man7.org/linux/man-pages/man1/mkfifo.1.html) command creates a named pipe.+  The [`-l`](https://downloads.haskell.org/ghc/latest/docs/users_guide/runtime_control.html#rts-flag-l-flags) flag passed to your application's RTS tells it to write the eventlog in binary form and the [`-ol`](https://downloads.haskell.org/ghc/latest/docs/users_guide/runtime_control.html#rts-flag-olfilename) flag tells it to write it to the named pipe.+  The `--eventlog-file` flag passed to Eventlog Live tells it to read the eventlog from the named pipe.++- **Eventlog flushing**.++  The [`--eventlog-flush-interval=1`](https://downloads.haskell.org/ghc/latest/docs/users_guide/runtime_control.html#rts-flag-eventlog-flush-interval-seconds) flag passed to your application's RTS tells it to flush the eventlog every second.++  The `--eventlog-flush-interval=1` flag passed to Eventlog Live tells it your application's flush interval.++  The eventlog must be sorted for various analyses. In the RTS, events accumulate in per-capability buffers, which are usually only flushed when they fill up. This makes it impossible to sort the incoming eventlog, as events could be arbitrarily delayed.++  Flushing the eventlog may have a significant performance impact, as each flush requires all threads in your application to synchronise. To mitigate this, you may want to increase the flush interval in production.+  As a rule of thumb:+  - If you pass `--eventlog-flush-interval=N` to your application, it synchronises all threads every `N` seconds.++  - If you pass `--eventlog-flush-interval=N` to Eventlog Live, your telemetry data is delayed by at least `2N` seconds, more if you configure longer aggregation or export intervals.++  Usually, you want to pass the same value to both your application and Eventlog Live. However, there is no harm in passing Eventlog Live a higher value and, if you are seeing many out-of-order event warnings, doing so may solve that.++  > ⚠️ **Warning:**+  > Passing `--eventlog-flush-interval=N` to an executable that was built without `-threaded` throws an error in GHC 9.14 and later, and causes eventlog corruption in GHC version 9.12 an earlier.+  > See GHC issue [#26222](https://gitlab.haskell.org/ghc/ghc/-/issues/26222) for details.++- **Heap profiles.**++  The [`-h`](https://downloads.haskell.org/ghc/latest/docs/users_guide/profiling.html#rts-options-for-heap-profiling) flag passed to your application's RTS tells it to enable Heap Profiling, which provides a detailed breakdown of memory usage.+  The `T` argument selects the "closure type" breakdown, which is the most well-supported breakdown and should work for every application without any further configuration. This will tell you which symbol is responsible for each heap segment, e.g., `ghc-prim:GHC.Tuple.(,)`.+  (Heap Profiling by Info Table is discussed under [Eventlog Live with Heap Profiling by Info Table](#eventlog-live-with-heap-profiling-by-info-table).)++  The `-hT` flag passed to Eventlog Live tells it your application's heap profile breakdown.+  This is only needed if your application was built wih GHC 9.12 or older, as those versions did not send the heap profile breakdown over the eventlog, but there's no harm in passing it even if your application was built with a more recent version of GHC.++  > ⚠️ **Warning:**+  > Heap profiling has a significant performance impact, as each sample requires a major garbage collection. The default sampling interval is 0.1, but this can be adjusted with the [`-i`](https://downloads.haskell.org/ghc/latest/docs/users_guide/profiling.html#rts-flag-i-secs) flag.+  >+  > Heap profiling can be enabled/disabled at runtime from within your application using the functions in [`GHC.Profiling`](https://hackage.haskell.org/package/base/docs/GHC-Profiling.html). If you plan to use these functions, you can pass [`--no-automatic-heap-samples`](https://downloads.haskell.org/ghc/latest/docs/users_guide/profiling.html#rts-flag-no-automatic-heap-samples) to disable heap samples until you first call [`startHeapProfTimer`](https://hackage.haskell.org/package/base-4.21.0.0/docs/GHC-Profiling.html#v:startHeapProfTimer).+  >+  > Alternatively, heap profiling can be enabled/disabled by Eventlog Live, e.g., using the Start/Stop buttons on the Heap Profiles dashboard. This requires that your application was instrumented with `eventlog-socket` using the `+control` flag. This is discussed under [Eventlog Live with Eventlog Socket](#eventlog-live-with-eventlog-socket).++### Eventlog Live with Eventlog Socket++Eventlog Socket gives us two things:++- If instrumented with Eventlog Socket, your application can write the eventlog to a Unix domain socket or a TCP/IP socket.++- If `eventlog-socket` is compiled with the `+control` feature flag, your application can read control messages from the eventlog socket. The builtin control messages can be used, e.g., to enable/disable heap or stack profiling at runtime. However, Eventlog Socket's control protocol is extensible. You can register new command messages from within your application using any Haskell function as their callbacks.++  > ⚠️ **Warning:**+  > For security reasons, the Eventlog Socket control protocol is hidden behind a feature flag. If you do not enable the `+control` feature flag at compile time, none of the code that handles the the control protocol will be present in the library.++To instrument your application with Eventlog Socket, you need to make four small changes:++1.  Add `eventlog-socket` to the `build-depends` for your application:++    ```diff+    executable your-application+      ...++      build-depends:+        ...+    +   , eventlog-socket  >=0.1.2 && <0.2+    ```++2.  Instrument your main function:++    ```diff+    module Main where+    ...++    + import qualified GHC.Eventlog.Socket++    main :: IO ()+    main = do+    + GHC.Eventlog.Socket.startFromEnv+      ...+    ```++    There are various ways to start Eventlog Socket. For more details, see [the Haddock documentation](https://hackage-content.haskell.org/package/eventlog-socket-0.1.3.0/docs/GHC-Eventlog-Socket.html).+    The [`startFromEnv`](https://hackage-content.haskell.org/package/eventlog-socket-0.1.3.0/docs/GHC-Eventlog-Socket.html#v:startFromEnv) function reads the Eventlog Socket configuration from environment variables:+    - If `GHC_EVENTLOG_UNIX_PATH` is set,+      it opens a Unix domain socket at the given path.+    - If `GHC_EVENTLOG_INET_HOST` and `GHC_EVENTLOG_INET_PORT` are set,+      it opens a TCP/IP socket at the given address.+    - If `GHC_EVENTLOG_WAIT` is set,+      it pauses the program until some other process connects to the socket.++3.  Build your application with support for the control protocol.++    You must ensure that its `eventlog-socket` dependency is built with the `+control` feature flag.+    - During development, the easiest way to do this is to add the following to your `cabal.project` file:++      ```+      package eventlog-socket+        flags:+          +control+      ```++    - During installation, the easiest way to do this is to pass the `--constraint` flag:++      ```sh+      cabal install your-application \+        --constraint='eventlog-socket +control'+      ```++4.  Build Eventlog Live with support for the control server.++    You must ensure that `eventlog-live` is built with the `+control` feature flag.++    ```sh+    cabal install eventlog-live:eventlog-live \+      -f+control                                   \+      --constraint='blockio +serialblockio'        \+      --constraint='grpc-spec -snappy'+    ```++    When built with the `+control` feature flag, Eventlog Live supports starting the control server, an HTTP server that offers a REST interface to the control protocol, which you can call from, e.g., the buttons on your Grafana dashboard.++To start monitoring your application, pass the same socket to it and Eventlog Live:++```sh+# Eventlog Socket Configuration+export GHC_EVENTLOG_UNIX_PATH="/tmp/eventlog.sock"+export GHC_EVENTLOG_WAIT="true"++# OpenTelemetry Configuration+export OTEL_LOG_LEVEL="debug"+export OTEL_SERVICE_NAME="your-application"+export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=$(uuidgen)"+export OTEL_EXPORTER_OTLP_PROTOCOL="grpc"++# Start your application+your-application                                \+  +RTS                                          \+  -l                                            \+  -hT                                           \+  --eventlog-flush-interval=1                   \+  -RTS                                          &++# Start eventlog-live+eventlog-live                                   \+  --eventlog-socket="${GHC_EVENTLOG_UNIX_PATH}" \+  -hT                                           \+  --eventlog-flush-interval=1                   \+  --control                                     \+  --server-port=30179                           \+  --server-cors-ignore-failure++# See: examples/oddball/oddball-with-hT.sh+```++If you run these commands, you should be greeted by a dashboard that looks something like this:++![A screen recording of the Grafana Heap Profiles dashboard for the oddball example program that shows dynamic control of heap profiling.](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/oddball-control-2026-09-21.gif?raw=true)++The Start and Stop buttons can now be used to enable/disable Heap Profiling and the Census button can now be used to request a single heap census.++Let's briefly discuss what the new parts of this script do:++- The `GHC_EVENTLOG_UNIX_PATH` and `GHC_EVENTLOG_WAIT` environment variables configure Eventlog Socket, see above.++- The `--control` and `--server-port=30179` flags passed to Eventlog Live tells it to start the control server on port 30179, which is the port used in the Grafana dashboards included in the demo.++- The `--server-cors-ignore-failure` flag passed to Eventlog Live tells it to ignore and accept malformed [CORS preflight requests](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing).+  This is a workaround for Safari's broken CORS preflight requests for localhost.+  You should not pass this flag in production.++### Eventlog Live with Cost-Centre Stack Profiling++Cost-Centre Stack Profiling is [GHC's builtin time profiler](https://downloads.haskell.org/ghc/latest/docs/users_guide/profiling.html#time-and-allocation-profiling). When enabled, cost-centre profiling maintains virtual cost-centre stacks that contain entries for all symbols marked as cost centres.++To use Cost-Centre Stack Profiling, you must make two changes:++1.  Build your application and its dependencies must be built with profiling.+    - During development, the easiest way to do this is to add the following to your `cabal.project` file:++      ```+      profiling: True+      ```++    - During installation, the easiest way to do this is to pass the `--enable-profiling` flag:++      ```sh+      cabal install your-application --enable-profiling+      ```++2.  Add cost centres to your application.++    If you are only interested in specific symbols, you can manually add cost centres using the `SCC` pragma, e.g.,++    ```diff+    + {-# SCC myGreeter #-}+      myGreeter :: String -> String+      myGreeter name = "Hello, " <> name+    ```++    If you would like to automatically add cost centres for all symbols, you can use the Cabal [`profiling-detail`](https://cabal.readthedocs.io/en/3.18/cabal-project-description-file.html#cfg-flag---profiling-detail) option.+    The easiest way to add cost centres for all packages is to add the following to your `cabal.project` file:++    ```+    package *+      profiling-detail: late+    ```++    There are several different strategies, e.g., `all-functions` and `late`.+    Our recommendation is to use `late`.+    See [Late Cost Centre Profiling](https://well-typed.com/blog/2023/03/prof-late/).++To start monitoring your application, run your application and Evenlog Live. The following script builds on the example from [Eventlog Live with Eventlog Socket](#eventlog-live-with-eventlog-socket), but using Cost-Centre Stack Profiling is independent from Eventlog Socket.++```sh+# Eventlog Socket Configuration+export GHC_EVENTLOG_UNIX_PATH="/tmp/eventlog.sock"+export GHC_EVENTLOG_WAIT="true"++# OpenTelemetry Configuration+export OTEL_LOG_LEVEL="debug"+export OTEL_SERVICE_NAME="your-application"+export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=$(uuidgen)"+export OTEL_EXPORTER_OTLP_PROTOCOL="grpc"++# Start your application+your-application                                \+  +RTS                                          \+  -l                                            \+  -p                                            \+  --eventlog-flush-interval=1                   \+  -RTS                                          &++# Start eventlog-live+eventlog-live                                   \+  --eventlog-socket="${GHC_EVENTLOG_UNIX_PATH}" \+  --eventlog-flush-interval=1                   \+  --control                                     \+  --server-port=30179                           \+  --server-cors-ignore-failure++# See: examples/jumpy-jump/jumpy-jump-with-cost-centre-profiler.sh+```++If you run these commands, you should start seeing profiles show up on your dashboard.++- Navigate to Grafana at <localhost:3000>.+- Log in with username `admin` and password `admin`.+- Select '☰ > Dashboards > Cost-Centre Stack Profiles'++  You should be greeted by a dashboard that looks something like this:++  ![A screen capture of the Grafana Cost-Centre Stack Profiles dashboard for the jumpy-jump example program.](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/jumpy-jump-with-cost-centre-profiler-2026-09-21.gif?raw=true)++If your application is instrumented with Eventlog Socket, the Start and Stop buttons should enable/disable cost-centre stack profiling.++Let's briefly discuss what the new parts of this script do:++- The [`-p`](https://downloads.haskell.org/ghc/latest/docs/users_guide/profiling.html#time-and-allocation-profiling) flag passed to your application's RTS tells it to enable Cost-Centre Stack Profiling.++> ℹ️ **Tip:**+> When compared to call-stack profiling, a cost-centre stack profile more closely models user expectation.+> For example, in a recursive loop without allocations, the recursive function is not pushed onto the call-stack, and won't show up in a call-stack profile. However, its cost centres _will_ be pushed to the virtual cost-centre stack.++> ⚠️ **Warning:**+> Cost-centre profiling has a huge runtime overhead. When compiled with profiling, the in-memory representation of all datatypes grows by one word and this alone results in a 50% runtime overhead even without any cost centres and even while running without `-p`, e.g., without maintaining the virtual cost-centre stacks. For production environments, we recommend running GHC Stack Profiler. See [Eventlog Live with GHC Stack Profiler](#eventlog-live-with-ghc-stack-profiler).++### Eventlog Live with Heap Profiling by Info Table++In [Eventlog Live – The Basic Version](#eventlog-live-the-basic-version), we told your application's RTS to enable heap profiling, using a breakdown by closure type (`-hT`). While this is incredibly useful, there's a good chance one of the largest categories will be something like `STACK` or `THUNK`.+We can use Heap Profiling by Info Table to get a much more detailed breakdown.++To use Heap Profiling by Info Table, your application and all its dependencies must be built with the GHC options [`-finfo-table-map`](https://downloads.haskell.org/ghc/latest/docs/users_guide/debug-info.html#ghc-flag-finfo-table-map) and [`-fdistinct-constructor-tables`](https://downloads.haskell.org/ghc/latest/docs/users_guide/debug-info.html#ghc-flag-fdistinct-constructor-tables) GHC options.++Let's do this in two steps:++1.  To build your application and its dependencies with info table maps, you must ensure that they are built with the `-finfo-table-map` and `-fdistinct-constructor-tables` GHC options.++    The easiest way to do this is to add the following to your `cabal.project` file:++    ```+    package *+      ghc-options:+        -finfo-table-map+        -fdistinct-constructor-tables+    ```++    There is currently no easy way to pass GHC options to all packages when using `cabal install`.+    As a workaround, you can add a `cabal.project` file to a source distribution and install from there.++If you run Heap Profiling by Info Table with your application built this way, you will get detailed information for all the symbols defined in your application and most symbols defined in your dependencies.+However, you will see some unresolved info tables, which will show as numbers, e.g., `0x100000000`.+These are symbols that are either built into GHC or defined in the [_boot libraries_](https://gitlab.haskell.org/ghc/ghc/-/wikis/working-conventions/boot-libraries) that came with GHC, such as `base`.+The boot packages are _never_ rebuilt by Cabal and are unaffected by the `package *` stanza.++2.  To build the GHC and the boot libaries with info table maps, you must build GHC with the `+ipe` flavour.++    The easiest way to do this is using `ghcup`. Some variant of the following command may work for you:++    ```sh+    ghcup compile ghc -j0 -b 9.10.3 -v 9.10.3 -f perf+ipe -o '%v-ipe' --+    ```++    You may need to pass the appropriate configure flags for your platform.+    See [Building and Porting GHC](https://gitlab.haskell.org/ghc/ghc/-/wikis/building#building-and-porting-ghc).++Once you have a version of GHC built with the `+ipe` flavour, you can rebuild your application, and start using Heap Profiling by Info Table. The following script builds on the example from [Eventlog Live with Eventlog Socket](#eventlog-live-with-eventlog-socket), but Heap Profiling by Info Table is independent from Eventlog Socket.++```sh+# Eventlog Socket Configuration+export GHC_EVENTLOG_UNIX_PATH="/tmp/eventlog.sock"+export GHC_EVENTLOG_WAIT="true"++# OpenTelemetry Configuration+export OTEL_LOG_LEVEL="debug"+export OTEL_SERVICE_NAME="your-application"+export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=$(uuidgen)"+export OTEL_EXPORTER_OTLP_PROTOCOL="grpc"++# Start your application+your-application                                \+  +RTS                                          \+  -l                                            \+  -hi                                           \+  --eventlog-flush-interval=1                   \+  -RTS                                          &++# Start eventlog-live+eventlog-live                                   \+  --eventlog-socket="${GHC_EVENTLOG_UNIX_PATH}" \+  -hi                                           \+  --eventlog-flush-interval=1                   \+  --control                                     \+  --server-port=30179                           \+  --server-cors-ignore-failure++# See: examples/oddball/oddball-with-hi.sh+```++If you run these commands, you should be greeted by a dashboard that looks something like this:++![A screen recording of the Grafana Heap Profiles dashboard for the oddball example program using Heap Profiling by Info Table.](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/oddball-with-hi-2026-09-21.gif?raw=true)++Notably, your Heap Profile should show Info Table information. If you ran Heap Profiles with different breakdowns, you can select the appropriate breakdown in the Heap Profile Breakdown dropdown menu.++Let's briefly discuss what the new parts of this script do:++- The [`-hi`](https://downloads.haskell.org/ghc/latest/docs/users_guide/profiling.html#rts-options-for-heap-profiling) flag passed to your application's RTS tells it to enable Heap Profiling by Info Table.++  As before, the `-hi` flag passed to Eventlog Live tells it your application's heap profile breakdown.++### Eventlog Live with GHC Stack Profiler++[GHC Stack Profiler](https://github.com/well-typed/ghc-stack-profiler) is a light-weight profiler that samples the runtime call-stack and writes these to the eventlog. The instrumentation alone has zero overhead and, when it's running, it has [about 2-8% overhead](https://github.com/well-typed/ghc-stack-profiler/#benchmarks). When compiled with the `+control` feature flag, it supports Eventlog Socket's command protocol, which lets you enable/disable samples at runtime.++To instrument your application with GHC Stack Profiler, you need to make three changes:++1.  Add `ghc-stack-profiler` to the `build-depends` for your application:++    ```diff+      executable your-application+        ...++        build-depends:+          ...+    +     , ghc-stack-profiler ==0.5.0.0+    ```++    > ⚠️ **Warning:** If you're using `ghc-stack-profiler-speedscope`, `eventlog-live`, or any other program that processes the eventlog produced by `ghc-stack-profiler`, it is important that both are built with the same version of `ghc-stack-profiler-core`.++2.  Instrument your main function:++    ```diff+      module Main where+      ...++    + import GHC.Stack.Profiler (withProfilerFromEnv)++      main :: IO ()+      main =+    +   withProfilerFromEnv $+          ...+    ```++    > ℹ️ **Tip:**+    > If you prefer not to configure your program from the environment, the [GHC.Stack.Profiler](https://hackage.haskell.org/package/ghc-stack-profiler/docs/GHC-Stack-Profiler.html) exposes a variety of function that instrument your program.++3.  Build your application and its dependencies with info table maps.++    For detailed instructions, see [Eventlog Live with Heap Profiling by Info Table](#eventlog-live-with-heap-profiling-by-info-table).++To start monitoring your application, run your application and Evenlog Live. The following script builds on the example from [Eventlog Live with Heap Profiling by Info Table](#eventlog-live-with-heap-profiling-by-info-table), but using GHC Stack Profiler is independent from Eventlog Socket and while it needs info table maps, it does not require _running_ an Info Table Profile (`-hi`).++```sh+# GHC Stack Profiler Configuration+export GHC_STACK_PROFILER="ON" # or any other non-empty value+export GHC_STACK_PROFILER_SAMPLE_INTERVAL="10" # milliseconds++# Eventlog Socket Configuration+export GHC_EVENTLOG_UNIX_PATH="/tmp/eventlog.sock"+export GHC_EVENTLOG_WAIT="true"++# OpenTelemetry Configuration+export OTEL_LOG_LEVEL="debug"+export OTEL_SERVICE_NAME="your-application"+export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=$(uuidgen)"+export OTEL_EXPORTER_OTLP_PROTOCOL="grpc"++# Start your application+your-application                                \+  +RTS                                          \+  -l                                            \+  -hi                                           \+  --eventlog-flush-interval=1                   \+  -RTS                                          &++# Start eventlog-live+eventlog-live                                   \+  --eventlog-socket="${GHC_EVENTLOG_UNIX_PATH}" \+  -hi                                           \+  --eventlog-flush-interval=1                   \+  --control                                     \+  --server-port=30179                           \+  --server-cors-ignore-failure++# See: examples/jumpy-jump/jumpy-jump-with-ghc-stack-profiler.sh+```++If you run these commands, you should start seeing profiles show up on your dashboard.++- Navigate to Grafana at <localhost:3000>.+- Log in with username `admin` and password `admin`.+- Select '☰ > Dashboards > Call-Stack Profiles'++  You should be greeted by a dashboard that looks something like this:++  ![A screen recording of the Grafana Call-Stack Profiles dashboard for the jumpy-jump example program.](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/jumpy-jump-with-ghc-stack-profiler-2026-09-21.gif?raw=true)++If your application is instrumented with Eventlog Socket, the Start and Stop buttons should enable/disable call-stack profiling.++> ℹ️ **Tip:**+> You can use the [`annotateStackIO`](https://hackage-content.haskell.org/package/ghc-stack-annotations/docs/GHC-Stack-Annotation.html#v:annotateStackIO) functions from [`ghc-stack-annotations`](https://hackage-content.haskell.org/package/ghc-stack-annotations) to push annotation frames onto the call-stack at runtime.+> These annotation frames are visible in call-stack profiles captured by GHC Stack Profiler.+> See [Better Haskell stack traces via user annotations](https://www.well-typed.com/blog/2025/09/better-haskell-stack-traces/).++> ⚠️ **Warning:**+> Due to a bug in GHC, copying the call-stack may cause a segfault at runtime in applications built with GHC 9.14.1 and older.+> If you use GHC Stack Profiler in production, you should build your application with GHC 9.14.2 or newer.++### Eventlog Live – The Local Web Viewer++Eventlog Live ships with a _local web viewer_, which lets you monitor and control your application without the need for an observability platform. It uses the same instrumentation as the OpenTelemetry exporter, so this section assumes you have followed the instructions in [Eventlog Live – The Basic Version](#eventlog-live-the-basic-version).++To start monitoring your application, pipe its eventlog to Eventlog Live, and pass `--viewer` to enable the local web viewer:++```sh+# OpenTelemetry Configuration+export OTEL_SERVICE_NAME="your-application"+export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=$(uuidgen)"++# Create a pipe for the eventlog+EVENTLOG_PIPE="/tmp/eventlog.pipe"+mkfifo "${EVENTLOG_PIPE}"++# Start your application+your-application                     \+  +RTS                               \+  -l                                 \+  -ol"${EVENTLOG_PIPE}"              \+  -hT                                \+  --eventlog-flush-interval=1        \+  -RTS                               &++# Start eventlog-live+eventlog-live                        \+  --eventlog-file="${EVENTLOG_PIPE}" \+  -hT                                \+  --eventlog-flush-interval=1        \+  --no-otel-exporter                 \+  --viewer                           \+  --server-port=30179++# See: examples/oddball/oddball-with-viewer.sh+```++If you run these commands, you should start seeing telemetry show up in your local web viewer.++- Navigate to the Local Web Viewer at <localhost:30179>.++  You should be greeted by a dashboard that looks something like this:++  ![A screen recording of the local web viewer for the oddball example program.](https://github.com/well-typed/eventlog-live/blob/eventlog-live-v0.11.0.0/assets/oddball-with-viewer-2026-11-16.gif?raw=true)++The local web viewer currently only supports a subset of the telemetry signals. Specifically, it supports the heap profile, heap size, and GC statistics metrics. Support for more telemetry signals is planned for future versions.++If your application is instrumented with Eventlog Socket, and both Eventlog Socket and Eventlog Live were built with the `+control` feature flag, the Start and Stop buttons can be used to enable/disable Heap Profiling and the Census button can be used to request a single heap census.++> ⚠️ **Warning:**+> The local web viewer is intended for local use only. Do not expose it to the public internet.++> ⚠️ **Warning:**+> The local web viewer is not designed to have a small and limited memory footprint.+> It keeps all received telemetry data until you close or refresh the browser tab.++## Fine-Tuning Eventlog Live++### Configuration Files++The telemetry data produced by Eventlog Live can be configured in great detail via configuration files.+These let you enable/disable each individual telemetry stream and control their aggregation and export intervals.+The [default configuration](eventlog-live/data/default.yaml) file contains comments that explain what each option means.+To get started, you can write the default configuration to a file using the following command:++```sh+eventlog-live --print-defaults > eventlog-live.yaml+```++To pass a configuration file to Eventlog Lie, use the `--config` flag:++```sh+eventlog-live --config=eventlog-live.yaml ...+```++For validation and editor support, Eventlog Live ships with a JSON Schema for the configuration file format.+To print the [JSON Schema](eventlog-live/data/config.schema.json), run the following command:++```sh+eventlog-live --print-config-json-schema+```++> ℹ️ **Tip:**+> If you use the RedHat YAML language server, you can instruct your editor to load this schema.+> See [Associating schemas](https://github.com/redhat-developer/yaml-language-server/blob/538c8abb924acf727a136351a42a0c34a8b35bae/README.md#associating-schemas).++> ℹ️ **Tip:**+> The configuration files are parsed using [`HsYAML`](https://hackage.haskell.org/package/HsYAML) which is a [YAML 1.2](https://yaml.org/spec/1.2/spec.html) compliant parser.++### Restricted Event Classes++If you're only interested in particular kinds of telemetry signals, you may be able to configure your application to only write out certain classes of events. This can help save memory usage and bandwidth on the eventlog pipe or socket.++For example, if you're not interested in productivity and the thread state and capability usage spans (which are disabled by default), you can disable the class of scheduler events. Replace the `-l` flag passed to your application's RTS with `-la-s` (which means "all minus scheduler").++```diff+  your-application \+    +RTS           \+-   -l             \++   -la-s          \+    ...+```++For a detailed overview of event classes, see [GHC's users guide](https://downloads.haskell.org/ghc/latest/docs/users_guide/runtime_control.html#rts-flag-l-flags).++### Info Table and Cost-Centre Databases++If your application is particularly large, you might want to strip its info table or cost centre maps.+You can use [IpeDB](https://github.com/well-typed/ipedb) to build an info table database or cost centre database for your executable.+These databases can be passed to Eventlog Live via the `--ipedb` and `--ccdb` flags.+Once you have built an info table database for your application, you can safely make the following changes:++- If you application was built with GHC 10 or later, you can also restrict the IPE event class using `I`, e.g., `-la-I`.+  For more details, see [Restricted Event Classes](#restricted-event-classes).+- If your application was built with GHC 9.14 or later, the info table maps are stored in named `.ipe` sections.+  These sections can be safely stripped from the executable.++There is currently no method for safely stripping cost-centre information.
+ app/eventlog-live.hs view
@@ -0,0 +1,8 @@+{-# LANGUAGE NoImplicitPrelude #-}+{-# OPTIONS_GHC -Wno-missing-signatures #-}++module Main where++import GHC.Eventlog.Live.App qualified (main)++main = GHC.Eventlog.Live.App.main
+ data/config.schema.json view
@@ -0,0 +1,182 @@+{+  "$schema": "https://json-schema.org/draft-07/schema",+  "title": "Config",+  "description": "Configuration for the eventlog-live program",+  "type": "object",+  "properties": {+    "processors": {+      "type": "object",+      "properties": {+        "defaults": { "#ref": "#/definitions/processor_defaults" },+        "logs": {+          "type": "object",+          "defaults": { "#ref": "#/definitions/log_defaults" },+          "thread_label": { "#ref": "#/definitions/log" },+          "user_marker": { "#ref": "#/definitions/log" },+          "user_message": { "#ref": "#/definitions/log" },+          "internal_log_message": { "#ref": "#/definitions/log" }+        },+        "metrics": {+          "type": "object",+          "properties": {+            "defaults": { "#ref": "#/definitions/metric_defaults" },+            "blocks_size": { "$ref": "#/definitions/metric" },+            "capability_usage": { "$ref": "#/definitions/metric" },+            "heap_allocated": { "$ref": "#/definitions/metric" },+            "heap_live": { "$ref": "#/definitions/metric" },+            "heap_prof_sample": { "$ref": "#/definitions/metric" },+            "heap_size": { "$ref": "#/definitions/metric" },+            "mem_current": { "$ref": "#/definitions/metric" },+            "mem_needed": { "$ref": "#/definitions/metric" },+            "mem_returned": { "$ref": "#/definitions/metric" },+            "gc_copied": { "$ref": "#/definitions/metric" },+            "gc_slop": { "$ref": "#/definitions/metric" },+            "gc_fragmentation": { "$ref": "#/definitions/metric" },+            "productivity": { "$ref": "#/definitions/metric" },+            "internal_event_count": { "$ref": "#/definitions/metric" },+            "internal_exported_logs": { "$ref": "#/definitions/metric" },+            "internal_rejected_logs": { "$ref": "#/definitions/metric" },+            "internal_exported_metrics": { "$ref": "#/definitions/metric" },+            "internal_rejected_metrics": { "$ref": "#/definitions/metric" },+            "internal_exported_samples": { "$ref": "#/definitions/metric" },+            "internal_rejected_samples": { "$ref": "#/definitions/metric" },+            "internal_exported_spans": { "$ref": "#/definitions/metric" },+            "internal_rejected_spans": { "$ref": "#/definitions/metric" }+          },+          "additionalProperties": false+        },+        "traces": {+          "type": "object",+          "properties": {+            "defaults": { "#ref": "#/definitions/trace_defaults" },+            "capability_usage": { "$ref": "#/definitions/trace" },+            "thread_state": { "$ref": "#/definitions/trace" }+          },+          "additionalProperties": false+        },+        "profiles": {+          "type": "object",+          "properties": {+            "defaults": { "#ref": "#/definitions/profile_defaults" },+            "call_stack_profile": { "$ref": "#/definitions/profile" },+            "cost_centre_stack_profile": { "$ref": "#/definitions/profile" }+          },+          "additionalProperties": false+        }+      }+    }+  },+  "definitions": {+    "duration": {},+    "duration_by_batches": {+      "type": "string",+      "pattern": "^([0-9]+)(x)$"+    },+    "duration_by_seconds": {+      "type": "string",+      "pattern": "^([0-9]+(\\.[0-9]+)?)(s)$"+    },+    "aggregation_strategy": {+      "oneOf": [+        { "type": "null" },+        { "$ref": "#/definitions/aggregation_strategy_bool" },+        { "$ref": "#/definitions/aggregation_strategy_duration" }+      ]+    },+    "aggregation_strategy_bool": {+      "type": "boolean"+    },+    "aggregation_strategy_duration": {+      "oneOf": [+        { "$ref": "#/definitions/duration_by_batches" },+        { "$ref": "#/definitions/duration_by_seconds" }+      ]+    },+    "export_strategy": {+      "oneOf": [+        { "type": "null" },+        { "$ref": "#/definitions/export_strategy_bool" },+        { "$ref": "#/definitions/export_strategy_duration" }+      ]+    },+    "export_strategy_bool": {+      "type": "boolean"+    },+    "export_strategy_duration": {+      "oneOf": [+        { "$ref": "#/definitions/duration_by_batches" },+        { "$ref": "#/definitions/duration_by_seconds" }+      ]+    },+    "processor_defaults": {+      "description": "An optional 'defaults' block for defining YAML anchors.",+      "properties": {+        "export": { "$ref": "#/definitions/export_strategy" },+        "aggregate": { "$ref": "#/definitions/aggregation_strategy" }+      },+      "additionalProperties": false+    },+    "log": {+      "properties": {+        "name": { "type": "string" },+        "description": { "type": "string" },+        "export": { "$ref": "#/definitions/export_strategy" }+      },+      "additionalProperties": false+    },+    "log_defaults": {+      "description": "An optional 'defaults' block for defining YAML anchors.",+      "properties": {+        "export": { "$ref": "#/definitions/export_strategy" }+      },+      "additionalProperties": false+    },+    "metric": {+      "properties": {+        "name": { "type": "string" },+        "description": { "type": "string" },+        "export": { "$ref": "#/definitions/export_strategy" },+        "aggregate": { "$ref": "#/definitions/aggregation_strategy" }+      },+      "additionalProperties": false+    },+    "metric_defaults": {+      "description": "An optional 'defaults' block for defining YAML anchors.",+      "properties": {+        "export": { "$ref": "#/definitions/export_strategy" },+        "aggregate": { "$ref": "#/definitions/aggregation_strategy" }+      },+      "additionalProperties": false+    },+    "trace": {+      "properties": {+        "name": { "type": "string" },+        "description": { "type": "string" },+        "export": { "$ref": "#/definitions/export_strategy" }+      },+      "additionalProperties": false+    },+    "trace_defaults": {+      "description": "An optional 'defaults' block for defining YAML anchors.",+      "properties": {+        "export": { "$ref": "#/definitions/export_strategy" }+      },+      "additionalProperties": false+    },+    "profile": {+      "properties": {+        "name": { "type": "string" },+        "description": { "type": "string" },+        "export": { "$ref": "#/definitions/export_strategy" }+      },+      "additionalProperties": false+    },+    "profile_defaults": {+      "description": "An optional 'defaults' block for defining YAML anchors.",+      "properties": {+        "export": { "$ref": "#/definitions/export_strategy" }+      },+      "additionalProperties": false+    }+  }+}
+ data/default.yaml view
@@ -0,0 +1,212 @@+# Configuration for the eventlog processors, organised by the type of telemetry+# data they produce. Every processor shares certain properties. Let's look at+# the default configuration for the `blocks_size` metrics processor:+#+#     blocks_size:+#       name: ghc_eventlog_BlocksSize+#       description: The current heap size, calculated by the allocated number of blocks.+#       aggregate: 1s+#       export: 60s+#+# - The `name` property is added to each piece of telemetry data,+#   and determines the name under which the data becomes available in your+#   data source, such as Prometheus.+#+#   The data produced by our example `blocks_size` processor will be available+#   in Prometheus as `ghc_eventlog_BlocksSize`.+#+# - The `description` property is added to each piece of telemetry data,+#   and may be used to describe it. In most cases, this can be safely set+#   to `null` to save bandwidth.+#+#   The data produced by our example `blocks_size` processor will be given the+#   above description.+#+# - The `export` property determines whether or not the telemetry data is+#   exported to the OpenTelemetry Collector and, if so, with what frequency.+#+#   There are three ways to configure the `export` property:+#+#   - A duration in seconds, given as "Ns". For instance, if `export` is "30s"+#     then the processor exports a batch of telemetry data every 30 seconds.+#+#   - A duration in batches, given as "Nx". The length of one batch interval+#     is determined by the `--eventlog-flush-interval=SECONDS` flag, as passed+#     to the RTS of the monitored process and to this program. For instance,+#     if `export` is "2x" and the eventlog flush interval is 30 seconds, then+#     the processor exports a batch of telemetery data every minute.+#+#   - A boolean flag, i.e., `true` or `false`. If `export` is `false`, then the+#     processor will not export data and, if its output is not needed by some+#     other processor, it will not run either. If `export` is `true`, then the+#     processor exports telemetry data as if configured with "1x" (see above).+#+#   The example `blocks_size` processor exports a batch of telemetry data every+#   60 seconds.+#+# - The `aggregate` property determines whether or not the telemetry data is+#   aggregated over time, and, if so, over what interval. Only metrics support+#   aggregation.+#+#   The aggregation interval uses the same format as the export interval (see+#   above). For instance, if `aggregate` is 5s, the processor aggregates data+#   over 5 second intervals.+#+#   Aggregation follows the OpenTelemetry specification. Sums are aggregated by+#   summation. Gauges are aggregated by taking the most recent data point.+#   The `heap_allocated` and `capability_usage` metrics are aggregated as sums.+#   All other metrics are aggregated as gauges.+#+#   The data produced by our example `blocks_size` processor aggregates data+#   over 1 second intervals and only keeps the last metric in each interval.+#+# If the key for any specific processor is present in the file, even if it sets+# none of the properties, the processor is _enabled_, and any missing keys will+# default to the values in this file. Otherwise, the processor is _disabled_.+processors:+  logs:+    thread_label:+      name: ghc_eventlog_ThreadLabel+      description: A thread label.+      export: 30s+    user_marker:+      name: ghc_eventlog_UserMarker+      description: A user marker.+      export: 30s+    user_message:+      name: ghc_eventlog_UserMessage+      description: A user log message.+      export: 30s+    internal_log_message:+      name: eventlog_live_InternalLogMessage+      description: An internal eventlog-live log message.+      export: 30s+  metrics:+    blocks_size:+      name: ghc_eventlog_BlocksSize+      description: The current heap size, calculated by the allocated number of blocks.+      aggregate: 1s+      export: 30s+    capability_usage:+      name: ghc_eventlog_CapabilityUsageDuration+      description: The duration of each capability usage span.+      aggregate: 1s+      export: 30s+    gc_copied:+      name: ghc_eventlog_GcCopied+      description: The number of bytes copied in one garbage collection pass.+      aggregate: 1s+      export: 30s+    gc_fragmentation:+      name: ghc_eventlog_GcFragmentation+      description: The number of bytes of fragmentation found in one garbage collection pass.+      aggregate: 1s+      export: 30s+    gc_slop:+      name: ghc_eventlog_GcSlop+      description: The number of slop bytes found in one garbage collection pass.+      aggregate: 1s+      export: 30s+    heap_allocated:+      name: ghc_eventlog_HeapAllocated+      description: The size of a newly allocated chunk of heap.+      aggregate: 1s+      export: 30s+    heap_live:+      name: ghc_eventlog_HeapLive+      description: The current heap size, calculated by the allocated number of megablocks.+      aggregate: 1s+      export: 30s+    heap_prof_sample:+      name: ghc_eventlog_HeapProfSample+      description: A heap profile sample.+      aggregate: 1s+      export: 30s+    heap_size:+      name: ghc_eventlog_HeapSize+      description: The current heap size, calculated by the allocated number of megablocks.+      aggregate: 1s+      export: 30s+    mem_current:+      name: ghc_eventlog_MemCurrent+      description: The number of megablocks currently allocated.+      aggregate: 1s+      export: 30s+    mem_needed:+      name: ghc_eventlog_MemNeeded+      description: The number of megablocks currently needed.+      aggregate: 1s+      export: 30s+    mem_returned:+      name: ghc_eventlog_MemReturned+      description: The number of megablocks currently being returned to the OS.+      aggregate: 1s+      export: 30s+    productivity:+      name: ghc_eventlog_Productivity+      description: The ratio between GC and mutator usage.+      aggregate: 1s+      export: 30s+    internal_event_count:+      name: eventlog_live_InternalEventCount+      description: The number of events received over the eventlog socket.+      aggregate: 1s+      export: 30s+    internal_exported_logs:+      name: eventlog_live_InternalExportedLogs+      description: The number of exported logs.+      aggregate: 1s+      export: 30s+    internal_rejected_logs:+      name: eventlog_live_InternalRejectedLogs+      description: The number of exported logs.+      aggregate: 1s+      export: 30s+    internal_exported_metrics:+      name: eventlog_live_InternalExportedMetrics+      description: The number of exported metrics.+      aggregate: 1s+      export: 30s+    internal_rejected_metrics:+      name: eventlog_live_InternalRejectedMetrics+      description: The number of exported metrics.+      aggregate: 1s+      export: 30s+    internal_exported_samples:+      name: eventlog_live_InternalExportedSamples+      description: The number of exported samples.+      aggregate: 1s+      export: 30s+    internal_rejected_samples:+      name: eventlog_live_InternalRejectedSamples+      description: The number of exported samples.+      aggregate: 1s+      export: 30s+    internal_exported_spans:+      name: eventlog_live_InternalExportedSpans+      description: The number of exported spans.+      aggregate: 1s+      export: 30s+    internal_rejected_spans:+      name: eventlog_live_InternalRejectedSpans+      description: The number of exported spans.+      aggregate: 1s+      export: 30s+  profiles:+    call_stack_profile:+      name: ghc_eventlog_CallStackProfile+      description: A GHC call-stack profile.+      export: 30s+    cost_centre_stack_profile:+      name: ghc_eventlog_CostCentreStackProfile+      description: A GHC cost-centre stack profile.+      export: 30s+  traces:+    capability_usage:+      name: ghc_eventlog_CapabilityUsage+      description: A trace of capability usage (either mutator thread or garbage collection).+      export: false # These spans easily overwhelm most OTLP receivers+    thread_state:+      name: ghc_eventlog_ThreadState+      description: A trace of thread state changes (either running or stopped).+      export: false # These spans easily overwhelm most OTLP receivers
+ data/help.footer.txt view
@@ -0,0 +1,33 @@+  OTEL_LOG_LEVEL                  Log level used by Eventlog Live's internal logger. Defaults to "info".+  OTEL_SERVICE_NAME               Sets the value of the service.name resource attribute.++                                  If service.name is also provided in OTEL_RESOURCE_ATTRIBUTES, then OTEL_SERVICE_NAME takes precedence.+  OTEL_RESOURCE_ATTRIBUTES        Key-value pairs to be used as resource attributes.++  https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration++OpenTelemetry Exporter selection:++  OTEL_LOGS_EXPORTER              Logs exporter to be used.+  OTEL_METRICS_EXPORTER           Metrics exporter to be used.+  OTEL_PROFILES_EXPORTER          Profiles exporter to be used.+  OTEL_TRACES_EXPORTER            Trace exporter to be used.++  Each option supports the values "console", "none" and "otlp" and defaults to "otlp".++  https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#exporter-selection++OpenTelemetry OTLP Exporter options:++  OTEL_EXPORTER_OTLP_PROTOCOL     The OTLP transport protocol. Defaults to "http/protobuf". Supported values are "http/protobuf" for protobuf-encoded data over HTTP connection and "grpc" for protobuf-encoded data using gRPC wire format over HTTP/2 connection.+  OTEL_EXPORTER_OTLP_ENDPOINT     Target to which the exporter is going to send telemetry data. A scheme of "https" indicates a secure connection and takes precendence over the insecure option. Defaults to "http://localhost:4318" if the OTLP transport protocol is "http/protobuf" and to "http://localhost:4317" if the OTLP transport protocol is "grpc".+  OTEL_EXPORTER_OTLP_INSECURE     Whether to enable client transport security for the exporter's gRPC connection. Defaults to "false".+  OTEL_EXPORTER_OTLP_CERTIFICATE  The trusted certificate to use when verifying a server's TLS credentials. Should only be used for a secure connection.+  OTEL_EXPORTER_OTLP_HEADERS      Key-value pairs to be used as headers associated with HTTP requests.+                                  N.B. This setting is only respected if the OTLP transport protocol is "http/protobuf".+  OTEL_EXPORTER_OTLP_COMPRESSION  The compression algorithm to be used by gRPC and HTTP requests. Supported values are "none" and "gzip". Defaults to "none".+  OTEL_EXPORTER_OTLP_TIMEOUT      The maximum time the OTLP exporter will wait for each batch export. Specified in milliseconds. A value of "0" means no timeout. Defaults to 10 seconds.++  Each option also supports signal-specific variants that only apply to the exporter for that specific signal. For instance, the signal-specific variants for OTEL_EXPORTER_OTLP_ENDPOINT are OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT, and OTEL_EXPORTER_OTLP_TRACES_ENDPOINT.++  https://opentelemetry.io/docs/specs/otel/protocol/exporter/
+ data/help.header.txt view
+ data/help.progDesc.txt view
@@ -0,0 +1,28 @@+Use eventlog-live to export eventlog telemetry to an OTLP endpoint.++The following sends your application's eventlog over a named pipe and exports the resulting telemetry to an OTLP gRPC endpoint at "localhost:4317".++  # Configure OpenTelemetry exporter+  export OTEL_SERVICE_NAME="your-application"+  export OTEL_RESOURCE_ATTRIBUTES="service.instance.id=$(uuidgen)"+  export OTEL_EXPORTER_OTLP_PROTOCOL="grpc"+  export OTEL_EXPORTER_OTLP_ENDPOINT="localhost:4317"++  # Create a pipe for the eventlog+  mkfifo "/tmp/your-application.eventlog"++  # Start your application+  your-application                                   \+    +RTS                                             \+      -l                                             \+      -ol"/tmp/your-application.eventlog"            \+      -hT                                            \+      --eventlog-flush-interval=1++  # Start eventlog-live+  eventlog-live                                 \+    --eventlog-file="/tmp/your-application.eventlog" \+    -hT                                              \+    --eventlog-flush-interval=1++For instructions and more in-depth examples, see the README.
+ data/viewer/apple-touch-icon.png view

binary file changed (absent → 13425 bytes)

+ data/viewer/favicon.ico view

binary file changed (absent → 432254 bytes)

+ data/viewer/icon-192.png view

binary file changed (absent → 11428 bytes)

+ data/viewer/icon-512.png view

binary file changed (absent → 32572 bytes)

+ data/viewer/icon-mask.png view

binary file changed (absent → 27816 bytes)

+ data/viewer/icon.svg view
@@ -0,0 +1,68 @@+<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<svg+	width="24"+	height="24"+	viewBox="0 0 24 24"+	version="1.1"+	id="eventlog-live-logo"+	xml:space="preserve"+	xmlns="http://www.w3.org/2000/svg">+    <style>+		circle.magnifying-glass {+			stroke: #333;+			stroke-width: 2;+			fill: none;+		}+		rect.magnifying-glass {+			fill: #333;+		}+        @media (prefers-color-scheme: dark) {+			circle.magnifying-glass {+				stroke: #a1af79;+			}+			rect.magnifying-glass {+				fill: #a1af79;+			}+        }+    </style>+	<defs>+		<path id="greater" d="M 0 0 L 4.25 0 L 8.5 9 L 4.25 18 L 0 18 L 4.25 9 Z" />+		<path id="lambda" d="M 0 0 L 4.25 0 L 8.5 9 L 12.75 18 L 9 18 L 6.375 12.5 L 4.25 18 L 0 18 L 4.25 9 Z" />+		<g id="equals">+			<rect x="0" y="0" width="10" height="3.75" />+			<rect x="0" y="4.75" width="10" height="3.75" />+		</g>+		<mask id="lambda_mask">+			<rect width="100%" height="100%" fill="white"/>+			<use style="fill:black" href="#lambda" x="-4.5" y="-4" />+		</mask>+		<use id="masked_equals" mask="url(#lambda_mask)" href="#equals"/>+		<mask id="lens_mask">+			<radialGradient id="grad" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">+				<stop offset="0%" stop-color="white" />+				<stop offset="100%" stop-color="black" />+			</radialGradient>+			<circle style="fill: url(#grad);" id="lens" cx="12.5" cy="8.5" r="12"/>+			<circle style="fill: white;" id="lens" cx="12.5" cy="8.5" r="8.5"/>+		</mask>+	</defs>+	<!-- Square Background (used for icon-X.png) -->+    <!-- <rect style="fill: #339989" x="0" y="0" width="24" height="24" rx="1" ry="1" /> -->+    <!-- Circle Background (used for favicon.ico and apple-icon.png) -->+    <!-- <circle style="fill: #339989" cx="12" cy="12" r="12" /> -->+	<!-- Uncomment for icon-mask.png -->+	<!-- <g transform="scale(0.79) translate(3,3)"> -->+	<g transform="rotate(45, 12, 12) translate(0, 3.5)">+		<!-- Haskell logo-->+		<g transform="translate(-0.75,0)" mask="url(#lens_mask)">+			<use style="fill: #453a62;" href="#greater" x="2.75" y="-0.5" />+			<use style="fill: #5e5086" href="#lambda" x="8" y="-0.5" />+			<use style="fill: #8f4e8b" href="#masked_equals" x="13.5" y="4" />+		</g>+		<!-- Magnifying Glass -->+		<circle class="magnifying-glass" id="lens" cx="12" cy="8.5" r="8.5"/>+		<rect class="magnifying-glass" x="20" y="7.25" width="6" height="2" rx="0.5" ry="0.5" />+	</g>+	<!-- Uncomment for icon-mask.png -->+	<!-- </g> -->+</svg>
+ data/viewer/index.css view
@@ -0,0 +1,1 @@+.uplot,.uplot *,.uplot *:before,.uplot *:after{box-sizing:border-box}.uplot{font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";line-height:1.5;width:min-content}.u-title{text-align:center;font-size:18px;font-weight:700}.u-wrap{position:relative;user-select:none}.u-over,.u-under{position:absolute}.u-under{overflow:hidden}.uplot canvas{display:block;position:relative;width:100%;height:100%}.u-axis{position:absolute}.u-legend{font-size:14px;margin:auto;text-align:center}.u-inline{display:block}.u-inline *{display:inline-block}.u-inline tr{margin-right:16px}.u-legend th{font-weight:600}.u-legend th>*{vertical-align:middle;display:inline-block}.u-legend .u-marker{width:1em;height:1em;margin-right:4px;background-clip:padding-box!important}.u-inline.u-live th:after{content:":";vertical-align:middle}.u-inline:not(.u-live) .u-value{display:none}.u-series>*{padding:4px}.u-series th{cursor:pointer}.u-legend .u-off>*{opacity:.3}.u-select{background:#00000012;position:absolute;pointer-events:none}.u-cursor-x,.u-cursor-y{position:absolute;left:0;top:0;pointer-events:none;will-change:transform}.u-hz .u-cursor-x,.u-vt .u-cursor-y{height:100%;border-right:1px dashed #607D8B}.u-hz .u-cursor-y,.u-vt .u-cursor-x{width:100%;border-bottom:1px dashed #607D8B}.u-cursor-pt{position:absolute;top:0;left:0;border-radius:50%;border:0 solid;pointer-events:none;will-change:transform;background-clip:padding-box!important}.u-axis.u-off,.u-select.u-off,.u-cursor-x.u-off,.u-cursor-y.u-off,.u-cursor-pt.u-off{display:none}.uplot.u-stacked-legend .u-legend{text-align:left}.uplot.u-stacked-legend .u-legend.u-inline tr{display:block}
+ data/viewer/index.html view
@@ -0,0 +1,23 @@+<!doctype html>+<html lang="en">+  <head>+    <meta charset="utf-8" />+    <meta name="viewport" content="width=device-width, initial-scale=1" />+    <link rel="stylesheet" href="index.css" />+    <link rel="icon" href="favicon.ico" sizes="256x256" type="image/x-icon" />+    <link rel="icon" href="icon.svg" sizes="any" type="image/svg+xml" />+    <link+      rel="apple-touch-icon"+      href="apple-touch-icon.png"+      sizes="180x180"+      type="image/png"+    />+    <link rel="manifest" href="manifest.webmanifest" />+    <title>Eventlog Live</title>+  </head>+  <body>+    <noscript>You need to enable JavaScript to run this app.</noscript>+    <div id="app"></div>+    <script src="index.js"></script>+  </body>+</html>
+ data/viewer/index.js view
@@ -0,0 +1,241 @@+"use strict";(()=>{var vS=Object.create;var Mc=Object.defineProperty;var TS=Object.getOwnPropertyDescriptor;var PS=Object.getOwnPropertyNames;var _S=Object.getPrototypeOf,SS=Object.prototype.hasOwnProperty;var Wf=(e,t)=>()=>(e&&(t=e(e=0)),t);var er=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),wS=(e,t)=>{for(var r in t)Mc(e,r,{get:t[r],enumerable:!0})},sg=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of PS(t))!SS.call(e,n)&&n!==r&&Mc(e,n,{get:()=>t[n],enumerable:!(o=TS(t,n))||o.enumerable});return e};var $c=(e,t,r)=>(r=e!=null?vS(_S(e)):{},sg(t||!e||!e.__esModule?Mc(r,"default",{value:e,enumerable:!0}):r,e)),Ic=e=>sg(Mc({},"__esModule",{value:!0}),e);function js(e){e&&e.parentNode&&e.remove()}function tr(e,t,r){var o,n,s,i={},a=arguments.length;for(s in t)s=="key"?o=t[s]:s=="ref"&&typeof e!="function"?n=t[s]:i[s]=t[s];return a>2&&(i.children=a>3?Fc.call(arguments,2):r),Fs(e,i,o,n,null)}function pg(e,t,r){var o,n,s,i=us({},e.props),a=arguments.length;for(s in t)s=="key"?o=t[s]:s=="ref"&&typeof e.type!="function"?n=t[s]:i[s]=t[s];return a>2&&(i.children=a>3?Fc.call(arguments,2):r),Fs(e.type,i,o!==void 0?o:e.key,n!==void 0?n:e.ref,null)}function Fs(e,t,r,o,n){var s={type:e,props:t,key:r,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:pl,__v:n||++ag,__i:-1,__u:0};return!n&&Ne.vnode&&Ne.vnode(s),s}function Vc(){return{current:null}}function Ie(e){return e.children}function vo(e,t){this.props=e,this.context=t,this.__g=0}function ps(e,t){if(t==null)return e.__&&ps(e.__,e.__i+1);for(var r;t<e.__k.length;t++)if((r=e.__k[t])&&r.__e)return r.__e;return typeof e.type!="function"||e.props.__P?null:ps(e)}function fg(e){if((e=e.__)&&e.__c&&!e.props.__P)return e.__e=null,e.__k.some(function(t){return t&&(e.__e=t.__e)}),fg(e)}function Kf(e){(8&e.__g||(e.__g|=8,cs.push(e),Dc++))&&Hf==Ne.debounceRendering||((Hf=Ne.debounceRendering)||queueMicrotask)(dg)}function dg(){var e,t,r,o,n,s,i,a,l;try{for(t=1;cs.length;)cs.length>t&&cs.sort(lg),e=cs.shift(),t=cs.length,8&e.__g&&(o=void 0,n=void 0,s=(n=(r=e).__v).__e,i=[],a=[],(l=r.__P)&&((o=us({constructor:pl},n)).__v=n.__v+1,Ne.vnode&&Ne.vnode(o),Xf(l,o,n,r.__n,l.namespaceURI,32&n.__u?[s]:null,i,s||ps(n),32&n.__u,a),o.__v=n.__v,o.__.__k[o.__i]=o,gg(i,o,a),n.__=n.__e=null,o.__e!=s&&fg(o)))}finally{(Dc=cs.length)&&(Hf||queueMicrotask)(dg)}}function mg(e,t,r,o,n,s,i,a,l,c,u){var f,m,p,y,x,T,S=o.__k||Lc,v=t.length;for(l=RS(r,t,S,l,v),f=0;f<v;f++)(p=r.__k[f])!=null&&(m=~p.__i&&S[p.__i]||Bc,p.__i=f,T=Xf(e,p,m,n,s,i,a,l,c,u),y=p.__e,(m.ref!=p.ref||8&m.__u)&&(m.ref&&Jf(m.ref,null,p,m),p.ref&&u.push(p.ref,p.__c||y,p)),x=x||y,4&p.__u?(l=hg(p,l,e,!m.__v),m.__e&&(m.__e=null)):typeof p.type=="function"&&T!==void 0?l=T:y&&(l=y.nextSibling),p.__u&=-21);return r.__e=x,l}function RS(e,t,r,o,n){var s,i,a,l,c,u,f,m,p,y=r.length,x=y,T=0,S=0,v=e.__k=Array(n);for(s=0;s<n;s++)(i=t[s])!=null&&typeof i!="boolean"&&typeof i!="function"?(typeof i!="object"||i.constructor===String?i=v[s]=Fs(null,i):jc(i)?i=v[s]=Fs(Ie,{children:i}):i.constructor===pl&&i.__b?i=v[s]=Fs(i.type,i.props,i.key,i.ref,i.__v):v[s]=i,l=s+T,i.__=e,i.__b=e.__b+1,a=null,~(c=i.__i=kS(i,r,l,x))&&(x--,(a=r[c])&&(a.__u|=2)),a&&a.__v?(i.__u|=16,c==l-1?T--:c==l+1?T++:c!=l&&(c>l?T--:T++,S=1)):(~c||(n>y?T--:n<y&&T++),typeof i.type!="function"&&(i.__u|=4))):v[s]=null;if(S){for(u=[],f=[],s=0;s<n;s++)if((i=v[s])&&16&i.__u){for(T=0,m=u.length;T<m;)u[p=T+m>>1]<i.__i?T=p+1:m=p;u[T]=i.__i,f[s]=T+1}for(T=u.length;s--;)f[s]&&(f[s]==T?T--:v[s].__u|=4)}if(x)for(s=0;s<y;s++)!(a=r[s])||2&a.__u||(a.__e==o&&(o=ps(a)),Qf(a,a));return o}function hg(e,t,r,o){var n,s,i,a;if(typeof e.type=="function"){if(e.props.__P)return t;if(n=e.__k)for(s=0;s<n.length;s++)n[s]&&(n[s].__=e,t=hg(n[s],t,r,!1));return t}for(t&&!t.parentNode&&(t=ps(e))&&!t.parentNode&&(t=null),i=e.__e,a=t;a&&a.nodeType==8;)a=a.nextSibling;for(i!=a&&(!o&&r.moveBefore&&i.parentNode?r.moveBefore(i,t):r.insertBefore(i,t||null)),t=i;(t=t&&t.nextSibling)&&t.nodeType==8&&!t.data.startsWith("$s"););return t}function In(e,t){return t=t||[],e!=null&&typeof e!="boolean"&&(jc(e)?e.some(function(r){In(r,t)}):t.push(e)),t}function kS(e,t,r,o){var n,s=e.key,i=e.type,a=t[r],l=a&&!(2&a.__u);if(a===null&&s==null||l&&s==a.key&&i==a.type)return r;if(o>(l?1:0)){for(n=r-1;n>=0;n--)if((a=t[n])&&!(2&a.__u)&&s==a.key&&i==a.type)return n;for(n=r+1;n<t.length;n++)if((a=t[n])&&!(2&a.__u)&&s==a.key&&i==a.type)return n}return-1}function ig(e,t,r){r==null&&(r=""),t[0]=="-"?e.setProperty(t,r):e[t]=r}function Nc(e,t,r,o,n){var s,i;if(t=="style")if(typeof r=="string")e.style.cssText=r;else{if(typeof o=="string"&&(e.style.cssText=o=""),o)for(t in o)r&&t in r||ig(e.style,t);if(r)for(t in r)o&&r[t]==o[t]||ig(e.style,t,r[t])}else if(t[0]=="o"&&t[1]=="n")(e.__e||(e.__e={}))[t]=r,r&&o||(i=Gf[t]||(Gf[t]=OS(t)),(e.__a||(e.__a={}))[t]=Yf,s=t!=(t=t.replace(cg,"$1")),(t=t.slice(2))[0]<"a"&&(t=t.toLowerCase()),r?e.addEventListener(t,i,s):e.removeEventListener(t,i,s));else{if(n=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{return void(e[t]=r??"")}catch{}if(typeof r=="function")return;r==null||r===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&r==1?"":r)}}function OS(e){return function(t){var r=this.__e;if(r){if(r=r[e],t[zc]==null)t[zc]=Yf++;else if(t[zc]<this.__a[e])return;return r(Ne.event?Ne.event(t):t)}}}function Xf(e,t,r,o,n,s,i,a,l,c){var u,f,m,p,y,x,T,S,v,R,P,O,E,A,I,N,D,w,$=t.type;if(t.constructor!==pl)return null;128&r.__u&&(l=32&r.__u,u=r.__c.__z)&&(t.__u|=l,f=s=[],u.nodeType==8?a=qf(u,s):s.push(u),a=s[0]||a),(u=Ne.__b)&&u(t);e:if(typeof $=="function"){m=i.length;try{if(S=t.props,v=(u=$.prototype)&&u.render,R=(u=$.contextType)&&o[u.__c],P=u?R?R.props.value:u.__:o,(p=r.__c)?(t.__c=p,2&p.__g&&(p.__g|=1)):(v?t.__c=p=new $(S,P):(t.__c=p=new vo(S,P),p.constructor=$,p.render=MS),R&&R.sub(p),p.state||(p.state={}),p.__n=o,p.__g|=8,p.__h=[],p.__k=[]),v&&(p.__s||(p.__s=p.state),$.getDerivedStateFromProps&&(p.__s==p.state&&(p.__s=us({},p.__s)),us(p.__s,$.getDerivedStateFromProps(S,p.__s)))),y=p.props,x=p.state,p.__v=t,r.__c){if(S!==y&&v&&!$.getDerivedStateFromProps&&p.componentWillReceiveProps&&p.componentWillReceiveProps(S,P),t.__v==r.__v&&!(8&p.__g)||!(4&p.__g)&&p.shouldComponentUpdate&&p.shouldComponentUpdate(S,p.__s,P)===!1){t.__v!=r.__v&&(p.props=S,p.state=p.__s,p.__g&=-9),t.__e=r.__e,t.__k=r.__k,t.__k.some(function(h){h&&(h.__=t)}),Lc.push.apply(p.__h,p.__k),p.__k=[],p.__h.length&&i.push(p),a=ps(r);break e}p.componentWillUpdate&&p.componentWillUpdate(S,p.__s,P),v&&p.componentDidUpdate&&p.__h.push(function(){p.componentDidUpdate(y,x,T)})}else v&&!$.getDerivedStateFromProps&&p.componentWillMount&&p.componentWillMount(),v&&p.componentDidMount&&p.__h.push(p.componentDidMount);if(p.context=P,p.props=S,p.__P=e,p.__g&=-5,O=Ne.__r,E=0,v)p.state=p.__s,p.__g&=-9,O&&O(t),u=p.render(p.props,p.state,p.context),Lc.push.apply(p.__h,p.__k),p.__k=[];else do p.__g&=-9,O&&O(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(8&p.__g&&++E<25);p.state=p.__s,p.getChildContext&&(o=us({},o,p.getChildContext())),v&&r.__c&&p.getSnapshotBeforeUpdate&&(T=p.getSnapshotBeforeUpdate(y,x)),A=u&&u.type===Ie&&u.key==null?u.props.children:u,S.__P&&(u=a,n=(e=S.__P).namespaceURI,l=s=null,r.props&&r.props.__P!=e&&(r.__k.some(function(h){h&&Qf(h,h)}),r.__k=null),a=r.__k?ps(r,0):null),a=mg(e,jc(A)?A:[A],t,r,o,n,s,i,a,l,c),S.__P&&(t.__e=null,a=u),t.__u&=-161,f&&f.some(js),p.__h.length&&i.push(p),1&p.__g&&(p.__g&=-4)}catch(h){if(i.length=m,t.__v=null,l||s)if(h.then){if(I=0,t.__u|=128|l,s){for(~(D=s.indexOf(a||void 0))||(D=s.length);(w=s[D-1])&&w.nodeType==8;)D--;for(;D<s.length;D++)if(w=s[D]){if(s[D]=null,w.nodeType==8){if(w.data.startsWith("$s"))I++||(N=w);else if(I&&w.data.startsWith("/$s")&&!--I)break}else if(!I)break}}if(!N){for(;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;N=a}(u=qf(N=t.__c.__z||(t.__c.__z=N)))?(t.__e=N,a=u):t.__e=a,a=a&&a.nextSibling}else s&&s.some(js);else t.__e=r.__e;t.__k||(t.__k=r.__k||[]),h.then||yg(t),Ne.__e(h,t,r)}}else a=t.__e=AS(r.__e,t,r,o,n,s,i,l,c,e);return(u=Ne.diffed)&&u(t),a}function qf(e,t){if(e&&e.nodeType==8&&e.data.startsWith("$s"))for(var r=1;e=e.nextSibling;){if(e.nodeType==8){if(e.data.startsWith("$s"))r++;else if(e.data.startsWith("/$s")&&!--r)return e}t&&t.push(e)}}function yg(e){e&&(e.__c&&(e.__c.__g|=4),e.__k&&e.__k.some(yg))}function gg(e,t,r){for(var o=0;o<r.length;)Jf(r[o++],r[o++],r[o++]);Ne.__c&&Ne.__c(t,e),e.some(function(n){try{e=n.__h,n.__h=[],e.some(function(s){s.call(n)})}catch(s){Ne.__e(s,n.__v)}})}function AS(e,t,r,o,n,s,i,a,l,c){var u,f,m,p,y,x,T,S,v,R=r.props||Bc,P=t.props,O=t.type;if(O=="svg"?n="http://www.w3.org/2000/svg":O=="math"?n="http://www.w3.org/1998/Math/MathML":n||(n="http://www.w3.org/1999/xhtml"),s){for(u=0;u<s.length;u++)if((y=s[u])&&(O?y.localName==O:y.nodeType==3)){e=y,s[u]=null;break}}if(!e){if(S=c.ownerDocument||document,!O)return S.createTextNode(P);e=S.createElementNS(n,O,P.is&&P),a&&(Ne.__m&&Ne.__m(t,s),a=!1),s=null}if(O){if(c=O=="template"?e.content:e,s=O=="textarea"&&P.defaultValue!=null?null:s&&Fc.call(c.childNodes),!a&&s)for(R={},u=0;u<e.attributes.length;u++)R[(y=e.attributes[u]).name]=y.value;for(u in R)y=R[u],u=="dangerouslySetInnerHTML"?m=y:u=="children"||u in P||u=="value"&&"defaultValue"in P||u=="checked"&&"defaultChecked"in P||Nc(e,u,null,y,n);for(u in v=1&r.__u,P)y=P[u],u=="children"?p=y:u=="dangerouslySetInnerHTML"?f=y:u=="value"?x=y:u=="checked"?T=y:a&&typeof y!="function"||!(R[u]!==y||v&&y!=null)||Nc(e,u,y,R[u],n);f?(a||m&&(f.__html==m.__html||f.__html==e.innerHTML)||(e.innerHTML=f.__html),t.__k=[]):(m&&(e.textContent=""),(O=="foreignObject"||n=="http://www.w3.org/1998/Math/MathML"&&ES.test(O))&&(n="http://www.w3.org/1999/xhtml"),mg(c,jc(p)?p:[p],t,r,o,n,s,i,s?s[0]:r.__k&&ps(r,0),a,l),s&&s.some(js)),a&&O!="textarea"||(u="value",O=="progress"&&x==null?e.removeAttribute(u):x==null||x===e[u]&&(O!="progress"||x)||Nc(e,u,x,R[u],n),u="checked",T!=null&&T!=e[u]&&Nc(e,u,T,R[u],n))}else R===P||a&&e.data==P||(e.data=P);return e}function Jf(e,t,r,o){try{typeof e=="function"?t?t.__x=e(t)||1:o&&(o=o.__c||o.__e)&&(t=o.__x)&&(o.__x=null,typeof t=="function"?t():e(null)):e.current=t}catch(n){Ne.__e(n,r)}}function Qf(e,t,r){var o,n,s,i;if(Ne.unmount&&Ne.unmount(e),!(o=e.ref)||o.current&&o.current!=e.__e||Jf(o,null,t,e),o=e.__c){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(a){Ne.__e(a,t)}o.__P=o.__n=null}if(o=e.__k)for(i=0;i<o.length;i++)o[i]&&Qf(o[i],t,typeof e.type!="function"||r&&!e.props.__P);!r&&(o=e.__c)&&(o=o.__z)&&(n=qf(o,s=[]))&&(o==e.__e&&s.some(js),js(n),js(o)),(o=e.__e)&&(r||js(o),o.__e&&(o.__e=null)),e.__e=e.__c=e.__=null}function MS(e,t,r){return this.constructor(e,r)}function Uc(e,t){var r,o,n,s;Ne.__&&Ne.__(e,t),t.nodeType==9&&(t=t.documentElement),o=(r=e&&32&e.__u)?null:t.__k,t.__k=Fs(Ie,{children:[e]}),n=[],s=[],Xf(t,t.__k,o||Bc,Bc,t.namespaceURI,o?null:t.firstChild?Fc.call(t.childNodes):null,n,o?o.__e:t.firstChild,r,s),gg(n,t.__k,s),t.__k.props.children=null}function bg(e,t){e&&typeof e=="object"&&(e.__u|=32),Uc(e,t)}function Je(e){function t(r){var o,n;return this.getChildContext||(o=new Set,(n={})[t.__c]=this,this.getChildContext=function(){return n},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&o.forEach(function(i){i.__g|=4,Kf(i)})},this.sub=function(s){o.add(s);var i=s.componentWillUnmount;s.componentWillUnmount=function(){o.delete(s),i&&i.call(s)}}),r.children}return t.__c="__cC"+ug++,t.__=e,t.Provider=(t.Consumer=function(r,o){return r.children(o)}).contextType=t,t}function $S(e){return e.children}function xg(e,t){return Fs($S,{__P:t,children:e})}var Ne,ag,CS,cs,Hf,Dc,lg,zc,cg,Yf,Gf,ug,pl,Bc,Lc,ES,jc,Fc,us,Vi=Wf(()=>{pl=Symbol.for("pv"),Bc={},Lc=[],ES=/^m(i|n|o|s|text|space)$/,jc=Array.isArray,Fc=Lc.slice,us=Object.assign;Ne={__e:function(e,t,r,o){for(var n,s,i;t=t.__;)if((n=t.__c)&&!(1&n.__g)){n.__g|=4;try{if((i=(s=n.constructor)&&s.getDerivedStateFromError)&&n.setState(s.getDerivedStateFromError(e)),n.componentDidCatch&&(n.componentDidCatch(e,o||{}),i=1),i&&8&n.__g)return void(n.__g|=2)}catch(a){e=a}}throw Dc=0,e}},ag=0,CS=function(e){return e!=null&&e.constructor===pl},vo.prototype.setState=function(e,t){var r=this.__s;r&&r!=this.state||(r=this.__s=us({},this.state)),typeof e=="function"&&(e=e(us({},r),this.props)),e&&(us(r,e),this.__v&&(t&&this.__k.push(t),Kf(this)))},vo.prototype.forceUpdate=function(e){this.__v&&(this.__g|=4,e&&this.__h.push(e),Kf(this))},vo.prototype.render=Ie,cs=[],Dc=0,lg=function(e,t){return e.__v.__b-t.__v.__b},zc=Symbol(),cg=/(PointerCapture)$|Capture$/i,Yf=0,Gf={},ug=0});function Vs(e,t){Ut.__h&&Ut.__h(It,e,Ui||t),Ui=0;var r=It.__H||(It.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function ie(e){return Ui=1,dl(Og,e)}function dl(e,t,r){var o=Vs(Nn++,2);if(o.t=e,!o.__c&&(o.__=[r?r(t):Og(void 0,t),function(s){var i=o.__N?o.__N[0]:o.__[0],a=o.t(i,s);td(i,a)||(o.__N=[a,o.__[1]],o.__c.setState({}))}],o.__c=It,!It.__f)){It.__f=!0;var n=It.shouldComponentUpdate;It.shouldComponentUpdate=function(s,i,a){var l=this.__H;if(!l)return!0;var c=!1,u=this.props!=s;if(l.__.some(function(m){m.__N&&(c=!0,td(m.__[0],m.__N[0])||(u=!0))}),n){var f=n.call(this,s,i,a);return c?f||u:f}return!c||u}}return o.__}function ce(e,t){var r=Vs(Nn++,3);!Ut.__s&&nd(r.__H,t)&&(r.__P=!0,r.__=e,r.u=t,It.__H.__h.push(r))}function Zo(e,t){var r=Vs(Nn++,4);!Ut.__s&&nd(r.__H,t)&&(r.__P=!1,r.__=e,r.u=t,It.__h.push(r))}function J(e){return Ui=5,Le(function(){return{current:e}},[])}function To(e,t,r){Ui=6,Zo(function(){if(typeof e=="function"){var o=e(t());return function(){e(null),o&&typeof o=="function"&&o()}}if(e)return e.current=t(),function(){return e.current=null}},r==null?r:r.concat(e))}function Le(e,t){var r=Vs(Nn++,7);return nd(r.__H,t)&&(r.__=e(),r.__H=t),r.__}function Ee(e,t){return Ui=8,Le(function(){return e},t)}function Se(e){var t=It.context[e.__c],r=Vs(Nn++,9);return r.c=e,t?(r.__==null&&(r.__=!0,t.sub(It)),t.props.value):e.__}function Us(e,t){Ut.useDebugValue&&Ut.useDebugValue(t?t(e):e)}function IS(e){var t=Vs(Nn++,10),r=ie();return t.__=e,It.componentDidCatch||(It.componentDidCatch=function(o,n){t.__&&t.__(o,n),r[1](o)}),[r[0],function(){r[1](void 0)}]}function xn(){var e=Vs(Nn++,11);if(!e.__){for(var t=It.__v;!t.__m&&t.__;)t=t.__;var r=t.__m||(t.__m=[0,0]);e.__="P"+r[0]+"-"+r[1]++}return e.__}function NS(){var e;do{for(;e=rd.shift();)try{fl(e)}catch(r){Ut.__e(r,{__:(e=e.__P)&&e.__v})}for(;e=kg.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(fl),t.__h.some(od),t.__h=[]}catch(r){t.__h=[],Ut.__e(r,e.__v)}}}while(rd.length)}function zS(e){var t,r=function(){clearTimeout(o),Eg&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(r,35);Eg&&(t=requestAnimationFrame(r))}function Rg(e){e!=1&&vg==Ut.requestAnimationFrame||((vg=Ut.requestAnimationFrame)||zS)(NS)}function fl(e){var t=It,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),It=t}function od(e){var t=It;e.__c=e.__(),It=t}function nd(e,t){return!e||e.length!=t.length||t.some(function(r,o){return!td(r,e[o])})}function Og(e,t){return typeof t=="function"?t(e):t}var Nn,It,ed,vg,td,Ui,kg,rd,Ut,Tg,Pg,_g,Sg,wg,Cg,Eg,sd=Wf(()=>{Vi();td=Object.is,Ui=0,kg=[],rd=[],Ut=Ne,Tg=Ut.__b,Pg=Ut.__r,_g=Ut.diffed,Sg=Ut.__c,wg=Ut.unmount,Cg=Ut.__;Ut.__b=function(e){It=null,Tg&&Tg(e)},Ut.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Cg&&Cg(e,t)},Ut.__r=function(e){Pg&&Pg(e),Nn=0;var t=(It=e.__c).__H;t&&(ed==It?It.__h=[]:(t.__h.some(fl),t.__h.some(od),Nn=0),t.__h=[],t.__.some(function(r){r.__N&&(r.__=r.__N),r.u=r.__N=void 0})),ed=It},Ut.diffed=function(e){_g&&_g(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&Rg(kg.push(t)),t.__H.__.some(function(r){r.u&&(r.__H=r.u)})),ed=It=null},Ut.__c=function(e,t){t.some(function(r){try{r.__h.some(fl),r.__h=r.__h.filter(function(o){return!o.__||od(o)})}catch(o){r.__h=[function(){throw o}]}}),Sg&&Sg(e,t)},Ut.unmount=function(e){wg&&wg(e);var t,r,o=e.__c;o&&o.__H&&(o.__H.__.some(function(n){try{if(n.__P&&n.__c){if(r===void 0){for(r=e.__;r&&(!r.__c||!r.__c.__P);)r=r.__;r=r&&r.__c}n.__P=r,Rg(rd.push(n))}else fl(n)}catch(s){t=s}}),o.__H=void 0,t&&Ut.__e(t,o.__v))};Eg=typeof requestAnimationFrame=="function"});var Q={};wS(Q,{Children:()=>zn,Component:()=>vo,Fragment:()=>Ie,PureComponent:()=>Ng,StrictMode:()=>Ie,Suspense:()=>Vg,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>Lg,cloneElement:()=>vr,createContext:()=>Je,createElement:()=>tr,createFactory:()=>Zg,createPortal:()=>Gc,createRef:()=>Vc,default:()=>hd,findDOMNode:()=>Gg,flushSync:()=>Kg,forwardRef:()=>ue,hydrate:()=>fd,isElement:()=>Rt,isFragment:()=>Wg,isMemo:()=>Hg,isValidElement:()=>Rt,lazy:()=>Ug,memo:()=>Hc,render:()=>Kc,startTransition:()=>ld,unmountComponentAtNode:()=>qc,unstable_batchedUpdates:()=>qg,use:()=>dd,useCallback:()=>Ee,useContext:()=>Se,useDebugValue:()=>Us,useDeferredValue:()=>cd,useEffect:()=>ce,useEffectEvent:()=>zg,useErrorBoundary:()=>IS,useId:()=>xn,useImperativeHandle:()=>To,useInsertionEffect:()=>Wi,useLayoutEffect:()=>Zo,useMemo:()=>Le,useReducer:()=>dl,useRef:()=>J,useState:()=>ie,useSyncExternalStore:()=>pd,useTransition:()=>ud,version:()=>md});function ad(e,t){for(var r in e)if(r!="__source"&&e[r]!==t[r])return!0;for(var o in t)if(o!="__source"&&!(o in e))return!0;return!1}function BS(){function e(t,r){this.props=t,this.context=r}return(e.prototype=new vo).isPureReactComponent=!0,e.prototype.shouldComponentUpdate=function(t,r){return ad(this.props,t)||ad(this.state,r)},e}function ue(e){function t(r){var o=Wc({},r);return delete o.ref,e(o,r.ref||null)}return t.$$typeof=LS,t.render=e,t.prototype.isReactComponent=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}function ld(e){e()}function cd(e){return e}function ud(){return[!1,ld]}function zg(e){var t=J(e);return t.current=e,function(){return t.current.apply(void 0,arguments)}}function Hc(e,t){function r(n){var s=this.props.ref;return s!=n.ref&&s&&(typeof s=="function"?s(null):s.current=null),t?!t(this.props,n)||s!=n.ref:ad(this.props,n)}function o(n){return this.shouldComponentUpdate=r,tr(e,n)}return o.displayName="Memo("+(e.displayName||e.name)+")",o.prototype.isReactComponent=!0,o.type=e,o}function Gc(e,t){var r=xg(e,t);return r.containerInfo=t,r}function id(e){try{return!Object.is(e.__,e.u())}catch{return!0}}function Kc(e,t,r){return t.__k==null&&(t.textContent=""),Uc(e,t),typeof r=="function"&&r(),e?e.__c:null}function fd(e,t,r){return bg(e,t),typeof r=="function"&&r(),e?e.__c:null}function Bg(e){if(!Mg){Mg=!0;var t=Ne.__r;Ne.__r=function(o){t&&t(o),32&o.__u&&(Zc=o),Zi=o.__c};var r=Ne.diffed;Ne.diffed=function(o){r&&r(o),Zi=null,Zc==o&&(Zc=null)}}return e}function jg(e,t,r){if(e){var o=e.__c&&e.__c.__H;o&&(o.__.forEach(function(n){n.__P!=null&&(typeof n.__c=="function"&&n.__c(),n.__c=n.__H=void 0)}),o.__h=e.__c.__h=[]),typeof e.type=="string"&&(e.__u|=8),(e=Wc({constructor:WS},e)).__c!=null&&(e.__c.__P==r&&(e.__c.__P=t),e.__c.__g|=4,e.__c=e.ref=null),e.__k=e.__k&&e.__k.map(function(n){return jg(n,t,r)})}return e}function Fg(e,t,r){return e&&r&&(typeof e.type=="string"&&(e.__u|=1),e.__v=null,e.__k=e.__k&&e.__k.map(function(o){return Fg(o,t,r)}),e.__c&&e.__c.__P==t&&(e.__e&&r.appendChild(e.__e),e.__c.__g|=4,e.__c.__P=r)),e}function HS(){function e(){this.__u=0,this.i=null,this.__b=null}return(function(){var t=Ne.__e;Ne.__e=function(o,n,s,i){if(o.then){for(var a,l=n;l=l.__;)if((a=l.__c)&&a.__c)return s&&!s.__c&&(n.__c.__H=void 0),a.__c(o,n)}t(o,n,s,i)};var r=Ne.unmount;Ne.unmount=function(o){var n=o.__c;n&&n.__R&&n.__R(),r&&r(o)}})(),(e.prototype=new vo).__c=function(t,r){var o=this,n=r.__c;this.i==null&&(this.i=[]),this.i.push(n);var s=!1,i=function(){!s&&o.__P&&(s=!0,n.__R=null,l())};n.__R=i;var a=n.__P;n.__P=null;var l=function(){if(!--o.__u){if(o.state.__a){var c=o.state.__a;o.__v.__k[0]=Fg(c,c.__c.__P,c.__c.__O)}var u;for(o.setState({__a:o.__b=null});u=o.i.pop();)u.__P=a,u.forceUpdate()}};this.__u++||32&r.__u||this.setState({__a:this.__b=this.__v.__k[0]}),t.then(i,i)},e.prototype.componentWillUnmount=function(){this.i=[],this.state.__a&&(this.__v.__k[0]=this.state.__a)},e.prototype.render=function(t,r){if(this.__b){if(this.__v.__k){var o=document.createElement("div"),n=this.__v.__k[0].__c;this.__v.__k[0]=jg(this.__b,o,n.__O=n.__P)}this.__b=null}return[tr(Ie,null,r.__a?null:t.children),r.__a&&tr(Ie,null,t.fallback)]},e}function Ug(e){var t,r,o,n=null;function s(i){if(t||(t=e()).then(function(a){a&&(n=a.default||a),o=!0},function(a){r=a,o=!0}),r)throw r;if(!o)throw t;return n?tr(n,i):null}return s.displayName="Lazy",s}function Zg(e){return tr.bind(null,e)}function Rt(e){return!!e&&e.$$typeof===Dg}function Wg(e){return Rt(e)&&e.type==Ie}function Hg(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function vr(e){return Rt(e)?pg.apply(null,arguments):e}function qc(e){return!!e.__k&&(Uc(null,e),!0)}function Gg(e){return e&&(e.__v&&e.__v.__e||e.nodeType==1&&e)||null}function qg(e,t){return e(t)}var Ag,zn,Wc,DS,Ng,LS,Wi,Zi,Zc,Mg,Dg,jS,FS,VS,pd,US,$g,ZS,Ig,dd,Lg,WS,Vg,md,Kg,hd,K=Wf(()=>{Vi();Vi();sd();sd();Ag=function(e,t,r){return e==null?null:In(In(e).map(t.bind(r)))},zn={map:Ag,forEach:Ag,count:function(e){return e?In(e).length:0},only:function(e){var t=In(e);if(t.length!=1)throw"Children.only";return t[0]},toArray:In},Wc=Object.assign;DS=/^(-|f[lo].*[^se]$|g.{5,}[^ps]$|z|o[pr]|(W.{5})?[lL]i.*(t|mp)$|an|(bo|s).{4}Im|sca|m.{6}[ds]|ta|c.*[st]$|wido|ini|asp|fill|st)/;Ng=BS(),LS=Symbol.for("react.forward_ref");Wi=Zo;Dg=Symbol.for("react.element"),jS=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(?!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,FS=/[A-Z0-9]/g,VS=typeof document<"u",pd=Bg(function(e,t,r){var o=Ne.__s||Zc?(r||t)():t(),n=ie({t:{__:o,u:t}}),s=n[0].t,i=n[1];return Zo(function(){s.__=o,s.u=t,id(s)&&i({t:s})},[e,o,t]),ce(function(){return id(s)&&i({t:s}),e(function(){id(s)&&i({t:s})})},[e]),o});US=function(e){return/fil|che|rad/.test(e)};vo.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(vo.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});$g=Ne.event;Ne.event=function(e){return $g&&(e=$g(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};ZS={configurable:!0,get:function(){return this.class}},Ig=Ne.vnode;Ne.vnode=function(e){if(typeof e.type=="string")(function(o){var n=o.props,s=o.type,i={},a=s.indexOf("-")==-1;for(var l in n){var c=n[l];if(!(l=="value"&&"defaultValue"in n&&c==null||VS&&l=="children"&&s=="noscript"||l=="class"||l=="className")){if(l=="style"&&c&&c.constructor==Object){var u=void 0;for(var f in c)typeof c[f]!="number"||DS.test(f)||(u||(u=c=Wc({},c)),c[f]+="px")}else if(l=="defaultValue"&&"value"in n&&n.value==null)l="value";else if(l=="download"&&c===!0)c="";else if(l=="translate"&&c==="no")c=!1;else if(l[0]=="o"&&l[1]=="n"){var m=l.toLowerCase();m=="ondoubleclick"?l="ondblclick":m!="onchange"||s!="input"&&s!="textarea"||US(n.type)?m=="onfocus"?l="onfocusin":m=="onblur"&&(l="onfocusout"):m=l="oninput",m=="oninput"&&i[l=m]&&(l="oninputCapture")}else a&&jS.test(l)?l=l.replace(FS,"-$&").toLowerCase():c===null&&(c=void 0);i[l]=c}}s=="select"&&(i.multiple&&Array.isArray(i.value)&&(i.value=In(n.children).forEach(function(p){p.props.selected=i.value.indexOf(p.props.value)!=-1})),i.defaultValue!=null&&(i.value=In(n.children).forEach(function(p){p.props.selected=i.multiple?i.defaultValue.indexOf(p.props.value)!=-1:i.defaultValue==p.props.value}))),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",ZS)):n.className&&(i.class=i.className=n.className),o.props=i})(e);else if(typeof e.type=="function"&&("ref"in e.props&&"prototype"in e.type&&e.type.prototype.render&&(e.ref=e.props.ref,delete e.props.ref),e.type.defaultProps)){var t=Wc({},e.props);for(var r in e.type.defaultProps)t[r]===void 0&&(t[r]=e.type.defaultProps[r]);e.props=t}e.ref&&!("ref"in e.props)&&Object.defineProperty(e.props,"ref",{value:e.ref,configurable:!0,writable:!0}),e.$$typeof=Dg,Ig&&Ig(e)};dd=Bg(function(e){if(e.then){if(e.status=="fulfilled")return e.value;throw e.status=="rejected"?e.reason:(e.status||(e.status="pending",e.then(function(o){e.status="fulfilled",e.value=o},function(o){e.status="rejected",e.reason=o})),e)}var t=e.__c,r=Zi.__n[t];return r?(Zi[t]||(Zi[t]=!0,r.sub(Zi)),r.props.value):e.__}),Lg={ReactCurrentDispatcher:{current:{readContext:dd,useCallback:Ee,useContext:Se,useDebugValue:Us,useDeferredValue:cd,useEffect:ce,useId:xn,useImperativeHandle:To,useInsertionEffect:Wi,useLayoutEffect:Zo,useMemo:Le,useReducer:dl,useRef:J,useState:ie,useSyncExternalStore:pd,useTransition:ud}}},WS=Symbol.for("pv");Vg=HS();md="19.0.0";Kg=function(e,t){var r,o=Ne.debounceRendering;Ne.debounceRendering=function(s){r=s};try{var n=e(t);return r&&r(),n}finally{Ne.debounceRendering=o}};hd={useState:ie,useId:xn,useReducer:dl,useEffect:ce,useLayoutEffect:Zo,useInsertionEffect:Wi,useTransition:ud,useDeferredValue:cd,useSyncExternalStore:pd,useEffectEvent:zg,startTransition:ld,useRef:J,useImperativeHandle:To,useMemo:Le,useCallback:Ee,useContext:Se,use:dd,useDebugValue:Us,version:"19.0.0",Children:zn,render:Kc,hydrate:fd,unmountComponentAtNode:qc,createPortal:Gc,createElement:tr,createContext:Je,createFactory:Zg,cloneElement:vr,createRef:Vc,Fragment:Ie,isValidElement:Rt,isElement:Rt,isFragment:Wg,isMemo:Hg,findDOMNode:Gg,Component:vo,PureComponent:Ng,memo:Hc,forwardRef:ue,flushSync:Kg,unstable_batchedUpdates:qg,StrictMode:Ie,Suspense:Vg,lazy:Ug,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Lg}});var Wo=er(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.isEventSourceSupported=ct.isReactNative=ct.ReadyState=ct.DEFAULT_HEARTBEAT=ct.UNPARSABLE_JSON_OBJECT=ct.DEFAULT_RECONNECT_INTERVAL_MS=ct.DEFAULT_RECONNECT_LIMIT=ct.SOCKET_IO_PING_CODE=ct.SOCKET_IO_PATH=ct.SOCKET_IO_PING_INTERVAL=ct.DEFAULT_EVENT_SOURCE_OPTIONS=ct.EMPTY_EVENT_HANDLERS=ct.DEFAULT_OPTIONS=void 0;var GS=1,KS=1e3*GS;ct.DEFAULT_OPTIONS={};ct.EMPTY_EVENT_HANDLERS={};ct.DEFAULT_EVENT_SOURCE_OPTIONS={withCredentials:!1,events:ct.EMPTY_EVENT_HANDLERS};ct.SOCKET_IO_PING_INTERVAL=25*KS;ct.SOCKET_IO_PATH="/socket.io/?EIO=3&transport=websocket";ct.SOCKET_IO_PING_CODE="2";ct.DEFAULT_RECONNECT_LIMIT=20;ct.DEFAULT_RECONNECT_INTERVAL_MS=5e3;ct.UNPARSABLE_JSON_OBJECT={};ct.DEFAULT_HEARTBEAT={message:"ping",timeout:6e4,interval:25e3};var Xg;(function(e){e[e.UNINSTANTIATED=-1]="UNINSTANTIATED",e[e.CONNECTING=0]="CONNECTING",e[e.OPEN=1]="OPEN",e[e.CLOSING=2]="CLOSING",e[e.CLOSED=3]="CLOSED"})(Xg||(ct.ReadyState=Xg={}));var qS=function(){try{return"EventSource"in globalThis}catch{return!1}};ct.isReactNative=typeof navigator<"u"&&navigator.product==="ReactNative";ct.isEventSourceSupported=!ct.isReactNative&&qS()});var Yc=er(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.resetWebSockets=Ho.sharedWebSockets=void 0;Ho.sharedWebSockets={};var YS=function(e){if(e&&Ho.sharedWebSockets.hasOwnProperty(e))delete Ho.sharedWebSockets[e];else for(var t in Ho.sharedWebSockets)Ho.sharedWebSockets.hasOwnProperty(t)&&delete Ho.sharedWebSockets[t]};Ho.resetWebSockets=YS});var Jc=er(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.setUpSocketIOPing=fs.appendQueryParams=fs.parseSocketIOUrl=void 0;var Xc=Wo(),XS=function(e){if(e){var t=/^https|wss/.test(e),r=e.replace(/^(https?|wss?)(:\/\/)?/,""),o=r.replace(/\/$/,""),n=t?"wss":"ws";return"".concat(n,"://").concat(o).concat(Xc.SOCKET_IO_PATH)}else if(e===""){var t=/^https/.test(window.location.protocol),n=t?"wss":"ws",s=window.location.port?":".concat(window.location.port):"";return"".concat(n,"://").concat(window.location.hostname).concat(s).concat(Xc.SOCKET_IO_PATH)}return e};fs.parseSocketIOUrl=XS;var JS=function(e,t){t===void 0&&(t={});var r=/\?([\w]+=[\w]+)/,o=r.test(e),n="".concat(Object.entries(t).reduce(function(s,i){var a=i[0],l=i[1];return s+"".concat(a,"=").concat(l,"&")},"").slice(0,-1));return"".concat(e).concat(o?"&":"?").concat(n)};fs.appendQueryParams=JS;var QS=function(e,t){t===void 0&&(t=Xc.SOCKET_IO_PING_INTERVAL);var r=function(){return e(Xc.SOCKET_IO_PING_CODE)};return window.setInterval(r,t)};fs.setUpSocketIOPing=QS});var bd=er(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});gd.heartbeat=tw;var yd=Wo();function ew(e){return Array.isArray(e)?e.reduce(function(t,r){return t.current>r.current?t:r}).current:e.current}function tw(e,t,r){var o=r||{},n=o.interval,s=n===void 0?yd.DEFAULT_HEARTBEAT.interval:n,i=o.timeout,a=i===void 0?yd.DEFAULT_HEARTBEAT.timeout:i,l=o.message,c=l===void 0?yd.DEFAULT_HEARTBEAT.message:l,u=Math.max(100,s/10),f=Date.now(),m=setInterval(function(){var p=Date.now(),y=ew(t);if(y+a<=p)console.warn("Heartbeat timed out, closing connection, last message received ".concat(p-y,"ms ago, last ping sent ").concat(p-f,"ms ago")),e.close();else if(y+s<=p&&f+s<=p)try{typeof c=="function"?e.send(c()):e.send(c),f=p}catch(x){console.error("Heartbeat failed, closing connection",x instanceof Error?x.message:x),e.close()}},u);return e.addEventListener("close",function(){clearInterval(m)}),function(){}}});var Qc=er(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.resetSubscribers=no.removeSubscriber=no.addSubscriber=no.hasSubscribers=no.getSubscribers=void 0;var Go={},rw=[],ow=function(e){return(0,no.hasSubscribers)(e)?Array.from(Go[e]):rw};no.getSubscribers=ow;var nw=function(e){var t;return((t=Go[e])===null||t===void 0?void 0:t.size)>0};no.hasSubscribers=nw;var sw=function(e,t){Go[e]=Go[e]||new Set,Go[e].add(t)};no.addSubscriber=sw;var iw=function(e,t){Go[e].delete(t)};no.removeSubscriber=iw;var aw=function(e){if(e&&Go.hasOwnProperty(e))delete Go[e];else for(var t in Go)Go.hasOwnProperty(t)&&delete Go[t]};no.resetSubscribers=aw});var tu=er(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.assertIsWebSocket=uw;eu.resetGlobalState=pw;var lw=Yc(),cw=Qc();function uw(e,t){if(!t&&!(e instanceof WebSocket))throw new Error("")}function pw(e){(0,cw.resetSubscribers)(e),(0,lw.resetWebSockets)(e)}});var Jg=er(Hi=>{"use strict";var ru=Hi&&Hi.__assign||function(){return ru=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++){t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},ru.apply(this,arguments)};Object.defineProperty(Hi,"__esModule",{value:!0});Hi.attachListeners=void 0;var fw=Jc(),dw=bd(),vn=Wo(),mw=tu(),hw=function(e,t,r,o){e.onmessage=function(n){var s;t.current.onMessage&&t.current.onMessage(n),typeof o?.current=="number"&&(o.current=Date.now()),!(typeof t.current.filter=="function"&&t.current.filter(n)!==!0)&&(t.current.heartbeat&&typeof t.current.heartbeat!="boolean"&&((s=t.current.heartbeat)===null||s===void 0?void 0:s.returnMessage)===n.data||r(n))}},yw=function(e,t,r,o,n){e.onopen=function(s){if(t.current.onOpen&&t.current.onOpen(s),o.current=0,r(vn.ReadyState.OPEN),t.current.heartbeat&&e instanceof WebSocket){var i=typeof t.current.heartbeat=="boolean"?void 0:t.current.heartbeat;n.current=Date.now(),(0,dw.heartbeat)(e,n,i)}}},gw=function(e,t,r,o,n){if(vn.isEventSourceSupported&&e instanceof EventSource)return function(){};(0,mw.assertIsWebSocket)(e,t.current.skipAssert);var s;return e.onclose=function(i){var a;if(t.current.onClose&&t.current.onClose(i),r(vn.ReadyState.CLOSED),t.current.shouldReconnect&&t.current.shouldReconnect(i)){var l=(a=t.current.reconnectAttempts)!==null&&a!==void 0?a:vn.DEFAULT_RECONNECT_LIMIT;if(n.current<l){var c=typeof t.current.reconnectInterval=="function"?t.current.reconnectInterval(n.current):t.current.reconnectInterval;s=window.setTimeout(function(){n.current++,o()},c??vn.DEFAULT_RECONNECT_INTERVAL_MS)}else t.current.onReconnectStop&&t.current.onReconnectStop(l),console.warn("Max reconnect attempts of ".concat(l," exceeded"))}},function(){return s&&window.clearTimeout(s)}},bw=function(e,t,r,o,n){var s;return e.onerror=function(i){var a;if(t.current.onError&&t.current.onError(i),vn.isEventSourceSupported&&e instanceof EventSource&&(t.current.onClose&&t.current.onClose(ru(ru({},i),{code:1006,reason:"An error occurred with the EventSource: ".concat(i),wasClean:!1})),r(vn.ReadyState.CLOSED),e.close()),t.current.retryOnError)if(n.current<((a=t.current.reconnectAttempts)!==null&&a!==void 0?a:vn.DEFAULT_RECONNECT_LIMIT)){var l=typeof t.current.reconnectInterval=="function"?t.current.reconnectInterval(n.current):t.current.reconnectInterval;s=window.setTimeout(function(){n.current++,o()},l??vn.DEFAULT_RECONNECT_INTERVAL_MS)}else t.current.onReconnectStop&&t.current.onReconnectStop(t.current.reconnectAttempts),console.warn("Max reconnect attempts of ".concat(t.current.reconnectAttempts," exceeded"))},function(){return s&&window.clearTimeout(s)}},xw=function(e,t,r,o,n,s,i){var a=t.setLastMessage,l=t.setReadyState,c,u,f;return r.current.fromSocketIO&&(c=(0,fw.setUpSocketIOPing)(i)),hw(e,r,a,s),yw(e,r,l,n,s),u=gw(e,r,l,o,n),f=bw(e,r,l,o,n),function(){l(vn.ReadyState.CLOSING),u(),f(),e.close(),c&&clearInterval(c)}};Hi.attachListeners=xw});var Qg=er(Gi=>{"use strict";var ou=Gi&&Gi.__assign||function(){return ou=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++){t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},ou.apply(this,arguments)};Object.defineProperty(Gi,"__esModule",{value:!0});Gi.attachSharedListeners=void 0;var vw=Yc(),Zs=Wo(),ml=Qc(),Tw=Jc(),Pw=bd(),_w=function(e,t,r){e.onmessage=function(o){(0,ml.getSubscribers)(t).forEach(function(n){var s;n.optionsRef.current.onMessage&&n.optionsRef.current.onMessage(o),typeof((s=n?.lastMessageTime)===null||s===void 0?void 0:s.current)=="number"&&(n.lastMessageTime.current=Date.now()),!(typeof n.optionsRef.current.filter=="function"&&n.optionsRef.current.filter(o)!==!0)&&(r&&typeof r!="boolean"&&r?.returnMessage===o.data||n.setLastMessage(o))})}},Sw=function(e,t,r){e.onopen=function(o){var n=(0,ml.getSubscribers)(t);n.forEach(function(s){s.reconnectCount.current=0,s.optionsRef.current.onOpen&&s.optionsRef.current.onOpen(o),s.setReadyState(Zs.ReadyState.OPEN);var i;r&&e instanceof WebSocket&&(s.lastMessageTime.current=Date.now())}),r&&e instanceof WebSocket&&(0,Pw.heartbeat)(e,n.map(function(s){return s.lastMessageTime}),typeof r=="boolean"?void 0:r)}},ww=function(e,t){e instanceof WebSocket&&(e.onclose=function(r){(0,ml.getSubscribers)(t).forEach(function(o){o.optionsRef.current.onClose&&o.optionsRef.current.onClose(r),o.setReadyState(Zs.ReadyState.CLOSED)}),delete vw.sharedWebSockets[t],(0,ml.getSubscribers)(t).forEach(function(o){var n;if(o.optionsRef.current.shouldReconnect&&o.optionsRef.current.shouldReconnect(r)){var s=(n=o.optionsRef.current.reconnectAttempts)!==null&&n!==void 0?n:Zs.DEFAULT_RECONNECT_LIMIT;if(o.reconnectCount.current<s){var i=typeof o.optionsRef.current.reconnectInterval=="function"?o.optionsRef.current.reconnectInterval(o.reconnectCount.current):o.optionsRef.current.reconnectInterval;setTimeout(function(){o.reconnectCount.current++,o.reconnect.current()},i??Zs.DEFAULT_RECONNECT_INTERVAL_MS)}else o.optionsRef.current.onReconnectStop&&o.optionsRef.current.onReconnectStop(o.optionsRef.current.reconnectAttempts),console.warn("Max reconnect attempts of ".concat(s," exceeded"))}})})},Cw=function(e,t){e.onerror=function(r){(0,ml.getSubscribers)(t).forEach(function(o){o.optionsRef.current.onError&&o.optionsRef.current.onError(r),Zs.isEventSourceSupported&&e instanceof EventSource&&(o.optionsRef.current.onClose&&o.optionsRef.current.onClose(ou(ou({},r),{code:1006,reason:"An error occurred with the EventSource: ".concat(r),wasClean:!1})),o.setReadyState(Zs.ReadyState.CLOSED))}),Zs.isEventSourceSupported&&e instanceof EventSource&&e.close()}},Ew=function(e,t,r,o){var n;return r.current.fromSocketIO&&(n=(0,Tw.setUpSocketIOPing)(o)),_w(e,t,r.current.heartbeat),ww(e,t),Sw(e,t,r.current.heartbeat),Cw(e,t),function(){n&&clearInterval(n)}};Gi.attachSharedListeners=Ew});var eb=er(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});nu.createOrJoinSocket=void 0;var ds=Yc(),hl=Wo(),Rw=Jg(),kw=Qg(),xd=Qc(),Ow=function(e,t,r,o,n){return function(){if((0,xd.removeSubscriber)(e,t),!(0,xd.hasSubscribers)(e)){try{var s=ds.sharedWebSockets[e];s instanceof WebSocket&&(s.onclose=function(i){r.current.onClose&&r.current.onClose(i),o(hl.ReadyState.CLOSED)}),s.close()}catch{}n&&n(),delete ds.sharedWebSockets[e]}}},Aw=function(e,t,r,o,n,s,i,a,l){if(!hl.isEventSourceSupported&&o.current.eventSourceOptions)throw hl.isReactNative?new Error("EventSource is not supported in ReactNative"):new Error("EventSource is not supported");if(o.current.share){var c=null;ds.sharedWebSockets[t]===void 0?(ds.sharedWebSockets[t]=o.current.eventSourceOptions?new EventSource(t,o.current.eventSourceOptions):new WebSocket(t,o.current.protocols),e.current=ds.sharedWebSockets[t],r(hl.ReadyState.CONNECTING),c=(0,kw.attachSharedListeners)(ds.sharedWebSockets[t],t,o,l)):(e.current=ds.sharedWebSockets[t],r(ds.sharedWebSockets[t].readyState));var u={setLastMessage:n,setReadyState:r,optionsRef:o,reconnectCount:i,lastMessageTime:a,reconnect:s};return(0,xd.addSubscriber)(t,u),Ow(t,u,o,r,c)}else{if(e.current=o.current.eventSourceOptions?new EventSource(t,o.current.eventSourceOptions):new WebSocket(t,o.current.protocols),r(hl.ReadyState.CONNECTING),!e.current)throw new Error("WebSocket failed to be created");return(0,Rw.attachListeners)(e.current,{setLastMessage:n,setReadyState:r},o,s.current,i,a,l)}};nu.createOrJoinSocket=Aw});var ob=er(Ko=>{"use strict";var Mw=Ko&&Ko.__awaiter||function(e,t,r,o){function n(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function a(u){try{c(o.next(u))}catch(f){i(f)}}function l(u){try{c(o.throw(u))}catch(f){i(f)}}function c(u){u.done?s(u.value):n(u.value).then(a,l)}c((o=o.apply(e,t||[])).next())})},$w=Ko&&Ko.__generator||function(e,t){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},o,n,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(c){return function(u){return l([c,u])}}function l(c){if(o)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(r=0)),r;)try{if(o=1,n&&(s=c[0]&2?n.return:c[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,c[1])).done)return s;switch(n=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,n=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){r.label=c[1];break}if(c[0]===6&&r.label<s[1]){r.label=s[1],s=c;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(c);break}s[2]&&r.ops.pop(),r.trys.pop();continue}c=t.call(e,r)}catch(u){c=[6,u],n=0}finally{o=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},Iw=Ko&&Ko.__spreadArray||function(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,s;o<n;o++)(s||!(o in t))&&(s||(s=Array.prototype.slice.call(t,0,o)),s[o]=t[o]);return e.concat(s||Array.prototype.slice.call(t))};Object.defineProperty(Ko,"__esModule",{value:!0});Ko.getUrl=void 0;var tb=Jc(),rb=Wo(),Nw=function(e){return new Promise(function(t){return window.setTimeout(t,e)})},zw=function(e,t){for(var r=[],o=2;o<arguments.length;o++)r[o-2]=arguments[o];return Mw(void 0,Iw([e,t],r,!0),void 0,function(n,s,i){var a,l,c,u,f,m,p,y,x;return i===void 0&&(i=0),$w(this,function(T){switch(T.label){case 0:if(typeof n!="function")return[3,10];T.label=1;case 1:return T.trys.push([1,3,,9]),[4,n()];case 2:return a=T.sent(),[3,9];case 3:return l=T.sent(),s.current.retryOnError?(c=(p=s.current.reconnectAttempts)!==null&&p!==void 0?p:rb.DEFAULT_RECONNECT_LIMIT,i<c?(u=typeof s.current.reconnectInterval=="function"?s.current.reconnectInterval(i):s.current.reconnectInterval,[4,Nw(u??rb.DEFAULT_RECONNECT_INTERVAL_MS)]):[3,5]):[3,7];case 4:return T.sent(),[2,(0,Ko.getUrl)(n,s,i+1)];case 5:return(x=(y=s.current).onReconnectStop)===null||x===void 0||x.call(y,i),[2,null];case 6:return[3,8];case 7:return[2,null];case 8:return[3,9];case 9:return[3,11];case 10:a=n,T.label=11;case 11:return f=s.current.fromSocketIO?(0,tb.parseSocketIOUrl)(a):a,m=s.current.queryParams?(0,tb.appendQueryParams)(f,s.current.queryParams):f,[2,m]}})})};Ko.getUrl=zw});var nb=er(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.websocketWrapper=void 0;var Dw=function(e,t){return new Proxy(e,{get:function(r,o){var n=r[o];return o==="reconnect"?t:typeof n=="function"?(console.error("Calling methods directly on the websocket is not supported at this moment. You must use the methods returned by useWebSocket."),function(){}):n},set:function(r,o,n){return/^on/.test(o)?(console.warn("The websocket's event handlers should be defined through the options object passed into useWebSocket."),!1):(r[o]=n,!0)}})};Ki.websocketWrapper=Dw;Ki.default=Ki.websocketWrapper});var su=er(Po=>{"use strict";var ms=Po&&Po.__assign||function(){return ms=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++){t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},ms.apply(this,arguments)},Bw=Po&&Po.__awaiter||function(e,t,r,o){function n(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function a(u){try{c(o.next(u))}catch(f){i(f)}}function l(u){try{c(o.throw(u))}catch(f){i(f)}}function c(u){u.done?s(u.value):n(u.value).then(a,l)}c((o=o.apply(e,t||[])).next())})},Lw=Po&&Po.__generator||function(e,t){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},o,n,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(c){return function(u){return l([c,u])}}function l(c){if(o)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(r=0)),r;)try{if(o=1,n&&(s=c[0]&2?n.return:c[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,c[1])).done)return s;switch(n=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,n=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){r.label=c[1];break}if(c[0]===6&&r.label<s[1]){r.label=s[1],s=c;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(c);break}s[2]&&r.ops.pop(),r.trys.pop();continue}c=t.call(e,r)}catch(u){c=[6,u],n=0}finally{o=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},jw=Po&&Po.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Po,"__esModule",{value:!0});Po.useWebSocket=void 0;var Mr=(K(),Ic(Q)),vd=(K(),Ic(Q)),Tn=Wo(),Fw=eb(),Vw=ob(),Uw=jw(nb()),sb=tu(),Zw=function(e,t,r){t===void 0&&(t=Tn.DEFAULT_OPTIONS),r===void 0&&(r=!0);var o=(0,Mr.useState)(null),n=o[0],s=o[1],i=(0,Mr.useState)({}),a=i[0],l=i[1],c=(0,Mr.useMemo)(function(){if(!t.disableJson&&n)try{return JSON.parse(n.data)}catch{return Tn.UNPARSABLE_JSON_OBJECT}return null},[n,t.disableJson]),u=(0,Mr.useRef)(null),f=(0,Mr.useRef)(null),m=(0,Mr.useRef)(function(){}),p=(0,Mr.useRef)(0),y=(0,Mr.useRef)(Date.now()),x=(0,Mr.useRef)([]),T=(0,Mr.useRef)(null),S=(0,Mr.useRef)(t);S.current=t;var v=u.current&&a[u.current]!==void 0?a[u.current]:e!==null&&r===!0?Tn.ReadyState.CONNECTING:Tn.ReadyState.UNINSTANTIATED,R=t.queryParams?JSON.stringify(t.queryParams):null,P=(0,Mr.useCallback)(function(A,I){var N;if(I===void 0&&(I=!0),Tn.isEventSourceSupported&&f.current instanceof EventSource){console.warn("Unable to send a message from an eventSource");return}((N=f.current)===null||N===void 0?void 0:N.readyState)===Tn.ReadyState.OPEN?((0,sb.assertIsWebSocket)(f.current,S.current.skipAssert),f.current.send(A)):I&&x.current.push(A)},[]),O=(0,Mr.useCallback)(function(A,I){I===void 0&&(I=!0),P(JSON.stringify(A),I)},[P]),E=(0,Mr.useCallback)(function(){return S.current.share!==!0||Tn.isEventSourceSupported&&f.current instanceof EventSource?f.current:(T.current===null&&f.current&&((0,sb.assertIsWebSocket)(f.current,S.current.skipAssert),T.current=(0,Uw.default)(f.current,m)),T.current)},[]);return(0,Mr.useEffect)(function(){if(e!==null&&r===!0){var A,I=!1,N=!0,D=function(){return Bw(void 0,void 0,void 0,function(){var w,$,h;return Lw(this,function(z){switch(z.label){case 0:return w=u,[4,(0,Vw.getUrl)(e,S)];case 1:return w.current=z.sent(),u.current===null?(console.error("Failed to get a valid URL. WebSocket connection aborted."),u.current="ABORTED",(0,vd.flushSync)(function(){return l(function(k){return ms(ms({},k),{ABORTED:Tn.ReadyState.CLOSED})})}),[2]):($=function(k){I||(0,vd.flushSync)(function(){return s(k)})},h=function(k){I||(0,vd.flushSync)(function(){return l(function(j){var B;return ms(ms({},j),u.current&&(B={},B[u.current]=k,B))})})},N&&(A=(0,Fw.createOrJoinSocket)(f,u.current,h,S,$,m,p,y,P)),[2])}})})};return m.current=function(){I||(T.current&&(T.current=null),A?.(),D())},D(),function(){I=!0,N=!1,T.current&&(T.current=null),A?.(),s(null)}}else(e===null||r===!1)&&(p.current=0,l(function(w){var $;return ms(ms({},w),u.current&&($={},$[u.current]=Tn.ReadyState.CLOSED,$))}))},[e,r,R,P]),(0,Mr.useEffect)(function(){v===Tn.ReadyState.OPEN&&x.current.splice(0).forEach(function(A){P(A)})},[v]),{sendMessage:P,sendJsonMessage:O,lastMessage:n,lastJsonMessage:c,readyState:v,getWebSocket:E}};Po.useWebSocket=Zw});var ab=er(qi=>{"use strict";var iu=qi&&qi.__assign||function(){return iu=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++){t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},iu.apply(this,arguments)};Object.defineProperty(qi,"__esModule",{value:!0});qi.useSocketIO=void 0;var ib=(K(),Ic(Q)),Ww=su(),Hw=Wo(),Td={type:"empty",payload:null},Gw=function(e){if(!e||!e.data)return Td;var t=e.data.match(/\[.*]/);if(!t)return Td;var r=JSON.parse(t);return!Array.isArray(r)||!r[1]?Td:{type:r[0],payload:r[1]}},Kw=function(e,t,r){t===void 0&&(t=Hw.DEFAULT_OPTIONS),r===void 0&&(r=!0);var o=(0,ib.useMemo)(function(){return iu(iu({},t),{fromSocketIO:!0})},[]),n=(0,Ww.useWebSocket)(e,o,r),s=n.sendMessage,i=n.sendJsonMessage,a=n.lastMessage,l=n.readyState,c=n.getWebSocket,u=(0,ib.useMemo)(function(){return Gw(a)},[a]);return{sendMessage:s,sendJsonMessage:i,lastMessage:u,lastJsonMessage:u,readyState:l,getWebSocket:c}};qi.useSocketIO=Kw});var ub=er(hs=>{"use strict";var au=hs&&hs.__assign||function(){return au=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++){t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},au.apply(this,arguments)},qw=hs&&hs.__rest||function(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,o=Object.getOwnPropertySymbols(e);n<o.length;n++)t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(r[o[n]]=e[o[n]]);return r};Object.defineProperty(hs,"__esModule",{value:!0});hs.useEventSource=void 0;var lb=(K(),Ic(Q)),Yw=su(),cb=Wo(),Xw=function(e,t,r){t===void 0&&(t=cb.DEFAULT_EVENT_SOURCE_OPTIONS);var o=t.withCredentials,n=t.events,s=qw(t,["withCredentials","events"]);r===void 0&&(r=!0);var i=au(au({},s),{eventSourceOptions:{withCredentials:o}}),a=(0,lb.useRef)(cb.EMPTY_EVENT_HANDLERS);n&&(a.current=n);var l=(0,Yw.useWebSocket)(e,i,r),c=l.lastMessage,u=l.readyState,f=l.getWebSocket;return(0,lb.useEffect)(function(){c?.type&&Object.entries(a.current).forEach(function(m){var p=m[0],y=m[1];p===c.type&&y(c)})},[c]),{lastEvent:c,readyState:u,getEventSource:f}};hs.useEventSource=Xw});var Pd=er(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.resetGlobalState=_o.useEventSource=_o.ReadyState=_o.useSocketIO=_o.default=void 0;var Jw=su();Object.defineProperty(_o,"default",{enumerable:!0,get:function(){return Jw.useWebSocket}});var Qw=ab();Object.defineProperty(_o,"useSocketIO",{enumerable:!0,get:function(){return Qw.useSocketIO}});var eC=Wo();Object.defineProperty(_o,"ReadyState",{enumerable:!0,get:function(){return eC.ReadyState}});var tC=ub();Object.defineProperty(_o,"useEventSource",{enumerable:!0,get:function(){return tC.useEventSource}});var rC=tu();Object.defineProperty(_o,"resetGlobalState",{enumerable:!0,get:function(){return rC.resetGlobalState}})});var ix=er(St=>{"use strict";var Vd=Symbol.for("react.transitional.element"),Ud=Symbol.for("react.portal"),bu=Symbol.for("react.fragment"),xu=Symbol.for("react.strict_mode"),vu=Symbol.for("react.profiler"),Tu=Symbol.for("react.consumer"),Pu=Symbol.for("react.context"),_u=Symbol.for("react.forward_ref"),Su=Symbol.for("react.suspense"),wu=Symbol.for("react.suspense_list"),Cu=Symbol.for("react.memo"),Eu=Symbol.for("react.lazy"),sx=Symbol.for("react.view_transition"),l1=Symbol.for("react.client.reference");function Co(e){if(typeof e=="object"&&e!==null){var t=e.$$typeof;switch(t){case Vd:switch(e=e.type,e){case bu:case vu:case xu:case Su:case wu:case sx:return e;default:switch(e=e&&e.$$typeof,e){case Pu:case _u:case Eu:case Cu:return e;case Tu:return e;default:return t}}case Ud:return t}}}St.ContextConsumer=Tu;St.ContextProvider=Pu;St.Element=Vd;St.ForwardRef=_u;St.Fragment=bu;St.Lazy=Eu;St.Memo=Cu;St.Portal=Ud;St.Profiler=vu;St.StrictMode=xu;St.Suspense=Su;St.SuspenseList=wu;St.isContextConsumer=function(e){return Co(e)===Tu};St.isContextProvider=function(e){return Co(e)===Pu};St.isElement=function(e){return typeof e=="object"&&e!==null&&e.$$typeof===Vd};St.isForwardRef=function(e){return Co(e)===_u};St.isFragment=function(e){return Co(e)===bu};St.isLazy=function(e){return Co(e)===Eu};St.isMemo=function(e){return Co(e)===Cu};St.isPortal=function(e){return Co(e)===Ud};St.isProfiler=function(e){return Co(e)===vu};St.isStrictMode=function(e){return Co(e)===xu};St.isSuspense=function(e){return Co(e)===Su};St.isSuspenseList=function(e){return Co(e)===wu};St.isValidElementType=function(e){return typeof e=="string"||typeof e=="function"||e===bu||e===vu||e===xu||e===Su||e===wu||e===sx||typeof e=="object"&&e!==null&&(e.$$typeof===Eu||e.$$typeof===Cu||e.$$typeof===Pu||e.$$typeof===Tu||e.$$typeof===_u||e.$$typeof===l1||e.getModuleId!==void 0)};St.typeOf=Co});var lx=er((WL,ax)=>{"use strict";ax.exports=ix()});var Ux=er(ht=>{"use strict";var Tr=typeof Symbol=="function"&&Symbol.for,om=Tr?Symbol.for("react.element"):60103,nm=Tr?Symbol.for("react.portal"):60106,Fu=Tr?Symbol.for("react.fragment"):60107,Vu=Tr?Symbol.for("react.strict_mode"):60108,Uu=Tr?Symbol.for("react.profiler"):60114,Zu=Tr?Symbol.for("react.provider"):60109,Wu=Tr?Symbol.for("react.context"):60110,sm=Tr?Symbol.for("react.async_mode"):60111,Hu=Tr?Symbol.for("react.concurrent_mode"):60111,Gu=Tr?Symbol.for("react.forward_ref"):60112,Ku=Tr?Symbol.for("react.suspense"):60113,aE=Tr?Symbol.for("react.suspense_list"):60120,qu=Tr?Symbol.for("react.memo"):60115,Yu=Tr?Symbol.for("react.lazy"):60116,lE=Tr?Symbol.for("react.block"):60121,cE=Tr?Symbol.for("react.fundamental"):60117,uE=Tr?Symbol.for("react.responder"):60118,pE=Tr?Symbol.for("react.scope"):60119;function io(e){if(typeof e=="object"&&e!==null){var t=e.$$typeof;switch(t){case om:switch(e=e.type,e){case sm:case Hu:case Fu:case Uu:case Vu:case Ku:return e;default:switch(e=e&&e.$$typeof,e){case Wu:case Gu:case Yu:case qu:case Zu:return e;default:return t}}case nm:return t}}}function Vx(e){return io(e)===Hu}ht.AsyncMode=sm;ht.ConcurrentMode=Hu;ht.ContextConsumer=Wu;ht.ContextProvider=Zu;ht.Element=om;ht.ForwardRef=Gu;ht.Fragment=Fu;ht.Lazy=Yu;ht.Memo=qu;ht.Portal=nm;ht.Profiler=Uu;ht.StrictMode=Vu;ht.Suspense=Ku;ht.isAsyncMode=function(e){return Vx(e)||io(e)===sm};ht.isConcurrentMode=Vx;ht.isContextConsumer=function(e){return io(e)===Wu};ht.isContextProvider=function(e){return io(e)===Zu};ht.isElement=function(e){return typeof e=="object"&&e!==null&&e.$$typeof===om};ht.isForwardRef=function(e){return io(e)===Gu};ht.isFragment=function(e){return io(e)===Fu};ht.isLazy=function(e){return io(e)===Yu};ht.isMemo=function(e){return io(e)===qu};ht.isPortal=function(e){return io(e)===nm};ht.isProfiler=function(e){return io(e)===Uu};ht.isStrictMode=function(e){return io(e)===Vu};ht.isSuspense=function(e){return io(e)===Ku};ht.isValidElementType=function(e){return typeof e=="string"||typeof e=="function"||e===Fu||e===Hu||e===Uu||e===Vu||e===Ku||e===aE||typeof e=="object"&&e!==null&&(e.$$typeof===Yu||e.$$typeof===qu||e.$$typeof===Zu||e.$$typeof===Wu||e.$$typeof===Gu||e.$$typeof===cE||e.$$typeof===uE||e.$$typeof===pE||e.$$typeof===lE)};ht.typeOf=io});var Wx=er((E5,Zx)=>{"use strict";Zx.exports=Ux()});var Jx=er((R5,Xx)=>{"use strict";var im=Wx(),fE={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},dE={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},mE={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},qx={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},am={};am[im.ForwardRef]=mE;am[im.Memo]=qx;function Hx(e){return im.isMemo(e)?qx:am[e.$$typeof]||fE}var hE=Object.defineProperty,yE=Object.getOwnPropertyNames,Gx=Object.getOwnPropertySymbols,gE=Object.getOwnPropertyDescriptor,bE=Object.getPrototypeOf,Kx=Object.prototype;function Yx(e,t,r){if(typeof t!="string"){if(Kx){var o=bE(t);o&&o!==Kx&&Yx(e,o,r)}var n=yE(t);Gx&&(n=n.concat(Gx(t)));for(var s=Hx(e),i=Hx(t),a=0;a<n.length;++a){var l=n[a];if(!dE[l]&&!(r&&r[l])&&!(i&&i[l])&&!(s&&s[l])){var c=gE(t,l);try{hE(e,l,c)}catch{}}}}return e}Xx.exports=Yx});K();function Yg(e){return{render:function(t){Kc(t,e)},unmount:function(){qc(e)}}}K();var lu=$c(Pd());K();Vi();Vi();var oC=Symbol.for("pv"),nC=0;function b(e,t,r,o,n,s){t||(t={});var i,a,l=t;if("ref"in l&&typeof e!="function")for(a in l={},t)a=="ref"?i=t[a]:l[a]=t[a];var c={type:e,props:l,key:r,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:oC,__v:--nC,__i:-1,__u:0};return(n||s)&&(c.__source=n,c.__self=s),Ne.vnode&&Ne.vnode(c),c}var yl=Je({lastError:null,lastMessage:null,readyState:lu.ReadyState.UNINSTANTIATED});function _d({url:e,children:t}){let[r,o]=ie(null),{lastMessage:n,readyState:s}=(0,lu.default)(e,{reconnectAttempts:10,reconnectInterval:3e4,retryOnError:!0,onClose:i=>o({code:i.code,reason:i.reason})});return b(yl.Provider,{value:{lastError:r,lastMessage:n,readyState:s},children:t})}K();function pb(e,t){return typeof t=="bigint"?t.toString():t}var wd=class{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}};function fb(e){return new wd(e)}function uu(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function db(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function mb(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}var Cd="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function cu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hb(e){if(cu(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(cu(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Ed(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pu(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function qo(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function yb(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}function Dn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function gb(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Hs(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function gl(e){return typeof e=="string"?e:e?.message}function Rd(e){let t=[];for(let r of e??[]){let o=r._zod.def;if(!/_(length|size)$|_equals$/.test(o.check))break;let n=o.maximum??o.length??o.size;n>=0&&t.push([n,r])}return t}function fu(e,t,r){var o;for(let n=t;n<e.length;n++)(o=e[n]).schema??(o.schema=r)}function Bn(e,t,r){var o;let n=e.inst?._zod?.traits;n?.has("$ZodType")&&(n.has("$ZodCheck")?(o=e).schema??(o.schema=e.inst):e.schema=e.inst);let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:gl(e.inst?._zod.def?.error?.(e))??gl(s?.(e))??gl(t?.error?.(e))??gl(r.customError?.(e))??gl(r.localeError?.(e))??"Invalid input",a={};for(let l of Object.keys(e))l==="inst"||l==="schema"||l==="continue"||l==="input"||l==="__proto__"||(a[l]=e[l]);return a.path??(a.path=[]),a.message=i,t?.reportInput&&(a.input=e.input),a}function bb(e,t){for(let r in t){let o=Object.getOwnPropertyDescriptor(t,r);o.get?Object.defineProperty(e,r,{...o,enumerable:!1}):sC(e,r,o.value)}}function Ws(e,t,r,o=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:o,value:r}),r}function xb(e,t,r){return Ws(e,t,r,!1)}function sC(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:Ws(this,t,r.bind(this))},set(o){Ws(this,t,o)}})}function iC(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var Sd,ys=!1,aC={configurable:!0,get(){ys=!0}};function Yr(e,t,r){let o=Object.getPrototypeOf(e._zod);if(t in o&&Sd!==e._zod){Sd=void 0;return}Sd=e._zod,Object.defineProperty(o,t,{configurable:!0,get(){Object.defineProperty(this,t,aC);let n=ys;ys=!1;try{let s=r(this);return ys?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s}),ys=ys||n,s}catch(s){throw delete this[t],ys=ys||n,s}},set(n){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:n})}})}function vb(e,t,r,o){let n=iC(e,t);n&&Object.defineProperty(n,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:o,value:void 0};return Object.defineProperty(this,t,s),s.value=r(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:o,value:s})}})}var Tb;var kd={value:void 0,enumerable:!1},Pb="captureStackTrace"in Error?Error:null;function lC(e){let t=Pb;if(t){let r=t.stackTraceLimit;if(typeof r=="number"){try{t.stackTraceLimit=0}catch{return Pb=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function it(e,t,r,o){let n={};function s(m){this.def=m,this.constr=f,this.traits=new Set}s.prototype=n;let i=r,a=i&&new WeakSet;function l(m,p){if(m._zod){if(m._zod.traits.has(e))return}else{kd.value=new s(p);try{Object.defineProperty(m,"_zod",kd)}finally{kd.value=void 0}}if(m._zod.traits.add(e),t(m,p),a){let x=Object.getPrototypeOf(m),T=m._zod.constr.prototype,S=x;for(;S&&S!==T;)S=Object.getPrototypeOf(S);let v=S??x;a.has(v)||(a.add(v),bb(v,i))}let y=f.prototype;for(let x in y)Object.prototype.hasOwnProperty.call(y,x)&&(x in m||(m[x]=y[x].bind(m)))}let c=o?.Parent??Object;class u extends c{}Object.defineProperty(u,"name",{value:e});function f(m){let p=o?.Parent?lC(u):this;l(p,m);let y=p._zod.deferred;if(y){for(let T of y)T();p._zod.deferred=void 0}let x=globalThis.__zod_globalConfig?.postProcessor;return x&&x(p),p}return Object.defineProperty(f,"init",{value:l}),Object.defineProperty(f,Symbol.hasInstance,{value:m=>o?.Parent&&m instanceof o.Parent?!0:m?._zod?.traits?.has(e)}),Object.defineProperty(f,"name",{value:e}),f}var Pn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(Tb=globalThis).__zod_globalConfig??(Tb.__zod_globalConfig={});var Xi=globalThis.__zod_globalConfig;function Ln(e){return e&&Object.assign(Xi,e),Xi}function cC(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,pb,2)),e.message}function uC(e){this._zod.message=e}var pC={get:cC,set:uC,enumerable:!0,configurable:!0},Od={value:void 0,enumerable:!1},Sb=new WeakSet([Object.prototype,Error.prototype]),wb=(e,t)=>{e.name="$ZodError",Od.value=t,Object.defineProperty(e,"issues",Od),Od.value=void 0,Object.defineProperty(e,"message",pC);let r=Object.getPrototypeOf(e);Sb.has(r)||(Sb.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let o=()=>this.message;return Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0})}}))},e2=it("$ZodError",wb),Ji=it("$ZodError",wb,void 0,{Parent:Error});function dC(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Cb=e=>{let t=(r,o,n,s)=>{let i=n?{...n,async:!1}:{async:!1},a=r._zod.run({value:o,issues:[]},i);if(a instanceof Promise)throw new Pn;if(a.issues.length){let l=new(s?.Err??e)(a.issues.map(c=>Bn(c,i,Ln())));throw Cd(l,s?.callee??t),l}return a.value};return t},Ad=Cb(Ji),mC=e=>{let t=async(r,o,n,s)=>{let i=n?{...n,async:!0}:{async:!0},a=r._zod.run({value:o,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let l=new(s?.Err??e)(a.issues.map(c=>Bn(c,i,Ln())));throw Cd(l,s?.callee??t),l}return a.value};return t},Md=mC(Ji),hC=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new Pn;return s.issues.length?Eb(e,s.issues,n):{success:!0,data:s.value}},$d=hC(Ji);function Eb(e,t,r){let o;return{success:!1,get error(){return o||(o=new e(t.map(n=>Bn(n,r,Ln()))),t=void 0,r=void 0),o},set error(n){o=n,t=void 0,r=void 0}}}var yC=e=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?Eb(e,s.issues,n):{success:!0,data:s.value}},Id=yC(Ji),gC=Symbol.for("zod.compile.invalid"),bC=Symbol.for("zod.compile.fallback"),So=((e,t,r)=>{let o=e._zod.bag.validator;if(o!==void 0){if(o(t)!==gC)return!0;if(o.definite===!0&&r===void 0)return!1}return xC(e,t,r)});function xC(e,t,r){let o=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},n=e._zod.bag.fallbackRun,s;if(n?(o[bC]=!0,s=n({value:t,issues:[]},o)):s=e._zod.run({value:t,issues:[]},o),s instanceof Promise)throw new Pn;return s.issues.length===0}var vC=e=>{let t=Cb(e),r=(o,n,s,i)=>t(o,n,s,dC(r,i));return r},Nd=vC(Ji);var Rb=/^[\s\S]{0,}$/;var zd=/^-?\d+(?:\.\d+)?$/;var Ob={major:4,minor:6,patch:7};var Xr=it("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ob;let o=e._zod.def.checks,n=e._zod.traits.has("$ZodCheck")?[e,...o??[]]:o?.length?[...o]:[];for(let s of n)for(let i of s._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(a,l,c)=>{if(a.memo)return a;let u=Dn(a),f;for(let m of l){if(m._zod.def.when){if(gb(a)||!m._zod.def.when(a))continue}else if(u)continue;let p=a.issues.length,y=m._zod.check(a);if(y instanceof Promise&&c?.async===!1)throw new Pn;if(f||y instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await y,a.issues.length!==p&&(fu(a.issues,p,e),u||(u=Dn(a,p)))});else{if(a.issues.length===p)continue;fu(a.issues,p,e),u||(u=Dn(a,p))}}return f?f.then(()=>a):a},i=(a,l,c)=>{if(Dn(a))return a.aborted=!0,a;let u=s(l,n,c);if(u instanceof Promise){if(c.async===!1)throw new Pn;return u.then(f=>e._zod.parse(f,c))}return e._zod.parse(u,c)};e._zod.run=(a,l)=>{if(l.skipChecks)return e._zod.parse(a,l);if(l.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...l,skipChecks:!0});return u instanceof Promise?u.then(f=>i(f,a,l)):i(u,a,l)}let c=e._zod.parse(a,l);if(c instanceof Promise){if(l.async===!1)throw new Pn;return c.then(u=>s(u,n,l))}return s(c,n,l)}}},{get"~standard"(){return xb(this,"~standard",_C(this))},set"~standard"(e){Ws(this,"~standard",e)}}),Ib=(e,t)=>e.issues.length?{issues:e.issues.map(r=>Bn(r,t,Ln()))}:{value:e.value};async function PC(e,t){let r={async:!0};return Ib(await e._zod.run({value:t,issues:[]},r),r)}function _C(e){return{validate:t=>{let r={async:!1};try{let o=e._zod.run({value:t,issues:[]},r);if(!(o instanceof Promise))return Ib(o,r)}catch{}return PC(e,t)},vendor:"zod",version:1}}var Nb=it("$ZodString",(e,t)=>{Xr.init(e,t),e._zod.pattern=t.pattern??Rb,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}});var zb=it("$ZodNumber",(e,t)=>{Xr.init(e,t),e._zod.pattern=zd,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let s=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:String(n):void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...s?{received:s}:{}}),r}});var Db=it("$ZodAny",(e,t)=>{Xr.init(e,t),e._zod.parse=r=>r}),Bb=it("$ZodUnknown",(e,t)=>{Xr.init(e,t),e._zod.parse=r=>r}),Lb=it("$ZodNever",(e,t)=>{Xr.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function SC(e,t){let r=Rd(e._zod.def.checks);if(!r.length)return;let o=Math.min(...r.map(s=>s[0])),n=e._zod.parse;e._zod.parse=(s,i)=>{let a=t(s.value);if(a>o&&!i?.skipChecks&&i?.direction!=="backward"){for(let[l,c]of Rd(e._zod.def.checks))if(a>l&&c._zod.def.when(s)){let u=s.issues.length;return c._zod.check(s),s.issues[u].continue=!1,fu(s.issues,u,e),s}}return n(s,i)}}var wC=e=>Array.isArray(e)?e.length:-1;function Ab(e,t,r){e.issues.length&&t.issues.push(...Hs(r,e.issues)),t.value[r]=e.value}var jb=it("$ZodArray",(e,t)=>{Xr.init(e,t);let r=Xi.memoizer;r?.attach(e),e._zod.parse=(o,n)=>{let s=o.value;if(!Array.isArray(s))return o.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),o;o.value=r?r.alloc(e,o,Array(s.length),n):Array(s.length);let i=[],a=n?.abortEarly;for(let l=0;l<s.length;l++){let c=s[l],u=t.element._zod.run({value:c,issues:[]},n);if(u instanceof Promise)i.push(u.then(f=>Ab(f,o,l)));else if(Ab(u,o,l),a&&u.issues.length!==0&&Dn(u))break}return i.length?Promise.all(i).then(()=>o):o},SC(e,wC)});function du(e,t,r,o,n,s){let i=r in o,a=s==="optional";if(!(!i&&a&&n==="optional")){if(e.issues.length){if(n!==void 0&&a&&!i)return;t.issues.push(...Hs(r,e.issues))}if(!i&&n===void 0){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?(i||n==="defaulted"&&!a)&&(t.value[r]=void 0):t.value[r]=e.value}}var CC=[];function EC(e){let t=Object.keys(e.shape),r=Object.getOwnPropertySymbols(e.shape),o=r.length?r:CC,n=o.length?[...t,...o]:t;for(let i of n)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(i)}": expected a Zod schema`);let s=yb(e.shape);return{...e,allKeys:n,symbolKeys:o,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function RC(e,t,r,o,n,s,i){let a=[],l=n.keySet,c=n.catchall._zod,u=c.def.type,f=c.optin,m=c.optout,p=0;for(let y in t){if(i&&r.issues.length!==p){if(Dn(r,p))break;p=r.issues.length}if(l.has(y))continue;if(y==="__proto__"){u==="never"&&a.push(y);continue}if(u==="never"){a.push(y);continue}let x=c.run({value:t[y],issues:[]},o);x instanceof Promise?e.push(x.then(T=>du(T,r,y,t,f,m))):du(x,r,y,t,f,m)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s,continue:!0}),e.length?Promise.all(e).then(()=>r):r}var Fb=it("$ZodObject",(e,t)=>{Xr.init(e,t);let r=Object.getOwnPropertyDescriptor(t,"shape"),o=r?.get?r.get.raw:t.shape??{};if(o){let c=()=>{let u={...o};return Object.defineProperty(t,"shape",{value:u}),c.raw=u,u};c.raw=o,Object.defineProperty(t,"shape",{get:c})}let n=fb(()=>EC(t));Yr(e,"propValues",c=>{let u=c.def.shape,f={};for(let m in u){let p=u[m]._zod;if(p.values){Object.prototype.hasOwnProperty.call(f,m)||db(f,m,new Set);for(let y of p.values)f[m].add(y);p.optin!==void 0&&f[m].add(void 0)}}return f});let s=cu,i=t.catchall,a,l=Xi.memoizer;l?.attach(e),e._zod.parse=(c,u)=>{a??(a=n.value);let f=c.value;if(!s(f))return c.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),c;c.value=l?l.alloc(e,c,{},u):{};let m=[],p=a.shape,y=u?.abortEarly,x=c.issues.length;for(let T of a.allKeys){if(y&&c.issues.length!==x){if(Dn(c,x))break;x=c.issues.length}if(T==="__proto__")continue;let S=p[T],v=S._zod.optin,R=S._zod.optout,P=S._zod.run({value:f[T],issues:[]},u);P instanceof Promise?m.push(P.then(O=>du(O,c,T,f,v,R))):du(P,c,T,f,v,R)}return i?RC(m,f,c,u,n.value,e,y===!0):m.length?Promise.all(m).then(()=>c):c}});function Mb(e,t,r,o){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let n=e.filter(s=>!Dn(s));return n.length===1?(t.value=n[0].value,n[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(i=>Bn(i,o,Ln())))}),t)}var Vb=it("$ZodUnion",(e,t)=>{Xr.init(e,t),Yr(e,"optin",o=>o.def.options.some(n=>n._zod.optin==="defaulted")?"defaulted":o.def.options.some(n=>n._zod.optin!==void 0)?"optional":void 0),Yr(e,"optout",o=>o.def.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Yr(e,"values",o=>{if(o.def.options.every(n=>n._zod.values))return new Set(o.def.options.flatMap(n=>Array.from(n._zod.values)))}),Yr(e,"pattern",o=>{if(o.def.options.every(n=>n._zod.pattern)){let n=o.def.options.map(s=>s._zod.pattern);return new RegExp(`^(${n.map(s=>uu(s.source)).join("|")})$`)}});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let s=!1,i=[];for(let a of t.options){let l=a._zod.run({value:o.value,issues:[]},n);if(l instanceof Promise)i.push(l),s=!0;else{if(l.issues.length===0)return l;i.push(l)}}return s?Promise.all(i).then(a=>Mb(a,o,e,n)):Mb(i,o,e,n)}});var Ub=it("$ZodRecord",(e,t)=>{Xr.init(e,t);let r=Xi.memoizer;r?.attach(e),e._zod.parse=(o,n)=>{let s=o.value;if(!hb(s))return o.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),o;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){o.value=r?r.alloc(e,o,{},n):{};let l=new Set;for(let u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){if(l.add(typeof u=="number"?u.toString():u),u==="__proto__")continue;let f=t.keyType._zod.run({value:u,issues:[]},n);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){o.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(y=>Bn(y,n,Ln())),input:u,path:[u],inst:e});continue}let m=f.value;if(m==="__proto__")continue;let p=t.valueType._zod.run({value:s[u],issues:[]},n);p instanceof Promise?i.push(p.then(y=>{y.issues.length&&o.issues.push(...Hs(u,y.issues)),o.value[m]=y.value})):(p.issues.length&&o.issues.push(...Hs(u,p.issues)),o.value[m]=p.value)}let c;for(let u in s)if(!l.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;o.value[u]=s[u]}else c=c??[],c.push(u);c&&c.length>0&&o.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}else{o.value=r?r.alloc(e,o,{},n):{};let l;for(let c of Reflect.ownKeys(s)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(s,c))continue;let u=t.keyType._zod.run({value:c,issues:[]},n);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&zd.test(c)&&u.issues.length){let y=t.keyType._zod.run({value:Number(c),issues:[]},n);if(y instanceof Promise)throw new Error("Async schemas not supported in object keys currently");y.issues.length===0&&(u=y)}if(u.issues.length){t.mode==="loose"?o.value[c]=s[c]:a?(l=l??[],l.push(c)):o.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(y=>Bn(y,n,Ln())),input:c,path:[c],inst:e});continue}let m=u.value;if(m==="__proto__")continue;let p=t.valueType._zod.run({value:s[c],issues:[]},n);p instanceof Promise?i.push(p.then(y=>{y.issues.length&&o.issues.push(...Hs(c,y.issues)),o.value[m]=y.value})):(p.issues.length&&o.issues.push(...Hs(c,p.issues)),o.value[m]=p.value)}l&&l.length>0&&o.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:l,continue:!0})}return i.length?Promise.all(i).then(()=>o):o}});var Zb=it("$ZodLiteral",(e,t)=>{Xr.init(e,t);let r=new Set(t.values);e._zod.values=r,Yr(e,"pattern",o=>{let n=o.def.values;return new RegExp(n.length?`^(${n.map(s=>typeof s=="string"?Ed(s):s?Ed(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,n)=>{let s=o.value;return r.has(s)||o.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),o}});function $b(e,t){return e.value=t.issues.length?void 0:t.value,e}var Wb=it("$ZodOptional",(e,t)=>{Xr.init(e,t),Yr(e,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",Yr(e,"values",r=>{let o=r.def.innerType._zod.values;return o?new Set([...o,void 0]):void 0}),Yr(e,"pattern",r=>{let o=r.def.innerType._zod.pattern;return o?new RegExp(`^(${uu(o.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let n=t.innerType._zod.run({value:r.value,issues:[]},o);return n instanceof Promise?n.then(s=>$b(r,s)):$b(r,n)}return t.innerType._zod.run(r,o)}});var Hb=it("$ZodNullable",(e,t)=>{Xr.init(e,t),Yr(e,"optin",r=>r.def.innerType._zod.optin),Yr(e,"optout",r=>r.def.innerType._zod.optout),Yr(e,"pattern",r=>{let o=r.def.innerType._zod.pattern;return o?new RegExp(`^(${uu(o.source)}|null)$`):void 0}),Yr(e,"values",r=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>r.value===null?r:t.innerType._zod.run(r,o)});function Gb(e){return e.checks&&(e.checks=[...e.checks]),e}function Kb(e,t){return new e(Gb({type:"string",...qo(t)}))}function qb(e,t){return new e(Gb({type:"number",checks:[],...qo(t)}))}function Yb(e){return new e({type:"any"})}function Xb(e){return new e({type:"unknown"})}function Jb(e,t){return new e({type:"never",...qo(t)})}var wo=it("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Xr.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){Ws(this,"with",e)},parse(e,t){return Ad(this,e,t,{callee:this.parse})},parseAsync(e,t){return Md(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return $d(this,e,t)},safeParseAsync(e,t){return Id(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0})},clone(e,t){return pu(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),AC=it("ZodMiniString",(e,t)=>{Nb.init(e,t),wo.init(e,t)});function $r(e){return Kb(AC,e)}var MC=it("ZodMiniNumber",(e,t)=>{zb.init(e,t),wo.init(e,t)});function Ir(e){return qb(MC,e)}var $C=it("ZodMiniAny",(e,t)=>{Db.init(e,t),wo.init(e,t)});function mu(){return Yb($C)}var IC=it("ZodMiniUnknown",(e,t)=>{Bb.init(e,t),wo.init(e,t)});function NC(){return Xb(IC)}var zC=it("ZodMiniNever",(e,t)=>{Lb.init(e,t),wo.init(e,t)});function DC(e){return Jb(zC,e)}var BC=it("ZodMiniArray",(e,t)=>{jb.init(e,t),wo.init(e,t)});function hu(e,t){return new BC({type:"array",element:e,...qo(t)})}var Qb=it("ZodMiniObject",(e,t)=>{Fb.init(e,t),wo.init(e,t),vb(e,"shape",r=>r._zod.def.shape,!1)});function Vr(e,t){return new Qb({type:"object",shape:e,catchall:DC(),...qo(t)})}function ex(e,t){return new Qb({type:"object",shape:e,catchall:NC(),...qo(t)})}function tx(e,t){return e.clone(mb(e._zod.def,{catchall:t}))}var LC=it("ZodMiniUnion",(e,t)=>{Vb.init(e,t),wo.init(e,t)});function yu(e,t){return new LC({type:"union",options:e,...qo(t)})}var jC=it("ZodMiniRecord",(e,t)=>{Ub.init(e,t),wo.init(e,t)});function gu(e,t,r){return new jC({type:"record",keyType:e,valueType:t,...qo(r),partial:!0})}var FC=it("ZodMiniLiteral",(e,t)=>{Zb.init(e,t),wo.init(e,t)});function Rr(e,t){return new FC({type:"literal",values:Array.isArray(e)?e:[e],...qo(t)})}var VC=it("ZodMiniOptional",(e,t)=>{Wb.init(e,t),wo.init(e,t)});function Dd(e){return new VC({type:"optional",innerType:e})}var UC=it("ZodMiniNullable",(e,t)=>{Hb.init(e,t),wo.init(e,t)});function Bd(e){return new UC({type:"nullable",innerType:e})}var ZC=gu($r(),mu()),Gs;(n=>{n.UNKNOWN_SERVICE_NAME="unknown";function t(s){return s["service.name"]??n.UNKNOWN_SERVICE_NAME}n.name=t,n.UNKNOWN_SERVICE_INSTANCE_ID="unknown";function o(s){return s["service.instance.id"]??n.UNKNOWN_SERVICE_INSTANCE_ID}n.instanceId=o})(Gs||={});var Ld=ex({"service.name":Dd($r()),"service.instance.id":Dd($r())}),WC=Vr({name:$r(),version:$r()}),uL=gu($r(),mu()),HC=tx(Vr({name:$r()}),mu()),GC=Vr({attrs:HC,yValues:hu(Bd(Ir()))}),KC=Vr({xValues:hu(Ir()),series:hu(GC)}),qC=gu(Rr(["heapSize","heapProfSample","gcCopied","gcSlop","gcFragmentation"]),Bd(KC)),rx=Vr({resource:ZC,scope:WC,telemetry:qC});var gs=Je({lastExportRequest:null});function jd({children:e}){let t=Se(yl),[r,o]=ie(null);return ce(()=>{let n=t.lastMessage;if(n!==null)try{let s=JSON.parse(n.data);o(Nd(rx,s))}catch(s){console.error(s)}},[t.lastMessage]),b(gs.Provider,{value:{lastExportRequest:r},children:e})}K();var xl=Je({refresh:!0,toggleRefresh:()=>{}});function Fd({children:e}){let[t,r]=ie(!0),o=()=>r(!t);return b(xl.Provider,{value:{refresh:t,toggleRefresh:o},children:e})}K();K();function ox(e){var t,r,o="";if(typeof e=="string"||typeof e=="number")o+=e;else if(typeof e=="object")if(Array.isArray(e)){var n=e.length;for(t=0;t<n;t++)e[t]&&(r=ox(e[t]))&&(o&&(o+=" "),o+=r)}else for(r in e)e[r]&&(o&&(o+=" "),o+=r);return o}function YC(){for(var e,t,r=0,o="",n=arguments.length;r<n;r++)(e=arguments[r])&&(t=ox(e))&&(o&&(o+=" "),o+=t);return o}var he=YC;function ke(e,t,r=void 0){let o={};for(let n in e){let s=e[n],i="",a=!0;for(let l=0;l<s.length;l+=1){let c=s[l];c&&(i+=(a===!0?"":" ")+t(c),a=!1,r&&r[c]&&(i+=" "+r[c]))}o[n]=i}return o}function Nr(e,...t){let r=new URL(`https://mui.com/production-error/?code=${e}`);return t.forEach(o=>r.searchParams.append("args[]",o)),`Minified MUI error #${e}; visit ${r} for the full message.`}function jn(e){if(typeof e!="string")throw new Error(Nr(7));return e.charAt(0).toUpperCase()+e.slice(1)}var Te=jn;function XC(e){return typeof e.main=="string"}function JC(e,t=[]){if(!XC(e))return!1;for(let r of t)if(!e.hasOwnProperty(r)||typeof e[r]!="string")return!1;return!0}function sr(e=[]){return([,t])=>t&&JC(t,e)}K();function QC(e){return e!=="ownerState"&&e!=="theme"&&e!=="sx"&&e!=="as"}var nx=QC;var e1=e=>nx(e)&&e!=="classes",bs=e1;function Yo(e,t){let r=Array.isArray(t),o=Array.isArray(e);return s1(t)?t:i1(e)?Qi(t):r&&o?o1(e,t):r!==o?Qi(t):a1(e,t)}function t1(e){let t=0,r=e.length,o=new Array(r);for(t=0;t<r;t+=1)o[t]=Qi(e[t]);return o}function r1(e){let t={};for(let r in e)r==="__proto__"||r==="constructor"||r==="prototype"||(t[r]=Qi(e[r]));return t}function o1(e,t){let r=e.length;for(let o=0;o<t.length;o+=1)e[r+o]=Qi(t[o]);return e}function n1(e){return typeof e=="object"&&e!==null&&!(e instanceof RegExp)&&!(e instanceof Date)}function s1(e){return typeof e!="object"||e===null}function i1(e){return typeof e!="object"||e===null||e instanceof RegExp||e instanceof Date}function Qi(e){return n1(e)?Array.isArray(e)?t1(e):r1(e):e}function a1(e,t){for(let r in t)r==="__proto__"||r==="constructor"||r==="prototype"||(r in e?e[r]=Yo(e[r],t[r]):e[r]=Qi(t[r]));return e}function ea(e){if(e==null)return!0;for(let t in e)return!1;return!0}K();var Zd=$c(lx(),1);function Xo(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function cx(e){if(Rt(e)||(0,Zd.isValidElementType)(e)||!Xo(e))return e;let t={};return Object.keys(e).forEach(r=>{t[r]=cx(e[r])}),t}function Dt(e,t,r={clone:!0}){let o=r.clone?{...e}:e;return Xo(e)&&Xo(t)&&Object.keys(t).forEach(n=>{Rt(t[n])||(0,Zd.isValidElementType)(t[n])?o[n]=t[n]:Xo(t[n])&&Object.prototype.hasOwnProperty.call(e,n)&&Xo(e[n])?o[n]=Dt(e[n],t[n],r):r.clone?o[n]=Xo(t[n])?cx(t[n]):t[n]:o[n]=t[n]}),o}var ux=/min-width:\s*([0-9.]+)/;function Ru(e,t){if(!e.containerQueries||!c1(t))return t;let r=[];for(let n in t)n.startsWith("@container")&&r.push(n);r.sort((n,s)=>+(n.match(ux)?.[1]||0)-+(s.match(ux)?.[1]||0));let o=t;for(let n=0;n<r.length;n+=1){let s=r[n],i=o[s];delete o[s],o[s]=i}return o}function c1(e){for(let t in e)if(t.startsWith("@container"))return!0;return!1}function ku(e,t){return t==="@"||t.startsWith("@")&&(e.some(r=>t.startsWith(`@${r}`))||!!t.match(/^@\d/))}function Wd(e,t){let r=t.match(/^@([^/]+)?\/?(.+)?$/);if(!r)return null;let[,o,n]=r,s=Number.isNaN(+o)?o||0:+o;return e.containerQueries(n).up(s)}function Ou(e){let t=(s,i)=>s.replace("@media",i?`@container ${i}`:"@container");function r(s,i){s.up=(...a)=>t(e.breakpoints.up(...a),i),s.down=(...a)=>t(e.breakpoints.down(...a),i),s.between=(...a)=>t(e.breakpoints.between(...a),i),s.only=(...a)=>t(e.breakpoints.only(...a),i),s.not=(...a)=>{let l=t(e.breakpoints.not(...a),i);return l.includes("not all and")?l.replace("not all and ","").replace("min-width:","width<").replace("max-width:","width>").replace("and","or"):l}}let o={},n=s=>(r(o,s),o);return r(n),{...e,containerQueries:n}}var u1=e=>{let t=Object.keys(e).map(r=>({key:r,val:e[r]}))||[];return t.sort((r,o)=>r.val-o.val),t.reduce((r,o)=>({...r,[o.key]:o.val}),{})};function vl(e){let{values:t={xs:0,sm:600,md:900,lg:1200,xl:1536},unit:r="px",step:o=5,...n}=e,s=u1(t),i=Object.keys(s);function a(p){return`@media (min-width:${typeof t[p]=="number"?t[p]:p}${r})`}function l(p){return`@media (max-width:${(typeof t[p]=="number"?t[p]:p)-o/100}${r})`}function c(p,y){let x=i.indexOf(y);return`@media (min-width:${typeof t[p]=="number"?t[p]:p}${r}) and (max-width:${(x!==-1&&typeof t[i[x]]=="number"?t[i[x]]:y)-o/100}${r})`}function u(p){return i.indexOf(p)+1<i.length?c(p,i[i.indexOf(p)+1]):a(p)}function f(p){let y=i.indexOf(p);return y===0?a(i[1]):y===i.length-1?l(i[y]):c(p,i[i.indexOf(p)+1]).replace("@media","@media not all and")}let m=[];for(let p=0;p<i.length;p+=1)m.push(a(i[p]));return{keys:i,values:s,up:a,down:l,between:c,only:u,not:f,unit:r,internal_mediaKeys:m,...n}}var p1={},Pl={xs:0,sm:600,md:900,lg:1200,xl:1536},Tl=vl({values:Pl}),f1={containerQueries:e=>({up:t=>{let r=typeof t=="number"?t:Pl[t]||t;return typeof r=="number"&&(r=`${r}px`),e?`@container ${e} (min-width:${r})`:`@container (min-width:${r})`}})};function _n(e,t,r){let o={};return ta(o,e.theme,t,(n,s,i)=>{let a=r(s,i);n?o[n]=a:Yo(o,a)})}function ta(e,t,r,o){if(t??=p1,Array.isArray(r)){let n=t.breakpoints??Tl;for(let s=0;s<r.length;s+=1)Hd(e,n.up(n.keys[s]),r[s],void 0,o);return e}if(typeof r=="object"){let n=t.breakpoints??Tl,s=n.values??Pl;for(let i in r)if(ku(n.keys,i)){let a=Wd(t.containerQueries?t:f1,i);a&&Hd(e,a,r[i],i,o)}else if(i in s){let a=n.up(i);Hd(e,a,r[i],i,o)}else{let a=i;e[a]=r[a]}return e}return o(void 0,r),e}function Hd(e,t,r,o,n){e[t]??={},n(t,r,o)}function px(e=Tl){let{internal_mediaKeys:t}=e,r={};for(let o=0;o<t.length;o+=1)r[t[o]]={};return r}function Gd(e,t){let r=e.internal_mediaKeys;for(let o=0;o<r.length;o+=1){let n=r[o];ea(t[n])&&delete t[n]}return t}function fx(e,t){if(Array.isArray(t))return!0;if(typeof t=="object"&&t!==null){for(let o=0;o<e.keys.length;o+=1)if(e.keys[o]in t)return!0;let r=Object.keys(t);for(let o=0;o<r.length;o+=1)if(ku(e.keys,r[o]))return!0}return!1}function Kd(e,t,r,o){let n;return typeof e=="function"?n=e(r):Array.isArray(e)?n=e[r]||r:typeof r=="string"?n=ra(e,r,!0,o)||r:n=r,t&&(n=t(n,r,e)),n}function ra(e,t,r=!0,o=void 0){if(!e||!t)return null;let n=t.split(".");if(e.vars&&r){let s=dx(e.vars,n,o);if(s!=null)return s}return dx(e,n,o)}function dx(e,t,r=void 0){let o,n=e,s=0;for(;s<t.length;){if(n==null)return n;o=n,n=n[t[s]],s+=1}if(r&&n===void 0){let i=t[t.length-1],a=`${r}${i==="default"?"":jn(i)}`;return o?.[a]}return n}function wt(e){let{prop:t,cssProperty:r=e.prop,themeKey:o,transform:n}=e,s=i=>{if(i[t]==null)return null;let a=i[t],l=i.theme,c=ra(l,o)||{};return _n(i,a,f=>{let m=Kd(c,n,f,t);return r===!1?m:{[r]:m}})};return s.propTypes={},s.filterProps=[t],s}var d1={internal_cache:{}},Au={m:"margin",p:"padding"},mx={t:"Top",r:"Right",b:"Bottom",l:"Left",x:["Left","Right"],y:["Top","Bottom"]},hx={marginX:"mx",marginY:"my",paddingX:"px",paddingY:"py"},_l={};for(let e in Au)_l[e]=[Au[e]];for(let e in Au)for(let t in mx){let r=Au[e],o=mx[t],n=Array.isArray(o)?o.map(s=>r+s):[r+o];_l[e+t]=n}for(let e in hx)_l[e]=_l[hx[e]];var qd=new Set(["m","mt","mr","mb","ml","mx","my","margin","marginTop","marginRight","marginBottom","marginLeft","marginX","marginY","marginInline","marginInlineStart","marginInlineEnd","marginBlock","marginBlockStart","marginBlockEnd"]),Yd=new Set(["p","pt","pr","pb","pl","px","py","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","paddingX","paddingY","paddingInline","paddingInlineStart","paddingInlineEnd","paddingBlock","paddingBlockStart","paddingBlockEnd"]),gx=new Set([...qd,...Yd]);function Ks(e,t,r,o){let n=ra(e,t,!0)??r;return typeof n=="number"||typeof n=="string"?s=>typeof s=="string"?s:typeof n=="string"?n.startsWith("var(")&&s===0?0:n.startsWith("var(")&&s===1?n:`calc(${s} * ${n})`:n*s:Array.isArray(n)?s=>{if(typeof s=="string")return s;let i=Math.abs(s),a=n[i];return s>=0?a:typeof a=="number"?-a:typeof a=="string"&&a.startsWith("var(")?`calc(-1 * ${a})`:`-${a}`}:typeof n=="function"?n:()=>{}}function Sl(e){return Ks(e,"spacing",8,"spacing")}function qs(e,t){return typeof t=="string"||t==null?t:e(t)}var yx=[""];function Xd(e,t){let r=e.theme??d1,o=r?.internal_cache?.unarySpacing??Sl(r),n={};for(let s in e){if(!t.has(s))continue;let i=_l[s]??(yx[0]=s,yx),a=e[s];ta(n,e.theme,a,(l,c)=>{let u=l?n[l]:n;for(let f=0;f<i.length;f+=1)u[i[f]]=qs(o,c)})}return n}function Jd(e){return Xd(e,qd)}Jd.propTypes={};Jd.filterProps=qd;var Kt=Jd;function Qd(e){return Xd(e,Yd)}Qd.propTypes={};Qd.filterProps=Yd;var qt=Qd;function bx(e){return Xd(e,gx)}bx.propTypes={};bx.filterProps=gx;function m1(...e){let t=e.reduce((o,n)=>(n.filterProps.forEach(s=>{o[s]=n}),o),{}),r=o=>{let n={};for(let s in o)t[s]&&Yo(n,t[s](o));return n};return r.propTypes={},r.filterProps=e.reduce((o,n)=>o.concat(n.filterProps),[]),r}var Fn=m1;function so(e){return typeof e!="number"?e:`${e}px solid`}function Eo(e,t){return wt({prop:e,themeKey:"borders",transform:t})}var h1=Eo("border",so),y1=Eo("borderTop",so),g1=Eo("borderRight",so),b1=Eo("borderBottom",so),x1=Eo("borderLeft",so),v1=Eo("borderColor"),T1=Eo("borderTopColor"),P1=Eo("borderRightColor"),_1=Eo("borderBottomColor"),S1=Eo("borderLeftColor"),w1=Eo("outline",so),C1=Eo("outlineColor"),wl=e=>{if(e.borderRadius!==void 0&&e.borderRadius!==null){let t=Ks(e.theme,"shape.borderRadius",4,"borderRadius"),r=o=>({borderRadius:qs(t,o)});return _n(e,e.borderRadius,r)}return null};wl.propTypes={};wl.filterProps=["borderRadius"];var _j=Fn(h1,y1,g1,b1,x1,v1,T1,P1,_1,S1,wl,w1,C1);var Cl=e=>{if(e.gap!==void 0&&e.gap!==null){let t=Ks(e.theme,"spacing",8,"gap"),r=o=>({gap:qs(t,o)});return _n(e,e.gap,r)}return null};Cl.propTypes={};Cl.filterProps=["gap"];var El=e=>{if(e.columnGap!==void 0&&e.columnGap!==null){let t=Ks(e.theme,"spacing",8,"columnGap"),r=o=>({columnGap:qs(t,o)});return _n(e,e.columnGap,r)}return null};El.propTypes={};El.filterProps=["columnGap"];var Rl=e=>{if(e.rowGap!==void 0&&e.rowGap!==null){let t=Ks(e.theme,"spacing",8,"rowGap"),r=o=>({rowGap:qs(t,o)});return _n(e,e.rowGap,r)}return null};Rl.propTypes={};Rl.filterProps=["rowGap"];var E1=wt({prop:"gridColumn"}),R1=wt({prop:"gridRow"}),k1=wt({prop:"gridAutoFlow"}),O1=wt({prop:"gridAutoColumns"}),A1=wt({prop:"gridAutoRows"}),M1=wt({prop:"gridTemplateColumns"}),$1=wt({prop:"gridTemplateRows"}),I1=wt({prop:"gridTemplateAreas"}),N1=wt({prop:"gridArea"}),kj=Fn(Cl,El,Rl,E1,R1,k1,O1,A1,M1,$1,I1,N1);function Ys(e,t){return t==="grey"?t:e}var z1=wt({prop:"color",themeKey:"palette",transform:Ys}),D1=wt({prop:"bgcolor",cssProperty:"backgroundColor",themeKey:"palette",transform:Ys}),B1=wt({prop:"backgroundColor",themeKey:"palette",transform:Ys}),$j=Fn(z1,D1,B1);var L1=Pl;function Jr(e){return e<=1&&e!==0?`${e*100}%`:e}var j1=wt({prop:"width",transform:Jr}),Mu=e=>{if(e.maxWidth!==void 0&&e.maxWidth!==null){let t=r=>{let o=e.theme?.breakpoints?.values?.[r]||L1[r];return o?e.theme?.breakpoints?.unit!=="px"?{maxWidth:`${o}${e.theme.breakpoints.unit}`}:{maxWidth:o}:{maxWidth:Jr(r)}};return _n(e,e.maxWidth,t)}return null};Mu.filterProps=["maxWidth"];var F1=wt({prop:"minWidth",transform:Jr}),V1=wt({prop:"height",transform:Jr}),U1=wt({prop:"maxHeight",transform:Jr}),Z1=wt({prop:"minHeight",transform:Jr}),Lj=wt({prop:"size",cssProperty:"width",transform:Jr}),jj=wt({prop:"size",cssProperty:"height",transform:Jr}),W1=wt({prop:"boxSizing"}),Fj=Fn(j1,Mu,F1,V1,U1,Z1,W1);var H1={border:{themeKey:"borders",transform:so},borderTop:{themeKey:"borders",transform:so},borderRight:{themeKey:"borders",transform:so},borderBottom:{themeKey:"borders",transform:so},borderLeft:{themeKey:"borders",transform:so},borderColor:{themeKey:"palette"},borderTopColor:{themeKey:"palette"},borderRightColor:{themeKey:"palette"},borderBottomColor:{themeKey:"palette"},borderLeftColor:{themeKey:"palette"},outline:{themeKey:"borders",transform:so},outlineColor:{themeKey:"palette"},borderRadius:{themeKey:"shape.borderRadius",style:wl},color:{themeKey:"palette",transform:Ys},bgcolor:{themeKey:"palette",cssProperty:"backgroundColor",transform:Ys},backgroundColor:{themeKey:"palette",transform:Ys},p:{style:qt},pt:{style:qt},pr:{style:qt},pb:{style:qt},pl:{style:qt},px:{style:qt},py:{style:qt},padding:{style:qt},paddingTop:{style:qt},paddingRight:{style:qt},paddingBottom:{style:qt},paddingLeft:{style:qt},paddingX:{style:qt},paddingY:{style:qt},paddingInline:{style:qt},paddingInlineStart:{style:qt},paddingInlineEnd:{style:qt},paddingBlock:{style:qt},paddingBlockStart:{style:qt},paddingBlockEnd:{style:qt},m:{style:Kt},mt:{style:Kt},mr:{style:Kt},mb:{style:Kt},ml:{style:Kt},mx:{style:Kt},my:{style:Kt},margin:{style:Kt},marginTop:{style:Kt},marginRight:{style:Kt},marginBottom:{style:Kt},marginLeft:{style:Kt},marginX:{style:Kt},marginY:{style:Kt},marginInline:{style:Kt},marginInlineStart:{style:Kt},marginInlineEnd:{style:Kt},marginBlock:{style:Kt},marginBlockStart:{style:Kt},marginBlockEnd:{style:Kt},displayPrint:{cssProperty:!1,transform:e=>({"@media print":{display:e}})},display:{},overflow:{},textOverflow:{},visibility:{},whiteSpace:{},flexBasis:{},flexDirection:{},flexWrap:{},justifyContent:{},alignItems:{},alignContent:{},order:{},flex:{},flexGrow:{},flexShrink:{},alignSelf:{},justifyItems:{},justifySelf:{},gap:{style:Cl},rowGap:{style:Rl},columnGap:{style:El},gridColumn:{},gridRow:{},gridAutoFlow:{},gridAutoColumns:{},gridAutoRows:{},gridTemplateColumns:{},gridTemplateRows:{},gridTemplateAreas:{},gridArea:{},position:{},zIndex:{themeKey:"zIndex"},top:{},right:{},bottom:{},left:{},boxShadow:{themeKey:"shadows"},width:{transform:Jr},maxWidth:{style:Mu},minWidth:{transform:Jr},height:{transform:Jr},maxHeight:{transform:Jr},minHeight:{transform:Jr},boxSizing:{},font:{themeKey:"font"},fontFamily:{themeKey:"typography"},fontSize:{themeKey:"typography"},fontStyle:{themeKey:"typography"},fontWeight:{themeKey:"typography"},letterSpacing:{},textTransform:{},lineHeight:{},textAlign:{},typography:{cssProperty:!1,themeKey:"typography"}},Vn=H1;var G1={};function K1(){function e(t){if(!t.sx)return null;let{sx:r,theme:o=G1,nested:n}=t,s=o.unstable_sxConfig??Vn,i={sx:null,theme:o,nested:!0};function a(l){let c=l;if(typeof l=="function")c=l(o);else if(typeof l!="object")return l;if(!c)return null;let u=o.breakpoints??Tl,f=px(u);for(let m in c){let p=q1(c[m],o);if(p!=null){if(typeof p!="object"){xx(f,m,p,o,s);continue}if(s[m]){xx(f,m,p,o,s);continue}fx(u,p)?ta(f,t.theme,p,(y,x)=>{f[y][m]=x}):(i.sx=p,f[m]=e(i))}}return!n&&o.modularCssLayers?{"@layer sx":Ru(o,Gd(u,f))}:Ru(o,Gd(u,f))}return Array.isArray(r)?r.map(a):a(r)}return e.filterProps=["sx"],e}var Qr=K1();function xx(e,t,r,o,n){let s=n[t];if(!s){e[t]=r;return}if(r==null)return;let{themeKey:i}=s;if(i==="typography"&&r==="inherit"){e[t]=r;return}let{style:a}=s;if(a){Yo(e,a({[t]:r,theme:o}));return}let{cssProperty:l=t,transform:c}=s,u=ra(o,i);ta(e,o,r,(f,m)=>{let p=Kd(u,c,m,t);l===!1?f?Yo(e[f],p):Yo(e,p):f?e[f][l]=p:e[l]=p})}function q1(e,t){return typeof e=="function"?e(t):e}K();function kl(){return kl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)({}).hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},kl.apply(null,arguments)}K();K();var Y1=!1;function X1(e){if(e.sheet)return e.sheet;for(var t=0;t<document.styleSheets.length;t++)if(document.styleSheets[t].ownerNode===e)return document.styleSheets[t]}function J1(e){var t=document.createElement("style");return t.setAttribute("data-emotion",e.key),e.nonce!==void 0&&t.setAttribute("nonce",e.nonce),t.appendChild(document.createTextNode("")),t.setAttribute("data-s",""),t}var vx=(function(){function e(r){var o=this;this._insertTag=function(n){var s;o.tags.length===0?o.insertionPoint?s=o.insertionPoint.nextSibling:o.prepend?s=o.container.firstChild:s=o.before:s=o.tags[o.tags.length-1].nextSibling,o.container.insertBefore(n,s),o.tags.push(n)},this.isSpeedy=r.speedy===void 0?!Y1:r.speedy,this.tags=[],this.ctr=0,this.nonce=r.nonce,this.key=r.key,this.container=r.container,this.prepend=r.prepend,this.insertionPoint=r.insertionPoint,this.before=null}var t=e.prototype;return t.hydrate=function(o){o.forEach(this._insertTag)},t.insert=function(o){this.ctr%(this.isSpeedy?65e3:1)===0&&this._insertTag(J1(this));var n=this.tags[this.tags.length-1];if(this.isSpeedy){var s=X1(n);try{s.insertRule(o,s.cssRules.length)}catch{}}else n.appendChild(document.createTextNode(o));this.ctr++},t.flush=function(){this.tags.forEach(function(o){var n;return(n=o.parentNode)==null?void 0:n.removeChild(o)}),this.tags=[],this.ctr=0},e})();var kr="-ms-",Ol="-moz-",rt="-webkit-",$u="comm",oa="rule",na="decl";var Tx="@import";var Iu="@keyframes";var Px="@layer";var _x=Math.abs,Xs=String.fromCharCode,Sx=Object.assign;function wx(e,t){return Yt(e,0)^45?(((t<<2^Yt(e,0))<<2^Yt(e,1))<<2^Yt(e,2))<<2^Yt(e,3):0}function Nu(e){return e.trim()}function em(e,t){return(e=t.exec(e))?e[0]:e}function Qe(e,t,r){return e.replace(t,r)}function Al(e,t){return e.indexOf(t)}function Yt(e,t){return e.charCodeAt(t)|0}function xs(e,t,r){return e.slice(t,r)}function Ur(e){return e.length}function sa(e){return e.length}function ia(e,t){return t.push(e),e}function tm(e,t){return e.map(t).join("")}var zu=1,aa=1,Cx=0,Zr=0,rr=0,ca="";function Ml(e,t,r,o,n,s,i){return{value:e,root:t,parent:r,type:o,props:n,children:s,line:zu,column:aa,length:i,return:""}}function ua(e,t){return Sx(Ml("",null,null,"",null,null,0),e,{length:-e.length},t)}function Ex(){return rr}function Rx(){return rr=Zr>0?Yt(ca,--Zr):0,aa--,rr===10&&(aa=1,zu--),rr}function Wr(){return rr=Zr<Cx?Yt(ca,Zr++):0,aa++,rr===10&&(aa=1,zu++),rr}function Ro(){return Yt(ca,Zr)}function $l(){return Zr}function pa(e,t){return xs(ca,e,t)}function la(e){switch(e){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function Du(e){return zu=aa=1,Cx=Ur(ca=e),Zr=0,[]}function Bu(e){return ca="",e}function fa(e){return Nu(pa(Zr-1,rm(e===91?e+2:e===40?e+1:e)))}function kx(e){for(;(rr=Ro())&&rr<33;)Wr();return la(e)>2||la(rr)>3?"":" "}function Ox(e,t){for(;--t&&Wr()&&!(rr<48||rr>102||rr>57&&rr<65||rr>70&&rr<97););return pa(e,$l()+(t<6&&Ro()==32&&Wr()==32))}function rm(e){for(;Wr();)switch(rr){case e:return Zr;case 34:case 39:e!==34&&e!==39&&rm(rr);break;case 40:e===41&&rm(e);break;case 92:Wr();break}return Zr}function Ax(e,t){for(;Wr()&&e+rr!==57;)if(e+rr===84&&Ro()===47)break;return"/*"+pa(t,Zr-1)+"*"+Xs(e===47?e:Wr())}function Mx(e){for(;!la(Ro());)Wr();return pa(e,Zr)}function Nx(e){return Bu(Lu("",null,null,null,[""],e=Du(e),0,[0],e))}function Lu(e,t,r,o,n,s,i,a,l){for(var c=0,u=0,f=i,m=0,p=0,y=0,x=1,T=1,S=1,v=0,R="",P=n,O=s,E=o,A=R;T;)switch(y=v,v=Wr()){case 40:if(y!=108&&Yt(A,f-1)==58){Al(A+=Qe(fa(v),"&","&\f"),"&\f")!=-1&&(S=-1);break}case 34:case 39:case 91:A+=fa(v);break;case 9:case 10:case 13:case 32:A+=kx(y);break;case 92:A+=Ox($l()-1,7);continue;case 47:switch(Ro()){case 42:case 47:ia(Q1(Ax(Wr(),$l()),t,r),l);break;default:A+="/"}break;case 123*x:a[c++]=Ur(A)*S;case 125*x:case 59:case 0:switch(v){case 0:case 125:T=0;case 59+u:S==-1&&(A=Qe(A,/\f/g,"")),p>0&&Ur(A)-f&&ia(p>32?Ix(A+";",o,r,f-1):Ix(Qe(A," ","")+";",o,r,f-2),l);break;case 59:A+=";";default:if(ia(E=$x(A,t,r,c,u,n,a,R,P=[],O=[],f),s),v===123)if(u===0)Lu(A,t,E,E,P,s,f,a,O);else switch(m===99&&Yt(A,3)===110?100:m){case 100:case 108:case 109:case 115:Lu(e,E,E,o&&ia($x(e,E,E,0,0,n,a,R,n,P=[],f),O),n,O,f,a,o?P:O);break;default:Lu(A,E,E,E,[""],O,0,a,O)}}c=u=p=0,x=S=1,R=A="",f=i;break;case 58:f=1+Ur(A),p=y;default:if(x<1){if(v==123)--x;else if(v==125&&x++==0&&Rx()==125)continue}switch(A+=Xs(v),v*x){case 38:S=u>0?1:(A+="\f",-1);break;case 44:a[c++]=(Ur(A)-1)*S,S=1;break;case 64:Ro()===45&&(A+=fa(Wr())),m=Ro(),u=f=Ur(R=A+=Mx($l())),v++;break;case 45:y===45&&Ur(A)==2&&(x=0)}}return s}function $x(e,t,r,o,n,s,i,a,l,c,u){for(var f=n-1,m=n===0?s:[""],p=sa(m),y=0,x=0,T=0;y<o;++y)for(var S=0,v=xs(e,f+1,f=_x(x=i[y])),R=e;S<p;++S)(R=Nu(x>0?m[S]+" "+v:Qe(v,/&\f/g,m[S])))&&(l[T++]=R);return Ml(e,t,r,n===0?oa:a,l,c,u)}function Q1(e,t,r){return Ml(e,t,r,$u,Xs(Ex()),xs(e,2,-2),0)}function Ix(e,t,r,o){return Ml(e,t,r,na,xs(e,0,o),xs(e,o+1,-1),o)}function Js(e,t){for(var r="",o=sa(e),n=0;n<o;n++)r+=t(e[n],n,e,t)||"";return r}function zx(e,t,r,o){switch(e.type){case Px:if(e.children.length)break;case Tx:case na:return e.return=e.return||e.value;case $u:return"";case Iu:return e.return=e.value+"{"+Js(e.children,o)+"}";case oa:e.value=e.props.join(",")}return Ur(r=Js(e.children,o))?e.return=e.value+"{"+r+"}":""}function Dx(e){var t=sa(e);return function(r,o,n,s){for(var i="",a=0;a<t;a++)i+=e[a](r,o,n,s)||"";return i}}function Bx(e){return function(t){t.root||(t=t.return)&&e(t)}}function ju(e){var t=Object.create(null);return function(r){return t[r]===void 0&&(t[r]=e(r)),t[r]}}var eE=function(t,r,o){for(var n=0,s=0;n=s,s=Ro(),n===38&&s===12&&(r[o]=1),!la(s);)Wr();return pa(t,Zr)},tE=function(t,r){var o=-1,n=44;do switch(la(n)){case 0:n===38&&Ro()===12&&(r[o]=1),t[o]+=eE(Zr-1,r,o);break;case 2:t[o]+=fa(n);break;case 4:if(n===44){t[++o]=Ro()===58?"&\f":"",r[o]=t[o].length;break}default:t[o]+=Xs(n)}while(n=Wr());return t},rE=function(t,r){return Bu(tE(Du(t),r))},Lx=new WeakMap,oE=function(t){if(!(t.type!=="rule"||!t.parent||t.length<1)){for(var r=t.value,o=t.parent,n=t.column===o.column&&t.line===o.line;o.type!=="rule";)if(o=o.parent,!o)return;if(!(t.props.length===1&&r.charCodeAt(0)!==58&&!Lx.get(o))&&!n){Lx.set(t,!0);for(var s=[],i=rE(r,s),a=o.props,l=0,c=0;l<i.length;l++)for(var u=0;u<a.length;u++,c++)t.props[c]=s[l]?i[l].replace(/&\f/g,a[u]):a[u]+" "+i[l]}}},nE=function(t){if(t.type==="decl"){var r=t.value;r.charCodeAt(0)===108&&r.charCodeAt(2)===98&&(t.return="",t.value="")}};function jx(e,t){switch(wx(e,t)){case 5103:return rt+"print-"+e+e;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return rt+e+e;case 5349:case 4246:case 4810:case 6968:case 2756:return rt+e+Ol+e+kr+e+e;case 6828:case 4268:return rt+e+kr+e+e;case 6165:return rt+e+kr+"flex-"+e+e;case 5187:return rt+e+Qe(e,/(\w+).+(:[^]+)/,rt+"box-$1$2"+kr+"flex-$1$2")+e;case 5443:return rt+e+kr+"flex-item-"+Qe(e,/flex-|-self/,"")+e;case 4675:return rt+e+kr+"flex-line-pack"+Qe(e,/align-content|flex-|-self/,"")+e;case 5548:return rt+e+kr+Qe(e,"shrink","negative")+e;case 5292:return rt+e+kr+Qe(e,"basis","preferred-size")+e;case 6060:return rt+"box-"+Qe(e,"-grow","")+rt+e+kr+Qe(e,"grow","positive")+e;case 4554:return rt+Qe(e,/([^-])(transform)/g,"$1"+rt+"$2")+e;case 6187:return Qe(Qe(Qe(e,/(zoom-|grab)/,rt+"$1"),/(image-set)/,rt+"$1"),e,"")+e;case 5495:case 3959:return Qe(e,/(image-set\([^]*)/,rt+"$1$`$1");case 4968:return Qe(Qe(e,/(.+:)(flex-)?(.*)/,rt+"box-pack:$3"+kr+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+rt+e+e;case 4095:case 3583:case 4068:case 2532:return Qe(e,/(.+)-inline(.+)/,rt+"$1$2")+e;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(Ur(e)-1-t>6)switch(Yt(e,t+1)){case 109:if(Yt(e,t+4)!==45)break;case 102:return Qe(e,/(.+:)(.+)-([^]+)/,"$1"+rt+"$2-$3$1"+Ol+(Yt(e,t+3)==108?"$3":"$2-$3"))+e;case 115:return~Al(e,"stretch")?jx(Qe(e,"stretch","fill-available"),t)+e:e}break;case 4949:if(Yt(e,t+1)!==115)break;case 6444:switch(Yt(e,Ur(e)-3-(~Al(e,"!important")&&10))){case 107:return Qe(e,":",":"+rt)+e;case 101:return Qe(e,/(.+:)([^;!]+)(;|!.+)?/,"$1"+rt+(Yt(e,14)===45?"inline-":"")+"box$3$1"+rt+"$2$3$1"+kr+"$2box$3")+e}break;case 5936:switch(Yt(e,t+11)){case 114:return rt+e+kr+Qe(e,/[svh]\w+-[tblr]{2}/,"tb")+e;case 108:return rt+e+kr+Qe(e,/[svh]\w+-[tblr]{2}/,"tb-rl")+e;case 45:return rt+e+kr+Qe(e,/[svh]\w+-[tblr]{2}/,"lr")+e}return rt+e+kr+e+e}return e}var sE=function(t,r,o,n){if(t.length>-1&&!t.return)switch(t.type){case na:t.return=jx(t.value,t.length);break;case Iu:return Js([ua(t,{value:Qe(t.value,"@","@"+rt)})],n);case oa:if(t.length)return tm(t.props,function(s){switch(em(s,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return Js([ua(t,{props:[Qe(s,/:(read-\w+)/,":"+Ol+"$1")]})],n);case"::placeholder":return Js([ua(t,{props:[Qe(s,/:(plac\w+)/,":"+rt+"input-$1")]}),ua(t,{props:[Qe(s,/:(plac\w+)/,":"+Ol+"$1")]}),ua(t,{props:[Qe(s,/:(plac\w+)/,kr+"input-$1")]})],n)}return""})}},iE=[sE],Fx=function(t){var r=t.key;if(r==="css"){var o=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(o,function(x){var T=x.getAttribute("data-emotion");T.indexOf(" ")!==-1&&(document.head.appendChild(x),x.setAttribute("data-s",""))})}var n=t.stylisPlugins||iE,s={},i,a=[];i=t.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+r+' "]'),function(x){for(var T=x.getAttribute("data-emotion").split(" "),S=1;S<T.length;S++)s[T[S]]=!0;a.push(x)});var l,c=[oE,nE];{var u,f=[zx,Bx(function(x){u.insert(x)})],m=Dx(c.concat(n,f)),p=function(T){return Js(Nx(T),m)};l=function(T,S,v,R){u=v,p(T?T+"{"+S.styles+"}":S.styles),R&&(y.inserted[S.name]=!0)}}var y={key:r,sheet:new vx({key:r,container:i,nonce:t.nonce,speedy:t.speedy,prepend:t.prepend,insertionPoint:t.insertionPoint}),nonce:t.nonce,inserted:s,registered:{},insert:l};return y.sheet.hydrate(a),y};var xE=!0;function Il(e,t,r){var o="";return r.split(" ").forEach(function(n){e[n]!==void 0?t.push(e[n]+";"):n&&(o+=n+" ")}),o}var da=function(t,r,o){var n=t.key+"-"+r.name;(o===!1||xE===!1)&&t.registered[n]===void 0&&(t.registered[n]=r.styles)},ma=function(t,r,o){da(t,r,o);var n=t.key+"-"+r.name;if(t.inserted[r.name]===void 0){var s=r;do t.insert(r===s?"."+n:"",s,t.sheet,!0),s=s.next;while(s!==void 0)}};function Qx(e){for(var t=0,r,o=0,n=e.length;n>=4;++o,n-=4)r=e.charCodeAt(o)&255|(e.charCodeAt(++o)&255)<<8|(e.charCodeAt(++o)&255)<<16|(e.charCodeAt(++o)&255)<<24,r=(r&65535)*1540483477+((r>>>16)*59797<<16),r^=r>>>24,t=(r&65535)*1540483477+((r>>>16)*59797<<16)^(t&65535)*1540483477+((t>>>16)*59797<<16);switch(n){case 3:t^=(e.charCodeAt(o+2)&255)<<16;case 2:t^=(e.charCodeAt(o+1)&255)<<8;case 1:t^=e.charCodeAt(o)&255,t=(t&65535)*1540483477+((t>>>16)*59797<<16)}return t^=t>>>13,t=(t&65535)*1540483477+((t>>>16)*59797<<16),((t^t>>>15)>>>0).toString(36)}var ev={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,scale:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1};var vE=!1,TE=/[A-Z]|^ms/g,PE=/_EMO_([^_]+?)_([^]*?)_EMO_/g,nv=function(t){return t.charCodeAt(1)===45},tv=function(t){return t!=null&&typeof t!="boolean"},lm=ju(function(e){return nv(e)?e:e.replace(TE,"-$&").toLowerCase()}),rv=function(t,r){switch(t){case"animation":case"animationName":if(typeof r=="string")return r.replace(PE,function(o,n,s){return Sn={name:n,styles:s,next:Sn},n})}return ev[t]!==1&&!nv(t)&&typeof r=="number"&&r!==0?r+"px":r},_E="Component selectors can only be used in conjunction with @emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware compiler transform.";function Nl(e,t,r){if(r==null)return"";var o=r;if(o.__emotion_styles!==void 0)return o;switch(typeof r){case"boolean":return"";case"object":{var n=r;if(n.anim===1)return Sn={name:n.name,styles:n.styles,next:Sn},n.name;var s=r;if(s.styles!==void 0){var i=s.next;if(i!==void 0)for(;i!==void 0;)Sn={name:i.name,styles:i.styles,next:Sn},i=i.next;var a=s.styles+";";return a}return SE(e,t,r)}case"function":{if(e!==void 0){var l=Sn,c=r(e);return Sn=l,Nl(e,t,c)}break}}var u=r;if(t==null)return u;var f=t[u];return f!==void 0?f:u}function SE(e,t,r){var o="";if(Array.isArray(r))for(var n=0;n<r.length;n++)o+=Nl(e,t,r[n])+";";else for(var s in r){var i=r[s];if(typeof i!="object"){var a=i;t!=null&&t[a]!==void 0?o+=s+"{"+t[a]+"}":tv(a)&&(o+=lm(s)+":"+rv(s,a)+";")}else{if(s==="NO_COMPONENT_SELECTOR"&&vE)throw new Error(_E);if(Array.isArray(i)&&typeof i[0]=="string"&&(t==null||t[i[0]]===void 0))for(var l=0;l<i.length;l++)tv(i[l])&&(o+=lm(s)+":"+rv(s,i[l])+";");else{var c=Nl(e,t,i);switch(s){case"animation":case"animationName":{o+=lm(s)+":"+c+";";break}default:o+=s+"{"+c+"}"}}}}return o}var ov=/label:\s*([^\s;{]+)\s*(;|$)/g,Sn;function Un(e,t,r){if(e.length===1&&typeof e[0]=="object"&&e[0]!==null&&e[0].styles!==void 0)return e[0];var o=!0,n="";Sn=void 0;var s=e[0];if(s==null||s.raw===void 0)o=!1,n+=Nl(r,t,s);else{var i=s;n+=i[0]}for(var a=1;a<e.length;a++)if(n+=Nl(r,t,e[a]),o){var l=s;n+=l[a]}ov.lastIndex=0;for(var c="",u;(u=ov.exec(n))!==null;)c+="-"+u[1];var f=Qx(n)+c;return{name:f,styles:n,next:Sn}}K();var wE=function(t){return t()},sv=Wi?Wi:!1,zl=sv||wE,cm=sv||Zo;var iv=!1,av=Je(typeof HTMLElement<"u"?Fx({key:"css"}):null),CE=av.Provider;var ha=function(t){return ue(function(r,o){var n=Se(av);return t(r,n,o)})},Jo=Je({});var Xu={}.hasOwnProperty,um="__EMOTION_TYPE_PLEASE_DO_NOT_USE__",lv=function(t,r){var o={};for(var n in r)Xu.call(r,n)&&(o[n]=r[n]);return o[um]=t,o},EE=function(t){var r=t.cache,o=t.serialized,n=t.isStringTag;return da(r,o,n),zl(function(){return ma(r,o,n)}),null},RE=ha(function(e,t,r){var o=e.css;typeof o=="string"&&t.registered[o]!==void 0&&(o=t.registered[o]);var n=e[um],s=[o],i="";typeof e.className=="string"?i=Il(t.registered,s,e.className):e.className!=null&&(i=e.className+" ");var a=Un(s,void 0,Se(Jo));i+=t.key+"-"+a.name;var l={};for(var c in e)Xu.call(e,c)&&c!=="css"&&c!==um&&!iv&&(l[c]=e[c]);return l.className=i,r&&(l.ref=r),tr(Ie,null,tr(EE,{cache:t,serialized:a,isStringTag:typeof n=="string"}),tr(n,l))}),cv=RE;K();var oF=$c(Jx()),uv=function(t,r){var o=arguments;if(r==null||!Xu.call(r,"css"))return tr.apply(void 0,o);var n=o.length,s=new Array(n);s[0]=cv,s[1]=lv(t,r);for(var i=2;i<n;i++)s[i]=o[i];return tr.apply(null,s)};(function(e){var t;t||(t=e.JSX||(e.JSX={}))})(uv||(uv={}));var pv=ha(function(e,t){var r=e.styles,o=Un([r],void 0,Se(Jo)),n=J();return cm(function(){var s=t.key+"-global",i=new t.sheet.constructor({key:s,nonce:t.sheet.nonce,container:t.sheet.container,speedy:t.sheet.isSpeedy}),a=!1,l=document.querySelector('style[data-emotion="'+s+" "+o.name+'"]');return t.sheet.tags.length&&(i.before=t.sheet.tags[0]),l!==null&&(a=!0,l.setAttribute("data-emotion",s),i.hydrate([l])),n.current=[i,a],function(){i.flush()}},[t]),cm(function(){var s=n.current,i=s[0],a=s[1];if(a){s[1]=!1;return}if(o.next!==void 0&&ma(t,o.next,!0),i.tags.length){var l=i.tags[i.tags.length-1].nextElementSibling;i.before=l,i.flush()}t.insert("",o,i,!1)},[t,o.name]),null});function wn(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return Un(t)}function Cn(){var e=wn.apply(void 0,arguments),t="animation-"+e.name;return{name:t,styles:"@keyframes "+t+"{"+e.styles+"}",anim:1,toString:function(){return"_EMO_"+this.name+"_"+this.styles+"_EMO_"}}}K();var kE=/^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|fetchpriority|fetchPriority|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|popover|popoverTarget|popoverTargetAction|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/,fv=ju(function(e){return kE.test(e)||e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)<91});var OE=!1,AE=fv,ME=function(t){return t!=="theme"},dv=function(t){return typeof t=="string"&&t.charCodeAt(0)>96?AE:ME},mv=function(t,r,o){var n;if(r){var s=r.shouldForwardProp;n=t.__emotion_forwardProp&&s?function(i){return t.__emotion_forwardProp(i)&&s(i)}:s}return typeof n!="function"&&o&&(n=t.__emotion_forwardProp),n},$E=function(t){var r=t.cache,o=t.serialized,n=t.isStringTag;return da(r,o,n),zl(function(){return ma(r,o,n)}),null},hv=function e(t,r){var o=t.__emotion_real===t,n=o&&t.__emotion_base||t,s,i;r!==void 0&&(s=r.label,i=r.target);var a=mv(t,r,o),l=a||dv(n),c=!l("as");return function(){var u=arguments,f=o&&t.__emotion_styles!==void 0?t.__emotion_styles.slice(0):[];if(s!==void 0&&f.push("label:"+s+";"),u[0]==null||u[0].raw===void 0)f.push.apply(f,u);else{var m=u[0];f.push(m[0]);for(var p=u.length,y=1;y<p;y++)f.push(u[y],m[y])}var x=ha(function(T,S,v){var R=c&&T.as||n,P="",O=[],E=T;if(T.theme==null){E={};for(var A in T)E[A]=T[A];E.theme=Se(Jo)}typeof T.className=="string"?P=Il(S.registered,O,T.className):T.className!=null&&(P=T.className+" ");var I=Un(f.concat(O),S.registered,E);P+=S.key+"-"+I.name,i!==void 0&&(P+=" "+i);var N=c&&a===void 0?dv(R):l,D={};for(var w in T)c&&w==="as"||N(w)&&(D[w]=T[w]);return D.className=P,v&&(D.ref=v),tr(Ie,null,tr($E,{cache:S,serialized:I,isStringTag:typeof R=="string"}),tr(R,D))});return x.displayName=s!==void 0?s:"Styled("+(typeof n=="string"?n:n.displayName||n.name||"Component")+")",x.defaultProps=t.defaultProps,x.__emotion_real=x,x.__emotion_base=n,x.__emotion_styles=f,x.__emotion_forwardProp=a,Object.defineProperty(x,"toString",{value:function(){return i===void 0&&OE?"NO_COMPONENT_SELECTOR":"."+i}}),x.withComponent=function(T,S){var v=e(T,kl({},r,S,{shouldForwardProp:mv(x,S,!0)}));return v.apply(void 0,f)},x}};K();var IE=["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","tspan"],Ju=hv.bind(null);IE.forEach(function(e){Ju[e]=Ju(e)});function NE(e){return e==null||Object.keys(e).length===0}function Qs(e){let{styles:t,defaultTheme:r={}}=e;return b(pv,{styles:typeof t=="function"?n=>t(NE(n)?r:n):t})}function zE(e,t){return Ju(e,t)}var Qu=zE;function gv(e,t){Array.isArray(e.__emotion_styles)&&(e.__emotion_styles=t(e.__emotion_styles))}var yv=[];function Qo(e){return yv[0]=e,Un(yv)}var DE={borderRadius:4},bv=DE;function ya(e=8,t=Sl({spacing:e})){if(e.mui)return e;let r=(...o)=>(o.length===0?[1]:o).map(s=>{let i=t(s);return typeof i=="number"?`${i}px`:i}).join(" ");return r.mui=!0,r}function pm(e,t){let r=this;if(r.vars){if(!r.colorSchemes?.[e]||typeof r.getColorSchemeSelector!="function")return{};let o=r.getColorSchemeSelector(e);return o==="&"?t:((o.includes("data-")||o.includes("."))&&(o=`*:where(${o.replace(/\s*&$/,"")}) &`),{[o]:t})}return r.palette.mode===e?t:{}}function BE(e={},...t){let{breakpoints:r={},palette:o={},spacing:n,shape:s={},...i}=e,a=vl(r),l=ya(n),c=Dt({breakpoints:a,direction:"ltr",components:{},palette:{mode:"light",...o},spacing:l,shape:{...bv,...s}},i);return c=Ou(c),c.applyStyles=pm,c=t.reduce((u,f)=>Dt(u,f),c),c.unstable_sxConfig={...Vn,...i?.unstable_sxConfig},c.unstable_sx=function(f){return Qr({sx:f,theme:this})},c.internal_cache={},c}var en=BE;K();function LE(e){return Object.keys(e).length===0}function jE(e=null){let t=Se(Jo);return!t||LE(t)?e:t}var Zn=jE;var FE=en();function VE(e=FE){return Zn(e)}var ko=VE;function fm(e){let t=Qo(e);return e!==t&&t.styles?(t.styles.match(/^@layer\s+[^{]*$/)||(t.styles=`@layer global{${t.styles}}`),t):e}function UE({styles:e,themeId:t,defaultTheme:r={}}){let o=ko(r),n=t&&o[t]||o,s=typeof e=="function"?e(n):e;return n.modularCssLayers&&(Array.isArray(s)?s=s.map(i=>fm(typeof i=="function"?i(n):i)):s=fm(s)),b(Qs,{styles:s})}var ga=UE;var xv=e=>e,ZE=()=>{let e=xv;return{configure(t){e=t},generate(t){return e(t)},reset(){e=xv}}},WE=ZE(),ba=WE;K();function Dl(e={}){let{themeId:t,defaultTheme:r,defaultClassName:o="MuiBox-root",generateClassName:n}=e,s=Qu("div",{shouldForwardProp:a=>a!=="theme"&&a!=="sx"&&a!=="as"})(Qr);return ue(function(l,c){let u=ko(r),{className:f,component:m="div",...p}=l;return b(s,{as:m,ref:c,className:he(f,n?n(o):o),theme:t&&u[t]||u,...p})})}var HE={active:"active",checked:"checked",completed:"completed",disabled:"disabled",error:"error",expanded:"expanded",focused:"focused",focusVisible:"focusVisible",open:"open",readOnly:"readOnly",required:"required",selected:"selected"};function we(e,t,r="Mui"){let o=HE[t];return o?`${r}-${o}`:`${ba.generate(e)}-${t}`}function Ce(e,t,r="Mui"){let o={};return t.forEach(n=>{o[n]=we(e,n,r)}),o}function Bl(e){let{variants:t,...r}=e,o={variants:t,style:Qo(r),isProcessed:!0};return o.style===r||t&&t.forEach(n=>{typeof n.style!="function"&&(n.style=Qo(n.style))}),o}var GE=en();function dm(e){return e!=="ownerState"&&e!=="theme"&&e!=="sx"&&e!=="as"}function ei(e,t){return t&&e&&typeof e=="object"&&e.styles&&!e.styles.startsWith("@layer")&&(e.styles=`@layer ${t}{${String(e.styles)}}`),e}function KE(e){return e?(t,r)=>r[e]:null}function qE(e,t,r){e.theme=ea(e.theme)?r:e.theme[t]||e.theme}function ep(e,t,r){let o=typeof t=="function"?t(e):t;if(Array.isArray(o))return o.flatMap(n=>ep(e,n,r));if(Array.isArray(o?.variants)){let n;if(o.isProcessed)n=r?ei(o.style,r):o.style;else{let{variants:s,...i}=o;n=r?ei(Qo(i),r):i}return vv(e,o.variants,[n],r)}return o?.isProcessed?r?ei(Qo(o.style),r):o.style:r?ei(Qo(o),r):o}function vv(e,t,r=[],o=void 0){let n;e:for(let s=0;s<t.length;s+=1){let i=t[s];if(typeof i.props=="function"){if(n??={...e,...e.ownerState,ownerState:e.ownerState},!i.props(n))continue}else for(let a in i.props)if(e[a]!==i.props[a]&&e.ownerState?.[a]!==i.props[a])continue e;typeof i.style=="function"?(n??={...e,...e.ownerState,ownerState:e.ownerState},r.push(o?ei(Qo(i.style(n)),o):i.style(n))):r.push(o?ei(Qo(i.style),o):i.style)}return r}function xa(e={}){let{themeId:t,defaultTheme:r=GE,rootShouldForwardProp:o=dm,slotShouldForwardProp:n=dm}=e;function s(a){qE(a,t,r)}return(a,l={})=>{gv(a,E=>E.filter(A=>A!==Qr));let{name:c,slot:u,skipVariantsResolver:f,skipSx:m,overridesResolver:p=KE(JE(u)),...y}=l,x=c&&c.startsWith("Mui")||u?"components":"custom",T=f!==void 0?f:u&&u!=="Root"&&u!=="root"||!1,S=m||!1,v=dm;u==="Root"||u==="root"?v=o:u?v=n:XE(a)&&(v=void 0);let R=Qu(a,{shouldForwardProp:v,label:YE(c,u),...y}),P=E=>{if(E.__emotion_real===E)return E;if(typeof E=="function")return function(I){return ep(I,E,I.theme.modularCssLayers?x:void 0)};if(Xo(E)){let A=Bl(E);return function(N){return A.variants?ep(N,A,N.theme.modularCssLayers?x:void 0):N.theme.modularCssLayers?ei(A.style,x):A.style}}return E},O=(...E)=>{let A=[],I=E.map(P),N=[];if(A.push(s),c&&p&&N.push(function(h){let k=h.theme.components?.[c]?.styleOverrides;if(!k)return null;let j={};for(let B in k)j[B]=ep(h,k[B],h.theme.modularCssLayers?"theme":void 0);return p(h,j)}),c&&!T&&N.push(function(h){let k=h.theme?.components?.[c]?.variants;return k?vv(h,k,[],h.theme.modularCssLayers?"theme":void 0):null}),S||N.push(Qr),Array.isArray(I[0])){let $=I.shift(),h=new Array(A.length).fill(""),z=new Array(N.length).fill(""),k;k=[...h,...$,...z],k.raw=[...h,...$.raw,...z],A.unshift(k)}let D=[...A,...I,...N],w=R(...D);return a.muiName&&(w.muiName=a.muiName),w};return R.withConfig&&(O.withConfig=R.withConfig),O}}function YE(e,t){return void 0}function XE(e){return typeof e=="string"&&e.charCodeAt(0)>96}function JE(e){return e&&e.charAt(0).toLowerCase()+e.slice(1)}var QE=xa(),Ll=QE;function tn(e,t,r=!1){let o={...t};for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let s=n;if(s==="components"||s==="slots")o[s]={...e[s],...o[s]};else if(s==="componentsProps"||s==="slotProps"){let i=e[s],a=t[s];if(!a)o[s]=i||{};else if(!i)o[s]=a;else{o[s]={...a};for(let l in i)if(Object.prototype.hasOwnProperty.call(i,l)){let c=l,u=i[c],f=a[c];typeof u=="function"||typeof f=="function"?o[s][c]=(...m)=>tn((typeof u=="function"?u(...m):u)??{},(typeof f=="function"?f(...m):f)??{},r):o[s][c]=tn(u??{},f??{},r)}}}else s==="className"&&r&&t.className!==void 0?o.className=he(e?.className,t?.className):s==="style"&&r&&t.style?o.style={...e?.style,...t?.style}:o[s]===void 0&&(o[s]=e[s])}return o}function va(e){let{theme:t,name:r,props:o}=e;return!t||!t.components||!t.components[r]||!t.components[r].defaultProps?o:tn(t.components[r].defaultProps,o)}function vs(e){let{props:t,name:r,defaultTheme:o,themeId:n}=e,s=ko(o);return n&&(s=s[n]||s),va({theme:s,name:r,props:t})}K();K();var eR=typeof window<"u"?Zo:ce,at=eR;function tR(e,t,r,o,n){let[s,i]=ie(()=>n&&r?r(e).matches:o?o(e).matches:t);return at(()=>{if(!r)return;let a=r(e),l=()=>{i(a.matches)};return l(),a.addEventListener("change",l),()=>{a.removeEventListener("change",l)}},[e,r]),s}var rR={...Q},Tv=rR.useSyncExternalStore;function oR(e,t,r,o,n){let s=Ee(()=>t,[t]),i=Le(()=>{if(n&&r)return()=>r(e).matches;if(o!==null){let{matches:u}=o(e);return()=>u}return s},[s,e,o,n,r]),[a,l]=Le(()=>{if(r===null)return[s,()=>()=>{}];let u=r(e);return[()=>u.matches,f=>(u.addEventListener("change",f),()=>{u.removeEventListener("change",f)})]},[s,r,e]);return Tv(l,a,i)}function mm(e={}){let{themeId:t}=e;return function(o,n={}){let s=Zn();s&&t&&(s=s[t]||s);let a=typeof window<"u"&&typeof window.matchMedia<"u"?window.matchMedia:null,{defaultMatches:l=!1,matchMedia:c,ssrMatchMedia:u=null,noSsr:f=!1}=va({name:"MuiUseMediaQuery",props:n,theme:s}),m=Le(()=>c!==void 0?c:a===null?null:a.bind(window),[c,a]),p=typeof o=="function"?o(s):o;return p=p.replace(/^@media( ?)/m,""),p.includes("print")&&console.warn(["MUI: You have provided a `print` query to the `useMediaQuery` hook.","Using the print media query to modify print styles can lead to unexpected results.","Consider using the `displayPrint` field in the `sx` prop instead.","More information about `displayPrint` on our docs: https://mui.com/system/display/#display-in-print."].join(`+`)),(Tv!==void 0?oR:tR)(p,l,m,u,f)}}var pV=mm();function nR(e,t=Number.MIN_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,r))}var hm=nR;function gm(e,t=0,r=1){return hm(e,t,r)}function sR(e){e=e.slice(1);let t=new RegExp(`.{1,${e.length>=6?2:1}}`,"g"),r=e.match(t);return r&&r[0].length===1&&(r=r.map(o=>o+o)),r?`rgb${r.length===4?"a":""}(${r.map((o,n)=>n<3?parseInt(o,16):Math.round(parseInt(o,16)/255*1e3)/1e3).join(", ")})`:""}function Ts(e){if(e.type)return e;if(e.charAt(0)==="#")return Ts(sR(e));let t=e.indexOf("("),r=e.substring(0,t);if(!["rgb","rgba","hsl","hsla","color"].includes(r))throw new Error(Nr(9,e));let o=e.substring(t+1,e.length-1),n;if(r==="color"){if(o=o.split(" "),n=o.shift(),o.length===4&&o[3].charAt(0)==="/"&&(o[3]=o[3].slice(1)),!["srgb","display-p3","a98-rgb","prophoto-rgb","rec-2020"].includes(n))throw new Error(Nr(10,n))}else o=o.split(",");return o=o.map(s=>parseFloat(s)),{type:r,values:o,colorSpace:n}}var bm=e=>{let t=Ts(e);return t.values.slice(0,3).map((r,o)=>t.type.includes("hsl")&&o!==0?`${r}%`:r).join(" ")},Ps=(e,t)=>{try{return bm(e)}catch{return e}};function tp(e){let{type:t,colorSpace:r}=e,{values:o}=e;return t.includes("rgb")?o=o.map((n,s)=>s<3?parseInt(n,10):n):t.includes("hsl")&&(o[1]=`${o[1]}%`,o[2]=`${o[2]}%`),t.includes("color")?o=`${r} ${o.join(" ")}`:o=`${o.join(", ")}`,`${t}(${o})`}function jl(e){e=Ts(e);let{values:t}=e,r=t[0],o=t[1]/100,n=t[2]/100,s=o*Math.min(n,1-n),i=(c,u=(c+r/30)%12)=>n-s*Math.max(Math.min(u-3,9-u,1),-1),a="rgb",l=[Math.round(i(0)*255),Math.round(i(8)*255),Math.round(i(4)*255)];return e.type==="hsla"&&(a+="a",l.push(t[3])),tp({type:a,values:l})}function ym(e){e=Ts(e);let t=e.type==="hsl"||e.type==="hsla"?Ts(jl(e)).values:e.values;return t=t.map(r=>(e.type!=="color"&&(r/=255),r<=.03928?r/12.92:((r+.055)/1.055)**2.4)),Number((.2126*t[0]+.7152*t[1]+.0722*t[2]).toFixed(3))}function Pv(e,t){let r=ym(e),o=ym(t);return(Math.max(r,o)+.05)/(Math.min(r,o)+.05)}function Ta(e,t){return e=Ts(e),t=gm(t),(e.type==="rgb"||e.type==="hsl")&&(e.type+="a"),e.type==="color"?e.values[3]=`/${t}`:e.values[3]=t,tp(e)}function _s(e,t,r){try{return Ta(e,t)}catch{return e}}function Pa(e,t){if(e=Ts(e),t=gm(t),e.type.includes("hsl"))e.values[2]*=1-t;else if(e.type.includes("rgb")||e.type.includes("color"))for(let r=0;r<3;r+=1)e.values[r]*=1-t;return tp(e)}function ut(e,t,r){try{return Pa(e,t)}catch{return e}}function _a(e,t){if(e=Ts(e),t=gm(t),e.type.includes("hsl"))e.values[2]+=(100-e.values[2])*t;else if(e.type.includes("rgb"))for(let r=0;r<3;r+=1)e.values[r]+=(255-e.values[r])*t;else if(e.type.includes("color"))for(let r=0;r<3;r+=1)e.values[r]+=(1-e.values[r])*t;return tp(e)}function pt(e,t,r){try{return _a(e,t)}catch{return e}}function rp(e,t=.15){return ym(e)>.5?Pa(e,t):_a(e,t)}function Fl(e,t,r){try{return rp(e,t)}catch{return e}}K();K();K();var iR=Je(null),op=iR;K();function Wn(){return Se(op)}var aR=typeof Symbol=="function"&&Symbol.for,_v=aR?Symbol.for("mui.nested"):"__THEME_NESTED__";function lR(e,t){return typeof t=="function"?t(e):{...e,...t}}function cR(e){let{children:t,theme:r}=e,o=Wn(),n=Le(()=>{let s=o===null?{...r}:lR(o,r);return s!=null&&(s[_v]=o!==null),s},[r,o]);return b(op.Provider,{value:n,children:t})}var np=cR;K();var Sv=Je(void 0);function uR({value:e,...t}){return b(Sv.Provider,{value:e??!0,...t})}var Sa=()=>Se(Sv)??!1,wv=uR;K();var Cv=Je(void 0);function pR({value:e,children:t}){return b(Cv.Provider,{value:e,children:t})}function fR(e){let{theme:t,name:r,props:o}=e;if(!t||!t.components||!t.components[r])return o;let n=t.components[r];return n.defaultProps?tn(n.defaultProps,o,t.components.mergeClassNameAndStyle):!n.styleOverrides&&!n.variants?tn(n,o,t.components.mergeClassNameAndStyle):o}function xm({props:e,name:t}){let r=Se(Cv);return fR({props:e,name:t,theme:{components:r}})}var sp=pR;K();var Ev=0;function dR(e){let[t,r]=ie(e),o=e||t;return ce(()=>{t==null&&(Ev+=1,r(`mui-${Ev}`))},[t]),o}var mR={...Q},Rv=mR.useId;function wa(e){if(Rv!==void 0){let t=Rv();return e??t}return dR(e)}function vm(e){let t=Zn(),r=wa()||"",{modularCssLayers:o}=e,n="mui.global, mui.components, mui.theme, mui.custom, mui.sx";return!o||t!==null?n="":typeof o=="string"?n=o.replace(/mui(?!\.)/g,n):n=`@layer ${n};`,at(()=>{let s=document.querySelector("head");if(!s)return;let i=s.firstChild;if(n){if(i&&i.hasAttribute?.("data-mui-layer-order")&&i.getAttribute("data-mui-layer-order")===r)return;let a=document.createElement("style");a.setAttribute("data-mui-layer-order",r),a.textContent=n,s.prepend(a)}else s.querySelector(`style[data-mui-layer-order="${r}"]`)?.remove()},[n,r]),n?b(ga,{styles:n}):null}var kv={};function Ov(e,t,r,o=!1){return Le(()=>{let n=e&&t[e]||t;if(typeof r=="function"){let s=r(n),i=e?{...t,[e]:s}:s;return o?()=>i:i}return e?{...t,[e]:r}:{...t,...r}},[e,t,r,o])}function hR(e){let{children:t,theme:r,themeId:o}=e,n=Zn(kv),s=Wn()||kv,i=Ov(o,n,r),a=Ov(o,s,r,!0),l=(o?i[o]:i).direction==="rtl",c=vm(i);return b(np,{theme:a,children:b(Jo.Provider,{value:i,children:b(wv,{value:l,children:b(sp,{value:o?i[o].components:i.components,children:[c,t]})})})})}var Ca=hR;var Av={theme:void 0};function ip(e){let t,r;return function(n){let s=t;return(s===void 0||n.theme!==r)&&(Av.theme=n.theme,s=Bl(e(Av)),t=s,r=n.theme),s}}K();K();var Vl="mode",Ul="color-scheme",yR="data-color-scheme",gR={...Q},pU=gR.useSyncExternalStore;function Ss(e){return JSON.stringify(e).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function ti(e,t){let r=e.split("%s"),o=[];for(let n=0;n<r.length;n+=1)n>0&&o.push(t),r[n]&&o.push(Ss(r[n]));return o.join(" + ")||'""'}function Mv(e){let{defaultMode:t="system",defaultLightColorScheme:r="light",defaultDarkColorScheme:o="dark",modeStorageKey:n=Vl,colorSchemeStorageKey:s=Ul,attribute:i=yR,colorSchemeNode:a="document.documentElement",nonce:l}=e||{},c="",u=i;if(i==="class"&&(u=".%s"),i==="data"&&(u="[data-%s]"),u.startsWith(".")){let m=u.substring(1);c+=`${a}.classList.remove(${ti(m,"light")}, ${ti(m,"dark")});+      ${a}.classList.add(${ti(m,"colorScheme")});`}let f=u.match(/\[([^[\]]+)\]/);if(f){let m=f[1].indexOf("="),p=m===-1?f[1]:f[1].slice(0,m),y=m===-1?void 0:f[1].slice(m+1);y||(c+=`${a}.removeAttribute(${ti(p,"light")});+      ${a}.removeAttribute(${ti(p,"dark")});`);let x=y?ti(y.replace(/^(['"])(.*)\1$/,"$2"),"colorScheme"):'""';c+=`+      ${a}.setAttribute(${ti(p,"colorScheme")}, ${x});`}else u.startsWith(".")||(c+=`${a}.setAttribute(${Ss(u)}, colorScheme);`);return b("script",{suppressHydrationWarning:!0,nonce:typeof window>"u"?l:"",dangerouslySetInnerHTML:{__html:`(function() {+try {+  let colorScheme = '';+  const mode = localStorage.getItem(${Ss(n)}) || ${Ss(t)};+  const dark = localStorage.getItem(${Ss(`${s}-dark`)}) || ${Ss(o)};+  const light = localStorage.getItem(${Ss(`${s}-light`)}) || ${Ss(r)};+  if (mode === 'system') {+    // handle system mode+    const mql = window.matchMedia('(prefers-color-scheme: dark)');+    if (mql.matches) {+      colorScheme = dark+    } else {+      colorScheme = light+    }+  }+  if (mode === 'light') {+    colorScheme = light;+  }+  if (mode === 'dark') {+    colorScheme = dark;+  }+  if (colorScheme) {+    ${c}+  }+} catch(e){}})();`}},"mui-color-scheme-init")}K();function bR(){}var xR=({key:e,storageWindow:t})=>(!t&&typeof window<"u"&&(t=window),{get(r){if(typeof window>"u")return;if(!t)return r;let o;try{o=t.localStorage.getItem(e)}catch{}return o||r},set:r=>{if(t)try{t.localStorage.setItem(e,r)}catch{}},subscribe:r=>{if(!t)return bR;let o=n=>{let s=n.newValue;n.key===e&&r(s)};return t.addEventListener("storage",o),()=>{t.removeEventListener("storage",o)}}}),$v=xR;function Tm(){}function Iv(e){if(typeof window<"u"&&typeof window.matchMedia=="function"&&e==="system")return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Nv(e,t){if(e.mode==="light"||e.mode==="system"&&e.systemMode==="light")return t("light");if(e.mode==="dark"||e.mode==="system"&&e.systemMode==="dark")return t("dark")}function vR(e){return Nv(e,t=>{if(t==="light")return e.lightColorScheme;if(t==="dark")return e.darkColorScheme})}function Pm(e){let{defaultMode:t="light",defaultLightColorScheme:r,defaultDarkColorScheme:o,supportedColorSchemes:n=[],modeStorageKey:s=Vl,colorSchemeStorageKey:i=Ul,storageWindow:a=typeof window>"u"?void 0:window,storageManager:l=$v,noSsr:c=!1}=e,u=n.join(","),f=n.length>1,m=Le(()=>l?.({key:s,storageWindow:a}),[l,s,a]),p=Le(()=>l?.({key:`${i}-light`,storageWindow:a}),[l,i,a]),y=Le(()=>l?.({key:`${i}-dark`,storageWindow:a}),[l,i,a]),[x,T]=ie(()=>{let I=m?.get(t)||t,N=p?.get(r)||r,D=y?.get(o)||o;return{mode:I,systemMode:Iv(I),lightColorScheme:N,darkColorScheme:D}}),[S,v]=ie(c||!f);ce(()=>{v(!0)},[]);let R=vR(x),P=Ee(I=>{T(N=>{if(I===N.mode)return N;let D=I??t;return m?.set(D),{...N,mode:D,systemMode:Iv(D)}})},[m,t]),O=Ee(I=>{I?typeof I=="string"?I&&!u.includes(I)?console.error(`\`${I}\` does not exist in \`theme.colorSchemes\`.`):T(N=>{let D={...N};return Nv(N,w=>{w==="light"&&(p?.set(I),D.lightColorScheme=I),w==="dark"&&(y?.set(I),D.darkColorScheme=I)}),D}):T(N=>{let D={...N},w=I.light===null?r:I.light,$=I.dark===null?o:I.dark;return w&&(u.includes(w)?(D.lightColorScheme=w,p?.set(w)):console.error(`\`${w}\` does not exist in \`theme.colorSchemes\`.`)),$&&(u.includes($)?(D.darkColorScheme=$,y?.set($)):console.error(`\`${$}\` does not exist in \`theme.colorSchemes\`.`)),D}):T(N=>(p?.set(r),y?.set(o),{...N,lightColorScheme:r,darkColorScheme:o}))},[u,p,y,r,o]),E=Ee(I=>{x.mode==="system"&&T(N=>{let D=I?.matches?"dark":"light";return N.systemMode===D?N:{...N,systemMode:D}})},[x.mode]),A=J(E);return A.current=E,ce(()=>{if(typeof window.matchMedia!="function"||!f)return;let I=(...D)=>A.current(...D),N=window.matchMedia("(prefers-color-scheme: dark)");return N.addListener(I),I(N),()=>{N.removeListener(I)}},[f]),ce(()=>{if(f){let I=m?.subscribe(w=>{(!w||["light","dark","system"].includes(w))&&P(w||t)})||Tm,N=p?.subscribe(w=>{(!w||u.match(w))&&O({light:w})})||Tm,D=y?.subscribe(w=>{(!w||u.match(w))&&O({dark:w})})||Tm;return()=>{I(),N(),D()}}},[O,P,u,t,a,f,m,p,y]),{...x,mode:S?x.mode:void 0,systemMode:S?x.systemMode:void 0,colorScheme:S?R:void 0,setMode:P,setColorScheme:O}}var TR="*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}";function ap(e){let{themeId:t,theme:r={},modeStorageKey:o=Vl,colorSchemeStorageKey:n=Ul,disableTransitionOnChange:s=!1,defaultColorScheme:i,resolveTheme:a}=e,l={allColorSchemes:[],colorScheme:void 0,darkColorScheme:void 0,lightColorScheme:void 0,mode:void 0,setColorScheme:()=>{},setMode:()=>{},systemMode:void 0},c=Je(void 0),u=()=>Se(c)||l,f={},m={};function p(S){let{children:v,theme:R,modeStorageKey:P=o,colorSchemeStorageKey:O=n,disableTransitionOnChange:E=s,storageManager:A,storageWindow:I=typeof window>"u"?void 0:window,documentNode:N=typeof document>"u"?void 0:document,colorSchemeNode:D=typeof document>"u"?void 0:document.documentElement,disableNestedContext:w=!1,disableStyleSheetGeneration:$=!1,defaultMode:h="system",forceThemeRerender:z=!1,noSsr:k}=S,j=J(!1),B=Wn(),W=Se(c),H=!!W&&!w,ee=Le(()=>R||(typeof r=="function"?r():r),[R]),G=ee[t],F=G||ee,{colorSchemes:V=f,components:te=m,cssVarPrefix:oe}=F,Y=Object.keys(V).filter(xe=>!!V[xe]).join(","),fe=Le(()=>Y.split(","),[Y]),se=typeof i=="string"?i:i.light,be=typeof i=="string"?i:i.dark,Pe=V[se]&&V[be]?h:V[F.defaultColorScheme]?.palette?.mode||F.palette?.mode,{mode:We,setMode:qe,systemMode:He,lightColorScheme:Ye,darkColorScheme:$e,colorScheme:Ge,setColorScheme:yt}=Pm({supportedColorSchemes:fe,defaultLightColorScheme:se,defaultDarkColorScheme:be,modeStorageKey:P,colorSchemeStorageKey:O,defaultMode:Pe,storageManager:A,storageWindow:I,noSsr:k}),Ot=We,Xe=Ge;H&&(Ot=W.mode,Xe=W.colorScheme);let Ve=Xe||F.defaultColorScheme;F.vars&&!z&&(Ve=F.defaultColorScheme);let Tt=Le(()=>{let xe=F.generateThemeVars?.()||F.vars,_e={...F,components:te,colorSchemes:V,cssVarPrefix:oe,vars:xe};if(typeof _e.generateSpacing=="function"&&(_e.spacing=_e.generateSpacing()),Ve){let je=V[Ve];je&&typeof je=="object"&&Object.keys(je).forEach(et=>{je[et]&&typeof je[et]=="object"?_e[et]={..._e[et],...je[et]}:_e[et]=je[et]})}return a?a(_e):_e},[F,Ve,te,V,oe]),dt=F.colorSchemeSelector;at(()=>{if(Xe&&D&&dt&&dt!=="media"){let xe=dt,_e=dt;if(xe==="class"&&(_e=".%s"),xe==="data"&&(_e="[data-%s]"),xe?.startsWith("data-")&&!xe.includes("%s")&&(_e=`[${xe}="%s"]`),_e.startsWith("."))D.classList.remove(...fe.map(je=>_e.substring(1).replace("%s",je))),D.classList.add(_e.substring(1).replace("%s",Xe));else{let je=_e.replace("%s",Xe).match(/\[([^\]]+)\]/);if(je){let[et,gt]=je[1].split("=");gt||fe.forEach(Oe=>{D.removeAttribute(et.replace(Xe,Oe))}),D.setAttribute(et,gt?gt.replace(/"|'/g,""):"")}else D.setAttribute(_e,Xe)}}},[Xe,dt,D,fe]),ce(()=>{let xe;if(E&&j.current&&N){let _e=N.createElement("style");_e.appendChild(N.createTextNode(TR)),N.head.appendChild(_e),window.getComputedStyle(N.body),xe=setTimeout(()=>{N.head.removeChild(_e)},1)}return()=>{clearTimeout(xe)}},[Xe,E,N]),ce(()=>(j.current=!0,()=>{j.current=!1}),[]);let Vt=Le(()=>({allColorSchemes:fe,colorScheme:Xe,darkColorScheme:$e,lightColorScheme:Ye,mode:Ot,setColorScheme:yt,setMode:qe,systemMode:He}),[fe,Xe,$e,Ye,Ot,yt,qe,He,Tt.colorSchemeSelector]),me=!0;($||F.cssVariables===!1||H&&B?.cssVarPrefix===oe)&&(me=!1);let re=b(Ie,{children:[b(Ca,{themeId:G?t:void 0,theme:Tt,children:v}),me&&b(Qs,{styles:Tt.generateStyleSheets?.()||[]})]});return H?re:b(c.Provider,{value:Vt,children:re})}let y=typeof i=="string"?i:i.light,x=typeof i=="string"?i:i.dark;return{CssVarsProvider:p,useColorScheme:u,getInitColorSchemeScript:S=>Mv({colorSchemeStorageKey:n,defaultLightColorScheme:y,defaultDarkColorScheme:x,modeStorageKey:o,...S})}}function lp(e=""){function t(...o){if(!o.length)return"";let n=o[0];return typeof n=="string"&&!n.match(/(#|\(|\)|(-?(\d*\.)?\d+)(px|em|%|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc))|^(-?(\d*\.)?\d+)$|(\d+ \d+ \d+)/)?`, var(--${e?`${e}-`:""}${n}${t(...o.slice(1))})`:`, ${n}`}return(o,...n)=>`var(--${e?`${e}-`:""}${o}${t(...n)})`}var PR=new Set(["__proto__","constructor","prototype"]),zv=(e,t,r,o=[])=>{let n=e;for(let s=0;s<t.length;s+=1){let i=t[s];if(PR.has(i))break;s===t.length-1?Array.isArray(n)?n[Number(i)]=r:n&&typeof n=="object"&&(n[i]=r):n&&typeof n=="object"&&(n[i]||(n[i]=o.includes(i)?[]:{}),n=n[i])}},_R=(e,t,r)=>{function o(n,s=[],i=[]){Object.entries(n).forEach(([a,l])=>{(!r||r&&!r([...s,a]))&&l!=null&&(typeof l=="object"&&Object.keys(l).length>0?o(l,[...s,a],Array.isArray(l)?[...i,a]:i):t([...s,a],l,i))})}o(e)},SR=(e,t)=>typeof t=="number"?["lineHeight","fontWeight","opacity","zIndex"].some(o=>e.includes(o))||e[e.length-1].toLowerCase().includes("opacity")?t:`${t}px`:t;function Zl(e,t){let{prefix:r,shouldSkipGeneratingVar:o}=t||{},n={},s={},i={};return _R(e,(a,l,c)=>{if((typeof l=="string"||typeof l=="number")&&(!o||!o(a,l))){let u=`--${r?`${r}-`:""}${a.join("-")}`,f=SR(a,l);Object.assign(n,{[u]:f}),zv(s,a,`var(${u})`,c),zv(i,a,`var(${u}, ${f})`,c)}},a=>a[0]==="vars"),{css:n,vars:s,varsWithDefaults:i}}function wR(e,t={}){let{getSelector:r=S,disableCssColorScheme:o,colorSchemeSelector:n,enableContrastVars:s}=t,{colorSchemes:i={},components:a,defaultColorScheme:l="light",...c}=e,{vars:u,css:f,varsWithDefaults:m}=Zl(c,t),p=m,y={},{[l]:x,...T}=i;if(Object.entries(T||{}).forEach(([P,O])=>{let{vars:E,css:A,varsWithDefaults:I}=Zl(O,t);p=Dt(p,I),y[P]={css:A,vars:E}}),x){let{css:P,vars:O,varsWithDefaults:E}=Zl(x,t);p=Dt(p,E),y[l]={css:P,vars:O}}function S(P,O){let E=n;if(n==="class"&&(E=".%s"),n==="data"&&(E="[data-%s]"),n?.startsWith("data-")&&!n.includes("%s")&&(E=`[${n}="%s"]`),P){if(E==="media")return e.defaultColorScheme===P?":root":{[`@media (prefers-color-scheme: ${i[P]?.palette?.mode||P})`]:{":root":O}};if(E)return e.defaultColorScheme===P?`:root, ${E.replace("%s",String(P))}`:E.replace("%s",String(P))}return":root"}return{vars:p,generateThemeVars:()=>{let P={...u};return Object.entries(y).forEach(([,{vars:O}])=>{P=Dt(P,O)}),P},generateStyleSheets:()=>{let P=[],O=e.defaultColorScheme||"light";function E(N,D){Object.keys(D).length&&P.push(typeof N=="string"?{[N]:{...D}}:N)}E(r(void 0,{...f}),f);let{[O]:A,...I}=y;if(A){let{css:N}=A,D=i[O]?.palette?.mode,w=!o&&D?{colorScheme:D,...N}:{...N};E(r(O,{...w}),w)}return Object.entries(I).forEach(([N,{css:D}])=>{let w=i[N]?.palette?.mode,$=!o&&w?{colorScheme:w,...D}:{...D};E(r(N,{...$}),$)}),s&&P.push({":root":{"--__l-threshold":"0.7","--__l":"clamp(0, (l / var(--__l-threshold) - 1) * -infinity, 1)","--__a":"clamp(0.87, (l / var(--__l-threshold) - 1) * -infinity, 1)"}}),P}}}var _m=wR;function Sm(e){return function(r){return e==="media"?`@media (prefers-color-scheme: ${r})`:e?e.startsWith("data-")&&!e.includes("%s")?`[${e}="${r}"] &`:e==="class"?`.${r} &`:e==="data"?`[data-${r}] &`:`${e.replace("%s",r)} &`:"&"}}K();var CR=en(),ER=Ll("div",{name:"MuiContainer",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,t[`maxWidth${jn(String(r.maxWidth))}`],r.fixed&&t.fixed,r.disableGutters&&t.disableGutters]}}),RR=e=>vs({props:e,name:"MuiContainer",defaultTheme:CR}),kR=(e,t)=>{let r=l=>we(t,l),{classes:o,fixed:n,disableGutters:s,maxWidth:i}=e,a={root:["root",i&&`maxWidth${jn(String(i))}`,n&&"fixed",s&&"disableGutters"]};return ke(a,r,o)};function cp(e={}){let{createStyledComponent:t=ER,useThemeProps:r=RR,componentName:o="MuiContainer"}=e,n=t(({theme:i,ownerState:a})=>({width:"100%",marginLeft:"auto",boxSizing:"border-box",marginRight:"auto",...!a.disableGutters&&{paddingLeft:i.spacing(2),paddingRight:i.spacing(2),[i.breakpoints.up("sm")]:{paddingLeft:i.spacing(3),paddingRight:i.spacing(3)}}}),({theme:i,ownerState:a})=>a.fixed&&Object.keys(i.breakpoints.values).reduce((l,c)=>{let u=c,f=i.breakpoints.values[u];return f!==0&&(l[i.breakpoints.up(u)]={maxWidth:`${f}${i.breakpoints.unit}`}),l},{}),({theme:i,ownerState:a})=>({...a.maxWidth==="xs"&&{[i.breakpoints.up("xs")]:{maxWidth:Math.max(i.breakpoints.values.xs,444)}},...a.maxWidth&&a.maxWidth!=="xs"&&{[i.breakpoints.up(a.maxWidth)]:{maxWidth:`${i.breakpoints.values[a.maxWidth]}${i.breakpoints.unit}`}}}));return ue(function(a,l){let c=r(a),{className:u,component:f="div",disableGutters:m=!1,fixed:p=!1,maxWidth:y="lg",classes:x,...T}=c,S={...c,component:f,disableGutters:m,fixed:p,maxWidth:y},v=kR(S,o);return b(n,{as:f,ownerState:S,className:he(v.root,u),ref:l,...T})})}K();K();function up(e,t){return Rt(e)&&t.indexOf(e.type.muiName??e.type?._payload?.value?.muiName)!==-1}var OR=(e,t)=>e.filter(r=>t.includes(r)),ri=(e,t,r)=>{let o=e.keys[0];Array.isArray(t)?t.forEach((n,s)=>{r((i,a)=>{s<=e.keys.length-1&&(s===0?Object.assign(i,a):i[e.up(e.keys[s])]=a)},n)}):t&&typeof t=="object"?(Object.keys(t).length>e.keys.length?e.keys:OR(e.keys,Object.keys(t))).forEach(s=>{if(e.keys.includes(s)){let i=t[s];i!==void 0&&r((a,l)=>{o===s?Object.assign(a,l):a[e.up(s)]=l},i)}}):(typeof t=="number"||typeof t=="string")&&r((n,s)=>{Object.assign(n,s)},t)};function pp(e){return`--Grid-${e}Spacing`}function fp(e){return`--Grid-parent-${e}Spacing`}var Dv="--Grid-columns",Ea="--Grid-parent-columns",Bv=({theme:e,ownerState:t})=>{let r={};return ri(e.breakpoints,t.size,(o,n)=>{let s={};n==="grow"&&(s={flexBasis:0,flexGrow:1,maxWidth:"100%"}),n==="auto"&&(s={flexBasis:"auto",flexGrow:0,flexShrink:0,maxWidth:"none",width:"auto"}),typeof n=="number"&&(s={flexGrow:0,flexBasis:"auto",width:`calc(100% * ${n} / var(${Ea}) - (var(${Ea}) - ${n}) * (var(${fp("column")}) / var(${Ea})))`}),o(r,s)}),r},Lv=({theme:e,ownerState:t})=>{let r={};return ri(e.breakpoints,t.offset,(o,n)=>{let s={};n==="auto"&&(s={marginLeft:"auto"}),typeof n=="number"&&(s={marginLeft:n===0?"0px":`calc(100% * ${n} / var(${Ea}) + var(${fp("column")}) * ${n} / var(${Ea}))`}),o(r,s)}),r},jv=({theme:e,ownerState:t})=>{if(!t.container)return{};let r={[Dv]:12};return ri(e.breakpoints,t.columns,(o,n)=>{let s=n??12;o(r,{[Dv]:s,"> *":{[Ea]:s}})}),r},Fv=({theme:e,ownerState:t})=>{if(!t.container)return{};let r={};return ri(e.breakpoints,t.rowSpacing,(o,n)=>{let s=typeof n=="string"?n:e.spacing?.(n);o(r,{[pp("row")]:s,"> *":{[fp("row")]:s}})}),r},Vv=({theme:e,ownerState:t})=>{if(!t.container)return{};let r={};return ri(e.breakpoints,t.columnSpacing,(o,n)=>{let s=typeof n=="string"?n:e.spacing?.(n);o(r,{[pp("column")]:s,"> *":{[fp("column")]:s}})}),r},Uv=({theme:e,ownerState:t})=>{if(!t.container)return{};let r={};return ri(e.breakpoints,t.direction,(o,n)=>{o(r,{flexDirection:n})}),r},Zv=({ownerState:e})=>({minWidth:0,boxSizing:"border-box",...e.container&&{display:"flex",flexWrap:"wrap",...e.wrap&&e.wrap!=="wrap"&&{flexWrap:e.wrap},gap:`var(${pp("row")}) var(${pp("column")})`}}),Wv=e=>{let t=[];return Object.entries(e).forEach(([r,o])=>{o!==!1&&o!==void 0&&t.push(`grid-${r}-${String(o)}`)}),t},Hv=(e,t="xs")=>{function r(o){return o===void 0?!1:typeof o=="string"&&!Number.isNaN(Number(o))||typeof o=="number"&&o>0}if(r(e))return[`spacing-${t}-${String(e)}`];if(typeof e=="object"&&!Array.isArray(e)){let o=[];return Object.entries(e).forEach(([n,s])=>{r(s)&&o.push(`spacing-${n}-${String(s)}`)}),o}return[]},Gv=e=>e===void 0?[]:typeof e=="object"?Object.entries(e).map(([t,r])=>`direction-${t}-${r}`):[`direction-xs-${String(e)}`];var AR=en(),MR=Ll("div",{name:"MuiGrid",slot:"Root"});function $R(e){return vs({props:e,name:"MuiGrid",defaultTheme:AR})}function dp(e={}){let{createStyledComponent:t=MR,useThemeProps:r=$R,useTheme:o=ko,componentName:n="MuiGrid"}=e,s=(c,u)=>{let{container:f,direction:m,spacing:p,wrap:y,size:x}=c,T={root:["root",f&&"container",y!=="wrap"&&`wrap-xs-${String(y)}`,...Gv(m),...Wv(x),...f?Hv(p,u.breakpoints.keys[0]):[]]};return ke(T,S=>we(n,S),{})};function i(c,u,f=()=>!0){let m={};return c===null||(Array.isArray(c)?c.forEach((p,y)=>{p!==null&&f(p)&&u.keys[y]&&(m[u.keys[y]]=p)}):typeof c=="object"?Object.keys(c).forEach(p=>{let y=c[p];y!=null&&f(y)&&(m[p]=y)}):m[u.keys[0]]=c),m}let a=t(jv,Vv,Fv,Bv,Uv,Zv,Lv),l=ue(function(u,f){let m=o(),y=r(u),{className:x,children:T,columns:S=12,container:v=!1,component:R="div",direction:P="row",wrap:O="wrap",size:E={},offset:A={},spacing:I=0,rowSpacing:N=I,columnSpacing:D=I,unstable_level:w=0,...$}=y,h=i(E,m.breakpoints,G=>G!==!1),z=i(A,m.breakpoints),k=u.columns??(w?void 0:S),j=u.spacing??(w?void 0:I),B=u.rowSpacing??u.spacing??(w?void 0:N),W=u.columnSpacing??u.spacing??(w?void 0:D),H={...y,level:w,columns:k,container:v,direction:P,wrap:O,spacing:j,rowSpacing:B,columnSpacing:W,size:h,offset:z},ee=s(H,m);return b(a,{ref:f,as:R,ownerState:H,className:he(ee.root,x),...$,children:zn.map(T,G=>Rt(G)&&up(G,["Grid"])&&v&&G.props.container?vr(G,{unstable_level:G.props?.unstable_level??w+1}):G)})});return l.muiName="Grid",l}var IR={black:"#000",white:"#fff"},Ra=IR;var NR={50:"#fafafa",100:"#f5f5f5",200:"#eeeeee",300:"#e0e0e0",400:"#bdbdbd",500:"#9e9e9e",600:"#757575",700:"#616161",800:"#424242",900:"#212121",A100:"#f5f5f5",A200:"#eeeeee",A400:"#bdbdbd",A700:"#616161"},Kv=NR;var zR={50:"#f3e5f5",100:"#e1bee7",200:"#ce93d8",300:"#ba68c8",400:"#ab47bc",500:"#9c27b0",600:"#8e24aa",700:"#7b1fa2",800:"#6a1b9a",900:"#4a148c",A100:"#ea80fc",A200:"#e040fb",A400:"#d500f9",A700:"#aa00ff"},oi=zR;var DR={50:"#ffebee",100:"#ffcdd2",200:"#ef9a9a",300:"#e57373",400:"#ef5350",500:"#f44336",600:"#e53935",700:"#d32f2f",800:"#c62828",900:"#b71c1c",A100:"#ff8a80",A200:"#ff5252",A400:"#ff1744",A700:"#d50000"},ni=DR;var BR={50:"#fff3e0",100:"#ffe0b2",200:"#ffcc80",300:"#ffb74d",400:"#ffa726",500:"#ff9800",600:"#fb8c00",700:"#f57c00",800:"#ef6c00",900:"#e65100",A100:"#ffd180",A200:"#ffab40",A400:"#ff9100",A700:"#ff6d00"},ka=BR;var LR={50:"#e3f2fd",100:"#bbdefb",200:"#90caf9",300:"#64b5f6",400:"#42a5f5",500:"#2196f3",600:"#1e88e5",700:"#1976d2",800:"#1565c0",900:"#0d47a1",A100:"#82b1ff",A200:"#448aff",A400:"#2979ff",A700:"#2962ff"},si=LR;var jR={50:"#e1f5fe",100:"#b3e5fc",200:"#81d4fa",300:"#4fc3f7",400:"#29b6f6",500:"#03a9f4",600:"#039be5",700:"#0288d1",800:"#0277bd",900:"#01579b",A100:"#80d8ff",A200:"#40c4ff",A400:"#00b0ff",A700:"#0091ea"},ii=jR;var FR={50:"#e8f5e9",100:"#c8e6c9",200:"#a5d6a7",300:"#81c784",400:"#66bb6a",500:"#4caf50",600:"#43a047",700:"#388e3c",800:"#2e7d32",900:"#1b5e20",A100:"#b9f6ca",A200:"#69f0ae",A400:"#00e676",A700:"#00c853"},ai=FR;function Xv(){return{text:{primary:"rgba(0, 0, 0, 0.87)",secondary:"rgba(0, 0, 0, 0.6)",disabled:"rgba(0, 0, 0, 0.38)"},divider:"rgba(0, 0, 0, 0.12)",background:{paper:Ra.white,default:Ra.white},action:{active:"rgba(0, 0, 0, 0.54)",hover:"rgba(0, 0, 0, 0.04)",hoverOpacity:.04,selected:"rgba(0, 0, 0, 0.08)",selectedOpacity:.08,disabled:"rgba(0, 0, 0, 0.26)",disabledBackground:"rgba(0, 0, 0, 0.12)",disabledOpacity:.38,focus:"rgba(0, 0, 0, 0.12)",focusOpacity:.12,activatedOpacity:.12}}}var wm=Xv();function Jv(){return{text:{primary:Ra.white,secondary:"rgba(255, 255, 255, 0.7)",disabled:"rgba(255, 255, 255, 0.5)",icon:"rgba(255, 255, 255, 0.5)"},divider:"rgba(255, 255, 255, 0.12)",background:{paper:"#121212",default:"#121212"},action:{active:Ra.white,hover:"rgba(255, 255, 255, 0.08)",hoverOpacity:.08,selected:"rgba(255, 255, 255, 0.16)",selectedOpacity:.16,disabled:"rgba(255, 255, 255, 0.3)",disabledBackground:"rgba(255, 255, 255, 0.12)",disabledOpacity:.38,focus:"rgba(255, 255, 255, 0.12)",focusOpacity:.12,activatedOpacity:.24}}}var mp=Jv();function qv(e,t,r,o){let n=o.light||o,s=o.dark||o*1.5;e[t]||(e.hasOwnProperty(r)?e[t]=e[r]:t==="light"?e.light=_a(e.main,n):t==="dark"&&(e.dark=Pa(e.main,s)))}function Yv(e,t,r,o,n){let s=n.light||n,i=n.dark||n*1.5;t[r]||(t.hasOwnProperty(o)?t[r]=t[o]:r==="light"?t.light=`color-mix(in ${e}, ${t.main}, #fff ${(s*100).toFixed(0)}%)`:r==="dark"&&(t.dark=`color-mix(in ${e}, ${t.main}, #000 ${(i*100).toFixed(0)}%)`))}function VR(e="light"){return e==="dark"?{main:si[200],light:si[50],dark:si[400]}:{main:si[700],light:si[400],dark:si[800]}}function UR(e="light"){return e==="dark"?{main:oi[200],light:oi[50],dark:oi[400]}:{main:oi[500],light:oi[300],dark:oi[700]}}function ZR(e="light"){return e==="dark"?{main:ni[500],light:ni[300],dark:ni[700]}:{main:ni[700],light:ni[400],dark:ni[800]}}function WR(e="light"){return e==="dark"?{main:ii[400],light:ii[300],dark:ii[700]}:{main:ii[700],light:ii[500],dark:ii[900]}}function HR(e="light"){return e==="dark"?{main:ai[400],light:ai[300],dark:ai[700]}:{main:ai[800],light:ai[500],dark:ai[900]}}function GR(e="light"){return e==="dark"?{main:ka[400],light:ka[300],dark:ka[700]}:{main:"#ed6c02",light:ka[500],dark:ka[900]}}function KR(e){return`oklch(from ${e} var(--__l) 0 h / var(--__a))`}function li(e){let{mode:t="light",contrastThreshold:r=3,tonalOffset:o=.2,colorSpace:n,...s}=e,i=e.primary||VR(t),a=e.secondary||UR(t),l=e.error||ZR(t),c=e.info||WR(t),u=e.success||HR(t),f=e.warning||GR(t);function m(T){return n?KR(T):Pv(T,mp.text.primary)>=r?mp.text.primary:wm.text.primary}let p=({color:T,name:S,mainShade:v=500,lightShade:R=300,darkShade:P=700})=>{if(T={...T},!T.main&&T[v]&&(T.main=T[v]),!T.hasOwnProperty("main"))throw new Error(Nr(11,S?` (${S})`:"",v));if(typeof T.main!="string")throw new Error(Nr(12,S?` (${S})`:"",JSON.stringify(T.main)));return n?(Yv(n,T,"light",R,o),Yv(n,T,"dark",P,o)):(qv(T,"light",R,o),qv(T,"dark",P,o)),T.contrastText||(T.contrastText=m(T.main)),T},y;return t==="light"?y=Xv():t==="dark"&&(y=Jv()),Dt({common:{...Ra},mode:t,primary:p({color:i,name:"primary"}),secondary:p({color:a,name:"secondary",mainShade:"A400",lightShade:"A200",darkShade:"A700"}),error:p({color:l,name:"error"}),warning:p({color:f,name:"warning"}),info:p({color:c,name:"info"}),success:p({color:u,name:"success"}),grey:Kv,contrastThreshold:r,getContrastText:m,augmentColor:p,tonalOffset:o,...y},s)}var Wl="--_focusVisible-offset",hp="--_focusVisible-behavior",Qv="--_focusVisible-shadow",qR=`var(${Wl}, 1)`,YR=`var(${hp}, )`,yp={[Wl]:1,[hp]:"initial"};function Oa(e){return{[Qv]:e}}function e0(e){return{[Wl]:-e,[hp]:"inset"}}function gp(e,t){return t.reduce((r,o)=>o&&"focusVisible"in o?Dt(r,{focusVisible:o.focusVisible}):r,{focusVisible:e}).focusVisible}function t0(e){return e!=null&&typeof e=="object"&&typeof e.outlineOffset=="string"&&e.outlineOffset.includes(Wl)}function Aa(e,t){return XR({outlineStyle:"solid",outlineColor:t,outlineWidth:2,outlineOffset:2,boxShadow:`var(${Qv}, 0 0)`,...e===!0?null:e})}function XR(e){let t=e.outlineOffset??0;if(typeof t!="string"||!t.includes(Wl)){let o=typeof t=="number"?`${t}px`:t;e.outlineOffset=`calc(${qR} * ${o})`}let r=new Set(["none","initial","inherit","unset","revert","revert-layer"]);return typeof e.boxShadow=="string"&&!r.has(e.boxShadow.trim().toLowerCase())&&!/\binset\b/.test(e.boxShadow)&&!e.boxShadow.includes(hp)&&(e.boxShadow=`${YR} ${e.boxShadow}`),e}function bp(e){let t={};return Object.entries(e).forEach(o=>{let[n,s]=o;typeof s=="object"&&(t[n]=`${s.fontStyle?`${s.fontStyle} `:""}${s.fontVariant?`${s.fontVariant} `:""}${s.fontWeight?`${s.fontWeight} `:""}${s.fontStretch?`${s.fontStretch} `:""}${s.fontSize||""}${s.lineHeight?`/${s.lineHeight} `:""}${s.fontFamily||""}`)}),t}function Cm(e,t){return{toolbar:{minHeight:56,[e.up("xs")]:{"@media (orientation: landscape)":{minHeight:48}},[e.up("sm")]:{minHeight:64}},...t}}function JR(e){return Math.round(e*1e5)/1e5}var r0={textTransform:"uppercase"},o0='"Roboto", "Helvetica", "Arial", sans-serif';function Hl(e,t){let{fontFamily:r=o0,fontSize:o=14,fontWeightLight:n=300,fontWeightRegular:s=400,fontWeightMedium:i=500,fontWeightBold:a=700,htmlFontSize:l=16,allVariants:c,pxToRem:u,...f}=typeof t=="function"?t(e):t,m=o/14,p=u||(T=>`${T/l*m}rem`),y=(T,S,v,R,P)=>({fontFamily:r,fontWeight:T,fontSize:p(S),lineHeight:v,...r===o0?{letterSpacing:`${JR(R/S)}em`}:{},...P,...c}),x={h1:y(n,96,1.167,-1.5),h2:y(n,60,1.2,-.5),h3:y(s,48,1.167,0),h4:y(s,34,1.235,.25),h5:y(s,24,1.334,0),h6:y(i,20,1.6,.15),subtitle1:y(s,16,1.75,.15),subtitle2:y(i,14,1.57,.1),body1:y(s,16,1.5,.15),body2:y(s,14,1.43,.15),button:y(i,14,1.75,.4,r0),caption:y(s,12,1.66,.4),overline:y(s,12,2.66,1,r0),inherit:{fontFamily:"inherit",fontWeight:"inherit",fontSize:"inherit",lineHeight:"inherit",letterSpacing:"inherit"}};return Dt({htmlFontSize:l,pxToRem:p,fontFamily:r,fontSize:o,fontWeightLight:n,fontWeightRegular:s,fontWeightMedium:i,fontWeightBold:a,...x},f,{clone:!1})}function Bt(...e){return[`${e[0]}px ${e[1]}px ${e[2]}px ${e[3]}px rgba(0,0,0,${.2})`,`${e[4]}px ${e[5]}px ${e[6]}px ${e[7]}px rgba(0,0,0,${.14})`,`${e[8]}px ${e[9]}px ${e[10]}px ${e[11]}px rgba(0,0,0,${.12})`].join(",")}var QR=["none",Bt(0,2,1,-1,0,1,1,0,0,1,3,0),Bt(0,3,1,-2,0,2,2,0,0,1,5,0),Bt(0,3,3,-2,0,3,4,0,0,1,8,0),Bt(0,2,4,-1,0,4,5,0,0,1,10,0),Bt(0,3,5,-1,0,5,8,0,0,1,14,0),Bt(0,3,5,-1,0,6,10,0,0,1,18,0),Bt(0,4,5,-2,0,7,10,1,0,2,16,1),Bt(0,5,5,-3,0,8,10,1,0,3,14,2),Bt(0,5,6,-3,0,9,12,1,0,3,16,2),Bt(0,6,6,-3,0,10,14,1,0,4,18,3),Bt(0,6,7,-4,0,11,15,1,0,4,20,3),Bt(0,7,8,-4,0,12,17,2,0,5,22,4),Bt(0,7,8,-4,0,13,19,2,0,5,24,4),Bt(0,7,9,-4,0,14,21,2,0,5,26,4),Bt(0,8,9,-5,0,15,22,2,0,6,28,5),Bt(0,8,10,-5,0,16,24,2,0,6,30,5),Bt(0,8,11,-5,0,17,26,2,0,6,32,5),Bt(0,9,11,-5,0,18,28,2,0,7,34,6),Bt(0,9,12,-6,0,19,29,2,0,7,36,6),Bt(0,10,13,-6,0,20,31,3,0,8,38,7),Bt(0,10,13,-6,0,21,33,3,0,8,40,7),Bt(0,10,14,-6,0,22,35,3,0,8,42,7),Bt(0,11,14,-7,0,23,36,3,0,9,44,8),Bt(0,11,15,-7,0,24,38,3,0,9,46,8)],n0=QR;var ek=["all"],tk={},rk={easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)",easeOut:"cubic-bezier(0.0, 0, 0.2, 1)",easeIn:"cubic-bezier(0.4, 0, 1, 1)",sharp:"cubic-bezier(0.4, 0, 0.6, 1)"},ok={shortest:150,shorter:200,short:250,standard:300,complex:375,enteringScreen:225,leavingScreen:195};function s0(e){return`${Math.round(e)}ms`}function nk(e){if(!e)return 0;let t=e/36;return Math.min(Math.round((4+15*t**.25+t/5)*10),3e3)}function Em(e){let t={...e};delete t.reducedMotion;let r={...rk,...t.easing},o={...ok,...t.duration},n=(i=ek,a=tk)=>{let{duration:l=o.standard,easing:c=r.easeInOut,delay:u=0,...f}=a;return(Array.isArray(i)?i:[i]).map(m=>`${m} ${typeof l=="string"?l:s0(l)} ${c} ${typeof u=="string"?u:s0(u)}`).join(",")},s=t.create??n;return{getAutoHeightDuration:nk,create:s,...t,easing:r,duration:o}}var sk={};function Rm(e=sk){return{reducedMotion:"never",...e}}var ik={mobileStepper:1e3,fab:1050,speedDial:1050,appBar:1100,drawer:1200,modal:1300,snackbar:1400,tooltip:1500},i0=ik;function ak(e){return Xo(e)||typeof e>"u"||typeof e=="string"||typeof e=="boolean"||typeof e=="number"||Array.isArray(e)}function xp(e={}){let t={...e};function r(o){let n=Object.entries(o);for(let s=0;s<n.length;s++){let[i,a]=n[s];!ak(a)||i.startsWith("unstable_")||i.startsWith("internal_")?delete o[i]:Xo(a)&&(o[i]={...a},r(o[i]))}}return r(t),`import { unstable_createBreakpoints as createBreakpoints, createTransitions } from '@mui/material/styles';++const theme = ${JSON.stringify(t,null,2)};++theme.breakpoints = createBreakpoints(theme.breakpoints || {});+theme.motion = { reducedMotion: 'never', ...theme.motion };+theme.transitions = createTransitions(theme.transitions || {});++export default theme;`}function a0(e){return typeof e=="number"?`${(e*100).toFixed(0)}%`:`calc((${e}) * 100%)`}var lk=e=>{if(!Number.isNaN(+e))return+e;let t=e.match(/\d*\.?\d+/g);if(!t)return 0;let r=0;for(let o=0;o<t.length;o+=1)r+=+t[o];return r};function l0(e){return e.startsWith("hsl")?jl(e):e}function ck(e,t,r=""){let o=r.trim();if(o&&!o.startsWith("color("))try{let n=bm(l0(o));if(n.split(" ").length===3&&!n.includes("NaN"))return`var(--${t}Channel, ${n})`}catch{}return`var(--${t}Channel)`}function uk(e){Object.assign(e,{alpha(t,r){let o=this||e;if(o.colorSpace)return`oklch(from ${t} l c h / ${typeof r=="string"?`calc(${r})`:r})`;if(o.vars){let n=typeof r=="string"?`calc(${r})`:r;return t.startsWith("color(")?t.replace(/\s*(?:\/[^)]*)?\)$/,` / ${n})`):`rgba(${t.includes("var(")?t.replace(/var\(--([^,\s)]+)(?:,((?:[^()]|\([^()]*\))+)\)|(?:,[^)]+)?\)+)/g,ck):Ps(l0(t))} / ${n})`}return Ta(t,lk(r))},lighten(t,r){let o=this||e;return o.colorSpace?`color-mix(in ${o.colorSpace}, ${t}, #fff ${a0(r)})`:_a(t,r)},darken(t,r){let o=this||e;return o.colorSpace?`color-mix(in ${o.colorSpace}, ${t}, #000 ${a0(r)})`:Pa(t,r)}})}function pk(e={},...t){let{breakpoints:r,mixins:o={},spacing:n,palette:s={},motion:i={},transitions:a={},typography:l={},shape:c,colorSpace:u,...f}=e;if(e.vars&&e.generateThemeVars===void 0)throw new Error(Nr(22));let m=li({...s,colorSpace:u}),p=en(e),y=Dt(p,{mixins:Cm(p.breakpoints,o),palette:m,shadows:n0.slice(),typography:Hl(m,l),motion:Rm(i),transitions:Em(a),zIndex:{...i0}});return y=Dt(y,f),y=t.reduce((x,T)=>Dt(x,T),y),delete y.transitions.reducedMotion,y.focusVisible!=null&&y.focusVisible!==!1&&(y.focusVisible=Aa(y.focusVisible,y.palette.primary.main)),y.unstable_sxConfig={...Vn,...f?.unstable_sxConfig},y.unstable_sx=function(T){return Qr({sx:T,theme:this})},y.toRuntimeSource=xp,uk(y),y}var Gl=pk;function Ma(e){let t;return e<1?t=5.11916*e**2:t=4.5*Math.log(e+1)+2,Math.round(t*10)/1e3}var fk=[...Array(25)].map((e,t)=>{if(t===0)return"none";let r=Ma(t);return`linear-gradient(rgba(255 255 255 / ${r}), rgba(255 255 255 / ${r}))`});function km(e){return{inputPlaceholder:e==="dark"?.5:.42,inputUnderline:e==="dark"?.7:.42,switchTrackDisabled:e==="dark"?.2:.12,switchTrack:e==="dark"?.3:.38}}function Om(e){return e==="dark"?fk:[]}function Am(e){let{palette:t={mode:"light"},opacity:r,overlays:o,colorSpace:n,...s}=e,i=li({...t,colorSpace:n});return{palette:i,opacity:{...km(i.mode),...r},overlays:o||Om(i.mode),...s}}function Mm(e){return e[0]==="motion"||e[0]==="focusVisible"||!!e[0].match(/(cssVarPrefix|colorSchemeSelector|modularCssLayers|rootSelector|typography|mixins|breakpoints|direction|transitions)/)||!!e[0].match(/sxConfig$/)||e[0]==="palette"&&!!e[1]?.match(/(mode|contrastThreshold|tonalOffset)/)}var dk=e=>[...[...Array(25)].map((t,r)=>`--${e?`${e}-`:""}overlays-${r}`),`--${e?`${e}-`:""}palette-AppBar-darkBg`,`--${e?`${e}-`:""}palette-AppBar-darkColor`],c0=dk;var u0=e=>(t,r)=>{let o=e.rootSelector||":root",n=e.colorSchemeSelector,s=n;if(n==="class"&&(s=".%s"),n==="data"&&(s="[data-%s]"),n?.startsWith("data-")&&!n.includes("%s")&&(s=`[${n}="%s"]`),e.defaultColorScheme===t){if(t==="dark"){let i={};return c0(e.cssVarPrefix).forEach(a=>{i[a]=r[a],delete r[a]}),s==="media"?{[o]:r,"@media (prefers-color-scheme: dark)":{[o]:i}}:s?{[s.replace("%s",t)]:i,[`${o}, ${s.replace("%s",t)}`]:r}:{[o]:{...r,...i}}}if(s&&s!=="media")return`${o}, ${s.replace("%s",String(t))}`}else if(t){if(s==="media")return{[`@media (prefers-color-scheme: ${String(t)})`]:{[o]:r}};if(s)return s.replace("%s",String(t))}return o};function mk(e,t){t.forEach(r=>{e[r]||(e[r]={})})}function U(e,t,r){!e[t]&&r&&(e[t]=r)}function Kl(e){return typeof e!="string"||!e.startsWith("hsl")?e:jl(e)}function En(e,t){`${t}Channel`in e||(e[`${t}Channel`]=Ps(Kl(e[t]),`MUI: Can't create \`palette.${t}Channel\` because \`palette.${t}\` is not one of these formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color().+To suppress this warning, you need to explicitly provide the \`palette.${t}Channel\` as a string (in rgb format, for example "12 12 12") or undefined if you want to remove the channel token.`))}function hk(e){return typeof e=="number"?`${e}px`:typeof e=="string"||typeof e=="function"||Array.isArray(e)?e:"8px"}var Rn=e=>{try{return e()}catch{}},yk=(e="mui")=>lp(e);function $m(e,t,r,o,n){if(!r)return;r=r===!0?{}:r;let s=n==="dark"?"dark":"light";if(!o){t[n]=Am({...r,palette:{mode:s,...r?.palette},colorSpace:e});return}let{palette:i,...a}=Gl({...o,palette:{mode:s,...r?.palette},colorSpace:e});return t[n]={...r,palette:i,opacity:{...km(s),...r?.opacity},overlays:r?.overlays||Om(s)},a}function Im(e={},...t){let{colorSchemes:r={light:!0},defaultColorScheme:o,disableCssColorScheme:n=!1,cssVarPrefix:s="mui",nativeColor:i=!1,shouldSkipGeneratingVar:a=Mm,colorSchemeSelector:l=r.light&&r.dark?"media":void 0,rootSelector:c=":root",...u}=e,f=Object.keys(r)[0],m=o||(r.light&&f!=="light"?"light":f),p=yk(s),{[m]:y,light:x,dark:T,...S}=r,v={...S},R=y;if((m==="dark"&&!("dark"in r)||m==="light"&&!("light"in r))&&(R=!0),!R)throw new Error(Nr(21,m));let P;i&&(P="oklch");let O=$m(P,v,R,u,m);x&&!v.light&&$m(P,v,x,void 0,"light"),T&&!v.dark&&$m(P,v,T,void 0,"dark");let E={defaultColorScheme:m,...O,cssVarPrefix:s,colorSchemeSelector:l,rootSelector:c,getCssVar:p,colorSchemes:v,font:{...bp(O.typography),...O.font},spacing:hk(u.spacing)};Object.keys(E.colorSchemes).forEach($=>{let h=E.colorSchemes[$].palette,z=j=>{let B=j.split("-"),W=B[1],H=B[2];return p(j,h[W][H])};h.mode==="light"&&(U(h.common,"background","#fff"),U(h.common,"onBackground","#000")),h.mode==="dark"&&(U(h.common,"background","#000"),U(h.common,"onBackground","#fff")),i||En(h.text,"primary");function k(j,B,W){if(P){let H;return j===_s&&(H=`transparent ${((1-W)*100).toFixed(0)}%`),j===ut&&(H=`#000 ${(W*100).toFixed(0)}%`),j===pt&&(H=`#fff ${(W*100).toFixed(0)}%`),`color-mix(in ${P}, ${B}, ${H})`}return j(B,W)}if(mk(h,["Alert","AppBar","Avatar","Button","Chip","FilledInput","Input","LinearProgress","Skeleton","Slider","SnackbarContent","SpeedDialAction","StepConnector","StepContent","Switch","TableCell","Tooltip"]),h.mode==="light"){U(h.Alert,"errorColor",k(ut,i?p("palette-error-light"):h.error.light,.6)),U(h.Alert,"infoColor",k(ut,i?p("palette-info-light"):h.info.light,.6)),U(h.Alert,"successColor",k(ut,i?p("palette-success-light"):h.success.light,.6)),U(h.Alert,"warningColor",k(ut,i?p("palette-warning-light"):h.warning.light,.6)),U(h.Alert,"errorFilledBg",z("palette-error-main")),U(h.Alert,"infoFilledBg",z("palette-info-main")),U(h.Alert,"successFilledBg",z("palette-success-main")),U(h.Alert,"warningFilledBg",z("palette-warning-main")),U(h.Alert,"errorFilledColor",Rn(()=>h.getContrastText(h.error.main))),U(h.Alert,"infoFilledColor",Rn(()=>h.getContrastText(h.info.main))),U(h.Alert,"successFilledColor",Rn(()=>h.getContrastText(h.success.main))),U(h.Alert,"warningFilledColor",Rn(()=>h.getContrastText(h.warning.main))),U(h.Alert,"errorStandardBg",k(pt,i?p("palette-error-light"):h.error.light,.9)),U(h.Alert,"infoStandardBg",k(pt,i?p("palette-info-light"):h.info.light,.9)),U(h.Alert,"successStandardBg",k(pt,i?p("palette-success-light"):h.success.light,.9)),U(h.Alert,"warningStandardBg",k(pt,i?p("palette-warning-light"):h.warning.light,.9)),U(h.Alert,"errorIconColor",z("palette-error-main")),U(h.Alert,"infoIconColor",z("palette-info-main")),U(h.Alert,"successIconColor",z("palette-success-main")),U(h.Alert,"warningIconColor",z("palette-warning-main")),U(h.AppBar,"defaultBg",z("palette-grey-100")),U(h.Avatar,"defaultBg",z("palette-grey-400")),U(h.Button,"inheritContainedBg",z("palette-grey-300")),U(h.Button,"inheritContainedHoverBg",z("palette-grey-A100")),U(h.Chip,"defaultBorder",z("palette-grey-400")),U(h.Chip,"defaultAvatarColor",z("palette-grey-700")),U(h.Chip,"defaultIconColor",z("palette-grey-700")),U(h.FilledInput,"bg","rgba(0, 0, 0, 0.06)"),U(h.FilledInput,"hoverBg","rgba(0, 0, 0, 0.09)"),U(h.FilledInput,"disabledBg","rgba(0, 0, 0, 0.12)"),U(h.Input,"autofillWebkitBoxShadow","none"),U(h.LinearProgress,"primaryBg",k(pt,i?p("palette-primary-main"):h.primary.main,.62)),U(h.LinearProgress,"secondaryBg",k(pt,i?p("palette-secondary-main"):h.secondary.main,.62)),U(h.LinearProgress,"errorBg",k(pt,i?p("palette-error-main"):h.error.main,.62)),U(h.LinearProgress,"infoBg",k(pt,i?p("palette-info-main"):h.info.main,.62)),U(h.LinearProgress,"successBg",k(pt,i?p("palette-success-main"):h.success.main,.62)),U(h.LinearProgress,"warningBg",k(pt,i?p("palette-warning-light"):h.warning.main,.62)),U(h.Skeleton,"bg",P?k(_s,i?p("palette-text-primary"):h.text.primary,.11):`rgba(${z("palette-text-primaryChannel")} / 0.11)`),U(h.Slider,"primaryTrack",k(pt,i?p("palette-primary-main"):h.primary.main,.62)),U(h.Slider,"secondaryTrack",k(pt,i?p("palette-secondary-main"):h.secondary.main,.62)),U(h.Slider,"errorTrack",k(pt,i?p("palette-error-main"):h.error.main,.62)),U(h.Slider,"infoTrack",k(pt,i?p("palette-info-main"):h.info.main,.62)),U(h.Slider,"successTrack",k(pt,i?p("palette-success-main"):h.success.main,.62)),U(h.Slider,"warningTrack",k(pt,i?p("palette-warning-main"):h.warning.main,.62));let j=P?k(ut,i?p("palette-background-default"):h.background.default,.6825):Fl(h.background.default,.8);U(h.SnackbarContent,"bg",j),U(h.SnackbarContent,"color",Rn(()=>P?mp.text.primary:h.getContrastText(j))),U(h.SpeedDialAction,"fabHoverBg",Fl(h.background.paper,.15)),U(h.StepConnector,"border",z("palette-grey-400")),U(h.StepContent,"border",z("palette-grey-400")),U(h.Switch,"defaultColor",z("palette-common-white")),U(h.Switch,"defaultDisabledColor",z("palette-grey-100")),U(h.Switch,"primaryDisabledColor",k(pt,i?p("palette-primary-main"):h.primary.main,.62)),U(h.Switch,"secondaryDisabledColor",k(pt,i?p("palette-secondary-main"):h.secondary.main,.62)),U(h.Switch,"errorDisabledColor",k(pt,i?p("palette-error-main"):h.error.main,.62)),U(h.Switch,"infoDisabledColor",k(pt,i?p("palette-info-main"):h.info.main,.62)),U(h.Switch,"successDisabledColor",k(pt,i?p("palette-success-main"):h.success.main,.62)),U(h.Switch,"warningDisabledColor",k(pt,i?p("palette-warning-main"):h.warning.main,.62)),U(h.TableCell,"border",k(pt,_s(i?p("palette-divider"):h.divider,1),.88)),U(h.Tooltip,"bg",k(_s,i?p("palette-grey-700"):h.grey[700],.92))}if(h.mode==="dark"){U(h.Alert,"errorColor",k(pt,i?p("palette-error-light"):h.error.light,.6)),U(h.Alert,"infoColor",k(pt,i?p("palette-info-light"):h.info.light,.6)),U(h.Alert,"successColor",k(pt,i?p("palette-success-light"):h.success.light,.6)),U(h.Alert,"warningColor",k(pt,i?p("palette-warning-light"):h.warning.light,.6)),U(h.Alert,"errorFilledBg",z("palette-error-dark")),U(h.Alert,"infoFilledBg",z("palette-info-dark")),U(h.Alert,"successFilledBg",z("palette-success-dark")),U(h.Alert,"warningFilledBg",z("palette-warning-dark")),U(h.Alert,"errorFilledColor",Rn(()=>h.getContrastText(h.error.dark))),U(h.Alert,"infoFilledColor",Rn(()=>h.getContrastText(h.info.dark))),U(h.Alert,"successFilledColor",Rn(()=>h.getContrastText(h.success.dark))),U(h.Alert,"warningFilledColor",Rn(()=>h.getContrastText(h.warning.dark))),U(h.Alert,"errorStandardBg",k(ut,i?p("palette-error-light"):h.error.light,.9)),U(h.Alert,"infoStandardBg",k(ut,i?p("palette-info-light"):h.info.light,.9)),U(h.Alert,"successStandardBg",k(ut,i?p("palette-success-light"):h.success.light,.9)),U(h.Alert,"warningStandardBg",k(ut,i?p("palette-warning-light"):h.warning.light,.9)),U(h.Alert,"errorIconColor",z("palette-error-main")),U(h.Alert,"infoIconColor",z("palette-info-main")),U(h.Alert,"successIconColor",z("palette-success-main")),U(h.Alert,"warningIconColor",z("palette-warning-main")),U(h.AppBar,"defaultBg",z("palette-grey-900")),U(h.AppBar,"darkBg",z("palette-background-paper")),U(h.AppBar,"darkColor",z("palette-text-primary")),U(h.Avatar,"defaultBg",z("palette-grey-600")),U(h.Button,"inheritContainedBg",z("palette-grey-800")),U(h.Button,"inheritContainedHoverBg",z("palette-grey-700")),U(h.Chip,"defaultBorder",z("palette-grey-700")),U(h.Chip,"defaultAvatarColor",z("palette-grey-300")),U(h.Chip,"defaultIconColor",z("palette-grey-300")),U(h.FilledInput,"bg","rgba(255, 255, 255, 0.09)"),U(h.FilledInput,"hoverBg","rgba(255, 255, 255, 0.13)"),U(h.FilledInput,"disabledBg","rgba(255, 255, 255, 0.12)"),U(h.Input,"autofillWebkitBoxShadow","0 0 0 100px #266798 inset"),U(h.LinearProgress,"primaryBg",k(ut,i?p("palette-primary-main"):h.primary.main,.5)),U(h.LinearProgress,"secondaryBg",k(ut,i?p("palette-secondary-main"):h.secondary.main,.5)),U(h.LinearProgress,"errorBg",k(ut,i?p("palette-error-main"):h.error.main,.5)),U(h.LinearProgress,"infoBg",k(ut,i?p("palette-info-main"):h.info.main,.5)),U(h.LinearProgress,"successBg",k(ut,i?p("palette-success-main"):h.success.main,.5)),U(h.LinearProgress,"warningBg",k(ut,i?p("palette-warning-main"):h.warning.main,.5)),U(h.Skeleton,"bg",P?k(_s,i?p("palette-text-primary"):h.text.primary,.13):`rgba(${z("palette-text-primaryChannel")} / 0.13)`),U(h.Slider,"primaryTrack",k(ut,i?p("palette-primary-main"):h.primary.main,.5)),U(h.Slider,"secondaryTrack",k(ut,i?p("palette-secondary-main"):h.secondary.main,.5)),U(h.Slider,"errorTrack",k(ut,i?p("palette-error-main"):h.error.main,.5)),U(h.Slider,"infoTrack",k(ut,i?p("palette-info-main"):h.info.main,.5)),U(h.Slider,"successTrack",k(ut,i?p("palette-success-main"):h.success.main,.5)),U(h.Slider,"warningTrack",k(ut,i?p("palette-warning-light"):h.warning.main,.5));let j=P?k(pt,i?p("palette-background-default"):h.background.default,.985):Fl(h.background.default,.98);U(h.SnackbarContent,"bg",j),U(h.SnackbarContent,"color",Rn(()=>P?wm.text.primary:h.getContrastText(j))),U(h.SpeedDialAction,"fabHoverBg",Fl(h.background.paper,.15)),U(h.StepConnector,"border",z("palette-grey-600")),U(h.StepContent,"border",z("palette-grey-600")),U(h.Switch,"defaultColor",z("palette-grey-300")),U(h.Switch,"defaultDisabledColor",z("palette-grey-600")),U(h.Switch,"primaryDisabledColor",k(ut,i?p("palette-primary-main"):h.primary.main,.55)),U(h.Switch,"secondaryDisabledColor",k(ut,i?p("palette-secondary-main"):h.secondary.main,.55)),U(h.Switch,"errorDisabledColor",k(ut,i?p("palette-error-main"):h.error.main,.55)),U(h.Switch,"infoDisabledColor",k(ut,i?p("palette-info-main"):h.info.main,.55)),U(h.Switch,"successDisabledColor",k(ut,i?p("palette-success-main"):h.success.main,.55)),U(h.Switch,"warningDisabledColor",k(ut,i?p("palette-warning-light"):h.warning.main,.55)),U(h.TableCell,"border",k(ut,_s(i?p("palette-divider"):h.divider,1),.68)),U(h.Tooltip,"bg",k(_s,i?p("palette-grey-700"):h.grey[700],.92))}i||(En(h.background,"default"),En(h.background,"paper"),En(h.common,"background"),En(h.common,"onBackground"),En(h,"divider")),Object.keys(h).forEach(j=>{let B=h[j];j!=="tonalOffset"&&!i&&B&&typeof B=="object"&&(B.main&&U(h[j],"mainChannel",Ps(Kl(B.main))),B.light&&U(h[j],"lightChannel",Ps(Kl(B.light))),B.dark&&U(h[j],"darkChannel",Ps(Kl(B.dark))),B.contrastText&&U(h[j],"contrastTextChannel",Ps(Kl(B.contrastText))),j==="text"&&(En(h[j],"primary"),En(h[j],"secondary")),j==="action"&&(B.active&&En(h[j],"active"),B.selected&&En(h[j],"selected")))})}),E=t.reduce(($,h)=>Dt($,h),E);let A=gp(e.focusVisible,t);A!=null&&A!==!1&&(E.focusVisible=Aa(A,p("palette-primary-main")));let I={prefix:s,disableCssColorScheme:n,shouldSkipGeneratingVar:a,getSelector:u0(E),enableContrastVars:i},{vars:N,generateThemeVars:D,generateStyleSheets:w}=_m(E,I);return E.vars=N,Object.entries(E.colorSchemes[E.defaultColorScheme]).forEach(([$,h])=>{E[$]=h}),E.generateThemeVars=D,E.generateStyleSheets=w,E.generateSpacing=function(){return ya(u.spacing,Sl(this))},E.getColorSchemeSelector=Sm(l),E.spacing=E.generateSpacing(),E.shouldSkipGeneratingVar=a,E.unstable_sxConfig={...Vn,...u?.unstable_sxConfig},E.unstable_sx=function(h){return Qr({sx:h,theme:this})},E.internal_cache={},E.toRuntimeSource=xp,E}function p0(e,t,r){e.colorSchemes&&r&&(e.colorSchemes[t]={...r!==!0&&r,palette:li({...r===!0?{}:r.palette,mode:t})})}function kn(e={},...t){let{palette:r,cssVariables:o=!1,colorSchemes:n=r?void 0:{light:!0},defaultColorScheme:s=r?.mode,...i}=e,a=s||"light",l=n?.[a],c={...n,...r?{[a]:{...typeof l!="boolean"&&l,palette:r}}:void 0};if(o===!1){if(!("colorSchemes"in e))return Gl(e,...t);let u=r;"palette"in e||c[a]&&(c[a]!==!0?u=c[a].palette:a==="dark"&&(u={mode:"dark"}));let f=Gl({...e,palette:u},...t);if(f.defaultColorScheme=a,f.colorSchemes=c,f.palette.mode==="light"&&(f.colorSchemes.light={...c.light!==!0&&c.light,palette:f.palette},p0(f,"dark",c.dark)),f.palette.mode==="dark"&&(f.colorSchemes.dark={...c.dark!==!0&&c.dark,palette:f.palette},p0(f,"light",c.light)),f.focusVisible!=null&&f.focusVisible!==!1){let m=f.focusVisible,p=gp(e.focusVisible,t),y=p&&typeof p=="object"?p.outlineColor:void 0;if(!y||t0(p)&&y===f.palette.primary.main){let{outlineColor:x,...T}=m;m=T}Object.keys(f.colorSchemes).forEach(x=>{let T=f.colorSchemes?.[x]?.palette;T?.primary&&(f.colorSchemes[x].focusVisible=Aa(m,T.primary.main))})}return f}return!r&&!("light"in c)&&a==="light"&&(c.light=!0),Im({...i,colorSchemes:c,defaultColorScheme:a,...typeof o!="boolean"&&o},...t)}var gk=kn(),ws=gk;var Xt="$$material";function ir(){let e=ko(ws);return e[Xt]||e}function bk(e){return b(ga,{...e,defaultTheme:ws,themeId:Xt})}var Nm=bk;var xk=xa({themeId:Xt,defaultTheme:ws,rootShouldForwardProp:bs}),ne=xk;function ql(e){return function(r){return b(Nm,{styles:typeof e=="function"?o=>e({theme:o,...r}):e})}}K();function vp(e){let{controlled:t,default:r,name:o,state:n="value"}=e,{current:s}=J(t!==void 0),[i,a]=ie(r),l=s?t:i,c=Ee(u=>{s||a(u)},[]);return[l,c]}var Tp=vp;K();K();var vk=Je(void 0),Yl=vk;function zm(){return Se(Yl)}function f0({props:e,states:t}){let r=Se(Yl),o={};return t.forEach(n=>{let s=e[n];o[n]=s===void 0&&r?r[n]:s}),[o,r]}K();function Cs(e){try{return e.matches(":focus-visible")}catch{}return!1}var Tk=ip,ze=Tk;K();function Me(e){return xm(e)}K();function ar(...e){let t=J(void 0),r=Ee(o=>{let n=e.map(s=>{if(s==null)return null;if(typeof s=="function"){let i=s,a=i(o);return typeof a=="function"?a:()=>{i(null)}}return s.current=o,()=>{s.current=null}});return()=>{n.forEach(s=>s?.())}},e);return Le(()=>e.every(o=>o==null)?null:o=>{t.current&&(t.current(),t.current=void 0),o!=null&&(t.current=r(o))},e)}var rn=ar;K();function Pk(e){let t=J(e);return at(()=>{t.current=e}),J((...r)=>(0,t.current)(...r)).current}var eo=Pk;var Pr=eo;K();K();function Dm(e){let{focusableWhenDisabled:t,disabled:r,composite:o=!1,tabIndex:n=0,isNativeButton:s}=e,i=o&&t!==!1,a=o&&t===!1;return Le(()=>{let c={onKeyDown(u){r&&t&&u.key!=="Tab"&&u.preventDefault()}};return o||(c.tabIndex=n,!s&&r&&(c.tabIndex=t?n:-1)),(s&&(t||i)||!s&&r)&&(c["aria-disabled"]=r),s&&(!t||a)&&(c.disabled=r),c},[o,r,t,i,a,s,n])}var _k={};function Bm(e){let{nativeButton:t,nativeButtonProp:r,internalNativeButton:o=t,allowInferredHostMismatch:n=!1,disabled:s,type:i,hasFormAction:a=!1,tabIndex:l=0,focusableWhenDisabled:c,stopEventPropagation:u=!1,onBeforeKeyDown:f,onBeforeKeyUp:m}=e,p=J(null),y=c===!0,x=Dm({focusableWhenDisabled:y,disabled:s,isNativeButton:t,tabIndex:l}),T=Ee(()=>{let R=p.current;return R==null?t:R.tagName==="BUTTON"?!0:!!(R.tagName==="A"&&R.href)},[t]),S=Le(()=>{let R=y?{}:{tabIndex:s?-1:l};return t?(R.type=i===void 0&&!a?"button":i,y||(R.disabled=s)):(R.role="button",!y&&s&&(R["aria-disabled"]=s)),y?{...R,...x}:R},[s,y,x,a,t,l,i]);return{getButtonProps:Ee((R=_k)=>{let{onClick:P,onKeyDown:O,onKeyUp:E,...A}=R;return{...S,...A,onClick:w=>{if(u&&w.stopPropagation(),s){w.preventDefault();return}P?.(w)},onKeyDown:w=>{if(y&&x.onKeyDown(w),!s&&(f?.(w),O?.(w),!(w.target!==w.currentTarget||T()))){if(w.key===" "){w.preventDefault();return}w.key==="Enter"&&(w.preventDefault(),w.currentTarget.click())}},onKeyUp:w=>{s||(m?.(w),E?.(w),w.target===w.currentTarget&&!T()&&w.key===" "&&!w.defaultPrevented&&w.currentTarget.click())}}},[S,s,y,x,T,f,m,u]),rootRef:p}}K();K();var d0={};function Es(e,t){let r=J(d0);return r.current===d0&&(r.current=e(t)),r}var Lm=class e{ref={current:null};shouldMount=!1;mounted=null;didMount=!1;setShouldMount=null;static create(){return new e}static use(){let t=Es(e.create).current,[r,o]=ie(!1);return t.shouldMount=r,t.setShouldMount=o,ce(t.mountEffect,[r]),t}mount(){return this.mounted||(this.mounted=Sk(),this.shouldMount=!0,this.setShouldMount(this.shouldMount)),this.mounted}mountEffect=()=>{this.shouldMount&&!this.didMount&&(this.ref.current!==null&&(this.didMount=!0),this.mounted.resolve())};start(...t){this.mount().then(()=>this.ref.current?.start(...t))}stop(...t){this.mount().then(()=>this.ref.current?.stop(...t))}pulsate(...t){this.mount().then(()=>this.ref.current?.pulsate(...t))}};function Pp(){return Lm.use()}function Sk(){let e,t,r=new Promise((o,n)=>{e=o,t=n});return r.resolve=e,r.reject=t,r}K();K();var wk=[];function $a(e){ce(e,wk)}var Ia=class e{static create(){return new e}currentId=null;start(t,r){this.clear(),this.currentId=setTimeout(()=>{this.currentId=null,r()},t)}clear=()=>{this.currentId!==null&&(clearTimeout(this.currentId),this.currentId=null)};disposeEffect=()=>this.clear};function ao(){let e=Es(Ia.create).current;return $a(e.disposeEffect),e}K();function Ck(e){let{className:t,classes:r,pulsate:o=!1,rippleX:n,rippleY:s,rippleSize:i,in:a,onExited:l,timeout:c}=e,[u,f]=ie(!1),m=ao(),p=J(!1),y=J(l);y.current=l;let x=l!=null,T=he(t,r.ripple,r.rippleVisible,o&&r.ripplePulsate),S={width:i,height:i,top:-(i/2)+s,left:-(i/2)+n},v=he(r.child,u&&r.childLeaving,o&&r.childPulsate);return!a&&!u&&f(!0),ce(()=>{!a&&x?p.current||(p.current=!0,m.start(c,()=>{p.current=!1,y.current?.()})):(p.current=!1,m.clear())},[m,x,a,c]),b("span",{className:T,style:S,children:b("span",{className:v})})}var m0=Ck;var Ek=Ce("MuiTouchRipple",["root","ripple","rippleVisible","ripplePulsate","child","childLeaving","childPulsate"]),zr=Ek;K();var y0="(prefers-reduced-motion: reduce)",Rk=0,kk="0ms",Ok=()=>{},h0=()=>!1,Ak=()=>!0,Mk=()=>Ok;function $k(e){let[t,r]=ie(()=>({enabled:e,matches:e?null:!1})),o=t.matches;return t.enabled!==e&&(o=null,e||(o=!1)),at(()=>{let n=a=>{r(l=>l.enabled===e&&l.matches===a?l:{enabled:e,matches:a})};if(!e){t.enabled&&n(!1);return}if(typeof window>"u"||typeof window.matchMedia!="function"){n(!1);return}let s=window.matchMedia(y0),i=()=>{n(s.matches)};return i(),s.addEventListener("change",i),()=>{s.removeEventListener("change",i)}},[e,t.enabled]),o}var Ik={...Q},g0=Ik.useSyncExternalStore;function Nk(e){let t=e?Ak:h0,[r,o]=Le(()=>{if(!e||typeof window>"u"||typeof window.matchMedia!="function")return[h0,Mk];let n=window.matchMedia(y0);return[()=>n.matches,s=>(n.addEventListener("change",s),()=>{n.removeEventListener("change",s)})]},[e]);return g0(o,r,t)}var zk=g0!==void 0?Nk:$k;function ci(e,t){let r=zk(!t&&e==="system"),o=!t&&(e==="always"||e==="system"&&r!==!1);return Le(()=>({shouldReduceMotion:o,getTransitionTiming(n){return o?{duration:Rk,delay:kk}:n}}),[o])}var Fm=550,Dk=80,_p={},b0=[],Bk=()=>{};function jm(e,t){let r=new Set(t),o=new Map,n=[];for(let i of e)r.has(i)?n.length>0&&(o.set(i,n),n=[]):n.push(i);let s=[];for(let i of t){let a=o.get(i);a&&s.push(...a),s.push(i)}return s.push(...n),s}function Lk({event:e,element:t,center:r}){let o=t?t.getBoundingClientRect():{width:0,height:0,left:0,top:0},n,s;if(r||e===void 0||e.clientX===0&&e.clientY===0||!e.clientX&&!e.touches)n=Math.round(o.width/2),s=Math.round(o.height/2);else{let{clientX:a,clientY:l}=e.touches&&e.touches.length>0?e.touches[0]:e;n=Math.round(a-o.left),s=Math.round(l-o.top)}let i;if(r)i=Math.sqrt((2*o.width**2+o.height**2)/3),i%2===0&&(i+=1);else{let a=Math.max(Math.abs((t?t.clientWidth:0)-n),n)*2+2,l=Math.max(Math.abs((t?t.clientHeight:0)-s),s)*2+2;i=Math.sqrt(a**2+l**2)}return{rippleX:n,rippleY:s,rippleSize:i}}var jk=Cn`+  0% {+    transform: scale(0);+    opacity: 0.1;+  }++  100% {+    transform: scale(1);+    opacity: 0.3;+  }+`,Fk=Cn`+  0% {+    opacity: 1;+  }++  100% {+    opacity: 0;+  }+`,Vk=Cn`+  0% {+    transform: scale(1);+  }++  50% {+    transform: scale(0.92);+  }++  100% {+    transform: scale(1);+  }+`;function Uk(e){if(e.motion.reducedMotion==="always")return null;let t=wn`+    &.${zr.rippleVisible} {+      animation-name: ${jk};+      animation-duration: ${Fm}ms;+      animation-timing-function: ${e.transitions.easing.easeInOut};+    }++    &.${zr.ripplePulsate} {+      animation-duration: ${e.transitions.duration.shorter}ms;+    }++    & .${zr.childLeaving} {+      animation-name: ${Fk};+      animation-duration: ${Fm}ms;+      animation-timing-function: ${e.transitions.easing.easeInOut};+    }++    & .${zr.childPulsate} {+      animation-name: ${Vk};+      animation-duration: 2500ms;+      animation-timing-function: ${e.transitions.easing.easeInOut};+      animation-iteration-count: infinite;+      animation-delay: 200ms;+    }+  `;return e.motion.reducedMotion==="system"?wn`+      @media (prefers-reduced-motion: no-preference) {+        ${t}+      }+    `:t}var Zk=ne("span",{name:"MuiTouchRipple",slot:"Root"})({overflow:"hidden",pointerEvents:"none",position:"absolute",zIndex:0,top:0,right:0,bottom:0,left:0,borderRadius:"inherit"}),Wk=ne(m0,{name:"MuiTouchRipple",slot:"Ripple"})`+  opacity: 0;+  position: absolute;++  &.${zr.rippleVisible} {+    opacity: 0.3;+    transform: scale(1);+  }++  /*+   * Order matters: 'child', 'childLeaving' and 'childPulsate' apply to the same+   * element with equal specificity, so the later rule wins. 'child' must come+   * before 'childLeaving' so the leaving 'opacity: 0' takes precedence. A focus+   * (pulsate) ripple keeps 'pulsateKeyframe' (no opacity animation) on exit, so+   * it relies on this static 'opacity: 0' to disappear on blur instead of+   * lingering until removal.+   */+  & .${zr.child} {+    opacity: 1;+    display: block;+    width: 100%;+    height: 100%;+    border-radius: 50%;+    background-color: currentColor;+  }++  & .${zr.childLeaving} {+    opacity: 0;+  }++  & .${zr.childPulsate} {+    position: absolute;+    /* @noflip */+    left: 0px;+    top: 0;+  }++  ${({theme:e})=>Uk(e)}+`,Hk=ue(function(t,r){let o=Me({props:t,name:"MuiTouchRipple"}),n=ir(),s=ci(n.motion.reducedMotion,!1),{center:i=!1,classes:a=_p,className:l,...c}=o,[u,f]=ie({items:b0,order:b0}),m=u.items,p=J(0),y=J(null),x=J(!1);$a(()=>(x.current=!0,()=>{x.current=!1})),ce(()=>{y.current&&(y.current(),y.current=null)},[m]);let T=J(!1),S=ao(),v=J(null),R=J(null),P=Pr(w=>{x.current&&f($=>{let h=$.items.filter(k=>k.key!==w),z=jm($.order.filter(k=>k!==w),h.filter(k=>!k.exiting).map(k=>k.key));return{items:h,order:z}})}),O=Pr(w=>{let{pulsate:$,rippleX:h,rippleY:z,rippleSize:k,cb:j}=w,B=p.current;p.current+=1,f(W=>{let H=[...W.items,{key:B,pulsate:$,rippleX:h,rippleY:z,rippleSize:k,exiting:!1}];return{items:H,order:jm(W.order,H.filter(ee=>!ee.exiting).map(ee=>ee.key))}}),y.current=j}),E=Pr((w=_p,$=_p,h=Bk)=>{let{pulsate:z=!1,center:k=i||$.pulsate,fakeElement:j=!1}=$;if(w?.type==="mousedown"&&T.current){T.current=!1;return}w?.type==="touchstart"&&(T.current=!0);let B=j?null:R.current,{rippleX:W,rippleY:H,rippleSize:ee}=Lk({event:w,element:B,center:k});w?.touches?v.current===null&&(v.current=()=>{O({pulsate:z,rippleX:W,rippleY:H,rippleSize:ee,cb:h})},S.start(Dk,()=>{v.current&&(v.current(),v.current=null)})):O({pulsate:z,rippleX:W,rippleY:H,rippleSize:ee,cb:h})}),A=Pr(()=>{E(_p,{pulsate:!0})}),I=Pr((w,$)=>{if(S.clear(),w?.type==="touchend"&&v.current){v.current(),v.current=null,S.start(0,()=>{I(w,$)});return}v.current=null,f(h=>{let z=h.items.findIndex(j=>!j.exiting);if(z===-1)return h;let k=h.items.slice();return k[z]={...k[z],exiting:!0},{items:k,order:jm(h.order,k.filter(j=>!j.exiting).map(j=>j.key))}}),y.current=$});To(r,()=>({pulsate:A,start:E,stop:I}),[A,E,I]);let N=new Map(m.map(w=>[w.key,w])),D=u.order.map(w=>N.get(w)).filter(Boolean);return b(Zk,{className:he(zr.root,a.root,l),ref:R,...c,children:D.map(w=>b(Wk,{classes:{ripple:he(a.ripple,zr.ripple),rippleVisible:he(a.rippleVisible,zr.rippleVisible),ripplePulsate:he(a.ripplePulsate,zr.ripplePulsate),child:he(a.child,zr.child),childLeaving:he(a.childLeaving,zr.childLeaving),childPulsate:he(a.childPulsate,zr.childPulsate)},timeout:s.shouldReduceMotion?0:Fm,pulsate:w.pulsate,rippleX:w.rippleX,rippleY:w.rippleY,rippleSize:w.rippleSize,in:!w.exiting,onExited:()=>P(w.key)},w.key))})}),x0=Hk;function v0(e){return we("MuiButtonBase",e)}var Gk=Ce("MuiButtonBase",["root","disabled","focusVisible"]),Rs=Gk;var Kk=e=>{let{disabled:t,focusVisible:r,focusVisibleClassName:o,suppressFocusVisible:n,classes:s}=e,a=ke({root:["root",t&&"disabled",r&&!n&&"focusVisible"]},v0,s);return r&&!n&&o&&(a.root+=` ${o}`),a},qk=ne("button",{name:"MuiButtonBase",slot:"Root"})(ze(({theme:e})=>({display:"inline-flex",alignItems:"center",justifyContent:"center",position:"relative",boxSizing:"border-box",WebkitTapHighlightColor:"transparent",backgroundColor:"transparent",outline:0,border:0,margin:0,borderRadius:0,padding:0,cursor:"pointer",userSelect:"none",verticalAlign:"middle",MozAppearance:"none",WebkitAppearance:"none",textDecoration:"none",color:"inherit","&::-moz-focus-inner":{borderStyle:"none"},[`&.${Rs.disabled}`]:{pointerEvents:"none",cursor:"default"},"@media print":{colorAdjust:"exact"},variants:[{props:{internalDisabledThemeFocusVisible:!1},style:e.focusVisible&&{...yp,[`&.${Rs.focusVisible}`]:e.focusVisible}}]}))),Yk=ue(function(t,r){let o=Me({props:t,name:"MuiButtonBase"}),{action:n,centerRipple:s=!1,children:i,className:a,component:l="button",disabled:c=!1,disableRipple:u=!1,disableTouchRipple:f=!1,focusRipple:m=!1,focusVisibleClassName:p,focusableWhenDisabled:y,suppressFocusVisible:x=!1,internalNativeButton:T,internalDisabledThemeFocusVisible:S=!1,LinkComponent:v="a",nativeButton:R,onBlur:P,onClick:O,onContextMenu:E,onDragLeave:A,onFocus:I,onFocusVisible:N,onKeyDown:D,onKeyUp:w,onMouseDown:$,onMouseLeave:h,onMouseUp:z,onTouchEnd:k,onTouchMove:j,onTouchStart:B,tabIndex:W=0,TouchRippleProps:H,touchRippleRef:ee,type:G,...F}=o,V=!!(F.href||F.to),te=!!F.formAction,oe=l;oe==="button"&&V&&(oe=v);let Y=typeof oe=="string"?oe==="button":T??!1,fe=R??Y,se=Pp(),be=rn(se.ref,ee),[Pe,We]=ie(!1);(c||x)&&Pe&&We(!1);let qe=Pr(Fe=>{m&&!Fe.repeat&&Pe&&Fe.key===" "&&se.stop(Fe,()=>{se.start(Fe)})}),He=Pr(Fe=>{m&&Fe.key===" "&&Pe&&!Fe.defaultPrevented&&se.stop(Fe,()=>{se.pulsate(Fe)})}),{getButtonProps:Ye,rootRef:$e}=Bm({nativeButton:fe,nativeButtonProp:R,internalNativeButton:Y,allowInferredHostMismatch:V||typeof oe=="string",disabled:c,type:G,hasFormAction:te,tabIndex:W,onBeforeKeyDown:qe,onBeforeKeyUp:He}),{onClick:Ge,onKeyDown:yt,onKeyUp:Ot,...Xe}=Ye({onClick:O,onKeyDown:D,onKeyUp:w});To(n,()=>({focusVisible:()=>{We(!0),$e.current.focus()}}),[$e]);let Ve=se.shouldMount&&!u&&!c;ce(()=>{Pe&&m&&!u&&se.pulsate()},[u,m,Pe,se]);let Tt=Hn(se,"start",$,f),dt=Hn(se,"stop",E,f),Vt=Hn(se,"stop",A,f),me=Hn(se,"stop",z,f),re=Hn(se,"stop",Fe=>{Pe&&Fe.preventDefault(),h&&h(Fe)},f),xe=Hn(se,"start",B,f),_e=Hn(se,"stop",k,f),je=Hn(se,"stop",j,f),et=Hn(se,"stop",Fe=>{Cs(Fe.target)||We(!1),P&&P(Fe)},!1),gt=Pr(Fe=>{$e.current||($e.current=Fe.currentTarget),!x&&Cs(Fe.target)&&(We(!0),N&&N(Fe)),I&&I(Fe)}),Oe={};V&&(Oe.tabIndex=c?-1:W,c&&(Oe["aria-disabled"]=c),Oe.type=G);let Pt=rn(r,$e),mt={...o,centerRipple:s,component:l,disabled:c,disableRipple:u,disableTouchRipple:f,focusRipple:m,suppressFocusVisible:x,tabIndex:W,focusVisible:Pe,internalDisabledThemeFocusVisible:S},bt=Kk(mt);return b(qk,{as:oe,className:he(bt.root,a),ownerState:mt,onBlur:et,onClick:Ge,onContextMenu:dt,onFocus:gt,onKeyDown:yt,onKeyUp:Ot,onMouseDown:Tt,onMouseLeave:re,onMouseUp:me,onDragLeave:Vt,onTouchEnd:_e,onTouchMove:je,onTouchStart:xe,ref:Pt,...V?Oe:Xe,...F,children:[i,Ve?b(x0,{ref:be,center:s,...H}):null]})});function Hn(e,t,r,o=!1){return Pr(n=>(r&&r(n),o||e[t](n),!0))}var on=Yk;function T0(e){return we("PrivateSwitchBase",e)}var b9=Ce("PrivateSwitchBase",["root","checked","disabled","input","edgeStart","edgeEnd"]);function Xk(e){return typeof e=="string"}var Na=Xk;function Jk(e,t,r){return e===void 0||Na(e)?t:{...t,ownerState:{...t.ownerState,...r}}}var Xl=Jk;function Qk(e,t,r){return typeof e=="function"?e(t,r):e}var Jl=Qk;function ks(e,t){let r=e.charCodeAt(2);return e[0]==="o"&&e[1]==="n"&&r>=65&&r<=90&&typeof t=="function"}function eO(e){if(e===void 0)return{};let t={},r=Object.keys(e);for(let o=0;o<r.length;o+=1){let n=r[o];ks(n,e[n])&&(t[n]=e[n])}return t}var za=eO;function tO(e){if(e===void 0)return{};let t={},r=Object.keys(e);for(let o=0;o<r.length;o+=1){let n=r[o];ks(n,e[n])||(t[n]=e[n])}return t}var Sp=tO;function rO(e){let{getSlotProps:t,additionalProps:r,externalSlotProps:o,externalForwardedProps:n,className:s}=e;if(!t){let m=he(r?.className,s,n?.className,o?.className),p={...r,...n,...o};if(m.length>0&&(p.className=m),r?.style||n?.style||o?.style){let y={...r?.style,...n?.style,...o?.style};Object.keys(y).length>0&&(p.style=y)}return{props:p,internalRef:void 0}}let i=za({...n,...o}),a=Sp(o),l=Sp(n),c=t(i),u=he(c?.className,r?.className,s,n?.className,o?.className),f={...c,...r,...l,...a};if(u.length>0&&(f.className=u),c?.style||r?.style||n?.style||o?.style){let m={...c?.style,...r?.style,...n?.style,...o?.style};Object.keys(m).length>0&&(f.style=m)}return{props:f,internalRef:c.ref}}var Ql=rO;function ot(e,t){let{className:r,elementType:o,ownerState:n,externalForwardedProps:s,internalForwardedProps:i,shouldForwardComponentProp:a=!1,...l}=t,{component:c,slots:u={[e]:void 0},slotProps:f={[e]:void 0},...m}=s,p=u[e]||o,y=Jl(f[e],n),{props:{component:x,...T},internalRef:S}=Ql({className:r,...l,externalForwardedProps:e==="root"?m:void 0,externalSlotProps:y}),v=ar(S,y?.ref,t.ref),R=e==="root"?x||c:x,P=Xl(p,{...e==="root"&&!c&&!u[e]&&i,...e!=="root"&&!u[e]&&i,...T,...R&&!a&&{as:R},...R&&a&&{component:R},ref:v},n);return[p,P]}var oO=e=>{let{classes:t,checked:r,disabled:o,edge:n}=e,s={root:["root",r&&"checked",o&&"disabled",n&&`edge${Te(n)}`],input:["input"]};return ke(s,T0,t)},nO=ne(on,{name:"MuiSwitchBase"})({padding:9,borderRadius:"50%",variants:[{props:{edge:"start",size:"small"},style:{marginLeft:-3}},{props:({edge:e,ownerState:t})=>e==="start"&&t.size!=="small",style:{marginLeft:-12}},{props:{edge:"end",size:"small"},style:{marginRight:-3}},{props:({edge:e,ownerState:t})=>e==="end"&&t.size!=="small",style:{marginRight:-12}}]}),sO=ne("input",{name:"MuiSwitchBase",shouldForwardProp:bs})({cursor:"inherit",position:"absolute",opacity:0,width:"100%",height:"100%",top:0,left:0,margin:0,padding:0,zIndex:1}),iO=ue(function(t,r){let{autoFocus:o,checked:n,checkedIcon:s,defaultChecked:i,disabled:a,disableFocusRipple:l=!1,edge:c=!1,icon:u,id:f,name:m,onBlur:p,onChange:y,onFocus:x,readOnly:T,required:S=!1,tabIndex:v,type:R,value:P,slots:O={},slotProps:E={},...A}=t,{nativeButton:I,...N}=A,[D,w]=Tp({controlled:n,default:!!i,name:"SwitchBase",state:"checked"}),$=zm(),h=oe=>{x&&x(oe),$&&$.onFocus&&$.onFocus(oe)},z=oe=>{p&&p(oe),$&&$.onBlur&&$.onBlur(oe)},k=oe=>{if(oe.nativeEvent.defaultPrevented||T)return;let Y=oe.target.checked;w(Y),y&&y(oe,Y)},j=a;$&&typeof j>"u"&&(j=$.disabled);let B=R==="checkbox"||R==="radio",W={...t,checked:D,disabled:j,disableFocusRipple:l,edge:c},H=oO(W),ee={slots:O,slotProps:E},[G,F]=ot("root",{ref:r,elementType:nO,className:H.root,shouldForwardComponentProp:!0,externalForwardedProps:{...ee,component:"span",...N},getSlotProps:oe=>({...oe,onFocus:Y=>{oe.onFocus?.(Y),h(Y)},onBlur:Y=>{oe.onBlur?.(Y),z(Y)}}),ownerState:W,additionalProps:{centerRipple:!0,focusRipple:!l,role:void 0,tabIndex:null,internalDisabledThemeFocusVisible:!0}}),[V,te]=ot("input",{elementType:sO,className:H.input,externalForwardedProps:ee,getSlotProps:oe=>({...oe,onChange:Y=>{oe.onChange?.(Y),k(Y)}}),ownerState:W,additionalProps:{autoFocus:o,checked:n,defaultChecked:i,disabled:j,id:B?f:void 0,name:m,readOnly:T,required:S,tabIndex:v,type:R,...R==="checkbox"&&P===void 0?{}:{value:P}}});return b(G,{...F,children:[b(V,{...te}),D?s:u]})}),P0=iO;function _0(e){return we("MuiSwitch",e)}var aO=Ce("MuiSwitch",["root","edgeStart","edgeEnd","switchBase","colorPrimary","colorSecondary","sizeSmall","sizeMedium","checked","disabled","input","thumb","track"]),vt=aO;K();K();function S0(e){return we("MuiSvgIcon",e)}var m8=Ce("MuiSvgIcon",["root","colorPrimary","colorSecondary","colorAction","colorError","colorDisabled","fontSizeInherit","fontSizeSmall","fontSizeMedium","fontSizeLarge"]);var w0={transition:"none"};function C0(e,t){return e==="always"?t:e==="system"?{"@media (prefers-reduced-motion: reduce)":t}:null}var wp=e=>e.scrollTop;var E0={},lO=["all"],cO={};function ui(e,t){return r=>{if(t){let o=e.current;r===void 0?t(o):t(o,r)}}}function R0(e,t,r,o,n,s){let i=e==="exited"&&!t?o:r[e]||r.exited;return n||s?{...i,...n,...s}:i}function Vm(e,t){let{timeout:r,easing:o,style:n=E0}=e;return{duration:n.transitionDuration??(typeof r=="number"?r:r[t.mode]||0),easing:n.transitionTimingFunction??(typeof o=="object"?o[t.mode]:o),delay:n.transitionDelay}}function Cp(e,t){let r=t??w0;return C0(e.motion?.reducedMotion,r)}function Lt(e,t=lO,r=cO){let o=e.transitions?.create?.(t,r),n=Cp(e);if(o===void 0)return n??E0;let s={transition:o};return n?{...s,...n}:s}var uO=e=>{let{color:t,fontSize:r,classes:o}=e,n={root:["root",t!=="inherit"&&`color${Te(t)}`,`fontSize${Te(r)}`]};return ke(n,S0,o)},pO=ne("svg",{name:"MuiSvgIcon",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,r.color!=="inherit"&&t[`color${Te(r.color)}`],t[`fontSize${Te(r.fontSize)}`]]}})(ze(({theme:e})=>({userSelect:"none",width:"1em",height:"1em",display:"inline-block",flexShrink:0,...Lt(e,"fill",{duration:(e.vars??e).transitions?.duration?.shorter}),variants:[{props:t=>!t.hasSvgAsChild,style:{fill:"currentColor"}},{props:{fontSize:"inherit"},style:{fontSize:"inherit"}},{props:{fontSize:"small"},style:{fontSize:e.typography?.pxToRem?.(20)||"1.25rem"}},{props:{fontSize:"medium"},style:{fontSize:e.typography?.pxToRem?.(24)||"1.5rem"}},{props:{fontSize:"large"},style:{fontSize:e.typography?.pxToRem?.(35)||"2.1875rem"}},...Object.entries((e.vars??e).palette).filter(([,t])=>t&&t.main).map(([t])=>({props:{color:t},style:{color:(e.vars??e).palette?.[t]?.main}})),{props:{color:"action"},style:{color:(e.vars??e).palette?.action?.active}},{props:{color:"disabled"},style:{color:(e.vars??e).palette?.action?.disabled}},{props:{color:"inherit"},style:{color:void 0}}]}))),k0=ue(function(t,r){let o=Me({props:t,name:"MuiSvgIcon"}),{children:n,className:s,color:i="inherit",component:a="svg",fontSize:l="medium",htmlColor:c,inheritViewBox:u=!1,titleAccess:f,viewBox:m="0 0 24 24",...p}=o,y=Rt(n)&&n.type==="svg",x={...o,color:i,component:a,fontSize:l,instanceFontSize:t.fontSize,inheritViewBox:u,viewBox:m,hasSvgAsChild:y},T={};u||(T.viewBox=m);let S=uO(x);return b(pO,{as:a,className:he(S.root,s),focusable:"false",color:c,"aria-hidden":f?void 0:!0,role:f?"img":void 0,ref:r,...T,...p,...y&&n.props,ownerState:x,children:[y?n.props.children:n,f?b("title",{children:f}):null]})});k0.muiName="SvgIcon";var Um=k0;function kt(e,t){function r(o,n){return b(Um,{"data-testid":void 0,ref:n,...o,children:e})}return r.muiName=Um.muiName,Hc(ue(r))}function Da(e,t=166){let r;function o(...n){let s=()=>{e.apply(this,n)};clearTimeout(r),r=setTimeout(s,t)}return o.clear=()=>{clearTimeout(r)},o}var Ep=Da;function pi(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}var Rp=pi;function Dr(e){return e&&e.ownerDocument||document}var kp=Dr;function fi(e){return Dr(e).defaultView||window}var Ba=fi;function di(e,t){typeof e=="function"?e(t):e&&(e.current=t)}var La=at;var mi=wa;function Op(e,t){if(!e)return t;function r(a,l){let c={};return Object.keys(l).forEach(u=>{ks(u,l[u])&&typeof a[u]=="function"&&(c[u]=(...f)=>{a[u](...f),l[u](...f)})}),c}if(typeof e=="function"||typeof t=="function")return a=>{let l=typeof t=="function"?t(a):t,c=typeof e=="function"?e({...a,...l}):e,u=he(a?.className,l?.className,c?.className),f=r(c,l),m={...l,...c,...f};return u&&(m.className=u),l?.style&&c?.style&&(m.style={...l.style,...c.style}),l?.sx&&c?.sx&&(m.sx=[...Array.isArray(l.sx)?l.sx:[l.sx],...Array.isArray(c.sx)?c.sx:[c.sx]]),m};let o=t,n=r(e,o),s=he(o?.className,e?.className),i={...t,...e,...n};return s&&(i.className=s),o?.style&&e?.style&&(i.style={...o.style,...e.style}),o?.sx&&e?.sx&&(i.sx=[...Array.isArray(o.sx)?o.sx:[o.sx],...Array.isArray(e.sx)?e.sx:[e.sx]]),i}var fO=e=>{let{classes:t,edge:r,size:o,color:n,checked:s,disabled:i}=e,a={root:["root",r&&`edge${Te(r)}`,`size${Te(o)}`],switchBase:["switchBase",`color${Te(n)}`,s&&"checked",i&&"disabled"],thumb:["thumb"],track:["track"],input:["input"]},l=ke(a,_0,t);return{...t,...l}},dO=ne("span",{name:"MuiSwitch",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,r.edge&&t[`edge${Te(r.edge)}`],t[`size${Te(r.size)}`]]}})({display:"inline-flex",width:58,height:38,overflow:"hidden",padding:12,boxSizing:"border-box",position:"relative",flexShrink:0,zIndex:0,verticalAlign:"middle","@media print":{colorAdjust:"exact"},variants:[{props:{edge:"start"},style:{marginLeft:-8}},{props:{edge:"end"},style:{marginRight:-8}},{props:{size:"small"},style:{width:40,height:24,padding:7,[`& .${vt.thumb}`]:{width:16,height:16},[`& .${vt.switchBase}`]:{padding:4,[`&.${vt.checked}`]:{transform:"translateX(16px)"}}}}]}),mO=ne(P0,{name:"MuiSwitch",slot:"SwitchBase",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.switchBase,{[`& .${vt.input}`]:t.input},r.color!=="default"&&t[`color${Te(r.color)}`]]}})(ze(({theme:e})=>({position:"absolute",top:0,left:0,zIndex:1,color:e.vars?e.vars.palette.Switch.defaultColor:`${e.palette.mode==="light"?e.palette.common.white:e.palette.grey[300]}`,...Lt(e,["left","transform"],{duration:e.transitions.duration.shortest}),[`&.${vt.checked}`]:{transform:"translateX(20px)"},[`&.${vt.disabled}`]:{color:e.vars?e.vars.palette.Switch.defaultDisabledColor:`${e.palette.mode==="light"?e.palette.grey[100]:e.palette.grey[600]}`},...e.focusVisible?{[`&.${Rs.focusVisible} ~ .${vt.track}`]:{...yp,...e.focusVisible},[`&.${vt.checked} + .${vt.track}`]:{backgroundColor:e.alpha(e.vars?e.vars.palette.common.onBackground:`${e.palette.mode==="light"?e.palette.common.black:e.palette.common.white}`,.5)},[`&.${vt.disabled} + .${vt.track}`]:{backgroundColor:e.alpha(e.vars?e.vars.palette.common.onBackground:`${e.palette.mode==="light"?e.palette.common.black:e.palette.common.white}`,e.vars?e.vars.opacity.switchTrackDisabled:`${e.palette.mode==="light"?.12:.2}`)}}:{[`&.${vt.checked} + .${vt.track}`]:{opacity:.5},[`&.${vt.disabled} + .${vt.track}`]:{opacity:e.vars?e.vars.opacity.switchTrackDisabled:`${e.palette.mode==="light"?.12:.2}`}},[`& .${vt.input}`]:{left:"-100%",width:"300%"}})),ze(({theme:e})=>({"&:hover":{backgroundColor:e.alpha((e.vars||e).palette.action.active,(e.vars||e).palette.action.hoverOpacity),"@media (hover: none)":{backgroundColor:"transparent"}},variants:[...Object.entries(e.palette).filter(sr(["light"])).map(([t])=>({props:{color:t},style:{[`&.${vt.checked}`]:{color:(e.vars||e).palette[t].main,"&:hover":{backgroundColor:e.alpha((e.vars||e).palette[t].main,(e.vars||e).palette.action.hoverOpacity),"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${vt.disabled}`]:{color:e.vars?e.vars.palette.Switch[`${t}DisabledColor`]:`${e.palette.mode==="light"?e.lighten(e.palette[t].main,.62):e.darken(e.palette[t].main,.55)}`}},[`&.${vt.checked} + .${vt.track}`]:{backgroundColor:(e.vars||e).palette[t].main},...e.focusVisible&&{[`&.${vt.checked} + .${vt.track}`]:{backgroundColor:e.alpha((e.vars||e).palette[t].main,.5)},[`&.${vt.disabled} + .${vt.track}`]:{backgroundColor:e.alpha(e.vars?e.vars.palette.common.onBackground:`${e.palette.mode==="light"?e.palette.common.black:e.palette.common.white}`,e.vars?e.vars.opacity.switchTrackDisabled:`${e.palette.mode==="light"?.12:.2}`)},[`&.${vt.checked}.${vt.disabled} + .${vt.track}`]:{backgroundColor:e.alpha((e.vars||e).palette[t].main,e.vars?e.vars.opacity.switchTrackDisabled:`${e.palette.mode==="light"?.12:.2}`)}}}}))]}))),hO=ne("span",{name:"MuiSwitch",slot:"Track"})(ze(({theme:e})=>({height:"100%",width:"100%",borderRadius:14/2,zIndex:-1,...Lt(e,["opacity","background-color"],{duration:e.transitions.duration.shortest}),"@media (forced-colors: active)":{boxSizing:"border-box",border:"1px solid ButtonBorder"},...e.focusVisible?{backgroundColor:e.alpha(e.vars?e.vars.palette.common.onBackground:`${e.palette.mode==="light"?e.palette.common.black:e.palette.common.white}`,e.vars?e.vars.opacity.switchTrack:`${e.palette.mode==="light"?.38:.3}`)}:{backgroundColor:e.vars?e.vars.palette.common.onBackground:`${e.palette.mode==="light"?e.palette.common.black:e.palette.common.white}`,opacity:e.vars?e.vars.opacity.switchTrack:`${e.palette.mode==="light"?.38:.3}`}}))),yO=ne("span",{name:"MuiSwitch",slot:"Thumb"})(ze(({theme:e})=>({boxShadow:(e.vars||e).shadows[1],backgroundColor:"currentColor",boxSizing:"border-box",border:"1px solid transparent",width:20,height:20,borderRadius:"50%"}))),gO=ue(function(t,r){let o=Me({props:t,name:"MuiSwitch"}),{className:n,color:s="primary",edge:i=!1,size:a="medium",sx:l,slots:c={},slotProps:u={},...f}=o,m={...o,color:s,edge:i,size:a},p=fO(m),y=u.input,x={slots:c,slotProps:u},[T,S]=ot("root",{className:he(p.root,n),elementType:dO,externalForwardedProps:x,ownerState:m,additionalProps:{sx:l}}),[v,R]=ot("thumb",{className:p.thumb,elementType:yO,externalForwardedProps:x,ownerState:m}),P=b(v,{...R}),[O,E]=ot("track",{className:p.track,elementType:hO,externalForwardedProps:x,ownerState:m});return b(T,{...S,children:[b(mO,{type:"checkbox",icon:P,checkedIcon:P,ref:r,ownerState:m,...f,classes:{...p,root:p.switchBase},slots:{...c.switchBase&&{root:c.switchBase},...c.input&&{input:c.input}},slotProps:{...u.switchBase&&{root:typeof u.switchBase=="function"?u.switchBase(m):u.switchBase},input:Op(typeof y=="function"?y(m):y,{role:"switch"})}}),b(O,{...E})]})}),ec=gO;K();function O0(e){return we("MuiTypography",e)}var BH=Ce("MuiTypography",["root","h1","h2","h3","h4","h5","h6","subtitle1","subtitle2","body1","body2","inherit","button","caption","overline","alignLeft","alignRight","alignCenter","alignJustify","noWrap","gutterBottom"]);var bO=e=>{let{align:t,gutterBottom:r,noWrap:o,variant:n,classes:s}=e,i={root:["root",n,e.align!=="inherit"&&`align${Te(t)}`,r&&"gutterBottom",o&&"noWrap"]};return ke(i,O0,s)},xO=ne("span",{name:"MuiTypography",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,r.variant&&t[r.variant],r.align!=="inherit"&&t[`align${Te(r.align)}`],r.noWrap&&t.noWrap,r.gutterBottom&&t.gutterBottom]}})(ze(({theme:e})=>({margin:0,variants:[{props:{variant:"inherit"},style:{font:"inherit",lineHeight:"inherit",letterSpacing:"inherit"}},...Object.entries(e.typography).filter(([t,r])=>t!=="inherit"&&r&&typeof r=="object").map(([t,r])=>({props:{variant:t},style:r})),...Object.entries(e.palette).filter(sr()).map(([t])=>({props:{color:t},style:{color:(e.vars||e).palette[t].main}})),...Object.entries(e.palette?.text||{}).filter(([,t])=>typeof t=="string").map(([t])=>({props:{color:`text${Te(t)}`},style:{color:(e.vars||e).palette.text[t]}})),{props:({ownerState:t})=>t.align!=="inherit",style:{textAlign:"var(--Typography-textAlign)"}},{props:({ownerState:t})=>t.noWrap,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},{props:({ownerState:t})=>t.gutterBottom,style:{marginBottom:"0.35em"}}]}))),A0={h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",subtitle1:"h6",subtitle2:"h6",body1:"p",body2:"p",inherit:"p"},vO=ue(function(t,r){let o=Me({props:t,name:"MuiTypography"}),{color:n,align:s="inherit",className:i,component:a,gutterBottom:l=!1,noWrap:c=!1,variant:u="body1",variantMapping:f=A0,...m}=o,p={...o,align:s,color:n,className:i,component:a,gutterBottom:l,noWrap:c,variant:u,variantMapping:f},y=a||f[u]||A0[u]||"span",x=bO(p);return b(xO,{as:y,ref:r,className:he(x.root,i),...m,ownerState:p,style:{...s!=="inherit"&&{"--Typography-textAlign":s},...m.style}})}),_r=vO;K();K();function On(e){return parseInt(md,10)>=19?e?.props?.ref||null:e?.ref||null}K();K();function Ap(e){let t=Es(()=>TO(e)).current;return t.next=e,at(t.effect),t}function TO(e){let t={current:e,next:e,effect:()=>{t.current=t.next}};return t}K();var Zm=hd.createContext(null);function PO(e){if(e==null)return{appear:void 0,enter:void 0,exit:void 0};if(typeof e=="number")return{appear:e,enter:e,exit:e};let t=e.enter,r=e.exit;return{appear:e.appear!==void 0?e.appear:t,enter:t,exit:r}}function _O(e){if(e.autoTimeout!=null)return e.autoTimeout;let t=PO(e.timeout);return e.currentStatus==="entering"?e.isAppearing?t.appear??t.enter??null:t.enter??null:t.exit??null}function SO(e){let{in:t=!1,appear:r=!1,enter:o=!0,exit:n=!0,mountOnEnter:s=!1,unmountOnExit:i=!1,timeout:a,addEndListener:l,reduceMotion:c=!1,getAutoTimeout:u,nodeRef:f,onEnter:m,onEntering:p,onEntered:y,onExit:x,onExiting:T,onExited:S,children:v,...R}=e,P=Se(Zm),O=P&&!P.isMounting?o:r,[E,A]=ie(()=>t?O?"exited":"entered":s||i?"unmounted":"exited"),I=J(E);I.current=E,t&&E==="unmounted"&&(I.current="exited",A("exited"));let N=J(t&&O),D=J(!1),w=J(null),$=J(E),h=J(!1),z=J(c),k=Ap({timeout:a,addEndListener:l,reduceMotion:c,getAutoTimeout:u,onEnter:m,onEntering:p,onEntered:y,onExit:x,onExiting:T,onExited:S,enter:o,exit:n,mountOnEnter:s,unmountOnExit:i,nodeRef:f,parentGroup:P}),j=Ee(()=>{w.current!==null&&(w.current.cancel(),w.current=null)},[]),B=Ee(F=>{let V=!0,te=()=>{V&&(V=!1,w.current=null,F())};return te.cancel=()=>{V=!1},w.current=te,te},[]),W=Ee((F,V)=>{let te,oe=()=>{te!==void 0&&(clearTimeout(te),te=void 0)},Y=B(()=>{oe(),I.current=F,A(F)}),fe=Y.cancel;Y.cancel=()=>{oe(),fe()};let se=k.current.nodeRef.current,be=k.current.addEndListener,Pe=k.current.getAutoTimeout!==void 0,We=k.current.getAutoTimeout?.(),qe=_O({currentStatus:V,isAppearing:h.current,timeout:k.current.timeout,autoTimeout:We}),He=z.current,Ye=qe??(He&&Pe?0:null),$e=Ge=>{te=setTimeout(Y,Ge)};if(!se){$e(0);return}if(be){Ye!=null&&$e(He?0:Ye),be.length>=2?be(se,Y):be(Y);return}$e(He?0:qe??0)},[B,k]),H=Ee(F=>{let V=k.current,te=V.parentGroup?V.parentGroup.isMounting:F;if(h.current=te,!F&&!V.enter){I.current="entered",A("entered");return}z.current=V.reduceMotion,V.onEnter?.(te),I.current="entering",A("entering")},[k]),ee=Ee(()=>{let F=k.current;if(!F.exit){I.current="exited",A("exited");return}z.current=F.reduceMotion,F.onExit?.(),I.current="exiting",A("exiting")},[k]),G=Ee((F,V)=>{if(j(),V==="entering"){let te=k.current;if(te.mountOnEnter||te.unmountOnExit){let oe=te.nodeRef.current;oe&&wp(oe)}H(F)}else ee()},[j,H,ee,k]);return at(()=>(D.current=!0,N.current&&(N.current=!1,G(!0,"entering")),()=>{D.current=!1,j()}),[j,G]),at(()=>{if(!D.current)return;let F=I.current;t?F!=="entering"&&F!=="entered"&&G(!1,"entering"):F==="entering"||F==="entered"?G(!1,"exiting"):F==="exited"&&i&&(I.current="unmounted",A("unmounted"))},[t,E,i,G]),at(()=>{if(E==="unmounted"||$.current==="unmounted"){$.current=E;return}let V=$.current!==E;V&&($.current=E);let te=k.current;E==="entering"?(V&&te.onEntering?.(h.current),w.current===null&&I.current===E&&W("entered","entering")):E==="exiting"?(V&&te.onExiting?.(),w.current===null&&I.current===E&&W("exited","exiting")):E==="entered"&&V?te.onEntered?.(h.current):E==="exited"&&V&&te.onExited?.()},[k,W,E]),E==="unmounted"?null:b(Zm.Provider,{value:null,children:v(E,R)})}var M0=SO;function tc(e){return`scale(${e}, ${e**2})`}var wO={entering:{opacity:1,transform:tc(1)},entered:{opacity:1,transform:"none"},exiting:{opacity:0,transform:tc(.75)},exited:{opacity:0,transform:tc(.75)}},CO={opacity:0,transform:tc(.75),visibility:"hidden"},Wm=ue(function(t,r){let{addEndListener:o,appear:n=!0,children:s,disablePrefersReducedMotion:i=!1,easing:a,in:l,onEnter:c,onEntered:u,onEntering:f,onExit:m,onExited:p,onExiting:y,style:x,timeout:T="auto",...S}=t,v=J(null),R=ir(),P=ci(R.motion.reducedMotion,i),O=J(null),E=rn(O,On(s),r),A=ui(O,f),I=ui(O,(z,k)=>{P.shouldReduceMotion||wp(z);let{duration:j,delay:B,easing:W}=Vm({style:x,timeout:T,easing:a},{mode:"enter"}),H;T==="auto"&&!P.shouldReduceMotion?(H=R.transitions.getAutoHeightDuration(z.clientHeight),v.current=H):(H=j,v.current=null);let ee=P.getTransitionTiming({duration:H,delay:B});z.style.transition=[R.transitions.create("opacity",{duration:ee.duration,delay:ee.delay}),R.transitions.create("transform",{duration:typeof ee.duration=="string"?ee.duration:ee.duration*.666,delay:ee.delay,easing:W})].join(","),c&&c(z,k)}),N=ui(O,u),D=ui(O,y),w=ui(O,z=>{let{duration:k,delay:j,easing:B}=Vm({style:x,timeout:T,easing:a},{mode:"exit"}),W;T==="auto"&&!P.shouldReduceMotion?(W=R.transitions.getAutoHeightDuration(z.clientHeight),v.current=W):(W=k,v.current=null);let H=P.getTransitionTiming({duration:W,delay:j});z.style.transition=[R.transitions.create("opacity",{duration:H.duration,delay:H.delay}),R.transitions.create("transform",{duration:typeof H.duration=="string"?H.duration:H.duration*.666,delay:H.delay||(typeof H.duration=="string"?H.duration:H.duration*.333),easing:B})].join(","),z.style.opacity=0,z.style.transform=tc(.75),m&&m(z)}),$=ui(O,z=>{z.style.transition="",p&&p(z)});return b(M0,{appear:n,in:l,nodeRef:O,onEnter:I,onEntered:N,onEntering:A,onExit:w,onExited:$,onExiting:D,addEndListener:o?z=>{o(O.current,z)}:void 0,getAutoTimeout:T==="auto"?()=>v.current:void 0,reduceMotion:P.shouldReduceMotion,timeout:T==="auto"?null:T,...S,children:(z,{ownerState:k,...j})=>{let B=R0(z,l,wO,CO,x,s.props.style);return vr(s,{style:B,ref:E,...j})}})});Wm&&(Wm.muiSupportAuto=!0);var rc=Wm;K();K();var Gt="top",lr="bottom",or="right",Jt="left",Mp="auto",Os=[Gt,lr,or,Jt],Gn="start",hi="end",$0="clippingParents",$p="viewport",ja="popper",I0="reference",Hm=Os.reduce(function(e,t){return e.concat([t+"-"+Gn,t+"-"+hi])},[]),Ip=[].concat(Os,[Mp]).reduce(function(e,t){return e.concat([t,t+"-"+Gn,t+"-"+hi])},[]),EO="beforeRead",RO="read",kO="afterRead",OO="beforeMain",AO="main",MO="afterMain",$O="beforeWrite",IO="write",NO="afterWrite",N0=[EO,RO,kO,OO,AO,MO,$O,IO,NO];function Sr(e){return e?(e.nodeName||"").toLowerCase():null}function jt(e){if(e==null)return window;if(e.toString()!=="[object Window]"){var t=e.ownerDocument;return t&&t.defaultView||window}return e}function Oo(e){var t=jt(e).Element;return e instanceof t||e instanceof Element}function cr(e){var t=jt(e).HTMLElement;return e instanceof t||e instanceof HTMLElement}function Fa(e){if(typeof ShadowRoot>"u")return!1;var t=jt(e).ShadowRoot;return e instanceof t||e instanceof ShadowRoot}function zO(e){var t=e.state;Object.keys(t.elements).forEach(function(r){var o=t.styles[r]||{},n=t.attributes[r]||{},s=t.elements[r];!cr(s)||!Sr(s)||(Object.assign(s.style,o),Object.keys(n).forEach(function(i){var a=n[i];a===!1?s.removeAttribute(i):s.setAttribute(i,a===!0?"":a)}))})}function DO(e){var t=e.state,r={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(t.elements.popper.style,r.popper),t.styles=r,t.elements.arrow&&Object.assign(t.elements.arrow.style,r.arrow),function(){Object.keys(t.elements).forEach(function(o){var n=t.elements[o],s=t.attributes[o]||{},i=Object.keys(t.styles.hasOwnProperty(o)?t.styles[o]:r[o]),a=i.reduce(function(l,c){return l[c]="",l},{});!cr(n)||!Sr(n)||(Object.assign(n.style,a),Object.keys(s).forEach(function(l){n.removeAttribute(l)}))})}}var z0={name:"applyStyles",enabled:!0,phase:"write",fn:zO,effect:DO,requires:["computeStyles"]};function wr(e){return e.split("-")[0]}var nn=Math.max,yi=Math.min,Kn=Math.round;function Va(){var e=navigator.userAgentData;return e!=null&&e.brands&&Array.isArray(e.brands)?e.brands.map(function(t){return t.brand+"/"+t.version}).join(" "):navigator.userAgent}function oc(){return!/^((?!chrome|android).)*safari/i.test(Va())}function Ao(e,t,r){t===void 0&&(t=!1),r===void 0&&(r=!1);var o=e.getBoundingClientRect(),n=1,s=1;t&&cr(e)&&(n=e.offsetWidth>0&&Kn(o.width)/e.offsetWidth||1,s=e.offsetHeight>0&&Kn(o.height)/e.offsetHeight||1);var i=Oo(e)?jt(e):window,a=i.visualViewport,l=!oc()&&r,c=(o.left+(l&&a?a.offsetLeft:0))/n,u=(o.top+(l&&a?a.offsetTop:0))/s,f=o.width/n,m=o.height/s;return{width:f,height:m,top:u,right:c+f,bottom:u+m,left:c,x:c,y:u}}function gi(e){var t=Ao(e),r=e.offsetWidth,o=e.offsetHeight;return Math.abs(t.width-r)<=1&&(r=t.width),Math.abs(t.height-o)<=1&&(o=t.height),{x:e.offsetLeft,y:e.offsetTop,width:r,height:o}}function nc(e,t){var r=t.getRootNode&&t.getRootNode();if(e.contains(t))return!0;if(r&&Fa(r)){var o=t;do{if(o&&e.isSameNode(o))return!0;o=o.parentNode||o.host}while(o)}return!1}function Hr(e){return jt(e).getComputedStyle(e)}function Gm(e){return["table","td","th"].indexOf(Sr(e))>=0}function Or(e){return((Oo(e)?e.ownerDocument:e.document)||window.document).documentElement}function qn(e){return Sr(e)==="html"?e:e.assignedSlot||e.parentNode||(Fa(e)?e.host:null)||Or(e)}function D0(e){return!cr(e)||Hr(e).position==="fixed"?null:e.offsetParent}function BO(e){var t=/firefox/i.test(Va()),r=/Trident/i.test(Va());if(r&&cr(e)){var o=Hr(e);if(o.position==="fixed")return null}var n=qn(e);for(Fa(n)&&(n=n.host);cr(n)&&["html","body"].indexOf(Sr(n))<0;){var s=Hr(n);if(s.transform!=="none"||s.perspective!=="none"||s.contain==="paint"||["transform","perspective"].indexOf(s.willChange)!==-1||t&&s.willChange==="filter"||t&&s.filter&&s.filter!=="none")return n;n=n.parentNode}return null}function sn(e){for(var t=jt(e),r=D0(e);r&&Gm(r)&&Hr(r).position==="static";)r=D0(r);return r&&(Sr(r)==="html"||Sr(r)==="body"&&Hr(r).position==="static")?t:r||BO(e)||t}function bi(e){return["top","bottom"].indexOf(e)>=0?"x":"y"}function xi(e,t,r){return nn(e,yi(t,r))}function B0(e,t,r){var o=xi(e,t,r);return o>r?r:o}function sc(){return{top:0,right:0,bottom:0,left:0}}function ic(e){return Object.assign({},sc(),e)}function ac(e,t){return t.reduce(function(r,o){return r[o]=e,r},{})}var LO=function(t,r){return t=typeof t=="function"?t(Object.assign({},r.rects,{placement:r.placement})):t,ic(typeof t!="number"?t:ac(t,Os))};function jO(e){var t,r=e.state,o=e.name,n=e.options,s=r.elements.arrow,i=r.modifiersData.popperOffsets,a=wr(r.placement),l=bi(a),c=[Jt,or].indexOf(a)>=0,u=c?"height":"width";if(!(!s||!i)){var f=LO(n.padding,r),m=gi(s),p=l==="y"?Gt:Jt,y=l==="y"?lr:or,x=r.rects.reference[u]+r.rects.reference[l]-i[l]-r.rects.popper[u],T=i[l]-r.rects.reference[l],S=sn(s),v=S?l==="y"?S.clientHeight||0:S.clientWidth||0:0,R=x/2-T/2,P=f[p],O=v-m[u]-f[y],E=v/2-m[u]/2+R,A=xi(P,E,O),I=l;r.modifiersData[o]=(t={},t[I]=A,t.centerOffset=A-E,t)}}function FO(e){var t=e.state,r=e.options,o=r.element,n=o===void 0?"[data-popper-arrow]":o;n!=null&&(typeof n=="string"&&(n=t.elements.popper.querySelector(n),!n)||nc(t.elements.popper,n)&&(t.elements.arrow=n))}var L0={name:"arrow",enabled:!0,phase:"main",fn:jO,effect:FO,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Mo(e){return e.split("-")[1]}var VO={top:"auto",right:"auto",bottom:"auto",left:"auto"};function UO(e,t){var r=e.x,o=e.y,n=t.devicePixelRatio||1;return{x:Kn(r*n)/n||0,y:Kn(o*n)/n||0}}function j0(e){var t,r=e.popper,o=e.popperRect,n=e.placement,s=e.variation,i=e.offsets,a=e.position,l=e.gpuAcceleration,c=e.adaptive,u=e.roundOffsets,f=e.isFixed,m=i.x,p=m===void 0?0:m,y=i.y,x=y===void 0?0:y,T=typeof u=="function"?u({x:p,y:x}):{x:p,y:x};p=T.x,x=T.y;var S=i.hasOwnProperty("x"),v=i.hasOwnProperty("y"),R=Jt,P=Gt,O=window;if(c){var E=sn(r),A="clientHeight",I="clientWidth";if(E===jt(r)&&(E=Or(r),Hr(E).position!=="static"&&a==="absolute"&&(A="scrollHeight",I="scrollWidth")),E=E,n===Gt||(n===Jt||n===or)&&s===hi){P=lr;var N=f&&E===O&&O.visualViewport?O.visualViewport.height:E[A];x-=N-o.height,x*=l?1:-1}if(n===Jt||(n===Gt||n===lr)&&s===hi){R=or;var D=f&&E===O&&O.visualViewport?O.visualViewport.width:E[I];p-=D-o.width,p*=l?1:-1}}var w=Object.assign({position:a},c&&VO),$=u===!0?UO({x:p,y:x},jt(r)):{x:p,y:x};if(p=$.x,x=$.y,l){var h;return Object.assign({},w,(h={},h[P]=v?"0":"",h[R]=S?"0":"",h.transform=(O.devicePixelRatio||1)<=1?"translate("+p+"px, "+x+"px)":"translate3d("+p+"px, "+x+"px, 0)",h))}return Object.assign({},w,(t={},t[P]=v?x+"px":"",t[R]=S?p+"px":"",t.transform="",t))}function ZO(e){var t=e.state,r=e.options,o=r.gpuAcceleration,n=o===void 0?!0:o,s=r.adaptive,i=s===void 0?!0:s,a=r.roundOffsets,l=a===void 0?!0:a,c={placement:wr(t.placement),variation:Mo(t.placement),popper:t.elements.popper,popperRect:t.rects.popper,gpuAcceleration:n,isFixed:t.options.strategy==="fixed"};t.modifiersData.popperOffsets!=null&&(t.styles.popper=Object.assign({},t.styles.popper,j0(Object.assign({},c,{offsets:t.modifiersData.popperOffsets,position:t.options.strategy,adaptive:i,roundOffsets:l})))),t.modifiersData.arrow!=null&&(t.styles.arrow=Object.assign({},t.styles.arrow,j0(Object.assign({},c,{offsets:t.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-placement":t.placement})}var F0={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:ZO,data:{}};var Np={passive:!0};function WO(e){var t=e.state,r=e.instance,o=e.options,n=o.scroll,s=n===void 0?!0:n,i=o.resize,a=i===void 0?!0:i,l=jt(t.elements.popper),c=[].concat(t.scrollParents.reference,t.scrollParents.popper);return s&&c.forEach(function(u){u.addEventListener("scroll",r.update,Np)}),a&&l.addEventListener("resize",r.update,Np),function(){s&&c.forEach(function(u){u.removeEventListener("scroll",r.update,Np)}),a&&l.removeEventListener("resize",r.update,Np)}}var V0={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:WO,data:{}};var HO={left:"right",right:"left",bottom:"top",top:"bottom"};function Ua(e){return e.replace(/left|right|bottom|top/g,function(t){return HO[t]})}var GO={start:"end",end:"start"};function zp(e){return e.replace(/start|end/g,function(t){return GO[t]})}function vi(e){var t=jt(e),r=t.pageXOffset,o=t.pageYOffset;return{scrollLeft:r,scrollTop:o}}function Ti(e){return Ao(Or(e)).left+vi(e).scrollLeft}function Km(e,t){var r=jt(e),o=Or(e),n=r.visualViewport,s=o.clientWidth,i=o.clientHeight,a=0,l=0;if(n){s=n.width,i=n.height;var c=oc();(c||!c&&t==="fixed")&&(a=n.offsetLeft,l=n.offsetTop)}return{width:s,height:i,x:a+Ti(e),y:l}}function qm(e){var t,r=Or(e),o=vi(e),n=(t=e.ownerDocument)==null?void 0:t.body,s=nn(r.scrollWidth,r.clientWidth,n?n.scrollWidth:0,n?n.clientWidth:0),i=nn(r.scrollHeight,r.clientHeight,n?n.scrollHeight:0,n?n.clientHeight:0),a=-o.scrollLeft+Ti(e),l=-o.scrollTop;return Hr(n||r).direction==="rtl"&&(a+=nn(r.clientWidth,n?n.clientWidth:0)-s),{width:s,height:i,x:a,y:l}}function Pi(e){var t=Hr(e),r=t.overflow,o=t.overflowX,n=t.overflowY;return/auto|scroll|overlay|hidden/.test(r+n+o)}function Dp(e){return["html","body","#document"].indexOf(Sr(e))>=0?e.ownerDocument.body:cr(e)&&Pi(e)?e:Dp(qn(e))}function As(e,t){var r;t===void 0&&(t=[]);var o=Dp(e),n=o===((r=e.ownerDocument)==null?void 0:r.body),s=jt(o),i=n?[s].concat(s.visualViewport||[],Pi(o)?o:[]):o,a=t.concat(i);return n?a:a.concat(As(qn(i)))}function Za(e){return Object.assign({},e,{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height})}function KO(e,t){var r=Ao(e,!1,t==="fixed");return r.top=r.top+e.clientTop,r.left=r.left+e.clientLeft,r.bottom=r.top+e.clientHeight,r.right=r.left+e.clientWidth,r.width=e.clientWidth,r.height=e.clientHeight,r.x=r.left,r.y=r.top,r}function U0(e,t,r){return t===$p?Za(Km(e,r)):Oo(t)?KO(t,r):Za(qm(Or(e)))}function qO(e){var t=As(qn(e)),r=["absolute","fixed"].indexOf(Hr(e).position)>=0,o=r&&cr(e)?sn(e):e;return Oo(o)?t.filter(function(n){return Oo(n)&&nc(n,o)&&Sr(n)!=="body"}):[]}function Ym(e,t,r,o){var n=t==="clippingParents"?qO(e):[].concat(t),s=[].concat(n,[r]),i=s[0],a=s.reduce(function(l,c){var u=U0(e,c,o);return l.top=nn(u.top,l.top),l.right=yi(u.right,l.right),l.bottom=yi(u.bottom,l.bottom),l.left=nn(u.left,l.left),l},U0(e,i,o));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}function lc(e){var t=e.reference,r=e.element,o=e.placement,n=o?wr(o):null,s=o?Mo(o):null,i=t.x+t.width/2-r.width/2,a=t.y+t.height/2-r.height/2,l;switch(n){case Gt:l={x:i,y:t.y-r.height};break;case lr:l={x:i,y:t.y+t.height};break;case or:l={x:t.x+t.width,y:a};break;case Jt:l={x:t.x-r.width,y:a};break;default:l={x:t.x,y:t.y}}var c=n?bi(n):null;if(c!=null){var u=c==="y"?"height":"width";switch(s){case Gn:l[c]=l[c]-(t[u]/2-r[u]/2);break;case hi:l[c]=l[c]+(t[u]/2-r[u]/2);break;default:}}return l}function an(e,t){t===void 0&&(t={});var r=t,o=r.placement,n=o===void 0?e.placement:o,s=r.strategy,i=s===void 0?e.strategy:s,a=r.boundary,l=a===void 0?$0:a,c=r.rootBoundary,u=c===void 0?$p:c,f=r.elementContext,m=f===void 0?ja:f,p=r.altBoundary,y=p===void 0?!1:p,x=r.padding,T=x===void 0?0:x,S=ic(typeof T!="number"?T:ac(T,Os)),v=m===ja?I0:ja,R=e.rects.popper,P=e.elements[y?v:m],O=Ym(Oo(P)?P:P.contextElement||Or(e.elements.popper),l,u,i),E=Ao(e.elements.reference),A=lc({reference:E,element:R,strategy:"absolute",placement:n}),I=Za(Object.assign({},R,A)),N=m===ja?I:E,D={top:O.top-N.top+S.top,bottom:N.bottom-O.bottom+S.bottom,left:O.left-N.left+S.left,right:N.right-O.right+S.right},w=e.modifiersData.offset;if(m===ja&&w){var $=w[n];Object.keys(D).forEach(function(h){var z=[or,lr].indexOf(h)>=0?1:-1,k=[Gt,lr].indexOf(h)>=0?"y":"x";D[h]+=$[k]*z})}return D}function Xm(e,t){t===void 0&&(t={});var r=t,o=r.placement,n=r.boundary,s=r.rootBoundary,i=r.padding,a=r.flipVariations,l=r.allowedAutoPlacements,c=l===void 0?Ip:l,u=Mo(o),f=u?a?Hm:Hm.filter(function(y){return Mo(y)===u}):Os,m=f.filter(function(y){return c.indexOf(y)>=0});m.length===0&&(m=f);var p=m.reduce(function(y,x){return y[x]=an(e,{placement:x,boundary:n,rootBoundary:s,padding:i})[wr(x)],y},{});return Object.keys(p).sort(function(y,x){return p[y]-p[x]})}function YO(e){if(wr(e)===Mp)return[];var t=Ua(e);return[zp(e),t,zp(t)]}function XO(e){var t=e.state,r=e.options,o=e.name;if(!t.modifiersData[o]._skip){for(var n=r.mainAxis,s=n===void 0?!0:n,i=r.altAxis,a=i===void 0?!0:i,l=r.fallbackPlacements,c=r.padding,u=r.boundary,f=r.rootBoundary,m=r.altBoundary,p=r.flipVariations,y=p===void 0?!0:p,x=r.allowedAutoPlacements,T=t.options.placement,S=wr(T),v=S===T,R=l||(v||!y?[Ua(T)]:YO(T)),P=[T].concat(R).reduce(function(te,oe){return te.concat(wr(oe)===Mp?Xm(t,{placement:oe,boundary:u,rootBoundary:f,padding:c,flipVariations:y,allowedAutoPlacements:x}):oe)},[]),O=t.rects.reference,E=t.rects.popper,A=new Map,I=!0,N=P[0],D=0;D<P.length;D++){var w=P[D],$=wr(w),h=Mo(w)===Gn,z=[Gt,lr].indexOf($)>=0,k=z?"width":"height",j=an(t,{placement:w,boundary:u,rootBoundary:f,altBoundary:m,padding:c}),B=z?h?or:Jt:h?lr:Gt;O[k]>E[k]&&(B=Ua(B));var W=Ua(B),H=[];if(s&&H.push(j[$]<=0),a&&H.push(j[B]<=0,j[W]<=0),H.every(function(te){return te})){N=w,I=!1;break}A.set(w,H)}if(I)for(var ee=y?3:1,G=function(oe){var Y=P.find(function(fe){var se=A.get(fe);if(se)return se.slice(0,oe).every(function(be){return be})});if(Y)return N=Y,"break"},F=ee;F>0;F--){var V=G(F);if(V==="break")break}t.placement!==N&&(t.modifiersData[o]._skip=!0,t.placement=N,t.reset=!0)}}var Z0={name:"flip",enabled:!0,phase:"main",fn:XO,requiresIfExists:["offset"],data:{_skip:!1}};function W0(e,t,r){return r===void 0&&(r={x:0,y:0}),{top:e.top-t.height-r.y,right:e.right-t.width+r.x,bottom:e.bottom-t.height+r.y,left:e.left-t.width-r.x}}function H0(e){return[Gt,or,lr,Jt].some(function(t){return e[t]>=0})}function JO(e){var t=e.state,r=e.name,o=t.rects.reference,n=t.rects.popper,s=t.modifiersData.preventOverflow,i=an(t,{elementContext:"reference"}),a=an(t,{altBoundary:!0}),l=W0(i,o),c=W0(a,n,s),u=H0(l),f=H0(c);t.modifiersData[r]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:u,hasPopperEscaped:f},t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-reference-hidden":u,"data-popper-escaped":f})}var G0={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:JO};function QO(e,t,r){var o=wr(e),n=[Jt,Gt].indexOf(o)>=0?-1:1,s=typeof r=="function"?r(Object.assign({},t,{placement:e})):r,i=s[0],a=s[1];return i=i||0,a=(a||0)*n,[Jt,or].indexOf(o)>=0?{x:a,y:i}:{x:i,y:a}}function eA(e){var t=e.state,r=e.options,o=e.name,n=r.offset,s=n===void 0?[0,0]:n,i=Ip.reduce(function(u,f){return u[f]=QO(f,t.rects,s),u},{}),a=i[t.placement],l=a.x,c=a.y;t.modifiersData.popperOffsets!=null&&(t.modifiersData.popperOffsets.x+=l,t.modifiersData.popperOffsets.y+=c),t.modifiersData[o]=i}var K0={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:eA};function tA(e){var t=e.state,r=e.name;t.modifiersData[r]=lc({reference:t.rects.reference,element:t.rects.popper,strategy:"absolute",placement:t.placement})}var q0={name:"popperOffsets",enabled:!0,phase:"read",fn:tA,data:{}};function Jm(e){return e==="x"?"y":"x"}function rA(e){var t=e.state,r=e.options,o=e.name,n=r.mainAxis,s=n===void 0?!0:n,i=r.altAxis,a=i===void 0?!1:i,l=r.boundary,c=r.rootBoundary,u=r.altBoundary,f=r.padding,m=r.tether,p=m===void 0?!0:m,y=r.tetherOffset,x=y===void 0?0:y,T=an(t,{boundary:l,rootBoundary:c,padding:f,altBoundary:u}),S=wr(t.placement),v=Mo(t.placement),R=!v,P=bi(S),O=Jm(P),E=t.modifiersData.popperOffsets,A=t.rects.reference,I=t.rects.popper,N=typeof x=="function"?x(Object.assign({},t.rects,{placement:t.placement})):x,D=typeof N=="number"?{mainAxis:N,altAxis:N}:Object.assign({mainAxis:0,altAxis:0},N),w=t.modifiersData.offset?t.modifiersData.offset[t.placement]:null,$={x:0,y:0};if(E){if(s){var h,z=P==="y"?Gt:Jt,k=P==="y"?lr:or,j=P==="y"?"height":"width",B=E[P],W=B+T[z],H=B-T[k],ee=p?-I[j]/2:0,G=v===Gn?A[j]:I[j],F=v===Gn?-I[j]:-A[j],V=t.elements.arrow,te=p&&V?gi(V):{width:0,height:0},oe=t.modifiersData["arrow#persistent"]?t.modifiersData["arrow#persistent"].padding:sc(),Y=oe[z],fe=oe[k],se=xi(0,A[j],te[j]),be=R?A[j]/2-ee-se-Y-D.mainAxis:G-se-Y-D.mainAxis,Pe=R?-A[j]/2+ee+se+fe+D.mainAxis:F+se+fe+D.mainAxis,We=t.elements.arrow&&sn(t.elements.arrow),qe=We?P==="y"?We.clientTop||0:We.clientLeft||0:0,He=(h=w?.[P])!=null?h:0,Ye=B+be-He-qe,$e=B+Pe-He,Ge=xi(p?yi(W,Ye):W,B,p?nn(H,$e):H);E[P]=Ge,$[P]=Ge-B}if(a){var yt,Ot=P==="x"?Gt:Jt,Xe=P==="x"?lr:or,Ve=E[O],Tt=O==="y"?"height":"width",dt=Ve+T[Ot],Vt=Ve-T[Xe],me=[Gt,Jt].indexOf(S)!==-1,re=(yt=w?.[O])!=null?yt:0,xe=me?dt:Ve-A[Tt]-I[Tt]-re+D.altAxis,_e=me?Ve+A[Tt]+I[Tt]-re-D.altAxis:Vt,je=p&&me?B0(xe,Ve,_e):xi(p?xe:dt,Ve,p?_e:Vt);E[O]=je,$[O]=je-Ve}t.modifiersData[o]=$}}var Y0={name:"preventOverflow",enabled:!0,phase:"main",fn:rA,requiresIfExists:["offset"]};function Qm(e){return{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}}function eh(e){return e===jt(e)||!cr(e)?vi(e):Qm(e)}function oA(e){var t=e.getBoundingClientRect(),r=Kn(t.width)/e.offsetWidth||1,o=Kn(t.height)/e.offsetHeight||1;return r!==1||o!==1}function th(e,t,r){r===void 0&&(r=!1);var o=cr(t),n=cr(t)&&oA(t),s=Or(t),i=Ao(e,n,r),a={scrollLeft:0,scrollTop:0},l={x:0,y:0};return(o||!o&&!r)&&((Sr(t)!=="body"||Pi(s))&&(a=eh(t)),cr(t)?(l=Ao(t,!0),l.x+=t.clientLeft,l.y+=t.clientTop):s&&(l.x=Ti(s))),{x:i.left+a.scrollLeft-l.x,y:i.top+a.scrollTop-l.y,width:i.width,height:i.height}}function nA(e){var t=new Map,r=new Set,o=[];e.forEach(function(s){t.set(s.name,s)});function n(s){r.add(s.name);var i=[].concat(s.requires||[],s.requiresIfExists||[]);i.forEach(function(a){if(!r.has(a)){var l=t.get(a);l&&n(l)}}),o.push(s)}return e.forEach(function(s){r.has(s.name)||n(s)}),o}function rh(e){var t=nA(e);return N0.reduce(function(r,o){return r.concat(t.filter(function(n){return n.phase===o}))},[])}function oh(e){var t;return function(){return t||(t=new Promise(function(r){Promise.resolve().then(function(){t=void 0,r(e())})})),t}}function nh(e){var t=e.reduce(function(r,o){var n=r[o.name];return r[o.name]=n?Object.assign({},n,o,{options:Object.assign({},n.options,o.options),data:Object.assign({},n.data,o.data)}):o,r},{});return Object.keys(t).map(function(r){return t[r]})}var X0={placement:"bottom",modifiers:[],strategy:"absolute"};function J0(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return!t.some(function(o){return!(o&&typeof o.getBoundingClientRect=="function")})}function Q0(e){e===void 0&&(e={});var t=e,r=t.defaultModifiers,o=r===void 0?[]:r,n=t.defaultOptions,s=n===void 0?X0:n;return function(a,l,c){c===void 0&&(c=s);var u={placement:"bottom",orderedModifiers:[],options:Object.assign({},X0,s),modifiersData:{},elements:{reference:a,popper:l},attributes:{},styles:{}},f=[],m=!1,p={state:u,setOptions:function(S){var v=typeof S=="function"?S(u.options):S;x(),u.options=Object.assign({},s,u.options,v),u.scrollParents={reference:Oo(a)?As(a):a.contextElement?As(a.contextElement):[],popper:As(l)};var R=rh(nh([].concat(o,u.options.modifiers)));return u.orderedModifiers=R.filter(function(P){return P.enabled}),y(),p.update()},forceUpdate:function(){if(!m){var S=u.elements,v=S.reference,R=S.popper;if(J0(v,R)){u.rects={reference:th(v,sn(R),u.options.strategy==="fixed"),popper:gi(R)},u.reset=!1,u.placement=u.options.placement,u.orderedModifiers.forEach(function(D){return u.modifiersData[D.name]=Object.assign({},D.data)});for(var P=0;P<u.orderedModifiers.length;P++){if(u.reset===!0){u.reset=!1,P=-1;continue}var O=u.orderedModifiers[P],E=O.fn,A=O.options,I=A===void 0?{}:A,N=O.name;typeof E=="function"&&(u=E({state:u,options:I,name:N,instance:p})||u)}}}},update:oh(function(){return new Promise(function(T){p.forceUpdate(),T(u)})}),destroy:function(){x(),m=!0}};if(!J0(a,l))return p;p.setOptions(c).then(function(T){!m&&c.onFirstUpdate&&c.onFirstUpdate(T)});function y(){u.orderedModifiers.forEach(function(T){var S=T.name,v=T.options,R=v===void 0?{}:v,P=T.effect;if(typeof P=="function"){var O=P({state:u,name:S,instance:p,options:R}),E=function(){};f.push(O||E)}})}function x(){f.forEach(function(T){return T()}),f=[]}return p}}var sA=[V0,q0,F0,z0,K0,Z0,Y0,L0,G0],sh=Q0({defaultModifiers:sA});function iA(e){let{elementType:t,externalSlotProps:r,ownerState:o,skipResolvingSlotProps:n=!1,...s}=e,i=n?{}:Jl(r,o),{props:a,internalRef:l}=Ql({...s,externalSlotProps:i}),c=ar(l,i?.ref,e.additionalProps?.ref);return Xl(t,{...a,ref:c},o)}var Yn=iA;K();K();function aA(e){return typeof e=="function"?e():e}var lA=ue(function(t,r){let{children:o,container:n,disablePortal:s=!1}=t,[i,a]=ie(null),l=ar(Rt(o)?On(o):null,r);return at(()=>{s||a(aA(n)||document.body)},[n,s]),at(()=>{if(i&&!s)return di(r,i),()=>{di(r,null)}},[r,i,s]),s?Rt(o)?vr(o,{ref:l}):o:i&&Gc(o,i)}),ih=lA;function eT(e){return we("MuiPopper",e)}var IY=Ce("MuiPopper",["root"]);function cA(e,t){if(t==="ltr")return e;switch(e){case"bottom-end":return"bottom-start";case"bottom-start":return"bottom-end";case"top-end":return"top-start";case"top-start":return"top-end";default:return e}}function tT(e){return typeof e=="function"?e():e}function uA(e){return e.nodeType!==void 0}var pA=e=>{let{classes:t}=e;return ke({root:["root"]},eT,t)},fA={},dA=ue(function(t,r){let{anchorEl:o,children:n,direction:s,disablePortal:i,modifiers:a,open:l,placement:c,popperOptions:u,popperRef:f,slotProps:m={},slots:p={},TransitionProps:y,ownerState:x,...T}=t,S=J(null),v=ar(S,r),R=J(null),P=ar(R,f),O=J(P);at(()=>{O.current=P},[P]),To(f,()=>R.current,[]);let E=cA(c,s),[A,I]=ie(E),N=Le(()=>tT(o),[o]);ce(()=>{R.current&&R.current.forceUpdate()}),at(()=>{if(!N||!l)return;let z=W=>{I(W.placement)},k=[{name:"preventOverflow",options:{altBoundary:i}},{name:"flip",options:{altBoundary:i}},{name:"onUpdate",enabled:!0,phase:"afterWrite",fn:({state:W})=>{z(W)}}];a!=null&&(k=k.concat(a)),u&&u.modifiers!=null&&(k=k.concat(u.modifiers));let j=sh(N,S.current,{placement:E,...u,modifiers:k});O.current(j);let B=S.current;return()=>{if(B){let{style:W}=B,H=W.position,ee=W.top,G=W.left,F=W.transform;j.destroy(),W.position=H,W.top=ee,W.left=G,W.transform=F}else j.destroy();O.current(null)}},[N,i,a,l,u,E]);let D={placement:A};y!==null&&(D.TransitionProps=y);let w=pA(t),$=p.root??"div",h=Yn({elementType:$,externalSlotProps:m.root,externalForwardedProps:T,additionalProps:{role:"tooltip",ref:v},ownerState:t,className:w.root});return b($,{...h,children:typeof n=="function"?n(D):n})}),mA=ue(function(t,r){let{anchorEl:o,children:n,container:s,direction:i="ltr",disablePortal:a=!1,keepMounted:l=!1,modifiers:c,open:u,placement:f="bottom",popperOptions:m=fA,popperRef:p,style:y,transition:x=!1,slotProps:T={},slots:S={},...v}=t,[R,P]=ie(!0),O=()=>{P(!1)},E=()=>{P(!0)};if(!l&&!u&&(!x||R))return null;let A;if(s)A=s;else if(o){let D=tT(o);A=D&&uA(D)?Dr(D).body:Dr(null).body}let I=!u&&l&&(!x||R)?"none":void 0,N=x?{in:u,onEnter:O,onExited:E}:void 0;return b(ih,{disablePortal:a,container:A,children:b(dA,{anchorEl:o,direction:i,disablePortal:a,modifiers:c,ref:r,open:x?!R:u,placement:f,popperOptions:m,popperRef:p,slotProps:T,slots:S,...v,style:{position:"fixed",top:0,left:0,display:I,...y},TransitionProps:N,children:n})})}),rT=mA;var hA=ne(rT,{name:"MuiPopper",slot:"Root"})({}),yA=ue(function(t,r){let o=Sa(),n=Me({props:t,name:"MuiPopper"}),{anchorEl:s,component:i,container:a,disablePortal:l,keepMounted:c,modifiers:u,open:f,placement:m,popperOptions:p,popperRef:y,transition:x,slots:T,slotProps:S,...v}=n,R={anchorEl:s,container:a,disablePortal:l,keepMounted:c,modifiers:u,open:f,placement:m,popperOptions:p,popperRef:y,transition:x,...v};return b(hA,{as:i,direction:o?"rtl":"ltr",slots:T,slotProps:S,...R,ref:r})}),Bp=yA;function oT(e){return we("MuiTooltip",e)}var gA=Ce("MuiTooltip",["popper","popperInteractive","popperArrow","popperClose","tooltip","tooltipArrow","touch","tooltipPlacementLeft","tooltipPlacementRight","tooltipPlacementTop","tooltipPlacementBottom","arrow"]),lo=gA;function bA(e){return Math.round(e*1e5)/1e5}var xA=e=>{let{classes:t,disableInteractive:r,arrow:o,touch:n,placement:s,open:i}=e,a={popper:["popper",!r&&"popperInteractive",o&&"popperArrow",!i&&"popperClose"],tooltip:["tooltip",o&&"tooltipArrow",n&&"touch",`tooltipPlacement${Te(s.split("-")[0])}`],arrow:["arrow"]};return ke(a,oT,t)},vA=ne(Bp,{name:"MuiTooltip",slot:"Popper",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.popper,!r.disableInteractive&&t.popperInteractive,r.arrow&&t.popperArrow,!r.open&&t.popperClose]}})(ze(({theme:e})=>({zIndex:(e.vars||e).zIndex.tooltip,pointerEvents:"none",variants:[{props:({ownerState:t})=>t.open&&!t.disableInteractive,style:{pointerEvents:"auto"}},{props:({ownerState:t})=>t.arrow,style:{[`&[data-popper-placement*="bottom"] .${lo.arrow}`]:{top:0,marginTop:"-0.71em","&::before":{transformOrigin:"0 100%"}},[`&[data-popper-placement*="top"] .${lo.arrow}`]:{bottom:0,marginBottom:"-0.71em","&::before":{transformOrigin:"100% 0"}},[`&[data-popper-placement*="right"] .${lo.arrow}`]:{height:"1em",width:"0.71em",insetInlineStart:0,marginInlineStart:"-0.71em","&::before":{transformOrigin:"100% 100%"}},[`&[data-popper-placement*="left"] .${lo.arrow}`]:{height:"1em",width:"0.71em",insetInlineEnd:0,marginInlineEnd:"-0.71em","&::before":{transformOrigin:"0 0"}}}}]}))),TA=ne("div",{name:"MuiTooltip",slot:"Tooltip",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.tooltip,r.touch&&t.touch,r.arrow&&t.tooltipArrow,t[`tooltipPlacement${Te(r.placement.split("-")[0])}`]]}})(ze(({theme:e})=>({backgroundColor:e.vars?e.vars.palette.Tooltip.bg:e.alpha(e.palette.grey[700],.92),borderRadius:(e.vars||e).shape.borderRadius,color:(e.vars||e).palette.common.white,fontFamily:e.typography.fontFamily,padding:"4px 8px",fontSize:e.typography.pxToRem(11),maxWidth:300,margin:2,wordWrap:"break-word",fontWeight:e.typography.fontWeightMedium,[`.${lo.popper}[data-popper-placement*="left"] &`]:{transformOrigin:"right center",marginInlineEnd:"14px"},[`.${lo.popper}[data-popper-placement*="right"] &`]:{transformOrigin:"left center",marginInlineStart:"14px"},[`.${lo.popper}[data-popper-placement*="top"] &`]:{transformOrigin:"center bottom",marginBottom:"14px"},[`.${lo.popper}[data-popper-placement*="bottom"] &`]:{transformOrigin:"center top",marginTop:"14px"},variants:[{props:({ownerState:t})=>t.arrow,style:{position:"relative",marginBlock:0}},{props:({ownerState:t})=>t.touch,style:{padding:"8px 16px",fontSize:e.typography.pxToRem(14),lineHeight:`${bA(16/14)}em`,fontWeight:e.typography.fontWeightRegular}},{props:({ownerState:t})=>t.touch,style:{[`.${lo.popper}[data-popper-placement*="left"] &`]:{marginInlineEnd:"24px"},[`.${lo.popper}[data-popper-placement*="right"] &`]:{marginInlineStart:"24px"},[`.${lo.popper}[data-popper-placement*="top"] &`]:{marginBottom:"24px"},[`.${lo.popper}[data-popper-placement*="bottom"] &`]:{marginTop:"24px"}}}]}))),PA=ne("span",{name:"MuiTooltip",slot:"Arrow"})(ze(({theme:e})=>({overflow:"hidden",position:"absolute",width:"1em",height:"0.71em",boxSizing:"border-box",color:e.vars?e.vars.palette.Tooltip.bg:e.alpha(e.palette.grey[700],.9),"&::before":{content:'""',margin:"auto",display:"block",width:"100%",height:"100%",backgroundColor:"currentColor",transform:"rotate(45deg)"}}))),Lp=!1,nT=new Ia,cc={x:0,y:0};function jp(e,t){return(r,...o)=>{t&&t(r,...o),e(r,...o)}}var _A=ue(function(t,r){let o=Me({props:t,name:"MuiTooltip"}),{arrow:n=!1,children:s,classes:i,describeChild:a=!1,disableFocusListener:l=!1,disableHoverListener:c=!1,disableInteractive:u=!1,disableTouchListener:f=!1,enterDelay:m=100,enterNextDelay:p=0,enterTouchDelay:y=700,followCursor:x=!1,id:T,leaveDelay:S=0,leaveTouchDelay:v=1500,onClose:R,onOpen:P,open:O,placement:E="bottom",slotProps:A={},slots:I={},title:N,...D}=o,w=Rt(s)?s:b("span",{children:s}),$=ir(),[h,z]=ie(),[k,j]=ie(null),B=J(!1),W=J(!1),H=u||x,ee=ao(),G=ao(),F=ao(),V=ao(),[te,oe]=Tp({controlled:O,default:!1,name:"Tooltip",state:"open"}),Y=te,{current:fe}=J(O!==void 0),se=mi(T),be=J(),Pe=Pr(()=>{be.current!==void 0&&(document.body.style.WebkitUserSelect=be.current,be.current=void 0),V.clear()});ce(()=>Pe,[Pe]);let We=Re=>{nT.clear(),Lp=!0,oe(!0),P&&!Y&&P(Re)},qe=Pr(Re=>{W.current=!1,nT.start(800+S,()=>{Lp=!1}),oe(!1),R&&Y&&R(Re),ee.start($.transitions.duration.shortest,()=>{B.current=!1})}),He=Re=>{B.current&&Re.type!=="touchstart"||(h&&h.removeAttribute("title"),G.clear(),F.clear(),m||Lp&&p?G.start(Lp?p:m,()=>{We(Re)}):We(Re))},Ye=Re=>{if(h?.disabled&&!fe){if(Y&&!W.current)return;W.current=!0}else W.current=!1;He(Re)},$e=Re=>{h?.disabled&&!fe&&!W.current||He(Re)},Ge=Re=>{G.clear(),F.start(S,()=>{qe(Re)})},[,yt]=ie(!1),Ot=Re=>{let Zt=Re?.target??h;if(!Zt||Zt.disabled||!Cs(Zt)){yt(!1);let Lo=Re??new Event("blur");!Re&&Zt&&(Object.defineProperty(Lo,"target",{value:Zt}),Object.defineProperty(Lo,"currentTarget",{value:Zt})),Ge(Lo)}},Xe=Re=>{if(h||z(Re.currentTarget),W.current=!1,Cs(Re.target)){let Zt=Lo=>{Lo.target.disabled&&Ot(Lo),Lo.target.removeEventListener("blur",Zt)};Re.target.addEventListener("blur",Zt),yt(!0),He(Re)}},Ve=Re=>{B.current=!0;let Zt=w.props;Zt.onTouchStart&&Zt.onTouchStart(Re)},Tt=Re=>{Ve(Re),F.clear(),ee.clear(),Pe(),be.current=document.body.style.WebkitUserSelect,document.body.style.WebkitUserSelect="none",V.start(y,()=>{document.body.style.WebkitUserSelect=be.current,Ye(Re)})},dt=Re=>{w.props.onTouchEnd&&w.props.onTouchEnd(Re),Pe(),F.start(v,()=>{qe(Re)})};ce(()=>{if(!Y)return;function Re(Zt){Zt.key==="Escape"&&qe(Zt)}return document.addEventListener("keydown",Re),()=>{document.removeEventListener("keydown",Re)}},[qe,Y]);let Vt=rn(On(w),z,r);!N&&N!==0&&(Y=!1);let me=J(),re=Re=>{let Zt=w.props;Zt.onMouseMove&&Zt.onMouseMove(Re),cc={x:Re.clientX,y:Re.clientY},me.current&&me.current.update()},xe={},_e=typeof N=="string";a?(xe.title=!Y&&_e&&!c?N:null,xe["aria-describedby"]=Y?se:null):(xe["aria-label"]=_e?N:null,xe["aria-labelledby"]=Y&&!_e?se:null);let je={...xe,...D,...w.props,className:he(D.className,w.props.className),onTouchStart:Ve,ref:Vt,...x?{onMouseMove:re}:{}},et={};f||(je.onTouchStart=Tt,je.onTouchEnd=dt),c||(je.onMouseOver=jp(Ye,je.onMouseOver),je.onMouseLeave=jp(Ge,je.onMouseLeave),H||(et.onMouseOver=$e,et.onMouseLeave=Ge)),l||(je.onFocus=jp(Xe,je.onFocus),je.onBlur=jp(Ot,je.onBlur),H||(et.onFocus=Xe,et.onBlur=Ot));let gt={...o,arrow:n,disableInteractive:H,open:Y,placement:E,touch:B.current},Oe=typeof A.popper=="function"?A.popper(gt):A.popper,Pt=Le(()=>{let Re=[{name:"arrow",enabled:!!k,options:{element:k,padding:4}}];return Oe?.popperOptions?.modifiers&&(Re=Re.concat(Oe.popperOptions.modifiers)),{...Oe?.popperOptions,modifiers:Re}},[k,Oe?.popperOptions]),mt=xA(gt),bt={slots:I,slotProps:{arrow:A.arrow,popper:Oe,tooltip:A.tooltip,transition:A.transition}},[Fe,Ns]=ot("popper",{elementType:vA,externalForwardedProps:bt,ownerState:gt,className:mt.popper}),[rs,Bo]=ot("transition",{elementType:rc,externalForwardedProps:bt,ownerState:gt}),[mo,mn]=ot("tooltip",{elementType:TA,className:mt.tooltip,externalForwardedProps:bt,ownerState:gt}),[Br,zs]=ot("arrow",{elementType:PA,className:mt.arrow,externalForwardedProps:bt,ownerState:gt,ref:j});return b(Ie,{children:[vr(w,je),b(Fe,{as:Bp,placement:E,anchorEl:x?{getBoundingClientRect:()=>({top:cc.y,left:cc.x,right:cc.x,bottom:cc.y,width:0,height:0})}:h,popperRef:me,open:h?Y:!1,id:se,transition:!0,...et,...Ns,popperOptions:Pt,children:({TransitionProps:Re})=>b(rs,{timeout:$.transitions.duration.shorter,...Re,...Bo,children:b(mo,{...mn,children:[N,n?b(Br,{...zs}):null]})})})]})}),$o=_A;function ah(e){let t=Se(xl);return b(Ie,{children:[b($o,{title:"Refresh",children:b(ec,{checked:t.refresh,onChange:t.toggleRefresh,...e})}),b(_r,{sx:{display:{xs:"none",sm:"inherit"},marginRight:1},children:"Refresh"})]})}K();K();function Fp(e){return parseInt(e,10)||0}var SA={shadow:{visibility:"hidden",position:"absolute",overflow:"hidden",height:0,top:0,left:0,transform:"translateZ(0)"}};function wA(e){for(let t in e)return!1;return!0}function sT(e){return wA(e)||e.outerHeightStyle===0&&!e.overflowing}var CA=ue(function(t,r){let{onChange:o,maxRows:n,minRows:s=1,style:i,value:a,...l}=t,{current:c}=J(a!=null),u=J(null),f=ar(r,u),m=J(null),p=J(null),y=Ee(()=>{let R=u.current,P=p.current;if(!R||!P)return;let E=fi(R).getComputedStyle(R);if(E.width==="0px")return{outerHeightStyle:0,overflowing:!1};P.style.width=E.width,P.value=R.value||t.placeholder||"x",P.value.slice(-1)===`+`&&(P.value+=" ");let A=E.boxSizing,I=Fp(E.paddingBottom)+Fp(E.paddingTop),N=Fp(E.borderBottomWidth)+Fp(E.borderTopWidth),D=P.scrollHeight;P.value="x";let w=P.scrollHeight,$=D;s&&($=Math.max(Number(s)*w,$)),n&&($=Math.min(Number(n)*w,$)),$=Math.max($,w);let h=$+(A==="border-box"?I+N:0),z=Math.abs($-D)<=1;return{outerHeightStyle:h,overflowing:z}},[n,s,t.placeholder]),x=eo(()=>{let R=u.current,P=y();if(!R||!P||sT(P))return!1;let O=P.outerHeightStyle;return m.current!=null&&m.current!==O}),T=Ee(()=>{let R=u.current,P=y();if(!R||!P||sT(P))return;let O=P.outerHeightStyle;m.current!==O&&(m.current=O,R.style.height=`${O}px`),R.style.overflow=P.overflowing?"hidden":""},[y]),S=J(-1);return at(()=>{let R=Da(T),P=u?.current;if(!P)return;let O=fi(P);O.addEventListener("resize",R);let E;return typeof ResizeObserver<"u"&&(E=new ResizeObserver(()=>{x()&&(E.unobserve(P),cancelAnimationFrame(S.current),T(),S.current=requestAnimationFrame(()=>{E.observe(P)}))}),E.observe(P)),()=>{R.clear(),cancelAnimationFrame(S.current),O.removeEventListener("resize",R),E&&E.disconnect()}},[y,T,x]),at(()=>{T()}),b(Ie,{children:[b("textarea",{value:a,onChange:R=>{c||T();let P=R.target,O=P.value.length,E=P.value.endsWith(`+`),A=P.selectionStart===O;E&&A&&P.setSelectionRange(O,O),o&&o(R)},ref:f,rows:s,style:i,...l}),b("textarea",{"aria-hidden":!0,className:t.className,readOnly:!0,ref:p,tabIndex:-1,style:{...SA.shadow,...i,paddingTop:0,paddingBottom:0}})]})}),lh=CA;function iT(e){return e!=null&&!(Array.isArray(e)&&e.length===0)}function aT(e,t=!1){return e&&(iT(e.value)&&e.value!==""||t&&iT(e.defaultValue)&&e.defaultValue!=="")}function lT(e){return we("MuiInputBase",e)}var EA=Ce("MuiInputBase",["root","formControl","focused","disabled","adornedStart","adornedEnd","error","sizeSmall","multiline","colorSecondary","fullWidth","hiddenLabel","readOnly","input","inputTypeSearch"]),_i=EA;var cT,ch="mui-auto-fill",Vp="mui-auto-fill-cancel",uh=(e,t)=>{let{ownerState:r}=e;return[t.root,r.formControl&&t.formControl,r.startAdornment&&t.adornedStart,r.endAdornment&&t.adornedEnd,r.error&&t.error,r.size==="small"&&t.sizeSmall,r.multiline&&t.multiline,r.color&&t[`color${Te(r.color)}`],r.fullWidth&&t.fullWidth,r.hiddenLabel&&t.hiddenLabel]},ph=(e,t)=>{let{ownerState:r}=e;return[t.input,r.type==="search"&&t.inputTypeSearch]},RA=e=>{let{classes:t,color:r,disabled:o,error:n,endAdornment:s,focused:i,formControl:a,fullWidth:l,hiddenLabel:c,multiline:u,readOnly:f,size:m,startAdornment:p,type:y}=e,x={root:["root",`color${Te(r)}`,o&&"disabled",n&&"error",l&&"fullWidth",i&&"focused",a&&"formControl",m&&m!=="medium"&&`size${Te(m)}`,u&&"multiline",p&&"adornedStart",s&&"adornedEnd",c&&"hiddenLabel",f&&"readOnly"],input:["input",o&&"disabled",y==="search"&&"inputTypeSearch",f&&"readOnly"]};return ke(x,lT,t)},fh=ne("div",{name:"MuiInputBase",slot:"Root",overridesResolver:uh})(ze(({theme:e})=>({...e.typography.body1,color:(e.vars||e).palette.text.primary,lineHeight:"1.4375em",boxSizing:"border-box",position:"relative",cursor:"text",display:"inline-flex",alignItems:"center",[`&.${_i.disabled}`]:{color:(e.vars||e).palette.text.disabled,cursor:"default"},variants:[{props:({ownerState:t})=>t.multiline,style:{padding:"4px 0 5px"}},{props:({ownerState:t,size:r})=>t.multiline&&r==="small",style:{paddingTop:1}},{props:({ownerState:t})=>t.fullWidth,style:{width:"100%"}}]}))),dh=ne("input",{name:"MuiInputBase",slot:"Input",overridesResolver:ph})(ze(({theme:e})=>{let t=e.palette.mode==="light",r={color:"currentColor",...e.vars?{opacity:e.vars.opacity.inputPlaceholder}:{opacity:t?.42:.5},...Lt(e,"opacity",{duration:e.transitions.duration.shorter})},o={opacity:"0 !important"},n=e.vars?{opacity:e.vars.opacity.inputPlaceholder}:{opacity:t?.42:.5};return{font:"inherit",letterSpacing:"inherit",color:"currentColor",padding:"4px 0 5px",border:0,boxSizing:"content-box",background:"none",height:"1.4375em",margin:0,WebkitTapHighlightColor:"transparent",display:"block",minWidth:0,width:"100%","&::-webkit-input-placeholder":r,"&::-moz-placeholder":r,"&::-ms-input-placeholder":r,"&:focus":{outline:0},"&:invalid":{boxShadow:"none"},"&::-webkit-search-decoration":{WebkitAppearance:"none"},[`label[data-shrink=false] + .${_i.formControl} &`]:{"&::-webkit-input-placeholder":o,"&::-moz-placeholder":o,"&::-ms-input-placeholder":o,"&:focus::-webkit-input-placeholder":n,"&:focus::-moz-placeholder":n,"&:focus::-ms-input-placeholder":n},[`&.${_i.disabled}`]:{opacity:1,WebkitTextFillColor:(e.vars||e).palette.text.disabled},variants:[{props:({ownerState:s})=>!s.disableInjectingGlobalStyles,style:{animationName:Vp,animationDuration:"10ms","&:-webkit-autofill":{animationDuration:"5000s",animationName:ch}}},{props:{size:"small"},style:{paddingTop:1}},{props:({ownerState:s})=>s.multiline,style:{height:"auto",resize:"none",padding:0,paddingTop:0}},{props:{type:"search"},style:{MozAppearance:"textfield"}}]}})),uT=ql({[`@keyframes ${ch}`]:{from:{animationName:ch}},[`@keyframes ${Vp}`]:{from:{animationName:Vp}}}),kA=ue(function(t,r){let o=Me({props:t,name:"MuiInputBase"}),{"aria-describedby":n,"aria-label":s,autoComplete:i,autoFocus:a,className:l,color:c,defaultValue:u,disabled:f,disableInjectingGlobalStyles:m,endAdornment:p,error:y,fullWidth:x=!1,id:T,inputComponent:S="input",inputProps:v,inputRef:R,margin:P,maxRows:O,minRows:E,multiline:A=!1,name:I,onBlur:N,onChange:D,onClick:w,onFocus:$,onKeyDown:h,onKeyUp:z,placeholder:k,readOnly:j,renderSuffix:B,rows:W,size:H,slotProps:ee={},slots:G={},startAdornment:F,type:V="text",value:te,...oe}=o,Y={...v,...ee.input},fe=Y.value!=null?Y.value:te,{current:se}=J(fe!=null),be=J(),Pe=Ee(Oe=>{},[]),We=rn(be,R,Y.ref,Pe),[qe,He]=ie(!1),[Ye,$e]=f0({props:o,states:["color","disabled","error","hiddenLabel","size","required","filled"]});Ye.focused=$e?$e.focused:qe,ce(()=>{!$e&&f&&qe&&(He(!1),N&&N())},[$e,f,qe,N]);let Ge=$e&&$e.onFilled,yt=$e&&$e.onEmpty,Ot=Ee(Oe=>{aT(Oe)?Ge&&Ge():yt&&yt()},[Ge,yt]);La(()=>{se&&Ot({value:fe})},[fe,Ot,se]),La(()=>{if(!a)return;let Oe=be.current;if(!Oe)return;let Pt=kp(Oe),mt=Rp(Pt),bt=mt==null||mt===Pt.body||mt===Pt.documentElement;Oe===mt?$e&&$e.onFocus?$e.onFocus():He(!0):bt&&Oe.focus()},[a]);let Xe=Oe=>{$&&$(Oe),Y.onFocus&&Y.onFocus(Oe),$e&&$e.onFocus?$e.onFocus(Oe):He(!0)},Ve=Oe=>{N&&N(Oe),Y.onBlur&&Y.onBlur(Oe),$e&&$e.onBlur?$e.onBlur(Oe):He(!1)},Tt=(Oe,...Pt)=>{if(!se){let mt=Oe.target||be.current;if(mt==null)throw new Error(Nr(1));Ot({value:mt.value})}Y.onChange&&Y.onChange(Oe,...Pt),D&&D(Oe,...Pt)};ce(()=>{Ot(be.current)},[]);let dt=Oe=>{be.current&&Oe.currentTarget===Oe.target&&be.current.focus(),w&&w(Oe)},Vt=S,me=Y;A&&Vt==="input"&&(W?me={type:void 0,minRows:W,maxRows:W,...me}:me={type:void 0,maxRows:O,minRows:E,...me},Vt=lh);let re=Oe=>{Ot(Oe.animationName===Vp?be.current:{value:"x"})};ce(()=>{$e&&$e.setAdornedStart(!!F)},[$e,F]);let xe={...o,color:Ye.color||"primary",disabled:Ye.disabled,endAdornment:p,error:Ye.error,focused:Ye.focused,formControl:$e,fullWidth:x,hiddenLabel:Ye.hiddenLabel,multiline:A,size:Ye.size,startAdornment:F,type:V},_e=RA(xe),je=G.root||fh,et=ee.root||{},gt=G.input||dh;return b(Ie,{children:[!m&&typeof uT=="function"&&(cT||(cT=b(uT,{}))),b(je,{...et,ref:r,onClick:dt,...oe,...!Na(je)&&{ownerState:{...xe,...et.ownerState}},className:he(_e.root,et.className,l,j&&"MuiInputBase-readOnly"),children:[F,b(Yl.Provider,{value:null,children:b(gt,{"aria-invalid":Ye.error,"aria-describedby":n,"aria-label":s,autoComplete:i,autoFocus:a,defaultValue:u,disabled:Ye.disabled,id:T,onAnimationStart:re,name:I,placeholder:k,readOnly:j,required:Ye.required,rows:W,value:fe,onKeyDown:h,onKeyUp:z,type:V,...me,...!Na(gt)&&{as:Vt,ownerState:{...xe,...me.ownerState}},ref:We,className:he(_e.input,me.className,j&&"MuiInputBase-readOnly"),onBlur:Ve,onChange:Tt,onFocus:Xe})}),p,B?B({...Ye,startAdornment:F}):null]})]})}),mh=kA;function pT(e){return we("MuiInput",e)}var OA={..._i,...Ce("MuiInput",["root","underline","input"])},Wa=OA;function Up({props:e,name:t}){return vs({props:e,name:t,defaultTheme:ws,themeId:Xt})}K();K();function hh({theme:e,...t}){let r=Xt in e?e[Xt]:void 0;return b(Ca,{...t,themeId:r?Xt:void 0,theme:r||e})}var uc={attribute:"data-mui-color-scheme",colorSchemeStorageKey:"mui-color-scheme",defaultLightColorScheme:"light",defaultDarkColorScheme:"dark",modeStorageKey:"mui-mode"};var{CssVarsProvider:AA,useColorScheme:fT,getInitColorSchemeScript:LJ}=ap({themeId:Xt,theme:()=>kn({cssVariables:!0}),colorSchemeStorageKey:uc.colorSchemeStorageKey,modeStorageKey:uc.modeStorageKey,defaultColorScheme:{light:uc.defaultLightColorScheme,dark:uc.defaultDarkColorScheme},resolveTheme:e=>{let t={...e,typography:Hl(e.palette,e.typography)};return t.unstable_sx=function(o){return Qr({sx:o,theme:this})},t}});var dT=AA;function Zp({theme:e,...t}){let r=Le(()=>{if(typeof e=="function")return e;let o=Xt in e?e[Xt]:e;return"colorSchemes"in o?null:"vars"in o?e:{...e,vars:null}},[e]);return r?b(hh,{theme:r,...t}):b(dT,{theme:e,...t})}var MA=dp({createStyledComponent:ne("div",{name:"MuiGrid",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,r.container&&t.container]}}),componentName:"MuiGrid",useThemeProps:e=>Me({props:e,name:"MuiGrid"}),useTheme:ir}),Ar=MA;var $A=cp({createStyledComponent:ne("div",{name:"MuiContainer",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,t[`maxWidth${Te(String(r.maxWidth))}`],r.fixed&&t.fixed,r.disableGutters&&t.disableGutters]}}),useThemeProps:e=>Me({props:e,name:"MuiContainer"})}),yh=$A;K();var mT=kt(b("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-2 15-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8z"}),"CheckCircle");var hT=kt(b("path",{d:"M12 6v3l4-4-4-4v3c-4.42 0-8 3.58-8 8 0 1.57.46 3.03 1.24 4.26L6.7 14.8c-.45-.83-.7-1.79-.7-2.8 0-3.31 2.69-6 6-6m6.76 1.74L17.3 9.2c.44.84.7 1.79.7 2.8 0 3.31-2.69 6-6 6v-3l-4 4 4 4v-3c4.42 0 8-3.58 8-8 0-1.57-.46-3.03-1.24-4.26"}),"Autorenew");var yT=kt(b("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m1 15h-2v-2h2zm0-4h-2V7h2z"}),"Error");var No=$c(Pd());K();function gT(e){return we("MuiPaper",e)}var MQ=Ce("MuiPaper",["root","rounded","outlined","elevation","elevation0","elevation1","elevation2","elevation3","elevation4","elevation5","elevation6","elevation7","elevation8","elevation9","elevation10","elevation11","elevation12","elevation13","elevation14","elevation15","elevation16","elevation17","elevation18","elevation19","elevation20","elevation21","elevation22","elevation23","elevation24"]);var IA=e=>{let{square:t,elevation:r,variant:o,classes:n}=e,s={root:["root",o,!t&&"rounded",o==="elevation"&&`elevation${r}`]};return ke(s,gT,n)},NA=ne("div",{name:"MuiPaper",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,t[r.variant],!r.square&&t.rounded,r.variant==="elevation"&&t[`elevation${r.elevation}`]]}})(ze(({theme:e})=>({backgroundColor:(e.vars||e).palette.background.paper,color:(e.vars||e).palette.text.primary,...Lt(e,"box-shadow"),variants:[{props:({ownerState:t})=>!t.square,style:{borderRadius:(e.vars||e).shape.borderRadius}},{props:{variant:"outlined"},style:{border:`1px solid ${(e.vars||e).palette.divider}`}},{props:{variant:"elevation"},style:{boxShadow:"var(--Paper-shadow)",backgroundImage:"var(--Paper-overlay)"}}]}))),zA=ue(function(t,r){let o=Me({props:t,name:"MuiPaper"}),n=ir(),{className:s,component:i="div",elevation:a=1,square:l=!1,variant:c="elevation",...u}=o,f={...o,component:i,elevation:a,square:l,variant:c},m=IA(f);return b(NA,{as:i,ownerState:f,className:he(m.root,s),ref:r,...u,style:{...c==="elevation"&&{"--Paper-shadow":(n.vars||n).shadows[a],...n.vars&&{"--Paper-overlay":n.vars.overlays?.[a]},...!n.vars&&n.palette.mode==="dark"&&{"--Paper-overlay":`linear-gradient(${Ta("#fff",Ma(a))}, ${Ta("#fff",Ma(a))})`}},...u.style}})}),Si=zA;K();function bT(e){return we("MuiAlert",e)}var DA=Ce("MuiAlert",["root","action","icon","message","filled","colorSuccess","colorInfo","colorWarning","colorError","outlined","standard"]),gh=DA;K();K();function xT(e){return we("MuiCircularProgress",e)}var QQ=Ce("MuiCircularProgress",["root","determinate","indeterminate","colorPrimary","colorSecondary","svg","track","circle","circleDisableShrink"]);var ln=44;var bh=Cn`+  0% {+    transform: rotate(0deg);+  }++  100% {+    transform: rotate(360deg);+  }+`,xh=Cn`+  0% {+    stroke-dasharray: 1px, 200px;+    stroke-dashoffset: 0;+  }++  50% {+    stroke-dasharray: 100px, 200px;+    stroke-dashoffset: -15px;+  }++  100% {+    stroke-dasharray: 1px, 200px;+    stroke-dashoffset: -126px;+  }+`,BA=typeof bh!="string"?wn`+        animation: ${bh} 1.4s linear infinite;+      `:null,LA=typeof xh!="string"?wn`+        animation: ${xh} 1.4s ease-in-out infinite;+      `:null,jA=e=>{let{classes:t,variant:r,color:o,disableShrink:n}=e,s={root:["root",r,`color${Te(o)}`],svg:["svg"],track:["track"],circle:["circle",n&&"circleDisableShrink"]};return ke(s,xT,t)},FA=ne("span",{name:"MuiCircularProgress",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,t[r.variant],t[`color${Te(r.color)}`]]}})(ze(({theme:e})=>{let t=Cp(e,{animation:"none"});return{display:"inline-block",variants:[{props:{variant:"determinate"},style:{...Lt(e,"transform")}},{props:{variant:"indeterminate"},style:BA||{animation:`${bh} 1.4s linear infinite`}},...t?[{props:{variant:"indeterminate"},style:t}]:[],...Object.entries(e.palette).filter(sr()).map(([r])=>({props:{color:r},style:{color:(e.vars||e).palette[r].main}}))]}})),VA=ne("svg",{name:"MuiCircularProgress",slot:"Svg"})({display:"block"}),UA=ne("circle",{name:"MuiCircularProgress",slot:"Circle",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.circle,r.disableShrink&&t.circleDisableShrink]}})(ze(({theme:e})=>{let t=Cp(e,{animation:"none"});return{stroke:"currentColor",variants:[{props:{variant:"determinate"},style:{...Lt(e,"stroke-dashoffset")}},{props:{variant:"indeterminate"},style:{strokeDasharray:"80px, 200px",strokeDashoffset:0}},{props:({ownerState:r})=>r.variant==="indeterminate"&&!r.disableShrink,style:LA||{animation:`${xh} 1.4s ease-in-out infinite`}},...t?[{props:({ownerState:r})=>r.variant==="indeterminate"&&!r.disableShrink,style:t}]:[]]}})),ZA=ne("circle",{name:"MuiCircularProgress",slot:"Track"})(ze(({theme:e})=>({stroke:"currentColor",opacity:(e.vars||e).palette.action.activatedOpacity}))),WA=ue(function(t,r){let o=Me({props:t,name:"MuiCircularProgress"}),{className:n,color:s="primary",disableShrink:i=!1,enableTrackSlot:a=!1,min:l,max:c,size:u=40,style:f,thickness:m=3.6,value:p=o.min??0,variant:y="indeterminate",...x}=o,T=l??0,S=c??100,v={...o,color:s,disableShrink:i,size:u,thickness:m,value:p,variant:y,enableTrackSlot:a},R=jA(v),P={},O={},E={};if(y==="determinate"){let A=2*Math.PI*((ln-m)/2),I=S-T;P.strokeDasharray=A.toFixed(3),P.strokeDashoffset=I>0?`${((S-p)/I*A).toFixed(3)}px`:`${A.toFixed(3)}px`,O.transform="rotate(-90deg)",E["aria-valuenow"]=p,E["aria-valuemin"]=T,E["aria-valuemax"]=S}return b(FA,{className:he(R.root,n),style:{width:u,height:u,...O,...f},ownerState:v,ref:r,role:"progressbar",...E,...x,children:b(VA,{className:R.svg,ownerState:v,viewBox:`${ln/2} ${ln/2} ${ln} ${ln}`,children:[a?b(ZA,{className:R.track,ownerState:v,cx:ln,cy:ln,r:(ln-m)/2,fill:"none",strokeWidth:m,"aria-hidden":"true"}):null,b(UA,{className:R.circle,style:P,ownerState:v,cx:ln,cy:ln,r:(ln-m)/2,fill:"none",strokeWidth:m})]})})}),pc=WA;function vT(e){return we("MuiIconButton",e)}var HA=Ce("MuiIconButton",["root","disabled","colorInherit","colorPrimary","colorSecondary","colorError","colorInfo","colorSuccess","colorWarning","edgeStart","edgeEnd","sizeSmall","sizeMedium","sizeLarge","loading","loadingIndicator","loadingWrapper"]),vh=HA;var GA=e=>{let{classes:t,disabled:r,color:o,edge:n,size:s,loading:i}=e,a={root:["root",i&&"loading",r&&"disabled",o!=="default"&&`color${Te(o)}`,n&&`edge${Te(n)}`,`size${Te(s)}`],loadingIndicator:["loadingIndicator"],loadingWrapper:["loadingWrapper"]};return ke(a,vT,t)},KA=ne(on,{name:"MuiIconButton",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,r.loading&&t.loading,r.color!=="default"&&t[`color${Te(r.color)}`],r.edge&&t[`edge${Te(r.edge)}`],t[`size${Te(r.size)}`]]}})(ze(({theme:e})=>({textAlign:"center",flex:"0 0 auto",fontSize:e.typography.pxToRem(24),padding:8,borderRadius:"50%",color:(e.vars||e).palette.action.active,...Lt(e,"background-color",{duration:e.transitions.duration.shortest}),variants:[{props:t=>!t.disableRipple,style:{"--IconButton-hoverBg":e.alpha((e.vars||e).palette.action.active,(e.vars||e).palette.action.hoverOpacity),"&:hover":{backgroundColor:"var(--IconButton-hoverBg)","@media (hover: none)":{backgroundColor:"transparent"}}}},{props:{edge:"start"},style:{marginLeft:-12}},{props:{edge:"start",size:"small"},style:{marginLeft:-3}},{props:{edge:"end"},style:{marginRight:-12}},{props:{edge:"end",size:"small"},style:{marginRight:-3}}]})),ze(({theme:e})=>({variants:[{props:{color:"inherit"},style:{color:"inherit"}},...Object.entries(e.palette).filter(sr()).map(([t])=>({props:{color:t},style:{color:(e.vars||e).palette[t].main,"--IconButton-hoverBg":e.alpha((e.vars||e).palette[t].main,(e.vars||e).palette.action.hoverOpacity)}})),{props:{size:"small"},style:{padding:5,fontSize:e.typography.pxToRem(18)}},{props:{size:"large"},style:{padding:12,fontSize:e.typography.pxToRem(28)}}],[`&.${vh.disabled}`]:{backgroundColor:"transparent",color:(e.vars||e).palette.action.disabled},[`&.${vh.loading}`]:{color:"transparent"}}))),qA=ne("span",{name:"MuiIconButton",slot:"LoadingIndicator"})(({theme:e})=>({display:"none",position:"absolute",visibility:"visible",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:(e.vars||e).palette.action.disabled,variants:[{props:{loading:!0},style:{display:"flex"}}]})),YA=ue(function(t,r){let o=Me({props:t,name:"MuiIconButton"}),{edge:n=!1,children:s,className:i,color:a="default",disabled:l=!1,disableFocusRipple:c=!1,size:u="medium",id:f,loading:m=null,loadingIndicator:p,...y}=o,x=mi(f),T=p??b(pc,{"aria-labelledby":x,color:"inherit",size:16}),S={...o,edge:n,color:a,disabled:l,disableFocusRipple:c,loading:m,loadingIndicator:T,size:u},v=GA(S);return b(KA,{id:m?x:f,className:he(v.root,i),centerRipple:!0,internalNativeButton:!0,focusRipple:!c,disabled:l||m,ref:r,...y,ownerState:S,children:[typeof m=="boolean"&&b("span",{className:v.loadingWrapper,style:{display:"contents"},children:b(qA,{className:v.loadingIndicator,ownerState:S,children:m&&T})}),s]})}),Ha=YA;var TT=kt(b("path",{d:"M20,12A8,8 0 0,1 12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4C12.76,4 13.5,4.11 14.2, 4.31L15.77,2.74C14.61,2.26 13.34,2 12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0, 0 22,12M7.91,10.08L6.5,11.5L11,16L21,6L19.59,4.58L11,13.17L7.91,10.08Z"}),"SuccessOutlined");var PT=kt(b("path",{d:"M12 5.99L19.53 19H4.47L12 5.99M12 2L1 21h22L12 2zm1 14h-2v2h2v-2zm0-6h-2v4h2v-4z"}),"ReportProblemOutlined");var _T=kt(b("path",{d:"M11 15h2v2h-2zm0-8h2v6h-2zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"}),"ErrorOutline");var ST=kt(b("path",{d:"M11,9H13V7H11M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20, 12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10, 10 0 0,0 12,2M11,17H13V11H11V17Z"}),"InfoOutlined");var wT=kt(b("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}),"Close");var XA=e=>{let{variant:t,color:r,severity:o,classes:n}=e,s={root:["root",`color${Te(r||o)}`,`${t}`],icon:["icon"],message:["message"],action:["action"]};return ke(s,bT,n)},JA=ne(Si,{name:"MuiAlert",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,t[r.variant]]}})(ze(({theme:e})=>{let t=e.palette.mode==="light"?e.darken:e.lighten,r=e.palette.mode==="light"?e.lighten:e.darken;return{...e.typography.body2,backgroundColor:"transparent",display:"flex",padding:"6px 16px",variants:[...Object.entries(e.palette).filter(sr(["light"])).map(([o])=>({props:{colorSeverity:o,variant:"standard"},style:{color:e.vars?e.vars.palette.Alert[`${o}Color`]:t(e.palette[o].light,.6),backgroundColor:e.vars?e.vars.palette.Alert[`${o}StandardBg`]:r(e.palette[o].light,.9),[`& .${gh.icon}`]:e.vars?{color:e.vars.palette.Alert[`${o}IconColor`]}:{color:e.palette[o].main}}})),...Object.entries(e.palette).filter(sr(["light"])).map(([o])=>({props:{colorSeverity:o,variant:"outlined"},style:{color:e.vars?e.vars.palette.Alert[`${o}Color`]:t(e.palette[o].light,.6),border:`1px solid ${(e.vars||e).palette[o].light}`,[`& .${gh.icon}`]:e.vars?{color:e.vars.palette.Alert[`${o}IconColor`]}:{color:e.palette[o].main}}})),...Object.entries(e.palette).filter(sr(["dark"])).map(([o])=>({props:{colorSeverity:o,variant:"filled"},style:{...e.focusVisible&&Oa(`0 0 0 4px ${(e.vars||e).palette.background.default}`),fontWeight:e.typography.fontWeightMedium,...e.vars?{color:e.vars.palette.Alert[`${o}FilledColor`],backgroundColor:e.vars.palette.Alert[`${o}FilledBg`]}:{backgroundColor:e.palette.mode==="dark"?e.palette[o].dark:e.palette[o].main,color:e.palette.getContrastText(e.palette[o].main)}}}))]}})),QA=ne("div",{name:"MuiAlert",slot:"Icon"})({marginRight:12,padding:"7px 0",display:"flex",fontSize:22,opacity:.9}),eM=ne("div",{name:"MuiAlert",slot:"Message"})({padding:"8px 0",minWidth:0,overflow:"auto"}),tM=ne("div",{name:"MuiAlert",slot:"Action"})({display:"flex",alignItems:"flex-start",padding:"4px 0 0 16px",marginLeft:"auto",marginRight:-8}),CT={success:b(TT,{fontSize:"inherit"}),warning:b(PT,{fontSize:"inherit"}),error:b(_T,{fontSize:"inherit"}),info:b(ST,{fontSize:"inherit"})},rM=ue(function(t,r){let o=Me({props:t,name:"MuiAlert"}),{action:n,children:s,className:i,closeText:a="Close",color:l,icon:c,iconMapping:u=CT,onClose:f,role:m="alert",severity:p="success",slotProps:y={},slots:x={},variant:T="standard",...S}=o,v={...o,color:l,severity:p,variant:T,colorSeverity:l||p},R=XA(v),P={slots:x,slotProps:y},[O,E]=ot("root",{ref:r,shouldForwardComponentProp:!0,className:he(R.root,i),elementType:JA,externalForwardedProps:{...P,...S},ownerState:v,additionalProps:{role:m,elevation:0}}),[A,I]=ot("icon",{className:R.icon,elementType:QA,externalForwardedProps:P,ownerState:v}),[N,D]=ot("message",{className:R.message,elementType:eM,externalForwardedProps:P,ownerState:v}),[w,$]=ot("action",{className:R.action,elementType:tM,externalForwardedProps:P,ownerState:v}),[h,z]=ot("closeButton",{elementType:Ha,externalForwardedProps:P,ownerState:v}),[k,j]=ot("closeIcon",{elementType:wT,externalForwardedProps:P,ownerState:v});return b(O,{...E,children:[c!==!1?b(A,{...I,children:c||u[p]||CT[p]}):null,b(N,{...D,children:s}),n!=null?b(w,{...$,children:n}):null,n==null&&f?b(w,{...$,children:b(h,{size:"small","aria-label":a,title:a,color:"inherit",onClick:f,...z,children:b(k,{fontSize:"small",...j})})}):null]})}),Th=rM;K();function ET(e){return we("MuiAppBar",e)}var vte=Ce("MuiAppBar",["root","positionFixed","positionAbsolute","positionSticky","positionStatic","positionRelative","colorDefault","colorPrimary","colorSecondary","colorInherit","colorTransparent","colorError","colorInfo","colorSuccess","colorWarning"]);var oM=e=>{let{color:t,position:r,classes:o}=e,n={root:["root",`color${Te(t)}`,`position${Te(r)}`]};return ke(n,ET,o)},RT=(e,t)=>e?`${e.replace(")","")}, ${t})`:t,nM=ne(Si,{name:"MuiAppBar",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,t[`position${Te(r.position)}`],t[`color${Te(r.color)}`]]}})(ze(({theme:e})=>({display:"flex",flexDirection:"column",width:"100%",boxSizing:"border-box",flexShrink:0,variants:[{props:{position:"fixed"},style:{position:"fixed",zIndex:(e.vars||e).zIndex.appBar,top:0,left:"auto",right:0,"@media print":{position:"absolute"}}},{props:{position:"absolute"},style:{position:"absolute",zIndex:(e.vars||e).zIndex.appBar,top:0,left:"auto",right:0}},{props:{position:"sticky"},style:{position:"sticky",zIndex:(e.vars||e).zIndex.appBar,top:0,left:"auto",right:0}},{props:{position:"static"},style:{position:"static"}},{props:{position:"relative"},style:{position:"relative"}},{props:{color:"inherit"},style:{"--AppBar-color":"inherit",color:"var(--AppBar-color)"}},{props:{color:"default"},style:{"--AppBar-background":e.vars?e.vars.palette.AppBar.defaultBg:e.palette.grey[100],"--AppBar-color":e.vars?e.vars.palette.text.primary:e.palette.getContrastText(e.palette.grey[100]),...e.applyStyles("dark",{"--AppBar-background":e.vars?e.vars.palette.AppBar.defaultBg:e.palette.grey[900],"--AppBar-color":e.vars?e.vars.palette.text.primary:e.palette.getContrastText(e.palette.grey[900])})}},...Object.entries(e.palette).filter(sr(["contrastText"])).map(([t])=>({props:{color:t},style:{"--AppBar-background":(e.vars??e).palette[t].main,"--AppBar-color":(e.vars??e).palette[t].contrastText,...e.focusVisible&&Oa(`0 0 0 4px ${(e.vars||e).palette.background.default}`)}})),{props:t=>t.enableColorOnDark===!0&&!["inherit","transparent"].includes(t.color),style:{backgroundColor:"var(--AppBar-background)",color:"var(--AppBar-color)"}},{props:t=>t.enableColorOnDark===!1&&!["inherit","transparent"].includes(t.color),style:{backgroundColor:"var(--AppBar-background)",color:"var(--AppBar-color)",...e.applyStyles("dark",{backgroundColor:e.vars?RT(e.vars.palette.AppBar.darkBg,"var(--AppBar-background)"):null,color:e.vars?RT(e.vars.palette.AppBar.darkColor,"var(--AppBar-color)"):null})}},{props:{color:"transparent"},style:{"--AppBar-background":"transparent","--AppBar-color":"inherit",backgroundColor:"var(--AppBar-background)",color:"var(--AppBar-color)",...e.applyStyles("dark",{backgroundImage:"none"})}}]}))),sM=ue(function(t,r){let o=Me({props:t,name:"MuiAppBar"}),{className:n,color:s="primary",enableColorOnDark:i=!1,position:a="fixed",...l}=o,c={...o,color:s,position:a,enableColorOnDark:i},u=oM(c);return b(nM,{square:!0,component:"header",ownerState:c,elevation:4,className:he(u.root,n,a==="fixed"&&"mui-fixed"),ref:r,...l})}),Ph=sM;function wi(e,t){if(!e||!t)return!1;if(e.contains(t))return!0;let r=t.getRootNode?.();if(r&&r instanceof ShadowRoot){let o=t;for(;o;){if(e===o)return!0;o=o.parentNode??o.host??null}}return!1}var iM=Ce("MuiBox",["root"]),kT=iM;var aM=kn(),lM=Dl({themeId:Xt,defaultTheme:aM,defaultClassName:kT.root,generateClassName:ba.generate}),Xn=lM;K();function OT(e){return we("MuiButton",e)}var cM=Ce("MuiButton",["root","text","outlined","contained","disableElevation","focusVisible","disabled","colorInherit","colorPrimary","colorSecondary","colorSuccess","colorError","colorInfo","colorWarning","sizeMedium","sizeSmall","sizeLarge","fullWidth","startIcon","endIcon","icon","loading","loadingWrapper","loadingIconPlaceholder","loadingIndicator","loadingPositionCenter","loadingPositionStart","loadingPositionEnd"]),Ms=cM;K();var uM=Je({}),AT=uM;K();var pM=Je(void 0),MT=pM;var fM=e=>{let{color:t,disableElevation:r,fullWidth:o,size:n,variant:s,loading:i,loadingPosition:a,classes:l}=e,c={root:["root",i&&"loading",s,`size${Te(n)}`,`color${Te(t)}`,r&&"disableElevation",o&&"fullWidth",i&&`loadingPosition${Te(a)}`],startIcon:["icon","startIcon"],endIcon:["icon","endIcon"],loadingIndicator:["loadingIndicator"],loadingWrapper:["loadingWrapper"]},u=ke(c,OT,l);return{...l,...u}},IT=[{props:{size:"small"},style:{"& > *:nth-of-type(1)":{fontSize:18}}},{props:{size:"medium"},style:{"& > *:nth-of-type(1)":{fontSize:20}}},{props:{size:"large"},style:{"& > *:nth-of-type(1)":{fontSize:22}}}],dM=ne(on,{shouldForwardProp:e=>bs(e)||e==="classes",name:"MuiButton",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,t[r.variant],t[`size${Te(r.size)}`],r.color==="inherit"&&t.colorInherit,r.disableElevation&&t.disableElevation,r.fullWidth&&t.fullWidth,r.loading&&t.loading]}})(ze(({theme:e})=>{let t=e.palette.mode==="light"?e.palette.grey[300]:e.palette.grey[800],r=e.palette.mode==="light"?e.palette.grey.A100:e.palette.grey[700];return{...e.typography.button,minWidth:64,padding:"6px 16px",border:0,borderRadius:(e.vars||e).shape.borderRadius,...Lt(e,["background-color","box-shadow","border-color","color"],{duration:e.transitions.duration.short}),"&:hover":{textDecoration:"none"},[`&.${Ms.disabled}`]:{color:(e.vars||e).palette.action.disabled},variants:[{props:{variant:"contained"},style:{color:"var(--variant-containedColor)",backgroundColor:"var(--variant-containedBg)",boxShadow:(e.vars||e).shadows[2],"&:hover":{boxShadow:(e.vars||e).shadows[4],"@media (hover: none)":{boxShadow:(e.vars||e).shadows[2]}},"&:active":{boxShadow:(e.vars||e).shadows[8]},[`&.${Ms.focusVisible}`]:{...e.focusVisible,boxShadow:e.focusVisible?.boxShadow?`${(e.vars||e).shadows[6]}, ${e.focusVisible.boxShadow}`:(e.vars||e).shadows[6]},[`&.${Ms.disabled}`]:{color:(e.vars||e).palette.action.disabled,boxShadow:(e.vars||e).shadows[0],backgroundColor:(e.vars||e).palette.action.disabledBackground}}},{props:{variant:"outlined"},style:{padding:"5px 15px",border:"1px solid currentColor",borderColor:"var(--variant-outlinedBorder, currentColor)",backgroundColor:"var(--variant-outlinedBg)",color:"var(--variant-outlinedColor)",[`&.${Ms.disabled}`]:{border:`1px solid ${(e.vars||e).palette.action.disabledBackground}`}}},{props:{variant:"text"},style:{padding:"6px 8px",color:"var(--variant-textColor)",backgroundColor:"var(--variant-textBg)"}},...Object.entries(e.palette).filter(sr()).map(([o])=>({props:{color:o},style:{"--variant-textColor":(e.vars||e).palette[o].main,"--variant-outlinedColor":(e.vars||e).palette[o].main,"--variant-outlinedBorder":e.alpha((e.vars||e).palette[o].main,.5),"--variant-containedColor":(e.vars||e).palette[o].contrastText,"--variant-containedBg":(e.vars||e).palette[o].main,"@media (hover: hover)":{"&:hover":{"--variant-containedBg":(e.vars||e).palette[o].dark,"--variant-textBg":e.alpha((e.vars||e).palette[o].main,(e.vars||e).palette.action.hoverOpacity),"--variant-outlinedBorder":(e.vars||e).palette[o].main,"--variant-outlinedBg":e.alpha((e.vars||e).palette[o].main,(e.vars||e).palette.action.hoverOpacity)}}}})),{props:{color:"inherit"},style:{color:"inherit",borderColor:"currentColor","--variant-containedBg":e.vars?e.vars.palette.Button.inheritContainedBg:t,"@media (hover: hover)":{"&:hover":{"--variant-containedBg":e.vars?e.vars.palette.Button.inheritContainedHoverBg:r,"--variant-textBg":e.alpha((e.vars||e).palette.text.primary,(e.vars||e).palette.action.hoverOpacity),"--variant-outlinedBg":e.alpha((e.vars||e).palette.text.primary,(e.vars||e).palette.action.hoverOpacity)}}}},{props:{size:"small",variant:"text"},style:{padding:"4px 5px",fontSize:e.typography.pxToRem(13)}},{props:{size:"large",variant:"text"},style:{padding:"8px 11px",fontSize:e.typography.pxToRem(15)}},{props:{size:"small",variant:"outlined"},style:{padding:"3px 9px",fontSize:e.typography.pxToRem(13)}},{props:{size:"large",variant:"outlined"},style:{padding:"7px 21px",fontSize:e.typography.pxToRem(15)}},{props:{size:"small",variant:"contained"},style:{padding:"4px 10px",fontSize:e.typography.pxToRem(13)}},{props:{size:"large",variant:"contained"},style:{padding:"8px 22px",fontSize:e.typography.pxToRem(15)}},{props:{disableElevation:!0},style:{boxShadow:"none","&:hover":{boxShadow:"none"},[`&.${Ms.focusVisible}`]:{boxShadow:e.focusVisible?.boxShadow??"none"},"&:active":{boxShadow:"none"},[`&.${Ms.disabled}`]:{boxShadow:"none"}}},{props:{fullWidth:!0},style:{width:"100%"}},{props:{loading:!0,loadingPosition:"center"},style:{...Lt(e,["background-color","box-shadow","border-color"],{duration:e.transitions.duration.short}),[`&.${Ms.loading}`]:{color:"transparent"}}}]}})),mM=ne("span",{name:"MuiButton",slot:"StartIcon",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.startIcon,r.loading&&t.startIconLoadingStart]}})(({theme:e})=>({display:"inherit",alignItems:"center",marginRight:8,marginLeft:-4,"&::before":{content:'"\\200b"',width:0,overflow:"hidden"},variants:[{props:{size:"small"},style:{marginLeft:-2}},{props:{loadingPosition:"start",loading:!0},style:{...Lt(e,["opacity"],{duration:e.transitions.duration.short}),opacity:0}},{props:{loadingPosition:"start",loading:!0,fullWidth:!0},style:{marginRight:-8}},...IT]})),hM=ne("span",{name:"MuiButton",slot:"EndIcon",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.endIcon,r.loading&&t.endIconLoadingEnd]}})(({theme:e})=>({display:"inherit",marginRight:-4,marginLeft:8,variants:[{props:{size:"small"},style:{marginRight:-2}},{props:{loadingPosition:"end",loading:!0},style:{...Lt(e,["opacity"],{duration:e.transitions.duration.short}),opacity:0}},{props:{loadingPosition:"end",loading:!0,fullWidth:!0},style:{marginLeft:-8}},...IT]})),yM=ne("span",{name:"MuiButton",slot:"LoadingIndicator"})(({theme:e})=>({display:"none",position:"absolute",visibility:"visible",variants:[{props:{loading:!0},style:{display:"flex"}},{props:{loadingPosition:"start"},style:{left:14}},{props:{loadingPosition:"start",size:"small"},style:{left:10}},{props:{variant:"text",loadingPosition:"start"},style:{left:6}},{props:{loadingPosition:"center"},style:{left:"50%",transform:"translate(-50%)",color:(e.vars||e).palette.action.disabled}},{props:{loadingPosition:"end"},style:{right:14}},{props:{loadingPosition:"end",size:"small"},style:{right:10}},{props:{variant:"text",loadingPosition:"end"},style:{right:6}},{props:{loadingPosition:"start",fullWidth:!0},style:{position:"relative",left:-10}},{props:{loadingPosition:"end",fullWidth:!0},style:{position:"relative",right:-10}}]})),$T=ne("span",{name:"MuiButton",slot:"LoadingIconPlaceholder"})({display:"inline-block",width:"1em",height:"1em"}),gM=ue(function(t,r){let o=Se(AT),n=Se(MT),s=tn(o,t),i=Me({props:s,name:"MuiButton"}),{children:a,color:l="primary",component:c="button",className:u,disabled:f=!1,disableElevation:m=!1,disableFocusRipple:p=!1,endIcon:y,focusVisibleClassName:x,fullWidth:T=!1,id:S,loading:v=null,loadingIndicator:R,loadingPosition:P="center",size:O="medium",startIcon:E,type:A,variant:I="text",...N}=i,D=mi(S),w=R??b(pc,{"aria-labelledby":D,color:"inherit",size:16}),$={...i,color:l,component:c,disabled:f,disableElevation:m,disableFocusRipple:p,fullWidth:T,loading:v,loadingIndicator:w,loadingPosition:P,size:O,type:A,variant:I},h=fM($),z=(E||v&&P==="start")&&b(mM,{className:h.startIcon,ownerState:$,children:E||b($T,{className:h.loadingIconPlaceholder,ownerState:$})}),k=(y||v&&P==="end")&&b(hM,{className:h.endIcon,ownerState:$,children:y||b($T,{className:h.loadingIconPlaceholder,ownerState:$})}),j=n||"",B=typeof v=="boolean"?b("span",{className:h.loadingWrapper,style:{display:"contents"},children:v&&b(yM,{className:h.loadingIndicator,ownerState:$,children:w})}):null,{root:W,...H}=h;return b(dM,{ownerState:$,className:he(o.className,h.root,u,j),component:c,disabled:f||v,focusRipple:!p,focusVisibleClassName:he(h.focusVisible,x),ref:r,internalNativeButton:!0,type:A,id:v?D:S,...N,classes:H,children:[z,P!=="end"&&B,a,P==="end"&&B,k]})}),_h=gM;K();function NT(e){return e.substring(2).toLowerCase()}function bM(e,t){return t.documentElement.clientWidth<e.clientX||t.documentElement.clientHeight<e.clientY}function Sh(e){let{children:t,disableReactTree:r=!1,mouseEvent:o="onClick",onClickAway:n,touchEvent:s="onTouchEnd"}=e,i=J(!1),a=J(null),l=J(!1),c=J(!1);ce(()=>(setTimeout(()=>{l.current=!0},0),()=>{l.current=!1}),[]);let u=ar(On(t),a),f=eo(y=>{let x=c.current;c.current=!1;let T=Dr(a.current);if(!l.current||!a.current||"clientX"in y&&bM(y,T))return;if(i.current){i.current=!1;return}let S;y.composedPath?S=y.composedPath().includes(a.current):S=!wi(T.documentElement,y.target)||wi(a.current,y.target),!S&&(r||!x)&&n(y)}),m=y=>x=>{c.current=!0;let T=t.props[y];T&&T(x)},p={ref:u};return s!==!1&&(p[s]=m(s)),ce(()=>{if(s!==!1){let y=NT(s),x=Dr(a.current),T=()=>{i.current=!0};return x.addEventListener(y,f),x.addEventListener("touchmove",T),()=>{x.removeEventListener(y,f),x.removeEventListener("touchmove",T)}}},[f,s]),o!==!1&&(p[o]=m(o)),ce(()=>{if(o!==!1){let y=NT(o),x=Dr(a.current);return x.addEventListener(y,f),()=>{x.removeEventListener(y,f)}}},[f,o]),vr(t,p)}K();var wh=typeof ql({})=="function",xM=(e,t)=>({WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale",boxSizing:"border-box",WebkitTextSizeAdjust:"100%",...t&&!e.vars&&{colorScheme:e.palette.mode}}),vM=e=>({color:(e.vars||e).palette.text.primary,...e.typography.body1,backgroundColor:(e.vars||e).palette.background.default,"@media print":{backgroundColor:(e.vars||e).palette.common.white}}),zT=(e,t=!1)=>{let r={};t&&e.colorSchemes&&typeof e.getColorSchemeSelector=="function"&&Object.entries(e.colorSchemes).forEach(([s,i])=>{let a=e.getColorSchemeSelector(s);a.startsWith("@")?r[a]={":root":{colorScheme:i.palette?.mode}}:r[a.replace(/\s*&/,"")]={colorScheme:i.palette?.mode}});let o={html:xM(e,t),"*, *::before, *::after":{boxSizing:"inherit"},"strong, b":{fontWeight:e.typography.fontWeightBold},body:{margin:0,...vM(e),"&::backdrop":{backgroundColor:(e.vars||e).palette.background.default}},...r},n=e.components?.MuiCssBaseline?.styleOverrides;return n&&(o=[o,n]),o},Wp="mui-ecs",TM=e=>{let t=zT(e,!1),r=Array.isArray(t)?t[0]:t;return!e.vars&&r&&(r.html[`:root:has(${Wp})`]={colorScheme:e.palette.mode}),e.colorSchemes&&Object.entries(e.colorSchemes).forEach(([o,n])=>{let s=e.getColorSchemeSelector(o);s.startsWith("@")?r[s]={[`:root:not(:has(.${Wp}))`]:{colorScheme:n.palette?.mode}}:r[s.replace(/\s*&/,"")]={[`&:not(:has(.${Wp}))`]:{colorScheme:n.palette?.mode}}}),t},PM=ql(wh?({theme:e,enableColorScheme:t})=>zT(e,t):({theme:e})=>TM(e));function _M(e){let t=Me({props:e,name:"MuiCssBaseline"}),{children:r,enableColorScheme:o=!1}=t;return b(Ie,{children:[wh&&b(PM,{enableColorScheme:o}),!wh&&!o&&b("span",{className:Wp,style:{display:"none"}}),r]})}var Hp=_M;var DT=wi;K();var SM=Ce("MuiInputLabel",["root","focused","disabled","error","required","asterisk","formControl","sizeSmall","shrink","animated","standard","filled","outlined"]),BT=SM;var wM=e=>{let{classes:t,disableUnderline:r}=e,n=ke({root:["root",!r&&"underline"],input:["input"]},pT,t);return{...t,...n}},CM=ne(fh,{shouldForwardProp:e=>bs(e)||e==="classes",name:"MuiInput",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[...uh(e,t),!r.disableUnderline&&t.underline]}})(ze(({theme:e})=>{let r=e.palette.mode==="light"?"rgba(0, 0, 0, 0.42)":"rgba(255, 255, 255, 0.7)";return e.vars&&(r=e.alpha(e.vars.palette.common.onBackground,e.vars.opacity.inputUnderline)),{position:"relative",variants:[{props:({ownerState:o})=>o.formControl,style:{[`label + &, .${BT.root} + &`]:{marginTop:16}}},{props:({ownerState:o})=>!o.disableUnderline,style:{"&::after":{left:0,bottom:0,content:'""',position:"absolute",right:0,transform:"scaleX(0)",...Lt(e,"transform",{duration:e.transitions.duration.shorter,easing:e.transitions.easing.easeOut}),pointerEvents:"none"},[`&.${Wa.focused}:after`]:{transform:"scaleX(1) translateX(0)"},[`&.${Wa.error}`]:{"&::before, &::after":{borderBottomColor:(e.vars||e).palette.error.main}},"&::before":{borderBottom:`1px solid ${r}`,left:0,bottom:0,content:'""',position:"absolute",right:0,...Lt(e,"border-bottom-color",{duration:e.transitions.duration.shorter}),pointerEvents:"none"},[`&:hover:not(.${Wa.disabled}, .${Wa.error}):before`]:{borderBottom:`2px solid ${(e.vars||e).palette.text.primary}`,"@media (hover: none)":{borderBottom:`1px solid ${r}`}},[`&.${Wa.disabled}:before`]:{borderBottomStyle:"dotted"}}},...Object.entries(e.palette).filter(sr()).map(([o])=>({props:{color:o,disableUnderline:!1},style:{"&::after":{borderBottom:`2px solid ${(e.vars||e).palette[o].main}`}}}))]}})),EM=ne(dh,{name:"MuiInput",slot:"Input",overridesResolver:ph})({}),LT=ue(function(t,r){let o=Me({props:t,name:"MuiInput"}),{disableUnderline:n=!1,fullWidth:s=!1,inputComponent:i="input",multiline:a=!1,notched:l,slotProps:c,slots:u={},type:f="text",...m}=o,p=wM(o),x={root:{ownerState:{disableUnderline:n}}},T=c?Dt(c,x):x,S=u.root??CM,v=u.input??EM;return b(mh,{slots:{root:S,input:v},slotProps:T,fullWidth:s,inputComponent:i,multiline:a,ref:r,type:f,...m,classes:p})});LT.muiName="Input";var Ch=LT;K();var Gp=Je(void 0);function fc(){let e=Se(Gp);if(e===void 0)throw new Error("MUI: RovingTabIndexContext is missing. Roving tab index items must be placed within a roving tab index provider.");return e}K();var RM=Object.is;function Kp(e,t){if(e===t)return!0;if(!(e instanceof Object)||!(t instanceof Object))return!1;let r=0,o=0;for(let n in e)if(r+=1,!RM(e[n],t[n])||!(n in t))return!1;for(let n in t)o+=1;return r===o}var kM=["ArrowRight","ArrowLeft","ArrowUp","ArrowDown","Home","End"];function kh(e){let{activeItemId:t,getDefaultActiveItemId:r,orientation:o,isRtl:n=!1,isItemFocusable:s=MM,wrap:i=!0}=e,[a,l]=ie(t),[c,u]=ie(t),f=a;t!==c&&(u(t),t!==void 0&&t!==a&&(f=t,l(t)));let m=J(null),p=J(new Map),[y,x]=ie(0),T=Le(()=>Eh(p.current),[y]),S=jT(f,T,s,r),v=J(S);v.current=S;let R=Ee(()=>{let $=Eh(p.current),h=jT(v.current,$,s,r);return WT($,h)},[r,s]),P=Ee(()=>p.current,[]),O=eo($=>{let h=p.current.get($.id);Kp(h??null,$)||(p.current.set($.id,$),x(z=>z+1))}),E=eo($=>{p.current.delete($)&&x(h=>h+1)}),A=eo($=>{l($)}),I=Ee($=>v.current===$,[]),N=Ee(($,h,z,k)=>{let j=qp(p.current),B=UT(j,$,h,z,k??s);return B?(B.element?.focus(),l(B.id),B):null},[s]),D=Ee(($,h,z)=>({onFocus:B=>{h?.(B);let W=qp(p.current),H=GT(W,B.target);H!==-1&&l(W[H].id)},onKeyDown:B=>{if(z?.(B),B.defaultPrevented||B.altKey||B.shiftKey||B.ctrlKey||B.metaKey||!kM.includes(B.key))return;let W=o==="horizontal"?"ArrowLeft":"ArrowUp",H=o==="horizontal"?"ArrowRight":"ArrowDown";o==="horizontal"&&n&&(W="ArrowRight",H="ArrowLeft");let ee=qp(p.current),G=pi(Dr(m.current)),F=G===m.current,V=FT(ee,G,v.current),te="next";switch(B.key){case W:te="previous",B.preventDefault(),F&&(V=ee.length);break;case H:B.preventDefault(),F&&(V=-1);break;case"Home":B.preventDefault(),V=-1;break;case"End":B.preventDefault(),te="previous",V=ee.length;break;default:return}N(V,te,i)},ref:IM($,B=>{m.current=B})}),[N,n,o,i]),w=Ee($=>{let h=qp(p.current),z=pi(Dr(m.current)),j=z===m.current?-1:FT(h,z,v.current);return N(j,"next",!0,$)?.id??null},[N]);return Le(()=>({activeItemId:S,focusNext:w,getActiveItem:R,getContainerProps:D,getItemMap:P,isItemActive:I,registerItem:O,setActiveItemId:A,unregisterItem:E}),[S,w,R,D,P,I,O,A,E])}function Oh(e){let t=fc(),{activeItemId:r,registerItem:o,unregisterItem:n}=t,s=J(null),i=Le(()=>({disabled:e.disabled??!1,element:null,focusableWhenDisabled:e.focusableWhenDisabled??!1,id:e.id,selected:e.selected??!1,textValue:e.textValue}),[e.disabled,e.focusableWhenDisabled,e.id,e.selected,e.textValue]),a=J(i);a.current=i;let l=Ee(u=>{if(s.current=u,u==null){queueMicrotask(()=>{s.current==null&&n(e.id)});return}o({...a.current,element:u})},[e.id,o,n]),c=ar(e.ref,l);return at(()=>{s.current&&o({...i,element:s.current})},[i,o]),at(()=>{let u=e.id;return()=>{n(u)}},[e.id,n]),{ref:c,tabIndex:r===e.id?0:-1}}function jT(e,t,r,o){return e!=null?OM(e,t,r):AM(t,r,o)}function OM(e,t,r){let o=HT(t,e);return o===-1?ZT(t,r):r(t[o])?t[o].id:UT(t,o,"next",!1,r)?.id??null}function AM(e,t,r){let o=r?.(e);if(o!=null){let n=WT(e,o);if(n&&t(n))return n.id}return ZT(e,t)}function FT(e,t,r){if(t){let o=GT(e,t);if(o!==-1)return o}return HT(e,r)}function UT(e,t,r,o,n){let s=e.length-1;if(s===-1)return null;let i=!1,a=VT(t,s,r,o),l=a;for(;a!==-1;){if(a===l){if(i)return null;i=!0}let c=e[a];if(!c||!n(c))a=VT(a,s,r,o);else return c}return null}function ZT(e,t){return e.find(r=>t(r))?.id??null}function WT(e,t){return t==null?null:e.find(r=>r.id===t)??null}function HT(e,t){return t==null?-1:e.findIndex(r=>r.id===t)}function GT(e,t){return t?e.findIndex(r=>r.element===t||r.element?.contains(t)):-1}function Eh(e){let t=Array.from(e.values());if(t.every(n=>n.element==null))return t;let r=t.filter(Rh).sort((n,s)=>$M(n.element,s.element)),o=t.filter(n=>!Rh(n));return[...r,...o]}function qp(e){return Eh(e).filter(Rh)}function VT(e,t,r,o=!0){return r==="next"?e===t?o?0:-1:e+1:e===0?o?t:-1:e-1}function MM(e){return e.element?e.focusableWhenDisabled?!0:!e.disabled&&!e.element.hasAttribute("disabled")&&e.element.getAttribute("aria-disabled")!=="true"&&e.element.hasAttribute("tabindex"):!1}function Rh(e){return e.element!=null&&e.element.isConnected}function $M(e,t){if(e===t)return 0;let r=e.compareDocumentPosition(t);return r&Node.DOCUMENT_POSITION_FOLLOWING||r&Node.DOCUMENT_POSITION_CONTAINED_BY?-1:r&Node.DOCUMENT_POSITION_PRECEDING||r&Node.DOCUMENT_POSITION_CONTAINS?1:0}function IM(...e){return t=>{e.forEach(r=>{di(r??null,t)})}}K();K();function NM(e={}){let{autoHideDuration:t=null,disableWindowBlurListener:r=!1,onClose:o,open:n,resumeHideDuration:s}=e,i=ao();ce(()=>{if(!n)return;function S(v){v.defaultPrevented||v.key==="Escape"&&o?.(v,"escapeKeyDown")}return document.addEventListener("keydown",S),()=>{document.removeEventListener("keydown",S)}},[n,o]);let a=eo((S,v)=>{o?.(S,v)}),l=eo(S=>{!o||S==null||i.start(S,()=>{a(null,"timeout")})});ce(()=>(n&&l(t),i.clear),[n,t,l,i]);let c=S=>{o?.(S,"clickaway")},u=i.clear,f=Ee(()=>{t!=null&&l(s??t*.5)},[t,s,l]),m=S=>v=>{let R=S.onBlur;R?.(v),f()},p=S=>v=>{let R=S.onFocus;R?.(v),u()},y=S=>v=>{let R=S.onMouseEnter;R?.(v),u()},x=S=>v=>{let R=S.onMouseLeave;R?.(v),f()};return ce(()=>{if(!r&&n)return window.addEventListener("focus",f),window.addEventListener("blur",u),()=>{window.removeEventListener("focus",f),window.removeEventListener("blur",u)}},[r,n,f,u]),{getRootProps:(S={})=>{let v={...za(e),...za(S)};return{role:"presentation",...S,...v,onBlur:m(v),onFocus:p(v),onMouseEnter:y(v),onMouseLeave:x(v)}},onClickAway:c}}var KT=NM;K();function qT(e){return we("MuiSnackbarContent",e)}var Eoe=Ce("MuiSnackbarContent",["root","message","action"]);var zM=e=>{let{classes:t}=e;return ke({root:["root"],action:["action"],message:["message"]},qT,t)},DM=ne(Si,{name:"MuiSnackbarContent",slot:"Root"})(ze(({theme:e})=>{let t=e.palette.mode==="light"?.8:.98;return{...e.focusVisible&&Oa(`0 0 0 4px ${(e.vars||e).palette.background.default}`),...e.typography.body2,color:e.vars?e.vars.palette.SnackbarContent.color:e.palette.getContrastText(rp(e.palette.background.default,t)),backgroundColor:e.vars?e.vars.palette.SnackbarContent.bg:rp(e.palette.background.default,t),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[e.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),BM=ne("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),LM=ne("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),jM=ue(function(t,r){let o=Me({props:t,name:"MuiSnackbarContent"}),{action:n,className:s,message:i,role:a="alert",...l}=o,c=o,u=zM(c);return b(DM,{role:a,elevation:6,className:he(u.root,s),ownerState:c,ref:r,...l,children:[b(BM,{className:u.message,ownerState:c,children:i}),n?b(LM,{className:u.action,ownerState:c,children:n}):null]})}),Ah=jM;function YT(e){return we("MuiSnackbar",e)}var Woe=Ce("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);var FM=e=>{let{classes:t,anchorOrigin:r}=e,o={root:["root",`anchorOrigin${Te(r.vertical)}${Te(r.horizontal)}`]};return ke(o,YT,t)},VM=ne("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,t[`anchorOrigin${Te(r.anchorOrigin.vertical)}${Te(r.anchorOrigin.horizontal)}`]]}})(ze(({theme:e})=>({zIndex:(e.vars||e).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:t})=>t.anchorOrigin.vertical==="top",style:{top:8,[e.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:t})=>t.anchorOrigin.vertical!=="top",style:{bottom:8,[e.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:t})=>t.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[e.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:t})=>t.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[e.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:t})=>t.anchorOrigin.horizontal==="center",style:{[e.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),UM=ue(function(t,r){let o=Me({props:t,name:"MuiSnackbar"}),n=ir(),s={enter:n.transitions.duration.enteringScreen,exit:n.transitions.duration.leavingScreen},{action:i,anchorOrigin:{vertical:a,horizontal:l}={vertical:"bottom",horizontal:"left"},autoHideDuration:c=null,children:u,className:f,disableWindowBlurListener:m=!1,message:p,onBlur:y,onClose:x,onFocus:T,onMouseEnter:S,onMouseLeave:v,open:R,resumeHideDuration:P,slots:O={},slotProps:E={},transitionDuration:A=s,...I}=o,N={...o,anchorOrigin:{vertical:a,horizontal:l},autoHideDuration:c,disableWindowBlurListener:m,transitionDuration:A},D=FM(N),{getRootProps:w,onClickAway:$}=KT(N),[h,z]=ie(!0),k={slots:O,slotProps:E},[j,B]=ot("root",{ref:r,className:[D.root,f],elementType:VM,getSlotProps:w,externalForwardedProps:{...k,...I},ownerState:N}),[W,{ownerState:H,...ee}]=ot("clickAwayListener",{elementType:Sh,externalForwardedProps:k,getSlotProps:oe=>({onClickAway:(...Y)=>{let fe=Y[0];oe.onClickAway?.(...Y),!fe?.defaultMuiPrevented&&$(...Y)}}),ownerState:N}),[G,F]=ot("content",{elementType:Ah,shouldForwardComponentProp:!0,externalForwardedProps:k,additionalProps:{message:p,action:i},ownerState:N}),[V,te]=ot("transition",{elementType:rc,externalForwardedProps:k,getSlotProps:oe=>({onEnter:(...Y)=>{oe.onEnter?.(...Y),z(!1)},onExited:(...Y)=>{oe.onExited?.(...Y),z(!0)}}),additionalProps:{appear:!0,in:R,timeout:A,direction:a==="top"?"down":"up"},ownerState:N});return!R&&h?null:b(W,{...ee,...O.clickAwayListener&&{ownerState:H},children:b(j,{...B,children:b(V,{...te,children:u||b(G,{...F})})})})}),Mh=UM;K();function XT(e){return we("MuiTab",e)}var ZM=Ce("MuiTab",["root","labelIcon","textColorInherit","textColorPrimary","textColorSecondary","selected","disabled","fullWidth","wrapped","icon"]),Io=ZM;var WM=e=>{let{classes:t,textColor:r,fullWidth:o,wrapped:n,icon:s,label:i,selected:a,disabled:l}=e,c={root:["root",s&&i&&"labelIcon",`textColor${Te(r)}`,o&&"fullWidth",n&&"wrapped",a&&"selected",l&&"disabled"],icon:["icon"]};return ke(c,XT,t)},HM=ne(on,{name:"MuiTab",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,r.label&&r.icon&&t.labelIcon,t[`textColor${Te(r.textColor)}`],r.fullWidth&&t.fullWidth,r.wrapped&&t.wrapped,{[`& .${Io.icon}`]:t.icon}]}})(ze(({theme:e})=>({...e.typography.button,maxWidth:360,minWidth:90,position:"relative",minHeight:48,flexShrink:0,padding:"12px 16px",overflow:"hidden",whiteSpace:"normal",textAlign:"center",lineHeight:1.25,...e.focusVisible&&e0(3),variants:[{props:({ownerState:t})=>t.label&&(t.iconPosition==="top"||t.iconPosition==="bottom"),style:{flexDirection:"column"}},{props:({ownerState:t})=>t.label&&t.iconPosition!=="top"&&t.iconPosition!=="bottom",style:{flexDirection:"row"}},{props:({ownerState:t})=>t.icon&&t.label,style:{minHeight:72,paddingTop:9,paddingBottom:9}},{props:({ownerState:t,iconPosition:r})=>t.icon&&t.label&&r==="top",style:{[`& > .${Io.icon}`]:{marginBottom:6}}},{props:({ownerState:t,iconPosition:r})=>t.icon&&t.label&&r==="bottom",style:{[`& > .${Io.icon}`]:{marginTop:6}}},{props:({ownerState:t,iconPosition:r})=>t.icon&&t.label&&r==="start",style:{[`& > .${Io.icon}`]:{marginRight:e.spacing(1)}}},{props:({ownerState:t,iconPosition:r})=>t.icon&&t.label&&r==="end",style:{[`& > .${Io.icon}`]:{marginLeft:e.spacing(1)}}},{props:{textColor:"inherit"},style:{color:"inherit",opacity:.6,[`&.${Io.selected}`]:{opacity:1},...e.focusVisible&&{[`&.${Rs.focusVisible}`]:{opacity:1}},[`&.${Io.disabled}`]:{opacity:(e.vars||e).palette.action.disabledOpacity}}},{props:{textColor:"primary"},style:{color:(e.vars||e).palette.text.secondary,[`&.${Io.selected}`]:{color:(e.vars||e).palette.primary.main},[`&.${Io.disabled}`]:{color:(e.vars||e).palette.text.disabled}}},{props:{textColor:"secondary"},style:{color:(e.vars||e).palette.text.secondary,[`&.${Io.selected}`]:{color:(e.vars||e).palette.secondary.main},[`&.${Io.disabled}`]:{color:(e.vars||e).palette.text.disabled}}},{props:({ownerState:t})=>t.fullWidth,style:{flexShrink:1,flexGrow:1,flexBasis:0,maxWidth:"none"}},{props:({ownerState:t})=>t.wrapped,style:{fontSize:e.typography.pxToRem(12)}}]}))),GM=ue(function(t,r){let o=Me({props:t,name:"MuiTab"}),{className:n,disabled:s=!1,disableFocusRipple:i=!1,fullWidth:a,icon:l,iconPosition:c="top",indicator:u,label:f,onChange:m,onClick:p,onFocus:y,selected:x,selectionFollowsFocus:T,textColor:S="inherit",value:v,wrapped:R=!1,...P}=o,O=fc(),E=Oh({id:v,ref:r,disabled:s,selected:x}),I=O.getItemMap().size===0&&x?0:E.tabIndex,N={...o,disabled:s,disableFocusRipple:i,selected:x,icon:!!l,iconPosition:c,label:!!f,fullWidth:a,textColor:S,wrapped:R},D=WM(N),w=l&&f&&Rt(l)?vr(l,{className:he(D.icon,l.props.className)}):l,$=z=>{!x&&m&&m(z,v),p&&p(z)},h=z=>{T&&!x&&m&&m(z,v),y&&y(z)};return b(HM,{internalNativeButton:!0,focusRipple:!i,className:he(D.root,n),ref:E.ref,role:"tab","aria-selected":x,disabled:s,onClick:$,onFocus:h,tabIndex:I,ownerState:N,...P,children:[c==="top"||c==="start"?b(Ie,{children:[w,f]}):b(Ie,{children:[f,w]}),u]})}),Yp=GM;K();function JT(e){return we("MuiToolbar",e)}var kne=Ce("MuiToolbar",["root","gutters","regular","dense"]);var KM=e=>{let{classes:t,disableGutters:r,variant:o}=e;return ke({root:["root",!r&&"gutters",o]},JT,t)},qM=ne("div",{name:"MuiToolbar",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,!r.disableGutters&&t.gutters,t[r.variant]]}})(ze(({theme:e})=>({position:"relative",display:"flex",alignItems:"center",variants:[{props:({ownerState:t})=>!t.disableGutters,style:{paddingLeft:e.spacing(2),paddingRight:e.spacing(2),[e.breakpoints.up("sm")]:{paddingLeft:e.spacing(3),paddingRight:e.spacing(3)}}},{props:{variant:"dense"},style:{minHeight:48}},{props:{variant:"regular"},style:e.mixins.toolbar}]}))),YM=ue(function(t,r){let o=Me({props:t,name:"MuiToolbar"}),{className:n,component:s="div",disableGutters:i=!1,variant:a="regular",...l}=o,c={...o,component:s,disableGutters:i,variant:a},u=KM(c);return b(qM,{as:s,className:he(u.root,n),ref:r,ownerState:c,...l})}),dc=YM;var QT=kt(b("path",{d:"M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z"}),"KeyboardArrowLeft");var eP=kt(b("path",{d:"M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"}),"KeyboardArrowRight");K();function XM(e){return(1+Math.sin(Math.PI*e-Math.PI/2))/2}function $h(e,t,r,o={},n=()=>{}){let{ease:s=XM,duration:i=300}=o,a=null,l=t[e],c=!1,u=()=>{c=!0},f=m=>{if(c){n(new Error("Animation cancelled"));return}a===null&&(a=m);let p=Math.min(1,(m-a)/i);if(t[e]=s(p)*(r-l)+l,p>=1){requestAnimationFrame(()=>{n(null)});return}requestAnimationFrame(f)};return l===r?(n(new Error("Element already at target position")),u):(requestAnimationFrame(f),u)}K();var JM={width:99,height:99,position:"absolute",top:-9999,overflow:"scroll",pointerEvents:"none"};function Ih(e){let{onChange:t,...r}=e,o=J(),n=J(null),s=()=>{o.current=n.current.offsetHeight-n.current.clientHeight};return La(()=>{let i=Ep(()=>{let l=o.current;s(),l!==o.current&&t(o.current)}),a=Ba(n.current);return a.addEventListener("resize",i),()=>{i.clear(),a.removeEventListener("resize",i)}},[t]),ce(()=>{s(),t(o.current)},[t]),b("div",{style:JM,...r,ref:n})}K();function tP(e){return we("MuiTabScrollButton",e)}var QM=Ce("MuiTabScrollButton",["root","vertical","horizontal","disabled"]),rP=QM;var e$=e=>{let{classes:t,orientation:r,disabled:o}=e;return ke({root:["root",r,o&&"disabled"]},tP,t)},t$=ne(on,{name:"MuiTabScrollButton",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.root,r.orientation&&t[r.orientation]]}})({width:40,flexShrink:0,opacity:.8,[`&.${rP.disabled}`]:{opacity:0},variants:[{props:{orientation:"vertical"},style:{width:"100%",height:40,"& svg":{transform:"var(--TabScrollButton-svgRotate)"}}}]}),r$=ue(function(t,r){let o=Me({props:t,name:"MuiTabScrollButton"}),{className:n,slots:s={},slotProps:i={},direction:a,orientation:l,disabled:c,...u}=o,{nativeButton:f,...m}=u,p=Sa(),y={isRtl:p,...o},x=e$(y),T=s.StartScrollButtonIcon??QT,S=s.EndScrollButtonIcon??eP,v=Yn({elementType:T,externalSlotProps:i.startScrollButtonIcon,additionalProps:{fontSize:"small"},ownerState:y}),R=Yn({elementType:S,externalSlotProps:i.endScrollButtonIcon,additionalProps:{fontSize:"small"},ownerState:y});return b(t$,{component:"div",className:he(x.root,n),ref:r,role:null,ownerState:y,tabIndex:null,...m,style:{...m.style,...l==="vertical"&&{"--TabScrollButton-svgRotate":`rotate(${p?-90:90}deg)`}},children:a==="left"?b(T,{...v}):b(S,{...R})})}),Nh=r$;function oP(e){return we("MuiTabs",e)}var o$=Ce("MuiTabs",["root","vertical","list","centered","scroller","fixed","scrollableX","scrollableY","hideScrollbar","scrollButtons","scrollButtonsHideMobile","indicator"]),Xp=o$;var n$=e=>{let{vertical:t,fixed:r,hideScrollbar:o,scrollableX:n,scrollableY:s,centered:i,scrollButtonsHideMobile:a,classes:l}=e;return ke({root:["root",t&&"vertical"],scroller:["scroller",r&&"fixed",o&&"hideScrollbar",n&&"scrollableX",s&&"scrollableY"],list:["list",t&&"vertical",i&&"centered"],indicator:["indicator"],scrollButtons:["scrollButtons",a&&"scrollButtonsHideMobile"],scrollableX:[n&&"scrollableX"],hideScrollbar:[o&&"hideScrollbar"]},oP,l)},s$=ne("div",{name:"MuiTabs",slot:"Root",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[{[`& .${Xp.scrollButtons}`]:t.scrollButtons},{[`& .${Xp.scrollButtons}`]:r.scrollButtonsHideMobile&&t.scrollButtonsHideMobile},t.root,r.vertical&&t.vertical]}})(ze(({theme:e})=>({overflow:"hidden",minHeight:48,WebkitOverflowScrolling:"touch",display:"flex",variants:[{props:({ownerState:t})=>t.vertical,style:{flexDirection:"column"}},{props:({ownerState:t})=>t.scrollButtonsHideMobile,style:{[`& .${Xp.scrollButtons}`]:{[e.breakpoints.down("sm")]:{display:"none"}}}}]}))),i$=ne("div",{name:"MuiTabs",slot:"Scroller",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.scroller,r.fixed&&t.fixed,r.hideScrollbar&&t.hideScrollbar,r.scrollableX&&t.scrollableX,r.scrollableY&&t.scrollableY]}})({position:"relative",display:"inline-block",flex:"1 1 auto",whiteSpace:"nowrap",variants:[{props:({ownerState:e})=>e.fixed,style:{overflowX:"hidden",width:"100%"}},{props:({ownerState:e})=>e.hideScrollbar,style:{scrollbarWidth:"none","&::-webkit-scrollbar":{display:"none"}}},{props:({ownerState:e})=>e.scrollableX,style:{overflowX:"auto",overflowY:"hidden"}},{props:({ownerState:e})=>e.scrollableY,style:{overflowY:"auto",overflowX:"hidden"}}]}),a$=ne("div",{name:"MuiTabs",slot:"List",overridesResolver:(e,t)=>{let{ownerState:r}=e;return[t.list,r.centered&&t.centered]}})({display:"flex",variants:[{props:({ownerState:e})=>e.vertical,style:{flexDirection:"column"}},{props:({ownerState:e})=>e.centered,style:{justifyContent:"center"}}]}),l$=ne("span",{name:"MuiTabs",slot:"Indicator"})(ze(({theme:e})=>({position:"absolute",height:2,bottom:0,width:"100%",...Lt(e),variants:[{props:{indicatorColor:"primary"},style:{backgroundColor:(e.vars||e).palette.primary.main}},{props:{indicatorColor:"secondary"},style:{backgroundColor:(e.vars||e).palette.secondary.main}},{props:({ownerState:t})=>t.vertical,style:{height:"100%",width:2,right:0}}]}))),c$=ne(Ih)({overflowX:"auto",overflowY:"hidden",scrollbarWidth:"none","&::-webkit-scrollbar":{display:"none"}}),zh={};function nP(e,t){let r=parseFloat(e);return Number.isNaN(r)?0:e.endsWith("%")?r/100*t:r}var u$=ue(function(t,r){let o=Me({props:t,name:"MuiTabs"}),n=ir(),s=Sa(),i=ci(n.motion.reducedMotion,!1),{"aria-label":a,"aria-labelledby":l,action:c,centered:u=!1,children:f,className:m,component:p="div",allowScrollButtonsMobile:y=!1,indicatorColor:x="primary",onChange:T,orientation:S="horizontal",scrollButtons:v="auto",selectionFollowsFocus:R,slots:P={},slotProps:O={},textColor:E="primary",value:A,variant:I="standard",visibleScrollbar:N=!1,...D}=o,w=I==="scrollable",$=S==="vertical",h=$?"scrollTop":"scrollLeft",z=$?"top":"left",k=$?"bottom":"right",j=$?"clientHeight":"clientWidth",B=$?"height":"width",W={...o,component:p,allowScrollButtonsMobile:y,indicatorColor:x,orientation:S,vertical:$,scrollButtons:v,textColor:E,variant:I,visibleScrollbar:N,fixed:!w,hideScrollbar:w&&!N,scrollableX:w&&!$,scrollableY:w&&$,centered:u&&!w,scrollButtonsHideMobile:!y},H=n$(W),ee=Yn({elementType:P.startScrollButtonIcon,externalSlotProps:O.startScrollButtonIcon,ownerState:W}),G=Yn({elementType:P.endScrollButtonIcon,externalSlotProps:O.endScrollButtonIcon,ownerState:W}),[F,V]=ie(zh),[te,oe]=ie(!1),[Y,fe]=ie(!1),[se,be]=ie(!1),Pe=A===!1?null:A,[We,qe]=ie(!1),[He,Ye]=ie({overflow:"hidden",scrollbarWidth:0}),$e=new Map,Ge=J(null),yt=J(null),Ot=F!==zh,Xe={slots:P,slotProps:O},Ve=()=>{let pe=Ge.current,ye;if(pe){let Ue=pe.getBoundingClientRect();ye={clientWidth:pe.clientWidth,clientHeight:pe.clientHeight,scrollLeft:pe.scrollLeft,scrollTop:pe.scrollTop,scrollWidth:pe.scrollWidth,top:Ue.top,bottom:Ue.bottom,left:Ue.left,right:Ue.right}}let Be;if(pe&&A!==!1){let Ue=yt.current.children;if(Ue.length>0){let _t=Ue[$e.get(A)];Be=_t?_t.getBoundingClientRect():null}}return{tabsMeta:ye,tabMeta:Be}},Tt=Pr(()=>{let{tabsMeta:pe,tabMeta:ye}=Ve(),Be=0,Ue;$?(Ue="top",ye&&pe&&(Be=ye.top-pe.top+pe.scrollTop)):(Ue=s?"right":"left",ye&&pe&&(Be=(s?-1:1)*(ye[Ue]-pe[Ue]+pe.scrollLeft)));let _t={[Ue]:Be,[B]:ye?ye[B]:0};if(typeof F[Ue]!="number"||typeof F[B]!="number")V(_t);else{let yo=Math.abs(F[Ue]-_t[Ue]),go=Math.abs(F[B]-_t[B]);(yo>=1||go>=1)&&V(_t)}}),dt=(pe,{animation:ye=!0}={})=>{ye&&!i.shouldReduceMotion?$h(h,Ge.current,pe,{duration:n.transitions.duration.standard}):Ge.current[h]=pe},Vt=pe=>{let ye=Ge.current[h];$?ye+=pe:ye+=pe*(s?-1:1),dt(ye)},me=()=>{let pe=Ge.current[j],ye=0,Be=Array.from(yt.current.children);for(let Ue=0;Ue<Be.length;Ue+=1){let _t=Be[Ue];if(ye+_t[j]>pe){Ue===0&&(ye=pe);break}ye+=_t[j]}return ye},re=()=>{Vt(-1*me())},xe=()=>{Vt(me())},[_e,{onChange:je,...et}]=ot("scrollbar",{className:he(H.scrollableX,H.hideScrollbar),elementType:c$,shouldForwardComponentProp:!0,externalForwardedProps:Xe,ownerState:W}),gt=Ee(pe=>{je?.(pe),Ye({overflow:null,scrollbarWidth:pe})},[je]),[Oe,Pt]=ot("scrollButtons",{className:H.scrollButtons,elementType:Nh,externalForwardedProps:Xe,ownerState:W,additionalProps:{orientation:S,slots:{StartScrollButtonIcon:P.startScrollButtonIcon,EndScrollButtonIcon:P.endScrollButtonIcon},slotProps:{startScrollButtonIcon:ee,endScrollButtonIcon:G}}}),mt=()=>{let pe={};pe.scrollbarSizeListener=w?b(_e,{...et,onChange:gt}):null;let Be=w&&(v==="auto"&&(te||Y)||v===!0);return pe.scrollButtonStart=Be?b(Oe,{direction:s?"right":"left",onClick:re,disabled:!te,...Pt}):null,pe.scrollButtonEnd=Be?b(Oe,{direction:s?"left":"right",onClick:xe,disabled:!Y,...Pt}):null,pe},bt=Pr(pe=>{let{tabsMeta:ye,tabMeta:Be}=Ve();if(!Be||!ye)return;let Ue=Ba(Ge.current).getComputedStyle(Ge.current),_t=$?ye.clientHeight:ye.clientWidth,yo=nP(Ue[$?"scrollPaddingTop":"scrollPaddingLeft"],_t),go=nP(Ue[$?"scrollPaddingBottom":"scrollPaddingRight"],_t),jo=ye[z]+yo,os=ye[k]-go,Kr=ye[h]+(Be[z]-jo);Be[z]<jo?dt(Kr,{animation:pe}):Be[k]>os&&(Be[k]-Be[z]>os-jo?dt(Kr,{animation:pe}):dt(ye[h]+(Be[k]-os),{animation:pe}))}),Fe=Pr(()=>{w&&v!==!1&&be(!se)});ce(()=>{let pe=Ep(()=>{Ge.current&&Tt()}),ye,Be=yo=>{yo.forEach(go=>{go.removedNodes.forEach(jo=>{ye?.unobserve(jo)}),go.addedNodes.forEach(jo=>{ye?.observe(jo)})}),pe(),Fe()},Ue=Ba(Ge.current);Ue.addEventListener("resize",pe);let _t;return typeof ResizeObserver<"u"&&(ye=new ResizeObserver(pe),Array.from(yt.current.children).forEach(yo=>{ye.observe(yo)})),typeof MutationObserver<"u"&&(_t=new MutationObserver(Be),_t.observe(yt.current,{childList:!0})),()=>{pe.clear(),Ue.removeEventListener("resize",pe),_t?.disconnect(),ye?.disconnect()}},[Tt,Fe]),ce(()=>{let pe=Array.from(yt.current.children),ye=pe.length;if(typeof IntersectionObserver<"u"&&ye>0&&w&&v!==!1){let Be=pe[0],Ue=pe[ye-1],_t={root:Ge.current,threshold:.99},yo=Kr=>{oe(!Kr[0].isIntersecting)},go=new IntersectionObserver(yo,_t);go.observe(Be);let jo=Kr=>{fe(!Kr[0].isIntersecting)},os=new IntersectionObserver(jo,_t);return os.observe(Ue),()=>{go.disconnect(),os.disconnect()}}},[w,v,se,f?.length]),ce(()=>{Tt()}),ce(()=>{bt(zh!==F)},[bt,F]),ce(()=>{if(typeof ResizeObserver>"u"||!w||v!=="auto")return;let pe=new ResizeObserver(()=>{bt(!1)});return pe.observe(Ge.current),()=>{pe.disconnect()}},[w,v,bt]),To(c,()=>({updateIndicator:Tt,updateScrollButtons:Fe}),[Tt,Fe]);let[Ns,rs]=ot("indicator",{className:H.indicator,elementType:l$,externalForwardedProps:Xe,ownerState:W,additionalProps:{style:F}}),Bo=b(Ns,{...rs}),mo=kh({activeItemId:We?void 0:Pe,orientation:S,isRtl:s}),mn=mo.getContainerProps(),zs=zn.toArray(f).filter(Rt).map((pe,ye)=>{let Be=pe.props.value===void 0?ye:pe.props.value;return $e.set(Be,ye),{child:pe,index:ye,childValue:Be}}).map(({child:pe,childValue:ye})=>{let Be=ye===A;return vr(pe,{fullWidth:I==="fullWidth",indicator:Be&&!Ot&&Bo,selected:Be,selectionFollowsFocus:R,onChange:T,textColor:E,value:ye})}),Re=mt(),[Zt,Lo]=ot("root",{ref:r,className:he(H.root,m),elementType:s$,externalForwardedProps:{...Xe,...D,component:p},ownerState:W}),[Tf,Pf]=ot("scroller",{ref:Ge,className:H.scroller,elementType:i$,externalForwardedProps:Xe,ownerState:W,additionalProps:{style:{overflow:He.overflow,[$?`margin${s?"Left":"Right"}`:"marginBottom"]:N?void 0:-He.scrollbarWidth}}}),_f=rn(mn.ref,yt),Mn=pe=>{let ye=yt.current;Rp(kp(ye))?.getAttribute("role")==="tab"&&mn.onKeyDown(pe)},[dr,ho]=ot("list",{ref:_f,className:H.list,elementType:a$,externalForwardedProps:Xe,ownerState:W,getSlotProps:pe=>({...pe,onBlur:ye=>{DT(ye.currentTarget,ye.relatedTarget)||qe(!1),pe.onBlur?.(ye)},onKeyDown:ye=>{Mn(ye),pe.onKeyDown?.(ye)},onFocus:ye=>{qe(!0),mn.onFocus(ye),pe.onFocus?.(ye)}})});return b(Zt,{...Lo,children:[Re.scrollButtonStart,Re.scrollbarSizeListener,b(Tf,{...Pf,children:[b(dr,{"aria-label":a,"aria-labelledby":l,"aria-orientation":S==="vertical"?"vertical":null,role:"tablist",...ho,children:b(Gp.Provider,{value:mo,children:zs})}),Ot&&Bo]}),Re.scrollButtonEnd]})}),Dh=u$;var p$=mm({themeId:Xt}),Bh=p$;var f$=()=>b(hT,{sx:{animation:"spin 2s linear infinite","@keyframes spin":{"0%":{transform:"rotate(0deg)"},"100%":{transform:"rotate(360deg)"}}}}),d$=()=>b(mT,{color:"success"}),m$=()=>b(yT,{color:"error"});function Lh(){let e=Se(yl),[t,r]=ie(No.ReadyState.UNINSTANTIATED),o=t===No.ReadyState.CONNECTING?"Connecting":t===No.ReadyState.OPEN?"Connected":b(Ie,{children:"Not\xA0Connected"});return ce(()=>{r(e.readyState)},[e.readyState]),b(Ie,{children:[b($o,{title:t===No.ReadyState.CONNECTING?"Connecting":t===No.ReadyState.OPEN?"Connected":"Not Connected",children:b(Ha,{disabled:t===No.ReadyState.CONNECTING||t===No.ReadyState.OPEN,children:t===No.ReadyState.CONNECTING?b(f$,{}):t===No.ReadyState.OPEN?b(d$,{}):b(m$,{})})}),b(_r,{sx:{display:{xs:"none",sm:"inherit"}},children:t===No.ReadyState.CONNECTING?b(Ie,{children:"Connecting"}):t===No.ReadyState.OPEN?b(Ie,{children:"Connected"}):b(Ie,{children:"Not\xA0Connected"})})]})}K();var h$="uplot",y$="u-hz",g$="u-vt",b$="u-title",x$="u-wrap",v$="u-under",T$="u-over",P$="u-axis",Ri="u-off",_$="u-select",S$="u-cursor-x",w$="u-cursor-y",C$="u-cursor-pt",E$="u-legend",R$="u-live",k$="u-inline",O$="u-series",A$="u-marker",sP="u-label",M$="u-value",hc="width",yc="height";var iP="bottom",Ga="left",jh="right",oy="#000",aP=oy+"0",Fh="mousemove",lP="mousedown",Vh="mouseup",cP="mouseenter",uP="mouseleave",pP="dblclick",$$="resize",I$="scroll",fP="change",rf="dppxchange",ny="--",el=typeof window<"u",Gh=el?document:null,qa=el?window:null,N$=el?navigator:null,lt,Jp;function Kh(){let e=devicePixelRatio;lt!=e&&(lt=e,Jp&&Yh(fP,Jp,Kh),Jp=matchMedia(`(min-resolution: ${lt-.001}dppx) and (max-resolution: ${lt+.001}dppx)`),ki(fP,Jp,Kh),qa.dispatchEvent(new CustomEvent(rf)))}function co(e,t){if(t!=null){let r=e.classList;!r.contains(t)&&r.add(t)}}function qh(e,t){let r=e.classList;r.contains(t)&&r.remove(t)}function Nt(e,t,r){e.style[t]=r+"px"}function cn(e,t,r,o){let n=Gh.createElement(e);return t!=null&&co(n,t),r?.insertBefore(n,o),n}function zo(e,t){return cn("div",e,t)}var dP=new WeakMap;function An(e,t,r,o,n){let s="translate("+t+"px,"+r+"px)",i=dP.get(e);s!=i&&(e.style.transform=s,dP.set(e,s),t<0||r<0||t>o||r>n?co(e,Ri):qh(e,Ri))}var mP=new WeakMap;function hP(e,t,r){let o=t+r,n=mP.get(e);o!=n&&(mP.set(e,o),e.style.background=t,e.style.borderColor=r)}var yP=new WeakMap;function gP(e,t,r,o){let n=t+""+r,s=yP.get(e);n!=s&&(yP.set(e,n),e.style.height=r+"px",e.style.width=t+"px",e.style.marginLeft=o?-t/2+"px":0,e.style.marginTop=o?-r/2+"px":0)}var sy={passive:!0},z$={...sy,capture:!0};function ki(e,t,r,o){t.addEventListener(e,r,o?z$:sy)}function Yh(e,t,r,o){t.removeEventListener(e,r,sy)}el&&Kh();function un(e,t,r,o){let n;r=r||0,o=o||t.length-1;let s=o<=2147483647;for(;o-r>1;)n=s?r+o>>1:uo((r+o)/2),t[n]<e?r=n:o=n;return e-t[r]<=t[o]-e?r:o}function WP(e){return(r,o,n)=>{let s=-1,i=-1;for(let a=o;a<=n;a++)if(e(r[a])){s=a;break}for(let a=n;a>=o;a--)if(e(r[a])){i=a;break}return[s,i]}}var HP=e=>e!=null,GP=e=>e!=null&&e>0,sf=WP(HP),D$=WP(GP);function B$(e,t,r,o=0,n=!1){let s=n?D$:sf,i=n?GP:HP;[t,r]=s(e,t,r);let a=e[t],l=e[t];if(t>-1)if(o==1)a=e[t],l=e[r];else if(o==-1)a=e[r],l=e[t];else for(let c=t;c<=r;c++){let u=e[c];i(u)&&(u<a?a=u:u>l&&(l=u))}return[a??Ct,l??-Ct]}function af(e,t,r,o){let n=vP(e),s=vP(t);e==t&&(n==-1?(e*=r,t/=r):(e/=r,t*=r));let i=r==10?Jn:KP,a=n==1?uo:Do,l=s==1?Do:uo,c=a(i(pr(e))),u=l(i(pr(t))),f=Ya(r,c),m=Ya(r,u);return r==10&&(c<0&&(f=Et(f,-c)),u<0&&(m=Et(m,-u))),o||r==2?(e=f*n,t=m*s):(e=JP(e,f),t=lf(t,m)),[e,t]}function iy(e,t,r,o){let n=af(e,t,r,o);return e==0&&(n[0]=0),t==0&&(n[1]=0),n}var ay=.1,bP={mode:3,pad:ay},bc={pad:0,soft:null,mode:0},L$={min:bc,max:bc};function of(e,t,r,o){return cf(r)?xP(e,t,r):(bc.pad=r,bc.soft=o?0:null,bc.mode=o?3:0,xP(e,t,L$))}function nt(e,t){return e??t}function j$(e,t,r){for(t=nt(t,0),r=nt(r,e.length-1);t<=r;){if(e[t]!=null)return!0;t++}return!1}function xP(e,t,r){let o=r.min,n=r.max,s=nt(o.pad,0),i=nt(n.pad,0),a=nt(o.hard,-Ct),l=nt(n.hard,Ct),c=nt(o.soft,Ct),u=nt(n.soft,-Ct),f=nt(o.mode,0),m=nt(n.mode,0),p=t-e,y=Jn(p),x=Gr(pr(e),pr(t)),T=Jn(x),S=pr(T-y);(p<1e-24||S>10)&&(p=0,(e==0||t==0)&&(p=1e-24,f==2&&c!=Ct&&(s=0),m==2&&u!=-Ct&&(i=0)));let v=p||x||1e3,R=Jn(v),P=Ya(10,uo(R)),O=v*(p==0?e==0?.1:1:s),E=Et(JP(e-O,P/10),24),A=e>=c&&(f==1||f==3&&E<=c||f==2&&E>=c)?c:Ct,I=Gr(a,E<A&&e>=A?A:pn(A,E)),N=v*(p==0?t==0?.1:1:i),D=Et(lf(t+N,P/10),24),w=t<=u&&(m==1||m==3&&D>=u||m==2&&D<=u)?u:-Ct,$=pn(l,D>w&&t<=w?w:Gr(w,D));return I==$&&I==0&&($=100),[I,$]}var F$=new Intl.NumberFormat(el?N$.language:"en-US"),ly=e=>F$.format(e),po=Math,tf=po.PI,pr=po.abs,uo=po.floor,ur=po.round,Do=po.ceil,pn=po.min,Gr=po.max,Ya=po.pow,vP=po.sign,Jn=po.log10,KP=po.log2,V$=(e,t=1)=>po.sinh(e)*t,Uh=(e,t=1)=>po.asinh(e/t),Ct=1/0;function TP(e){return(Jn((e^e>>31)-(e>>31))|0)+1}function Xh(e,t,r){return pn(Gr(e,t),r)}function qP(e){return typeof e=="function"}function Ke(e){return qP(e)?e:()=>e}var U$=()=>{},YP=e=>e,XP=(e,t)=>t,Z$=e=>null,PP=e=>!0,_P=(e,t)=>e==t,W$=/\.\d*?(?=9{6,}|0{6,})/gm,Oi=e=>{if(e_(e)||Is.has(e))return e;let t=`${e}`,r=t.match(W$);if(r==null)return e;let o=r[0].length-1;if(t.indexOf("e-")!=-1){let[n,s]=t.split("e");return+`${Oi(n)}e${s}`}return Et(e,o)};function Ci(e,t){return Oi(Et(Oi(e/t))*t)}function lf(e,t){return Oi(Do(Oi(e/t))*t)}function JP(e,t){return Oi(uo(Oi(e/t))*t)}function Et(e,t=0){if(e_(e))return e;let r=10**t,o=e*r*(1+Number.EPSILON);return ur(o)/r}var Is=new Map;function QP(e){return((""+e).split(".")[1]||"").length}function vc(e,t,r,o){let n=[],s=o.map(QP);for(let i=t;i<r;i++){let a=pr(i),l=Et(Ya(e,i),a);for(let c=0;c<o.length;c++){let u=e==10?+`${o[c]}e${i}`:o[c]*l,f=(i>=0?0:a)+(i>=s[c]?0:s[c]),m=e==10?u:Et(u,f);n.push(m),Is.set(m,f)}}return n}var xc={},cy=[],Xa=[null,null],$s=Array.isArray,e_=Number.isInteger,H$=e=>e===void 0;function SP(e){return typeof e=="string"}function cf(e){let t=!1;if(e!=null){let r=e.constructor;t=r==null||r==Object}return t}function G$(e){return e!=null&&typeof e=="object"}var K$=Object.getPrototypeOf(Uint8Array),t_="__proto__";function Ja(e,t=cf){let r;if($s(e)){let o=e.find(n=>n!=null);if($s(o)||t(o)){r=Array(e.length);for(let n=0;n<e.length;n++)r[n]=Ja(e[n],t)}else r=e.slice()}else if(e instanceof K$)r=e.slice();else if(t(e)){r={};for(let o in e)o!=t_&&(r[o]=Ja(e[o],t))}else r=e;return r}function nr(e){let t=arguments;for(let r=1;r<t.length;r++){let o=t[r];for(let n in o)n!=t_&&(cf(e[n])?nr(e[n],Ja(o[n])):e[n]=Ja(o[n]))}return e}var q$=0,Y$=1,X$=2;function J$(e,t,r){for(let o=0,n,s=-1;o<t.length;o++){let i=t[o];if(i>s){for(n=i-1;n>=0&&e[n]==null;)e[n--]=null;for(n=i+1;n<r&&e[n]==null;)e[s=n++]=null}}}function Q$(e,t){if(rI(e)){let i=e[0].slice();for(let a=1;a<e.length;a++)i.push(...e[a].slice(1));return oI(i[0])||(i=tI(i)),i}let r=new Set;for(let i=0;i<e.length;i++){let l=e[i][0],c=l.length;for(let u=0;u<c;u++)r.add(l[u])}let o=[Array.from(r).sort((i,a)=>i-a)],n=o[0].length,s=new Map;for(let i=0;i<n;i++)s.set(o[0][i],i);for(let i=0;i<e.length;i++){let a=e[i],l=a[0];for(let c=1;c<a.length;c++){let u=a[c],f=Array(n).fill(void 0),m=t?t[i][c]:Y$,p=[];for(let y=0;y<u.length;y++){let x=u[y],T=s.get(l[y]);x===null?m!=q$&&(f[T]=x,m==X$&&p.push(T)):f[T]=x}J$(f,p,n),o.push(f)}}return o}var eI=typeof queueMicrotask>"u"?e=>Promise.resolve().then(e):queueMicrotask;function tI(e){let t=e[0],r=t.length,o=Array(r);for(let s=0;s<o.length;s++)o[s]=s;o.sort((s,i)=>t[s]-t[i]);let n=[];for(let s=0;s<e.length;s++){let i=e[s],a=Array(r);for(let l=0;l<r;l++)a[l]=i[o[l]];n.push(a)}return n}function rI(e){let t=e[0][0],r=t.length;for(let o=1;o<e.length;o++){let n=e[o][0];if(n.length!=r)return!1;if(n!=t){for(let s=0;s<r;s++)if(n[s]!=t[s])return!1}}return!0}function oI(e,t=100){let r=e.length;if(r<=1)return!0;let o=0,n=r-1;for(;o<=n&&e[o]==null;)o++;for(;n>=o&&e[n]==null;)n--;if(n<=o)return!0;let s=Gr(1,uo((n-o+1)/t));for(let i=e[o],a=o+s;a<=n;a+=s){let l=e[a];if(l!=null){if(l<=i)return!1;i=l}}return!0}var r_=["January","February","March","April","May","June","July","August","September","October","November","December"],o_=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function n_(e){return e.slice(0,3)}var nI=o_.map(n_),sI=r_.map(n_),iI={MMMM:r_,MMM:sI,WWWW:o_,WWW:nI};function mc(e){return(e<10?"0":"")+e}function aI(e){return(e<10?"00":e<100?"0":"")+e}var lI={YYYY:e=>e.getFullYear(),YY:e=>(e.getFullYear()+"").slice(2),MMMM:(e,t)=>t.MMMM[e.getMonth()],MMM:(e,t)=>t.MMM[e.getMonth()],MM:e=>mc(e.getMonth()+1),M:e=>e.getMonth()+1,DD:e=>mc(e.getDate()),D:e=>e.getDate(),WWWW:(e,t)=>t.WWWW[e.getDay()],WWW:(e,t)=>t.WWW[e.getDay()],HH:e=>mc(e.getHours()),H:e=>e.getHours(),h:e=>{let t=e.getHours();return t==0?12:t>12?t-12:t},AA:e=>e.getHours()>=12?"PM":"AM",aa:e=>e.getHours()>=12?"pm":"am",a:e=>e.getHours()>=12?"p":"a",mm:e=>mc(e.getMinutes()),m:e=>e.getMinutes(),ss:e=>mc(e.getSeconds()),s:e=>e.getSeconds(),fff:e=>aI(e.getMilliseconds())};function uy(e,t){t=t||iI;let r=[],o=/\{([a-z]+)\}|[^{]+/gi,n;for(;n=o.exec(e);)r.push(n[0][0]=="{"?lI[n[1]]:n[0]);return s=>{let i="";for(let a=0;a<r.length;a++)i+=typeof r[a]=="string"?r[a]:r[a](s,t);return i}}var cI=new Intl.DateTimeFormat().resolvedOptions().timeZone;function uI(e,t){let r;return t=="UTC"||t=="Etc/UTC"?r=new Date(+e+e.getTimezoneOffset()*6e4):t==cI?r=e:(r=new Date(e.toLocaleString("en-US",{timeZone:t})),r.setMilliseconds(e.getMilliseconds())),r}var s_=e=>e%1==0,nf=[1,2,2.5,5],pI=vc(10,-32,0,nf),i_=vc(10,0,32,nf),fI=i_.filter(s_),Ei=pI.concat(i_),py=`+`,a_="{YYYY}",wP=py+a_,l_="{M}/{D}",gc=py+l_,Qp=gc+"/{YY}",c_="{aa}",dI="{h}:{mm}",Ka=dI+c_,CP=py+Ka,EP=":{ss}",ft=null;function u_(e){let t=e*1e3,r=t*60,o=r*60,n=o*24,s=n*30,i=n*365,l=(e==1?vc(10,0,3,nf).filter(s_):vc(10,-3,0,nf)).concat([t,t*5,t*10,t*15,t*30,r,r*5,r*10,r*15,r*30,o,o*2,o*3,o*4,o*6,o*8,o*12,n,n*2,n*3,n*4,n*5,n*6,n*7,n*8,n*9,n*10,n*15,s,s*2,s*3,s*4,s*6,i,i*2,i*5,i*10,i*25,i*50,i*100]),c=[[i,a_,ft,ft,ft,ft,ft,ft,1],[n*28,"{MMM}",wP,ft,ft,ft,ft,ft,1],[n,l_,wP,ft,ft,ft,ft,ft,1],[o,"{h}"+c_,Qp,ft,gc,ft,ft,ft,1],[r,Ka,Qp,ft,gc,ft,ft,ft,1],[t,EP,Qp+" "+Ka,ft,gc+" "+Ka,ft,CP,ft,1],[e,EP+".{fff}",Qp+" "+Ka,ft,gc+" "+Ka,ft,CP,ft,1]];function u(f){return(m,p,y,x,T,S)=>{let v=[],R=T>=i,P=T>=s&&T<i,O=f(y),E=Et(O*e,3),A=Zh(O.getFullYear(),R?0:O.getMonth(),P||R?1:O.getDate()),I=Et(A*e,3);if(P||R){let N=P?T/s:0,D=R?T/i:0,w=E==I?E:Et(Zh(A.getFullYear()+D,A.getMonth()+N,1)*e,3),$=new Date(ur(w/e)),h=$.getFullYear(),z=$.getMonth();for(let k=0;w<=x;k++){let j=Zh(h+D*k,z+N*k,1),B=j-f(Et(j*e,3));w=Et((+j+B)*e,3),w<=x&&v.push(w)}}else{let N=T>=n?n:T,D=uo(y)-uo(E),w=I+D+lf(E-I,N);v.push(w);let $=f(w),h=$.getHours()+$.getMinutes()/r+$.getSeconds()/o,z=T/o,k=m.axes[p]._space,j=S/k;for(;w=Et(w+T,e==1?0:3),!(w>x);)if(z>1){let B=uo(Et(h+z,6))%24,ee=f(w).getHours()-B;ee>1&&(ee=-1),w-=ee*o,h=(h+z)%24;let G=v[v.length-1];Et((w-G)/T,3)*j>=.7&&v.push(w)}else v.push(w)}return v}}return[l,c,u]}var[mI,hI,yI]=u_(1),[gI,bI,xI]=u_(.001);vc(2,-53,53,[1]);function RP(e,t){return e.map(r=>r.map((o,n)=>n==0||n==8||o==null?o:t(n==1||r[8]==0?o:r[1]+o)))}function kP(e,t){return(r,o,n,s,i)=>{let a=t.find(y=>i>=y[0])||t[t.length-1],l,c,u,f,m,p;return o.map(y=>{let x=e(y),T=x.getFullYear(),S=x.getMonth(),v=x.getDate(),R=x.getHours(),P=x.getMinutes(),O=x.getSeconds(),E=T!=l&&a[2]||S!=c&&a[3]||v!=u&&a[4]||R!=f&&a[5]||P!=m&&a[6]||O!=p&&a[7]||a[1];return l=T,c=S,u=v,f=R,m=P,p=O,E(x)})}}function vI(e,t){let r=uy(t);return(o,n,s,i,a)=>n.map(l=>r(e(l)))}function Zh(e,t,r){return new Date(e,t,r)}function OP(e,t){return t(e)}var TI="{YYYY}-{MM}-{DD} {h}:{mm}{aa}";function AP(e,t){return(r,o,n,s)=>s==null?ny:t(e(o))}function PI(e,t){let r=e.series[t];return r.width?r.stroke(e,t):r.points.width?r.points.stroke(e,t):null}function _I(e,t){return e.series[t].fill(e,t)}var SI={show:!0,live:!0,isolate:!1,mount:U$,markers:{show:!0,width:2,stroke:PI,fill:_I,dash:"solid"},idx:null,idxs:null,values:[]};function wI(e,t){let r=e.cursor.points,o=zo(),n=r.size(e,t);Nt(o,hc,n),Nt(o,yc,n);let s=n/-2;Nt(o,"marginLeft",s),Nt(o,"marginTop",s);let i=r.width(e,t,n);return i&&Nt(o,"borderWidth",i),o}function CI(e,t){let r=e.series[t].points;return r._fill||r._stroke}function EI(e,t){let r=e.series[t].points;return r._stroke||r._fill}function RI(e,t){return e.series[t].points.size}var Wh=[0,0];function kI(e,t,r){return Wh[0]=t,Wh[1]=r,Wh}function ef(e,t,r,o=!0){return n=>{n.button==0&&(!o||n.target==t)&&r(n)}}function Hh(e,t,r,o=!0){return n=>{(!o||n.target==t)&&r(n)}}var OI={show:!0,x:!0,y:!0,lock:!1,move:kI,points:{one:!1,show:wI,size:RI,width:0,stroke:EI,fill:CI},bind:{mousedown:ef,mouseup:ef,click:ef,dblclick:ef,mousemove:Hh,mouseleave:Hh,mouseenter:Hh},drag:{setScale:!0,x:!0,y:!1,dist:0,uni:null,click:(e,t)=>{t.stopPropagation(),t.stopImmediatePropagation()},_x:!1,_y:!1},focus:{dist:(e,t,r,o,n)=>o-n,prox:-1,bias:0},hover:{skip:[void 0],prox:null,bias:0},left:-10,top:-10,idx:null,dataIdx:null,idxs:null,event:null},p_={show:!0,stroke:"rgba(0,0,0,0.07)",width:2},fy=nr({},p_,{filter:XP}),f_=nr({},fy,{size:10}),d_=nr({},p_,{show:!1}),dy='12px system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',m_="bold "+dy,h_=1.5,MP={show:!0,scale:"x",stroke:oy,space:50,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:m_,side:2,grid:fy,ticks:f_,border:d_,font:dy,lineGap:h_,rotate:0},AI="Value",MI="Time",$P={show:!0,scale:"x",auto:!1,sorted:1,min:Ct,max:-Ct,idxs:[]};function $I(e,t,r,o,n){return t.map(s=>s==null?"":ly(s))}function II(e,t,r,o,n,s,i){let a=[],l=Is.get(n)||0;r=i?r:Et(lf(r,n),l);for(let c=r;c<=o;c=Et(c+n,l))a.push(Object.is(c,-0)?0:c);return a}function Jh(e,t,r,o,n,s,i){let a=[],l=e.scales[e.axes[t].scale].log,c=l==10?Jn:KP,u=uo(c(r));n=Ya(l,u),l==10&&(n=Ei[un(n,Ei)]);let f=r,m=n*l;l==10&&(m=Ei[un(m,Ei)]);do a.push(f),f=f+n,l==10&&!Is.has(f)&&(f=Et(f,Is.get(n))),f>=m&&(n=f,m=n*l,l==10&&(m=Ei[un(m,Ei)]));while(f<=o);return a}function NI(e,t,r,o,n,s,i){let l=e.scales[e.axes[t].scale].asinh,c=o>l?Jh(e,t,Gr(l,r),o,n):[l],u=o>=0&&r<=0?[0]:[];return(r<-l?Jh(e,t,Gr(l,-o),-r,n):[l]).reverse().map(m=>-m).concat(u,c)}var y_=/./,zI=/[12357]/,DI=/[125]/,IP=/1/,Qh=(e,t,r,o)=>e.map((n,s)=>t==4&&n==0||s%o==0&&r.test(n.toExponential()[n<0?1:0])?n:null);function BI(e,t,r,o,n){let s=e.axes[r],i=s.scale,a=e.scales[i],l=e.valToPos,c=s._space,u=l(10,i),f=l(9,i)-u>=c?y_:l(7,i)-u>=c?zI:l(5,i)-u>=c?DI:IP;if(f==IP){let m=pr(l(1,i)-u);if(m<c)return Qh(t.slice().reverse(),a.distr,f,Do(c/m)).reverse()}return Qh(t,a.distr,f,1)}function LI(e,t,r,o,n){let s=e.axes[r],i=s.scale,a=s._space,l=e.valToPos,c=pr(l(1,i)-l(2,i));return c<a?Qh(t.slice().reverse(),3,y_,Do(a/c)).reverse():t}function jI(e,t,r,o){return o==null?ny:t==null?"":ly(t)}var NP={show:!0,scale:"y",stroke:oy,space:30,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:m_,side:3,grid:fy,ticks:f_,border:d_,font:dy,lineGap:h_,rotate:0};function FI(e,t){let r=3+(e||1)*2;return Et(r*t,3)}function VI(e,t){let{scale:r,idxs:o}=e.series[0],n=e._data[0],s=e.valToPos(n[o[0]],r,!0),i=e.valToPos(n[o[1]],r,!0),a=pr(i-s),l=e.series[t],c=a/(l.points.space*lt);return o[1]-o[0]<=c}var zP={scale:null,auto:!0,sorted:0,min:Ct,max:-Ct},g_=(e,t,r,o,n)=>n,DP={show:!0,auto:!0,sorted:0,gaps:g_,alpha:1,facets:[nr({},zP,{scale:"x"}),nr({},zP,{scale:"y"})]},BP={scale:"y",auto:!0,sorted:0,show:!0,spanGaps:!1,gaps:g_,alpha:1,points:{show:VI,filter:null},values:null,min:Ct,max:-Ct,idxs:[],path:null,clip:null};function UI(e,t,r,o,n){return r/10}var b_={time:!0,auto:!0,distr:1,log:10,asinh:1,min:null,max:null,dir:1,ori:0},ZI=nr({},b_,{time:!1,ori:1}),LP={};function x_(e,t){let r=LP[e];return r||(r={key:e,plots:[],sub(o){r.plots.push(o)},unsub(o){r.plots=r.plots.filter(n=>n!=o)},pub(o,n,s,i,a,l,c){for(let u=0;u<r.plots.length;u++)r.plots[u]!=n&&r.plots[u].pub(o,n,s,i,a,l,c)}},e!=null&&(LP[e]=r)),r}var Qa=1,ey=2;function Ai(e,t,r){let o=e.mode,n=e.series[t],s=o==2?e._data[t]:e._data,i=e.scales,a=e.bbox,l=s[0],c=o==2?s[1]:s[t],u=o==2?i[n.facets[0].scale]:i[e.series[0].scale],f=o==2?i[n.facets[1].scale]:i[n.scale],m=a.left,p=a.top,y=a.width,x=a.height,T=e.valToPosH,S=e.valToPosV;return u.ori==0?r(n,l,c,u,f,T,S,m,p,y,x,pf,tl,df,T_,__):r(n,l,c,u,f,S,T,p,m,x,y,ff,rl,yy,P_,S_)}function my(e,t){let r=0,o=0,n=nt(e.bands,cy);for(let s=0;s<n.length;s++){let i=n[s];i.series[0]==t?r=i.dir:i.series[1]==t&&(i.dir==1?o|=1:o|=2)}return[r,o==1?-1:o==2?1:o==3?2:0]}function WI(e,t,r,o,n){let s=e.mode,i=e.series[t],a=s==2?i.facets[1].scale:i.scale,l=e.scales[a];return n==-1?l.min:n==1?l.max:l.distr==3?l.dir==1?l.min:l.max:0}function Qn(e,t,r,o,n,s){return Ai(e,t,(i,a,l,c,u,f,m,p,y,x,T)=>{let S=i.pxRound,v=c.dir*(c.ori==0?1:-1),R=c.ori==0?tl:rl,P,O;v==1?(P=r,O=o):(P=o,O=r);let E=S(f(a[P],c,x,p)),A=S(m(l[P],u,T,y)),I=S(f(a[O],c,x,p)),N=S(m(s==1?u.max:u.min,u,T,y)),D=new Path2D(n);return R(D,I,N),R(D,E,N),R(D,E,A),D})}function uf(e,t,r,o,n,s){let i=null;if(e.length>0){i=new Path2D;let a=t==0?df:yy,l=r;for(let f=0;f<e.length;f++){let m=e[f];if(m[1]>m[0]){let p=m[0]-l;p>0&&a(i,l,o,p,o+s),l=m[1]}}let c=r+n-l,u=10;c>0&&a(i,l,o-u/2,c,o+s+u)}return i}function HI(e,t,r){let o=e[e.length-1];o&&o[0]==t?o[1]=r:e.push([t,r])}function hy(e,t,r,o,n,s,i){let a=[],l=e.length;for(let c=n==1?r:o;c>=r&&c<=o;c+=n)if(t[c]===null){let f=c,m=c;if(n==1)for(;++c<=o&&t[c]===null;)m=c;else for(;--c>=r&&t[c]===null;)m=c;let p=s(e[f]),y=m==f?p:s(e[m]),x=f-n;p=i<=0&&x>=0&&x<l?s(e[x]):p;let S=m+n;y=i>=0&&S>=0&&S<l?s(e[S]):y,y>=p&&a.push([p,y])}return a}function jP(e){return e==0?YP:e==1?ur:t=>Ci(t,e)}function v_(e){let t=e==0?pf:ff,r=e==0?(n,s,i,a,l,c)=>{n.arcTo(s,i,a,l,c)}:(n,s,i,a,l,c)=>{n.arcTo(i,s,l,a,c)},o=e==0?(n,s,i,a,l)=>{n.rect(s,i,a,l)}:(n,s,i,a,l)=>{n.rect(i,s,l,a)};return(n,s,i,a,l,c=0,u=0)=>{c==0&&u==0?o(n,s,i,a,l):(c=pn(c,a/2,l/2),u=pn(u,a/2,l/2),t(n,s+c,i),r(n,s+a,i,s+a,i+l,c),r(n,s+a,i+l,s,i+l,u),r(n,s,i+l,s,i,u),r(n,s,i,s+a,i,c),n.closePath())}}var pf=(e,t,r)=>{e.moveTo(t,r)},ff=(e,t,r)=>{e.moveTo(r,t)},tl=(e,t,r)=>{e.lineTo(t,r)},rl=(e,t,r)=>{e.lineTo(r,t)},df=v_(0),yy=v_(1),T_=(e,t,r,o,n,s)=>{e.arc(t,r,o,n,s)},P_=(e,t,r,o,n,s)=>{e.arc(r,t,o,n,s)},__=(e,t,r,o,n,s,i)=>{e.bezierCurveTo(t,r,o,n,s,i)},S_=(e,t,r,o,n,s,i)=>{e.bezierCurveTo(r,t,n,o,i,s)};function w_(e){return(t,r,o,n,s)=>Ai(t,r,(i,a,l,c,u,f,m,p,y,x,T)=>{let{pxRound:S,points:v}=i,R,P;c.ori==0?(R=pf,P=T_):(R=ff,P=P_);let O=Et(v.width*lt,3),E=(v.size-v.width)/2*lt,A=Et(E*2,3),I=new Path2D,N=new Path2D,{left:D,top:w,width:$,height:h}=t.bbox;df(N,D-A,w-A,$+A*2,h+A*2);let z=k=>{if(l[k]!=null){let j=S(f(a[k],c,x,p)),B=S(m(l[k],u,T,y));R(I,j+E,B),P(I,j,B,E,0,tf*2)}};if(s)s.forEach(z);else for(let k=o;k<=n;k++)z(k);return{stroke:O>0?I:null,fill:I,clip:N,flags:Qa|ey}})}function C_(e){return(t,r,o,n,s,i)=>{o!=n&&(s!=o&&i!=o&&e(t,r,o),s!=n&&i!=n&&e(t,r,n),e(t,r,i))}}var GI=C_(tl),KI=C_(rl);function E_(e){let t=nt(e?.alignGaps,0);return(r,o,n,s)=>Ai(r,o,(i,a,l,c,u,f,m,p,y,x,T)=>{[n,s]=sf(l,n,s);let S=i.pxRound,v=h=>S(f(h,c,x,p)),R=h=>S(m(h,u,T,y)),P,O;c.ori==0?(P=tl,O=GI):(P=rl,O=KI);let E=c.dir*(c.ori==0?1:-1),A={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:Qa},I=A.stroke,N=!1;if(s-n>=x*4){let h=V=>r.posToVal(V,c.key,!0),z=null,k=null,j,B,W,H=v(a[E==1?n:s]),ee=v(a[n]),G=v(a[s]),F=h(E==1?ee+1:G-1);for(let V=E==1?n:s;V>=n&&V<=s;V+=E){let te=a[V],Y=(E==1?te<F:te>F)?H:v(te),fe=l[V];Y==H?fe!=null?(B=fe,z==null?(P(I,Y,R(B)),j=z=k=B):B<z?z=B:B>k&&(k=B)):fe===null&&(N=!0):(z!=null&&O(I,H,R(z),R(k),R(j),R(B)),fe!=null?(B=fe,P(I,Y,R(B)),z=k=j=B):(z=k=null,fe===null&&(N=!0)),H=Y,F=h(H+E))}z!=null&&z!=k&&W!=H&&O(I,H,R(z),R(k),R(j),R(B))}else for(let h=E==1?n:s;h>=n&&h<=s;h+=E){let z=l[h];z===null?N=!0:z!=null&&P(I,v(a[h]),R(z))}let[w,$]=my(r,o);if(i.fill!=null||w!=0){let h=A.fill=new Path2D(I),z=i.fillTo(r,o,i.min,i.max,w),k=R(z),j=v(a[n]),B=v(a[s]);E==-1&&([B,j]=[j,B]),P(h,B,k),P(h,j,k)}if(!i.spanGaps){let h=[];N&&h.push(...hy(a,l,n,s,E,v,t)),A.gaps=h=i.gaps(r,o,n,s,h),A.clip=uf(h,c.ori,p,y,x,T)}return $!=0&&(A.band=$==2?[Qn(r,o,n,s,I,-1),Qn(r,o,n,s,I,1)]:Qn(r,o,n,s,I,$)),A})}function qI(e){let t=nt(e.align,1),r=nt(e.ascDesc,!1),o=nt(e.alignGaps,0),n=nt(e.extend,!1);return(s,i,a,l)=>Ai(s,i,(c,u,f,m,p,y,x,T,S,v,R)=>{[a,l]=sf(f,a,l);let P=c.pxRound,{left:O,width:E}=s.bbox,A=ee=>P(y(ee,m,v,T)),I=ee=>P(x(ee,p,R,S)),N=m.ori==0?tl:rl,D={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:Qa},w=D.stroke,$=m.dir*(m.ori==0?1:-1),h=I(f[$==1?a:l]),z=A(u[$==1?a:l]),k=z,j=z;n&&t==-1&&(j=O,N(w,j,h)),N(w,z,h);for(let ee=$==1?a:l;ee>=a&&ee<=l;ee+=$){let G=f[ee];if(G==null)continue;let F=A(u[ee]),V=I(G);t==1?N(w,F,h):N(w,k,V),N(w,F,V),h=V,k=F}let B=k;n&&t==1&&(B=O+E,N(w,B,h));let[W,H]=my(s,i);if(c.fill!=null||W!=0){let ee=D.fill=new Path2D(w),G=c.fillTo(s,i,c.min,c.max,W),F=I(G);N(ee,B,F),N(ee,j,F)}if(!c.spanGaps){let ee=[];ee.push(...hy(u,f,a,l,$,A,o));let G=c.width*lt/2,F=r||t==1?G:-G,V=r||t==-1?-G:G;ee.forEach(te=>{te[0]+=F,te[1]+=V}),D.gaps=ee=c.gaps(s,i,a,l,ee),D.clip=uf(ee,m.ori,T,S,v,R)}return H!=0&&(D.band=H==2?[Qn(s,i,a,l,w,-1),Qn(s,i,a,l,w,1)]:Qn(s,i,a,l,w,H)),D})}function FP(e,t,r,o,n,s,i=Ct){if(e.length>1){let a=null;for(let l=0,c=1/0;l<e.length;l++)if(t[l]!==void 0){if(a!=null){let u=pr(e[l]-e[a]);u<c&&(c=u,i=pr(r(e[l],o,n,s)-r(e[a],o,n,s)))}a=l}}return i}function YI(e){e=e||xc;let t=nt(e.size,[.6,Ct,1]),r=e.align||0,o=e.gap||0,n=e.radius;n=n==null?[0,0]:typeof n=="number"?[n,0]:n;let s=Ke(n),i=1-t[0],a=nt(t[1],Ct),l=nt(t[2],1),c=nt(e.disp,xc),u=nt(e.each,p=>{}),{fill:f,stroke:m}=c;return(p,y,x,T)=>Ai(p,y,(S,v,R,P,O,E,A,I,N,D,w)=>{let $=S.pxRound,h=r,z=o*lt,k=a*lt,j=l*lt,B,W;P.ori==0?[B,W]=s(p,y):[W,B]=s(p,y);let H=P.dir*(P.ori==0?1:-1),ee=P.ori==0?df:yy,G=P.ori==0?u:(re,xe,_e,je,et,gt,Oe)=>{u(re,xe,_e,et,je,Oe,gt)},F=nt(p.bands,cy).find(re=>re.series[0]==y),V=F!=null?F.dir:0,te=S.fillTo(p,y,S.min,S.max,V),oe=$(A(te,O,w,N)),Y,fe,se,be=D,Pe=$(S.width*lt),We=!1,qe=null,He=null,Ye=null,$e=null;f!=null&&(Pe==0||m!=null)&&(We=!0,qe=f.values(p,y,x,T),He=new Map,new Set(qe).forEach(re=>{re!=null&&He.set(re,new Path2D)}),Pe>0&&(Ye=m.values(p,y,x,T),$e=new Map,new Set(Ye).forEach(re=>{re!=null&&$e.set(re,new Path2D)})));let{x0:Ge,size:yt}=c;if(Ge!=null&&yt!=null){h=1,v=Ge.values(p,y,x,T),Ge.unit==2&&(v=v.map(_e=>p.posToVal(I+_e*D,P.key,!0)));let re=yt.values(p,y,x,T);yt.unit==2?fe=re[0]*D:fe=E(re[0],P,D,I)-E(0,P,D,I),be=FP(v,R,E,P,D,I,be),se=be-fe+z}else be=FP(v,R,E,P,D,I,be),se=be*i+z,fe=be-se;se<1&&(se=0),Pe>=fe/2&&(Pe=0),se<5&&($=YP);let Ot=se>0,Xe=be-se-(Ot?Pe:0);fe=$(Xh(Xe,j,k)),Y=(h==0?fe/2:h==H?0:fe)-h*H*((h==0?z/2:0)+(Ot?Pe/2:0));let Ve={stroke:null,fill:null,clip:null,band:null,gaps:null,flags:0},Tt=We?null:new Path2D,dt=null;if(F!=null)dt=p.data[F.series[1]];else{let{y0:re,y1:xe}=c;re!=null&&xe!=null&&(R=xe.values(p,y,x,T),dt=re.values(p,y,x,T))}let Vt=B*fe,me=W*fe;for(let re=H==1?x:T;re>=x&&re<=T;re+=H){let xe=R[re];if(xe==null)continue;if(dt!=null){let bt=dt[re]??0;if(xe-bt==0)continue;oe=A(bt,O,w,N)}let _e=P.distr!=2||c!=null?v[re]:re,je=E(_e,P,D,I),et=A(nt(xe,te),O,w,N),gt=$(je-Y),Oe=$(Gr(et,oe)),Pt=$(pn(et,oe)),mt=Oe-Pt;if(xe!=null){let bt=xe<0?me:Vt,Fe=xe<0?Vt:me;We?(Pe>0&&Ye[re]!=null&&ee($e.get(Ye[re]),gt,Pt+uo(Pe/2),fe,Gr(0,mt-Pe),bt,Fe),qe[re]!=null&&ee(He.get(qe[re]),gt,Pt+uo(Pe/2),fe,Gr(0,mt-Pe),bt,Fe)):ee(Tt,gt,Pt+uo(Pe/2),fe,Gr(0,mt-Pe),bt,Fe),G(p,y,re,gt-Pe/2,Pt,fe+Pe,mt)}}return Pe>0?Ve.stroke=We?$e:Tt:We||(Ve._fill=S.width==0?S._fill:S._stroke??S._fill,Ve.width=0),Ve.fill=We?He:Tt,Ve})}function XI(e,t){let r=nt(t?.alignGaps,0);return(o,n,s,i)=>Ai(o,n,(a,l,c,u,f,m,p,y,x,T,S)=>{[s,i]=sf(c,s,i);let v=a.pxRound,R=B=>v(m(B,u,T,y)),P=B=>v(p(B,f,S,x)),O,E,A;u.ori==0?(O=pf,A=tl,E=__):(O=ff,A=rl,E=S_);let I=u.dir*(u.ori==0?1:-1),N=R(l[I==1?s:i]),D=N,w=[],$=[];for(let B=I==1?s:i;B>=s&&B<=i;B+=I)if(c[B]!=null){let H=l[B],ee=R(H);w.push(D=ee),$.push(P(c[B]))}let h={stroke:e(w,$,O,A,E,v),fill:null,clip:null,band:null,gaps:null,flags:Qa},z=h.stroke,[k,j]=my(o,n);if(a.fill!=null||k!=0){let B=h.fill=new Path2D(z),W=a.fillTo(o,n,a.min,a.max,k),H=P(W);A(B,D,H),A(B,N,H)}if(!a.spanGaps){let B=[];B.push(...hy(l,c,s,i,I,R,r)),h.gaps=B=a.gaps(o,n,s,i,B),h.clip=uf(B,u.ori,y,x,T,S)}return j!=0&&(h.band=j==2?[Qn(o,n,s,i,z,-1),Qn(o,n,s,i,z,1)]:Qn(o,n,s,i,z,j)),h})}function JI(e){return XI(QI,e)}function QI(e,t,r,o,n,s){let i=e.length;if(i<2)return null;let a=new Path2D;if(r(a,e[0],t[0]),i==2)o(a,e[1],t[1]);else{let l=Array(i),c=Array(i-1),u=Array(i-1),f=Array(i-1);for(let m=0;m<i-1;m++)u[m]=t[m+1]-t[m],f[m]=e[m+1]-e[m],c[m]=u[m]/f[m];l[0]=c[0];for(let m=1;m<i-1;m++)c[m]===0||c[m-1]===0||c[m-1]>0!=c[m]>0?l[m]=0:(l[m]=3*(f[m-1]+f[m])/((2*f[m]+f[m-1])/c[m-1]+(f[m]+2*f[m-1])/c[m]),isFinite(l[m])||(l[m]=0));l[i-1]=c[i-2];for(let m=0;m<i-1;m++)n(a,e[m]+f[m]/3,t[m]+l[m]*f[m]/3,e[m+1]-f[m]/3,t[m+1]-l[m+1]*f[m]/3,e[m+1],t[m+1])}return a}var ty=new Set;function VP(){for(let e of ty)e.syncRect(!0)}el&&(ki($$,qa,VP),ki(I$,qa,VP,!0),ki(rf,qa,()=>{fr.pxRatio=lt}));var eN=E_(),tN=w_();function UP(e,t,r,o){return(o?[e[0],e[1]].concat(e.slice(2)):[e[0]].concat(e.slice(1))).map((s,i)=>ry(s,i,t,r))}function rN(e,t){return e.map((r,o)=>o==0?{}:nr({},t,r))}function ry(e,t,r,o){return nr({},t==0?r:o,e)}function R_(e,t,r){return t==null?Xa:[t,r]}var oN=R_;function nN(e,t,r){return t==null?Xa:of(t,r,ay,!0)}function k_(e,t,r,o){return t==null?Xa:af(t,r,e.scales[o].log,!1)}var sN=k_;function O_(e,t,r,o){return t==null?Xa:iy(t,r,e.scales[o].log,!1)}var iN=O_;function aN(e,t,r,o,n){let s=Gr(TP(e),TP(t)),i=t-e,a=un(n/o*i,r);do{let l=r[a],c=o*l/i;if(c>=n&&s+(l<5?Is.get(l):0)<=17)return[l,c]}while(++a<r.length);return[0,0]}function ZP(e){let t,r;return e=e.replace(/(\d+)px/,(o,n)=>(t=ur((r=+n)*lt))+"px"),[e,t,r]}function lN(e){e.show&&[e.font,e.labelFont].forEach(t=>{let r=Et(t[2]*lt,1);t[0]=t[0].replace(/[0-9.]+px/,r+"px"),t[1]=r})}function fr(e,t,r){let o={mode:nt(e.mode,1)},n=o.mode;function s(d,g,_,C){let M=g.valToPct(d);return C+_*(g.dir==-1?1-M:M)}function i(d,g,_,C){let M=g.valToPct(d);return C+_*(g.dir==-1?M:1-M)}function a(d,g,_,C){return g.ori==0?s(d,g,_,C):i(d,g,_,C)}o.valToPosH=s,o.valToPosV=i;let l=!1;o.status=0;let c=o.root=zo(h$);if(e.id!=null&&(c.id=e.id),co(c,e.class),e.title){let d=zo(b$,c);d.textContent=e.title}let u=cn("canvas"),f=o.ctx=u.getContext("2d"),m=zo(x$,c);ki("click",m,d=>{d.target===y&&(At!=Di||zt!=Bi)&&Er.click(o,d)},!0);let p=o.under=zo(v$,m);m.appendChild(u);let y=o.over=zo(T$,m);e=Ja(e);let x=+nt(e.pxAlign,1),T=jP(x);(e.plugins||[]).forEach(d=>{d.opts&&(e=d.opts(o,e)||e)});let S=e.ms||.001,v=o.series=n==1?UP(e.series||[],$P,BP,!1):rN(e.series||[null],DP),R=o.axes=UP(e.axes||[],MP,NP,!0),P=o.scales={},O=o.bands=e.bands||[];O.forEach(d=>{d.fill=Ke(d.fill||null),d.dir=nt(d.dir,-1)});let E=n==2?v[1].facets[0].scale:v[0].scale,A={axes:sS,series:eS},I=(e.drawOrder||["axes","series"]).map(d=>A[d]);function N(d){let g=d.distr==3?_=>Jn(_>0?_:d.clamp(o,_,d.min,d.max,d.key)):d.distr==4?_=>Uh(_,d.asinh):d.distr==100?_=>d.fwd(_):_=>_;return _=>{let C=g(_),{_min:M,_max:L}=d,Z=L-M;return(C-M)/Z}}function D(d){let g=P[d];if(g==null){let _=(e.scales||xc)[d]||xc;if(_.from!=null){D(_.from);let C=nr({},P[_.from],_,{key:d});C.valToPct=N(C),P[d]=C}else{g=P[d]=nr({},d==E?b_:ZI,_),g.key=d;let C=g.time,M=g.range,L=$s(M);if((d!=E||n==2&&!C)&&(L&&(M[0]==null||M[1]==null)&&(M={min:M[0]==null?bP:{mode:1,hard:M[0],soft:M[0]},max:M[1]==null?bP:{mode:1,hard:M[1],soft:M[1]}},L=!1),!L&&cf(M))){let Z=M;M=(q,X,ae)=>X==null?Xa:of(X,ae,Z)}g.range=Ke(M||(C?oN:d==E?g.distr==3?sN:g.distr==4?iN:R_:g.distr==3?k_:g.distr==4?O_:nN)),g.auto=Ke(L?!1:g.auto),g.clamp=Ke(g.clamp||UI),g._min=g._max=null,g.valToPct=N(g)}}}D("x"),D("y"),n==1&&v.forEach(d=>{D(d.scale)}),R.forEach(d=>{D(d.scale)});for(let d in e.scales)D(d);let w=P[E],$=w.distr,h,z;w.ori==0?(co(c,y$),h=s,z=i):(co(c,g$),h=i,z=s);let k={};for(let d in P){let g=P[d];(g.min!=null||g.max!=null)&&(k[d]={min:g.min,max:g.max},g.min=g.max=null)}let j=e.tzDate||(d=>new Date(ur(d/S))),B=e.fmtDate||uy,W=S==1?yI(j):xI(j),H=kP(j,RP(S==1?hI:bI,B)),ee=AP(j,OP(TI,B)),G=[],F=o.legend=nr({},SI,e.legend),V=o.cursor=nr({},OI,{drag:{y:n==2}},e.cursor),te=F.show,oe=V.show,Y=F.markers;F.idxs=G,Y.width=Ke(Y.width),Y.dash=Ke(Y.dash),Y.stroke=Ke(Y.stroke),Y.fill=Ke(Y.fill);let fe,se,be,Pe=[],We=[],qe,He=!1,Ye={};if(F.live){let d=v[1]?v[1].values:null;He=d!=null,qe=He?d(o,1,0):{_:0};for(let g in qe)Ye[g]=ny}if(te)if(fe=cn("table",E$,c),be=cn("tbody",null,fe),F.mount(o,fe),He){se=cn("thead",null,fe,be);let d=cn("tr",null,se);cn("th",null,d);for(var $e in qe)cn("th",sP,d).textContent=$e}else co(fe,k$),F.live&&co(fe,R$);let Ge={show:!0},yt={show:!1};function Ot(d,g){if(g==0&&(He||!F.live||n==2))return Xa;let _=[],C=cn("tr",O$,be,be.childNodes[g]);co(C,d.class),d.show||co(C,Ri);let M=cn("th",null,C);if(Y.show){let q=zo(A$,M);if(g>0){let X=Y.width(o,g);X&&(q.style.border=X+"px "+Y.dash(o,g)+" "+Y.stroke(o,g)),q.style.background=Y.fill(o,g)}}let L=zo(sP,M);d.label instanceof HTMLElement?L.appendChild(d.label):L.textContent=d.label,g>0&&(Y.show||(L.style.color=d.width>0?Y.stroke(o,g):Y.fill(o,g)),Ve("click",M,q=>{if(V._lock)return;Mn(q);let X=v.indexOf(d);if((q.ctrlKey||q.metaKey)!=F.isolate){let ae=v.some((le,de)=>de>0&&de!=X&&le.show);v.forEach((le,de)=>{de>0&&hn(de,ae?de==X?Ge:yt:Ge,!0,Qt.setSeries)})}else hn(X,{show:!d.show},!0,Qt.setSeries)},!1),pe&&Ve(cP,M,q=>{V._lock||(Mn(q),hn(v.indexOf(d),ji,!0,Qt.setSeries))},!1));for(var Z in qe){let q=cn("td",M$,C);q.textContent="--",_.push(q)}return[C,_]}let Xe=new Map;function Ve(d,g,_,C=!0){let M=Xe.get(g)||{},L=V.bind[d](o,g,_,C);L&&(ki(d,g,M[d]=L),Xe.set(g,M))}function Tt(d,g,_){let C=Xe.get(g)||{};for(let M in C)(d==null||M==d)&&(Yh(M,g,C[M]),delete C[M]);d==null&&Xe.delete(g)}let dt=0,Vt=0,me=0,re=0,xe=0,_e=0,je=xe,et=_e,gt=me,Oe=re,Pt=0,mt=0,bt=0,Fe=0;o.bbox={};let Ns=!1,rs=!1,Bo=!1,mo=!1,mn=!1,Br=!1;function zs(d,g,_){(_||d!=o.width||g!=o.height)&&Re(d,g),$i(!1),Bo=!0,rs=!0,Ii()}function Re(d,g){o.width=dt=me=d,o.height=Vt=re=g,xe=_e=0,Pf(),_f();let _=o.bbox;Pt=_.left=Ci(xe*lt,.5),mt=_.top=Ci(_e*lt,.5),bt=_.width=Ci(me*lt,.5),Fe=_.height=Ci(re*lt,.5)}let Zt=3;function Lo(){let d=!1,g=0;for(;!d;){g++;let _=oS(g),C=nS(g);d=g==Zt||_&&C,d||(Re(o.width,o.height),rs=!0)}}function Tf({width:d,height:g}){zs(d,g)}o.setSize=Tf;function Pf(){let d=!1,g=!1,_=!1,C=!1;R.forEach((M,L)=>{if(M.show&&M._show){let{side:Z,_size:q}=M,X=Z%2,ae=M.label!=null?M.labelSize:0,le=q+ae;le>0&&(X?(me-=le,Z==3?(xe+=le,C=!0):_=!0):(re-=le,Z==0?(_e+=le,d=!0):g=!0))}}),Kr[0]=d,Kr[1]=_,Kr[2]=g,Kr[3]=C,me-=ns[1]+ns[3],xe+=ns[3],re-=ns[2]+ns[0],_e+=ns[0]}function _f(){let d=xe+me,g=_e+re,_=xe,C=_e;function M(L,Z){switch(L){case 1:return d+=Z,d-Z;case 2:return g+=Z,g-Z;case 3:return _-=Z,_+Z;case 0:return C-=Z,C+Z}}R.forEach((L,Z)=>{if(L.show&&L._show){let q=L.side;L._pos=M(q,L._size),L.label!=null&&(L._lpos=M(q,L.labelSize))}})}if(V.dataIdx==null){let d=V.hover,g=d.skip=new Set(d.skip??[]);g.add(void 0);let _=d.prox=Ke(d.prox),C=d.bias??=0;V.dataIdx=(M,L,Z,q)=>{if(L==0)return Z;let X=Z,ae=_(M,L,Z,q)??Ct,le=ae>=0&&ae<Ct,de=w.ori==0?me:re,De=V.left,st=t[0],tt=t[L];if(g.has(tt[Z])){X=null;let Ze=null,Ae=null,ve;if(C==0||C==-1)for(ve=Z;Ze==null&&ve-- >0;)g.has(tt[ve])||(Ze=ve);if(C==0||C==1)for(ve=Z;Ae==null&&ve++<tt.length;)g.has(tt[ve])||(Ae=ve);if(Ze!=null||Ae!=null)if(le){let $t=Ze==null?-1/0:h(st[Ze],w,de,0),Wt=Ae==null?1/0:h(st[Ae],w,de,0),xr=De-$t,xt=Wt-De;xr<=xt?xr<=ae&&(X=Ze):xt<=ae&&(X=Ae)}else X=Ae==null?Ze:Ze==null?Ae:Z-Ze<=Ae-Z?Ze:Ae}else le&&pr(De-h(st[Z],w,de,0))>ae&&(X=null);return X}}let Mn=d=>{V.event=d};V.idxs=G,V._lock=!1;let dr=V.points;dr.show=Ke(dr.show),dr.size=Ke(dr.size),dr.stroke=Ke(dr.stroke),dr.width=Ke(dr.width),dr.fill=Ke(dr.fill);let ho=o.focus=nr({},e.focus||{alpha:.3},V.focus),pe=ho.prox>=0,ye=pe&&dr.one,Be=[],Ue=[],_t=[];function yo(d,g){let _=dr.show(o,g);if(_ instanceof HTMLElement)return co(_,C$),co(_,d.class),An(_,-10,-10,me,re),y.insertBefore(_,Be[g]),_}function go(d,g){if(n==1||g>0){let _=n==1&&P[d.scale].time,C=d.value;d.value=_?SP(C)?AP(j,OP(C,B)):C||ee:C||jI,d.label=d.label||(_?MI:AI)}if(ye||g>0){d.width=d.width==null?1:d.width,d.paths=d.paths||eN||Z$,d.fillTo=Ke(d.fillTo||WI),d.pxAlign=+nt(d.pxAlign,x),d.pxRound=jP(d.pxAlign),d.stroke=Ke(d.stroke||null),d.fill=Ke(d.fill||null),d._stroke=d._fill=d._paths=d._focus=null;let _=FI(Gr(1,d.width),1),C=d.points=nr({},{size:_,width:Gr(1,_*.2),stroke:d.stroke,space:_*2,paths:tN,_stroke:null,_fill:null},d.points);C.show=Ke(C.show),C.filter=Ke(C.filter),C.fill=Ke(C.fill),C.stroke=Ke(C.stroke),C.paths=Ke(C.paths),C.pxAlign=d.pxAlign}if(te){let _=Ot(d,g);Pe.splice(g,0,_[0]),We.splice(g,0,_[1]),F.values.push(null)}if(oe){G.splice(g,0,null);let _=null;ye?g==0&&(_=yo(d,g)):g>0&&(_=yo(d,g)),Be.splice(g,0,_),Ue.splice(g,0,0),_t.splice(g,0,0)}br("addSeries",g)}function jo(d,g){g=g??v.length,d=n==1?ry(d,g,$P,BP):ry(d,g,{},DP),v.splice(g,0,d),go(v[g],g)}o.addSeries=jo;function os(d){if(v.splice(d,1),te){F.values.splice(d,1),We.splice(d,1);let g=Pe.splice(d,1)[0];Tt(null,g.firstChild),g.remove()}oe&&(G.splice(d,1),Be.splice(d,1)[0].remove(),Ue.splice(d,1),_t.splice(d,1)),br("delSeries",d)}o.delSeries=os;let Kr=[!1,!1,!1,!1];function X_(d,g){if(d._show=d.show,d.show){let _=d.side%2,C=P[d.scale];C==null&&(d.scale=_?v[1].scale:E,C=P[d.scale]);let M=C.time;d.size=Ke(d.size),d.space=Ke(d.space),d.rotate=Ke(d.rotate),$s(d.incrs)&&d.incrs.forEach(Z=>{!Is.has(Z)&&Is.set(Z,QP(Z))}),d.incrs=Ke(d.incrs||(C.distr==2?fI:M?S==1?mI:gI:Ei)),d.splits=Ke(d.splits||(M&&C.distr==1?W:C.distr==3?Jh:C.distr==4?NI:II)),d.stroke=Ke(d.stroke),d.grid.stroke=Ke(d.grid.stroke),d.ticks.stroke=Ke(d.ticks.stroke),d.border.stroke=Ke(d.border.stroke);let L=d.values;d.values=$s(L)&&!$s(L[0])?Ke(L):M?$s(L)?kP(j,RP(L,B)):SP(L)?vI(j,L):L||H:L||$I,d.filter=Ke(d.filter||(C.distr>=3&&C.log==10?BI:C.distr==3&&C.log==2?LI:XP)),d.font=ZP(d.font),d.labelFont=ZP(d.labelFont),d._size=d.size(o,null,g,0),d._space=d._rotate=d._incrs=d._found=d._splits=d._values=null,d._size>0&&(Kr[g]=!0,d._el=zo(P$,m))}}function nl(d,g,_,C){let[M,L,Z,q]=_,X=g%2,ae=0;return X==0&&(q||L)&&(ae=g==0&&!M||g==2&&!Z?ur(MP.size/3):0),X==1&&(M||Z)&&(ae=g==1&&!L||g==3&&!q?ur(NP.size/2):0),ae}let My=o.padding=(e.padding||[nl,nl,nl,nl]).map(d=>Ke(nt(d,nl))),ns=o._padding=My.map((d,g)=>d(o,g,Kr,0)),Cr,mr=null,hr=null,wc=n==1?v[0].idxs:null,Fo=null,sl=!1;function $y(d,g){if(t=d??[],o.data=o._data=t,n==2){Cr=0;for(let _=1;_<v.length;_++)Cr+=t[_][0].length}else{t.length==0&&(o.data=o._data=t=[[]]),Fo=t[0],Cr=Fo.length;let _=t;if($==2){_=t.slice();let C=_[0]=Array(Cr);for(let M=0;M<Cr;M++)C[M]=M}o._data=t=_}if($i(!0),br("setData"),$==2&&(Bo=!0),g!==!1){let _=w;_.auto(o,sl)?Sf():is(E,_.min,_.max),mo=mo||V.left>=0,Br=!0,Ii()}}o.setData=$y;function Sf(){sl=!0;let d,g;n==1&&(Cr>0?(mr=wc[0]=0,hr=wc[1]=Cr-1,d=t[0][mr],g=t[0][hr],$==2?(d=mr,g=hr):d==g&&($==3?[d,g]=af(d,d,w.log,!1):$==4?[d,g]=iy(d,d,w.log,!1):w.time?g=d+ur(86400/S):[d,g]=of(d,g,ay,!0))):(mr=wc[0]=d=null,hr=wc[1]=g=null)),is(E,d,g)}let Cc,Mi,wf,Cf,Ef,Rf,kf,Of,Af,qr;function Iy(d,g,_,C,M,L){d??=aP,_??=cy,C??="butt",M??=aP,L??="round",d!=Cc&&(f.strokeStyle=Cc=d),M!=Mi&&(f.fillStyle=Mi=M),g!=wf&&(f.lineWidth=wf=g),L!=Ef&&(f.lineJoin=Ef=L),C!=Rf&&(f.lineCap=Rf=C),_!=Cf&&f.setLineDash(Cf=_)}function Ny(d,g,_,C){g!=Mi&&(f.fillStyle=Mi=g),d!=kf&&(f.font=kf=d),_!=Of&&(f.textAlign=Of=_),C!=Af&&(f.textBaseline=Af=C)}function Mf(d,g,_,C,M=0){if(C.length>0&&d.auto(o,sl)&&(g==null||g.min==null)){let L=nt(mr,0),Z=nt(hr,C.length-1),q=_.min==null?B$(C,L,Z,M,d.distr==3):[_.min,_.max];d.min=pn(d.min,_.min=q[0]),d.max=Gr(d.max,_.max=q[1])}}let zy={min:null,max:null};function J_(){for(let C in P){let M=P[C];k[C]==null&&(M.min==null||k[E]!=null&&M.auto(o,sl))&&(k[C]=zy)}for(let C in P){let M=P[C];k[C]==null&&M.from!=null&&k[M.from]!=null&&(k[C]=zy)}k[E]!=null&&$i(!0);let d={};for(let C in k){let M=k[C];if(M!=null){let L=d[C]=Ja(P[C],G$);if(M.min!=null)nr(L,M);else if(C!=E||n==2)if(Cr==0&&L.from==null){let Z=L.range(o,null,null,C);L.min=Z[0],L.max=Z[1]}else L.min=Ct,L.max=-Ct}}if(Cr>0){v.forEach((C,M)=>{if(n==1){let L=C.scale,Z=k[L];if(Z==null)return;let q=d[L];if(M==0){let X=q.range(o,q.min,q.max,L);q.min=X[0],q.max=X[1],mr=un(q.min,t[0]),hr=un(q.max,t[0]),hr-mr>1&&(t[0][mr]<q.min&&mr++,t[0][hr]>q.max&&hr--),C.min=Fo[mr],C.max=Fo[hr]}else C.show&&C.auto&&Mf(q,Z,C,t[M],C.sorted);C.idxs[0]=mr,C.idxs[1]=hr}else if(M>0&&C.show&&C.auto){let[L,Z]=C.facets,q=L.scale,X=Z.scale,[ae,le]=t[M],de=d[q],De=d[X];de!=null&&Mf(de,k[q],L,ae,L.sorted),De!=null&&Mf(De,k[X],Z,le,Z.sorted),C.min=Z.min,C.max=Z.max}});for(let C in d){let M=d[C],L=k[C];if(M.from==null&&(L==null||L.min==null)){let Z=M.range(o,M.min==Ct?null:M.min,M.max==-Ct?null:M.max,C);M.min=Z[0],M.max=Z[1]}}}for(let C in d){let M=d[C];if(M.from!=null){let L=d[M.from];if(L.min==null)M.min=M.max=null;else{let Z=M.range(o,L.min,L.max,C);M.min=Z[0],M.max=Z[1]}}}let g={},_=!1;for(let C in d){let M=d[C],L=P[C];if(L.min!=M.min||L.max!=M.max){L.min=M.min,L.max=M.max;let Z=L.distr;L._min=Z==3?Jn(L.min):Z==4?Uh(L.min,L.asinh):Z==100?L.fwd(L.min):L.min,L._max=Z==3?Jn(L.max):Z==4?Uh(L.max,L.asinh):Z==100?L.fwd(L.max):L.max,g[C]=_=!0}}if(_){v.forEach((C,M)=>{n==2?M>0&&g.y&&(C._paths=null):g[C.scale]&&(C._paths=null)});for(let C in g)Bo=!0,br("setScale",C);oe&&V.left>=0&&(mo=Br=!0)}for(let C in k)k[C]=null}function Q_(d){let g=Xh(mr-1,0,Cr-1),_=Xh(hr+1,0,Cr-1);for(;d[g]==null&&g>0;)g--;for(;d[_]==null&&_<Cr-1;)_++;return[g,_]}function eS(){if(Cr>0){let d=v.some(g=>g._focus)&&qr!=ho.alpha;d&&(f.globalAlpha=qr=ho.alpha),v.forEach((g,_)=>{if(_>0&&g.show&&(Dy(_,!1),Dy(_,!0),g._paths==null)){let C=qr;qr!=g.alpha&&(f.globalAlpha=qr=g.alpha);let M=n==2?[0,t[_][0].length-1]:Q_(t[_]);g._paths=g.paths(o,_,M[0],M[1]),qr!=C&&(f.globalAlpha=qr=C)}}),v.forEach((g,_)=>{if(_>0&&g.show){let C=qr;qr!=g.alpha&&(f.globalAlpha=qr=g.alpha),g._paths!=null&&By(_,!1);{let M=g._paths!=null?g._paths.gaps:null,L=g.points.show(o,_,mr,hr,M),Z=g.points.filter(o,_,L,M);(L||Z)&&(g.points._paths=g.points.paths(o,_,mr,hr,Z),By(_,!0))}qr!=C&&(f.globalAlpha=qr=C),br("drawSeries",_)}}),d&&(f.globalAlpha=qr=1)}}function Dy(d,g){let _=g?v[d].points:v[d];_._stroke=_.stroke(o,d),_._fill=_.fill(o,d)}function By(d,g){let _=g?v[d].points:v[d],{stroke:C,fill:M,clip:L,flags:Z,_stroke:q=_._stroke,_fill:X=_._fill,_width:ae=_.width}=_._paths;ae=Et(ae*lt,3);let le=null,de=ae%2/2;g&&X==null&&(X=ae>0?"#fff":q);let De=_.pxAlign==1&&de>0;if(De&&f.translate(de,de),!g){let st=Pt-ae/2,tt=mt-ae/2,Ze=bt+ae,Ae=Fe+ae;le=new Path2D,le.rect(st,tt,Ze,Ae)}g?$f(q,ae,_.dash,_.cap,X,C,M,Z,L):tS(d,q,ae,_.dash,_.cap,X,C,M,Z,le,L),De&&f.translate(-de,-de)}function tS(d,g,_,C,M,L,Z,q,X,ae,le){let de=!1;X!=0&&O.forEach((De,st)=>{if(De.series[0]==d){let tt=v[De.series[1]],Ze=t[De.series[1]],Ae=(tt._paths||xc).band;$s(Ae)&&(Ae=De.dir==1?Ae[0]:Ae[1]);let ve,$t=null;tt.show&&Ae&&j$(Ze,mr,hr)?($t=De.fill(o,st)||L,ve=tt._paths.clip):Ae=null,$f(g,_,C,M,$t,Z,q,X,ae,le,ve,Ae),de=!0}}),de||$f(g,_,C,M,L,Z,q,X,ae,le)}let Ly=Qa|ey;function $f(d,g,_,C,M,L,Z,q,X,ae,le,de){Iy(d,g,_,C,M),(X||ae||de)&&(f.save(),X&&f.clip(X),ae&&f.clip(ae)),de?(q&Ly)==Ly?(f.clip(de),le&&f.clip(le),Rc(M,Z),Ec(d,L,g)):q&ey?(Rc(M,Z),f.clip(de),Ec(d,L,g)):q&Qa&&(f.save(),f.clip(de),le&&f.clip(le),Rc(M,Z),f.restore(),Ec(d,L,g)):(Rc(M,Z),Ec(d,L,g)),(X||ae||de)&&f.restore()}function Ec(d,g,_){_>0&&(g instanceof Map?g.forEach((C,M)=>{f.strokeStyle=Cc=M,f.stroke(C)}):g!=null&&d&&f.stroke(g))}function Rc(d,g){g instanceof Map?g.forEach((_,C)=>{f.fillStyle=Mi=C,f.fill(_)}):g!=null&&d&&f.fill(g)}function rS(d,g,_,C){let M=R[d],L;if(C<=0)L=[0,0];else{let Z=M._space=M.space(o,d,g,_,C),q=M._incrs=M.incrs(o,d,g,_,C,Z);L=aN(g,_,q,C,Z)}return M._found=L}function If(d,g,_,C,M,L,Z,q,X,ae){let le=Z%2/2;x==1&&f.translate(le,le),Iy(q,Z,X,ae,q),f.beginPath();let de,De,st,tt,Ze=M+(C==0||C==3?-L:L);_==0?(De=M,tt=Ze):(de=M,st=Ze);for(let Ae=0;Ae<d.length;Ae++)g[Ae]!=null&&(_==0?de=st=d[Ae]:De=tt=d[Ae],f.moveTo(de,De),f.lineTo(st,tt));f.stroke(),x==1&&f.translate(-le,-le)}function oS(d){let g=!0;return R.forEach((_,C)=>{if(!_.show)return;let M=P[_.scale];if(M.min==null){_._show&&(g=!1,_._show=!1,$i(!1));return}else _._show||(g=!1,_._show=!0,$i(!1));let L=_.side,Z=L%2,{min:q,max:X}=M,[ae,le]=rS(C,q,X,Z==0?me:re);if(le==0)return;let de=M.distr==2,De=_._splits=_.splits(o,C,q,X,ae,le,de),st=M.distr==2?De.map(ve=>Fo[ve]):De,tt=M.distr==2?Fo[De[1]]-Fo[De[0]]:ae,Ze=_._values=_.values(o,_.filter(o,st,C,le,tt),C,le,tt);_._rotate=L==2?_.rotate(o,Ze,C,le):0;let Ae=_._size;_._size=Do(_.size(o,Ze,C,d)),Ae!=null&&_._size!=Ae&&(g=!1)}),g}function nS(d){let g=!0;return My.forEach((_,C)=>{let M=_(o,C,Kr,d);M!=ns[C]&&(g=!1),ns[C]=M}),g}function sS(){for(let d=0;d<R.length;d++){let g=R[d];if(!g.show||!g._show)continue;let _=g.side,C=_%2,M,L,Z=g.stroke(o,d),q=_==0||_==3?-1:1,[X,ae]=g._found;if(g.label!=null){let jr=g.labelGap*q,oo=ur((g._lpos+jr)*lt);Ny(g.labelFont[0],Z,"center",_==2?"top":iP),f.save(),C==1?(M=L=0,f.translate(oo,ur(mt+Fe/2)),f.rotate((_==3?-tf:tf)/2)):(M=ur(Pt+bt/2),L=oo);let Ls=qP(g.label)?g.label(o,d,X,ae):g.label;f.fillText(Ls,M,L),f.restore()}if(ae==0)continue;let le=P[g.scale],de=C==0?bt:Fe,De=C==0?Pt:mt,st=g._splits,tt=le.distr==2?st.map(jr=>Fo[jr]):st,Ze=le.distr==2?Fo[st[1]]-Fo[st[0]]:X,Ae=g.ticks,ve=g.border,$t=Ae.show?Ae.size:0,Wt=ur($t*lt),xr=ur((g.alignTo==2?g._size-$t-g.gap:g.gap)*lt),xt=g._rotate*-tf/180,Ht=T(g._pos*lt),to=(Wt+xr)*q,Lr=Ht+to;L=C==0?Lr:0,M=C==1?Lr:0;let bo=g.font[0],Vo=g.align==1?Ga:g.align==2?jh:xt>0?Ga:xt<0?jh:C==0?"center":_==3?jh:Ga,gn=xt||C==1?"middle":_==2?"top":iP;Ny(bo,Z,Vo,gn);let ro=g.font[1]*g.lineGap,xo=st.map(jr=>T(a(jr,le,de,De))),Uo=g._values;for(let jr=0;jr<Uo.length;jr++){let oo=Uo[jr];if(oo!=null){C==0?M=xo[jr]:L=xo[jr],oo=""+oo;let Ls=oo.indexOf(`+`)==-1?[oo]:oo.split(/\n/gm);for(let Fr=0;Fr<Ls.length;Fr++){let ng=Ls[Fr];xt?(f.save(),f.translate(M,L+Fr*ro),f.rotate(xt),f.fillText(ng,0,0),f.restore()):f.fillText(ng,M,L+Fr*ro)}}}Ae.show&&If(xo,Ae.filter(o,tt,d,ae,Ze),C,_,Ht,Wt,Et(Ae.width*lt,3),Ae.stroke(o,d),Ae.dash,Ae.cap);let bn=g.grid;bn.show&&If(xo,bn.filter(o,tt,d,ae,Ze),C,C==0?2:1,C==0?mt:Pt,C==0?Fe:bt,Et(bn.width*lt,3),bn.stroke(o,d),bn.dash,bn.cap),ve.show&&If([Ht],[1],C==0?1:0,C==0?1:2,C==1?mt:Pt,C==1?Fe:bt,Et(ve.width*lt,3),ve.stroke(o,d),ve.dash,ve.cap)}br("drawAxes")}function $i(d){v.forEach((g,_)=>{_>0&&(g._paths=null,d&&(n==1?(g.min=null,g.max=null):g.facets.forEach(C=>{C.min=null,C.max=null})))})}let kc=!1,Nf=!1,il=[];function iS(){Nf=!1;for(let d=0;d<il.length;d++)br(...il[d]);il.length=0}function Ii(){kc||(eI(jy),kc=!0)}function aS(d,g=!1){kc=!0,Nf=g,d(o),jy(),g&&il.length>0&&queueMicrotask(iS)}o.batch=aS;function jy(){if(Ns&&(J_(),Ns=!1),Bo&&(Lo(),Bo=!1),rs){if(Nt(p,Ga,xe),Nt(p,"top",_e),Nt(p,hc,me),Nt(p,yc,re),Nt(y,Ga,xe),Nt(y,"top",_e),Nt(y,hc,me),Nt(y,yc,re),Nt(m,hc,dt),Nt(m,yc,Vt),u.width=ur(dt*lt),u.height=ur(Vt*lt),R.forEach(({_el:d,_show:g,_size:_,_pos:C,side:M})=>{if(d!=null)if(g){let L=M===3||M===0?_:0,Z=M%2==1;Nt(d,Z?"left":"top",C-L),Nt(d,Z?"width":"height",_),Nt(d,Z?"top":"left",Z?_e:xe),Nt(d,Z?"height":"width",Z?re:me),qh(d,Ri)}else co(d,Ri)}),Cc=Mi=wf=Ef=Rf=kf=Of=Af=Cf=null,qr=1,cl(!0),xe!=je||_e!=et||me!=gt||re!=Oe){$i(!1);let d=me/gt,g=re/Oe;if(oe&&!mo&&V.left>=0){V.left*=d,V.top*=g,Ni&&An(Ni,ur(V.left),0,me,re),zi&&An(zi,0,ur(V.top),me,re);for(let _=0;_<Be.length;_++){let C=Be[_];C!=null&&(Ue[_]*=d,_t[_]*=g,An(C,Do(Ue[_]),Do(_t[_]),me,re))}}if(Mt.show&&!mn&&Mt.left>=0&&Mt.width>0){Mt.left*=d,Mt.width*=d,Mt.top*=g,Mt.height*=g;for(let _ in Ff)Nt(Li,_,Mt[_])}je=xe,et=_e,gt=me,Oe=re}br("setSize"),rs=!1}dt>0&&Vt>0&&(f.clearRect(0,0,u.width,u.height),br("drawClear"),I.forEach(d=>d()),br("draw")),Mt.show&&mn&&(Oc(Mt),mn=!1),oe&&mo&&(Bs(null,!0,!1),mo=!1),F.show&&F.live&&Br&&(Lf(),Br=!1),l||(l=!0,o.status=1,br("ready")),sl=!1,kc=!1}o.redraw=(d,g)=>{Bo=g||!1,d!==!1?is(E,w.min,w.max):Ii()};function zf(d,g){let _=P[d];if(_.from==null){if(Cr==0){let C=_.range(o,g.min,g.max,d);g.min=C[0],g.max=C[1]}if(g.min>g.max){let C=g.min;g.min=g.max,g.max=C}if(Cr>1&&g.min!=null&&g.max!=null&&g.max-g.min<1e-16)return;d==E&&_.distr==2&&Cr>0&&(g.min=un(g.min,t[0]),g.max=un(g.max,t[0]),g.min==g.max&&g.max++),k[d]=g,Ns=!0,Ii()}}o.setScale=zf;let Df,Bf,Ni,zi,Fy,Vy,Di,Bi,Uy,Zy,At,zt,ss=!1,Er=V.drag,yr=Er.x,gr=Er.y;oe&&(V.x&&(Df=zo(S$,y)),V.y&&(Bf=zo(w$,y)),w.ori==0?(Ni=Df,zi=Bf):(Ni=Bf,zi=Df),At=V.left,zt=V.top);let Mt=o.select=nr({show:!0,over:!0,left:0,width:0,top:0,height:0},e.select),Li=Mt.show?zo(_$,Mt.over?y:p):null;function Oc(d,g){if(Mt.show){for(let _ in d)Mt[_]=d[_],_ in Ff&&Nt(Li,_,d[_]);g!==!1&&br("setSelect")}}o.setSelect=Oc;function lS(d){if(v[d].show)te&&qh(Pe[d],Ri);else if(te&&co(Pe[d],Ri),oe){let _=ye?Be[0]:Be[d];_!=null&&An(_,-10,-10,me,re)}}function is(d,g,_){zf(d,{min:g,max:_})}function hn(d,g,_,C){g.focus!=null&&dS(d),g.show!=null&&v.forEach((M,L)=>{L>0&&(d==L||d==null)&&(M.show=g.show,lS(L),n==2?(is(M.facets[0].scale,null,null),is(M.facets[1].scale,null,null)):is(M.scale,null,null),Ii())}),_!==!1&&br("setSeries",d,g),C&&ul("setSeries",o,d,g)}o.setSeries=hn;function cS(d,g){nr(O[d],g)}function uS(d,g){d.fill=Ke(d.fill||null),d.dir=nt(d.dir,-1),g=g??O.length,O.splice(g,0,d)}function pS(d){d==null?O.length=0:O.splice(d,1)}o.addBand=uS,o.setBand=cS,o.delBand=pS;function fS(d,g){v[d].alpha=g,oe&&Be[d]!=null&&(Be[d].style.opacity=g),te&&Pe[d]&&(Pe[d].style.opacity=g)}let $n,as,Ds,ji={focus:!0};function dS(d){if(d!=Ds){let g=d==null,_=ho.alpha!=1;v.forEach((C,M)=>{if(n==1||M>0){let L=g||M==0||M==d;C._focus=g?null:L,_&&fS(M,L?1:ho.alpha)}}),Ds=d,_&&Ii()}}te&&pe&&Ve(uP,fe,d=>{V._lock||(Mn(d),Ds!=null&&hn(null,ji,!0,Qt.setSeries))});function yn(d,g,_){let C=P[g];_&&(d=d/lt-(C.ori==1?_e:xe));let M=me;C.ori==1&&(M=re,d=M-d),C.dir==-1&&(d=M-d);let L=C._min,Z=C._max,q=d/M,X=L+(Z-L)*q,ae=C.distr;return ae==3?Ya(10,X):ae==4?V$(X,C.asinh):ae==100?C.bwd(X):X}function mS(d,g){let _=yn(d,E,g);return un(_,t[0],mr,hr)}o.valToIdx=d=>un(d,t[0]),o.posToIdx=mS,o.posToVal=yn,o.valToPos=(d,g,_)=>P[g].ori==0?s(d,P[g],_?bt:me,_?Pt:0):i(d,P[g],_?Fe:re,_?mt:0),o.setCursor=(d,g,_)=>{At=d.left,zt=d.top,Bs(null,g,_)};function Wy(d,g){Nt(Li,Ga,Mt.left=d),Nt(Li,hc,Mt.width=g)}function Hy(d,g){Nt(Li,"top",Mt.top=d),Nt(Li,yc,Mt.height=g)}let al=w.ori==0?Wy:Hy,ll=w.ori==1?Wy:Hy;function hS(){if(te&&F.live)for(let d=n==2?1:0;d<v.length;d++){if(d==0&&He)continue;let g=F.values[d],_=0;for(let C in g)We[d][_++].firstChild.nodeValue=g[C]}}function Lf(d,g){if(d!=null&&(d.idxs?d.idxs.forEach((_,C)=>{G[C]=_}):H$(d.idx)||G.fill(d.idx),F.idx=G[0]),te&&F.live){for(let _=0;_<v.length;_++)(_>0||n==1&&!He)&&yS(_,G[_]);hS()}Br=!1,g!==!1&&br("setLegend")}o.setLegend=Lf;function yS(d,g){let _=v[d],C=d==0&&$==2?Fo:t[d],M;He?M=_.values(o,d,g)??Ye:(M=_.value(o,g==null?null:C[g],d,g),M=M==null?Ye:{_:M}),F.values[d]=M}function Bs(d,g,_){Uy=At,Zy=zt,[At,zt]=V.move(o,At,zt),V.left=At,V.top=zt,oe&&(Ni&&An(Ni,ur(At),0,me,re),zi&&An(zi,0,ur(zt),me,re));let C,M=mr>hr;$n=Ct,as=null;let L=w.ori==0?me:re,Z=w.ori==1?me:re;if(At<0||Cr==0||M){C=V.idx=null;for(let q=0;q<v.length;q++){let X=Be[q];X!=null&&An(X,-10,-10,me,re)}pe&&hn(null,ji,!0,d==null&&Qt.setSeries),F.live&&(G.fill(C),Br=!0)}else{let q,X,ae;n==1&&(q=w.ori==0?At:zt,X=yn(q,E),C=V.idx=un(X,t[0],mr,hr),ae=h(t[0][C],w,L,0));let le=-10,de=-10,De=0,st=0,tt=!0,Ze="",Ae="";for(let ve=n==2?1:0;ve<v.length;ve++){let $t=v[ve],Wt=G[ve],xr=Wt==null?null:n==1?t[ve][Wt]:t[ve][1][Wt],xt=V.dataIdx(o,ve,C,X),Ht=xt==null?null:n==1?t[ve][xt]:t[ve][1][xt];if(Br=Br||Ht!=xr||xt!=Wt,G[ve]=xt,ve>0&&$t.show){let to=xt==null?-10:xt==C?ae:h(n==1?t[0][xt]:t[ve][0][xt],w,L,0),Lr=Ht==null?-10:z(Ht,n==1?P[$t.scale]:P[$t.facets[1].scale],Z,0);if(pe&&Ht!=null){let bo=w.ori==1?At:zt,Vo=pr(ho.dist(o,ve,xt,Lr,bo));if(Vo<$n){let gn=ho.bias;if(gn!=0){let ro=yn(bo,$t.scale),xo=Ht>=0?1:-1,Uo=ro>=0?1:-1;Uo==xo&&(Uo==1?gn==1?Ht>=ro:Ht<=ro:gn==1?Ht<=ro:Ht>=ro)&&($n=Vo,as=ve)}else $n=Vo,as=ve}}if(Br||ye){let bo,Vo;w.ori==0?(bo=to,Vo=Lr):(bo=Lr,Vo=to);let gn,ro,xo,Uo,bn,jr,oo=!0,Ls=dr.bbox;if(Ls!=null){oo=!1;let Fr=Ls(o,ve);xo=Fr.left,Uo=Fr.top,gn=Fr.width,ro=Fr.height}else xo=bo,Uo=Vo,gn=ro=dr.size(o,ve);if(jr=dr.fill(o,ve),bn=dr.stroke(o,ve),ye)ve==as&&$n<=ho.prox&&(le=xo,de=Uo,De=gn,st=ro,tt=oo,Ze=jr,Ae=bn);else{let Fr=Be[ve];Fr!=null&&(Ue[ve]=xo,_t[ve]=Uo,gP(Fr,gn,ro,oo),hP(Fr,jr,bn),An(Fr,Do(xo),Do(Uo),me,re))}}}}if(ye){let ve=ho.prox,$t=Ds==null?$n<=ve:$n>ve||as!=Ds;if(Br||$t){let Wt=Be[0];Wt!=null&&(Ue[0]=le,_t[0]=de,gP(Wt,De,st,tt),hP(Wt,Ze,Ae),An(Wt,Do(le),Do(de),me,re))}}}if(Mt.show&&ss)if(d!=null){let[q,X]=Qt.scales,[ae,le]=Qt.match,[de,De]=d.cursor.sync.scales,st=d.cursor.drag;if(yr=st._x,gr=st._y,yr||gr){let{left:tt,top:Ze,width:Ae,height:ve}=d.select,$t=d.scales[de].ori,Wt=d.posToVal,xr,xt,Ht,to,Lr,bo=q!=null&&ae(q,de),Vo=X!=null&&le(X,De);bo&&yr?($t==0?(xr=tt,xt=Ae):(xr=Ze,xt=ve),Ht=P[q],to=h(Wt(xr,de),Ht,L,0),Lr=h(Wt(xr+xt,de),Ht,L,0),al(pn(to,Lr),pr(Lr-to))):al(0,L),Vo&&gr?($t==1?(xr=tt,xt=Ae):(xr=Ze,xt=ve),Ht=P[X],to=z(Wt(xr,De),Ht,Z,0),Lr=z(Wt(xr+xt,De),Ht,Z,0),ll(pn(to,Lr),pr(Lr-to))):ll(0,Z)}else Vf()}else{let q=pr(Uy-Fy),X=pr(Zy-Vy);if(w.ori==1){let De=q;q=X,X=De}yr=Er.x&&q>=Er.dist,gr=Er.y&&X>=Er.dist;let ae=Er.uni;ae!=null?yr&&gr&&(yr=q>=ae,gr=X>=ae,!yr&&!gr&&(X>q?gr=!0:yr=!0)):Er.x&&Er.y&&(yr||gr)&&(yr=gr=!0);let le,de;yr&&(w.ori==0?(le=Di,de=At):(le=Bi,de=zt),al(pn(le,de),pr(de-le)),gr||ll(0,Z)),gr&&(w.ori==1?(le=Di,de=At):(le=Bi,de=zt),ll(pn(le,de),pr(de-le)),yr||al(0,L)),!yr&&!gr&&(al(0,0),ll(0,0))}if(Er._x=yr,Er._y=gr,d==null){if(_){if(og!=null){let[q,X]=Qt.scales;Qt.values[0]=q!=null?yn(w.ori==0?At:zt,q):null,Qt.values[1]=X!=null?yn(w.ori==1?At:zt,X):null}ul(Fh,o,At,zt,me,re,C)}if(pe){let q=_&&Qt.setSeries,X=ho.prox;Ds==null?$n<=X&&hn(as,ji,!0,q):$n>X?hn(null,ji,!0,q):as!=Ds&&hn(as,ji,!0,q)}}Br&&(F.idx=C,Lf()),g!==!1&&br("setCursor")}let ls=null;Object.defineProperty(o,"rect",{get(){return ls==null&&cl(!1),ls}});function cl(d=!1){d?ls=null:(ls=y.getBoundingClientRect(),br("syncRect",ls))}function Gy(d,g,_,C,M,L,Z){V._lock||ss&&d!=null&&d.movementX==0&&d.movementY==0||(jf(d,g,_,C,M,L,Z,!1,d!=null),d!=null?Bs(null,!0,!0):Bs(g,!0,!1))}function jf(d,g,_,C,M,L,Z,q,X){if(ls==null&&cl(!1),Mn(d),d!=null)_=d.clientX-ls.left,C=d.clientY-ls.top;else{if(_<0||C<0){At=-10,zt=-10;return}let[ae,le]=Qt.scales,de=g.cursor.sync,[De,st]=de.values,[tt,Ze]=de.scales,[Ae,ve]=Qt.match,$t=g.axes[0].side%2==1,Wt=w.ori==0?me:re,xr=w.ori==1?me:re,xt=$t?L:M,Ht=$t?M:L,to=$t?C:_,Lr=$t?_:C;if(tt!=null?_=Ae(ae,tt)?a(De,P[ae],Wt,0):-10:_=Wt*(to/xt),Ze!=null?C=ve(le,Ze)?a(st,P[le],xr,0):-10:C=xr*(Lr/Ht),w.ori==1){let bo=_;_=C,C=bo}}X&&(g==null||g.cursor.event.type==Fh)&&((_<=1||_>=me-1)&&(_=Ci(_,me)),(C<=1||C>=re-1)&&(C=Ci(C,re))),q?(Fy=_,Vy=C,[Di,Bi]=V.move(o,_,C)):(At=_,zt=C)}let Ff={width:0,height:0,left:0,top:0};function Vf(){Oc(Ff,!1)}let Ky,qy,Yy,Xy;function Jy(d,g,_,C,M,L,Z){ss=!0,yr=gr=Er._x=Er._y=!1,jf(d,g,_,C,M,L,Z,!0,!1),d!=null&&(Ve(Vh,Gh,Qy,!1),ul(lP,o,Di,Bi,me,re,null));let{left:q,top:X,width:ae,height:le}=Mt;Ky=q,qy=X,Yy=ae,Xy=le}function Qy(d,g,_,C,M,L,Z){ss=Er._x=Er._y=!1,jf(d,g,_,C,M,L,Z,!1,!0);let{left:q,top:X,width:ae,height:le}=Mt,de=ae>0||le>0,De=Ky!=q||qy!=X||Yy!=ae||Xy!=le;if(de&&De&&Oc(Mt),Er.setScale&&de&&De){let st=q,tt=ae,Ze=X,Ae=le;if(w.ori==1&&(st=X,tt=le,Ze=q,Ae=ae),yr&&is(E,yn(st,E),yn(st+tt,E)),gr)for(let ve in P){let $t=P[ve];ve!=E&&$t.from==null&&$t.min!=Ct&&is(ve,yn(Ze+Ae,ve),yn(Ze,ve))}Vf()}else V.lock&&(V._lock=!V._lock,Bs(g,!0,d!=null));d!=null&&(Tt(Vh,Gh),ul(Vh,o,At,zt,me,re,null))}function gS(d,g,_,C,M,L,Z){if(V._lock)return;Mn(d);let q=ss;if(ss){let X=!0,ae=!0,le=10,de,De;w.ori==0?(de=yr,De=gr):(de=gr,De=yr),de&&De&&(X=At<=le||At>=me-le,ae=zt<=le||zt>=re-le),de&&X&&(At=At<Di?0:me),De&&ae&&(zt=zt<Bi?0:re),Bs(null,!0,!0),ss=!1}At=-10,zt=-10,G.fill(null),Bs(null,!0,!0),q&&(ss=q)}function eg(d,g,_,C,M,L,Z){V._lock||(Mn(d),Sf(),Vf(),d!=null&&ul(pP,o,At,zt,me,re,null))}function tg(){R.forEach(lN),zs(o.width,o.height,!0)}ki(rf,qa,tg);let Fi={};Fi.mousedown=Jy,Fi.mousemove=Gy,Fi.mouseup=Qy,Fi.dblclick=eg,Fi.setSeries=(d,g,_,C)=>{let M=Qt.match[2];_=M(o,g,_),_!=-1&&hn(_,C,!0,!1)},oe&&(Ve(lP,y,Jy),Ve(Fh,y,Gy),Ve(cP,y,d=>{Mn(d),cl(!1)}),Ve(uP,y,gS),Ve(pP,y,eg),ty.add(o),o.syncRect=cl);let Ac=o.hooks=e.hooks||{};function br(d,g,_){Nf?il.push([d,g,_]):d in Ac&&Ac[d].forEach(C=>{C.call(null,o,g,_)})}(e.plugins||[]).forEach(d=>{for(let g in d.hooks)Ac[g]=(Ac[g]||[]).concat(d.hooks[g])});let rg=(d,g,_)=>_,Qt=nr({key:null,setSeries:!1,filters:{pub:PP,sub:PP},scales:[E,v[1]?v[1].scale:null],match:[_P,_P,rg],values:[null,null]},V.sync);Qt.match.length==2&&Qt.match.push(rg),V.sync=Qt;let og=Qt.key,Uf=x_(og);function ul(d,g,_,C,M,L,Z){Qt.filters.pub(d,g,_,C,M,L,Z)&&Uf.pub(d,g,_,C,M,L,Z)}Uf.sub(o);function bS(d,g,_,C,M,L,Z){Qt.filters.sub(d,g,_,C,M,L,Z)&&Fi[d](null,g,_,C,M,L,Z)}o.pub=bS;function xS(){Uf.unsub(o),ty.delete(o),Xe.clear(),Yh(rf,qa,tg),c.remove(),fe?.remove(),br("destroy")}o.destroy=xS;function Zf(){br("init",e,t),$y(t||e.data,!1),k[E]?zf(E,k[E]):Sf(),mn=Mt.show&&(Mt.width>0||Mt.height>0),mo=Br=!0,zs(e.width,e.height)}return v.forEach(go),R.forEach(X_),r?r instanceof HTMLElement?(r.appendChild(c),Zf()):r(o,Zf):Zf(),o}fr.assign=nr;fr.fmtNum=ly;fr.rangeNum=of;fr.rangeLog=af;fr.rangeAsinh=iy;fr.orient=Ai;fr.pxRatio=lt;fr.join=Q$;fr.fmtDate=uy,fr.tzDate=uI;fr.sync=x_;{fr.addGap=HI,fr.clipGaps=uf;let e=fr.paths={points:w_};e.linear=E_,e.stepped=qI,e.bars=YI,e.spline=JI}function gy(e){return e.reduce(([t,r],[o,n])=>[[...t,o],[...r,n]],[[],[]])}function mf(e){"@babel/helpers - typeof";return mf=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},mf(e)}var cN=/^\s+/,uN=/\s+$/;function ge(e,t){if(e=e||"",t=t||{},e instanceof ge)return e;if(!(this instanceof ge))return new ge(e,t);var r=pN(e);this._originalInput=e,this._r=r.r,this._g=r.g,this._b=r.b,this._a=r.a,this._roundA=Math.round(100*this._a)/100,this._format=t.format||r.format,this._gradientType=t.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=r.ok}ge.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(t.r*299+t.g*587+t.b*114)/1e3},getLuminance:function(){var t=this.toRgb(),r,o,n,s,i,a;return r=t.r/255,o=t.g/255,n=t.b/255,r<=.03928?s=r/12.92:s=Math.pow((r+.055)/1.055,2.4),o<=.03928?i=o/12.92:i=Math.pow((o+.055)/1.055,2.4),n<=.03928?a=n/12.92:a=Math.pow((n+.055)/1.055,2.4),.2126*s+.7152*i+.0722*a},setAlpha:function(t){return this._a=D_(t),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var t=M_(this._r,this._g,this._b);return{h:t.h*360,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=M_(this._r,this._g,this._b),r=Math.round(t.h*360),o=Math.round(t.s*100),n=Math.round(t.v*100);return this._a==1?"hsv("+r+", "+o+"%, "+n+"%)":"hsva("+r+", "+o+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=A_(this._r,this._g,this._b);return{h:t.h*360,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=A_(this._r,this._g,this._b),r=Math.round(t.h*360),o=Math.round(t.s*100),n=Math.round(t.l*100);return this._a==1?"hsl("+r+", "+o+"%, "+n+"%)":"hsla("+r+", "+o+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return $_(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return hN(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return this._a==1?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(Ft(this._r,255)*100)+"%",g:Math.round(Ft(this._g,255)*100)+"%",b:Math.round(Ft(this._b,255)*100)+"%",a:this._a}},toPercentageRgbString:function(){return this._a==1?"rgb("+Math.round(Ft(this._r,255)*100)+"%, "+Math.round(Ft(this._g,255)*100)+"%, "+Math.round(Ft(this._b,255)*100)+"%)":"rgba("+Math.round(Ft(this._r,255)*100)+"%, "+Math.round(Ft(this._g,255)*100)+"%, "+Math.round(Ft(this._b,255)*100)+"%, "+this._roundA+")"},toName:function(){return this._a===0?"transparent":this._a<1?!1:EN[$_(this._r,this._g,this._b,!0)]||!1},toFilter:function(t){var r="#"+I_(this._r,this._g,this._b,this._a),o=r,n=this._gradientType?"GradientType = 1, ":"";if(t){var s=ge(t);o="#"+I_(s._r,s._g,s._b,s._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+r+",endColorstr="+o+")"},toString:function(t){var r=!!t;t=t||this._format;var o=!1,n=this._a<1&&this._a>=0,s=!r&&n&&(t==="hex"||t==="hex6"||t==="hex3"||t==="hex4"||t==="hex8"||t==="name");return s?t==="name"&&this._a===0?this.toName():this.toRgbString():(t==="rgb"&&(o=this.toRgbString()),t==="prgb"&&(o=this.toPercentageRgbString()),(t==="hex"||t==="hex6")&&(o=this.toHexString()),t==="hex3"&&(o=this.toHexString(!0)),t==="hex4"&&(o=this.toHex8String(!0)),t==="hex8"&&(o=this.toHex8String()),t==="name"&&(o=this.toName()),t==="hsl"&&(o=this.toHslString()),t==="hsv"&&(o=this.toHsvString()),o||this.toHexString())},clone:function(){return ge(this.toString())},_applyModification:function(t,r){var o=t.apply(null,[this].concat([].slice.call(r)));return this._r=o._r,this._g=o._g,this._b=o._b,this.setAlpha(o._a),this},lighten:function(){return this._applyModification(xN,arguments)},brighten:function(){return this._applyModification(vN,arguments)},darken:function(){return this._applyModification(TN,arguments)},desaturate:function(){return this._applyModification(yN,arguments)},saturate:function(){return this._applyModification(gN,arguments)},greyscale:function(){return this._applyModification(bN,arguments)},spin:function(){return this._applyModification(PN,arguments)},_applyCombination:function(t,r){return t.apply(null,[this].concat([].slice.call(r)))},analogous:function(){return this._applyCombination(wN,arguments)},complement:function(){return this._applyCombination(_N,arguments)},monochromatic:function(){return this._applyCombination(CN,arguments)},splitcomplement:function(){return this._applyCombination(SN,arguments)},triad:function(){return this._applyCombination(N_,[3])},tetrad:function(){return this._applyCombination(N_,[4])}};ge.fromRatio=function(e,t){if(mf(e)=="object"){var r={};for(var o in e)e.hasOwnProperty(o)&&(o==="a"?r[o]=e[o]:r[o]=Tc(e[o]));e=r}return ge(e,t)};function pN(e){var t={r:0,g:0,b:0},r=1,o=null,n=null,s=null,i=!1,a=!1;return typeof e=="string"&&(e=AN(e)),mf(e)=="object"&&(es(e.r)&&es(e.g)&&es(e.b)?(t=fN(e.r,e.g,e.b),i=!0,a=String(e.r).substr(-1)==="%"?"prgb":"rgb"):es(e.h)&&es(e.s)&&es(e.v)?(o=Tc(e.s),n=Tc(e.v),t=mN(e.h,o,n),i=!0,a="hsv"):es(e.h)&&es(e.s)&&es(e.l)&&(o=Tc(e.s),s=Tc(e.l),t=dN(e.h,o,s),i=!0,a="hsl"),e.hasOwnProperty("a")&&(r=e.a)),r=D_(r),{ok:i,format:e.format||a,r:Math.min(255,Math.max(t.r,0)),g:Math.min(255,Math.max(t.g,0)),b:Math.min(255,Math.max(t.b,0)),a:r}}function fN(e,t,r){return{r:Ft(e,255)*255,g:Ft(t,255)*255,b:Ft(r,255)*255}}function A_(e,t,r){e=Ft(e,255),t=Ft(t,255),r=Ft(r,255);var o=Math.max(e,t,r),n=Math.min(e,t,r),s,i,a=(o+n)/2;if(o==n)s=i=0;else{var l=o-n;switch(i=a>.5?l/(2-o-n):l/(o+n),o){case e:s=(t-r)/l+(t<r?6:0);break;case t:s=(r-e)/l+2;break;case r:s=(e-t)/l+4;break}s/=6}return{h:s,s:i,l:a}}function dN(e,t,r){var o,n,s;e=Ft(e,360),t=Ft(t,100),r=Ft(r,100);function i(c,u,f){return f<0&&(f+=1),f>1&&(f-=1),f<1/6?c+(u-c)*6*f:f<1/2?u:f<2/3?c+(u-c)*(2/3-f)*6:c}if(t===0)o=n=s=r;else{var a=r<.5?r*(1+t):r+t-r*t,l=2*r-a;o=i(l,a,e+1/3),n=i(l,a,e),s=i(l,a,e-1/3)}return{r:o*255,g:n*255,b:s*255}}function M_(e,t,r){e=Ft(e,255),t=Ft(t,255),r=Ft(r,255);var o=Math.max(e,t,r),n=Math.min(e,t,r),s,i,a=o,l=o-n;if(i=o===0?0:l/o,o==n)s=0;else{switch(o){case e:s=(t-r)/l+(t<r?6:0);break;case t:s=(r-e)/l+2;break;case r:s=(e-t)/l+4;break}s/=6}return{h:s,s:i,v:a}}function mN(e,t,r){e=Ft(e,360)*6,t=Ft(t,100),r=Ft(r,100);var o=Math.floor(e),n=e-o,s=r*(1-t),i=r*(1-n*t),a=r*(1-(1-n)*t),l=o%6,c=[r,i,s,s,a,r][l],u=[a,r,r,i,s,s][l],f=[s,s,a,r,r,i][l];return{r:c*255,g:u*255,b:f*255}}function $_(e,t,r,o){var n=[dn(Math.round(e).toString(16)),dn(Math.round(t).toString(16)),dn(Math.round(r).toString(16))];return o&&n[0].charAt(0)==n[0].charAt(1)&&n[1].charAt(0)==n[1].charAt(1)&&n[2].charAt(0)==n[2].charAt(1)?n[0].charAt(0)+n[1].charAt(0)+n[2].charAt(0):n.join("")}function hN(e,t,r,o,n){var s=[dn(Math.round(e).toString(16)),dn(Math.round(t).toString(16)),dn(Math.round(r).toString(16)),dn(B_(o))];return n&&s[0].charAt(0)==s[0].charAt(1)&&s[1].charAt(0)==s[1].charAt(1)&&s[2].charAt(0)==s[2].charAt(1)&&s[3].charAt(0)==s[3].charAt(1)?s[0].charAt(0)+s[1].charAt(0)+s[2].charAt(0)+s[3].charAt(0):s.join("")}function I_(e,t,r,o){var n=[dn(B_(o)),dn(Math.round(e).toString(16)),dn(Math.round(t).toString(16)),dn(Math.round(r).toString(16))];return n.join("")}ge.equals=function(e,t){return!e||!t?!1:ge(e).toRgbString()==ge(t).toRgbString()};ge.random=function(){return ge.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})};function yN(e,t){t=t===0?0:t||10;var r=ge(e).toHsl();return r.s-=t/100,r.s=hf(r.s),ge(r)}function gN(e,t){t=t===0?0:t||10;var r=ge(e).toHsl();return r.s+=t/100,r.s=hf(r.s),ge(r)}function bN(e){return ge(e).desaturate(100)}function xN(e,t){t=t===0?0:t||10;var r=ge(e).toHsl();return r.l+=t/100,r.l=hf(r.l),ge(r)}function vN(e,t){t=t===0?0:t||10;var r=ge(e).toRgb();return r.r=Math.max(0,Math.min(255,r.r-Math.round(255*-(t/100)))),r.g=Math.max(0,Math.min(255,r.g-Math.round(255*-(t/100)))),r.b=Math.max(0,Math.min(255,r.b-Math.round(255*-(t/100)))),ge(r)}function TN(e,t){t=t===0?0:t||10;var r=ge(e).toHsl();return r.l-=t/100,r.l=hf(r.l),ge(r)}function PN(e,t){var r=ge(e).toHsl(),o=(r.h+t)%360;return r.h=o<0?360+o:o,ge(r)}function _N(e){var t=ge(e).toHsl();return t.h=(t.h+180)%360,ge(t)}function N_(e,t){if(isNaN(t)||t<=0)throw new Error("Argument to polyad must be a positive number");for(var r=ge(e).toHsl(),o=[ge(e)],n=360/t,s=1;s<t;s++)o.push(ge({h:(r.h+s*n)%360,s:r.s,l:r.l}));return o}function SN(e){var t=ge(e).toHsl(),r=t.h;return[ge(e),ge({h:(r+72)%360,s:t.s,l:t.l}),ge({h:(r+216)%360,s:t.s,l:t.l})]}function wN(e,t,r){t=t||6,r=r||30;var o=ge(e).toHsl(),n=360/r,s=[ge(e)];for(o.h=(o.h-(n*t>>1)+720)%360;--t;)o.h=(o.h+n)%360,s.push(ge(o));return s}function CN(e,t){t=t||6;for(var r=ge(e).toHsv(),o=r.h,n=r.s,s=r.v,i=[],a=1/t;t--;)i.push(ge({h:o,s:n,v:s})),s=(s+a)%1;return i}ge.mix=function(e,t,r){r=r===0?0:r||50;var o=ge(e).toRgb(),n=ge(t).toRgb(),s=r/100,i={r:(n.r-o.r)*s+o.r,g:(n.g-o.g)*s+o.g,b:(n.b-o.b)*s+o.b,a:(n.a-o.a)*s+o.a};return ge(i)};ge.readability=function(e,t){var r=ge(e),o=ge(t);return(Math.max(r.getLuminance(),o.getLuminance())+.05)/(Math.min(r.getLuminance(),o.getLuminance())+.05)};ge.isReadable=function(e,t,r){var o=ge.readability(e,t),n,s;switch(s=!1,n=MN(r),n.level+n.size){case"AAsmall":case"AAAlarge":s=o>=4.5;break;case"AAlarge":s=o>=3;break;case"AAAsmall":s=o>=7;break}return s};ge.mostReadable=function(e,t,r){var o=null,n=0,s,i,a,l;r=r||{},i=r.includeFallbackColors,a=r.level,l=r.size;for(var c=0;c<t.length;c++)s=ge.readability(e,t[c]),s>n&&(n=s,o=ge(t[c]));return ge.isReadable(e,o,{level:a,size:l})||!i?o:(r.includeFallbackColors=!1,ge.mostReadable(e,["#fff","#000"],r))};var by=ge.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},EN=ge.hexNames=RN(by);function RN(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[e[r]]=r);return t}function D_(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function Ft(e,t){kN(e)&&(e="100%");var r=ON(e);return e=Math.min(t,Math.max(0,parseFloat(e))),r&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function hf(e){return Math.min(1,Math.max(0,e))}function fo(e){return parseInt(e,16)}function kN(e){return typeof e=="string"&&e.indexOf(".")!=-1&&parseFloat(e)===1}function ON(e){return typeof e=="string"&&e.indexOf("%")!=-1}function dn(e){return e.length==1?"0"+e:""+e}function Tc(e){return e<=1&&(e=e*100+"%"),e}function B_(e){return Math.round(parseFloat(e)*255).toString(16)}function z_(e){return fo(e)/255}var fn=(function(){var e="[-\\+]?\\d+%?",t="[-\\+]?\\d*\\.\\d+%?",r="(?:"+t+")|(?:"+e+")",o="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?",n="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?";return{CSS_UNIT:new RegExp(r),rgb:new RegExp("rgb"+o),rgba:new RegExp("rgba"+n),hsl:new RegExp("hsl"+o),hsla:new RegExp("hsla"+n),hsv:new RegExp("hsv"+o),hsva:new RegExp("hsva"+n),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}})();function es(e){return!!fn.CSS_UNIT.exec(e)}function AN(e){e=e.replace(cN,"").replace(uN,"").toLowerCase();var t=!1;if(by[e])e=by[e],t=!0;else if(e=="transparent")return{r:0,g:0,b:0,a:0,format:"name"};var r;return(r=fn.rgb.exec(e))?{r:r[1],g:r[2],b:r[3]}:(r=fn.rgba.exec(e))?{r:r[1],g:r[2],b:r[3],a:r[4]}:(r=fn.hsl.exec(e))?{h:r[1],s:r[2],l:r[3]}:(r=fn.hsla.exec(e))?{h:r[1],s:r[2],l:r[3],a:r[4]}:(r=fn.hsv.exec(e))?{h:r[1],s:r[2],v:r[3]}:(r=fn.hsva.exec(e))?{h:r[1],s:r[2],v:r[3],a:r[4]}:(r=fn.hex8.exec(e))?{r:fo(r[1]),g:fo(r[2]),b:fo(r[3]),a:z_(r[4]),format:t?"name":"hex8"}:(r=fn.hex6.exec(e))?{r:fo(r[1]),g:fo(r[2]),b:fo(r[3]),format:t?"name":"hex"}:(r=fn.hex4.exec(e))?{r:fo(r[1]+""+r[1]),g:fo(r[2]+""+r[2]),b:fo(r[3]+""+r[3]),a:z_(r[4]+""+r[4]),format:t?"name":"hex8"}:(r=fn.hex3.exec(e))?{r:fo(r[1]+""+r[1]),g:fo(r[2]+""+r[2]),b:fo(r[3]+""+r[3]),format:t?"name":"hex"}:!1}function MN(e){var t,r;return e=e||{level:"AA",size:"small"},t=(e.level||"AA").toUpperCase(),r=(e.size||"small").toLowerCase(),t!=="AA"&&t!=="AAA"&&(t="AA"),r!=="small"&&r!=="large"&&(r="small"),{level:t,size:r}}var $N=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],IN=(e,t)=>ge(e).lighten(t).toString(),NN=(e,t)=>ge(e).darken(t).toString(),zN=[[],[1,1],[10,10],[20,5]],xy=zN.flatMap(e=>$N.map(t=>({stroke:t,dash:e}))),DN=[...xy,...xy.map(({stroke:e,dash:t})=>({stroke:IN(e,20),dash:t})),...xy.map(({stroke:e,dash:t})=>({stroke:NN(e,20),dash:t}))],L_=DN;function vy(e,t){let r=t.reduce((o,n)=>o===void 0?n.length:Math.min(o,n.length),void 0)??0;return Array.apply(null,new Array(r)).map((o,n)=>e(t.map(s=>s[n])))}function Ty(e){return e.reduce((t,r)=>t+r,0)}function Py(e,t){return e==="system"?t:e}function BN(e,t){let r=Math.floor(Math.max(0,Math.log10(Math.abs(e))))+1,o=Math.max(0,t-r),n=e.toFixed(o);return o<=0?n:n.replace(/\.?0+$/,"")}var LN=["B","KB","MB","GB","TB","PB","EB","ZB","YB","RB","QB"].entries().map(([e,t])=>[1e3**e,t]).toArray().reverse(),jN=e=>{if(e===null)return"--";{let t=Math.abs(e);for(let[r,o]of LN)if(t>=r)return`${BN(e/r,3)} ${o}`;return`${e} B`}},j_=jN;K();var Pc=Je({cursorSync:!0,cursorSyncPubSub:null,toggleCursorSync:()=>{}});function _y({children:e}){let[t,r]=ie(!0),o=fr.sync(xn()),n=()=>r(!t);return b(Pc.Provider,{value:{cursorSync:t,cursorSyncPubSub:o,toggleCursorSync:n},children:e})}var FN=e=>j_,VN=e=>({value:(t,r,o,n)=>{if(r!==null)return e(r);let s=t.data[o];n===null&&(n=s.length-1);let i=t.data[0][n];for(;n>=0;--n){let a=s[n]??null;if(a!==null)return e(a);let l=t.data[0][n];if(i-l>1)break}return"--"}}),UN=([e,t])=>Math.max(...t.filter(r=>r!=null)),Sy=e=>vy(t=>Ty(t.filter(r=>r!==null)),e);function ol(e){return e===void 0?[]:[e]}var ZN={x:{time:!0},y:{time:!1}},F_=(e,t)=>e===t,WN=e=>e!==null?{sync:{key:e.key,match:[F_,F_]}}:{};function ts({name:e,validateAttrs:t,getSeriesLabel:r,getSeriesOptions:o,unit:n,seriesLimit:s,seriesPriority:i=UN,seriesStyle:a=L_,totalSeries:l,otherSeries:c,options:u}){let{mode:f,systemMode:m}=fT(),p=J(Py(f,m)),y=J(u),x=n&&FN(n),T=x?VN(x):{},S=x?{size:75,values:(G,F)=>F.map(V=>x(V))}:{},{lastExportRequest:v}=Se(gs),{refresh:R}=Se(xl),{cursorSync:P,cursorSyncPubSub:O}=Se(Pc);ce(()=>{k.current!==null&&O!==null&&(P?O.sub(k.current):O.unsub(k.current))},[P]);let E=J([...a]),A=J([[]]),I=J([{}]),N=J({}),D=Ee(()=>{let[G,...F]=I.current,[V,...te]=A.current;if(s!==void 0&&F.length>s){let[oe,Y]=gy(F.entries().map(([We,qe])=>[qe,te[We]]).toArray().toSorted((We,qe)=>i(qe)-i(We))),fe=oe.slice(0,s),se=Y.slice(0,s),be=c&&Sy(Y.slice(s+1)),Pe=l&&Sy(be?[be,...se]:Y);return[[G,...ol(l),...fe,...ol(c)],[V,...ol(Pe),...se,...ol(be)]]}else{let oe=l&&Sy(te);return[[G,...ol(l),...F],[V,...ol(oe),...te]]}},[s]),w=Ee((G,F)=>{let V=I.current.length;return N.current[G]=V,I.current[V]=o(G,F),A.current[V]=new Array(A.current[0].length).fill(null),V},[]),$=Ee(G=>{let F=G.stroke===void 0?E.current.shift():{};return{...G,...F,...T}},[]),h=Ee(G=>typeof G=="string"||typeof G=="function"||G instanceof CanvasGradient||G instanceof CanvasPattern?G:p.current==="dark"?G?.dark??"#fff":G?.light??"#000",[]),z=Ee((G,F)=>({...F>0?S:{},...G,stroke:h(G.stroke)}),[]),k=J(null),j=J(null),B=xn(),W=Ee(([[G,...F],V])=>{if(k.current!==null)return;document.getElementById(B)?.remove();let te=[G,...F.map($)],Y=(u.axes??new Array(2).fill({})).map(z);k.current=new fr({...u,cursor:{...u.cursor??{},...WN(O)},scales:ZN,series:te,axes:Y},V,j.current)},[z,$]),H=Ee(()=>{k.current!==null&&(k.current.destroy(),k.current=null,E.current=[...a])},[]),ee=Ee(G=>{let F=D();if(k.current===null)G&&W(F);else{let[[V,...te],oe]=F,[Y,...fe]=k.current.series,se=te.find((be,Pe)=>be.label!==fe.at(Pe)?.label);if(se===void 0)k.current.setData(oe);else if(se===fe.length-1){for(let be=fe.length;be<te.length;++be)k.current.addSeries($(te[be]),be+1);k.current.setData(oe)}else H(),W(F)}},[D,$,W,H]);return ce(()=>{if(k.current===null)return;let{width:G,height:F}=y.current,{width:V,height:te}=u;(V!==G||te!==F)&&(k.current.setSize({width:V,height:te}),y.current=u)},[u.width,u.height]),ce(()=>{let G=p.current,F=Py(f,m);G!==F&&(p.current=F,H(),ee())},[ee,H,f,m]),ce(()=>{if(v===null)return;let G=v.telemetry[e];if(G==null)return;let F=G.xValues,V=[];G.series.forEach(({attrs:se,yValues:be})=>{if(t(se)){let Pe=r(se),We=N.current[Pe]??w(Pe,se);V[We-1]=be}else console.warn(`Unexpected attrs for series ${e} `,se)});let[te,...oe]=A.current,Y=[...te,...G.xValues],fe=[];for(let se=0;se<I.current.length-1;++se){let be=se in oe?oe[se]:new Array(te.length).fill(null),Pe=se in V?V[se]:new Array(F.length).fill(null);fe[se]=[...be,...Pe]}A.current=[Y,...fe],R&&ee(!0)},[v,R,w,W,H]),ce(()=>()=>{H()},[]),b(Xn,{sx:{display:"flex",justifyContent:"center",alignItems:"center",marginBottom:"1rem"},children:b("div",{ref:j,children:b(Xn,{id:B,children:[u.title&&b("div",{className:"u-title",children:u.title}),b(Xn,{sx:{width:u.width,height:u.height},children:b(_r,{sx:{textAlign:"center"},children:"Waiting for data..."})})]})})})}K();K();K();K();var V_=Je(null);function HN(){let[e,t]=ie(null);return ce(()=>{t(`mui-p-${Math.round(Math.random()*1e5)}`)},[]),e}function _c(e){let{children:t,value:r}=e,o=HN(),n=Le(()=>({idPrefix:o,value:r}),[o,r]);return b(V_.Provider,{value:n,children:t})}function yf(){return Se(V_)}function gf(e,t){let{idPrefix:r}=e;return r===null?null:`${e.idPrefix}-P-${t}`}function bf(e,t){let{idPrefix:r}=e;return r===null?null:`${e.idPrefix}-T-${t}`}K();var GN=ue(function(t,r){let{children:o,...n}=t,s=yf();if(s===null)throw new TypeError("No TabContext provided");let i=zn.map(o,a=>Rt(a)?vr(a,{"aria-controls":gf(s,a.props.value),id:bf(s,a.props.value)}):null);return b(Dh,{...n,ref:r,value:s.value,children:i})}),xf=GN;K();function U_(e){return we("MuiTabPanel",e)}var Rce=Ce("MuiTabPanel",["root","hidden"]);var KN=e=>{let{classes:t,hidden:r}=e;return ke({root:["root",r&&"hidden"]},U_,t)},qN=ne("div",{name:"MuiTabPanel",slot:"Root"})(({theme:e})=>({padding:e.spacing(3)})),YN=ue(function(t,r){let o=Up({props:t,name:"MuiTabPanel"}),{children:n,className:s,value:i,keepMounted:a=!1,...l}=o,c={...o},u=KN(c),f=yf();if(f===null)throw new TypeError("No TabContext provided");let m=gf(f,i),p=bf(f,i);return b(qN,{"aria-labelledby":p,className:he(u.root,s),hidden:i!==f.value,id:m,ref:r,role:"tabpanel",ownerState:c,...l,children:(a||i===f.value)&&n})}),vf=YN;var wy=Je({name:Gs.UNKNOWN_SERVICE_NAME,instanceId:Gs.UNKNOWN_SERVICE_INSTANCE_ID});function XN({name:e,children:t}){let{lastExportRequest:r}=Se(gs),[o,n]=ie({}),[s,i]=ie(null),a=(l,c)=>i(c);return ce(()=>{if(r===null)return;let{resource:l}=r;if(So(Ld,l)){if(e!==Gs.name(l))return;let c=Gs.instanceId(l);n(u=>({...u,[c]:r})),s===null&&i(c)}else console.warn("Unexpected resource ",l)},[r]),s===null?b(_r,{children:"Waiting for data..."}):b(_c,{value:s,children:[b(xf,{onChange:a,variant:"scrollable",scrollButtons:"auto","aria-label":"Tabs for the service instances",sx:{borderBottom:1,borderColor:"divider"},children:Object.keys(o).map(l=>b(Yp,{label:l,value:l}))}),Object.entries(o).map(([l,c])=>b(vf,{value:l,keepMounted:!0,sx:{paddingLeft:0,paddingRight:0},children:b(wy.Provider,{value:{name:e,instanceId:l},children:b(gs.Provider,{value:{lastExportRequest:c},children:t})})}))]})}var JN="eventlog-live-for-";function Cy({children:e}){let{lastExportRequest:t}=Se(gs),[r,o]=ie({}),[n,s]=ie(null),i=(a,l)=>s(l);return ce(()=>{if(t===null)return;let{resource:a}=t;if(So(Ld,a)){let l=Gs.name(a);if(l.startsWith(JN))return;o(c=>({...c,[l]:t})),n===null&&s(l)}else console.warn("Unexpected resource ",a)},[t]),n===null?b(_r,{children:"Waiting for data..."}):b(_c,{value:n,children:[b(xf,{onChange:i,variant:"scrollable",scrollButtons:"auto","aria-label":"Tabs for the services",sx:{borderBottom:1,borderColor:"divider"},children:Object.keys(r).map(a=>b(Yp,{label:a,value:a}))}),Object.entries(r).map(([a,l])=>b(vf,{value:a,keepMounted:!0,sx:{paddingTop:0,paddingLeft:0,paddingRight:0},children:b(gs.Provider,{value:{lastExportRequest:l},children:b(XN,{name:a,children:e})})}))]})}function Ey(){return typeof IS_DEVELOPMENT=="boolean"&&IS_DEVELOPMENT?"http://localhost:30179":`http://${window.location.host}`}function Sc(e){let{label:t,title:r,namespace:o,commandId:n,...s}=e,{onSend:i="Request sent.",onReceive:a="Request received."}=e.feedback??{},l=Se(wy),[c,u]=ie(null),f=async p=>{u({severity:"info",message:i});let y=new URL(`/control/${o}/${n}`,Ey());if((await fetch(y,{method:"POST",headers:new Headers({"content-type":"application/x-www-form-urlencoded"}),mode:"no-cors",body:`service-name=${l.name}`})).type==="opaque"){u({severity:"info",message:a});return}},m=async(p,y)=>{u(null)};return b(Ie,{children:[b($o,{title:r,children:b(_h,{onClick:f,disabled:c!==null,...s,children:t})}),b(Mh,{open:c!==null,autoHideDuration:5e3,onClose:m,children:b(Th,{severity:c?.severity??"info",variant:"filled",onClose:m,sx:{width:"100%"},children:c?.message})})]})}K();var QN=e=>{let t="The maximum number of series to display in this plot.",r=e&&` Additional series are summarised under ${e}.`;return t+(r??"")};function Ry(e){let{otherLabel:t,setSeriesLimit:r,id:o,sx:n,...s}=e,i=l=>{let{value:c}=l.target,u=parseInt(c);Number.isNaN(u)?console.log("Invalid value for series limit: ",c):r(u)},a=o??xn();return b(Xn,{sx:{display:"flex",alignItems:"baseline",columnGap:1},children:[b(_r,{children:"Series\xA0Limit"}),b($o,{title:QN(t),children:b(Ch,{disableUnderline:!0,type:"number",margin:"dense",sx:{...n??{},width:"2.5em"},onChange:i,id:a,...s})})]})}var ez=Vr({name:Rr("heapProfSample"),heapProfBreakdown:Rr("-hT"),heapProfId:Rr(0),heapProfLabel:$r(),heapProfSampleEra:Ir()}),tz=Vr({name:Rr("heapProfSample"),heapProfBreakdown:Rr("-hi"),heapProfId:Rr(0),heapProfLabel:$r(),heapProfSampleEra:Ir(),ipClosureDesc:Ir(),ipLabel:$r(),ipModule:$r(),ipName:$r(),ipSrcLoc:$r(),ipTyDesc:$r()}),rz=yu([ez,tz]),oz=e=>e.heapProfBreakdown==="-hT"?e.heapProfLabel:`${e.ipModule}:${e.ipLabel}`,nz=(e,t)=>{if(t.heapProfBreakdown==="-hT")return{label:e,spanGaps:!0};{let o=document.createElement("span");return o.innerText=e,o.title=t.ipSrcLoc,{label:o,spanGaps:!0}}};function Z_(e){let t=ir(),r=Bh(t.breakpoints.up("lg")),o=Bh(t.breakpoints.up("xl")),n=e.size??(()=>[600,400]),[s,i]=ie(n(r,o)),a={label:"Total"},l={label:"Other"},[c,u]=ie(e.seriesLimit??10);return ce(()=>i(n(r,o)),[r,o]),b(Ie,{children:[b(dc,{disableGutters:!0,variant:"dense",sx:{flexGrow:1,justifyContent:"center"},children:b(Ar,{container:!0,columns:10,sx:{width:s[0],alignItems:"center"},children:[b(Ar,{size:4,sx:{display:"flex",justifyContent:"left"},children:b(Ry,{defaultValue:c,otherLabel:l.label,setSeriesLimit:u})},0),b(Ar,{size:2,sx:{textAlign:"center"},children:b("div",{className:"u-title",children:"Heap\xA0Profile"})},2),b(Ar,{size:4,container:!0,columns:3,sx:{display:"flex",justifyContent:"right"},children:[b(Ar,{size:1,sx:{display:"flex",justifyContent:"center"},children:b(Sc,{label:"Start",title:"Start heap profiling.",namespace:"eventlog-socket",commandId:"start-heap-profiling"})},31),b(Ar,{size:1,sx:{display:"flex",justifyContent:"center"},children:b(Sc,{label:"Stop",title:"Stop heap profiling.",namespace:"eventlog-socket",commandId:"stop-heap-profiling"})},32),b(Ar,{size:1,sx:{display:"flex",justifyContent:"center"},children:b(Sc,{label:"Census",title:"Request a single heap census.",namespace:"eventlog-socket",commandId:"request-heap-census"})},33)]},3)]})}),b(ts,{name:"heapProfSample",validateAttrs:f=>So(rz,f),getSeriesLabel:oz,getSeriesOptions:nz,unit:"By",seriesLimit:c,totalSeries:a,otherSeries:l,options:{width:s[0],height:s[1],...e.options??{}}})]})}var sz=Vr({name:yu([Rr("heapSize"),Rr("blocksSize"),Rr("heapLive")]),capNo:Ir()}),W_=e=>b(ts,{name:"heapSize",validateAttrs:t=>So(sz,t),getSeriesLabel:t=>`${iz(t.name)} (cap ${t.capNo})`,getSeriesOptions:t=>({label:t,spanGaps:!0}),unit:"By",options:{title:"Heap Size",width:600,height:400,...e.options??{}}}),iz=e=>e.charAt(0).toUpperCase()+e.slice(1).replaceAll(/([A-Z]+)/g," $1");var az=Vr({name:Rr("gcCopied"),capNo:Ir(),gen:Ir()}),H_=e=>b(ts,{name:"gcCopied",validateAttrs:t=>So(az,t),getSeriesLabel:t=>`GC Copied (cap ${t.capNo}, gen ${t.gen})`,getSeriesOptions:t=>({label:t,spanGaps:!0}),unit:"By",options:{title:"GC Copied",width:600,height:400,...e.options??{}}}),lz=Vr({name:Rr("gcSlop"),capNo:Ir(),gen:Ir()}),G_=e=>b(ts,{name:"gcSlop",validateAttrs:t=>So(lz,t),getSeriesLabel:t=>`GC Slop (cap ${t.capNo}, gen ${t.gen})`,getSeriesOptions:t=>({label:t,spanGaps:!0}),unit:"By",options:{title:"GC Slop",width:600,height:400,...e.options??{}}}),cz=Vr({name:Rr("gcFragmentation"),capNo:Ir(),gen:Ir()}),K_=e=>b(ts,{name:"gcFragmentation",validateAttrs:t=>So(cz,t),getSeriesLabel:t=>`GC Fragmentation (cap ${t.capNo}, gen ${t.gen})`,getSeriesOptions:t=>({label:t,spanGaps:!0}),unit:"By",options:{title:"GC Fragmentation",width:600,height:400,...e.options??{}}});K();var pz=e=>b("svg",{width:24,height:24,viewBox:"0 0 24 24",id:"eventlog-live-logo",xmlSpace:"preserve",xmlns:"http://www.w3.org/2000/svg",...e,children:[b("style",{children:`+		circle.magnifying-glass {+			stroke: #333;+			stroke-width: 2;+			fill: none;+		}+		rect.magnifying-glass {+			fill: #333;+		}+        @media (prefers-color-scheme: dark) {+			circle.magnifying-glass {+				stroke: #a1af79;+			}+			rect.magnifying-glass {+				fill: #a1af79;+			}+        }+    `}),b("defs",{children:[b("path",{id:"greater",d:"M 0 0 L 4.25 0 L 8.5 9 L 4.25 18 L 0 18 L 4.25 9 Z"}),b("path",{id:"lambda",d:"M 0 0 L 4.25 0 L 8.5 9 L 12.75 18 L 9 18 L 6.375 12.5 L 4.25 18 L 0 18 L 4.25 9 Z"}),b("g",{id:"equals",children:[b("rect",{x:0,y:0,width:10,height:3.75}),b("rect",{x:0,y:4.75,width:10,height:3.75})]}),b("mask",{id:"lambda_mask",children:[b("rect",{width:"100%",height:"100%",fill:"white"}),b("use",{style:{fill:"black"},href:"#lambda",x:-4.5,y:-4})]}),b("use",{id:"masked_equals",mask:"url(#lambda_mask)",href:"#equals"}),b("mask",{id:"lens_mask",children:[b("radialGradient",{id:"grad",cx:"50%",cy:"50%",r:"50%",fx:"50%",fy:"50%",children:[b("stop",{offset:"0%",stopColor:"white"}),b("stop",{offset:"100%",stopColor:"black"})]}),b("circle",{style:{fill:"url(#grad)"},id:"lens",cx:12.5,cy:8.5,r:12}),b("circle",{style:{fill:"white"},id:"lens",cx:12.5,cy:8.5,r:8.5})]})]}),b("g",{transform:"rotate(45, 12, 12) translate(0, 3.5)",children:[b("g",{transform:"translate(-0.75,0)",mask:"url(#lens_mask)",children:[b("use",{style:{fill:"#453a62"},href:"#greater",x:2.75,y:-.5}),b("use",{style:{fill:"#5e5086"},href:"#lambda",x:8,y:-.5}),b("use",{style:{fill:"#8f4e8b"},href:"#masked_equals",x:13.5,y:4})]}),b("circle",{className:"magnifying-glass",id:"lens",cx:12,cy:8.5,r:8.5}),b("rect",{className:"magnifying-glass",x:20,y:7.25,width:6,height:2,rx:.5,ry:.5})]})]}),q_=pz;var fz=kt(b(q_,{}),"EventlogLive"),Y_=fz;function ky(){return typeof IS_DEVELOPMENT=="boolean"&&IS_DEVELOPMENT?"ws://localhost:30179":`ws://${window.location.host}`}K();function Oy(e){let t=Se(Pc);return b(Ie,{children:[b($o,{sx:{display:{xs:"none",sm:"inherit"}},title:"Synchonize the cursor position and view between all plots.",children:b(ec,{checked:t.cursorSync,onChange:t.toggleCursorSync,...e})}),b(_r,{sx:{display:{xs:"none",md:"inherit"}},children:"Cursor\xA0"}),b(_r,{sx:{display:{xs:"none",sm:"inherit"},marginRight:1},children:"Sync"})]})}var dz=(e,t)=>t?[1200,800]:e?[900,600]:[600,400],mz=ne("div")(({theme:e})=>e.mixins.toolbar);function Ay(){let e={init:[t=>{t.root.classList.add("u-stacked-legend")}]};return b(_d,{url:ky(),children:b(jd,{children:b(Fd,{children:b(_y,{children:b(yh,{maxWidth:"xl",children:[b(Ph,{color:"default",position:"fixed",children:b(dc,{variant:"dense",children:[b(Y_,{sx:[{fontSize:"2.35em",marginRight:1,marginBottom:"0.22em"}]}),b(_r,{variant:"h4",sx:{display:{xs:"none",sm:"inherit"}},children:"Eventlog\xA0Live"}),b(Xn,{sx:{flexGrow:1}}),b(Oy,{}),b(ah,{}),b(Lh,{})]})}),b(mz,{}),b(Cy,{children:b(Ar,{container:!0,spacing:0,columns:{xs:1,md:2},sx:{justifyContent:"center",alignItems:"start"},children:[b(Ar,{size:1,children:b(Z_,{size:dz,options:{hooks:e}})}),b(Ar,{size:1,container:!0,spacing:0,columns:{xs:1,xl:2},sx:{justifyContent:"center",alignItems:"start"},children:[b(Ar,{size:1,children:b(W_,{options:{hooks:e}})}),b(Ar,{size:1,children:b(H_,{options:{hooks:e}})}),b(Ar,{size:1,children:b(G_,{options:{hooks:e}})}),b(Ar,{size:1,children:b(K_,{options:{hooks:e}})})]})]})})]})})})})})}var hz=kn({colorSchemes:{dark:!0},breakpoints:{values:{xs:0,sm:650,md:1250,lg:1850,xl:2450}}}),yz=Yg(document.getElementById("app"));yz.render(b(Zp,{theme:hz,children:[b(Hp,{}),b(Ay,{})]}));typeof IS_DEVELOPMENT=="boolean"&&IS_DEVELOPMENT&&new EventSource("/esbuild").addEventListener("change",()=>location.reload());})();+/*! Bundled license information:++react-is/cjs/react-is.production.js:+  (**+   * @license React+   * react-is.production.js+   *+   * Copyright (c) Meta Platforms, Inc. and affiliates.+   *+   * This source code is licensed under the MIT license found in the+   * LICENSE file in the root directory of this source tree.+   *)++react-is/cjs/react-is.production.min.js:+  (** @license React v16.13.1+   * react-is.production.min.js+   *+   * Copyright (c) Facebook, Inc. and its affiliates.+   *+   * This source code is licensed under the MIT license found in the+   * LICENSE file in the root directory of this source tree.+   *)++@mui/styled-engine/index.mjs:+  (**+   * @mui/styled-engine v9.5.0+   *+   * @license MIT+   * This source code is licensed under the MIT license found in the+   * LICENSE file in the root directory of this source tree.+   *)++@mui/private-theming/index.mjs:+  (**+   * @mui/private-theming v9.5.0+   *+   * @license MIT+   * This source code is licensed under the MIT license found in the+   * LICENSE file in the root directory of this source tree.+   *)++@mui/system/index.mjs:+  (**+   * @mui/system v9.5.0+   *+   * @license MIT+   * This source code is licensed under the MIT license found in the+   * LICENSE file in the root directory of this source tree.+   *)++@mui/material/index.mjs:+  (**+   * @mui/material v9.5.0+   *+   * @license MIT+   * This source code is licensed under the MIT license found in the+   * LICENSE file in the root directory of this source tree.+   *)+*/
+ data/viewer/manifest.webmanifest view
@@ -0,0 +1,13 @@+{+  "name": "Eventlog Live",+  "icons": [+    { "src": "/icon-192.png", "type": "image/png", "sizes": "192x192" },+    {+      "src": "/icon-mask.png",+      "type": "image/png",+      "sizes": "512x512",+      "purpose": "maskable"+    },+    { "src": "/icon-512.png", "type": "image/png", "sizes": "512x512" }+  ]+}
eventlog-live.cabal view
@@ -1,72 +1,115 @@-cabal-version:   3.0-name:            eventlog-live-version:         0.4.0.0-synopsis:        Live processing of eventlog data.-description:-  This package supports live processing of eventlog data.-  It consists of three libraries:--  *   The @eventlog-live@ library defines-      [machines](https://hackage.haskell.org/package/machines)-      for processing eventlog data.-  *   The @eventlog-live:options@ sub-library defines-      [optparse-applicative](https://hackage.haskell.org/package/optparse-applicative)-      parsers for common command-line arguments.-  *   The @eventlog-live:socket@ sub-library defines functions to read the-      eventlog from a Unix socket, which depend on the-      [network](https://hackage.haskell.org/package/network) package.--  This package is primarily intended for use via the-  [eventlog-live-influxdb](https://hackage.haskell.org/package/eventlog-live-influxdb)-  and-  [eventlog-live-otelcol](https://hackage.haskell.org/package/eventlog-live-otelcol)-  packages.--  [⚠️ Warning]:-      This package is experimental.-      It is versioned according to the [PVP](https://pvp.haskell.org).-      However, breaking changes should be expected and no effort will be-      made to avoid major version bumps until at least version @1.0.0.0@.+cabal-version: 3.0+name: eventlog-live+version: 0.11.0.0+synopsis: Real-time monitoring for any Haskell application with little to no instrumentation+description: Real-time monitoring for any Haskell application with little to no instrumentation!+license: BSD-3-Clause+license-file: LICENSE+author: Wen Kokke+maintainer: wen@well-typed.com+copyright: (c) 2021-2026 Well-Typed+build-type: Simple+category: Debug, Monitoring, System+extra-doc-files:+  CHANGELOG.md+  README.md -  For more information, see [the README](https://github.com/well-typed/eventlog-live#readme).+extra-source-files:+  data/config.schema.json+  data/default.yaml+  data/help.footer.txt+  data/help.header.txt+  data/help.progDesc.txt+  data/viewer/apple-touch-icon.png+  data/viewer/favicon.ico+  data/viewer/icon-192.png+  data/viewer/icon-512.png+  data/viewer/icon-mask.png+  data/viewer/icon.svg+  data/viewer/index.css+  data/viewer/index.html+  data/viewer/index.js+  data/viewer/manifest.webmanifest -license:         BSD-3-Clause-license-file:    LICENSE-author:          Wen Kokke-maintainer:      wen@well-typed.com-copyright:       (c) 2021-2025 Well-Typed-build-type:      Simple-category:        Debug, Monitoring, System-extra-doc-files: CHANGELOG.md tested-with:-  GHC ==9.2.8-   || ==9.4.8-   || ==9.6.7-   || ==9.8.4-   || ==9.10.2-   || ==9.12.2+  ghc ==9.6.7 || ==9.8.4 || ==9.10.3 || ==9.12.4  source-repository head-  type:     git+  type: git   location: https://github.com/well-typed/eventlog-live.git-  subdir:   eventlog-live+  subdir: eventlog-live +source-repository this+  type: git+  location: https://github.com/well-typed/eventlog-live.git+  tag: eventlog-live-v0.11.0.0+  subdir: eventlog-live++-- This flag enables the control command server, which is an HTTP endpoint+-- that gets started by eventlog-live. If +control is set, then+-- eventlog-socket SHOULD also be compiled with +control. If this flag is+-- set at compile-time, the control server can be enabled at runtime.+flag control+  description: Enable control command server.+  default: False+  manual: True++-- 2026-07-29:+-- This flag should enable switching between hs-opentelemetry-api and the+-- vendored copy of the packages, as only a small subset is needed.+flag use-hs-opentelemetry-api+  description: Use hs-opentelemetry-api in place of the vendored copy+  default: False+  manual: True++-- 2026-04-02:+-- This flag should enable switching the use of eventlog-socket on+-- and off, since it may cause issues with certain versions of GHC.+flag use-eventlog-socket+  description: Use eventlog-socket+  default: False+  manual: True++-- 2025-11-10:+-- This flag should enable switching the use of ghc-debug-stub on+-- and off, since it may cause issues with certain versions of GHC.+-- See https://github.com/well-typed/eventlog-live/issues/88+flag use-ghc-debug-stub+  description: Use ghc-debug-stub+  default: False+  manual: True++-- 2026-10-12:+-- This flag should enable switching the use of ghc-stack-profiler on+-- and off, since it may cause issues with certain versions of GHC.+flag use-ghc-stack-profiler+  description: Use use-ghc-stack-profiler+  default: False+  manual: True+ common language   ghc-options:-    -Wall -Wcompat -Widentities -Wprepositive-qualified-module-    -Wredundant-constraints -Wunticked-promoted-constructors+    -Wall+    -Wcompat+    -Widentities+    -Wprepositive-qualified-module+    -Wredundant-constraints+    -Wunticked-promoted-constructors     -Wunused-packages -  default-language:   Haskell2010+  default-language: Haskell2010   default-extensions:     BangPatterns     ConstraintKinds     DataKinds+    DefaultSignatures     DeriveFoldable     DeriveFunctor     DeriveGeneric+    DeriveLift     DeriveTraversable     DerivingStrategies+    DerivingVia     DuplicateRecordFields     FlexibleContexts     FlexibleInstances@@ -82,45 +125,228 @@     NoFieldSelectors     NumericUnderscores     OverloadedRecordDot+    PatternSynonyms+    PolyKinds     RankNTypes     RecordWildCards     ScopedTypeVariables     StandaloneDeriving+    StandaloneKindSignatures     TupleSections     TypeApplications     TypeFamilies+    TypeOperators+    ViewPatterns  library-  import:          language-  hs-source-dirs:  src+  import: language+  hs-source-dirs:+    src-lib+   exposed-modules:-    GHC.Eventlog.Live.Data.Attribute-    GHC.Eventlog.Live.Data.Group-    GHC.Eventlog.Live.Data.Metric-    GHC.Eventlog.Live.Data.Span+    GHC.Eventlog.Live.Config     GHC.Eventlog.Live.Logger     GHC.Eventlog.Live.Machine.Analysis.Capability     GHC.Eventlog.Live.Machine.Analysis.Heap+    GHC.Eventlog.Live.Machine.Analysis.Log+    GHC.Eventlog.Live.Machine.Analysis.Profile     GHC.Eventlog.Live.Machine.Analysis.Thread     GHC.Eventlog.Live.Machine.Core     GHC.Eventlog.Live.Machine.Decoder     GHC.Eventlog.Live.Machine.Sink     GHC.Eventlog.Live.Machine.Source+    GHC.Eventlog.Live.Machine.Validate     GHC.Eventlog.Live.Machine.WithStartTime     GHC.Eventlog.Live.Options-    GHC.Eventlog.Live.Socket-    GHC.Eventlog.Live.Verbosity+    GHC.Eventlog.Live.Processor+    GHC.Eventlog.Live.Processor.Core+    GHC.Eventlog.Live.Source+    GHC.Eventlog.Live.Source.Core+    GHC.Eventlog.Live.Types.Attribute+    GHC.Eventlog.Live.Types.Capability+    GHC.Eventlog.Live.Types.Group+    GHC.Eventlog.Live.Types.HeapProfBreakdown+    GHC.Eventlog.Live.Types.Logs+    GHC.Eventlog.Live.Types.Metrics+    GHC.Eventlog.Live.Types.Profiles+    GHC.Eventlog.Live.Types.Severity+    GHC.Eventlog.Live.Types.Thread+    GHC.Eventlog.Live.Types.Traces +  other-modules:+    GHC.Eventlog.Live.Config.Default+    GHC.Eventlog.Live.Config.Default.Raw+    GHC.Eventlog.Live.Config.Types+    GHC.Eventlog.Live.Processor.Core.Logs+    GHC.Eventlog.Live.Processor.Core.Metrics+    GHC.Eventlog.Live.Processor.Core.Traces+    GHC.Eventlog.Live.Processor.Heap+    GHC.Eventlog.Live.Processor.Logs+    GHC.Eventlog.Live.Processor.Profiles+    GHC.Eventlog.Live.Processor.Threads+   build-depends:-    , ansi-terminal         >=1.1    && <1.2-    , base                  >=4.16   && <4.22-    , bytestring            >=0.11   && <0.13-    , dlist                 >=1.0    && <1.1-    , ghc-events            >=0.20   && <0.21-    , hashable              >=1.4    && <1.6-    , machines              >=0.7.4  && <0.8-    , network               >=3.2.7  && <3.3-    , optparse-applicative  >=0.17   && <0.20-    , text                  >=1.2    && <2.2-    , unliftio-core         >=0.2.1  && <0.3-    , unordered-containers  >=0.2.20 && <0.3+    aeson >=2.2 && <2.3,+    ansi-terminal >=1.1 && <1.2,+    base >=4.16 && <5,+    base64 >=1.0 && <1.1,+    bytestring >=0.11 && <0.13,+    clock >=0.8 && <0.9,+    co-log-core >=0.3 && <0.4,+    containers >=0.6 && <0.9,+    data-default >=0.2 && <0.9,+    dlist >=1.0 && <1.1,+    file-embed >=0.0.16 && <0.1,+    ghc-events >=0.20 && <0.21,+    ghc-stack-profiler-core ==0.5.0.0,+    hashable >=1.4 && <1.6,+    HsYAML >=0.2 && <0.3,+    ipedb >=0.2 && <0.3,+    lossy-chan >=0.2 && <0.3,+    machines >=0.7.4 && <0.8,+    network >=3.2.7 && <3.3,+    optparse-applicative >=0.17 && <0.20,+    random >=1.2 && <1.4,+    template-haskell-lift >=0.1 && <0.2,+    text >=1.2 && <2.2,+    transformers >=0.2 && <0.7,+    unordered-containers >=0.2.20 && <0.3,+    vector >=0.12.2 && <0.14,++  -- 2026-09-29:+  -- This includes a backport of uniformByteString.+  hs-source-dirs:+    src-compat++  other-modules:+    System.Random.Compat++  -- 2026-07-17:+  -- This includes a vendored copy of mapAccumM from the base-compat+  -- package version 0.15.0.+  hs-source-dirs:+    vendor/base-compat-0.15.0++  other-modules:+    Data.Traversable.Compat++executable eventlog-live+  import: language+  main-is: eventlog-live.hs+  hs-source-dirs:+    app++  ghc-options:+    -threaded+    -rtsopts+    -finfo-table-map++  hs-source-dirs:+    src-app++  other-modules:+    GHC.Eventlog.Live.App+    GHC.Eventlog.Live.App.Environment+    GHC.Eventlog.Live.App.Exporter.Otlp+    GHC.Eventlog.Live.App.Exporter.Otlp.Core+    GHC.Eventlog.Live.App.Exporter.Otlp.Logs+    GHC.Eventlog.Live.App.Exporter.Otlp.Metrics+    GHC.Eventlog.Live.App.Exporter.Otlp.Profiles+    GHC.Eventlog.Live.App.Exporter.Otlp.ProfilesDictionary+    GHC.Eventlog.Live.App.Exporter.Otlp.SymbolTable+    GHC.Eventlog.Live.App.Exporter.Otlp.Traces+    GHC.Eventlog.Live.App.Options+    GHC.Eventlog.Live.App.Options.Raw+    GHC.Eventlog.Live.App.Server+    GHC.Eventlog.Live.App.Server.Control+    GHC.Eventlog.Live.App.Server.Viewer+    GHC.Eventlog.Live.App.Server.Viewer.AlignedData+    GHC.Eventlog.Live.App.Server.Viewer.Embedded++  hs-source-dirs:+    src-app-internal++  other-modules:+    GHC.Debug.Stub.Compat+    GHC.Eventlog.Socket.Compat+    GHC.Stack.Profiler.Compat+    Options.Applicative.Compat+    Options.Applicative.Extra.Feature+    Paths_eventlog_live++  autogen-modules: Paths_eventlog_live+  build-depends:+    aeson >=2.2 && <2.3,+    base >=4.16 && <5,+    base64 >=1.0 && <1.1,+    bytestring >=0.11 && <0.13,+    case-insensitive >=1.2 && <1.3,+    containers >=0.6 && <0.9,+    cryptohash-md5 >=0.11 && <0.12,+    data-default >=0.2 && <0.9,+    dlist >=1.0 && <1.1,+    eventlog-live,+    fast-logger >=3.0 && <3.3,+    file-embed >=0.0.16 && <0.1,+    ghc-events >=0.20 && <0.21,+    grapesy >=1.0.0 && <1.2,+    hashable >=1.4 && <1.6,+    hs-opentelemetry-otlp >=0.2.0 && <0.3,+    http-api-data >=0.6 && <0.7,+    http-client >=0.7 && <0.8,+    http-client-tls >=0.3.5 && <0.4,+    http-media >=0.8 && <0.9,+    http-types >=0.12 && <0.13,+    ipedb >=0.2.0.1 && <0.3,+    lens-family >=2.1.3 && <2.2,+    lossy-chan >=0.2 && <0.3,+    machines >=0.7.4 && <0.8,+    network-uri >=2.6 && <2.8,+    open-browser >=0.2 && <0.6,+    optparse-applicative >=0.17 && <0.20,+    proto-lens >=0.7.1 && <0.8,+    servant >=0.20 && <0.21,+    servant-server >=0.20 && <0.21,+    template-haskell-lift >=0.1 && <0.2,+    text >=1.2 && <2.2,+    transformers >=0.2 && <0.7,+    unordered-containers >=0.2.20 && <0.3,+    vector >=0.11 && <0.14,+    wai >=3.2 && <3.3,+    wai-app-static >=3 && <3.3,+    wai-cors >=0.2 && <0.3,+    wai-extra >=3.1 && <3.2,+    wai-websockets >=3 && <3.1,+    warp >=3.4 && <3.5,+    websockets >=0.13 && <0.15,+    zlib >=0.2 && <0.8,++  if flag(control)+    build-depends:+      binary >=0.8 && <0.9,+      eventlog-socket-control >=0.1.1 && <0.2,+      network >=3.2.7 && <3.3,++    cpp-options: -DEVENTLOG_LIVE_FEATURE_CONTROL++  if flag(use-eventlog-socket)+    build-depends: eventlog-socket >=0.1.2 && <0.2+    cpp-options: -DEVENTLOG_LIVE_USE_EVENTLOG_SOCKET++  if flag(use-ghc-debug-stub)+    build-depends: ghc-debug-stub >=0.1 && <1+    cpp-options: -DEVENTLOG_LIVE_USE_GHC_DEBUG_STUB++  if flag(use-ghc-stack-profiler)+    build-depends: ghc-stack-profiler ==0.5.0.0+    cpp-options: -DEVENTLOG_LIVE_USE_GHC_STACK_PROFILER++  -- 2026-07-29:+  -- This configures the build requirements for the vendored copy of+  -- the hs-opentelemetry-api package version 1.0.0.0.+  if flag(use-hs-opentelemetry-api)+    build-depends: hs-opentelemetry-api >=1.0.0.0 && <1.1+  else+    build-depends: template-haskell+    hs-source-dirs: vendor/hs-opentelemetry-api-1.0.0.0/src+    other-modules: OpenTelemetry.Baggage
+ src-app-internal/GHC/Debug/Stub/Compat.hs view
@@ -0,0 +1,118 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Debug.Stub.Compat+Description : The implementation of @eventlog-live@.+Stability   : experimental+Portability : portable+-}+module GHC.Debug.Stub.Compat (+  MyGhcDebugSocket (..),+  withMyGhcDebug,+  maybeMyGhcDebugSocketParser,+) where++import Control.Applicative (asum)+import GHC.Eventlog.Live.Logger (Logger)+import Options.Applicative qualified as O+import Options.Applicative.Extra.Feature (Feature (..))+import Options.Applicative.Extra.Feature qualified as OF++#ifdef EVENTLOG_LIVE_USE_GHC_DEBUG_STUB+import Data.Text qualified as T+import GHC.Debug.Stub qualified as GHC.Debug (withGhcDebug, withGhcDebugTCP, withGhcDebugUnix)+import Text.Read (readEither)+import GHC.Eventlog.Live.Logger (logInfo, logFatal)+#else+import Data.Maybe (isJust)+import Control.Monad (when)+#endif++--------------------------------------------------------------------------------+-- Feature: use-ghc-debug-stub+--------------------------------------------------------------------------------++useGhcDebugStub :: Feature+useGhcDebugStub = Feature{flag = "use-ghc-debug-stub", isOn = isOn, info = "Cannot open ghc-debug socket."}+ where+  isOn :: Bool+#ifdef EVENTLOG_LIVE_USE_GHC_DEBUG_STUB+  isOn = True+#else+  isOn = False+#endif++--------------------------------------------------------------------------------+-- My GHC Debug+--------------------------------------------------------------------------------++data MyGhcDebugSocket+  = MyGhcDebugSocketDefault+  | MyGhcDebugSocketUnix FilePath+  | MyGhcDebugSocketTcp String+  deriving (Show)++{- |+Internal helper.+Start @ghc-debug@ on the given `MyGhcDebugSocket`.+-}+withMyGhcDebug :: Logger IO -> Maybe MyGhcDebugSocket -> IO a -> IO a+#ifdef EVENTLOG_LIVE_USE_GHC_DEBUG_STUB+withMyGhcDebug logger maybeMyGhcDebugSocket action =+  case maybeMyGhcDebugSocket of+    Nothing -> action+    Just MyGhcDebugSocketDefault -> do+      logInfo logger $+        "Start ghc-debug with default socket."+      GHC.Debug.withGhcDebug action+    Just (MyGhcDebugSocketUnix myGhcDebugSocketUnix) -> do+      logInfo logger $+        "Start ghc-debug with Unix domain socket at " <> T.pack myGhcDebugSocketUnix <> "."+      GHC.Debug.withGhcDebugUnix myGhcDebugSocketUnix action+    Just (MyGhcDebugSocketTcp myGhcDebugSocketTcp) -> do+      let (host, port) = break (== ':') myGhcDebugSocketTcp+      logInfo logger $+        "Start ghc-debug with TCP/IP socket at " <> T.pack host <> ":" <> T.pack port <> "."+      case readEither port of+        Left _parseError -> do+          logFatal logger $+            T.pack $ "Could not parse ghc-debug TCP address " <> myGhcDebugSocketTcp <> "."+        Right portWord16 ->+          GHC.Debug.withGhcDebugTCP host portWord16 action+#else+withMyGhcDebug logger maybeMyGhcDebugSocket action = do+  when (isJust maybeMyGhcDebugSocket) $+    OF.exitIfUnsupported useGhcDebugStub logger+  action+#endif++--------------------------------------------------------------------------------+-- My GHC Debug++maybeMyGhcDebugSocketParser :: O.Parser (Maybe MyGhcDebugSocket)+maybeMyGhcDebugSocketParser =+  asum $+    [ myGhcDebugSocketDefaultParser+    , myGhcDebugSocketUnixParser+    , myGhcDebugSocketTcpParser+    , pure Nothing+    ]++myGhcDebugSocketDefaultParser :: O.Parser (Maybe MyGhcDebugSocket)+myGhcDebugSocketDefaultParser =+  OF.onlyFor useGhcDebugStub (O.flag' $ Just MyGhcDebugSocketDefault) mempty $+    O.long "my-ghc-debug-socket"+      <> OF.helpFor useGhcDebugStub "Open the default ghc-debug socket for this program."++myGhcDebugSocketUnixParser :: O.Parser (Maybe MyGhcDebugSocket)+myGhcDebugSocketUnixParser =+  OF.onlyFor useGhcDebugStub (O.option (Just . MyGhcDebugSocketUnix <$> O.str)) (O.metavar "FILE") $+    O.long "my-ghc-debug-socket-unix"+      <> OF.helpFor useGhcDebugStub "Open a ghc-debug Unix domain socket with the given file path."++myGhcDebugSocketTcpParser :: O.Parser (Maybe MyGhcDebugSocket)+myGhcDebugSocketTcpParser =+  OF.onlyFor useGhcDebugStub (O.option (Just . MyGhcDebugSocketTcp <$> O.str)) (O.metavar "ADDRESS") $+    O.long "my-ghc-debug-socket-tcp"+      <> OF.helpFor useGhcDebugStub "Open a ghc-debug TCP/IP socket with the given address as 'host:port'."
+ src-app-internal/GHC/Eventlog/Socket/Compat.hs view
@@ -0,0 +1,82 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Socket.Compat+Description : The implementation of @eventlog-live@.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Socket.Compat (+  MyEventlogSocket (..),+  maybeMyEventlogSocketParser,+  startMyEventlogSocket,+) where++import Control.Applicative (asum)+import GHC.Eventlog.Live.Logger (Logger)+import Options.Applicative qualified as O+import Options.Applicative.Extra.Feature (Feature (..))+import Options.Applicative.Extra.Feature qualified as OF++#ifdef EVENTLOG_LIVE_USE_EVENTLOG_SOCKET+import Data.Foldable (for_)+import Data.Text qualified as T+import GHC.Eventlog.Live.Types.Severity (Severity (..))+import GHC.Eventlog.Live.Logger (logInfo)+import GHC.Eventlog.Socket qualified as Eventlog.Socket+#else+import Control.Monad (when)+import Data.Maybe (isJust)+#endif++--------------------------------------------------------------------------------+-- Feature: use-eventlog-socket+--------------------------------------------------------------------------------++useEventlogSocket :: Feature+useEventlogSocket = Feature{flag = "use-eventlog-socket", isOn = isOn, info = "Cannot open eventlog socket."}+ where+  isOn :: Bool+#ifdef EVENTLOG_LIVE_USE_EVENTLOG_SOCKET+  isOn = True+#else+  isOn = False+#endif++--------------------------------------------------------------------------------+-- My Eventlog Socket+--------------------------------------------------------------------------------++newtype MyEventlogSocket+  = MyEventlogSocketUnix FilePath++maybeMyEventlogSocketParser :: O.Parser (Maybe MyEventlogSocket)+maybeMyEventlogSocketParser =+  asum $+    [ myEventlogSocketUnixParser+    , pure Nothing+    ]++myEventlogSocketUnixParser :: O.Parser (Maybe MyEventlogSocket)+myEventlogSocketUnixParser =+  OF.onlyFor useEventlogSocket (O.option (Just . MyEventlogSocketUnix <$> O.str)) (O.metavar "FILE") $+    O.long "my-eventlog-socket-unix"+      <> OF.helpFor useEventlogSocket "Open an eventlog socket for this program on the given Unix socket."++{- |+Set @eventlog-socket@ as the eventlog writer.+-}+startMyEventlogSocket :: Logger IO -> Maybe MyEventlogSocket -> IO ()+#ifdef EVENTLOG_LIVE_USE_EVENTLOG_SOCKET+startMyEventlogSocket logger maybeMyEventlogSocket =+  for_ maybeMyEventlogSocket $ \case+    MyEventlogSocketUnix myEventlogSocketUnix -> do+      logInfo logger $+        "Start eventlog-socket with Unix domain socket at " <> T.pack myEventlogSocketUnix <> "."+      Eventlog.Socket.startWait myEventlogSocketUnix+#else+startMyEventlogSocket logger maybeMyEventlogSocket =+  when (isJust maybeMyEventlogSocket) $+    OF.exitIfUnsupported useEventlogSocket logger+#endif
+ src-app-internal/GHC/Stack/Profiler/Compat.hs view
@@ -0,0 +1,29 @@+{-# LANGUAGE CPP #-}++{- |+Module      : GHC.Stack.Profiler.Compat+Description : The implementation of @eventlog-live@.+Stability   : experimental+Portability : portable+-}+module GHC.Stack.Profiler.Compat (+  withGhcStackProfiler,+) where++#ifdef EVENTLOG_LIVE_USE_GHC_STACK_PROFILER+import GHC.Stack.Profiler (withProfilerFromEnv)+#endif++--------------------------------------------------------------------------------+-- My Eventlog Socket+--------------------------------------------------------------------------------++{- |+Set @ghc-stack-profiler@ as the eventlog writer.+-}+withGhcStackProfiler :: IO () -> IO ()+#ifdef EVENTLOG_LIVE_USE_GHC_STACK_PROFILER+withGhcStackProfiler action = withProfilerFromEnv $ const action+#else+withGhcStackProfiler action = action+#endif
+ src-app-internal/Options/Applicative/Compat.hs view
@@ -0,0 +1,34 @@+{-# LANGUAGE CPP #-}++module Options.Applicative.Compat (+  parserOptionGroup,+  simpleVersioner,+) where++#if MIN_VERSION_optparse_applicative(0,19,0)+import Options.Applicative (parserOptionGroup)+import Options.Applicative (simpleVersioner)+#else+#if MIN_VERSION_optparse_applicative(0,18,1)+import Options.Applicative (simpleVersioner)+#else+import Options.Applicative (infoOption, long, help, hidden)+#endif+import Options.Applicative (Parser)+#endif++#if MIN_VERSION_optparse_applicative(0,19,0)+#else+-- Prior to optparse-applicative-0.19.0.0, option groups were not supported,+-- so this definition simply drops the group.+parserOptionGroup :: String -> Parser a -> Parser a+parserOptionGroup _ p = p+#if MIN_VERSION_optparse_applicative(0,18,1)+#else+-- Prior to optparse-applicative-0.18.1.0, simpleVersioner was not defined,+-- so this definition is taken verbatim from optparse-applicative-0.18.1.0.+simpleVersioner :: String -> Parser (a -> a)+simpleVersioner version = infoOption version $+  mconcat [long "version", help "Show version information", hidden]+#endif+#endif
+ src-app-internal/Options/Applicative/Extra/Feature.hs view
@@ -0,0 +1,59 @@+{-# LANGUAGE OverloadedStrings #-}++module Options.Applicative.Extra.Feature (+  Feature (..),+  helpFor,+  onlyFor,+  exitIfUnsupported,+) where++import Control.Monad (unless)+import Data.Default (Default (..))+import Data.Text (Text)+import Data.Text qualified as T+import GHC.Eventlog.Live.Logger (Logger, logFatal)+import Options.Applicative qualified as O+import Options.Applicative.Help.Pretty qualified as OP++data Feature = Feature+  { flag :: !String+  , isOn :: !Bool+  , info :: !String+  }++{- |+Create a command-line help document for an option that depend on a feature flag.+-}+helpFor :: Feature -> String -> O.Mod f a+helpFor feature help+  | feature.isOn = O.help help+  | otherwise = O.helpDoc (Just $ OP.vcat [OP.pretty unsupported, OP.pretty help]) <> O.hidden+ where+  unsupported :: Text+  unsupported = T.pack "Unsupported. Requires build with -f+" <> T.pack feature.flag <> "."++{- |+Create a command-line option that depends on a feature flag.+-}+onlyFor ::+  forall f a.+  (O.HasName f, Default a) =>+  Feature ->+  (O.Mod f a -> O.Parser a) ->+  O.Mod f a ->+  (forall g x. (O.HasName g) => O.Mod g x) ->+  O.Parser a+onlyFor feature opt optIfSupported optAlways+  | feature.isOn = opt (optAlways <> optIfSupported)+  | otherwise = def <$ O.infoOption unsupportedInfo optAlways+ where+  unsupportedInfo :: String+  unsupportedInfo = feature.info <> " Requires build with -f+" <> feature.flag <> "."++{- |+Exit with the feature info.+-}+exitIfUnsupported :: Feature -> Logger IO -> IO ()+exitIfUnsupported feature logger =+  unless feature.isOn $ do+    logFatal logger (T.pack feature.info)
+ src-app/GHC/Eventlog/Live/App.hs view
@@ -0,0 +1,295 @@+{-# LANGUAGE OverloadedLists #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.App+Description : The implementation of @eventlog-live@.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.App (+  main,+) where++import Control.Concurrent (ThreadId, forkIO)+import Control.Concurrent.Chan (newChan)+import Control.Concurrent.LossyChan qualified as LC+import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, readMVar)+import Control.Exception (SomeException, bracket_, catch, finally)+import Control.Monad.IO.Class (MonadIO (..))+import Control.Monad.Trans.Class (MonadTrans (..))+import Control.Monad.Trans.Except (runExceptT)+import Data.DList qualified as D+import Data.Default (Default (..))+import Data.Foldable (for_)+import Data.Machine (ProcessT, asParts, await, mapping, repeatedly, runT_, stopped, (~>))+import Data.Maybe (fromMaybe, isNothing)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Void (Void, absurd)+import GHC.Debug.Stub.Compat (withMyGhcDebug)+import GHC.Eventlog.Live.App.Environment (OpenTelemetrySdkOptions (..), ServiceName (..), lookupLogLevel, lookupOpenTelemetrySdkOptions)+import GHC.Eventlog.Live.App.Exporter.Otlp (exportToOtlp)+import GHC.Eventlog.Live.App.Exporter.Otlp.Core (withExporters)+import GHC.Eventlog.Live.App.Options (MyDebugOptions (..), OpenTelemetryOptions (openTelemetryExporter), Options (..), options)+import GHC.Eventlog.Live.App.Server (ControlHooks (..), ServerHandle (..), startServer)+import GHC.Eventlog.Live.Config (FullConfig (..))+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Logger (InternalMetric (..), Logger, chanLogger, chanSource, filterBySeverity, logDebug, logException, logFatal, logInfo, logMetric, logTick, lossyChanSource, mkStderrLogger, withScope)+import GHC.Eventlog.Live.Machine.Core (Tick (..), dropTick, onlyTick)+import GHC.Eventlog.Live.Machine.Core qualified as M+import GHC.Eventlog.Live.Machine.Validate (validateInput)+import GHC.Eventlog.Live.Machine.WithStartTime qualified as M+import GHC.Eventlog.Live.Processor (InstrumentationScope (..), Resource (..), processEventlogTelemetry, processInternalTelemetry)+import GHC.Eventlog.Live.Source (runWithEventlogSourceHandle, withEventlogSourceHandle)+import GHC.Eventlog.Live.Types.Attribute (AttrValue (..), (~=))+import GHC.Eventlog.Socket.Compat (startMyEventlogSocket)+import GHC.IsList (IsList (..))+import GHC.RTS.Events (Event (..))+import GHC.Stack.Profiler.Compat (withGhcStackProfiler)+import IpeDB.Database qualified as DB+import IpeDB.Types.CostCentre qualified as CC+import IpeDB.Types.InfoProv qualified as IP+import Options.Applicative qualified as O+import Paths_eventlog_live qualified as App+import System.Exit (die)++--------------------------------------------------------------------------------+-- Instrumentation Scope+--------------------------------------------------------------------------------++-- 2025-09-22:+-- Once `cabal2nix` supports Cabal 3.12, this can once again use the value from:+-- `PackageInfo_eventlog_live.name`.+appName :: Text+appName = "eventlog-live"++appScope :: InstrumentationScope+appScope = InstrumentationScope{name = appName, version = App.version}++{- |+The main function for @eventlog-live@.+-}+main :: IO ()+main =+  withGhcStackProfiler $ do+    -- Parse the command-line options+    Options{..} <- O.execParser options++    -- Create a queue for internal telemetry+    internalTelemetryQueue <- newChan++    -- Create a queue for export requests+    (exportRequestInChan, exportRequestOutChan) <- LC.new 8++    -- Construct a logger+    logLevel <- either die pure =<< runExceptT lookupLogLevel+    stderrLogger <- mkStderrLogger+    let logger =+          filterBySeverity logLevel $+            stderrLogger <> chanLogger internalTelemetryQueue++    -- Lookup the OpenTelemetry SDK options+    OpenTelemetrySdkOptions{..} <-+      either die pure =<< runExceptT (lookupOpenTelemetrySdkOptions logger)++    -- Instument THIS PROGRAM with eventlog-socket and/or ghc-debug.+    let MyDebugOptions{..} = myDebugOptions+    startMyEventlogSocket logger maybeMyEventlogSocket+    withMyGhcDebug logger maybeMyGhcDebugSocket $ do+      --+      -- Start the server.+      server <- startServer logger serverOptions exportRequestInChan++      -- Read the configuration file.+      let readConfigFile configFile = do+            logDebug logger $ "Reading configuration file from " <> T.pack configFile+            config <- either (logFatal logger . T.pack) pure =<< C.readConfigFile configFile+            logDebug logger $ "Configuration file:\n" <> C.prettyConfig config+            pure config++      -- Read the configuration file and add derived settings.+      fullConfig <-+        C.toFullConfig eventlogFlushIntervalS+          <$> maybe (pure def) readConfigFile maybeConfigFile+      logDebug logger $+        "Batch interval is " <> T.pack (show fullConfig.batchIntervalMs) <> "ms"+      logDebug logger $+        "Eventlog flush interval is " <> T.pack (show fullConfig.eventlogFlushIntervalX) <> "x"++      -- Find the service name, if any:+      let !serviceName =+            fromMaybe (ServiceName "undefined") $+              (.serviceName) =<< maybeResourceAttributes++      -- Create a resource to represent the monitored process.+      let eventlogResource :: Resource+          eventlogResource =+            Resource+              { attrs =+                  fromList $+                    uncurry (~=) <$> maybe [] (.attributes) maybeResourceAttributes+              }++      -- Create machine to process eventlog into export requests.+      let eventlogProcessor ccdb ipedb =+            M.liftTick M.withStartTime+              ~> M.fanoutTick+                [ -- Log a warning if no input has been received after 10 ticks.+                  validateInput logger 10+                , -- Log event counts.+                  countEvents logger+                , -- Log ticks.+                  logTicks logger+                , -- If no cost-centre database was provided, index the cost-centre events.+                  indexCostCentreEvents (ccdb `onlyIf` isNothing maybeCCDBPath)+                , -- If no info-prov database was provided, index the info-prov events.+                  indexInfoProvEvents (ipedb `onlyIf` isNothing maybeIpeDBPath)+                , -- Process the eventlog events.+                  processEventlogTelemetry logger fullConfig eventlogResource appScope maybeHeapProfBreakdown ccdb ipedb+                    ~> M.liftTick (mapping D.singleton)+                ]+              ~> M.liftTick asParts+              ~> sending exportRequestInChan++      -- Create thread to process eventlog into export requests.+      eventlogProcessorHandle <-+        withScope "eventlogProcessor" logger $ \logger' ->+          fork logger' $ do+            DB.withNewSession def $ \session -> do+              withCostCentreTable maybeCCDBPath session $ \ccdb ->+                withInfoProvTable maybeIpeDBPath session $ \ipedb ->+                  withEventlogSourceHandle+                    logger'+                    eventlogSocketTimeoutS+                    eventlogSocketTimeoutExponent+                    eventlogSourceOptions+                    $ \eventlogSourceHandle -> do+                      -- Notify the control server of the connection status.+                      let newConnection = server.controlHooks.notifyNewConnection serviceName eventlogSourceHandle+                      let endConnection = server.controlHooks.notifyEndConnection serviceName+                      bracket_ newConnection endConnection $+                        -- Run the eventlog processor.+                        runWithEventlogSourceHandle+                          logger'+                          eventlogSourceHandle+                          fullConfig.batchIntervalMs+                          Nothing+                          maybeEventlogLogFile+                          (eventlogProcessor ccdb ipedb)++      -- Create a resource to represent the eventlog-live process.+      let internalResource :: Resource+          internalResource =+            Resource+              { attrs =+                  [ "service.name" ~= AttrText (appName <> "-for-" <> serviceName.serviceName)+                  , "service.version" ~= App.version+                  ]+              }++      -- Create thread to process internal telemetry into export requests.+      let internalTelemetryProcessor =+            runT_ $+              chanSource internalTelemetryQueue+                ~> processInternalTelemetry fullConfig internalResource appScope+                -- NOTE: eventlogProcessor writes ticks to the exportRequestInChan,+                --       and we don't want to duplicate those.+                ~> dropTick+                ~> mapping Item+                ~> sending exportRequestInChan+      internalTelemetryProcessorHandle <-+        withScope "internalTelemetryProcessor" logger $ \logger' ->+          fork logger' internalTelemetryProcessor++      -- Create machine to process export requests.+      let otelExporter =+            withExporters logger exporterOptions $ \exporters ->+              runT_ $+                lossyChanSource exportRequestOutChan+                  ~> exportToOtlp logger fullConfig exporters+      maybeExportRequestProcessorHandle <-+        withScope "otelExporter" logger $ \logger' ->+          if openTelemetryOptions.openTelemetryExporter+            then Just <$> fork logger' otelExporter+            else pure Nothing++      -- Wait for these threads to finish, then exit.+      join eventlogProcessorHandle+      join internalTelemetryProcessorHandle+      for_ maybeExportRequestProcessorHandle join+      server.stop++-- Log all ticks.+logTicks :: (Monad m) => Logger m -> ProcessT m (Tick x) y+logTicks logger = onlyTick ~> logTicks'+ where+  logTicks' = repeatedly $ await >>= lift . logTick logger++-- Count all input events.+countEvents :: (Monad m) => Logger m -> ProcessT m (Tick x) y+countEvents logger =+  M.batchByTickList ~> countEvents'+ where+  countEvents' = repeatedly $ await >>= lift . logMetric logger EventCount . fromIntegral . length++-- Run an action with access to a cost-centre table.+withCostCentreTable :: Maybe FilePath -> DB.Session -> (DB.Table CC.CostCentreId CC.CostCentre -> IO ()) -> IO ()+withCostCentreTable maybeCCDBPath session =+  maybe+    (DB.withNewTable session def)+    (\ccDBPath -> DB.withTableFrom session ccDBPath def)+    maybeCCDBPath++-- Run an action with access to an info-prov table.+withInfoProvTable :: Maybe FilePath -> DB.Session -> (DB.Table IP.InfoProvId IP.InfoProv -> IO ()) -> IO ()+withInfoProvTable maybeIpeDBPath session =+  maybe+    (DB.withNewTable session def)+    (\ipeDBPath -> DB.withTableFrom session ipeDBPath def)+    maybeIpeDBPath++-- Create machine that indexes CostCentre data.+indexCostCentreEvents ::+  Maybe (DB.Table CC.CostCentreId CC.CostCentre) ->+  ProcessT IO (Tick (M.WithStartTime Event)) x+indexCostCentreEvents =+  -- If a cost-centre database was not provided, don't index any new entries.+  maybe stopped (\ccdb -> dropTick ~> DB.indexer (CC.toCostCentre . (.value)) def ccdb ~> mapping absurd)++-- Create machine that indexes InfoProv data.+indexInfoProvEvents ::+  Maybe (DB.Table IP.InfoProvId IP.InfoProv) ->+  ProcessT IO (Tick (M.WithStartTime Event)) x+indexInfoProvEvents =+  -- If an IPE database was not provided, don't index any new entries.+  maybe stopped (\ipedb -> dropTick ~> DB.indexer (IP.toInfoProv . (.value)) def ipedb ~> mapping absurd)++--------------------------------------------------------------------------------+-- Internal helpers+--------------------------------------------------------------------------------++-- A machine that sends values to a `Chan`.+sending :: LC.InChan a -> ProcessT IO a Void+sending chan = repeatedly $ await >>= liftIO . LC.send chan++data ThreadHandle = ThreadHandle {threadId :: ThreadId, finished :: MVar ()}++fork :: Logger IO -> IO () -> IO ThreadHandle+fork logger action = do+  finished <- newEmptyMVar+  threadId <- forkIO $ do+    let finish :: IO ()+        finish = logInfo logger "thread finished" >> putMVar finished ()+        handler :: SomeException -> IO ()+        handler = logException logger+    (action `catch` handler) `finally` finish+  pure ThreadHandle{..}++join :: ThreadHandle -> IO ()+join ThreadHandle{..} =+  readMVar finished++onlyIf :: a -> Bool -> Maybe a+onlyIf a b =+  if b then Just a else Nothing
+ src-app/GHC/Eventlog/Live/App/Environment.hs view
@@ -0,0 +1,654 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}++module GHC.Eventlog.Live.App.Environment (+  -- * OpenTelemetry SDK Options+  OpenTelemetrySdkOptions (..),+  lookupOpenTelemetrySdkOptions,+  Severity (..),+  lookupLogLevel,+  ServiceName (..),+  ResourceAttributes (..),++  -- * OpenTelemetry Exporter Options+  ExporterOptions (..),++  -- ** OpenTelemetry Signals and Per-Signal Options+  PerSignal (..),+  Signal (..),+  forSignal,++  -- ** OpenTelemetry OTLP Exporter Options+  OtlpExporterOptions (..),+  Protocol (..),+  Endpoint (..),+  Compression (..),+  Timeout (..),+  defaultEndpointFor,+  defaultPortFor,+) where++import Control.Monad (join, unless)+import Control.Monad.Trans.Class (MonadTrans (..))+import Control.Monad.Trans.Except (ExceptT, throwE)+import Data.CaseInsensitive qualified as CI+import Data.Default (Default (..))+import Data.Foldable (for_)+import Data.Hashable (Hashable)+import Data.List qualified as L+import Data.Maybe (catMaybes, fromMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Data.Traversable (for)+import Data.Word (Word16)+import GHC.Eventlog.Live.Logger (Logger, logTrace, logWarn)+import GHC.Eventlog.Live.Types.Severity (Severity (..), fromSeverityString)+import GHC.IsList qualified as IsList+import GHC.Records (HasField (..))+import Network.URI (URI (..), URIAuth (..))+import Network.URI qualified as URI+import OpenTelemetry.Baggage (Baggage, decodeBaggageHeader)+import OpenTelemetry.Baggage qualified as Baggage+import System.Environment (lookupEnv)+import Text.Printf (printf)+import Text.Read (readMaybe)++--------------------------------------------------------------------------------+-- OpenTelemetry SDK Options+--------------------------------------------------------------------------------++{- |+The OpenTelemetry SDK configuration options.++Read these values from the environment using `lookupOpenTelemetrySdkOptions`.+This function writes to a `Logger` when it encounters configuration errors.+Hence, it does not read @OTEL_LOG_LEVEL@, which is needed to construct a logger.++See: https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables+-}+data OpenTelemetrySdkOptions = OpenTelemetrySdkOptions+  { maybeResourceAttributes :: !(Maybe ResourceAttributes)+  , exporterOptions :: !(PerSignal (Maybe ExporterOptions))+  }++lookupOpenTelemetrySdkOptions ::+  Logger IO ->+  ExceptT String IO OpenTelemetrySdkOptions+lookupOpenTelemetrySdkOptions logger = do+  maybeResourceAttributes <- lookupResourceAttributes logger+  exporterOptions <- lookupExporterOptions logger+  pure OpenTelemetrySdkOptions{..}++--------------------------------------------------------------------------------+-- OpenTelemetry Log Level++{- |+Lookup the OpenTelemetry Log Level from the environment.+-}+lookupLogLevel ::+  ExceptT String IO Severity+lookupLogLevel = do+  -- Lookup OTEL_LOG_LEVEL+  let otelLogLevel = "OTEL_LOG_LEVEL"+  fmap (fromMaybe INFO)+    <$> traverse (readSeverity otelLogLevel)+    =<< lift (lookupEnv otelLogLevel)++--------------------------------------------------------------------------------+-- OpenTelemetry Resource Attributes++{- |+OpenTelemetry Service Name.+-}+newtype ServiceName = ServiceName {serviceName :: Text}+  deriving newtype (Eq, Hashable, Show)++{- |+OpenTelemetry Resource Attributes.+-}+newtype ResourceAttributes = ResourceAttributes+  { resourceAttributeBaggage :: Baggage+  }++{- |+Internal helper.++The @service.name@ token.+-}+serviceNameToken :: Baggage.Token+serviceNameToken = [Baggage.token|service.name|]++instance HasField "serviceName" ResourceAttributes (Maybe ServiceName) where+  getField :: ResourceAttributes -> Maybe ServiceName+  getField ResourceAttributes{..} =+    ServiceName <$> Baggage.getValue serviceNameToken resourceAttributeBaggage++instance HasField "attributes" ResourceAttributes [(Text, Text)] where+  getField :: ResourceAttributes -> [(Text, Text)]+  getField ResourceAttributes{..} =+    [ (key, value)+    | (token, Baggage.Element value _properties) <-+        IsList.toList (Baggage.values resourceAttributeBaggage)+    , let key = TE.decodeUtf8 (Baggage.tokenValue token)+    ]++{- |+Lookup the OpenTelemetry Resource Attributes from the environment.++This function reads both @OTEL_RESOURCE_ATTRIBUTES@ and @OTEL_SERVICE_NAME@.+-}+lookupResourceAttributes ::+  Logger IO ->+  ExceptT String IO (Maybe ResourceAttributes)+lookupResourceAttributes logger = do+  -- Lookup OTEL_SERVICE_NAME+  let otelServiceName = "OTEL_SERVICE_NAME"+  maybeServiceName <-+    fmap (singletonBaggage serviceNameToken . T.pack)+      <$> lift (lookupEnv otelServiceName)++  -- Lookup OTEL_RESOURCE_ATTRIBUTES+  let otelResourceAttributes = "OTEL_RESOURCE_ATTRIBUTES"+  maybeResourceAttributeBaggage <-+    traverse (readBaggage logger otelResourceAttributes)+      =<< lift (lookupEnv otelResourceAttributes)++  pure $ fmap ResourceAttributes (maybeServiceName <> maybeResourceAttributeBaggage)++{- |+Internal helper.++Convert a `Text` value to singleton `Baggage`.+-}+singletonBaggage :: Baggage.Token -> Text -> Baggage+singletonBaggage token value = Baggage.insert token (Baggage.element value) Baggage.empty++--------------------------------------------------------------------------------+-- OpenTelemetry Exporter Options+--------------------------------------------------------------------------------++{- |+Supported exporters.+-}+data ExporterType = Console | Otlp+  deriving (Eq, Show)++{- |+Lookup the OpenTelemetry Exporter Type for a signal from the environment.++See: https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#exporter-selection+-}+lookupExporterType ::+  Logger IO ->+  Signal ->+  ExceptT String IO (Maybe ExporterType)+lookupExporterType logger signal = do+  let otelExporter = "OTEL_" <> show signal <> "_EXPORTER"+  lift (lookupEnv otelExporter) >>= \case+    Nothing ->+      pure (Just Otlp)+    Just otelExporterType ->+      readExporterType logger otelExporter otelExporterType++{- |+Exporter options for each exporter type.+-}+data ExporterOptions+  = ExporterOptions'Console+  | ExporterOptions'Otlp OtlpExporterOptions+  deriving (Eq, Show)++{- |+Lookup the OpenTelemetry Exporter options from the environment.++See: https://opentelemetry.io/docs/specs/otel/protocol/exporter+-}+lookupExporterOptions ::+  Logger IO ->+  ExceptT String IO (PerSignal (Maybe ExporterOptions))+lookupExporterOptions logger = do+  !tracesExporterType <- lookupExporterType logger TRACES+  !tracesExporterOptions <-+    for tracesExporterType $ \case+      Console ->+        pure ExporterOptions'Console+      Otlp ->+        ExporterOptions'Otlp <$> lookupOtlpExporterOptions logger (Just TRACES)++  !metricsExporterType <- lookupExporterType logger METRICS+  !metricsExporterOptions <-+    for metricsExporterType $ \case+      Console ->+        pure ExporterOptions'Console+      Otlp ->+        ExporterOptions'Otlp <$> lookupOtlpExporterOptions logger (Just METRICS)++  !logsExporterType <- lookupExporterType logger LOGS+  !logsExporterOptions <-+    for logsExporterType $ \case+      Console ->+        pure ExporterOptions'Console+      Otlp ->+        ExporterOptions'Otlp <$> lookupOtlpExporterOptions logger (Just LOGS)++  !profilesExporterType <- lookupExporterType logger PROFILES+  !profilesExporterOptions <-+    for profilesExporterType $ \case+      Console ->+        pure ExporterOptions'Console+      Otlp ->+        ExporterOptions'Otlp <$> lookupOtlpExporterOptions logger (Just PROFILES)++  let exporterOptions =+        [tracesExporterOptions, metricsExporterOptions, logsExporterOptions, profilesExporterOptions]+  pure $+    if allSame exporterOptions+      then+        Shared tracesExporterOptions+      else+        PerSignal+          { forTRACES = tracesExporterOptions+          , forMETRICS = metricsExporterOptions+          , forLOGS = logsExporterOptions+          , forPROFILES = profilesExporterOptions+          }++--------------------------------------------------------------------------------+-- OpenTelemetry OTLP Exporter Options++{- |+OTLP protocol.+-}+data Protocol = Grpc | HttpProtobuf+  deriving (Eq, Show)++instance Default Protocol where+  def :: Protocol+  def = HttpProtobuf++{- |+OTLP endpoint.+-}+data Endpoint = Endpoint+  { host :: !String+  , port :: !(Maybe Word16)+  , path :: !String+  , secure :: !Bool+  }+  deriving (Eq)++toURI :: Endpoint -> URI+toURI endpoint =+  URI.rectify $+    URI.nullURI+      { uriScheme = if endpoint.secure then "https" else "http"+      , uriAuthority = Just URI.nullURIAuth{uriRegName = endpoint.host, uriPort = maybe "" show endpoint.port}+      , uriPath = endpoint.path+      }++instance Show Endpoint where+  showsPrec :: Int -> Endpoint -> ShowS+  showsPrec p = showsPrec p . toURI++{- |+The default endpoint for each protocol.++See: https://opentelemetry.io/docs/specs/otel/protocol/exporter/#configuration-options+-}+defaultEndpointFor :: Protocol -> Endpoint+defaultEndpointFor protocol =+  Endpoint{host = "localhost", port = Just $ defaultPortFor protocol, path = "", secure = False}++{- |+The default port for each protocol.+-}+defaultPortFor :: Protocol -> Word16+defaultPortFor = \case Grpc -> 4317; HttpProtobuf -> 4318++{- |+OTLP compression.+-}+data Compression = GZip+  deriving (Eq, Show)++{- |+OTLP timeout.++The value is specified in milliseconds.+The value @0@ should be interpreted as "no timeout".+-}+newtype Timeout = Timeout {milliseconds :: Word}+  deriving (Eq, Show)++instance HasField "microseconds" Timeout Word where+  getField :: Timeout -> Word+  getField timeout = 1_000 * timeout.milliseconds++instance Default Timeout where+  def :: Timeout+  def = Timeout 10_000++{- |+OpenTelemetry OTLP Exporter options.+-}+data OtlpExporterOptions = OtlpExporterOptions+  { protocol :: !Protocol+  , endpoint :: !Endpoint+  , maybeCertificate :: !(Maybe String)+  , maybeHeaders :: !(Maybe Baggage)+  , maybeCompression :: !(Maybe Compression)+  , timeout :: !Timeout+  }+  deriving (Eq, Show)++{- |+Lookup the OpenTelemetry OTLP Exporter options from the environment.++See: https://opentelemetry.io/docs/specs/otel/protocol/exporter+-}+lookupOtlpExporterOptions ::+  Logger IO ->+  Maybe Signal ->+  ExceptT String IO OtlpExporterOptions+lookupOtlpExporterOptions logger signal = do+  maybeProtocol <- lookupOtlpExporterOption logger signal PROTOCOL readProtocol+  let !protocol = fromMaybe HttpProtobuf maybeProtocol+  -- The INSECURE option should be used to infer http/https, but whenever+  -- http/https is specified in the endpoint, this should take precedence.+  maybeInsecure <- lookupOtlpExporterOption logger signal INSECURE readBoolean+  maybeEndpoint <- lookupOtlpExporterOption logger signal ENDPOINT (readEndpoint protocol maybeInsecure)+  let !endpoint = fromMaybe (defaultEndpointFor protocol) maybeEndpoint+  maybeCertificate <- lookupOtlpExporterOption logger signal CERTIFICATE readString+  maybeHeaders <- lookupOtlpExporterOption logger signal HEADERS readBaggage+  maybeCompression <- join <$> lookupOtlpExporterOption logger signal COMPRESSION readCompression+  maybeTimeout <- lookupOtlpExporterOption logger signal TIMEOUT readTimeout+  let timeout = fromMaybe def maybeTimeout+  pure OtlpExporterOptions{..}++{- |+Internal helper.++The exporter options supported by OTLP.+-}+data OtlpExporterOption+  = PROTOCOL+  | ENDPOINT+  | INSECURE+  | CERTIFICATE+  | HEADERS+  | COMPRESSION+  | TIMEOUT+  deriving (Show)++{- |+Internal helper.++Render an exporter option name as a string.++>>> exporterOptionName Nothing        ENDPOINT == "OTEL_EXPORTER_OTLP_ENDPOINT"+>>> exporterOptionName (Just TRACES)  ENDPOINT == "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"+>>> exporterOptionName (Just METRICS) ENDPOINT == "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"+>>> exporterOptionName (Just LOGS)    ENDPOINT == "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"+-}+exporterOptionName :: Maybe Signal -> OtlpExporterOption -> String+exporterOptionName signal option =+  L.intercalate "_" . catMaybes $+    [Just "OTEL_EXPORTER_OTLP", show <$> signal, Just (show option)]++{- |+Internal helper.++Look up an exporter option, cascading from signal-specific for generic options.+-}+lookupOtlpExporterOption ::+  Logger IO ->+  Maybe Signal ->+  OtlpExporterOption ->+  (Logger IO -> String -> String -> ExceptT e IO a) ->+  ExceptT e IO (Maybe a)+lookupOtlpExporterOption logger maybeSignal option parser =+  -- Look up the exporter option for the specified signal, if any.+  case maybeSignal of+    Nothing ->+      lookupOtlpExporterOptionOnlyFor Nothing+    Just signal ->+      lookupOtlpExporterOptionOnlyFor (Just signal)+        >>= maybe (lookupOtlpExporterOptionOnlyFor Nothing) (pure . Just)+ where+  -- Look up the exporter option /only/ for the specified signal.+  lookupOtlpExporterOptionOnlyFor maybeSignal' =+    let optionName = exporterOptionName maybeSignal' option+     in lift (lookupEnv optionName) >>= traverse (parser logger optionName)++{- |+Internal helper.++Parse a protocol.+-}+readProtocol :: (Monad m) => Logger m -> String -> String -> ExceptT String m Protocol+readProtocol _logger optionName protocol+  | CI.mk protocol == "grpc" = pure Grpc+  | CI.mk protocol == "http/protobuf" = pure HttpProtobuf+  | CI.mk protocol == "http/json" =+      throwE $+        "Environment variable " <> optionName <> " specifies unsupported protocol 'http/json'."+  | otherwise =+      throwE $+        "Environment variable " <> optionName <> " specifies unknown protocol '" <> protocol <> "'."++{- |+Internal helper.++Parse a boolean.++See: https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#boolean+-}+readBoolean :: (Monad m) => Logger m -> String -> String -> ExceptT String m Bool+readBoolean logger optionName boolean+  | CI.mk boolean == "true" = pure True+  | CI.mk boolean == "false" = pure False+  | otherwise = do+      lift . logWarn logger . T.pack $+        "Environment variable " <> optionName <> " has non-boolean value '" <> boolean <> "'. Use 'true' or 'false'."+      pure False++{- |+Internal helper.++Parse a string.+-}+readString :: (Monad m) => Logger m -> String -> String -> ExceptT String m String+readString _logger _optionName = pure++{- |+Internal helper.++Show an URI.+-}+showURI :: URI -> String+showURI URI{..} =+  printf+    "URI {uriScheme = \"%s\", uriAuthority = %s, uriPath = \"%s\", uriQuery = \"%s\", uriFragment = \"%s\"}"+    uriScheme+    (show uriAuthority)+    uriPath+    uriQuery+    uriFragment++{- |+Internal helper.++Parse an endpoint.++@`readEndpoint` maybeInsecure@ uses the value of @maybeInsecure@, to determine+whether or not to infer the URI scheme as http or https, if unspecified.+-}+readEndpoint ::+  (Monad m) =>+  Protocol ->+  Maybe Bool ->+  Logger m ->+  String ->+  String ->+  ExceptT String m Endpoint+readEndpoint protocol maybeInsecure logger optionName = go True+ where+  go retry endpoint = do+    let maybeURI = URI.parseAbsoluteURI endpoint+    for_ maybeURI $ \uri ->+      lift . logTrace logger . T.pack $+        "Environment variable " <> optionName <> " specifies URI: " <> showURI uri+    case maybeURI of+      Nothing+        -- If the endpoint was specified without a scheme, then we retry with a+        -- scheme that is either based on the value of the insecure setting or+        -- the default insecure http scheme, but this applies *only* to gRPC.+        | protocol == Grpc && retry -> do+            if maybeInsecure == Just False+              then go False ("https://" <> endpoint)+              else go False ("http://" <> endpoint)+        | otherwise ->+            throwE $ "Environment variable " <> optionName <> " specifies malformed URI '" <> endpoint <> "'."+      Just URI{uriAuthority = Nothing} -> do+        throwE $ "Environment variable " <> optionName <> " specifies URI without authority '" <> endpoint <> "'."+      Just URI{uriScheme}+        | uriScheme `notElem` ["http:", "https:"] ->+            throwE $ "Environment variable " <> optionName <> " specifies URI with unsupported scheme '" <> endpoint <> "'. Use 'http' or 'https'."+      Just URI{uriAuthority = Just URIAuth{..}, ..} -> do+        unless (null uriUserInfo) $+          lift . logWarn logger . T.pack $+            "Environment variable " <> optionName <> " specifies URI with user info '" <> uriUserInfo <> "'."+        unless (null uriQuery) $+          lift . logWarn logger . T.pack $+            "Environment variable " <> optionName <> " specifies URI with query '" <> uriQuery <> "'."+        unless (null uriFragment) $+          lift . logWarn logger . T.pack $+            "Environment variable " <> optionName <> " specifies URI with fragment '" <> uriFragment <> "'."+        pure+          Endpoint+            { host = uriRegName+            , port = readMaybe @Word16 (dropColon uriPort)+            , path = uriPath+            , secure = uriScheme == "https:"+            }++  dropColon :: String -> String+  dropColon = \case (':' : str) -> str; str -> str++{- |+Internal helper.++Parse headers in the baggage format.+-}+readBaggage :: (Monad m) => Logger m -> String -> String -> ExceptT String m Baggage+readBaggage _logger optionName baggage =+  either onErr pure . decodeBaggageHeader . TE.encodeUtf8 . T.pack $ baggage+ where+  onErr e =+    throwE $ printf "Environment variable %s specifies malformed baggage '%s': %s" optionName baggage e++{- |+Internal helper.++Parse compression.+-}+readCompression :: (Monad m) => Logger m -> String -> String -> ExceptT String m (Maybe Compression)+readCompression _logger optionName compression+  | CI.mk compression == "none" = pure Nothing+  | CI.mk compression == "gzip" = pure (Just GZip)+  | otherwise =+      throwE $+        "Environment variable " <> optionName <> " specifies unknown compression '" <> compression <> "'. Use 'none' or 'gzip'."++{- |+Internal helper.++Parse a timeout.+-}+readTimeout :: (Monad m) => Logger m -> String -> String -> ExceptT String m Timeout+readTimeout logger optionName timeout+  | Just milliseconds <- readMaybe @Word timeout =+      pure (Timeout milliseconds)+  | otherwise = do+      lift . logWarn logger . T.pack $+        "Environment variable " <> optionName <> " specifies malformed timeout '" <> timeout <> "'."+      pure def++{- |+Internal helper.++Parse a log level.++See: https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-severitytext+-}+readSeverity :: (Monad m) => String -> String -> ExceptT String m Severity+readSeverity optionName logLevel+  | Just severity <- fromSeverityString logLevel = pure severity+  | otherwise =+      throwE $+        "Environment variable " <> optionName <> " specifies malformed log level '" <> logLevel <> "'."++{- |+Internal helper.++Parse an exporter type.+-}+readExporterType :: (Monad m) => Logger m -> String -> String -> ExceptT String m (Maybe ExporterType)+readExporterType _logger optionName exporterType+  | CI.mk exporterType == "none" = pure Nothing+  | CI.mk exporterType == "otlp" = pure (Just Otlp)+  | CI.mk exporterType == "console" = pure (Just Console)+  | CI.mk exporterType `elem` ["zipkin", "prometheus", "logging"] =+      throwE $+        "Environment variable " <> optionName <> " specifies unsupported exporter '" <> exporterType <> "'."+  | otherwise =+      throwE $+        "Environment variable " <> optionName <> " specifies unknown exporter '" <> exporterType <> "'."++{- |+Internal helper.++Check if all elements are the same.+-}+allSame :: (Eq a) => [a] -> Bool+allSame [] = True+allSame (x : xs) = all (== x) xs++--------------------------------------------------------------------------------+-- OpenTelemetry Signals and Options per Signal++{- |+The signals supported by OTLP.+-}+data Signal+  = TRACES+  | METRICS+  | LOGS+  | PROFILES+  deriving (Show, Enum, Bounded)++{- |+A collection of values for per signal.+-}+data PerSignal a+  = Shared !a+  | PerSignal+      { forTRACES :: !a+      , forMETRICS :: !a+      , forLOGS :: !a+      , forPROFILES :: !a+      }+  deriving stock (Functor, Foldable, Traversable)++{- |+Get the element for a specific signal.+-}+forSignal :: PerSignal a -> Signal -> a+forSignal = \case+  Shared a -> const a+  PerSignal{..} -> \case+    TRACES -> forTRACES+    METRICS -> forMETRICS+    LOGS -> forLOGS+    PROFILES -> forPROFILES
+ src-app/GHC/Eventlog/Live/App/Exporter/Otlp.hs view
@@ -0,0 +1,182 @@+module GHC.Eventlog.Live.App.Exporter.Otlp (+  exportToOtlp,+) where++import Data.DList qualified as D+import Data.Machine (ProcessT, asParts, mapping, (~>))+import Data.Maybe (catMaybes, mapMaybe)+import Data.Text qualified as T+import Data.Version (showVersion)+import GHC.Eventlog.Live.App.Environment (PerSignal, Signal (..), forSignal)+import GHC.Eventlog.Live.App.Exporter.Otlp.Core (Exporter, messageWith, toMaybeKeyValues)+import GHC.Eventlog.Live.App.Exporter.Otlp.Logs (exportResourceLogs, toExportLogsServiceRequest, toLogRecords, toResourceLogs, toScopeLogs)+import GHC.Eventlog.Live.App.Exporter.Otlp.Metrics (exportResourceMetrics, toExportMetricsServiceRequest, toMetric, toResourceMetrics, toScopeMetrics)+import GHC.Eventlog.Live.App.Exporter.Otlp.Profiles (exportResourceProfiles, toExportProfileServiceRequest, toProfiles, toProfilesData, toResourceProfiles, toScopeProfiles)+import GHC.Eventlog.Live.App.Exporter.Otlp.Traces (exportResourceSpans, toExportTracesServiceRequest, toResourceSpans, toScopeSpans, toSpans)+import GHC.Eventlog.Live.Config (FullConfig (..))+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Logger (Logger)+import GHC.Eventlog.Live.Machine.Core (Tick)+import GHC.Eventlog.Live.Machine.Core qualified as M+import GHC.Eventlog.Live.Processor (ExportRequest (..), InstrumentationScope (..), Resource (..), Telemetry (..))+import GHC.Eventlog.Live.Processor.Core+import GHC.Eventlog.Live.Types.Logs (SomeLogs)+import GHC.Eventlog.Live.Types.Metrics (SomeMetrics)+import GHC.Eventlog.Live.Types.Profiles (SomeSamples)+import GHC.Eventlog.Live.Types.Traces (SomeSpans)+import Lens.Family2 ((.~))+import Proto.Opentelemetry.Proto.Common.V1.Common qualified as OC+import Proto.Opentelemetry.Proto.Common.V1.Common_Fields qualified as OC+import Proto.Opentelemetry.Proto.Logs.V1.Logs qualified as OL+import Proto.Opentelemetry.Proto.Metrics.V1.Metrics qualified as OM+import Proto.Opentelemetry.Proto.Profiles.V1development.Profiles qualified as OP+import Proto.Opentelemetry.Proto.Resource.V1.Resource qualified as OR+import Proto.Opentelemetry.Proto.Resource.V1.Resource_Fields qualified as OR+import Proto.Opentelemetry.Proto.Trace.V1.Trace qualified as OT++{- |+Convert a `Resource` to an OTLP `OR.Resource`.+-}+toResource :: Resource -> OR.Resource+toResource Resource{..} =+  messageWith [OR.attributes .~ toMaybeKeyValues attrs]++toInstrumentationScope :: InstrumentationScope -> OC.InstrumentationScope+toInstrumentationScope InstrumentationScope{..} =+  messageWith+    [ OC.name .~ name+    , OC.version .~ T.pack (showVersion version)+    ]++data ResourceTelemetry+  = ResourceTelemetry'Logs OL.ResourceLogs+  | ResourceTelemetry'Metrics OM.ResourceMetrics+  | ResourceTelemetry'Spans OT.ResourceSpans+  | ResourceTelemetry'Profile OP.ProfilesData++{- |+Internal helper.+Export resource telemetry data and yield statistics.+-}+exportToOtlp ::+  Logger IO ->+  FullConfig ->+  PerSignal (Maybe Exporter) ->+  ProcessT IO (Tick ExportRequest) (Tick ())+exportToOtlp logger fullConfig exporters =+  M.liftTick (mapping (toResourceTelemetry fullConfig) ~> asParts)+    ~> M.fanoutTick+      [ -- Export logs.+        runIf (C.shouldExportLogs fullConfig) $+          runWith (exporters `forSignal` LOGS) $ \logsExporter ->+            M.liftTick (mapping getResourceLogs ~> asParts ~> mapping D.singleton)+              -- NOTE: This is required to combine different resource telemetry+              --       streams. However, it has the "unfortunate" side-effect of+              --       making it impossible to not batch once per interval.+              ~> M.batchByTick+              ~> M.liftTick+                ( mapping (toExportLogsServiceRequest . D.toList)+                    ~> exportResourceLogs logger logsExporter+                )+      , -- Export metrics.+        runIf (C.shouldExportMetrics fullConfig) $+          runWith (exporters `forSignal` METRICS) $ \metricsExporter ->+            M.liftTick (mapping getResourceMetrics ~> asParts ~> mapping D.singleton)+              -- NOTE: See note above.+              ~> M.batchByTick+              ~> M.liftTick+                ( mapping (toExportMetricsServiceRequest . D.toList)+                    ~> exportResourceMetrics logger metricsExporter+                )+      , -- Export spans.+        runIf (C.shouldExportTraces fullConfig) $+          runWith (exporters `forSignal` TRACES) $ \tracesExporter ->+            M.liftTick (mapping getResourceSpans ~> asParts ~> mapping D.singleton)+              -- NOTE: See note above.+              ~> M.batchByTick+              ~> M.liftTick+                ( mapping (toExportTracesServiceRequest . D.toList)+                    ~> exportResourceSpans logger tracesExporter+                )+      , -- Export profiles.+        runIf (C.shouldExportProfiles fullConfig) $+          runWith (exporters `forSignal` PROFILES) $ \profilesExporter ->+            M.liftTick+              ( mapping getResourceProfiles+                  ~> asParts+                  ~> mapping toExportProfileServiceRequest+                  ~> exportResourceProfiles logger profilesExporter+              )+      ]++getResourceLogs :: ResourceTelemetry -> Maybe OL.ResourceLogs+getResourceLogs = \case+  (ResourceTelemetry'Logs resourceLogs) -> Just resourceLogs+  _otherwise -> Nothing++getResourceMetrics :: ResourceTelemetry -> Maybe OM.ResourceMetrics+getResourceMetrics = \case+  (ResourceTelemetry'Metrics resourceMetrics) -> Just resourceMetrics+  _otherwise -> Nothing++getResourceSpans :: ResourceTelemetry -> Maybe OT.ResourceSpans+getResourceSpans = \case+  (ResourceTelemetry'Spans resourceSpans) -> Just resourceSpans+  _otherwise -> Nothing++getResourceProfiles :: ResourceTelemetry -> Maybe OP.ProfilesData+getResourceProfiles = \case+  (ResourceTelemetry'Profile profilesData) -> Just profilesData+  _otherwise -> Nothing++{- |+Internal helper.++Repack `Telemetry` into batched `ResourceTelemetry`.+-}+toResourceTelemetry ::+  FullConfig ->+  ExportRequest ->+  [ResourceTelemetry]+toResourceTelemetry fullConfig ExportRequest{..} =+  catMaybes [maybeResourceLogs, maybeResourceMetrics, maybeResourceSpans, maybeProfiles]+ where+  (someLogs, someMetrics, someSpans, someSamples) = partitionTelemetry telemetry+  resource' = toResource resource+  scope' = toInstrumentationScope scope++  maybeResourceLogs = do+    let logRecords = concatMap (toLogRecords fullConfig) someLogs+    scopeLogs <- toScopeLogs scope' logRecords+    resourceLogs <- toResourceLogs resource' [scopeLogs]+    pure $ ResourceTelemetry'Logs resourceLogs+  maybeResourceMetrics = do+    let metrics = mapMaybe (toMetric fullConfig) someMetrics+    scopeMetrics <- toScopeMetrics scope' metrics+    resourceMetrics <- toResourceMetrics resource' [scopeMetrics]+    pure $ ResourceTelemetry'Metrics resourceMetrics+  maybeResourceSpans = do+    let spans = concatMap (toSpans fullConfig) someSpans+    scopeSpans <- toScopeSpans scope' spans+    resourceSpans <- toResourceSpans resource' [scopeSpans]+    pure $ ResourceTelemetry'Spans resourceSpans+  maybeProfiles = do+    (profiles, dictionary) <- toProfiles fullConfig someSamples+    scopeProfiles <- toScopeProfiles scope' profiles+    resourceProfiles <- toResourceProfiles resource' [scopeProfiles]+    profilesData <- toProfilesData [resourceProfiles] dictionary+    pure $ ResourceTelemetry'Profile profilesData++{- |+Partition a stream of `Telemetry` batches to individual batches for each kind of telemetry data.+-}+partitionTelemetry :: [Telemetry] -> ([SomeLogs], [SomeMetrics], [SomeSpans], [SomeSamples])+partitionTelemetry = go ([], [], [], [])+ where+  go :: ([SomeLogs], [SomeMetrics], [SomeSpans], [SomeSamples]) -> [Telemetry] -> ([SomeLogs], [SomeMetrics], [SomeSpans], [SomeSamples])+  go (logsRev, metricsRev, spansRev, samplesRev) = \case+    [] -> (reverse logsRev, reverse metricsRev, reverse spansRev, reverse samplesRev)+    (Telemetry'Logs log_ : rest) -> go (log_ : logsRev, metricsRev, spansRev, samplesRev) rest+    (Telemetry'Metrics metric : rest) -> go (logsRev, metric : metricsRev, spansRev, samplesRev) rest+    (Telemetry'Spans spans : rest) -> go (logsRev, metricsRev, spans : spansRev, samplesRev) rest+    (Telemetry'Samples sample : rest) -> go (logsRev, metricsRev, spansRev, sample : samplesRev) rest
+ src-app/GHC/Eventlog/Live/App/Exporter/Otlp/Core.hs view
@@ -0,0 +1,460 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE OverloadedStrings #-}++module GHC.Eventlog.Live.App.Exporter.Otlp.Core (+  -- * Exporter+  Exporter (..),+  withExporter,+  withExporters,+  export,+  ExportError (..),++  -- ** Export via gRPC+  CanExportToConsole,++  -- ** Export via gRPC+  CanExportToOltpViaGrpc,++  -- ** Export via HTTP/Protobuf+  CanExportToOltpViaHttpProtobuf (..),+  HttpError (..),++  -- * Helpers for conversion to OTLP+  ifNonEmpty,+  messageWith,+  (.~?),+  toMaybeKeyValues,+  toMaybeKeyValue,+  toMaybeAnyValue,+) where++import Codec.Compression.GZip qualified as GZip+import Control.Exception (Exception (..), throwIO)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BSC+import Data.ByteString.Lazy qualified as BSL+import Data.CaseInsensitive qualified as CI+import Data.Functor ((<&>))+import Data.Maybe (fromMaybe, mapMaybe)+import Data.ProtoLens (Message (..))+import Data.ProtoLens.Encoding qualified as Proto+import Data.ProtoLens.Service.Types (HasMethodImpl (..))+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Data.Text.IO qualified as TIO+import GHC.Eventlog.Live.App.Environment (Compression (..))+import GHC.Eventlog.Live.App.Environment qualified as E (Endpoint (..), ExporterOptions (..), OtlpExporterOptions (..), PerSignal (..), Protocol (..), Timeout (..), defaultPortFor)+import GHC.Eventlog.Live.Logger (Logger, logDebug, logTrace)+import GHC.Eventlog.Live.Types.Attribute (Attr, AttrValue (..), Attrs)+import GHC.IsList (IsList (..))+import GHC.IsList qualified as IsList+import Lens.Family2 (Setter, (.~))+import Network.GRPC.Client qualified as G+import Network.GRPC.Client.StreamType.IO qualified as G+import Network.GRPC.Common qualified as G+import Network.GRPC.Common.Compression qualified as G+import Network.GRPC.Common.Protobuf (Protobuf, StreamingType (..))+import Network.GRPC.Common.Protobuf qualified as G+import Network.GRPC.Common.StreamType qualified as G+import Network.HTTP.Client qualified as H+import Network.HTTP.Client.TLS qualified as H+import Network.HTTP.Types.Header qualified as HTTP+import Network.HTTP.Types.Status qualified as HTTP+import OpenTelemetry.Baggage qualified as Baggage+import Proto.Opentelemetry.Proto.Common.V1.Common qualified as OC+import Proto.Opentelemetry.Proto.Common.V1.Common_Fields qualified as OC++--------------------------------------------------------------------------------+-- OTLP Exporter+--------------------------------------------------------------------------------++data Exporter+  = Exporter'Console+  | Exporter'OtlpGrpc !OtlpGrpcExporter+  | Exporter'OtlpHttpProtobuf !OtlpHttpProtobufExporter++{- |+Construct one shared t`OtlpExporter` or one t`OtlpExporter` per signal.+-}+withExporters ::+  Logger IO ->+  E.PerSignal (Maybe E.ExporterOptions) ->+  (E.PerSignal (Maybe Exporter) -> IO a) ->+  IO a+withExporters logger (E.Shared maybeOptions) action =+  withMaybeExporter logger maybeOptions $ action . E.Shared+withExporters logger E.PerSignal{..} action =+  withMaybeExporter logger forTRACES $ \exporterForTRACES ->+    withMaybeExporter logger forMETRICS $ \exporterForMETRICS ->+      withMaybeExporter logger forLOGS $ \exporterForLOGS ->+        withMaybeExporter logger forPROFILES $ \exporterForPROFILES ->+          action $ E.PerSignal exporterForTRACES exporterForMETRICS exporterForLOGS exporterForPROFILES++{- |+Construct a @Maybe t`Exporter`@ from @Maybe t`OtlpExporterOptions`@.+-}+withMaybeExporter ::+  Logger IO ->+  Maybe E.ExporterOptions ->+  (Maybe Exporter -> IO a) ->+  IO a+withMaybeExporter logger maybeOptions action =+  case maybeOptions of+    Nothing ->+      action Nothing+    Just options ->+      withExporter logger options $ action . Just++{- |+Construct an t`Exporter` from t`ExporterOptions`.+-}+withExporter ::+  Logger IO ->+  E.ExporterOptions ->+  (Exporter -> IO a) ->+  IO a+withExporter logger options action =+  case options of+    E.ExporterOptions'Console ->+      action Exporter'Console+    E.ExporterOptions'Otlp otlpExporterOptions ->+      case otlpExporterOptions.protocol of+        E.Grpc ->+          withOtlpGrpcExporter logger otlpExporterOptions $ action . Exporter'OtlpGrpc+        E.HttpProtobuf ->+          withOtlpHttpProtobufExporter logger otlpExporterOptions $ action . Exporter'OtlpHttpProtobuf++{- |+Export telemetry data to the t`OtlpExporter`.+-}+export ::+  forall serv meth.+  ( CanExportToConsole serv meth+  , CanExportToOltpViaGrpc serv meth+  , CanExportToOltpViaHttpProtobuf serv meth+  ) =>+  Logger IO ->+  -- | The HTTP/Protobuf exporter.+  Exporter ->+  -- | The request message.+  MethodInput serv meth ->+  IO (MethodOutput serv meth)+export logger = \case+  Exporter'Console -> \req -> do+    TIO.putStrLn (displayExportRequest @serv @meth req)+    pure (makeExportResponse @serv @meth req)+  Exporter'OtlpGrpc exporter ->+    exportGrpc @serv @meth logger exporter+  Exporter'OtlpHttpProtobuf exporter ->+    exportHttpProtobuf @serv @meth logger exporter++--------------------------------------------------------------------------------+-- Console Exporter+--------------------------------------------------------------------------------++class CanExportToConsole serv meth where+  {- |+  Display an export request message.+  -}+  displayExportRequest :: MethodInput serv meth -> Text+  default displayExportRequest :: (Show (MethodInput serv meth)) => MethodInput serv meth -> Text+  displayExportRequest = T.pack . show+  {-# INLINE displayExportRequest #-}++  {- |+  Construct an export response.+  -}+  makeExportResponse :: MethodInput serv meth -> MethodOutput serv meth+  default makeExportResponse :: (Message (MethodOutput serv meth)) => MethodInput serv meth -> MethodOutput serv meth+  makeExportResponse = const defMessage+  {-# INLINE makeExportResponse #-}++--------------------------------------------------------------------------------+-- OTLP gRPC Exporter+--------------------------------------------------------------------------------++{- |+An opaque OTLP gRPC exporter.+-}+newtype OtlpGrpcExporter = OtlpGrpcExporter+  { connection :: G.Connection+  }++type CanExportToOltpViaGrpc serv meth =+  ( G.SupportsClientRpc (Protobuf serv meth)+  , G.SupportsStreamingType (Protobuf serv meth) 'NonStreaming+  , G.RequestMetadata (Protobuf serv meth) ~ G.NoMetadata+  )++withOtlpGrpcExporter ::+  Logger IO ->+  E.OtlpExporterOptions ->+  (OtlpGrpcExporter -> IO a) ->+  IO a+withOtlpGrpcExporter logger options action = do+  logDebug logger . T.pack $+    "OTLP gRPC Exporter - Endpoint: " <> show options.endpoint+  let !connParams =+        G.def+          { -- The compression negotiation strategy:+            G.connCompression =+              case options.maybeCompression of+                Nothing -> G.none+                Just GZip -> G.only G.gzip+          , -- The default timeout:+            G.connDefaultTimeout =+              if options.timeout.milliseconds == 0+                then Nothing+                else Just (G.Timeout G.Millisecond (G.TimeoutValue options.timeout.milliseconds))+          }+  G.withConnection connParams server $ \connection ->+    action OtlpGrpcExporter{..}+ where+  server :: G.Server+  server+    | options.endpoint.secure = G.ServerSecure serverValidation G.SslKeyLogNone address+    | otherwise = G.ServerInsecure address+   where+    port = fromIntegral $ fromMaybe (E.defaultPortFor options.protocol) options.endpoint.port+    address = G.Address options.endpoint.host port Nothing+    serverValidation = G.ValidateServer $ maybe G.certStoreFromSystem G.certStoreFromPath options.maybeCertificate++exportGrpc ::+  forall serv meth.+  (CanExportToOltpViaGrpc serv meth) =>+  Logger IO ->+  OtlpGrpcExporter ->+  MethodInput serv meth ->+  IO (MethodOutput serv meth)+exportGrpc _logger grpcExporter input =+  let callParams :: G.CallParams (G.Protobuf serv meth)+      callParams = G.def+   in G.getProto <$> G.nonStreaming grpcExporter.connection (G.rpcWith callParams) (G.Proto input)++--------------------------------------------------------------------------------+-- OTLP HTTP/Protobuf Exporter+--------------------------------------------------------------------------------++{- |+The options for an OTLP HTTP/Protobuf endpoint.+-}+newtype OtlpHttpEndpoint = OtlpHttpEndpoint+  { baseUrl :: String+  }+  deriving (Show)++data OtlpHttpProtobufExporter = OtlpHttpProtobufExporter+  { manager :: H.Manager+  , baseUrl :: String+  , headers :: HTTP.RequestHeaders+  , maybeCompression :: Maybe Compression+  }++data HttpError+  = HttpStatusError+      { statusCode :: Int+      , statusMessage :: ByteString+      , responseBody :: ByteString+      }+  | HttpDecodeError+      { errorMessage :: String+      }+  deriving (Show)++instance Exception HttpError where+  displayException :: HttpError -> String+  displayException = \case+    HttpStatusError{..} ->+      "OTLP HTTP/Protobuf Exporter - HTTP Response: "+        <> show statusCode+        <> " "+        <> BSC.unpack statusMessage+        <> " with body: "+        <> BSC.unpack responseBody+    HttpDecodeError{..} ->+      "OTLP HTTP/Protobuf Exporter - Malformed HTTP Response: "+        <> errorMessage++{- |+Internal helper.++Run an action with an t`OtlpHttpProtobufExporter`.+-}+withOtlpHttpProtobufExporter ::+  Logger IO ->+  E.OtlpExporterOptions ->+  (OtlpHttpProtobufExporter -> IO a) ->+  IO a+withOtlpHttpProtobufExporter logger options action = do+  logDebug logger . T.pack $+    "OTLP HTTP/Protobuf Exporter - Endpoint: " <> show options.endpoint+  -- Create HTTP manager settings.+  let responseTimeout+        | options.timeout.microseconds == 0 =+            H.responseTimeoutNone+        | options.timeout.microseconds <= fromIntegral (maxBound @Int) =+            H.responseTimeoutMicro (fromIntegral options.timeout.microseconds)+        | otherwise =+            -- NOTE: Oh no, this truncates the response timeout to 292,271 years!+            H.responseTimeoutMicro maxBound+  -- Create an HTTP manager.+  --+  -- NOTE: newTlsManagerWith respects proxy environment variables+  manager <-+    H.newTlsManagerWith H.tlsManagerSettings{H.managerResponseTimeout = responseTimeout}+  -- Create the HTTP headers.+  logTrace logger . T.pack $+    "OTLP HTTP/Protobuf Exporter - Headers: " <> show options.maybeHeaders+  let headers =+        [ (CI.mk (Baggage.tokenValue token), TE.encodeUtf8 value)+        | (token, Baggage.Element value _properties) <-+            IsList.toList (maybe mempty Baggage.values options.maybeHeaders)+        ]+  -- Run the action.+  action+    OtlpHttpProtobufExporter+      { baseUrl = show options.endpoint+      , maybeCompression = options.maybeCompression+      , ..+      }++class+  ( Message (MethodInput serv meth)+  , Message (MethodOutput serv meth)+  ) =>+  CanExportToOltpViaHttpProtobuf serv meth+  where+  apiPath :: String++{- |+Send a Protobuf message over an HTTP connection.+-}+exportHttpProtobuf ::+  forall serv meth.+  (CanExportToOltpViaHttpProtobuf serv meth) =>+  Logger IO ->+  -- | The HTTP/Protobuf exporter.+  OtlpHttpProtobufExporter ->+  -- | The request message.+  MethodInput serv meth ->+  IO (MethodOutput serv meth)+exportHttpProtobuf logger OtlpHttpProtobufExporter{..} req = do+  baseRequest <- H.parseRequest (baseUrl <> apiPath @serv @meth)+  let (compressionHeaders, compress) = httpCompression maybeCompression+  let !requestBody = H.RequestBodyBS (compress (Proto.encodeMessage req))+  let request =+        baseRequest+          { H.method = "POST"+          , H.requestBody = requestBody+          , H.checkResponse = \_ _ -> pure ()+          , H.requestHeaders =+              [ (HTTP.hContentType, "application/x-protobuf")+              , (HTTP.hAccept, "application/x-protobuf")+              ]+                <> headers -- user-provided+                <> compressionHeaders+          }+  logTrace logger . T.pack $ "HTTP/Protobuf Exporter - HTTP Request:  " <> show request+  response <- H.httpLbs request manager+  logTrace logger . T.pack $ "HTTP/Protobuf Exporter - HTTP Response:  " <> show response+  let status = H.responseStatus response+  let body = BSL.toStrict (H.responseBody response)+  if HTTP.statusIsSuccessful status+    then decodeResponseBody body+    else+      throwIO+        HttpStatusError+          { statusCode = HTTP.statusCode status+          , statusMessage = HTTP.statusMessage status+          , responseBody = body+          }++{- |+Internal helper.++Decode the HTTP response body into a Protobuf message.+-}+decodeResponseBody :: (Message msg) => ByteString -> IO msg+decodeResponseBody body+  | BS.null body = pure defMessage+  | otherwise =+      case Proto.decodeMessage body of+        Left errorMessage -> throwIO HttpDecodeError{..}+        Right msg -> pure msg++{- |+Internal helper.++Determine HTTP compression headers and algorithms.+-}+httpCompression :: Maybe Compression -> ([HTTP.Header], ByteString -> ByteString)+httpCompression = \case+  Nothing -> ([], id)+  Just GZip -> ([(HTTP.hContentEncoding, "gzip")], BSL.toStrict . GZip.compress . BSL.fromStrict)++--------------------------------------------------------------------------------+-- Error Message+--------------------------------------------------------------------------------++newtype ExportError = ExportError {message :: Text}+  deriving (Show)++instance Exception ExportError where+  displayException :: ExportError -> String+  displayException = T.unpack . (.message)++--------------------------------------------------------------------------------+-- Conversion to OLTP+--------------------------------------------------------------------------------++-- | Return the second argument if the first argument is non-empty.+ifNonEmpty :: [a] -> b -> Maybe b+ifNonEmpty xs r = if null xs then Nothing else Just r++-- | Construct a message with a list of modifications applied.+messageWith :: (Message msg) => [msg -> msg] -> msg+messageWith = foldr ($) defMessage++-- | Set a value if it is `Just`.+(.~?) :: Setter s s a a -> Maybe a -> s -> s+setter .~? maybeValue = maybe id (setter .~) maybeValue++{- |+Convert an `Attrs` to a list of OTLP `OC.KeyValue`.+-}+toMaybeKeyValues :: Attrs -> [OC.KeyValue]+toMaybeKeyValues = mapMaybe toMaybeKeyValue . toList++{- |+Convert an `Attr` to an OTLP `OC.KeyValue`.+-}+toMaybeKeyValue :: Attr -> Maybe OC.KeyValue+toMaybeKeyValue (k, v) =+  toMaybeAnyValue v <&> \v' ->+    messageWith+      [ OC.key .~ k+      , OC.value .~ v'+      ]++{- |+Internal helper.+Convert an `AttrValue` to an OTLP `OC.AnyValue`.+-}+toMaybeAnyValue :: AttrValue -> Maybe OC.AnyValue+toMaybeAnyValue = \case+  AttrBool v -> Just $ messageWith [OC.boolValue .~ v]+  AttrInt v -> Just $ messageWith [OC.intValue .~ fromIntegral v]+  AttrInt8 v -> Just $ messageWith [OC.intValue .~ fromIntegral v]+  AttrInt16 v -> Just $ messageWith [OC.intValue .~ fromIntegral v]+  AttrInt32 v -> Just $ messageWith [OC.intValue .~ fromIntegral v]+  AttrInt64 v -> Just $ messageWith [OC.intValue .~ v]+  AttrWord v -> Just $ messageWith [OC.intValue .~ fromIntegral v]+  AttrWord8 v -> Just $ messageWith [OC.intValue .~ fromIntegral v]+  AttrWord16 v -> Just $ messageWith [OC.intValue .~ fromIntegral v]+  AttrWord32 v -> Just $ messageWith [OC.intValue .~ fromIntegral v]+  AttrWord64 v -> Just $ messageWith [OC.intValue .~ fromIntegral v]+  AttrDouble v -> Just $ messageWith [OC.doubleValue .~ v]+  AttrText v -> Just $ messageWith [OC.stringValue .~ v]+  AttrNull -> Nothing
+ src-app/GHC/Eventlog/Live/App/Exporter/Otlp/Logs.hs view
@@ -0,0 +1,159 @@+{-# LANGUAGE OverloadedLists #-}+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_GHC -Wno-orphans #-}++module GHC.Eventlog.Live.App.Exporter.Otlp.Logs (+  -- * Export+  exportResourceLogs,++  -- * Conversion to OTLP+  toExportLogsServiceRequest,+  toResourceLogs,+  toScopeLogs,+  toLogRecords,+) where++import Control.Exception (SomeException (..), catch)+import Control.Monad (unless)+import Control.Monad.IO.Class (MonadIO (..))+import Data.Data (Proxy (..))+import Data.Int (Int64)+import Data.Machine (ProcessT, traversing)+import Data.Maybe (fromMaybe)+import Data.Semigroup (Sum (..))+import Data.Vector qualified as V+import GHC.Eventlog.Live.App.Exporter.Otlp.Core (CanExportToConsole, CanExportToOltpViaHttpProtobuf (..), ExportError (..), Exporter (..), export, ifNonEmpty, messageWith, toMaybeKeyValues)+import GHC.Eventlog.Live.Config (FullConfig)+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Logger (ExportResult (..), InternalMetric (..), Logger, logException, logMetric)+import GHC.Eventlog.Live.Types.Attribute ((~=))+import GHC.Eventlog.Live.Types.Logs (LogRecord (..), SomeLogs (..), logConfig)+import GHC.Eventlog.Live.Types.Severity (Severity)+import GHC.Eventlog.Live.Types.Severity qualified as DS+import Lens.Family2 ((.~), (^.))+import Network.GRPC.Common qualified as G+import Network.GRPC.Common.Protobuf (Protobuf)+import Proto.Opentelemetry.Proto.Collector.Logs.V1.LogsService qualified as OLS+import Proto.Opentelemetry.Proto.Collector.Logs.V1.LogsService_Fields qualified as OLS+import Proto.Opentelemetry.Proto.Common.V1.Common qualified as OC+import Proto.Opentelemetry.Proto.Common.V1.Common_Fields qualified as OC+import Proto.Opentelemetry.Proto.Logs.V1.Logs qualified as OL+import Proto.Opentelemetry.Proto.Logs.V1.Logs_Fields qualified as OL+import Proto.Opentelemetry.Proto.Resource.V1.Resource qualified as OR++--------------------------------------------------------------------------------+-- OpenTelemetry Exporter for Logs++exportResourceLogs ::+  Logger IO ->+  Exporter ->+  ProcessT IO OLS.ExportLogsServiceRequest ()+exportResourceLogs logger exporter =+  traversing sendResourceLogs+ where+  sendResourceLogs :: OLS.ExportLogsServiceRequest -> IO ()+  sendResourceLogs exportLogsServiceRequest =+    doExport `catch` handleSomeException+   where+    doExport :: IO ()+    doExport = do+      resp <- export @OLS.LogsService @"export" logger exporter exportLogsServiceRequest+      let !exported = countLogRecordsInExportLogsServiceRequest exportLogsServiceRequest+      let !rejected = resp ^. OLS.partialSuccess . OLS.rejectedLogRecords+      liftIO (logMetric logger ExportLogs ExportResult{..})+      unless (rejected == 0) $+        liftIO (logException logger $ ExportError $ resp ^. OLS.partialSuccess . OLS.errorMessage)++    handleSomeException :: SomeException -> IO ()+    handleSomeException = logException logger++--------------------------------------------------------------------------------+-- CanExportToConsole++instance CanExportToConsole OLS.LogsService "export"++--------------------------------------------------------------------------------+-- CanExportToOltpViaGrpc++type instance G.RequestMetadata (Protobuf OLS.LogsService meth) = G.NoMetadata+type instance G.ResponseInitialMetadata (Protobuf OLS.LogsService meth) = G.NoMetadata+type instance G.ResponseTrailingMetadata (Protobuf OLS.LogsService meth) = G.NoMetadata++--------------------------------------------------------------------------------+-- CanExportToOltpViaHttpProtobuf++instance CanExportToOltpViaHttpProtobuf OLS.LogsService "export" where+  apiPath :: String+  apiPath = "/v1/logs"++--------------------------------------------------------------------------------+-- Internal Helpers+--------------------------------------------------------------------------------++{- |+Internal helper.+Count the number of `OL.NumberDataPoint` values in an `OLS.ExportLogsServiceRequest`.+-}+{-# SPECIALIZE countLogRecordsInExportLogsServiceRequest :: OLS.ExportLogsServiceRequest -> Int64 #-}+{-# SPECIALIZE countLogRecordsInExportLogsServiceRequest :: OLS.ExportLogsServiceRequest -> Word #-}+countLogRecordsInExportLogsServiceRequest :: (Integral i) => OLS.ExportLogsServiceRequest -> i+countLogRecordsInExportLogsServiceRequest exportLogsServiceRequest =+  getSum $ foldMap (Sum . countLogRecordsInResourceLogs) (exportLogsServiceRequest ^. OLS.vec'resourceLogs)++{- |+Internal helper.+Count the number of `OL.NumberDataPoint` values in an `OL.ResourceLogs`.+-}+{-# SPECIALIZE countLogRecordsInResourceLogs :: OL.ResourceLogs -> Int64 #-}+{-# SPECIALIZE countLogRecordsInResourceLogs :: OL.ResourceLogs -> Word #-}+countLogRecordsInResourceLogs :: (Integral i) => OL.ResourceLogs -> i+countLogRecordsInResourceLogs resourceLogs =+  getSum $ foldMap (Sum . countLogRecordsInScopeLogs) (resourceLogs ^. OL.vec'scopeLogs)++{- |+Internal helper.+Count the number of `OL.NumberDataPoint` values in an `OL.ScopeLogs`.+-}+{-# SPECIALIZE countLogRecordsInScopeLogs :: OL.ScopeLogs -> Int64 #-}+{-# SPECIALIZE countLogRecordsInScopeLogs :: OL.ScopeLogs -> Word #-}+countLogRecordsInScopeLogs :: (Integral i) => OL.ScopeLogs -> i+countLogRecordsInScopeLogs scopeLogs =+  fromIntegral $+    V.length (scopeLogs ^. OL.vec'logRecords)++--------------------------------------------------------------------------------+-- Conversion to OTLP+--------------------------------------------------------------------------------++toExportLogsServiceRequest :: [OL.ResourceLogs] -> OLS.ExportLogsServiceRequest+toExportLogsServiceRequest resourceLogs =+  messageWith [OL.resourceLogs .~ resourceLogs]++toResourceLogs :: OR.Resource -> [OL.ScopeLogs] -> Maybe OL.ResourceLogs+toResourceLogs resource scopeLogs =+  ifNonEmpty scopeLogs $+    messageWith [OL.resource .~ resource, OL.scopeLogs .~ scopeLogs]++toScopeLogs :: OC.InstrumentationScope -> [OL.LogRecord] -> Maybe OL.ScopeLogs+toScopeLogs instrumentationScope logRecords =+  ifNonEmpty logRecords $+    messageWith [OL.scope .~ instrumentationScope, OL.logRecords .~ logRecords]++toLogRecords :: FullConfig -> SomeLogs -> [OL.LogRecord]+toLogRecords fullConfig (SomeLogs (_log :: Proxy log) logRecords) =+  [toLogRecord logRecord{attrs = ["name" ~= name] <> logRecord.attrs} | logRecord <- logRecords]+ where+  name = C.processorName (.logs) (logConfig $ Proxy @log) fullConfig++toLogRecord :: LogRecord -> OL.LogRecord+toLogRecord l =+  messageWith+    [ OL.body .~ messageWith [OC.stringValue .~ l.value]+    , OL.timeUnixNano .~ fromMaybe 0 l.maybeTimeUnixNano+    , OL.observedTimeUnixNano .~ fromMaybe 0 l.maybeTimeUnixNano+    , OL.severityNumber .~ toSeverityNumber l.maybeSeverity+    , OL.attributes .~ toMaybeKeyValues l.attrs+    ]+ where+  toSeverityNumber :: Maybe Severity -> OL.SeverityNumber+  toSeverityNumber = maybe OL.SEVERITY_NUMBER_UNSPECIFIED (toEnum . (.value) . DS.toSeverityNumber)
+ src-app/GHC/Eventlog/Live/App/Exporter/Otlp/Metrics.hs view
@@ -0,0 +1,310 @@+{-# OPTIONS_GHC -Wno-orphans #-}++module GHC.Eventlog.Live.App.Exporter.Otlp.Metrics (+  -- * Export+  exportResourceMetrics,++  -- * Conversion+  toExportMetricsServiceRequest,+  toResourceMetrics,+  toScopeMetrics,+  toMetric,+) where++import Control.Exception (SomeException (..), catch)+import Control.Monad (unless)+import Control.Monad.IO.Class (MonadIO (..))+import Data.Int (Int16, Int32, Int64, Int8)+import Data.Machine (ProcessT, traversing)+import Data.Maybe (fromMaybe)+import Data.Proxy (Proxy (..))+import Data.Semigroup (Sum (..))+import Data.Vector qualified as V+import Data.Word (Word16, Word32, Word64, Word8)+import GHC.Eventlog.Live.App.Exporter.Otlp.Core (CanExportToConsole, CanExportToOltpViaHttpProtobuf (..), ExportError (..), Exporter (..), export, ifNonEmpty, messageWith, toMaybeKeyValues)+import GHC.Eventlog.Live.Config (FullConfig)+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Logger (ExportResult (..), InternalMetric (..), Logger, logException, logMetric)+import GHC.Eventlog.Live.Types.Metrics (KnownMetric (..), KnownMetricKind (..), KnownMetricType (..), KnownMetricUnit (..), Metric (..), SAggregationTemporality (..), SMetricKind (..), SMetricType (..), SMonotonicity (..), SomeMetrics (..), metricConfig, toUCUM)+import Lens.Family2 ((.~), (^.))+import Network.GRPC.Common qualified as G+import Network.GRPC.Common.Protobuf (Protobuf)+import Proto.Opentelemetry.Proto.Collector.Metrics.V1.MetricsService qualified as OMS+import Proto.Opentelemetry.Proto.Collector.Metrics.V1.MetricsService_Fields qualified as OMS+import Proto.Opentelemetry.Proto.Common.V1.Common qualified as OC+import Proto.Opentelemetry.Proto.Metrics.V1.Metrics qualified as OM+import Proto.Opentelemetry.Proto.Metrics.V1.Metrics_Fields qualified as OM+import Proto.Opentelemetry.Proto.Resource.V1.Resource qualified as OR++--------------------------------------------------------------------------------+-- OpenTelemetry Exporter for Metrics++exportResourceMetrics ::+  Logger IO ->+  Exporter ->+  ProcessT IO OMS.ExportMetricsServiceRequest ()+exportResourceMetrics logger exporter =+  traversing sendResourceMetrics+ where+  sendResourceMetrics :: OMS.ExportMetricsServiceRequest -> IO ()+  sendResourceMetrics exportMetricsServiceRequest =+    doExport `catch` handleSomeException+   where+    doExport :: IO ()+    doExport = do+      resp <- export @OMS.MetricsService @"export" logger exporter exportMetricsServiceRequest+      let !exported = countDataPointsInExportMetricsServiceRequest exportMetricsServiceRequest+      let !rejected = resp ^. OMS.partialSuccess . OMS.rejectedDataPoints+      liftIO (logMetric logger ExportMetrics ExportResult{..})+      unless (rejected == 0) $+        liftIO (logException logger $ ExportError $ resp ^. OMS.partialSuccess . OMS.errorMessage)++    handleSomeException :: SomeException -> IO ()+    handleSomeException = logException logger++--------------------------------------------------------------------------------+-- CanExportToConsole++instance CanExportToConsole OMS.MetricsService "export"++--------------------------------------------------------------------------------+-- CanExportToOltpViaGrpc++type instance G.RequestMetadata (Protobuf OMS.MetricsService meth) = G.NoMetadata+type instance G.ResponseInitialMetadata (Protobuf OMS.MetricsService meth) = G.NoMetadata+type instance G.ResponseTrailingMetadata (Protobuf OMS.MetricsService meth) = G.NoMetadata++--------------------------------------------------------------------------------+-- CanExportToOltpViaHttpProtobuf++instance CanExportToOltpViaHttpProtobuf OMS.MetricsService "export" where+  apiPath :: String+  apiPath = "/v1/metrics"++--------------------------------------------------------------------------------+-- Internal Helpers+--------------------------------------------------------------------------------++{- |+Internal helper.+Count the number of `OM.NumberDataPoint` values in an `OMS.ExportMetricsServiceRequest`.+-}+countDataPointsInExportMetricsServiceRequest :: OMS.ExportMetricsServiceRequest -> Int64+countDataPointsInExportMetricsServiceRequest exportMetricsServiceRequest =+  getSum $ foldMap (Sum . countDataPointsInResourceMetrics) (exportMetricsServiceRequest ^. OMS.vec'resourceMetrics)++{- |+Internal helper.+Count the number of `OM.NumberDataPoint` values in an `OM.ResourceMetrics`.+-}+countDataPointsInResourceMetrics :: OM.ResourceMetrics -> Int64+countDataPointsInResourceMetrics resourceMetrics =+  getSum $ foldMap (Sum . countDataPointsInScopeMetrics) (resourceMetrics ^. OM.vec'scopeMetrics)++{- |+Internal helper.+Count the number of `OM.NumberDataPoint` values in an `OM.ScopeMetrics`.+-}+countDataPointsInScopeMetrics :: OM.ScopeMetrics -> Int64+countDataPointsInScopeMetrics scopeMetrics =+  getSum $ foldMap (Sum . countDataPointsInMetric) (scopeMetrics ^. OM.vec'metrics)++{- |+Internal helper.+Count the number of `OM.NumberDataPoint` values in an `OM.Metric`.+-}+countDataPointsInMetric :: OM.Metric -> Int64+countDataPointsInMetric metric =+  fromIntegral $+    case metric ^. OM.maybe'data' of+      Nothing -> 0+      Just (OM.Metric'Gauge gauge) ->+        V.length (gauge ^. OM.vec'dataPoints)+      Just (OM.Metric'Sum sum_) ->+        V.length (sum_ ^. OM.vec'dataPoints)+      Just (OM.Metric'Histogram histogram) ->+        V.length (histogram ^. OM.vec'dataPoints)+      Just (OM.Metric'ExponentialHistogram exponentialHistogram) ->+        V.length (exponentialHistogram ^. OM.vec'dataPoints)+      Just (OM.Metric'Summary summary) ->+        V.length (summary ^. OM.vec'dataPoints)++--------------------------------------------------------------------------------+-- Conversion to OTLP+--------------------------------------------------------------------------------++toExportMetricsServiceRequest :: [OM.ResourceMetrics] -> OMS.ExportMetricsServiceRequest+toExportMetricsServiceRequest resourceMetrics =+  messageWith [OM.resourceMetrics .~ resourceMetrics]+{-# INLINE toExportMetricsServiceRequest #-}++toResourceMetrics :: OR.Resource -> [OM.ScopeMetrics] -> Maybe OM.ResourceMetrics+toResourceMetrics resource scopeMetrics =+  ifNonEmpty scopeMetrics $+    messageWith [OM.resource .~ resource, OM.scopeMetrics .~ scopeMetrics]+{-# INLINE toResourceMetrics #-}++toScopeMetrics :: OC.InstrumentationScope -> [OM.Metric] -> Maybe OM.ScopeMetrics+toScopeMetrics instrumentationScope metrics =+  ifNonEmpty metrics $+    messageWith [OM.scope .~ instrumentationScope, OM.metrics .~ metrics]+{-# INLINE toScopeMetrics #-}++toMetric ::+  FullConfig ->+  SomeMetrics ->+  Maybe OM.Metric+toMetric fullConfig (SomeMetrics (metric :: Proxy metric) measurements) = do+  metricData <- toMetric'Data metric (metricToNumberDataPoint metric <$> measurements)+  pure $+    messageWith $+      [ OM.name .~ C.processorName (.metrics) (metricConfig $ Proxy @metric) fullConfig+      , maybe id (OM.description .~) $ C.processorDescription (.metrics) (metricConfig $ Proxy @metric) fullConfig+      , OM.unit .~ toUCUM (metricUnitSing (Proxy @(GetMetricUnit metric)))+      , OM.maybe'data' .~ Just metricData+      ]+{-# INLINE toMetric #-}++toMetric'Data ::+  (KnownMetric metric) =>+  Proxy metric ->+  [OM.NumberDataPoint] ->+  Maybe OM.Metric'Data+toMetric'Data (_metric :: Proxy metric) dataPoints =+  ifNonEmpty dataPoints $+    case metricKindSing (Proxy @(GetMetricKind metric)) of+      SGauge ->+        OM.Metric'Gauge . messageWith $+          [ OM.dataPoints .~ dataPoints+          ]+      SSum sAggregationTemporality sMonotonicity ->+        OM.Metric'Sum . messageWith $+          [ OM.dataPoints .~ dataPoints+          , OM.aggregationTemporality .~ toAggregationTemporality sAggregationTemporality+          , OM.isMonotonic .~ isMonotonic sMonotonicity+          ]+{-# INLINE toMetric'Data #-}++metricToNumberDataPoint ::+  (KnownMetric metric) =>+  Proxy metric ->+  Metric (GetMetricType metric) ->+  OM.NumberDataPoint+metricToNumberDataPoint (metric :: Proxy metric) =+  metricTypeIsNumberDataPoint'Value metric toNumberDataPoint+{-# INLINE metricToNumberDataPoint #-}++toAggregationTemporality :: SAggregationTemporality aggregationTemporality -> OM.AggregationTemporality+toAggregationTemporality = \case+  SCumulative -> OM.AGGREGATION_TEMPORALITY_CUMULATIVE+  SDelta -> OM.AGGREGATION_TEMPORALITY_DELTA+{-# INLINE toAggregationTemporality #-}++isMonotonic :: SMonotonicity monotonicity -> Bool+isMonotonic = \case+  SMonotonic -> True+  SNonMonotonic -> False+{-# INLINE isMonotonic #-}++toNumberDataPoint :: (IsNumberDataPoint'Value v) => Metric v -> OM.NumberDataPoint+toNumberDataPoint i =+  messageWith+    [ OM.maybe'value .~ Just (toNumberDataPoint'Value i.value)+    , OM.timeUnixNano .~ fromMaybe 0 i.maybeTimeUnixNano+    , OM.startTimeUnixNano .~ fromMaybe 0 i.maybeStartTimeUnixNano+    , OM.attributes .~ toMaybeKeyValues i.attrs+    ]++{- |+Internal helper.++Every supported metric type has an instance of `IsNumberDataPoint'Value`.+-}+metricTypeIsNumberDataPoint'Value ::+  (KnownMetric metric) =>+  Proxy metric -> ((IsNumberDataPoint'Value (GetMetricType metric)) => a) -> a+metricTypeIsNumberDataPoint'Value (_proxy :: Proxy metric) x =+  case metricTypeSing (Proxy :: Proxy (GetMetricType metric)) of+    SMetricTypeFloat -> x+    SMetricTypeDouble -> x+    SMetricTypeWord -> x+    SMetricTypeWord8 -> x+    SMetricTypeWord16 -> x+    SMetricTypeWord32 -> x+    SMetricTypeWord64 -> x+    SMetricTypeInt -> x+    SMetricTypeInt8 -> x+    SMetricTypeInt16 -> x+    SMetricTypeInt32 -> x+    SMetricTypeInt64 -> x+{-# INLINE metricTypeIsNumberDataPoint'Value #-}++{- |+Internal helper.++Class of types that can be converted to `OM.NumberDataPoint'Value` values.+-}+class IsNumberDataPoint'Value v where+  toNumberDataPoint'Value :: v -> OM.NumberDataPoint'Value++instance IsNumberDataPoint'Value Float where+  toNumberDataPoint'Value :: Float -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsDouble . realToFrac+  {-# INLINE toNumberDataPoint'Value #-}++instance IsNumberDataPoint'Value Double where+  toNumberDataPoint'Value :: Double -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsDouble+  {-# INLINE toNumberDataPoint'Value #-}++instance IsNumberDataPoint'Value Word8 where+  toNumberDataPoint'Value :: Word8 -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsInt . fromIntegral+  {-# INLINE toNumberDataPoint'Value #-}++instance IsNumberDataPoint'Value Word16 where+  toNumberDataPoint'Value :: Word16 -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsInt . fromIntegral+  {-# INLINE toNumberDataPoint'Value #-}++instance IsNumberDataPoint'Value Word32 where+  toNumberDataPoint'Value :: Word32 -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsInt . fromIntegral+  {-# INLINE toNumberDataPoint'Value #-}++-- | __Warning__: This instance may cause overflow.+instance IsNumberDataPoint'Value Word64 where+  toNumberDataPoint'Value :: Word64 -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsInt . fromIntegral+  {-# INLINE toNumberDataPoint'Value #-}++-- | __Warning__: This instance may cause overflow.+instance IsNumberDataPoint'Value Word where+  toNumberDataPoint'Value :: Word -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsInt . fromIntegral+  {-# INLINE toNumberDataPoint'Value #-}++instance IsNumberDataPoint'Value Int8 where+  toNumberDataPoint'Value :: Int8 -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsInt . fromIntegral+  {-# INLINE toNumberDataPoint'Value #-}++instance IsNumberDataPoint'Value Int16 where+  toNumberDataPoint'Value :: Int16 -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsInt . fromIntegral+  {-# INLINE toNumberDataPoint'Value #-}++instance IsNumberDataPoint'Value Int32 where+  toNumberDataPoint'Value :: Int32 -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsInt . fromIntegral+  {-# INLINE toNumberDataPoint'Value #-}++instance IsNumberDataPoint'Value Int64 where+  toNumberDataPoint'Value :: Int64 -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsInt+  {-# INLINE toNumberDataPoint'Value #-}++instance IsNumberDataPoint'Value Int where+  toNumberDataPoint'Value :: Int -> OM.NumberDataPoint'Value+  toNumberDataPoint'Value = OM.NumberDataPoint'AsInt . fromIntegral+  {-# INLINE toNumberDataPoint'Value #-}
+ src-app/GHC/Eventlog/Live/App/Exporter/Otlp/Profiles.hs view
@@ -0,0 +1,284 @@+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_GHC -Wno-orphans #-}++module GHC.Eventlog.Live.App.Exporter.Otlp.Profiles (+  -- * Export+  exportResourceProfiles,++  -- * Conversion to OTLP+  toExportProfileServiceRequest,+  toProfilesData,+  toResourceProfiles,+  toScopeProfiles,+  toProfiles,+)+where++import Control.Exception (SomeException (..), catch)+import Control.Monad (unless)+import Control.Monad.IO.Class (MonadIO (..))+import Control.Monad.Trans.State.Strict (StateT (..))+import Data.Bifunctor (Bifunctor (..))+import Data.Functor.Identity (Identity (..))+import Data.Int (Int64)+import Data.Machine (ProcessT, traversing)+import Data.Maybe (catMaybes)+import Data.Proxy (Proxy (..))+import Data.Semigroup (Sum (..))+import Data.Text qualified as T+import Data.Vector (Vector)+import Data.Vector qualified as V+import Data.Word (Word32)+import GHC.Eventlog.Live.App.Exporter.Otlp.Core+import GHC.Eventlog.Live.App.Exporter.Otlp.ProfilesDictionary (ProfilesDictionary, SymbolIndex)+import GHC.Eventlog.Live.App.Exporter.Otlp.ProfilesDictionary qualified as PD+import GHC.Eventlog.Live.Config (FullConfig (..))+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Logger (ExportResult (..), InternalMetric (..), Logger, logException, logMetric)+import GHC.Eventlog.Live.Types.Attribute ((~=))+import GHC.Eventlog.Live.Types.Profiles (KnownProfile (..), Location (..), Sample (..), SomeSamples (..), profileConfig)+import GHC.IsList (IsList (..))+import GHC.TypeLits (symbolVal)+import IpeDB.Types.SrcLoc (Point (..), SrcLoc (..))+import Lens.Family2 ((.~), (^.))+import Network.GRPC.Common qualified as G+import Network.GRPC.Common.Protobuf (Protobuf)+import Proto.Opentelemetry.Proto.Collector.Profiles.V1development.ProfilesService qualified as OPS+import Proto.Opentelemetry.Proto.Collector.Profiles.V1development.ProfilesService_Fields qualified as OPS+import Proto.Opentelemetry.Proto.Common.V1.Common qualified as OC+import Proto.Opentelemetry.Proto.Profiles.V1development.Profiles qualified as OP+import Proto.Opentelemetry.Proto.Profiles.V1development.Profiles_Fields qualified as OP+import Proto.Opentelemetry.Proto.Resource.V1.Resource qualified as OR++--------------------------------------------------------------------------------+-- OpenTelemetry Exporter for Profiles++exportResourceProfiles ::+  Logger IO ->+  Exporter ->+  ProcessT IO OPS.ExportProfilesServiceRequest ()+exportResourceProfiles logger exporter =+  traversing sendResourceProfiles+ where+  sendResourceProfiles :: OPS.ExportProfilesServiceRequest -> IO ()+  sendResourceProfiles exportProfilesServiceRequest =+    doExport `catch` handleSomeException+   where+    doExport :: IO ()+    doExport = do+      resp <- export @OPS.ProfilesService @"export" logger exporter exportProfilesServiceRequest+      let !exported = countSamplesInExportProfileServiceRequest exportProfilesServiceRequest+      let !rejected = resp ^. OPS.partialSuccess . OPS.rejectedProfiles+      liftIO (logMetric logger ExportSamples ExportResult{..})+      unless (rejected == 0) $+        liftIO (logException logger $ ExportError $ resp ^. OPS.partialSuccess . OPS.errorMessage)++    handleSomeException :: SomeException -> IO ()+    handleSomeException = logException logger++--------------------------------------------------------------------------------+-- CanExportToConsole++instance CanExportToConsole OPS.ProfilesService "export"++--------------------------------------------------------------------------------+-- CanExportToOltpViaGrpc++type instance G.RequestMetadata (Protobuf OPS.ProfilesService meth) = G.NoMetadata+type instance G.ResponseInitialMetadata (Protobuf OPS.ProfilesService meth) = G.NoMetadata+type instance G.ResponseTrailingMetadata (Protobuf OPS.ProfilesService meth) = G.NoMetadata++--------------------------------------------------------------------------------+-- CanExportToOltpViaHttpProtobuf++instance CanExportToOltpViaHttpProtobuf OPS.ProfilesService "export" where+  apiPath :: String+  apiPath = "/v1development/profiles"++--------------------------------------------------------------------------------+-- Internal Helpers+--------------------------------------------------------------------------------++{- |+Internal helper.+Count the number of 'OP.Sample' values in an 'OPS.ExportProfilesServiceRequest'.+-}+{-# SPECIALIZE countSamplesInExportProfileServiceRequest :: OPS.ExportProfilesServiceRequest -> Int64 #-}+{-# SPECIALIZE countSamplesInExportProfileServiceRequest :: OPS.ExportProfilesServiceRequest -> Word #-}+countSamplesInExportProfileServiceRequest :: (Integral i) => OPS.ExportProfilesServiceRequest -> i+countSamplesInExportProfileServiceRequest exportProfileServiceRequest =+  getSum $ foldMap (Sum . countSamplesInResourceProfiles) (exportProfileServiceRequest ^. OPS.vec'resourceProfiles)++countSamplesInResourceProfiles :: (Integral i) => OP.ResourceProfiles -> i+countSamplesInResourceProfiles resourceProfiles =+  getSum $ foldMap (Sum . countSamplesInScopeProfiles) (resourceProfiles ^. OP.vec'scopeProfiles)++countSamplesInScopeProfiles :: (Integral i) => OP.ScopeProfiles -> i+countSamplesInScopeProfiles scopeProfiles =+  getSum $ foldMap (Sum . countSamplesInProfile) (scopeProfiles ^. OP.vec'profiles)++countSamplesInProfile :: (Integral i) => OP.Profile -> i+countSamplesInProfile profile =+  fromIntegral $+    V.length (profile ^. OP.vec'samples)++--------------------------------------------------------------------------------+-- Translation to OTLP profiles+--------------------------------------------------------------------------------++toExportProfileServiceRequest :: OP.ProfilesData -> OPS.ExportProfilesServiceRequest+toExportProfileServiceRequest profilesData =+  messageWith+    [ OPS.resourceProfiles .~ profilesData ^. OPS.resourceProfiles+    , OPS.dictionary .~ profilesData ^. OPS.dictionary+    ]++toProfilesData :: [OP.ResourceProfiles] -> OP.ProfilesDictionary -> Maybe OP.ProfilesData+toProfilesData resourceProfiles dictionary =+  ifNonEmpty resourceProfiles $+    messageWith [OP.resourceProfiles .~ resourceProfiles, OP.dictionary .~ dictionary]++toResourceProfiles :: OR.Resource -> [OP.ScopeProfiles] -> Maybe OP.ResourceProfiles+toResourceProfiles resource scopeProfiles =+  ifNonEmpty scopeProfiles $+    messageWith [OP.resource .~ resource, OP.scopeProfiles .~ scopeProfiles]++toScopeProfiles :: OC.InstrumentationScope -> [OP.Profile] -> Maybe OP.ScopeProfiles+toScopeProfiles instrumentationScope profiles =+  ifNonEmpty profiles $+    messageWith [OP.scope .~ instrumentationScope, OP.profiles .~ profiles]++toProfiles ::+  FullConfig ->+  [SomeSamples] ->+  Maybe ([OP.Profile], OP.ProfilesDictionary)+toProfiles fullConfig profiles =+  ifNonEmpty opProfiles opProfilesData+ where+  opProfilesData@(opProfiles, _) =+    second PD.toProfilesDictionary . runIdentity . flip runStateT PD.empty $ do+      traverse (getProfile fullConfig) profiles++--------------------------------------------------------------------------------+-- Translating profiles to OTLP profiles++getProfile ::+  forall m.+  (Monad m) =>+  FullConfig ->+  SomeSamples ->+  StateT ProfilesDictionary m OP.Profile+getProfile fullConfig (SomeSamples (profile :: Proxy profile) samples) = do+  -- Construct the sample type.+  let metricType = symbolVal (Proxy @(GetProfileMetricName profile))+  let metricUnit = symbolVal (Proxy @(GetProfileMetricUnit profile))+  typeStrindex <- PD.getText (T.pack metricType)+  unitStrindex <- PD.getText (T.pack metricUnit)+  let opSampleType :: OP.ValueType+      opSampleType =+        messageWith+          [ OP.typeStrindex .~ typeStrindex+          , OP.unitStrindex .~ unitStrindex+          ]++  -- Construct the profile.+  opSamples <- traverse (getSample fullConfig profile) samples+  let opProfile :: OP.Profile+      opProfile =+        messageWith+          [ OP.samples .~ opSamples+          , OP.sampleType .~ opSampleType+          ]+  pure opProfile++getSample ::+  (Monad m, KnownProfile profile) =>+  FullConfig ->+  Proxy profile ->+  Sample (GetProfileMetricType profile) ->+  StateT ProfilesDictionary m OP.Sample+getSample fullConfig (_profile :: Proxy profile) sample = do+  -- Encode the stack.+  stackIndex <- getStack sample.stack++  -- Encode the attributes.+  let name = C.processorName (.profiles) (profileConfig $ Proxy @profile) fullConfig+  let attributes = "__name__" ~= name : toList sample.attrs+  attributeIndices <- catMaybes <$> traverse PD.getAttr attributes++  -- Construct the sample.+  let opSample :: OP.Sample+      opSample =+        messageWith $+          [ OP.values .~ [fromIntegral @(GetProfileMetricType profile) @Int64 sample.value]+          , OP.stackIndex .~ stackIndex+          , OP.attributeIndices .~ attributeIndices+          , OP.timestampsUnixNano .~? sequence [sample.maybeTimeUnixNano]+          ]+  pure opSample++getStack ::+  (Monad m) =>+  Vector Location ->+  StateT ProfilesDictionary m SymbolIndex+getStack stack = do+  -- Encode the locations.+  locationIndices <- traverse getLocation stack++  -- Create the stack.+  let opStack :: OP.Stack+      opStack =+        messageWith $+          [ OP.vec'locationIndices .~ V.convert locationIndices+          ]++  -- Index the stack.+  PD.getStack opStack++getLocation ::+  (Monad m) =>+  Location ->+  StateT ProfilesDictionary m SymbolIndex+getLocation Location{..} = do+  -- Encode the filename.+  filenameStrindex <-+    if null srcLoc.srcFilePath+      then pure 0+      else PD.getString srcLoc.srcFilePath++  -- Encode the function name.+  nameStrindex <- PD.getText name++  -- Encode the start point.+  let !maybeStart = (.start) <$> srcLoc.srcRange+  let !maybeStartLine = fromIntegral @Word32 @Int64 . (.line) <$> maybeStart+  let !maybeStartColumn = fromIntegral @Word32 @Int64 . (.column) <$> maybeStart++  -- Encode the function metadata.+  let function :: OP.Function+      function =+        messageWith+          [ OP.nameStrindex .~ nameStrindex+          , OP.filenameStrindex .~ filenameStrindex+          , OP.startLine .~? maybeStartLine+          ]+  functionIndex <- PD.getFunction function++  -- Encode the location metadata.+  let line :: OP.Line+      line =+        messageWith+          [ OP.functionIndex .~ functionIndex+          , OP.line .~? maybeStartLine+          , OP.column .~? maybeStartColumn+          ]++  -- Create the location.+  let opLocation :: OP.Location+      opLocation =+        messageWith $+          [ OP.lines .~ [line]+          ]++  -- Index the location.+  PD.getLocation opLocation
+ src-app/GHC/Eventlog/Live/App/Exporter/Otlp/ProfilesDictionary.hs view
@@ -0,0 +1,173 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.Processor.Core.Profiles+Description : Abstraction over ProfilesDictionary for the OTLP protocol.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.App.Exporter.Otlp.ProfilesDictionary (+  -- * Dictionary for deduplication logic of common values+  ProfilesDictionary,+  empty,++  -- * Retrieve the 'SymbolIndex' for various 'OP.ProfilesData' fields+  SymbolIndex,+  getLocation,+  getFunction,+  getText,+  getString,+  getMapping,+  getLink,+  getAttribute,+  getAttr,+  getStack,++  -- * Convert data to the formats used by @hs-opentelemetry-otlp@.+  toProfilesDictionary,+)+where++import Control.Monad.Trans.State.Strict (StateT)+import Control.Monad.Trans.State.Strict qualified as State+import Data.ProtoLens (Message (..))+import Data.Text (Text)+import Data.Text qualified as T+import GHC.Eventlog.Live.App.Exporter.Otlp.Core (messageWith, toMaybeAnyValue)+import GHC.Eventlog.Live.App.Exporter.Otlp.SymbolTable (SymbolIndex, SymbolTable)+import GHC.Eventlog.Live.App.Exporter.Otlp.SymbolTable qualified as ST+import GHC.Eventlog.Live.Types.Attribute (Attr)+import GHC.Generics (Generic)+import Lens.Family2 (Lens', (.~), (^.))+import Lens.Family2.Unchecked (lens)+import Proto.Opentelemetry.Proto.Profiles.V1development.Profiles qualified as OP+import Proto.Opentelemetry.Proto.Profiles.V1development.Profiles_Fields qualified as OP++data ProfilesDictionary = ProfilesDictionary+  { locationTable :: SymbolTable OP.Location+  {- ^ Common 'OP.Location' table, first entry is the 'defMessage'.+  This holds for OTLP 1.9.0.+  -}+  , functionTable :: SymbolTable OP.Function+  {- ^ Common 'OP.Function' table, first entry is the 'defMessage'.+  This holds for OTLP 1.9.0.+  -}+  , stringTable :: SymbolTable Text+  {- ^ Common string table, the first entry must be "" per the protobuf+  documentation.++  @+   // A common table for strings referenced by various messages.+   // string_table[0] must always be "".+   repeated string string_table = 5;+  @+  -}+  , mappingTable :: SymbolTable OP.Mapping+  {- ^ Common 'OP.Mapping' table, first entry is the 'defMessage'.+  This holds for OTLP 1.9.0.+  -}+  , linkTable :: SymbolTable OP.Link+  {- ^ Common 'OP.Link' table, first entry is the 'defMessage'.+  This holds for OTLP 1.9.0.+  -}+  , attributeTable :: SymbolTable OP.KeyValueAndUnit+  {- ^ Common 'OP.KeyValueAndUnit' table, first entry is the 'defMessage'.+  This holds for OTLP 1.9.0.+  -}+  , stackTable :: SymbolTable OP.Stack+  {- ^ Common 'OP.Stack' table, first entry is the 'defMessage'.+  This holds for OTLP 1.9.0.+  -}+  }+  deriving (Show, Ord, Eq, Generic)++toProfilesDictionary :: ProfilesDictionary -> OP.ProfilesDictionary+toProfilesDictionary st =+  messageWith+    [ OP.locationTable .~ locations st+    , OP.functionTable .~ functions st+    , OP.stringTable .~ strings st+    , OP.mappingTable .~ mappings st+    , OP.linkTable .~ links st+    , OP.attributeTable .~ attributes st+    , OP.stackTable .~ stacks st+    ]++empty :: ProfilesDictionary+empty =+  ProfilesDictionary+    { locationTable = ST.fromList [defMessage]+    , functionTable = ST.fromList [defMessage]+    , stringTable = ST.fromList [""]+    , mappingTable = ST.fromList [defMessage]+    , linkTable = ST.fromList [defMessage]+    , attributeTable = ST.fromList [defMessage]+    , stackTable = ST.fromList [defMessage]+    }++locations :: ProfilesDictionary -> [OP.Location]+locations pd = ST.toList pd.locationTable++functions :: ProfilesDictionary -> [OP.Function]+functions pd = ST.toList pd.functionTable++strings :: ProfilesDictionary -> [Text]+strings pd = ST.toList pd.stringTable++mappings :: ProfilesDictionary -> [OP.Mapping]+mappings pd = ST.toList pd.mappingTable++links :: ProfilesDictionary -> [OP.Link]+links pd = ST.toList pd.linkTable++attributes :: ProfilesDictionary -> [OP.KeyValueAndUnit]+attributes pd = ST.toList pd.attributeTable++stacks :: ProfilesDictionary -> [OP.Stack]+stacks pd = ST.toList pd.stackTable++getSymbolIndexFor :: (Ord a, Monad m) => Lens' ProfilesDictionary (SymbolTable a) -> a -> StateT ProfilesDictionary m SymbolIndex+getSymbolIndexFor accessor a = do+  st <- State.gets (^. accessor)+  let (si, pd') = ST.insert a st+  State.modify' (accessor .~ pd')+  pure si++getLocation :: (Monad m) => OP.Location -> StateT ProfilesDictionary m SymbolIndex+getLocation = getSymbolIndexFor (lens (.locationTable) (\pd st -> pd{locationTable = st}))++getFunction :: (Monad m) => OP.Function -> StateT ProfilesDictionary m SymbolIndex+getFunction = getSymbolIndexFor (lens (.functionTable) (\pd st -> pd{functionTable = st}))++getText :: (Monad m) => Text -> StateT ProfilesDictionary m SymbolIndex+getText = getSymbolIndexFor (lens (.stringTable) (\pd st -> pd{stringTable = st}))++getString :: (Monad m) => String -> StateT ProfilesDictionary m SymbolIndex+getString = getText . T.pack++getMapping :: (Monad m) => OP.Mapping -> StateT ProfilesDictionary m SymbolIndex+getMapping = getSymbolIndexFor (lens (.mappingTable) (\pd st -> pd{mappingTable = st}))++getLink :: (Monad m) => OP.Link -> StateT ProfilesDictionary m SymbolIndex+getLink = getSymbolIndexFor (lens (.linkTable) (\pd st -> pd{linkTable = st}))++getAttribute :: (Monad m) => OP.KeyValueAndUnit -> StateT ProfilesDictionary m SymbolIndex+getAttribute = getSymbolIndexFor (lens (.attributeTable) (\pd st -> pd{attributeTable = st}))++getAttr :: (Monad m) => Attr -> StateT ProfilesDictionary m (Maybe SymbolIndex)+getAttr (key, value) =+  case toMaybeAnyValue value of+    Nothing ->+      pure Nothing+    Just anyValue -> do+      keyStrindex <- getText key+      let keyValueAndUnit :: OP.KeyValueAndUnit+          keyValueAndUnit =+            messageWith+              [ OP.keyStrindex .~ keyStrindex+              , OP.value .~ anyValue+              ]+      Just <$> getAttribute keyValueAndUnit++getStack :: (Monad m) => OP.Stack -> StateT ProfilesDictionary m SymbolIndex+getStack = getSymbolIndexFor (lens (.stackTable) (\pd st -> pd{stackTable = st}))
+ src-app/GHC/Eventlog/Live/App/Exporter/Otlp/SymbolTable.hs view
@@ -0,0 +1,76 @@+{- |+Module      : GHC.Eventlog.Live.App.Exporter.Otlp.SymbolTable+Description : Abstract symbol table datatype.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.App.Exporter.Otlp.SymbolTable (+  SymbolIndex,+  SymbolTable,+  empty,+  elemIndex,+  toList,+  fromList,+  insert,+)+where++import Data.Int (Int32)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import GHC.Generics (Generic)++type SymbolIndex = Int32++data SymbolTable a+  = SymbolTable+  { nextSymbolIndex :: !SymbolIndex+  {- ^+  The next unused `SymbolIndex`.++  > st.nextSymbolIndex == length st.entriesRev+  -}+  , entryToSymbolIndex :: !(Map a SymbolIndex)+  {- ^+  A map from entries to their `SymbolIndex`.++  > toList st !! (st.entryToSymbolIndex Map.! a) == a+  -}+  , entriesRev :: ![a] -- reverse order of insertion into entryToSymbolIndex++  {- ^+  A list of entries in the `SymbolTable` in reverse order.+  -}+  }+  deriving (Show, Ord, Eq, Generic)++empty :: SymbolTable a+empty =+  SymbolTable+    { nextSymbolIndex = 0+    , entryToSymbolIndex = Map.empty+    , entriesRev = []+    }++elemIndex :: (Ord a) => a -> SymbolTable a -> Maybe SymbolIndex+elemIndex a st = Map.lookup a st.entryToSymbolIndex++toList :: SymbolTable a -> [a]+toList st = reverse st.entriesRev++fromList :: (Ord a) => [a] -> SymbolTable a+fromList = foldr (\val st -> snd (insert val st)) empty++insert :: (Ord a) => a -> SymbolTable a -> (SymbolIndex, SymbolTable a)+insert a st = (si, st'')+ where+  ((si, isNew, st'), entryToSymbolIndex') = Map.alterF (updateEntry st) a st.entryToSymbolIndex+  entriesRev' = if isNew then a : st'.entriesRev else st'.entriesRev+  st'' = st'{entryToSymbolIndex = entryToSymbolIndex', entriesRev = entriesRev'}++updateEntry :: SymbolTable a -> Maybe SymbolIndex -> ((SymbolIndex, Bool, SymbolTable a), Maybe SymbolIndex)+updateEntry st Nothing = let (si, st') = freshSymbolIndex st in ((si, True, st'), Just si)+updateEntry st (Just si) = ((si, False, st), Just si)++freshSymbolIndex :: SymbolTable a -> (SymbolIndex, SymbolTable a)+freshSymbolIndex st = (st.nextSymbolIndex, st{nextSymbolIndex = st.nextSymbolIndex + 1})
+ src-app/GHC/Eventlog/Live/App/Exporter/Otlp/Traces.hs view
@@ -0,0 +1,151 @@+{-# OPTIONS_GHC -Wno-orphans #-}++module GHC.Eventlog.Live.App.Exporter.Otlp.Traces (+  -- * Export+  exportResourceSpans,++  -- * Conversion to OTLP+  toExportTracesServiceRequest,+  toResourceSpans,+  toScopeSpans,+  toSpans,+) where++import Control.Exception (SomeException (..), catch)+import Control.Monad (unless)+import Control.Monad.IO.Class (MonadIO (..))+import Data.Int (Int64)+import Data.Machine (ProcessT, traversing)+import Data.Proxy (Proxy (..))+import Data.Semigroup (Sum (..))+import Data.Vector qualified as V+import GHC.Eventlog.Live.App.Exporter.Otlp.Core (CanExportToConsole, CanExportToOltpViaHttpProtobuf (..), ExportError (..), Exporter (..), export, ifNonEmpty, messageWith, toMaybeKeyValues)+import GHC.Eventlog.Live.Config (FullConfig)+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Logger (ExportResult (..), InternalMetric (..), Logger, logException, logMetric)+import GHC.Eventlog.Live.Types.Traces (SomeSpans (..), Span (..), traceConfig)+import Lens.Family2 ((.~), (^.))+import Network.GRPC.Common qualified as G+import Network.GRPC.Common.Protobuf (Protobuf)+import Proto.Opentelemetry.Proto.Collector.Trace.V1.TraceService qualified as OTS+import Proto.Opentelemetry.Proto.Collector.Trace.V1.TraceService_Fields qualified as OTS+import Proto.Opentelemetry.Proto.Common.V1.Common qualified as OC+import Proto.Opentelemetry.Proto.Resource.V1.Resource qualified as OR+import Proto.Opentelemetry.Proto.Trace.V1.Trace qualified as OT+import Proto.Opentelemetry.Proto.Trace.V1.Trace_Fields qualified as OT++--------------------------------------------------------------------------------+-- OpenTelemetry Exporter for Traces++exportResourceSpans ::+  Logger IO ->+  Exporter ->+  ProcessT IO OTS.ExportTraceServiceRequest ()+exportResourceSpans logger exporter =+  traversing sendResourceSpans+ where+  sendResourceSpans :: OTS.ExportTraceServiceRequest -> IO ()+  sendResourceSpans exportTraceServiceRequest =+    doExport `catch` handleSomeException+   where+    doExport :: IO ()+    doExport = do+      resp <- export @OTS.TraceService @"export" logger exporter exportTraceServiceRequest+      let !exported = countSpansInExportTraceServiceRequest exportTraceServiceRequest+      let !rejected = resp ^. OTS.partialSuccess . OTS.rejectedSpans+      liftIO (logMetric logger ExportSpans ExportResult{..})+      unless (rejected == 0) $+        liftIO (logException logger $ ExportError $ resp ^. OTS.partialSuccess . OTS.errorMessage)++    handleSomeException :: SomeException -> IO ()+    handleSomeException = logException logger++--------------------------------------------------------------------------------+-- CanExportToConsole++instance CanExportToConsole OTS.TraceService "export"++--------------------------------------------------------------------------------+-- CanExportToOltpViaGrpc++type instance G.RequestMetadata (Protobuf OTS.TraceService meth) = G.NoMetadata+type instance G.ResponseInitialMetadata (Protobuf OTS.TraceService meth) = G.NoMetadata+type instance G.ResponseTrailingMetadata (Protobuf OTS.TraceService meth) = G.NoMetadata++--------------------------------------------------------------------------------+-- CanExportToOltpViaHttpProtobuf++instance CanExportToOltpViaHttpProtobuf OTS.TraceService "export" where+  apiPath :: String+  apiPath = "/v1/traces"++--------------------------------------------------------------------------------+-- Internal Helpers+--------------------------------------------------------------------------------++{- |+Internal helper.+Count the number of `OT.Span` values in an `OTS.ExportTraceServiceRequest`.+-}+{-# SPECIALIZE countSpansInExportTraceServiceRequest :: OTS.ExportTraceServiceRequest -> Int64 #-}+{-# SPECIALIZE countSpansInExportTraceServiceRequest :: OTS.ExportTraceServiceRequest -> Word #-}+countSpansInExportTraceServiceRequest :: (Integral i) => OTS.ExportTraceServiceRequest -> i+countSpansInExportTraceServiceRequest exportTraceServiceRequest =+  getSum $ foldMap (Sum . countSpansInResourceSpans) (exportTraceServiceRequest ^. OTS.vec'resourceSpans)++{- |+Internal helper.+Count the number of `OT.Span` values in an `OT.ResourceSpans`.+-}+{-# SPECIALIZE countSpansInResourceSpans :: OT.ResourceSpans -> Int64 #-}+{-# SPECIALIZE countSpansInResourceSpans :: OT.ResourceSpans -> Word #-}+countSpansInResourceSpans :: (Integral i) => OT.ResourceSpans -> i+countSpansInResourceSpans resourceSpans =+  getSum $ foldMap (Sum . countSpansInScopeSpans) (resourceSpans ^. OT.vec'scopeSpans)++{- |+Internal helper.+Count the number of `OT.Span` values in an `OT.ScopeSpans`.+-}+{-# SPECIALIZE countSpansInScopeSpans :: OT.ScopeSpans -> Int64 #-}+{-# SPECIALIZE countSpansInScopeSpans :: OT.ScopeSpans -> Word #-}+countSpansInScopeSpans :: (Integral i) => OT.ScopeSpans -> i+countSpansInScopeSpans scopeSpans =+  fromIntegral $+    V.length (scopeSpans ^. OT.vec'spans)++--------------------------------------------------------------------------------+-- Conversion to OTLP+--------------------------------------------------------------------------------++toExportTracesServiceRequest :: [OT.ResourceSpans] -> OTS.ExportTraceServiceRequest+toExportTracesServiceRequest resourceSpans =+  messageWith [OTS.resourceSpans .~ resourceSpans]+{-# INLINE toExportTracesServiceRequest #-}++toResourceSpans :: OR.Resource -> [OT.ScopeSpans] -> Maybe OT.ResourceSpans+toResourceSpans resource scopeSpans =+  ifNonEmpty scopeSpans $+    messageWith [OT.resource .~ resource, OT.scopeSpans .~ scopeSpans]+{-# INLINE toResourceSpans #-}++toScopeSpans :: OC.InstrumentationScope -> [OT.Span] -> Maybe OT.ScopeSpans+toScopeSpans instrumentationScope spans =+  ifNonEmpty spans $+    messageWith [OT.scope .~ instrumentationScope, OT.spans .~ spans]+{-# INLINE toScopeSpans #-}++toSpans :: FullConfig -> SomeSpans -> [OT.Span]+toSpans fullConfig (SomeSpans (_trace :: Proxy trace) spans) =+  map toSpan spans+ where+  toSpan :: Span -> OT.Span+  toSpan s =+    messageWith+      [ OT.name .~ C.processorName (.traces) (traceConfig $ Proxy @trace) fullConfig+      , OT.traceId .~ s.traceId+      , OT.spanId .~ s.spanId+      , OT.startTimeUnixNano .~ s.startTimeUnixNano+      , OT.endTimeUnixNano .~ s.endTimeUnixNano+      , OT.attributes .~ toMaybeKeyValues s.attrs+      ]
+ src-app/GHC/Eventlog/Live/App/Options.hs view
@@ -0,0 +1,226 @@+module GHC.Eventlog.Live.App.Options (+  Options (..),+  MyDebugOptions (..),+  OpenTelemetryOptions (..),+  options,+) where++import Control.Applicative (asum)+import Data.Char (isSpace)+import Data.Default (Default (..))+import Data.List qualified as L+import Data.Text qualified as T+import Data.Version (showVersion)+import GHC.Debug.Stub.Compat (MyGhcDebugSocket, maybeMyGhcDebugSocketParser)+import GHC.Eventlog.Live.App.Options.Raw (footerString, headerString, progDescString)+import GHC.Eventlog.Live.App.Server (ServerOptions, serverOptionsParser)+import GHC.Eventlog.Live.Config (Config)+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Options+import GHC.Eventlog.Live.Source.Core (EventlogSourceOptions (..))+import GHC.Eventlog.Socket.Compat (MyEventlogSocket (..), maybeMyEventlogSocketParser)+import GHC.RTS.Events (HeapProfBreakdown (..))+import Options.Applicative qualified as O+import Options.Applicative.Compat qualified as OC+import Options.Applicative.Extra qualified as OE+import Options.Applicative.Help.Chunk qualified as OHC+import Options.Applicative.Help.Pretty qualified as OHP+import Paths_eventlog_live qualified as EventlogLive++options :: O.ParserInfo Options+options =+  O.info+    ( optionsParser+        O.<**> defaultsPrinter+        O.<**> debugDefaultsPrinter+        O.<**> configJSONSchemaPrinter+        O.<**> OE.helperWith (O.long "help" <> O.help "Show this help text.")+        O.<**> OC.simpleVersioner (showVersion EventlogLive.version)+    )+    ( O.headerDoc (helpDoc headerString)+        <> O.progDescDoc (helpDoc progDescString)+        <> O.footerDoc (helpDoc footerString)+    )++{- |+Internal helper.++Render a text as an `OHP.Doc`.+-}+helpDoc :: String -> Maybe OHP.Doc+helpDoc doc+  | OHC.isEmpty (OHC.vcatChunks docChunks) = Nothing+  | otherwise = OHC.unChunk $ vcatChunks docChunks+ where+  docChunks :: [OHC.Chunk OHP.Doc]+  docChunks = helpDocLine <$> lines doc++  -- NOTE: Variant of vcatChunks that uses hardline+  vcatChunks :: [OHC.Chunk OHP.Doc] -> OHC.Chunk OHP.Doc+  vcatChunks = mconcat . L.intersperse (OHC.Chunk $ Just OHP.hardline)++{- |+Internal helper.++Internal accumulated state for `helpDocLine`.+-}+data LineAcc+  = Space {count :: !Int, chunk :: !(OHC.Chunk OHP.Doc)}+  | Token {token :: !String, chunk :: !(OHC.Chunk OHP.Doc)}++{- |+Internal helper.++Render a line as an `OHP.Doc`.+-}+helpDocLine :: String -> OHC.Chunk OHP.Doc+helpDocLine =+  asDoc True . L.foldl' trans empty . reverse+ where+  empty :: LineAcc+  empty = Space 0 mempty++  trans :: LineAcc -> Char -> LineAcc+  trans la@Space{..} c+    | isSpace c = Space{count = count + 1, ..}+    | count >= 2 = Token{token = [c], chunk = asDoc False la}+    | otherwise = Token{token = [c], ..}+  trans la@Token{..} c+    | isSpace c = Space{count = 1, chunk = asDoc False la}+    | otherwise = Token{token = c : token, ..}++  asDoc :: Bool -> LineAcc -> OHC.Chunk OHP.Doc+  asDoc isFinal = \case+    Space{..} ->+      OHP.indent (if isFinal then count else count - 1) <$> chunk+    Token{..} ->+      OHC.stringChunk token OHC.<</>> chunk++data Options = Options+  { eventlogSourceOptions :: EventlogSourceOptions+  , eventlogSocketTimeoutS :: Double+  , eventlogSocketTimeoutExponent :: Double+  , eventlogFlushIntervalS :: Double+  , maybeEventlogLogFile :: Maybe FilePath+  , maybeHeapProfBreakdown :: Maybe HeapProfBreakdown+  , maybeIpeDBPath :: Maybe FilePath+  , maybeCCDBPath :: Maybe FilePath+  , maybeConfigFile :: Maybe FilePath+  , serverOptions :: ServerOptions+  , myDebugOptions :: MyDebugOptions+  , openTelemetryOptions :: OpenTelemetryOptions+  }++optionsParser :: O.Parser Options+optionsParser =+  Options+    <$> eventlogSourceOptionsParser+    <*> eventlogSocketTimeoutSParser+    <*> eventlogSocketTimeoutExponentParser+    <*> eventlogFlushIntervalSParser+    <*> O.optional eventlogLogFileParser+    <*> O.optional heapProfBreakdownParser+    <*> O.optional ipeDBPathParser+    <*> O.optional ccDBPathParser+    <*> O.optional configFileParser+    <*> serverOptionsParser+    <*> myDebugOptionsParser+    <*> openTelemetryOptionsParser++--------------------------------------------------------------------------------+-- Configuration++configFileParser :: O.Parser FilePath+configFileParser =+  O.strOption+    ( O.long "config"+        <> O.metavar "FILE"+        <> O.help "The path to a detailed configuration file."+    )++defaultsPrinter :: O.Parser (a -> a)+defaultsPrinter =+  O.infoOption C.defaultConfigString . mconcat $+    [ O.long "print-defaults"+    , O.help "Print default configuration options."+    ]++configJSONSchemaPrinter :: O.Parser (a -> a)+configJSONSchemaPrinter =+  O.infoOption C.defaultConfigJSONSchemaString . mconcat $+    [ O.long "print-config-json-schema"+    , O.help "Print JSON Schema for configuration format."+    ]++debugDefaultsPrinter :: O.Parser (a -> a)+debugDefaultsPrinter =+  O.infoOption defaultConfigDebugString . mconcat $+    [ O.long "print-defaults-debug"+    , O.help "Print default configuration options using the parsed representation."+    , O.internal+    ]+ where+  defaultConfigDebugString =+    T.unpack . C.prettyConfig $ (def :: Config)++--------------------------------------------------------------------------------+-- InfoProv Tables++ipeDBPathParser :: O.Parser FilePath+ipeDBPathParser =+  O.strOption+    ( O.long "ipedb"+        <> O.metavar "FILE"+        <> O.help "The path to an IPE database."+    )++--------------------------------------------------------------------------------+-- CostCentre Tables++ccDBPathParser :: O.Parser FilePath+ccDBPathParser =+  O.strOption+    ( O.long "ccdb"+        <> O.metavar "FILE"+        <> O.help "The path a cost-centre database."+    )++--------------------------------------------------------------------------------+-- Debug Options++data MyDebugOptions = MyDebugOptions+  { maybeMyEventlogSocket :: Maybe MyEventlogSocket+  , maybeMyGhcDebugSocket :: Maybe MyGhcDebugSocket+  }++myDebugOptionsParser :: O.Parser MyDebugOptions+myDebugOptionsParser =+  OC.parserOptionGroup "Debug options:" $+    MyDebugOptions+      <$> maybeMyEventlogSocketParser+      <*> maybeMyGhcDebugSocketParser++--------------------------------------------------------------------------------+-- OpenTelemetry Options++newtype OpenTelemetryOptions = OpenTelemetryOptions+  { openTelemetryExporter :: Bool+  }++openTelemetryOptionsParser :: O.Parser OpenTelemetryOptions+openTelemetryOptionsParser =+  OC.parserOptionGroup "OpenTelemetry options:" $+    OpenTelemetryOptions+      <$> openTelemetryExporterParser++openTelemetryExporterParser :: O.Parser Bool+openTelemetryExporterParser =+  asum+    [ O.flag' True $+        O.long "otel-exporter"+          <> O.help "Enable the OpenTelemetry Exporter. Default."+    , O.flag' False $+        O.long "no-otel-exporter"+          <> O.help "Disable the Enable the OpenTelemetry Exporter."+    , pure True+    ]
+ src-app/GHC/Eventlog/Live/App/Options/Raw.hs view
@@ -0,0 +1,73 @@+{-# LANGUAGE TemplateHaskell #-}++{- |+Module      : GHC.Eventlog.Live.App.Options.Raw+Description : The implementation of @eventlog-live@.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.App.Options.Raw (+  headerString,+  progDescString,+  footerString,+) where++import Data.ByteString (ByteString)+import Data.FileEmbed (embedFileRelative)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE++{- |+Internal helper.++The help header as a `ByteString`.+-}+headerByteString :: ByteString+headerByteString = $(embedFileRelative "data/help.header.txt")++{- |+Internal helper.++The help header as a `String`.+-}+headerString :: String+headerString = fromByteString headerByteString++{- |+Internal helper.++The help program description as a `ByteString`.+-}+progDescByteString :: ByteString+progDescByteString = $(embedFileRelative "data/help.progDesc.txt")++{- |+Internal helper.++The help program description as a `String`.+-}+progDescString :: String+progDescString = fromByteString progDescByteString++{- |+Internal helper.++The help footer as a `ByteString`.+-}+footerByteString :: ByteString+footerByteString = $(embedFileRelative "data/help.footer.txt")++{- |+Internal helper.++The help footer as a `String`.+-}+footerString :: String+footerString = fromByteString footerByteString++{- |+Internal helper.+Decode a `ByteString` to a `String`.+-}+fromByteString :: ByteString -> String+fromByteString = T.unpack . TE.decodeUtf8Lenient
+ src-app/GHC/Eventlog/Live/App/Server.hs view
@@ -0,0 +1,342 @@+{-# LANGUAGE OverloadedStrings #-}++module GHC.Eventlog.Live.App.Server (+  ServerHandle (..),+  ControlHooks (..),+  startServer,+  ServerOptions (..),+  serverOptionsParser,+)+where++import Control.Applicative (asum)+import Control.Concurrent (forkIO, killThread)+import Control.Concurrent.LossyChan (InChan)+import Control.Monad (unless, when)+import Control.Monad.IO.Class (MonadIO (..))+import Data.ByteString.Char8 qualified as BSC+import Data.Char (isSpace)+import Data.Proxy (Proxy (..))+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import GHC.Eventlog.Live.App.Server.Control (ControlApi, ControlHooks (..), newControlServer, newDisabledControlServer, noopControlHooks)+import GHC.Eventlog.Live.App.Server.Control qualified as CF (control)+import GHC.Eventlog.Live.App.Server.Viewer (ViewerApi, viewerServer, viewerWsServerApp)+import GHC.Eventlog.Live.Logger (Logger, logDebug, logInfo, logTrace, logWarn)+import GHC.Eventlog.Live.Machine.Core (Tick)+import GHC.Eventlog.Live.Processor (ExportRequest)+import Network.Wai (Middleware)+import Network.Wai.Handler.Warp qualified as Warp+import Network.Wai.Handler.WebSockets (websocketsOr)+import Network.Wai.Middleware.Cors (CorsResourcePolicy (..), Origin, cors)+import Network.Wai.Middleware.RequestLogger qualified as RL+import Network.WebSockets (defaultConnectionOptions)+import Options.Applicative qualified as O+import Options.Applicative.Compat qualified as OC+import Options.Applicative.Extra.Feature qualified as OF+import Servant.API (Get, JSON, (:<|>) (..), (:>))+import Servant.Server (Handler, serve)+import System.Log.FastLogger (fromLogStr)+import Text.ParserCombinators.ReadP (ReadP)+import Text.ParserCombinators.ReadP qualified as P+import Web.Browser (openBrowser)++--------------------------------------------------------------------------------+-- Server+--------------------------------------------------------------------------------++data ServerHandle = ServerHandle+  { controlHooks :: ControlHooks+  , stop :: IO ()+  }++noopServerHandle :: ServerHandle+noopServerHandle =+  ServerHandle+    { controlHooks = noopControlHooks+    , stop = pure ()+    }++startServer ::+  Logger IO ->+  ServerOptions ->+  InChan (Tick ExportRequest) ->+  IO ServerHandle+startServer logger ServerOptions{..} exportRequestChan+  | viewer == ViewerDisabled && not control =+      pure noopServerHandle+  | otherwise = do+      -- Announce the server+      logInfo logger $ "Starting server on " <> T.show serverPort.port++      -- Create middleware that logs all incoming requests.+      requestLogger <- mkLoggerMiddleware logger++      -- Create CORS resource policy.+      --+      -- NOTE: The @wai-cors@ package lets the resource policy depend dynamically+      -- on the received request. However, it is difficult to expose this freedom+      -- via command-line arguments.+      --+      -- TODO: We might have to manually find the origin in the request, check it+      -- against the allow-list, and set the @corsOrigins@ field.+      let !corsResourcePolicy = mkCorsResourcePolicy serverCors++      -- Create the control server.+      (controlHooks, controlServer) <-+        (if control then newControlServer else newDisabledControlServer)+          logger+          corsResourcePolicy.corsIgnoreFailures++      -- Create the viewer websocket server.+      let viewerWebsocketOr app+            | viewer >= ViewerEnabled =+                let server = viewerWsServerApp logger exportRequestChan+                    options = defaultConnectionOptions+                 in websocketsOr options server app+            | otherwise = app++      -- Start the server.+      serverThreadId <-+        forkIO $+          Warp.run serverPort.port $+            requestLogger $+              cors (const $ Just corsResourcePolicy) $+                viewerWebsocketOr $+                  serve (Proxy @ServerApi) $+                    controlServer :<|> health logger :<|> viewerServer++      -- Announce the viewer and open the browser:+      let viewerUrl = "http://localhost:" <> show serverPort.port <> "/viewer/"+      logInfo logger ("Viewer URL: " <> T.pack viewerUrl)+      when (viewer == ViewerEnabledAndOpen) $ do+        success <- openBrowser viewerUrl+        unless success $ logWarn logger "Could not open browser."++      -- Create the stop function.+      let stop = killThread serverThreadId+      pure ServerHandle{..}++--------------------------------------------------------------------------------+-- Server API+--------------------------------------------------------------------------------++type ServerApi =+  ("control" :> ControlApi)+    :<|> ("health" :> HealthApi)+    :<|> ViewerApi++--------------------------------------------------------------------------------+-- Health API+--------------------------------------------------------------------------------++type HealthApi =+  Get '[JSON] ()++health :: Logger IO -> Handler ()+health logger = do+  liftIO . logDebug logger $+    "Received request on /health."++--------------------------------------------------------------------------------+-- Logger Middleware+--------------------------------------------------------------------------------++mkLoggerMiddleware :: Logger IO -> IO Middleware+mkLoggerMiddleware logger =+  RL.mkRequestLogger $+    RL.defaultRequestLoggerSettings+      { RL.destination = RL.Callback $ logTrace logger . TE.decodeUtf8Lenient . fromLogStr+      , RL.outputFormat =+          RL.DetailedWithSettings+            RL.defaultDetailedSettings+              { RL.useColors = False+              }+      }++--------------------------------------------------------------------------------+-- Server Options+--------------------------------------------------------------------------------++data ServerOptions = ServerOptions+  { viewer :: !Viewer+  , control :: !Bool+  , serverPort :: !ServerPort+  , serverCors :: !ServerCors+  }++serverOptionsParser :: O.Parser ServerOptions+serverOptionsParser =+  OC.parserOptionGroup "Server options:" $+    ServerOptions+      <$> viewerParser+      <*> controlParser+      <*> serverPortParser+      <*> serverCorsParser++--------------------------------------------------------------------------------+-- Server Enabled++data Viewer = ViewerDisabled | ViewerEnabled | ViewerEnabledAndOpen+  deriving (Eq, Ord)++viewerParser :: O.Parser Viewer+viewerParser =+  asum+    [ O.flag' ViewerEnabled $+        O.long "viewer"+          <> O.help "Enable the local web viewer."+    , O.flag' ViewerEnabledAndOpen $+        O.long "viewer-open"+          <> O.help "Enable and open the local web viewer."+    , O.flag' ViewerDisabled $+        O.long "no-viewer"+          <> O.help "Disable the local web viewer. Default."+    , pure ViewerDisabled+    ]++--------------------------------------------------------------------------------+-- Server Enabled++controlParser :: O.Parser Bool+controlParser =+  asum+    [ OF.onlyFor CF.control (O.flag' True) mempty $+        O.long "control"+          <> O.help "Enable the control server."+    , O.flag' False $+        O.long "no-control"+          <> O.help "Disable the control server. Default."+    , pure False+    ]++--------------------------------------------------------------------------------+-- Server Port++newtype ServerPort = ServerPort {port :: Int}+  deriving (Eq, Show)++serverPortParser :: O.Parser ServerPort+serverPortParser =+  O.option (ServerPort <$> O.auto) . mconcat $+    [ O.metavar "PORT"+    , O.long "server-port"+    , O.help "The port number for the server."+    , O.value (ServerPort 30179)+    ]++--------------------------------------------------------------------------------+-- Server CORS++data ServerCors = ServerCors+  { serverCorsAllowOrigin :: !(Maybe ServerCorsAllowOrigin)+  , serverCorsMaxAgeS :: !(Maybe Int)+  , serverCorsRequireOrigin :: !Bool+  , serverCorsIgnoreFailures :: !Bool+  }++serverCorsParser :: O.Parser ServerCors+serverCorsParser =+  ServerCors+    <$> serverCorsAllowOriginParser+    <*> serverCorsMaxAgeSParser+    <*> serverCorsRequireOriginParser+    <*> serverCorsIgnoreFailuresParser++serverCorsMaxAgeSParser :: O.Parser (Maybe Int)+serverCorsMaxAgeSParser =+  O.optional . O.option O.auto . mconcat $+    [ O.metavar "SECONDS"+    , O.long "server-cors-max-age"+    , O.help "Set the maximum age of a cached CORS preflight request for the server CORS policy."+    ]++serverCorsRequireOriginParser :: O.Parser Bool+serverCorsRequireOriginParser =+  O.flag False True . mconcat $+    [ O.long "server-cors-require-origin"+    , O.help "If enabled, the server will not accept requests without an Origin header."+    ]++serverCorsIgnoreFailuresParser :: O.Parser Bool+serverCorsIgnoreFailuresParser =+  O.flag False True . mconcat $+    [ O.long "server-cors-ignore-failure"+    , O.help "If enabled, the control server will accept malformed CORS preflight requests."+    ]++type ServerCorsOrigin = BSC.ByteString++data ServerCorsAllowOrigin+  = ServerCorsAllowOriginWildcard+  | ServerCorsAllowOriginList [ServerCorsOrigin]++serverCorsAllowOriginParser :: O.Parser (Maybe ServerCorsAllowOrigin)+serverCorsAllowOriginParser =+  O.optional . O.option (readPReader pServerCorsAllowOrigin) . mconcat $+    [ O.long "server-cors-allow-origin"+    , O.metavar "ORIGIN"+    , O.help "Set the allowed origins for the control server CORS policy."+    ]++readPReader :: ReadP a -> O.ReadM a+readPReader readP = readSReader (P.readP_to_S readP)++readSReader :: ReadS a -> O.ReadM a+readSReader readS = O.maybeReader $ \str ->+  case readS str of+    [(a, "")] -> Just a+    _otherwise -> Nothing++pServerCorsAllowOrigin :: ReadP ServerCorsAllowOrigin+pServerCorsAllowOrigin =+  P.skipSpaces+    *> asum+      [ -- Wildcard+        ServerCorsAllowOriginWildcard <$ P.char '*' <* P.skipSpaces+      , -- List of origins+        ServerCorsAllowOriginList <$> P.sepBy1 pOrigin (P.char ',' <* P.skipSpaces)+      ]+ where+  -- TODO: The parser for origin could parse the syntax for origins:+  --+  -- Origin: null+  -- Origin: <scheme>://<hostname>+  -- Origin: <scheme>://<hostname>:<port>+  --+  pOrigin :: ReadP ServerCorsOrigin+  pOrigin = BSC.pack <$> P.munch1 (\c -> not (c == ',' || isSpace c)) <* P.skipSpaces++mkCorsResourcePolicy :: ServerCors -> CorsResourcePolicy+mkCorsResourcePolicy ServerCors{..} =+  CorsResourcePolicy+    { corsOrigins = corsOrigins+    , corsMethods = ["GET", "POST"]+    , corsRequestHeaders = ["Content-Type", "Origin"]+    , corsExposedHeaders = Nothing+    , corsMaxAge = serverCorsMaxAgeS+    , corsVaryOrigin = corsVaryOrigin+    , corsRequireOrigin = serverCorsRequireOrigin+    , corsIgnoreFailures = serverCorsIgnoreFailures+    }+ where+  -- TODO: If we add authentication, this flag needs to be set.+  corsCredentials :: Bool+  corsCredentials = False++  -- The @wai-cors@ package represents wildcard as @Nothing@ and otherwise+  -- accepts a list of origins and a boolean that determines whether or not+  -- credentials are used to access the resource.+  corsOrigins :: Maybe ([Origin], Bool)+  corsOrigins =+    case serverCorsAllowOrigin of+      Just (ServerCorsAllowOriginList origins) -> Just (origins, corsCredentials)+      _otherwise -> Nothing++  -- The @Vary: Origin@ header must be added if @Access-Control-Allow-Origin@+  -- is not set to wildcard and there are multiple origins.+  corsVaryOrigin :: Bool+  corsVaryOrigin =+    case serverCorsAllowOrigin of+      Just (ServerCorsAllowOriginList origins) -> length origins >= 2+      _otherwise -> False
+ src-app/GHC/Eventlog/Live/App/Server/Control.hs view
@@ -0,0 +1,415 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++module GHC.Eventlog.Live.App.Server.Control (+  ControlHooks (..),+  noopControlHooks,+  ControlApi,+  newControlServer,+  newDisabledControlServer,+  control,+) where++import Control.Monad.IO.Class (MonadIO (..))+import Data.Aeson qualified as JSON+import Data.Aeson.Types (FromJSON (..), Parser, ToJSON (..), Value, genericParseJSON, genericToJSON)+import Data.ByteString.Lazy qualified as BSL+import Data.Char (isLower, isUpper, toLower)+import Data.Text (Text)+import Data.Text.Encoding qualified as TE+import GHC.Eventlog.Live.App.Environment (ServiceName (..))+import GHC.Eventlog.Live.Logger (Logger, logDebug)+import GHC.Eventlog.Live.Source.Core (EventlogSourceHandle (..))+import GHC.Generics (Generic)+import Options.Applicative.Extra.Feature (Feature (..))+import Servant (PlainText, throwError)+import Servant.API (Capture, FormUrlEncoded, Header, Headers, JSON, NoContent (..), ReqBody, StdMethod (..), UVerb, Union, WithStatus (..), addHeader, (:>), type (:<|>) (..))+import Servant.Server (Handler, Server, ServerError (..), respond)+import Web.FormUrlEncoded (Form, FormOptions, FromForm (..), genericFromForm)+import Web.FormUrlEncoded qualified as Form (FormOptions (fieldLabelModifier), defaultFormOptions)++#ifdef EVENTLOG_LIVE_FEATURE_CONTROL+import Control.Exception (Exception (..), catches)+import Control.Exception qualified as E (Handler (..))+import Data.Binary qualified as B+import Data.HashMap.Strict (HashMap)+import Data.HashMap.Strict qualified as M+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)+import Data.Text qualified as T+import Data.Word (Word8)+import GHC.Eventlog.Socket.Control qualified as C+import Network.Socket (Socket)+import Network.Socket.ByteString.Lazy qualified as SBSL+import Text.Read (readMaybe)+#endif++--------------------------------------------------------------------------------+-- Feature: control+--------------------------------------------------------------------------------++control :: Feature+control = Feature{flag = "control", isOn = isOn, info = "Cannot start control server."}+ where+  isOn :: Bool+#ifdef EVENTLOG_LIVE_FEATURE_CONTROL+  isOn = True+#else+  isOn = False+#endif++--------------------------------------------------------------------------------+-- Control App+--------------------------------------------------------------------------------++data ControlHooks = ControlHooks+  { notifyNewConnection :: ServiceName -> EventlogSourceHandle -> IO ()+  , notifyEndConnection :: ServiceName -> IO ()+  }++noopControlHooks :: ControlHooks+noopControlHooks =+  ControlHooks+    { notifyNewConnection = \_serviceName _eventlogSourceHandle -> pure ()+    , notifyEndConnection = \_serviceName -> pure ()+    }++newControlServer :: Logger IO -> Bool -> IO (ControlHooks, Server ControlApi)+#ifdef EVENTLOG_LIVE_FEATURE_CONTROL+newControlServer = newEnabledControlServer+#else+newControlServer = newDisabledControlServer+#endif++--------------------------------------------------------------------------------+-- Control App - Disabled+--------------------------------------------------------------------------------++newDisabledControlServer :: Logger IO -> Bool -> IO (ControlHooks, Server ControlApi)+newDisabledControlServer logger corsIgnoreFailures = do+  pure (noopControlHooks, server)+ where+  server :: Server ControlApi+  server _namespaceText _commandText = handleCommand :<|> badCORSPreflight+   where+    badCORSPreflight :: Handler (Union '[BadCORSPreflightAccept, BadCORSPreflightReject])+    badCORSPreflight = badCORSPreflightHandler logger corsIgnoreFailures++    handleCommand :: CommandReq -> Handler (Union '[CommandAccept, CommandReject])+    handleCommand _req = disabled++    disabled :: Handler a+    disabled =+      throwError+        ServerError+          { errHTTPCode = 400+          , errReasonPhrase = "Bad Request"+          , errBody = BSL.fromStrict . TE.encodeUtf8 $ "The control server is disabled."+          , errHeaders = []+          }++--------------------------------------------------------------------------------+-- Control App - Enabled+--------------------------------------------------------------------------------+#ifdef EVENTLOG_LIVE_FEATURE_CONTROL++newEnabledControlServer :: Logger IO -> Bool -> IO (ControlHooks, Server ControlApi)+newEnabledControlServer logger corsIgnoreFailures = do+  -- Create variable for storing sockets.+  connectionMapRef <- newIORef @(HashMap ServiceName EventlogSourceHandle) M.empty+  pure (api connectionMapRef, server connectionMapRef)+ where+  api :: IORef (HashMap ServiceName EventlogSourceHandle) -> ControlHooks+  api connectionMapRef = ControlHooks{..}+   where+    -- When notified of a new connection, update the connectionMapRef.+    notifyNewConnection serviceName eventlogSourceHandle = do+      logDebug logger $+        "New connection for service " <> serviceName.serviceName <> "."+      atomicModifyIORef' connectionMapRef $ \connectionMap ->+        let !connectionMap' = M.insert serviceName eventlogSourceHandle connectionMap+         in (connectionMap', ())++    -- When notified of the end of a connection, update the connectionMapRef.+    notifyEndConnection serviceName = do+      logDebug logger $+        "End connection for service " <> serviceName.serviceName <> "."+      atomicModifyIORef' connectionMapRef $ \connectionMap ->+        let !connectionMap' = M.delete serviceName connectionMap+         in (connectionMap', ())++  server :: IORef (HashMap ServiceName EventlogSourceHandle) -> Server ControlApi+  server connectionMapRef namespaceText commandText = handleCommand :<|> badCORSPreflight+   where+    badCORSPreflight :: Handler (Union '[BadCORSPreflightAccept, BadCORSPreflightReject])+    badCORSPreflight = badCORSPreflightHandler logger corsIgnoreFailures++    handleCommand :: CommandReq -> Handler (Union '[CommandAccept, CommandReject])+    handleCommand req+        | -- Handle the builtin eventlog-socket commands by name.+          namespaceText == "eventlog-socket"+        , Just command <- eventlogSocketCommandId commandText = do+            withSocketFor (ServiceName req.serviceName) $ \socket ->+              liftIO (SBSL.sendAll socket $ B.encode command)+            respond $ WithStatus @204 NoContent+        -- Handle custom commands.+        | Just commandId <- readMaybe @Word8 (T.unpack commandText) = do+            -- Construct the user namespace.+            liftIO (eitherUserNamespace namespaceText) >>= \case+              -- If userNamespace throws an exception, then...+              Left customCommandError ->+                -- ...respond with a custom command error.+                respond $ WithStatus @404 customCommandError+              -- Otherwise, ...+              Right namespace -> do+                -- ...construct the user command...+                let command = C.userCommand namespace (C.CommandId commandId)+                -- ...send the user command...+                withSocketFor (ServiceName req.serviceName) $ \socket -> do+                  liftIO (SBSL.sendAll socket $ B.encode command)+                -- ...respond with a success status.+                respond $ WithStatus @204 NoContent+        | otherwise = do+          let errorMessage="Unknown command "<>T.unpack commandText+          respond $ WithStatus @404 CustomCommandError{..}++    withSocketFor :: ServiceName -> (Socket -> Handler ()) -> Handler ()+    withSocketFor serviceName action = do+      connectionMap <- liftIO (readIORef connectionMapRef)+      case M.lookup serviceName connectionMap of+        -- If the service is not known, return a 404.+        Nothing ->+          throwError+            ServerError+              { errHTTPCode = 404+              , errReasonPhrase = "Not Found"+              , errBody = BSL.fromStrict . TE.encodeUtf8 $ "Could not find eventlog socket for service " <> serviceName.serviceName <> "."+              , errHeaders = []+              }+        -- If the service telemetry is streamed from stdin or a file, return a 400.+        Just EventlogSourceHandleStdin ->+          throwError+            ServerError+              { errHTTPCode = 400+              , errReasonPhrase = "Bad Request"+              , errBody = BSL.fromStrict . TE.encodeUtf8 $ "The telemetry for service " <> serviceName.serviceName <> " is streamed from stdin."+              , errHeaders = []+              }+        Just (EventlogSourceHandleFile _h) ->+          throwError+            ServerError+              { errHTTPCode = 400+              , errReasonPhrase = "Bad Request"+              , errBody = BSL.fromStrict . TE.encodeUtf8 $ "The telemetry for service " <> serviceName.serviceName <> " is streamed from a file."+              , errHeaders = []+              }+        -- If the service telemetry is streamed from a socket, continue.+        Just (EventlogSourceHandleSocket s) -> action s+++eventlogSocketCommandId :: Text -> Maybe C.Command+eventlogSocketCommandId commandText+  | commandText == "start-profiling" = Just C.startProfiling+  | commandText == "stop-profiling" = Just C.stopProfiling+  | commandText == "start-heap-profiling" = Just C.startHeapProfiling+  | commandText == "stop-heap-profiling" = Just C.stopHeapProfiling+  | commandText == "request-heap-census" = Just C.requestHeapCensus+  | otherwise = Nothing++eitherUserNamespace :: Text -> IO (Either CustomCommandError C.Namespace)+eitherUserNamespace namespace =+  (pure . Right . C.userNamespace $ namespace) `catches` handlers+ where+  handlers =+    [ E.Handler $ pure . Left . toCustomCommandError @C.NamespaceReservedError+    , E.Handler $ pure . Left . toCustomCommandError @C.NamespaceTooLongError+    ]++toCustomCommandError :: (Exception e) => e -> CustomCommandError+toCustomCommandError = CustomCommandError . displayException++-- EVENTLOG_LIVE_FEATURE_CONTROL+#endif+--------------------------------------------------------------------------------+-- Control API+--------------------------------------------------------------------------------++type ControlApi =+  Capture "namespace" Text+    :> Capture "commandId" Text+    :> ( ( ReqBody '[FormUrlEncoded, JSON] CommandReq+             :> UVerb 'POST '[JSON] '[CommandAccept, CommandReject]+         )+           :<|> BadCORSPreflight+       )++type CommandAccept = WithStatus 204 NoContent++type CommandReject = WithStatus 404 CustomCommandError++newtype CustomCommandError = CustomCommandError+  { errorMessage :: String+  }+  deriving (Generic, Show)++instance ToJSON CustomCommandError where+  toJSON :: CustomCommandError -> Value+  toJSON = genericToJSON myJSONOptions++--------------------------------------------------------------------------------+-- CommandReq++newtype CommandReq = CommandReq+  { serviceName :: Text+  }+  deriving (Generic, Show)++instance FromForm CommandReq where+  fromForm :: Form -> Either Text CommandReq+  fromForm = genericFromForm myFormOptions++instance FromJSON CommandReq where+  parseJSON :: Value -> Parser CommandReq+  parseJSON = genericParseJSON myJSONOptions++--------------------------------------------------------------------------------+-- Bad CORS preflight requests++type BadCORSPreflight =+  UVerb 'OPTIONS '[PlainText] '[BadCORSPreflightAccept, BadCORSPreflightReject]++type BadCORSPreflightAccept =+  WithStatus+    204+    ( Headers+        '[ Header "Access-Control-Allow-Origin" String+         , Header "Access-Control-Allow-Methods" String+         , Header "Access-Control-Allow-Headers" String+         ]+        NoContent+    )++type BadCORSPreflightReject = WithStatus 400 NoContent++--------------------------------------------------------------------------------+-- StartProfilingReq++newtype StartProfilingReq = StartProfilingReq+  { serviceName :: Text+  }+  deriving (Generic, Show)++instance FromForm StartProfilingReq where+  fromForm :: Form -> Either Text StartProfilingReq+  fromForm = genericFromForm myFormOptions++instance FromJSON StartProfilingReq where+  parseJSON :: Value -> Parser StartProfilingReq+  parseJSON = genericParseJSON myJSONOptions++--------------------------------------------------------------------------------+-- StopProfilingReq++newtype StopProfilingReq = StopProfilingReq+  { serviceName :: Text+  }+  deriving (Generic, Show)++instance FromForm StopProfilingReq where+  fromForm :: Form -> Either Text StopProfilingReq+  fromForm = genericFromForm myFormOptions++instance FromJSON StopProfilingReq where+  parseJSON :: Value -> Parser StopProfilingReq+  parseJSON = genericParseJSON myJSONOptions++--------------------------------------------------------------------------------+-- StartHeapProfilingReq++newtype StartHeapProfilingReq = StartHeapProfilingReq+  { serviceName :: Text+  }+  deriving (Generic, Show)++instance FromForm StartHeapProfilingReq where+  fromForm :: Form -> Either Text StartHeapProfilingReq+  fromForm = genericFromForm myFormOptions++instance FromJSON StartHeapProfilingReq where+  parseJSON :: Value -> Parser StartHeapProfilingReq+  parseJSON = genericParseJSON myJSONOptions++--------------------------------------------------------------------------------+-- StopHeapProfilingReq++newtype StopHeapProfilingReq = StopHeapProfilingReq+  { serviceName :: Text+  }+  deriving (Generic, Show)++instance FromForm StopHeapProfilingReq where+  fromForm :: Form -> Either Text StopHeapProfilingReq+  fromForm = genericFromForm myFormOptions++instance FromJSON StopHeapProfilingReq where+  parseJSON :: Value -> Parser StopHeapProfilingReq+  parseJSON = genericParseJSON myJSONOptions++--------------------------------------------------------------------------------+-- RequestHeapCensusReq++newtype RequestHeapCensusReq = RequestHeapCensusReq+  { serviceName :: Text+  }+  deriving (Generic, Show)++instance FromForm RequestHeapCensusReq where+  fromForm :: Form -> Either Text RequestHeapCensusReq+  fromForm = genericFromForm myFormOptions++instance FromJSON RequestHeapCensusReq where+  parseJSON :: Value -> Parser RequestHeapCensusReq+  parseJSON = genericParseJSON myJSONOptions++--------------------------------------------------------------------------------+-- Internal helpers.++-- | Handler for bad CORS preflight requests.+badCORSPreflightHandler :: Logger IO -> Bool -> Handler (Union '[BadCORSPreflightAccept, BadCORSPreflightReject])+badCORSPreflightHandler logger corsIgnoreFailures+  | corsIgnoreFailures = do+      -- This accepts malformed CORS preflight requests.+      liftIO . logDebug logger $ "Accepted malformed CORS preflight request."+      respond . WithStatus @204 $+        addHeader @"Access-Control-Allow-Origin" @String "*" $+          addHeader @"Access-Control-Allow-Methods" @String "GET, POST" $+            addHeader @"Access-Control-Allow-Headers" @String "*" $+              NoContent+  | otherwise = do+      liftIO . logDebug logger $ "Accepted malformed CORS preflight request."+      respond . WithStatus @400 $+        NoContent++-- | Generic options for `FromForm`.+myFormOptions :: FormOptions+myFormOptions =+  Form.defaultFormOptions+    { Form.fieldLabelModifier = camelTo2 '-'+    }++-- | Generic options for `FromJSON`.+myJSONOptions :: JSON.Options+myJSONOptions =+  JSON.defaultOptions+    { JSON.fieldLabelModifier = camelTo2 '-'+    }++-- | Taken from aeson.+camelTo2 :: Char -> String -> String+camelTo2 c = map toLower . go2 . go1+ where+  go1 "" = ""+  go1 (x : u : l : xs) | isUpper u && isLower l = x : c : u : l : go1 xs+  go1 (x : xs) = x : go1 xs+  go2 "" = ""+  go2 (l : u : xs) | isLower l && isUpper u = l : c : u : go2 xs+  go2 (x : xs) = x : go2 xs
+ src-app/GHC/Eventlog/Live/App/Server/Viewer.hs view
@@ -0,0 +1,263 @@+{-# LANGUAGE OverloadedLists #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}++module GHC.Eventlog.Live.App.Server.Viewer (+  ViewerApi,+  viewerServer,+  viewerWsServerApp,+) where++import Control.Concurrent (forkIO, killThread)+import Control.Concurrent.LossyChan qualified as LC+import Control.Exception (bracket, handle)+import Control.Monad (void)+import Data.Aeson qualified as JSON+import Data.Aeson.Types (KeyValue (..), KeyValueOmit (..), ToJSON, Value (..), pairs)+import Data.ByteString.Lazy qualified as BSL+import Data.DList (DList)+import Data.DList qualified as D+import Data.Kind (Type)+import Data.Maybe (mapMaybe)+import Data.Proxy (Proxy (..))+import Data.Text qualified as T+import Data.Word (Word64)+import GHC.Eventlog.Live.App.Server.Viewer.AlignedData (AlignedData, toAlignedData)+import GHC.Eventlog.Live.App.Server.Viewer.AlignedData qualified as AD+import GHC.Eventlog.Live.App.Server.Viewer.Embedded (mkEmbedded)+import GHC.Eventlog.Live.Logger (Logger, logDebug, logException, logInfo, logTrace)+import GHC.Eventlog.Live.Machine.Core (Tick (..))+import GHC.Eventlog.Live.Processor (ExportRequest (..), InstrumentationScope, Resource, toSomeMetrics)+import GHC.Eventlog.Live.Types.Attribute ((~=))+import GHC.Eventlog.Live.Types.Metrics (KnownMetric (..), Metric, SomeMetrics, getMetrics)+import GHC.Eventlog.Live.Types.Metrics qualified as M+import GHC.TypeLits (symbolVal)+import Network.HTTP.Media (MediaType, (//), (/:))+import Network.Wai (Application)+import Network.Wai.Application.Static (staticApp)+import Network.WebSockets qualified as WS+import Network.WebSockets.Connection.PingPong qualified as WS (PongTimeout (..))+import Servant.API (Accept (..), Header, Headers, NoContent (..), Raw, StdMethod (..), Verb, addHeader, (:<|>) (..), (:>))+import Servant.Server (Handler, Server, Tagged (..))+import WaiAppStatic.Storage.Embedded (mkSettings)+import WaiAppStatic.Types qualified as WAS+import Prelude hiding (null)++--------------------------------------------------------------------------------+-- Viewer App Server+--------------------------------------------------------------------------------++type ViewerApi =+  ViewerRedirect+    :<|> "viewer" :> Raw++viewerServer :: Server ViewerApi+viewerServer =+  viewerRedirectServer :<|> Tagged viewerApp++viewerApp :: Application+viewerApp =+  staticApp+    $(mkSettings mkEmbedded)+      { WAS.ssIndices = WAS.unsafeToPiece <$> ["index.html"]+      , WAS.ssRedirectToIndex = True+      , WAS.ssAddTrailingSlash = True+      }++--------------------------------------------------------------------------------+-- HTML content type+--------------------------------------------------------------------------------++data HTML++instance Accept HTML where+  contentType :: Proxy HTML -> MediaType+  contentType _ = "text" // "html" /: ("charset", "utf-8")++--------------------------------------------------------------------------------+-- Redirect from index+--------------------------------------------------------------------------------++type ViewerRedirect =+  Verb 'GET 302 '[HTML] (Headers '[Header "Location" String] NoContent)++viewerRedirectServer :: Handler (Headers '[Header "Location" String] NoContent)+viewerRedirectServer = pure $ addHeader "viewer" NoContent++--------------------------------------------------------------------------------+-- Viewer Websocket Server+--------------------------------------------------------------------------------++viewerWsServerApp ::+  Logger IO -> LC.InChan (Tick ExportRequest) -> WS.ServerApp+viewerWsServerApp logger exportRequestChan pending = do+  conn <- WS.acceptRequest pending+  logInfo logger $ "Accepted new viewer connection."+  handle handlePongTimeout $+    withMessageDiscarder logger conn $+      WS.withPingPong pingPongOptions conn $ \conn' ->+        LC.out exportRequestChan >>= \chan ->+          viewer chan conn'+ where+  pingPongOptions :: WS.PingPongOptions+  pingPongOptions = WS.defaultPingPongOptions++  handlePongTimeout :: WS.PongTimeout -> IO ()+  handlePongTimeout WS.PongTimeout =+    logInfo logger $ "Viewer timed out."++  viewer :: LC.OutChan (Tick ExportRequest) -> WS.Connection -> IO ()+  viewer chan conn =+    handle handleConnectionException viewerLoop+   where+    viewerLoop =+      LC.receive chan >>= \case+        Tick ->+          viewerLoop+        Item er -> do+          let ver = toViewerExportRequest er+          let verBytes = JSON.encode ver+          let verByteSize = BSL.length verBytes+          logTrace logger $ "Send " <> T.show verByteSize <> " bytes to viewer."+          WS.sendTextData conn verBytes+          viewerLoop++    handleConnectionException :: WS.ConnectionException -> IO ()+    handleConnectionException = \case+      WS.ConnectionClosed{} -> do+        logInfo logger $ "Viewer closed the connection."+      _wsErr ->+        -- NOTE: Using viewerLoop would uninstall the handler.+        viewer chan conn++{- |+This function spawns a thread that receives all incoming data messages on+the websocket connection and discards them. This is needed, because, with the+current @websockets@ library, the user must call `WS.receiveDataMessage` for+the library to handle control messages.+-}+withMessageDiscarder :: Logger IO -> WS.Connection -> IO () -> IO ()+withMessageDiscarder logger conn action =+  bracket (forkIO messageDiscarder) killThread (const action)+ where+  messageDiscarder :: IO ()+  messageDiscarder = handle handleConnectionException mesageDiscarderLoop++  mesageDiscarderLoop :: IO ()+  mesageDiscarderLoop = void (WS.receiveDataMessage conn) >> mesageDiscarderLoop++  handleConnectionException :: WS.ConnectionException -> IO ()+  handleConnectionException = \case+    WS.CloseRequest{} -> do+      logInfo logger $ "Viewer requested to close the connection."+      -- NOTE: Using mesageDiscarderLoop would uninstall the handler.+      messageDiscarder+    WS.ConnectionClosed{} ->+      logDebug logger $ "Viewer closed the connection; stopping message discarder."+    wsErr ->+      logException logger wsErr++data ViewerExportRequest = ViewerExportRequest+  { resource :: !Resource+  , scope :: !InstrumentationScope+  , telemetry :: !ViewerTelemetry+  }++viewerExportRequestToKV :: (KeyValueOmit e kv, Monoid kv) => ViewerExportRequest -> kv+viewerExportRequestToKV vt =+  mconcat+    [ "resource" .= vt.resource+    , "scope" .= vt.scope+    , "telemetry" .= vt.telemetry+    ]+{-# INLINE viewerExportRequestToKV #-}++instance ToJSON ViewerExportRequest where+  toJSON :: ViewerExportRequest -> JSON.Value+  toJSON = Object . viewerExportRequestToKV++  toEncoding :: ViewerExportRequest -> JSON.Encoding+  toEncoding = pairs . viewerExportRequestToKV++data ViewerTelemetry = ViewerTelemetry+  { heapSize :: Maybe (AlignedData Word64)+  , heapProfSample :: Maybe (AlignedData Word64)+  , gcCopied :: Maybe (AlignedData Word64)+  , gcSlop :: Maybe (AlignedData Word64)+  , gcFragmentation :: Maybe (AlignedData Word64)+  }++viewerTelemetryToKV :: (KeyValueOmit e kv, Monoid kv) => ViewerTelemetry -> kv+viewerTelemetryToKV vt =+  mconcat+    [ "heapSize" .?= vt.heapSize+    , "heapProfSample" .?= vt.heapProfSample+    , "gcCopied" .?= vt.gcCopied+    , "gcSlop" .?= vt.gcSlop+    , "gcFragmentation" .?= vt.gcFragmentation+    ]+{-# INLINE viewerTelemetryToKV #-}++instance ToJSON ViewerTelemetry where+  toJSON :: ViewerTelemetry -> JSON.Value+  toJSON = Object . viewerTelemetryToKV++  toEncoding :: ViewerTelemetry -> JSON.Encoding+  toEncoding = pairs . viewerTelemetryToKV++toViewerExportRequest :: ExportRequest -> ViewerExportRequest+toViewerExportRequest r =+  ViewerExportRequest+    { resource = r.resource+    , scope = r.scope+    , telemetry =+        ViewerTelemetry+          { heapSize = heapSize+          , heapProfSample = heapProfSample+          , gcCopied = gcCopied+          , gcSlop = gcSlop+          , gcFragmentation = gcFragmentation+          }+    }+ where+  someMetrics :: [SomeMetrics]+  someMetrics = mapMaybe toSomeMetrics r.telemetry++  heapProfSample, heapSize, gcCopied, gcSlop, gcFragmentation :: Maybe (AlignedData Word64)+  heapProfSample = alignKnownMetric (Proxy @"heapProfSample") someMetrics+  heapSize = alignKnownMetrics (Proxy @"heapSize" :&: Proxy @"blocksSize" :&: Proxy @"heapLive" :&: End) someMetrics+  gcCopied = alignKnownMetric (Proxy @"gcCopied") someMetrics+  gcSlop = alignKnownMetric (Proxy @"gcSlop") someMetrics+  gcFragmentation = alignKnownMetric (Proxy @"gcFragmentation") someMetrics++infixr 0 :&:++data KnownMetrics (a :: Type) where+  (:&:) :: (KnownMetric metric, GetMetricType metric ~ a) => Proxy metric -> KnownMetrics a -> KnownMetrics a+  End :: KnownMetrics a++alignKnownMetric :: (KnownMetric metric) => Proxy metric -> [SomeMetrics] -> Maybe (AlignedData (GetMetricType metric))+alignKnownMetric metric =+  alignKnownMetrics (metric :&: End)++alignKnownMetrics :: KnownMetrics a -> [SomeMetrics] -> Maybe (AlignedData a)+alignKnownMetrics metrics =+  (`onlyIf` not . AD.null)+    . toAlignedData+    . D.toList+    . foldMap (getNamedMetrics metrics)++getNamedMetrics :: KnownMetrics a -> SomeMetrics -> DList (Metric a)+getNamedMetrics End _someMetrics = mempty+getNamedMetrics (metric :&: metrics) someMetrics =+  getNamedMetric metric someMetrics <> getNamedMetrics metrics someMetrics++getNamedMetric :: (KnownMetric metric) => Proxy metric -> SomeMetrics -> DList (Metric (GetMetricType metric))+getNamedMetric (metric :: Proxy metric) =+  fmap (addName metric) . maybe mempty D.fromList . getMetrics metric++addName :: (KnownMetric metric) => Proxy metric -> Metric (GetMetricType metric) -> Metric (GetMetricType metric)+addName metric x = x{M.attrs = ["name" ~= symbolVal metric] <> x.attrs}++onlyIf :: a -> (a -> Bool) -> Maybe a+onlyIf a p = if p a then Just a else Nothing
+ src-app/GHC/Eventlog/Live/App/Server/Viewer/AlignedData.hs view
@@ -0,0 +1,111 @@+{-# LANGUAGE OverloadedStrings #-}++module GHC.Eventlog.Live.App.Server.Viewer.AlignedData (+  AlignedData (..),+  Series (..),+  TimeUnix,+  null,+  validate,+  toAlignedData,+) where++import Control.Monad.ST.Strict (runST)+import Data.Aeson.Types (Encoding, KeyValue (..), ToJSON (..), Value (..), pairs)+import Data.Foldable (for_)+import Data.Functor ((<&>))+import Data.IntMap.Strict qualified as IM+import Data.IntSet qualified as IS+import Data.Map.Strict qualified as M+import Data.Maybe (mapMaybe)+import Data.Set qualified as S+import Data.Vector (Vector)+import Data.Vector qualified as V+import Data.Vector.Mutable (MVector)+import Data.Vector.Mutable qualified as VM+import Data.Vector.Unboxed qualified as U+import GHC.Eventlog.Live.Machine.WithStartTime (TimeUnixNano)+import GHC.Eventlog.Live.Types.Attribute (Attrs)+import GHC.Eventlog.Live.Types.Metrics (Metric (..))+import Prelude hiding (null)++type TimeUnix = Int++toTimeUnix :: TimeUnixNano -> TimeUnix+toTimeUnix timeUnixNano = fromIntegral (timeUnixNano `div` 1_000_000_000)++data AlignedData a = AlignedData+  { xValues :: !(U.Vector TimeUnix)+  , series :: !(Vector (Series a))+  }+  deriving (Show)++alignedDataToKV :: (KeyValue e kv, Monoid kv, ToJSON a) => AlignedData a -> kv+alignedDataToKV d = mconcat ["xValues" .= d.xValues, "series" .= d.series]+{-# INLINE alignedDataToKV #-}++instance (ToJSON a) => ToJSON (AlignedData a) where+  toJSON :: AlignedData a -> Value+  toJSON = Object . alignedDataToKV++  toEncoding :: AlignedData a -> Encoding+  toEncoding = pairs . alignedDataToKV++data Series a = Series+  { attrs :: !Attrs+  , yValues :: !(Vector (Maybe a))+  }+  deriving (Show)++seriesToKV :: (KeyValue e kv, Monoid kv, ToJSON a) => Series a -> kv+seriesToKV s = mconcat ["attrs" .= s.attrs, "yValues" .= s.yValues]+{-# INLINE seriesToKV #-}++instance (ToJSON a) => ToJSON (Series a) where+  toJSON :: Series a -> Value+  toJSON = Object . seriesToKV++  toEncoding :: Series a -> Encoding+  toEncoding = pairs . seriesToKV++null :: AlignedData a -> Bool+null d = U.null d.xValues++-- | Check the invariant for `AlignedData`.+validate :: AlignedData a -> Bool+validate d = V.all (\s -> U.length d.xValues == V.length s.yValues) d.series++data DataPoint a = DataPoint {attrs :: !Attrs, timeUnix :: !TimeUnix, value :: !a}++toDataPoint :: Metric a -> Maybe (DataPoint a)+toDataPoint Metric{..} =+  maybeTimeUnixNano <&> \timeUnixNano -> DataPoint{timeUnix = toTimeUnix timeUnixNano, ..}++toAlignedData :: [Metric a] -> AlignedData a+toAlignedData metrics = AlignedData xValues series+ where+  dps = mapMaybe toDataPoint metrics+  (xValuesSet, attrsSet) = foldMap (\dp -> (IS.singleton dp.timeUnix, S.singleton dp.attrs)) dps++  xValuesCount = IS.size xValuesSet+  xValues = U.fromListN xValuesCount (IS.toAscList xValuesSet)+  xValuesMap = IM.fromAscList (zip (U.toList xValues) [(0 :: Int) ..])++  attrs = S.toAscList attrsSet+  attrsCount = S.size attrsSet++  series = runST $ do+    -- Create mutable vectors for the yValues of every series initialised to Nothing.+    seriesMut :: Vector (MVector s (Maybe a)) <- V.replicateM attrsCount (VM.replicate xValuesCount Nothing)++    -- Create an index over the series.+    let seriesMutMap = M.fromAscList . zip attrs $ (seriesMut V.!) <$> [0 .. attrsCount]++    -- Process all data points.+    for_ dps $ \dp -> do+      let yValues = seriesMutMap M.! dp.attrs+      let i = xValuesMap IM.! dp.timeUnix+      VM.write yValues i (Just dp.value)++    -- Freeze the yValues and wrap them as series.+    seriesMap <- traverse V.unsafeFreeze seriesMutMap+    pure $ V.fromListN attrsCount (uncurry Series <$> M.toAscList seriesMap)
+ src-app/GHC/Eventlog/Live/App/Server/Viewer/Embedded.hs view
@@ -0,0 +1,139 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}++module GHC.Eventlog.Live.App.Server.Viewer.Embedded where++import Crypto.Hash.MD5 qualified as MD5 (hashlazy)+import Data.Base64.Types qualified as B64+import Data.ByteString.Base64 qualified as B64B+import Data.ByteString.Lazy qualified as BSL+import Data.FileEmbed (makeRelativeToProject)+import Data.Text qualified as T+import Language.Haskell.TH.Lift (Lift (..))+import WaiAppStatic.Storage.Embedded (EmbeddableEntry (..))++--------------------------------------------------------------------------------+-- Paths+--------------------------------------------------------------------------------++appleTouchIconPngPath :: FilePath+appleTouchIconPngPath = $(lift =<< makeRelativeToProject "data/viewer/apple-touch-icon.png")++faviconIcoPath :: FilePath+faviconIcoPath = $(lift =<< makeRelativeToProject "data/viewer/favicon.ico")++icon192PngPath :: FilePath+icon192PngPath = $(lift =<< makeRelativeToProject "data/viewer/icon-192.png")++icon512PngPath :: FilePath+icon512PngPath = $(lift =<< makeRelativeToProject "data/viewer/icon-512.png")++iconMaskPngPath :: FilePath+iconMaskPngPath = $(lift =<< makeRelativeToProject "data/viewer/icon-mask.png")++iconSvgPath :: FilePath+iconSvgPath = $(lift =<< makeRelativeToProject "data/viewer/icon.svg")++indexCssPath :: FilePath+indexCssPath = $(lift =<< makeRelativeToProject "data/viewer/index.css")++indexHtmlPath :: FilePath+indexHtmlPath = $(lift =<< makeRelativeToProject "data/viewer/index.html")++indexJsPath :: FilePath+indexJsPath = $(lift =<< makeRelativeToProject "data/viewer/index.js")++manifestJsonPath :: FilePath+manifestJsonPath = $(lift =<< makeRelativeToProject "data/viewer/manifest.webmanifest")++--------------------------------------------------------------------------------+-- Embeddable Entries+--------------------------------------------------------------------------------++hash :: BSL.ByteString -> T.Text+hash = T.take 8 . B64.extractBase64 . B64B.encodeBase64 . MD5.hashlazy++mkEmbedded :: IO [EmbeddableEntry]+mkEmbedded = do+  appleTouchIconPngContent <- BSL.readFile appleTouchIconPngPath+  let appleTouchIconPngEntry =+        EmbeddableEntry+          { eLocation = "apple-touch-icon.png"+          , eMimeType = "image/png"+          , eContent = Left (hash appleTouchIconPngContent, appleTouchIconPngContent)+          }+  faviconIcoContent <- BSL.readFile faviconIcoPath+  let faviconIcoEntry =+        EmbeddableEntry+          { eLocation = "favicon.ico"+          , eMimeType = "image/x-icon"+          , eContent = Left (hash faviconIcoContent, faviconIcoContent)+          }+  icon192PngContent <- BSL.readFile icon192PngPath+  let icon192PngEntry =+        EmbeddableEntry+          { eLocation = "icon-192.png"+          , eMimeType = "image/png"+          , eContent = Left (hash icon192PngContent, icon192PngContent)+          }+  icon512PngContent <- BSL.readFile icon512PngPath+  let icon512PngEntry =+        EmbeddableEntry+          { eLocation = "icon-512.png"+          , eMimeType = "image/png"+          , eContent = Left (hash icon512PngContent, icon512PngContent)+          }+  iconMaskPngContent <- BSL.readFile iconMaskPngPath+  let iconMaskPngEntry =+        EmbeddableEntry+          { eLocation = "icon-mask.png"+          , eMimeType = "image/png"+          , eContent = Left (hash iconMaskPngContent, iconMaskPngContent)+          }+  iconSvgContent <- BSL.readFile iconSvgPath+  let iconSvgEntry =+        EmbeddableEntry+          { eLocation = "icon.svg"+          , eMimeType = "image/svg+xml"+          , eContent = Left (hash iconSvgContent, iconSvgContent)+          }+  indexCssContent <- BSL.readFile indexCssPath+  let indexCssEntry =+        EmbeddableEntry+          { eLocation = "index.css"+          , eMimeType = "text/css"+          , eContent = Left (hash indexCssContent, indexCssContent)+          }+  indexHtmlContent <- BSL.readFile indexHtmlPath+  let indexHtmlEntry =+        EmbeddableEntry+          { eLocation = "index.html"+          , eMimeType = "text/html"+          , eContent = Left (hash indexHtmlContent, indexHtmlContent)+          }+  indexJsContent <- BSL.readFile indexJsPath+  let indexJsEntry =+        EmbeddableEntry+          { eLocation = "index.js"+          , eMimeType = "text/javascript"+          , eContent = Left (hash indexJsContent, indexJsContent)+          }+  manifestJsonContent <- BSL.readFile manifestJsonPath+  let manifestJsonEntry =+        EmbeddableEntry+          { eLocation = "manifest.webmanifest"+          , eMimeType = "application/manifest+json"+          , eContent = Left (hash manifestJsonContent, manifestJsonContent)+          }+  pure+    [ appleTouchIconPngEntry+    , faviconIcoEntry+    , icon192PngEntry+    , icon512PngEntry+    , iconMaskPngEntry+    , iconSvgEntry+    , indexCssEntry+    , indexHtmlEntry+    , indexJsEntry+    , manifestJsonEntry+    ]
+ src-compat/System/Random/Compat.hs view
@@ -0,0 +1,17 @@+{-# LANGUAGE CPP #-}++module System.Random.Compat (+  uniformByteString,+) where++#if MIN_VERSION_random(1,3,0)+import System.Random (uniformByteString)+#else+import Data.Bifunctor (Bifunctor (first))+import Data.ByteString (ByteString)+import Data.ByteString.Short (fromShort)+import System.Random (RandomGen (genShortByteString))++uniformByteString :: RandomGen g => Int -> g -> (ByteString, g)+uniformByteString n g = first fromShort (genShortByteString n g)+#endif
+ src-lib/GHC/Eventlog/Live/Config.hs view
@@ -0,0 +1,739 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}+{-# OPTIONS_GHC -Wno-orphans #-}++{- |+Module      : GHEventlog.Live.Otlp.Config+Description : The implementation of @eventlog-live@.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Config (+  -- * Configuration type+  Config (..),+  readConfigFile,+  prettyConfig,+  FullConfig (..),+  toFullConfig,++  -- ** Processor configuration types+  Processors (..),+  IsProcessorConfig,+  processorEnabled,+  processorDescription,+  processorName,++  -- *** Log processor configuration types+  Logs (..),+  IsLogProcessorConfig,+  shouldExportLogs,+  ThreadLabelLog (..),+  UserMarkerLog (..),+  UserMessageLog (..),+  InternalLogMessageLog (..),++  -- *** Metric processor configuration types+  Metrics (..),+  IsMetricProcessorConfig,+  shouldExportMetrics,+  HeapAllocatedMetric (..),+  BlocksSizeMetric (..),+  HeapSizeMetric (..),+  HeapLiveMetric (..),+  MemCurrentMetric (..),+  MemNeededMetric (..),+  MemReturnedMetric (..),+  GcCopiedMetric (..),+  GcSlopMetric (..),+  GcFragmentationMetric (..),+  HeapProfSampleMetric (..),+  CapabilityUsageMetric (..),+  ProductivityMetric (..),+  InternalEventCountMetric (..),+  InternalExportedLogsMetric (..),+  InternalRejectedLogsMetric (..),+  InternalExportedMetricsMetric (..),+  InternalRejectedMetricsMetric (..),+  InternalExportedSamplesMetric (..),+  InternalRejectedSamplesMetric (..),+  InternalExportedSpansMetric (..),+  InternalRejectedSpansMetric (..),++  -- *** Trace processor configuration types+  Traces (..),+  IsTraceProcessorConfig,+  shouldExportTraces,+  CapabilityUsageSpan (..),+  ThreadStateSpan (..),++  -- *** Profiler processor configuration types+  Profiles (..),+  IsProfileProcessorConfig,+  shouldExportProfiles,+  CallStackProfile (..),+  CostCentreStackProfile (..),++  -- ** Property types++  -- *** Aggregation strategy+  AggregationStrategy (..),+  toAggregationBatches,+  processorAggregationStrategy,+  processorAggregationBatches,+  maximumAggregationBatches,++  -- *** Export strategy+  ExportStrategy (..),+  toExportBatches,+  processorExportStrategy,+  processorExportBatches,+  maximumExportBatches,++  -- *** Batch interval+  toBatchIntervalMs,+  toBatches,++  -- * Default configuration file+  defaultConfigByteString,+  defaultConfigString,+  defaultConfigJSONSchemaByteString,+  defaultConfigJSONSchemaString,+) where++import Control.Exception (assert)+import Control.Monad ((<=<))+import Control.Monad.IO.Class (MonadIO (..))+import Data.ByteString.Lazy qualified as BSL+import Data.Default (Default (..))+import Data.List.NonEmpty (NonEmpty (..))+import Data.Maybe (catMaybes, fromMaybe, mapMaybe)+import Data.Monoid (Any (..))+import Data.Semigroup (Semigroup (..))+import Data.Text (Text)+import Data.Text.Encoding qualified as TE+import Data.YAML qualified as YAML+import GHC.Eventlog.Live.Config.Default (defaultConfig, getDefault)+import GHC.Eventlog.Live.Config.Default.Raw+import GHC.Eventlog.Live.Config.Types+import GHC.Records (HasField (..))+import GHC.Stack.Types (HasCallStack)++{- |+Read a `Config` from a configuration file.+-}+readConfigFile ::+  FilePath ->+  IO (Either String Config)+readConfigFile filePath =+  readConfig =<< liftIO (BSL.readFile filePath)++{- |+Read a `Config` from a `BSL.ByteString`.+-}+readConfig ::+  BSL.ByteString ->+  IO (Either String Config)+readConfig fileContents = do+  case YAML.decode1 fileContents of+    Left (pos, errorMessage) -> do+      pure $ Left $ YAML.prettyPosWithSource pos fileContents " error" <> errorMessage+    Right config ->+      pure $ Right config++{- |+Pretty-print a `Config` to YAML.+-}+prettyConfig :: Config -> Text+prettyConfig = TE.decodeUtf8Lenient . BSL.toStrict . YAML.encode1++{- |+Create a full configuration.+-}+toFullConfig ::+  -- | The @--eventlog-flush-interval@ in seconds.+  Double ->+  -- | The user configuration.+  Config ->+  FullConfig+toFullConfig eventlogFlushIntervalS config =+  FullConfig{..}+ where+  batchIntervalMs = toBatchIntervalMs eventlogFlushIntervalS config+  eventlogFlushIntervalX = toBatches batchIntervalMs eventlogFlushIntervalS++-------------------------------------------------------------------------------+-- Default Instances+-------------------------------------------------------------------------------++instance Default Config where+  def :: Config+  def = defaultConfig++instance Default Processors where+  def :: Processors+  def = $(getDefault @'["processors"] defaultConfig)++instance Default Logs where+  def :: Logs+  def = $(getDefault @'["processors", "logs"] defaultConfig)++instance Default Metrics where+  def :: Metrics+  def = $(getDefault @'["processors", "metrics"] defaultConfig)++instance Default Traces where+  def :: Traces+  def = $(getDefault @'["processors", "traces"] defaultConfig)++instance Default Profiles where+  def :: Profiles+  def = $(getDefault @'["processors", "profiles"] defaultConfig)++-- NOTE: This should be kept in sync with the list of logs.+--       Specifically, there should be a `Default` instance for every log.++instance Default ThreadLabelLog where+  def :: ThreadLabelLog+  def = $(getDefault @'["processors", "logs", "threadLabel"] defaultConfig)++instance Default UserMarkerLog where+  def :: UserMarkerLog+  def = $(getDefault @'["processors", "logs", "userMarker"] defaultConfig)++instance Default UserMessageLog where+  def :: UserMessageLog+  def = $(getDefault @'["processors", "logs", "userMessage"] defaultConfig)++instance Default InternalLogMessageLog where+  def :: InternalLogMessageLog+  def = $(getDefault @'["processors", "logs", "internalLogMessage"] defaultConfig)++-- NOTE: This should be kept in sync with the list of metrics.+--       Specifically, there should be a `Default` instance for every metric.++instance Default HeapAllocatedMetric where+  def :: HeapAllocatedMetric+  def = $(getDefault @'["processors", "metrics", "heapAllocated"] defaultConfig)++instance Default BlocksSizeMetric where+  def :: BlocksSizeMetric+  def = $(getDefault @'["processors", "metrics", "blocksSize"] defaultConfig)++instance Default HeapSizeMetric where+  def :: HeapSizeMetric+  def = $(getDefault @'["processors", "metrics", "heapSize"] defaultConfig)++instance Default HeapLiveMetric where+  def :: HeapLiveMetric+  def = $(getDefault @'["processors", "metrics", "heapLive"] defaultConfig)++instance Default MemCurrentMetric where+  def :: MemCurrentMetric+  def = $(getDefault @'["processors", "metrics", "memCurrent"] defaultConfig)++instance Default MemNeededMetric where+  def :: MemNeededMetric+  def = $(getDefault @'["processors", "metrics", "memNeeded"] defaultConfig)++instance Default MemReturnedMetric where+  def :: MemReturnedMetric+  def = $(getDefault @'["processors", "metrics", "memReturned"] defaultConfig)++instance Default GcCopiedMetric where+  def :: GcCopiedMetric+  def = $(getDefault @'["processors", "metrics", "gcCopied"] defaultConfig)++instance Default GcSlopMetric where+  def :: GcSlopMetric+  def = $(getDefault @'["processors", "metrics", "gcSlop"] defaultConfig)++instance Default GcFragmentationMetric where+  def :: GcFragmentationMetric+  def = $(getDefault @'["processors", "metrics", "gcFragmentation"] defaultConfig)++instance Default HeapProfSampleMetric where+  def :: HeapProfSampleMetric+  def = $(getDefault @'["processors", "metrics", "heapProfSample"] defaultConfig)++instance Default CapabilityUsageMetric where+  def :: CapabilityUsageMetric+  def = $(getDefault @'["processors", "metrics", "capabilityUsage"] defaultConfig)++instance Default ProductivityMetric where+  def :: ProductivityMetric+  def = $(getDefault @'["processors", "metrics", "productivity"] defaultConfig)++instance Default InternalEventCountMetric where+  def :: InternalEventCountMetric+  def = $(getDefault @'["processors", "metrics", "internalEventCount"] defaultConfig)++instance Default InternalExportedLogsMetric where+  def :: InternalExportedLogsMetric+  def = $(getDefault @'["processors", "metrics", "internalExportedLogs"] defaultConfig)++instance Default InternalRejectedLogsMetric where+  def :: InternalRejectedLogsMetric+  def = $(getDefault @'["processors", "metrics", "internalRejectedLogs"] defaultConfig)++instance Default InternalExportedMetricsMetric where+  def :: InternalExportedMetricsMetric+  def = $(getDefault @'["processors", "metrics", "internalExportedMetrics"] defaultConfig)++instance Default InternalRejectedMetricsMetric where+  def :: InternalRejectedMetricsMetric+  def = $(getDefault @'["processors", "metrics", "internalRejectedMetrics"] defaultConfig)++instance Default InternalExportedSamplesMetric where+  def :: InternalExportedSamplesMetric+  def = $(getDefault @'["processors", "metrics", "internalExportedSamples"] defaultConfig)++instance Default InternalRejectedSamplesMetric where+  def :: InternalRejectedSamplesMetric+  def = $(getDefault @'["processors", "metrics", "internalRejectedSamples"] defaultConfig)++instance Default InternalExportedSpansMetric where+  def :: InternalExportedSpansMetric+  def = $(getDefault @'["processors", "metrics", "internalExportedSpans"] defaultConfig)++instance Default InternalRejectedSpansMetric where+  def :: InternalRejectedSpansMetric+  def = $(getDefault @'["processors", "metrics", "internalRejectedSpans"] defaultConfig)++-- NOTE: This should be kept in sync with the list of traces.+--       Specifically, there should be a `Default` instance for every trace.++instance Default CapabilityUsageSpan where+  def :: CapabilityUsageSpan+  def = $(getDefault @'["processors", "traces", "capabilityUsage"] defaultConfig)++instance Default ThreadStateSpan where+  def :: ThreadStateSpan+  def = $(getDefault @'["processors", "traces", "threadState"] defaultConfig)++-- NOTE: This should be kept in sync with the list of profiles.+--       Specifically, there should be a `Default` instance for every profile.++instance Default CallStackProfile where+  def :: CallStackProfile+  def = $(getDefault @'["processors", "profiles", "callStackProfile"] defaultConfig)++instance Default CostCentreStackProfile where+  def :: CostCentreStackProfile+  def = $(getDefault @'["processors", "profiles", "costCentreStackProfile"] defaultConfig)++-------------------------------------------------------------------------------+-- Accessors+-------------------------------------------------------------------------------++{- |+Get the user-specified processor configuration.+-}+userProcessorConfig ::+  (Processors -> Maybe processorGroup) ->+  (processorGroup -> Maybe processorConfig) ->+  FullConfig ->+  Maybe processorConfig+userProcessorConfig group processor fullConfig =+  processor =<< group =<< fullConfig.config.processors++{- |+Get whether or not a processor is enabled.+-}+processorEnabled ::+  (HasField "export" processorConfig (Maybe ExportStrategy)) =>+  (Processors -> Maybe processorGroup) ->+  (processorGroup -> Maybe processorConfig) ->+  FullConfig ->+  Bool+processorEnabled group processor =+  isEnabled . userProcessorConfig group processor++{- |+Get the description corresponding to a processor.+-}+processorDescription ::+  forall a b.+  (Default b, HasField "description" b (Maybe Text)) =>+  (Processors -> Maybe a) ->+  (a -> Maybe b) ->+  FullConfig ->+  Maybe Text+processorDescription group processor =+  (.description) . fromMaybe (def :: b) . userProcessorConfig group processor++{- |+Get the name corresponding to a processor.+-}+processorName ::+  forall a b.+  (HasCallStack, Show b, Default b, HasField "name" b (Maybe Text)) =>+  (Processors -> Maybe a) ->+  (a -> Maybe b) ->+  FullConfig ->+  Text+processorName group processor =+  fromMaybe defaultName . ((.name) <=< userProcessorConfig group processor)+ where+  defaultName = fromMaybe (error errMsg) config.name+   where+    config = def :: b+    errMsg = "The default configuration has no name: " <> show config++--------------------------------------------------------------------------------+-- Aggregation Strategy++{- |+Get the aggregation strategy corresponding to a metric processor.+-}+processorAggregationStrategy ::+  (Default b, HasField "aggregate" b (Maybe AggregationStrategy)) =>+  (Processors -> Maybe a) ->+  (a -> Maybe b) ->+  FullConfig ->+  Maybe AggregationStrategy+processorAggregationStrategy group field =+  (.aggregate) . fromMaybe def . userProcessorConfig group field++{- |+Convert an `AggregationStrategy` to a number of batches.++__Precondition:__+If the aggregation strategy is defined in seconds,+then the batch interval should divide this duration.+-}+toAggregationBatches ::+  -- | The batch interval in milliseconds.+  Int ->+  -- | The @--eventlog-flush-interval@ in /batches/.+  Int ->+  -- | The aggregation strategy.+  Maybe AggregationStrategy ->+  Int+toAggregationBatches batchIntervalMs eventlogFlushIntervalX = \case+  -- If the setting is '60s' this means 60 seconds.+  Just (AggregationStrategyDuration DurationBySeconds{..}) -> toMilli seconds `div` batchIntervalMs+  -- If the setting is '60x' this means 60 times the /eventlog flush interval/,+  -- not the interal batch interval.+  Just (AggregationStrategyDuration DurationByBatches{..}) -> batches * eventlogFlushIntervalX+  -- If the setting is 'true' this means '1x', i.e., /eventlog flush interval/.+  Just AggregationStrategyBool{..} | isOn -> eventlogFlushIntervalX+  -- If the setting is absent or 'false' this means /do not aggregate/.+  Nothing -> 0+  Just AggregationStrategyBool{..} -> assert (not isOn) 0++{- |+Get the aggregation strategy corresponding to a metric processor.+-}+processorAggregationBatches ::+  (Default b, HasField "aggregate" b (Maybe AggregationStrategy)) =>+  -- | The accessor for the sub-group of processors.+  (Processors -> Maybe a) ->+  -- | The accessor for the individual processor.+  (a -> Maybe b) ->+  -- | The full configuration.+  FullConfig ->+  Int+processorAggregationBatches group field fullConfig =+  toAggregationBatches fullConfig.batchIntervalMs fullConfig.eventlogFlushIntervalX $+    processorAggregationStrategy group field fullConfig++{- |+Get all aggregation strategies.+-}+allAggregationStrategies ::+  Config ->+  [AggregationStrategy]+allAggregationStrategies =+  catMaybes . with (.processors) (with (.metrics) (forEachMetricProcessor ((.aggregate) =<<)))++{- |+Get the largest aggregation strategy in batches.+-}+maximumAggregationBatches ::+  FullConfig ->+  Int+maximumAggregationBatches fullConfig =+  maximum . fmap (toAggregationBatches fullConfig.batchIntervalMs fullConfig.eventlogFlushIntervalX . Just) $+    allAggregationStrategies fullConfig.config++--------------------------------------------------------------------------------+-- Export Strategy++{- |+Get the export strategy corresponding to a processor.+-}+processorExportStrategy ::+  (Default b, HasField "export" b (Maybe ExportStrategy)) =>+  (Processors -> Maybe a) ->+  (a -> Maybe b) ->+  FullConfig ->+  Maybe ExportStrategy+processorExportStrategy group field =+  (.export) . fromMaybe def . userProcessorConfig group field++{- |+Convert an `ExportStrategy` to a number of batches.++__Precondition:__+If the export strategy is defined in seconds,+then the batch interval should divide this duration.+-}+toExportBatches ::+  -- | The batch interval in milliseconds.+  Int ->+  -- | The @--eventlog-flush-interval@ in /batches/.+  Int ->+  -- | The export strategy.+  Maybe ExportStrategy ->+  Int+toExportBatches batchIntervalMs eventlogFlushIntervalX = \case+  -- If the setting is '60s' this means 60 seconds.+  Just (ExportStrategyDuration DurationBySeconds{..}) -> toMilli seconds `div` batchIntervalMs+  -- If the setting is '60x' this means 60 times the /eventlog flush interval/,+  -- not the interal batch interval.+  Just (ExportStrategyDuration DurationByBatches{..}) -> batches * eventlogFlushIntervalX+  -- If the setting is 'true' this means '1x', i.e., /eventlog flush interval/.+  Just ExportStrategyBool{..} | isOn -> eventlogFlushIntervalX+  -- If the setting is absent or 'false' this means /do not aggregate/.+  Nothing -> 0+  Just ExportStrategyBool{..} -> assert (not isOn) 0++{- |+Get the export strategy corresponding to processor in batches.+-}+processorExportBatches ::+  (Default b, HasField "export" b (Maybe ExportStrategy)) =>+  (Processors -> Maybe a) ->+  (a -> Maybe b) ->+  FullConfig ->+  Int+processorExportBatches group field fullConfig =+  toExportBatches fullConfig.batchIntervalMs fullConfig.eventlogFlushIntervalX $+    processorExportStrategy group field fullConfig++{- |+Get all export strategies.+-}+allExportStrategies ::+  Config ->+  [ExportStrategy]+allExportStrategies =+  catMaybes . with (.processors) (forEachProcessor ((.export) =<<))++{- |+Get the largest export strategy in batches.+-}+maximumExportBatches ::+  FullConfig ->+  Int+maximumExportBatches fullConfig =+  maximum . fmap (toExportBatches fullConfig.batchIntervalMs fullConfig.eventlogFlushIntervalX . Just) $+    allExportStrategies fullConfig.config++-------------------------------------------------------------------------------+-- Batch Interval++{- |+Get the batch interval such that all user-specified intervals can be respected.+-}+toBatchIntervalMs ::+  -- | The @--eventlog-flush-interval@.+  Double ->+  -- | The configuration.+  Config ->+  Int+toBatchIntervalMs eventlogFlushIntervalS config =+  (.getGCD) . sconcat . fmap GCD $+    eventlogFlushIntervalMs :| aggregationIntervalsMs <> exportIntervalsMs+ where+  -- TODO: Check if any intervals round to 0ms.+  eventlogFlushIntervalMs =+    toMilli eventlogFlushIntervalS+  aggregationIntervalsMs =+    mapMaybe (fmap toMilli . toAggregationSeconds) . allAggregationStrategies $ config+  exportIntervalsMs =+    mapMaybe (fmap toMilli . toExportSeconds) . allExportStrategies $ config++{- |+Get the relevant interval in batches.++__Precondition:__ The batch interval divides the relevant interval.+-}+toBatches ::+  -- | The batch interval in milliseconds.+  Int ->+  -- | The relevant interval in seconds.+  Double ->+  Int+toBatches batchIntervalMs intervalS =+  toMilli intervalS `div` batchIntervalMs++-------------------------------------------------------------------------------+-- Exporters+-------------------------------------------------------------------------------++shouldExportLogs :: FullConfig -> Bool+shouldExportLogs =+  getAny+    . with+      (.processors)+      ( with+          (.logs)+          (mconcat . forEachLogProcessor (Any . isEnabled))+      )+    . (.config)++shouldExportMetrics :: FullConfig -> Bool+shouldExportMetrics =+  getAny+    . with+      (.processors)+      ( with+          (.metrics)+          (mconcat . forEachMetricProcessor (Any . isEnabled))+      )+    . (.config)++shouldExportTraces :: FullConfig -> Bool+shouldExportTraces =+  getAny+    . with+      (.processors)+      ( with+          (.traces)+          (mconcat . forEachTraceProcessor (Any . isEnabled))+      )+    . (.config)++shouldExportProfiles :: FullConfig -> Bool+shouldExportProfiles =+  getAny+    . with+      (.processors)+      ( with+          (.profiles)+          (mconcat . forEachProfileProcessor (Any . isEnabled))+      )+    . (.config)++-------------------------------------------------------------------------------+-- Functors for processor configurations+-------------------------------------------------------------------------------++{- |+Apply a function to each processor.+-}+forEachProcessor ::+  ( forall processorConfig.+    (IsProcessorConfig processorConfig) =>+    Maybe processorConfig -> a+  ) ->+  Processors ->+  [a]+forEachProcessor f processors =+  concatMap (fromMaybe []) $+    [ forEachLogProcessor f <$> processors.logs+    , forEachMetricProcessor f <$> processors.metrics+    , forEachTraceProcessor f <$> processors.traces+    , forEachProfileProcessor f <$> processors.profiles+    ]++{- |+Apply a function to each metric processor.+-}+forEachLogProcessor ::+  ( forall traceProcessorConfig.+    (IsLogProcessorConfig traceProcessorConfig) =>+    Maybe traceProcessorConfig -> a+  ) ->+  Logs ->+  [a]+forEachLogProcessor f logs =+  [ -- NOTE: This should be kept in sync with the list of logs.+    f logs.threadLabel+  , f logs.userMarker+  , f logs.userMessage+  , f logs.internalLogMessage+  ]++{- |+Apply a function to each metric processor.+-}+forEachMetricProcessor ::+  ( forall metricProcessorConfig.+    (IsMetricProcessorConfig metricProcessorConfig) =>+    Maybe metricProcessorConfig -> a+  ) ->+  Metrics ->+  [a]+forEachMetricProcessor f metrics =+  [ -- NOTE: This should be kept in sync with the list of metrics.+    f metrics.heapAllocated+  , f metrics.blocksSize+  , f metrics.heapSize+  , f metrics.heapLive+  , f metrics.memCurrent+  , f metrics.memNeeded+  , f metrics.memReturned+  , f metrics.heapProfSample+  , f metrics.capabilityUsage+  ]++{- |+Apply a function to each metric processor.+-}+forEachTraceProcessor ::+  ( forall traceProcessorConfig.+    (IsTraceProcessorConfig traceProcessorConfig) =>+    Maybe traceProcessorConfig -> a+  ) ->+  Traces ->+  [a]+forEachTraceProcessor f traces =+  [ -- NOTE: This should be kept in sync with the list of traces.+    f traces.capabilityUsage+  , f traces.threadState+  ]++{- |+Apply a function to each metric processor.+-}+forEachProfileProcessor ::+  ( forall profileProcessorConfig.+    (IsProfileProcessorConfig profileProcessorConfig) =>+    Maybe profileProcessorConfig -> a+  ) ->+  Profiles ->+  [a]+forEachProfileProcessor f profiles =+  [ -- NOTE: This should be kept in sync with the list of profiles.+    f profiles.callStackProfile+  , f profiles.costCentreStackProfile+  ]++-------------------------------------------------------------------------------+-- Internal Helpers+-------------------------------------------------------------------------------++{- |+Internal helper.+-}+with :: (Foldable f, Monoid r) => (s -> f t) -> (t -> r) -> s -> r+with = flip ((.) . foldMap)++{- |+Internal helper.+Convert seconds to milliseconds.+-}+toMilli :: Double -> Int+toMilli seconds = round (seconds * 1_000)++{- |+Internal helper.+Wrapper that provides a `Semigroup` instance for `gcd`.+-}+newtype GCD a = GCD {getGCD :: a}++instance (Integral a) => Semigroup (GCD a) where+  (<>) :: GCD a -> GCD a -> GCD a+  x <> y = GCD{getGCD = x.getGCD `gcd` y.getGCD}
+ src-lib/GHC/Eventlog/Live/Config/Default.hs view
@@ -0,0 +1,104 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE UndecidableInstances #-}++{- |+Module      : GHC.Eventlog.Live.Config+Description : The implementation of @eventlog-live@.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Config.Default (+  defaultConfig,++  -- * Internal helpers for defining `Default` instances+  MissingDefaultException (..),+  getDefault,+) where++import Control.Exception (Exception (..), throw)+import Data.Bifunctor (Bifunctor (..))+import Data.Kind (Type)+import Data.List (intercalate)+import Data.Proxy (Proxy (..))+import GHC.Eventlog.Live.Config.Default.Raw (decodeThrow, defaultConfigByteString)+import GHC.Eventlog.Live.Config.Types (Config)+import GHC.Records (HasField (..))+import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)+import Language.Haskell.TH.Lift (Exp, Lift (..), Q)++{- |+Internal helper.+The default configuration.+-}+defaultConfig :: Config+defaultConfig = $(lift =<< decodeThrow @Q @Config defaultConfigByteString)++{- |+__Warning:__ Compile-time only.++Internal helper.+This exception is thrown when a property is missing from the default configuration file.+-}+newtype MissingDefaultException+  = MissingDefaultException+  { accessors :: [String]+  }++instance Show MissingDefaultException where+  show :: MissingDefaultException -> String+  show e =+    "Missing property '" <> intercalate "." e.accessors <> "' in default configuration"++instance Exception MissingDefaultException++{- |+__Warning:__ Compile-time only.++Internal helper.+Get the default value under the given path of accessors and `lift` it.+-}+getDefault ::+  forall xs a b.+  (GetDefault xs a b, Lift b) =>+  a ->+  Q Exp+getDefault a = either throw lift (getDefaultEither @xs @a @b a)++{- |+__Warning:__ Compile-time only.++Internal helper.+Get the default value under the given accessor after calling a recursor.+This function is used to implement the `GetDefault` instances.+-}+getDefaultEither' ::+  forall x a b c.+  (KnownSymbol x, HasField x a (Maybe b)) =>+  (b -> Either MissingDefaultException c) ->+  a ->+  Either MissingDefaultException c+getDefaultEither' rec a =+  first addAccessor . maybe (Left $ MissingDefaultException []) rec $ getField @x a+ where+  addAccessor :: MissingDefaultException -> MissingDefaultException+  addAccessor e = MissingDefaultException{accessors = symbolVal (Proxy @x) : e.accessors}++{- |+__Warning:__ Compile-time only.++Internal helper.+This class guides the search for `getDefaultEither` functions from a list of accessors.+-}+class GetDefault (xs :: [Symbol]) (a :: Type) (b :: Type) where+  getDefaultEither :: a -> Either MissingDefaultException b++instance (KnownSymbol x, HasField x a (Maybe b)) => GetDefault (x ': '[]) a b where+  getDefaultEither :: a -> Either MissingDefaultException b+  getDefaultEither = getDefaultEither' @x Right+  {-# INLINE getDefaultEither #-}++instance (KnownSymbol x, HasField x a (Maybe b), GetDefault (y ': ys) b c) => GetDefault (x ': y ': ys) a c where+  getDefaultEither :: a -> Either MissingDefaultException c+  getDefaultEither = getDefaultEither' @x (getDefaultEither @(y ': ys))+  {-# INLINE getDefaultEither #-}
+ src-lib/GHC/Eventlog/Live/Config/Default/Raw.hs view
@@ -0,0 +1,74 @@+{-# LANGUAGE TemplateHaskell #-}++{- |+Module      : GHC.Eventlog.Live.Config.Default.Raw+Description : The implementation of @eventlog-live@.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Config.Default.Raw (+  defaultConfigByteString,+  defaultConfigString,+  defaultConfigJSONSchemaByteString,+  defaultConfigJSONSchemaString,++  -- * Compile-time only helper functions+  decodeThrow,+) where++import Data.ByteString (ByteString)+import Data.ByteString.Lazy qualified as BSL+import Data.FileEmbed (embedFileRelative)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Data.YAML (FromYAML)+import Data.YAML qualified as YAML++{- |+Internal helper.+The default configuration as a `ByteString`.+-}+defaultConfigByteString :: ByteString+defaultConfigByteString = $(embedFileRelative "data/default.yaml")++{- |+Internal helper.+The default configuration as a `String`.+-}+defaultConfigString :: String+defaultConfigString = fromByteString defaultConfigByteString++{- |+Internal helper.+The default configuration as a `ByteString`.+-}+defaultConfigJSONSchemaByteString :: ByteString+defaultConfigJSONSchemaByteString = $(embedFileRelative "data/config.schema.json")++{- |+Internal helper.+The default configuration as a `String`.+-}+defaultConfigJSONSchemaString :: String+defaultConfigJSONSchemaString = fromByteString defaultConfigJSONSchemaByteString++{- |+__Warning:__ Compile-time only.++Internal helper.+Decode a `ByteString` or throw an exception.+-}+decodeThrow :: (MonadFail m, FromYAML a) => ByteString -> m a+decodeThrow byteString =+  either (fail . prettyErrorMessage) pure $ YAML.decode1Strict byteString+ where+  prettyErrorMessage :: (YAML.Pos, String) -> String+  prettyErrorMessage (pos, errorMessage) =+    YAML.prettyPosWithSource pos (BSL.fromStrict byteString) " error" <> errorMessage++{- |+Internal helper.+Decode a `ByteString` to a `String`.+-}+fromByteString :: ByteString -> String+fromByteString = T.unpack . TE.decodeUtf8Lenient
+ src-lib/GHC/Eventlog/Live/Config/Types.hs view
@@ -0,0 +1,1163 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.Config.Types+Description : The implementation of @eventlog-live@.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Config.Types (+  -- * Configuration type+  Config (..),+  FullConfig (..),++  -- ** Processor configuration types+  Processors (..),+  IsProcessorConfig,++  -- *** Log processor configuration types+  Logs (..),+  IsLogProcessorConfig,+  ThreadLabelLog (..),+  UserMarkerLog (..),+  UserMessageLog (..),+  InternalLogMessageLog (..),++  -- *** Metric processor configuration types+  Metrics (..),+  IsMetricProcessorConfig,+  HeapAllocatedMetric (..),+  BlocksSizeMetric (..),+  HeapSizeMetric (..),+  HeapLiveMetric (..),+  MemCurrentMetric (..),+  MemNeededMetric (..),+  MemReturnedMetric (..),+  HeapProfSampleMetric (..),+  GcCopiedMetric (..),+  GcSlopMetric (..),+  GcFragmentationMetric (..),+  CapabilityUsageMetric (..),+  ProductivityMetric (..),+  InternalEventCountMetric (..),+  InternalExportedLogsMetric (..),+  InternalRejectedLogsMetric (..),+  InternalExportedMetricsMetric (..),+  InternalRejectedMetricsMetric (..),+  InternalExportedSamplesMetric (..),+  InternalRejectedSamplesMetric (..),+  InternalExportedSpansMetric (..),+  InternalRejectedSpansMetric (..),++  -- *** Trace processor configuration types+  Traces (..),+  IsTraceProcessorConfig,+  CapabilityUsageSpan (..),+  ThreadStateSpan (..),++  -- *** Profile processor configuration types+  Profiles (..),+  IsProfileProcessorConfig,+  CallStackProfile (..),+  CostCentreStackProfile (..),++  -- ** Property types+  Duration (..),+  AggregationStrategy (..),+  toAggregationSeconds,+  ExportStrategy (..),+  toExportSeconds,+  isEnabled,+) where++import Control.Applicative (asum)+import Data.Char (isDigit)+import Data.Kind (Constraint, Type)+import Data.Text (Text)+import Data.Text qualified as T+import Data.YAML (FromYAML (..), ToYAML, (.:?), (.=))+import Data.YAML qualified as YAML+import GHC.Records (HasField (..))+import Language.Haskell.TH.Lift (Lift)+import Text.ParserCombinators.ReadP (ReadP)+import Text.ParserCombinators.ReadP qualified as P+import Text.Read (readEither)++{- |+The extended configuration with derived fields.+-}+data FullConfig = FullConfig+  { batchIntervalMs :: !Int+  -- ^ The batch interval in milliseconds.+  , eventlogFlushIntervalX :: !Int+  -- ^ The @--eventlog-flush-interval@ in /batches/.+  , config :: !Config+  }++{- |+The configuration for @eventlog-live@.+-}+newtype Config = Config+  { processors :: Maybe Processors+  }+  deriving (Lift, Show)++instance FromYAML Config where+  parseYAML = YAML.withMap "Config" $ \m ->+    Config+      <$> m .:? "processors"++instance ToYAML Config where+  toYAML config =+    YAML.mapping+      [ "processors" .= config.processors+      ]++{- |+The configuration options for the processors.+-}+data Processors = Processors+  { logs :: Maybe Logs+  , metrics :: Maybe Metrics+  , traces :: Maybe Traces+  , profiles :: Maybe Profiles+  }+  deriving (Lift, Show)++instance FromYAML Processors where+  parseYAML = YAML.withMap "Processors" $ \m ->+    Processors+      <$> m .:? "logs"+      <*> m .:? "metrics"+      <*> m .:? "traces"+      <*> m .:? "profiles"++instance ToYAML Processors where+  toYAML processors =+    YAML.mapping+      [ "logs" .= processors.logs+      , "metrics" .= processors.metrics+      , "traces" .= processors.traces+      , "profiles" .= processors.profiles+      ]++{- |+The configuration options for the span processors.+-}++-- NOTE:+-- If you add a new log, search for the string...+--+--   This should be kept in sync with the list of logs.+--+-- ...and update all the relevant locations.+data Logs = Logs+  { threadLabel :: Maybe ThreadLabelLog+  , userMarker :: Maybe UserMarkerLog+  , userMessage :: Maybe UserMessageLog+  , internalLogMessage :: Maybe InternalLogMessageLog+  }+  deriving (Lift, Show)++instance FromYAML Logs where+  parseYAML =+    -- NOTE: This should be kept in sync with the list of logs.+    YAML.withMap "Logs" $ \m ->+      Logs+        <$> m .:? "thread_label"+        <*> m .:? "user_marker"+        <*> m .:? "user_message"+        <*> m .:? "internal_log_message"++instance ToYAML Logs where+  toYAML logs =+    -- NOTE: This should be kept in sync with the list of logs.+    YAML.mapping+      [ "thread_label" .= logs.threadLabel+      , "user_marker" .= logs.userMarker+      , "user_message" .= logs.userMessage+      , "internal_log_message" .= logs.internalLogMessage+      ]++{- |+The configuration options for the metric processors.+-}++-- NOTE:+-- If you add a new metric, search for the string...+--+--   This should be kept in sync with the list of metrics.+--+-- ...and update all the relevant locations.+data Metrics = Metrics+  { heapAllocated :: Maybe HeapAllocatedMetric+  , blocksSize :: Maybe BlocksSizeMetric+  , heapSize :: Maybe HeapSizeMetric+  , heapLive :: Maybe HeapLiveMetric+  , memCurrent :: Maybe MemCurrentMetric+  , memNeeded :: Maybe MemNeededMetric+  , memReturned :: Maybe MemReturnedMetric+  , gcCopied :: Maybe GcCopiedMetric+  , gcSlop :: Maybe GcSlopMetric+  , gcFragmentation :: Maybe GcFragmentationMetric+  , heapProfSample :: Maybe HeapProfSampleMetric+  , capabilityUsage :: Maybe CapabilityUsageMetric+  , productivity :: Maybe ProductivityMetric+  , internalEventCount :: Maybe InternalEventCountMetric+  , internalExportedLogs :: Maybe InternalExportedLogsMetric+  , internalRejectedLogs :: Maybe InternalRejectedLogsMetric+  , internalExportedMetrics :: Maybe InternalExportedMetricsMetric+  , internalRejectedMetrics :: Maybe InternalRejectedMetricsMetric+  , internalExportedSamples :: Maybe InternalExportedSamplesMetric+  , internalRejectedSamples :: Maybe InternalRejectedSamplesMetric+  , internalExportedSpans :: Maybe InternalExportedSpansMetric+  , internalRejectedSpans :: Maybe InternalRejectedSpansMetric+  }+  deriving (Lift, Show)++instance FromYAML Metrics where+  parseYAML =+    -- NOTE: This should be kept in sync with the list of metrics.+    YAML.withMap "Metrics" $ \m -> do+      heapAllocated <- m .:? "heap_allocated"+      blocksSize <- m .:? "blocks_size"+      heapSize <- m .:? "heap_size"+      heapLive <- m .:? "heap_live"+      memCurrent <- m .:? "mem_current"+      memNeeded <- m .:? "mem_needed"+      memReturned <- m .:? "mem_returned"+      gcCopied <- m .:? "gc_copied"+      gcSlop <- m .:? "gc_slop"+      gcFragmentation <- m .:? "gc_fragmentation"+      heapProfSample <- m .:? "heap_prof_sample"+      capabilityUsage <- m .:? "capability_usage"+      productivity <- m .:? "productivity"+      internalEventCount <- m .:? "internal_event_count"+      internalExportedLogs <- m .:? "internal_exported_logs"+      internalRejectedLogs <- m .:? "internal_rejected_logs"+      internalExportedMetrics <- m .:? "internal_exported_metrics"+      internalRejectedMetrics <- m .:? "internal_rejected_metrics"+      internalExportedSamples <- m .:? "internal_exported_samples"+      internalRejectedSamples <- m .:? "internal_rejected_samples"+      internalExportedSpans <- m .:? "internal_exported_spans"+      internalRejectedSpans <- m .:? "internal_rejected_spans"+      pure Metrics{..}++instance ToYAML Metrics where+  toYAML metrics =+    -- NOTE: This should be kept in sync with the list of metrics.+    YAML.mapping+      [ "heap_allocated" .= metrics.heapAllocated+      , "blocks_size" .= metrics.blocksSize+      , "heap_size" .= metrics.heapSize+      , "heap_live" .= metrics.heapLive+      , "mem_current" .= metrics.memCurrent+      , "mem_needed" .= metrics.memNeeded+      , "mem_returned" .= metrics.memReturned+      , "gc_copied" .= metrics.gcCopied+      , "gc_slop" .= metrics.gcSlop+      , "gc_fragmentation" .= metrics.gcFragmentation+      , "heap_prof_sample" .= metrics.heapProfSample+      , "capability_usage" .= metrics.capabilityUsage+      , "productivity" .= metrics.productivity+      , "internal_event_count" .= metrics.internalEventCount+      , "internal_exported_logs" .= metrics.internalExportedLogs+      , "internal_rejected_logs" .= metrics.internalRejectedLogs+      , "internal_exported_metrics" .= metrics.internalExportedMetrics+      , "internal_rejected_metrics" .= metrics.internalRejectedMetrics+      , "internal_exported_samples" .= metrics.internalExportedSamples+      , "internal_rejected_samples" .= metrics.internalRejectedSamples+      , "internal_exported_spans" .= metrics.internalExportedSpans+      , "internal_rejected_spans" .= metrics.internalRejectedSpans+      ]++{- |+The configuration options for the span processors.+-}++-- NOTE:+-- If you add a new trace, search for the string...+--+--   This should be kept in sync with the list of traces.+--+-- ...and update all the relevant locations.+data Traces = Traces+  { capabilityUsage :: Maybe CapabilityUsageSpan+  , threadState :: Maybe ThreadStateSpan+  }+  deriving (Lift, Show)++instance FromYAML Traces where+  parseYAML =+    -- NOTE: This should be kept in sync with the list of traces.+    YAML.withMap "Traces" $ \m ->+      Traces+        <$> m .:? "capability_usage"+        <*> m .:? "thread_state"++instance ToYAML Traces where+  toYAML traces =+    -- NOTE: This should be kept in sync with the list of traces.+    YAML.mapping+      [ "capability_usage" .= traces.capabilityUsage+      , "thread_state" .= traces.threadState+      ]++{- |+The configuration options for the profile processors.+-}+data Profiles = Profiles+  { callStackProfile :: Maybe CallStackProfile+  , costCentreStackProfile :: Maybe CostCentreStackProfile+  }+  deriving (Lift, Show)++instance FromYAML Profiles where+  parseYAML =+    -- NOTE: This should be kept in sync with the list of profiles.+    YAML.withMap "Profiles" $ \m ->+      Profiles+        <$> m .:? "call_stack_profile"+        <*> m .:? "cost_centre_stack_profile"++instance ToYAML Profiles where+  toYAML profiles =+    -- NOTE: This should be kept in sync with the list of profiles.+    YAML.mapping+      [ "call_stack_profile" .= profiles.callStackProfile+      , "cost_centre_stack_profile" .= profiles.costCentreStackProfile+      ]++-------------------------------------------------------------------------------+-- Logs+-------------------------------------------------------------------------------++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Thread.processThreadLabelLogData`.+-}+data ThreadLabelLog = ThreadLabelLog+  { name :: Maybe Text+  , description :: Maybe Text+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML ThreadLabelLog where+  parseYAML = genericParseYAMLLogProcessorConfig "ThreadLabelLog" ThreadLabelLog++instance ToYAML ThreadLabelLog where+  toYAML = genericToYAMLLogProcessorConfig++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Log.processUserMessageLog`.+-}+data UserMessageLog = UserMessageLog+  { name :: Maybe Text+  , description :: Maybe Text+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML UserMessageLog where+  parseYAML = genericParseYAMLLogProcessorConfig "UserMessageLog" UserMessageLog++instance ToYAML UserMessageLog where+  toYAML = genericToYAMLLogProcessorConfig++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Log.processUserMarkerLog`.+-}+data UserMarkerLog = UserMarkerLog+  { name :: Maybe Text+  , description :: Maybe Text+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML UserMarkerLog where+  parseYAML = genericParseYAMLLogProcessorConfig "UserMarkerLog" UserMarkerLog++instance ToYAML UserMarkerLog where+  toYAML = genericToYAMLLogProcessorConfig++{- |+The configuration options for internal log messages.+-}+data InternalLogMessageLog = InternalLogMessageLog+  { name :: Maybe Text+  , description :: Maybe Text+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML InternalLogMessageLog where+  parseYAML = genericParseYAMLLogProcessorConfig "InternalLogMessageLog" InternalLogMessageLog++instance ToYAML InternalLogMessageLog where+  toYAML = genericToYAMLLogProcessorConfig++-------------------------------------------------------------------------------+-- Metrics+-------------------------------------------------------------------------------++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Heap.processHeapAllocatedData`.+-}+data HeapAllocatedMetric = HeapAllocatedMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML HeapAllocatedMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "HeapAllocatedMetric" HeapAllocatedMetric++instance ToYAML HeapAllocatedMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Heap.processHeapSizeData`.+-}+data HeapSizeMetric = HeapSizeMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML HeapSizeMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "HeapSizeMetric" HeapSizeMetric++instance ToYAML HeapSizeMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Heap.processBlocksSizeData`.+-}+data BlocksSizeMetric = BlocksSizeMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML BlocksSizeMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "BlocksSizeMetric" BlocksSizeMetric++instance ToYAML BlocksSizeMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Heap.processHeapLiveData`.+-}+data HeapLiveMetric = HeapLiveMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML HeapLiveMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "HeapLiveMetric" HeapLiveMetric++instance ToYAML HeapLiveMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the @memCurrent@ field `GHC.Eventlog.Live.Machine.Analysis.Heap.processMemReturnData`.+-}+data MemCurrentMetric = MemCurrentMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML MemCurrentMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "MemCurrentMetric" MemCurrentMetric++instance ToYAML MemCurrentMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the @memNeeded@ field `GHC.Eventlog.Live.Machine.Analysis.Heap.processMemReturnData`.+-}+data MemNeededMetric = MemNeededMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML MemNeededMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "MemNeededMetric" MemNeededMetric++instance ToYAML MemNeededMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the @memReturned@ field `GHC.Eventlog.Live.Machine.Analysis.Heap.processMemReturnData`.+-}+data MemReturnedMetric = MemReturnedMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML MemReturnedMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "MemReturnedMetric" MemReturnedMetric++instance ToYAML MemReturnedMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Heap.processHeapProfSampleData`.+-}+data HeapProfSampleMetric = HeapProfSampleMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML HeapProfSampleMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "HeapProfSampleMetric" HeapProfSampleMetric++instance ToYAML HeapProfSampleMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the @copied@ field for `GHC.Eventlog.Live.Machine.Analysis.Heap.processGcStats`.+-}+data GcCopiedMetric = GcCopiedMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML GcCopiedMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "GcCopiedMetric" GcCopiedMetric++instance ToYAML GcCopiedMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the @copied@ field for `GHC.Eventlog.Live.Machine.Analysis.Heap.processGcStats`.+-}+data GcSlopMetric = GcSlopMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML GcSlopMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "GcSlopMetric" GcSlopMetric++instance ToYAML GcSlopMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the @copied@ field for `GHC.Eventlog.Live.Machine.Analysis.Heap.processGcStats`.+-}+data GcFragmentationMetric = GcFragmentationMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML GcFragmentationMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "GcFragmentationMetric" GcFragmentationMetric++instance ToYAML GcFragmentationMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Capability.processCapabilityUsageDurationData`.+-}+data CapabilityUsageMetric = CapabilityUsageMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML CapabilityUsageMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "CapabilityUsageMetric" CapabilityUsageMetric++instance ToYAML CapabilityUsageMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Capability.processProductivityData`.+-}+data ProductivityMetric = ProductivityMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML ProductivityMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "ProductivityMetric" ProductivityMetric++instance ToYAML ProductivityMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the internal count of received events.+-}+data InternalEventCountMetric = InternalEventCountMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML InternalEventCountMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "InternalEventCountMetric" InternalEventCountMetric++instance ToYAML InternalEventCountMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the internal count of exported logs metric.+-}+data InternalExportedLogsMetric = InternalExportedLogsMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML InternalExportedLogsMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "InternalExportedLogsMetric" InternalExportedLogsMetric++instance ToYAML InternalExportedLogsMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the internal count of rejected logs.+-}+data InternalRejectedLogsMetric = InternalRejectedLogsMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML InternalRejectedLogsMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "InternalRejectedLogsMetric" InternalRejectedLogsMetric++instance ToYAML InternalRejectedLogsMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the internal count of exported metrics metric.+-}+data InternalExportedMetricsMetric = InternalExportedMetricsMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML InternalExportedMetricsMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "InternalExportedMetricsMetric" InternalExportedMetricsMetric++instance ToYAML InternalExportedMetricsMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the internal count of rejected metrics.+-}+data InternalRejectedMetricsMetric = InternalRejectedMetricsMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML InternalRejectedMetricsMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "InternalRejectedMetricsMetric" InternalRejectedMetricsMetric++instance ToYAML InternalRejectedMetricsMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the internal count of exported samples metric.+-}+data InternalExportedSamplesMetric = InternalExportedSamplesMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML InternalExportedSamplesMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "InternalExportedSamplesMetric" InternalExportedSamplesMetric++instance ToYAML InternalExportedSamplesMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the internal count of rejected samples.+-}+data InternalRejectedSamplesMetric = InternalRejectedSamplesMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML InternalRejectedSamplesMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "InternalRejectedSamplesMetric" InternalRejectedSamplesMetric++instance ToYAML InternalRejectedSamplesMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the internal count of exported spans metric.+-}+data InternalExportedSpansMetric = InternalExportedSpansMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML InternalExportedSpansMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "InternalExportedSpansMetric" InternalExportedSpansMetric++instance ToYAML InternalExportedSpansMetric where+  toYAML = genericToYAMLMetricProcessorConfig++{- |+The configuration options for the internal count of rejected spans.+-}+data InternalRejectedSpansMetric = InternalRejectedSpansMetric+  { name :: Maybe Text+  , description :: Maybe Text+  , aggregate :: Maybe AggregationStrategy+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML InternalRejectedSpansMetric where+  parseYAML = genericParseYAMLMetricProcessorConfig "InternalRejectedSpansMetric" InternalRejectedSpansMetric++instance ToYAML InternalRejectedSpansMetric where+  toYAML = genericToYAMLMetricProcessorConfig++-------------------------------------------------------------------------------+-- Traces+-------------------------------------------------------------------------------++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Capability.processCapabilityUsageTraces`.+-}+data CapabilityUsageSpan = CapabilityUsageSpan+  { name :: Maybe Text+  , description :: Maybe Text+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML CapabilityUsageSpan where+  parseYAML = genericParseYAMLTraceProcessorConfig "CapabilityUsageSpan" CapabilityUsageSpan++instance ToYAML CapabilityUsageSpan where+  toYAML = genericToYAMLTraceProcessorConfig++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Thread.processThreadStateSpan`.+-}+data ThreadStateSpan = ThreadStateSpan+  { name :: Maybe Text+  , description :: Maybe Text+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML ThreadStateSpan where+  parseYAML = genericParseYAMLTraceProcessorConfig "ThreadStateSpan" ThreadStateSpan++instance ToYAML ThreadStateSpan where+  toYAML = genericToYAMLTraceProcessorConfig++-------------------------------------------------------------------------------+-- Profiles+-------------------------------------------------------------------------------++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Profile.processStackProfSampleData`.+-}+data CallStackProfile = CallStackProfile+  { name :: Maybe Text+  , description :: Maybe Text+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML CallStackProfile where+  parseYAML = genericParseYAMLProfilerProcessorConfig "CallStackProfile" CallStackProfile++instance ToYAML CallStackProfile where+  toYAML = genericToYAMLProfilerProcessorConfig++{- |+The configuration options for `GHC.Eventlog.Live.Machine.Analysis.Profile.processCostCentreProfSampleData`.+-}+data CostCentreStackProfile = CostCentreStackProfile+  { name :: Maybe Text+  , description :: Maybe Text+  , export :: Maybe ExportStrategy+  }+  deriving (Lift, Show)++instance FromYAML CostCentreStackProfile where+  parseYAML = genericParseYAMLProfilerProcessorConfig "CostCentreStackProfile" CostCentreStackProfile++instance ToYAML CostCentreStackProfile where+  toYAML = genericToYAMLProfilerProcessorConfig++-------------------------------------------------------------------------------+-- Configuration supertypes+-------------------------------------------------------------------------------++{- |+The structural type of processor configurations.+-}+type IsProcessorConfig :: Type -> Constraint+type IsProcessorConfig config =+  ( HasField "name" config (Maybe Text)+  , HasField "description" config (Maybe Text)+  , HasField "export" config (Maybe ExportStrategy)+  )++{- |+The structural type of log processor configurations.+-}+type IsLogProcessorConfig :: Type -> Constraint+type IsLogProcessorConfig config =+  (IsProcessorConfig config)++{- |+The structural type of metric processor configurations.+-}+type IsMetricProcessorConfig :: Type -> Constraint+type IsMetricProcessorConfig config =+  ( IsProcessorConfig config+  , HasField "aggregate" config (Maybe AggregationStrategy)+  )++{- |+The structural type of span processor configurations.+-}+type IsTraceProcessorConfig :: Type -> Constraint+type IsTraceProcessorConfig config =+  (IsProcessorConfig config)++{- |+The structural type of span processor configurations.+-}+type IsProfileProcessorConfig :: Type -> Constraint+type IsProfileProcessorConfig config =+  (IsProcessorConfig config)++--------------------------------------------------------------------------------+-- Duration+--------------------------------------------------------------------------------++data Duration+  = DurationByBatches {batches :: !Int}+  | DurationBySeconds {seconds :: !Double}+  deriving (Lift, Show)++{- |+Internal helper.+A `ReadP` style parser for `AggregationStrategy`.+-}+readPDuration :: ReadP Duration+readPDuration = do+  -- Parse the number+  integerPart <- P.munch1 isDigit+  maybeFractionPart <- P.option Nothing (Just <$ P.char '.' <*> P.munch1 isDigit)++  -- Make a duration by batches+  let byBatches =+        case maybeFractionPart of+          Nothing ->+            case readEither integerPart of+              Left errorMsg -> fail $ "Could not parse duration: " <> errorMsg+              Right batches -> pure DurationByBatches{..}+          Just fractionPart -> fail $ "Fractional batches are unsupported; found " <> integerPart <> "." <> fractionPart <> "x"++  -- Make a duration by seconds+  let bySeconds =+        case readEither $ integerPart <> maybe "" ('.' :) maybeFractionPart of+          Left errorMsg -> fail $ "Could not parse duration: " <> errorMsg+          Right seconds -> pure DurationBySeconds{..}++  -- Parse the unit+  asum+    [ P.char 'x' >> byBatches+    , P.char 's' >> bySeconds+    ]++{- |+Internal helper.+Pretty-print a duration.+-}+prettyDuration :: Duration -> String+prettyDuration = \case+  DurationByBatches{..} -> show batches <> "x"+  DurationBySeconds{..} -> show seconds <> "s"++--------------------------------------------------------------------------------+-- Aggregation Strategy+--------------------------------------------------------------------------------++{- |+The options for metric aggregation strategies.+-}+data AggregationStrategy+  = AggregationStrategyBool {isOn :: !Bool}+  | AggregationStrategyDuration {duration :: !Duration}+  deriving (Lift, Show)++{- |+Convert an `AggregationStrategy` to a number of seconds, if specified in seconds.+-}+toAggregationSeconds :: AggregationStrategy -> Maybe Double+toAggregationSeconds aggregationStrategy+  | AggregationStrategyDuration DurationBySeconds{..} <- aggregationStrategy = Just seconds+  | otherwise = Nothing++instance FromYAML AggregationStrategy where+  parseYAML node = YAML.withScalar "AggregationStrategy" parseYAMLScalar node+   where+    parseYAMLScalar = \case+      YAML.SBool isOn -> pure AggregationStrategyBool{..}+      YAML.SStr str+        | [(duration, "")] <- P.readP_to_S readPDuration (T.unpack str) ->+            pure AggregationStrategyDuration{..}+      _otherwise -> YAML.typeMismatch "AggregationStrategy" node++instance ToYAML AggregationStrategy where+  toYAML = \case+    AggregationStrategyBool{..} ->+      YAML.Scalar () (YAML.SBool isOn)+    AggregationStrategyDuration{..} ->+      YAML.Scalar () (YAML.SStr . T.pack . prettyDuration $ duration)++--------------------------------------------------------------------------------+-- Export Strategy+--------------------------------------------------------------------------------++{- |+The options for export strategies.+-}+data ExportStrategy+  = ExportStrategyBool {isOn :: !Bool}+  | ExportStrategyDuration {duration :: !Duration}+  deriving (Lift, Show)++{- |+Check whether or not a processor is enabled based on its export strategy.+-}+isEnabled ::+  forall processorConfig.+  (HasField "export" processorConfig (Maybe ExportStrategy)) =>+  Maybe processorConfig -> Bool+isEnabled =+  maybe False (isEnabledByExportStrategy . (.export))+ where+  isEnabledByExportStrategy :: Maybe ExportStrategy -> Bool+  isEnabledByExportStrategy = \case+    Nothing -> True+    Just ExportStrategyBool{..} -> isOn+    Just ExportStrategyDuration{..} ->+      case duration of+        DurationByBatches{..} -> batches > 0+        DurationBySeconds{..} -> seconds > 0++{- |+Convert an `ExportStrategy` to a number of seconds, if specified in seconds.+-}+toExportSeconds :: ExportStrategy -> Maybe Double+toExportSeconds exportStrategy+  | ExportStrategyDuration DurationBySeconds{..} <- exportStrategy = Just seconds+  | otherwise = Nothing++instance FromYAML ExportStrategy where+  parseYAML node = YAML.withScalar "ExportStrategy" parseYAMLScalar node+   where+    parseYAMLScalar = \case+      YAML.SBool isOn -> pure ExportStrategyBool{..}+      YAML.SStr str+        | [(duration, "")] <- P.readP_to_S readPDuration (T.unpack str) ->+            pure ExportStrategyDuration{..}+      _otherwise -> YAML.typeMismatch "ExportStrategy" node++instance ToYAML ExportStrategy where+  toYAML = \case+    ExportStrategyBool{..} ->+      YAML.Scalar () (YAML.SBool isOn)+    ExportStrategyDuration{..} ->+      YAML.Scalar () (YAML.SStr . T.pack . prettyDuration $ duration)++-------------------------------------------------------------------------------+-- Internal Helpers+-------------------------------------------------------------------------------++{- |+Internal helper.+Generic parser for log processor configuration.+-}+genericParseYAMLLogProcessorConfig ::+  String ->+  (Maybe Text -> Maybe Text -> Maybe ExportStrategy -> logProcessorConfig) ->+  YAML.Node YAML.Pos ->+  YAML.Parser logProcessorConfig+genericParseYAMLLogProcessorConfig log_ mkLogProcessorConfig =+  YAML.withMap log_ $ \m ->+    mkLogProcessorConfig+      <$> m .:? "name"+      <*> m .:? "description"+      <*> m .:? "export"++{- |+Internal helper.+Generic conversion from log processor configuration to YAML mappings.+-}+genericToYAMLLogProcessorConfig ::+  (IsLogProcessorConfig logProcessorConfig) =>+  logProcessorConfig ->+  YAML.Node ()+genericToYAMLLogProcessorConfig logProcessorConfig =+  YAML.mapping+    [ "name" .= logProcessorConfig.name+    , "description" .= logProcessorConfig.description+    , "export" .= logProcessorConfig.export+    ]++{- |+Internal helper.+Generic parser for metric processor configuration.+-}+genericParseYAMLMetricProcessorConfig ::+  String ->+  (Maybe Text -> Maybe Text -> Maybe AggregationStrategy -> Maybe ExportStrategy -> metricProcessorConfig) ->+  YAML.Node YAML.Pos ->+  YAML.Parser metricProcessorConfig+genericParseYAMLMetricProcessorConfig metric mkMetricProcessorConfig =+  YAML.withMap metric $ \m ->+    mkMetricProcessorConfig+      <$> m .:? "name"+      <*> m .:? "description"+      <*> m .:? "aggregate"+      <*> m .:? "export"++{- |+Internal helper.+Generic conversion from metric processor configuration to YAML mappings.+-}+genericToYAMLMetricProcessorConfig ::+  (IsMetricProcessorConfig metricProcessorConfig) =>+  metricProcessorConfig ->+  YAML.Node ()+genericToYAMLMetricProcessorConfig metricProcessorConfig =+  YAML.mapping+    [ "name" .= metricProcessorConfig.name+    , "description" .= metricProcessorConfig.description+    , "aggregate" .= metricProcessorConfig.aggregate+    , "export" .= metricProcessorConfig.export+    ]++{- |+Internal helper.+Generic parser for trace processor configuration.+-}+genericParseYAMLTraceProcessorConfig ::+  String ->+  (Maybe Text -> Maybe Text -> Maybe ExportStrategy -> traceProcessorConfig) ->+  YAML.Node YAML.Pos ->+  YAML.Parser traceProcessorConfig+genericParseYAMLTraceProcessorConfig trace mkTraceProcessorConfig =+  YAML.withMap trace $ \m ->+    mkTraceProcessorConfig+      <$> m .:? "name"+      <*> m .:? "description"+      <*> m .:? "export"++{- |+Internal helper.+Generic conversion from trace processor configuration to YAML mappings.+-}+genericToYAMLTraceProcessorConfig ::+  (IsTraceProcessorConfig traceProcessorConfig) =>+  traceProcessorConfig ->+  YAML.Node ()+genericToYAMLTraceProcessorConfig traceProcessorConfig =+  YAML.mapping+    [ "name" .= traceProcessorConfig.name+    , "description" .= traceProcessorConfig.description+    , "export" .= traceProcessorConfig.export+    ]++{- |+Internal helper.+Generic parser for processor configuration.+-}+genericParseYAMLProfilerProcessorConfig ::+  String ->+  (Maybe Text -> Maybe Text -> Maybe ExportStrategy -> profilerConfig) ->+  YAML.Node YAML.Pos ->+  YAML.Parser profilerConfig+genericParseYAMLProfilerProcessorConfig trace mkProfilerConfig =+  YAML.withMap trace $ \m ->+    mkProfilerConfig+      <$> m .:? "name"+      <*> m .:? "description"+      <*> m .:? "export"++{- |+Internal helper.+Generic parser for metric configuration.+-}+genericToYAMLProfilerProcessorConfig ::+  (IsTraceProcessorConfig profilerConfig) =>+  profilerConfig ->+  YAML.Node ()+genericToYAMLProfilerProcessorConfig profilerConfig =+  YAML.mapping+    [ "name" .= profilerConfig.name+    , "description" .= profilerConfig.description+    , "export" .= profilerConfig.export+    ]
+ src-lib/GHC/Eventlog/Live/Logger.hs view
@@ -0,0 +1,450 @@+{-# LANGUAGE OverloadedLists #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live..Logger+Description : Logging functions.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Logger (+  Logger,+  Scoped (..),+  InternalTelemetry (..),+  InternalMetric (..),+  ExportResult (..),+  withScope,+  logMetric,+  logTick,+  logTrace,+  logDebug,+  logInfo,+  logWarn,+  logError,+  logFatal,+  logException,+  filterBySeverity,+  stderrLogger,+  mkStderrLogger,+  handleLogger,+  chanLogger,+  chanSource,+  lossyChanSource,+) where++import Colog.Core.Action (cfilter, cmap, (<&))+import Colog.Core.Action qualified as CCA (LogAction (..))+import Control.Concurrent (forkIO)+import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)+import Control.Concurrent.LossyChan qualified as LC+import Control.Exception (Exception (..), bracket_)+import Control.Monad (forever)+import Control.Monad.IO.Class (MonadIO (..))+import Data.Functor.Const (Const (..))+import Data.Functor.Identity (Identity (..))+import Data.Int (Int64)+import Data.Ix (Ix (..))+import Data.Machine (SourceT, repeatedly, yield)+import Data.Maybe (isJust)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO qualified as TIO+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TLB+import GHC.Eventlog.Live.Machine.Core (Tick (..))+import GHC.Eventlog.Live.Machine.WithStartTime (TimeUnixNano)+import GHC.Eventlog.Live.Types.Attribute (AttrValue (..), (~=))+import GHC.Eventlog.Live.Types.Attribute qualified as A+import GHC.Eventlog.Live.Types.Logs (LogRecord (..))+import GHC.Eventlog.Live.Types.Logs qualified as LogRecord+import GHC.Eventlog.Live.Types.Metrics (Metric (..))+import GHC.Eventlog.Live.Types.Metrics qualified as Metric+import GHC.Eventlog.Live.Types.Severity (Severity (..), toSeverityString)+import GHC.IsList (IsList (..))+import GHC.Stack (CallStack, callStack, prettyCallStack)+import GHC.Stack.Types (HasCallStack)+import System.Clock (Clock (..), TimeSpec (..), getTime)+import System.Console.ANSI (Color (..), ColorIntensity (..), ConsoleLayer (..), SGR (..), hNowSupportsANSI, hSetSGR)+import System.Exit (exitFailure)+import System.IO qualified as IO++newtype Logger m = Logger {unLogger :: CCA.LogAction m (Tick (Scoped InternalTelemetry))}+  deriving newtype (Semigroup, Monoid)++{- |+The type of scoped data.+-}+data Scoped a = Scoped {scope :: ![Text], unScope :: !a}+  deriving stock (Functor, Foldable, Traversable)++{- |+Construct a value without any scope.+-}+noScope :: a -> Scoped a+noScope = Scoped []++{- |+The type of internal telemetry data.+-}+data InternalTelemetry+  = InternalTelemetry'LogRecord !LogRecord+  | forall a. InternalTelemetry'Metric !(InternalMetric a) !(Metric a)++{- |+Tags for the known internal metrics.+-}+data InternalMetric a where+  EventCount :: InternalMetric Word+  ExportLogs :: InternalMetric ExportResult+  ExportMetrics :: InternalMetric ExportResult+  ExportSpans :: InternalMetric ExportResult+  ExportSamples :: InternalMetric ExportResult++{- |+The result of an export.+-}+data ExportResult = ExportResult+  { exported :: !Int64+  , rejected :: !Int64+  }+  deriving (Show)++instance Semigroup ExportResult where+  r1 <> r2 = ExportResult{exported = r1.exported + r2.exported, rejected = r1.rejected + r2.rejected}++instance Monoid ExportResult where+  mempty = ExportResult{exported = 0, rejected = 0}++{- |+Use a `Logger` to log a message with a severity.+-}+writeLog :: (HasCallStack) => Logger m -> Severity -> Text -> m ()+writeLog logger severity message =+  writeLogRecord+    LogRecord+      { value = message+      , maybeSeverity = Just severity+      , maybeTimeUnixNano = Nothing+      , attrs = maybe mempty (\cs -> ["call-stack" ~= prettyCallStack cs]) (cleanCallStack callStack)+      }+ where+  writeLogRecord = (logger.unLogger <&) . Item . noScope . InternalTelemetry'LogRecord++{- |+Use a `Logger` at a particular scope.+-}+withScope :: Text -> Logger m -> (Logger m -> m a) -> m a+withScope scope logger action = action (addScope scope logger)++{- |+Create a `Logger` for a particular scope.+-}+addScope :: Text -> Logger m -> Logger m+addScope scope (Logger logger) = Logger (cmap (fmap (\(Scoped scopes a) -> Scoped (scope : scopes) a)) logger)++{- |+Use a `Logger` to log an internal metric.+-}+logMetric :: Logger m -> InternalMetric a -> a -> m ()+logMetric logger internalMetric value =+  writeMetric+    Metric+      { value = value+      , maybeTimeUnixNano = Nothing+      , maybeStartTimeUnixNano = Nothing+      , attrs = mempty+      }+ where+  writeMetric = (logger.unLogger <&) . Item . noScope . InternalTelemetry'Metric internalMetric++{- |+Internal helper.++Remove all log functions from the `CallStack`.+-}+cleanCallStack :: CallStack -> Maybe CallStack+cleanCallStack =+  toMaybeCallStack . dropWhile ((`elem` logFunctions) . fst) . toList+ where+  toMaybeCallStack locations = if null locations then Nothing else Just (fromList locations)+  logFunctions :: [String]+  logFunctions = ["writeLog", "logTrace", "logDebug", "logInfo", "logWarn", "logError", "logFatal", "logException"]++{- |+Use a `Logger` to log a `Tick`.+-}+logTick :: (Applicative m) => Logger m -> Tick x -> m ()+logTick logger = \case Tick -> logger.unLogger <& Tick; Item{} -> pure ()++{- |+Use a `Logger` to log a message with `TRACE` severity.+-}+logTrace :: (HasCallStack) => Logger m -> Text -> m ()+logTrace = flip writeLog TRACE++{- |+Use a `Logger` to log a message with `DEBUG` severity.+-}+logDebug :: (HasCallStack) => Logger m -> Text -> m ()+logDebug = flip writeLog DEBUG++{- |+Use a `Logger` to log a message with `INFO` severity.+-}+logInfo :: (HasCallStack) => Logger m -> Text -> m ()+logInfo = flip writeLog INFO++{- |+Use a `Logger` to log a message with `WARN` severity.+-}+logWarn :: (HasCallStack) => Logger m -> Text -> m ()+logWarn = flip writeLog WARN++{- |+Use a `Logger` to log a message with `ERROR` severity.+-}+logError :: (HasCallStack) => Logger m -> Text -> m ()+logError = flip writeLog ERROR++{- |+Use a `Logger` to log a message with `FATAL` severity and exit.+-}+logFatal :: (HasCallStack) => Logger IO -> Text -> IO x+logFatal logger message = writeLog logger FATAL message >> exitFailure++{- |+Use a `Logger` to log an exception.+-}+logException :: (Exception e) => Logger m -> e -> m ()+logException logger e =+  logError logger (T.pack $ displayException e)++{- |+A `Logger` that writes each `LogRecord` to a `IO.stderr` and ignores all other telemetry data.++__TODO:__ Support the remaining telemetry data.+-}+stderrLogger :: Logger IO+stderrLogger = handleLogger IO.stderr++{- |+A `Logger` that writes each `LogRecord` to a `IO.stderr` and ignores all other telemetry data.+-}+mkStderrLogger :: IO (Logger IO)+mkStderrLogger = do+  chan <- newChan++  -- Create a thread that prints log records from the chan+  _threadId <- forkIO $ forever $ do+    scopedLogRecord <- readChan chan+    withSeverityColor scopedLogRecord.unScope.maybeSeverity IO.stderr $ \handleWithColor ->+      TIO.hPutStrLn handleWithColor $ formatScopedLogRecord scopedLogRecord+    IO.hFlush IO.stderr++  -- Create a log action that writes log records to the chan+  pure . Logger . CCA.LogAction $ \case+    Tick -> pure ()+    Item (Scoped scope (toLogRecord -> logRecord)) -> liftIO $ do+      writeChan chan (Scoped scope logRecord)++{- |+A `Logger` that writes each `LogRecord` to a `IO.Handle` and ignores all other telemetry data.++__TODO:__ Support the remaining telemetry data.+-}+handleLogger ::+  IO.Handle ->+  Logger IO+handleLogger handle = Logger . CCA.LogAction $ \case+  Tick ->+    pure ()+  Item (Scoped scope (toLogRecord -> logRecord)) -> liftIO $ do+    withSeverityColor logRecord.maybeSeverity handle $ \handleWithColor ->+      TIO.hPutStrLn handleWithColor $ formatScopedLogRecord (Scoped scope logRecord)+    IO.hFlush handle++{- |+Convert `InternalTelemetry` to a `LogRecord` for the `handleLogger`.+-}+toLogRecord :: InternalTelemetry -> LogRecord+toLogRecord = \case+  InternalTelemetry'LogRecord logRecord -> logRecord+  InternalTelemetry'Metric internalMetric metric -> toLogRecord'Metric metric internalMetric+ where+  toLogRecord'Metric :: Metric a -> InternalMetric a -> LogRecord+  toLogRecord'Metric metric = \case+    EventCount ->+      logRecord DEBUG $ "Received " <> T.show metric.value <> " events."+    ExportLogs+      | ExportResult{..} <- metric.value ->+          if rejected > 0+            then logRecord ERROR $ "Exported " <> T.show exported <> " logs (" <> T.show rejected <> " rejected)."+            else logRecord DEBUG $ "Exported " <> T.show exported <> " logs."+    ExportMetrics+      | ExportResult{..} <- metric.value ->+          if rejected > 0+            then logRecord ERROR $ "Exported " <> T.show exported <> " metrics (" <> T.show rejected <> " rejected)."+            else logRecord DEBUG $ "Exported " <> T.show exported <> " metrics."+    ExportSpans+      | ExportResult{..} <- metric.value ->+          if rejected > 0+            then logRecord ERROR $ "Exported " <> T.show exported <> " spans (" <> T.show rejected <> " rejected)."+            else logRecord DEBUG $ "Exported " <> T.show exported <> " spans."+    ExportSamples+      | ExportResult{..} <- metric.value ->+          if rejected > 0+            then logRecord ERROR $ "Exported " <> T.show exported <> " samples (" <> T.show rejected <> " rejected)."+            else logRecord DEBUG $ "Exported " <> T.show exported <> " samples."+   where+    logRecord :: Severity -> Text -> LogRecord+    logRecord severity value =+      LogRecord{maybeTimeUnixNano = metric.maybeTimeUnixNano, maybeSeverity = Just severity, attrs = metric.attrs, ..}++{- |+Filter a @`Logger` m@ by a `Severity`.+-}+filterBySeverity ::+  (Applicative m) =>+  Severity ->+  Logger m ->+  Logger m+filterBySeverity severityThreshold =+  Logger . cfilter severityFilter . (.unLogger)+ where+  severityFilter = \case+    Item (Scoped _scope (InternalTelemetry'LogRecord logRecord)) ->+      maybe False (>= severityThreshold) logRecord.maybeSeverity+    _otherwise -> True++{- |+Internal helper.+Format the message appropriately for the given verbosity level and threshold.+-}+formatScopedLogRecord :: Scoped LogRecord -> Text+formatScopedLogRecord (Scoped scope logRecord) =+  TL.toStrict . TLB.toLazyText . mconcat $+    [ -- format the severity+      maybe "" (\severity -> "[" <> TLB.fromString (toSeverityString severity) <> "] ") logRecord.maybeSeverity+    , -- format the scope+      if null scope then "" else "(" <> TLB.fromText (T.intercalate "." scope) <> ") "+    , -- format the body+      TLB.fromText logRecord.value+    , -- format the call-stack, if any+      case A.lookup "call-stack" logRecord.attrs of+        Just (AttrText theCallStack)+          | maybe False (>= ERROR) logRecord.maybeSeverity ->+              "\n" <> TLB.fromText theCallStack+        _otherwise -> ""+    ]++{- |+Internal helper.+Determine the ANSI color and intensity associated with a particular `Severity`.+-}+severityColor :: Severity -> Maybe (Color, ColorIntensity)+severityColor severity+  | inRange (TRACE, TRACE4) severity = Just (Blue, Dull)+  | inRange (DEBUG, DEBUG4) severity = Just (Blue, Vivid)+  | inRange (WARN, WARN4) severity = Just (Yellow, Vivid)+  | inRange (ERROR, ERROR4) severity = Just (Red, Dull)+  | inRange (FATAL, FATAL4) severity = Just (Red, Vivid)+  | otherwise = Nothing++{- |+Internal helper.+Use a handle with the color set appropriately for the given `Severity`.+-}+withSeverityColor :: Maybe Severity -> IO.Handle -> (IO.Handle -> IO a) -> IO a+withSeverityColor maybeSeverity handle action = do+  supportsANSI <- hNowSupportsANSI handle+  if not supportsANSI+    then+      action handle+    else case severityColor =<< maybeSeverity of+      Nothing ->+        action handle+      Just (color, intensity) -> do+        let setVerbosityColor = hSetSGR handle [SetColor Foreground intensity color]+        let setDefaultColor = hSetSGR handle [SetDefaultColor Foreground]+        bracket_ setVerbosityColor setDefaultColor $ action handle++{- |+A `Logger` that writes the internal telemetry data to a channel.+-}+chanLogger :: Chan (Tick (Scoped InternalTelemetry)) -> Logger IO+chanLogger chan =+  Logger . CCA.LogAction $ \x -> do+    traverse (traverse addTimeUnixNano) x >>= \x' ->+      writeChan chan x'++{- |+A `Data.Machine.Souce` that reads the data from a channel.+-}+chanSource :: (MonadIO m) => Chan a -> SourceT m a+chanSource chan = repeatedly $ do+  yield =<< liftIO (readChan chan)++{- |+A `Data.Machine.Souce` that reads the data from a channel.+-}+lossyChanSource :: (MonadIO m) => LC.OutChan a -> SourceT m a+lossyChanSource chan = repeatedly $ do+  yield =<< liftIO (LC.receive chan)++{- |+Add the current Unix timestamp in nanoseconds to telemetry data.+-}+addTimeUnixNano :: InternalTelemetry -> IO InternalTelemetry+addTimeUnixNano i+  | has maybeTimeUnixNano'InternalTelemetry i = pure i+  | otherwise = set maybeTimeUnixNano'InternalTelemetry i . Just <$> getTimeUnixNano++{- |+Get the current Unix time in nanoseconds.++__Warning:__ This will start overflowing in the year 2554.+-}+getTimeUnixNano :: IO TimeUnixNano+getTimeUnixNano = toNanos <$> getTime Realtime+ where+  -- NOTE: This will overflow if @t.sec > (2^64 - 1) `div` 10^9@,+  --       which means you're running this code in the year 2554.+  --       What's that like?+  toNanos :: TimeSpec -> TimeUnixNano+  toNanos t = 1_000_000_000 * fromIntegral t.sec + fromIntegral t.nsec++--------------------------------------------------------------------------------+-- Lenses for InternalTelemetry+--+-- NOTE: If you are tempted to export these, just replace them with lens-family2+--------------------------------------------------------------------------------++type Lens s a = forall f. (Functor f) => (a -> f a) -> s -> f s++get :: Lens s a -> s -> a+get l s = getConst $ l Const s+{-# INLINE get #-}++has :: Lens s (Maybe a) -> s -> Bool+has l s = isJust (get l s)+{-# INLINE has #-}++set :: Lens s a -> s -> a -> s+set l s a = runIdentity $ l (const $ Identity a) s+{-# INLINE set #-}++maybeTimeUnixNano'InternalTelemetry :: Lens InternalTelemetry (Maybe TimeUnixNano)+maybeTimeUnixNano'InternalTelemetry f = \case+  InternalTelemetry'LogRecord l -> InternalTelemetry'LogRecord <$> maybeTimeUnixNano'LogRecord f l+  InternalTelemetry'Metric t m -> InternalTelemetry'Metric t <$> maybeTimeUnixNano'Metric f m+{-# INLINE maybeTimeUnixNano'InternalTelemetry #-}++maybeTimeUnixNano'LogRecord :: Lens LogRecord (Maybe TimeUnixNano)+maybeTimeUnixNano'LogRecord f l =+  fmap (\x -> l{LogRecord.maybeTimeUnixNano = x}) (f l.maybeTimeUnixNano)+{-# INLINE maybeTimeUnixNano'LogRecord #-}++maybeTimeUnixNano'Metric :: Lens (Metric a) (Maybe TimeUnixNano)+maybeTimeUnixNano'Metric f m =+  fmap (\x -> m{Metric.maybeTimeUnixNano = x}) (f m.maybeTimeUnixNano)+{-# INLINE maybeTimeUnixNano'Metric #-}
+ src-lib/GHC/Eventlog/Live/Machine/Analysis/Capability.hs view
@@ -0,0 +1,678 @@+{-# LANGUAGE OverloadedLists #-}+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_GHC -Wno-name-shadowing #-}++{- |+Module      : GHC.Eventlog.Live.Machine+Description : Machines for processing eventlog data.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Machine.Analysis.Capability (+  -- * Capability Usage++  -- ** Productivity Metrics+  Productivity (..),+  processProductivity,++  -- ** Capability Usage Metrics+  processCapabilityUsageDuration,+  CapabilityUsageDuration (..),+  processCapabilityUsageDuration'Delta,+  processCapabilityUsageDuration'DeltaToCumulative,++  -- ** Capability Usage Spans+  CapabilityUsageSpan,+  CapabilityUser (..),+  capabilityUser,+  showCapabilityUser,+  processCapabilityUsageSpans,+  processCapabilityUsageSpans',++  -- ** GC Spans+  GCSpan (..),+  processGCSpans,+  processGCSpans',++  -- ** Mutator Spans+  MutatorSpan (..),+  asMutatorSpans,+  asMutatorSpans',+  processMutatorSpans,+  processMutatorSpans',+) where++import Control.Exception (assert)+import Control.Monad (when)+import Control.Monad.Trans.Class (MonadTrans (..))+import Data.Char (isSpace)+import Data.Coerce (coerce)+import Data.Foldable (for_)+import Data.Hashable (Hashable)+import Data.Machine (Is (..), PlanT, ProcessT, asParts, await, construct, mapping, repeatedly, yield, (~>))+import Data.Machine.Fanout (fanout)+import Data.Semigroup (Sum (..))+import Data.Text (Text)+import Data.Text qualified as T+import Data.Void (Void)+import GHC.Eventlog.Live.Logger (Logger, logWarn)+import GHC.Eventlog.Live.Machine.Analysis.Thread (ThreadState (..), ThreadStateSpan (..), processThreadStateSpans')+import GHC.Eventlog.Live.Machine.Core (deltaToCumulative, liftRouter)+import GHC.Eventlog.Live.Machine.WithStartTime (TimeUnixNano, WithStartTime (..), setWithStartTime'value, tryGetTimeUnixNano)+import GHC.Eventlog.Live.Types.Attribute (AttrValue, Attrs, IsAttrValue (..), (~=))+import GHC.Eventlog.Live.Types.Capability (CapNo (..), evCapNo)+import GHC.Eventlog.Live.Types.Traces (duration)+import GHC.Generics (Generic)+import GHC.RTS.Events (Event (..), EventInfo, ThreadId)+import GHC.RTS.Events qualified as E+import GHC.Records (HasField (..))+import Text.Printf (printf)++-------------------------------------------------------------------------------+-- Productivity Metrics++{- |+The productivity measure.++This holds the cumulative elapsed time for both GC and mutator threads.+-}+data Productivity = Productivity+  { gc :: !TimeUnixNano+  , mutator :: !TimeUnixNano+  , maybeTimeUnixNano :: !(Maybe TimeUnixNano)+  , maybeStartTimeUnixNano :: !(Maybe TimeUnixNano)+  , capNo :: CapNo+  }++instance HasField "value" Productivity Double where+  getField :: Productivity -> Double+  getField Productivity{..} =+    realToFrac mutator / realToFrac (mutator + gc)++instance HasField "attrs" Productivity Attrs where+  getField :: Productivity -> Attrs+  getField Productivity{..} =+    ["capNo" ~= capNo]++instance Semigroup Productivity where+  (<>) :: Productivity -> Productivity -> Productivity+  x <> y =+    Productivity+      { gc = max x.gc y.gc+      , mutator = max x.mutator y.mutator+      , maybeTimeUnixNano = forceMaybe $ x.maybeTimeUnixNano `max` y.maybeTimeUnixNano+      , maybeStartTimeUnixNano = forceMaybe $ x.maybeStartTimeUnixNano `max` y.maybeStartTimeUnixNano+      , capNo = assert (x.capNo == y.capNo) x.capNo+      }+   where+    -- NOTE: Without this function, `max` creates a space leak.+    forceMaybe :: Maybe a -> Maybe a+    forceMaybe Nothing = Nothing+    forceMaybe (Just a) = a `seq` Just a++{- |+Convert a t`CapabilityUsageDuration` to a partial t`Productivity` that only+represents the category corresponding to this t`CapabilityUsageDuration`'s+usage category (GC or mutator).+-}+toProductivity :: CapabilityUsageDuration TimeUnixNano -> Maybe Productivity+toProductivity CapabilityUsageDuration{..} = do+  usage >>= \case+    GC -> pure Productivity{gc = value, mutator = 0, ..}+    Mutator{} -> pure Productivity{gc = 0, mutator = value, ..}++{- |+This machine processes t`CapabilityUsageDuration` with the cumulative elapsed+time for each category and produces metrics that contain productivity.+-}+processProductivity ::+  forall m.+  (Monad m) =>+  ProcessT m (CapabilityUsageDuration TimeUnixNano) Productivity+processProductivity =+  liftRouter measure spawn+ where+  -- This measure splits the input by capability.+  measure :: CapabilityUsageDuration TimeUnixNano -> Maybe CapNo+  measure cud = Just cud.capNo++  spawn :: CapNo -> ProcessT m (CapabilityUsageDuration TimeUnixNano) Productivity+  spawn _capNo = construct $ go Nothing+   where+    go ::+      Maybe Productivity ->+      PlanT (Is (CapabilityUsageDuration TimeUnixNano)) Productivity m Void+    go maybeProductivity =+      await >>= \case+        cud+          -- If this usage duration yields a productivity update,+          -- yield an updated productivity.+          | productivityUpdate@Just{} <- toProductivity cud -> do+              let maybeProductivity' = maybeProductivity <> productivityUpdate+              for_ maybeProductivity' yield+              go maybeProductivity'+          -- Otherwise, ignore it.+          | otherwise ->+              go maybeProductivity++-------------------------------------------------------------------------------+-- Capability Usage Duration - Cumulative++{- |+This machine processes t`CapabilityUsageSpan` data and produces metrics+that contain the cumulative elapsed time for each category (idle, GC, mutator).+-}+processCapabilityUsageDuration ::+  forall m.+  (Monad m) =>+  ProcessT m (WithStartTime CapabilityUsageSpan) (CapabilityUsageDuration TimeUnixNano)+processCapabilityUsageDuration =+  processCapabilityUsageDuration'Delta+    ~> processCapabilityUsageDuration'DeltaToCumulative++-------------------------------------------------------------------------------+-- Capability Usage Duration++{- |+The delta capability usage duration.+-}+data CapabilityUsageDuration a+  = CapabilityUsageDuration+  { value :: !a+  , maybeTimeUnixNano :: !(Maybe TimeUnixNano)+  , maybeStartTimeUnixNano :: !(Maybe TimeUnixNano)+  , capNo :: !CapNo+  , usage :: !(Maybe CapabilityUser)+  {- ^+  If the capability is actively used, this value is `Just` a `CapabilityUser`.+  If the capability is idle, this value is `Nothing`.+  -}+  }+  deriving (Functor, Foldable, Traversable)++instance HasField "attrs" (CapabilityUsageDuration a) Attrs where+  getField :: CapabilityUsageDuration a -> Attrs+  getField CapabilityUsageDuration{..} =+    [ "capNo" ~= capNo+    , "usage" ~= maybe "Idle" showCapabilityUser usage+    , "user" ~= usage+    ]++{- |+This machine processes t`CapabilityUsageDuration` with the delta of elapsed+time for each category and produces metrics that contain the cumulative elapsed+time for each category (idle, GC, mutator).+-}+processCapabilityUsageDuration'DeltaToCumulative ::+  forall m.+  (Monad m) =>+  ProcessT m (CapabilityUsageDuration TimeUnixNano) (CapabilityUsageDuration TimeUnixNano)+processCapabilityUsageDuration'DeltaToCumulative =+  liftRouter measure . const $+    mapping coerce+      ~> deltaToCumulative @m @CapabilityUsageDuration @(Sum TimeUnixNano)+      ~> mapping coerce+ where+  -- This measure splits the input by capability _and_ usage category:+  --+  -- 1. The `Int` represents the capability.+  -- 2. The `Maybe CapabilityUser` represents the usage category.+  --+  measure :: CapabilityUsageDuration TimeUnixNano -> Maybe (CapNo, Maybe CapabilityUser)+  measure cud = Just (cud.capNo, cud.usage)++{- |+This machine processes t`CapabilityUsageSpan` spans and produces metrics that+contain the duration and category of each such span and each idle period in+between.+-}+processCapabilityUsageDuration'Delta ::+  forall m.+  (Monad m) =>+  ProcessT m (WithStartTime CapabilityUsageSpan) (CapabilityUsageDuration TimeUnixNano)+processCapabilityUsageDuration'Delta =+  liftRouter measure spawn+ where+  measure :: WithStartTime CapabilityUsageSpan -> Maybe CapNo+  measure = Just . (.value.capNo)++  spawn :: CapNo -> ProcessT m (WithStartTime CapabilityUsageSpan) (CapabilityUsageDuration TimeUnixNano)+  spawn capNo = construct $ go Nothing+   where+    go ::+      Maybe CapabilityUsageSpan ->+      PlanT (Is (WithStartTime CapabilityUsageSpan)) (CapabilityUsageDuration TimeUnixNano) m Void+    go mi =+      await >>= \j -> do+        -- If there is a previous span, and...+        for_ mi $ \i ->+          -- ...the end time of the previous span precedes the start time of the current span, then...+          when (i.endTimeUnixNano < j.value.startTimeUnixNano) $+            -- ...yield an idle duration metric.+            yield+              CapabilityUsageDuration+                { value = j.value.startTimeUnixNano - i.endTimeUnixNano+                , maybeTimeUnixNano = Just i.endTimeUnixNano+                , maybeStartTimeUnixNano = j.maybeStartTimeUnixNano+                , capNo = capNo+                , usage = Nothing -- Idle+                }+        -- Yield a duration metric for the current span.+        yield+          CapabilityUsageDuration+            { value = duration j.value+            , maybeTimeUnixNano = Just j.value.startTimeUnixNano+            , maybeStartTimeUnixNano = j.maybeStartTimeUnixNano+            , capNo = capNo+            , usage = Just $! capabilityUser j.value+            }+        go (Just j.value)++{- |+The type of process using a capability,+which is either a mutator thread or garbage collection.+-}+data CapabilityUser+  = GC+  | Mutator {thread :: !ThreadId}+  deriving stock (Eq, Generic)++instance Hashable CapabilityUser++instance Show CapabilityUser where+  show :: CapabilityUser -> String+  show = \case+    GC -> "GC"+    Mutator{thread} -> show thread++instance IsAttrValue CapabilityUser where+  toAttrValue :: CapabilityUser -> AttrValue+  toAttrValue = toAttrValue . show+  {-# INLINE toAttrValue #-}++{- |+Get the t`CapabilityUser` associated with a t`CapabilityUsageSpan`.+-}+capabilityUser :: CapabilityUsageSpan -> CapabilityUser+capabilityUser = either (const GC) (Mutator . (.thread))++{- |+Show the category of a `CapabilityUser` as either @"GC"@ or @"Mutator"@.+-}+showCapabilityUser :: CapabilityUser -> Text+showCapabilityUser = \case+  GC{} -> "GC"+  Mutator{} -> "Mutator"++-------------------------------------------------------------------------------+-- Capability Usage Spans++{- |+A t`CapabilityUsageSpan` is either a t`GCSpan` or a t`MutatorSpan`.+-}+type CapabilityUsageSpan = Either GCSpan MutatorSpan++instance HasField "startTimeUnixNano" CapabilityUsageSpan TimeUnixNano where+  getField :: CapabilityUsageSpan -> TimeUnixNano+  getField = either (.startTimeUnixNano) (.startTimeUnixNano)++instance HasField "endTimeUnixNano" CapabilityUsageSpan TimeUnixNano where+  getField :: CapabilityUsageSpan -> TimeUnixNano+  getField = either (.endTimeUnixNano) (.endTimeUnixNano)++instance HasField "capNo" CapabilityUsageSpan CapNo where+  getField :: CapabilityUsageSpan -> CapNo+  getField = either (.capNo) (.capNo)++instance HasField "traceId" CapabilityUsageSpan CapNo where+  getField :: CapabilityUsageSpan -> CapNo+  getField = either (.traceId) (.traceId)++instance HasField "attrs" CapabilityUsageSpan Attrs where+  getField :: CapabilityUsageSpan -> Attrs+  getField s =+    ["usage" ~= showCapabilityUser (capabilityUser s)]+      <> either (.attrs) (.attrs) s++{-# SPECIALIZE duration :: CapabilityUsageSpan -> TimeUnixNano #-}++{- |+This machine runs `processGCSpans` and `processMutatorSpans` in parallel and+combines their output.++This is effectively a fanout of `processGCSpans` and `processMutatorSpans`, the+latter of which runs `processThreadStateSpans` internally. If you are running+`processThreadStateSpans` as well, then using `asMutatorSpans` and constructing+the fanout yourself is more efficient.+-}+processCapabilityUsageSpans ::+  forall m.+  (Monad m) =>+  Logger m ->+  ProcessT m (WithStartTime Event) (WithStartTime CapabilityUsageSpan)+processCapabilityUsageSpans logger =+  processCapabilityUsageSpans' tryGetTimeUnixNano (.value) setWithStartTime'value setWithStartTime'value logger+    ~> mapping (either (fmap Left) (fmap Right))++{- |+Generalised version of `processCapabilityUsageSpans` that can be adapted to+work on arbitrary types using a getter and a pair of lenses.+-}+processCapabilityUsageSpans' ::+  forall m s t1 t2.+  (Monad m) =>+  (s -> Maybe TimeUnixNano) ->+  (s -> Event) ->+  (s -> GCSpan -> t1) ->+  (s -> MutatorSpan -> t2) ->+  Logger m ->+  ProcessT m s (Either t1 t2)+processCapabilityUsageSpans' timeUnixNano getEvent setGCSpan setMutatorSpan logger =+  -- NOTE:+  -- Combining this fanout with an `Either` is risky, because it+  -- has the potential to lose information if both `processGCSpans`+  -- and `processMutatorSpans` yield a value for the same input.+  -- However, this shouldn't ever happen, since the two processors+  -- process disjoint sets of events.+  fanout+    [ processGCSpans' timeUnixNano getEvent setGCSpan logger+        ~> mapping Left+    , processMutatorSpans' timeUnixNano getEvent setMutatorSpan logger+        ~> mapping Right+    ]++-------------------------------------------------------------------------------+-- GC spans++{- |+A t`GCSpan` represents a segment of time during which the specified capability+ran GC.+-}+data GCSpan = GCSpan+  { capNo :: !CapNo+  , startTimeUnixNano :: !TimeUnixNano+  , endTimeUnixNano :: !TimeUnixNano+  }+  deriving (Show)++instance HasField "traceId" GCSpan CapNo where+  getField :: GCSpan -> CapNo+  getField = (.capNo)++instance HasField "attrs" GCSpan Attrs where+  getField :: GCSpan -> Attrs+  getField s =+    [ "capNo" ~= s.capNo+    ]++{-# SPECIALIZE duration :: GCSpan -> TimeUnixNano #-}++{- |+This machine processes `E.StartGC` and `E.EndGC` events to produce t`GCSpan`+values that represent the segments of time a capability spent in GC.++This processor uses the following finite-state automaton:++@+      ┌─(EndGC)───┐+      │           ↓+    ┌→[   Idle    ]─┐+    │               │+(EndGC)         (StartGC)+    │               │+    └─[    GC     ]←┘+      ↑           │+      └─(StartGC)─┘+@++The transition from @GC@ to @Idle@ yields a GC span.+-}+processGCSpans ::+  forall m.+  (Monad m) =>+  Logger m ->+  ProcessT m (WithStartTime Event) (WithStartTime GCSpan)+processGCSpans =+  processGCSpans' tryGetTimeUnixNano (.value) setWithStartTime'value++{- |+Generalised version of `processGCSpans` that can be adapted to work on+arbitrary types using a getter and a lens.+-}+processGCSpans' ::+  forall m s t.+  (Monad m) =>+  (s -> Maybe TimeUnixNano) ->+  (s -> Event) ->+  (s -> GCSpan -> t) ->+  Logger m ->+  ProcessT m s t+processGCSpans' timeUnixNano getEvent setGCSpan logger =+  liftRouter measure spawn+ where+  getEventTime = (.evTime) . getEvent+  getEventInfo = (.evSpec) . getEvent+  getEventCapNo = evCapNo . getEvent++  measure :: s -> Maybe CapNo+  measure i+    | accept (getEventInfo i) = getEventCapNo i+    | otherwise = Nothing+   where+    accept E.StartGC{} = True+    accept E.EndGC{} = True+    accept _ = False++  -- TODO: Rewrite using `MealyT`+  spawn :: CapNo -> ProcessT m s t+  spawn capNo = construct $ go Nothing+   where+    -- The "mi" variable tracks the previous event for this capability, which+    -- is either `Nothing` or `Just` a `StartGC` or a `EndGC` event.+    go :: Maybe s -> PlanT (Is s) t m Void+    go mi =+      -- We start by awaiting the next event "j"...+      await >>= \j -> case getEventInfo j of+        -- If the next event is a `RunThread` event, and...+        E.StartGC{} -> case mi of+          Just i+            -- If the previous event was a `StartGC` event, then...+            | E.StartGC{} <- getEventInfo i ->+                -- ...continue with the oldest event.+                go (Just $ minBy getEventTime i j)+            -- If the previous event was a `EndGC` event, then...+            | E.EndGC{} <- getEventInfo i ->+                -- ...continue with the current event.+                go (Just j)+            -- If the previous event was any other event, then...+            | otherwise -> do+                -- ...emit a warning, and...+                let msg =+                      T.pack $+                        printf+                          "Capability %d: Unsupported trace %s --> %s"+                          capNo.value+                          (showEventInfo (getEventInfo i))+                          (showEventInfo (getEventInfo j))+                lift $ logWarn logger $ msg+                -- ...continue with the previous event.+                go (Just i)+          -- If there was no previous event, then...+          Nothing ->+            -- ...continue with the current event.+            go (Just j)+        -- If the next event is a `StopThread` event...+        E.EndGC{} -> case mi of+          Just i+            -- If the previous event was a `StartGC` event, then...+            | E.StartGC{} <- getEventInfo i+            , Just startTimeUnixNano <- timeUnixNano i+            , Just endTimeUnixNano <- timeUnixNano j -> do+                -- ...yield a GC span, and...+                yield . setGCSpan j $ GCSpan{..}+                -- ...continue with the current event.+                go (Just j)+            -- If the previous event was a `EndGC` event, then...+            | E.EndGC{} <- getEventInfo i ->+                -- ...continue with the oldest event.+                go (Just $ minBy getEventTime i j)+          -- If there was no previous event or it was any other event, then...+          _otherwise -> do+            -- ...emit a warning, and...+            let msg =+                  T.pack $+                    printf+                      "Capability %d: Unsupported trace %s --> %s"+                      capNo.value+                      (maybe "?" (showEventInfo . getEventInfo) mi)+                      (showEventInfo (getEventInfo j))+            lift $ logWarn logger $ msg+            -- ...continue with the previous event.+            go mi+        -- If the next event is any other event, ignore it.+        _otherwise -> go mi++-------------------------------------------------------------------------------+-- Mutator spans++{- |+A t`MutatorSpan` represents a segment of time during which the specified+capability ran the specified mutator thread.+-}+data MutatorSpan = MutatorSpan+  { capNo :: !CapNo+  , thread :: !ThreadId+  , startTimeUnixNano :: !TimeUnixNano+  , endTimeUnixNano :: !TimeUnixNano+  }+  deriving (Show)++instance HasField "traceId" MutatorSpan CapNo where+  getField :: MutatorSpan -> CapNo+  getField = (.capNo)++instance HasField "attrs" MutatorSpan Attrs where+  getField :: MutatorSpan -> Attrs+  getField s =+    [ "capNo" ~= s.capNo+    , "thread" ~= s.thread+    ]++{-# SPECIALIZE duration :: MutatorSpan -> TimeUnixNano #-}++{- |+This machine processes `E.RunThread` and `E.StopThread` events to produce+t`MutatorSpan` values that represent the segments of time a capability spent+executating a mutator.++This processor uses the following finite-state automaton:++@+      ┌─(StopThread[X])─┐+      │                 ↓+    ┌→[      Idle       ]─┐+    │                     │+(StopThread[X])       (RunThread[X])+    │                     │+    └─[   Mutator[X]    ]←┘+      ↑                 │+      └─(RunThread[X])──┘+@++The transition from @Mutator[X]@ to @Idle@ yields a t`MutatorSpan`.+While in the @Mutator[X]@ state, any @RunThread[Y]@ or @StopThread[Y]@ events result in an error.+Furthermore, when a @StopThread[X]@ event with the @ThreadFinished@ status is processed,+the thread @X@ is added to a set of finished threads,+and any further @RunThread[X]@ events for that thread are ignored.+This is done because the GHC RTS frequently emits a @RunThread[X]@ event+immediately after a @StopThread[X]@ event with the @ThreadFinished@ status.++This runs `processThreadStateSpans` internally. If you are also running+`processThreadStateSpans`, then post-composing it with `asMutatorSpans`+is more efficient.+-}+processMutatorSpans ::+  forall m.+  (Monad m) =>+  Logger m ->+  ProcessT m (WithStartTime Event) (WithStartTime MutatorSpan)+processMutatorSpans =+  processMutatorSpans' tryGetTimeUnixNano (.value) setWithStartTime'value++{- |+Generalised version of `processMutatorSpans` that can be adapted to work on+arbitrary types using a getter and a lens.+-}+processMutatorSpans' ::+  forall m s t.+  (Monad m) =>+  (s -> Maybe TimeUnixNano) ->+  (s -> Event) ->+  (s -> MutatorSpan -> t) ->+  Logger m ->+  ProcessT m s t+processMutatorSpans' timeUnixNano getEvent setMutatorSpan logger =+  processThreadStateSpans' timeUnixNano getEvent setThreadStateSpan logger ~> asParts+ where+  setThreadStateSpan :: s -> ThreadStateSpan -> Maybe t+  setThreadStateSpan s threadStateSpan =+    setMutatorSpan s <$> threadStateSpanToMutatorSpan threadStateSpan++{- |+This machine converts any `Running` t`ThreadStateSpan` to a t`MutatorSpan`.+-}+asMutatorSpans ::+  forall m.+  (Monad m) =>+  ProcessT m ThreadStateSpan MutatorSpan+asMutatorSpans = asMutatorSpans' id (const id)++{- |+Generalised version of `asMutatorSpans` that can be adapted to work on+arbitrary types using a getter and a lens.+-}+asMutatorSpans' ::+  forall m s t.+  (Monad m) =>+  (s -> ThreadStateSpan) ->+  (s -> MutatorSpan -> t) ->+  ProcessT m s t+asMutatorSpans' getThreadStateSpan setMutatorSpan = repeatedly go+ where+  go =+    await >>= \s -> do+      let threadStateSpan = getThreadStateSpan s+      let maybeMutatorSpan = threadStateSpanToMutatorSpan threadStateSpan+      for_ maybeMutatorSpan $ yield . setMutatorSpan s++{- |+Convert the `Running` t`ThreadStateSpan` to `Just` a t`MutatorSpan`.+-}+threadStateSpanToMutatorSpan :: ThreadStateSpan -> Maybe MutatorSpan+threadStateSpanToMutatorSpan ThreadStateSpan{..} =+  case threadState of+    Running{..} -> Just MutatorSpan{..}+    _otherwise -> Nothing++-------------------------------------------------------------------------------+-- Internal Helpers+-------------------------------------------------------------------------------++{- |+Internal helper.+Show `EventInfo` in a condensed format suitable for logging.+-}+showEventInfo :: EventInfo -> String+showEventInfo = \case+  E.RunThread{thread} -> printf "RunThread{%d}" thread+  E.StopThread{thread, status} -> printf "StopThread{%d,%s}" thread (E.showThreadStopStatus status)+  E.MigrateThread{thread} -> printf "MigrateThread{%d}" thread+  E.StartGC{} -> "StartGC"+  E.EndGC{} -> "EndGC"+  evSpec -> takeWhile (not . isSpace) . show $ evSpec++{- |+Internal helper. Return the minimal value by some projection.+-}+minBy :: (Ord b) => (a -> b) -> a -> a -> a+minBy f x y = if f x < f y then x else y
+ src-lib/GHC/Eventlog/Live/Machine/Analysis/Heap.hs view
@@ -0,0 +1,432 @@+{-# LANGUAGE OverloadedLists #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.Machine.Analysis.Heap+Description : Machines for processing eventlog data.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Machine.Analysis.Heap (+  -- * Heap Usage+  processHeapAllocated,+  processHeapSize,+  processBlocksSize,+  processHeapLive,+  MemReturn (..),+  processMemReturn,+  GcStats (..),+  processGcStats,+  HeapProfSample,+  heapProfSamples,+  processHeapProfSample,+) where++import Control.Monad (unless, when)+import Control.Monad.IO.Class (MonadIO (..))+import Control.Monad.Trans.Class (MonadTrans (..))+import Data.Either (isLeft)+import Data.Foldable (for_)+import Data.HashMap.Strict (HashMap)+import Data.HashMap.Strict qualified as M+import Data.List qualified as L+import Data.Machine (Process, ProcessT, await, construct, repeatedly, yield)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Word (Word32, Word64)+import GHC.Eventlog.Live.Logger (Logger, logTrace, logWarn)+import GHC.Eventlog.Live.Machine.WithStartTime (WithStartTime (..), tryGetTimeUnixNano)+import GHC.Eventlog.Live.Types.Attribute (Attrs, (~=))+import GHC.Eventlog.Live.Types.Capability (evCapNo)+import GHC.Eventlog.Live.Types.Group (GroupBy (..))+import GHC.Eventlog.Live.Types.HeapProfBreakdown (findHeapProfBreakdown, heapProfBreakdownShow)+import GHC.Eventlog.Live.Types.Metrics (Metric (..), (<+>))+import GHC.RTS.Events (Event (..), HeapProfBreakdown (..))+import GHC.RTS.Events qualified as E+import IpeDB.Database (Table)+import IpeDB.Database qualified as DB+import IpeDB.Types.InfoProv (InfoProv (..), InfoProvId (..))+import IpeDB.Types.SrcLoc (ppSrcLoc)+import Text.Printf (printf)+import Text.Read (readMaybe)++-------------------------------------------------------------------------------+-- Heap events+-------------------------------------------------------------------------------++--------------------------------------------------------------------------------+-- HeapAllocated++{- |+This machine processes `E.HeapAllocated` events into metrics.++This metric is the total bytes allocated over the whole run by the heap capability set.+-}+processHeapAllocated :: Process (WithStartTime Event) (Metric Word64)+processHeapAllocated =+  repeatedly $+    await >>= \case+      i+        | E.HeapAllocated{..} <- i.value.evSpec ->+            yield $ metric i allocBytes []+        | otherwise -> pure ()++-------------------------------------------------------------------------------+-- HeapSize++{- |+This machine processes `E.HeapSize` events into metrics.++This metric is the current bytes allocated from the OS to use for the heap.+-}+processHeapSize :: Process (WithStartTime Event) (Metric Word64)+processHeapSize =+  repeatedly $+    await >>= \case+      i+        | E.HeapSize{..} <- i.value.evSpec -> do+            yield $ metric i sizeBytes []+        | otherwise -> pure ()++-------------------------------------------------------------------------------+-- BlocksSize++{- |+This machine processes `E.BlocksSize` events into metrics.+-}+processBlocksSize :: Process (WithStartTime Event) (Metric Word64)+processBlocksSize =+  repeatedly $+    await >>= \case+      i+        | E.BlocksSize{..} <- i.value.evSpec -> do+            yield $ metric i blocksSize []+        | otherwise -> pure ()++-------------------------------------------------------------------------------+-- HeapLive++{- |+This machine processes `E.HeapLive` events into metrics.++This metric is the current amount of live/reachable data in the heap.+-}+processHeapLive :: Process (WithStartTime Event) (Metric Word64)+processHeapLive =+  repeatedly $+    await >>= \case+      i+        | E.HeapLive{..} <- i.value.evSpec -> do+            yield $ metric i liveBytes []+        | otherwise -> pure ()++-------------------------------------------------------------------------------+-- MemReturn++{- |+The type of data associated with a `E.MemReturn` event.+-}+data MemReturn = MemReturn+  { current :: !Word32+  -- ^ The number of megablocks currently allocated.+  , needed :: !Word32+  -- ^ The number of megablocks currently needed.+  , returned :: !Word32+  -- ^ The number of megablocks currently being returned to the OS.+  }++{- |+This machine processes `E.MemReturn` events into metrics.+-}+processMemReturn :: Process (WithStartTime Event) (Metric MemReturn)+processMemReturn =+  repeatedly $+    await >>= \case+      i+        | E.MemReturn{..} <- i.value.evSpec -> do+            yield $ metric i MemReturn{..} []+        | otherwise -> pure ()++-------------------------------------------------------------------------------+-- GcStats++data GcStats = GcStats+  { copied :: !Word64+  -- ^ Number of bytes copied.+  , slop :: !Word64+  {- ^ Amount of slop in bytes.++  Slop is unused memory between objects in the heap.+  -}+  , fragmentation :: !Word64+  {- ^ Amount of fragmentation in bytes.++  The difference between total mblock size and total block size.+  If all mblocks are full of blocks, this number is 0.+  -}+  }++{- |+This machine processes `E.GCStatsGHC` events into metrics.+-}+processGcStats :: Process (WithStartTime Event) (Metric GcStats)+processGcStats =+  repeatedly $+    await >>= \case+      i+        | E.GCStatsGHC{..} <- i.value.evSpec -> do+            yield $+              metric i GcStats{copied, slop, fragmentation = frag} $+                ["gen" ~= gen]+        | otherwise -> pure ()++-------------------------------------------------------------------------------+-- HeapProfSample++{- |+The type of all heap profile samples from a single garbage collection pass.+-}+newtype HeapProfSample = HeapProfSample+  { heapProfSampleMap :: HashMap Text (Metric Word64)+  }+  deriving (Show)+  deriving newtype (Semigroup, Monoid)++instance GroupBy HeapProfSample where+  type Key HeapProfSample = ()++  toKey :: HeapProfSample -> ()+  toKey = const ()++{- |+Get the elements of a heap profile sample collection.+-}+heapProfSamples :: HeapProfSample -> [Metric Word64]+heapProfSamples = M.elems . (.heapProfSampleMap)++{- |+Internal helper.+Insert a heap profiling sample into the collection.+-}+insertHeapProfSampleString ::+  forall m.+  (Monad m) =>+  Logger m ->+  Text ->+  Metric Word64 ->+  HeapProfSample ->+  m HeapProfSample+insertHeapProfSampleString _logger heapProfLabel heapProfSample heapProfSampleData = do+  -- NOTE: When using -fdistinct-constructor-tables, GHC creates a distinct+  --       info table for each usage site. When using heap profiling by closure+  --       type, GHC uses the address of the StgInfoTable->con_desc as its+  --       identifier. When using both flags, this causes GHC to emit multiple+  --       samples with the same label.+  let insert :: Maybe (Metric Word64) -> Maybe (Metric Word64)+      insert = Just . maybe heapProfSample (<+> heapProfSample)++  let heapProfSampleMap' = M.alter insert heapProfLabel heapProfSampleData.heapProfSampleMap+  pure HeapProfSample{heapProfSampleMap = heapProfSampleMap'}++{- |+Internal helper.+The type of the state kept by `processHeapProfSample`.+-}+data HeapProfSampleState = HeapProfSampleState+  { eitherShouldWarnOrHeapProfBreakdown :: !(Either Bool HeapProfBreakdown)+  , heapProfSampleEraStack :: ![Word64]+  , maybeHeapProfSample :: !(Maybe HeapProfSample)+  }+  deriving (Show)++{- |+This machine processes `E.HeapProfSampleString` events into metrics.+Furthermore, it processes the `E.HeapProfBegin` and `E.ProgramArgs` events+to determine the heap profile breakdown, processes `E.InfoTableProv` events to+build an info table map, if necessary, and processes `E.HeapProfSampleBegin`+and `E.HeapProfSampleEnd` events to maintain an era stack.+-}+processHeapProfSample ::+  (MonadIO m) =>+  Logger m ->+  Maybe (Table InfoProvId InfoProv) ->+  Maybe HeapProfBreakdown ->+  ProcessT m (WithStartTime Event) HeapProfSample+processHeapProfSample logger maybeInfoProvTable maybeHeapProfBreakdown =+  construct $+    go+      HeapProfSampleState+        { eitherShouldWarnOrHeapProfBreakdown = maybe (Left True) Right maybeHeapProfBreakdown+        , heapProfSampleEraStack = mempty+        , maybeHeapProfSample = mempty+        }+ where+  -- go :: HeapProfSampleState -> PlanT (Is (WithStartTime Event)) HeapProfSample m Void+  go st@HeapProfSampleState{..} = do+    await >>= \i -> case i.value.evSpec of+      -- Announces the heap profile breakdown, amongst other things.+      -- This event is only emitted for code compiled with GHC >=9.14.+      E.HeapProfBegin{..}+        | isLeft eitherShouldWarnOrHeapProfBreakdown ->+            go st{eitherShouldWarnOrHeapProfBreakdown = Right heapProfBreakdown}+      -- Announces the arguments with which the program was called.+      -- This *may* include RTS options, which can be used to determine the+      -- heap profile breakdown for code compiled with GHC <9.14.+      E.ProgramArgs{..}+        | isLeft eitherShouldWarnOrHeapProfBreakdown+        , Just heapProfBreakdown <- findHeapProfBreakdown args ->+            go st{eitherShouldWarnOrHeapProfBreakdown = Right heapProfBreakdown}+      -- Announces the beginning of a heap profile sample.+      E.HeapProfSampleBegin{..} -> do+        -- Check that maybeHeapProfSample is Nothing.+        for_ st.maybeHeapProfSample $ \heapProfSampleData -> do+          let msg =+                "Unexpected event HeapProfSampleBegin while previous garbage collection pass was left open.\n\+                \This may indicate that the eventlog is not properly ordered or that its semantics have changed."+          lift $ logWarn logger $ msg++          -- Yield the previous sample data anyway.+          yield heapProfSampleData+        -- Start a new garbage collection pass.+        go+          st+            { heapProfSampleEraStack = heapProfSampleEra : heapProfSampleEraStack+            , maybeHeapProfSample = Just mempty+            }+      -- Announces the end of a heap profile sample.+      E.HeapProfSampleEnd{..} -> do+        -- Yield the previous heap profile sample data+        for_ st.maybeHeapProfSample yield+        -- Pop the heapProfSampleEraStack+        heapProfSampleEraStack' <-+          case L.uncons heapProfSampleEraStack of+            Nothing -> do+              let msg =+                    T.pack $+                      printf+                        "Eventlog closed era %d, but there is no current era."+                        heapProfSampleEra+              lift $ logWarn logger $ msg+              pure heapProfSampleEraStack+            Just (currentEra, heapProfSampleEraStack') -> do+              unless (currentEra == heapProfSampleEra) $ do+                let msg =+                      T.pack $+                        printf+                          "Eventlog closed era %d, but the current era is era %d."+                          heapProfSampleEra+                          currentEra+                lift $ logWarn logger $ msg+              pure heapProfSampleEraStack'+        go+          st+            { heapProfSampleEraStack = heapProfSampleEraStack'+            , maybeHeapProfSample = Nothing+            }+      -- Announces a heap profile sample.+      E.HeapProfSampleString{..}+        -- If there is no heap profile breakdown, issue a warning, then disable warnings.+        | Left True <- eitherShouldWarnOrHeapProfBreakdown -> do+            let msg =+                  "Cannot infer heap profile breakdown.\n\+                  \         If your binary was compiled with a GHC version prior to 9.14,\n\+                  \         you must also pass the heap profile type to this executable.\n\+                  \         See: https://gitlab.haskell.org/ghc/ghc/-/commit/76d392a"+            lift $ logWarn logger $ msg+            go st{eitherShouldWarnOrHeapProfBreakdown = Left False}+        -- If the heap profile breakdown is by info table, but the shared info+        -- prov table was not provided, issue a warning, then disable warnings.+        | Right HeapProfBreakdownInfoTable <- eitherShouldWarnOrHeapProfBreakdown+        , Nothing <- maybeInfoProvTable -> do+            let msg =+                  "Heap profile breakdown is "+                    <> heapProfBreakdownShow HeapProfBreakdownInfoTable+                    <> ", but no shared InfoProv table was provided."+            lift $ logWarn logger $ T.pack msg+            go st{eitherShouldWarnOrHeapProfBreakdown = Left False}+        -- If the heap profile breakdown is biographical, issue a warning, then disable warnings.+        | Right HeapProfBreakdownBiography <- eitherShouldWarnOrHeapProfBreakdown -> do+            let msg =+                  "Unsupported heap profile breakdown "+                    <> heapProfBreakdownShow HeapProfBreakdownBiography+            lift $ logWarn logger $ T.pack msg+            go st{eitherShouldWarnOrHeapProfBreakdown = Left False}+        -- If there is a heap profile breakdown, handle it appropriately.+        | Right heapProfBreakdown <- eitherShouldWarnOrHeapProfBreakdown -> do+            -- If the heap profile breakdown is by info table, add the info table.+            maybeInfoProv <-+              case heapProfBreakdown of+                -- NOTE: The case where maybeInfoProvTable is Nothing is handled above.+                HeapProfBreakdownInfoTable | Just infoProvTable <- maybeInfoProvTable ->+                  case readMaybe (T.unpack heapProfLabel) of+                    Nothing -> do+                      lift . logWarn logger $+                        "Expected InfoProv ID, found '" <> heapProfLabel <> "' for HeapProfSampleString."+                      pure Nothing+                    Just infoProvPtr -> do+                      maybeInfoProv <- liftIO $ DB.lookup infoProvTable infoProvPtr+                      case maybeInfoProv of+                        Nothing ->+                          when (infoProvPtr /= InfoProvId 0) . lift . logWarn logger $+                            "Could not resolve IPE for " <> T.pack (show infoProvPtr) <> "."+                        Just infoProv ->+                          lift . logTrace logger $+                            "Resolved IPE for " <> T.pack (show infoProvPtr) <> " to " <> infoProv.ipName <> "."+                      pure maybeInfoProv+                _otherwise -> pure Nothing+            -- Get the HeapProfSample+            heapProfSampleData <-+              case st.maybeHeapProfSample of+                Nothing -> do+                  let msg =+                        "Unexpected event HeapProfSampleString out of scope of HeapProfSampleBegin and HeapProfSampleEnd.\n\+                        \This may indicate that the eventlog is not properly ordered or that its semantics have changed."+                  lift $ logWarn logger $ msg+                  pure mempty+                Just heapProfSampleData ->+                  pure heapProfSampleData+            -- Update the HeapProfSample+            let heapProfSample =+                  metric i heapProfResidency $+                    [ "heapProfBreakdown" ~= heapProfBreakdownShow heapProfBreakdown+                    , "heapProfId" ~= heapProfId+                    , "heapProfLabel" ~= heapProfLabel+                    , "heapProfSampleEra" ~= (fst <$> L.uncons heapProfSampleEraStack)+                    , "ipName" ~= fmap (.ipName) maybeInfoProv+                    , "ipClosureDesc" ~= fmap (.ipClosureDesc) maybeInfoProv+                    , "ipTyDesc" ~= fmap (.ipTyDesc) maybeInfoProv+                    , "ipLabel" ~= fmap (.ipLabel) maybeInfoProv+                    , "ipModule" ~= fmap (.ipModule) maybeInfoProv+                    , "ipSrcLoc" ~= fmap (flip (ppSrcLoc . (.ipSrcLoc)) "") maybeInfoProv+                    ]+            heapProfSampleData' <-+              lift $ insertHeapProfSampleString logger heapProfLabel heapProfSample heapProfSampleData+            -- Continue with the updated HeapProfSampleState+            go+              st+                { -- Add the update HeapProfSample+                  maybeHeapProfSample = Just heapProfSampleData'+                }+      _otherwise -> go st++-------------------------------------------------------------------------------+-- Internal Helpers+-------------------------------------------------------------------------------++{- |+Internal helper. Construct a t`Metric` from an event with a start time+(t`WithStartTime` t`Event`), together with the measurement and any attributes.+This is a smart constructor that pulls the various timestamps out of the event.+-}+metric ::+  WithStartTime Event ->+  v ->+  Attrs ->+  Metric v+metric i v attrs =+  Metric+    { value = v+    , maybeTimeUnixNano = tryGetTimeUnixNano i+    , maybeStartTimeUnixNano = i.maybeStartTimeUnixNano+    , attrs = ["capNo" ~= evCapNo i.value] <> attrs+    }
+ src-lib/GHC/Eventlog/Live/Machine/Analysis/Log.hs view
@@ -0,0 +1,84 @@+{-# LANGUAGE OverloadedLists #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.Machine.Analysis.Log+Description : Machines for processing eventlog data.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Machine.Analysis.Log where++import Data.Machine (Process, await, repeatedly, yield)+import Data.Text (Text)+import GHC.Eventlog.Live.Machine.WithStartTime (TimeUnixNano, WithStartTime (..), tryGetTimeUnixNano)+import GHC.Eventlog.Live.Types.Attribute (Attrs, (~=))+import GHC.Eventlog.Live.Types.Capability (CapNo, evCapNo)+import GHC.Eventlog.Live.Types.Severity (Severity (..))+import GHC.RTS.Events (Event)+import GHC.RTS.Events qualified as E+import GHC.Records (HasField (..))++--------------------------------------------------------------------------------+-- UserMessage++data UserMessage = UserMessage+  { value :: !Text+  , maybeTimeUnixNano :: !(Maybe TimeUnixNano)+  , capNo :: !(Maybe CapNo)+  }++instance HasField "maybeSeverity" UserMessage (Maybe Severity) where+  getField = const (Just TRACE)++instance HasField "attrs" UserMessage Attrs where+  getField i = ["capNo" ~= i.capNo]++{- |+This machine processes `E.UserMessage` events into logs.+-}+processUserMessage :: Process (WithStartTime Event) UserMessage+processUserMessage =+  repeatedly $+    await >>= \case+      i+        | E.UserMessage{..} <- i.value.evSpec ->+            yield+              UserMessage+                { value = msg+                , maybeTimeUnixNano = tryGetTimeUnixNano i+                , capNo = evCapNo i.value+                }+        | otherwise -> pure ()++--------------------------------------------------------------------------------+-- UserMarker++data UserMarker = UserMarker+  { value :: !Text+  , maybeTimeUnixNano :: !(Maybe TimeUnixNano)+  , capNo :: !(Maybe CapNo)+  }++instance HasField "maybeSeverity" UserMarker (Maybe Severity) where+  getField = const Nothing++instance HasField "attrs" UserMarker Attrs where+  getField i = ["capNo" ~= i.capNo]++{- |+This machine processes `E.UserMarker` events into logs.+-}+processUserMarker :: Process (WithStartTime Event) UserMarker+processUserMarker =+  repeatedly $+    await >>= \case+      i+        | E.UserMarker{..} <- i.value.evSpec ->+            yield+              UserMarker+                { value = markername+                , maybeTimeUnixNano = tryGetTimeUnixNano i+                , capNo = evCapNo i.value+                }+        | otherwise -> pure ()
+ src-lib/GHC/Eventlog/Live/Machine/Analysis/Profile.hs view
@@ -0,0 +1,356 @@+{-# LANGUAGE OverloadedLists #-}+{-# LANGUAGE OverloadedStrings #-}++module GHC.Eventlog.Live.Machine.Analysis.Profile (+  -- * Call-stack profiling+  CallStack (..),+  CallStackFrame (..),+  processGhcStackProfilerData,++  -- * Cost-centre profiling+  CostCentreStack (..),+  CostCentreStackFrame (..),+  processProfSampleCostCentreData,+)+where++import Control.Applicative (Alternative (..))+import Control.Exception (Exception (..))+import Control.Monad (unless, when)+import Control.Monad.IO.Class (MonadIO (..))+import Control.Monad.Trans.Class (MonadTrans (..))+import Data.ByteString.Lazy qualified as BSL+import Data.List.NonEmpty (NonEmpty ((:|)))+import Data.List.NonEmpty qualified as NE+import Data.Machine (Is, PlanT, ProcessT, await, construct, repeatedly, yield)+import Data.Map.Strict qualified as M+import Data.Maybe (catMaybes, isNothing, mapMaybe)+import Data.Set qualified as S+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text qualified as Text+import Data.Traversable.Compat (mapAccumM)+import Data.Vector (Vector)+import Data.Vector qualified as V+import Data.Word (Word16, Word32, Word8)+import GHC.Eventlog.Live.Logger (Logger, logError, logWarn)+import GHC.Eventlog.Live.Machine.WithStartTime (TimeUnixNano, WithStartTime (..), tryGetTimeUnixNano)+import GHC.Eventlog.Live.Types.Attribute (Attrs, (~=))+import GHC.Eventlog.Live.Types.Capability (CapNo (..), fromCapabilityId)+import GHC.Eventlog.Live.Types.Profiles (Location (..))+import GHC.Eventlog.Live.Types.Thread (ThreadId (..), fromThreadId)+import GHC.RTS.Events (Event (..))+import GHC.RTS.Events qualified as E+import GHC.Records (HasField (..))+import GHC.Stack.Profiler.Core qualified as GSP+import IpeDB.Database qualified as DB+import IpeDB.Types.CostCentre (CostCentre (..), CostCentreId (..))+import IpeDB.Types.InfoProv (InfoProv (..), InfoProvId (..))+import IpeDB.Types.SrcLoc (Range (..), SrcLoc (..))++--------------------------------------------------------------------------------+-- Processor for `ghc-stack-profiler` call-stack samples+--------------------------------------------------------------------------------++{- |+A GHC call-stack as produced by @ghc-stack-profiler@.+-}+data CallStack = CallStack+  { capNo :: !CapNo+  , threadId :: !ThreadId+  , callStack :: !(Vector CallStackFrame)+  , maybeTimeUnixNano :: !(Maybe TimeUnixNano)+  }+  deriving stock (Show)++instance HasField "value" CallStack Word8 where+  getField :: CallStack -> Word8+  getField _s = 1++instance HasField "stack" CallStack (Vector Location) where+  getField :: CallStack -> Vector Location+  getField = fmap toLocation . (.callStack)+   where+    toLocation :: CallStackFrame -> Location+    toLocation = \case+      CallStackFrame _ipId (Just InfoProv{..})+        -- If there's a non-empty ipLabel, use it.+        | not (T.null ipLabel) ->+            Location{name = ipModule <> ":" <> ipLabel, srcLoc = ipSrcLoc}+        -- If there's a non-empty ipName, use it.+        | not (T.null ipName) ->+            Location{name = ipModule <> ":" <> ipName, srcLoc = ipSrcLoc}+      -- Otherwise, there's no helpful location information.+      CallStackFrame ipId maybeInfoProv ->+        Location{name = T.show ipId, srcLoc = maybe UnhelpfulSrcLoc (.ipSrcLoc) maybeInfoProv}+      CallStackMessage name srcLoc ->+        Location{..}++instance HasField "attrs" CallStack Attrs where+  getField :: CallStack -> Attrs+  getField s =+    [ "capNo" ~= s.capNo+    , "thread" ~= s.threadId+    ]++{- |+A GHC call-stack frame as produced by @ghc-stack-profiler@.+-}+data CallStackFrame+  = CallStackFrame !InfoProvId !(Maybe InfoProv)+  | CallStackMessage !Text !SrcLoc+  deriving stock (Show)++{- |+Internal helper.++The internal state for `processGhcStackProfilerData`.+-}+data GhcStackProfilerState = GhcStackProfilerState+  { warnOnDeserializeError :: !Bool+  , callStackChunksRev :: ![GSP.CallStackChunk]+  , maybeTimeUnixNano :: !(Maybe TimeUnixNano)+  , symbolTable :: !GSP.IntMapTable+  }++{- |+Internal helper.++The initial state for `processGhcStackProfilerData`.+-}+emptyGhcStackProfilerState :: GhcStackProfilerState+emptyGhcStackProfilerState =+  GhcStackProfilerState+    { warnOnDeserializeError = True+    , callStackChunksRev = []+    , maybeTimeUnixNano = Nothing+    , symbolTable = GSP.emptyIntMapTable+    }++{- |+This machine processes the `E.UserBinaryMessage` events produced by+@ghc-stack-profiler@ into `CallStack` samples.+-}+processGhcStackProfilerData ::+  forall m.+  (MonadIO m) =>+  Logger m ->+  DB.Table InfoProvId InfoProv ->+  ProcessT m (WithStartTime Event) CallStack+processGhcStackProfilerData logger infoProvTable =+  construct $ go emptyGhcStackProfilerState+ where+  go :: GhcStackProfilerState -> PlanT (Is (WithStartTime Event)) CallStack m ()+  go st =+    await >>= \i -> do+      case i.value.evSpec of+        E.UserBinaryMessage{..} -> do+          case GSP.deserializeEventlogMessage (BSL.fromStrict payload) of+            Left errMsg+              | st.warnOnDeserializeError -> do+                  lift . logWarn logger . T.unlines $+                    [ "Could not parse UserBinaryMessage as ghc-stack-profiler message:"+                    , T.pack errMsg+                    , "If other plugins are communicating via binary eventlog messages, this is expected."+                    ]+                  go st{warnOnDeserializeError = False}+              | otherwise -> go st+            -- If we receive a protocol version, do nothing.+            Right (GSP.ProtocolVersion _protocolVersion) -> do+              go st+            -- If we receive the final call-stack chunk, decode and yield the call-stack, the restart...+            Right (GSP.CallStackFinal callStackChunk) -> do+              let symbolTableReader = GSP.mkIntMapSymbolTableReader st.symbolTable+              let callStackChunks = NE.reverse (callStackChunk :| st.callStackChunksRev)+              let !maybeTimeUnixNano = st.maybeTimeUnixNano <|> tryGetTimeUnixNano i+              callStack <- lift $ decodeCallStack maybeTimeUnixNano symbolTableReader callStackChunks+              unless (V.null callStack.callStack) $ yield callStack+              go+                st+                  { callStackChunksRev = []+                  , maybeTimeUnixNano = Nothing+                  }+            -- If we receive a call-stack chunk, add it to the list of chunks and continue...+            Right (GSP.CallStackChunk callStackChunk) ->+              go+                st+                  { callStackChunksRev = callStackChunk : st.callStackChunksRev+                  , maybeTimeUnixNano = st.maybeTimeUnixNano <|> tryGetTimeUnixNano i+                  }+            -- If we receive a string definition, update the symbol table and continue...+            Right (GSP.StringDef string) -> do+              let !symbolTable' = GSP.insertTextMessage string st.symbolTable+              go st{symbolTable = symbolTable'}+            -- If we receive a source location definition, update the symbol table and continue...+            Right (GSP.SourceLocationDef sourceLocation) ->+              case GSP.insertSourceLocationMessage sourceLocation st.symbolTable of+                Left errMsg -> do+                  lift . logWarn logger . T.unlines $+                    [ "Could not decode source location from ghc-stack-profiler message:"+                    , T.pack (displayException errMsg)+                    ]+                  go st+                Right symbolTable' ->+                  go st{symbolTable = symbolTable'}+        _otherwise -> go st++  decodeCallStack ::+    Maybe TimeUnixNano ->+    GSP.SymbolTableReader ->+    NonEmpty GSP.CallStackChunk ->+    m CallStack+  decodeCallStack maybeTimeUnixNano symbolTableReader callStackChunks = do+    -- Concatenate the chunks into a full binary call-stack message.+    let !gspBinaryCallStack = GSP.joinCallStackChunks callStackChunks++    -- Decode the binary call-stack and log any decoding errors.+    let !(gspCallStackMessage, decodeErrors) =+          GSP.hydrateEventlogCallStackMessage symbolTableReader gspBinaryCallStack+    let !gspCallStack = GSP.callStack gspCallStackMessage+    unless (null decodeErrors) $+      logWarn logger . T.unlines $+        ["Encountered errors while decoding binary call-stack from ghc-stack-profiler message:"]+          <> [T.pack (displayException decodeError) | decodeError <- decodeErrors]++    -- Extract the IPE IDs and look them up in a single batched database query.+    let getMaybeInfoProvId :: GSP.StackItem -> Maybe InfoProvId+        getMaybeInfoProvId = \case GSP.IpeId iid -> Just (toInfoProvId iid); _otherwise -> Nothing+    let infoProvIds = V.fromList . mapMaybe getMaybeInfoProvId $ gspCallStack+    maybeInfoProvs <- liftIO $ lookups infoProvTable infoProvIds++    -- Convert each `GSP.StackItem` to a `CallStackFrame`.+    let toCallStackFrame :: [Maybe InfoProv] -> GSP.StackItem -> m ([Maybe InfoProv], Maybe CallStackFrame)+        toCallStackFrame (maybeInfoProv : acc) (GSP.IpeId iid) = do+          when (isNothing maybeInfoProv) $+            logWarn logger $+              "Could not resolve IPE ID " <> T.pack (show (toInfoProvId iid))+          pure (acc, Just $! CallStackFrame (toInfoProvId iid) maybeInfoProv)+        toCallStackFrame acc (GSP.UserAnnotation msg maybeSourceLocation) =+          pure (acc, Just $! CallStackMessage (T.pack msg) (toSrcLoc maybeSourceLocation))+        toCallStackFrame [] (GSP.IpeId _iid) = do+          logError logger $+            "Did not receive enough IPEs to annotate each call-stack item. Please report this as a bug."+          pure ([], Nothing)+    callStack <-+      V.fromList . catMaybes . snd+        <$> mapAccumM toCallStackFrame (V.toList maybeInfoProvs) gspCallStack++    let !capNo = fromCapabilityId . GSP.callCapabilityId $ gspCallStackMessage+    let !threadId = fromThreadId . GSP.callThreadId $ gspCallStackMessage+    pure CallStack{..}++{- |+Internal helper.++Convert a @ghc-stack-profiler@ `GSP.IpeID` to an `InfoProvId`.+-}+toInfoProvId :: GSP.IpeId -> InfoProvId+toInfoProvId (GSP.MkIpeId x) = InfoProvId x++{- |+Internal helper.++Convert a `GSP.SourceLocation` to a `SrcLoc`.+-}+toSrcLoc :: Maybe GSP.SourceLocation -> SrcLoc+toSrcLoc = \case+  Nothing ->+    UnhelpfulSrcLoc+  Just GSP.MkSourceLocation{fileName, column, line} ->+    SrcLoc (Text.unpack fileName) (Just $! Range'Point column line)++--------------------------------------------------------------------------------+-- Processor for cost-centre stack samples+--------------------------------------------------------------------------------++{- |+A GHC cost-centre stack.+-}+data CostCentreStack = CostCentreStack+  { capNo :: !CapNo+  , costCentreStack :: !(Vector CostCentreStackFrame)+  , maybeTimeUnixNano :: !(Maybe TimeUnixNano)+  }+  deriving stock (Show)++instance HasField "value" CostCentreStack Word8 where+  getField :: CostCentreStack -> Word8+  getField _s = 1++instance HasField "stack" CostCentreStack (Vector Location) where+  getField :: CostCentreStack -> Vector Location+  getField = fmap toLocation . (.costCentreStack)+   where+    toLocation :: CostCentreStackFrame -> Location+    toLocation = \case+      CostCentreStackFrame _ccId (Just CostCentre{..})+        -- If there's a non-empty ccLabel, use it.+        | not (T.null ccLabel) ->+            Location{name = ccModule <> ":" <> ccLabel, srcLoc = ccSrcLoc}+      CostCentreStackFrame ccId maybeCostCentre ->+        Location{name = T.show ccId, srcLoc = maybe UnhelpfulSrcLoc (.ccSrcLoc) maybeCostCentre}++instance HasField "attrs" CostCentreStack Attrs where+  getField :: CostCentreStack -> Attrs+  getField s = ["capNo" ~= s.capNo]++{- |+A GHC cost-centre stack frame.+-}+data CostCentreStackFrame+  = CostCentreStackFrame !CostCentreId !(Maybe CostCentre)+  deriving stock (Show)++{- |+This machine processes `E.ProfSampleCostCentre` events into `CostCentreStack` samples.+-}+processProfSampleCostCentreData ::+  forall m.+  (MonadIO m) =>+  Logger m ->+  DB.Table CostCentreId CostCentre ->+  ProcessT m (WithStartTime Event) CostCentreStack+processProfSampleCostCentreData logger costCentreTable =+  repeatedly $+    await >>= \i ->+      case i.value.evSpec of+        E.ProfSampleCostCentre{..} -> do+          -- Look up all cost centre IDs in the cost centre stack.+          let !costCentreIds = CostCentreId <$> V.convert profCcsStack+          !maybeCostCentres <- liftIO $ lookups costCentreTable costCentreIds+          -- NOTE: The following is equivalent to `CostCentreStackFrame`, but+          --       logs a warning if the cost centre was not resolved.+          let warnIfNotFound costCentreId maybeCostCentre = do+                lift . when (isNothing maybeCostCentre) $ do+                  logWarn logger . T.pack $+                    "Could not resolve cost centre ID " <> show costCentreId+                pure $ CostCentreStackFrame costCentreId maybeCostCentre+          costCentreStack <- V.zipWithM warnIfNotFound costCentreIds maybeCostCentres++          -- Yield the cost centre stack.+          let !capNo = CapNo $ fromIntegral @Word16 @Word32 profCap+          let !maybeTimeUnixNano = tryGetTimeUnixNano i+          yield CostCentreStack{..}+        _otherwise -> pure ()++--------------------------------------------------------------------------------+-- Internal helpers+--------------------------------------------------------------------------------++{- |+Variant of `DB.lookups` that deduplicates keys before performing the database lookup.+-}+lookups :: (Ord k, DB.Key k, DB.Value v) => DB.Table k v -> Vector k -> IO (Vector (Maybe v))+lookups table keys = do+  -- Build a set of keys:+  let !keysSet = S.fromList (V.toList keys)+  if S.size keysSet == V.length keys+    then do+      -- If all keys are unique, we can just perform the database lookup...+      DB.lookups table keys+    else do+      -- Otherwise, we perform the database lookup with the unique keys and resolve them via a map...+      let !keysUniq = V.fromList (S.toAscList keysSet)+      maybeValues <- DB.lookups table keysUniq+      let !keyValueMap = M.fromAscList . V.toList . V.mapMaybe sequence $ V.zip keysUniq maybeValues+      pure $ V.map (`M.lookup` keyValueMap) keys
+ src-lib/GHC/Eventlog/Live/Machine/Analysis/Thread.hs view
@@ -0,0 +1,340 @@+{-# LANGUAGE OverloadedLists #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.Machine.Analysis.Thread+Description : Machines for processing eventlog data.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Machine.Analysis.Thread (+  -- * Thread Analysis++  -- ** Thread Labels+  ThreadLabel (..),+  processThreadLabel,++  -- ** Thread State Spans+  ThreadState (..),+  showThreadState,+  threadStopStatus,+  threadStateCapNo,+  ThreadStateSpan (..),+  processThreadStateSpans,+  processThreadStateSpans',+) where++import Control.Monad.Trans.Class (MonadTrans (..))+import Data.Char (isSpace)+import Data.Machine (Is (..), PlanT, Process, ProcessT, await, construct, repeatedly, yield)+import Data.Maybe (isNothing)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Void (Void)+import GHC.Eventlog.Live.Logger (Logger, logWarn)+import GHC.Eventlog.Live.Machine.Core (liftRouter)+import GHC.Eventlog.Live.Machine.WithStartTime (TimeUnixNano, WithStartTime (..), tryGetTimeUnixNano)+import GHC.Eventlog.Live.Types.Attribute (Attrs, (~=))+import GHC.Eventlog.Live.Types.Capability (CapNo, evCapNo)+import GHC.Eventlog.Live.Types.Severity (Severity (..))+import GHC.Eventlog.Live.Types.Traces (duration)+import GHC.RTS.Events (Event (..), EventInfo, ThreadId, ThreadStopStatus (..), showThreadStopStatus)+import GHC.RTS.Events qualified as E+import GHC.Records (HasField (..))+import Text.Printf (printf)++-------------------------------------------------------------------------------+-- Thread Labels++{- |+The t`ThreadLabel` type represents the association of a label with a thread+starting at a given time.+-}+data ThreadLabel+  = ThreadLabel+  { thread :: !ThreadId+  , threadlabel :: !Text+  , startTimeUnixNano :: !TimeUnixNano+  }++instance HasField "value" ThreadLabel Text where+  getField = (.threadlabel)++instance HasField "maybeTimeUnixNano" ThreadLabel (Maybe TimeUnixNano) where+  getField = Just . (.startTimeUnixNano)++instance HasField "maybeSeverity" ThreadLabel (Maybe Severity) where+  getField = const Nothing++instance HasField "attrs" ThreadLabel Attrs where+  getField i = ["thread" ~= i.thread]++{- |+This machine processes `E.ThreadLabel` events and yields t`ThreadLabel` values.+-}+processThreadLabel :: Process (WithStartTime Event) ThreadLabel+processThreadLabel = repeatedly go+ where+  go =+    await >>= \i -> case i.value.evSpec of+      E.ThreadLabel{..}+        | Just startTimeUnixNano <- tryGetTimeUnixNano i ->+            yield ThreadLabel{..}+      _otherwise -> pure ()++-------------------------------------------------------------------------------+-- Thread State Spans++{- |+The execution states of a mutator thread.+-}+data ThreadState+  = Running {capNo :: !CapNo}+  | Blocked {status :: !ThreadStopStatus}+  | Finished+  deriving (Show)++{- |+Pretty-print a thread state as "Running", "Blocked", or "Finished".+-}+showThreadState :: ThreadState -> Text+showThreadState = \case+  Running{} -> "Running"+  Blocked{} -> "Blocked"+  Finished{} -> "Finished"++{- |+Get the t`ThreadState` status, if the t`ThreadState` is `Blocked`.+-}+threadStopStatus :: ThreadState -> Maybe ThreadStopStatus+threadStopStatus = \case+  Running{} -> Nothing+  Blocked{status} -> Just status+  Finished{} -> Nothing++{- |+Get the t`ThreadState` capability, if the `ThreadState` is `Running`.+-}+threadStateCapNo :: ThreadState -> Maybe CapNo+threadStateCapNo = \case+  Running{capNo} -> Just capNo+  Blocked{} -> Nothing+  Finished{} -> Nothing++{- |+A span representing the state of a mutator thread.+-}+data ThreadStateSpan+  = ThreadStateSpan+  { thread :: !ThreadId+  , threadState :: !ThreadState+  , startTimeUnixNano :: !TimeUnixNano+  , endTimeUnixNano :: !TimeUnixNano+  }+  deriving (Show)++instance HasField "traceId" ThreadStateSpan ThreadId where+  getField :: ThreadStateSpan -> ThreadId+  getField = (.thread)++instance HasField "attrs" ThreadStateSpan Attrs where+  getField :: ThreadStateSpan -> Attrs+  getField s =+    [ "capNo" ~= threadStateCapNo s.threadState+    , "thread" ~= s.thread+    , "threadState" ~= showThreadState s.threadState+    , "threadStopStatus" ~= (showThreadStopStatus <$> threadStopStatus s.threadState)+    ]++{-# SPECIALIZE duration :: ThreadStateSpan -> TimeUnixNano #-}++{- |+This machine processes `E.RunThread` and `E.StopThread` events to produce+t`ThreadStateSpan` values that represent segments of time where a thread is+running, blocked, or finished.++This processor uses the following finite-state automaton:++@+      ┌─(StopThread)─┐+      │              ↓+    ┌→[   Blocked    ]─┐+    │                  │+(StopThread)       (RunThread)+    │                  │+    └─[   Running    ]←┘+      ↑              │+      └─(RunThread)──┘+@++The transitions from @Blocked@ to @Blocked@, @Blocked@ to @Running@, and+@Running@ to @Running@ yield a t`ThreadStateSpan`. There are additional+transitions (not pictured) from either state to the final `Finished` state+with a `E.StopThread` event with the `ThreadFinished` status.+-}+processThreadStateSpans ::+  (Monad m) =>+  Logger m ->+  ProcessT m (WithStartTime Event) ThreadStateSpan+processThreadStateSpans =+  processThreadStateSpans' tryGetTimeUnixNano (.value) (const id)++{- |+Generalised version of `processThreadStateSpans` that can be adapted to work+on arbitrary types using a getter and a lens.+-}+processThreadStateSpans' ::+  forall m s t.+  (Monad m) =>+  (s -> Maybe TimeUnixNano) ->+  (s -> Event) ->+  (s -> ThreadStateSpan -> t) ->+  Logger m ->+  ProcessT m s t+processThreadStateSpans' timeUnixNano getEvent setThreadStateSpan logger =+  liftRouter measure spawn+ where+  getEventTime = (.evTime) . getEvent+  getEventInfo = (.evSpec) . getEvent+  getEventCapNo = evCapNo . getEvent++  measure :: s -> Maybe ThreadId+  measure i = case getEventInfo i of+    E.RunThread{thread} -> Just thread+    E.StopThread{thread} -> Just thread+    _otherwise -> Nothing++  spawn :: ThreadId -> ProcessT m s t+  spawn thread = construct $ go Nothing+   where+    go :: Maybe s -> PlanT (Is s) t m Void+    go mi =+      await >>= \case+        j+          -- If the previous event was a `E.StopThread` event, and...+          | Just E.StopThread{status} <- getEventInfo <$> mi+          , --- ...it has the `ThreadFinished` status, then...+            isThreadFinished status ->+              -- ...ignore the current event.+              go mi+          --+          -- If the current event is a `E.RunThread` event, and...+          | E.RunThread{} <- getEventInfo j+          , -- ...the previous event was a `E.StopThread` event, then...+            Just E.StopThread{status} <- getEventInfo <$> mi+          , -- ...gather the end time of the previous event, and...+            Just startTimeUnixNano <- timeUnixNano =<< mi+          , -- ...gather the start time of the current event, and...+            Just endTimeUnixNano <- timeUnixNano j -> do+              -- ...yield a thread state span, and...+              yield . setThreadStateSpan j $+                ThreadStateSpan{threadState = Blocked status, ..}+              go (Just j)+          --+          -- If the current event is a `E.RunThread` event, and...+          | E.RunThread{} <- getEventInfo j+          , -- ...the previous event was a `E.RunThread` event, then...+            Just E.RunThread{} <- getEventInfo <$> mi -> do+              -- ...keep the oldest event.+              go (Just $ maybe j (minBy getEventTime j) mi)+          --+          -- If the current event is a `E.RunThread` event, and...+          | E.RunThread{} <- getEventInfo j+          , -- ...there is no previous event, then...+            isNothing mi ->+              -- ...keep the current event.+              --+              -- The reason for the additional `isNothing` test is because,+              -- otherwise, this case might silently swallow any `E.StopThread`+              -- events for which `timeUnixNano` gives `Nothing`.+              -- By excluding these, they are forwarded to the catch-all case.+              go (Just j)+          --+          -- If the current event is a `E.StopThread` event, and...+          | E.StopThread{} <- getEventInfo j+          , -- ...the previous event was a `E.StopThread` event, then...+            Just E.StopThread{status} <- getEventInfo <$> mi+          , -- ...gather the end time of the previous event, and...+            Just startTimeUnixNano <- timeUnixNano =<< mi+          , -- ...gather the start time of the current event, and...+            Just endTimeUnixNano <- timeUnixNano j -> do+              -- ...yield a thread state span, and...+              yield . setThreadStateSpan j $+                ThreadStateSpan{threadState = Blocked status, ..}+              -- ...keep the current event.+              --+              -- This causes us to adopt every `E.StopThread` event, until+              -- we hit a `E.StopThread` event with the `ThreadFinished`, at+              -- which point the first clause will cause us to stick with it.+              go (Just j)+          --+          -- If the current event is a `E.StopThread` event, and...+          | E.StopThread{} <- getEventInfo j+          , -- ...the previous event was a `E.RunThread` event, then...+            Just E.RunThread{} <- getEventInfo <$> mi+          , -- ...gather the capability of the `E.RunThread` event, and...+            Just capNo <- getEventCapNo =<< mi+          , -- ...gather the end time of the previous event, and...+            Just startTimeUnixNano <- timeUnixNano =<< mi+          , -- ...gather the start time of the current event, and...+            Just endTimeUnixNano <- timeUnixNano j -> do+              -- ...yield a thread state span, and...+              yield . setThreadStateSpan j $+                ThreadStateSpan{threadState = Running capNo, ..}+              -- ...keep the current event.+              go (Just j)+          --+          -- If the current event is any other event, then...+          | otherwise -> do+              -- ...emit a warning, and...+              let msg =+                    T.pack $+                      printf+                        "Thread %d: Unexpected event %s\n\+                        \This happens once per running thread when connecting to a running process,\n\+                        \but should not happen multiple times per thread."+                        thread+                        (showEventInfo (getEventInfo j))+              lift $ logWarn logger $ msg++              --+              -- This case may trigger for any event that isn't `E.RunThread`+              -- or `E.StopThread` and for any `E.StopThread` event that comes+              -- before the first `E.RunThread` event. It may also trigger for+              -- any event for which `timeUnixNano` returns `Nothing`.+              --+              -- ...ignore it.+              go mi++-------------------------------------------------------------------------------+-- Internal Helpers+-------------------------------------------------------------------------------++{- |+Internal helper.+Check whether a t`ThreadStopStatus` is equal to `ThreadFinished`.+This is needed because t`ThreadStopStatus` does not define an `Eq` instance.+-}+isThreadFinished :: ThreadStopStatus -> Bool+isThreadFinished = \case+  ThreadFinished -> True+  _otherwise -> False++{- |+Internal helper.+Show `EventInfo` in a condensed format suitable for logging.+-}+showEventInfo :: EventInfo -> String+showEventInfo = \case+  E.RunThread{thread} -> printf "RunThread{%d}" thread+  E.StopThread{thread, status} -> printf "StopThread{%d,%s}" thread (E.showThreadStopStatus status)+  E.MigrateThread{thread} -> printf "MigrateThread{%d}" thread+  E.StartGC{} -> "StartGC"+  E.EndGC{} -> "EndGC"+  evSpec -> takeWhile (not . isSpace) . show $ evSpec++{- |+Internal helper. Return the minimal value by some projection.+-}+minBy :: (Ord b) => (a -> b) -> a -> a -> a+minBy f x y = if f x < f y then x else y
+ src-lib/GHC/Eventlog/Live/Machine/Core.hs view
@@ -0,0 +1,718 @@+{-# LANGUAGE ImplicitParams #-}++{- |+Module      : GHC.Eventlog.Live.Machine.Core+Description : Core machines for processing data in batches.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Machine.Core (+  -- * Ticks+  TickInfo (..),+  HasTickInfo,+  Tick (Item, Tick, TickWithInfo, tickInfo),+  fanoutTick,+  batchByTickList,+  batchByTicksList,+  batchByTick,+  batchByTicks,+  dropTick,+  onlyTick,+  liftTick,++  -- * Machine combinators+  (&>),+  embed,++  -- * Routers+  liftRouter,++  -- * Event sorting+  sortByBatch,+  sortByTick,+  sortByTicks,++  -- * Aggregation Temporality+  deltaToCumulative,++  -- * Delimiting+  delimit,+  betweenEach,+  betweenFirst,+) where++import Control.Monad (when)+import Control.Monad.Trans.State.Strict (get, put, runState)+import Data.DList qualified as D+import Data.Foldable (Foldable (..))+import Data.Function (on)+import Data.Functor ((<&>))+import Data.HashMap.Strict (HashMap)+import Data.HashMap.Strict qualified as M+import Data.Hashable (Hashable (..))+import Data.Kind (Constraint)+import Data.List qualified as L+import Data.Machine (Is (..), MachineT (..), Moore (..), Plan, PlanT, Process, ProcessT, Step (..), asParts, await, construct, encased, mapping, repeatedly, starve, stopped, yield, (~>))+import Data.Machine.Fanout (fanout)+import Data.Maybe (fromMaybe)+import Data.Semigroup (Max (..))+import Data.Traversable (for)+import Data.Void (Void)++{- $setup+>>> :set -XFlexibleContexts+>>> :set -XImplicitParams+>>> :set -XImportQualifiedPost+>>> :set -XLambdaCase+>>> :set -XRankNTypes+>>> :set -XTypeApplications+>>> import Data.Functor.Identity (Identity)+>>> import Data.Machine qualified as M+>>> import Data.Machine hiding (run, runT_)+>>> import Data.Machine.Fanout (fanout)+>>> import Data.Semigroup (Sum (..))++>>> :{+run :: (HasTickInfo => M.MachineT Identity k b) -> [b]+run = let ?tickInfo = TickInfo { tick = 0 } in M.run+:}++>>> :{+runT_ :: Monad m => (HasTickInfo => MachineT m k b) -> m ()+runT_ = let ?tickInfo = TickInfo { tick = 0 } in M.runT_+:}+-}++-------------------------------------------------------------------------------+-- Ticks+-------------------------------------------------------------------------------++{- |+The type of v`Tick` information.+-}+newtype TickInfo = TickInfo+  { tick :: Word+  }++{- |+The constraint that adds information to each v`Tick`.+This should be treated as opaque.+-}+type HasTickInfo :: Constraint+type HasTickInfo = (?tickInfo :: TickInfo)++{- |+The type of data on a stream of items and ticks.++The t`Tick` type is isomorphic to `Maybe` modulo strictness,+but with the caveat that v`Tick` does not represent failure.+-}+data Tick a+  = Item !a+  | (HasTickInfo) => Tick++{- |+__Warning:__+This instance loses ticks and should only be used with `fanout` to combine+streams which pass on ticks.+-}+instance (Semigroup a) => Semigroup (Tick a) where+  (<>) :: Tick a -> Tick a -> Tick a+  t@Tick <> Tick = t+  i@Item{} <> Tick = i+  Tick <> i@Item{} = i+  Item a <> Item a' = Item (a <> a')++deriving instance (Eq a) => Eq (Tick a)+deriving instance Functor Tick+deriving instance Foldable Tick+deriving instance Traversable Tick+deriving instance (Show a) => Show (Tick a)++{- |+Internal helper.+Get `TickInfo` from a t`Tick`.+-}+toTickInfo :: Tick x -> Maybe TickInfo+toTickInfo Item{} = Nothing+toTickInfo Tick = Just ?tickInfo++{- |+Internal helper.+Lift `TickInfo` to a constraint.+-}+withTickInfo :: TickInfo -> ((HasTickInfo) => a) -> a+withTickInfo tickInfo action =+  let ?tickInfo = tickInfo in action++pattern TickWithInfo :: TickInfo -> Tick a+pattern TickWithInfo{tickInfo} <- (toTickInfo -> Just tickInfo)+  where+    TickWithInfo tickInfo = withTickInfo tickInfo Tick++{-# COMPLETE Item, TickWithInfo #-}++{- |+Variant of `fanout` for processes that act on t`Tick` streams.++==== __Examples__++>>> run $ fanoutTick [echo, echo] <~ source [Item [1], Tick, Item [2]]+[Item [1,1],Tick,Item [2,2]]+-}+fanoutTick ::+  forall m a b.+  (Monad m, Semigroup b) =>+  [ProcessT m (Tick a) (Tick b)] ->+  ProcessT m (Tick a) (Tick b)+fanoutTick processes =+  fanout+    [ fanout+        [ process ~> dropTick+        | process <- processes+        ]+        ~> mapping (D.singleton . Item)+    , onlyTick+        ~> mapping D.singleton+    ]+    ~> asParts++{- |+Batches items to lists.++The process @`batchByTickList`@ consumes a stream of items and ticks.+It preserves ticks but batches items between ticks to lists.++__Warning:__ This process does not yield empty batches.++==== __Examples__++>>> run $ batchByTickList <~ source [Item 1,Item 2,Tick,Item 3,Tick,Item 4,Item 5,Tick,Item 6,Tick]+[[1,2],[3],[4,5],[6]]++>>> run $ batchByTickList <~ source [Item 1,Item 2,Tick,Tick]+[[1,2]]+-}+batchByTickList :: Process (Tick a) [a]+batchByTickList =+  mapping (fmap D.singleton)+    ~> batchByTick+    ~> dropTick+    ~> mapping D.toList++{- |+Batches items for a given number of ticks to lists.++The process @`batchByTicksList` n@ consumes a stream of items and ticks.+It preserves ticks but batches items for @n@ ticks to lists and yields the batch before the @n@'th tick.++__Warning:__ This process does not yield empty batches.++==== __Examples__++>>> run $ batchByTicksList 2 <~ source [Item 1,Item 2,Tick,Item 3,Tick,Item 4,Item 5,Tick,Item 6,Tick]+[[1,2,3],[4,5,6]]++>>> run $ batchByTicksList 2 <~ source [Item 1,Item 2,Tick,Tick]+[[1,2]]+-}+batchByTicksList ::+  -- | The number of ticks per batch.+  Int ->+  Process (Tick a) [a]+batchByTicksList ticks =+  mapping (fmap D.singleton)+    ~> batchByTicks ticks+    ~> dropTick+    ~> mapping D.toList++{- |+Batches items via their `Semigroup` instance.++The process @`batchByTick`@ consumes a stream of items and ticks.+It preserves ticks but batches items between ticks using `sconcat`.++==== __Examples__++>>> run $ batchByTick <~ source [Item [1],Item [2],Tick,Item [3],Tick,Item [4],Item [5],Tick,Item [6],Tick]+[Item [1,2],Tick,Item [3],Tick,Item [4,5],Tick,Item [6],Tick]++>>> run $ batchByTick <~ source [Item (Sum 1),Item (Sum 2),Tick,Item (Sum 3),Tick,Item (Sum 4),Item (Sum 5),Tick,Item (Sum 6),Tick]+[Item (Sum {getSum = 3}),Tick,Item (Sum {getSum = 3}),Tick,Item (Sum {getSum = 9}),Tick,Item (Sum {getSum = 6}),Tick]+-}+batchByTick ::+  forall a.+  (Monoid a) => Process (Tick a) (Tick a)+batchByTick = batchByTicks 1++{- |+Batches items for a given number of ticks via their `Semigroup` instance.++The process @`batchByTicks` n@ consumes a stream of items and ticks.+It preserves ticks but batches items for @n@ ticks using `sconcat` and yields the batch before the @n@'th tick.++==== __Examples__++>>> run $ batchByTicks 2 <~ source [Item [1],Item [2],Tick,Item [3],Tick,Item [4],Item [5],Tick,Item [6],Tick]+[Tick,Item [1,2,3],Tick,Tick,Item [4,5,6],Tick]++>>> run $ batchByTicks 2 <~ source [Item (Sum 1),Item (Sum 2),Tick,Item (Sum 3),Tick,Item (Sum 4),Item (Sum 5),Tick,Item (Sum 6),Tick]+[Tick,Item (Sum {getSum = 6}),Tick,Tick,Item (Sum {getSum = 15}),Tick]+-}+batchByTicks ::+  forall a.+  (Semigroup a) =>+  -- | The number of ticks per batch.+  Int ->+  Process (Tick a) (Tick a)+batchByTicks ticks = batchByTicksWith ticks mempty+ where+  batchByTicksWith ::+    forall m.+    (Monad m) =>+    Int ->+    Maybe a ->+    MachineT m (Is (Tick a)) (Tick a)+  batchByTicksWith ticksRemaining maybeAcc =+    MachineT $ pure $ Await onNext Refl onStop+   where+    yieldItem :: a -> ProcessT m (Tick a) (Tick a) -> ProcessT m (Tick a) (Tick a)+    yieldItem a = MachineT . pure . Yield (Item a)++    yieldTick :: (HasTickInfo) => ProcessT m (Tick a) (Tick a) -> ProcessT m (Tick a) (Tick a)+    yieldTick = MachineT . pure . Yield Tick++    onNext :: Tick a -> MachineT m (Is (Tick a)) (Tick a)+    onNext = \case+      Item a -> batchByTicksWith ticksRemaining (maybeAcc <> Just a)+      Tick+        | ticksRemaining <= 1 ->+            -- Yield an `Item` if any items were accumulated.+            maybe id yieldItem maybeAcc $+              -- Yield the `Tick`.+              yieldTick $+                -- Continue with the initial state.+                batchByTicksWith ticks Nothing+        | otherwise ->+            -- Yield the `Tick`.+            yieldTick $+              -- Continue with one fewer tick remaining.+              batchByTicksWith (ticksRemaining - 1) maybeAcc++    onStop :: MachineT m (Is (Tick a)) (Tick a)+    onStop =+      -- Yield an `Item` if any items were accumulated.+      maybe id yieldItem maybeAcc $+        -- Stop.+        stopped++{- |+This machine drops all ticks.+-}+dropTick :: Process (Tick a) a+dropTick =+  repeatedly $+    await >>= \case+      Item a -> yield a+      Tick -> pure ()++{- |+This machine drops all items.+-}+onlyTick :: Process (Tick a) (Tick b)+onlyTick =+  repeatedly $+    await >>= \case+      Tick -> yield Tick+      Item{} -> pure ()++-------------------------------------------------------------------------------+-- Machine combinators+-------------------------------------------------------------------------------++infixl 7 &>++{- |+Run two machines in sequence.+-}+(&>) :: (Monad m) => MachineT m k a -> MachineT m k a -> MachineT m k a+m &> n =+  MachineT $+    runMachineT m >>= \case+      Stop ->+        runMachineT n+      Yield o k ->+        pure (Yield o (k &> n))+      Await onNext k onStop ->+        pure (Await (\t -> onNext t &> n) k (onStop &> n))++{- |+Run a monadic action as a machine.+-}+embed :: (Monad m) => m () -> MachineT m k a+embed action = MachineT $! action >> pure Stop++--------------------------------------------------------------------------------+-- Lift a machine to a machine that passes on ticks unchanged++{- |+Lift a machine to a machine that passes on ticks unchanged.++Constructs the following machine:++@+           ┌─(if Tick)────────────────────┐+  [ Tick a ]                              [ Tick b ]+           └─(if Item)─( ProcessT m a b )─┘+@++==== __Examples__++>>> run $ liftTick (mapping (+1)) <~ source [Item 1,Tick,Item 2,Item 3,Tick,Tick]+[Item 2,Tick,Item 3,Item 4,Tick,Tick]++>>> run $ liftTick (scan (+) 0) <~ source [Item 1,Tick,Item 2,Item 3,Tick,Tick]+[Item 0,Item 1,Tick,Item 3,Item 6,Tick,Tick]+-}+liftTick ::+  (Monad m) =>+  ProcessT m a b ->+  ProcessT m (Tick a) (Tick b)+liftTick m =+  MachineT $+    runMachineT m <&> \case+      Stop ->+        Stop+      Yield o k ->+        Yield (Item o) (liftTick k)+      Await (onNext :: t -> ProcessT m a b) Refl onStop ->+        await'+       where+        await' = Await onNext' Refl onStop'+         where+          onNext' :: Tick a -> ProcessT m (Tick a) (Tick b)+          onNext' = \case+            Tick ->+              MachineT . pure . Yield Tick $+                MachineT . pure $+                  await'+            Item a -> liftTick (onNext a)+          onStop' :: ProcessT m (Tick a) (Tick b)+          onStop' = liftTick onStop++--------------------------------------------------------------------------------+-- Construct a processor that spawns a separate child processor for each measure++{- |+Spawns a process for each measure.++Constructs the following machine:++@+    ┌─────(if measure == k0)─( spawn k0 :: ProcessT m a b )────┐+  [ a ] ──(if measure == ..)─( spawn .. :: ProcessT m a b )─ [ b ]+    └─────(if measure == kN)─( spawn kN :: ProcessT m a b )────┘+@++If the spawned process for some measure stops,+then all future inputs for that measure are ignored.++__Warning:__+The router process holds on to a reference to each measure @i@ for each child+process, even after that child process has stopped.++==== __Examples__++>>> run $ liftRouter (Just . even) (\case {True -> mapping (+1); False -> echo}) <~ source [1,2,3,4,5]+[1,3,3,5,5]++>>> run $ liftRouter (Just . even) (\case {True -> echo; False -> stopped}) <~ source [1,2,3,4,5]+[2,4]++>>> run $ liftRouter (Just . even) (\case {True -> echo; False -> taking 1}) <~ source [1,2,3,4,5]+[1,2,4]+-}+liftRouter ::+  forall m i a b.+  (Monad m, Hashable i) =>+  -- | Function to measure.+  (a -> Maybe i) ->+  -- | Function to spawn child processors.+  (i -> ProcessT m a b) ->+  ProcessT m a b+liftRouter measure spawn = awaiting M.empty+ where+  awaiting :: HashMap i (Child (ProcessT m a b)) -> ProcessT m a b+  awaiting st = MachineT . pure $ Await onNext Refl onStop+   where+    onNext :: a -> MachineT m (Is a) b+    onNext a = case measure a of+      Nothing -> awaiting st+      Just i ->+        case fromMaybe (ChildRunning $ spawn i) (M.lookup i st) of+          ChildRunning p ->+            provideThen a p $ \p' ->+              let !st' = M.insert i p' st+               in awaiting st'+          ChildStopped ->+            awaiting st++    onStop :: MachineT m (Is a) b+    onStop = foldr starve stopped (concatMap toList . M.elems $ st)++  provideThen :: a -> ProcessT m a b -> (Child (ProcessT m a b) -> ProcessT m a b) -> ProcessT m a b+  provideThen a p k =+    MachineT $+      runMachineT p >>= \case+        Stop -> runMachineT (k ChildStopped)+        Yield o p' -> pure (Yield o (provideThen a p' k))+        Await onNext Refl _onStop -> runMachineT (exhaustThen (onNext a) k)++  exhaustThen :: ProcessT m a b -> (Child (ProcessT m a b) -> ProcessT m a b) -> ProcessT m a b+  exhaustThen p k =+    MachineT $+      runMachineT p >>= \case+        Yield o p' -> pure (Yield o (k $ ChildRunning p'))+        p' -> runMachineT (k (ChildRunning $ encased p'))++{- |+Internal helper.+A wrapper for child processes spawned by `liftRouter`.+-}+data Child a+  = ChildRunning !a+  | ChildStopped+  deriving (Functor, Foldable)++-------------------------------------------------------------------------------+-- Event stream sorting+-------------------------------------------------------------------------------++{- |+Sort items in @N@ successive batches.++If the maximum key in batch @i@ is guaranteed to be smaller than the minimum+key in batch @i + 2N@, this process produces a totally ordered stream of items.++The process @`sortByBatch` key@ caches @N@ batches of items, sorts them+together, and yields only those items whose key is less than or equal+to the maximum key in the first batch.++==== __Examples__++>>> run $ sortByBatch @Int id <~ source [[1,4],[7,2,3,5],[6,8]]+[[1,2,3,4],[5,6,7],[8]]++>>> run $ sortByBatch @Int id <~ source [[1,7],[4,2,3,5],[6,8]]+[[1,2,3,4,5,7],[6,8]]+-}+sortByBatch ::+  forall a k.+  (Bounded k, Ord k) =>+  (a -> k) ->+  Process [a] [a]+sortByBatch key = sortByBatchWith Nothing+ where+  sortByBatchWith ::+    forall m.+    (Monad m) =>+    Maybe [a] ->+    ProcessT m [a] [a]+  sortByBatchWith = \case+    Nothing -> MachineT $ pure $ Await onNext Refl onStop+     where+      onNext :: [a] -> ProcessT m [a] [a]+      onNext new = sortByBatchWith (Just sortedNew)+       where+        sortedNew = sortByKey new+      onStop :: ProcessT m [a] [a]+      onStop = stopped+    Just sortedOld -> MachineT $ pure $ Await onNext Refl onStop+     where+      onNext :: [a] -> ProcessT m [a] [a]+      onNext new+        | null sortedOld = sortByBatchWith $ Just sortedNew+        | otherwise = MachineT $ pure $ Yield sortedBeforeCutoff $ sortByBatchWith $ Just sortedAfterCutoff+       where+        -- NOTE: use of partial @maximum@ is guarded by the check @null old@.+        cutoff = getMax (foldMap (Max . key) sortedOld)+        sortedNew = sortByKey new+        sorted = joinByKey sortedOld sortedNew+        (sortedBeforeCutoff, sortedAfterCutoff) = L.partition ((<= cutoff) . key) sorted+      onStop :: ProcessT m [a] [a]+      onStop = MachineT $ pure $ Yield sortedOld $ stopped++  compByKey :: a -> a -> Ordering+  compByKey = compare `on` key++  sortByKey :: [a] -> [a]+  sortByKey = L.sortBy compByKey++  joinByKey {- Sorted -} :: [a {- Sorted -}] -> [a {- Sorted -}] -> [a]+  joinByKey [] ys = ys+  joinByKey xs [] = xs+  joinByKey (x : xs) (y : ys)+    | compByKey x y == LT = x : joinByKey xs (y : ys)+    | otherwise = y : joinByKey (x : xs) ys++{- |+Sort items between successive ticks.++If the maximum key in batch @i@ is guaranteed to be smaller than the minimum+key in batch @i + 2@, this process produces a totally ordered stream of items.++==== __Examples__++>>> run $ sortByTick @Int id <~ source [Item 1,Item 4,Tick,Item 7,Item 2,Item 3,Item 5,Tick,Item 6,Item 8]+[Tick,Item 1,Item 2,Item 3,Item 4,Tick,Item 5,Item 6,Item 7,Item 8]++>>> run $ sortByTick @Int id <~ source [Item 1,Item 7,Tick,Item 4,Item 2,Item 3,Item 5,Tick,Item 6,Item 8]+[Tick,Item 1,Item 2,Item 3,Item 4,Item 5,Item 7,Tick,Item 6,Item 8]+-}+sortByTick ::+  forall a k.+  (Bounded k, Ord k) =>+  (a -> k) ->+  Process (Tick a) (Tick a)+sortByTick key =+  mapping (fmap D.singleton)+    ~> batchByTick+    ~> mapping (fmap D.toList)+    ~> liftTick (sortByBatch key ~> asParts)++{- |+Sort items between @2*K@ successive ticks.++If the maximum key in batch @i@ is guaranteed to be smaller than the minimum+key in batch @i + K@, this process produces a totally ordered stream of items.++==== __Examples__++>>> run $ sortByTicks @Int id 2 <~ source [Item 2,Tick,Item 1,Tick,Item 4,Tick,Item 3,Tick]+[Tick,Tick,Tick,Item 1,Item 2,Tick,Item 3,Item 4]++>>> run $ sortByTicks @Int id 2 <~ source [Item 1,Tick,Item 3,Tick,Item 2,Tick,Item 4,Tick]+[Tick,Tick,Tick,Item 1,Item 2,Item 3,Tick,Item 4]++>>> run $ sortByTicks @Int id 2 <~ source [Item 1,Tick,Item 4,Tick,Item 2,Tick,Item 3,Tick]+[Tick,Tick,Tick,Item 1,Item 2,Item 3,Item 4,Tick]+-}+sortByTicks ::+  forall a k.+  (Bounded k, Ord k) =>+  (a -> k) ->+  Int ->+  Process (Tick a) (Tick a)+sortByTicks key ticks =+  mapping (fmap D.singleton)+    ~> batchByTicks ticks+    ~> mapping (fmap D.toList)+    ~> liftTick (sortByBatch key ~> asParts)++-------------------------------------------------------------------------------+-- Aggregation+-------------------------------------------------------------------------------++deltaToCumulative :: forall m f a. (Monad m, Traversable f, Monoid a) => ProcessT m (f a) (f a)+deltaToCumulative = construct $ go mempty+ where+  go :: a -> Plan (Is (f a)) (f a) ()+  go acc =+    await >>= \fa -> do+      -- Add the cumulative sum to the value in the item.+      let (!fa', !acc') = flip runState acc . for fa $ \a -> do+            a' <- (a <>) <$> get; put a'; pure a'+      -- Yield the updated item.+      yield fa'+      -- Continue with the new cumulative sum.+      go acc'++-------------------------------------------------------------------------------+-- Filtering semaphores+-------------------------------------------------------------------------------++{- |+A delimiting t`Moore` machine based on constant open/close markers.++The machine @`between` o c@ consumes consumes a stream of items, and produces+a stream of `Bool` that is `False` up to and including the first occurrence of+@o@, then is `True` up to and including the first occurrence of @c@, and then+is `False` forever.++==== __Examples__++>>> run $ auto (betweenEach (2, 4)) <~ source [1, 2, 3, 4, 5]+[False,False,True,True,False,False]++>>> run $ auto (betweenEach (2, 4)) <~ source [2, 3, 4, 2, 3, 4]+[False,True,True,False,True,True,False]+-}+betweenEach :: (Eq a) => (a, a) -> Moore a Bool+betweenEach (open, close) = beforeOpen+ where+  beforeOpen = Moore False $ \a ->+    if a == open then betweenOpenAndClose else beforeOpen+  betweenOpenAndClose = Moore True $ \a ->+    if a == close then beforeOpen else betweenOpenAndClose++{- |+A delimiting t`Moore` machine based on constant open/close markers.++The machine @`between` o c@ consumes consumes a stream of items, and produces+a stream of `Bool` that is `False` up to and including the first occurrence of+@o@, then is `True` up to and including the first occurrence of @c@, and then+is `False` forever.++==== __Examples__++>>> run $ auto (betweenFirst (2, 4)) <~ source [1, 2, 3, 4, 5]+[False,False,True,True,False,False]++>>> run $ auto (betweenFirst (2, 4)) <~ source [2, 3, 4, 2, 3, 4]+[False,True,True,False,False,False,False]+-}+betweenFirst :: (Eq a) => (a, a) -> Moore a Bool+betweenFirst (open, close) = beforeFirstOpen+ where+  beforeFirstOpen = Moore False $ \a ->+    if a == open then betweenFirstOpenAndClose else beforeFirstOpen+  betweenFirstOpenAndClose = Moore True $ \a ->+    if a == close then afterFirstClose else betweenFirstOpenAndClose+  afterFirstClose = Moore False (const afterFirstClose)++{- |+Filter the items in a stream based on a t`Moore` machine.++==== __Examples__++>>> run $ delimit (betweenEach (2, 4)) <~ source [1, 2, 3, 4, 5]+[2,3,4]++>>> run $ delimit (betweenEach (2, 4)) <~ source [2, 3, 4, 2, 3, 4]+[2,3,4,2,3,4]++>>> run $ delimit (betweenFirst (2, 4)) <~ source [1, 2, 3, 4, 5]+[2,3,4]++>>> run $ delimit (betweenFirst (2, 4)) <~ source [2, 3, 4, 2, 3, 4]+[2,3,4]+-}+delimit ::+  forall m a.+  (Monad m) =>+  Moore a Bool ->+  ProcessT m a a+delimit = construct . go+ where+  go ::+    Moore a Bool ->+    PlanT (Is a) a m Void+  go _st@(Moore wasOpen onNext) =+    await >>= \a -> do+      -- Feed the item to the delimiting Moore machine.+      let st'@(Moore willBeOpen _) = onNext a+      -- If the state has changed, i.e., @wasOpen /= willBeOpen@, then+      -- the current item is a marker. All markers should be yielded.+      let isMarker = wasOpen /= willBeOpen+      when (wasOpen || isMarker) $ yield a+      go st'
+ src-lib/GHC/Eventlog/Live/Machine/Decoder.hs view
@@ -0,0 +1,52 @@+{- |+Module      : GHC.Eventlog.Live.Machine.Decoder+Description : Machines for processing eventlog data.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Machine.Decoder (+  -- * Event decoding+  decodeEvent,+  decodeEventBatch,+) where++import Control.Monad.Trans.Class (MonadTrans (..))+import Data.ByteString qualified as BS+import Data.Machine (Is, PlanT, ProcessT, await, construct, yield)+import Data.Text qualified as T+import GHC.Eventlog.Live.Logger (Logger, logError)+import GHC.Eventlog.Live.Machine.Core (Tick (..), liftTick)+import GHC.RTS.Events (Event)+import GHC.RTS.Events.Incremental (Decoder (..), decodeEventLog)++-------------------------------------------------------------------------------+-- Decoding events++{- |+Parse t'Event's from a stream of 'BS.ByteString' chunks with ticks.++Throws a t'DecodeError' on error.+-}+decodeEvent ::+  forall m.+  (Monad m) =>+  Logger m ->+  ProcessT m BS.ByteString Event+decodeEvent logger = construct $ loop decodeEventLog+ where+  loop :: Decoder a -> PlanT (Is BS.ByteString) a m ()+  loop Done{} = pure ()+  loop (Consume k) = await >>= \chunk -> loop (k chunk)+  loop (Produce a d') = yield a >> loop d'+  loop (Error _ err) = lift $ logError logger $ T.pack err++{- |+Parse 'Event's from a stream of 'BS.ByteString' chunks with ticks.++Throws 'DecodeError' on error.+-}+decodeEventBatch ::+  (Monad m) =>+  Logger m ->+  ProcessT m (Tick BS.ByteString) (Tick Event)+decodeEventBatch logger = liftTick $ decodeEvent logger
+ src-lib/GHC/Eventlog/Live/Machine/Sink.hs view
@@ -0,0 +1,42 @@+{- |+Module      : GHC.Eventlog.Live.Machine.Sink+Description : Machines for processing eventlog data.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Machine.Sink (+  -- * Eventlog file sink+  fileSink,+  fileSinkBatch,+) where++import Control.Monad.IO.Class (MonadIO (..))+import Data.ByteString qualified as BS+import Data.Machine (ProcessT, await, repeatedly, (~>))+import Data.Void (Void)+import GHC.Eventlog.Live.Machine.Core (Tick (..), dropTick)+import System.IO (Handle)++-------------------------------------------------------------------------------+-- Log file sink++{- |+File sink for optional eventlog log file.+-}+fileSink ::+  (MonadIO m) =>+  Handle ->+  ProcessT m BS.ByteString Void+fileSink handle = repeatedly $ await >>= liftIO . BS.hPut handle++-------------------------------------------------------------------------------+-- Log file sink with batches++{- |+File sink for optional eventlog log file.+-}+fileSinkBatch ::+  (MonadIO m) =>+  Handle ->+  ProcessT m (Tick BS.ByteString) Void+fileSinkBatch handle = dropTick ~> fileSink handle
+ src-lib/GHC/Eventlog/Live/Machine/Source.hs view
@@ -0,0 +1,90 @@+{- |+Module      : GHC.Eventlog.Live.Machine.Source+Description : Machines for processing eventlog data.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Machine.Source (+  -- * Eventlog source+  eventlogSourceTick,+  defaultChunkSizeBytes,+) where++import Control.Monad.IO.Class (MonadIO (..))+import Data.ByteString qualified as BS+import Data.Machine (MachineT (..), construct, yield)+import Data.Word (Word64)+import GHC.Clock (getMonotonicTimeNSec)+import GHC.Eventlog.Live.Machine.Core (Tick (..), TickInfo (..))+import GHC.Eventlog.Live.Source.Core (EventlogSourceData (..), EventlogSourceHandle, recv)++{- |+A source which reads chunks from a `Handle`.+When input is available, it yields an v`Item`.+It yields a v`Tick` at each increment of the batch interval.+-}+eventlogSourceTick ::+  (MonadIO m) =>+  -- | The batch interval in milliseconds.+  Int ->+  -- | The number of bytes to read.+  Int ->+  -- | The eventlog source handle.+  EventlogSourceHandle ->+  MachineT m k (Tick BS.ByteString)+eventlogSourceTick batchIntervalMilli chunkSizeBytes h =+  construct $ start 0+ where+  batchIntervalMicro = milliToMicro batchIntervalMilli++  start tick = do+    startTimeMicro <- liftIO getMonotonicTimeMicro+    batch tick startTimeMicro++  batch tick startTimeMicro = batchLoop+   where+    getRemainingTimeMicro = do+      currentTimeMicro <- liftIO getMonotonicTimeMicro+      pure $ (startTimeMicro + batchIntervalMicro) - currentTimeMicro++    batchLoop = do+      remainingTimeMicro <- getRemainingTimeMicro+      if remainingTimeMicro <= 0+        then do+          yield TickWithInfo{tickInfo = TickInfo{tick}}+          start (tick + 1)+        else do+          liftIO (recv h remainingTimeMicro chunkSizeBytes) >>= \case+            EventlogSourceData chunk -> yield (Item chunk) >> batchLoop+            EventlogSourceTimeout -> batchLoop+            EventlogSourceClosed -> pure ()++{- |+Eventlog chunk size in bytes.+This should be equal to the page size.+-}+defaultChunkSizeBytes :: Int+defaultChunkSizeBytes = 4096++{- |+Internal helper.+Return monotonic time in microseconds, since some unspecified starting point+-}+getMonotonicTimeMicro :: IO Int+getMonotonicTimeMicro = nanoToMicro <$> getMonotonicTimeNSec++{- |+Internal helper.+Convert nanoseconds to microseconds.+If the size of @Int@ is at least as big as that of @Word64@, then+the conversion from 'Word64' to 'Int' is safe, due to the division by 1000.+-}+nanoToMicro :: Word64 -> Int+nanoToMicro = fromIntegral . (`div` 1_000)++{- |+Internal helper.+Convert milliseconds to microseconds.+-}+milliToMicro :: Int -> Int+milliToMicro = (* 1_000)
+ src-lib/GHC/Eventlog/Live/Machine/Validate.hs view
@@ -0,0 +1,115 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.Machine.Validate+Description : Core machines for processing data in batches.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Machine.Validate (+  -- * Validation+  validateInput,+  validateOrder,+  validateTicks,+) where++import Control.Monad.Trans.Class (MonadTrans (..))+import Data.Foldable (for_)+import Data.Machine (ProcessT, await, construct)+import Data.Text qualified as T+import GHC.Eventlog.Live.Logger (Logger, logDebug, logError, logTrace, logWarn)+import GHC.Eventlog.Live.Machine.Core (Tick (..), TickInfo (..))+import Text.Printf (printf)++-------------------------------------------------------------------------------+-- Validation+--+-- TODO: These machines, or at least the error messages that they print, are+--       specific to eventlog processing. Hence, they should be moved.+-------------------------------------------------------------------------------++{- |+This machine validates that there is some input.++If no input is encountered after the given number of ticks, the machine prints+a warning that directs the user to check that the @-l@ flag was set correctly.+-}+validateInput ::+  (Monad m) =>+  Logger m ->+  Int ->+  ProcessT m (Tick a) x+validateInput logger ticks = construct $ start ticks+ where+  start remaining+    | remaining <= 0 = do+        let msg = printf "No input after %d ticks. Did you pass -l to the GHC RTS?" ticks+        lift $ logWarn logger $ T.pack msg+        pure ()+    | otherwise = do+        let msg = "Waiting for " <> T.pack (show remaining) <> " more ticks before showing input warning."+        lift $ logDebug logger $ msg+        await >>= \case+          Item{} ->+            lift $ logDebug logger $ "Received item. Cancelled input warning."+          Tick ->+            start (pred remaining)++{- |+This machine validates that the inputs are received in order.++If an out-of-order input is encountered, the machine prints an error message+that directs the user to check that the @--eventlog-flush-interval@ flag is+set correctly.+-}+validateOrder ::+  (Monad m, Ord k, Show a) =>+  Logger m ->+  (a -> k) ->+  ProcessT m a x+validateOrder logger timestamp = construct $ go Nothing+ where+  go maybeOld =+    await >>= \new ->+      case maybeOld of+        Just old+          | timestamp new < timestamp old -> do+              let msg1 =+                    "Encountered two out-of-order inputs.\n\+                    \Did you pass --eventlog-flush-interval=SECONDS to the GHC RTS?\n\+                    \Did you pass the same flag to this program?"+              lift $ logError logger $ T.pack msg1+              let msg2 =+                    printf+                      "Out-of-order inputs:\n\+                      \- %s\n\+                      \- %s"+                      (show old)+                      (show new)+              lift $ logDebug logger $ T.pack msg2+        _otherwise -> do+          go (Just new)++{- |+This machine validates that ticks are unique and increasing.+-}+validateTicks ::+  (Monad m) =>+  Logger m ->+  ProcessT m (Tick a) (Tick a)+validateTicks logger = construct $ go Nothing+ where+  go maybeTick =+    await >>= \case+      Item _ ->+        go maybeTick+      TickWithInfo{tickInfo = TickInfo{tick = tick'}} -> do+        for_ maybeTick $ \case+          tick+            | tick' == tick + 1 -> do+                let msg = "Saw tick " <> T.pack (show tick) <> "."+                lift $ logTrace logger $ msg+            | otherwise -> do+                let msg = "Encountered non-increasing ticks " <> T.pack (show tick) <> " and " <> T.pack (show tick') <> "."+                lift $ logError logger $ msg+        go (Just tick')
+ src-lib/GHC/Eventlog/Live/Machine/WithStartTime.hs view
@@ -0,0 +1,95 @@+{- |+Module      : GHC.Eventlog.Live.Machine.WithStartTime+Description : Machines for processing eventlog data.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Machine.WithStartTime (+  TimeUnixNano,+  WithStartTime (..),+  setWithStartTime'value,+  tryGetTimeUnixNano,+  withStartTime,+  withStartTime',+  dropStartTime,+) where++import Control.Monad (forever)+import Data.Machine (Is (..), PlanT, Process, await, construct, mapping, yield)+import Data.Word (Word64)+import GHC.RTS.Events (Event (..), EventInfo)+import GHC.RTS.Events qualified as E++-------------------------------------------------------------------------------+-- Start time++{- |+Time in nanoseconds since the Unix epoch.+-}+type TimeUnixNano = Word64++{- |+Data decorated with a start time in nanoseconds since the Unix epoch.+-}+data WithStartTime a = WithStartTime+  { value :: !a+  , maybeStartTimeUnixNano :: !(Maybe TimeUnixNano)+  }+  deriving (Functor, Show)++{- |+Setter for the value of a t`WithStartTime`+-}+setWithStartTime'value :: WithStartTime a -> b -> WithStartTime b+setWithStartTime'value (WithStartTime _a t) b = WithStartTime b t++{- |+If the event has a start time, return `Just` the time of the event in+nanoseconds since the Unix epoch. Otherwise, return `Nothing`.+-}+tryGetTimeUnixNano :: WithStartTime Event -> Maybe TimeUnixNano+tryGetTimeUnixNano i = (i.value.evTime +) <$> i.maybeStartTimeUnixNano++{- |+Wrap every event in t`WithStartTime`. Every event after `E.WallClockTime` will+have its start time field set to `Just` the process start time.++This machine swallows the first and only `E.WallClockTime` event.+-}+withStartTime :: Process Event (WithStartTime Event)+withStartTime = withStartTime' E.evSpec WithStartTime++{- |+Generalised version of `withStartTime` that can be adapted to work on arbitrary+types using a getter and a setter.+-}+withStartTime' :: (a -> EventInfo) -> (a -> Maybe TimeUnixNano -> b) -> Process a b+withStartTime' getEventInfo setStartTime = construct start+ where+  start =+    await >>= \case+      value+        -- The `WallClockTime` event announces the wall-clock time at which the+        -- process was started.+        | E.WallClockTime{..} <- getEventInfo value -> do+            -- This will start overflowing on Sunday, 21 July 2554 23:34:33, UTC.+            let !startTimeNs = sec * 1_000_000_000 + fromIntegral nsec+            -- We do not re-emit the `WallClockTime` event.+            continue startTimeNs+        | otherwise ->+            yield (value `setStartTime` Nothing) >> start+  continue startTimeUnixNano =+    mappingPlan $ \value ->+      value `setStartTime` Just startTimeUnixNano++{- |+Drop the t`WithStartTime` wrapper.+-}+dropStartTime :: Process (WithStartTime a) a+dropStartTime = mapping (.value)++{- |+Internal helper. Variant of `mapping` for plans.+-}+mappingPlan :: (a -> b) -> PlanT (Is a) b m a+mappingPlan f = forever (await >>= \a -> yield (f a))
+ src-lib/GHC/Eventlog/Live/Options.hs view
@@ -0,0 +1,182 @@+{- |+Module      : GHC.Eventlog.Live.Options+Description : Command-line option parsers for eventlog machines.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Options (+  eventlogSourceOptionsParser,+  eventlogSocketTimeoutSParser,+  eventlogSocketTimeoutExponentParser,+  heapProfBreakdownParser,+  eventlogLogFileParser,+  eventlogFlushIntervalSParser,+  verbosityParser,+) where++import Control.Applicative (asum)+import GHC.Eventlog.Live.Source.Core (EventlogSocketAddr (..), EventlogSourceOptions (..))+import GHC.Eventlog.Live.Types.HeapProfBreakdown (heapProfBreakdownEitherReader)+import GHC.Eventlog.Live.Types.Severity (Severity (..), fromSeverityString)+import GHC.RTS.Events (HeapProfBreakdown (..))+import Options.Applicative qualified as O+import Options.Applicative.Help.Pretty qualified as OP++--------------------------------------------------------------------------------+-- Eventlog Source++{- |+Parser for the eventlog socket.+-}+eventlogSourceOptionsParser :: O.Parser EventlogSourceOptions+eventlogSourceOptionsParser =+  asum+    [ stdinParser+    , fileParser+    , socketParser+    ]+ where+  stdinParser =+    EventlogSourceOptionsStdin+      <$ O.flag'+        ()+        ( O.long "eventlog-stdin"+            <> O.help "Read the eventlog from stdin."+        )+  fileParser =+    EventlogSourceOptionsFile+      <$> O.strOption+        ( O.long "eventlog-file"+            <> O.metavar "FILE"+            <> O.help "Read the eventlog from a file."+        )+  socketParser =+    EventlogSourceOptionsSocket+      <$> asum+        [ socketUnixParser+        , socketInetParser+        ]+  socketUnixParser =+    EventlogSocketUnixAddr+      <$> O.strOption+        ( O.long "eventlog-socket"+            <> O.metavar "SOCKET"+            <> O.help "Read the eventlog from a Unix socket."+        )+  socketInetParser =+    EventlogSocketInetAddr+      <$> socketInetHostParser+      <*> socketInetPortParser++  socketInetHostParser =+    O.strOption+      ( O.long "eventlog-socket-host"+          <> O.metavar "HOST"+          <> O.help "Read the eventlog from a TCP/IP socket."+      )+  socketInetPortParser =+    O.strOption+      ( O.long "eventlog-socket-port"+          <> O.metavar "PORT"+          <> O.help "Read the eventlog from a TCP/IP socket."+      )++{- |+Parser for the intial timeout for exponential backoff.+-}+eventlogSocketTimeoutSParser :: O.Parser Double+eventlogSocketTimeoutSParser =+  O.option+    O.auto+    ( O.long "eventlog-socket-timeout"+        <> O.metavar "SECONDS"+        <> O.help "Eventlog socket connection retry timeout in seconds."+        <> O.value 1+    )++{- |+Parser for the exponent for exponential backoff.+-}+eventlogSocketTimeoutExponentParser :: O.Parser Double+eventlogSocketTimeoutExponentParser =+  O.option+    O.auto+    ( O.long "eventlog-socket-exponent"+        <> O.metavar "NUMBER"+        <> O.help "Eventlog socket connection retry timeout exponent."+        <> O.value 1+    )++--------------------------------------------------------------------------------+-- Heap Profile Breakdown++{- |+Parser for the heap profile breakdown.+-}+heapProfBreakdownParser :: O.Parser HeapProfBreakdown+heapProfBreakdownParser =+  O.option (O.eitherReader heapProfBreakdownEitherReader) . mconcat $+    [ O.short 'h'+    , O.metavar "Tcmdyrbi"+    , O.helpDoc . Just . OP.vcat . fmap OP.pretty $+        [ "Heap profile breakdown."+        , "Should match the option passed to the application."+        ]+    ]++--------------------------------------------------------------------------------+-- Eventlog Log File++{- |+Parser for the eventlog log file.+-}+eventlogLogFileParser :: O.Parser FilePath+eventlogLogFileParser =+  O.strOption+    ( O.long "eventlog-log-file"+        <> O.metavar "FILE"+        <> O.help "Use file to log binary eventlog data."+    )++--------------------------------------------------------------------------------+-- Batch Interval++{- |+Parser for the eventlog flush interval.+-}+eventlogFlushIntervalSParser :: O.Parser Double+eventlogFlushIntervalSParser =+  O.option O.auto . mconcat $+    [ O.long "eventlog-flush-interval"+    , O.metavar "SECONDS"+    , O.helpDoc . Just . OP.vcat . fmap OP.pretty $+        [ "Eventlog flush interval in seconds."+        , "Should match the option passed to the application."+        ]+    , O.value defaultEventlogFlushIntervalS+    ]++{- |+Internal helper.+The default interval in which the eventlog is flushed in seconds.+-}+defaultEventlogFlushIntervalS :: Double+defaultEventlogFlushIntervalS = 1++--------------------------------------------------------------------------------+-- Verbosity++{- |+Parser for `Severity`+The default severity is `WARN`.+-}+verbosityParser :: O.Parser Severity+verbosityParser =+  O.option+    (O.maybeReader fromSeverityString)+    ( O.short 'v'+        <> O.long "verbosity"+        <> O.metavar "fatal|error|warning|info|debug|trace"+        <> O.help "The severity threshold for logging."+        <> O.value WARN+    )
+ src-lib/GHC/Eventlog/Live/Processor.hs view
@@ -0,0 +1,233 @@+{-# LANGUAGE OverloadedStrings #-}++module GHC.Eventlog.Live.Processor (+  Resource (..),+  Telemetry (..),+  toSomeLogs,+  toSomeMetrics,+  toSomeSamples,+  toSomeSpans,+  ExportRequest (..),+  InstrumentationScope (..),+  processEventlogTelemetry,+  processInternalTelemetry,+) where++import Data.Aeson.Types (Encoding, KeyValue (..), ToJSON (..), Value (..), pairs)+import Data.Coerce (coerce)+import Data.DList qualified as D+import Data.Machine (ProcessT, asParts, mapping, (~>))+import Data.Monoid (Sum (..))+import Data.Proxy (Proxy (..))+import Data.Text (Text)+import Data.Version (Version)+import GHC.Eventlog.Live.Config (FullConfig (..))+import GHC.Eventlog.Live.Logger (ExportResult (..), InternalMetric (..), InternalTelemetry (..), Logger, Scoped (..))+import GHC.Eventlog.Live.Machine.Core (Tick, deltaToCumulative)+import GHC.Eventlog.Live.Machine.Core qualified as M+import GHC.Eventlog.Live.Machine.WithStartTime (WithStartTime)+import GHC.Eventlog.Live.Processor.Core.Logs qualified as CL+import GHC.Eventlog.Live.Processor.Core.Metrics (MetricProcessors (..), select)+import GHC.Eventlog.Live.Processor.Core.Metrics qualified as CM+import GHC.Eventlog.Live.Processor.Heap (processHeapEvents)+import GHC.Eventlog.Live.Processor.Logs (processLogEvents)+import GHC.Eventlog.Live.Processor.Profiles (processProfileEvents)+import GHC.Eventlog.Live.Processor.Threads (processThreadEvents)+import GHC.Eventlog.Live.Types.Attribute (Attrs, IsAttrValue (toAttrValue))+import GHC.Eventlog.Live.Types.Logs (LogRecord (..), SomeLogs)+import GHC.Eventlog.Live.Types.Metrics (Metric, SomeMetrics)+import GHC.Eventlog.Live.Types.Profiles (SomeSamples)+import GHC.Eventlog.Live.Types.Traces (SomeSpans)+import GHC.RTS.Events (Event (..), HeapProfBreakdown)+import IpeDB.Database qualified as DB+import IpeDB.Types.CostCentre qualified as CC+import IpeDB.Types.InfoProv qualified as IP++newtype Resource+  = Resource {attrs :: Attrs}+  deriving newtype (ToJSON)++data InstrumentationScope+  = InstrumentationScope {name :: Text, version :: Version}++instance ToJSON InstrumentationScope where+  toJSON :: InstrumentationScope -> Value+  toJSON = Object . instrumentationScopeToKV++  toEncoding :: InstrumentationScope -> Encoding+  toEncoding = pairs . instrumentationScopeToKV++instrumentationScopeToKV :: (KeyValue e kv, Monoid kv) => InstrumentationScope -> kv+instrumentationScopeToKV s =+  mconcat+    [ "name" .= s.name+    , "version" .= toAttrValue s.version+    ]+{-# INLINE instrumentationScopeToKV #-}++data Telemetry+  = Telemetry'Logs SomeLogs+  | Telemetry'Metrics SomeMetrics+  | Telemetry'Samples SomeSamples+  | Telemetry'Spans SomeSpans++toSomeLogs :: Telemetry -> Maybe SomeLogs+toSomeLogs = \case Telemetry'Logs x -> Just x; _ -> Nothing++toSomeMetrics :: Telemetry -> Maybe SomeMetrics+toSomeMetrics = \case Telemetry'Metrics x -> Just x; _ -> Nothing++toSomeSamples :: Telemetry -> Maybe SomeSamples+toSomeSamples = \case Telemetry'Samples x -> Just x; _ -> Nothing++toSomeSpans :: Telemetry -> Maybe SomeSpans+toSomeSpans = \case Telemetry'Spans x -> Just x; _ -> Nothing++instance ToJSON Telemetry where+  toJSON :: Telemetry -> Value+  toJSON = \case+    Telemetry'Logs x -> toJSON x+    Telemetry'Metrics x -> toJSON x+    Telemetry'Spans x -> toJSON x+    Telemetry'Samples x -> toJSON x++  toEncoding :: Telemetry -> Encoding+  toEncoding = \case+    Telemetry'Logs x -> toEncoding x+    Telemetry'Metrics x -> toEncoding x+    Telemetry'Spans x -> toEncoding x+    Telemetry'Samples x -> toEncoding x++data ExportRequest = ExportRequest+  { resource :: !Resource+  , scope :: !InstrumentationScope+  , telemetry :: ![Telemetry]+  }++exportRequestToKV :: (KeyValue e kv, Monoid kv) => ExportRequest -> kv+exportRequestToKV r =+  mconcat+    [ "resource" .= r.resource+    , "scope" .= r.scope+    , "telemetry" .= r.telemetry+    ]+{-# INLINE exportRequestToKV #-}++instance ToJSON ExportRequest where+  toJSON :: ExportRequest -> Value+  toJSON = Object . exportRequestToKV++  toEncoding :: ExportRequest -> Encoding+  toEncoding = pairs . exportRequestToKV++-- Create machine that processes eventlog data into telemetry data+processEventlogTelemetry ::+  Logger IO ->+  FullConfig ->+  Resource ->+  InstrumentationScope ->+  Maybe HeapProfBreakdown ->+  DB.Table CC.CostCentreId CC.CostCentre ->+  DB.Table IP.InfoProvId IP.InfoProv ->+  ProcessT IO (Tick (WithStartTime Event)) (Tick ExportRequest)+processEventlogTelemetry logger fullConfig resource scope maybeHeapProfBreakdown ccdb ipedb =+  M.fanoutTick+    [ -- Process the heap events.+      processHeapEvents logger (Just ipedb) maybeHeapProfBreakdown fullConfig+        ~> mapping (fmap (fmap Telemetry'Metrics))+    , -- Process the log events.+      processLogEvents fullConfig+        ~> mapping (fmap (fmap Telemetry'Logs))+    , -- Process the thread events.+      processThreadEvents logger fullConfig+        ~> mapping (fmap (fmap (either Telemetry'Metrics Telemetry'Spans)))+    , -- Process the profile events.+      processProfileEvents logger ccdb ipedb fullConfig+        ~> mapping (fmap (fmap Telemetry'Samples))+    ]+    ~> M.liftTick (mapping $ ExportRequest resource scope . D.toList)++{- |+Create the machine that processes internal telemetry data++NOTE: This process only takes a stream of inputs to use their tick.+-}+processInternalTelemetry ::+  FullConfig ->+  Resource ->+  InstrumentationScope ->+  ProcessT IO (Tick (Scoped InternalTelemetry)) (Tick ExportRequest)+processInternalTelemetry fullConfig resource scope =+  mapping (fmap (.unScope))+    ~> M.fanoutTick+      [ -- Process internal log messages.+        CL.process (Proxy @"internalLogMessage") processLogRecords fullConfig+          ~> M.liftTick (mapping $ D.singleton . Telemetry'Logs)+      , -- Process internal metrics.+        M.fanoutTick+          [ -- Process internal event counts.+            CM.process (Proxy @"internalEventCount") processEventCount fullConfig+              ~> M.liftTick (mapping D.singleton)+          , -- Process internal exported log counts.+            CM.processAllWith fullConfig processExportLogs $+              select (Proxy @"internalExportedLogs") (.exported)+                :&: select (Proxy @"internalRejectedLogs") (.rejected)+                :&: End+          , -- Process internal exported metric counts.+            CM.processAllWith fullConfig processExportMetrics $+              select (Proxy @"internalExportedMetrics") (.exported)+                :&: select (Proxy @"internalRejectedMetrics") (.rejected)+                :&: End+          , -- Process internal exported sample counts.+            CM.processAllWith fullConfig processExportSamples $+              select (Proxy @"internalExportedSamples") (.exported)+                :&: select (Proxy @"internalRejectedSamples") (.rejected)+                :&: End+          , -- Process internal exported span counts.+            CM.processAllWith fullConfig processExportSpans $+              select (Proxy @"internalExportedSpans") (.exported)+                :&: select (Proxy @"internalRejectedSpans") (.rejected)+                :&: End+          ]+          ~> M.liftTick (mapping (fmap Telemetry'Metrics))+      ]+    ~> M.liftTick (mapping $ ExportRequest resource scope . D.toList)+ where+  processLogRecords =+    mapping getLogRecord ~> asParts+   where+    getLogRecord :: InternalTelemetry -> Maybe LogRecord+    getLogRecord = \case InternalTelemetry'LogRecord l -> Just l; _ -> Nothing++  processEventCount =+    mapping (coerce @_ @(Maybe (Metric (Sum Word))) . getEventCount)+      ~> asParts+      ~> deltaToCumulative @_ @Metric @(Sum Word)+      ~> mapping (coerce @_ @(Metric Word))+   where+    getEventCount :: InternalTelemetry -> Maybe (Metric Word)+    getEventCount = \case InternalTelemetry'Metric EventCount m -> Just m; _ -> Nothing++  processExportLogs =+    mapping getExportLogs ~> asParts ~> deltaToCumulative+   where+    getExportLogs :: InternalTelemetry -> Maybe (Metric ExportResult)+    getExportLogs = \case InternalTelemetry'Metric ExportLogs m -> Just m; _ -> Nothing++  processExportMetrics =+    mapping getExportMetrics ~> asParts ~> deltaToCumulative+   where+    getExportMetrics :: InternalTelemetry -> Maybe (Metric ExportResult)+    getExportMetrics = \case InternalTelemetry'Metric ExportMetrics m -> Just m; _ -> Nothing++  processExportSpans =+    mapping getExportSpans ~> asParts ~> deltaToCumulative+   where+    getExportSpans :: InternalTelemetry -> Maybe (Metric ExportResult)+    getExportSpans = \case InternalTelemetry'Metric ExportSpans m -> Just m; _ -> Nothing++  processExportSamples =+    mapping getExportSamples ~> asParts ~> deltaToCumulative+   where+    getExportSamples :: InternalTelemetry -> Maybe (Metric ExportResult)+    getExportSamples = \case InternalTelemetry'Metric ExportSamples m -> Just m; _ -> Nothing
+ src-lib/GHC/Eventlog/Live/Processor/Core.hs view
@@ -0,0 +1,21 @@+{- |+Module      : GHC.Eventlog.Live.Processor.Core+Description : Common utilities shared across telemetry data types.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Processor.Core (+  runIf,+  runWith,+)+where++import Data.Machine (MachineT, stopped)++-- | Run a machine if a boolean is @True@, otherwise stop.+runIf :: (Monad m) => Bool -> MachineT m k o -> MachineT m k o+runIf b m = if b then m else stopped++-- | Run a machine with the value from a @Maybe a@, otherwise stop.+runWith :: (Monad m) => Maybe a -> (a -> MachineT m k o) -> MachineT m k o+runWith ma mf = maybe stopped mf ma
+ src-lib/GHC/Eventlog/Live/Processor/Core/Logs.hs view
@@ -0,0 +1,37 @@+{- |+Module      : GHC.Eventlog.Live.Processor.Core.Logs+Description : Profile Processors for OTLP.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Processor.Core.Logs (+  process,+)+where++import Data.DList qualified as D+import Data.Machine (ProcessT, mapping, (~>))+import Data.Proxy (Proxy (..))+import GHC.Eventlog.Live.Config (FullConfig)+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Machine.Core (Tick)+import GHC.Eventlog.Live.Machine.Core qualified as M+import GHC.Eventlog.Live.Processor.Core (runIf)+import GHC.Eventlog.Live.Types.Logs (IsLogRecord, KnownLog, SomeLogs (..), logConfig, toLogRecord)++--------------------------------------------------------------------------------+-- Generic processor for logs+--------------------------------------------------------------------------------++process ::+  (Monad m, IsLogRecord l) =>+  (KnownLog log) =>+  Proxy log ->+  ProcessT m i l ->+  FullConfig ->+  ProcessT m (Tick i) (Tick SomeLogs)+process (log_ :: Proxy log) processor fullConfig =+  runIf (C.processorEnabled (.logs) (logConfig $ Proxy @log) fullConfig) $+    M.liftTick (processor ~> mapping (D.singleton . toLogRecord))+      ~> M.batchByTicks (C.processorExportBatches (.logs) (logConfig $ Proxy @log) fullConfig)+      ~> M.liftTick (mapping $ SomeLogs log_ . D.toList)
+ src-lib/GHC/Eventlog/Live/Processor/Core/Metrics.hs view
@@ -0,0 +1,234 @@+{- |+Module      : GHC.Eventlog.Live.Processor.Core.Metrics+Description : Common utilities for metric processors.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Processor.Core.Metrics (+  -- * Metric Processor+  MetricProcessor (..),+  process,+  processorFor,+  processWith,++  -- * Multi-Metric Processor+  MetricProcessors (..),+  select,+  processAllWith,++  -- * Metric Aggregatorss+  MetricAggregators (..),+  viaSum,+  viaLast,+)+where++import Data.Coerce (Coercible, coerce)+import Data.DList (DList)+import Data.DList qualified as D+import Data.Functor.Identity (Identity (..))+import Data.Kind (Type)+import Data.Machine (Process, ProcessT, asParts, echo, mapping, (~>))+import Data.Proxy (Proxy (..))+import Data.Semigroup (Last (..), Sum (..))+import GHC.Eventlog.Live.Config (FullConfig)+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Machine.Core (Tick)+import GHC.Eventlog.Live.Machine.Core qualified as M+import GHC.Eventlog.Live.Processor.Core (runIf)+import GHC.Eventlog.Live.Types.Group (Group, GroupBy, GroupedBy)+import GHC.Eventlog.Live.Types.Group qualified as DG+import GHC.Eventlog.Live.Types.Metrics (KnownMetric (..), KnownMetricKind (..), Metric (..), SAggregationTemporality (..), SMetricKind (..), SomeMetrics (..), metricConfig)+import GHC.TypeLits (Symbol)++--------------------------------------------------------------------------------+-- Metric Processor+--------------------------------------------------------------------------------++{- |+A t`MetricProcessor` holds the building blocks for the processing pipeline for a+single metric.+-}+type MetricProcessor :: Symbol -> (Type -> Type) -> Type -> Type -> Type -> Type+data MetricProcessor metric m a b c+  = forall f.+  (Monad m, KnownMetric metric, Foldable f) =>+  MetricProcessor+  { processor :: !(ProcessT m a b)+  -- ^ The `processor` field holds the input processor. Usually, this processes events into t`Metric`.+  , aggregators :: !(MetricAggregators b c)+  -- ^ The `aggregators` field holds the aggregation strategies.+  , ungroup :: !(c -> f (Metric (GetMetricType metric)))+  -- ^ The `ungroup` function is useful when one value holds multiple metrics of the same type.+  }++process ::+  (Monad m, KnownMetric metric) =>+  Proxy metric ->+  ProcessT m i (Metric (GetMetricType metric)) ->+  FullConfig ->+  ProcessT m (Tick i) (Tick SomeMetrics)+process (metric :: Proxy metric) processor =+  processWith @metric (processorFor metric processor)+{-# INLINE process #-}++processorFor ::+  (Monad m, KnownMetric metric) =>+  Proxy metric ->+  ProcessT m i (Metric (GetMetricType metric)) ->+  MetricProcessor metric m i (Metric (GetMetricType metric)) (Metric (GetMetricType metric))+processorFor (metric :: Proxy metric) processor =+  MetricProcessor{processor = processor, aggregators = aggregatorsFor metric, ungroup = Identity}+{-# INLINE processorFor #-}++processWith ::+  forall metric m a b c.+  MetricProcessor metric m a b c ->+  FullConfig ->+  ProcessT m (Tick a) (Tick SomeMetrics)+processWith MetricProcessor{..} fullConfig =+  runIf (C.processorEnabled (.metrics) (metricConfig $ Proxy @metric) fullConfig) $+    M.liftTick processor+      ~> aggregate aggregators (C.processorAggregationBatches (.metrics) (metricConfig $ Proxy @metric) fullConfig)+      ~> M.liftTick (mapping ungroup ~> asParts ~> mapping D.singleton)+      ~> M.batchByTicks (C.processorExportBatches (.metrics) (metricConfig $ Proxy @metric) fullConfig)+      ~> M.liftTick (mapping $ SomeMetrics (Proxy @metric) . D.toList)+{-# INLINE processWith #-}++--------------------------------------------------------------------------------+-- Multi-Metric Processor+--------------------------------------------------------------------------------++infixr 6 :&:++{- |+A t`MetricProcessors` holds a series of t`MetricProcessor`s that work from the same input type.+-}+type MetricProcessors :: [Symbol] -> (Type -> Type) -> Type -> Type+data MetricProcessors metrics m a where+  End ::+    MetricProcessors '[] m i+  (:&:) ::+    forall metric metrics m i a b.+    (KnownMetric metric) =>+    (MetricProcessor metric m i a b) ->+    MetricProcessors metrics m i ->+    MetricProcessors (metric ': metrics) m i++{- |+Check if /any/ of the t`MetricProcessors` is enabled.+-}+anyProcessorEnabled :: FullConfig -> MetricProcessors metrics m i -> Bool+anyProcessorEnabled _fullConfig End = False+anyProcessorEnabled fullConfig ((_ :: MetricProcessor metric m i a b) :&: rest) =+  C.processorEnabled (.metrics) (metricConfig $ Proxy @metric) fullConfig || anyProcessorEnabled fullConfig rest++select ::+  (Monad m, KnownMetric metric) =>+  Proxy metric ->+  (i -> GetMetricType metric) ->+  MetricProcessor metric m (Metric i) (Metric (GetMetricType metric)) (Metric (GetMetricType metric))+select (metric :: Proxy metric) f =+  MetricProcessor{processor = mapping (fmap f), aggregators = aggregatorsFor metric, ungroup = Identity}+{-# INLINE select #-}++processAllWith ::+  forall metrics m i a.+  (Monad m) =>+  -- | The full configuration.+  FullConfig ->+  ProcessT m i a ->+  MetricProcessors metrics m a ->+  ProcessT m (Tick i) (Tick (DList SomeMetrics))+processAllWith fullConfig preprocessor processors =+  runIf (anyProcessorEnabled fullConfig processors) $+    M.liftTick preprocessor+      ~> M.fanoutTick+        [ processor ~> M.liftTick (mapping D.singleton)+        | processor <- processAllWith' processors+        ]+ where+  processAllWith' :: MetricProcessors metrics' m a -> [ProcessT m (Tick a) (Tick SomeMetrics)]+  processAllWith' End = []+  processAllWith' (p :&: ps) = processWith p fullConfig : processAllWith' ps++--------------------------------------------------------------------------------+-- Metric Aggregators+--------------------------------------------------------------------------------++data MetricAggregators a b = MetricAggregators+  { nothing :: Process (Tick a) (Tick b)+  , byBatches :: Int -> Process (Tick a) (Tick b)+  }++{- |+Internal helper.++Get the aggregator for a known metric, based on its known `MetricKind`.+-}+aggregatorsFor ::+  (KnownMetric metric) =>+  Proxy metric ->+  MetricAggregators (Metric (GetMetricType metric)) (Metric (GetMetricType metric))+aggregatorsFor (_metric :: Proxy metric) =+  case metricKindSing (Proxy @(GetMetricKind metric)) of+    SGauge -> viaLast+    SSum SCumulative _sMonotonicity -> viaLast+    SSum SDelta _sMonotonicity -> viaSum++{- |+Internal helper.++Aggregate items based on the provided aggregators and aggregation strategy.+-}+aggregate :: MetricAggregators a b -> Int -> Process (Tick a) (Tick b)+aggregate MetricAggregators{..} aggregationBatches+  | aggregationBatches >= 1 = byBatches aggregationBatches+  | otherwise = nothing++{- |+Internal helper.++Metric aggregators via the `Semigroup` instance for `Sum`.+-}+viaSum :: forall a. (Num a) => MetricAggregators (Metric a) (Metric a)+viaSum =+  MetricAggregators+    { nothing = echo+    , byBatches = \ticks ->+        -- TODO: Yield group sample counts as separate metric.+        batchByTicksVia ticks (Proxy @(Metric (Sum a)))+          ~> M.liftTick (mapping (fmap (.representative)) ~> asParts)+    }++{- |+Internal helper.++Metric aggregators via the `Semigroup` instance for `Last`.+-}+viaLast :: forall a. (GroupBy a) => MetricAggregators a a+viaLast =+  MetricAggregators+    { nothing = echo+    , byBatches = \ticks ->+        -- TODO: Yield group sample counts as separate metric.+        batchByTicksVia ticks (Proxy @(Last a))+          ~> M.liftTick (mapping (fmap (.representative)) ~> asParts)+    }++{- |+Internal helper.++This function aggregates items via a `Semigroup` instance and grouped by the `GroupBy` instance.+-}+batchByTicksVia ::+  forall a b.+  (Coercible a b, GroupBy b, Semigroup b) =>+  -- | The number of ticks per batch.+  Int ->+  Proxy b ->+  Process (Tick a) (Tick [Group a])+batchByTicksVia ticks (Proxy :: Proxy b) =+  mapping (fmap DG.singleton . coerce @(Tick a) @(Tick b))+    ~> M.batchByTicks @(GroupedBy b) ticks+    ~> M.liftTick (mapping (coerce @[Group b] @[Group a] . DG.groups))
+ src-lib/GHC/Eventlog/Live/Processor/Core/Traces.hs view
@@ -0,0 +1,38 @@+{- |+Module      : GHC.Eventlog.Live.Processor.Core.Traces+Description : Profile Processors for OTLP.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Processor.Core.Traces (+  process,+)+where++import Control.Monad.IO.Class (MonadIO)+import Data.DList qualified as D+import Data.Machine (ProcessT, mapping, (~>))+import Data.Proxy (Proxy (..))+import GHC.Eventlog.Live.Config (FullConfig)+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Machine.Core (Tick)+import GHC.Eventlog.Live.Machine.Core qualified as M+import GHC.Eventlog.Live.Processor.Core (runIf)+import GHC.Eventlog.Live.Types.Traces (IsSpan, KnownTrace, SomeSpans (..), asSpan, traceConfig)++--------------------------------------------------------------------------------+-- Existential wrapper for spans+--------------------------------------------------------------------------------++process ::+  (MonadIO m, IsSpan s k) =>+  (KnownTrace trace) =>+  Proxy trace ->+  FullConfig ->+  ProcessT m (Tick s) (Tick SomeSpans)+process (trace :: Proxy trace) fullConfig =+  runIf (C.processorEnabled (.traces) (traceConfig $ Proxy @trace) fullConfig) $+    M.liftTick asSpan+      ~> M.liftTick (mapping D.singleton)+      ~> M.batchByTicks (C.processorExportBatches (.traces) (traceConfig $ Proxy @trace) fullConfig)+      ~> M.liftTick (mapping $ SomeSpans trace . D.toList)
+ src-lib/GHC/Eventlog/Live/Processor/Heap.hs view
@@ -0,0 +1,125 @@+{-# OPTIONS_GHC -Wno-orphans #-}++{- |+Module      : GHC.Eventlog.Live.Processor.Heap+Description : Heap Event Processors for OTLP.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Processor.Heap (+  processHeapEvents,+)+where++import Control.Monad.IO.Class (MonadIO (..))+import Data.DList (DList)+import Data.DList qualified as D+import Data.Machine (Process, ProcessT, mapping, (~>))+import Data.Proxy (Proxy (..))+import GHC.Eventlog.Live.Config (FullConfig (..))+import GHC.Eventlog.Live.Logger (Logger)+import GHC.Eventlog.Live.Machine.Analysis.Heap (GcStats (..), MemReturn (..))+import GHC.Eventlog.Live.Machine.Analysis.Heap qualified as M+import GHC.Eventlog.Live.Machine.Core (Tick)+import GHC.Eventlog.Live.Machine.Core qualified as M+import GHC.Eventlog.Live.Machine.WithStartTime (WithStartTime (..))+import GHC.Eventlog.Live.Processor.Core.Metrics+import GHC.Eventlog.Live.Types.Metrics (SomeMetrics (..))+import GHC.RTS.Events (Event (..), HeapProfBreakdown (..))+import IpeDB.Database qualified as DB+import IpeDB.Types.InfoProv qualified as IP++--------------------------------------------------------------------------------+-- processHeapEvents+--------------------------------------------------------------------------------++processHeapEvents ::+  (MonadIO m) =>+  Logger m ->+  Maybe (DB.Table IP.InfoProvId IP.InfoProv) ->+  Maybe HeapProfBreakdown ->+  FullConfig ->+  ProcessT m (Tick (WithStartTime Event)) (Tick (DList SomeMetrics))+processHeapEvents verbosity maybeInfoProvTable maybeHeapProfBreakdown fullConfig =+  M.fanoutTick+    [ processHeapAllocated fullConfig+        ~> M.liftTick (mapping D.singleton)+    , processHeapSize fullConfig+        ~> M.liftTick (mapping D.singleton)+    , processBlocksSize fullConfig+        ~> M.liftTick (mapping D.singleton)+    , processHeapLive fullConfig+        ~> M.liftTick (mapping D.singleton)+    , processMemReturn fullConfig+    , processGcStats fullConfig+    , processHeapProfSample verbosity maybeInfoProvTable maybeHeapProfBreakdown fullConfig+        ~> M.liftTick (mapping D.singleton)+    ]++--------------------------------------------------------------------------------+-- HeapAllocated++processHeapAllocated :: FullConfig -> Process (Tick (WithStartTime Event)) (Tick SomeMetrics)+processHeapAllocated =+  process (Proxy @"heapAllocated") M.processHeapAllocated++--------------------------------------------------------------------------------+-- HeapSize++processHeapSize :: FullConfig -> Process (Tick (WithStartTime Event)) (Tick SomeMetrics)+processHeapSize =+  process (Proxy @"heapSize") M.processHeapSize++--------------------------------------------------------------------------------+-- BlocksSize++processBlocksSize :: FullConfig -> Process (Tick (WithStartTime Event)) (Tick SomeMetrics)+processBlocksSize =+  process (Proxy @"blocksSize") M.processBlocksSize++--------------------------------------------------------------------------------+-- HeapLive++processHeapLive :: FullConfig -> Process (Tick (WithStartTime Event)) (Tick SomeMetrics)+processHeapLive =+  process (Proxy @"heapLive") M.processHeapLive++--------------------------------------------------------------------------------+-- MemReturn++processMemReturn :: FullConfig -> Process (Tick (WithStartTime Event)) (Tick (DList SomeMetrics))+processMemReturn fullConfig =+  processAllWith fullConfig M.processMemReturn $+    select (Proxy @"memCurrent") (.current)+      :&: select (Proxy @"memNeeded") (.needed)+      :&: select (Proxy @"memReturned") (.returned)+      :&: End++--------------------------------------------------------------------------------+-- GcStats++processGcStats :: FullConfig -> Process (Tick (WithStartTime Event)) (Tick (DList SomeMetrics))+processGcStats fullConfig =+  processAllWith fullConfig M.processGcStats $+    select (Proxy @"gcCopied") (.copied)+      :&: select (Proxy @"gcSlop") (.slop)+      :&: select (Proxy @"gcFragmentation") (.fragmentation)+      :&: End++--------------------------------------------------------------------------------+-- HeapProfSample++processHeapProfSample ::+  (MonadIO m) =>+  Logger m ->+  Maybe (DB.Table IP.InfoProvId IP.InfoProv) ->+  Maybe HeapProfBreakdown ->+  FullConfig ->+  ProcessT m (Tick (WithStartTime Event)) (Tick SomeMetrics)+processHeapProfSample logger maybeInfoProvTable maybeHeapProfBreakdown =+  processWith @"heapProfSample"+    MetricProcessor+      { processor = M.processHeapProfSample logger maybeInfoProvTable maybeHeapProfBreakdown+      , aggregators = viaLast+      , ungroup = M.heapProfSamples+      }
+ src-lib/GHC/Eventlog/Live/Processor/Logs.hs view
@@ -0,0 +1,64 @@+{- |+Module      : GHC.Eventlog.Live.Processor.Logs+Description : Log Processors for OTLP.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Processor.Logs (+  processLogEvents,+)+where++import Control.Monad.IO.Class (MonadIO (..))+import Data.DList (DList)+import Data.DList qualified as D+import Data.Data (Proxy (..))+import Data.Machine (Process, ProcessT, mapping, (~>))+import GHC.Eventlog.Live.Config (FullConfig (..))+import GHC.Eventlog.Live.Machine.Analysis.Log qualified as M+import GHC.Eventlog.Live.Machine.Analysis.Thread qualified as M+import GHC.Eventlog.Live.Machine.Core (Tick)+import GHC.Eventlog.Live.Machine.Core qualified as M+import GHC.Eventlog.Live.Machine.WithStartTime (WithStartTime (..))+import GHC.Eventlog.Live.Processor.Core.Logs (process)+import GHC.Eventlog.Live.Types.Logs (SomeLogs (..))+import GHC.RTS.Events (Event (..))++--------------------------------------------------------------------------------+-- processLogEvents+--------------------------------------------------------------------------------++processLogEvents ::+  (MonadIO m) =>+  FullConfig ->+  ProcessT m (Tick (WithStartTime Event)) (Tick (DList SomeLogs))+processLogEvents fullConfig =+  M.fanoutTick+    [ processThreadLabel fullConfig+        ~> M.liftTick (mapping D.singleton)+    , processUserMarker fullConfig+        ~> M.liftTick (mapping D.singleton)+    , processUserMessage fullConfig+        ~> M.liftTick (mapping D.singleton)+    ]++--------------------------------------------------------------------------------+-- UserMessage++processUserMessage :: FullConfig -> Process (Tick (WithStartTime Event)) (Tick SomeLogs)+processUserMessage =+  process (Proxy @"userMessage") M.processUserMessage++--------------------------------------------------------------------------------+-- UserMarker++processUserMarker :: FullConfig -> Process (Tick (WithStartTime Event)) (Tick SomeLogs)+processUserMarker =+  process (Proxy @"userMarker") M.processUserMarker++--------------------------------------------------------------------------------+-- ThreadLabel++processThreadLabel :: FullConfig -> Process (Tick (WithStartTime Event)) (Tick SomeLogs)+processThreadLabel =+  process (Proxy @"threadLabel") M.processThreadLabel
+ src-lib/GHC/Eventlog/Live/Processor/Profiles.hs view
@@ -0,0 +1,83 @@+{- |+Module      : GHC.Eventlog.Live.Processor.Profiles+Description : Profile Processors for OTLP.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Processor.Profiles (+  processProfileEvents,+)+where++import Control.Monad.IO.Class (MonadIO (..))+import Data.DList (DList)+import Data.DList qualified as D+import Data.Machine (ProcessT, mapping, (~>))+import Data.Proxy (Proxy (..))+import GHC.Eventlog.Live.Config (FullConfig (..))+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Logger (Logger)+import GHC.Eventlog.Live.Machine.Analysis.Profile qualified as M+import GHC.Eventlog.Live.Machine.Core (Tick)+import GHC.Eventlog.Live.Machine.Core qualified as M+import GHC.Eventlog.Live.Machine.WithStartTime (WithStartTime (..))+import GHC.Eventlog.Live.Processor.Core+import GHC.Eventlog.Live.Types.Profiles (SomeSamples (..), toSample)+import GHC.RTS.Events (Event (..))+import IpeDB.Database qualified as DB+import IpeDB.Types.CostCentre qualified as CC+import IpeDB.Types.InfoProv qualified as IP++--------------------------------------------------------------------------------+-- Profiles+--------------------------------------------------------------------------------++processProfileEvents ::+  forall m.+  (MonadIO m) =>+  Logger m ->+  DB.Table CC.CostCentreId CC.CostCentre ->+  DB.Table IP.InfoProvId IP.InfoProv ->+  FullConfig ->+  ProcessT m (Tick (WithStartTime Event)) (Tick (DList SomeSamples))+processProfileEvents logger ccdb ipedb config =+  M.fanoutTick+    [ processProfSampleCostCentre logger ccdb config+        ~> M.liftTick (mapping D.singleton)+    , processGhcStackProfiler logger ipedb config+        ~> M.liftTick (mapping D.singleton)+    ]++--------------------------------------------------------------------------------+-- Processor for `ghc-stack-profiler` call-stack samples+--------------------------------------------------------------------------------++processGhcStackProfiler ::+  forall m.+  (MonadIO m) =>+  Logger m ->+  DB.Table IP.InfoProvId IP.InfoProv ->+  FullConfig ->+  ProcessT m (Tick (WithStartTime Event)) (Tick SomeSamples)+processGhcStackProfiler logger ipedb config =+  runIf (C.processorEnabled (.profiles) (.callStackProfile) config) $+    M.liftTick (M.processGhcStackProfilerData logger ipedb ~> mapping (D.singleton . toSample))+      ~> M.batchByTicks (C.processorExportBatches (.profiles) (.callStackProfile) config)+      ~> M.liftTick (mapping $ SomeSamples (Proxy @"callStackProfile") . D.toList)++--------------------------------------------------------------------------------+-- Processor for cost-centre stack samples+--------------------------------------------------------------------------------++processProfSampleCostCentre ::+  forall m.+  (MonadIO m) =>+  Logger m ->+  DB.Table CC.CostCentreId CC.CostCentre ->+  FullConfig ->+  ProcessT m (Tick (WithStartTime Event)) (Tick SomeSamples)+processProfSampleCostCentre logger ccdb config =+  runIf (C.processorEnabled (.profiles) (.costCentreStackProfile) config) $+    M.liftTick (M.processProfSampleCostCentreData logger ccdb ~> mapping (D.singleton . toSample))+      ~> M.batchByTicks (C.processorExportBatches (.profiles) (.callStackProfile) config)+      ~> M.liftTick (mapping $ SomeSamples (Proxy @"costCentreStackProfile") . D.toList)
+ src-lib/GHC/Eventlog/Live/Processor/Threads.hs view
@@ -0,0 +1,127 @@+{-# OPTIONS_GHC -Wno-orphans #-}++{- |+Module      : GHC.Eventlog.Live.Processor.Threads+Description : Thread Event Processors for OTLP.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Processor.Threads (+  processThreadEvents,+)+where++import Control.Monad.IO.Class (MonadIO (..))+import Data.DList (DList)+import Data.DList qualified as D+import Data.Machine (ProcessT, asParts, mapping, (~>))+import Data.Machine.Fanout (fanout)+import Data.Proxy (Proxy (..))+import GHC.Eventlog.Live.Config (FullConfig (..))+import GHC.Eventlog.Live.Config qualified as C+import GHC.Eventlog.Live.Logger (Logger)+import GHC.Eventlog.Live.Machine.Analysis.Capability qualified as M+import GHC.Eventlog.Live.Machine.Analysis.Thread qualified as M+import GHC.Eventlog.Live.Machine.Core (Tick)+import GHC.Eventlog.Live.Machine.Core qualified as M+import GHC.Eventlog.Live.Machine.Validate (validateOrder)+import GHC.Eventlog.Live.Machine.WithStartTime (WithStartTime (..))+import GHC.Eventlog.Live.Machine.WithStartTime qualified as M+import GHC.Eventlog.Live.Processor.Core (runIf)+import GHC.Eventlog.Live.Processor.Core.Metrics qualified as CM+import GHC.Eventlog.Live.Processor.Core.Traces qualified as CT+import GHC.Eventlog.Live.Types.Metrics (SomeMetrics, toMetric)+import GHC.Eventlog.Live.Types.Traces (SomeSpans (..))+import GHC.RTS.Events (Event (..))++data ABC a b c = A !a | B !b | C !c++processThreadEvents ::+  (MonadIO m) =>+  Logger m ->+  FullConfig ->+  ProcessT m (Tick (WithStartTime Event)) (Tick (DList (Either SomeMetrics SomeSpans)))+processThreadEvents verbosity fullConfig =+  runIf (shouldProcessThreadEvents fullConfig) $+    M.sortByTicks (.value.evTime) fullConfig.eventlogFlushIntervalX+      ~> M.liftTick+        ( fanout+            [ validateOrder verbosity (.value.evTime)+            , runIf (shouldComputeCapabilityUsageSpan fullConfig) $+                M.processGCSpans verbosity+                  ~> mapping (D.singleton . A)+            , runIf (shouldComputeThreadStateSpan fullConfig) $+                M.processThreadStateSpans' M.tryGetTimeUnixNano (.value) M.setWithStartTime'value verbosity+                  ~> fanout+                    [ M.asMutatorSpans' (.value) M.setWithStartTime'value+                        ~> mapping (D.singleton . B)+                    , mapping (D.singleton . C)+                    ]+            ]+        )+      ~> M.liftTick (asParts ~> mapping repackCapabilityUsageSpanOrThreadStateSpan)+      ~> fanout+        [ M.liftTick (mapping leftToMaybe ~> asParts)+            ~> M.fanoutTick+              [ M.liftTick M.processCapabilityUsageDuration+                  ~> M.fanoutTick+                    [ CM.process (Proxy @"capabilityUsage") (mapping toMetric) fullConfig+                        ~> M.liftTick (mapping D.singleton)+                    , CM.process (Proxy @"productivity") (M.processProductivity ~> mapping (fmap (* 100.0) . toMetric)) fullConfig+                        ~> M.liftTick (mapping D.singleton)+                    ]+                  ~> mapping (fmap (fmap Left))+              , M.liftTick M.dropStartTime+                  ~> CT.process (Proxy @"capabilityUsage") fullConfig+                  ~> M.liftTick (mapping (D.singleton . Right))+              ]+        , M.liftTick (mapping rightToMaybe ~> asParts)+            ~> M.liftTick M.dropStartTime+            ~> CT.process (Proxy @"threadState") fullConfig+            ~> M.liftTick (mapping (D.singleton . Right))+        ]+ where+  repackCapabilityUsageSpanOrThreadStateSpan = \case+    A i -> Left $ fmap Left i+    B i -> Left $ fmap Right i+    C i -> Right i++{- |+Internal helper.+Get the `Left` value, if any.+-}+leftToMaybe :: Either a b -> Maybe a+leftToMaybe = either Just (const Nothing)++{- |+Internal helper.+Get the `Right` value, if any.+-}+rightToMaybe :: Either a b -> Maybe b+rightToMaybe = either (const Nothing) Just++{- |+Internal helper.+Determine whether or not any thread events should be processed at all.+-}+shouldProcessThreadEvents :: FullConfig -> Bool+shouldProcessThreadEvents = shouldComputeThreadStateSpan++{- |+Internal helper.+Determine whether or not the capability usage spans should be computed.+-}+shouldComputeCapabilityUsageSpan :: FullConfig -> Bool+shouldComputeCapabilityUsageSpan fullConfig =+  C.processorEnabled (.metrics) (.capabilityUsage) fullConfig+    || C.processorEnabled (.metrics) (.productivity) fullConfig+    || C.processorEnabled (.traces) (.capabilityUsage) fullConfig++{- |+Internal helper.+Determine whether or not the thread state spans should be computed.+-}+shouldComputeThreadStateSpan :: FullConfig -> Bool+shouldComputeThreadStateSpan fullConfig =+  C.processorEnabled (.traces) (.threadState) fullConfig+    || shouldComputeCapabilityUsageSpan fullConfig
+ src-lib/GHC/Eventlog/Live/Source.hs view
@@ -0,0 +1,210 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.Source+Description : Utilities for running eventlog machines with sockets.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Source (+  Tick (..),+  withEventlogSourceHandle,+  runWithEventlogSourceHandle,+  runWithEventlogSourceOptions,+) where++import Control.Concurrent (threadDelay)+import Control.Exception (Exception (..))+import Control.Exception qualified as E+import Data.Foldable (traverse_)+import Data.List.NonEmpty qualified as NE+import Data.Machine (ProcessT, runT_, (~>))+import Data.Machine.Fanout (fanout)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Void (Void)+import GHC.Eventlog.Live.Logger (Logger, logDebug, logInfo)+import GHC.Eventlog.Live.Machine.Core+import GHC.Eventlog.Live.Machine.Decoder+import GHC.Eventlog.Live.Machine.Sink+import GHC.Eventlog.Live.Machine.Source+import GHC.Eventlog.Live.Source.Core+import GHC.RTS.Events (Event)+import Network.Socket (Socket)+import Network.Socket qualified as S+import System.IO qualified as IO+import Text.Printf (printf)++{- |+Run an event processor with `EventlogSourceOptions`.+-}+runWithEventlogSourceOptions ::+  -- | The logging action.+  Logger IO ->+  -- | The eventlog socket handle.+  EventlogSourceOptions ->+  -- | The initial timeout in seconds for exponential backoff.+  Double ->+  -- | The timeout exponent for exponential backoff.+  Double ->+  -- | The batch interval in milliseconds.+  Int ->+  -- | The number of bytes to read (defaults to 4KiB).+  Maybe Int ->+  -- | An optional file to which to stream binary eventlog data.+  Maybe FilePath ->+  -- | The event processor.+  ProcessT IO (Tick Event) Void ->+  IO ()+runWithEventlogSourceOptions logger eventlogSourceOptions timeoutExponent initialTimeoutS batchIntervalMs maybeChuckSizeBytes maybeOutputFile toEventSink = do+  withEventlogSourceHandle logger timeoutExponent initialTimeoutS eventlogSourceOptions $ \eventlogSourceHandle ->+    runWithEventlogSourceHandle logger eventlogSourceHandle batchIntervalMs maybeChuckSizeBytes maybeOutputFile toEventSink++{- |+Run an event processor with an eventlog socket handle.+-}+runWithEventlogSourceHandle ::+  -- | The logging action.+  Logger IO ->+  -- | The eventlog socket handle.+  EventlogSourceHandle ->+  -- | The batch interval in milliseconds.+  Int ->+  -- | The number of bytes to read (defaults to 4KiB).+  Maybe Int ->+  -- | An optional file to which to stream binary eventlog data.+  Maybe FilePath ->+  -- | The event processor.+  ProcessT IO (Tick Event) Void ->+  IO ()+runWithEventlogSourceHandle logger eventlogSourceHandle batchIntervalMs maybeChuckSizeBytes maybeOutputFile toEventSink = do+  let chuckSizeBytes = fromMaybe defaultChunkSizeBytes maybeChuckSizeBytes+  let fromSocket = eventlogSourceTick batchIntervalMs chuckSizeBytes eventlogSourceHandle+  case maybeOutputFile of+    Nothing ->+      runT_ $+        fromSocket ~> decodeEventBatch logger ~> toEventSink+    Just outputFile ->+      IO.withFile outputFile IO.WriteMode $ \outputHandle -> do+        runT_ $+          fromSocket+            ~> fanout+              [ fileSinkBatch outputHandle+              , decodeEventBatch logger ~> toEventSink+              ]++{- |+Run an action with a `Handle` to the eventlog described by `EventlogSourceOptions`.+-}+withEventlogSourceHandle ::+  -- | The logging action.+  Logger IO ->+  -- | The initial timeout in seconds for exponential backoff.+  Double ->+  -- | The timeout exponent for exponential backoff.+  Double ->+  -- | The eventlog socket.+  EventlogSourceOptions ->+  (EventlogSourceHandle -> IO ()) ->+  IO ()+withEventlogSourceHandle logger initialTimeoutS timeoutExponent eventlogSource action = do+  case eventlogSource of+    EventlogSourceOptionsStdin -> do+      logInfo logger $+        "Reading eventlog from stdin"+      let enter = do+            maybeStdinTextEncoding <- IO.hGetEncoding IO.stdin+            IO.hSetBinaryMode IO.stdin True+            pure maybeStdinTextEncoding+      let leave maybeStdinTextEncoding = do+            traverse_ (IO.hSetEncoding IO.stdin) maybeStdinTextEncoding+            IO.hSetNewlineMode IO.stdin IO.nativeNewlineMode+      E.bracket enter leave . const . action $ EventlogSourceHandleStdin+    EventlogSourceOptionsFile eventlogFile -> do+      logInfo logger $+        "Reading eventlog from " <> T.pack eventlogFile+      IO.withBinaryFile eventlogFile IO.ReadMode $ \handle ->+        action $ EventlogSourceHandleFile handle+    EventlogSourceOptionsSocket eventlogSocketAddr -> do+      logInfo logger $+        "Waiting to connect on " <> prettyEventlogSocketAddr eventlogSocketAddr+      E.bracket (connectRetry logger initialTimeoutS timeoutExponent eventlogSocketAddr) S.close $ \socket ->+        action $ EventlogSourceHandleSocket socket++{- |+Connect to the eventlog described by `EventlogSourceOptions` with retries and non-randomised exponential backoff.+-}+connectRetry ::+  -- | The logging action.+  Logger IO ->+  -- | The initial timeout in seconds for exponential backoff.+  Double ->+  -- | The timeout exponent for exponential backoff.+  Double ->+  -- | The eventlog socket address.+  EventlogSocketAddr ->+  IO Socket+connectRetry logger initialTimeoutS timeoutExponent eventlogSocketAddr =+  connectLoop initialTimeoutS+ where+  waitFor :: Double -> IO ()+  waitFor timeoutS = threadDelay $ round $ timeoutS * 1e6++  connectLoop :: Double -> IO Socket+  connectLoop timeoutS = do+    let connect = do+          logDebug logger $+            "Trying to connect on " <> prettyEventlogSocketAddr eventlogSocketAddr+          socket <- tryConnect eventlogSocketAddr+          logDebug logger $+            "Connected on " <> prettyEventlogSocketAddr eventlogSocketAddr+          pure socket+    let cleanup (e :: E.IOException) = do+          logDebug logger $+            "Failed to connect on "+              <> prettyEventlogSocketAddr eventlogSocketAddr+              <> ": "+              <> T.pack (displayException e)+          logDebug logger $+            "Waiting "+              <> prettyTimeoutMcs timeoutS+              <> " to retry..."+          waitFor timeoutS+          connectLoop (timeoutS * timeoutExponent)+    E.catch connect cleanup++tryConnect :: EventlogSocketAddr -> IO Socket+tryConnect = \case+  EventlogSocketUnixAddr{..} -> do+    E.bracketOnError (S.socket S.AF_UNIX S.Stream S.defaultProtocol) S.close $ \socket -> do+      S.connect socket (S.SockAddrUnix esaUnixPath)+      pure socket+  EventlogSocketInetAddr{..} -> do+    let addrInfo = S.defaultHints{S.addrFamily = S.AF_UNSPEC, S.addrSocketType = S.Stream}+    addr <- NE.head <$> S.getAddrInfo (Just addrInfo) (Just esaInetHost) (Just $ esaInetPort)+    E.bracketOnError (S.socket (S.addrFamily addr) (S.addrSocketType addr) (S.addrProtocol addr)) S.close $ \socket -> do+      S.connect socket (S.addrAddress addr)+      pure socket++{- |+Interal helper. Pretty-printer for timeout values in microseconds.+-}+prettyTimeoutMcs :: Double -> Text+prettyTimeoutMcs timeoutS+  | timeoutS > 86400 = T.pack $ printf "%.2f days" (timeoutS / 86400)+  | timeoutS > 3600 = T.pack $ printf "%.2f hours" (timeoutS / 3600)+  | timeoutS > 60 = T.pack $ printf "%.2f minutes" (timeoutS / 60)+  | timeoutS > 1 = T.pack $ printf "%.2f seconds" timeoutS+  | timeoutS > 1e-3 = T.pack $ printf "%.2f milliseconds" (timeoutS / 1e-3)+  | timeoutS > 1e-6 = T.pack $ printf "%.2f microseconds" (timeoutS / 1e-6)+  | timeoutS > 1e-9 = T.pack $ printf "%.2f nanoseconds" (timeoutS / 1e-9)+  | otherwise = T.pack $ printf "%.2f seconds" timeoutS++{- |+Internal helper. Pretty-printer for eventlog socket addresses.+-}+prettyEventlogSocketAddr :: EventlogSocketAddr -> Text+prettyEventlogSocketAddr = \case+  EventlogSocketUnixAddr{..} -> "Unix socket " <> T.pack esaUnixPath+  EventlogSocketInetAddr{..} -> "Inet socket " <> T.pack (esaInetHost <> ":" <> esaInetPort)
+ src-lib/GHC/Eventlog/Live/Source/Core.hs view
@@ -0,0 +1,134 @@+module GHC.Eventlog.Live.Source.Core (+  EventlogSourceOptions (..),+  EventlogSocketAddr (..),+  EventlogSourceHandle (..),+  EventlogSourceData (..),+  recv,+) where++import Control.Exception (handle, throwIO)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.Maybe (fromMaybe)+import Network.Socket (Socket)+import Network.Socket.ByteString qualified as SB+import System.IO (Handle)+import System.IO qualified as IO (stdin)+import System.IO.Error (isEOFError)+import System.Timeout (timeout)++{- |+The options for different kinds of eventlog sources.+-}+data EventlogSourceOptions+  = EventlogSourceOptionsStdin+  | EventlogSourceOptionsFile FilePath+  | EventlogSourceOptionsSocket EventlogSocketAddr++{- |+The options for different kinds of eventlog sockets.+-}+data EventlogSocketAddr+  = EventlogSocketUnixAddr+      { esaUnixPath :: FilePath+      {- ^ Unix socket path, e.g., @"\/tmp\/ghc_eventlog.sock"@.++      __Warning:__ Unix domain socket paths are often limited to 107 characters or less.+      -}+      }+  | EventlogSocketInetAddr+      { esaInetHost :: String+      -- ^ TCP host or interface, e.g. @"127.0.0.1"@.+      , esaInetPort :: String+      -- ^ TCP port, e.g., @"4242"@.+      }+  deriving (Eq, Show)++{- |+The handles for different kinds of eventlog sources.+-}+data EventlogSourceHandle+  = EventlogSourceHandleStdin+  | EventlogSourceHandleFile Handle+  | EventlogSourceHandleSocket Socket++data EventlogSourceData+  = EventlogSourceData ByteString+  | EventlogSourceTimeout+  | EventlogSourceClosed++{- |+Receive data from an `EventlogSourceHandle`.++__Warning__: The current implementation is blocking on Windows. See the documentation for `timeout`.+-}+recv ::+  -- | The handle to the eventlog source.+  EventlogSourceHandle ->+  -- | The timeout in microseconds.+  Int ->+  -- | The number of bytes to read.+  Int ->+  IO EventlogSourceData+recv = \case+  EventlogSourceHandleStdin -> recvFromHandle IO.stdin+  EventlogSourceHandleFile h -> recvFromHandle h+  EventlogSourceHandleSocket s -> recvFromSocket s++-- Permit a timeout and wrap the result appropriately.++{- |+Internal helper.+Receive data from a `Socket`.+-}+recvFromSocket ::+  -- | The eventlog socket.+  Socket ->+  -- | The timeout in microseconds.+  Int ->+  -- | The number of bytes to read.+  Int ->+  IO EventlogSourceData+recvFromSocket s timeoutMicros chunkSizeBytes =+  withTimeout timeoutMicros $ do+    msg <- SB.recv s chunkSizeBytes+    if BS.null msg+      then pure EventlogSourceClosed+      else pure $ EventlogSourceData msg++{- |+Internal helper.+Receive data from a `Handle`.+-}+recvFromHandle ::+  -- | The handle to the eventlog source.+  Handle ->+  -- | The timeout in microseconds.+  Int ->+  -- | The number of bytes to read.+  Int ->+  IO EventlogSourceData+recvFromHandle h timeoutMicros chunkSizeBytes =+  withTimeout timeoutMicros $+    handleEOFError EventlogSourceClosed $+      EventlogSourceData <$> BS.hGetSome h chunkSizeBytes++{- |+Internal helper.+Allow the IO operation to timeout.+-}+withTimeout ::+  -- | The timeout in microseconds.+  Int ->+  -- | The IO action to read data from the eventlog source.+  IO EventlogSourceData ->+  IO EventlogSourceData+withTimeout timeoutMicros =+  fmap (fromMaybe EventlogSourceTimeout) . timeout timeoutMicros++{- |+Internal helper.+Recover from an EOF error with a default value.+-}+handleEOFError :: a -> IO a -> IO a+handleEOFError d = handle (\e -> if isEOFError e then pure d else throwIO e)
+ src-lib/GHC/Eventlog/Live/Types/Attribute.hs view
@@ -0,0 +1,242 @@+{- |+Module      : GHC.Eventlog.Live.Attribute+Description : Representation for OTLP attributes.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Types.Attribute (+  Attrs,+  lookup,+  toList,+  Attr,+  AttrKey,+  AttrValue (..),+  IsAttrValue (..),+  (~=),+) where++import Data.Aeson (ToJSON)+import Data.Aeson.Encoding (null_)+import Data.Aeson.Types (Encoding, ToJSON (..), Value (..))+import Data.HashMap.Strict (HashMap)+import Data.HashMap.Strict qualified as M+import Data.Hashable (Hashable)+import Data.Int (Int16, Int32, Int64, Int8)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Version (Version, showVersion)+import Data.Word (Word16, Word32, Word64, Word8)+import GHC.Generics (Generic)+import GHC.IsList (IsList (..))+import Prelude hiding (lookup)++{- |+A set of attributes is a t`HashMap`+-}+newtype Attrs = Attrs {attrMap :: HashMap AttrKey AttrValue}+  deriving (Eq, Ord, Generic, Show)++lookup :: AttrKey -> Attrs -> Maybe AttrValue+lookup attrKey attrs = M.lookup attrKey attrs.attrMap++instance Hashable Attrs++instance Semigroup Attrs where+  (<>) :: Attrs -> Attrs -> Attrs+  x <> y = Attrs{attrMap = x.attrMap <> y.attrMap}++instance Monoid Attrs where+  mempty = Attrs mempty++instance IsList Attrs where+  type Item Attrs = Attr++  fromList :: [Item Attrs] -> Attrs+  fromList = Attrs . M.fromList++  toList :: Attrs -> [Item Attrs]+  toList = M.toList . (.attrMap)++instance ToJSON Attrs where+  toJSON :: Attrs -> Value+  toJSON Attrs{..} =+    toJSON $ M.filter (/= AttrNull) attrMap++  toEncoding :: Attrs -> Encoding+  toEncoding Attrs{..} =+    toEncoding $ M.filter (/= AttrNull) attrMap++  omitField :: Attrs -> Bool+  omitField Attrs{..} = M.null attrMap++{- |+An attribute is a key-value pair where the key is any string and the value is+some numeric type, string, or null. Attributes should be constructed using the+`(~=)` operator, which automatically converts Haskell types to t`AttrValue`.+-}+type Attr = (AttrKey, AttrValue)++{- |+Construct an t`Attr` as a pair of an t`AttrKey` and an t`AttrValue`,+constructed via the t`IsAttrValue` class.+-}+(~=) :: (IsAttrValue v) => AttrKey -> v -> Attr+k ~= v = (ak, av)+ where+  !ak = k+  !av = toAttrValue v+{-# INLINE (~=) #-}++{- |+The type of attribute keys.+-}+type AttrKey =+  Text++{- |+The type of attribute values.+-}+data AttrValue+  = AttrBool !Bool+  | AttrInt !Int+  | AttrInt8 !Int8+  | AttrInt16 !Int16+  | AttrInt32 !Int32+  | AttrInt64 !Int64+  | AttrWord !Word+  | AttrWord8 !Word8+  | AttrWord16 !Word16+  | AttrWord32 !Word32+  | AttrWord64 !Word64+  | AttrDouble !Double+  | AttrText !Text+  | AttrNull+  deriving (Eq, Ord, Generic, Show)++instance Hashable AttrValue++instance ToJSON AttrValue where+  toJSON :: AttrValue -> Value+  toJSON = \case+    AttrBool v -> toJSON v+    AttrInt v -> toJSON v+    AttrInt8 v -> toJSON v+    AttrInt16 v -> toJSON v+    AttrInt32 v -> toJSON v+    AttrInt64 v -> toJSON v+    AttrWord v -> toJSON v+    AttrWord8 v -> toJSON v+    AttrWord16 v -> toJSON v+    AttrWord32 v -> toJSON v+    AttrWord64 v -> toJSON v+    AttrDouble v -> toJSON v+    AttrText v -> toJSON v+    AttrNull -> Null++  toEncoding :: AttrValue -> Encoding+  toEncoding = \case+    AttrBool v -> toEncoding v+    AttrInt v -> toEncoding v+    AttrInt8 v -> toEncoding v+    AttrInt16 v -> toEncoding v+    AttrInt32 v -> toEncoding v+    AttrInt64 v -> toEncoding v+    AttrWord v -> toEncoding v+    AttrWord8 v -> toEncoding v+    AttrWord16 v -> toEncoding v+    AttrWord32 v -> toEncoding v+    AttrWord64 v -> toEncoding v+    AttrDouble v -> toEncoding v+    AttrText v -> toEncoding v+    AttrNull -> null_++{- |+Utility class to help construct values of the t`AttrValue` type.+-}+class IsAttrValue v where+  toAttrValue :: v -> AttrValue++instance IsAttrValue AttrValue where+  toAttrValue :: AttrValue -> AttrValue+  toAttrValue = id+  {-# INLINE toAttrValue #-}++instance IsAttrValue Bool where+  toAttrValue :: Bool -> AttrValue+  toAttrValue = AttrBool+  {-# INLINE toAttrValue #-}++instance IsAttrValue Int where+  toAttrValue :: Int -> AttrValue+  toAttrValue = AttrInt+  {-# INLINE toAttrValue #-}++instance IsAttrValue Int8 where+  toAttrValue :: Int8 -> AttrValue+  toAttrValue = AttrInt8+  {-# INLINE toAttrValue #-}++instance IsAttrValue Int16 where+  toAttrValue :: Int16 -> AttrValue+  toAttrValue = AttrInt16+  {-# INLINE toAttrValue #-}++instance IsAttrValue Int32 where+  toAttrValue :: Int32 -> AttrValue+  toAttrValue = AttrInt32+  {-# INLINE toAttrValue #-}++instance IsAttrValue Int64 where+  toAttrValue :: Int64 -> AttrValue+  toAttrValue = AttrInt64+  {-# INLINE toAttrValue #-}++instance IsAttrValue Word where+  toAttrValue :: Word -> AttrValue+  toAttrValue = AttrWord+  {-# INLINE toAttrValue #-}++instance IsAttrValue Word8 where+  toAttrValue :: Word8 -> AttrValue+  toAttrValue = AttrWord8+  {-# INLINE toAttrValue #-}++instance IsAttrValue Word16 where+  toAttrValue :: Word16 -> AttrValue+  toAttrValue = AttrWord16+  {-# INLINE toAttrValue #-}++instance IsAttrValue Word32 where+  toAttrValue :: Word32 -> AttrValue+  toAttrValue = AttrWord32+  {-# INLINE toAttrValue #-}++instance IsAttrValue Word64 where+  toAttrValue :: Word64 -> AttrValue+  toAttrValue = AttrWord64+  {-# INLINE toAttrValue #-}++instance IsAttrValue Double where+  toAttrValue :: Double -> AttrValue+  toAttrValue = AttrDouble+  {-# INLINE toAttrValue #-}++instance IsAttrValue String where+  toAttrValue :: String -> AttrValue+  toAttrValue = AttrText . T.pack+  {-# INLINE toAttrValue #-}++instance IsAttrValue Text where+  toAttrValue :: Text -> AttrValue+  toAttrValue = AttrText+  {-# INLINE toAttrValue #-}++instance IsAttrValue Version where+  toAttrValue :: Version -> AttrValue+  toAttrValue = toAttrValue . showVersion+  {-# INLINE toAttrValue #-}++instance (IsAttrValue v) => IsAttrValue (Maybe v) where+  toAttrValue :: Maybe v -> AttrValue+  toAttrValue = maybe AttrNull toAttrValue+  {-# INLINE toAttrValue #-}
+ src-lib/GHC/Eventlog/Live/Types/Capability.hs view
@@ -0,0 +1,50 @@+{- |+Module      : GHC.Eventlog.Live.Types.Capability+Description : Reprsentation for capability data.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Types.Capability (+  CapNo (..),+  evCapNo,+  fromCapabilityId,+) where++import Data.Hashable (Hashable)+import Data.Word (Word32)+import GHC.Eventlog.Live.Types.Attribute (IsAttrValue)+import GHC.RTS.Events (Event (..))+import GHC.Stack.Profiler.Core (CapabilityId (..))++{- |+A capability number.++In the GHC RTS, all capabilities are assigned a `Word32` identifier.++In @ghc-events@, the event capability number is received as a `Word32`,+if present, and converted to an `Int`, using @-1@ for global events.++In @ghc-stack-profiler@, the capability number is added to the event,+and upcast to `Word64`.+-}+newtype CapNo = CapNo+  { value :: Word32+  }+  deriving (Show, Eq, Ord)+  deriving newtype (Hashable, IsAttrValue)++{- |+Get the capability number from a @ghc-events@ `Event`.+-}+evCapNo :: Event -> Maybe CapNo+evCapNo ev+  | Just cap <- ev.evCap+  , 0 <= cap && cap <= fromIntegral @Word32 maxBound =+      Just (CapNo $ fromIntegral cap)+  | otherwise = Nothing++{- |+Get the capability number from a @ghc-stack-profiler@ `CapabilityId`.+-}+fromCapabilityId :: CapabilityId -> CapNo+fromCapabilityId (MkCapabilityId cap) = CapNo cap
+ src-lib/GHC/Eventlog/Live/Types/Group.hs view
@@ -0,0 +1,82 @@+{- |+Module      : GHC.Eventlog.Live.Types.Group+Description : Reprsentation for grouped data.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Types.Group (+  -- * GroupBy+  GroupBy (..),+  Group (..),+  GroupedBy,+  singleton,+  elems,+  groups,+) where++import Data.HashMap.Strict (HashMap)+import Data.HashMap.Strict qualified as M+import Data.Hashable (Hashable (..))+import Data.Kind (Type)+import Data.Semigroup (First (..), Last (..), Max (..), Min (..), Product (..), Sum (..))++{- |+This class defines the key to group by when aggregating.+-}+class (Hashable (Key a)) => GroupBy a where+  type Key a :: Type+  toKey :: a -> Key a++deriving newtype instance (GroupBy a) => GroupBy (First a)+deriving newtype instance (GroupBy a) => GroupBy (Last a)+deriving newtype instance (GroupBy a) => GroupBy (Max a)+deriving newtype instance (GroupBy a) => GroupBy (Min a)+deriving newtype instance (GroupBy a) => GroupBy (Product a)+deriving newtype instance (GroupBy a) => GroupBy (Sum a)++{- |+This type defines a set of groups, grouped by the key given by `GroupBy`.+-}+data GroupedBy a = (GroupBy a) => GroupedBy+  { groups :: HashMap (Key a) (Group a)+  }++{- |+Internal helper.+This type defines a group representative and the group size.+-}+data Group a = Group+  { representative :: !a+  , size :: !Word+  }+  deriving (Show, Functor, Foldable, Traversable)++{- |+Construct the singleton `GroupedBy`.+-}+singleton :: (GroupBy a) => a -> GroupedBy a+singleton a = GroupedBy{groups = M.singleton (toKey a) Group{representative = a, size = 1}}++{- |+Get all group representatives from a `GroupedBy`.+-}+elems :: GroupedBy a -> [a]+elems = fmap (.representative) . groups++{- |+Get all group representatives and sizes from a `GroupedBy`.+-}+groups :: GroupedBy a -> [Group a]+groups = M.elems . (.groups)++instance (Semigroup a) => Semigroup (Group a) where+  (<>) :: Group a -> Group a -> Group a+  x <> y =+    Group+      { representative = x.representative <> y.representative+      , size = x.size + y.size+      }++instance (Semigroup a, GroupBy a) => Semigroup (GroupedBy a) where+  (<>) :: GroupedBy a -> GroupedBy a -> GroupedBy a+  x <> y = GroupedBy{groups = M.unionWith (<>) x.groups y.groups}
+ src-lib/GHC/Eventlog/Live/Types/HeapProfBreakdown.hs view
@@ -0,0 +1,93 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.Types.HeapProfBreakdown+Description : Utilities for GHC heap profiling breakdowns.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Types.HeapProfBreakdown (+  HeapProfBreakdown (..),+  heapProfBreakdownEitherReader,+  heapProfBreakdownShow,+  findHeapProfBreakdown,+) where++import Data.Maybe (listToMaybe, mapMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import GHC.RTS.Events (HeapProfBreakdown (..))++{- |+Parses the `HeapProfBreakdown` command-line arguments:++> heapProfBreakdownEitherReader "T" == Left HeapProfBreakdownClosureType+> heapProfBreakdownEitherReader "c" == Left HeapProfBreakdownCostCentre+> heapProfBreakdownEitherReader "m" == Left HeapProfBreakdownModule+> heapProfBreakdownEitherReader "d" == Left HeapProfBreakdownClosureDescr+> heapProfBreakdownEitherReader "y" == Left HeapProfBreakdownTypeDescr+> heapProfBreakdownEitherReader "e" == Left HeapProfBreakdownEra+> heapProfBreakdownEitherReader "r" == Left HeapProfBreakdownRetainer+> heapProfBreakdownEitherReader "b" == Left HeapProfBreakdownBiography+> heapProfBreakdownEitherReader "i" == Left HeapProfBreakdownInfoTable+-}+heapProfBreakdownEitherReader :: String -> Either String HeapProfBreakdown+heapProfBreakdownEitherReader =+  \case+    "T" -> Right HeapProfBreakdownClosureType+    "c" -> Right HeapProfBreakdownCostCentre+    "m" -> Right HeapProfBreakdownModule+    "d" -> Right HeapProfBreakdownClosureDescr+    "y" -> Right HeapProfBreakdownTypeDescr+    "e" -> Right HeapProfBreakdownEra+    "r" -> Right HeapProfBreakdownRetainer+    "b" -> Right HeapProfBreakdownBiography+    "i" -> Right HeapProfBreakdownInfoTable+    str -> Left $ "Unsupported heap profile breakdown -h" <> str++{- |+Shows a `HeapProfBreakdown` as its corresponding command-line flag:++> heapProfBreakdownShow HeapProfBreakdownClosureType == "-hT"+> heapProfBreakdownShow HeapProfBreakdownCostCentre == "-hc"+> heapProfBreakdownShow HeapProfBreakdownModule == "-hm"+> heapProfBreakdownShow HeapProfBreakdownClosureDescr == "-hd"+> heapProfBreakdownShow HeapProfBreakdownTypeDescr == "-hy"+> heapProfBreakdownShow HeapProfBreakdownEra == "-he"+> heapProfBreakdownShow HeapProfBreakdownRetainer == "-hr"+> heapProfBreakdownShow HeapProfBreakdownBiography == "-hb"+> heapProfBreakdownShow HeapProfBreakdownInfoTable == "-hi"+-}+heapProfBreakdownShow :: HeapProfBreakdown -> String+heapProfBreakdownShow =+  ("-h" <>) . \case+    HeapProfBreakdownClosureType -> "T"+    HeapProfBreakdownCostCentre -> "c"+    HeapProfBreakdownModule -> "m"+    HeapProfBreakdownClosureDescr -> "d"+    HeapProfBreakdownTypeDescr -> "y"+    HeapProfBreakdownEra -> "e"+    HeapProfBreakdownRetainer -> "r"+    HeapProfBreakdownBiography -> "b"+    HeapProfBreakdownInfoTable -> "i"++{- |+Determine the `HeapProfBreakdown` from the list of program arguments.++__Warning__: This scan is not fully correct. It merely scans for the presence+of arguments that, as a whole, parse with `heapProfBreakdownEitherReader`.+It does not handle @-with-rtsopts@ and does not restrict its search to those+arguments between @+RTS@ and @-RTS@ tags.+-}+findHeapProfBreakdown :: [Text] -> Maybe HeapProfBreakdown+findHeapProfBreakdown = listToMaybe . mapMaybe parseHeapProfBreakdown+ where+  parseHeapProfBreakdown :: Text -> Maybe HeapProfBreakdown+  parseHeapProfBreakdown arg+    | "-h" `T.isPrefixOf` arg =+        either (const Nothing) Just+          . heapProfBreakdownEitherReader+          . T.unpack+          . T.drop 2+          $ arg+    | otherwise = Nothing
+ src-lib/GHC/Eventlog/Live/Types/Logs.hs view
@@ -0,0 +1,143 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.LogRecord+Description : Representation for OTLP log records.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Types.Logs (+  -- * Logs+  SomeLogs (..),+  KnownLog (..),+  logConfig,++  -- * Log record superclass+  IsLogRecord,+  toLogRecord,++  -- * Generic log record type+  LogRecord (..),+) where++import Data.Aeson.Types (Encoding, KeyValue (..), KeyValueOmit (..), ToJSON (..), Value (..), pairs)+import Data.Default (Default)+import Data.Kind (Constraint, Type)+import Data.Proxy (Proxy)+import Data.Text (Text)+import GHC.Eventlog.Live.Config+import GHC.Eventlog.Live.Machine.WithStartTime (TimeUnixNano)+import GHC.Eventlog.Live.Types.Attribute (Attrs)+import GHC.Eventlog.Live.Types.Severity (Severity)+import GHC.Records (HasField (..))+import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)++-------------------------------------------------------------------------------+-- KnownLog & Instances+-------------------------------------------------------------------------------++type SomeLogs :: Type+data SomeLogs+  = forall log. (KnownLog log) => SomeLogs !(Proxy log) [LogRecord]++instance ToJSON SomeLogs where+  toJSON :: SomeLogs -> Value+  toJSON = Object . someLogsToKV++  toEncoding :: SomeLogs -> Encoding+  toEncoding = pairs . someLogsToKV++  omitField :: SomeLogs -> Bool+  omitField (SomeLogs _log logs) = null logs++someLogsToKV :: (KeyValueOmit e kv, Monoid kv) => SomeLogs -> kv+someLogsToKV (SomeLogs (log_ :: Proxy log) logs) =+  mconcat $+    [ "name" .= symbolVal log_+    , "logs" .?= logs+    -- "logs" is the unique property that identifies this type.+    ]+{-# INLINE someLogsToKV #-}++type KnownLog :: Symbol -> Constraint+class+  ( HasField log Logs (Maybe (GetLogConf log))+  , IsLogProcessorConfig (GetLogConf log)+  , Show (GetLogConf log)+  , Default (GetLogConf log)+  , KnownSymbol log+  ) =>+  KnownLog log+  where+  type GetLogConf log :: Type++logConfig :: forall log. (KnownLog log) => Proxy log -> Logs -> Maybe (GetLogConf log)+logConfig (_log :: Proxy log) = getField @log+{-# INLINE logConfig #-}++instance KnownLog "threadLabel" where+  type GetLogConf "threadLabel" = ThreadLabelLog++instance KnownLog "userMarker" where+  type GetLogConf "userMarker" = UserMarkerLog++instance KnownLog "userMessage" where+  type GetLogConf "userMessage" = UserMessageLog++instance KnownLog "internalLogMessage" where+  type GetLogConf "internalLogMessage" = InternalLogMessageLog++--------------------------------------------------------------------------------+-- Log Records+--------------------------------------------------------------------------------++{- |+A log record is any type that has the fields of the generic `LogRecord` type.+-}+type IsLogRecord l =+  ( HasField "value" l Text+  , HasField "maybeTimeUnixNano" l (Maybe TimeUnixNano)+  , HasField "maybeSeverity" l (Maybe Severity)+  , HasField "attrs" l Attrs+  )++toLogRecord :: (IsLogRecord l) => l -> LogRecord+toLogRecord l =+  LogRecord+    { value = l.value+    , maybeTimeUnixNano = l.maybeTimeUnixNano+    , maybeSeverity = l.maybeSeverity+    , attrs = l.attrs+    }++{- |+LogRecords combine a timestamp, message and a severity.+-}+data LogRecord = LogRecord+  { value :: !Text+  -- ^ The log message.+  , maybeTimeUnixNano :: !(Maybe TimeUnixNano)+  -- ^ The time at which the log was created.+  , maybeSeverity :: !(Maybe Severity)+  -- ^ The severity of the log.+  , attrs :: Attrs+  -- ^ A set of attributes.+  }+  deriving (Show)++instance ToJSON LogRecord where+  toJSON :: LogRecord -> Value+  toJSON = Object . logRecordToKV++  toEncoding :: LogRecord -> Encoding+  toEncoding = pairs . logRecordToKV++logRecordToKV :: (KeyValueOmit e kv, Monoid kv) => LogRecord -> kv+logRecordToKV l =+  mconcat $+    [ "value" .= l.value+    , "timeUnixNano" .?= l.maybeTimeUnixNano+    , "severity" .?= l.maybeSeverity+    , "attrs" .?= l.attrs+    ]+{-# INLINE logRecordToKV #-}
+ src-lib/GHC/Eventlog/Live/Types/Metrics.hs view
@@ -0,0 +1,586 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.Metric+Description : Representation for OTLP metrics.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Types.Metrics (+  -- * Known Metrics+  SomeMetrics (..),+  KnownMetric (..),+  getMetrics,+  metricConfig,++  -- ** Monotonicity+  Monotonicity (..),+  SMonotonicity (..),+  KnownMonotonicity (..),++  -- ** Aggregation Temporality+  AggregationTemporality (..),+  SAggregationTemporality (..),+  KnownAggregationTemporality (..),++  -- ** Metric Kind+  MetricKind (..),+  SMetricKind (..),+  KnownMetricKind (..),++  -- ** Metric Unit+  MetricUnit (..),+  SMetricUnit (..),+  KnownMetricUnit (..),+  toUCUM,++  -- ** Metric Type+  SMetricType (..),+  KnownMetricType (..),++  -- * Metric superclass+  IsMetric,+  toMetric,++  -- * Generic metric type+  Metric (..),+  (<+>),+) where++import Control.Exception (assert)+import Data.Aeson (KeyValue (..))+import Data.Aeson.Types (Encoding, KeyValueOmit (..), ToJSON (..), Value (..), pairs)+import Data.Coerce (coerce)+import Data.Default (Default)+import Data.Functor ((<&>))+import Data.Int (Int16, Int32, Int64, Int8)+import Data.Kind (Constraint, Type)+import Data.Proxy (Proxy (..))+import Data.Semigroup qualified as Semigroup+import Data.Text (Text)+import Data.Text qualified as T+import Data.Type.Equality (type (:~:) (Refl))+import Data.Word (Word16, Word32, Word64, Word8)+import GHC.Eventlog.Live.Config+import GHC.Eventlog.Live.Machine.WithStartTime (TimeUnixNano)+import GHC.Eventlog.Live.Types.Attribute (Attrs)+import GHC.Eventlog.Live.Types.Group (GroupBy (..))+import GHC.Records (HasField (..))+import GHC.TypeLits (KnownSymbol (..), Symbol, sameSymbol, symbolVal)++--------------------------------------------------------------------------------+-- Known Metrics+--------------------------------------------------------------------------------++type SomeMetrics :: Type+data SomeMetrics+  = forall metric. (KnownMetric metric) => SomeMetrics !(Proxy metric) [Metric (GetMetricType metric)]++instance ToJSON SomeMetrics where+  toJSON :: SomeMetrics -> Value+  toJSON = Object . someMetricsToKV++  toEncoding :: SomeMetrics -> Encoding+  toEncoding = pairs . someMetricsToKV++  omitField :: SomeMetrics -> Bool+  omitField (SomeMetrics _metric metrics) = null metrics++someMetricsToKV :: (KeyValueOmit e kv, Monoid kv) => SomeMetrics -> kv+someMetricsToKV (SomeMetrics (metric :: Proxy metric) metrics) =+  mconcat $+    [ "name" .= symbolVal metric+    , "metrics" .?= coerce @_ @[Metric (KnownMetricTypeWrapper (GetMetricType metric))] metrics+    -- "metrics" is the unique property that identifies this type.+    ]+{-# INLINE someMetricsToKV #-}++type KnownMetric :: Symbol -> Constraint+class+  ( HasField metric Metrics (Maybe (GetMetricConf metric))+  , IsMetricProcessorConfig (GetMetricConf metric)+  , Show (GetMetricConf metric)+  , Default (GetMetricConf metric)+  , KnownSymbol metric+  , KnownMetricType (GetMetricType metric)+  , KnownMetricKind (GetMetricKind metric)+  , KnownMetricUnit (GetMetricUnit metric)+  ) =>+  KnownMetric metric+  where+  type GetMetricConf metric :: Type+  type GetMetricType metric :: Type+  type GetMetricUnit metric :: MetricUnit+  type GetMetricKind metric :: MetricKind++getMetrics ::+  (KnownMetric metric) =>+  Proxy metric -> SomeMetrics -> Maybe [Metric (GetMetricType metric)]+getMetrics metric (SomeMetrics metric' metrics) =+  sameSymbol metric metric' <&> \Refl -> metrics++metricConfig :: forall metric. (KnownMetric metric) => Proxy metric -> Metrics -> Maybe (GetMetricConf metric)+metricConfig (_metric :: Proxy metric) = getField @metric+{-# INLINE metricConfig #-}++-- NOTE: This should be kept in sync with the list of metrics.+--       Specifically, there should be a `KnownMetric` instance for every metric.++instance KnownMetric "heapAllocated" where+  type GetMetricConf "heapAllocated" = HeapAllocatedMetric+  type GetMetricType "heapAllocated" = Word64+  type GetMetricUnit "heapAllocated" = 'Byte+  type GetMetricKind "heapAllocated" = 'Sum 'Cumulative 'Monotonic++instance KnownMetric "heapSize" where+  type GetMetricConf "heapSize" = HeapSizeMetric+  type GetMetricType "heapSize" = Word64+  type GetMetricUnit "heapSize" = 'Byte+  type GetMetricKind "heapSize" = 'Gauge++instance KnownMetric "blocksSize" where+  type GetMetricConf "blocksSize" = BlocksSizeMetric+  type GetMetricType "blocksSize" = Word64+  type GetMetricUnit "blocksSize" = 'Byte+  type GetMetricKind "blocksSize" = 'Gauge++instance KnownMetric "heapLive" where+  type GetMetricConf "heapLive" = HeapLiveMetric+  type GetMetricType "heapLive" = Word64+  type GetMetricUnit "heapLive" = 'Byte+  type GetMetricKind "heapLive" = 'Gauge++instance KnownMetric "memCurrent" where+  type GetMetricConf "memCurrent" = MemCurrentMetric+  type GetMetricType "memCurrent" = Word32+  type GetMetricUnit "memCurrent" = 'MegaBlock+  type GetMetricKind "memCurrent" = 'Gauge++instance KnownMetric "memNeeded" where+  type GetMetricConf "memNeeded" = MemNeededMetric+  type GetMetricType "memNeeded" = Word32+  type GetMetricUnit "memNeeded" = 'MegaBlock+  type GetMetricKind "memNeeded" = 'Gauge++instance KnownMetric "memReturned" where+  type GetMetricConf "memReturned" = MemReturnedMetric+  type GetMetricType "memReturned" = Word32+  type GetMetricUnit "memReturned" = 'MegaBlock+  type GetMetricKind "memReturned" = 'Gauge++instance KnownMetric "gcCopied" where+  type GetMetricConf "gcCopied" = GcCopiedMetric+  type GetMetricType "gcCopied" = Word64+  type GetMetricUnit "gcCopied" = 'Byte+  type GetMetricKind "gcCopied" = 'Gauge++instance KnownMetric "gcSlop" where+  type GetMetricConf "gcSlop" = GcSlopMetric+  type GetMetricType "gcSlop" = Word64+  type GetMetricUnit "gcSlop" = 'Byte+  type GetMetricKind "gcSlop" = 'Gauge++instance KnownMetric "gcFragmentation" where+  type GetMetricConf "gcFragmentation" = GcFragmentationMetric+  type GetMetricType "gcFragmentation" = Word64+  type GetMetricUnit "gcFragmentation" = 'Byte+  type GetMetricKind "gcFragmentation" = 'Gauge++instance KnownMetric "heapProfSample" where+  type GetMetricConf "heapProfSample" = HeapProfSampleMetric+  type GetMetricType "heapProfSample" = Word64+  type GetMetricUnit "heapProfSample" = 'Byte+  type GetMetricKind "heapProfSample" = 'Gauge++instance KnownMetric "capabilityUsage" where+  type GetMetricConf "capabilityUsage" = CapabilityUsageMetric+  type GetMetricType "capabilityUsage" = TimeUnixNano+  type GetMetricUnit "capabilityUsage" = 'NanoSecond+  type GetMetricKind "capabilityUsage" = 'Sum 'Cumulative 'Monotonic++instance KnownMetric "productivity" where+  type GetMetricConf "productivity" = ProductivityMetric+  type GetMetricType "productivity" = Double+  type GetMetricUnit "productivity" = 'Percent+  type GetMetricKind "productivity" = 'Gauge++instance KnownMetric "internalEventCount" where+  type GetMetricConf "internalEventCount" = InternalEventCountMetric+  type GetMetricType "internalEventCount" = Word+  type GetMetricUnit "internalEventCount" = 'Arbitrary "event"+  type GetMetricKind "internalEventCount" = 'Sum 'Cumulative 'Monotonic++instance KnownMetric "internalExportedLogs" where+  type GetMetricConf "internalExportedLogs" = InternalExportedLogsMetric+  type GetMetricType "internalExportedLogs" = Int64+  type GetMetricUnit "internalExportedLogs" = 'Arbitrary "log"+  type GetMetricKind "internalExportedLogs" = 'Sum 'Cumulative 'Monotonic++instance KnownMetric "internalRejectedLogs" where+  type GetMetricConf "internalRejectedLogs" = InternalRejectedLogsMetric+  type GetMetricType "internalRejectedLogs" = Int64+  type GetMetricUnit "internalRejectedLogs" = 'Arbitrary "log"+  type GetMetricKind "internalRejectedLogs" = 'Sum 'Cumulative 'Monotonic++instance KnownMetric "internalExportedMetrics" where+  type GetMetricConf "internalExportedMetrics" = InternalExportedMetricsMetric+  type GetMetricType "internalExportedMetrics" = Int64+  type GetMetricUnit "internalExportedMetrics" = 'Arbitrary "metric"+  type GetMetricKind "internalExportedMetrics" = 'Sum 'Cumulative 'Monotonic++instance KnownMetric "internalRejectedMetrics" where+  type GetMetricConf "internalRejectedMetrics" = InternalRejectedMetricsMetric+  type GetMetricType "internalRejectedMetrics" = Int64+  type GetMetricUnit "internalRejectedMetrics" = 'Arbitrary "metric"+  type GetMetricKind "internalRejectedMetrics" = 'Sum 'Cumulative 'Monotonic++instance KnownMetric "internalExportedSamples" where+  type GetMetricConf "internalExportedSamples" = InternalExportedSamplesMetric+  type GetMetricType "internalExportedSamples" = Int64+  type GetMetricUnit "internalExportedSamples" = 'Arbitrary "sample"+  type GetMetricKind "internalExportedSamples" = 'Sum 'Cumulative 'Monotonic++instance KnownMetric "internalRejectedSamples" where+  type GetMetricConf "internalRejectedSamples" = InternalRejectedSamplesMetric+  type GetMetricType "internalRejectedSamples" = Int64+  type GetMetricUnit "internalRejectedSamples" = 'Arbitrary "sample"+  type GetMetricKind "internalRejectedSamples" = 'Sum 'Cumulative 'Monotonic++instance KnownMetric "internalExportedSpans" where+  type GetMetricConf "internalExportedSpans" = InternalExportedSpansMetric+  type GetMetricType "internalExportedSpans" = Int64+  type GetMetricUnit "internalExportedSpans" = 'Arbitrary "span"+  type GetMetricKind "internalExportedSpans" = 'Sum 'Cumulative 'Monotonic++instance KnownMetric "internalRejectedSpans" where+  type GetMetricConf "internalRejectedSpans" = InternalRejectedSpansMetric+  type GetMetricType "internalRejectedSpans" = Int64+  type GetMetricUnit "internalRejectedSpans" = 'Arbitrary "span"+  type GetMetricKind "internalRejectedSpans" = 'Sum 'Cumulative 'Monotonic++--------------------------------------------------------------------------------+-- Superclass for metric types+--------------------------------------------------------------------------------++{- |+A metric is any type that has the fields of the generic metric type.+-}+type IsMetric ma a =+  ( HasField "value" ma a+  , HasField "maybeTimeUnixNano" ma (Maybe TimeUnixNano)+  , HasField "maybeStartTimeUnixNano" ma (Maybe TimeUnixNano)+  , HasField "attrs" ma Attrs+  )++toMetric :: (IsMetric ma a) => ma -> Metric a+toMetric ma =+  Metric+    { value = ma.value+    , maybeTimeUnixNano = ma.maybeTimeUnixNano+    , maybeStartTimeUnixNano = ma.maybeStartTimeUnixNano+    , attrs = ma.attrs+    }++--------------------------------------------------------------------------------+-- Generic metric type+--------------------------------------------------------------------------------++{- |+Metrics combine a measurement with a timestamp representing the time of the+measurement, a timestamp representing the earliest possible measurement, and+a list of attributes.+-}+data Metric a = Metric+  { value :: !a+  -- ^ The measurement.+  , maybeTimeUnixNano :: !(Maybe TimeUnixNano)+  -- ^ The time at which the measurement was taken.+  , maybeStartTimeUnixNano :: !(Maybe TimeUnixNano)+  {- ^ The earliest time at which any measurement could have been taken.+  Usually, this represents the start time of a process.+  -}+  , attrs :: Attrs+  -- ^ A set of attributes.+  }+  deriving (Functor, Foldable, Traversable, Show)++instance (ToJSON a) => ToJSON (Metric a) where+  toJSON :: Metric a -> Value+  toJSON = Object . metricToKV++  toEncoding :: Metric a -> Encoding+  toEncoding = pairs . metricToKV++metricToKV :: (KeyValueOmit e kv, Monoid kv, ToJSON a) => Metric a -> kv+metricToKV m =+  mconcat $+    [ "value" .= m.value+    , "timeUnixNano" .?= m.maybeTimeUnixNano+    , "startTimeUnixNano" .?= m.maybeStartTimeUnixNano+    , "attrs" .?= m.attrs+    ]+{-# INLINE metricToKV #-}++instance GroupBy (Metric a) where+  type Key (Metric a) = Attrs+  toKey :: Metric a -> Attrs+  toKey = (.attrs)++instance (Semigroup a) => Semigroup (Metric a) where+  (<>) :: Metric a -> Metric a -> Metric a+  x <> y =+    assert (x.attrs == y.attrs) $+      Metric+        { value = x.value <> y.value+        , maybeTimeUnixNano = forceMaybe $ x.maybeTimeUnixNano `max` y.maybeTimeUnixNano+        , maybeStartTimeUnixNano = forceMaybe $ x.maybeStartTimeUnixNano `min` y.maybeStartTimeUnixNano+        , attrs = x.attrs+        }+   where+    -- NOTE: Without this function, `max` creates a space leak.+    forceMaybe :: Maybe b -> Maybe b+    forceMaybe Nothing = Nothing+    forceMaybe (Just b) = b `seq` Just b++(<+>) :: forall a. (Semigroup (Semigroup.Sum a)) => Metric a -> Metric a -> Metric a+x <+> y = unSum (toSum x <> toSum y)+ where+  toSum = coerce @(Metric a) @(Metric (Semigroup.Sum a))+  unSum = coerce @(Metric (Semigroup.Sum a)) @(Metric a)+{-# INLINE (<+>) #-}++--------------------------------------------------------------------------------+-- Type-Level Information for Metrics+--------------------------------------------------------------------------------++--------------------------------------------------------------------------------+-- Monotonicity++data Monotonicity+  = Monotonic+  | NonMonotonic++data SMonotonicity monotonicity where+  SMonotonic :: SMonotonicity 'Monotonic+  SNonMonotonic :: SMonotonicity 'NonMonotonic++type KnownMonotonicity :: Monotonicity -> Constraint+class KnownMonotonicity monotonicity where+  monotonicitySing :: Proxy monotonicity -> SMonotonicity monotonicity++instance KnownMonotonicity 'Monotonic where+  monotonicitySing _proxy = SMonotonic+  {-# INLINE monotonicitySing #-}++instance KnownMonotonicity 'NonMonotonic where+  monotonicitySing _proxy = SNonMonotonic+  {-# INLINE monotonicitySing #-}++--------------------------------------------------------------------------------+-- AggregationTemporality++data AggregationTemporality+  = Cumulative+  | Delta++data SAggregationTemporality aggregationTemporality where+  SCumulative :: SAggregationTemporality 'Cumulative+  SDelta :: SAggregationTemporality 'Delta++type KnownAggregationTemporality :: AggregationTemporality -> Constraint+class KnownAggregationTemporality aggregationTemporality where+  aggregationTemporalitySing :: Proxy aggregationTemporality -> SAggregationTemporality aggregationTemporality++instance KnownAggregationTemporality 'Cumulative where+  aggregationTemporalitySing _proxy = SCumulative+  {-# INLINE aggregationTemporalitySing #-}++instance KnownAggregationTemporality 'Delta where+  aggregationTemporalitySing _proxy = SDelta+  {-# INLINE aggregationTemporalitySing #-}++--------------------------------------------------------------------------------+-- Metric Point Kinds++data MetricKind+  = Gauge+  | Sum AggregationTemporality Monotonicity++data SMetricKind metricKind where+  SGauge :: SMetricKind 'Gauge+  SSum :: SAggregationTemporality aggregationTemporality -> SMonotonicity monotonicity -> SMetricKind ('Sum aggregationTemporality monotonicity)++type KnownMetricKind :: MetricKind -> Constraint+class KnownMetricKind metricKind where+  metricKindSing :: Proxy metricKind -> SMetricKind metricKind++instance KnownMetricKind 'Gauge where+  metricKindSing _proxy = SGauge+  {-# INLINE metricKindSing #-}++instance (KnownAggregationTemporality aggregationTemporality, KnownMonotonicity monotonicity) => KnownMetricKind ('Sum aggregationTemporality monotonicity) where+  metricKindSing _proxy = SSum (aggregationTemporalitySing (Proxy @aggregationTemporality)) (monotonicitySing (Proxy @monotonicity))+  {-# INLINE metricKindSing #-}++--------------------------------------------------------------------------------+-- Metric Units++data MetricUnit+  = Byte+  | MegaBlock+  | NanoSecond+  | Percent+  | Arbitrary Symbol++data SMetricUnit metricUnit where+  SByte :: SMetricUnit 'Byte+  SMegaBlock :: SMetricUnit 'MegaBlock+  SNanoSecond :: SMetricUnit 'NanoSecond+  SPercent :: SMetricUnit 'Percent+  SArbitrary :: (KnownSymbol unit) => Proxy unit -> SMetricUnit ('Arbitrary unit)++toUCUM :: SMetricUnit metricUnit -> Text+toUCUM SByte = "By"+toUCUM SMegaBlock = "{mblock}"+toUCUM SNanoSecond = "ns"+toUCUM SPercent = "%"+toUCUM (SArbitrary unit) = "{" <> T.pack (symbolVal unit) <> "}"++type KnownMetricUnit :: MetricUnit -> Constraint+class KnownMetricUnit metricUnit where+  metricUnitSing :: Proxy metricUnit -> SMetricUnit metricUnit++instance KnownMetricUnit 'Byte where+  metricUnitSing _proxy = SByte+  {-# INLINE metricUnitSing #-}++instance KnownMetricUnit 'MegaBlock where+  metricUnitSing _proxy = SMegaBlock+  {-# INLINE metricUnitSing #-}++instance KnownMetricUnit 'NanoSecond where+  metricUnitSing _proxy = SNanoSecond+  {-# INLINE metricUnitSing #-}++instance KnownMetricUnit 'Percent where+  metricUnitSing _proxy = SPercent+  {-# INLINE metricUnitSing #-}++instance (KnownSymbol symbol) => KnownMetricUnit ('Arbitrary symbol) where+  metricUnitSing _proxy = SArbitrary Proxy+  {-# INLINE metricUnitSing #-}++--------------------------------------------------------------------------------+-- Metric Types++data SMetricType (a :: Type) where+  SMetricTypeFloat :: SMetricType Float+  SMetricTypeDouble :: SMetricType Double+  SMetricTypeWord :: SMetricType Word+  SMetricTypeWord8 :: SMetricType Word8+  SMetricTypeWord16 :: SMetricType Word16+  SMetricTypeWord32 :: SMetricType Word32+  SMetricTypeWord64 :: SMetricType Word64+  SMetricTypeInt :: SMetricType Int+  SMetricTypeInt8 :: SMetricType Int8+  SMetricTypeInt16 :: SMetricType Int16+  SMetricTypeInt32 :: SMetricType Int32+  SMetricTypeInt64 :: SMetricType Int64++class (Num a) => KnownMetricType a where+  metricTypeSing :: Proxy a -> SMetricType a++instance KnownMetricType Float where+  metricTypeSing :: Proxy Float -> SMetricType Float+  metricTypeSing _proxy = SMetricTypeFloat+  {-# INLINE metricTypeSing #-}++instance KnownMetricType Double where+  metricTypeSing :: Proxy Double -> SMetricType Double+  metricTypeSing _proxy = SMetricTypeDouble+  {-# INLINE metricTypeSing #-}++instance KnownMetricType Word where+  metricTypeSing :: Proxy Word -> SMetricType Word+  metricTypeSing _proxy = SMetricTypeWord+  {-# INLINE metricTypeSing #-}++instance KnownMetricType Word8 where+  metricTypeSing :: Proxy Word8 -> SMetricType Word8+  metricTypeSing _proxy = SMetricTypeWord8+  {-# INLINE metricTypeSing #-}++instance KnownMetricType Word16 where+  metricTypeSing :: Proxy Word16 -> SMetricType Word16+  metricTypeSing _proxy = SMetricTypeWord16+  {-# INLINE metricTypeSing #-}++instance KnownMetricType Word32 where+  metricTypeSing :: Proxy Word32 -> SMetricType Word32+  metricTypeSing _proxy = SMetricTypeWord32+  {-# INLINE metricTypeSing #-}++instance KnownMetricType Word64 where+  metricTypeSing :: Proxy Word64 -> SMetricType Word64+  metricTypeSing _proxy = SMetricTypeWord64+  {-# INLINE metricTypeSing #-}++instance KnownMetricType Int where+  metricTypeSing :: Proxy Int -> SMetricType Int+  metricTypeSing _proxy = SMetricTypeInt+  {-# INLINE metricTypeSing #-}++instance KnownMetricType Int8 where+  metricTypeSing :: Proxy Int8 -> SMetricType Int8+  metricTypeSing _proxy = SMetricTypeInt8+  {-# INLINE metricTypeSing #-}++instance KnownMetricType Int16 where+  metricTypeSing :: Proxy Int16 -> SMetricType Int16+  metricTypeSing _proxy = SMetricTypeInt16+  {-# INLINE metricTypeSing #-}++instance KnownMetricType Int32 where+  metricTypeSing :: Proxy Int32 -> SMetricType Int32+  metricTypeSing _proxy = SMetricTypeInt32+  {-# INLINE metricTypeSing #-}++instance KnownMetricType Int64 where+  metricTypeSing :: Proxy Int64 -> SMetricType Int64+  metricTypeSing _proxy = SMetricTypeInt64+  {-# INLINE metricTypeSing #-}++newtype KnownMetricTypeWrapper a = KnownMetricTypeWrapper {metricValue :: a}++instance (KnownMetricType a) => ToJSON (KnownMetricTypeWrapper a) where+  toJSON :: KnownMetricTypeWrapper a -> Value+  toJSON =+    case metricTypeSing (Proxy @a) of+      SMetricTypeFloat -> toJSON . (.metricValue)+      SMetricTypeDouble -> toJSON . (.metricValue)+      SMetricTypeWord -> toJSON . (.metricValue)+      SMetricTypeWord8 -> toJSON . (.metricValue)+      SMetricTypeWord16 -> toJSON . (.metricValue)+      SMetricTypeWord32 -> toJSON . (.metricValue)+      SMetricTypeWord64 -> toJSON . (.metricValue)+      SMetricTypeInt -> toJSON . (.metricValue)+      SMetricTypeInt8 -> toJSON . (.metricValue)+      SMetricTypeInt16 -> toJSON . (.metricValue)+      SMetricTypeInt32 -> toJSON . (.metricValue)+      SMetricTypeInt64 -> toJSON . (.metricValue)++  toEncoding :: KnownMetricTypeWrapper a -> Encoding+  toEncoding =+    case metricTypeSing (Proxy @a) of+      SMetricTypeFloat -> toEncoding . (.metricValue)+      SMetricTypeDouble -> toEncoding . (.metricValue)+      SMetricTypeWord -> toEncoding . (.metricValue)+      SMetricTypeWord8 -> toEncoding . (.metricValue)+      SMetricTypeWord16 -> toEncoding . (.metricValue)+      SMetricTypeWord32 -> toEncoding . (.metricValue)+      SMetricTypeWord64 -> toEncoding . (.metricValue)+      SMetricTypeInt -> toEncoding . (.metricValue)+      SMetricTypeInt8 -> toEncoding . (.metricValue)+      SMetricTypeInt16 -> toEncoding . (.metricValue)+      SMetricTypeInt32 -> toEncoding . (.metricValue)+      SMetricTypeInt64 -> toEncoding . (.metricValue)
+ src-lib/GHC/Eventlog/Live/Types/Profiles.hs view
@@ -0,0 +1,222 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.Sample+Description : Representation for OTLP stack samples.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Types.Profiles (+  -- * Samples+  SomeSamples (..),+  KnownProfile (..),+  profileConfig,++  -- * Sample superclass+  IsSample,+  toSample,++  -- * Generic Sample Kind+  Sample (..),+  Location (..),+) where++import Data.Aeson.Types (Encoding, KeyValue (..), KeyValueOmit (..), ToJSON (..), Value (..), pairs)+import Data.Default (Default)+import Data.Int (Int64)+import Data.Kind (Constraint, Type)+import Data.Proxy (Proxy)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Vector (Vector)+import Data.Word (Word8)+import GHC.Eventlog.Live.Config (CallStackProfile (..), CostCentreStackProfile (..), IsProfileProcessorConfig, Profiles (..))+import GHC.Eventlog.Live.Machine.WithStartTime (TimeUnixNano)+import GHC.Eventlog.Live.Types.Attribute (Attrs)+import GHC.Records (HasField (..))+import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)+import IpeDB.Types.SrcLoc (Range (..), SrcLoc (..))++--------------------------------------------------------------------------------+-- Samples+--------------------------------------------------------------------------------++type SomeSamples :: Type+data SomeSamples+  = forall profile.+    (KnownProfile profile) =>+    SomeSamples+      !(Proxy profile)+      ![Sample (GetProfileMetricType profile)]++instance ToJSON SomeSamples where+  toJSON :: SomeSamples -> Value+  toJSON = Object . someSamplesToKV++  toEncoding :: SomeSamples -> Encoding+  toEncoding = pairs . someSamplesToKV++  omitField :: SomeSamples -> Bool+  omitField (SomeSamples _profile samples) = null samples++someSamplesToKV :: (KeyValueOmit e kv, Monoid kv) => SomeSamples -> kv+someSamplesToKV (SomeSamples (profile :: Proxy profile) samples) =+  mconcat $+    [ "name" .= symbolVal profile+    , "samples" .?= (fmap (fromIntegral @_ @Int64) <$> samples)+    -- "samples" is the unique property that identifies this type.+    ]+{-# INLINE someSamplesToKV #-}++-------------------------------------------------------------------------------+-- KnownProfile & Instances+-------------------------------------------------------------------------------++type KnownProfile :: Symbol -> Constraint+class+  ( HasField profile Profiles (Maybe (GetProfileConf profile))+  , IsProfileProcessorConfig (GetProfileConf profile)+  , Show (GetProfileConf profile)+  , Default (GetProfileConf profile)+  , KnownSymbol profile+  , KnownSymbol (GetProfileMetricName profile)+  , Integral (GetProfileMetricType profile)+  , KnownSymbol (GetProfileMetricUnit profile)+  ) =>+  KnownProfile profile+  where+  type GetProfileConf profile :: Type+  type GetProfileMetricName profile :: Symbol+  type GetProfileMetricType profile :: Type+  type GetProfileMetricUnit profile :: Symbol++profileConfig :: forall profile. (KnownProfile profile) => Proxy profile -> Profiles -> Maybe (GetProfileConf profile)+profileConfig (_profile :: Proxy profile) = getField @profile+{-# INLINE profileConfig #-}++instance KnownProfile "callStackProfile" where+  type GetProfileConf "callStackProfile" = CallStackProfile+  type GetProfileMetricName "callStackProfile" = "callStack"+  type GetProfileMetricType "callStackProfile" = Word8+  type GetProfileMetricUnit "callStackProfile" = "count"++instance KnownProfile "costCentreStackProfile" where+  type GetProfileConf "costCentreStackProfile" = CostCentreStackProfile+  type GetProfileMetricName "costCentreStackProfile" = "costCentreStack"+  type GetProfileMetricType "costCentreStackProfile" = Word8+  type GetProfileMetricUnit "costCentreStackProfile" = "count"++--------------------------------------------------------------------------------+-- Superclass for span types+--------------------------------------------------------------------------------++type IsSample s v =+  ( HasField "value" s v+  , HasField "stack" s (Vector Location)+  , HasField "maybeTimeUnixNano" s (Maybe TimeUnixNano)+  , HasField "attrs" s Attrs+  )++toSample :: (IsSample s v) => s -> Sample v+toSample s =+  Sample+    { value = s.value+    , stack = s.stack+    , maybeTimeUnixNano = s.maybeTimeUnixNano+    , attrs = s.attrs+    }++--------------------------------------------------------------------------------+-- Generic sample type+--------------------------------------------------------------------------------++-- TODO: This sample type encodes the one-value, one-timestamp shape, but+--       the OTLP specification supports many other shapes.+--       See: https://github.com/open-telemetry/opentelemetry-proto/blob/b3f75588eb23c5fca62264edd05d382de49beb1a/opentelemetry/proto/profiles/v1development/profiles.proto#L460-L493++data Sample v = Sample+  { value :: !v+  , stack :: !(Vector Location)+  , maybeTimeUnixNano :: !(Maybe TimeUnixNano)+  -- ^ The time at which the sample was taken.+  , attrs :: Attrs+  -- ^ A set of attributes.+  }+  deriving (Functor)++instance (ToJSON v) => ToJSON (Sample v) where+  toJSON :: Sample v -> Value+  toJSON = Object . sampleToKV++  toEncoding :: Sample v -> Encoding+  toEncoding = pairs . sampleToKV++sampleToKV ::+  forall e kv v.+  (KeyValueOmit e kv, Monoid kv, ToJSON v) =>+  Sample v -> kv+sampleToKV s =+  mconcat+    [ "value" .= s.value+    , "stack" .?= s.stack+    , "timeUnixNano" .?= s.maybeTimeUnixNano+    , "attrs" .?= s.attrs+    ]+{-# INLINE sampleToKV #-}++data Location = Location+  { name :: !Text+  , srcLoc :: !SrcLoc+  }++instance ToJSON Location where+  toJSON :: Location -> Value+  toJSON = Object . locationToKV++  toEncoding :: Location -> Encoding+  toEncoding = pairs . locationToKV++locationToKV ::+  forall e kv.+  (KeyValueOmit e kv, Monoid kv) =>+  Location -> kv+locationToKV l =+  mconcat+    [ "name" .= l.name `onlyIf` (not . T.null)+    , srcLocToKV l.srcLoc+    ]+ where+  srcLocToKV :: SrcLoc -> kv+  srcLocToKV = \case+    UnhelpfulSrcLoc ->+      mempty+    SrcLoc{..} ->+      mconcat+        [ "file" .?= srcFilePath `onlyIf` (not . null)+        , maybe mempty rangeToKV srcRange+        ]++  rangeToKV :: Range -> kv+  rangeToKV = \case+    Range'Point{..} ->+      mconcat+        [ "line" .= line+        , "column" .= column+        ]+    Range'OneLine{..} ->+      mconcat+        [ "line" .= line+        , "column" .= column+        , "endColumn" .= endColumn+        ]+    Range'MultiLine{..} ->+      mconcat+        [ "line" .= line+        , "column" .= column+        , "endLine" .= endLine+        , "endColumn" .= endColumn+        ]++  onlyIf :: a -> (a -> Bool) -> Maybe a+  onlyIf a p = if p a then Just a else Nothing+{-# INLINE locationToKV #-}
+ src-lib/GHC/Eventlog/Live/Types/Severity.hs view
@@ -0,0 +1,93 @@+{- |+Module      : GHC.Eventlog.Live.Severity+Description : Representation for OTLP log record severities.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Types.Severity (+  Severity (..),+  SeverityNumber (..),+  toSeverityNumber,+  fromSeverityNumber,+  toSeverityString,+  fromSeverityString,+) where++import Data.Aeson (Value)+import Data.Aeson.Types (Encoding, ToJSON (..))+import Data.Char (toUpper)+import Data.Ix (Ix)+import Text.Read (readMaybe)++{- |+The severity number as specified by the OpenTelemetry specification.++See: https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-severitynumber+-}+newtype SeverityNumber = SeverityNumber {value :: Int}++{- |+The severity as specified by the OpenTelemetry specification.++See: https://opentelemetry.io/docs/specs/otel/logs/data-model/#displaying-severity+-}+data Severity+  = TRACE+  | TRACE2+  | TRACE3+  | TRACE4+  | DEBUG+  | DEBUG2+  | DEBUG3+  | DEBUG4+  | INFO+  | INFO2+  | INFO3+  | INFO4+  | WARN+  | WARN2+  | WARN3+  | WARN4+  | ERROR+  | ERROR2+  | ERROR3+  | ERROR4+  | FATAL+  | FATAL2+  | FATAL3+  | FATAL4+  deriving (Bounded, Enum, Eq, Ord, Read, Show, Ix)++instance ToJSON Severity where+  toJSON :: Severity -> Value+  toJSON = toJSON . (.value) . toSeverityNumber++  toEncoding :: Severity -> Encoding+  toEncoding = toEncoding . (.value) . toSeverityNumber++{- |+Convert from a `Severity` to a `SeverityNumber`.+-}+toSeverityNumber :: Severity -> SeverityNumber+toSeverityNumber = SeverityNumber . (+ 1) . fromEnum++{- |+Convert from a `SeverityNumber` to a `Severity`.+-}+fromSeverityNumber :: SeverityNumber -> Maybe Severity+fromSeverityNumber severityNumber+  | 1 <= severityNumber.value && severityNumber.value <= 24 =+      Just (toEnum $ severityNumber.value - 1)+  | otherwise = Nothing++{- |+Convert from a `Severity` to a `String`.+-}+toSeverityString :: Severity -> String+toSeverityString = show++{- |+Convert from a `String` to a `Severity`.+-}+fromSeverityString :: String -> Maybe Severity+fromSeverityString = readMaybe . fmap toUpper
+ src-lib/GHC/Eventlog/Live/Types/Thread.hs view
@@ -0,0 +1,36 @@+{- |+Module      : GHC.Eventlog.Live.Types.Thread+Description : Reprsentation for thread data.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Types.Thread (+  ThreadId (..),+  fromThreadId,+) where++import Data.Word (Word64)+import GHC.Eventlog.Live.Types.Attribute (IsAttrValue)+import GHC.Stack.Profiler.Core qualified as GSP++{- |+A thread ID.++In the GHC RTS, all threads are assigned a `Word64` identifier.+However, thread IDs are posted to the eventlog as `Word32` values.++In @ghc-events@, the thread ID is received and represented as a `Word32` value.++In @ghc-stack-profiler@, the thread ID is retrieved and posted as a `Word64` value.+-}+newtype ThreadId = ThreadId+  { value :: Word64+  }+  deriving stock (Show, Eq, Ord)+  deriving newtype (IsAttrValue)++{- |+Get the thread ID from a @ghc-stack-profiler@ `ThreadId`.+-}+fromThreadId :: GSP.ThreadId -> ThreadId+fromThreadId (GSP.MkThreadId value) = ThreadId value
+ src-lib/GHC/Eventlog/Live/Types/Traces.hs view
@@ -0,0 +1,223 @@+{-# LANGUAGE OverloadedStrings #-}++{- |+Module      : GHC.Eventlog.Live.Span+Description : Representation for OTLP spans.+Stability   : experimental+Portability : portable+-}+module GHC.Eventlog.Live.Types.Traces (+  -- * Known Spans+  SomeSpans (..),+  KnownTrace (..),+  traceConfig,++  -- * Span superclass+  IsSpan,+  duration,++  -- * Generic span type+  Span (..),+  asSpan,+  toSpan,+  ToSpanState,+  initToSpanState,+) where++import Control.Monad.IO.Class (MonadIO (..))+import Control.Monad.Trans.State.Strict (State, runState, state)+import Data.Aeson.Types (Encoding, KeyValue (..), KeyValueOmit (..), ToJSON (..), Value (..), pairs)+import Data.Base64.Types qualified as B64+import Data.ByteString (ByteString)+import Data.ByteString.Base64 qualified as B64B+import Data.Default (Default)+import Data.HashMap.Strict (HashMap)+import Data.HashMap.Strict qualified as HM+import Data.Hashable (Hashable)+import Data.Kind (Constraint, Type)+import Data.Machine (ProcessT, await, construct, yield)+import Data.Proxy (Proxy)+import Data.Text (Text)+import GHC.Eventlog.Live.Config (CapabilityUsageSpan (..), IsTraceProcessorConfig, ThreadStateSpan (..), Traces (..))+import GHC.Eventlog.Live.Machine.WithStartTime (TimeUnixNano)+import GHC.Eventlog.Live.Types.Attribute (Attrs)+import GHC.Records (HasField (..))+import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)+import System.Random (StdGen, initStdGen)+import System.Random.Compat (uniformByteString)++--------------------------------------------------------------------------------+-- Known Spans+--------------------------------------------------------------------------------++type SomeSpans :: Type+data SomeSpans+  = forall trace. (KnownTrace trace) => SomeSpans !(Proxy trace) [Span]++instance ToJSON SomeSpans where+  toJSON :: SomeSpans -> Value+  toJSON = Object . someSpansToKV++  toEncoding :: SomeSpans -> Encoding+  toEncoding = pairs . someSpansToKV++  omitField :: SomeSpans -> Bool+  omitField (SomeSpans _trace spans) = null spans++someSpansToKV :: (KeyValueOmit e kv, Monoid kv) => SomeSpans -> kv+someSpansToKV (SomeSpans (trace :: Proxy trace) spans) =+  mconcat $+    [ "name" .= symbolVal trace+    , "spans" .?= spans+    -- "spans" is the unique property that identifies this type.+    ]+{-# INLINE someSpansToKV #-}++-------------------------------------------------------------------------------+-- KnownTrace & Instances+-------------------------------------------------------------------------------++type KnownTrace :: Symbol -> Constraint+class+  ( HasField trace Traces (Maybe (GetTraceConf trace))+  , IsTraceProcessorConfig (GetTraceConf trace)+  , Show (GetTraceConf trace)+  , Default (GetTraceConf trace)+  , KnownSymbol trace+  ) =>+  KnownTrace trace+  where+  type GetTraceConf trace :: Type++traceConfig :: forall trace. (KnownTrace trace) => Proxy trace -> Traces -> Maybe (GetTraceConf trace)+traceConfig (_trace :: Proxy trace) = getField @trace+{-# INLINE traceConfig #-}++instance KnownTrace "capabilityUsage" where+  type GetTraceConf "capabilityUsage" = CapabilityUsageSpan++instance KnownTrace "threadState" where+  type GetTraceConf "threadState" = ThreadStateSpan++--------------------------------------------------------------------------------+-- Superclass for span types+--------------------------------------------------------------------------------++{- |+A span is any type with a start and end time.+-}+type IsSpan s k =+  ( HasField "traceId" s k+  , HasField "startTimeUnixNano" s TimeUnixNano+  , HasField "endTimeUnixNano" s TimeUnixNano+  , HasField "attrs" s Attrs+  , Hashable k+  )++{- |+Determine the duration of a span.+-}+duration ::+  ( HasField "startTimeUnixNano" s TimeUnixNano+  , HasField "endTimeUnixNano" s TimeUnixNano+  ) =>+  s -> TimeUnixNano+duration s+  | s.startTimeUnixNano < s.endTimeUnixNano = s.endTimeUnixNano - s.startTimeUnixNano+  | otherwise = 0+{-# INLINEABLE duration #-}++--------------------------------------------------------------------------------+-- Generic span type+--------------------------------------------------------------------------------++-- TODO:+-- The current `Span` type only supports a small subset of OpenTelemetry's+-- specification for spans, e.g., it doesn't support parent spans, links,+-- or events, doesn't support span kinds, and doesn't support status codes.++data Span = Span+  { traceId :: !ByteString+  , spanId :: !ByteString+  , startTimeUnixNano :: !TimeUnixNano+  , endTimeUnixNano :: !TimeUnixNano+  , attrs :: Attrs+  }++instance HasField "traceIdBase64" Span Text where+  getField :: Span -> Text+  getField = B64.extractBase64 . B64B.encodeBase64 . (.traceId)++instance HasField "spanIdBase64" Span Text where+  getField :: Span -> Text+  getField = B64.extractBase64 . B64B.encodeBase64 . (.spanId)++instance ToJSON Span where+  toJSON :: Span -> Value+  toJSON = Object . spanToKV++  toEncoding :: Span -> Encoding+  toEncoding = pairs . spanToKV++spanToKV :: (KeyValueOmit e kv, Monoid kv) => Span -> kv+spanToKV s =+  mconcat $+    [ "traceId" .= s.traceIdBase64+    , "spanId" .= s.spanIdBase64+    , "startTimeUnixNano" .= s.startTimeUnixNano+    , "endTimeUnixNano" .= s.endTimeUnixNano+    , "attrs" .?= s.attrs+    ]+{-# INLINE spanToKV #-}++data ToSpanState k = ToSpanState+  { traceIdMap :: !(HashMap k ByteString)+  , stdGen :: !StdGen+  }++initToSpanState :: StdGen -> ToSpanState k+initToSpanState stdGen = ToSpanState{traceIdMap = HM.empty, ..}++asSpan :: (MonadIO m, IsSpan s k) => ProcessT m s Span+asSpan = construct $ go Nothing+ where+  -- go :: Maybe (ToSpanState k) -> PlanT (Is s) Span m Void+  go Nothing = do+    stdGen <- liftIO initStdGen+    go (Just $ initToSpanState stdGen)+  go (Just st) =+    await >>= \s -> do+      let (s', st') = runState (toSpan s) st+      yield s'+      go (Just st')++toSpan :: (IsSpan s k) => s -> State (ToSpanState k) Span+toSpan s = do+  traceId <- state (getTraceId s.traceId)+  spanId <- state getSpanId+  pure+    Span+      { startTimeUnixNano = s.startTimeUnixNano+      , endTimeUnixNano = s.endTimeUnixNano+      , attrs = s.attrs+      , ..+      }++getTraceId :: (Hashable k) => k -> ToSpanState k -> (ByteString, ToSpanState k)+getTraceId k st =+  let ((traceId, stdGen), traceIdMap) = HM.alterF ensureTraceId k st.traceIdMap+   in (traceId, st{traceIdMap = traceIdMap, stdGen = stdGen})+ where+  ensureTraceId :: Maybe ByteString -> ((ByteString, StdGen), Maybe ByteString)+  ensureTraceId = \case+    Nothing ->+      ((traceId, stdGen'), Just traceId)+     where+      (traceId, stdGen') = uniformByteString 16 st.stdGen+    Just traceId ->+      ((traceId, st.stdGen), Just traceId)++getSpanId :: ToSpanState k -> (ByteString, ToSpanState k)+getSpanId st =+  let (spanId, stdGen) = uniformByteString 8 st.stdGen+   in (spanId, st{stdGen = stdGen})
− src/GHC/Eventlog/Live/Data/Attribute.hs
@@ -1,172 +0,0 @@-{- |-Module      : GHC.Eventlog.Live.Attribute-Description : Representation for attributes.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Data.Attribute (-  Attrs,-  toList,-  Attr,-  AttrKey,-  AttrValue (..),-  IsAttrValue (..),-  (~=),-) where--import Data.HashMap.Strict (HashMap)-import Data.HashMap.Strict qualified as M-import Data.Hashable (Hashable)-import Data.Int (Int16, Int32, Int64, Int8)-import Data.Text (Text)-import Data.Text qualified as T-import Data.Word (Word16, Word32, Word64, Word8)-import GHC.Generics (Generic)-import GHC.IsList (IsList (..))--{- |-A set of attributes is a t`HashMap`--}-newtype Attrs = Attrs {attrMap :: HashMap AttrKey AttrValue}-  deriving (Eq, Generic, Show)--instance Hashable Attrs--instance Semigroup Attrs where-  (<>) :: Attrs -> Attrs -> Attrs-  x <> y = Attrs{attrMap = x.attrMap <> y.attrMap}--instance IsList Attrs where-  type Item Attrs = Attr--  fromList :: [Item Attrs] -> Attrs-  fromList = Attrs . M.fromList--  toList :: Attrs -> [Item Attrs]-  toList = M.toList . (.attrMap)--{- |-An attribute is a key-value pair where the key is any string and the value is-some numeric type, string, or null. Attributes should be constructed using the-`(~=)` operator, which automatically converts Haskell types to t`AttrValue`.--}-type Attr = (AttrKey, AttrValue)--{- |-Construct an t`Attr` as a pair of an t`AttrKey` and an t`AttrValue`,-constructed via the t`IsAttrValue` class.--}-(~=) :: (IsAttrValue v) => AttrKey -> v -> Attr-k ~= v = (ak, av)- where-  !ak = k-  !av = toAttrValue v-{-# INLINE (~=) #-}--{- |-The type of attribute keys.--}-type AttrKey =-  Text--{- |-The type of attribute values.--}-data AttrValue-  = AttrInt !Int-  | AttrInt8 !Int8-  | AttrInt16 !Int16-  | AttrInt32 !Int32-  | AttrInt64 !Int64-  | AttrWord !Word-  | AttrWord8 !Word8-  | AttrWord16 !Word16-  | AttrWord32 !Word32-  | AttrWord64 !Word64-  | AttrDouble !Double-  | AttrText !Text-  | AttrNull-  deriving (Eq, Generic, Show)--instance Hashable AttrValue--{- |-Utility class to help construct values of the t`AttrValue` type.--}-class IsAttrValue v where-  toAttrValue :: v -> AttrValue--instance IsAttrValue AttrValue where-  toAttrValue :: AttrValue -> AttrValue-  toAttrValue = id-  {-# INLINE toAttrValue #-}--instance IsAttrValue Int where-  toAttrValue :: Int -> AttrValue-  toAttrValue = AttrInt-  {-# INLINE toAttrValue #-}--instance IsAttrValue Int8 where-  toAttrValue :: Int8 -> AttrValue-  toAttrValue = AttrInt8-  {-# INLINE toAttrValue #-}--instance IsAttrValue Int16 where-  toAttrValue :: Int16 -> AttrValue-  toAttrValue = AttrInt16-  {-# INLINE toAttrValue #-}--instance IsAttrValue Int32 where-  toAttrValue :: Int32 -> AttrValue-  toAttrValue = AttrInt32-  {-# INLINE toAttrValue #-}--instance IsAttrValue Int64 where-  toAttrValue :: Int64 -> AttrValue-  toAttrValue = AttrInt64-  {-# INLINE toAttrValue #-}--instance IsAttrValue Word where-  toAttrValue :: Word -> AttrValue-  toAttrValue = AttrWord-  {-# INLINE toAttrValue #-}--instance IsAttrValue Word8 where-  toAttrValue :: Word8 -> AttrValue-  toAttrValue = AttrWord8-  {-# INLINE toAttrValue #-}--instance IsAttrValue Word16 where-  toAttrValue :: Word16 -> AttrValue-  toAttrValue = AttrWord16-  {-# INLINE toAttrValue #-}--instance IsAttrValue Word32 where-  toAttrValue :: Word32 -> AttrValue-  toAttrValue = AttrWord32-  {-# INLINE toAttrValue #-}--instance IsAttrValue Word64 where-  toAttrValue :: Word64 -> AttrValue-  toAttrValue = AttrWord64-  {-# INLINE toAttrValue #-}--instance IsAttrValue Double where-  toAttrValue :: Double -> AttrValue-  toAttrValue = AttrDouble-  {-# INLINE toAttrValue #-}--instance IsAttrValue String where-  toAttrValue :: String -> AttrValue-  toAttrValue = AttrText . T.pack-  {-# INLINE toAttrValue #-}--instance IsAttrValue Text where-  toAttrValue :: Text -> AttrValue-  toAttrValue = AttrText-  {-# INLINE toAttrValue #-}--instance (IsAttrValue v) => IsAttrValue (Maybe v) where-  toAttrValue :: Maybe v -> AttrValue-  toAttrValue = maybe AttrNull toAttrValue-  {-# INLINE toAttrValue #-}
− src/GHC/Eventlog/Live/Data/Group.hs
@@ -1,82 +0,0 @@-{- |-Module      : GHC.Eventlog.Live.Data.Group-Description : Core machines for processing data in batches.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Data.Group (-  -- * GroupBy-  GroupBy (..),-  Group (..),-  GroupedBy,-  singleton,-  elems,-  groups,-) where--import Data.HashMap.Strict (HashMap)-import Data.HashMap.Strict qualified as M-import Data.Hashable (Hashable (..))-import Data.Kind (Type)-import Data.Semigroup (First (..), Last (..), Max (..), Min (..), Product (..), Sum (..))--{- |-This class defines the key to group by when aggregating.--}-class (Hashable (Key a)) => GroupBy a where-  type Key a :: Type-  toKey :: a -> Key a--deriving newtype instance (GroupBy a) => GroupBy (First a)-deriving newtype instance (GroupBy a) => GroupBy (Last a)-deriving newtype instance (GroupBy a) => GroupBy (Max a)-deriving newtype instance (GroupBy a) => GroupBy (Min a)-deriving newtype instance (GroupBy a) => GroupBy (Product a)-deriving newtype instance (GroupBy a) => GroupBy (Sum a)--{- |-This type defines a set of groups, grouped by the key given by `GroupBy`.--}-data GroupedBy a = (GroupBy a) => GroupedBy-  { groups :: HashMap (Key a) (Group a)-  }--{- |-Internal helper.-This type defines a group representative and the group size.--}-data Group a = Group-  { representative :: !a-  , size :: !Word-  }-  deriving (Show, Functor, Foldable, Traversable)--{- |-Construct the singleton `GroupedBy`.--}-singleton :: (GroupBy a) => a -> GroupedBy a-singleton a = GroupedBy{groups = M.singleton (toKey a) Group{representative = a, size = 1}}--{- |-Get all group representatives from a `GroupedBy`.--}-elems :: GroupedBy a -> [a]-elems = fmap (.representative) . groups--{- |-Get all group representatives and sizes from a `GroupedBy`.--}-groups :: GroupedBy a -> [Group a]-groups = M.elems . (.groups)--instance (Semigroup a) => Semigroup (Group a) where-  (<>) :: Group a -> Group a -> Group a-  x <> y =-    Group-      { representative = x.representative <> y.representative-      , size = x.size + y.size-      }--instance (Semigroup a, GroupBy a) => Semigroup (GroupedBy a) where-  (<>) :: GroupedBy a -> GroupedBy a -> GroupedBy a-  x <> y = GroupedBy{groups = M.unionWith (<>) x.groups y.groups}
− src/GHC/Eventlog/Live/Data/Metric.hs
@@ -1,48 +0,0 @@-{- |-Module      : GHC.Eventlog.Live.Metric-Description : Representation for metrics.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Data.Metric (-  Metric (..),-) where--import Control.Exception (assert)-import GHC.Eventlog.Live.Data.Attribute (Attrs)-import GHC.Eventlog.Live.Data.Group (GroupBy (..))-import GHC.RTS.Events (Timestamp)--{- |-Metrics combine a measurement with a timestamp representing the time of the-measurement, a timestamp representing the earliest possible measurment, and-a list of attributes.--}-data Metric a = Metric-  { value :: !a-  -- ^ The measurement.-  , maybeTimeUnixNano :: !(Maybe Timestamp)-  -- ^ The time at which the measurment was taken.-  , maybeStartTimeUnixNano :: !(Maybe Timestamp)-  -- ^ The earliest time at which any measurement could have been taken.-  --   Usually, this represents the start time of a process.-  , attrs :: Attrs-  -- ^ A set of attributes.-  }-  deriving (Functor, Show)--instance GroupBy (Metric a) where-  type Key (Metric a) = Attrs-  toKey :: Metric a -> Attrs-  toKey = (.attrs)--instance (Semigroup a) => Semigroup (Metric a) where-  (<>) :: Metric a -> Metric a -> Metric a-  x <> y =-    assert (x.attrs == y.attrs) $-      Metric-        { value = x.value <> y.value-        , maybeTimeUnixNano = x.maybeTimeUnixNano `max` y.maybeTimeUnixNano-        , maybeStartTimeUnixNano = x.maybeStartTimeUnixNano `min` y.maybeStartTimeUnixNano-        , attrs = x.attrs-        }
− src/GHC/Eventlog/Live/Data/Span.hs
@@ -1,25 +0,0 @@-{- |-Module      : GHC.Eventlog.Live.Span-Description : Representation for spans.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Data.Span (-  IsSpan,-  duration,-) where--import GHC.RTS.Events (Timestamp)-import GHC.Records (HasField)--{- |-A span is any type with a start and end time.--}-type IsSpan s = (HasField "startTimeUnixNano" s Timestamp, HasField "endTimeUnixNano" s Timestamp)--{- |-Determine the duration of a span.--}-duration :: (IsSpan s) => s -> Timestamp-duration s = if s.startTimeUnixNano < s.endTimeUnixNano then s.endTimeUnixNano - s.startTimeUnixNano else 0-{-# INLINEABLE duration #-}
− src/GHC/Eventlog/Live/Logger.hs
@@ -1,117 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--{- |-Module      : GHC.Eventlog.Live..Logger-Description : Logging functions.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Logger (-  logError,-  logWarning,-  logInfo,-  logDebug,-) where--import Control.Exception (bracket_)-import Control.Monad.IO.Class (MonadIO (..))-import Data.List qualified as L-import Data.Text (Text)-import Data.Text qualified as T-import Data.Text.IO qualified as TIO-import GHC.Eventlog.Live.Verbosity (Verbosity, showVerbosity, verbosityDebug, verbosityError, verbosityInfo, verbosityWarning)-import GHC.Stack (CallStack, HasCallStack, SrcLoc (..), callStack, getCallStack)-import System.Console.ANSI (Color (..), ColorIntensity (..), ConsoleLayer (..), SGR (..), hNowSupportsANSI, hSetSGR)-import System.IO qualified as IO--{- |-Log messages to given handle.-Only prints a message if its verbosity level is above the verbosity threshold.--}-logMessage :: (MonadIO m) => IO.Handle -> CallStack -> Verbosity -> Verbosity -> Text -> m ()-logMessage handle theCallStack verbosityLevel verbosityThreshold msg-  | verbosityLevel >= verbosityThreshold = liftIO $ do-      withVerbosityColor verbosityLevel handle-        . flip TIO.hPutStrLn-        . formatMessage verbosityLevel verbosityThreshold theCallStack-        $ msg-      IO.hFlush handle-  | otherwise = pure ()--{- |-Internal helper.-Format the `CallStack`.--}-formatCallStack :: CallStack -> Text-formatCallStack theCallStack =-  maybe T.empty (formatSrcLoc . snd . fst) (L.uncons (getCallStack theCallStack))- where-  formatSrcLoc :: SrcLoc -> Text-  formatSrcLoc srcLoc =-    mconcat [T.pack srcLoc.srcLocFile, ":", T.pack (show srcLoc.srcLocStartLine), ":", T.pack (show srcLoc.srcLocStartCol)]--{- |-Internal helper.-Format the message appropriately for the given verbosity level and threshold.--}-formatMessage :: Verbosity -> Verbosity -> CallStack -> Text -> Text-formatMessage verbosityLevel verbosityThreshold theCallStack msg-  | verbosityLevel == verbosityInfo && verbosityThreshold /= verbosityDebug = msg-  | otherwise = mconcat [showVerbosity verbosityLevel, " (", formatCallStack theCallStack, "): ", msg]--{- |-Internal helper.-Use a handle with the color set appropriately for the given verbosity level.--}-withVerbosityColor :: Verbosity -> IO.Handle -> (IO.Handle -> IO a) -> IO a-withVerbosityColor verbosity handle action = do-  supportsANSI <- hNowSupportsANSI handle-  if not supportsANSI-    then-      action handle-    else case verbosityColor verbosity of-      Nothing ->-        action handle-      Just color -> do-        let setVerbosityColor = hSetSGR handle [SetColor Foreground Vivid color]-        let setDefaultColor = hSetSGR handle [SetDefaultColor Foreground]-        bracket_ setVerbosityColor setDefaultColor $ action handle--{- |-Internal helper.-Determine the ANSI color associated with a particular verbosity level.--}-verbosityColor :: Verbosity -> Maybe Color-verbosityColor verbosity-  | verbosity == verbosityError = Just Red-  | verbosity == verbosityWarning = Just Yellow-  | verbosity == verbosityDebug = Just Blue-  | otherwise = Nothing--{- |-Log errors to `IO.stderr`.--}-logError :: (HasCallStack, MonadIO m) => Verbosity -> Text -> m ()-logError = logMessage IO.stderr callStack verbosityError--{- |-Log warnings to `IO.stderr`.--}-logWarning :: (HasCallStack, MonadIO m) => Verbosity -> Text -> m ()-logWarning = logMessage IO.stderr callStack verbosityWarning--{- |-Log info messages to `IO.stderr`.--}-logInfo :: (HasCallStack, MonadIO m) => Verbosity -> Text -> m ()-logInfo verbosityThreshold = logMessage handle callStack verbosityInfo verbosityThreshold- where-  handle-    | verbosityThreshold <= verbosityDebug = IO.stderr-    | otherwise = IO.stdout--{- |-Log debug messages to `IO.stderr`.--}-logDebug :: (HasCallStack, MonadIO m) => Verbosity -> Text -> m ()-logDebug = logMessage IO.stderr callStack verbosityDebug
− src/GHC/Eventlog/Live/Machine/Analysis/Capability.hs
@@ -1,478 +0,0 @@-{-# LANGUAGE OverloadedLists #-}-{-# LANGUAGE OverloadedStrings #-}-{-# OPTIONS_GHC -Wno-name-shadowing #-}--{- |-Module      : GHC.Eventlog.Live.Machine-Description : Machines for processing eventlog data.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Machine.Analysis.Capability (-  -- * Capability Usage--  -- ** Capability Usage Metrics-  processCapabilityUsageMetrics,--  -- ** Capability Usage Spans-  CapabilityUsageSpan,-  CapabilityUser (..),-  capabilityUser,-  showCapabilityUserCategory,-  processCapabilityUsageSpans,-  processCapabilityUsageSpans',--  -- ** GC Spans-  GCSpan (..),-  processGCSpans,-  processGCSpans',--  -- ** Mutator Spans-  MutatorSpan (..),-  asMutatorSpans,-  asMutatorSpans',-  processMutatorSpans,-  processMutatorSpans',-) where--import Control.Monad (when)-import Control.Monad.IO.Class (MonadIO (..))-import Data.Char (isSpace)-import Data.Foldable (for_)-import Data.Machine (Is (..), PlanT, ProcessT, asParts, await, construct, mapping, repeatedly, yield, (~>))-import Data.Machine.Fanout (fanout)-import Data.Text (Text)-import Data.Text qualified as T-import Data.Void (Void)-import GHC.Eventlog.Live.Data.Attribute (AttrValue, IsAttrValue (..), (~=))-import GHC.Eventlog.Live.Data.Metric (Metric (..))-import GHC.Eventlog.Live.Data.Span (duration)-import GHC.Eventlog.Live.Logger (logWarning)-import GHC.Eventlog.Live.Machine.Analysis.Thread (ThreadState (..), ThreadStateSpan (..), processThreadStateSpans')-import GHC.Eventlog.Live.Machine.Core (liftRouter)-import GHC.Eventlog.Live.Machine.WithStartTime (WithStartTime (..), setWithStartTime'value, tryGetTimeUnixNano)-import GHC.Eventlog.Live.Verbosity (Verbosity)-import GHC.RTS.Events (Event (..), EventInfo, ThreadId, Timestamp)-import GHC.RTS.Events qualified as E-import GHC.Records (HasField (..))-import Text.Printf (printf)------------------------------------------------------------------------------------ Capability Usage Metrics--{- |-This machine processes t`CapabilityUsageSpan` spans and produces metrics that-contain the duration and category of each such span and each idle period in-between.--}-processCapabilityUsageMetrics ::-  forall m.-  (MonadIO m) =>-  ProcessT m (WithStartTime CapabilityUsageSpan) (Metric Timestamp)-processCapabilityUsageMetrics =-  liftRouter measure spawn- where-  measure :: WithStartTime CapabilityUsageSpan -> Maybe Int-  measure = Just . (.value.cap)--  spawn :: Int -> ProcessT m (WithStartTime CapabilityUsageSpan) (Metric Timestamp)-  spawn cap = construct $ go Nothing-   where-    go ::-      Maybe CapabilityUsageSpan ->-      PlanT (Is (WithStartTime CapabilityUsageSpan)) (Metric Timestamp) m Void-    go mi =-      await >>= \j -> do-        -- If there is a previous span, and...-        for_ mi $ \i ->-          -- ...the end time of the previous span precedes the start time of the current span, then...-          when (i.endTimeUnixNano < j.value.startTimeUnixNano) $-            -- ...yield an idle duration metric.-            yield-              Metric-                { value = j.value.startTimeUnixNano - i.endTimeUnixNano-                , maybeTimeUnixNano = Just i.endTimeUnixNano-                , maybeStartTimeUnixNano = j.maybeStartTimeUnixNano-                , attrs = ["cap" ~= cap, "category" ~= ("Idle" :: Text)]-                }-        -- Yield a duration metric for the current span.-        let user = capabilityUser j.value-        yield-          Metric-            { value = duration j.value-            , maybeTimeUnixNano = Just j.value.startTimeUnixNano-            , maybeStartTimeUnixNano = j.maybeStartTimeUnixNano-            , attrs = ["cap" ~= cap, "category" ~= showCapabilityUserCategory user, "user" ~= user]-            }-        go (Just j.value)--{- |-The type of process using a capability,-which is either a mutator thread or garbage collection.--}-data CapabilityUser-  = GC-  | Mutator {thread :: !ThreadId}--instance Show CapabilityUser where-  show :: CapabilityUser -> String-  show = \case-    GC -> "GC"-    Mutator{thread} -> show thread--instance IsAttrValue CapabilityUser where-  toAttrValue :: CapabilityUser -> AttrValue-  toAttrValue = toAttrValue . show-  {-# INLINE toAttrValue #-}--{- |-Get the t`CapabilityUser` associated with a t`CapabilityUsageSpan`.--}-capabilityUser :: CapabilityUsageSpan -> CapabilityUser-capabilityUser = either (const GC) (Mutator . (.thread))--{- |-Show the category of a `CapabilityUser` as either @"GC"@ or @"Mutator"@.--}-showCapabilityUserCategory :: CapabilityUser -> Text-showCapabilityUserCategory = \case-  GC{} -> "GC"-  Mutator{} -> "Mutator"------------------------------------------------------------------------------------ Capability Usage Spans--{- |-A t`CapabilityUsageSpan` is either a t`GCSpan` or a t`MutatorSpan`.--}-type CapabilityUsageSpan = Either GCSpan MutatorSpan--instance HasField "startTimeUnixNano" CapabilityUsageSpan Timestamp where-  getField :: CapabilityUsageSpan -> Timestamp-  getField = either (.startTimeUnixNano) (.startTimeUnixNano)--instance HasField "endTimeUnixNano" CapabilityUsageSpan Timestamp where-  getField :: CapabilityUsageSpan -> Timestamp-  getField = either (.endTimeUnixNano) (.endTimeUnixNano)--instance HasField "cap" CapabilityUsageSpan Int where-  getField :: CapabilityUsageSpan -> Int-  getField = either (.cap) (.cap)--{-# SPECIALIZE duration :: CapabilityUsageSpan -> Timestamp #-}--{- |-This machine runs `processGCSpans` and `processMutatorSpans` in parallel and-combines their output.--This is effectively a fanout of `processGCSpans` and `processMutatorSpans`, the-latter of which runs `processThreadStateSpans` internally. If you are running-`processThreadStateSpans` as well, then using `asMutatorSpans` and constructing-the fanout yourself is more efficient.--}-processCapabilityUsageSpans ::-  forall m.-  (MonadIO m) =>-  Verbosity ->-  ProcessT m (WithStartTime Event) (WithStartTime CapabilityUsageSpan)-processCapabilityUsageSpans verbosity =-  processCapabilityUsageSpans' tryGetTimeUnixNano (.value) setWithStartTime'value setWithStartTime'value verbosity-    ~> mapping (either (fmap Left) (fmap Right))--{- |-Generalised version of `processCapabilityUsageSpans` that can be adapted to-work on arbitrary types using a getter and a pair of lenses.--}-processCapabilityUsageSpans' ::-  forall m s t1 t2.-  (MonadIO m) =>-  (s -> Maybe Timestamp) ->-  (s -> Event) ->-  (s -> GCSpan -> t1) ->-  (s -> MutatorSpan -> t2) ->-  Verbosity ->-  ProcessT m s (Either t1 t2)-processCapabilityUsageSpans' timeUnixNano getEvent setGCSpan setMutatorSpan verbosity =-  -- NOTE:-  -- Combining this fanout with an `Either` is risky, because it-  -- has the potential to lose information if both `processGCSpans`-  -- and `processMutatorSpans` yield a value for the same input.-  -- However, this shouldn't ever happen, since the two processors-  -- process disjoint sets of events.-  fanout-    [ processGCSpans' timeUnixNano getEvent setGCSpan verbosity-        ~> mapping Left-    , processMutatorSpans' timeUnixNano getEvent setMutatorSpan verbosity-        ~> mapping Right-    ]------------------------------------------------------------------------------------ GC spans--{- |-A t`GCSpan` represents a segment of time during which the specified capability-ran GC.--}-data GCSpan = GCSpan-  { cap :: !Int-  , startTimeUnixNano :: !Timestamp-  , endTimeUnixNano :: !Timestamp-  }-  deriving (Show)--{-# SPECIALIZE duration :: GCSpan -> Timestamp #-}--{- |-This machine processes `E.StartGC` and `E.EndGC` events to produce t`GCSpan`-values that represent the segments of time a capability spent in GC.--This processor uses the following finite-state automaton:--@-      ┌─(EndGC)───┐-      │           ↓-    ┌→[   Idle    ]─┐-    │               │-(EndGC)         (StartGC)-    │               │-    └─[    GC     ]←┘-      ↑           │-      └─(StartGC)─┘-@--The transition from @GC@ to @Idle@ yields a GC span.--}-processGCSpans ::-  forall m.-  (MonadIO m) =>-  Verbosity ->-  ProcessT m (WithStartTime Event) (WithStartTime GCSpan)-processGCSpans =-  processGCSpans' tryGetTimeUnixNano (.value) setWithStartTime'value--{- |-Generalised version of `processGCSpans` that can be adapted to work on-arbitrary types using a getter and a lens.--}-processGCSpans' ::-  forall m s t.-  (MonadIO m) =>-  (s -> Maybe Timestamp) ->-  (s -> Event) ->-  (s -> GCSpan -> t) ->-  Verbosity ->-  ProcessT m s t-processGCSpans' timeUnixNano getEvent setGCSpan verbosity =-  liftRouter measure spawn- where-  getEventTime = (.evTime) . getEvent-  getEventInfo = (.evSpec) . getEvent-  getEventCap = (.evCap) . getEvent--  measure :: s -> Maybe Int-  measure i-    | accept (getEventInfo i) = getEventCap i-    | otherwise = Nothing-   where-    accept E.StartGC{} = True-    accept E.EndGC{} = True-    accept _ = False--  -- TODO: Rewrite using `MealyT`-  spawn :: Int -> ProcessT m s t-  spawn cap = construct $ go Nothing-   where-    -- The "mi" variable tracks the previous event for this capability, which-    -- is either `Nothing` or `Just` a `StartGC` or a `EndGC` event.-    go :: Maybe s -> PlanT (Is s) t m Void-    go mi =-      -- We start by awaiting the next event "j"...-      await >>= \j -> case getEventInfo j of-        -- If the next event is a `RunThread` event, and...-        E.StartGC{} -> case mi of-          Just i-            -- If the previous event was a `StartGC` event, then...-            | E.StartGC{} <- getEventInfo i ->-                -- ...continue with the oldest event.-                go (Just $ minBy getEventTime i j)-            -- If the previous event was a `EndGC` event, then...-            | E.EndGC{} <- getEventInfo i ->-                -- ...continue with the current event.-                go (Just j)-            -- If the previous event was any other event, then...-            | otherwise -> do-                -- ...emit an error, and...-                logWarning verbosity . T.pack $-                  printf-                    "Capability %d: Unsupported trace %s --> %s"-                    cap-                    (showEventInfo (getEventInfo i))-                    (showEventInfo (getEventInfo j))-                -- ...continue with the previous event.-                go (Just i)-          -- If there was no previous event, then...-          Nothing ->-            -- ...continue with the current event.-            go (Just j)-        -- If the next event is a `StopThread` event...-        E.EndGC{} -> case mi of-          Just i-            -- If the previous event was a `StartGC` event, then...-            | E.StartGC{} <- getEventInfo i-            , Just startTimeUnixNano <- timeUnixNano i-            , Just endTimeUnixNano <- timeUnixNano j -> do-                -- ...yield a GC span, and...-                yield . setGCSpan j $ GCSpan{..}-                -- ...continue with the current event.-                go (Just j)-            -- If the previous event was a `EndGC` event, then...-            | E.EndGC{} <- getEventInfo i ->-                -- ...continue with the oldest event.-                go (Just $ minBy getEventTime i j)-          -- If there was no previous event or it was any other event, then...-          _otherwise -> do-            -- ...emit an error, and...-            logWarning verbosity . T.pack $-              printf-                "Capability %d: Unsupported trace %s --> %s"-                cap-                (maybe "?" (showEventInfo . getEventInfo) mi)-                (showEventInfo (getEventInfo j))-            -- ...continue with the previous event.-            go mi-        -- If the next event is any other event, ignore it.-        _otherwise -> go mi------------------------------------------------------------------------------------ Mutator spans--{- |-A t`MutatorSpan` represents a segment of time during which the specified-capability ran the specified mutator thread.--}-data MutatorSpan = MutatorSpan-  { cap :: !Int-  , thread :: !ThreadId-  , startTimeUnixNano :: !Timestamp-  , endTimeUnixNano :: !Timestamp-  }-  deriving (Show)--{-# SPECIALIZE duration :: MutatorSpan -> Timestamp #-}--{- |-This machine processes `E.RunThread` and `E.StopThread` events to produce-t`MutatorSpan` values that represent the segments of time a capability spent-executating a mutator.--This processor uses the following finite-state automaton:--@-      ┌─(StopThread[X])─┐-      │                 ↓-    ┌→[      Idle       ]─┐-    │                     │-(StopThread[X])       (RunThread[X])-    │                     │-    └─[   Mutator[X]    ]←┘-      ↑                 │-      └─(RunThread[X])──┘-@--The transition from @Mutator[X]@ to @Idle@ yields a t`MutatorSpan`.-While in the @Mutator[X]@ state, any @RunThread[Y]@ or @StopThread[Y]@ events result in an error.-Furthermore, when a @StopThread[X]@ event with the @ThreadFinished@ status is processed,-the thread @X@ is added to a set of finished threads,-and any further @RunThread[X]@ events for that thread are ignored.-This is done because the GHC RTS frequently emits a @RunThread[X]@ event-immediately after a @StopThread[X]@ event with the @ThreadFinished@ status.--This runs `processThreadStateSpans` internally. If you are also running-`processThreadStateSpans`, then post-composing it with `asMutatorSpans`-is more efficient.--}-processMutatorSpans ::-  forall m.-  (MonadIO m) =>-  Verbosity ->-  ProcessT m (WithStartTime Event) (WithStartTime MutatorSpan)-processMutatorSpans =-  processMutatorSpans' tryGetTimeUnixNano (.value) setWithStartTime'value--{- |-Generalised version of `processMutatorSpans` that can be adapted to work on-arbitrary types using a getter and a lens.--}-processMutatorSpans' ::-  forall m s t.-  (MonadIO m) =>-  (s -> Maybe Timestamp) ->-  (s -> Event) ->-  (s -> MutatorSpan -> t) ->-  Verbosity ->-  ProcessT m s t-processMutatorSpans' timeUnixNano getEvent setMutatorSpan verbosity =-  processThreadStateSpans' timeUnixNano getEvent setThreadStateSpan verbosity ~> asParts- where-  setThreadStateSpan :: s -> ThreadStateSpan -> Maybe t-  setThreadStateSpan s threadStateSpan =-    setMutatorSpan s <$> threadStateSpanToMutatorSpan threadStateSpan--{- |-This machine converts any `Running` t`ThreadStateSpan` to a t`MutatorSpan`.--}-asMutatorSpans ::-  forall m.-  (MonadIO m) =>-  ProcessT m ThreadStateSpan MutatorSpan-asMutatorSpans = asMutatorSpans' id (const id)--{- |-Generalised version of `asMutatorSpans` that can be adapted to work on-arbitrary types using a getter and a lens.--}-asMutatorSpans' ::-  forall m s t.-  (MonadIO m) =>-  (s -> ThreadStateSpan) ->-  (s -> MutatorSpan -> t) ->-  ProcessT m s t-asMutatorSpans' getThreadStateSpan setMutatorSpan = repeatedly go- where-  go =-    await >>= \s -> do-      let threadStateSpan = getThreadStateSpan s-      let maybeMutatorSpan = threadStateSpanToMutatorSpan threadStateSpan-      for_ maybeMutatorSpan $ yield . setMutatorSpan s--{- |-Convert the `Running` t`ThreadStateSpan` to `Just` a t`MutatorSpan`.--}-threadStateSpanToMutatorSpan :: ThreadStateSpan -> Maybe MutatorSpan-threadStateSpanToMutatorSpan ThreadStateSpan{..} =-  case threadState of-    Running{..} -> Just MutatorSpan{..}-    _otherwise -> Nothing------------------------------------------------------------------------------------ Internal Helpers----------------------------------------------------------------------------------{- |-Internal helper.-Show `EventInfo` in a condensed format suitable for logging.--}-showEventInfo :: EventInfo -> String-showEventInfo = \case-  E.RunThread{thread} -> printf "RunThread{%d}" thread-  E.StopThread{thread, status} -> printf "StopThread{%d,%s}" thread (E.showThreadStopStatus status)-  E.MigrateThread{thread} -> printf "MigrateThread{%d}" thread-  E.StartGC{} -> "StartGC"-  E.EndGC{} -> "EndGC"-  evSpec -> takeWhile (not . isSpace) . show $ evSpec--{- |-Internal helper. Return the minimal value by some projection.--}-minBy :: (Ord b) => (a -> b) -> a -> a -> a-minBy f x y = if f x < f y then x else y
− src/GHC/Eventlog/Live/Machine/Analysis/Heap.hs
@@ -1,530 +0,0 @@-{-# LANGUAGE OverloadedLists #-}-{-# LANGUAGE OverloadedStrings #-}-{-# OPTIONS_GHC -Wno-name-shadowing #-}--{- |-Module      : GHC.Eventlog.Live.Machine.Analysis.Heap-Description : Machines for processing eventlog data.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Machine.Analysis.Heap (-  -- * Heap Usage-  processHeapAllocatedData,-  processHeapSizeData,-  processBlocksSizeData,-  processHeapLiveData,-  MemReturnData (..),-  processMemReturnData,-  HeapProfSampleData,-  heapProfSamples,-  processHeapProfSampleData,--  -- ** Heap Profile Breakdown-  heapProfBreakdownEitherReader,-  heapProfBreakdownShow,-) where--import Control.Monad (unless, when)-import Control.Monad.IO.Class (MonadIO (..))-import Data.Either (isLeft)-import Data.Foldable (for_)-import Data.HashMap.Strict (HashMap)-import Data.HashMap.Strict qualified as M-import Data.Hashable (Hashable (..))-import Data.List qualified as L-import Data.Machine (Process, ProcessT, await, construct, repeatedly, yield)-import Data.Maybe (isJust, listToMaybe, mapMaybe)-import Data.Text (Text)-import Data.Text qualified as T-import Data.Word (Word32, Word64)-import GHC.Eventlog.Live.Data.Attribute (Attrs, (~=))-import GHC.Eventlog.Live.Data.Group (GroupBy (..))-import GHC.Eventlog.Live.Data.Metric (Metric (..))-import GHC.Eventlog.Live.Logger (logWarning)-import GHC.Eventlog.Live.Machine.WithStartTime (WithStartTime (..), tryGetTimeUnixNano)-import GHC.Eventlog.Live.Verbosity (Verbosity)-import GHC.RTS.Events (Event (..), HeapProfBreakdown (..))-import GHC.RTS.Events qualified as E-import Numeric (showHex)-import Text.ParserCombinators.ReadP (readP_to_S)-import Text.ParserCombinators.ReadP qualified as P-import Text.Printf (printf)-import Text.Read (readMaybe)-import Text.Read.Lex (readHexP)------------------------------------------------------------------------------------ Heap events--------------------------------------------------------------------------------------------------------------------------------------------------------------------- HeapAllocated--{- |-This machine processes `E.HeapAllocated` events into metrics.--}-processHeapAllocatedData :: Process (WithStartTime Event) (Metric Word64)-processHeapAllocatedData =-  repeatedly $-    await >>= \case-      i-        | E.HeapAllocated{..} <- i.value.evSpec ->-            yield $-              metric i allocBytes $-                [ "evCap" ~= i.value.evCap-                , "heapCapset" ~= heapCapset-                ]-        | otherwise -> pure ()------------------------------------------------------------------------------------ HeapSize--{- |-This machine processes `E.HeapSize` events into metrics.--}-processHeapSizeData :: Process (WithStartTime Event) (Metric Word64)-processHeapSizeData = repeatedly go- where-  go =-    await >>= \case-      i-        | E.HeapSize{..} <- i.value.evSpec -> do-            yield $-              metric i sizeBytes $-                [ "evCap" ~= i.value.evCap-                , "heapCapset" ~= heapCapset-                ]-        | otherwise -> pure ()------------------------------------------------------------------------------------ BlocksSize--{- |-This machine processes `E.BlocksSize` events into metrics.--}-processBlocksSizeData :: Process (WithStartTime Event) (Metric Word64)-processBlocksSizeData =-  repeatedly $-    await >>= \case-      i-        | E.BlocksSize{..} <- i.value.evSpec -> do-            yield $-              metric i blocksSize $-                [ "evCap" ~= i.value.evCap-                , "heapCapset" ~= heapCapset-                ]-        | otherwise -> pure ()------------------------------------------------------------------------------------ HeapLive--{- |-This machine processes `E.HeapLive` events into metrics.--}-processHeapLiveData :: Process (WithStartTime Event) (Metric Word64)-processHeapLiveData =-  repeatedly $-    await >>= \case-      i-        | E.HeapLive{..} <- i.value.evSpec -> do-            yield $-              metric i liveBytes $-                [ "evCap" ~= i.value.evCap-                , "heapCapset" ~= heapCapset-                ]-        | otherwise -> pure ()------------------------------------------------------------------------------------ MemReturn--{- |-The type of data associated with a `E.MemReturn` event.--}-data MemReturnData = MemReturnData-  { current :: !Word32-  -- ^ The number of megablocks currently allocated.-  , needed :: !Word32-  -- ^ The number of megablocks currently needed.-  , returned :: !Word32-  -- ^ The number of megablocks currently being returned to the OS.-  }--{- |-This machine processes `E.MemReturn` events into metrics.--}-processMemReturnData :: Process (WithStartTime Event) (Metric MemReturnData)-processMemReturnData =-  repeatedly $-    await >>= \case-      i-        | E.MemReturn{..} <- i.value.evSpec -> do-            yield $-              metric i MemReturnData{..} $-                [ "evCap" ~= i.value.evCap-                , "heapCapset" ~= heapCapset-                ]-        | otherwise -> pure ()------------------------------------------------------------------------------------ HeapProfSample--{- |-The type of all heap profile samples from a single garbage collection pass.--}-newtype HeapProfSampleData = HeapProfSampleData-  { heapProfSampleMap :: HashMap Text (Metric Word64)-  }-  deriving (Show)-  deriving newtype (Semigroup, Monoid)--instance GroupBy HeapProfSampleData where-  type Key HeapProfSampleData = ()--  toKey :: HeapProfSampleData -> ()-  toKey = const ()--{- |-Get the elements of a heap profile sample collection.--}-heapProfSamples :: HeapProfSampleData -> [Metric Word64]-heapProfSamples = M.elems . (.heapProfSampleMap)--{- |-Internal helper.-Insert a heap profiling sample into the collection.--}-insertHeapProfSampleString ::-  forall m.-  (MonadIO m) =>-  Verbosity ->-  Text ->-  Metric Word64 ->-  HeapProfSampleData ->-  m HeapProfSampleData-insertHeapProfSampleString verbosityThreshold heapProfLabel heapProfSample heapProfSamples = do-  let insert :: Maybe (Metric Word64) -> m (Maybe (Metric Word64))-      insert heapProfSample' = do-        when (isJust heapProfSample') $-          logWarning verbosityThreshold $-            "Duplicate HeapProfSampleString for " <> heapProfLabel <> " within the same garbage collection pass."-        pure (Just heapProfSample)-  heapProfSampleMap' <- M.alterF insert heapProfLabel heapProfSamples.heapProfSampleMap-  pure HeapProfSampleData{heapProfSampleMap = heapProfSampleMap'}--{- |-Internal helper.-The type of info table pointers.--}-newtype InfoTablePtr = InfoTablePtr Word64-  deriving newtype (Eq, Hashable, Ord)--instance Show InfoTablePtr where-  showsPrec :: Int -> InfoTablePtr -> ShowS-  showsPrec _ (InfoTablePtr ptr) =-    showString "0x" . showHex ptr--instance Read InfoTablePtr where-  readsPrec :: Int -> ReadS InfoTablePtr-  readsPrec _ = readP_to_S (InfoTablePtr <$> (P.string "0x" *> readHexP))--{- |-Internal helper.-The type of an info table entry, as produced by the `E.InfoTableProv` event.--}-data InfoTable = InfoTable-  { infoTablePtr :: !InfoTablePtr-  , infoTableName :: !Text-  , infoTableClosureDesc :: !Int-  , infoTableTyDesc :: !Text-  , infoTableLabel :: !Text-  , infoTableModule :: !Text-  , infoTableSrcLoc :: !Text-  }-  deriving (Show)--{- |-Internal helper.-The type of the state kept by `processHeapProfSampleData`.--}-data HeapProfSampleState = HeapProfSampleState-  { eitherShouldWarnOrHeapProfBreakdown :: !(Either Bool HeapProfBreakdown)-  , infoTableMap :: !(HashMap InfoTablePtr InfoTable)-  , heapProfSampleEraStack :: ![Word64]-  , maybeHeapProfSampleData :: !(Maybe HeapProfSampleData)-  }-  deriving (Show)--{- |-Internal helper.-Decides whether or not `processHeapProfSampleData` should track info tables.-We track info tables until (1) we learn that the RTS is not run with @-hi@,-or (2) we see the first heap profiling sample and don't yet know for sure-that the RTS is run with @-hi@.--}-shouldTrackInfoTableMap :: Either Bool HeapProfBreakdown -> Bool-shouldTrackInfoTableMap (Left _shouldWarn) = True-shouldTrackInfoTableMap (Right HeapProfBreakdownInfoTable) = True-shouldTrackInfoTableMap _ = False--{- |-Internal helper.-Checks whether a `HeapProfBreakdown` is `HeapProfBreakdownInfoTable`.-This is needed because the ghc-events package does not define an `Eq`-instance for the `HeapProfBreakdown` type.--}-isHeapProfBreakdownInfoTable :: HeapProfBreakdown -> Bool-isHeapProfBreakdownInfoTable HeapProfBreakdownInfoTable = True-isHeapProfBreakdownInfoTable _ = False--{- |-This machine processes `E.HeapProfSampleString` events into metrics.-Furthermore, it processes the `E.HeapProfBegin` and `E.ProgramArgs` events-to determine the heap profile breakdown, processes `E.InfoTableProv` events to-build an info table map, if necessary, and processes `E.HeapProfSampleBegin`-and `E.HeapProfSampleEnd` events to maintain an era stack.--}-processHeapProfSampleData ::-  (MonadIO m) =>-  Verbosity ->-  Maybe HeapProfBreakdown ->-  ProcessT m (WithStartTime Event) HeapProfSampleData-processHeapProfSampleData verbosityThreshold maybeHeapProfBreakdown =-  construct $-    go-      HeapProfSampleState-        { eitherShouldWarnOrHeapProfBreakdown = maybe (Left True) Right maybeHeapProfBreakdown-        , infoTableMap = mempty-        , heapProfSampleEraStack = mempty-        , maybeHeapProfSampleData = mempty-        }- where-  -- go :: HeapProfSampleState -> PlanT (Is (WithStartTime Event)) HeapProfSampleData m Void-  go st@HeapProfSampleState{..} = do-    await >>= \i -> case i.value.evSpec of-      -- Announces the heap profile breakdown, amongst other things.-      -- This event is only emitted for code compiled with GHC >=9.14.-      E.HeapProfBegin{..}-        | isLeft eitherShouldWarnOrHeapProfBreakdown ->-            go st{eitherShouldWarnOrHeapProfBreakdown = Right heapProfBreakdown}-      -- Announces the arguments with which the program was called.-      -- This *may* include RTS options, which can be used to determine the-      -- heap profile breakdown for code compiled with GHC <9.14.-      E.ProgramArgs{..}-        | isLeft eitherShouldWarnOrHeapProfBreakdown-        , Just heapProfBreakdown <- findHeapProfBreakdown args ->-            go st{eitherShouldWarnOrHeapProfBreakdown = Right heapProfBreakdown}-      -- Announces an info table entry.-      E.InfoTableProv{..}-        | shouldTrackInfoTableMap eitherShouldWarnOrHeapProfBreakdown -> do-            let infoTablePtr = InfoTablePtr itInfo-                infoTable =-                  InfoTable-                    { infoTablePtr = infoTablePtr-                    , infoTableName = itTableName-                    , infoTableClosureDesc = itClosureDesc-                    , infoTableTyDesc = itTyDesc-                    , infoTableLabel = itLabel-                    , infoTableModule = itModule-                    , infoTableSrcLoc = itSrcLoc-                    }-            go st{infoTableMap = M.insert infoTablePtr infoTable infoTableMap}-      -- Announces the beginning of a heap profile sample.-      E.HeapProfSampleBegin{..} -> do-        -- Check that maybeHeapProfSampleData is Nothing.-        for_ st.maybeHeapProfSampleData $ \heapProfSampleData -> do-          logWarning-            verbosityThreshold-            "Unexpected event HeapProfSampleBegin while previous garbage collection pass was left open.\n\-            \This may indicate that the eventlog is not properly ordered or that its semantics have changed."-          -- Yield the previous sample data anyway.-          yield heapProfSampleData-        -- Start a new garbage collection pass.-        go-          st-            { heapProfSampleEraStack = heapProfSampleEra : heapProfSampleEraStack-            , maybeHeapProfSampleData = Just mempty-            }-      -- Announces the end of a heap profile sample.-      E.HeapProfSampleEnd{..} -> do-        -- Yield the previous heap profile sample data-        for_ st.maybeHeapProfSampleData yield-        -- Pop the heapProfSampleEraStack-        heapProfSampleEraStack' <--          case L.uncons heapProfSampleEraStack of-            Nothing -> do-              logWarning verbosityThreshold . T.pack $-                printf-                  "Eventlog closed era %d, but there is no current era."-                  heapProfSampleEra-              pure heapProfSampleEraStack-            Just (currentEra, heapProfSampleEraStack') -> do-              unless (currentEra == heapProfSampleEra) $-                logWarning verbosityThreshold . T.pack $-                  printf-                    "Eventlog closed era %d, but the current era is era %d."-                    heapProfSampleEra-                    currentEra-              pure heapProfSampleEraStack'-        go-          st-            { heapProfSampleEraStack = heapProfSampleEraStack'-            , maybeHeapProfSampleData = Nothing-            }-      -- Announces a heap profile sample.-      E.HeapProfSampleString{..}-        -- If there is no heap profile breakdown, issue a warning, then disable warnings.-        | Left True <- eitherShouldWarnOrHeapProfBreakdown -> do-            logWarning verbosityThreshold $-              "Cannot infer heap profile breakdown.\n\-              \         If your binary was compiled with a GHC version prior to 9.14,\n\-              \         you must also pass the heap profile type to this executable.\n\-              \         See: https://gitlab.haskell.org/ghc/ghc/-/commit/76d392a"-            go st{eitherShouldWarnOrHeapProfBreakdown = Left False, infoTableMap = mempty}-        -- If the heap profile breakdown is biographical, issue a warning, then disable warnings.-        | Right HeapProfBreakdownBiography <- eitherShouldWarnOrHeapProfBreakdown -> do-            logWarning verbosityThreshold . T.pack $-              printf-                "Unsupported heap profile breakdown %s"-                (heapProfBreakdownShow HeapProfBreakdownBiography)-            go st{eitherShouldWarnOrHeapProfBreakdown = Left False, infoTableMap = mempty}-        -- If there is a heap profile breakdown, handle it appropriately.-        | Right heapProfBreakdown <- eitherShouldWarnOrHeapProfBreakdown -> do-            -- If the heap profile breakdown is by info table, add the info table.-            let maybeInfoTable-                  | isHeapProfBreakdownInfoTable heapProfBreakdown = do-                      !infoTablePtr <- readMaybe (T.unpack heapProfLabel)-                      M.lookup infoTablePtr infoTableMap-                  | otherwise = Nothing-            -- Get the HeapProfSampleData-            heapProfSampleData <--              case st.maybeHeapProfSampleData of-                Nothing -> do-                  logWarning verbosityThreshold $-                    "Unexpected event HeapProfSampleString out of scope of HeapProfSampleBegin and HeapProfSampleEnd.\n\-                    \This may indicate that the eventlog is not properly ordered or that its semantics have changed."-                  pure mempty-                Just heapProfSampleData ->-                  pure heapProfSampleData-            -- Update the HeapProfSampleData-            let heapProfSample =-                  metric i heapProfResidency $-                    [ "evCap" ~= i.value.evCap-                    , "heapProfBreakdown" ~= heapProfBreakdownShow heapProfBreakdown-                    , "heapProfId" ~= heapProfId-                    , "heapProfLabel" ~= heapProfLabel-                    , "heapProfSampleEra" ~= (fst <$> L.uncons heapProfSampleEraStack)-                    , "infoTableName" ~= fmap (.infoTableName) maybeInfoTable-                    , "infoTableClosureDesc" ~= fmap (.infoTableClosureDesc) maybeInfoTable-                    , "infoTableTyDesc" ~= fmap (.infoTableTyDesc) maybeInfoTable-                    , "infoTableLabel" ~= fmap (.infoTableLabel) maybeInfoTable-                    , "infoTableModule" ~= fmap (.infoTableModule) maybeInfoTable-                    , "infoTableSrcLoc" ~= fmap (.infoTableSrcLoc) maybeInfoTable-                    ]-            heapProfSampleData' <--              insertHeapProfSampleString verbosityThreshold heapProfLabel heapProfSample heapProfSampleData-            -- Continue with the updated HeapProfSampleState-            go-              st-                { -- If we're not profiling with -hi, discard the info table map-                  infoTableMap = if isHeapProfBreakdownInfoTable heapProfBreakdown then st.infoTableMap else mempty-                , -- Add the update HeapProfSampleData-                  maybeHeapProfSampleData = Just heapProfSampleData'-                }-      _otherwise -> go st--{- |-Parses the `HeapProfBreakdown` command-line arguments:--> heapProfBreakdownEitherReader "T" == Left HeapProfBreakdownClosureType-> heapProfBreakdownEitherReader "c" == Left HeapProfBreakdownCostCentre-> heapProfBreakdownEitherReader "m" == Left HeapProfBreakdownModule-> heapProfBreakdownEitherReader "d" == Left HeapProfBreakdownClosureDescr-> heapProfBreakdownEitherReader "y" == Left HeapProfBreakdownTypeDescr-> heapProfBreakdownEitherReader "e" == Left HeapProfBreakdownEra-> heapProfBreakdownEitherReader "r" == Left HeapProfBreakdownRetainer-> heapProfBreakdownEitherReader "b" == Left HeapProfBreakdownBiography-> heapProfBreakdownEitherReader "i" == Left HeapProfBreakdownInfoTable--}-heapProfBreakdownEitherReader :: String -> Either String HeapProfBreakdown-heapProfBreakdownEitherReader =-  \case-    "T" -> Right HeapProfBreakdownClosureType-    "c" -> Right HeapProfBreakdownCostCentre-    "m" -> Right HeapProfBreakdownModule-    "d" -> Right HeapProfBreakdownClosureDescr-    "y" -> Right HeapProfBreakdownTypeDescr-    "e" -> Right HeapProfBreakdownEra-    "r" -> Right HeapProfBreakdownRetainer-    "b" -> Right HeapProfBreakdownBiography-    "i" -> Right HeapProfBreakdownInfoTable-    str -> Left $ "Unsupported heap profile breakdown -h" <> str--{- |-Shows a `HeapProfBreakdown` as its corresponding command-line flag:--> heapProfBreakdownShow HeapProfBreakdownClosureType == "-hT"-> heapProfBreakdownShow HeapProfBreakdownCostCentre == "-hc"-> heapProfBreakdownShow HeapProfBreakdownModule == "-hm"-> heapProfBreakdownShow HeapProfBreakdownClosureDescr == "-hd"-> heapProfBreakdownShow HeapProfBreakdownTypeDescr == "-hy"-> heapProfBreakdownShow HeapProfBreakdownEra == "-he"-> heapProfBreakdownShow HeapProfBreakdownRetainer == "-hr"-> heapProfBreakdownShow HeapProfBreakdownBiography == "-hb"-> heapProfBreakdownShow HeapProfBreakdownInfoTable == "-hi"--}-heapProfBreakdownShow :: HeapProfBreakdown -> String-heapProfBreakdownShow =-  ("-h" <>) . \case-    HeapProfBreakdownClosureType -> "T"-    HeapProfBreakdownCostCentre -> "c"-    HeapProfBreakdownModule -> "m"-    HeapProfBreakdownClosureDescr -> "d"-    HeapProfBreakdownTypeDescr -> "y"-    HeapProfBreakdownEra -> "e"-    HeapProfBreakdownRetainer -> "r"-    HeapProfBreakdownBiography -> "b"-    HeapProfBreakdownInfoTable -> "i"--{- |-Internal helper.-Determine the `HeapProfBreakdown` from the list of program arguments.--__Warning__: This scan is not fully correct. It merely scans for the presence-of arguments that, as a whole, parse with `heapProfBreakdownEitherReader`.-It does not handle @-with-rtsopts@ and does not restrict its search to those-arguments between @+RTS@ and @-RTS@ tags.--}-findHeapProfBreakdown :: [Text] -> Maybe HeapProfBreakdown-findHeapProfBreakdown = listToMaybe . mapMaybe parseHeapProfBreakdown- where-  parseHeapProfBreakdown :: Text -> Maybe HeapProfBreakdown-  parseHeapProfBreakdown arg-    | "-h" `T.isPrefixOf` arg =-        either (const Nothing) Just-          . heapProfBreakdownEitherReader-          . T.unpack-          . T.drop 2-          $ arg-    | otherwise = Nothing------------------------------------------------------------------------------------ Internal Helpers----------------------------------------------------------------------------------{- |-Internal helper. Construct a t`Metric` from an event with a start time-(t`WithStartTime` t`Event`), together with the measurement and any attributes.-This is a smart constructor that pulls the various timestamps out of the event.--}-metric ::-  WithStartTime Event ->-  v ->-  Attrs ->-  Metric v-metric i v attrs =-  Metric-    { value = v-    , maybeTimeUnixNano = tryGetTimeUnixNano i-    , maybeStartTimeUnixNano = i.maybeStartTimeUnixNano-    , attrs = attrs-    }
− src/GHC/Eventlog/Live/Machine/Analysis/Thread.hs
@@ -1,307 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}-{-# OPTIONS_GHC -Wno-name-shadowing #-}--{- |-Module      : GHC.Eventlog.Live.Machine.Analysis.Thread-Description : Machines for processing eventlog data.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Machine.Analysis.Thread (-  -- * Thread Analysis--  -- ** Thread Labels-  ThreadLabel (..),-  processThreadLabels,--  -- ** Thread State Spans-  ThreadState (..),-  showThreadStateCategory,-  threadStateStatus,-  threadStateCap,-  ThreadStateSpan (..),-  processThreadStateSpans,-  processThreadStateSpans',-) where--import Control.Monad.IO.Class (MonadIO (..))-import Data.Char (isSpace)-import Data.Machine (Is (..), PlanT, Process, ProcessT, await, construct, repeatedly, yield)-import Data.Maybe (isNothing)-import Data.Text (Text)-import Data.Text qualified as T-import Data.Void (Void)-import GHC.Eventlog.Live.Data.Span (duration)-import GHC.Eventlog.Live.Logger (logWarning)-import GHC.Eventlog.Live.Machine.Core (liftRouter)-import GHC.Eventlog.Live.Machine.WithStartTime (WithStartTime (..), tryGetTimeUnixNano)-import GHC.Eventlog.Live.Verbosity (Verbosity)-import GHC.RTS.Events (Event (..), EventInfo, ThreadId, ThreadStopStatus (..), Timestamp)-import GHC.RTS.Events qualified as E-import Text.Printf (printf)------------------------------------------------------------------------------------ Thread Labels--{- |-The t`ThreadLabel` type represents the association of a label with a thread-starting at a given time.--}-data ThreadLabel-  = ThreadLabel-  { thread :: !ThreadId-  , threadlabel :: !Text-  , startTimeUnixNano :: !Timestamp-  }--{- |-This machine processes `E.ThreadLabel` events and yields t`ThreadLabel` values.--}-processThreadLabels :: Process (WithStartTime Event) ThreadLabel-processThreadLabels = repeatedly go- where-  go =-    await >>= \i -> case i.value.evSpec of-      E.ThreadLabel{..}-        | Just startTimeUnixNano <- tryGetTimeUnixNano i ->-            yield ThreadLabel{..}-      _otherwise -> pure ()------------------------------------------------------------------------------------ Thread State Spans--{- |-The execution states of a mutator thread.--}-data ThreadState-  = Running {cap :: !Int}-  | Blocked {status :: !ThreadStopStatus}-  | Finished-  deriving (Show)--{- |-Pretty-print a thread state as "Running", "Blocked", or "Finished".--}-showThreadStateCategory :: ThreadState -> Text-showThreadStateCategory = \case-  Running{} -> "Running"-  Blocked{} -> "Blocked"-  Finished{} -> "Finished"--{- |-Get the t`ThreadState` status, if the t`ThreadState` is `Blocked`.--}-threadStateStatus :: ThreadState -> Maybe ThreadStopStatus-threadStateStatus = \case-  Running{} -> Nothing-  Blocked{status} -> Just status-  Finished{} -> Nothing--{- |-Get the t`ThreadState` capability, if the `ThreadState` is `Running`.--}-threadStateCap :: ThreadState -> Maybe Int-threadStateCap = \case-  Running{cap} -> Just cap-  Blocked{} -> Nothing-  Finished{} -> Nothing--{- |-A span representing the state of a mutator thread.--}-data ThreadStateSpan-  = ThreadStateSpan-  { thread :: !ThreadId-  , threadState :: !ThreadState-  , startTimeUnixNano :: !Timestamp-  , endTimeUnixNano :: !Timestamp-  }-  deriving (Show)--{-# SPECIALIZE duration :: ThreadStateSpan -> Timestamp #-}--{- |-This machine processes `E.RunThread` and `E.StopThread` events to produce-t`ThreadStateSpan` values that represent segments of time where a thread is-running, blocked, or finished.--This processor uses the following finite-state automaton:--@-      ┌─(StopThread)─┐-      │              ↓-    ┌→[   Blocked    ]─┐-    │                  │-(StopThread)       (RunThread)-    │                  │-    └─[   Running    ]←┘-      ↑              │-      └─(RunThread)──┘-@--The transitions from @Blocked@ to @Blocked@, @Blocked@ to @Running@, and-@Running@ to @Running@ yield a t`ThreadStateSpan`. There are additional-transitions (not pictured) from either state to the final `Finished` state-with a `E.StopThread` event with the `ThreadFinished` status.--}-processThreadStateSpans ::-  (MonadIO m) =>-  Verbosity ->-  ProcessT m (WithStartTime Event) ThreadStateSpan-processThreadStateSpans =-  processThreadStateSpans' tryGetTimeUnixNano (.value) (const id)--{- |-Generalised version of `processThreadStateSpans` that can be adapted to work-on arbitrary types using a getter and a lens.--}-processThreadStateSpans' ::-  forall m s t.-  (MonadIO m) =>-  (s -> Maybe Timestamp) ->-  (s -> Event) ->-  (s -> ThreadStateSpan -> t) ->-  Verbosity ->-  ProcessT m s t-processThreadStateSpans' timeUnixNano getEvent setThreadStateSpan verbosity =-  liftRouter measure spawn- where-  getEventTime = (.evTime) . getEvent-  getEventInfo = (.evSpec) . getEvent-  getEventCap = (.evCap) . getEvent--  measure :: s -> Maybe ThreadId-  measure i = case getEventInfo i of-    E.RunThread{thread} -> Just thread-    E.StopThread{thread} -> Just thread-    _otherwise -> Nothing--  spawn :: ThreadId -> ProcessT m s t-  spawn thread = construct $ go Nothing-   where-    go :: Maybe s -> PlanT (Is s) t m Void-    go mi =-      await >>= \case-        j-          -- If the previous event was a `E.StopThread` event, and...-          | Just E.StopThread{status} <- getEventInfo <$> mi-          , --- ...it has the `ThreadFinished` status, then...-            isThreadFinished status ->-              -- ...ignore the current event.-              go mi-          ---          -- If the current event is a `E.RunThread` event, and...-          | E.RunThread{} <- getEventInfo j-          , -- ...the previous event was a `E.StopThread` event, then...-            Just E.StopThread{status} <- getEventInfo <$> mi-          , -- ...gather the end time of the previous event, and...-            Just startTimeUnixNano <- timeUnixNano =<< mi-          , -- ...gather the start time of the current event, and...-            Just endTimeUnixNano <- timeUnixNano j -> do-              -- ...yield a thread state span, and...-              yield . setThreadStateSpan j $-                ThreadStateSpan{threadState = Blocked status, ..}-              go (Just j)-          ---          -- If the current event is a `E.RunThread` event, and...-          | E.RunThread{} <- getEventInfo j-          , -- ...the previous event was a `E.RunThread` event, then...-            Just E.RunThread{} <- getEventInfo <$> mi -> do-              -- ...keep the oldest event.-              go (Just $ maybe j (minBy getEventTime j) mi)-          ---          -- If the current event is a `E.RunThread` event, and...-          | E.RunThread{} <- getEventInfo j-          , -- ...there is no previous event, then...-            isNothing mi ->-              -- ...keep the current event.-              ---              -- The reason for the additional `isNothing` test is because,-              -- otherwise, this case might silently swallow any `E.StopThread`-              -- events for which `timeUnixNano` gives `Nothing`.-              -- By excluding these, they are forwarded to the catch-all case.-              go (Just j)-          ---          -- If the current event is a `E.StopThread` event, and...-          | E.StopThread{} <- getEventInfo j-          , -- ...the previous event was a `E.StopThread` event, then...-            Just E.StopThread{status} <- getEventInfo <$> mi-          , -- ...gather the end time of the previous event, and...-            Just startTimeUnixNano <- timeUnixNano =<< mi-          , -- ...gather the start time of the current event, and...-            Just endTimeUnixNano <- timeUnixNano j -> do-              -- ...yield a thread state span, and...-              yield . setThreadStateSpan j $-                ThreadStateSpan{threadState = Blocked status, ..}-              -- ...keep the current event.-              ---              -- This causes us to adopt every `E.StopThread` event, until-              -- we hit a `E.StopThread` event with the `ThreadFinished`, at-              -- which point the first clause will cause us to stick with it.-              go (Just j)-          ---          -- If the current event is a `E.StopThread` event, and...-          | E.StopThread{} <- getEventInfo j-          , -- ...the previous event was a `E.RunThread` event, then...-            Just E.RunThread{} <- getEventInfo <$> mi-          , -- ...gather the capability of the `E.RunThread` event, and...-            Just cap <- getEventCap =<< mi-          , -- ...gather the end time of the previous event, and...-            Just startTimeUnixNano <- timeUnixNano =<< mi-          , -- ...gather the start time of the current event, and...-            Just endTimeUnixNano <- timeUnixNano j -> do-              -- ...yield a thread state span, and...-              yield . setThreadStateSpan j $-                ThreadStateSpan{threadState = Running cap, ..}-              -- ...keep the current event.-              go (Just j)-          ---          -- If the current event is any other event, then...-          | otherwise -> do-              -- ...emit an error, and...-              logWarning verbosity . T.pack $-                printf-                  "Thread %d: Unexpected event %s"-                  thread-                  (showEventInfo (getEventInfo j))-              ---              -- This case may trigger for any event that isn't `E.RunThread`-              -- or `E.StopThread` and for any `E.StopThread` event that comes-              -- before the first `E.RunThread` event. It may also trigger for-              -- any event for which `timeUnixNano` returns `Nothing`.-              ---              -- ...ignore it.-              go mi------------------------------------------------------------------------------------ Internal Helpers----------------------------------------------------------------------------------{- |-Internal helper.-Check whether a t`ThreadStopStatus` is equal to `ThreadFinished`.-This is needed because t`ThreadStopStatus` does not define an `Eq` instance.--}-isThreadFinished :: ThreadStopStatus -> Bool-isThreadFinished = \case-  ThreadFinished -> True-  _otherwise -> False--{- |-Internal helper.-Show `EventInfo` in a condensed format suitable for logging.--}-showEventInfo :: EventInfo -> String-showEventInfo = \case-  E.RunThread{thread} -> printf "RunThread{%d}" thread-  E.StopThread{thread, status} -> printf "StopThread{%d,%s}" thread (E.showThreadStopStatus status)-  E.MigrateThread{thread} -> printf "MigrateThread{%d}" thread-  E.StartGC{} -> "StartGC"-  E.EndGC{} -> "EndGC"-  evSpec -> takeWhile (not . isSpace) . show $ evSpec--{- |-Internal helper. Return the minimal value by some projection.--}-minBy :: (Ord b) => (a -> b) -> a -> a -> a-minBy f x y = if f x < f y then x else y
− src/GHC/Eventlog/Live/Machine/Core.hs
@@ -1,510 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--{- |-Module      : GHC.Eventlog.Live.Machine.Core-Description : Core machines for processing data in batches.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Machine.Core (-  -- * Ticks-  Tick (..),-  batchByTick,-  batchToTick,-  batchListToTick,-  batchByTickList,-  dropTick,-  onlyTick,-  aggregateByTick,-  liftTick,-  liftBatch,--  -- * Debug-  counterBy,-  counterByTick,--  -- * Routers-  liftRouter,--  -- * Event sorting-  sortByBatch,-  sortByBatchTick,--  -- * Delimiting-  between,-  delimit,--  -- * Validation-  validateInput,-  validateOrder,-) where--import Control.Monad (when)-import Control.Monad.IO.Class (MonadIO (..))-import Data.DList qualified as D-import Data.Foldable (for_)-import Data.Function (on)-import Data.Functor ((<&>))-import Data.HashMap.Strict (HashMap)-import Data.HashMap.Strict qualified as M-import Data.Hashable (Hashable (..))-import Data.List qualified as L-import Data.Machine (Is (..), MachineT (..), Moore (..), PlanT, Process, ProcessT, Step (..), asParts, await, construct, encased, mapping, repeatedly, starve, stopped, yield, (~>))-import Data.Maybe (fromMaybe)-import Data.Semigroup (Max (..))-import Data.Text (Text)-import Data.Text qualified as T-import GHC.Eventlog.Live.Logger (logDebug, logError, logWarning)-import GHC.Eventlog.Live.Verbosity (Verbosity, verbosityDebug, verbosityError, verbosityWarning)-import GHC.RTS.Events (Event (..), Timestamp)-import GHC.RTS.Events qualified as E-import Text.Printf (printf)------------------------------------------------------------------------------------ Ticks----------------------------------------------------------------------------------{- |-The type of data on a stream of items and ticks.--The t`Tick` type is isomorphic to `Maybe` modulo strictness,-but with the caveat that v`Tick` does not represent failure.--}-data Tick a = Item !a | Tick-  deriving (Eq, Functor, Foldable, Traversable, Show)--{- |-This machine batches all items between two ticks into a list.--}-batchByTickList :: Process (Tick a) [a]-batchByTickList =-  mapping (fmap D.singleton)-    ~> batchByTick-    ~> mapping D.toList--{- |-Generalised version of `batchByTickList`.--}-batchByTick ::-  forall a.-  (Monoid a) => Process (Tick a) a-batchByTick = batchByTickWith mempty- where-  batchByTickWith ::-    forall m.-    (Monad m) =>-    a -> MachineT m (Is (Tick a)) a-  batchByTickWith acc = MachineT $ pure $ Await onNext Refl onStop-   where-    onNext :: Tick a -> MachineT m (Is (Tick a)) a-    onNext = \case-      Item a -> batchByTickWith (a <> acc)-      Tick -> MachineT $ pure $ Yield acc batchByTick-    onStop :: MachineT m (Is (Tick a)) a-    onStop = MachineT $ pure $ Yield acc stopped--{- |-This machine streams a list of items into a series of items-separated by ticks.--}-batchListToTick :: Process [a] (Tick a)-batchListToTick = batchToTick--{- |-Generalised version of `batchListToTick`.--}-batchToTick :: (Foldable f) => Process (f a) (Tick a)-batchToTick = repeatedly go- where-  go = await >>= \xs -> for_ xs (yield . Item) >> yield Tick--{- |-This machine drops all ticks.--}-dropTick :: Process (Tick a) a-dropTick =-  repeatedly $-    await >>= \case-      Item a -> yield a-      Tick -> pure ()--{- |-This machine drops all items.--}-onlyTick :: Process (Tick a) ()-onlyTick =-  repeatedly $-    await >>= \case-      Tick -> yield ()-      Item{} -> pure ()--{- |-This machine aggregates a value by tick.--The difference between `batchByTick` and `aggregateByTick` is that-`batchByTick` yields a batch on every tick whereas-`aggregateByTick` only yields a batch if there were any values.--}-aggregateByTick :: (Semigroup a) => Process (Tick a) a-aggregateByTick =-  mapping (fmap Just)-    ~> batchByTick-    ~> asParts------------------------------------------------------------------------------------ Machine combinators----------------------------------------------------------------------------------{- |-This machine counts the number of inputs it received,-using the given function, and logs this value.--}-counterBy ::-  forall m a x.-  (MonadIO m) =>-  Verbosity ->-  Text ->-  (a -> Word) ->-  ProcessT m a x-counterBy verbosity label counter-  | verbosityDebug >= verbosity = repeatedly go-  | otherwise = stopped- where-  go :: PlanT (Is a) x m ()-  go =-    await >>= \a ->-      logDebug verbosity (T.pack (show (counter a)) <> " " <> label)--{- |-This machine counts the number of inputs it received,-and logs this value on every tick.--}-counterByTick ::-  forall m a x.-  (MonadIO m) =>-  Verbosity ->-  Text ->-  ProcessT m (Tick a) x-counterByTick verbosity label-  | verbosityDebug >= verbosity = construct $ go 0-  | otherwise = stopped- where-  go :: Word -> PlanT (Is (Tick a)) x m ()-  go count =-    await >>= \case-      Item _ -> go (count + 1)-      Tick -> logDebug verbosity (T.pack (show count) <> " " <> label) >> go 0------------------------------------------------------------------------------------ Machine combinators--------------------------------------------------------------------------------------------------------------------------------------------------------------------- Lift a machine to a machine that passes on ticks unchanged--{- |-Lift a machine to a machine that passes on ticks unchanged.--Constructs the following machine:--@-           ┌─(if Tick)────────────────────┐-  [ Tick a ]                              [ Tick b ]-           └─(if Item)─( ProcessT m a b )─┘-@--}-liftTick ::-  (Monad m) =>-  ProcessT m a b ->-  ProcessT m (Tick a) (Tick b)-liftTick m =-  MachineT $-    runMachineT m <&> \case-      Stop ->-        Stop-      Yield o k ->-        Yield (Item o) (liftTick k)-      Await (onNext :: t -> ProcessT m a b) Refl onStop ->-        await'-       where-        await' = Await onNext' Refl onStop'-         where-          onNext' :: Tick a -> ProcessT m (Tick a) (Tick b)-          onNext' = \case-            Tick ->-              MachineT . pure . Yield Tick $-                MachineT . pure $-                  await'-            Item a -> liftTick (onNext a)-          onStop' :: ProcessT m (Tick a) (Tick b)-          onStop' = liftTick onStop------------------------------------------------------------------------------------- Lift a machine to a machine that operates on batches--{- |-Lift a machine that processes @a@s into @b@s to a machine that processes-batches of @a@s into batches of @b@s.--}-liftBatch ::-  forall m a b.-  (Monad m) =>-  ProcessT m a b ->-  ProcessT m [a] [b]-liftBatch = MachineT . running [] []- where-  -- The parent machine is running the child machine with the current batch.-  running :: [a] -> [b] -> ProcessT m a b -> m (Step (Is [a]) [b] (ProcessT m [a] [b]))-  running as bs m =-    runMachineT m >>= \case-      Stop ->-        pure Stop-      Yield b k ->-        running as (b : bs) k-      Await (onNext :: t -> ProcessT m a b) Refl onStop ->-        pure $ Yield (reverse bs) $ MachineT $ awaiting as onNext onStop--  -- The parent machine is awaiting new input.-  awaiting :: [a] -> (a -> ProcessT m a b) -> ProcessT m a b -> m (Step (Is [a]) [b] (ProcessT m [a] [b]))-  awaiting (a : as) onNext _onStop = running as [] $ onNext a-  awaiting [] onNext onStop = pure $ Await onNext' Refl onStop'-   where-    onNext' :: [a] -> ProcessT m [a] [b]-    onNext' as = MachineT $ awaiting as onNext onStop-    onStop' :: ProcessT m [a] [b]-    onStop' = exhausting onStop--  -- The parent machine is exhausting the child machine to gather its output.-  exhausting :: ProcessT m a b -> ProcessT m x [b]-  exhausting = MachineT . go []-   where-    go :: [b] -> ProcessT m a b -> m (Step (Is x) [b] (ProcessT m x [b]))-    go bs m =-      runMachineT m >>= \case-        Stop ->-          pure Stop-        Yield b k ->-          go (b : bs) k-        Await _onNext _Refl onStop ->-          pure $ Yield (reverse bs) $ MachineT $ go [] onStop------------------------------------------------------------------------------------- Construct a processor that spawns a separate child processor for each measure--{- |-Spawn a copy of a machine for each "measure".--Constructs the following machine:--@-    ┌─────(if measure == k0)─( ProcessT m a b )────┐-  [ a ] ──(if measure == ..)─( ProcessT m a b )─ [ b ]-    └─────(if measure == kN)─( ProcessT m a b )────┘-@--__Warning:__ The router does not currently garbage-collect terminated child processors.--}-liftRouter ::-  forall m k a b.-  (MonadIO m, Hashable k) =>-  -- | Function to measure.-  (a -> Maybe k) ->-  -- | Function to spawn child processors.-  (k -> ProcessT m a b) ->-  ProcessT m a b-liftRouter measure spawn = awaiting M.empty- where-  awaiting :: HashMap k (ProcessT m a b) -> ProcessT m a b-  awaiting st = MachineT . pure $ Await onNext Refl onStop-   where-    onNext :: a -> MachineT m (Is a) b-    onNext a = case measure a of-      Nothing -> awaiting st-      Just k -> provideThen a m $ \m' -> awaiting (M.insert k m' st)-       where-        m = fromMaybe (spawn k) (M.lookup k st)-    onStop :: MachineT m (Is a) b-    onStop = foldr starve stopped (M.elems st)--  provideThen :: a -> ProcessT m a b -> (ProcessT m a b -> ProcessT m a b) -> ProcessT m a b-  provideThen a m k =-    MachineT $-      runMachineT m >>= \case-        Stop -> runMachineT (k stopped)-        Yield o m' -> pure (Yield o (provideThen a m' k))-        Await onNext Refl _onStop -> runMachineT (exhaustThen (onNext a) k)--  exhaustThen :: ProcessT m a b -> (ProcessT m a b -> ProcessT m a b) -> ProcessT m a b-  exhaustThen m k =-    MachineT $-      runMachineT m >>= \case-        Yield o m' -> pure (Yield o (k m'))-        m' -> runMachineT (k (encased m'))------------------------------------------------------------------------------------ Event stream sorting----------------------------------------------------------------------------------{- |-Reorder events respecting ticks.--This machine caches two batches worth of events, sorts them together,-and then yields only those events whose timestamp is less than or equal-to the maximum of the first batch.--}-sortByBatch ::-  forall m a.-  (Monad m) =>-  (a -> Timestamp) ->-  ProcessT m [a] [a]-sortByBatch timestamp = sortByBatchWith Nothing- where-  sortByBatchWith :: Maybe [a] -> ProcessT m [a] [a]-  sortByBatchWith = \case-    Nothing -> MachineT $ pure $ Await onNext Refl onStop-     where-      onNext :: [a] -> ProcessT m [a] [a]-      onNext new = sortByBatchWith (Just sortedNew)-       where-        sortedNew = sortByTime new-      onStop :: ProcessT m [a] [a]-      onStop = stopped-    Just sortedOld -> MachineT $ pure $ Await onNext Refl onStop-     where-      onNext :: [a] -> ProcessT m [a] [a]-      onNext new-        | null sortedOld = sortByBatchWith $ Just sortedNew-        | otherwise = MachineT $ pure $ Yield sortedBeforeCutoff $ sortByBatchWith $ Just sortedAfterCutoff-       where-        -- NOTE: use of partial @maximum@ is guarded by the check @null old@.-        cutoff = getMax (foldMap (Max . timestamp) sortedOld)-        sortedNew = sortByTime new-        sorted = joinByTime sortedOld sortedNew-        (sortedBeforeCutoff, sortedAfterCutoff) = L.partition ((<= cutoff) . timestamp) sorted-      onStop :: ProcessT m [a] [a]-      onStop = MachineT $ pure $ Yield sortedOld $ stopped--  -- compByTime :: a -> a -> Ordering-  compByTime = compare `on` timestamp--  -- sortByTime :: [a] -> [a]-  sortByTime = L.sortBy compByTime--  -- joinByTime :: [a] -> [a] -> [a]-  joinByTime [] ys = ys-  joinByTime xs [] = xs-  joinByTime (x : xs) (y : ys) = case compByTime x y of-    LT -> x : joinByTime xs (y : ys)-    _ -> y : joinByTime (x : xs) ys--{- |-Variant of `sortByBatch` that operates on streams of items and ticks.--}-sortByBatchTick :: (a -> Timestamp) -> Process (Tick a) (Tick a)-sortByBatchTick timestamp =-  mapping (fmap (: [])) ~> batchByTick ~> sortByBatch timestamp ~> batchListToTick------------------------------------------------------------------------------------ Filtering semaphores----------------------------------------------------------------------------------{- | A simple delimiting t'Moore' machine,-which is opened by one constant marker and closed by the other one.--}-between :: Text -> Text -> Moore Text Bool-between x y = open- where-  open = Moore False open' where open' x' = if x == x' then close else open-  close = Moore True close' where close' y' = if y == y' then end else close-  end = Moore False (const end)---- | Delimit the event process.-delimit :: (Monad m) => Moore Text Bool -> ProcessT m Event Event-delimit = construct . go- where-  go :: (Monad m) => Moore Text Bool -> PlanT (Is Event) Event m ()-  go mm@(Moore s next) = do-    e <- await-    case evSpec e of-      -- on marker step the moore machine.-      E.UserMarker m -> do-        let mm'@(Moore s' _) = next m-        -- if current or next state is open (== True), emit the marker.-        when (s || s') $ yield e-        go mm'--      -- for other events, emit if the state is open.-      _ -> do-        when s $ yield e-        go mm------------------------------------------------------------------------------------ Validation----------------------------------------------------------------------------------{- |-This machine validates that there is some input.--If no input is encountered after the given number of ticks, the machine prints-a warning that directs the user to check that the @-l@ flag was set correctly.--}-validateInput ::-  (MonadIO m) =>-  Verbosity ->-  Int ->-  ProcessT m (Tick a) x-validateInput verbosity ticks-  | verbosityWarning >= verbosity = construct $ start ticks-  | otherwise = stopped- where-  start remaining-    | remaining <= 0 = liftIO $ do-        logWarning verbosity . T.pack $-          printf-            "No input after %d ticks. Did you pass -l to the GHC RTS?"-            ticks-    | otherwise = do-        logDebug verbosity $-          T.pack (show remaining) <> " ticks remaining."-        await >>= \case-          Item{} -> do-            logDebug verbosity "Received item."-          Tick -> do-            logDebug verbosity "Received tick."-            start (pred remaining)--{- |-This machine validates that the inputs are received in order.--If an out-of-order input is encountered, the machine prints an error message-that directs the user to check that the @--eventlog-flush-interval@ and the-@--batch-interval@ flags are set correctly.--}-validateOrder ::-  (MonadIO m, Show a) =>-  Verbosity ->-  (a -> Timestamp) ->-  ProcessT m a x-validateOrder verbosity timestamp-  | verbosityError >= verbosity = construct $ start Nothing-  | otherwise = stopped- where-  start maybeOld =-    await >>= \new ->-      case maybeOld of-        Just old-          | timestamp new < timestamp old -> do-              logError verbosity . T.pack $-                "Encountered two out-of-order inputs.\n\-                \Did you pass --eventlog-flush-interval to the GHC RTS?\n\-                \Did you set --batch-interval to be at least as big as the value of --eventlog-flush-interval?"-              logDebug verbosity . T.pack $-                printf-                  "Out-of-order inputs:\n\-                  \- %s\n\-                  \- %s"-                  (show old)-                  (show new)-              pure ()-        _otherwise -> do-          start (Just new)
− src/GHC/Eventlog/Live/Machine/Decoder.hs
@@ -1,49 +0,0 @@-{- |-Module      : GHC.Eventlog.Live.Machine.Decoder-Description : Machines for processing eventlog data.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Machine.Decoder (-  -- * Event decoding-  DecodeError (..),-  decodeEvent,-  decodeEventBatch,-) where--import Control.Exception (Exception, throwIO)-import Control.Monad.IO.Class (MonadIO (..))-import Data.ByteString qualified as BS-import Data.Machine (Is, PlanT, ProcessT, await, construct, yield)-import GHC.Eventlog.Live.Machine.Core (Tick (..), liftTick)-import GHC.RTS.Events (Event)-import GHC.RTS.Events.Incremental (Decoder (..), decodeEventLog)------------------------------------------------------------------------------------ Decoding events--{- |-Parse t'Event's from a stream of 'BS.ByteString' chunks with ticks.--Throws a t'DecodeError' on error.--}-decodeEvent :: (MonadIO m) => ProcessT m BS.ByteString Event-decodeEvent = construct $ loop decodeEventLog- where-  loop :: (MonadIO m) => Decoder a -> PlanT (Is BS.ByteString) a m ()-  loop Done{} = pure ()-  loop (Consume k) = await >>= \chunk -> loop (k chunk)-  loop (Produce a d') = yield a >> loop d'-  loop (Error _ err) = liftIO $ throwIO $ DecodeError err--{- |-Parse 'Event's from a stream of 'BS.ByteString' chunks with ticks.--Throws 'DecodeError' on error.--}-decodeEventBatch :: (MonadIO m) => ProcessT m (Tick BS.ByteString) (Tick Event)-decodeEventBatch = liftTick decodeEvent--newtype DecodeError = DecodeError String deriving (Show)--instance Exception DecodeError
− src/GHC/Eventlog/Live/Machine/Sink.hs
@@ -1,42 +0,0 @@-{- |-Module      : GHC.Eventlog.Live.Machine.Sink-Description : Machines for processing eventlog data.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Machine.Sink (-  -- * Eventlog file sink-  fileSink,-  fileSinkBatch,-) where--import Control.Monad.IO.Class (MonadIO (..))-import Data.ByteString qualified as BS-import Data.Machine (ProcessT, await, repeatedly, (~>))-import Data.Void (Void)-import GHC.Eventlog.Live.Machine.Core (Tick (..), dropTick)-import System.IO (Handle)------------------------------------------------------------------------------------ Log file sink--{- |-File sink for optional eventlog log file.--}-fileSink ::-  (MonadIO m) =>-  Handle ->-  ProcessT m BS.ByteString Void-fileSink handle = repeatedly $ await >>= liftIO . BS.hPut handle------------------------------------------------------------------------------------ Log file sink with batches--{- |-File sink for optional eventlog log file.--}-fileSinkBatch ::-  (MonadIO m) =>-  Handle ->-  ProcessT m (Tick BS.ByteString) Void-fileSinkBatch handle = dropTick ~> fileSink handle
− src/GHC/Eventlog/Live/Machine/Source.hs
@@ -1,144 +0,0 @@-{- |-Module      : GHC.Eventlog.Live.Machine.Source-Description : Machines for processing eventlog data.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Machine.Source (-  -- * Eventlog source-  sourceHandleWait,-  sourceHandleBatch,-  defaultChunkSizeBytes,-) where--import Control.Exception (catch, throwIO)-import Control.Monad.IO.Class (MonadIO (..))-import Data.ByteString qualified as BS-import Data.Function (fix)-import Data.Machine (MachineT (..), construct, yield)-import Data.Word (Word64)-import GHC.Clock (getMonotonicTimeNSec)-import GHC.Eventlog.Live.Machine.Core (Tick (..))-import System.IO (Handle, hWaitForInput)-import System.IO.Error (isEOFError)------------------------------------------------------------------------------------ Socket source--{- |-A source which reads chunks from a `Handle`.-When an input is available, it yields an v`Item`.-When the timeout is reached, it yields a v`Tick`.--}-sourceHandleWait ::-  (MonadIO m) =>-  -- | The wait timeout in milliseconds.-  Int ->-  -- | The number of bytes to read.-  Int ->-  -- | The eventlog socket handle.-  Handle ->-  MachineT m k (Tick BS.ByteString)-sourceHandleWait timeoutMilli chunkSizeBytes handle =-  construct $ fix $ \loop -> do-    ready <- liftIO $ hWaitForInput' handle timeoutMilli-    case ready of-      Ready -> do-        bs <- liftIO $ BS.hGetSome handle chunkSizeBytes-        yield (Item bs)-        loop-      NotReady -> do-        yield Tick-        loop-      EOF ->-        pure ()------------------------------------------------------------------------------------ Socket source with batches--{- |-A source which reads chunks from a `Handle`.-When input is available, it yields an v`Item`.-It yields a v`Tick` at each increment of the batch interval.--}-sourceHandleBatch ::-  (MonadIO m) =>-  -- | The batch interval in milliseconds.-  Int ->-  -- | The number of bytes to read.-  Int ->-  -- | The eventlog socket handle.-  Handle ->-  MachineT m k (Tick BS.ByteString)-sourceHandleBatch batchIntervalMs chunkSizeBytes handle = construct start- where-  start = do-    startTimeMs <- liftIO getMonotonicTimeMilli-    batch startTimeMs-  batch startTimeMs = waitForInput-   where-    getRemainingTimeMilli = do-      currentTimeMilli <- liftIO getMonotonicTimeMilli-      pure $ (startTimeMs + batchIntervalMs) - currentTimeMilli-    waitForInput = do-      remainingTimeMilli <- getRemainingTimeMilli-      if remainingTimeMilli <= 0-        then do-          yield Tick-          start-        else do-          ready <- liftIO (hWaitForInput' handle remainingTimeMilli)-          case ready of-            Ready -> do-              chunk <- liftIO $ BS.hGetSome handle chunkSizeBytes-              yield (Item chunk) >> waitForInput-            NotReady -> waitForInput-            EOF -> pure ()--{- |-Eventlog chunk size in bytes.-This should be equal to the page size.--}-defaultChunkSizeBytes :: Int-defaultChunkSizeBytes = 4096--{- |-Internal helper.-Return monotonic time in milliseconds, since some unspecified starting point--}-getMonotonicTimeMilli :: IO Int-getMonotonicTimeMilli = nanoToMilli <$> getMonotonicTimeNSec--{- |-Internal helper.-Convert nanoseconds to milliseconds.-The conversion from 'Word64' to 'Int' is safe.-It cannot overflow due to the division by 1_000_000.--}-nanoToMilli :: Word64 -> Int-nanoToMilli = fromIntegral . (`div` 1_000_000)--{- |-Internal helper.-Type to represent the state of a handle.--}-data Ready = Ready | NotReady | EOF--{- |-Internal helper.-Wait for input from a `Handle` for a given number of milliseconds.--}-hWaitForInput' ::-  -- | The handle.-  Handle ->-  -- | The timeout in milliseconds.-  Int ->-  IO Ready-hWaitForInput' handle timeoutMilli =-  catch (boolToReady <$> hWaitForInput handle timeoutMilli) handleEOFError- where-  boolToReady True = Ready-  boolToReady False = NotReady-  handleEOFError err-    | isEOFError err = pure EOF-    | otherwise = throwIO err
− src/GHC/Eventlog/Live/Machine/WithStartTime.hs
@@ -1,88 +0,0 @@-{- |-Module      : GHC.Eventlog.Live.Machine.WithStartTime-Description : Machines for processing eventlog data.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Machine.WithStartTime (-  WithStartTime (..),-  setWithStartTime'value,-  tryGetTimeUnixNano,-  withStartTime,-  withStartTime',-  dropStartTime,-) where--import Control.Monad (forever)-import Data.Machine (Is (..), PlanT, Process, await, construct, mapping, yield)-import GHC.RTS.Events (Event (..), EventInfo, Timestamp)-import GHC.RTS.Events qualified as E------------------------------------------------------------------------------------ Start time--{- |-Data decorated with a start time in nanoseconds since the Unix epoch.--}-data WithStartTime a = WithStartTime-  { value :: !a-  , maybeStartTimeUnixNano :: !(Maybe Timestamp)-  }-  deriving (Functor, Show)--{- |-Setter for the value of a t`WithStartTime`--}-setWithStartTime'value :: WithStartTime a -> b -> WithStartTime b-setWithStartTime'value (WithStartTime _a t) b = WithStartTime b t--{- |-If the event has a start time, return `Just` the time of the event in-nanoseconds since the Unix epoch. Otherwise, return `Nothing`.--}-tryGetTimeUnixNano :: WithStartTime Event -> Maybe Timestamp-tryGetTimeUnixNano i = (i.value.evTime +) <$> i.maybeStartTimeUnixNano--{- |-Wrap every event in t`WithStartTime`. Every event after `E.WallClockTime` will-have its start time field set to `Just` the process start time.--This machine swallows the first and only `E.WallClockTime` event.--}-withStartTime :: Process Event (WithStartTime Event)-withStartTime = withStartTime' E.evSpec WithStartTime--{- |-Generalised version of `withStartTime` that can be adapted to work on arbitrary-types using a getter and a setter.--}-withStartTime' :: (a -> EventInfo) -> (a -> Maybe Timestamp -> b) -> Process a b-withStartTime' getEventInfo setStartTime = construct start- where-  start =-    await >>= \case-      value-        -- The `WallClockTime` event announces the wall-clock time at which the-        -- process was started.-        | E.WallClockTime{..} <- getEventInfo value -> do-            -- This will start overflowing on Sunday, 21 July 2554 23:34:33, UTC.-            let !startTimeNs = sec * 1_000_000_000 + fromIntegral nsec-            -- We do not re-emit the `WallClockTime` event.-            continue startTimeNs-        | otherwise ->-            yield (value `setStartTime` Nothing) >> start-  continue startTimeUnixNano =-    mappingPlan $ \value ->-      value `setStartTime` Just startTimeUnixNano--{- |-Drop the t`WithStartTime` wrapper.--}-dropStartTime :: Process (WithStartTime a) a-dropStartTime = mapping (.value)--{- |-Internal helper. Variant of `mapping` for plans.--}-mappingPlan :: (a -> b) -> PlanT (Is a) b m a-mappingPlan f = forever (await >>= \a -> yield (f a))
− src/GHC/Eventlog/Live/Options.hs
@@ -1,201 +0,0 @@-{- |-Module      : GHC.Eventlog.Live.Options-Description : Command-line option parsers for eventlog machines.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Options (-  EventlogSource (..),-  eventlogSourceParser,-  eventlogSocketTimeoutParser,-  eventlogSocketTimeoutExponentParser,-  heapProfBreakdownParser,-  eventlogLogFileParser,-  batchIntervalParser,-  verbosityParser,-  statsParser,-) where--import Control.Applicative (asum)-import Data.Char (toLower)-import GHC.Eventlog.Live.Machine.Analysis.Heap (heapProfBreakdownEitherReader)-import GHC.Eventlog.Live.Verbosity (Verbosity, verbosityDebug, verbosityError, verbosityInfo, verbosityQuiet, verbosityWarning)-import GHC.RTS.Events (HeapProfBreakdown (..))-import Options.Applicative qualified as O-import Text.Read (readEither)------------------------------------------------------------------------------------- Eventlog Source--{- |-The type of eventlog sockets.--}-data EventlogSource-  = EventlogStdin-  | EventlogFile FilePath-  | EventlogSocketUnix FilePath--{- |-Parser for the eventlog socket.--}-eventlogSourceParser :: O.Parser EventlogSource-eventlogSourceParser =-  asum-    [ stdinParser-    , fileParser-    , socketUnixParser-    ]- where-  stdinParser =-    EventlogStdin-      <$ O.flag'-        ()-        ( O.long "eventlog-stdin"-            <> O.help "Read the eventlog from stdin."-        )-  fileParser =-    EventlogFile-      <$> O.strOption-        ( O.long "eventlog-file"-            <> O.metavar "FILE"-            <> O.help "Read the eventlog from a file."-        )-  socketUnixParser =-    EventlogSocketUnix-      <$> O.strOption-        ( O.long "eventlog-socket"-            <> O.metavar "SOCKET"-            <> O.help "Read the eventlog from a Unix socket."-        )--{- |-Parser for the intial timeout for exponential backoff.--}-eventlogSocketTimeoutParser :: O.Parser Double-eventlogSocketTimeoutParser =-  O.option-    O.auto-    ( O.long "eventlog-socket-timeout"-        <> O.metavar "NUM"-        <> O.help "Eventlog socket connection retry timeout in microseconds."-        <> O.value 1-    )--{- |-Parser for the exponent for exponential backoff.--}-eventlogSocketTimeoutExponentParser :: O.Parser Double-eventlogSocketTimeoutExponentParser =-  O.option-    O.auto-    ( O.long "eventlog-socket-exponent"-        <> O.metavar "NUM"-        <> O.help "Eventlog socket connection retry timeout exponent."-        <> O.value 1-    )------------------------------------------------------------------------------------- Heap Profile Breakdown--{- |-Parser for the heap profile breakdown.--}-heapProfBreakdownParser :: O.Parser HeapProfBreakdown-heapProfBreakdownParser =-  O.option-    (O.eitherReader heapProfBreakdownEitherReader)-    ( O.short 'h'-        <> O.metavar "Tcmdyrbi"-        <> O.help "Heap profile breakdown."-    )------------------------------------------------------------------------------------- Eventlog Log File--{- |-Parser for the eventlog log file.--}-eventlogLogFileParser :: O.Parser FilePath-eventlogLogFileParser =-  O.strOption-    ( O.long "eventlog-log-file"-        <> O.metavar "FILE"-        <> O.help "Use file to log binary eventlog data."-    )------------------------------------------------------------------------------------- Batch Interval--{- |-Parser for the batch interval.--}-batchIntervalParser :: O.Parser Int-batchIntervalParser =-  O.option-    O.auto-    ( O.long "batch-interval"-        <> O.metavar "NUM"-        <> O.help "Batch interval in milliseconds."-        <> O.value defaultBatchIntervalMs-    )--{- |-Internal helper.-The default batch interval in milliseconds.--}-defaultBatchIntervalMs :: Int-defaultBatchIntervalMs = 1_000------------------------------------------------------------------------------------- Verbosity--{- |-Parser for verbosities.-The default verbosity is `verbosityWarning`.--}-verbosityParser :: O.Parser Verbosity-verbosityParser =-  O.option-    (O.eitherReader readEitherVerbosity)-    ( O.short 'v'-        <> O.long "verbosity"-        <> O.metavar "quiet|error|warning|info|debug|0-4"-        <> O.help "The verbosity threshold for logging."-        <> O.value verbosityWarning-    )--{- |-Internal helper.-Parser for verbosities by number or name.-Case insensitive.--}-readEitherVerbosity :: String -> Either String Verbosity-readEitherVerbosity rawVerbosity =-  -- try to parse the verbosity as a number...-  case readEither @Word rawVerbosity of-    -- if the verbosity string is a number, map it to a verbosity...-    Right verbosityThreshold-      | verbosityThreshold <= 0 -> Right verbosityQuiet-      | verbosityThreshold == 1 -> Right verbosityError-      | verbosityThreshold == 2 -> Right verbosityWarning-      | verbosityThreshold == 3 -> Right verbosityInfo-      | otherwise -> Right verbosityDebug-    -- otherwise, match it against the literal names of the levels...-    Left _parseError -> case toLower <$> rawVerbosity of-      "quiet" -> Right verbosityQuiet-      "error" -> Right verbosityError-      "warning" -> Right verbosityWarning-      "info" -> Right verbosityInfo-      "debug" -> Right verbosityDebug-      _otherwise -> Left $ "Could not parse verbosity '" <> rawVerbosity <> "'."------------------------------------------------------------------------------------- Statistics--statsParser :: O.Parser Bool-statsParser =-  O.flag False True $-    ( O.short 's'-        <> O.long "stats"-        <> O.help "Display runtime statistics."-    )
− src/GHC/Eventlog/Live/Socket.hs
@@ -1,177 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--{- |-Module      : GHC.Eventlog.Live.Socket-Description : Utilities for running eventlog machines with sockets.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Socket (-  EventlogSource (..),-  Tick (..),-  tryConnect,-  runWithEventlogSource,-) where--import Control.Concurrent (threadDelay)-import Control.Exception (Exception (..))-import Control.Exception qualified as E-import Control.Monad.IO.Unlift (MonadUnliftIO (..))-import Data.Foldable (traverse_)-import Data.Machine (ProcessT, runT_, (~>))-import Data.Machine.Fanout (fanout)-import Data.Maybe (fromMaybe)-import Data.Text (Text)-import Data.Text qualified as T-import Data.Void (Void)-import GHC.Eventlog.Live.Logger (logDebug, logInfo)-import GHC.Eventlog.Live.Machine.Core-import GHC.Eventlog.Live.Machine.Decoder-import GHC.Eventlog.Live.Machine.Sink-import GHC.Eventlog.Live.Machine.Source-import GHC.Eventlog.Live.Options (EventlogSource (..))-import GHC.Eventlog.Live.Verbosity (Verbosity)-import GHC.RTS.Events (Event)-import Network.Socket qualified as S-import System.IO (Handle)-import System.IO qualified as IO-import Text.Printf (printf)--{- |-Run an event processor with an eventlog socket.--}-runWithEventlogSource ::-  (MonadUnliftIO m) =>-  -- | The logging verbosity.-  Verbosity ->-  -- | The eventlog socket handle.-  EventlogSource ->-  -- | The initial timeout in microseconds for exponential backoff.-  Double ->-  -- | The timeout exponent for exponential backoff.-  Double ->-  -- | The batch interval in milliseconds.-  Int ->-  -- | The number of bytes to read (defaults to 4KiB).-  Maybe Int ->-  -- | An optional file to which to stream binary eventlog data.-  Maybe FilePath ->-  -- | The event processor.-  ProcessT m (Tick Event) Void ->-  m ()-runWithEventlogSource verbosity eventlogSocket timeoutExponent initialTimeoutMcs batchIntervalMs maybeChuckSizeBytes maybeOutputFile toEventSink = do-  withEventlogSource verbosity timeoutExponent initialTimeoutMcs eventlogSocket $ \eventlogSource -> do-    let chuckSizeBytes = fromMaybe defaultChunkSizeBytes maybeChuckSizeBytes-    let fromSocket = sourceHandleBatch batchIntervalMs chuckSizeBytes eventlogSource-    case maybeOutputFile of-      Nothing ->-        runT_ $-          fromSocket ~> decodeEventBatch ~> toEventSink-      Just outputFile ->-        withRunInIO $ \runInIO ->-          IO.withFile outputFile IO.WriteMode $ \outputHandle -> do-            runInIO . runT_ $-              fromSocket-                ~> fanout-                  [ fileSinkBatch outputHandle-                  , decodeEventBatch ~> toEventSink-                  ]--{- |-Run an action with a `Handle` to an `EventlogSource`.--}-withEventlogSource ::-  (MonadUnliftIO m) =>-  -- | The logging verbosity.-  Verbosity ->-  -- | The initial timeout in microseconds for exponential backoff.-  Double ->-  -- | The timeout exponent for exponential backoff.-  Double ->-  -- | The eventlog socket.-  EventlogSource ->-  (Handle -> m ()) ->-  m ()-withEventlogSource verbosity initialTimeoutMcs timeoutExponent eventlogSource action = do-  withRunInIO $ \runInIO ->-    case eventlogSource of-      EventlogStdin -> do-        logInfo verbosity "Reading eventlog from stdin"-        let enter = do-              maybeStdinTextEncoding <- IO.hGetEncoding IO.stdin-              IO.hSetBinaryMode IO.stdin True-              pure maybeStdinTextEncoding-        let leave maybeStdinTextEncoding = do-              traverse_ (IO.hSetEncoding IO.stdin) maybeStdinTextEncoding-              IO.hSetNewlineMode IO.stdin IO.nativeNewlineMode-        E.bracket enter leave . const . runInIO . action $ IO.stdin-      EventlogFile eventlogFile -> do-        logInfo verbosity $ "Reading eventlog from " <> T.pack eventlogFile-        IO.withBinaryFile eventlogFile IO.ReadMode $ \handle ->-          runInIO $ action handle-      EventlogSocketUnix eventlogSocketUnix -> do-        logInfo verbosity $ "Waiting to connect on " <> prettyEventlogSocketUnix eventlogSocketUnix-        E.bracket (connectRetry verbosity initialTimeoutMcs timeoutExponent eventlogSocketUnix) IO.hClose $ \handle ->-          runInIO $ action handle--{- |-Connect to an `EventlogSource` with retries and non-randomised exponential backoff.--}-connectRetry ::-  -- | The logging verbosity.-  Verbosity ->-  -- | The initial timeout in microseconds for exponential backoff.-  Double ->-  -- | The timeout exponent for exponential backoff.-  Double ->-  -- | The eventlog socket.-  FilePath ->-  IO Handle-connectRetry verbosity initialTimeoutMcs timeoutExponent eventlogSocketUnix =-  connectLoop initialTimeoutMcs- where-  waitFor :: Double -> IO ()-  waitFor timeoutMcs = threadDelay $ round $ timeoutMcs * 1_000_000--  connectLoop :: Double -> IO Handle-  connectLoop timeoutMcs = do-    let connect = do-          logDebug verbosity $ "Trying to connect on " <> prettyEventlogSocketUnix eventlogSocketUnix-          handle <- tryConnect eventlogSocketUnix-          logInfo verbosity $ "Connected on " <> prettyEventlogSocketUnix eventlogSocketUnix-          pure handle-    let cleanup (e :: E.IOException) = do-          logDebug verbosity $ "Failed to connect on " <> prettyEventlogSocketUnix eventlogSocketUnix <> ": " <> T.pack (displayException e)-          logDebug verbosity $ "Waiting " <> prettyTimeoutMcs timeoutMcs <> " to retry..."-          waitFor timeoutMcs-          connectLoop (timeoutMcs * timeoutExponent)-    E.catch connect cleanup--{- |-Try to connect to a Unix socket.--}-tryConnect :: FilePath -> IO Handle-tryConnect eventlogSocketUnix =-  E.bracketOnError (S.socket S.AF_UNIX S.Stream S.defaultProtocol) S.close $ \socket -> do-    S.connect socket (S.SockAddrUnix eventlogSocketUnix)-    handle <- S.socketToHandle socket IO.ReadMode-    IO.hSetBuffering handle IO.NoBuffering-    pure handle--{- |-Interal helper. Pretty-printer for timeout values in microseconds.--}-prettyTimeoutMcs :: Double -> Text-prettyTimeoutMcs timeoutMcs-  | timeoutMcs > 8.64e10 = T.pack $ printf "%.2f days" (timeoutMcs / 8.64e10)-  | timeoutMcs > 3.6e9 = T.pack $ printf "%.2f hours" (timeoutMcs / 3.6e9)-  | timeoutMcs > 6e7 = T.pack $ printf "%.2f minutes" (timeoutMcs / 6e7)-  | timeoutMcs > 1e6 = T.pack $ printf "%.2f seconds" (timeoutMcs / 1e6)-  | timeoutMcs > 1e3 = T.pack $ printf "%.2f milliseconds" (timeoutMcs / 1e3)-  | otherwise = T.pack $ printf "%.2f microseconds" timeoutMcs--{- |-Internal helper. Pretty-printer for eventlog sockets.--}-prettyEventlogSocketUnix :: FilePath -> Text-prettyEventlogSocketUnix eventlogSocketUnix = "Unix socket " <> T.pack eventlogSocketUnix
− src/GHC/Eventlog/Live/Verbosity.hs
@@ -1,76 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--{- |-Module      : GHC.Eventlog.Live.Verbosity-Description : Logging verbosity for eventlog machines.-Stability   : experimental-Portability : portable--}-module GHC.Eventlog.Live.Verbosity (-  Verbosity,-  showVerbosity,-  verbosityQuiet,-  verbosityError,-  verbosityWarning,-  verbosityInfo,-  verbosityDebug,-) where--import Data.Text (Text)------------------------------------------------------------------------------------ Verbosity----------------------------------------------------------------------------------{- |-The type of logging verbosities supported by the machines-in "GHC.Eventlog.Live.Machines".--}-data Verbosity-  = VerbosityDebug-  | VerbosityInfo-  | VerbosityWarning-  | VerbosityError-  | VerbosityQuiet-  deriving (Eq, Ord)--{- |-Pretty-printer for t`Verbosity`.--}-showVerbosity :: Verbosity -> Text-showVerbosity = \case-  VerbosityDebug -> "Debug"-  VerbosityInfo -> "Info"-  VerbosityWarning -> "Warning"-  VerbosityError -> "Error"-  VerbosityQuiet -> "Quiet"--{- |-Quiet t`Verbosity`.--}-verbosityQuiet :: Verbosity-verbosityQuiet = VerbosityQuiet--{- |-Error t`Verbosity`.--}-verbosityError :: Verbosity-verbosityError = VerbosityError--{- |-Warning t`Verbosity`.--}-verbosityWarning :: Verbosity-verbosityWarning = VerbosityWarning--{- |-Info t`Verbosity`.--}-verbosityInfo :: Verbosity-verbosityInfo = VerbosityInfo--{- |-Debug t`Verbosity`.--}-verbosityDebug :: Verbosity-verbosityDebug = VerbosityDebug
+ vendor/base-compat-0.15.0/Data/Traversable/Compat.hs view
@@ -0,0 +1,94 @@+{-# LANGUAGE CPP #-}++{- |+Module      : Data.Traversable.Compat+Description : Compatibility module for `mapAccumM`.+Copyright   : (c) 2012-2018 Simon Hengel,+              (c) 2014-2018 João Cristóvão,+              (c) 2015-2018 Ryan Scott+License     : MIT+Stability   : experimental+Portability : portable+-}+module Data.Traversable.Compat (+  mapAccumM,+) where++#if MIN_VERSION_base(4,18,0)+import Data.Traversable (mapAccumM)++#else+-- !MIN_VERSION_base(4,18,0)++import Control.Monad (liftM)+import Data.Coerce (Coercible, coerce)++-- | A state transformer monad parameterized by the state and inner monad.+-- The implementation is copied from the transformers package with the+-- return tuple swapped.+--+-- /Since: 4.18.0.0/+newtype StateT s m a = StateT { runStateT :: s -> m (s, a) }++-- | /Since: 4.18.0.0/+instance Monad m => Functor (StateT s m) where+    fmap = liftM+    {-# INLINE fmap #-}++-- | /Since: 4.18.0.0/+instance Monad m => Applicative (StateT s m) where+    pure a = StateT $ \ s -> return (s, a)+    {-# INLINE pure #-}+    StateT mf <*> StateT mx = StateT $ \ s -> do+        (s', f) <- mf s+        (s'', x) <- mx s'+        return (s'', f x)+    {-# INLINE (<*>) #-}+    m *> k = m >> k+    {-# INLINE (*>) #-}++(#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c)+(#.) _f = coerce++-- | /Since: 4.18.0.0/+instance (Monad m) => Monad (StateT s m) where+    m >>= k  = StateT $ \ s -> do+        (s', a) <- (.runStateT) m s+        (.runStateT) (k a) s'+    {-# INLINE (>>=) #-}+# if !(MIN_VERSION_base(4,11,0))+    return = pure+# endif++-- | The `mapAccumM` function behaves like a combination of `mapM` and+-- `mapAccumL` that traverses the structure while evaluating the actions+-- and passing an accumulating parameter from left to right.+-- It returns a final value of this accumulator together with the new structure.+-- The accummulator is often used for caching the intermediate results of a computation.+--+--  @since 4.18.0.0+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> let expensiveDouble a = putStrLn ("Doubling " <> show a) >> pure (2 * a)+-- >>> :{+-- mapAccumM (\cache a -> case lookup a cache of+--     Nothing -> expensiveDouble a >>= \double -> pure ((a, double):cache, double)+--     Just double -> pure (cache, double)+--     ) [] [1, 2, 3, 1, 2, 3]+-- :}+-- Doubling 1+-- Doubling 2+-- Doubling 3+-- ([(3,6),(2,4),(1,2)],[2,4,6,2,4,6])+--+mapAccumM+  :: forall m t s a b. (Monad m, Traversable t)+  => (s -> a -> m (s, b))+  -> s -> t a -> m (s, t b)+mapAccumM f s t = (.runStateT) (mapM (StateT #. flip f) t) s++-- !MIN_VERSION_base(4,18,0)+#endif
+ vendor/hs-opentelemetry-api-1.0.0.0/src/OpenTelemetry/Baggage.hs view
@@ -0,0 +1,708 @@+{- HLINT ignore -}+{- FOURMOLU_DISABLE -}+{-# OPTIONS_GHC -Wno-identities #-}+{-# OPTIONS_GHC -Wno-prepositive-qualified-module #-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE DeriveLift #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE TemplateHaskell #-}++{- |+Module      :  OpenTelemetry.Baggage+Copyright   :  (c) Ian Duncan, 2021-2026+License     :  BSD-3+Description :  Propagated key-value metadata for cross-service context+Stability   :  experimental++= Overview++Baggage is a set of key-value pairs that propagate alongside trace context+across service boundaries (typically via the @baggage@ HTTP header). Use it+to pass metadata like tenant IDs, feature flags, or routing hints through+your distributed system.++Baggage is /not/ for span-specific annotations. Use 'OpenTelemetry.Trace.addAttribute'+for that.++= Quick example++@+import OpenTelemetry.Baggage++-- Create baggage:+let bag = insert [token|tenant-id|] (element "abc123")+        $ insert [token|region|] (element "us-east-1")+        $ empty++-- Encode for HTTP propagation:+let headerValue = encodeBaggageHeader bag+-- "tenant-id=abc123,region=us-east-1"++-- Decode from an incoming header:+case decodeBaggageHeader headerBytes of+  Right bag -> -- use the baggage+  Left err  -> -- malformed header+@++= Thread-local baggage++Use the functions in "OpenTelemetry.Context.ThreadLocal" to get\/set baggage+on the current thread:++@+import OpenTelemetry.Context.ThreadLocal (getContext, adjustContext)+import OpenTelemetry.Context (insertBaggage, lookupBaggage)++-- Read:+mbag <- lookupBaggage \<$\> getContext+-- Write:+adjustContext (insertBaggage myBaggage)+@++= Limits++W3C Baggage specification enforces:++* Max 8192 bytes total serialized size+* Max 4096 bytes per member+* Max 180 members++'insertChecked' validates these limits and returns 'Left' 'InvalidBaggage'+on violation.++= Spec reference++<https://opentelemetry.io/docs/specs/otel/baggage/api/>+-}+module OpenTelemetry.Baggage (+  -- * Constructing 'Baggage' structures+  Baggage,+  empty,+  fromHashMap,+  values,+  Token,+  token,+  mkToken,+  tokenValue,+  Element (..),+  element,+  property,+  InvalidBaggage (..),++  -- * Limits (W3C Baggage specification)+  maxBaggageBytes,+  maxMemberBytes,+  maxMembers,++  -- * Modifying 'Baggage'+  insert,+  insertChecked,+  delete,++  -- * Querying 'Baggage'+  getValue,++  -- * Encoding and decoding 'Baggage'+  encodeBaggageHeader,+  encodeBaggageHeaderB,+  decodeBaggageHeader,+) where++import Control.Monad (when)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as B+import qualified Data.ByteString.Builder.Extra as BS+import Data.ByteString.Char8 (ByteString)+import qualified Data.ByteString.Char8 as B8+import qualified Data.ByteString.Internal as BS+import qualified Data.ByteString.Lazy as L+import Data.ByteString.Unsafe (unsafePackAddressLen)+import qualified Data.HashMap.Strict as H+import Data.Hashable+import Data.Text (Text)+import qualified Data.Text as T+import Data.Text.Encoding (decodeUtf8', encodeUtf8)+import Data.Word (Word8)+import Language.Haskell.TH.Lib+import Language.Haskell.TH.Quote+import Language.Haskell.TH.Syntax+import System.IO.Unsafe+++{- | A key for a baggage entry, restricted to the set of valid characters+ specified in the @token@ definition of RFC 2616:++ https://www.rfc-editor.org/rfc/rfc2616#section-2.2++ @since 0.0.1.0+-}+newtype Token = Token ByteString+  deriving stock (Show, Eq, Ord)+  deriving newtype (Hashable)+++{- | Convert a 'Token' into a 'ByteString'++@since 0.0.1.0+-}+tokenValue :: Token -> ByteString+tokenValue (Token t) = t++#if MIN_VERSION_template_haskell(2, 17, 0)+instance Lift Token where+  liftTyped (Token tok) = liftCode $ unsafeTExpCoerce $ bsToExp tok+#else+instance Lift Token where+  liftTyped (Token tok) = unsafeTExpCoerce $ bsToExp tok+#endif+++{- | An entry into the baggage++@since 0.0.1.0+-}+data Element = Element+  { value :: Text+  , properties :: [Property]+  }+  deriving stock (Show, Eq)+++-- | @since 0.0.1.0+element :: Text -> Element+element t = Element t []+++data Property = Property+  { propertyKey :: Token+  , propertyValue :: Maybe Text+  }+  deriving stock (Show, Eq)+++-- | @since 0.0.1.0+property :: Token -> Maybe Text -> Property+property = Property+++{- | Baggage is used to annotate telemetry, adding context and information to metrics, traces, and logs.+ It is a set of name/value pairs describing user-defined properties.+ Each name in Baggage is associated with exactly one value.++ @since 0.0.1.0+-}+newtype Baggage = Baggage (H.HashMap Token Element)+  deriving stock (Show, Eq)+  deriving newtype (Semigroup)+++-- | RFC 2616 token character predicate (no allocation, branchless via table)+isTokenChar :: Char -> Bool+isTokenChar c = w < 128 && tokenTable `BS.index` fromIntegral w /= 0+  where+    w = fromEnum c+{-# INLINE isTokenChar #-}+++-- 128-byte lookup: 1 = valid token char, 0 = invalid+tokenTable :: ByteString+tokenTable =+  BS.pack+    [ 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0 -- 0x00-0x0f+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0 -- 0x10-0x1f+    , 0+    , 1+    , 0+    , 1+    , 1+    , 1+    , 1+    , 1+    , 0+    , 0+    , 1+    , 1+    , 0+    , 1+    , 1+    , 0 --  ! # $ % & ' * + - .+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 0+    , 0+    , 0+    , 0+    , 0+    , 0 -- 0-9+    , 0+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1 -- A-O+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 0+    , 0+    , 0+    , 1+    , 1 -- P-Z ^ _+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1 -- ` a-o+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 1+    , 0+    , 1+    , 0+    , 1+    , 0 -- p-z | ~+    ]+{-# NOINLINE tokenTable #-}+++-- Ripped from file-embed-0.0.13+bsToExp :: (Monad m) => ByteString -> m Exp+#if MIN_VERSION_template_haskell(2, 5, 0)+bsToExp bs =+    return $ ConE 'Token+      `AppE` (VarE 'unsafePerformIO+      `AppE` (VarE 'unsafePackAddressLen+      `AppE` LitE (IntegerL $ fromIntegral $ BS.length bs)+#if MIN_VERSION_template_haskell(2, 16, 0)+      `AppE` LitE (bytesPrimL (+                let BS.PS ptr off sz = bs+                in  mkBytes ptr (fromIntegral off) (fromIntegral sz)))))+#elif MIN_VERSION_template_haskell(2, 8, 0)+      `AppE` LitE (StringPrimL $ B.unpack bs)))+#else+      `AppE` LitE (StringPrimL $ B8.unpack bs)))+#endif+#else+bsToExp bs = do+    helper <- [| stringToBs |]+    let chars = B8.unpack bs+    return $! AppE helper $! LitE $! StringL chars+#endif+++-- | @since 0.0.1.0+mkToken :: Text -> Maybe Token+mkToken txt+  | T.null txt = Nothing+  | txt `T.compareLength` 4096 == GT = Nothing+  | T.all isTokenChar txt = Just $ Token $ encodeUtf8 txt+  | otherwise = Nothing+++-- | @since 0.0.1.0+token :: QuasiQuoter+token =+  QuasiQuoter+    { quoteExp = parseExp+    , quotePat = \_ -> fail "Token as pattern not implemented"+    , quoteType = \_ -> fail "Can't use a Baggage Token as a type"+    , quoteDec = \_ -> fail "Can't use a Baggage Token as a declaration"+    }+  where+    parseExp = \str -> case mkToken $ T.pack str of+      Nothing -> fail (show str ++ " is not a valid Token.")+      Just tok -> lift tok+++-- | @since 0.0.1.0+data InvalidBaggage+  = BaggageTooLong+  | MemberTooLong+  | TooManyListMembers+  | Empty+  deriving stock (Show, Eq)+++-- | @since 0.0.1.0+encodeBaggageHeader :: Baggage -> ByteString+encodeBaggageHeader =+  L.toStrict+    . BS.toLazyByteStringWith (BS.untrimmedStrategy (8192 + 16) BS.smallChunkSize) L.empty+    . encodeBaggageHeaderB+++-- | @since 0.0.1.0+encodeBaggageHeaderB :: Baggage -> B.Builder+encodeBaggageHeaderB (Baggage bmap) =+  go 0 True (take maxMembers $ H.toList bmap)+  where+    go :: Int -> Bool -> [(Token, Element)] -> B.Builder+    go _ _ [] = mempty+    go totalSoFar isFirst ((tok, el) : rest) =+      let memberBs = builderToStrict (encodeMemberB tok el)+          memberLen = BS.length memberBs+          sep = if isFirst then 0 else 1+          newTotal = totalSoFar + sep + memberLen+      in if memberLen > maxMemberBytes+           then go totalSoFar isFirst rest+           else+             if newTotal > maxBaggageBytes+               then mempty+               else+                 (if isFirst then mempty else B.char7 ',')+                   <> B.byteString memberBs+                   <> go newTotal False rest+++encodeMemberB :: Token -> Element -> B.Builder+encodeMemberB (Token k) (Element v props) =+  B.byteString k+    <> B.char7 '='+    <> percentEncodeBuilder (encodeUtf8 v)+    <> mconcat (map (\p -> B.char7 ';' <> propEncoderB p) props)+++propEncoderB :: Property -> B.Builder+propEncoderB (Property (Token k) mv) =+  B.byteString k+    <> maybe+      mempty+      (\v -> B.char7 '=' <> percentEncodeBuilder (encodeUtf8 v))+      mv+++builderToStrict :: B.Builder -> ByteString+builderToStrict = L.toStrict . B.toLazyByteString+++{- | W3C Baggage: max 8192 bytes total, max 180 members, max 4096 bytes per member++@since 0.0.1.0+-}+maxBaggageBytes, maxMemberBytes, maxMembers :: Int+maxBaggageBytes = 8192+maxMemberBytes = 4096+maxMembers = 180+++-- | @since 0.0.1.0+decodeBaggageHeader :: ByteString -> Either String Baggage+decodeBaggageHeader bs+  | BS.length bs > maxBaggageBytes = Left "Baggage header exceeds 8192 byte limit"+  | otherwise = parseBaggageHeader bs+++parseBaggageHeader :: ByteString -> Either String Baggage+parseBaggageHeader input = do+  let stripped = stripOWS input+  when (BS.null stripped) $ Left "Empty baggage header"+  let rawMembers = splitOnByte 0x2C stripped -- ','+  when (length rawMembers > maxMembers) $+    Left ("Baggage has more than " ++ show maxMembers ++ " members")+  members <- mapM parseMember rawMembers+  pure $ Baggage $ H.fromList members+++parseMember :: ByteString -> Either String (Token, Element)+parseMember raw = do+  let s = stripOWS raw+  let (keyBs, rest0) = B8.span isTokenChar s+  when (BS.null keyBs) $ Left "Expected token in baggage member"+  let rest1 = stripOWS rest0+  rest2 <- expectByte 0x3D rest1 -- '='+  let rest3 = stripOWS rest2+      (valBs, rest4) = BS.span isValueByte rest3+  val <- case decodeUtf8' (percentDecode valBs) of+    Right t -> Right t+    Left _ -> Left "Invalid UTF-8 in baggage value"+  props <- parseProperties rest4+  pure (Token keyBs, Element val props)+++parseProperties :: ByteString -> Either String [Property]+parseProperties bs = go (stripOWS bs)+  where+    go s+      | BS.null s = Right []+      | BS.head s == 0x3B = do+          -- ';'+          let s1 = stripOWS (BS.tail s)+              (keyBs, rest0) = B8.span isTokenChar s1+          when (BS.null keyBs) $ Left "Expected token in baggage property"+          let rest1 = stripOWS rest0+          if not (BS.null rest1) && BS.head rest1 == 0x3D -- '='+            then do+              let rest2 = stripOWS (BS.tail rest1)+                  (valBs, rest3) = BS.span isValueByte rest2+              rest <- go (stripOWS rest3)+              propVal <- case decodeUtf8' (percentDecode valBs) of+                Right t -> Right t+                Left _ -> Left "Invalid UTF-8 in baggage property value"+              pure $ Property (Token keyBs) (Just propVal) : rest+            else do+              rest <- go rest1+              pure $ Property (Token keyBs) Nothing : rest+      | otherwise = Left $ "Unexpected byte in baggage: " ++ show (BS.head s)+++isValueByte :: Word8 -> Bool+isValueByte w =+  w == 0x21+    || (w >= 0x23 && w <= 0x2B)+    || (w >= 0x2D && w <= 0x3A)+    || (w >= 0x3C && w <= 0x5B)+    || (w >= 0x5D && w <= 0x7E)+{-# INLINE isValueByte #-}+++stripOWS :: ByteString -> ByteString+stripOWS = B8.dropWhile (\c -> c == ' ' || c == '\t') . B8.dropWhileEnd (\c -> c == ' ' || c == '\t')+{-# INLINE stripOWS #-}+++expectByte :: Word8 -> ByteString -> Either String ByteString+expectByte expected bs+  | BS.null bs = Left $ "Expected " ++ show expected ++ " but got end of input"+  | BS.head bs == expected = Right (BS.tail bs)+  | otherwise = Left $ "Expected " ++ show expected ++ " but got " ++ show (BS.head bs)+{-# INLINE expectByte #-}+++splitOnByte :: Word8 -> ByteString -> [ByteString]+splitOnByte w bs+  | BS.null bs = []+  | otherwise =+      let (before, rest) = BS.break (== w) bs+      in before : if BS.null rest then [] else splitOnByte w (BS.tail rest)+++{- | An empty initial baggage value++@since 0.0.1.0+-}+empty :: Baggage+empty = Baggage H.empty+++-- | @since 0.0.1.0+insert+  :: Token+  -- ^ The name for which to set the value+  -> Element+  -- ^ The value to set. Use 'element' to construct a well-formed element value.+  -> Baggage+  -> Baggage+insert k v (Baggage c) = Baggage (H.insert k v c)+++{- | Insert a key\/value pair into the baggage with W3C limit enforcement.++Returns 'Left' 'InvalidBaggage' if adding the entry would violate:++* 'TooManyListMembers': exceeds 180 entries (W3C ABNF max)+* 'BaggageTooLong': serialized header would exceed 8192 bytes++@since 0.4.0.0+-}+insertChecked+  :: Token+  -> Element+  -> Baggage+  -> Either InvalidBaggage Baggage+insertChecked k v (Baggage c) =+  let c' = H.insert k v c+      newCount = H.size c'+      newBag = Baggage c'+  in if newCount > maxMembers+       then Left TooManyListMembers+       else+         let totalBytes = baggageSerializedSize c'+         in if totalBytes > maxBaggageBytes+              then Left BaggageTooLong+              else Right newBag+++baggageSerializedSize :: H.HashMap Token Element -> Int+baggageSerializedSize m =+  let entries = H.toList m+      memberSizes = map (\(tok, el) -> memberByteLen tok el) entries+      separators = max 0 (length entries - 1)+  in sum memberSizes + separators+  where+    memberByteLen (Token k) (Element v props) =+      BS.length k+        + 1+        + BS.length (percentEncode (encodeUtf8 v))+        + sum (map propLen props)+    propLen (Property (Token pk) Nothing) = 1 + BS.length pk+    propLen (Property (Token pk) (Just pv)) = 1 + BS.length pk + 1 + BS.length (percentEncode (encodeUtf8 pv))+++{- | Delete a key/value pair from the baggage.++@since 0.0.1.0+-}+delete :: Token -> Baggage -> Baggage+delete k (Baggage c) = Baggage (H.delete k c)+++{- | Look up a baggage value by name.++Per the spec, this takes a name and returns the associated value, or+'Nothing' if the name is not present in the baggage.++@since 0.4.0.0+-}+getValue :: Token -> Baggage -> Maybe Text+getValue k (Baggage m) = case H.lookup k m of+  Just (Element v _) -> Just v+  Nothing -> Nothing+++{- | Returns the name/value pairs in the `Baggage`. The order of name/value pairs+ is not significant.++ @since 0.0.1.0+-}+values :: Baggage -> H.HashMap Token Element+values (Baggage m) = m+++{- | Convert a 'H.HashMap' into 'Baggage'++@since 0.0.1.0+-}+fromHashMap :: H.HashMap Token Element -> Baggage+fromHashMap = Baggage+++-- Percent-encoding (RFC 3986 unreserved characters)+-- Spaces are always encoded as %20 (not +).++isUnreserved :: Word8 -> Bool+isUnreserved w =+  (w >= 65 && w <= 90) -- A-Z+    || (w >= 97 && w <= 122) -- a-z+    || (w >= 48 && w <= 57) -- 0-9+    || w == 45 -- -+    || w == 46 -- .+    || w == 95 -- _+    || w == 126 -- ~+{-# INLINE isUnreserved #-}+++percentEncode :: ByteString -> ByteString+percentEncode = L.toStrict . B.toLazyByteString . percentEncodeBuilder+{-# INLINE percentEncode #-}+++percentEncodeBuilder :: ByteString -> B.Builder+percentEncodeBuilder = BS.foldl' (\acc w -> acc <> encodeWord8 w) mempty+  where+    encodeWord8 w+      | isUnreserved w = B.word8 w+      | otherwise = B.char7 '%' <> hexWord8 w+    hexWord8 w =+      let (hi, lo) = w `divMod` 16+      in B.word8 (hexDigit hi) <> B.word8 (hexDigit lo)+    hexDigit n+      | n < 10 = n + 48 -- '0'+      | otherwise = n + 55 -- 'A' - 10+++percentDecode :: ByteString -> ByteString+percentDecode bs = L.toStrict $ B.toLazyByteString $ go 0+  where+    len = BS.length bs+    go i+      | i >= len = mempty+      | BS.index bs i == 0x25+      , i + 2 < len -- '%'+      , Just hi <- unhex (BS.index bs (i + 1))+      , Just lo <- unhex (BS.index bs (i + 2)) =+          B.word8 (hi * 16 + lo) <> go (i + 3)+      | otherwise =+          B.word8 (BS.index bs i) <> go (i + 1)+    unhex w+      | w >= 48 && w <= 57 = Just (w - 48) -- 0-9+      | w >= 65 && w <= 70 = Just (w - 55) -- A-F+      | w >= 97 && w <= 102 = Just (w - 87) -- a-f+      | otherwise = Nothing