# FeedHub Edge guide

FeedHub Edge is the container you run in your own infrastructure to receive FeedHub's sports data, to place bets
through FeedHub, to ask for their state and to receive their results. This guide is for a team that runs Edge and
builds an application on it. It covers connecting to FeedHub and checking a first start, the sandbox, running Edge
with compose or its Helm chart, getting and verifying its image, configuring it, its local API
(the gRPC service `FeedEdge`, with `PlaceBet` for bets, `GetBets` for their state, `ReadBetResults` and
`ConfirmBetResult` for their results, and the local REST API under `/local/v1`), the rules your application applies,
the Edge versions FeedHub supports, the local API's versioning, the .NET client package, what this build doesn't serve
yet, a runbook, and the sample consumer.

The local API is the whole interface between Edge and your applications. How Edge itself talks to FeedHub is
internal to Edge, isn't part of this guide, and may change in any Edge release without notice.

## What Edge is to an application

- Edge connects to one FeedHub instance with the credentials of your client entry, loads the current state of the
  sports your entry receives, and then keeps that state in memory, current with every change FeedHub publishes. It
  hides disconnects and repairs its own state; your application never sees any of that, only the changes it results
  in.
- Your applications connect to Edge, never to FeedHub. Each one calls `Subscribe` over gRPC to get a snapshot of the
  events and markets it asked for, then their changes, and reads reference data, events, markets and the pre-bet
  refresh over local REST.
- An application places a bet by calling `PlaceBet` over gRPC. Edge passes each call on to FeedHub and returns
  FeedHub's answer; it holds nothing of the bet beyond the wait for that answer (`PlaceBet`).
- An application asks for the state of its bets by calling `GetBets` over gRPC. Edge passes each call on to FeedHub and
  returns FeedHub's answer; it holds nothing of it (`GetBets`).
- An application receives its bets' results through `ReadBetResults` and confirms each with `ConfirmBetResult`. A
  result it hasn't confirmed comes again, also after an Edge restart: FeedHub keeps it until Edge passes on your
  confirmation (`ReadBetResults` and `ConfirmBetResult`).
- Edge's state is in memory only. A restart loads it again from FeedHub, and every application gets a fresh snapshot.
- Run one Edge per client environment, as a service of its own that all your applications share, not as a sidecar of
  each application. Its status (`ready` or `degraded`) is its availability signal. One replica is the default; for
  availability you can run several (Several replicas).

## Connecting to FeedHub

FeedHub operations create a client entry for you and hand over its values:

- the FeedHub instance, for `FeedHub:Instance`;
- the host name of that instance's broker and its AMQPS port, for `RabbitMq:Host` and `RabbitMq:Port`;
- the username of your client entry, for `RabbitMq:Username`;
- its secret, for `RabbitMq:Password`;
- its binding keys, for `FeedHub:Bindings`;
- the number of replicas you may run (Several replicas).

The secret leaves FeedHub once, to the person your organisation names, over one channel FeedHub operations choose. It
is never sent in a ticket, a wiki page, a repository, a chat or an email, so keep it the same way, in your own secret
store. FeedHub can't recover a lost secret: ask FeedHub operations for a new one, which replaces it (Keys you must
give). Everything else you need is published, without credentials: the image and the client package of each Edge
release (Getting the image).

Connect in this order:

1. Get the image and verify its signature (Getting the image).
2. Fill in `.env` from the env file template (Running Edge), or the chart's values (Helm), with the values handed
   over.
3. Start Edge.
4. Run the checks below, in their order. Each check that fails points to the runbook rows that explain it (Runbook);
   Edge's log says which one applies.

The commands reach Edge on the compose example's host ports, 8089 for HTTP and 8090 for gRPC. Under Kubernetes, forward
them first with `kubectl port-forward service/<service> 8089:8080 8090:8081`, where `<service>` is the chart's Service:
`<release>-feedhub-edge`, or `<release>` alone when the release name already contains `feedhub-edge`.

| Check | Passes when | When it fails |
| --- | --- | --- |
| `curl -i http://localhost:8089/healthz` | `200` with the body `Healthy` | Edge has exited `1`: "Start with invalid or missing settings", "Edge's credentials refused" or "This Edge version disabled". Under compose the container stays stopped (the example sets no `restart` policy); under Kubernetes the pod restarts in a crash loop |
| `curl -i http://localhost:8089/local/v1/ready` | `200` with the body `Healthy`, once Edge has loaded its initial state | `503` `edge-not-ready`: "Edge is loading its initial state" while it loads, then by the log "FeedHub unreachable at start", "Broker unreachable", "TLS connection to the broker fails", "Broker connection refused at your client entry's connection cap" or "A replica started with an index your client entry doesn't have" |
| `curl -s http://localhost:8089/local/v1/status` | `status` reads `Ready` | `Degraded`: "Edge is degraded", by its `reason` |
| `curl -s 'http://localhost:8089/local/v1/events?limit=5'` | `items` holds events | no events: check `FeedHub:Bindings` against the binding keys handed over (Keys you must give), and "Edge is degraded" for `ARRIVAL` |
| `Subscribe`, below | it prints `"snapshotEnd"` | the status code, by `Subscribe`'s Status codes; `UNAVAILABLE` as for `/local/v1/ready` |

The gRPC checks run `grpcurl` from its Docker image, with the proto file `feed_edge.proto` from the client package in
the current folder. `--network host` lets the container reach `localhost:8090` on Linux; elsewhere, drop it and use
`host.docker.internal:8090` instead of `localhost:8090`. `Subscribe` with an empty filter receives every event of your
client entry, and the command prints `"snapshotEnd"` once the snapshot is complete. It ends within 60 s:

```bash
docker run --rm --network host -v "$PWD:/protos:ro" fullstorydev/grpcurl:v1.9.1 \
  -plaintext -import-path /protos -proto feed_edge.proto -max-time 60 -d '{}' \
  localhost:8090 feedhub.edge.v1.FeedEdge/Subscribe | grep -m 1 '"snapshotEnd"'
```

On a production client entry the checks end here: the local REST read and `Subscribe` reaching `"snapshotEnd"` are
enough for the first start. `PlaceBet` is a sandbox check only, below.

### The sandbox

Before production, FeedHub operations can give you a client entry on the sandbox, FeedHub's test instance. Its values
are handed over as production's are, the list above, and you connect to it by the same steps:

- your entry receives the sports you ask for, live and prematch as you ask; Football live and prematch when you name
  none. It may place bets, and it has one replica;
- the sandbox makes no availability promise: FeedHub may redeploy it, or run a FeedHub build not yet released, at any
  time. A redeploy reads, for your Edge, as an unreachable broker or FeedHub, and Edge recovers on its own (Runbook). A
  FeedHub build there ahead of the feed format versions your Edge reads (`wire_versions`) turns Edge `degraded` until
  you run an Edge release that reads them;
- its allowed Edge versions can hold test entries, and an Edge version disabled there stops as on any instance
  (Runbook);
- when your use of the sandbox ends, FeedHub operations revoke the entry, and Edge's credentials are refused from then
  on.

The sandbox also has the `PlaceBet` check. The `PlaceBet` check places a real bet, so run it on the sandbox only, never
as a first-start check of a production client entry. Take an event from the events check, read its markets with `curl -s http://localhost:8089/local/v1/events/<eventId>/markets`,
and fill in a new `clientBetKey` of your own, a `marketId` from an item's `market.markets`, the `selectionId` and `value` of
one of that market's selections, a `stake`, and the event's `isLive`. The check passes when the command prints a reply
with an `outcome`, whichever it is; `UNAVAILABLE` or `DEADLINE_EXCEEDED` is explained by "`PlaceBet` or `GetBets`
answers `UNAVAILABLE` or `DEADLINE_EXCEEDED` on every call" (Runbook), any other code by the Status codes of `PlaceBet`.
The command waits 20 s at most, above `Betting:RequestTimeout`:

```bash
docker run --rm --network host -v "$PWD:/protos:ro" fullstorydev/grpcurl:v1.9.1 \
  -plaintext -import-path /protos -proto feed_edge.proto -max-time 20 \
  -d '{"clientBetKey": "<new key>", "marketId": "<marketId>", "selectionId": "<selectionId>", "price": "<value>", "stake": "<stake>", "acceptPriceChanges": true, "isLive": <true or false>}' \
  localhost:8090 feedhub.edge.v1.FeedEdge/PlaceBet
```

## Running Edge

Edge ships as the image `feedhub-edge`, published to a public registry with its signature, its SBOM and its release
notes (Getting the image). Each release's client package holds a compose example, an env file template and a Helm chart
(Helm):

- `docker-compose.example.yml` runs one service, `feedhub-edge`, from the image by name, with
  `image: ${DOCKER_REGISTRY-}feedhub-edge:${EDGE_IMAGE_TAG:?set EDGE_IMAGE_TAG}` and `env_file: .env`;
- `edge.env.example` is the env file template. Copy it to `.env` next to the compose file and fill in every key
  (Configuration). `DOCKER_REGISTRY` is the registry the image is pulled from, ending in a slash (`registry.betfeedpro.com/`
  for the published image, empty for an image already on the machine), and `EDGE_IMAGE_TAG` the Edge version to run,
  alone or pinned to its digest (Getting the image). Compose reads both; Edge doesn't;
- the example publishes container port 8080 (HTTP/1.1: `/healthz` and `/local/v1`) on host port 8089, and container
  port 8081 (gRPC over HTTP/2 without TLS) on host port 8090;
- it sets no compose `healthcheck` (the image has no `curl` or `wget`) and no `restart` policy, so an Edge that exits
  `1` stays stopped. Under Kubernetes, the chart probes liveness on `/healthz` and readiness on `/local/v1/ready`, both
  with `httpGet` on the HTTP/1.1 port (Helm).

```bash
cp edge.env.example .env      # then fill in .env
docker compose -f docker-compose.example.yml up
```

`GET /healthz` answers `200` with the body `Healthy` once the process runs. It never says that data is current
(Runbook). `GET /local/v1/ready` answers `503` with the problem code `edge-not-ready` until Edge has loaded its initial
state, and `200` with the body `Healthy` from then on, also while the status is `degraded`: a pod probed on it gets no
connection through its Service before it can serve, and stays NotReady while Edge waits for FeedHub at start.

### Helm

The chart `feedhub-edge` runs Edge on Kubernetes. Its `.tgz` is in the client package (Getting the image), and its
version is the Edge version it runs: a chart is published only with an Edge release, so a fix to the chart alone is a
new Edge `PATCH`. It creates:

- one Deployment per replica index from 1 to `replicas`, each with one replica, `strategy: Recreate` and its index in
  `FeedHub:Replica` (Several replicas), and one Service selecting the pods of all of them, with ports `http` 8080 and
  `grpc` 8081;
- a liveness probe on `/healthz` and a readiness probe on `/local/v1/ready`, both `httpGet` on port 8080 (Running
  Edge), and the pod annotations `prometheus.io/scrape`, `prometheus.io/path` and `prometheus.io/port` for `/metrics`
  on port 8080 (Monitoring);
- with `lease.enabled`, a ServiceAccount the pods run as, a Role allowing `get`, `create` and `update` on `leases` in
  `coordination.k8s.io`, and a RoleBinding of that Role to that ServiceAccount (Several replicas).

It creates no Secret and takes no password. Create the Secret holding your client entry's secret first, in the
namespace you install into, under the key `password` (or the key you set in `rabbitMq.passwordSecret.key`). From a file
that holds only the secret, with no line break at its end:

```bash
kubectl create secret generic feedhub-edge-broker --from-file=password=./broker-secret
```

Then write a values file with the values handed over (Connecting to FeedHub), and install the chart of the Edge version
you chose:

