zeitreihermodels

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 17 Imported by: 0

README

zeitreiher-models

Go Tests Go Lint Go Reference Python Tests Python Coverage Python Lint Python Formatting Proto

Public data models of the Zeitreiher API, version 1: a read-only API over SAP IS-U EDM profile values (Lastgänge) — profile metadata plus many [from, to) intervals with values.

This repository holds

  • Go structs (package zeitreihermodels, module github.com/hochfrequenz/zeitreiher-models),
  • Python frozen pydantic v2 models (package zeitreiher_models),
  • the shared fixtures in testdata/ that define the JSON contract, and
  • the gRPC contract in proto/zeitreiher/v1.

Everything is written by hand. No code is generated and no generated code is committed: every type, validator and (un)marshaller is ordinary, readable code. Both languages parse every valid fixture, write it back and compare the result with the fixture, and reject every invalid fixture — so Go and Python agree on the contract by construction.

The contract in short

Topic Rule
Intervals Half-open everywhere: [from, to); from must be before to.
Request timestamps RFC 3339, whole seconds, explicit offset (Z or ±hh:mm), ASCII digits only, hours 00–23. The instant must lie in the years 1900–9999 in UTC, so that it can be echoed in a response (1900-01-01T00:00:00+01:00 is 1899 in UTC and rejected). Kept as sent (+02:00 stays +02:00). A missing offset (2026-01-01T00:00:00) and the "unknown offset" -00:00 are rejected.
Response timestamps RFC 3339, whole seconds, always UTC (Z). Instants built in code must survive the round trip (no offsets with seconds, years 1900–9999).
Values Already-scaled decimal strings in their shortest canonical form ("160", "0.022", "25.25", "-3.5"), never JSON numbers. No exponent, no plus sign, no leading zeros, no trailing zeros after the decimal point ("160.0" is rejected: after parsing it equals "160"), no negative zero.
Profile numbers In requests 1–18 digits, leading zeros allowed, not all zeros; in responses without leading zeros.
Units unit is a canonical unit code: a UN/ECE Recommendation 20 code such as KWH, MWH or KVR (2 or 3 upper-case ASCII letters or digits, strict). Requests send canonical codes; the server maps them to the customer's SAP unit (an unknown code is a 400). In series records unit is always present and null when the SAP unit has no mapping; the series is delivered anyway. unit_raw (series records) is the SAP unit key (T006 MSEHI) as SAP delivers it, mapped or not, read leniently: any non-empty text of at most 30 characters (code points) without control characters (Unicode Cc).
Series role Every series record carries role, the role of its profile assignment (SAP EPROFASS role, e.g. "0001"; any non-empty text), or null when the series was not resolved through a role (e.g. by: profile). For by: malo the roles to deliver are configurable (default: all).
Selectors {"by":"profile","profile":"…"}, {"by":"malo","malo":"<11 digits>"}, or a customer resolver {"by":"<snake_case name>","params":{"<key>":"<string>"}}.
Version selector Exactly one of {"current":{}} (default) or {"number":N}; no null members. v1 has no as-of selector: {"as_of":…} is rejected. {"number":N} returns the current values overlaid with the stored values of versions ≥ N (the lowest wins), only inside N's covered range (gaps outside). Each value record says its source: "version":<n> for a stored version row, "version":null for a current value.
Intervals (interval) Sub-daily ISO 8601 durations in minutes: PT15M, PT60M, … Hours are written in minutes: PT60M, never PT1H (rejected, so that every interval has one spelling).
Text Every string is valid Unicode and is written unchanged. Parsers reject invalid UTF-8 and unpaired \uD800–\uDFFF escapes. Go refuses to marshal a string that is not valid UTF-8 (instead of writing U+FFFD); Python rejects a string with a lone surrogate when the model is built (ValidationError).
Unknown keys Requests reject them (a typo fails loudly). Responses ignore them (additive server changes do not break older clients).
Duplicate keys Not rejected: when an object repeats a key, the last occurrence wins and earlier ones are ignored without validation ({"unit":"K H","unit":"MWH"} is read as "MWH"), in both languages and on both sides. Producers must not write duplicate keys; the models never do. Pinned by the *duplicate_key_last_wins* fixtures.
null Request fields that are optional may be omitted or null. In responses, series.role, series.unit, value.version, end.next, version.to and version.created_at are always present and may be null; other optional response fields are omitted when unset.
Error codes Request-level codes in the error envelope {"error":{"code","message","request_id"?}} — btpingo's vocabulary (invalid_request, unauthorized, forbidden, not_found, method_not_allowed, request_too_large, upstream_unreachable, internal), shared by the Hochfrequenz BTP services, plus cursor_invalid, cursor_mismatch, cursor_expired, cursor_stale and upstream_timeout; record-level codes in error records and resolve/versions results. The known codes are listed in testdata/error_codes.json. Strict on write, lenient on read: parsers accept unknown snake_case codes so that a newer server does not break older clients (Go IsKnown(), Python `RecordErrorCode
NDJSON One record per line, lines end with \n (the last one optionally), no \r, no blank lines. A response that does not end with exactly one end record was cut off and must be treated as a failure. The end record's series, values and errors count the records on this page only; a series record re-sent at the start of a continuation page counts again.

