Skip to content

feat(cloudwatch): serve CBOR, JSON and Query from one document (#785) - #791

Merged
scttfrdmn merged 1 commit into
mainfrom
feat/785-cloudwatch-protocols
Sep 11, 2026
Merged

scttfrdmn merged 1 commit into
mainfrom
feat/785-cloudwatch-protocols

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

CloudWatch's service shape, com.amazonaws.cloudwatch#GraniteServiceVersion20100801, carries
aws.protocols#awsQuery, aws.protocols#awsJson1_0, smithy.protocols#rpcv2Cbor and
aws.protocols#awsQueryCompatible at the same time, and its clients disagree about which to
use. Substrate read query-form parameters and answered XML no matter what had been asked for.
#739 fixed the routing and v0.109.0 shipped an honest caveat saying so; #757 fixed the
errors. This is the success body, which is the half that made CloudWatch unusable.

Closes #785.

Measured, against a running emulator

Two binaries: main at ae8d706 built in a detached worktree, and this branch. Same script,
same substrate server --address :4678, retries off.

Client before after
aws-sdk-go-v2 v1.47.0 / cloudwatch v1.72.0 — every operation deserialization failed, expected map for struct, got major type 1 (0x3C, the leading <, read as a CBOR head) every operation succeeds; Threshold reads back 80.5, EvaluationPeriods 2, Period 300
AWS CLI put-metric-data, list-metrics, describe-alarms, describe-alarms-for-metric, get-metric-data exit 0, prints nothing at all JSON output, the metric and alarm present
AWS CLI put-metric-alarm, set-alarm-state An error occurred (InvalidParameterValue) … AlarmName is required — the body was never parsed exit 0
raw Query form works works; three deliberate byte changes, below

The Unit-output rule, on the wire:

before:  HTTP/1.1 200 OK          after:  HTTP/1.1 200 OK
         Content-Length: 225              Content-Length: 0
         Content-Type: text/xml…          Smithy-Protocol: rpc-v2-cbor
         <?xml version="1.0"…

and the modeled output it used to make unreadable:

<-- HTTP/1.1 200 OK
    Content-Type: application/cbor
    Smithy-Protocol: rpc-v2-cbor
    a1 67 "Metrics" 81 a3 6a "MetricName" 65 "Probe" 69 "Namespace" 6f "Substrate/Probe" 6a "Dimensions" 80

A malformed body is refused rather than silently answered:

HTTP/1.1 400 Bad Request
Content-Type: application/cbor
Smithy-Protocol: rpc-v2-cbor

a2 66 "__type" 76 "SerializationException"
   67 "message" 78 6a "the request body is not well-formed CBOR: member \"abc\": cbor: unexpected end of input reading an item head"

main answered that same request 200 with a ListMetricsResult XML document.

The two files that carry the change

emulator/cloudwatch_input.go flattens a JSON or CBOR body into req.Params using the
query protocol's own spelling (MetricData.member.1.MetricName), so all ten handlers read
req.Params unchanged and parseMemberList is untouched. Zero handler-logic changes on
input. That direction is only correct because the CloudWatch model declares no
smithy.api#xmlName and no smithy.api#xmlFlattened trait anywhere — checked across the
whole model, not assumed — which is what makes a member's query key equal to its member name
and every list wrapped in member. The other direction would have rewritten all ten handlers'
parameter reads for no gain.

emulator/cloudwatch_render.go is one ordered neutral document (cwDoc/cwList) plus
three renderers. A handler has no idea which protocol it is answering — nothing in the file is
reachable from a handler except cwRespond and cwUnitResponse — because the alternative, a
per-protocol branch inside ten handlers, is thirty places for the serializations to drift
apart. The document is an ordered slice rather than a map for the same reason cborMap is:
ranging a Go map orders members by randomized iteration, so one response would encode two ways
and no recorded event could be replayed byte-for-byte.

XML member order is substrate's existing order, not the model's. Order is semantically
meaningless in all three protocols, so keeping the old one costs nothing and buys a byte-exact
assertion over the Query path a consumer already depends on — which is what guards a
ten-operation rewrite.

Unit outputs

Six of the ten are modeled smithy.api#Unit: PutMetricAlarm, DeleteAlarms,
SetAlarmState, EnableAlarmActions, DisableAlarmActions, PutMetricData. On CBOR they
answer 200 with no body and no Content-Type, carrying only Smithy-Protocol. On JSON
they answer {} — awsJson1_0 has no equivalent rule, and botocore reads a zero-length JSON
body as a parse failure. On Query they answer a response wrapper with no result element.

This corrects what the issue asked for. #785 requests "a CBOR map — an empty map for
PutMetricData"; the empty map is tolerated by NoOutputClientAllowsEmptyCbor, which is a
requirement on clients, not the conformant server answer. Verified that
server.go's writeResponse adds no default Content-Type, so an empty body genuinely
produces none.

Defects found while rewriting

  • DescribeAlarmsForMetric answered DescribeAlarmsResponse/DescribeAlarmsResult,
    borrowed from DescribeAlarms. The query protocol names both elements after the operation.
  • EnableAlarmActions and DisableAlarmActions emitted malformed XML — a
    string-replacement hack left the opening tag as the literal <placeholder> while the closing
    tag was the operation's:
    <placeholder xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">…</EnableAlarmActionsResponse>
    Both are Unit outputs now, so the hack is gone rather than patched.
  • StateReasonData was stored by SetAlarmState and never rendered.
  • GetMetricStatistics was documented as supported and has never had a dispatch arm.

Absent versus present-and-empty

The handler's explicit choice, and it matters to a typed client. MetricAlarms is always
present (a byte change: an empty one used to be omitted). Dimensions on a metric published
without any is present-and-empty. GetMetricData returns present-and-empty
MetricDataResults and Messages. A MetricAlarm omits every member substrate does not
track — the three timestamps, Unit, ExtendedStatistic, DatapointsToAlarm,
TreatMissingData — and an alarm with no OK actions omits OKActions, so a client reads nil
and can tell it was never set.

Tests

  • emulator/cloudwatch_protocols_test.go (new, ~620 lines) — input flattening for JSON and
    CBOR against the same expected keys, tag-1 timestamps, indefinite-length input, three
    malformed-body cases, and the assertion that the protocol decides rather than the body
    (a JSON-looking body on the Query protocol is left alone). Rendering asserts the whole
    XML byte string, JSON member order, CBOR types (Threshold a double, EvaluationPeriods
    and Period int64), empty-list encoding in all three, and the Unit rule in all three.
    Four end-to-end tiers post real HTTP through httptest.
  • test/e2e/journey_cloudwatch_protocols_test.go (new) — the missing tier. Drives the real
    aws-sdk-go-v2 client through all ten operations behind a recording RoundTripper, so it
    asserts the requests genuinely went out as rpc-v2-cbor (a journey that silently fell back
    to another protocol would prove nothing), that each Unit response carried no body and no
    Content-Type, that Threshold/EvaluationPeriods/Period keep their modeled types, that
    an unset OKActions is nil where an empty Dimensions is a zero-length slice, and that a
    refusal deserializes into *types.ResourceNotFoundException. It fails at ae8d706:
    PutMetricData: … expected map for struct, got major type 1.
  • TestCW_GetMetricData_SmithyRPCV2CBOR no longer asserts a single 0xa0 byte; it decodes the
    response and asserts the members.

Every CloudWatch unit test before this posted a form body and read the XML back as a string,
and test/e2e had no CloudWatch journey, so the suite was green over a service no modern
client could use. That is the gap the journey closes.

Provenance

  • The no-body/no-Content-Type rule for a Unit output comes from the no_output test in
    smithy-protocol-tests/model/rpcv2Cbor/empty-input-output.smithy, which lists Content-Type
    in its forbidHeaders — not from the rpcv2Cbor spec page, which does not state it.
    EmptyInputOutput, a modeled empty structure rather than Unit, does set Content-Type
    and send bf ff; the two are different cases.
  • SerializationException for an undeserializable body is substrate's choice. Neither the
    protocol nor the CloudWatch model names a shape for it.
  • The absent-versus-present-and-empty decisions are substrate's reading of what a typed client
    can distinguish, stated in docs/services.md rather than left implicit.

Compatibility

  • CloudWatch responses now differ by client. The Go SDK gets CBOR where it got unparseable
    XML; the CLI and boto3 get JSON where they got silence.
  • The Query path is unchanged except in three places, all documented: MetricAlarms and
    GetMetricData's Messages are now always present where an empty one was omitted,
    DescribeAlarmsForMetric uses its own wrapper element names, and the two alarm-action
    operations produce well-formed XML. A test asserting <placeholder> would break; nothing
    should have been asserting it.
  • GetMetricData on CBOR previously returned a fixed 0xa0; it now returns a real map
    with both empty lists. A fixture asserting the byte changes; a client reading the value gets
    strictly more.
  • test/e2e gains service/cloudwatch, which pulls aws-sdk-go-v2 v1.45.1 → v1.47.0
    (plus two internal/ patches). Both go.mod and go.sum are tidy in this commit; the full
    e2e suite passes on the bump.

Verification

gofmt -l .                                   clean
go build ./...                               0
go vet ./...                                 0
golangci-lint run ./...                      0 issues
make test                                    0 (go1.27.1, race detector)
GOTOOLCHAIN=go1.26.6 make test               0
GOTOOLCHAIN=go1.26.6 make coverage           emulator 83.5%, total 83.0% (baseline held)
make docs-reference docs-reference-check     0
make docs-versions                           0
npm --prefix docs run build                  0; href="#…" vs id="…" diff empty
go vet -C test/e2e ./...                     0
go test -C test/e2e ./...                    0

Plus the fail-before/pass-after live run above, driven with bash, AWS_MAX_ATTEMPTS=1, both
AWS_REGION and AWS_DEFAULT_REGION exported and AWS_PROFILE unset.

CloudWatch's service shape declares awsQuery, awsJson1_0, rpcv2Cbor and
awsQueryCompatible at once, and its clients disagree about which to use.
Substrate read query-form parameters and answered XML no matter what had
been asked for, so aws-sdk-go-v2 failed every call with "deserialization
failed, expected map for struct, got major type 1" and the AWS CLI printed
nothing at all.

Input is normalized rather than handlers rewritten: a JSON or CBOR body is
flattened into the query protocol's spelling before dispatch, which is
correct only because the model declares no xmlName and no xmlFlattened
trait anywhere. Output moves the other way — a handler builds one ordered
neutral document and three renderers consume it.

The six smithy.api#Unit operations now answer 200 with no body and no
Content-Type on the CBOR path, per the no_output protocol test's
forbidHeaders. Two Query-path defects surfaced and are fixed with it:
DescribeAlarmsForMetric borrowed DescribeAlarms' wrapper element names, and
the two alarm-action operations emitted XML opening with a literal
<placeholder> tag. StateReasonData was stored and never rendered.

A test/e2e journey drives the real aws-sdk-go-v2 client through all ten
operations — the tier whose absence let this ship.

Closes #785
@scttfrdmn scttfrdmn added this to the v0.110.0 milestone Sep 11, 2026
@codecov

codecov Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.32877% with 37 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
emulator/cloudwatch_render.go 83.83% 27 Missing ⚠️
emulator/cloudwatch_input.go 86.84% 10 Missing ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn
scttfrdmn merged commit 0c3e7d9 into main Sep 11, 2026
17 checks passed
@scttfrdmn
scttfrdmn deleted the feat/785-cloudwatch-protocols branch September 11, 2026 00:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CloudWatch emulation doesn't speak rpc-v2-cbor — current aws-sdk-go-v2 clients fail to deserialize responses

1 participant