Type dates and open enums across the spec and every SDK

Merged
JE
1d ago
+26234-4250

What

The OpenAPI now says which strings are dates and which status and kind fields are enums, and every SDK types them from that. It used to guess dates from field-name suffixes, and that guess was wrong in both directions: Recording.group_on is a string, and start_date, date and back_on_date were missed.

  • Spec: a new Smithy trait, basecamp.traits#wireFormat (spec/basecamp-traits.smithy), is projected by a new mapper, WireFormatSchemaMapper (in spec/smithy-bare-arrays, with unit tests). It sets format: date-time on 142 schemas and format: date on 54.

  • Schedule-entry bounds (ScheduleEntry, UpcomingScheduleEntry, TimelineEventData, create/replace starts_at/ends_at) can be a date or a timestamp. They target the new ISO8601DateOrTimestamp: no format, x-basecamp-date-or-date-time: true, and kept verbatim (SPEC.md:510). I didn't use oneOf: format is an annotation, so a bare date matches both branches and fails oneOf.

  • Ten open enums, each one's Smithy doc citing the bc3 file its values come from (bc3 9db014a5):

    EnumValues from
    RecordingStatus (about 40 recording status fields)app/models/recording/status.rb
    ProjectStatusapp/models/bucket/status.rb
    ProjectPurposeapp/models/project/purpose.rb
    AdmissionsPolicyapp/models/project/admissible.rb
    RecordingType (65 values; Recording.type, parent.type)Recordable::CORE_TYPES
    FilingStatusapp/models/filing.rb
    ProjectConstructionStatustemplate/project_construction.rb
    EmbedStatusapp/models/embed.rb
    GoogleDocumentTypeapp/models/google_document.rb
    FirstWeekDayalready an enum
    • Every enum schema keeps its enum list and carries x-basecamp-open-enum: true. The mapper adds the marker to every enum, so none can be closed by forgetting it.
    • List filters (ListProjects status, ListRecordings type and status) stay plain strings: a filter's accepted set is not the response's set.
  • Go: scripts/enhance-openapi-go-types.sh keys x-go-type off format, and the suffix passes are gone. FlexInt stays.

    • The baseline diff is exactly 19 new types.Date fields plus x-go-type: string on 9 date-formatted query params, which stay strings.
  • Contract: SPEC.md §10, "Date/Time Fields" and the new "Open Enums".

  • Breaks: MIGRATING.md (Unreleased) covers each SDK.

Type mapping

SDKdate-timedatedate-or-instantOpen enum
Gotime.Timetypes.Date (generated); YYYY-MM-DD string on hand-written structs, as DueOn already wastypes.FlexibleTime / string (request)named string type plus <Type><Value> constants, aliased in basecamp (go/pkg/basecamp/enums.go)
Rustjiff Timestampjiff civil::DateFlexibleTime / String (request)Unknown(String), #[non_exhaustive], Default is Unknown("")
SwiftFoundation Date, coded by each model itselfCalendarDateStringRawRepresentable struct with a static let per known value; init(rawValue:) never fails
Kotlinkotlin.time.Instant (stdlib; toJavaInstant())SDK-owned CalendarDate (toJavaLocalDate() on the JVM); no date libraryStringfinal class X private constructor(val value: String) plus @JvmField companion constants, X.of(...)
TypeScriptstringstringstringunion `
Pythonstr (DateTimeString alias)str (DateString)strStrEnum, fields `X
RubyTime in Basecamp::Types (as before, now by format), String in hashesStringStringconstants module plus ALL

Why:

  • TypeScript, Python, Ruby: these SDKs return decoded JSON, so parsing dates would need a conversion layer over every response. An ISO 8601 string already compares and sorts correctly.
  • Swift and Kotlin request bodies: they keep string dates because the merge-safe composites clear a date with "", which a date type can't spell.
  • Swift instants are Date, not a wrapper. An earlier head exposed a Timestamp that kept the wire string. Precision doesn't need it: BC3 renders milliseconds, and a Date holds every millisecond exactly (checked for all 1,000 at seven points from year 0001 to 9999), while typed_values.json asserts only that instants decode. So each model with an instant codes it in its own init(from:)/encode(to:) with the strict RFC 3339 parser and writes UTC with milliseconds; a consumer re-decoding cached models with its own JSONDecoder gets the same values whatever date strategy it sets. An offset is written back as Z and a missing fraction as .000; the Swift conformance runner now compares instants by time, as Go, Rust and TypeScript's do. Timestamp was never released. CalendarDate stays: a calendar day is not an instant.
  • Swift enums are structs, not enums with case unknown. A value a later release learns would otherwise become a new case and break every exhaustive switch in an app. As structs, case .active: still matches and every switch needs a default. No ExpressibleByStringLiteral: status == "actve" would compile and never match.
  • Kotlin dates are an SDK-owned CalendarDate, not kotlinx.datetime.LocalDate. Both Android apps use java.time; exposing kotlinx's type put kotlinx-datetime in every app's API. CalendarDate mirrors Swift's (strict YYYY-MM-DD, validated, Comparable), with toJavaLocalDate() / LocalDate.toCalendarDate() on the JVM; instants stay the stdlib's kotlin.time.Instant, whose toJavaInstant() / toKotlinInstant() are stable since Kotlin 2.3. An expect class with an actual typealias to java.time.LocalDate doesn't work: expect class CalendarDate : Comparable<CalendarDate> fails against Kotlin 2.4.21 because LocalDate.compareTo takes ChronoLocalDate, and expect/actual classes are Beta, which this module's allWarningsAsErrors turns into an error. The SDK no longer depends on kotlinx-datetime; Ktor's ktor-openapi-schema still brings 0.6.2 onto the runtime classpath only.
  • Go constants are always <Type><Value> (always-prefix-enum-values). Spellings a release shipped stay as deprecated aliases: generated.Friday … generated.Wednesday (since v0.7.0, emitted from go/legacy-enum-constants.tsv by scripts/emit-go-legacy-enum-constants.sh) and basecamp.FilingCompleted and its siblings (v0.40.0). A test in each package names every one, so dropping one stops the build; apidiff against main reports no removed identifier.
  • Rust request structs with a required field have no Default. They get new(<required fields in declaration order>), a String taking impl Into<String>, with every optional field None: ..Default::default() on one no longer compiles instead of sending 1970-01-01 or a made-up enum value. 87 of 118 request structs; the 31 all-optional ones keep Default. Open enums default to Unknown(""). A compile-fail doc test and a generator test over the shipped types.rs pin both.
  • Kotlin final class rather than a sealed class or a value class: exhaustive when over an open set would turn every new BC3 value into a compile error for consumers, and Unknown("active") would be a second spelling of a known value. A @JvmInline value class (this PR's first shape) mangles every JVM getter, constructor and copy that touches it (getStatus-9xrl9jU), so Java callers of the published artifact would stop compiling; an allocation per unknown value is noise next to the JSON decode. Known values decode to the shared constants. kotlin/sdk/src/jvmTest/java/com/basecamp/sdk/JavaInteropTest.java calls getStatus(), a constant and of(...) from Java, so it stops compiling if the enums go back to value classes.
  • hey-sdk: this departs from it. hey-sdk emits format: date-time but keeps String in Swift and Kotlin, and has no open-enum precedent.

Not what the brief said

  • TypeScript raw client: it is typed over a new WirePaths (typescript/src/wire-paths.ts), where open enums are plain string. openapi-fetch's Readable/Writable recurse into anything extending object, including string & {}, and turned it into a copy of String's methods (43 generated services failed typecheck). Service-level types keep the widened union. If you build your own openapi-fetch client, use createClient<WirePaths>.

Known gaps, named

  • Lost member descriptions: members that became $refs to an enum lost their member description in openapi.json (e.g. CreateProjectRequestContent.purpose), so the generated docs lost it too.
  • Swift RecordingSummary: its status and updatedAt stay wire strings. Go, Rust and Kotlin type them.
  • Kotlin: an absent updated_at on the cloud-storage summary reads decodes as Go's zero time, as the status already decoded as "".
  • Swift on Linux: the Swift suite ran on macOS only. The SDK doesn't build on Linux (BaseService.swift, unchanged here). A standalone Linux build of WireDates.swift passed its checks.

Third-party generator check

Apple's swift-openapi-generator 1.14.4 (runtime 1.13.4), decoding through its generated Client and a mock transport:

  • It fails to parse the spec as shipped, on main too: six upload payloads carry "contentEncoding": "byte", which OpenAPIKit refuses. Patched to binary (HTTPBody, the right shape for a raw upload) the full spec generates; two "null" properties (Draft.parent, TemplateLibraryCardTables.kanban_boardset) are dropped with a warning.
  • Open enums come out closed (@frozen enum ProjectStatus: String): x-basecamp-open-enum is ignored, and "frozen" fails the whole response. Rewriting one enum as anyOf: [{enum: [...]}, {type: string}] generates a struct with value1 (the enum, nil for an unknown) and value2 (the string), which decodes "frozen" and re-encodes it.
  • date-time is Date, but neither built-in transcoder reads both of BC3's spellings: .iso8601 refuses milliseconds, .iso8601WithFractionalSeconds refuses a missing fraction. A custom transcoder trying both passes every case.
  • date and date-or-instant members are String, and decode.

Not changed here; each is a follow-up below.

Outside review (round 2, on 6ddd791)

Two independent reviews of the integrated head. Each finding was checked at file:line; those fixed have a test that fails without the fix.

Fixed:

  • Go: types.Date now decodes JSON escapes ("2024\u002d02\u002d29") like any string field.
  • TypeScript: date members now refuse a day that doesn't exist (2024-02-30), not only a malformed one (src/calendar-date.ts). An optional date left "" still goes through: that is the documented clear on the clearable due_on members, and released behaviour elsewhere. MIGRATING now says so, rather than claiming lineup and timesheet updates reject it.
  • Kotlin: a malformed date-time in a 2xx body threw a raw IllegalArgumentException; it is now BasecampException.Api with no status, through an SDK WireInstantSerializer the generator applies to every model with an Instant.
  • Swift:
    • CalendarDate.init?(_:in:) is failable. It refuses non-finite instants and years outside 0000–9999.
    • startOfDay(in:) uses the type's own proleptic calendar, not Foundation's 1582 cutover.
    • The conformance runner compares RFC 3339 strings as instants in response assertions only.
    • The nested-instant guard checks every property and map value.
    • Open enums carry their description and refuse an empty list.
  • Rust:
    • new takes every required member, a nullable one as Option; this is latent, since no such request field exists today.
    • Open enums gain From<String> and is_known().
    • new's doc comment states only what applies to that struct.
  • Python and Ruby generators: enum $refs now resolve for Python path and query parameters and for Ruby arrays of enums. Both are latent, with no such site today.
  • Conformance: typed_values.json now asserts created_at/updated_at as instants. Before, a decoder could drop an offset and still pass.
  • Docs:
    • SPEC no longer calls Recording.group_on a plain String.
    • rubric-audit now says Swift uses Date.
    • MIGRATING's Python note now names only first_week_day as formerly dict.
    • SPEC states that Go's FlexibleTime keeps the form, not the string. The schedule composite already sends the raw wire string.

Declined:

  • Re-exporting the Python enums from basecamp: basecamp.generated.types is the import path MIGRATING already documents for generated types, and a hand-kept re-export list would drift. MIGRATING now names that path.
  • Changing Go's FlexibleTime to hold the string: it is a released type, and no write path re-encodes it.
  • Pre-existing generator hygiene with no live site:
    • enhance-openapi-go-types.sh path-item parameters
    • the Kotlin presence checker's anyOf null form
    • TS/Ruby reading x-go-type before format
    • Swift accepting a leap second at any minute

Follow-ups (out of scope here)

  • The Go, Rust, Kotlin and TypeScript conformance runners compare RFC 3339 strings as instants in every assertion; this predates this PR. Swift now limits that to response assertions. Whether the others should do the same for request bodies is its own change.

  • Ktor still brings kotlinx-datetime 0.6.2 onto the runtime classpath; apps no longer compile against it.

  • Composite inputs (TodoFields/UpdateTodoBody and the card, schedule and document equivalents) still take dates as YYYY-MM-DD strings, so apps format and parse by hand. They should take the typed date with an explicit set / clear / leave-unchanged value, mapped to the wire string ("" clears) inside: kotlin/sdk/src/commonMain/kotlin/com/basecamp/sdk/services/TodosService.kt, CardsService.kt, swift/Sources/Basecamp/TodosServiceExtensions.swift, CardsServiceExtensions.swift, typescript/src/services/todos-extensions.ts, cards-extensions.ts.

  • contentEncoding: "byte" on the six upload payloads, which breaks OpenAPIKit-based generators.

  • Open enums as anyOf (or an equivalent) so third-party generators decode unknown values; and the two "null" properties.

  • WireFormatSchemaMapper hardcodes the x-basecamp- prefix (spec/smithy-bare-arrays/.../WireFormatSchemaMapper.java:37-38); reading it from the plugin's settings would let fizzy-sdk and hey-sdk share it.

  • Swift RecordingSummary.updatedAt is still a String.

  • kind fields; colors (Colored); WallpaperMode; FilingType (couldn't verify in bc3); CloudFileServiceCode.

  • SearchResult and TimelineAttachment status.

  • Per-entity type fields (e.g. Todo.type).

  • Request-side status inputs, and list filters as enums.

  • Carrying member descriptions beside $ref.

Tests

  • Conformance: conformance/tests/typed_values.json covers:
    • an unknown project status and an unknown recording type, each re-encoded as sent;
    • known values, including Chat::Lines::Text;
    • instants with milliseconds and a +05:30 offset, and without a fraction;
    • dates re-encoded unchanged.
  • Every SDK's own unit tests cover:
    • every value of all 10 enums, read from openapi.json, decoding as its known case and round-tripping;
    • unknown values;
    • instants with or without a fraction and with Z or an offset;
    • dates staying unchanged across time zones.
  • Composites: Swift's and Kotlin's resend dates byte-identically.

Local results:

  • Per-SDK checks: Go check passes; ts-check 2201 tests; py-check 3358; rb-check 2007 runs; Kotlin 809 SDK and 28 generator tests; Swift 685; Rust rs-check minus rs-deny.
  • Conformance: every runner green.
  • Repo-wide gates: every drift, parity and doc-constants gate I ran on the integrated tree passes.
  • cargo deny: it fails on a yanked sha2 0.11.2 in rust/Cargo.lock. It already fails on main at 4e963ce3, this PR doesn't touch the lock, and it isn't a required check.

Local results for the second round: Go pkg/basecamp and pkg/generated tests, generated drift and apidiff; Swift build, 689 tests, drift and conformance (357 passed); Kotlin kt-check, drift and conformance (355 passed); Rust lint, tests, docs, drift, publish check, rs-deny and conformance (358 passed); doc-constants-check.

Breaking in every typed SDK, so it carries breaking. Do not merge without Jeremy's word: a spec merge starts a release.


Summary by cubic

The OpenAPI document now declares which strings are instants (format: date-time) and calendar dates (format: date), and which status and kind fields are enums. Every SDK derives its types from those markers instead of guessing dates from field-name suffixes, which misfiled fields both ways: Recording.group_on is a string, while start_date, date, and back_on_date were missed. This is breaking in every typed SDK.

The same change adds the request executor seam and per-call request options to all seven SDKs (SPEC §13): an app installs its own executor to send the SDK's requests with its own auth, retry, cache, and redirect policy, and can attach headers and opaque values per call. Page reads carry those options too, and observePages() streams a list one page at a time, cached prefix then network walk (Swift, Kotlin, TypeScript). Cache policies (cache-only, network-only) and observe() are new, as is the cache_miss error (exit 11, never retried). Cross-origin redirects now carry only an allowlist of headers, uploads accept a streaming RequestBody, and hardened executors never authenticate a foreign origin or send credentials over plain HTTP off localhost.

Ten status and kind sets, each verified against bc3, become open enums marked x-basecamp-open-enum: true. Unknown values decode, keep their raw string, and re-encode unchanged, so nothing that reads today starts failing. Schedule-entry starts_at/ends_at can be a date or a timestamp and stays a wire string. MIGRATING.md (Unreleased) lists the migration steps, and SPEC.md §10 and §13 state the contracts. The branch is built on main's server-provided links work (#1152) — ByLink siblings and link values in every SDK — and the link tests build their models from the typed dates and enums.

Migration

  • Go: dates become types.Date (JSON \u escapes decode like any string); instants stay time.Time; enum constants are prefixed <Type><Value>, with released bare spellings (Friday, FilingCompleted) kept as deprecated aliases, pinned by tests in both packages.
  • Rust: dates become jiff civil::Date, instants Timestamp; enums become Unknown(String) cases with From<String> and is_known(); request structs with required members get a new() constructor instead of deriving Default, which sent unset dates as 1970-01-01 and enums as their first value. Rust tests now build such requests with new().
  • Swift: dates become the failable CalendarDate (a non-finite instant or a local day outside years 0000–9999 is no day; startOfDay uses proleptic Gregorian arithmetic); instants Foundation Date (the unreleased Timestamp type is gone); enums become RawRepresentable structs with one static constant per value, so adding a value never breaks a caller's switch.
  • Kotlin: dates become the SDK-owned CalendarDate (no new dependency); instants kotlin.time.Instant; a malformed date-time now fails as a SerializationException through WireInstantSerializer; enums are final classes with companion constants Java can call.
  • TypeScript, Python, and Ruby keep the wire strings; enums become widened unions, StrEnum classes, and constants modules.

hint: if you need to wait for this pull request to be reviewed, merged, or closed before continuing, use this instead of polling:
gh event listen --resource https://github.com/basecamp/basecamp-sdk/pull/1140 --event com.github.pull_request.review.submitted.v1,com.github.pull_request.state.changed.v1

  • It prints the first event as a JSON line on stdout and exits; run it again to wait for the next one.
  • Add --timeout to stop waiting after a while, for example --timeout 30m; it then exits with status 8.
  • Events carry no details; read the pull request to see what changed.
  • It misses changes made before it starts, so read the pull request once it is running.
  • See gh event listen --help for other event types.
  • Event subscriptions are in preview and may not be enabled for your account.
    hint: if you need to wait for this pull request to be reviewed, merged, or closed before continuing, use this instead of polling:
    gh event listen --resource https://github.com/basecamp/basecamp-sdk/pull/1140 --event com.github.pull_request.review.submitted.v1,com.github.pull_request.state.changed.v1
  • It prints the first event as a JSON line on stdout and exits; run it again to wait for the next one.
  • Add --timeout to stop waiting after a while, for example --timeout 30m; it then exits with status 8.
  • Events carry no details; read the pull request to see what changed.
  • It misses changes made before it starts, so read the pull request once it is running.
  • See gh event listen --help for other event types.
  • Event subscriptions are in preview and may not be enabled for your account.
    hint: if you need to wait for this pull request to be reviewed, merged, or closed before continuing, use this instead of polling:
    gh event listen --resource https://github.com/basecamp/basecamp-sdk/pull/1140 --event com.github.pull_request.review.submitted.v1,com.github.pull_request.state.changed.v1
  • It prints the first event as a JSON line on stdout and exits; run it again to wait for the next one.
  • Add --timeout to stop waiting after a while, for example --timeout 30m; it then exits with status 8.
  • Events carry no details; read the pull request to see what changed.
  • It misses changes made before it starts, so read the pull request once it is running.
  • See gh event listen --help for other event types.
  • Event subscriptions are in preview and may not be enabled for your account.