```yaml
feedHub:
  instance: <instance>
  bindings:
    - <binding key>
rabbitMq:
  host: <broker host name>
  port: <AMQPS port>
  username: <username>
  passwordSecret:
    name: feedhub-edge-broker
```

```bash
helm install feedhub-edge https://releases.betfeedpro.com/<version>/feedhub-edge-<version>.tgz -f values.yaml
```

| Value | Default | What it sets |
| --- | --- | --- |
| `image.registry` | `registry.betfeedpro.com` | the registry the image is pulled from |
| `image.repository` | `feedhub-edge` | the image name |
| `image.tag` | the chart's `appVersion`, the Edge version it runs | the Edge version, or `<tag>@sha256:<digest>` to pin its digest (Getting the image) |
| `replicas` | `1` | the number of replica indexes, each its own Deployment: a whole number from 1 to 16, never above the number FeedHub operations set for your client entry |
| `feedHub.instance` | none, required | `FeedHub:Instance` |
| `feedHub.bindings` | none, required | `FeedHub:Bindings`, a list of every binding key handed over |
| `rabbitMq.host` | none, required | `RabbitMq:Host` |
| `rabbitMq.port` | `5671` | `RabbitMq:Port` |
| `rabbitMq.tls` | `true` | `RabbitMq:Tls` |
| `rabbitMq.username` | none, required | `RabbitMq:Username` |
| `rabbitMq.passwordSecret.name` | none, required | the existing Secret `RabbitMq:Password` is read from |
| `rabbitMq.passwordSecret.key` | `password` | the key of that Secret holding the secret |
| `observability.otlpEndpoint` | empty | `Observability:OtlpEndpoint` (Monitoring) |
| `lease.enabled` | `false` | `Lease:Enabled`, with the ServiceAccount, Role and RoleBinding above; `false` creates none of them |
| `extraEnv` | empty | any other `FEEDHUB_EDGE_` variable (Optional keys): a list of Kubernetes `EnvVar` objects added to the container's `env` as they are, so an entry may read a Secret with `valueFrom` and `secretKeyRef` |
| `resources` | empty | the container's CPU and memory requests and limits; none unless you set them (Sizing) |

Rendering fails, naming the value, when a required value is empty, `feedHub.bindings` has no key, or `replicas` isn't a
whole number from 1 to 16.

- Install one release of the chart per client entry. Two releases for one entry run each replica index twice, which
  splits its feed between them (Several replicas), and nothing reports it.
- The chart can't know the number of replicas FeedHub operations set. A replica above it is refused (Runbook, "A
  replica started with an index your client entry doesn't have"). Lowering `replicas` with `helm upgrade` deletes the
  Deployments above the new number, the first step of running fewer replicas (Several replicas).
- The pods' restart policy is `Always`, the only one a Deployment allows, so an Edge that exits `1`, on refused
  credentials or a disabled Edge version, shows as a crash loop (Runbook).
- Changing the Secret doesn't restart the pods: Edge's open connections stay. Restart them at your own pace, with
  `kubectl rollout restart deployment -l app.kubernetes.io/instance=<release>`.
- To upgrade Edge, `helm upgrade` the release with the chart of the new version and the same values file: the image tag
  follows the chart's version unless `image.tag` is set.

### Several replicas

Edge runs as one replica unless you run more. Several replicas keep your applications served when one of them stops:

- Pull mode, which is everything this guide describes (`Subscribe`, local REST, `PlaceBet`, `GetBets`, bet results),
  runs on any number of replicas up to the number FeedHub operations set for your client entry. Each replica loads,
  holds and streams its own state and computes its own status; nothing connects the replicas, so each one needs the
  CPU and memory of a single Edge (Sizing).
- Give each replica its own index in `FeedHub:Replica`, from `1` to that number, and run each index in exactly one
  process at a time. Under Kubernetes that is one Deployment per index, each with one replica and `strategy: Recreate`,
  and one Service that selects the pods of all of them; the chart creates exactly that from `replicas` (Helm). Under
  compose, run one service per index. Two processes started with one index split your client entry's feed between them, each repairing the rest, and nothing reports it.
- Probe readiness on `/local/v1/ready` (Running Edge). A replica that restarts then takes no application before it has
  loaded its state.
- When a replica stops, the streams of the applications connected to it end. An application subscribes again, reaches
  another replica through the Service and gets a fresh snapshot there: a resume token from one replica isn't known to
  another, so it is answered with a snapshot. The other replicas' streams go on with no gap.
- Run one reader of bet results per client entry, and send each `ConfirmBetResult` over the same gRPC channel as its
  `ReadBetResults` stream: a confirmation that reaches another replica answers `NOT_FOUND`, and the result comes again
  once its stream ends.
- FeedHub caps the broker connections of your client entry: each replica holds one, and one more while a bet results
  stream is open. A replica refused at the cap keeps retrying and connects once a slot frees (Runbook).
- To run fewer replicas, stop the highest indexes first and then ask FeedHub operations to lower the number: what a
  replica above the new number receives is removed from FeedHub, with what is still waiting for it.

A push adapter that publishes Edge's data into a system of yours (such as a Kafka topic) on several replicas needs a
leader, so that only one replica publishes at a time. Edge elects it through a Kubernetes `Lease` in its pod's namespace
when `Lease:Enabled` is `true`. Without it (the default) every Edge process publishes, so without Kubernetes run a
push adapter on one replica only. The Lease guarantees one leader at a time but no fence: a replica that stalls in the
middle of a publish can still complete it after another has taken over, so the target system sees at most one
duplicate per takeover.

| Key | Default | What it sets |
| --- | --- | --- |
| `Lease:Enabled` | `false` | `true`: Edge takes part in the election through the Kubernetes API, as its pod's service account. Edge then has to run in a Kubernetes pod with the service account's token mounted |
| `Lease:Name` | your client entry's username followed by `-feedhub-edge` | the name of the `Lease` object, the same on every replica of one Edge: a Kubernetes object name (lowercase letters, digits, `-` and `.`, at most 253 characters) |
| `Lease:Duration` | `00:00:15` | how long the leader's last renewal stays valid for the others: a replica takes the `Lease` once it has seen it unchanged that long. A whole number of seconds |
| `Lease:RenewDeadline` | `00:00:10` | how long the leader may go without renewing before it steps down, below `Lease:Duration` |
| `Lease:RetryPeriod` | `00:00:02` | how often the leader renews and the other replicas try, below `Lease:RenewDeadline` |

A stopping leader gives the `Lease` up, and another replica takes over within `Lease:RetryPeriod`; after a crash it
takes over within `Lease:Duration` plus `Lease:RetryPeriod`. A failed call to the Kubernetes API never stops Edge or
pull mode: Edge logs it at `Warning` and stays a follower, and a leader that can't renew steps down by
`Lease:RenewDeadline`. Edge logs taking leadership at `Information` and losing it at `Warning` with the reason;
`feedhub_edge_lease_held` is `1` on the leader and `feedhub_edge_lease_failures_total` counts the failed calls.

Grant Edge's service account the right to the `Lease` in its namespace: a `Role` whose one rule allows the verbs
`get`, `create` and `update` on the resource `leases` of the API group `coordination.k8s.io`, and a `RoleBinding` of
that `Role` to the service account Edge's pods run as. `get` and `update` can be narrowed to the one `Lease` with
`resourceNames`; `create` can't. The chart's `lease.enabled` sets `Lease:Enabled` and creates both (Helm).

### Getting the image

FeedHub publishes each Edge release as `registry.betfeedpro.com/feedhub-edge`, and its release notes and signing keys
on the release page `https://releases.betfeedpro.com`: the notes of version `X.Y.Z` at
`https://releases.betfeedpro.com/X.Y.Z.md`, the public keys under `https://releases.betfeedpro.com/keys/`. Anyone pulls the image without credentials,
by tag or by digest, and reads the release page without access to FeedHub's repositories. The image holds no secret
and no FeedHub address, and nothing in it is hidden: every host, user and password comes from your environment
(Configuration), and your client entry's broker credentials are what gives access to FeedHub.

- **Tags.** A tag is an Edge version, `MAJOR.MINOR.PATCH` such as `1.4.0`, the same string Edge's status reports as
  `edge_version`. A published tag never moves to another image: a rebuild is a new version. Choose the tag from the
  release notes, among the supported Edge versions (Supported Edge versions). A tag whose release notes aren't
  published yet isn't released to clients, and running it is at your own risk.
- **Pinning a digest.** To run exactly the image you verified, set `EDGE_IMAGE_TAG` in `.env`, or the chart's
  `image.tag` (Helm), to the tag and the digest from the release notes, `1.4.0@sha256:<digest>`. The pull then takes
  the digest and ignores the tag.
- **Verifying the signature.** Every published image is signed over its digest with cosign and a key pair. Download
  the public key the release notes name from the release page, check that its SHA-256 fingerprint is the one the
  release notes give, then verify the image with cosign 3.x (cosign 2.x doesn't find the signature, which is stored
  as an OCI 1.1 referrer):

  ```bash
  sha256sum feedhub-edge-<key>.pub      # must print the fingerprint in the release notes
  cosign verify --key feedhub-edge-<key>.pub --insecure-ignore-tlog=true registry.betfeedpro.com/feedhub-edge@sha256:<digest>
  ```

  The command fails for an image FeedHub didn't sign and for an image whose digest differs from the signed one.
  FeedHub writes its signatures to no public transparency log, hence `--insecure-ignore-tlog=true`, for which cosign
  prints a warning.
- **Signing keys.** Every public key FeedHub has signed with stays on the release page, and each release's notes name
  the key that signed it, so an older release verifies with its own key and isn't signed again. A key that leaked is
  withdrawn from the page instead: FeedHub re-releases every supported Edge version as a new patch signed with the new
  key and deprecates the patches the leaked key signed (Supported Edge versions).
- **SBOM.** Every published image has an SPDX-JSON SBOM of its digest, attached to it in the registry as a cosign
  attestation signed with the same key. Verify and read it without credentials:

  ```bash
  cosign verify-attestation --key feedhub-edge-<key>.pub --type spdxjson --insecure-ignore-tlog=true \
    registry.betfeedpro.com/feedhub-edge@sha256:<digest> | jq -r '.payload' | base64 -d | jq '.predicate'
  ```

- **Release notes.** Each release's notes name its tag and digest, what changed for a client, the key that signed it
  (its file and fingerprint), the local API versions it serves (Versioning), anything FeedHub must have in place
  first, and the Edge versions the release makes deprecated or disabled.
- **Client package.** Each release publishes, next to its notes, a folder `https://releases.betfeedpro.com/X.Y.Z/` that
  anyone reads without credentials. It holds everything a client takes from FeedHub besides the image: this guide,
  the compose example `docker-compose.example.yml`, the env file template `edge.env.example`, the proto file
  `feed_edge.proto`, the REST contract `openapi.json` and the Helm chart `feedhub-edge-X.Y.Z.tgz`.
  Each published folder stays fixed. Corrections go in a later release. The registry holds images, their signatures
  and their SBOMs.

### Network access

Edge only connects out; FeedHub never connects in to Edge. It needs to reach only the broker at `RabbitMq:Host` on
`RabbitMq:Port`. From outside FeedHub's cluster the broker answers only over TLS (AMQPS), at the public host name and
port FeedHub operations hand over, so set `RabbitMq:Tls` to `true` (Configuration). The broker presents a certificate
for that host name from a public certificate authority, and asks for no client certificate: your client entry's
username and password are Edge's only credential.

With `RabbitMq:Tls` `true`, Edge validates the broker's certificate chain against the system trust store and its host
name against `RabbitMq:Host`, refuses an invalid certificate and never falls back to a connection without TLS. The TLS
version is the operating system's default; the broker accepts TLS 1.2 and 1.3.

### Sizing

