zeitreihermodels

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 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 K3 (K3 = kvarh) (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; GET /api/v1/system lists the codes the system can map in units). 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 and resolve/versions assignments) 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). See the paragraph below the table for a missing raw unit and for IsUnitCode.
Series role Every series record and every resolve/versions assignment without error 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).
Assignments Resolve and versions assignments describe their profile like the series record: role and unit are always written (null when unset) and unit_raw is required, with the same shapes as in series. An assignment with error may omit all three.
System info GET /api/v1/system reports units (the canonical unit codes the system can map) and caps (limits, all at least 1: max_window_seconds and max_values bound one internal SAP values call and the service splits a query window accordingly; max_resolve_window_seconds is the longest request window the service accepts for query, resolve and versions, a longer window is a 400 invalid_request; versions and resolve are not split and have no value cap; window_too_large never reaches public clients). The optional abap_* members are described below the table.
Selectors {"by":"profile","profile":"…"}, {"by":"malo","malo":"<11 digits>"}, or a customer resolver {"by":"<snake_case name>","params":{"<key>":"<string>"}} (by is 1 to 30 characters).
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, assignment.role and assignment.unit (without error), 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.

Units, in detail: unit_raw is always required and never null. A backend unit key that is empty (or only control characters) cannot be represented in a series record, so that series is reported as an error record with the code unit_missing instead. The series_unit_raw_empty, series_unit_raw_null and series_unit_raw_control_char fixtures in testdata/records/invalid/ pin the rejected shapes, and testdata/records/valid/error_unit_missing.json shows the error record. Consumers can check the canonical unit rule with Go IsUnitCode(s) and Python is_unit_code(value), the same check the models apply to unit. The shared cases are in testdata/unit_codes.json.

System info, the ABAP version state: The three abap_* members pass the version state of the ABAP backend through. All three are optional: older services and backends omit them (an explicit null counts as absent), unknown members stay ignored, and an unset member is omitted when writing. abap_last_source_change_utc is an instant (RFC 3339 with Z, whole seconds, like every response instant); absent and null both mean unknown. abap_inactive_objects is {"available": true, "count": n, "names": [...]} (count at least 0 and equal to the number of names) or {"available": false, "reason": "..."} (non-empty reason, no count or names). abap_source_fingerprint is the aggregate SHA-256 of the ABAP sources: exactly 64 lower-case hex characters. In Go they are SystemInfo.AbapLastSourceChangeUTC (*time.Time), SystemInfo.AbapInactiveObjects (*InactiveObjects) and SystemInfo.AbapSourceFingerprint (*string); in Python abap_last_source_change_utc, abap_inactive_objects (InactiveObjects) and abap_source_fingerprint. In SystemResponse they are fields 10 to 12 (a Timestamp, an InactiveObjects message and an optional string).

Every public model and field is documented: Python fields carry Field(description=...) (so the descriptions land in the JSON schema from model_json_schema()), Go types, fields and constants carry godoc comments (revive enforces them on exported types, functions and constants; field docs are a convention kept by review), and the two languages are kept in step.

The client-relevant decisions are all in the table above, "The contract in short".

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
  unit_codes.json                        valid and invalid canonical unit codes, shared by IsUnitCode and is_unit_code
  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. Go and other languages generate code in the consuming project, e.g. with buf managed mode; Python consumers use the grpc extra (see below) instead.

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 when it is present. Errors of the RPC framework itself (malformed message INVALID_ARGUMENT, oversized body RESOURCE_EXHAUSTED, unknown method UNIMPLEMENTED) and calls ended by the client (CANCELED, a client-set DEADLINE_EXCEEDED) carry no ErrorInfo; clients switch on the status code for those.

gRPC from Python
pip install "zeitreiher-models[grpc]"

The extra ships the generated stubs (zeitreiher_models.grpc.v1) and converters between the proto messages and the models (zeitreiher_models.grpc: query_request_to_proto, record_from_proto, resolve_response_from_proto, ... in both directions, and error_reason). The base install stays pydantic-only and never imports grpc or protobuf. Request timestamps stay RFC 3339 strings, response timestamps become aware UTC datetime, decimal values stay strings.

import grpc

from zeitreiher_models import EndRecord, ErrorRecord, QueryRequest, SeriesRecord, ValueRecord
from zeitreiher_models.grpc import error_reason, query_request_to_proto, record_from_proto
from zeitreiher_models.grpc.v1 import series_service_pb2_grpc

# h2c without TLS (e.g. in a test); for the BTP use grpc.secure_channel(host, grpc.ssl_channel_credentials())
channel = grpc.insecure_channel("localhost:8080")
stub = series_service_pb2_grpc.SeriesServiceStub(channel)
request = QueryRequest.model_validate(
    {
        "select": [{"by": "profile", "profile": "50000000000056"}],
        "from": "2026-01-14T00:00:00+01:00",
        "to": "2026-01-15T00:00:00+01:00",
    }
)
metadata = (("authorization", "Bearer " + token),)  # the token is yours to obtain
complete = False
try:
    for message in stub.Query(query_request_to_proto(request), metadata=metadata):
        record = record_from_proto(message)
        if isinstance(record, EndRecord):
            complete = True  # record.next is the cursor of the next page, or None
        elif isinstance(record, SeriesRecord | ValueRecord | ErrorRecord):
            ...  # collect
except grpc.RpcError as err:
    print(err.code(), error_reason(err))  # e.g. cursor_stale; None if the status carries no ErrorInfo
    raise
if not complete:
    raise RuntimeError("the stream ended without an EndRecord: treat the response as failed")

error_reason reads the google.rpc.ErrorInfo (domain zeitreiher.hochfrequenz.de) of the grpc-status-details-bin trailer and returns its reason; it returns None when there is none (a cancelled call, a client deadline, a transport error). Converting a request from proto (query_request_from_proto) raises the models' pydantic.ValidationError for an invalid message. Token handling, paging and retries stay with the consumer.

The stubs are generated and committed; regenerate them after a proto change with uv sync --locked --group codegen --extra grpc && uv run --no-sync python scripts/generate_grpc.py (the Python version and the exact generator versions pinned in the repo are required; the script refuses anything else).

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. While the major version is 0, minor releases may contain breaking changes (announced in the release notes); 1.0 freezes the v1 contract. From 1.0 on, releases are 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 --extra grpc  # Python
uv run pytest unittests
uv run ruff check src unittests && uv run ruff format --check .
uv run mypy --strict src/zeitreiher_models unittests
uv sync --locked --group codegen --extra grpc && uv run --no-sync python scripts/generate_grpc.py  # regenerate the gRPC stubs
buf lint && buf build && buf format --diff --exit-code   # buf version as in CI

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.

Regenerating the stubs (scripts/generate_grpc.py) requires the codegen dependency group from the lockfile (--locked) and the pinned Python version; the script checks the exact versions of grpcio-tools and mypy-protobuf. CI regenerates and fails on any diff in src/zeitreiher_models/grpc/v1. unittests/test_grpc_conformance.py ports the Go conformance test of the proto mapping.

  • Hochfrequenz/mdq-models (public, MIT) holds the canonical schema of the Messdatenqualitätsagent (MQA), written by hand in the same way as this repository.

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 opens a series: one profile assignment of one selector, cut to the request window.
	RecordTypeSeries = "series"
	// RecordTypeValue is one value of a series for a half-open interval [from, to).
	RecordTypeValue = "value"
	// RecordTypeError is a per-selector or per-assignment problem; the stream continues.
	RecordTypeError = "error"
	// RecordTypeEnd closes a successful response; a response without it is incomplete and a failure.
	RecordTypeEnd = "end"
)

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

View Source
const (
	// SelectorByProfile selects a profile by its number.
	SelectorByProfile = "profile"
	// SelectorByMaLo selects the profiles assigned to a market location (11 digits).
	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 IsUnitCode added in v0.4.0

func IsUnitCode(s string) bool

IsUnitCode reports whether s is a canonical unit code: a UN/ECE Recommendation 20 code such as "KWH", "MWH" or "K3" ("K3" = kvarh), that is 2 or 3 upper-case ASCII letters or digits, strict. It is the rule the models apply to unit in requests, series records and assignments, exported so that consumers need not copy the pattern. The Python counterpart is zeitreiher_models.is_unit_code. Whether a well-formed code is supported is the server's decision (an unknown code is a 400).

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 is the profile number without leading zeros.
	Profile string
	// Role is the profile role of the assignment (SAP EPROFASS role, e.g. "0001"; any non-empty text),
	// or nil when the assignment was not resolved through a role (e.g. by: profile).
	Role *string
	// From is the start of the assignment (inclusive), cut to the request window; set together with To.
	From *time.Time
	// To is the end of the assignment (exclusive), cut to the request window.
	To *time.Time
	// Unit is the canonical unit code (UN/ECE Rec. 20, e.g. "KWH") of the profile's values, or nil when the
	// SAP unit has no mapping.
	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
	// Error is the assignment-level error; nil for a usable assignment.
	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.

Role, Unit and UnitRaw describe the profile of the assignment exactly like the fields of the same name in a series record. Without an Error, Role and Unit are always written (null when nil) and UnitRaw is required. With an Error they may be left out: nil Role, nil Unit and an empty UnitRaw are then omitted.

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 Caps added in v0.2.0

type Caps struct {
	// MaxWindowSeconds is the longest window in seconds of one internal SAP values call; the service splits
	// longer query windows (at least 1).
	MaxWindowSeconds int64
	// MaxValues is the highest number of values of one internal SAP values call (at least 1).
	MaxValues int64
	// MaxResolveWindowSeconds is the longest request window in seconds the service accepts for query, resolve
	// and versions; a longer window is a 400 invalid_request (at least 1).
	MaxResolveWindowSeconds int64
}

Caps are the limits of the service (spec section 3.1), reported so that clients know how it works. MaxWindowSeconds and MaxValues bound one internal SAP values call; the service splits a query window accordingly. MaxResolveWindowSeconds is the longest request window the service accepts for query, resolve and versions; longer windows are 400 invalid_request. Versions and resolve are not split and have no value cap. The internal window_too_large answer of SAP never reaches public clients.

func (Caps) MarshalJSON added in v0.2.0

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

MarshalJSON validates and writes the caps.

func (*Caps) UnmarshalJSON added in v0.2.0

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

UnmarshalJSON parses and validates the caps; unknown keys are ignored.

func (Caps) Validate added in v0.2.0

func (c Caps) Validate() error

Validate checks that every cap is positive.

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".

Decimal is an already-scaled decimal value, a string on the wire. 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 is the error code, message and optional request id.
	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 InactiveObjects added in v0.6.0

type InactiveObjects struct {
	// Available says whether the ABAP backend could determine the inactive objects.
	Available bool
	// Count is the number of inactive objects; set exactly when Available (equals len(Names)).
	Count *int64
	// Names are the inactive object names; nil or empty is written as [] when Available, and must be nil
	// otherwise.
	Names []string
	// Reason says why the inactive objects are unknown; set exactly when not Available (non-empty text).
	Reason string
}

InactiveObjects reports the inactive ABAP objects of the package, or why that is unknown. Available true: Count and Names are set (Count equals len(Names)) and Reason is empty. Available false: Reason is set and Count and Names are not.

func (InactiveObjects) MarshalJSON added in v0.6.0

func (o InactiveObjects) MarshalJSON() ([]byte, error)

MarshalJSON validates and writes the report.

func (*InactiveObjects) UnmarshalJSON added in v0.6.0

func (o *InactiveObjects) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and validates the report; unknown keys are ignored.

func (InactiveObjects) Validate added in v0.6.0

func (o InactiveObjects) Validate() error

Validate checks the inactive-objects report.

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 "K3" ("K3" = kvarh); 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 is used when the selector matches no business object (e.g. an unknown
	// market location).
	RecordErrorSelectorNotFound RecordErrorCode = "selector_not_found"
	// RecordErrorNoAssignment is used when the selector exists but has no profile assignment in the
	// request window.
	RecordErrorNoAssignment RecordErrorCode = "no_assignment"
	// RecordErrorUnknownSelector is used when the selector kind (by) is not known to this installation.
	RecordErrorUnknownSelector RecordErrorCode = "unknown_selector"
	// RecordErrorBadSelector is used when the selector's parameters are not acceptable to its resolver.
	RecordErrorBadSelector RecordErrorCode = "bad_selector"
	// RecordErrorAccessDenied is used when the caller is not allowed to read this profile.
	RecordErrorAccessDenied RecordErrorCode = "access_denied"
	// RecordErrorProfileNotFound is used when the profile does not exist.
	RecordErrorProfileNotFound RecordErrorCode = "profile_not_found"
	// RecordErrorProfileTimeZoneMissing is used when the profile has no time zone, so its values cannot be
	// read.
	RecordErrorProfileTimeZoneMissing RecordErrorCode = "profile_time_zone_missing"
	// RecordErrorIntervalSizeUnsupported is used when the profile's interval size is not supported.
	RecordErrorIntervalSizeUnsupported RecordErrorCode = "interval_size_unsupported"
	// RecordErrorWindowUnaligned is used when the request window does not lie on the grid of the profile
	// and the requested interval (the least common multiple of both interval lengths); the end of the
	// window must lie on that grid too.
	RecordErrorWindowUnaligned RecordErrorCode = "window_unaligned"
	// RecordErrorAssignmentUnaligned is used when the bounds of the profile assignment are not aligned to
	// the profile's intervals.
	RecordErrorAssignmentUnaligned RecordErrorCode = "assignment_unaligned"
	// RecordErrorVersionNotFound is used when the requested version number does not exist for the profile.
	RecordErrorVersionNotFound RecordErrorCode = "version_not_found"
	// RecordErrorVersionDeleted is used when 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 is used when the requested unit or interval conversion is not
	// allowed for the profile.
	RecordErrorConversionNotAllowed RecordErrorCode = "conversion_not_allowed"
	// RecordErrorAmbiguousLocalTime is used when a local time in the window occurs twice (daylight saving
	// change) and cannot be mapped to one instant.
	RecordErrorAmbiguousLocalTime RecordErrorCode = "ambiguous_local_time"
	// RecordErrorBadiFailed is used when any customer BAdI (spec section 3.2) raised an exception.
	RecordErrorBadiFailed RecordErrorCode = "badi_failed"
	// RecordErrorUnitMissing is used when the SAP unit key of the series is empty (or only control characters) and no
	// canonical code exists, so unit_raw cannot be filled.
	RecordErrorUnitMissing RecordErrorCode = "unit_missing"
)

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 is used when the request is invalid: missing offset, fractional seconds,
	// from not before to, bad selector shape, too many selectors, unsupported interval, unknown unit,
	// number with interval or unit, or a window longer than the resolve limit. HTTP 400; gRPC
	// INVALID_ARGUMENT.
	RequestErrorInvalidRequest RequestErrorCode = "invalid_request"
	// RequestErrorUnauthorized is used when authentication is missing or invalid. HTTP 401; gRPC
	// UNAUTHENTICATED.
	RequestErrorUnauthorized RequestErrorCode = "unauthorized"
	// RequestErrorForbidden is used when the caller is authenticated but not allowed to use the API. HTTP
	// 403; gRPC PERMISSION_DENIED.
	RequestErrorForbidden RequestErrorCode = "forbidden"
	// RequestErrorNotFound is used when the route is unknown. HTTP 404; gRPC NOT_FOUND.
	RequestErrorNotFound RequestErrorCode = "not_found"
	// RequestErrorMethodNotAllowed is used when the HTTP method is not allowed for the route. HTTP 405;
	// gRPC UNIMPLEMENTED.
	RequestErrorMethodNotAllowed RequestErrorCode = "method_not_allowed"
	// RequestErrorRequestTooLarge is used when the request body exceeds the size limit. HTTP 413; gRPC
	// RESOURCE_EXHAUSTED.
	RequestErrorRequestTooLarge RequestErrorCode = "request_too_large"
	// RequestErrorUpstreamUnreachable is used when the SAP system cannot be reached, or fails in a way the
	// service cannot pass on, before the first record. HTTP 502; gRPC UNAVAILABLE.
	RequestErrorUpstreamUnreachable RequestErrorCode = "upstream_unreachable"
	// RequestErrorInternal is used when the service fails unexpectedly before the first record. HTTP 500;
	// gRPC INTERNAL.
	RequestErrorInternal RequestErrorCode = "internal"
	// RequestErrorCursorInvalid is used when the cursor is malformed or its signature is bad. HTTP 400;
	// gRPC INVALID_ARGUMENT.
	RequestErrorCursorInvalid RequestErrorCode = "cursor_invalid"
	// RequestErrorCursorMismatch is used when the cursor does not match the request. HTTP 400; gRPC
	// INVALID_ARGUMENT.
	RequestErrorCursorMismatch RequestErrorCode = "cursor_mismatch"
	// RequestErrorCursorExpired is used when the cursor has expired. HTTP 400; gRPC INVALID_ARGUMENT.
	RequestErrorCursorExpired RequestErrorCode = "cursor_expired"
	// RequestErrorCursorStale is used when the profile assignments changed since the cursor was issued;
	// restart the query. HTTP 409; gRPC ABORTED.
	RequestErrorCursorStale RequestErrorCode = "cursor_stale"
	// RequestErrorUpstreamTimeout is used when the SAP system does not answer in time before the first
	// record. HTTP 504; gRPC DEADLINE_EXCEEDED.
	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 holds one result per request selector, in request order.
	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 is the index of the request selector (0-based).
	Selector int
	// Select is the request selector, echoed.
	Select Selector
	// Assignments are the profile assignments of the selector; possibly empty, unset with an Error.
	Assignments []Assignment
	// Error is a selector-level error; exactly one of Assignments or Error is set.
	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 is the record-level error code (snake_case); unknown codes are kept on read (see IsKnown)
	// but refused on write.
	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 names the variant: "profile", "malo" or a snake_case customer resolver name of 1 to 30 characters.
	By string
	// Profile is the profile number (By "profile"): 1 to 18 digits; leading zeros are allowed in requests.
	Profile string
	// MaLo is the market location id (By "malo"): exactly 11 digits.
	MaLo string
	// Params are the string parameters of a customer resolver (any other By); keys are non-empty.
	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 is the SAP system id.
	SID string
	// Client is the SAP client the service reads from.
	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
	// Units lists the canonical unit codes (UN/ECE Rec. 20, e.g. "KWH") the system can map to SAP units;
	// a request unit outside this list is a 400. Never nil after unmarshalling.
	Units []string
	// Caps are the per-call self-protection caps.
	Caps Caps
	// AbapLastSourceChangeUTC is the instant of the last source change of the ABAP package (whole seconds,
	// written in UTC "Z"); nil when unknown, then the key is omitted. Absent and null both mean unknown.
	AbapLastSourceChangeUTC *time.Time
	// AbapInactiveObjects reports the inactive objects of the ABAP package; nil when the backend does not
	// say, then the key is omitted.
	AbapInactiveObjects *InactiveObjects
	// AbapSourceFingerprint is the aggregate SHA-256 of the ABAP sources, exactly 64 lower-case hex
	// characters; nil when unknown, then the key is omitted.
	AbapSourceFingerprint *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 is the start of the covered range [From, To) (inclusive).
	From time.Time
	// To is the end of the covered range (exclusive); nil for an open end.
	To *time.Time
	// CreatedAt is the creation instant (UTC); nil when it cannot be determined.
	CreatedAt *time.Time
	// CreatedAtUnknown is true exactly when CreatedAt is nil.
	CreatedAtUnknown bool
	// Reason is SAP's VERSREASON; it may be empty.
	Reason string
	// Description is SAP's VERSDESCR; it may be empty.
	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 selects the current values; exclusive with Number.
	Current bool
	// Number is the version number to rebuild (at least 1); exclusive with Current.
	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 lists the versions overlapping the assignment; written as [] when empty, omitted with an Error.
	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 holds one result per request selector, in request order.
	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 is the index of the request selector (0-based).
	Selector int
	// Select is the request selector, echoed.
	Select Selector
	// Assignments are the profile assignments with their versions; possibly empty, unset with an Error.
	Assignments []VersionedAssignment
	// Error is a selector-level error; exactly one of Assignments or Error is set.
	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 lists one or more selectors; results come back per selector index.
	Select []Selector
	// From is the start of the request window (inclusive); RFC 3339, whole seconds, explicit offset.
	From time.Time
	// To is the end of the request window (exclusive, after From); RFC 3339, whole seconds, explicit offset.
	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