Surface field-keyed 422 validation payloads in all six transports

Merged
JE
4mo ago
+4030-3291

Closes #527. Split out of #526, which modeled the wire contract (FieldValidationError → {"errors": FieldErrorMap}) in the spec; this PR makes all six transports honor it.

The real payload (verified against bc3)

app/controllers/calendars_controller.rb renders both variants of the field-keyed shape:

rescue ActiveRecord::RecordInvalid => e
  raise unless request.format.json?
  render json: { errors: e.record.errors }, status: :unprocessable_entity

and the up-front enum guard, which pins the exact wire shape:

render json: { errors: { color: [ "is not a valid color" ] } }, status: :unprocessable_entity

(ActiveModel::Errors#as_json serializes to {attribute => [messages]}.) The route is resources :calendars, only: [ :update, :show ] (config/routes.rb:858) and the controller responds to JSON, so UpdateCalendar — the operation the spec maps to FieldValidationError — hits this rendering. The same { errors: e.record.errors } pattern appears in google_documents_controller.rb and cloud_files_controller.rb, confirming it as the Rails RecordInvalid family shape. Smithy's FieldErrorMap (map<String, list<String>>) matches.

What changed (identical in all six)

Scoped to 400/422 responses:

  1. Parse the errors map: object value; entries whose value is an array keep their string elements; unusable shapes (non-object errors, non-array entries, no surviving messages) are treated as absent — flat-body behavior is unchanged.
  2. Flatten identically everywhere: fields sorted lexicographically, each field rendered field: msg1; msg2 (messages joined "; "), fields joined ", ". Appended in parentheses after a top-level error message (Validation failed (color: is not a valid color)), standing alone when only errors is present. Truncated after flattening via each SDK's existing 500-char message cap.
  3. Structured slot carrying the raw, untruncated map:
    • Go: Error.FieldErrors map[string][]string
    • TypeScript: BasecampError.fieldErrors?: Record<string, string[]> (+ toJSON)
    • Python: ValidationError.field_errors: dict[str, list[str]] | None
    • Ruby: ValidationError#field_errors (both construction paths: Basecamp.error_from_response and Http#handle_error)
    • Kotlin: BasecampException.Validation.fieldErrors: Map<String, List<String>>? (trailing default param — source-additive)
    • Swift: message-only flattening. Extending the .validation associated values breaks every case .validation(let ...) match, so the structured slot awaits a deliberate source break (documented on the case and in SPEC §6).

SPEC §6 gains a "Field-Keyed Validation Bodies (400/422)" subsection documenting the shared algorithm and the Swift deviation.

Breaking: Go (deliberate, pre-1.0)

Adding FieldErrors to the exported basecamp.Error struct. apidiff base.api pr.api:

Incompatible changes:
- Error: old is comparable, new is not
Compatible changes:
- Error.FieldErrors: added

Unkeyed composite literals of basecamp.Error also break. The SDK itself uses *Error and keyed literals throughout. Labeled breaking; consolidate with the upcoming C4 Go type changes so pre-1.0 consumers absorb one break, not two.

Latent TS bug fixed along the way

The TS service path passed the Response to errorFromResponse, which re-read response.json() — but openapi-fetch has already consumed and parsed the error body by then, so the re-read threw and every service-layer error message silently fell back to statusText. The parsed body was sitting unused in handleError's error param. errorFromResponse now delegates to a new exported errorFromParsedBody, and handleError feeds the parsed body through it. The new conformance cases are what surfaced this (unit tests constructed fresh Response objects and passed).

Tests

Red-first: per-SDK unit tests were run against the pristine transports and failed as expected before the implementation landed —

  • Go: build failure, e.FieldErrors undefined (compile-level red)
  • TS: 7 failed / 50 (vitest tests/errors.test.ts)
  • Python: 12 failed, 1 passed (pytest -k FieldKeyed)
  • Ruby: NoMethodError: field_errors + message mismatches in both errors_test.rb and http_test.rb
  • Swift: 6 XCTAssert failures ("client error" / "Validation failed" vs flattened)
  • Kotlin: compile failure, unresolved fieldErrors / flattenFieldErrors

Green, full suites (after all review rounds): Go go test ./... ok (lint 0 issues); TS 1031 passed; Python 725 passed (uv run pytest); Ruby 963 runs / 0 failures; Swift 267 tests / 0 failures; Kotlin :basecamp-sdk:jvmTest BUILD SUCCESSFUL.

Conformance: seven new error-mapping.json cases on UpdateCalendar (single-field, multi-field sort/join, top-level append, non-string-sibling survival, message-key fallback, __proto__-as-ordinary-field, mixed-validity map tolerance), asserted via language-independent errorMessage substrings — never the structured slot. All five runners green with the new cases passing: Go 129/0, Kotlin 122/0, TypeScript 147 passed, Ruby 113/0, Python 127/0. Swift mirrors the cases as native XCTests in ErrorTests.swift. No skip-roster changes.


Summary by cubic

Make 400/422 validation errors field-aware across all transports and align error parsing across surfaces. We flatten Rails-style field maps into clear messages, expose the raw map (except Swift), honor a "message" fallback, and harden TypeScript against __proto__.

  • New Features

    • 400/422: parse {"errors": {field: [messages]}}, keep string elements only, skip unusable shapes; flatten as field: msg1; msg2, other: msg; append to any top-level error; truncate after flattening.
    • Structured slot for the raw, untruncated map: Go Error.FieldErrors, TypeScript BasecampError.fieldErrors, Python/Ruby/Kotlin field_errors/fieldErrors; Swift flattens message only for now.
    • SPEC documents the shared algorithm; conformance adds sorted/multi-field, append, non-string-sibling survival, "message"-fallback, __proto__ cases, and a malformed-entry tolerance case (Swift mirrors as XCTests).
  • Bug Fixes

    • Top-level message fallback: Go/TypeScript/Kotlin/Swift now honor the "message" fallback when composing field errors.
    • Robustness: parse scalar members independently so non-string error/error_description don’t discard field errors (Go json.RawMessage + safe string extraction; Kotlin/Python/Ruby string-only reads).
    • Go generation: 4xx/5xx parsers tolerate undecodable error bodies so wrappers still see the raw body (wired via go/generate.go and scripts/normalize-go-error-response-parsing.sh); 2xx stays strict.
    • TypeScript service: stop re-reading consumed bodies from openapi-fetch — use errorFromParsedBody to preserve server messages and field errors; treat "__proto__" as a normal key via a null‑prototype accumulator.
    • Kotlin consistency: one shared parser (exceptionFromErrorBody) powers both services and Download.
    • Go: error message truncation matches SPEC (500-byte cap, last 3 replaced with ...).
    • Breaking (Go): added FieldErrors to basecamp.Error; the struct is no longer comparable and unkeyed literals break.