Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ experimental/mocks/service/catalog/mock_grants_interface.go linguist-generated=t
experimental/mocks/service/catalog/mock_metastores_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_model_versions_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_online_tables_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_policies_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_quality_monitors_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_registered_models_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_resource_quotas_interface.go linguist-generated=true
Expand All @@ -34,6 +35,7 @@ experimental/mocks/service/catalog/mock_storage_credentials_interface.go linguis
experimental/mocks/service/catalog/mock_system_schemas_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_table_constraints_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_tables_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_temporary_path_credentials_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_temporary_table_credentials_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_volumes_interface.go linguist-generated=true
experimental/mocks/service/catalog/mock_workspace_bindings_interface.go linguist-generated=true
Expand Down
88 changes: 88 additions & 0 deletions common/types/duration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package types

import (
"encoding/json"
"fmt"
"net/url"
"time"
)

// Duration is a wrapper for time.Duration to provide custom marshaling
// for JSON and URL query strings.
//
// It embeds time.Duration, so all standard methods (Seconds, String, etc.)
// are directly accessible. The underlying time.Duration value can be
// accessed via the .Duration field.
//
// Example:
//
// customDur := types.NewDuration(30 * time.Second)
// goDur := customDur.Duration // Access the underlying time.Duration
type Duration struct {
time.Duration

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought this would be a wrapper over the Google types, as the marshalling/unmarshalling function will be defined by the Google library. It's just that it is not a JSON marshal.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We were split between native types (better CUX) and well known types (easier code) and decided for the second. Since well known types do support native json marshall, we do need to wrap and convert anyway. So the reason to use well known does not exist anymore.

}

// NewDuration creates a custom Duration from a standard time.Duration.
func NewDuration(d time.Duration) Duration {
return Duration{Duration: d}
}

// MarshalJSON implements the json.Marshaler interface by formatting the
// duration as a string according to Google Well Known Type
func (d Duration) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, d.ToWireFormat())), nil
}

// String returns a string representation of Duration
// which follows the wire format from Google Well Known Type:
// a String that ends in s to indicate seconds and is preceded by
// the number of seconds, with nanoseconds expressed as fractional seconds.
// https://protobuf.dev/reference/protobuf/google.protobuf/#duration
func (d Duration) ToWireFormat() string {
// We do not use the standard time.Duration.String() method because it
// loses precision when converting to a string.

// Get the total nanoseconds as a precise integer.
nanos := d.Duration.Nanoseconds()

// Calculate seconds and fractional nanoseconds.
secs := nanos / 1_000_000_000
fracNanos := nanos % 1_000_000_000

// Format the string, ensuring the fractional part is zero-padded to 9 digits.
// This correctly handles both positive and negative durations.
if nanos < 0 {
// For negative values, both parts should be negative.
secs = -(-nanos / 1_000_000_000)
fracNanos = -(-nanos % 1_000_000_000)
return fmt.Sprintf(`%d.%09ds`, secs, -fracNanos)
}

return fmt.Sprintf(`%d.%09ds`, secs, fracNanos)
}

// EncodeValues implements the query.Encoder interface by formatting the
// duration as a string, like "3.3s".
func (d Duration) EncodeValues(key string, v *url.Values) error {
v.Set(key, d.ToWireFormat())
return nil
}

// UnmarshalJSON implements the json.Unmarshaler interface. It can parse a
// duration from the Google well-known type format (e.g., "3.123s").
func (d *Duration) UnmarshalJSON(b []byte) error {
if d == nil {
return fmt.Errorf("json.Unmarshal on nil pointer")
}
// Remove the quotes from the string
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
dur, err := time.ParseDuration(s)
if err != nil {
return err
}
*d = NewDuration(dur)
return nil
}
252 changes: 252 additions & 0 deletions common/types/duration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
package types

import (
"encoding/json"
"net/url"
"testing"
"time"
)

func TestDuration_MarshalJSON(t *testing.T) {
tests := []struct {
name string
duration Duration
expected string
wantErr bool
}{
{
name: "zero duration",
duration: NewDuration(0),
expected: "0.000000000s",
},
{
name: "positive duration",
duration: NewDuration(5 * time.Second),
expected: "5.000000000s",
},
{
name: "negative duration",
duration: NewDuration(-2 * time.Minute),
expected: "-120.000000000s",
},
{
name: "negative duration with fractional seconds",
duration: NewDuration(-2*time.Minute + 100*time.Millisecond),
expected: "-119.900000000s",
},
{
name: "fractional seconds",
duration: NewDuration(1500 * time.Millisecond),
expected: "1.500000000s",
},
{
name: "large duration",
duration: NewDuration(9223372036*time.Second + 854775000*time.Nanosecond),
expected: "9223372036.854775000s",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := tt.duration.MarshalJSON()
if (err != nil) != tt.wantErr {
t.Errorf("Duration.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
return
}
if string(result) != `"`+tt.expected+`"` {
t.Errorf("Duration.MarshalJSON() = %v, want %v", string(result), `"`+tt.expected+`"`)
}
})
}
}

func TestDuration_UnmarshalJSON(t *testing.T) {
tests := []struct {
name string
input string
want Duration
wantErr bool
}{
{
name: "zero duration",
input: `"0s"`,
want: NewDuration(0),
wantErr: false,
},
{
name: "positive duration",
input: `"5s"`,
want: NewDuration(5 * time.Second),
wantErr: false,
},
{
name: "negative duration",
input: `"-2s"`,
want: NewDuration(-2 * time.Second),
wantErr: false,
},
{
name: "negative duration with fractional seconds",
input: `"-2.1s"`,
want: NewDuration(-2*time.Second - 100*time.Millisecond),
wantErr: false,
},
{
name: "fractional seconds",
input: `"1.5s"`,
want: NewDuration(1500 * time.Millisecond),
wantErr: false,
},
{
name: "large duration",
input: `"9223372036.854775000s"`,
want: NewDuration(9223372036*time.Second + 854775000*time.Nanosecond),
wantErr: false,
},
{
name: "invalid duration format",
input: `"invalid"`,
want: NewDuration(0),
wantErr: true,
},
{
name: "empty string",
input: `""`,
want: NewDuration(0),
wantErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var d Duration
err := d.UnmarshalJSON([]byte(tt.input))
if (err != nil) != tt.wantErr {
t.Errorf("Duration.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && d != tt.want {
t.Errorf("Duration.UnmarshalJSON() = %v, want %v", d, tt.want)
}
})
}
}

func TestDuration_UnmarshalJSON_NilPointer(t *testing.T) {
var d *Duration
err := d.UnmarshalJSON([]byte(`"5s"`))
if err == nil {
t.Error("Duration.UnmarshalJSON() on nil pointer should return error")
}
expectedErr := "json.Unmarshal on nil pointer"
if err.Error() != expectedErr {
t.Errorf("Duration.UnmarshalJSON() error = %v, want %v", err.Error(), expectedErr)
}
}

func TestDuration_EncodeValues(t *testing.T) {
tests := []struct {
name string
duration Duration
key string
expected string
}{
{
name: "zero duration",
duration: NewDuration(0),
key: "duration",
expected: "0.000000000s",
},
{
name: "positive duration",
duration: NewDuration(5 * time.Second),
key: "timeout",
expected: "5.000000000s",
},
{
name: "negative duration",
duration: NewDuration(-2 * time.Minute),
key: "delay",
expected: "-120.000000000s",
},
{
name: "fractional seconds",
duration: NewDuration(1500 * time.Millisecond),
key: "interval",
expected: "1.500000000s",
},
{
name: "large duration",
duration: NewDuration(24 * time.Hour),
key: "period",
expected: "86400.000000000s",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
values := url.Values{}
err := tt.duration.EncodeValues(tt.key, &values)
if err != nil {
t.Errorf("Duration.EncodeValues() error = %v", err)
return
}
result := values.Get(tt.key)
if result != tt.expected {
t.Errorf("Duration.EncodeValues() = %v, want %v", result, tt.expected)
}
})
}
}

func TestDuration_JSONRoundTrip(t *testing.T) {
tests := []struct {
name string
duration Duration
}{
{
name: "zero duration",
duration: NewDuration(0),
},
{
name: "positive duration",
duration: NewDuration(5 * time.Second),
},
{
name: "negative duration",
duration: NewDuration(-2 * time.Minute),
},
{
name: "fractional seconds",
duration: NewDuration(1500 * time.Millisecond),
},
{
name: "complex duration",
duration: NewDuration(1*time.Hour + 2*time.Minute + 3*time.Second),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Marshal to JSON
jsonData, err := json.Marshal(tt.duration)
if err != nil {
t.Errorf("json.Marshal() error = %v", err)
return
}

// Unmarshal from JSON
var result Duration
err = json.Unmarshal(jsonData, &result)
if err != nil {
t.Errorf("json.Unmarshal() error = %v", err)
return
}

// Check that the round trip preserved the value
if result != tt.duration {
t.Errorf("JSON round trip failed: original = %v, result = %v", tt.duration, result)
}
})
}
}
Loading
Loading