The full design lives in the zeitreiher-go repository (docs/superpowers/specs/2026-10-27-zeitreiher-design.md).

Go

go get github.com/hochfrequenz/zeitreiher-models
import zrm "github.com/hochfrequenz/zeitreiher-models"

cet := time.FixedZone("CET", 3600)
req := zrm.QueryRequest{
	Select:   []zrm.Selector{zrm.MaLoSelector("87253749908"), zrm.ProfileSelector("50000000000056")},
	From:     time.Date(2026, 1, 1, 0, 0, 0, 0, cet),
	To:       time.Date(2026, 2, 1, 0, 0, 0, 0, cet),
	Interval: "PT60M",
}
body, err := json.Marshal(req) // validates; an invalid request does not marshal

records, err := zrm.ReadStream(resp.Body) // errors.Is(err, zrm.ErrMissingEnd) for a cut-off stream
for _, rec := range records {
	switch r := rec.(type) {
	case *zrm.SeriesRecord:
	case *zrm.ValueRecord: // r.Value is a zrm.Decimal (string)
	case *zrm.ErrorRecord: // r.Code.IsKnown()
	case *zrm.EndRecord: // r.Next != nil → request the next page with Cursor = *r.Next
	}
}

ReadRecords(io.Reader) yields records one by one (iter.Seq2[Record, error]) for streaming; WriteRecord writes one NDJSON line. Every type validates itself in UnmarshalJSON and refuses to marshal when it is invalid.

Python

pip install zeitreiher-models  # once published to PyPI
from datetime import datetime, timedelta, timezone

from zeitreiher_models import MaLoSelector, QueryRequest, ValueRecord, iter_records, read_stream

cet = timezone(timedelta(hours=1))
request = QueryRequest(
    select=[MaLoSelector(malo="87253749908")],
    from_=datetime(2026, 1, 1, tzinfo=cet),
    to=datetime(2026, 2, 1, tzinfo=cet),
    interval="PT60M",
)
body = request.model_dump_json()  # {"select":[…],"from":"2026-01-01T00:00:00+01:00",…}

for record in read_stream(response_bytes):  # raises MissingEndError for a cut-off stream
    if isinstance(record, ValueRecord):
        print(record.from_, record.decimal)  # decimal.Decimal, no float rounding

from is a Python keyword, so the attribute is from_; the JSON key is always from.

Fixtures

testdata/
  error_codes.json                       the known request- and record-level codes
  query_request/{valid,invalid}/         request bodies (DST days, +02:00 vs Z, naive timestamps, custom selectors, versions, …)
  resolve_request/, versions_request/
  records/{valid,invalid}/               single NDJSON records, one valid fixture per record-level error code
  streams/{valid,invalid}/               whole NDJSON responses (DST days with 92/100 quarter hours, gaps, versions, paging, …)
  resolve_response/, versions_response/
  error_envelope/{valid,invalid}/        one valid fixture per request-level error code
  records/read_only/, error_envelope/read_only/
                                         unknown error codes: they parse, but writing them is refused
  system_info/

