diff --git a/README.md b/README.md index 8fb21bd7..ee904586 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,11 @@ How the specification maps onto Go: in another fails generation, since its name cannot tell them apart. A oneOf of a date-time and an integer reads either and is written as the others are, or as a string where they mix. +- **Unix times in milliseconds** — an integer of format `date-time-ms`, such as + `1795464914123`, is a `time.Time` to the millisecond, written and read the same + way, through jsonutil's `TimeMarshalIntUnixMilli` and the like, by member name + where other forms are about. A query parameter of the format is sent and read + the same way. - **Dates in ISO 8601's basic form** — a string of format `date-basic`, such as `"20260320"`, is a `civil.Date`, written and read without separators: by one marshaler where every date is in that form, else by the names of the members diff --git a/README/features.md b/README/features.md index cf7d1f90..51551144 100644 --- a/README/features.md +++ b/README/features.md @@ -153,6 +153,11 @@ How the specification maps onto Go: in another fails generation, since its name cannot tell them apart. A oneOf of a date-time and an integer reads either and is written as the others are, or as a string where they mix. +- **Unix times in milliseconds** — an integer of format `date-time-ms`, such as + `1795464914123`, is a `time.Time` to the millisecond, written and read the same + way, through jsonutil's `TimeMarshalIntUnixMilli` and the like, by member name + where other forms are about. A query parameter of the format is sent and read + the same way. - **Dates in ISO 8601's basic form** — a string of format `date-basic`, such as `"20260320"`, is a `civil.Date`, written and read without separators: by one marshaler where every date is in that form, else by the names of the members diff --git a/docs/roadmap.md b/docs/roadmap.md index 080c2d95..44d614dd 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -33,18 +33,6 @@ is still a single value, with no `label` or `matrix` style and no array or object, and a header parameter likewise; the server does not read header parameters at all, so a service sees them empty. -## Unix times in milliseconds - -An integer `date-time` is read as Unix seconds. Some APIs write milliseconds: -go-api-libs/finnhub's tick, NBBO and bid-ask timestamps ("List of timestamp in -UNIX ms.") and the websocket's trade times, and go-api-libs/yahoo-finance's -`dateEpochMs` and `firstTradeDateMilliseconds`. They are integers until -recordings show their values, since a spec's types rest on recordings: then a -custom format, `date-time-ms`, like `date-basic`, makes them a `time.Time` in -milliseconds, written and read through jsonutil helpers beside -`TimeMarshalIntUnix`, in a body and a query parameter alike. openapi-enrich -must keep the format when a recording's integer meets it. - ## Server routes for a parameter inside a segment A path parameter can share its segment with fixed text, as go-api-libs/ibkr's diff --git a/go.mod b/go.mod index 13f66082..ca124629 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.27 require ( github.com/MarkRosemaker/cassette v0.0.0-20261125180804-407fe91b7b7d github.com/MarkRosemaker/errpath v0.0.0-20261118230255-99e20cb3445a - github.com/MarkRosemaker/openapi v0.0.0-20261124050252-52a60c76de04 + github.com/MarkRosemaker/openapi v0.0.0-20261125191600-33a241ac282b github.com/MarkRosemaker/openapi-compress v0.0.0-20261124050556-094155f0b064 github.com/MarkRosemaker/openapi-edit v0.0.0-20261124050336-02af6fa36ba9 github.com/MarkRosemaker/openapi-flatten v0.0.0-20261124050336-684f3610d8d7 @@ -19,7 +19,7 @@ require ( require ( cloud.google.com/go v0.123.0 // indirect github.com/MarkRosemaker/json2yaml v0.0.0-20261118230255-853c75cf2bf9 // indirect - github.com/MarkRosemaker/jsonutil v0.0.0-20261118230255-4b04cfc02484 // indirect + github.com/MarkRosemaker/jsonutil v0.0.0-20261125191625-3f67f86ead2a // indirect github.com/MarkRosemaker/openapi-compare v0.0.0-20261124050336-b439780a57a8 // indirect github.com/MarkRosemaker/yaml v0.0.0-20261118230544-f88f96ca5149 // indirect github.com/MarkRosemaker/yaml2json v0.0.0-20261118230255-06c4fe76a5b8 // indirect diff --git a/go.sum b/go.sum index 474a8e67..6347f801 100644 --- a/go.sum +++ b/go.sum @@ -6,10 +6,10 @@ github.com/MarkRosemaker/errpath v0.0.0-20261118230255-99e20cb3445a h1:C7Oyg94gP github.com/MarkRosemaker/errpath v0.0.0-20261118230255-99e20cb3445a/go.mod h1:VnXpUlsS3n1gSToedcQl2FCARGoA16CyitbCanUIv+I= github.com/MarkRosemaker/json2yaml v0.0.0-20261118230255-853c75cf2bf9 h1:NVTLiOVHTQ/PSq3ihG3kT/P1UqNjJiBHHCGbgNq2rP8= github.com/MarkRosemaker/json2yaml v0.0.0-20261118230255-853c75cf2bf9/go.mod h1:eUwIjjooIESK1Ymw4bbMdSDF6feAblyZjxyoo5o/W6U= -github.com/MarkRosemaker/jsonutil v0.0.0-20261118230255-4b04cfc02484 h1:mWQovC60M6QVWXpitDiB2bwT+Jr8uQH2eyjOcUE2EcI= -github.com/MarkRosemaker/jsonutil v0.0.0-20261118230255-4b04cfc02484/go.mod h1:SzjJlgYFlzpbFGvUUoQgfEsWlbai63bvhDPK8J0MNYM= -github.com/MarkRosemaker/openapi v0.0.0-20261124050252-52a60c76de04 h1:glGad+2S6xb+6gddFIcTahqzcGW2MO++45wrCtVvCGA= -github.com/MarkRosemaker/openapi v0.0.0-20261124050252-52a60c76de04/go.mod h1:1FPgdpi6Y8EUPTFOLQrf9Qrrs38oWNHFyAlQmSEjMy8= +github.com/MarkRosemaker/jsonutil v0.0.0-20261125191625-3f67f86ead2a h1:7k/JXkxig7+xgT8ENKGf+EiZuT6OAQWnkccQ/k3Rues= +github.com/MarkRosemaker/jsonutil v0.0.0-20261125191625-3f67f86ead2a/go.mod h1:SzjJlgYFlzpbFGvUUoQgfEsWlbai63bvhDPK8J0MNYM= +github.com/MarkRosemaker/openapi v0.0.0-20261125191600-33a241ac282b h1:lHveG/mKG3Wv0cwHysci7eC8gqfFZdzAgCxP8WBwBL4= +github.com/MarkRosemaker/openapi v0.0.0-20261125191600-33a241ac282b/go.mod h1:1FPgdpi6Y8EUPTFOLQrf9Qrrs38oWNHFyAlQmSEjMy8= github.com/MarkRosemaker/openapi-compare v0.0.0-20261124050336-b439780a57a8 h1:hdfWfYdKhh8lbsUm6QstsJW7Sw2RQGYIRSbCEfCcGAc= github.com/MarkRosemaker/openapi-compare v0.0.0-20261124050336-b439780a57a8/go.mod h1:wDy5Ifa/rKsnIk0At/LY6A0GhlAgLLqC5hi9VwcFrVU= github.com/MarkRosemaker/openapi-compress v0.0.0-20261124050556-094155f0b064 h1:g6oVQzTRZd04LFEaPh9EWGrc6dU3wyNwhEsGkmM0+Mo= diff --git a/interactions.go b/interactions.go index 4c7e43af..a3642171 100644 --- a/interactions.go +++ b/interactions.go @@ -520,6 +520,10 @@ func goLiteralForType(p ir.Param, value string) string { return fmt.Sprintf("time.Unix(%s, 0)", value) } + if p.IsUnixMilli { + return fmt.Sprintf("time.UnixMilli(%s)", value) + } + if t, err := time.Parse(time.RFC3339Nano, value); err == nil { return timeLiteral(t) } @@ -634,6 +638,10 @@ func bodyLiteral(doc *ir.Document, goType string, v any) string { continue // absent optional field: leave it at its zero value } + if f.IsUnixMilli { + val = milliAsTime(val) + } + fields = append(fields, fmt.Sprintf("%s: %s", f.Name, bodyLiteral(doc, f.Type, val))) } @@ -828,3 +836,21 @@ func fallbackJSON(v any) string { return fmt.Sprintf("%q", string(data)) } + +// milliAsTime is v, an integer of unix milliseconds or an array of them, as the time it holds in RFC 3339, which +// scalarLiteral takes as it is, where it would take an integer as unix seconds; see ir.Field.IsUnixMilli. +func milliAsTime(v any) any { + switch v := v.(type) { + case float64: + return time.UnixMilli(int64(v)).UTC().Format(time.RFC3339Nano) + case []any: + out := make([]any, len(v)) + for i, e := range v { + out[i] = milliAsTime(e) + } + + return out + default: + return v + } +} diff --git a/ir/document.go b/ir/document.go index da84c710..72c7ae0a 100644 --- a/ir/document.go +++ b/ir/document.go @@ -134,13 +134,15 @@ func FromDocument(doc *openapi.Document, packageName, userAgent string, producti HasStringOrNumberFields: slices.ContainsFunc(schemas, func(s Schema) bool { return slices.ContainsFunc(s.Fields, func(f Field) bool { return f.IsStringOrNumber }) }), - HasUnixTimeFields: encodings["time.Time"][encodingUnix].all, - HasUnixDateFields: encodings["civil.Date"][encodingUnix].all, - UnixTimeMembers: encodings["time.Time"][encodingUnix].members, - UnixDateMembers: encodings["civil.Date"][encodingUnix].members, - HasBasicDateFields: encodings["civil.Date"][encodingBasic].all, - BasicDateMembers: encodings["civil.Date"][encodingBasic].members, - HasStringDateFields: hasEncoding(encodings, "civil.Date", ""), + HasUnixTimeFields: encodings["time.Time"][encodingUnix].all, + HasUnixDateFields: encodings["civil.Date"][encodingUnix].all, + UnixTimeMembers: encodings["time.Time"][encodingUnix].members, + UnixDateMembers: encodings["civil.Date"][encodingUnix].members, + HasBasicDateFields: encodings["civil.Date"][encodingBasic].all, + BasicDateMembers: encodings["civil.Date"][encodingBasic].members, + HasUnixMilliTimeFields: encodings["time.Time"][encodingMilli].all, + UnixMilliTimeMembers: encodings["time.Time"][encodingMilli].members, + HasStringDateFields: hasEncoding(encodings, "civil.Date", ""), // a date-time that may be an integer is read by an unmarshaler of every time.Time, which comes first HasStringTimeFields: hasEncoding(encodings, "time.Time", "") && !hasDateTimeOrInt, HasServerOverrides: slices.ContainsFunc(operations, func(op Operation) bool { diff --git a/ir/ir.go b/ir/ir.go index a7e9c47e..a8a196e4 100644 --- a/ir/ir.go +++ b/ir/ir.go @@ -40,6 +40,9 @@ type Document struct { // HasBasicDateFields and BasicDateMembers are the same for dates in ISO 8601's basic form, such as "20260320". HasBasicDateFields bool `json:"hasBasicDateFields,omitzero"` BasicDateMembers []string `json:"basicDateMembers,omitempty"` + // HasUnixMilliTimeFields and UnixMilliTimeMembers are the same for date-times that are integers of unix milliseconds. + HasUnixMilliTimeFields bool `json:"hasUnixMilliTimeFields,omitzero"` + UnixMilliTimeMembers []string `json:"unixMilliTimeMembers,omitempty"` // HasStringDateFields and HasStringTimeFields are set when a JSON body holds a civil.Date, or a time.Time, as the // type writes it, so that an empty string, which an API may send for one it leaves out, reads as the zero value. A zero // date is written as null, since civil.Date would write it as "0000-00-00", which is no date. @@ -406,6 +409,10 @@ type Field struct { // IsDateBasic is true when Type is civil.Date but the property's schema is a string of format date-basic, such as // "20260320", see [Document.HasBasicDateFields] and [Document.BasicDateMembers]. IsDateBasic bool `json:"isDateBasic,omitzero"` + + // IsUnixMilli is true when Type is time.Time but the property's schema is an integer of format date-time-ms: it is + // written and read as unix milliseconds, see [Document.HasUnixMilliTimeFields] and [Document.UnixMilliTimeMembers]. + IsUnixMilli bool `json:"isUnixMilli,omitzero"` } // EnumValue is one member of an enum type. @@ -469,6 +476,9 @@ type Param struct { // IsDateBasic is true when Type is "civil.Date" but the schema is a string of format date-basic, such as // "20260320", which FormatExpr writes and ParseExpr reads. IsDateBasic bool `json:"isDateBasic,omitzero"` + // IsUnixMilli is true when Type is "time.Time" but the schema is an integer of format date-time-ms, which FormatExpr + // writes and ParseExpr reads as unix milliseconds. + IsUnixMilli bool `json:"isUnixMilli,omitzero"` // AllowSlashes is set for a path parameter marked x-allow-slashes, a path of its own, as pkg.go.dev's // /package/{path} takes golang.org/x/time/rate: its slashes stay slashes, where any other path parameter's are // escaped, as OpenAPI requires. diff --git a/ir/operation.go b/ir/operation.go index 1b52cf8d..5c301e26 100644 --- a/ir/operation.go +++ b/ir/operation.go @@ -246,6 +246,7 @@ func (p *Param) setType(s *openapi.Schema) error { p.IsUnix = isUnix(p.Type, deref(s)) p.IsDateBasic = isDateBasic(p.Type, deref(s)) + p.IsUnixMilli = isUnixMilli(p.Type, deref(s)) if p.BaseType == "" { p.ParseExpr, p.ParseConv, p.ParseErrFree = parseExpr(p.Type, p.IsUnix) @@ -253,6 +254,10 @@ func (p *Param) setType(s *openapi.Schema) error { p.ParseExpr, p.ParseConv, p.ParseErrFree = `time.Parse("20060102", %s)`, "civil.DateOf(%s)", false } + if p.IsUnixMilli { + p.ParseExpr, p.ParseConv, p.ParseErrFree = "strconv.ParseInt(%s, 10, 64)", "time.UnixMilli(%s)", false + } + return nil } @@ -598,6 +603,10 @@ func (p Param) FormatExpr() string { return "strconv.Itoa(int(" + v + ".Unix()))" } + if p.IsUnixMilli { + return "strconv.FormatInt(" + v + ".UnixMilli(), 10)" + } + return v + ".Format(time.RFC3339)" case "civil.Date": if p.IsUnix { @@ -645,7 +654,7 @@ func (p Param) PathExpr() string { "uuid.UUID", "time.Duration", "civil.Date": return expr case "time.Time": - if p.IsUnix { + if p.IsUnix || p.IsUnixMilli { return expr } } diff --git a/ir/schema.go b/ir/schema.go index a40b54a5..2d51c95d 100644 --- a/ir/schema.go +++ b/ir/schema.go @@ -254,7 +254,7 @@ func integerGoType(f openapi.Format) *GoType { return &GoType{Name: "uint64"} case openapi.FormatDuration: return &GoType{Name: "time.Duration"} - case openapi.FormatDateTime: + case openapi.FormatDateTime, openapi.FormatDateTimeMs: return &GoType{Name: "time.Time"} case openapi.FormatDate: return &GoType{Name: "civil.Date"} @@ -593,6 +593,7 @@ func getField(jsonName string, propRef *openapi.Schema, requiredSet map[string]b IsDateTimeOrInt: isDateTimeOrIntegerOneOf(v), IsStringOrNumber: isStringOrNumberOneOf(v), IsUnix: isUnix(goType.Name, v), + IsUnixMilli: isUnixMilli(goType.Name, v), IsDateBasic: isDateBasic(goType.Name, v), Fixed: fixedJSON(v), }, nil @@ -628,7 +629,18 @@ func isUnix(goType string, s *openapi.Schema) bool { s = deref(s.Items) } - return (goType == "time.Time" || goType == "civil.Date") && s != nil && s.Type == openapi.TypeInteger + return (goType == "time.Time" || goType == "civil.Date") && s != nil && s.Type == openapi.TypeInteger && + s.Format != openapi.FormatDateTimeMs +} + +// isUnixMilli reports whether a value of the Go type named, from schema s, is an integer of unix milliseconds: a +// date-time-ms, or an array of them. +func isUnixMilli(goType string, s *openapi.Schema) bool { + for s != nil && s.Type == openapi.TypeArray { // the items of an array + s = deref(s.Items) + } + + return goType == "time.Time" && s != nil && s.Type == openapi.TypeInteger && s.Format == openapi.FormatDateTimeMs } // isDateBasic reports whether a value of the Go type named, from schema s, is a date in ISO 8601's basic form, such as @@ -815,6 +827,7 @@ func fromTupleSchema(name string, s *openapi.Schema) (*Schema, error) { Type: tp.String(), Description: cmp.Or(p.Description, deref(p).Description), IsUnix: isUnix(tp.Name, deref(p)), + IsUnixMilli: isUnixMilli(tp.Name, deref(p)), IsDateBasic: isDateBasic(tp.Name, deref(p)), } } diff --git a/ir/unix.go b/ir/unix.go index fda9cdd2..f5a28318 100644 --- a/ir/unix.go +++ b/ir/unix.go @@ -8,10 +8,11 @@ import ( ) // encodings are how a time.Time or civil.Date may be written other than as its type does it: as an integer of unix -// time, or, for a date, in ISO 8601's basic form, such as "20260320". +// time, for a time as one of unix milliseconds, or, for a date, in ISO 8601's basic form, such as "20260320". const ( encodingUnix = "integer" encodingBasic = "basic-form" + encodingMilli = "integer-ms" ) // encodingMode is how a document's values of one Go type in one encoding are written and read. @@ -25,6 +26,8 @@ type encodingMode struct { // fieldEncoding is the encoding of f's time.Time or civil.Date, or "" for the type's own. func fieldEncoding(f Field) string { switch { + case f.IsUnixMilli: + return encodingMilli case f.IsUnix: return encodingUnix case f.IsDateBasic: @@ -77,7 +80,7 @@ func markEncodings(schemas []Schema) (map[string]map[string]encodingMode, error) var encs []string - for _, enc := range []string{encodingUnix, encodingBasic} { + for _, enc := range []string{encodingUnix, encodingMilli, encodingBasic} { if len(names[enc]) > 0 || position[enc] != "" { encs = append(encs, enc) } diff --git a/render/templates/types.gen.go.tmpl b/render/templates/types.gen.go.tmpl index 814aacb4..3d7a55e0 100644 --- a/render/templates/types.gen.go.tmpl +++ b/render/templates/types.gen.go.tmpl @@ -7,12 +7,12 @@ package {{.PackageName}} var jsonOpts = json.JoinOptions( json.RejectUnknownMembers(true), - {{- if or .HasURLFields .HasDurationFields .HasUnixTimeFields .HasUnixDateFields .UnixTimeMembers .UnixDateMembers .HasBasicDateFields .BasicDateMembers .HasStringDateFields }} + {{- if or .HasURLFields .HasDurationFields .HasUnixTimeFields .HasUnixDateFields .UnixTimeMembers .UnixDateMembers .HasUnixMilliTimeFields .UnixMilliTimeMembers .HasBasicDateFields .BasicDateMembers .HasStringDateFields }} json.WithMarshalers(json.JoinMarshalers( {{- template "marshalers" . }} )), {{- end }} - {{- if or .HasURLFields .HasDateTimeOrIntFields .HasStringOrNumberFields .HasDurationFields .HasUnixTimeFields .HasUnixDateFields .UnixTimeMembers .UnixDateMembers .HasBasicDateFields .BasicDateMembers .HasStringDateFields .HasStringTimeFields }} + {{- if or .HasURLFields .HasDateTimeOrIntFields .HasStringOrNumberFields .HasDurationFields .HasUnixTimeFields .HasUnixDateFields .UnixTimeMembers .UnixDateMembers .HasUnixMilliTimeFields .UnixMilliTimeMembers .HasBasicDateFields .BasicDateMembers .HasStringDateFields .HasStringTimeFields }} json.WithUnmarshalers(json.JoinUnmarshalers( {{- with .UnixTimeMembers }} json.UnmarshalFromFunc(jsonutil.TimeUnmarshalIntUnixFor({{ range $i, $m := . }}{{ if $i }}, {{ end }}{{ printf "%q" $m }}{{ end }})), @@ -20,6 +20,9 @@ var jsonOpts = json.JoinOptions( {{- with .UnixDateMembers }} json.UnmarshalFromFunc(jsonutil.DateUnmarshalIntUnixFor({{ range $i, $m := . }}{{ if $i }}, {{ end }}{{ printf "%q" $m }}{{ end }})), {{- end }} + {{- with .UnixMilliTimeMembers }} + json.UnmarshalFromFunc(jsonutil.TimeUnmarshalIntUnixMilliFor({{ range $i, $m := . }}{{ if $i }}, {{ end }}{{ printf "%q" $m }}{{ end }})), + {{- end }} {{- with .BasicDateMembers }} json.UnmarshalFromFunc(jsonutil.DateUnmarshalBasicFor({{ range $i, $m := . }}{{ if $i }}, {{ end }}{{ printf "%q" $m }}{{ end }})), {{- end }} @@ -41,6 +44,9 @@ var jsonOpts = json.JoinOptions( {{- if .HasUnixDateFields }} json.UnmarshalFromFunc(jsonutil.DateUnmarshalIntUnix), {{- end }} + {{- if .HasUnixMilliTimeFields }} + json.UnmarshalFromFunc(jsonutil.TimeUnmarshalIntUnixMilli), + {{- end }} {{- if .HasBasicDateFields }} json.UnmarshalFromFunc(jsonutil.DateUnmarshalBasic), {{- end }} @@ -752,6 +758,9 @@ func (v *{{.Name}}) unmarshalJSONMember(dec *jsontext.Decoder, name string) (boo {{- if .HasUnixDateFields }} json.MarshalToFunc(jsonutil.DateMarshalIntUnix), {{- end }} + {{- if .HasUnixMilliTimeFields }} + json.MarshalToFunc(jsonutil.TimeMarshalIntUnixMilli), + {{- end }} {{- if .HasBasicDateFields }} json.MarshalToFunc(jsonutil.DateMarshalBasic), {{- end }} @@ -761,6 +770,9 @@ func (v *{{.Name}}) unmarshalJSONMember(dec *jsontext.Decoder, name string) (boo {{- with .UnixDateMembers }} json.MarshalToFunc(jsonutil.DateMarshalIntUnixFor({{ range $i, $m := . }}{{ if $i }}, {{ end }}{{ printf "%q" $m }}{{ end }})), {{- end }} + {{- with .UnixMilliTimeMembers }} + json.MarshalToFunc(jsonutil.TimeMarshalIntUnixMilliFor({{ range $i, $m := . }}{{ if $i }}, {{ end }}{{ printf "%q" $m }}{{ end }})), + {{- end }} {{- with .BasicDateMembers }} json.MarshalToFunc(jsonutil.DateMarshalBasicFor({{ range $i, $m := . }}{{ if $i }}, {{ end }}{{ printf "%q" $m }}{{ end }})), {{- end }} diff --git a/testdata/golden/api/openapi.json b/testdata/golden/api/openapi.json index b33fea19..b0601e31 100644 --- a/testdata/golden/api/openapi.json +++ b/testdata/golden/api/openapi.json @@ -1008,6 +1008,15 @@ "format": "date-time" } }, + { + "name": "seen", + "in": "query", + "description": "A Unix time in milliseconds.", + "schema": { + "type": "integer", + "format": "date-time-ms" + } + }, { "name": "on", "in": "query", @@ -2740,6 +2749,12 @@ "type": "string", "format": "date-basic", "example": "20260320" + }, + "seenAt": { + "description": "A time in Unix milliseconds, among times of other forms.", + "type": "integer", + "format": "date-time-ms", + "example": 1795464914123 } }, "required": [ diff --git a/testdata/golden/pkg/golden/api.js b/testdata/golden/pkg/golden/api.js index 670a0e82..1427da3e 100644 --- a/testdata/golden/pkg/golden/api.js +++ b/testdata/golden/pkg/golden/api.js @@ -249,6 +249,7 @@ window.API = { if (params.cells?.length) raw.push("cells=" + join(params.cells, ",", escR)); if (params.every != null) q.set("every", String(params.every)); if (params.at != null) q.set("at", String(params.at)); + if (params.seen != null) q.set("seen", String(params.seen)); if (params.on != null) q.set("on", String(params.on)); if (params.modules?.length) raw.push("modules=" + join(params.modules, ",", esc)); if (params.since != null) q.set("since", String(params.since)); diff --git a/testdata/golden/pkg/golden/client.gen.go b/testdata/golden/pkg/golden/client.gen.go index de9d995e..12f659cd 100644 --- a/testdata/golden/pkg/golden/client.gen.go +++ b/testdata/golden/pkg/golden/client.gen.go @@ -1170,7 +1170,7 @@ func (c *Client) GetStatus(ctx context.Context) ([]byte, error) { func (c *Client) QueryStyles(ctx context.Context, page int, params QueryStylesParams) error { u := c.baseURL.JoinPath("queries", strconv.Itoa(page)) - q := make(url.Values, 23) + q := make(url.Values, 24) escaped := url.Values{} if len(params.Csv) > 0 { @@ -1286,6 +1286,10 @@ func (c *Client) QueryStyles(ctx context.Context, page int, params QueryStylesPa q["at"] = []string{strconv.Itoa(int(params.At.Unix()))} } + if !params.Seen.IsZero() { + q["seen"] = []string{strconv.FormatInt(params.Seen.UnixMilli(), 10)} + } + if params.On != (civil.Date{}) { q["on"] = []string{params.On.String()} } diff --git a/testdata/golden/pkg/golden/ir.json b/testdata/golden/pkg/golden/ir.json index e17da94e..41221c95 100644 --- a/testdata/golden/pkg/golden/ir.json +++ b/testdata/golden/pkg/golden/ir.json @@ -1303,6 +1303,17 @@ "isUnix": true, "description": "A Unix time." }, + { + "varName": "params.Seen", + "goName": "seen", + "fieldName": "Seen", + "jsonName": "seen", + "type": "time.Time", + "parseExpr": "strconv.ParseInt(%s, 10, 64)", + "parseConv": "time.UnixMilli(%s)", + "isUnixMilli": true, + "description": "A Unix time in milliseconds." + }, { "varName": "params.On", "goName": "on", @@ -2147,6 +2158,14 @@ "jsonTag": "json:\"settled,omitzero\"", "description": "A date in ISO 8601's basic form, among dates of other forms.", "isDateBasic": true + }, + { + "name": "SeenAt", + "jsonName": "seenAt", + "type": "time.Time", + "jsonTag": "json:\"seenAt,omitzero\"", + "description": "A time in Unix milliseconds, among times of other forms.", + "isUnixMilli": true } ] }, @@ -5440,5 +5459,8 @@ "basicDateMembers": [ "settled" ], + "unixMilliTimeMembers": [ + "seenAt" + ], "hasStringDateFields": true } \ No newline at end of file diff --git a/testdata/golden/pkg/golden/server.gen.go b/testdata/golden/pkg/golden/server.gen.go index 9ac77c82..97bd5479 100644 --- a/testdata/golden/pkg/golden/server.gen.go +++ b/testdata/golden/pkg/golden/server.gen.go @@ -1399,7 +1399,7 @@ func parseQueryStylesArgs(req *http.Request) (page int, params QueryStylesParams for k, vs := range query { switch k { - case "csv", "spaced", "piped", "r", "g", "name", "fade", "colorCsv", "colorPiped", "weights", "next", "paths", "cells", "every", "at", "on", "modules", "since", "day", "site", "ip", "level", "ratio", "v": + case "csv", "spaced", "piped", "r", "g", "name", "fade", "colorCsv", "colorPiped", "weights", "next", "paths", "cells", "every", "at", "seen", "on", "modules", "since", "day", "site", "ip", "level", "ratio", "v": continue } @@ -1452,6 +1452,15 @@ func parseQueryStylesArgs(req *http.Request) (page int, params QueryStylesParams params.At = time.Unix(v, 0) } + if s := query.Get("seen"); s != "" { + v, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return page, params, fmt.Errorf("invalid seen: %w", err) + } + + params.Seen = time.UnixMilli(v) + } + if s := query.Get("on"); s != "" { v, err := civil.ParseDate(s) if err != nil { diff --git a/testdata/golden/pkg/golden/types.gen.go b/testdata/golden/pkg/golden/types.gen.go index 42798061..0970d97f 100644 --- a/testdata/golden/pkg/golden/types.gen.go +++ b/testdata/golden/pkg/golden/types.gen.go @@ -27,12 +27,14 @@ var jsonOpts = json.JoinOptions( json.MarshalToFunc(jsonutil.DurationMarshalIntSeconds), json.MarshalToFunc(jsonutil.TimeMarshalIntUnixFor("at")), json.MarshalToFunc(jsonutil.DateMarshalIntUnixFor("expires", "raw")), + json.MarshalToFunc(jsonutil.TimeMarshalIntUnixMilliFor("seenAt")), json.MarshalToFunc(jsonutil.DateMarshalBasicFor("settled")), json.MarshalToFunc(jsonutil.DateMarshalZeroAsNull), )), json.WithUnmarshalers(json.JoinUnmarshalers( json.UnmarshalFromFunc(jsonutil.TimeUnmarshalIntUnixFor("at")), json.UnmarshalFromFunc(jsonutil.DateUnmarshalIntUnixFor("expires", "raw")), + json.UnmarshalFromFunc(jsonutil.TimeUnmarshalIntUnixMilliFor("seenAt")), json.UnmarshalFromFunc(jsonutil.DateUnmarshalBasicFor("settled")), json.UnmarshalFromFunc(jsonutil.URLUnmarshal), json.UnmarshalFromFunc(jsonutil.Float64UnmarshalStringOrNumber), @@ -53,6 +55,7 @@ var jsonOptsRequest = json.JoinOptions(jsonOpts, json.WithMarshalers(json.JoinMa json.MarshalToFunc(jsonutil.DurationMarshalIntSeconds), json.MarshalToFunc(jsonutil.TimeMarshalIntUnixFor("at")), json.MarshalToFunc(jsonutil.DateMarshalIntUnixFor("expires", "raw")), + json.MarshalToFunc(jsonutil.TimeMarshalIntUnixMilliFor("seenAt")), json.MarshalToFunc(jsonutil.DateMarshalBasicFor("settled")), json.MarshalToFunc(jsonutil.DateMarshalZeroAsNull), json.MarshalToFunc(func(enc *jsontext.Encoder, v Meta) error { @@ -89,6 +92,7 @@ var jsonOptsResponse = json.JoinOptions(jsonOpts, json.WithMarshalers(json.JoinM json.MarshalToFunc(jsonutil.DurationMarshalIntSeconds), json.MarshalToFunc(jsonutil.TimeMarshalIntUnixFor("at")), json.MarshalToFunc(jsonutil.DateMarshalIntUnixFor("expires", "raw")), + json.MarshalToFunc(jsonutil.TimeMarshalIntUnixMilliFor("seenAt")), json.MarshalToFunc(jsonutil.DateMarshalBasicFor("settled")), json.MarshalToFunc(jsonutil.DateMarshalZeroAsNull), json.MarshalToFunc(func(enc *jsontext.Encoder, v User) error { @@ -160,6 +164,8 @@ type QueryStylesParams struct { Every time.Duration // A Unix time. At time.Time + // A Unix time in milliseconds. + Seen time.Time // A date. On civil.Date // A named array: the parameter keeps its name. @@ -748,6 +754,8 @@ type DateWrapper struct { Fmt string `json:"fmt"` // A date in ISO 8601's basic form, among dates of other forms. Settled civil.Date `json:"settled,omitzero"` + // A time in Unix milliseconds, among times of other forms. + SeenAt time.Time `json:"seenAt,omitzero"` } // Emoji defines a model diff --git a/testdata/golden/pkg/golden/unix_test.go b/testdata/golden/pkg/golden/unix_test.go index 6a764471..9f674f52 100644 --- a/testdata/golden/pkg/golden/unix_test.go +++ b/testdata/golden/pkg/golden/unix_test.go @@ -1,7 +1,7 @@ // This file is written by hand, not by the generator. // -// It pins how dates and date-times that are integers of unix time are written among those that are strings: each -// as its own schema says, also through an embedded part and where a request leaves members out. +// It pins how dates and date-times that are integers of unix time, in seconds or milliseconds, are written among those +// that are strings: each as its own schema says, also through an embedded part and where a request leaves members out. package golden @@ -32,6 +32,12 @@ func TestUnix_AmongStrings(t *testing.T) { opts: jsonOpts, want: `{"raw":1759190400,"fmt":"2025-09-30"}`, }, + { + name: "a time in unix milliseconds keeps its milliseconds", + in: DateWrapper{Raw: day, Fmt: "2025-09-30", SeenAt: time.UnixMilli(1795464914123)}, + opts: jsonOpts, + want: `{"raw":1759190400,"fmt":"2025-09-30","seenAt":1795464914123}`, + }, { name: "a string date-time stays a string", in: Meta{Created: created, Expires: day}, diff --git a/vendor/github.com/MarkRosemaker/jsonutil/time.go b/vendor/github.com/MarkRosemaker/jsonutil/time.go index 97a49b2a..5a620ff8 100644 --- a/vendor/github.com/MarkRosemaker/jsonutil/time.go +++ b/vendor/github.com/MarkRosemaker/jsonutil/time.go @@ -62,6 +62,62 @@ func TimeUnmarshalIntUnixFor(names ...string) func(*jsontext.Decoder, *time.Time } } +// TimeMarshalIntUnixMilli is a custom marshaler for time.Time, marshaling them as integers representing unix time in +// milliseconds. +func TimeMarshalIntUnixMilli(enc *jsontext.Encoder, t time.Time) error { + if t.IsZero() { + return enc.WriteToken(jsontext.Int(0)) + } + + return enc.WriteToken(jsontext.Int(t.UnixMilli())) +} + +// TimeUnmarshalIntUnixMilli is a custom unmarshaler for time.Time, unmarshaling them from integers representing unix +// time in milliseconds. +func TimeUnmarshalIntUnixMilli(dec *jsontext.Decoder, d *time.Time) error { + var ms int64 + if err := json.UnmarshalDecode(dec, &ms); err != nil { + return err + } + + if ms == 0 { + *d = time.Time{} + } else { + *d = time.UnixMilli(ms) + } + + return nil +} + +// TimeMarshalIntUnixMilliFor returns a marshaler for time.Time that writes, as [TimeMarshalIntUnixMilli] does, the times +// held by an object member of one of the names given, or by an array such a member holds; see [DateMarshalIntUnixFor]. +func TimeMarshalIntUnixMilliFor(names ...string) func(*jsontext.Encoder, time.Time) error { + set := nameSet(names) + + return func(enc *jsontext.Encoder, t time.Time) error { + if !set[memberName(enc.StackPointer())] { + return errors.ErrUnsupported + } + + return TimeMarshalIntUnixMilli(enc, t) + } +} + +// TimeUnmarshalIntUnixMilliFor returns an unmarshaler for time.Time that reads, as [TimeUnmarshalIntUnixMilli] does, the +// times held by an object member of one of the names given, or by an array such a member holds; see +// [DateMarshalIntUnixFor]. +func TimeUnmarshalIntUnixMilliFor(names ...string) func(*jsontext.Decoder, *time.Time) error { + set := nameSet(names) + + return func(dec *jsontext.Decoder, t *time.Time) error { + if !set[memberName(dec.StackPointer())] { + return errors.ErrUnsupported + } + + return TimeUnmarshalIntUnixMilli(dec, t) + } +} + // timeAltLayout is a fallback layout for time strings that don't conform to RFC3339. const timeAltLayout = "Mon Jan 2 2006 15:04:05 MST-0700" diff --git a/vendor/github.com/MarkRosemaker/openapi/data_type_format.go b/vendor/github.com/MarkRosemaker/openapi/data_type_format.go index 0b499ad8..495b4b6a 100644 --- a/vendor/github.com/MarkRosemaker/openapi/data_type_format.go +++ b/vendor/github.com/MarkRosemaker/openapi/data_type_format.go @@ -39,6 +39,9 @@ const ( FormatDateBasic Format = "date-basic" // FormatDateTime represents a date-time. FormatDateTime Format = "date-time" + // FormatDateTimeMs represents a date-time written as an integer of unix milliseconds, such as 1795464914000. It is + // not one of JSON Schema's formats, but some APIs write a time this way. + FormatDateTimeMs Format = "date-time-ms" // FormatDuration represents a duration. FormatDuration Format = "duration" // FormatEmail represents an email. @@ -64,7 +67,7 @@ var allFormats = []Format{ FormatUint, FormatUint32, FormatUint64, FormatFloat, FormatDouble, FormatByte, FormatBinary, - FormatDate, FormatDateBasic, FormatDateTime, FormatDuration, + FormatDate, FormatDateBasic, FormatDateTime, FormatDateTimeMs, FormatDuration, FormatEmail, FormatPassword, FormatUUID, FormatURI, FormatURIRef, FormatZipCode, diff --git a/vendor/github.com/MarkRosemaker/openapi/schema.go b/vendor/github.com/MarkRosemaker/openapi/schema.go index fd455ea0..433f2b80 100644 --- a/vendor/github.com/MarkRosemaker/openapi/schema.go +++ b/vendor/github.com/MarkRosemaker/openapi/schema.go @@ -235,7 +235,7 @@ func (s *Schema) validateFormat() error { var types string switch s.Format { - case FormatInt32, FormatInt64, FormatUint, FormatUint32, FormatUint64: + case FormatInt32, FormatInt64, FormatUint, FormatUint32, FormatUint64, FormatDateTimeMs: if !s.allows(TypeInteger) { types = "integer" } diff --git a/vendor/modules.txt b/vendor/modules.txt index ee419488..859663a6 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -10,10 +10,10 @@ github.com/MarkRosemaker/errpath # github.com/MarkRosemaker/json2yaml v0.0.0-20261118230255-853c75cf2bf9 ## explicit; go 1.27 github.com/MarkRosemaker/json2yaml -# github.com/MarkRosemaker/jsonutil v0.0.0-20261118230255-4b04cfc02484 +# github.com/MarkRosemaker/jsonutil v0.0.0-20261125191625-3f67f86ead2a ## explicit; go 1.27 github.com/MarkRosemaker/jsonutil -# github.com/MarkRosemaker/openapi v0.0.0-20261124050252-52a60c76de04 +# github.com/MarkRosemaker/openapi v0.0.0-20261125191600-33a241ac282b ## explicit; go 1.27 github.com/MarkRosemaker/openapi # github.com/MarkRosemaker/openapi-compare v0.0.0-20261124050336-b439780a57a8