Edge is one process, and it has to take in every change FeedHub publishes for your client entry as fast as FeedHub
publishes it. A rate above what one Edge process consumes means a growing backlog: changes reach Edge later and later
(`feedhub_edge_message_age_seconds` rises, and the status turns `degraded` with `QUEUE_LAG`), and once the backlog
reaches its limit the oldest changes are lost. Size Edge's CPU and its network path to FeedHub for the highest rate you
expect, and watch that series under load. On 27.10.2026 FeedHub's development instance published about 220–330 messages
per second to one client receiving every sport; production rates are higher. On 09.11.2026 FeedHub's sample client, one
process with the same client rules and 16 concurrent messages, drained a backlog of 100000 messages in under 45 seconds.
That is not a measurement of Edge, and the highest rate one Edge process can sustain hasn't been measured. What has been
measured is a rate Edge did sustain: from 12.11.2026 to 16.11.2026 one Edge bound to every sport of an instance that
polls the production line took 880 messages per second over its busiest 20 minutes on 1.2 CPU cores, and up to 562 per
second averaged over six hours on 0.8 of a core, while `feedhub_edge_message_age_seconds` averaged 0.02 to 0.06 s.

Edge keeps everything it serves in memory. In that run, 84 hours through a weekend without a restart, with 35 sports
bound and one application subscribed, Edge held 2,400 to 4,200 events and 219,000 to 345,000 markets. The data itself
took 1.1 to 1.5 GiB, about 5 KiB per market held. The process uses more than its data, and how much is set by the
container's memory limit: .NET lets the heap grow up to 75% of the limit and compacts it only there. With a limit of
4 GiB the heap climbed to about 3 GiB every 17 to 24 hours and fell back to about 1.3 GiB, the working set averaged
2.6 GiB and peaked at 3.2 GiB, and Edge stayed `ready` with no restart. So choose the limit, not the request, by the
data: 75% of the limit should be at least twice the data you expect at your busiest hour. Set the request near what
the process will really use, about three quarters of the limit: Edge spent 92% of that run above half its limit. For
every sport of that instance this gives a limit of 4 GiB and a request of 3 GiB. A run of one afternoon and evening
with one sport bound (Football, about 105,000 markets) stayed near 1 GiB, but it was too short to reach the heap's
ceiling. Edge loads its state in 23 s at the size of the long run and is `ready` 50 s after its process starts.

The backlog has two limits, a length and an age: 1,000,000 messages and 5 minutes on FeedHub's development instance.
Past either, the oldest changes are lost. Edge itself recovers with no restart and no reload: it was `ready` again 58 s after a 124 s
cut with an overflow, and 84 s after a 497 s cut longer than the age limit. What the lost changes carried stays wrong until
Edge repairs it: prematch events whose poll fell into them keep serving markets FeedHub has withdrawn and old market
versions, and new events are missing. Edge repairs them on its own within 3 minutes of its broker connection returning
(the backlog drains, the next list of active events follows within a minute, and the repair requests are spread over up
to 5 seconds). On 09.11.2026, on FeedHub's development instance with one sport bound, each of those two cuts left 20
prematch events stale, with 16 and 33 withdrawn markets still served, about 300 and 480 old markets and 2 new events
missing. Two cases take longer: an event whose newest poll survived in the backlog while an earlier one was lost heals
at its next poll (5 or 10 minutes for events starting within a day, up to 60 minutes for later ones, and those only
after a cut of more than an hour), and a new event whose first poll failed can take about a minute longer. The status
is `degraded` during the repair, and only such a new event can still be missing once it turns `ready`. You need to do
nothing.

## Configuration

Edge reads `appsettings.json` from the image, then environment variables prefixed `FEEDHUB_EDGE_`, with `__` for each
`:` of a key (`FEEDHUB_EDGE_RabbitMq__Password` sets `RabbitMq:Password`). Unprefixed variables, and those prefixed
`FEEDHUB_` without `EDGE_`, aren't read, so a key given that way counts as missing.

### Keys you must give

These keys have no default. Their values are what FeedHub operations hand over with your client entry; take them as
handed over:

| Variable | What it holds |
| --- | --- |
| `FEEDHUB_EDGE_FeedHub__Instance` | the FeedHub instance Edge is a client of |
| `FEEDHUB_EDGE_FeedHub__Bindings__0` | a binding key of your client entry; further keys as `FEEDHUB_EDGE_FeedHub__Bindings__1`, `__2` and so on |
| `FEEDHUB_EDGE_RabbitMq__Host` | the host name of that instance's broker: its public host name for an Edge outside FeedHub's cluster |
| `FEEDHUB_EDGE_RabbitMq__Username` | the username of your client entry |
| `FEEDHUB_EDGE_RabbitMq__Password` | the password of your client entry; for a client FeedHub onboarded through its control plane, the secret issued to you. A new secret replaces the old one on the broker within a minute: open connections stay, so set it and restart Edge at your own pace |

An Edge outside FeedHub's cluster also sets `FEEDHUB_EDGE_RabbitMq__Port` to the AMQPS port FeedHub operations hand
over and `FEEDHUB_EDGE_RabbitMq__Tls` to `true`; the env file template holds both lines. Moving an Edge onto the
public address changes only `RabbitMq:Host`, `RabbitMq:Port` and `RabbitMq:Tls`: its username, password and queues
stay as they are. Otherwise `RabbitMq:Port` (default 5672) and `RabbitMq:VirtualHost` (default `/`) need setting only
when FeedHub operations hand over other values. The broker host is Edge's only network path to FeedHub: Edge needs no
HTTP or HTTPS egress to FeedHub. List exactly the binding keys you were given: they decide which sports, and for each
sport live or prematch, Edge receives and so can serve. Secrets go into `.env` or your orchestrator's secret store,
never into an image or a repository.

### Optional keys

| Key | Default | What it sets |
| --- | --- | --- |
| `RabbitMq:Tls` | `false` | `true` connects both of Edge's broker connections over TLS, which an Edge outside FeedHub's cluster needs (Network access); `false` connects without TLS. A boolean, `true` or `false` |
| `FeedHub:Replica` | `1` | the index of this replica, a whole number from 1 to 16 and at most the number of replicas FeedHub operations set for your client entry (Several replicas) |
| `Ports:Http` | `8080` | the container port of the HTTP/1.1 endpoint (`/healthz`, `/metrics`, `/local/v1`), a whole number from 0 to 65535 |
| `Ports:Grpc` | `8081` | the container port of the gRPC endpoint, a whole number from 0 to 65535 |
| `Grpc:KeepAlivePingDelay` | `00:00:30` | how long a connection on the gRPC port may send Edge nothing before Edge pings it, a duration of at least 1 second (Keepalive) |
| `Grpc:KeepAlivePingTimeout` | `00:00:20` | how long Edge then waits for anything from that connection before closing it, a duration of at least 1 second (Keepalive) |
| `Refresh:FreshAge` | `00:00:02` | the age under which the pre-bet refresh answers an event from Edge's state (Local REST) |
| `Refresh:UpstreamTimeout` | `00:00:08` | the longest the pre-bet refresh waits for FeedHub before it answers `Unknown` |
| `Betting:RequestTimeToLive` | `00:00:03` | how long a `PlaceBet` or `GetBets` request waits for FeedHub to take it; a `PlaceBet` request not taken by then is never placed. A positive duration |
| `Betting:RequestTimeout` | `00:00:15` | how long `PlaceBet` waits for FeedHub's answer before it answers `DEADLINE_EXCEEDED`. A positive duration above `Betting:RequestTimeToLive` |
| `Betting:QueryTimeout` | `00:00:05` | how long `GetBets` waits for FeedHub's answer before it answers `DEADLINE_EXCEEDED`. A positive duration |
| `Betting:ResultPrefetch` | `50` | how many results one `ReadBetResults` stream holds unconfirmed at most; the next result comes once one of them is confirmed. A whole number from 1 to 65535 |
| `Heartbeat:Interval` | `00:00:30` | how often Edge reports itself to FeedHub (its version, status, lag, state size and subscribers) and gets FeedHub's verdict on its version (Runbook). A positive duration |
| `Heartbeat:Timeout` | `00:00:05` | how long Edge waits for FeedHub's verdict on one report before it counts it unanswered. A positive duration below `Heartbeat:Interval` |
| `Bootstrap:RetryDelay` | `00:00:10` | the pause between a failed attempt to load the initial state from FeedHub and the next attempt, a positive duration (Runbook) |
| `Resume:Window` | `00:05:00` | how long Edge keeps what it withdrew or finished for applications that reconnect. It counts from the last message your application received. A subscriber on a quiet filter can get a fresh snapshot after any drop, because the purge that ends a token covers every sport |
| `Serilog` | console, `Information` | log levels and the console sink, as Serilog's configuration reads them (`FEEDHUB_EDGE_Serilog__MinimumLevel__Default=Debug`) |
| `Observability:OtlpEndpoint` | unset | the OTLP gRPC endpoint Edge sends metrics, traces and logs to, an absolute `http` or `https` URL; unset or empty means no OTLP export (Monitoring) |
| `Lease:*` | `Lease:Enabled` `false` | the leader election of push adapters on several replicas (Several replicas) |

Leave `Client:*`, `References:*`, `Catalog:*`, `Resync:*`, `Liveness:*`, `Heartbeat:*` and `Betting:*` at their defaults unless FeedHub operations
ask otherwise: the `Betting` keys fit the time FeedHub takes to place a bet and to answer for its state. Give each
`PlaceBet` call a deadline of your own above `Betting:RequestTimeout`, and each `GetBets` call one above
`Betting:QueryTimeout`, so that Edge's answer reaches your application before its deadline passes.

### Invalid settings

Edge checks its settings at start. When any key is missing or invalid, Edge doesn't start: it never answers `/healthz`,
logs one critical entry `FeedHub.Edge did not start, invalid settings:` with one line per failing key, naming the key
and its reason and never its value, and exits with code `1`. A copy of the template with keys left empty fails this
way, naming every empty key.

### Exit codes

| Code | When |
| --- | --- |
| `0` | Edge stopped because it was told to: a `SIGTERM` or `SIGINT`, such as a container stop or a deploy |
| `1` | Edge stopped because it failed: invalid settings, or a failure at start that Edge doesn't retry (a request FeedHub refuses during the initial load, which waiting can't fix, Edge's credentials refused, the snapshot queue not connecting, the bus failing to start), or FeedHub having disabled this Edge version, at start or while running (Runbook) |

The log entry before the exit says which failure it was. An orchestrator that restarts only a failed container, such as
compose with `restart: on-failure`, restarts Edge on `1` and leaves it stopped on `0`. Any other non-zero code is a
crash of the process and counts as a failure too.

## The local API over gRPC

Edge serves the service `FeedEdge` of the proto package `feedhub.edge.v1`, published as one proto file,
`feed_edge.proto`, in the client package (Getting the image). Generate a client from it in your language, or take the .NET package (The .NET package).

Connect over HTTP/2 without TLS (cleartext, "prior knowledge"), to host port 8090 with the compose example or
container port 8081 (`Ports:Grpc`) from inside the network: `http://<edge-host>:8090`. TLS, if you need it between
your application and Edge, is your proxy's or service mesh's.

### `Subscribe`

`rpc Subscribe(SubscribeRequest) returns (stream FeedEvent)` sends the current state your filter selects, then its
changes, for as long as the call lasts:

- the first message is `StatusChanged` with Edge's current status;
- then `SnapshotBegin`; then, for every event that matches the filter and that Edge holds as not withdrawn (finished
  events Edge still holds included, with `is_finished`), its `EventChanged` followed by one `MarketChanged` per market
  snapshot of the event that still has a market; then `SnapshotEnd`. A market snapshot is the set of an event's markets
  that share one `snapshot_key`, and one `MarketChanged` carries one;