X.canonical.json next to X.json is the expected re-serialization when it differs from the input (e.g. +00:00 becomes Z, "cursor": null is omitted, unknown response keys are dropped). Consumers in other languages (the Go service, future Rust/C#/TS models) should run the same fixtures.

testdata/serialized.golden pins the exact bytes both languages write for every valid fixture (<fixture>\t<JSON> per line), so Go and Python output is byte-for-byte identical: compact JSON, keys in model order, map keys (params, attributes) sorted, and Go's string escaping — <, >, &, U+2028 and U+2029 are written as <, >, &, 
, 
; all other non-ASCII characters are written as UTF-8. Python's model_dump_json() and dump_record() apply that escaping; in Go, json.Marshal, MarshalRecord and a default json.Encoder produce it (an encoder with SetEscapeHTML(false) would not).

Every invalid fixture has an entry in testdata/invalid_reasons.json, so that a fixture cannot pass by being rejected for the wrong reason:

  • go: a substring of the Go error (the field path and the failed rule);
  • python: the pydantic error that must be among ValidationError.errors() — its loc (joined with .), its type and, only for the error types whose messages the models write themselves (value_error, instant, unknown_key, version_selector), msg, a substring of its message. pydantic's own messages are not compared, so rewording them in a pydantic upgrade does not break the fixtures.
Regenerating the pinned files
  • serialized.golden — after an intended change to the output (or a new valid fixture), run go test -run Golden -update ., review the diff, then uv run pytest unittests to confirm that Python writes the same bytes. The file is only ever written by Go; Python compares against it.
  • invalid_reasons.json — maintained by hand, not generated, because each entry states the intended reason. For a new invalid fixture, the failing Go test prints the actual error (go test -run InvalidFixtures .) and the failing Python test prints a ready-made python entry (uv run pytest unittests -k invalid_fixture); check that both name the rule the fixture is about before adding them. Keep the file sorted, two-space indented and ASCII-only (json.dumps(..., indent=2, sort_keys=True, ensure_ascii=True)).
  • After a pydantic upgrade — run uv run pytest unittests. A failing invalid_fixture test means that pydantic changed an error's loc or type (messages are not compared), or that a fixture is now rejected for a different reason; compare the printed errors() with the entry and update the entry only if the fixture is still rejected for the intended reason. serialized.golden failures after an upgrade mean that the output bytes changed and need a fix in the models, not a new golden file.

gRPC

proto/zeitreiher/v1/*.proto (package zeitreiher.v1, service SeriesService with Query, Resolve, ListVersions, System) is the published gRPC contract. Field names equal the JSON keys. Request timestamps are RFC 3339 strings (so the explicit-offset rule holds for gRPC too); response timestamps are google.protobuf.Timestamp. Conformance with the JSON contract is defined through the hand-written models (fixture → model → proto → model → JSON), not through protojson. Generate code in the consuming project, e.g. with buf managed mode.

A failed call (and a Query stream cut off before its EndRecord) ends with a gRPC status that carries a google.rpc.ErrorInfo detail with reason = the public request-level code and domain = "zeitreiher.hochfrequenz.de"; series_service.proto lists the status code for each code. Clients switch on reason.

Versioning

v1 is in the URL path (/api/v1/…), the proto package (zeitreiher.v1) and the models' major version. Additive changes (new optional fields, new error codes) stay in v1; breaking changes need v2.

The Go package zeitreihermodels lives at the repository root (import path github.com/hochfrequenz/zeitreiher-models); there is no v1 sub-package. Its major version follows Go module versioning: v1 is released as tags v1.x.y of this module path, and a breaking v2 becomes the module github.com/hochfrequenz/zeitreiher-models/v2 (tags v2.x.y). The Python package takes its version from the same tags.

Development

go test ./...                      # Go
golangci-lint run && golangci-lint fmt --diff
uv sync --group dev                # Python
uv run pytest unittests
uv run ruff check src unittests && uv run ruff format --check .
uv run mypy --strict src/zeitreiher_models unittests
buf lint && buf build && buf format --diff --exit-code   # buf v1.75.0

The Go tests (fixtures_test.go) and the Python tests (unittests/test_fixtures.py) use the same table of fixture kinds; a new fixture directory must be added to both. unittests/test_proto_contract.py fails when a model and its proto message disagree on field names.

License

MIT

Documentation

Overview

Package zeitreihermodels holds the hand-written public data models of the Zeitreiher API, version 1.

Zeitreiher is a read-only API over SAP IS-U EDM profile values (Lastgänge). The contract is the JSON form of the types in this package, pinned by the shared fixtures in testdata/, which the Go and the Python models both parse and round-trip. The gRPC contract lives in proto/zeitreiher/v1.

The package lives at the repository root; its major version follows Go module versioning, so a breaking v2 is the module github.com/hochfrequenz/zeitreiher-models/v2 (spec §3.4).

Nothing in this package is generated. Every type validates itself when it is unmarshalled and refuses to marshal when it is invalid, so a value that leaves or enters a program through these types always satisfies the contract:

  • Request timestamps are RFC 3339 with whole seconds and an explicit offset (Z or ±hh:mm). Timestamps without an offset and the "unknown offset" -00:00 are rejected.
  • Response timestamps are RFC 3339 with whole seconds in UTC (Z).
  • Intervals are half-open: [from, to), and from must be before to.
  • Values are decimal strings, already scaled, in shortest canonical form ("160", "0.022"; never "160.0"), never JSON numbers.
  • Error codes are strict on write, lenient on read: unknown snake_case codes parse, only the public codes are written.
  • Requests reject unknown keys; responses ignore them, so additive server changes do not break older clients.

Index

Constants

View Source
const (
	RecordTypeSeries = "series"
	RecordTypeValue  = "value"
	RecordTypeError  = "error"
	RecordTypeEnd    = "end"
)

Record types, the value of the "type" key of every NDJSON line.

View Source
const (
	SelectorByProfile = "profile"
	SelectorByMaLo    = "malo"
)

Selector kinds known to every Zeitreiher installation. Any other kind is a custom selector that a customer resolver implements.

Variables

View Source
var ErrMissingEnd = errors.New("response stream does not end with an end record")

ErrMissingEnd is returned by ReadStream when a response does not end with exactly one end record. Such a response was cut off and must be treated as a failure (spec §4.3).

Functions

func MarshalRecord

func MarshalRecord(rec Record) ([]byte, error)

MarshalRecord validates rec and returns its JSON form without a trailing newline.

func ReadRecords

func ReadRecords(r io.Reader) iter.Seq2[Record, error]

ReadRecords yields the records of an NDJSON stream. Every line must hold one record; the final newline is optional. Blank lines and carriage returns are errors. Iteration stops after the first error. ReadRecords does not check for the end record; use ReadStream for complete responses.

func WriteRecord

func WriteRecord(w io.Writer, rec Record) error

WriteRecord writes rec as one NDJSON line.

Types

type Assignment

type Assignment struct {
	Profile string
	From    *time.Time
	To      *time.Time
	Error   *ResultError
}

Assignment is one profile assignment of a resolve result (spec §4.4). Either From and To are set (the assignment, cut to the request window) or Error is set (e.g. access_denied); an assignment with an error may still carry its window.

func (Assignment) MarshalJSON

func (a Assignment) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the assignment.

func (*Assignment) UnmarshalJSON

func (a *Assignment) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the assignment; unknown keys (such as versions) are ignored.

type Decimal

type Decimal string

Decimal is an already-scaled decimal number in its shortest canonical string form, e.g. "160", "0.022", "25.25" or "-3.5".

Values are strings on the wire so that no client loses precision by parsing them as floats. The accepted syntax is an optional minus, an integer part without leading zeros and an optional fractional part without trailing zeros: ^-?(0|[1-9][0-9]*)(\.[0-9]+)?$, and the fraction must not end in 0. Exponents, a plus sign, negative zero, trailing zeros ("160.0", "0.0220") and JSON numbers are rejected: after parsing, 160.0 and 160 are the same number, so the wire carries one spelling.

func (Decimal) MarshalJSON

func (d Decimal) MarshalJSON() ([]byte, error)

MarshalJSON writes d as a JSON string after validating it.

func (*Decimal) UnmarshalJSON

func (d *Decimal) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts a JSON string with a valid decimal only.

func (Decimal) Validate

func (d Decimal) Validate() error

Validate checks the syntax of d.

type EndRecord

type EndRecord struct {
	// Series, Values and Errors count the series, value and error records on this page only (not
	// the whole result). A series record re-sent at the start of a continuation page counts again.
	Series, Values, Errors int
	// Next is the cursor for the next page, or nil when the result is complete.
	Next *string
}

EndRecord closes a successful response. A response without an end record is incomplete and must be treated as a failure.

func (*EndRecord) MarshalJSON

func (r *EndRecord) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the record; a nil Next is written as null.

func (*EndRecord) RecordType

func (*EndRecord) RecordType() string

RecordType returns "end".

func (*EndRecord) UnmarshalJSON

func (r *EndRecord) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the record.

func (*EndRecord) Validate

func (r *EndRecord) Validate() error

Validate checks the record.

type ErrorDetail

type ErrorDetail struct {
	// Code is stable and machine-readable; clients switch on it, never on Message.
	Code RequestErrorCode `json:"code"`
	// Message is a human-readable explanation.
	Message string `json:"message"`
	// RequestID correlates the response with server logs; empty when unknown (omitted on the wire).
	RequestID string `json:"request_id,omitempty"`
}

ErrorDetail is the content of an ErrorEnvelope.

func (*ErrorDetail) UnmarshalJSON

func (d *ErrorDetail) UnmarshalJSON(b []byte) error

UnmarshalJSON enforces the presence rules of the detail.

type ErrorEnvelope

type ErrorEnvelope struct {
	Error ErrorDetail `json:"error"`
}

ErrorEnvelope is the body of every failed (non-2xx) HTTP response: {"error":{"code":"…","message":"…","request_id":"…"}}. It has the shape of btpingo.ErrorEnvelope.

func (ErrorEnvelope) MarshalJSON

func (e ErrorEnvelope) MarshalJSON() ([]byte, error)

MarshalJSON validates before writing.

func (*ErrorEnvelope) UnmarshalJSON

func (e *ErrorEnvelope) UnmarshalJSON(b []byte) error

UnmarshalJSON enforces the presence rules of the envelope.

func (ErrorEnvelope) Validate

func (e ErrorEnvelope) Validate() error

Validate checks the envelope.

type ErrorRecord

type ErrorRecord struct {
	// Selector is the index of the request selector the problem belongs to.
	Selector int
	// Select echoes the request selector.
	Select Selector
	// Profile is set where the problem concerns one profile assignment; empty otherwise.
	Profile string
	// Code says what went wrong; see the RecordError* constants.
	Code RecordErrorCode
}

ErrorRecord reports a per-selector or per-assignment problem; the stream continues.

func (*ErrorRecord) MarshalJSON

func (r *ErrorRecord) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the record; an empty Profile is omitted.

func (*ErrorRecord) RecordType

func (*ErrorRecord) RecordType() string

RecordType returns "error".

func (*ErrorRecord) UnmarshalJSON

func (r *ErrorRecord) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the record.

func (*ErrorRecord) Validate

func (r *ErrorRecord) Validate() error

Validate checks the record.

type QueryRequest

type QueryRequest struct {
	// Select lists one or more selectors; results refer to them by index.
	Select []Selector
	// From and To bound the half-open window [From, To). Their offsets are kept on the wire.
	From, To time.Time
	// Version is optional; nil means the current values.
	Version *VersionSelector
	// Interval is optional, e.g. "PT15M"; empty means the profile's own interval.
	Interval string
	// Unit is optional, a canonical unit code (UN/ECE Rec. 20) such as "KWH", "MWH" or "KVR"; the server
	// maps it to the customer's SAP unit. Empty means the profile's own unit.
	Unit string
	// Cursor continues a previous response (its end record's next); empty starts at the beginning.
	Cursor string
}

QueryRequest is the body of POST /api/v1/series/query (and QUERY /api/v1/series), spec §4.1.

func (QueryRequest) MarshalJSON

func (q QueryRequest) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the request; unset optional fields are omitted.

func (*QueryRequest) UnmarshalJSON

func (q *QueryRequest) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the request. Unknown keys are rejected; null optional fields count as absent.

func (QueryRequest) Validate

func (q QueryRequest) Validate() error

Validate checks the request.

type Record

type Record interface {
	// RecordType returns the value of the "type" key.
	RecordType() string
	// Validate checks the record.
	Validate() error
	// contains filtered or unexported methods
}

Record is one line of a query response (NDJSON) and one gRPC Record message. It is one of *SeriesRecord, *ValueRecord, *ErrorRecord or *EndRecord.

func ParseRecord

func ParseRecord(line []byte) (Record, error)

ParseRecord parses one NDJSON line (without its trailing newline) into a record.

func ReadStream

func ReadStream(r io.Reader) ([]Record, error)

ReadStream reads a complete response and checks that its last record, and only its last record, is an end record. It returns ErrMissingEnd (wrapped) otherwise.

type RecordErrorCode

type RecordErrorCode string

RecordErrorCode is a per-selector or per-assignment error code. It appears in NDJSON error records and in the error objects of resolve/versions results; the rest of the response continues.

const (
	RecordErrorSelectorNotFound        RecordErrorCode = "selector_not_found"
	RecordErrorNoAssignment            RecordErrorCode = "no_assignment"
	RecordErrorUnknownSelector         RecordErrorCode = "unknown_selector"
	RecordErrorBadSelector             RecordErrorCode = "bad_selector"
	RecordErrorAccessDenied            RecordErrorCode = "access_denied"
	RecordErrorProfileNotFound         RecordErrorCode = "profile_not_found"
	RecordErrorProfileTimeZoneMissing  RecordErrorCode = "profile_time_zone_missing"
	RecordErrorIntervalSizeUnsupported RecordErrorCode = "interval_size_unsupported"
	RecordErrorWindowUnaligned         RecordErrorCode = "window_unaligned"
	RecordErrorAssignmentUnaligned     RecordErrorCode = "assignment_unaligned"
	RecordErrorVersionNotFound         RecordErrorCode = "version_not_found"
	// RecordErrorVersionDeleted: the requested {"number":N} names a version that is flagged as deleted
	// (it is still listed by the versions endpoint, with deleted: true).
	RecordErrorVersionDeleted       RecordErrorCode = "version_deleted"
	RecordErrorConversionNotAllowed RecordErrorCode = "conversion_not_allowed"
	RecordErrorAmbiguousLocalTime   RecordErrorCode = "ambiguous_local_time"
	RecordErrorBadiFailed           RecordErrorCode = "badi_failed"
)

Record-level error codes (spec §4.3, consolidated list).

func AllRecordErrorCodes

func AllRecordErrorCodes() []RecordErrorCode

AllRecordErrorCodes returns every record-level error code in specification order.

func (RecordErrorCode) IsKnown

func (c RecordErrorCode) IsKnown() bool

IsKnown reports whether c is one of the record-level codes this version of the models knows. Parsing accepts unknown snake_case codes so that a newer server does not break older clients.

func (RecordErrorCode) MarshalJSON

func (c RecordErrorCode) MarshalJSON() ([]byte, error)

MarshalJSON writes only the public codes: error codes are strict on write, lenient on read.

func (*RecordErrorCode) UnmarshalJSON

func (c *RecordErrorCode) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts any snake_case code; use IsKnown to tell known from unknown codes.

func (RecordErrorCode) Validate

func (c RecordErrorCode) Validate() error

Validate checks the code syntax (snake_case). It accepts unknown codes, as parsing does.

type RequestErrorCode

type RequestErrorCode string

RequestErrorCode is a request-level error code. It appears in the error envelope of an HTTP response that failed as a whole (before any NDJSON record was written).

const (
	RequestErrorInvalidRequest      RequestErrorCode = "invalid_request"
	RequestErrorUnauthorized        RequestErrorCode = "unauthorized"
	RequestErrorForbidden           RequestErrorCode = "forbidden"
	RequestErrorNotFound            RequestErrorCode = "not_found"
	RequestErrorMethodNotAllowed    RequestErrorCode = "method_not_allowed"
	RequestErrorRequestTooLarge     RequestErrorCode = "request_too_large"
	RequestErrorUpstreamUnreachable RequestErrorCode = "upstream_unreachable"
	RequestErrorInternal            RequestErrorCode = "internal"
	RequestErrorCursorInvalid       RequestErrorCode = "cursor_invalid"
	RequestErrorCursorMismatch      RequestErrorCode = "cursor_mismatch"
	RequestErrorCursorExpired       RequestErrorCode = "cursor_expired"
	RequestErrorCursorStale         RequestErrorCode = "cursor_stale"
	RequestErrorUpstreamTimeout     RequestErrorCode = "upstream_timeout"
)

Request-level error codes (spec §4.3, consolidated list). The first eight are btpingo's request-level vocabulary (btpingo.ErrorCode in httperr.go), shared by the Hochfrequenz BTP services; the cursor codes and upstream_timeout are Zeitreiher's own.

func AllRequestErrorCodes

func AllRequestErrorCodes() []RequestErrorCode

AllRequestErrorCodes returns every request-level error code in specification order.

func (RequestErrorCode) IsKnown

func (c RequestErrorCode) IsKnown() bool

IsKnown reports whether c is one of the request-level codes this version of the models knows. Parsing accepts unknown snake_case codes so that a newer server does not break older clients.

func (RequestErrorCode) MarshalJSON

func (c RequestErrorCode) MarshalJSON() ([]byte, error)

MarshalJSON writes only the public codes: error codes are strict on write, lenient on read.

func (*RequestErrorCode) UnmarshalJSON

func (c *RequestErrorCode) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts any snake_case code; use IsKnown to tell known from unknown codes.

func (RequestErrorCode) Validate

func (c RequestErrorCode) Validate() error

Validate checks the code syntax (snake_case). It accepts unknown codes, as parsing does.

type ResolveRequest

type ResolveRequest = WindowRequest

ResolveRequest is the body of POST /api/v1/series/resolve.

type ResolveResponse

type ResolveResponse struct {
	Results []ResolveResult `json:"results"`
}

ResolveResponse is the body of a successful resolve response: {"results":[…]}.

func (ResolveResponse) MarshalJSON

func (r ResolveResponse) MarshalJSON() ([]byte, error)

MarshalJSON writes {"results":[…]}; nil Results is written as [].

func (*ResolveResponse) UnmarshalJSON

func (r *ResolveResponse) UnmarshalJSON(b []byte) error

UnmarshalJSON parses the response.

type ResolveResult

type ResolveResult struct {
	Selector    int
	Select      Selector
	Assignments []Assignment
	Error       *ResultError
}

ResolveResult is the outcome for one request selector of the resolve endpoint: either Assignments (possibly empty) or Error.

func (ResolveResult) MarshalJSON

func (r ResolveResult) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the result.

func (*ResolveResult) UnmarshalJSON

func (r *ResolveResult) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the result.

type ResultError

type ResultError struct {
	Code RecordErrorCode `json:"code"`
}

ResultError is the error object of a resolve/versions result or assignment: {"code":"…"}.

func (ResultError) MarshalJSON

func (r ResultError) MarshalJSON() ([]byte, error)

MarshalJSON validates before writing.

func (*ResultError) UnmarshalJSON

func (r *ResultError) UnmarshalJSON(b []byte) error

UnmarshalJSON enforces the presence rules.

type Selector

type Selector struct {
	By      string
	Profile string
	MaLo    string
	Params  map[string]string
}

Selector names the business object whose profile assignments are queried. It is a union over By:

{"by":"profile","profile":"50000000000056"}     – a profile number
{"by":"malo","malo":"87253749908"}              – a market location
{"by":"<name>","params":{"<key>":"<string>"}}  – a customer resolver

Build selectors with ProfileSelector, MaLoSelector or CustomSelector. Only the fields of the variant named by By are used; the others must be empty.

func CustomSelector

func CustomSelector(by string, params map[string]string) Selector

CustomSelector selects via a customer resolver named by. params may be nil.

func MaLoSelector

func MaLoSelector(malo string) Selector

MaLoSelector selects the profiles assigned to a market location.

func ProfileSelector

func ProfileSelector(profile string) Selector

ProfileSelector selects a profile by number (leading zeros allowed).

func (Selector) IsCustom

func (s Selector) IsCustom() bool

IsCustom reports whether s is a custom selector.

func (Selector) MarshalJSON

func (s Selector) MarshalJSON() ([]byte, error)

MarshalJSON writes the keys of the variant only, after validating with the request rules.

func (*Selector) UnmarshalJSON

func (s *Selector) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts exactly the keys of the variant named by "by" (request rules).

func (Selector) Validate

func (s Selector) Validate() error

Validate checks the variant and its fields with the request rules (leading zeros allowed).

type SeriesRecord

type SeriesRecord struct {
	// Series numbers the series of a response, starting at 1 and continuing across pages.
	Series int
	// Selector is the index of the request selector this series belongs to.
	Selector int
	// Select echoes the request selector (profile numbers without leading zeros).
	Select Selector
	// Profile is the SAP profile number, without leading zeros.
	Profile string
	// Role is the role of the profile assignment (SAP EPROFASS role, e.g. "0001"), or nil when the series
	// was not resolved through a role (e.g. by: profile). The Resolver BAdI may override it.
	Role *string
	// From and To bound the assignment, cut to the request window.
	From, To time.Time
	// Unit is the canonical unit code (UN/ECE Rec. 20, e.g. "KWH") of the delivered values (after any
	// conversion), or nil when the SAP unit has no mapping. The series is delivered either way.
	Unit *string
	// UnitRaw is the SAP unit key (T006 MSEHI) as SAP delivers it, mapped or not: any non-empty text of
	// at most 30 characters without control characters.
	UnitRaw string
	// Interval is that of the delivered values (after any conversion).
	Interval string
	// Attributes come from the customer's Metadata BAdI; never nil after unmarshalling.
	Attributes map[string]string
	// Versions lists the profile versions overlapping the series; never nil after unmarshalling.
	Versions []Version
}

SeriesRecord opens a series: one profile assignment of one selector, cut to the request window.

func (*SeriesRecord) MarshalJSON

func (r *SeriesRecord) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the record with "type" first; a nil Role or Unit is written as null.

func (*SeriesRecord) RecordType

func (*SeriesRecord) RecordType() string

RecordType returns "series".

func (*SeriesRecord) UnmarshalJSON

func (r *SeriesRecord) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the record.

func (*SeriesRecord) Validate

func (r *SeriesRecord) Validate() error

Validate checks the record.

type SystemInfo

type SystemInfo struct {
	// ServiceVersion is the version of the Zeitreiher service (Go).
	ServiceVersion string
	// AbapPackageVersion is the version of the ABAP package /HFQ/ZEITREIHER.
	AbapPackageVersion string
	// SID and Client identify the SAP system.
	SID    string
	Client string
	// Release is the SAP release.
	Release string
	// BusinessTimeZone is the configured SAP time zone code, e.g. "CET".
	BusinessTimeZone string
	// Intervals lists the supported request intervals, e.g. ["PT15M","PT60M"].
	Intervals []string
}

SystemInfo is the body of GET /api/v1/system (spec §4.4).

func (SystemInfo) MarshalJSON

func (s SystemInfo) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the system info.

func (*SystemInfo) UnmarshalJSON

func (s *SystemInfo) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the system info.

func (SystemInfo) Validate

func (s SystemInfo) Validate() error

Validate checks the system info.

type ValueRecord

type ValueRecord struct {
	// Series is the number of the series record this value belongs to.
	Series int
	// From and To bound the value's interval.
	From, To time.Time
	// Value is the already-scaled decimal value.
	Value Decimal
	// Status holds the active SAP status codes overlapping the interval, sorted; never nil after
	// unmarshalling.
	Status []string
	// Version is the source of the value: the number of the stored version row it came from, or nil
	// when it is a current value. With {"number":N} a series mixes both: current values overlaid with
	// the stored values of versions >= N (the lowest wins), only inside N's covered range.
	Version *int
}

ValueRecord is one value of a series for the half-open interval [From, To).

func (*ValueRecord) MarshalJSON

func (r *ValueRecord) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the record; a nil Version is written as null.

func (*ValueRecord) RecordType

func (*ValueRecord) RecordType() string

RecordType returns "value".

func (*ValueRecord) UnmarshalJSON

func (r *ValueRecord) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the record.

func (*ValueRecord) Validate

func (r *ValueRecord) Validate() error

Validate checks the record.

type Version

type Version struct {
	// Number is the SAP version number (CVERSNO), at least 1.
	Number int
	// From and To bound the covered range [From, To); To is nil for an open end.
	From time.Time
	To   *time.Time
	// CreatedAt is the creation instant; nil when it cannot be determined, then CreatedAtUnknown is true.
	CreatedAt        *time.Time
	CreatedAtUnknown bool
	// Reason and Description are SAP's VERSREASON and VERSDESCR; either may be empty.
	Reason      string
	Description string
	// Deleted is true for versions flagged as deleted in SAP. They are still listed; querying their
	// values gives an error record with code version_deleted.
	Deleted bool
}

Version describes one EDM profile version that overlaps a series (spec §4.2, §5).

func (Version) MarshalJSON

func (v Version) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the version; To and CreatedAt are written as null when nil.

func (*Version) UnmarshalJSON

func (v *Version) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the version.

func (Version) Validate

func (v Version) Validate() error

Validate checks the version.

type VersionSelector

type VersionSelector struct {
	Current bool
	Number  *int
}

VersionSelector chooses which values a query returns (spec §5). Exactly one form is set:

{"current":{}}   – the current values (the default when omitted)
{"number":3}     – version 3 as SAP rebuilds it: the current values overlaid with the stored
                   values of versions >= 3 (the lowest version wins), only inside version 3's
                   covered range; outside it the series has gaps

v1 has no as-of selector; {"as_of":…} is rejected as an unknown key. Build it with CurrentVersion or VersionNumber.

func CurrentVersion

func CurrentVersion() VersionSelector

CurrentVersion selects the current values.

func VersionNumber

func VersionNumber(n int) VersionSelector

VersionNumber selects version n (see VersionSelector).

func (VersionSelector) MarshalJSON

func (v VersionSelector) MarshalJSON() ([]byte, error)

MarshalJSON writes the single set form.

func (*VersionSelector) UnmarshalJSON

func (v *VersionSelector) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts exactly one of the two forms.

func (VersionSelector) Validate

func (v VersionSelector) Validate() error

Validate checks that exactly one form is set and that it is valid.

type VersionedAssignment

type VersionedAssignment struct {
	Assignment
	Versions []Version
}

VersionedAssignment is one profile assignment of a versions result: an Assignment plus the overlapping versions. Versions is written as [] when there are none and omitted with an error.

func (VersionedAssignment) MarshalJSON

func (v VersionedAssignment) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the assignment.

func (*VersionedAssignment) UnmarshalJSON

func (v *VersionedAssignment) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the assignment; versions is required unless error is set.

type VersionsRequest

type VersionsRequest = WindowRequest

VersionsRequest is the body of POST /api/v1/series/versions.

type VersionsResponse

type VersionsResponse struct {
	Results []VersionsResult `json:"results"`
}

VersionsResponse is the body of a successful versions response: {"results":[…]}.

func (VersionsResponse) MarshalJSON

func (r VersionsResponse) MarshalJSON() ([]byte, error)

MarshalJSON writes {"results":[…]}; nil Results is written as [].

func (*VersionsResponse) UnmarshalJSON

func (r *VersionsResponse) UnmarshalJSON(b []byte) error

UnmarshalJSON parses the response.

type VersionsResult

type VersionsResult struct {
	Selector    int
	Select      Selector
	Assignments []VersionedAssignment
	Error       *ResultError
}

VersionsResult is the outcome for one request selector of the versions endpoint.

func (VersionsResult) MarshalJSON

func (r VersionsResult) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the result.

func (*VersionsResult) UnmarshalJSON

func (r *VersionsResult) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the result.

type WindowRequest

type WindowRequest struct {
	Select   []Selector
	From, To time.Time
}

WindowRequest is the body of the resolve and versions endpoints (spec §4.4): selectors and a window, nothing else.

func (WindowRequest) MarshalJSON

func (w WindowRequest) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the request.

func (*WindowRequest) UnmarshalJSON

func (w *WindowRequest) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the request; unknown keys (e.g. version, cursor) are rejected.

func (WindowRequest) Validate

func (w WindowRequest) Validate() error

Validate checks the request.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL