Dokumentation · Data og kilder
The Eloverblik client
elo_sources.eloverblik is the only code that talks to the Eloverblik Customer API. It is built to
docs/architecture/phase-1.md §5 (calls, pacing, egress ownership) and §12.1 (the token, logs). The
worker (B07 onwards) and the capture tool (B06b) use the same client: the worker with a store in
PostgreSQL, the capture tool with a file. This page says how it behaves, so that neither has to read the
code to use it.
The interface
elo_sources.source.MeteringSource has five calls: health(), list_metering_points(),
get_details(ids), get_charges(ids), get_timeseries(ids, date_from, date_to, aggregation="Actual").
Each data call returns a SourceResponse:
items: oneItemResultper item, in the order of the requested IDs, matched on the item'sid(or, for a time series, onMarketEvaluationPoint.mRID.name), never on the order of the response. A requested ID with no item in the response getsPARSE_ERROR. The list names no ID: when it fails as a whole (a status other than 200, or a 200 whose list is unreadable, absent ornull),itemsholds oneItemResultwithmetering_point_idNoneand the outcome (PARSE_ERROR,RETRY_LATERorPERMANENT). An emptyitemsmeans only that the API answered{"result": []}; access state must never be reconciled from a list response that holds an item without an ID.fetch: aFetchRecord, the columns ofraw.fetchthe source can fill: endpoint, request key (the endpoint and the window, never a token or an ID), the reserved start, the completion, the status, both correlation IDs, the code of a request refused as a whole,Retry-Afterin seconds, and the body as received (never for a token response; never shown byrepr()). The server's correlation ID is kept only in a known shape (the observed0HNPUVU7MMH2U:00000274, or a UUID as documented); any other value is dropped unseen.unknown_fields: the paths of fields the allowlist does not know, foringest.unknown_field.
ItemResult.outcome is a SourceOutcome: values 1 to 6 of raw.fetch_item.outcome. That is what a
source can tell from the response alone:
| Outcome | When |
|---|---|
1 OK | 10000 and the payload parsed |
2 NO_DATA | 30015 |
3 OUTSIDE | 30018, 30017, 30010, 30016, 20010, 40014, 20012 |
4 PERMANENT | 20003, 20004, 20008 (an invalid ID), any other documented code, or the request refused as a whole (400, 403, 404) |
5 RETRY_LATER | 20011, or the request got 429, 503, another 5xx, 401, or no response |
6 PARSE_ERROR | the item or the whole response could not be read, or there was no item for the ID |
Values 7 to 9 (unsupported unit, stale on every day, unsupported resolution) are decided by the validation and the merge of §4.3, after the source has answered. The source never returns them.
A request is checked before it is sent: 1 to 10 metering points of 18 digits each, none twice, date_from
before date_to, a documented aggregation. A request that breaks a rule raises ValueError and is not
sent. The message never contains an ID.
readings(period) turns a period's positions into UTC interval starts:
start + (position − 1) × resolution. expected_points(period) gives the number of intervals the period's
own bounds hold: 23, 24 or 25 hourly, or 92, 96 or 100 quarter-hourly.
One call at a time
Every call, whether data, token or health, runs in the store's exclusive() section:
- Reserve the start in the store (
reserve_start). The store makes the reservation durable first and then runs the observer'sreserved(transaction A: insertraw.fetch, count the attempts). 2. Wait until the start on the store's clock. 3. Send, then receive the response or time out. Connect timeout 10 s, read timeout 120 s, and one deadline of 130 s for the whole call (B101: an answer in pieces is given up at it). In the worker it starts at the lock gate's own final elapsed reading, which is handed to the receive code and checked again before the HTTP send; an already expired call sends nothing and cuts a retained connection. Without a worker lock the deadline starts at the send. In the worker the lockelo.workeris asked immediately before the send, and again where more than 2 s of the boot-time clock have passed since it was asked; without it nothing is sent (WorkerLockLost). No HTTP cache: the client sendsCache-Control: no-cacheand uses a generic user agent. 4. Record the completion with the cooldown of the response table (finish_call). The store then runs the observer'scompleted(transaction B: completeraw.fetch, apply the items).
The next call is spaced from the completion of this one. A process paused between its reservation and its send therefore cannot be followed too closely.
| Response | Pace |
|---|---|
| 200 | cooldown level and the count of 503 in a row back to 0 |
| 429 | cooldown until the greatest of Retry-After and 60 s × 2^level (the 60 s back-off doubles and stops at 900 s; Retry-After is never capped); level + 1. fetch.attempt_counts is false, so the caller gives the attempt back and does not split the batch |
503, another 5xx, a timeout or a transport error, isalive not true | cooldown until the greatest of Retry-After and 60 s; from the fifth in a row, at least 900 s, and the next call is isalive. Data calls resume when it answers true; until then a data call raises Deferred |
| 401 on a data call | the access-token file is deleted, a new token is obtained, the call is sent once more; a second 401 raises AccountInvalid |
/token 401, 403 or code 50001 | AccountInvalid: a new refresh token is needed |
/token with anything else | Deferred, with the cooldown if there is one |
| 400 | the code is parsed and kept; the same request (same endpoint, window and IDs) raises AlreadyRefused and is never sent again by this client |
The client never resends a 429 or a 503 by itself. It returns the items as RETRY_LATER, and the next
call waits for the cooldown.
Stores
PaceState holds the columns of ingest.pacer. The rules of reserving, finishing and recovering are
pure functions in pacing.py, and a store keeps the state and applies them on its own clock:
FilePaceStore(path): the capture tool'sdata/capture/pace.json. It is read at every step and written through a synced temporary file at each reservation and completion.exclusive()holds anflockonpace.json.lock, so two processes on the host call one after the other. An unreadable file stops the store: it never starts from an empty history.MemoryPaceStore(): the other mode in B05's tests.PostgresPaceStore(engine)(elo_worker.eloverblik.store, B07): the worker's. The state isingest.pacer; the transitions are the database's functions (ingest.reserve_start(kind, not_before),ingest.finish_call(kind, signal, retry_after_s), which applies the whole response table), with the spacings ofingest.pace_setting, which the migrate step installs fromELO_CALLS_PER_MINUTEandELO_TOKEN_SPACING_Sas the owner;settingsis read from that row.now()isingest.pacer_clock(), and a wait is the duration to the instant on the elapsed clock. The store holds one connection:exclusive()is the session advisory lockelo.ingeston it, and the observer's writes of transactions A and B run on it (store.connection) and commit with the reservation and the completion. Beside each deadline the row keeps the wait it still implied (next_start_in_s,token_next_start_in_s,cooldown_in_s), so that a restart takes it as a lower bound whatever the clock did meanwhile. Those three waits are all the worker role may update itself; the handoff isingest.absorb(…), and the three functions run with the owner's rights, so no caller can move a deadline earlier (B07v-09). When transaction B fails, the completion is recorded alone before the error propagates, as the file store saves it beforewithin; and a reservation that finds a call still in flight under the lock finishes it first (B07v-04).
The deadlines are stored as wall-clock instants, which survive a restart and pass to the other mode.
While a process runs, a store also carries every deadline it has seen onto the clock's monotonic counter
(Clock.monotonic()), and no reservation starts before those, and every wait is measured on that counter:
a forward correction of the wall clock never shortens a spacing, a token spacing or a cooldown. A backward
correction makes the stored deadlines lie further ahead; they are honoured, so the store waits longer.
The call kinds are CallKind.DATA = 1, TOKEN = 2 and HEALTH = 3, the values of
ingest.pacer.in_flight_kind.
The egress
Egress(state_dir, mode) is the ownership of §5.2. The owner is whoever creates
data/state/egress/lock/ with mkdir; the directory holds owner.json (mode, start ID, host, PID,
time). EloverblikClient.start() acquires it or raises EgressBusy, whose message names the owner and
says how to release it. That is how the capture tool exits. start_waiting() tries again once a minute
on the store's clock. The worker polls once a minute and also at its lock+150 s takeover boundary;
until it owns the egress, its Eloverblik jobs remain unclaimed. After acquiring, the client:
- takes the greatest of its store and the handoff record
data/state/egress/pace.json; 2. puts the first call at least one spacing after the acquisition, and the first token call at least one token spacing after it when the other mode wrote the record; 3. recovers: a reservation whose completion was never recorded is finished now, so the next call waits a full spacing, and a full token spacing after a token call.
close() writes the handoff record and removes the lock. The lock is renamed away first and deleted
afterwards. Every call first checks that the lock is still there and still belongs to this client.
A lock left by a crash is taken over only by the same mode: the worker always (one container), the
capture tool only when no process with the recorded PID runs on the recorded host. The other mode never
takes it over. A lock without a readable owner.json is taken over by neither mode, and the error says
which directory to remove after checking that nothing runs.
A takeover replaces exactly the predecessor it checked: it creates lock/claim-<start ID>/ with mkdir,
reads owner.json again, and writes its own only if that still names the start ID it claimed. If the lock
has meanwhile been taken over, released or acquired anew, the takeover fails and the client makes no call;
of two takeovers of one predecessor exactly one succeeds.
The token
- The refresh token is passed in as a
SecretStr. Its SHA-256 is the fingerprint. - The access token is kept in a file,
data/state/eloverblik-access-tokenfor the worker anddata/state/capture-access-tokenfor the capture tool, with mode 0600. The file has two lines: a header with the fingerprint and the expiry, then the token. A file of another refresh token is deleted after reading only its header. - The file is written as a fresh temporary file in the same directory, created exclusively with an
unpredictable name, mode 0600 and without following a symbolic link, then renamed over the token file. If
the write fails, the temporary file is emptied and removed, and
TokenFileErroris raised. - The file is refused unread (
TokenFileUnsafe, and the client releases the egress and makes no call) when it is a symbolic link, not a regular file, not owned by the current user, has a group or other permission bit, or cannot be opened. A safe file whose header or token line cannot be read is deleted, and a new token is obtained. - A token with 30 minutes or less left is renewed before the next call.
- Of the claims, only
expandtokenTypeare read. A token without a readableexpis assumed to last the documented 24 hours. - No log line, exception message or argument, exception chain, local variable of a library frame in a
traceback,
repr()orFetchRecordholds a token, a claim or anAuthorizationheader. Log lines are built from the fields inclient.LOG_FIELDSonly: mode, endpoint, kind, status, duration, both correlation IDs, codes,Retry-After, item counts and outcome counts.
Tests never call the real API
While pytest is loaded or ELO_FORBID_LIVE_API=1 is set, the client calls only a local destination: a
loopback address, localhost, a single-label name (a container of the test network) or a name under
.test, .example, .invalid or .localhost. The host is compared as a resolver sees it: without user
info and port, percent-decoded, IDNA-mapped, lower case and without a trailing dot, so
https://API.Eloverblik.dk.:443/ is the real API. Anything else, the real API above all, raises
LiveApiForbidden when the client is made and again before every send. Environment proxies are ignored
under test, and redirects are never followed. elo_sources.eloverblik.testing provides:
SimClock, a simulated clock with a separate elapsed counter andjump()for wall-clock corrections;ReplayServer, a local HTTP server that answers fromfixtures/contract/, issues tokens generated at run time, and logs every request with its arrival time;KillAfterSendandPauseBeforeSend, transports that kill or pause the caller;RecordingObserver;Harness, which builds clients in both modes.
B06b and B07 repeat PT-10 and PT-15 to PT-18 with these.
Kilde: docs/eloverblik-client.md i løsningens
repository.