diff --git a/cmd/vet/jsontags/analyzer.go b/cmd/vet/jsontags/analyzer.go index 5842fc1c1..a57c97048 100644 --- a/cmd/vet/jsontags/analyzer.go +++ b/cmd/vet/jsontags/analyzer.go @@ -112,7 +112,7 @@ func run(pass *analysis.Pass) (any, error) { report(pass, structType, fieldVar, OmitEmptyShouldBeOmitZeroButHasIsZero) } case "string": - if !isNumericKind(fieldVar.Type()) { + if !isStringTagSafe(fieldVar.Type()) { report(pass, structType, fieldVar, StringOnNonNumericKind) } default: @@ -184,3 +184,31 @@ func isNumericKind(t types.Type) bool { } return false } + +// isStringTagSafe reports whether the JSON `string` tag option is valid for t. +// It is valid for basic numeric types and for jsonformat types that encode as +// JSON numbers (and honor StringifyNumbers / the string tag). +func isStringTagSafe(t types.Type) bool { + if pointer, ok := t.(*types.Pointer); ok { + t = pointer.Elem() + } + if isNumericKind(t) { + return true + } + return isJSONFormatNumeric(t) +} + +// isJSONFormatNumeric reports whether t is a tailscale.com/types/jsonformat +// type that represents a JSON number (optionally stringified). +func isJSONFormatNumeric(t types.Type) bool { + pkgPath, name := typeName(t) + if pkgPath != "tailscale.com/types/jsonformat" { + return false + } + switch name { + case "TimeUnix", "TimeUnixNano", "DurationNano": + return true + default: + return false + } +} diff --git a/types/jsonformat/arshal_time.go b/types/jsonformat/arshal_time.go new file mode 100644 index 000000000..b4e63e1b6 --- /dev/null +++ b/types/jsonformat/arshal_time.go @@ -0,0 +1,370 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package jsonformat + +import ( + "bytes" + "errors" + "fmt" + "math" + "math/bits" + "strconv" + "time" +) + +// arshal_time.go contains a verbatim copy of: +// - appendTimeUnix +// - parseTimeUnix +// - appendDurationISO8601 +// - parseDurationISO8601 +// - (and any supporting functions) +// +// from encoding/json/v2/arshal_time.go@go1.27rc2. +// The only modification is that calling jsonwire.ParseUint was switched +// to jsonwireParseUint and that function verbatim copied here. + +// appendDurationISO8601 appends an ISO 8601 duration with a restricted grammar, +// where leading and trailing zeroes and zero-value designators are omitted. +// It only uses hour, minute, and second designators since ISO 8601 defines +// those as being "accurate", while year, month, week, and day are "nominal". +func appendDurationISO8601(b []byte, d time.Duration) []byte { + if d == 0 { + return append(b, "PT0S"...) + } + b, n := mayAppendDurationSign(b, d) + b = append(b, "PT"...) + n, nsec := bits.Div64(0, n, 1e9) // compute nsec field + n, sec := bits.Div64(0, n, 60) // compute sec field + hour, min := bits.Div64(0, n, 60) // compute hour and min fields + if hour > 0 { + b = append(strconv.AppendUint(b, hour, 10), 'H') + } + if min > 0 { + b = append(strconv.AppendUint(b, min, 10), 'M') + } + if sec > 0 || nsec > 0 { + b = append(appendFracBase10(strconv.AppendUint(b, sec, 10), nsec, 1e9), 'S') + } + return b +} + +// daysPerYear is the exact average number of days in a year according to +// the Gregorian calendar, which has an extra day each year that is +// a multiple of 4, unless it is evenly divisible by 100 but not by 400. +// This does not take into account leap seconds, which are not deterministic. +const daysPerYear = 365.2425 + +var errInaccurateDateUnits = errors.New("inaccurate year, month, week, or day units") + +// parseDurationISO8601 parses a duration according to ISO 8601-1:2019, +// section 5.5.2.2 and 5.5.2.3 with the following restrictions or extensions: +// +// - A leading minus sign is permitted for negative duration according +// to ISO 8601-2:2019, section 4.4.1.9. We do not permit negative values +// for each "time scale component", which is permitted by section 4.4.1.1, +// but rarely supported by parsers. +// +// - A leading plus sign is permitted (and ignored). +// This is not required by ISO 8601, but not forbidden either. +// There is some precedent for this as it is supported by the principle of +// duration arithmetic as specified in ISO 8601-2-2019, section 14.1. +// Of note, the JavaScript grammar for ISO 8601 permits a leading plus sign. +// +// - A fractional value is only permitted for accurate units +// (i.e., hour, minute, and seconds) in the last time component, +// which is permissible by ISO 8601-1:2019, section 5.5.2.3. +// +// - Both periods ('.') and commas (',') are supported as the separator +// between the integer part and fraction part of a number, +// as specified in ISO 8601-1:2019, section 3.2.6. +// While ISO 8601 recommends comma as the default separator, +// most formatters use a period. +// +// - Leading zeros are ignored. This is not required by ISO 8601, +// but also not forbidden by the standard. Many parsers support this. +// +// - Lowercase designators are supported. This is not required by ISO 8601, +// but also not forbidden by the standard. Many parsers support this. +// +// If the nominal units of year, month, week, or day are present, +// this produces a best-effort value and also reports [errInaccurateDateUnits]. +// +// The accepted grammar is identical to JavaScript's Duration: +// +// https://tc39.es/proposal-temporal/#prod-Duration +// +// We follow JavaScript's grammar as JSON itself is derived from JavaScript. +// The Temporal.Duration.toJSON method is guaranteed to produce an output +// that can be parsed by this function so long as arithmetic in JavaScript +// does not use a largestUnit value higher than "hours" (which is the default). +// Even if it does, this will do a best-effort parsing with inaccurate units, +// but report [errInaccurateDateUnits]. +func parseDurationISO8601(b []byte) (time.Duration, error) { + var invalid, overflow, inaccurate, sawFrac bool + var sumNanos, n, co uint64 + + // cutBytes is like [bytes.Cut], but uses either c0 or c1 as the separator. + cutBytes := func(b []byte, c0, c1 byte) (prefix, suffix []byte, ok bool) { + for i, c := range b { + if c == c0 || c == c1 { + return b[:i], b[i+1:], true + } + } + return b, nil, false + } + + // mayParseUnit attempts to parse another date or time number + // identified by the desHi and desLo unit characters. + // If the part is absent for current unit, it returns b as is. + mayParseUnit := func(b []byte, desHi, desLo byte, unit time.Duration) []byte { + number, suffix, ok := cutBytes(b, desHi, desLo) + if !ok || sawFrac { + return b // designator is not present or already saw fraction, which can only be in the last component + } + + // Parse the number. + // A fraction is allowed for the accurate units in the last part. + whole, frac, ok := cutBytes(number, '.', ',') + if ok { + sawFrac = true + invalid = invalid || len(frac) == len("") || unit > time.Hour + if unit == time.Second { + n, ok = parsePaddedBase10(frac, uint64(time.Second)) + invalid = invalid || !ok + } else { + f, err := strconv.ParseFloat("0."+string(frac), 64) + invalid = invalid || err != nil || len(bytes.Trim(frac[len("."):], "0123456789")) > 0 + n = uint64(math.Round(f * float64(unit))) // never overflows since f is within [0..1] + } + sumNanos, co = bits.Add64(sumNanos, n, 0) // overflow if co > 0 + overflow = overflow || co > 0 + } + for len(whole) > 1 && whole[0] == '0' { + whole = whole[len("0"):] // trim leading zeros + } + n, ok := jsonwireParseUint(whole) // overflow if !ok && MaxUint64 + hi, lo := bits.Mul64(n, uint64(unit)) // overflow if hi > 0 + sumNanos, co = bits.Add64(sumNanos, lo, 0) // overflow if co > 0 + invalid = invalid || (!ok && n != math.MaxUint64) + overflow = overflow || (!ok && n == math.MaxUint64) || hi > 0 || co > 0 + inaccurate = inaccurate || unit > time.Hour + return suffix + } + + suffix, neg := consumeSign(b, true) + prefix, suffix, okP := cutBytes(suffix, 'P', 'p') + durDate, durTime, okT := cutBytes(suffix, 'T', 't') + invalid = invalid || len(prefix) > 0 || !okP || (okT && len(durTime) == 0) || len(durDate)+len(durTime) == 0 + if len(durDate) > 0 { // nominal portion of the duration + durDate = mayParseUnit(durDate, 'Y', 'y', time.Duration(daysPerYear*24*60*60*1e9)) + durDate = mayParseUnit(durDate, 'M', 'm', time.Duration(daysPerYear/12*24*60*60*1e9)) + durDate = mayParseUnit(durDate, 'W', 'w', time.Duration(7*24*60*60*1e9)) + durDate = mayParseUnit(durDate, 'D', 'd', time.Duration(24*60*60*1e9)) + invalid = invalid || len(durDate) > 0 // unknown elements + } + if len(durTime) > 0 { // accurate portion of the duration + durTime = mayParseUnit(durTime, 'H', 'h', time.Duration(60*60*1e9)) + durTime = mayParseUnit(durTime, 'M', 'm', time.Duration(60*1e9)) + durTime = mayParseUnit(durTime, 'S', 's', time.Duration(1e9)) + invalid = invalid || len(durTime) > 0 // unknown elements + } + d := mayApplyDurationSign(sumNanos, neg) + overflow = overflow || (neg != (d < 0) && d != 0) // overflows signed duration + + switch { + case invalid: + return 0, fmt.Errorf("invalid ISO 8601 duration %q: %w", b, strconv.ErrSyntax) + case overflow: + return 0, fmt.Errorf("invalid ISO 8601 duration %q: %w", b, strconv.ErrRange) + case inaccurate: + return d, fmt.Errorf("invalid ISO 8601 duration %q: %w", b, errInaccurateDateUnits) + default: + return d, nil + } +} + +// mayAppendDurationSign appends a negative sign if n is negative. +func mayAppendDurationSign(b []byte, d time.Duration) ([]byte, uint64) { + if d < 0 { + b = append(b, '-') + d *= -1 + } + return b, uint64(d) +} + +// mayApplyDurationSign inverts n if neg is specified. +func mayApplyDurationSign(n uint64, neg bool) time.Duration { + if neg { + return -1 * time.Duration(n) + } else { + return +1 * time.Duration(n) + } +} + +// appendTimeUnix appends t formatted as a decimal fractional number, +// where pow10 is a power-of-10 used to scale up the number. +func appendTimeUnix(b []byte, t time.Time, pow10 uint64) []byte { + sec, nsec := t.Unix(), int64(t.Nanosecond()) + if sec < 0 { + b = append(b, '-') + sec, nsec = negateSecNano(sec, nsec) + } + switch { + case pow10 == 1e0: // fast case where units is in seconds + b = strconv.AppendUint(b, uint64(sec), 10) + return appendFracBase10(b, uint64(nsec), 1e9) + case uint64(sec) < 1e9: // intermediate case where units is not seconds, but no overflow + b = strconv.AppendUint(b, uint64(sec)*uint64(pow10)+uint64(uint64(nsec)/(1e9/pow10)), 10) + return appendFracBase10(b, (uint64(nsec)*pow10)%1e9, 1e9) + default: // slow case where units is not seconds and overflow would occur + b = strconv.AppendUint(b, uint64(sec), 10) + b = appendPaddedBase10(b, uint64(nsec)/(1e9/pow10), pow10) + return appendFracBase10(b, (uint64(nsec)*pow10)%1e9, 1e9) + } +} + +// parseTimeUnix parses t formatted as a decimal fractional number, +// where pow10 is a power-of-10 used to scale down the number. +func parseTimeUnix(b []byte, pow10 uint64) (time.Time, error) { + suffix, neg := consumeSign(b, false) // consume sign + wholeBytes, fracBytes := bytesCutByte(suffix, '.', true) // consume whole and frac fields + whole, okWhole := jsonwireParseUint(wholeBytes) // parse whole field; may overflow + frac, okFrac := parseFracBase10(fracBytes, 1e9/pow10) // parse frac field + var sec, nsec int64 + switch { + case pow10 == 1e0: // fast case where units is in seconds + sec = int64(whole) // check overflow later after negation + nsec = int64(frac) // cannot overflow + case okWhole: // intermediate case where units is not seconds, but no overflow + sec = int64(whole / pow10) // check overflow later after negation + nsec = int64((whole%pow10)*(1e9/pow10) + frac) // cannot overflow + case !okWhole && whole == math.MaxUint64: // slow case where units is not seconds and overflow occurred + width := int(math.Log10(float64(pow10))) // compute len(strconv.Itoa(pow10-1)) + whole, okWhole = jsonwireParseUint(wholeBytes[:len(wholeBytes)-width]) // parse the upper whole field + mid, _ := parsePaddedBase10(wholeBytes[len(wholeBytes)-width:], pow10) // parse the lower whole field + sec = int64(whole) // check overflow later after negation + nsec = int64(mid*(1e9/pow10) + frac) // cannot overflow + } + if neg { + sec, nsec = negateSecNano(sec, nsec) + } + switch t := time.Unix(sec, nsec).UTC(); { + case (!okWhole && whole != math.MaxUint64) || !okFrac: + return time.Time{}, fmt.Errorf("invalid time %q: %w", b, strconv.ErrSyntax) + case !okWhole || neg != (t.Unix() < 0): + return time.Time{}, fmt.Errorf("invalid time %q: %w", b, strconv.ErrRange) + default: + return t, nil + } +} + +// negateSecNano negates a Unix timestamp, where nsec must be within [0, 1e9). +func negateSecNano(sec, nsec int64) (int64, int64) { + sec = ^sec // twos-complement negation (i.e., -1*sec + 1) + nsec = -nsec + 1e9 // negate nsec and add 1e9 (which is the extra +1 from sec negation) + sec += int64(nsec / 1e9) // handle possible overflow of nsec if it started as zero + nsec %= 1e9 // ensure nsec stays within [0, 1e9) + return sec, nsec +} + +// appendFracBase10 appends the fraction of n/max10, +// where max10 is a power-of-10 that is larger than n. +func appendFracBase10(b []byte, n, max10 uint64) []byte { + if n == 0 { + return b + } + return bytes.TrimRight(appendPaddedBase10(append(b, '.'), n, max10), "0") +} + +// parseFracBase10 parses the fraction of n/max10, +// where max10 is a power-of-10 that is larger than n. +func parseFracBase10(b []byte, max10 uint64) (n uint64, ok bool) { + switch { + case len(b) == 0: + return 0, true + case len(b) < len(".0") || b[0] != '.': + return 0, false + } + return parsePaddedBase10(b[len("."):], max10) +} + +// appendPaddedBase10 appends a zero-padded encoding of n, +// where max10 is a power-of-10 that is larger than n. +func appendPaddedBase10(b []byte, n, max10 uint64) []byte { + if n < max10/10 { + // Formatting of n is shorter than log10(max10), + // so add max10/10 to ensure the length is equal to log10(max10). + i := len(b) + b = strconv.AppendUint(b, n+max10/10, 10) + b[i]-- // subtract the addition of max10/10 + return b + } + return strconv.AppendUint(b, n, 10) +} + +// parsePaddedBase10 parses b as the zero-padded encoding of n, +// where max10 is a power-of-10 that is larger than n. +// Truncated suffix is treated as implicit zeros. +// Extended suffix is ignored, but verified to contain only digits. +func parsePaddedBase10(b []byte, max10 uint64) (n uint64, ok bool) { + pow10 := uint64(1) + for pow10 < max10 { + n *= 10 + if len(b) > 0 { + if b[0] < '0' || '9' < b[0] { + return n, false + } + n += uint64(b[0] - '0') + b = b[1:] + } + pow10 *= 10 + } + if len(b) > 0 && len(bytes.TrimRight(b, "0123456789")) > 0 { + return n, false // trailing characters are not digits + } + return n, true +} + +// consumeSign consumes an optional leading negative or positive sign. +func consumeSign(b []byte, allowPlus bool) ([]byte, bool) { + if len(b) > 0 { + if b[0] == '-' { + return b[len("-"):], true + } else if b[0] == '+' && allowPlus { + return b[len("+"):], false + } + } + return b, false +} + +// bytesCutByte is similar to bytes.Cut(b, []byte{c}), +// except c may optionally be included as part of the suffix. +func bytesCutByte(b []byte, c byte, include bool) ([]byte, []byte) { + if i := bytes.IndexByte(b, c); i >= 0 { + if include { + return b[:i], b[i:] + } + return b[:i], b[i+1:] + } + return b, nil +} + +// jsonwireParseUint parses b as a decimal unsigned integer according to +// a strict subset of the JSON number grammar, returning the value if valid. +// It returns (0, false) if there is a syntax error and +// returns (math.MaxUint64, false) if there is an overflow. +func jsonwireParseUint(b []byte) (v uint64, ok bool) { + const unsafeWidth = 20 // len(fmt.Sprint(uint64(math.MaxUint64))) + var n int + for ; len(b) > n && ('0' <= b[n] && b[n] <= '9'); n++ { + v = 10*v + uint64(b[n]-'0') + } + switch { + case n == 0 || len(b) != n || (b[0] == '0' && string(b) != "0"): + return 0, false + case n >= unsafeWidth && (b[0] != '1' || v < 1e19 || n > unsafeWidth): + return math.MaxUint64, false + } + return v, true +} diff --git a/types/jsonformat/containers.go b/types/jsonformat/containers.go new file mode 100644 index 000000000..d2c8c5992 --- /dev/null +++ b/types/jsonformat/containers.go @@ -0,0 +1,41 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package jsonformat + +import ( + "github.com/go-json-experiment/json" + "github.com/go-json-experiment/json/jsontext" +) + +// SliceEmitEmpty is a generic slice where nil marshals as an empty JSON array. +type SliceEmitEmpty[E any] []E + +var emptyArray = []byte(`[]`) + +func (s SliceEmitEmpty[E]) MarshalJSON() ([]byte, error) { + return json.Marshal(s) +} + +func (s SliceEmitEmpty[E]) MarshalJSONTo(enc *jsontext.Encoder) error { + if s == nil { + return enc.WriteValue(emptyArray) + } + return json.MarshalEncode(enc, ([]E)(s)) +} + +// MapEmitEmpty is a generic map where nil marshals as an empty JSON object. +type MapEmitEmpty[K comparable, V any] map[K]V + +var emptyObject = []byte(`{}`) + +func (m MapEmitEmpty[K, V]) MarshalJSON() ([]byte, error) { + return json.Marshal(m) +} + +func (m MapEmitEmpty[K, V]) MarshalJSONTo(enc *jsontext.Encoder) error { + if m == nil { + return enc.WriteValue(emptyObject) + } + return json.MarshalEncode(enc, (map[K]V)(m)) +} diff --git a/types/jsonformat/doc.go b/types/jsonformat/doc.go new file mode 100644 index 000000000..8f17cba88 --- /dev/null +++ b/types/jsonformat/doc.go @@ -0,0 +1,51 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +// Package jsonformat provides custom JSON representation for common Go types. +// +// For custom representations of [time.Time], see: +// +// - [TimeUnix] +// - [TimeUnixNano] +// - [TimeRFC1123] +// +// For custom representations of [time.Duration], see: +// +// - [DurationNano] +// - [DurationISO8601] +// - [DurationUnits] +// +// For custom representations of slices and maps, see: +// +// - [SliceEmitEmpty] +// - [MapEmitEmpty] +// +// # History and future +// +// The [github.com/go-json-experiment/json] package was +// the prototype implementation for what became [encoding/json/v2]. +// That prototype originally provided a `format` tag option that allowed +// certain types to customize their exact JSON representation. +// See [github.com/go-json-experiment/json.ExperimentalSupportFormatTag]. +// +// While there was widespread support for the concept of +// custom per-type formatting in encoding/json/v2, there was also concern +// about its use of a bespoke DSL to express formatting directives. +// Consequently, support for the `format` tag was removed from the initial +// release of encoding/json/v2 in Go 1.27. +// +// The hope is that "typed struct tags" (see https://go.dev/issues/74472) +// will land in a future release of Go, in which case encoding/json/v2 +// will make use of typed struct tags to express formatting directives +// in a more natural way without resorting to inventing its own DSL. +// +// This package exists as an intermediate step to support custom formats +// while encoding/json/v2 currently does not directly support it. +// Once the Go standard library supports such a feature, +// existing usages of this package are expected to migrate to using +// typed struct tags to express formatting. +// +// In the future, this package may be deleted. +package jsonformat + +import _ "time" // for hotlinking [time.Duration] and [time.Time] diff --git a/types/jsonformat/duration.go b/types/jsonformat/duration.go new file mode 100644 index 000000000..17132bbaa --- /dev/null +++ b/types/jsonformat/duration.go @@ -0,0 +1,123 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package jsonformat + +import ( + "time" + + "github.com/go-json-experiment/json" + "github.com/go-json-experiment/json/jsontext" +) + +// DurationNano is a [time.Duration] that represents a duration as +// a JSON number of nanoseconds. If [json.StringifyNumbers] is specified, +// then it represents the duration as a JSON number within a JSON string. +// +// This format is what v1 [encoding/json] historically used for durations. +// It is not recommended that newly defined types represent durations +// using this format, as a standalone JSON number lacks context +// as to the units of the duration. +type DurationNano struct{ time.Duration } + +func (d DurationNano) MarshalJSON() ([]byte, error) { + return json.Marshal(d) +} + +func (d DurationNano) MarshalJSONTo(enc *jsontext.Encoder) error { + // Marshaling as an int64 directly allows us to properly handle + // the [json.StringifyNumbers] option. + return json.MarshalEncode(enc, int64(d.Duration)) +} + +func (d *DurationNano) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, d) +} + +func (d *DurationNano) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + // Unmarshaling into an int64 directly allows us to properly handle + // the [json.StringifyNumbers] option. + return json.UnmarshalDecode(dec, (*int64)(&d.Duration)) +} + +// DurationUnits is a [time.Duration] that represents a duration as +// a JSON string using the format of [time.Duration.String]. +// +// While this format is human-readable (e.g., "43m17.152s"), +// it is also highly specific to the Go ecosystem +// (and not used elsewhere in the industry). +type DurationUnits struct{ time.Duration } + +func (d DurationUnits) MarshalJSON() ([]byte, error) { + return json.Marshal(d) +} + +func (d DurationUnits) MarshalJSONTo(enc *jsontext.Encoder) error { + b := enc.AvailableBuffer() + b = append(b, '"') + b = append(b, d.Duration.String()...) + b = append(b, '"') + return enc.WriteValue(b) +} + +func (d *DurationUnits) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, d) +} + +func (d *DurationUnits) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + isNull := dec.PeekKind() == 'n' + var s string + if err := json.UnmarshalDecode(dec, &s); err != nil { + return err + } + if isNull { + d.Duration = 0 + return nil + } + var err error + d.Duration, err = time.ParseDuration(s) + return err +} + +// DurationISO8601 is a [time.Duration] that represents a duration as +// a JSON string using a subset of the ISO 8601 format. +// In particular, it uses the exact grammar of ISO 8601 that JavaScript +// uses for its Temporal.Duration type. +// +// While this format is relatively novel in the Go ecosystem, +// the fact that JSON finds its heritage in JavaScript and that +// JavaScript has adopted ISO 8601 as the JSON representation for durations +// suggests that JavaScript's particular flavor of ISO 8601 may well become +// the de facto standard for representing durations across the industry. +type DurationISO8601 struct{ time.Duration } + +func (d DurationISO8601) MarshalJSON() ([]byte, error) { + return json.Marshal(d) +} + +func (d DurationISO8601) MarshalJSONTo(enc *jsontext.Encoder) error { + b := enc.AvailableBuffer() + b = append(b, '"') + b = appendDurationISO8601(b, d.Duration) + b = append(b, '"') + return enc.WriteValue(b) +} + +func (d *DurationISO8601) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, d) +} + +func (d *DurationISO8601) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + isNull := dec.PeekKind() == 'n' + var s string + if err := json.UnmarshalDecode(dec, &s); err != nil { + return err + } + if isNull { + d.Duration = 0 + return nil + } + var err error + d.Duration, err = parseDurationISO8601([]byte(s)) + return err +} diff --git a/types/jsonformat/jsonformat_test.go b/types/jsonformat/jsonformat_test.go new file mode 100644 index 000000000..dddc68aba --- /dev/null +++ b/types/jsonformat/jsonformat_test.go @@ -0,0 +1,169 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//lint:file-ignore SA5008 The `string` tag option is valid on jsonformat +// types: they honor it via jsonv2 StringifyNumbers, but staticcheck only +// accepts it on basic numeric types. + +package jsonformat + +import ( + "testing" + "time" + + "github.com/go-json-experiment/json" + "github.com/google/go-cmp/cmp" +) + +// All types under test, as they are intended to be used: struct fields +// replacing historical `format` tags. Numeric fields are present both with +// and without the `string` tag. +type formatStruct struct { + Unix TimeUnix + UnixStr TimeUnix `json:",string"` + UnixNano TimeUnixNano + UnixNStr TimeUnixNano `json:",string"` + RFC1123 TimeRFC1123 + + DurNano DurationNano + DurStr DurationNano `json:",string"` + Units DurationUnits + ISO DurationISO8601 + + Items SliceEmitEmpty[string] + Labels MapEmitEmpty[string, int] +} + +func TestRoundTrip(t *testing.T) { + ts := time.Unix(1257894000, 0).UTC() // 2009-11-10 23:00:00 UTC + in := formatStruct{ + Unix: TimeUnix{ts}, + UnixStr: TimeUnix{ts}, + UnixNano: TimeUnixNano{ts}, + UnixNStr: TimeUnixNano{ts}, + RFC1123: TimeRFC1123{ts}, + DurNano: DurationNano{time.Hour}, + DurStr: DurationNano{time.Hour}, + Units: DurationUnits{time.Hour}, + ISO: DurationISO8601{time.Hour}, + Items: SliceEmitEmpty[string]{"a", "b"}, + Labels: MapEmitEmpty[string, int]{"n": 1}, + } + wantJSON := `{"Unix":1257894000,"UnixStr":"1257894000","UnixNano":1257894000000000000,"UnixNStr":"1257894000000000000","RFC1123":"Tue, 10 Nov 2009 23:00:00 UTC","DurNano":3600000000000,"DurStr":"3600000000000","Units":"1h0m0s","ISO":"PT1H","Items":["a","b"],"Labels":{"n":1}}` + + got, err := json.Marshal(in) + if err != nil { + t.Fatal(err) + } + if string(got) != wantJSON { + t.Errorf("Marshal:\n got %s\nwant %s", got, wantJSON) + } + + var back formatStruct + if err := json.Unmarshal(got, &back); err != nil { + t.Fatal(err) + } + if diff := cmp.Diff(in, back, cmpOpts()); diff != "" { + t.Errorf("round-trip (-want +got):\n%s", diff) + } +} + +func TestStringTag(t *testing.T) { + // `string` requires a JSON string containing a number; a bare number fails. + // Without `string`, a JSON string fails. + type S struct { + N DurationNano `json:",string"` + T TimeUnix `json:",string"` + U TimeUnixNano `json:",string"` + B DurationNano // no string tag + } + for _, inBuf := range []string{ + `{"N":1000000000}`, // bare number into string-tagged field + `{"T":1257894000}`, // bare number into string-tagged field + `{"U":1257894000000000000}`, // bare number into string-tagged field + `{"B":"1000000000"}`, // string into untagged numeric field + } { + var s S + if err := json.Unmarshal([]byte(inBuf), &s); err == nil { + t.Errorf("Unmarshal(%s): want error", inBuf) + } + } + + // Happy path already covered by TestRoundTrip; also check StringifyNumbers + // global option is observed by the numeric wrappers. + got, err := json.Marshal(DurationNano{time.Second}, json.StringifyNumbers(true)) + if err != nil { + t.Fatal(err) + } + if string(got) != `"1000000000"` { + t.Errorf("StringifyNumbers = %s, want \"1000000000\"", got) + } +} + +func TestNull(t *testing.T) { + // null clears each type to its zero value (including string-tagged fields). + in := formatStruct{ + Unix: TimeUnix{time.Unix(1, 0)}, + UnixStr: TimeUnix{time.Unix(1, 0)}, + UnixNano: TimeUnixNano{time.Unix(1, 0)}, + UnixNStr: TimeUnixNano{time.Unix(1, 0)}, + RFC1123: TimeRFC1123{time.Unix(1, 0)}, + DurNano: DurationNano{time.Hour}, + DurStr: DurationNano{time.Hour}, + Units: DurationUnits{time.Hour}, + ISO: DurationISO8601{time.Hour}, + Items: SliceEmitEmpty[string]{"x"}, + Labels: MapEmitEmpty[string, int]{"x": 1}, + } + const nulls = `{ + "Unix":null,"UnixStr":null,"UnixNano":null,"UnixNStr":null,"RFC1123":null, + "DurNano":null,"DurStr":null,"Units":null,"ISO":null, + "Items":null,"Labels":null + }` + if err := json.Unmarshal([]byte(nulls), &in); err != nil { + t.Fatal(err) + } + if diff := cmp.Diff(formatStruct{}, in, cmpOpts()); diff != "" { + t.Errorf("after null (-want +got):\n%s", diff) + } +} + +func TestEmitEmpty(t *testing.T) { + // Nil slice/map fields emit [] / {} rather than null. + type S struct { + A SliceEmitEmpty[int] `json:",omitzero"` + B SliceEmitEmpty[int] + C MapEmitEmpty[string, int] `json:",omitzero"` + D MapEmitEmpty[string, int] + } + got, err := json.Marshal(S{}) + if err != nil { + t.Fatal(err) + } + if want := `{"B":[],"D":{}}`; string(got) != want { + t.Errorf("Marshal = %s, want %s", got, want) + } + + // Non-nil values round-trip. + in := S{ + A: SliceEmitEmpty[int]{1}, + B: SliceEmitEmpty[int]{2}, + C: MapEmitEmpty[string, int]{"c": 3}, + D: MapEmitEmpty[string, int]{"d": 4}, + } + b, err := json.Marshal(in) + if err != nil { + t.Fatal(err) + } + var back S + if err := json.Unmarshal(b, &back); err != nil { + t.Fatal(err) + } + if diff := cmp.Diff(in, back); diff != "" { + t.Errorf("round-trip (-want +got):\n%s", diff) + } +} + +func cmpOpts() cmp.Option { + return cmp.Comparer(func(a, b time.Time) bool { return a.Equal(b) }) +} diff --git a/types/jsonformat/time.go b/types/jsonformat/time.go new file mode 100644 index 000000000..a8f55982e --- /dev/null +++ b/types/jsonformat/time.go @@ -0,0 +1,131 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package jsonformat + +import ( + "reflect" + "time" + + "github.com/go-json-experiment/json" + "github.com/go-json-experiment/json/jsontext" +) + +// TimeUnix is a [time.Time] that represents time as a JSON number +// of seconds since the Unix epoch. If [json.StringifyNumbers] is specified, +// then it represents the time as a JSON number within a JSON string. +// +// Note that this format preserves the fractional number of seconds. +// To encode just the seconds as an integer, call [time.Time.Round] +// prior to JSON marshaling. +type TimeUnix struct{ time.Time } + +func (t TimeUnix) MarshalJSON() ([]byte, error) { + return json.Marshal(t) +} + +func (t TimeUnix) MarshalJSONTo(enc *jsontext.Encoder) error { + return marshalTimeUnixTo(enc, t.Time, 1e0) +} + +func (t *TimeUnix) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, t) +} + +func (t *TimeUnix) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + return unmarshalTimeUnixFrom(dec, &t.Time, 1e0) +} + +// TimeUnixNano is a [time.Time] that represents time as a JSON number +// of nanoseconds since the Unix epoch. If [json.StringifyNumbers] is specified, +// then it represents the time as a JSON number within a JSON string. +type TimeUnixNano struct{ time.Time } + +func (t TimeUnixNano) MarshalJSON() ([]byte, error) { + return json.Marshal(t) +} + +func (t TimeUnixNano) MarshalJSONTo(enc *jsontext.Encoder) error { + return marshalTimeUnixTo(enc, t.Time, 1e9) +} + +func (t *TimeUnixNano) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, t) +} + +func (t *TimeUnixNano) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + return unmarshalTimeUnixFrom(dec, &t.Time, 1e9) +} + +func marshalTimeUnixTo(enc *jsontext.Encoder, t time.Time, pow10 uint64) error { + stringify, _ := json.GetOption(enc.Options(), json.StringifyNumbers) + b := enc.AvailableBuffer() + if stringify { + b = append(b, '"') + } + b = appendTimeUnix(b, t, pow10) + if stringify { + b = append(b, '"') + } + return enc.WriteValue(b) +} + +func unmarshalTimeUnixFrom(dec *jsontext.Decoder, t *time.Time, pow10 uint64) error { + stringify, _ := json.GetOption(dec.Options(), json.StringifyNumbers) + switch tok, err := dec.ReadToken(); { + case err != nil: + return err + case tok.Kind() == 'n': + *t = time.Time{} + return nil + case tok.Kind() == '"' && stringify, + tok.Kind() == '0' && !stringify: + t2, err := parseTimeUnix([]byte(tok.String()), pow10) + if err != nil { + return err + } + *t = t2 + return nil + default: + return &json.SemanticError{JSONKind: tok.Kind(), GoType: reflect.TypeFor[time.Time]()} + } +} + +// TimeRFC1123 is a [time.Time] that represents time as a JSON string +// formatted using [time.RFC1123]. +type TimeRFC1123 struct{ time.Time } + +func (t TimeRFC1123) MarshalJSON() ([]byte, error) { + return json.Marshal(t) +} + +func (t TimeRFC1123) MarshalJSONTo(enc *jsontext.Encoder) error { + b := enc.AvailableBuffer() + b = append(b, '"') + b = t.Time.AppendFormat(b, time.RFC1123) + b = append(b, '"') + return enc.WriteValue(b) +} + +func (t *TimeRFC1123) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, t) +} + +func (t *TimeRFC1123) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + switch tok, err := dec.ReadToken(); { + case err != nil: + return err + case tok.Kind() == 'n': + t.Time = time.Time{} + return nil + case tok.Kind() == '"': + t2, err := time.Parse(time.RFC1123, tok.String()) + if err != nil { + return err + } + t.Time = t2 + return nil + default: + return &json.SemanticError{JSONKind: tok.Kind(), GoType: reflect.TypeFor[time.Time]()} + } +}