- then changes, until the call ends. Edge ends a stream when it shuts down, when your application has stopped reading
  for longer than `Resume:Window` and a withdrawal still waiting to be sent on that stream ages out of Edge's state, or
  when its connection stops answering Edge's keepalive (Keepalive). A new filter takes a new `Subscribe` call;
- with a `resume_token` Edge can resume, it skips the snapshot and continues with the changes since the token.

`SubscribeRequest`:

| Field | What it holds |
| --- | --- |
| `sport_ids` | sport ids, UUIDs as strings; repeats collapse |
| `tournament_ids` | tournament ids, UUIDs as strings; repeats collapse. A well-formed id of a tournament Edge doesn't know yet is accepted |
| `phase` | `PHASE_ANY` (the default), `PHASE_LIVE` or `PHASE_PREMATCH` |
| `resume_token` | the latest `resume_token` you received, or empty |

### The filter

An event matches by its live state and by the sport and tournament of its latest content:

- `phase`: `PHASE_LIVE` matches live events only, `PHASE_PREMATCH` prematch events only, `PHASE_ANY` both;
- no `sport_ids` and no `tournament_ids`: every event Edge receives;
- a sport in `sport_ids` matches every event of that sport, including tournaments that appear after the subscription
  started;
- `tournament_ids` matches only the tournaments listed. A tournament that appears later never joins the subscription;
  to get new tournaments, subscribe by sport;
- with both, an event matches when it is in a listed sport or a listed tournament. `phase` applies on top;
- an event whose sport or tournament changes so that it leaves your filter gets `EventUnsubscribed`; one that enters it
  is sent as new, with its `EventChanged` and its `MarketChanged`s.

### `GetStatus`

`rpc GetStatus(GetStatusRequest) returns (EdgeStatus)`, with an empty `GetStatusRequest`, answers Edge's current
status. It answers also while Edge is loading its initial state, when `Subscribe` answers `UNAVAILABLE`, and never
fails on Edge's state.

### Messages

Each `FeedEvent` carries one member of its `oneof body`, plus `resume_token`:

| `body` member | Message | What it carries |
| --- | --- | --- |
| `status` | `StatusChanged` | `status`: an `EdgeStatus` with `state` (`Status`), `reason` (`DegradedReason`), `since`, `edge_version`, `wire_versions`, `last_fetched_at`, optional `lag_seconds` |
| `snapshot_begin` | `SnapshotBegin` | nothing; the snapshot starts |
| `snapshot_end` | `SnapshotEnd` | nothing; the snapshot is complete |
| `event` | `EventChanged` | `event_id`, `fetched_at`, `is_live`, `is_finished`, `content` (`EventContent`), `manifest` (repeated `ManifestEntry { market_id, content_hash }`, informational) |
| `market` | `MarketChanged` | `event_id`, `tournament_id`, `snapshot_key`, `group` (`MarketGroup { id, name }`, set only for a sub-game's markets), `markets` (repeated `Market`), `content_hash`, `fetched_at` |
| `market_removed` | `MarketRemoved` | `event_id`, `market_id`, `removed_at` |
| `event_withdrawn` | `EventWithdrawn` | `event_id`, `withdrawn_at` |
| `event_unsubscribed` | `EventUnsubscribed` | `event_id` |

- `EventContent`: `game_start`, `sport_id`, `tournament_id`, `kind` (`EventKind`: `EVENT_KIND_MATCH`,
  `EVENT_KIND_OUTRIGHT`, `EVENT_KIND_UNRECOGNIZED`), and the optional `country_id`, `team_a_id`, `team_b_id`,
  `prematch_event_id`, `score_full`, `score_period`, `score_extra`, `period_name`, `extra_time`, `pitch`, `timer`,
  `name`. `content` is absent when the provider no longer returns the event.
- `Market`: `market_id`, `market_type_id`, optional `name`, `columns`, `rows` (repeated `SelectionRow { selections }`),
  `suspended`, optional `split_number`.
- `Selection`: `selection_id`, optional `name`, `value`, `is_suspended`, optional `column_index`, optional
  `line`, optional `participant_id`, `sort_order`.
- Ids are UUIDs as strings in canonical form. Times are `google.protobuf.Timestamp` in UTC, at microseconds.
  Decimals (`value`, `line`) are strings. An optional field is a proto3 `optional` scalar or an unset message, so
  absent stays distinct from a default. Key an event by `event_id`, a market snapshot by
  (`event_id`, `snapshot_key`), and an individual market by `market_id`.
- `fetched_at` is the version of an event or a market, on FeedHub's clock. Compare it only with other times from
  Edge, never with your own clock.
- `EdgeStatus`, the same in `StatusChanged`, `GetStatus` and `GET /local/v1/status`: `state` (`Status`) and `reason`
  (`DegradedReason`, `DEGRADED_REASON_UNSPECIFIED` while ready), as rule 6 reads them; `since`, when Edge last turned
  ready or degraded (a change of reason alone doesn't move it); `edge_version`, the version of the Edge image;
  `wire_versions`, the versions of FeedHub's feed format this image reads; `last_fetched_at`, the newest `fetched_at`
  Edge has received from FeedHub since it started, unset until the first; `lag_seconds`, how long the latest change
  took to reach Edge, in seconds, unset until the first. `last_fetched_at` and `lag_seconds` are on FeedHub's clock.

Delivery is coalesced per subscriber. Each event, market snapshot, removed market, withdrawn event and the status is a
key that is sent once with its latest state, however often it changed since it was last sent, so a slow application
gets the latest state and never a backlog of versions. Within one send, the status comes first, then events in the
order they first changed, and for each event its `EventChanged`, its `MarketChanged`s, its `MarketRemoved`s, then its
`EventWithdrawn` or `EventUnsubscribed`. You never get a `MarketChanged`, `MarketRemoved`, `EventWithdrawn` or
`EventUnsubscribed` for an event before that event's first `EventChanged` on your stream. A withdrawal followed by a
restore before you read it reaches you as the restore alone. An application that stops reading costs Edge nothing
but its pending keys, and never slows another application.

### Status codes

| Code | When | Retry |
| --- | --- | --- |
| `INVALID_ARGUMENT` | a `sport_ids` or `tournament_ids` entry isn't a UUID, or `phase` isn't a defined value; the detail names the field | no: fix the request |
| `FAILED_PRECONDITION` | `sport_ids` names a sport your client entry doesn't receive for the requested phase (for `PHASE_ANY`, in neither phase); the detail names the sport | no: ask FeedHub operations to add the sport to your client entry, or drop it from the filter |
| `CANCELLED` | your application cancelled the call, or Edge reset a stream your application had stopped reading while a withdrawal still waiting to be sent on it aged out of Edge's state | yes unless your application cancelled the call, after a delay, with the latest `resume_token` |
| `UNAVAILABLE` | Edge hasn't loaded its initial state yet after a start, Edge is shutting down, Edge can't be reached, or a withdrawal still waiting to be sent on this stream aged out of Edge's state | yes, after a delay, with the latest `resume_token` |
| `INTERNAL` | the client's HTTP/2 keepalive gave up on a connection that died, or Edge reset a stream your application had stopped reading while a withdrawal still waiting to be sent on it aged out of Edge's state | yes, after a delay, with the latest `resume_token` |

A call that fails several checks gets the first in this order: `INVALID_ARGUMENT`, `FAILED_PRECONDITION`,
`UNAVAILABLE`.

An application subscribes again, after a delay and with the latest `resume_token` it received, when a `Subscribe`
stream ends with `UNAVAILABLE`, `INTERNAL`, a `CANCELLED` it didn't cause, or no error (a proxy closing it, for
example). Every `INTERNAL` counts, with no attempt limit, as for `UNAVAILABLE`, and every other code keeps the handling above.

A stream Edge ended at a purge can arrive as any of `UNAVAILABLE`, `CANCELLED` or `INTERNAL`, depending on timing, and
the three are handled alike. Branch on the code, never on the detail text, which is not part of the contract.

### Keepalive

A connection can die with neither end being told: a NAT or a firewall on the path stops passing its packets. Without a
keepalive of its own your application doesn't notice: in the measurement, not within 3 minutes. Edge pings its gRPC
connections and closes one that stops answering (`Grpc:KeepAlivePingDelay`, `Grpc:KeepAlivePingTimeout`), but that
protects only Edge and tells your application nothing.

Set both values to 30 s on the channel's handler:

```csharp
var handler = new SocketsHttpHandler
{
    KeepAlivePingDelay = TimeSpan.FromSeconds(30),
    KeepAlivePingTimeout = TimeSpan.FromSeconds(30),
};
using var channel = GrpcChannel.ForAddress("http://localhost:8090", new GrpcChannelOptions { HttpHandler = handler });
```

With those values a dead connection was noticed after 60.7 s to 68.9 s (FeedHub's development instance, four measurements, 09.11.2026).
That is about twice the keepalive only because the two values are equal; in general, expect delay plus timeout plus
several seconds.

When the keepalive gives up, the call fails, with the status `INTERNAL` in the measurement, and your application
subscribes again with its latest `resume_token`. Inside `Resume:Window` the token resumes: after 68 s, the first message
arrived in 0.48 s and 0.86 s, with 442 messages to catch up. A token past the window may resume or get a fresh snapshot,
either being valid; the measured example is a fresh snapshot after 960 s, in 41.3 s. No removal was lost.

### `PlaceBet`

`rpc PlaceBet(PlaceBetRequest) returns (PlaceBetReply)` places one bet on one selection. Edge passes the request on to
FeedHub, waits up to `Betting:RequestTimeout` for FeedHub's answer and returns it. FeedHub places the bet with the
provider before it answers. Edge holds nothing of the bet: it answers nothing from its own state, keeps no answer,
retries nothing and doesn't deduplicate, so a call repeated with the same key is passed on again and FeedHub answers it.

`PlaceBet` needs only Edge's connection to FeedHub. It answers while Edge loads its initial state and while the status
is `degraded`, whatever the reason; whether your application takes bets on a market while the status is degraded is
your application's rule (rule 6 suspends every market then).

| `PlaceBetRequest` field | What it holds |
| --- | --- |
| `client_bet_key` | your key for this bet, 1 to 100 characters; FeedHub places at most one bet per key |
| `market_id` | the market's `market_id`, a UUID |
| `selection_id` | the UUID of the selection within the market |
| `price` | the price you bet at, a decimal above 1 |
| `stake` | the stake, a decimal above 0 |
| `accept_price_changes` | whether the bet may be taken at a moved price |
| `is_live` | whether the event has started |

Write `price` and `stake` as Edge writes decimals: invariant digits, an optional leading `-` and an optional `.`
fraction, with no group separator, exponent or whitespace. Edge checks only that `market_id` is a UUID and that `price`
and `stake` read as decimals in that form; FeedHub checks the rest and answers `PLACE_BET_OUTCOME_REFUSED`.

| `PlaceBetReply` field | What it holds |
| --- | --- |
| `client_bet_key` | the request's key |
| `bet_id` | optional: FeedHub's id of the bet, a UUID; unset with `PLACE_BET_OUTCOME_REFUSED` and `PLACE_BET_OUTCOME_CONFLICT` |
| `outcome` | a `PlaceBetOutcome`, below |
| `current_price` | optional: the provider's price, a decimal; set only with `PLACE_BET_OUTCOME_PRICE_CHANGED` |
| `problem` | optional: the request field FeedHub refused, set only with `PLACE_BET_OUTCOME_REFUSED`, as `ClientBetKey` (`client_bet_key`), `MarketId` (`market_id`), `SelectionId` (`selection_id`), `Price` (`price`) or `Stake` (`stake`); a name not in this list is a field a newer FeedHub checks |

| `PlaceBetOutcome` | Meaning |
| --- | --- |
| `PLACE_BET_OUTCOME_ACCEPTED` | the provider took the bet |
| `PLACE_BET_OUTCOME_PRICE_CHANGED` | the provider refused it on a moved price; `current_price` holds the provider's price |
| `PLACE_BET_OUTCOME_SUSPENDED` | the provider holds the market blocked |
| `PLACE_BET_OUTCOME_UNAVAILABLE` | the provider has no data for it, or FeedHub doesn't hold the market or the selection |
| `PLACE_BET_OUTCOME_FAILED` | anything else: a provider error, a timeout, an unreadable answer, a closed gate |
| `PLACE_BET_OUTCOME_REFUSED` | the request failed FeedHub's checks, `problem` naming the field, or FeedHub couldn't tell who sent it; nothing was placed |
| `PLACE_BET_OUTCOME_CONFLICT` | the key is already recorded with a different selection, price or stake; nothing was placed |
| `PLACE_BET_OUTCOME_UNRECOGNIZED` | an outcome of a newer FeedHub that this Edge doesn't know: read it as `PLACE_BET_OUTCOME_FAILED` |

`PLACE_BET_OUTCOME_UNSPECIFIED` is never written. Read it, or a number your build doesn't define, as
`PLACE_BET_OUTCOME_FAILED` (rule 11).

A key's outcome is final, `PLACE_BET_OUTCOME_FAILED` included: a new attempt takes a new key. A call repeated with the
same key places nothing and returns the outcome recorded under it, or `PLACE_BET_OUTCOME_FAILED` while the first
attempt is still being placed.

#### Status codes of `PlaceBet`

FeedHub's outcomes come only in `PlaceBetReply`, never as a status code. `PlaceBet` fails with a status code only for
these reasons:

| Code | When | What it means for the bet |
| --- | --- | --- |
| `INVALID_ARGUMENT` | `market_id` isn't a UUID, or `price` or `stake` isn't a decimal in the form above or is out of range; the detail names each field | nothing was sent. Not retried with a new key: fix the request |
| `UNAVAILABLE` | Edge's connection to FeedHub is down; or the request could not be sent; or Edge is shutting down; or Edge can't be reached | with the connection to FeedHub down, or Edge not reached, nothing was sent. After a failed send, or Edge shutting down during the wait, the bet may have been placed, its outcome recorded under its key |
| `DEADLINE_EXCEEDED` | no answer from FeedHub within `Betting:RequestTimeout`, or your own deadline passed first | the bet may have been placed, its outcome recorded under its key |
| `CANCELLED` | your application cancelled the call | the bet may have been placed, its outcome recorded under its key |
| `INTERNAL` | FeedHub's answer is in a form this Edge doesn't read, or FeedHub failed while handling the request | the bet may have been placed, its outcome recorded under its key |

A call that fails several checks gets the first in this order: `INVALID_ARGUMENT`, `UNAVAILABLE`. A request FeedHub
hasn't taken within `Betting:RequestTimeToLive` is never placed. A call your application cancels, or whose deadline
passes, ends Edge's wait, but a request already passed on stays valid until its `Betting:RequestTimeToLive` passes. A
call dropped on its way, its connection to Edge lost or Edge restarted during the wait, may also have placed the bet,
its outcome recorded under its key; Edge held nothing of it. Branch on the code, never on the detail text.

### `GetBets`

`rpc GetBets(GetBetsRequest) returns (GetBetsReply)` asks for the state of your client entry's bets, by FeedHub's id or
by your key. Use it to recover a result you confirmed without applying, or never received. Edge passes the request on to
FeedHub, waits up to `Betting:QueryTimeout` for FeedHub's answer and returns it. FeedHub answers from its own record of
your bets and never asks the provider. Edge holds nothing of it: it answers nothing from its own state, keeps no answer
and retries nothing.

`GetBets` needs only Edge's connection to FeedHub. It answers while Edge loads its initial state and while the status
is `degraded`, whatever the reason.

| `GetBetsRequest` field | What it holds |
| --- | --- |
| `bet_ids` | bets asked for by FeedHub's id, each a UUID as `PlaceBetReply` or `SettledBet` gave it; empty if none |
| `client_bet_keys` | bets asked for by your key, each 1 to 100 characters; empty if none |

The two lists together name at least 1 bet and at most 100, repeats counted. Edge checks that count, that each id is a
UUID and that each key is 1 to 100 characters long, counted in UTF-16 code units as .NET counts a string's length, and
nothing else: repeats are kept, and an id or key that isn't yours is passed on, FeedHub answering it
`BET_STATUS_STATE_NOT_FOUND`.

`GetBetsReply` has one field, `bets`: one `BetStatus` per asked id or key, in the order asked, ids first. A repeated id
or key, and an id and a key naming the same bet, each get their own entry. A key matches only the identical string.

| `BetStatus` field | What it holds |
| --- | --- |
| `bet_id` | optional: FeedHub's id of the bet, a UUID, also on a `BET_STATUS_STATE_NOT_PLACED` entry whose outcome is `PLACE_BET_OUTCOME_REFUSED`, though that `PlaceBetReply` had none; unset only on a `BET_STATUS_STATE_NOT_FOUND` entry asked for by key |
| `client_bet_key` | optional: the bet's key; unset on a `BET_STATUS_STATE_NOT_FOUND` entry asked for by id |
| `state` | a `BetStatusState`, below |
| `outcome` | optional: a `PlaceBetOutcome` (`PlaceBet`), set only with `BET_STATUS_STATE_NOT_PLACED` |
| `current_price` | optional: the provider's price, a decimal; set only with `BET_STATUS_STATE_NOT_PLACED`, when the outcome has one |
| `result` | optional: a `SettlementResult`, below; set only with `BET_STATUS_STATE_SETTLED` |
| `settled_at` | when FeedHub recorded the result, UTC; set only with `BET_STATUS_STATE_SETTLED` |

| `BetStatusState` | Meaning |
| --- | --- |
| `BET_STATUS_STATE_NOT_FOUND` | you have no such bet; another client's bet reads the same |
| `BET_STATUS_STATE_PLACING` | the key is recorded and has no outcome yet |
| `BET_STATUS_STATE_NOT_PLACED` | an outcome other than `PLACE_BET_OUTCOME_ACCEPTED`, given in `outcome` |
| `BET_STATUS_STATE_OPEN` | accepted, no result, and FeedHub still checks it for a result |
| `BET_STATUS_STATE_SETTLED` | it has a result, whether or not that result was delivered or confirmed |
| `BET_STATUS_STATE_EXPIRED` | accepted, no result, and FeedHub has stopped checking it for a result |
| `BET_STATUS_STATE_UNRECOGNIZED` | a state of a newer FeedHub that this Edge doesn't know |

`BET_STATUS_STATE_UNSPECIFIED` is never written. A state that reads as it, as `BET_STATUS_STATE_UNRECOGNIZED` or as a
number your build doesn't define changes nothing on your side: ask again later (rule 11).

`result` takes the values of `SettlementResult` (`ReadBetResults` and `ConfirmBetResult`): `SETTLEMENT_RESULT_WIN`,
`SETTLEMENT_RESULT_LOSS`, `SETTLEMENT_RESULT_VOID`, `SETTLEMENT_RESULT_HALF_WIN`, `SETTLEMENT_RESULT_HALF_LOSS` and
`SETTLEMENT_RESULT_UNRECOGNIZED`, with the meanings given there. A result that reads as `SETTLEMENT_RESULT_UNSPECIFIED`,
as `SETTLEMENT_RESULT_UNRECOGNIZED` or as a number your build doesn't define is one your application leaves for manual
settlement.

#### Status codes of `GetBets`

A query changes nothing, so no status code means a bet may have changed, and any failed call can be repeated:

| Code | When | Retry |
| --- | --- | --- |
| `INVALID_ARGUMENT` | the lists together name no bet or more than 100, an id isn't a UUID, or a key is empty or longer than 100 characters; the detail names each field | no: fix the request. Nothing was sent |
| `UNAVAILABLE` | Edge's connection to FeedHub is down; or the request could not be sent; or Edge is shutting down; or Edge can't be reached | yes: ask again after a delay |
| `DEADLINE_EXCEEDED` | no answer from FeedHub within `Betting:QueryTimeout`, or your own deadline passed first | yes: ask again after a delay |
| `CANCELLED` | your application cancelled the call | as your application decides |
| `INTERNAL` | FeedHub's answer is in a form this Edge doesn't read, or FeedHub failed while handling the request | yes: ask again after a delay |

A call that fails several checks gets the first in this order: `INVALID_ARGUMENT`, `UNAVAILABLE`. A call your
application cancels, or whose deadline passes, ends Edge's wait; a request already passed on stays valid until its
`Betting:RequestTimeToLive` passes, and its late answer is dropped. Branch on the code, never on the detail text.

### `ReadBetResults` and `ConfirmBetResult`

`rpc ReadBetResults(ReadBetResultsRequest) returns (stream BetResultDelivery)` streams the results of your client
entry's bets as FeedHub settles them. `rpc ConfirmBetResult(ConfirmBetResultRequest) returns (ConfirmBetResultReply)`
confirms one of them. Edge holds a result only while the stream that carries it is open and the result unconfirmed: a
result you confirm is gone for good, and one you don't confirm before its stream ends comes again on a later stream,
also after an Edge restart. Edge keeps nothing of a result once it is confirmed.

`ReadBetResultsRequest` and `ConfirmBetResultReply` have no fields. Run one reader of results per client entry: each
result goes to one open stream, so two readers split the results between them, and each confirms only the results its
own stream received.

| `BetResultDelivery` field | What it holds |
| --- | --- |
| `delivery_id` | the id to confirm this delivery with, an opaque string, valid only while its stream is open; a result that comes again has a new one |
| `result` | a `SettledBet`, below |

| `SettledBet` field | What it holds |
| --- | --- |
| `bet_id` | FeedHub's id of the bet, a UUID, as `PlaceBetReply` gave it |
| `client_bet_key` | the bet's `client_bet_key` |
| `result` | a `SettlementResult`, below |
| `settled_at` | when FeedHub recorded the result, UTC |

| `SettlementResult` | Meaning |
| --- | --- |
| `SETTLEMENT_RESULT_WIN` | the bet won |
| `SETTLEMENT_RESULT_LOSS` | the bet lost |
| `SETTLEMENT_RESULT_VOID` | the bet is void: the stake is returned |
| `SETTLEMENT_RESULT_HALF_WIN` | half the stake won, the other half is returned |
| `SETTLEMENT_RESULT_HALF_LOSS` | half the stake lost, the other half is returned |
| `SETTLEMENT_RESULT_UNRECOGNIZED` | a result of a newer FeedHub that this Edge doesn't know |

`SETTLEMENT_RESULT_UNSPECIFIED` is never written. Read it, or a number your build doesn't define, as
`SETTLEMENT_RESULT_UNRECOGNIZED` (rule 11). Confirm an unrecognized result like any other and leave the bet for manual
settlement.

`ConfirmBetResultRequest` has one field, `delivery_id`, the id of the delivery to confirm.

Delivery is at least once: a result can come again after a lost confirmation, an Edge restart or a stream that ended
with it unconfirmed. Key each result by `bet_id` and apply one you have already applied as nothing. Confirm a result
only after your application has applied it durably, its write committed: a result confirmed and then lost on your side
doesn't come again.

`ReadBetResults` and `ConfirmBetResult` need only Edge's connection to FeedHub. Both answer while Edge loads its initial
state and while the status is `degraded`, whatever the reason.

#### Status codes of `ReadBetResults` and `ConfirmBetResult`

A `ReadBetResults` stream sends its response headers once it is reading, before the first result, and then runs until
one of these ends it. Every result it delivered and you haven't confirmed comes again:

| Code | When | Retry |
| --- | --- | --- |
| `UNAVAILABLE` | Edge's connection to FeedHub is down or can't be opened for results; the connection dropped while the stream was open (a FeedHub broker restart, for example); FeedHub refused the stream because your client entry receives no results; a result was held unconfirmed longer than FeedHub allows; Edge is shutting down; or Edge can't be reached | yes: read again after a delay |
| `CANCELLED` | your application cancelled the call | as your application decides |
| `DEADLINE_EXCEEDED` | your own deadline on the call passed | give the stream no deadline, or read again |
| `INTERNAL` | the client's HTTP/2 keepalive gave up on a connection that died | yes: read again after a delay |

FeedHub allows a result to stay unconfirmed for 30 minutes by default. A stream holding one longer ends `UNAVAILABLE`,
and its unconfirmed results come again on the next stream, so confirm each result as soon as it is applied.

`ConfirmBetResult` answers with an empty reply once the delivery is confirmed, and fails with `NOT_FOUND` when Edge
holds no unconfirmed delivery under the id: its stream has ended, it was already confirmed, it came from an Edge
process that has since restarted, or it isn't an id Edge gave. Nothing is confirmed then, and the result comes again on
a later stream, where you apply it as nothing and confirm it. With one replica, any of your connections may confirm a
delivery; it needn't be the one that reads the stream. With several, confirm over the stream's own gRPC channel
(Several replicas). Branch on the code, never on the detail text.

## Local REST

The HTTP/1.1 port (host port 8089 with the Compose example) serves the Edge REST API under `/local/v1`.
Open Swagger UI at [`http://localhost:8089/swagger`](http://localhost:8089/swagger) or download the live
[OpenAPI document](http://localhost:8089/swagger/v1/swagger.json) from `/swagger/v1/swagger.json`.
Both are enabled by default and share the local REST API's access controls. For offline use or a static site build,
download `https://releases.betfeedpro.com/X.Y.Z/openapi.json` for the matching Edge release. Consult the release's
client kit for asset availability.

Successful responses use `application/json` with `camelCase` members, named enums, decimals encoded as strings
and ISO 8601 UTC timestamps with `Z`. The readiness probe's success body uses `text/plain`. Errors use RFC 9457
problem details (`application/problem+json`). Use `code` for machine handling when present. An unsupported refresh
content type produces a `415` problem without an Edge code.

| Route | Answer |
| --- | --- |
| `GET /local/v1/{sports\|countries\|tournaments\|teams\|market-types}/{id}` | the record; `404` `not-found` for an id FeedHub doesn't hold either; `503` `feedhub-unavailable` when Edge doesn't hold the id and couldn't read it from FeedHub |
| `GET /local/v1/{sports\|countries\|tournaments\|teams\|market-types}?updatedSince=&cursor=&limit=` | a page `{ items, nextCursor }` of records |
| `GET /local/v1/events?sportId=&isLive=&cursor=&limit=` | a page `{ items: [{ event }], nextCursor }` of the events a snapshot would serve, finished events left out |
| `GET /local/v1/events/{id}/markets` | `{ items: [{ market, suspended }] }`, one item per market snapshot of the event that has a market; `404` `not-found` if the event is absent or hidden by publication policy; `503` `feedhub-unavailable` if Edge holds an otherwise servable event and FeedHub cannot confirm managed publication membership |
| `POST /local/v1/refresh` | the current state of up to 100 markets, one entry per event (Pre-bet refresh) |
| `GET /local/v1/status` | Edge's current status, `200` also while Edge is loading its initial state |
| `GET /local/v1/ready` | `503` `edge-not-ready` with a problem JSON body until Edge has loaded its initial state, then `200` `text/plain` with the body `Healthy`, including while degraded. Use this route as the readiness probe. |

Every reference record has `id`, `name` and `updatedAt`. A sport also has a FeedHub `key` such as `football`. A
country’s `key` is its ISO 3166-1 alpha-2 code where assigned or a FeedHub key for a region without one. A tournament
also has `sportId` and `countryId`
(`null` for none), a team `iconUrl` (an absolute image URL, or `null`), a market type `key` (its short name) and
`sportNames` (`[{ sportId, name }]`).

An event item's `event` has `eventId`, `fetchedAt`, `isLive`, `isFinished` (`false`), `content` (the
members of `EventContent`, `kind` as `Match`, `Outright` or `Unrecognized`) and `manifest`
(`[{ marketId, contentHash }]`), plus `schemaVersion`, `messageId` and `producedAt`, which you can ignore. A markets
item's `market` is a `MarketSnapshot`. Each market's `selections` is an array of rows of selections. The item's
`suspended` is `true` while the event is withdrawn or any of the item's markets is suspended.

The status is `{ status, reason, since, edgeVersion, wireVersions, lastFetchedAt, lagSeconds }`, the members of
`EdgeStatus` (Messages): `status` is `Ready` or `Degraded`, and `reason` is `Starting`, `Liveness`, `Arrival` or
`QueueLag`, `null` while ready. Older Edge builds can also report `LiveLag`. Read a `status` your build doesn't know
as `Degraded`, and a `reason` it doesn't know as unknown. `since` and `lastFetchedAt` are times, `lagSeconds` a number
of seconds, `wireVersions` an array of whole numbers and `edgeVersion` a string; a member Edge hasn't set yet is `null`.

### Paging

- Reference lists are ordered by (`updatedAt`, `id`). `updatedSince` (ISO 8601 with `Z` or an offset) is inclusive;
  without it a list starts at the beginning. A list holds only the records Edge has caught up to, so a record Edge just
  fetched by id is listed once its catch-up has passed it, and a reader that moves its watermark by `updatedAt` never
  skips one.
- `GET /local/v1/events` is ordered by `eventId`. `sportId` is repeatable and keeps the events of any listed sport;
  absent, every sport Edge receives. `isLive` is `true` or `false` and keeps the events of that live state; absent,
  both.
- `limit` is 1-1000, 500 when absent. `nextCursor` is `null` on the last page.
- A cursor is opaque and carries the list and the filters it was issued under, so the next page needs only `cursor`.
  An `updatedSince`, `sportId` or `isLive` sent with it must equal the cursor's. On `invalid-cursor`, restart from your
  last `updatedSince` or from the first page.
- An empty query parameter (`?limit=`) counts as absent.

### Problem codes

| Status | `code` | When |
| --- | --- | --- |
| `400` | `invalid-limit` | `limit` isn't an integer in 1-1000 |
| `400` | `invalid-updated-since` | `updatedSince` isn't an ISO 8601 timestamp with `Z` or an offset |
| `400` | `invalid-sport-id` | a `sportId` isn't a UUID |
| `400` | `invalid-is-live` | `isLive` isn't `true` or `false` |
| `400` | `invalid-cursor` | the cursor is malformed or another list's, or sent with another `updatedSince`, `sportId` or `isLive` |
| `400` | `invalid-market-ids` | a refresh body isn't `{ "marketIds": [UUID] }` with 1-100 ids |
| `400` | `unbound-sport` | a `sportId` of `GET /local/v1/events` names a sport your client entry doesn't receive for the requested `isLive` (absent: in neither) |
| `404` | `not-found` | an unknown id, a non-UUID id, an event Edge doesn't serve, or an unknown route |
| `415` | none | a refresh body has no supported JSON media type (`application/json` or a subtype with the `+json` suffix) |
| `500` | `internal-error` | an unexpected failure; retry later |
| `503` | `feedhub-unavailable` | FeedHub could not answer a reference lookup, or could not confirm managed publication membership for an otherwise servable held event on the markets route |
| `503` | `edge-not-ready` | Edge hasn't loaded its initial state yet after a start (Runbook), on every route but `GET /local/v1/status`; retry later |

A request that fails validation gets its `400` even before Edge has loaded its state.

### Pre-bet refresh

Call `POST /local/v1/refresh` with `{ "marketIds": [UUID] }` (1-100 ids, as `application/json`) before you accept a
bet, to price it on current data:

- the requested markets are grouped by their event. Edge answers an event from its own state, with `status` `Served`,
  when it holds the event (not finished, not withdrawn), every requested market of it (not removed, not suspended),
  each matching the event's manifest, and the event was fetched less than `Refresh:FreshAge` ago on FeedHub's clock;
- every other event is asked of FeedHub in one call, bounded by `Refresh:UpstreamTimeout`. FeedHub's entries, and the
  ids no event holds (`unknownMarketIds`), are answered as FeedHub wrote them. What FeedHub serves is also applied to
  Edge's state, so every subscriber gets the refreshed markets on its stream;
- the answer is `{ events: [{ eventId, status, event, markets }], unknownMarketIds }`, `200` whatever the entries'
  statuses. `markets` holds the whole market snapshot of each requested market's `snapshotKey`. The open `status`
  field can contain `Served`, `Unknown`, `Failed` or `Unrecognized`. Handle unfamiliar values as `Failed`.
- When the upstream refresh fails for a held event, Edge answers with `status` `Unknown`, `event` `null`, `markets`
  `[]` and `heldFetchedAt`. That timestamp is the held event's `fetchedAt`, or `null` when Edge holds no servable
  snapshot. Other entries omit `heldFetchedAt`. Keep the bet blocked on an `Unknown` result. FeedHub's later data
  reaches you on the stream as usual.

## The application's rules

These are the rules your application applies to what `Subscribe` sends. The client package carries none of them.

1. A snapshot is the whole state for its filter. After `SnapshotEnd`, an event the application holds for this
   subscription that the snapshot didn't list is no longer served; it is handled as withdrawn, never as finished.
   `SnapshotBegin` opens the snapshot and `SnapshotEnd` closes it. A fresh snapshot is always a valid answer to a
   `Subscribe`, with or without a token, and this rule is how you apply it.
2. Changes are applied in stream order. `EventChanged` with `is_finished` finishes an event.
3. `MarketRemoved` removes a market. `manifest` is informational, and the application never removes a market by it.
4. `EventWithdrawn` suspends the event and all its markets, with no finish-side action. A later `EventChanged`
   restores the event, and each restored market comes with `MarketChanged` and its `Market.suspended` cleared.
5. A market is suspended while its own `Market.suspended` is set, and a selection while its own `is_suspended` is set.
   `MarketChanged` has no suspension field of its own.
6. Every market, live and prematch, matches and outrights, is suspended while the status is `degraded`.
   `StatusChanged` carries the status:
   - `STATUS_READY`: markets trade, each under its own suspension (rules 4 and 5);
   - `STATUS_DEGRADED`: suspend every market until `STATUS_READY`. When it comes, markets reopen, except a market
     whose own `Market.suspended` is set, a selection whose own `is_suspended` is set, and the markets of a withdrawn
     event (rules 4 and 5);
   - `STATUS_UNSPECIFIED`, or a number your build doesn't define: read as `STATUS_DEGRADED`. Edge never writes it.

   The `reason` of a degraded status is for your logs and dashboards; every reason suspends every market the same way,
   and a change of reason is sent as a new `StatusChanged`:
   - `DEGRADED_REASON_STARTING`: Edge is loading its initial state, or has loaded it and its checks of the feed have
     been healthy since, but not yet for long enough to turn ready;
   - `DEGRADED_REASON_LIVENESS`: FeedHub doesn't report its feed as fresh, or didn't answer Edge's check in time;
   - Older Edge builds can report `DEGRADED_REASON_LIVE_LAG` when SportApi reports live lag or when live polling stops
     while Edge holds an active live event.
   - `DEGRADED_REASON_ARRIVAL`: FeedHub reports its feed polled, but no change has reached Edge for the arrival
     threshold while Edge holds an event, live or prematch;
   - `DEGRADED_REASON_QUEUE_LAG`: changes reached Edge later than the queue-lag threshold within the last window;
   - `DEGRADED_REASON_UNSPECIFIED` (set while `STATUS_READY`), or a number your build doesn't define: an unknown
     reason. Keep every market suspended while the status is degraded.
7. `EventUnsubscribed` drops the event and its markets from the application's state for this subscription, with no
   suspension and no finish-side action.
8. A `FeedEvent` whose body the application's build doesn't know is skipped.
9. A snapshot also lists the finished events Edge still holds, so an application that missed the finish learns it from
   the snapshot.
10. The filter selects what you get (The filter). Subscribe by sport to get the sport's new tournaments; a tournament
    list never grows.
11. Proto enums are open. Each enum's zero value is a meaningful default (`PHASE_ANY`) or `<ENUM>_UNSPECIFIED`, which
    Edge never writes. Read the zero value, or a number your build doesn't define, as the fallback: `Status` as
    `STATUS_DEGRADED`, `DegradedReason` as unknown, `PlaceBetOutcome` as `PLACE_BET_OUTCOME_FAILED`,
    `BetStatusState` as `BET_STATUS_STATE_UNRECOGNIZED`, and `SettlementResult` as `SETTLEMENT_RESULT_UNRECOGNIZED`.
12. Keep the latest `resume_token` you received and send it when you subscribe again. The token is opaque. Edge answers
    a token it can't resume with a fresh snapshot, never with an error, and rule 1 applies it.

Each `body` member, with its rule:

| Message | Rule |
| --- | --- |
| `StatusChanged` | 6 |
| `SnapshotBegin` | 1 |
| `SnapshotEnd` | 1, 9 |
| `EventChanged` | 2, 4, 9 |
| `MarketChanged` | 4, 5 |
| `MarketRemoved` | 3 |
| `EventWithdrawn` | 4 |
| `EventUnsubscribed` | 7 |

## Supported Edge versions

This section is about Edge versions, the releases of the image. The versions of the local API an image serves are
another matter (Versioning).

- FeedHub supports the newest published Edge version (N) and the one before it (N-1). A version here is
  `MAJOR.MINOR`: patches don't count. Within a supported `MAJOR.MINOR` the latest patch is the supported one: an older
  patch keeps running, but FeedHub answers problems on the latest patch.
- A release's number tells you what it asks of you. A new `MAJOR` is a change you must act on, such as a new local API
  version (`/local/v2`) or a new required setting; a new `MINOR` is a new feature or something FeedHub must have in
  place first; a new `PATCH` is fixes or a rebuild (a patched base image, for example). The line starts at `1.0.0` and
  is apart from the .NET package's version (The .NET package).
- When a release pushes a `MAJOR.MINOR` out of N-1, FeedHub deprecates that version, with all its patches, when the
  release is published, and disables it no sooner than 30 days later. The release's notes name both. FeedHub
  operations make each change by hand; no version is deprecated or disabled by itself.
- Edge learns its version's state at each report to FeedHub (`Heartbeat:Interval`). A deprecated version logs a
  `Warning` and runs on; a disabled version stops, at start or while running, whether you pulled it by tag or by digest
  (Runbook).
- For example, with 1.4 as N and 1.3 as N-1, publishing `1.5.0` makes 1.4 the N-1 and deprecates 1.3; every 1.3 patch
  is disabled 30 days later at the earliest.
- To stay supported, run the latest patch of a supported version, chosen from the release notes (Getting the image),
  and update Edge before your applications.

## Versioning

- The proto file is the local API's published interface, package `feedhub.edge.v1`. Within a version, changes are
  additive only: a new field with a new number, a new message, a new `oneof` member, a new enum value, a new RPC, a new
  REST route or optional member. A field is never renumbered, retyped or reused; a removed field's number and name are
  `reserved`.
- Any other change is a new version (`feedhub.edge.v2`, `/local/v2`). An Edge image serves local API versions N and
  N-1 side by side. These aren't the Edge versions FeedHub supports (Supported Edge versions). The provider-neutral
  contract is a one-time exception for GB2’s coordinated non-production rollout. It keeps `feedhub.edge.v1` and
  `/local/v1`. Stop old Edge instances before FeedHub deploys and start the new Edge with compatible applications.
- **Update Edge before your applications.** An application built against an older proto keeps working against a
  newer Edge of the same version: it skips a body it doesn't know (rule 8) and reads an enum value it doesn't know as
  its fallback (rule 11).

## The .NET package

`FeedHub.Edge.Client` is the .NET client of `feedhub.edge.v1`, generated from the proto file with `Grpc.Tools`. It
holds only the generated message and enum types, in namespace `FeedHub.Edge.V1`, and the generated client
`FeedEdge.FeedEdgeClient`. It carries no rule of the application, so you apply The application's rules yourself. It
depends on `Google.Protobuf` and `Grpc.Net.Client`, so you need no other package to create a channel. Its version's
major is the proto package's version (`feedhub.edge.v1` is 1.x), and each additive proto change raises the minor. The
package has no types for local REST; write your own for its JSON from Local REST.

Add the [public BetFeedPro NuGet feed](https://releases.betfeedpro.com/nuget/index.json) to your package sources and pick the
package version compatible with your Edge. For example, `1.6.0` requires the Edge protocol with `SelectionId` for `PlaceBet`.

```xml
<PackageReference Include="FeedHub.Edge.Client" Version="1.6.0" />
```

A channel to an `http://` address speaks HTTP/2 without TLS on .NET 10 with no switch. A `Subscribe` loop that keeps
the latest token and subscribes again after `UNAVAILABLE`, `INTERNAL`, or a `CANCELLED` it didn't cause, where `stopping` is your application's stop token:

```csharp
using FeedHub.Edge.V1;
using Grpc.Core;
using Grpc.Net.Client;

using var channel = GrpcChannel.ForAddress("http://localhost:8090");
var client = new FeedEdge.FeedEdgeClient(channel);
var resumeToken = string.Empty;

while (!stopping.IsCancellationRequested)
{
    var request = new SubscribeRequest { Phase = Phase.Any, ResumeToken = resumeToken };
    request.SportIds.Add("0199f3a1-7c20-7b4e-9a51-3d8e2f604a11");
    try
    {
        using var call = client.Subscribe(request, cancellationToken: stopping);
        await foreach (var message in call.ResponseStream.ReadAllAsync(stopping))
        {
            if (message.ResumeToken.Length > 0)
                resumeToken = message.ResumeToken;
            Apply(message);
        }
    }
    catch (RpcException exception) when (exception.StatusCode is StatusCode.Unavailable or StatusCode.Internal
        || (exception.StatusCode == StatusCode.Cancelled && !stopping.IsCancellationRequested))
    {
    }

    await Task.Delay(TimeSpan.FromSeconds(2), stopping);
}
```

`Apply` switches on `message.BodyCase` and applies The application's rules; `BodyOneofCase.None` is a body your build
doesn't know (rule 8). Any other `RpcException` (`INVALID_ARGUMENT`, `FAILED_PRECONDITION`) means the request needs
fixing and is not retried.

A `PlaceBet` call, with a deadline above `Betting:RequestTimeout` (15 s by default):

```csharp
var reply = await client.PlaceBetAsync(new PlaceBetRequest
{
    ClientBetKey = "5f0c2a7e-3b1d-4c6a-9e2f-7d8b1a4c6e10",
    MarketId = "019a1c2e-6b00-7d20-8f31-5c4d3e2f1a01",
    SelectionId = "019a1c2e-7c00-7e30-a041-6d5e4f3a2b01",
    Price = "1.45",
    Stake = "25.00",
    AcceptPriceChanges = false,
    IsLive = true,
}, deadline: DateTime.UtcNow.AddSeconds(18), cancellationToken: stopping);
```

`reply.Outcome` is the bet's outcome (`PlaceBet`); `reply.HasBetId`, `reply.HasCurrentPrice` and `reply.HasProblem`
tell a set optional field from an unset one.

A `GetBets` call, with a deadline above `Betting:QueryTimeout` (5 s by default):

```csharp
var query = new GetBetsRequest();
query.BetIds.Add("019a1c2f-1a00-7a10-8c41-2f3e4d5c6b02");
query.ClientBetKeys.Add("5f0c2a7e-3b1d-4c6a-9e2f-7d8b1a4c6e10");
var bets = await client.GetBetsAsync(query, deadline: DateTime.UtcNow.AddSeconds(8), cancellationToken: stopping);
```

`bets.Bets` holds one entry per asked id, then one per asked key, in the order asked (`GetBets`); `HasBetId`,
`HasClientBetKey`, `HasOutcome`, `HasCurrentPrice` and `HasResult` tell a set optional field from an unset one, and
`SettledAt` is `null` when unset.

A results loop that applies and confirms each result, and reads again after a delay when the stream ends:

```csharp
while (!stopping.IsCancellationRequested)
{
    try
    {
        using var call = client.ReadBetResults(new ReadBetResultsRequest(), cancellationToken: stopping);
        await foreach (var delivery in call.ResponseStream.ReadAllAsync(stopping))
        {
            await ApplyAsync(delivery.Result, stopping);
            await client.ConfirmBetResultAsync(new ConfirmBetResultRequest { DeliveryId = delivery.DeliveryId }, cancellationToken: stopping);
        }
    }
    catch (RpcException exception) when (exception.StatusCode is StatusCode.Unavailable or StatusCode.Internal or StatusCode.NotFound
        || (exception.StatusCode == StatusCode.Cancelled && !stopping.IsCancellationRequested))
    {
    }

    await Task.Delay(TimeSpan.FromSeconds(2), stopping);
}
```

`ApplyAsync` writes the result durably, keyed by `bet_id`, and returns once the write has committed; a result already
applied it applies as nothing.

## Runbook

| Situation | What the operator sees | What to do |
| --- | --- | --- |
| Start with invalid or missing settings | Edge exits `1` after the critical entry `FeedHub.Edge did not start, invalid settings:`, one line per failing key with its reason; `/healthz` never answers | fix each named key in `.env`, or its value in the chart's values (Helm), and start again |
| Edge runs | `/healthz` answers `200` `Healthy`. It says only that the process runs, never that data is current | read data health from the status: `StatusChanged` on the stream, `GetStatus`, or `GET /local/v1/status` |
| Edge is loading its initial state | `Subscribe` answers `UNAVAILABLE`, `/local/v1` answers `503` `edge-not-ready` except `GET /local/v1/status`; the status is `degraded` with `STARTING` meanwhile; `PlaceBet` and `GetBets` answer as usual | nothing: applications retry `UNAVAILABLE`; it ends once the state is loaded, logged at `Information` with the number of events loaded |
| Edge is degraded | the status is `degraded` with its reason, and Edge logged a `Warning` entry when it turned degraded | by reason: `STARTING`, wait: it turns `ready` about 30 s after loading once the feed is healthy. `LIVENESS` lasting beyond a FeedHub restart: check with FeedHub operations that your client entry and FeedHub are in order. For `LIVE_LAG` on older Edge builds, contact FeedHub operations if the delay lasts. `ARRIVAL`: check that `FeedHub:Bindings` matches what was handed over and, after a FeedHub upgrade, update Edge. `QUEUE_LAG`: Edge is working through a backlog (after a long stop, for example) and recovers on its own; if it lasts, check Edge's CPU and its network path to the broker |
| FeedHub unreachable at start | Edge keeps running and doesn't restart: the status stays `degraded` with `STARTING`, Edge logs one `Warning` entry per failed attempt to load its initial state and tries again after `Bootstrap:RetryDelay`, and `feedhub_edge_bootstrap_failures_total` counts the attempts. Once FeedHub answers, the state loads without a restart. Meanwhile `/local/v1/ready` answers `503`, so a pod probed on it stays NotReady and its Service sends it no connection | check `FeedHub:Instance`, the broker host and the network path to it against what FeedHub operations handed over: a wrong instance looks the same as an outage. Contact FeedHub operations if the wait lasts |
| Edge's credentials refused | Edge logs the failure and exits `1`; its orchestrator restarts it, shown as a crash loop | check `FeedHub:Instance`, the broker host and the credentials against what FeedHub operations handed over; if they match, contact FeedHub operations |
| Broker unreachable | Edge keeps running and retrying the connection; `/healthz` answers; until it connects at start, Edge stays loading | check the network path to the broker host; Edge recovers on its own |
| TLS connection to the broker fails (an invalid or expired certificate, a host name the certificate doesn't match, `RabbitMq:Tls` `true` against a port without TLS or `false` against the AMQPS port) | the same as an unreachable broker: Edge keeps running and retrying, `/healthz` answers, and until it connects at start Edge stays loading; the log shows the failed connection attempts and their TLS error | check `RabbitMq:Host`, `RabbitMq:Port` and `RabbitMq:Tls` against what FeedHub operations handed over: the public host name, the AMQPS port and `true`. If they match, contact FeedHub operations. Edge recovers on its own once a connection opens |
| Broker connection refused at your client entry's connection cap | as for an unreachable broker: Edge keeps running and retrying, stays loading if it hasn't connected yet, and `ReadBetResults` answers `UNAVAILABLE` while its connection can't open. After a node loss the broker keeps the lost pod's connection until it times out, so its replacement waits that long | check that you run no more replicas than FeedHub operations set and no index twice; Edge connects on its own once a slot frees. If the cap is too low for your replicas, ask FeedHub operations to raise it |
| A replica started with an index your client entry doesn't have (above the number FeedHub operations set, or set before they raised it) | Edge keeps running but doesn't finish loading: the status stays `degraded` with `STARTING`, `/local/v1/ready` answers `503`, and Edge logs the broker refusing what this replica would receive; it can also exit `1` and be restarted | check `FeedHub:Replica` against the number of replicas FeedHub operations set. Once they have raised it, the replica loads on its own or at its next start |
| Changes lost to an overflow or an expired backlog (a broker outage past the backlog's five minutes of retention, or a shorter one that overflows it) | the status is `degraded` during the repair; prematch events whose poll was lost serve withdrawn markets and old content hashes, and new events are missing, for at most 3 minutes after the broker connection returns, with the exceptions and the numbers measured under Sizing | nothing: Edge repairs them on its own. Only a new event whose first poll failed can still be missing once the status is `ready` |
| A subscriber connection silently lost, a NAT black-hole for example | `feedhub_edge_subscribers` falls within about 54 s with the default settings (`Grpc:KeepAlivePingDelay` plus `Grpc:KeepAlivePingTimeout` plus about 4 s after the last frame Edge received) while Edge's sends on that connection aren't stalled; with stalled sends the time isn't measured. Edge logs `Service method 'Subscribe' canceled.` at `Information`, the entry of any call whose connection dropped. An application without a keepalive reports nothing | give the application a keepalive (Keepalive) and check the network path. Edge's state and its other streams aren't affected |
| `ReadBetResults` ends `UNAVAILABLE` at once on every call | each ended or refused stream is logged at `Warning` with its reason | if Edge's connection to FeedHub is down, check the network path to the broker host; Edge recovers on its own. If it is connected, your client entry receives no results: ask FeedHub operations to enable results for it |
| `ReadBetResults` ends `UNAVAILABLE` about every 30 minutes while `feedhub_edge_bet_results_unreadable_total` rises | Edge logs each result it can't read at `Error`, and each ended stream at `Warning`; results stop arriving once a stream holds only results it can't read | upgrade Edge: FeedHub sends results in a form this Edge doesn't read. They wait for the upgrade; nothing is lost |
| `PlaceBet` or `GetBets` answers `UNAVAILABLE` or `DEADLINE_EXCEEDED` on every call | each failed call is logged at `Warning`: a `PlaceBet` with its `client_bet_key`, `market_id` and status code, a `GetBets` with the number of ids and keys it asked for and the status code | `UNAVAILABLE`: check the network path to the broker host; if Edge is connected, ask FeedHub operations whether your client entry may place bets and ask for their state. `DEADLINE_EXCEEDED`: FeedHub isn't taking bets or answering for them (its betting turned off, or a deploy under way); contact FeedHub operations |
| This Edge version deprecated | Edge logs a `Warning` entry naming its version and FeedHub's instance and that the version will be disabled, at the first such verdict and whenever the verdict changes to it; Edge keeps running and serving as usual | plan the upgrade now: FeedHub disables this version no sooner than 30 days after deprecating it. Choose the latest patch of a supported Edge version from the release notes (Supported Edge versions), set `EDGE_IMAGE_TAG` to it and start Edge again, or `helm upgrade` to its chart (Helm) |
| This Edge version disabled | Edge logs one `Critical` entry naming its version and FeedHub's instance, that FeedHub has disabled this version and that an allowed version must be installed, and exits `1`, whether it has just started or has run for hours, and whether its image was pulled by tag or by digest; its orchestrator restarts it into the same refusal, shown as a crash loop. At start, Edge reports to FeedHub as soon as its broker connection is up, without waiting for its initial state, and stops on the answer. Until then, at most `Heartbeat:Timeout` (5 s by default) after the connection is up, it serves as at any start: `/healthz`, `GET /local/v1/status`, `PlaceBet` and `GetBets` answer, and `Subscribe` answers `UNAVAILABLE` until the state is loaded. Edge doesn't hold its local API waiting for that answer, and while FeedHub doesn't answer its reports, Edge keeps running (Edge's reports to FeedHub unanswered) | install the latest patch of a supported Edge version from the release notes (Supported Edge versions) with `EDGE_IMAGE_TAG`, and start Edge again, or `helm upgrade` to its chart (Helm). Setting the version back to allowed on FeedHub's side doesn't restart a stopped Edge |
| Edge's reports to FeedHub unanswered | nothing changes in Edge: its status, `/healthz` and the local API run on. Each unanswered report is logged at `Debug`, and Edge reports again at the next interval | nothing while it is occasional. If no report is answered for long, ask FeedHub operations to check your client entry: once it is fixed, Edge's reports are answered again without a restart |
| A restart | every application gets a fresh snapshot on its next `Subscribe` once Edge has loaded its state | nothing: rule 1 applies the snapshot |
| An upgrade | a new Edge version's release notes on the release page; after the restart, a fresh snapshot for every application | read the release notes for what FeedHub must have in place first and the local API versions the release serves, verify the image (Getting the image), set `EDGE_IMAGE_TAG`, or `helm upgrade` to the new chart (Helm), and update Edge first, then the applications: an image serves the local API's versions N and N-1 (Versioning) |

## Monitoring

`GET /metrics` on the HTTP/1.1 port (`Ports:Http`, beside `/healthz`) serves Edge's series in the Prometheus text
format: `200`, no authentication, also while Edge is loading its initial state. It doesn't depend on the status or on
FeedHub. Like `/local/v1` it is open to whatever reaches the port; its series carry no event, market or subscriber id.

Set `Observability:OtlpEndpoint` to an OTLP gRPC collector to receive the same metrics there, with traces and logs. An
unreachable collector only loses telemetry: Edge runs on and `/metrics` still answers. On `/metrics`, `env`, `client`
and `service_name` are `target_info` attributes rather than labels on each series.

The series an application team reads:

- **Lag**: `feedhub_edge_message_age_seconds`, a histogram of how old a message from FeedHub is when Edge receives it.
- **State size**: `feedhub_edge_state_events` and `feedhub_edge_state_markets`, what Edge's state holds.
- **Cache size**: `feedhub_edge_references_records`, the reference records held, by `kind`.
- **Subscribers**: `feedhub_edge_subscribers`, the `Subscribe` calls registered now.
- **Messages**: `feedhub_edge_subscriber_messages_total`, messages written to subscribers, by `type` and `part`.
- **Coalesced changes**: `feedhub_edge_subscriber_coalesced_total`, changes folded into a pending send, by `key`.
- **Waiting reference data**: `feedhub_edge_reference_waiting_events`, events held back until their reference data
  arrives.
- **Bootstrap failures**: `feedhub_edge_bootstrap_failures_total`, failed attempts to load the initial state from FeedHub
  that Edge retries. Any rise while the status stays `STARTING` means FeedHub doesn't answer Edge (Runbook).
- **Unreadable results**: `feedhub_edge_bet_results_unreadable_total`, bet results Edge received and couldn't read. Any
  rise means FeedHub sends results in a form this Edge doesn't read: upgrade Edge. Those results wait in FeedHub until
  then.

Every other `feedhub_edge_*` series and the .NET runtime and HTTP client series are diagnostics for FeedHub operations.

## Sample consumer

The sample consumer, `FeedHub.Edge.Client.Sample`, is a console application that uses Edge only through the .NET
package. Its source isn't in the client package: it is available from FeedHub operations on request. It
subscribes with its configured filter, applies The application's rules to an in-memory view of events and markets,
and logs what each message did. It keeps the latest `resume_token` and sends it when it subscribes again: a stream
that ends, or fails with `UNAVAILABLE`, `INTERNAL` or a `CANCELLED` it didn't cause, is subscribed again after
`Edge:ResubscribeDelay`, with the status and detail logged at `Warning`; any other status code is logged at `Error`
and the sample exits `1`. It runs until stopped.

Settings come from `appsettings.json`, then `appsettings.{DOTNET_ENVIRONMENT}.json` (optional), then variables
prefixed `FEEDHUB_EDGE_SAMPLE_` (`__` for `:`):

| Key | Committed value | What it sets |
| --- | --- | --- |
| `Edge:GrpcAddress` | `http://localhost:8090` | Edge's gRPC address, an absolute `http` or `https` URL |
| `Edge:ResubscribeDelay` | `00:00:02` | the delay before subscribing again, a positive duration |
| `Subscribe:SportIds` | `[]` | the filter's sport ids, UUIDs |
| `Subscribe:TournamentIds` | `[]` | the filter's tournament ids, UUIDs |
| `Subscribe:Phase` | `Any` | `Any`, `Live` or `Prematch` |
| `Smoke:Timeout` | `00:02:00` | how long `--smoke` waits for its checks, a positive duration |

An invalid setting is logged by name with its reason, never its value, and the sample exits `3`.

From the source's root folder:

```bash
dotnet run --project FeedHub.Edge.Client.Sample [-- --smoke]
```

`--smoke` keeps checking until `Smoke:Timeout`. On a stream that ends, or fails with `UNAVAILABLE`, `INTERNAL` or a
`CANCELLED` it didn't cause, it subscribes again after `Edge:ResubscribeDelay` with the latest `resume_token`. Every
stream starts with `StatusChanged`. A stream subscribed with a token may then go straight to changes; a stream that
answers with `SnapshotBegin` is checked as a first stream is: `SnapshotBegin`, at least one `EventChanged`, and
`SnapshotEnd`, with no `MarketChanged`, `MarketRemoved`, `EventWithdrawn` or `EventUnsubscribed` before its event's
first `EventChanged`. The check of that order carries over a resumed stream and restarts on a snapshot; on a resumed
stream, `EventUnsubscribed` for an event this run hasn't seen is no breach. After `SnapshotEnd` it keeps reading
changes under the same check. It exits:

- `0` passed: at `Smoke:Timeout`, some stream reached `SnapshotEnd` and no stream broke the order;
- `1` failed: a stream broke one of those orders;
- `2` not checked, with the reason: no stream reached `SnapshotEnd` by the timeout (the reason gives the last end's
  status), a `FAILED_PRECONDITION` or `INVALID_ARGUMENT` answer, any other status code the sample doesn't subscribe
  again after, or a snapshot with no event;
- `3` invalid settings.
