| 1 | // Copyright 2018 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package types |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "reflect" |
| 20 | "strconv" |
| 21 | "strings" |
| 22 | "time" |
| 23 | |
| 24 | "github.com/google/cel-go/common/overloads" |
| 25 | "github.com/google/cel-go/common/types/ref" |
| 26 | |
| 27 | anypb "google.golang.org/protobuf/types/known/anypb" |
| 28 | structpb "google.golang.org/protobuf/types/known/structpb" |
| 29 | tpb "google.golang.org/protobuf/types/known/timestamppb" |
| 30 | ) |
| 31 | |
| 32 | // Timestamp type implementation which supports add, compare, and subtract |
| 33 | // operations. Timestamps are also capable of participating in dynamic |
| 34 | // function dispatch to instance methods. |
| 35 | type Timestamp struct { |
| 36 | time.Time |
| 37 | } |
| 38 | |
| 39 | func timestampOf(t time.Time) Timestamp { |
| 40 | // Note that this function does not validate that time.Time is in our supported range. |
| 41 | return Timestamp{Time: t} |
| 42 | } |
| 43 | |
| 44 | const ( |
| 45 | // The number of seconds between year 1 and year 1970. This is borrowed from |
| 46 | // https://golang.org/src/time/time.go. |
| 47 | unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * (60 * 60 * 24) |
| 48 | |
| 49 | // Number of seconds between `0001-01-01T00:00:00Z` and the Unix epoch. |
| 50 | minUnixTime int64 = -62135596800 |
| 51 | // Number of seconds between `9999-12-31T23:59:59.999999999Z` and the Unix epoch. |
| 52 | maxUnixTime int64 = 253402300799 |
| 53 | ) |
| 54 | |
| 55 | // Add implements traits.Adder.Add. |
| 56 | func (t Timestamp) Add(other ref.Val) ref.Val { |
| 57 | switch other.Type() { |
| 58 | case DurationType: |
| 59 | return other.(Duration).Add(t) |
| 60 | } |
| 61 | return MaybeNoSuchOverloadErr(other) |
| 62 | } |
| 63 | |
| 64 | // Compare implements traits.Comparer.Compare. |
| 65 | func (t Timestamp) Compare(other ref.Val) ref.Val { |
| 66 | if TimestampType != other.Type() { |
| 67 | return MaybeNoSuchOverloadErr(other) |
| 68 | } |
| 69 | ts1 := t.Time |
| 70 | ts2 := other.(Timestamp).Time |
| 71 | switch { |
| 72 | case ts1.Before(ts2): |
| 73 | return IntNegOne |
| 74 | case ts1.After(ts2): |
| 75 | return IntOne |
| 76 | default: |
| 77 | return IntZero |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | // ConvertToNative implements ref.Val.ConvertToNative. |
| 82 | func (t Timestamp) ConvertToNative(typeDesc reflect.Type) (any, error) { |
| 83 | // If the timestamp is already assignable to the desired type return it. |
| 84 | if reflect.TypeOf(t.Time).AssignableTo(typeDesc) { |
| 85 | return t.Time, nil |
| 86 | } |
| 87 | if reflect.TypeOf(t).AssignableTo(typeDesc) { |
| 88 | return t, nil |
| 89 | } |
| 90 | switch typeDesc { |
| 91 | case anyValueType: |
| 92 | // Pack the underlying time as a tpb.Timestamp into an Any value. |
| 93 | return anypb.New(tpb.New(t.Time)) |
| 94 | case JSONValueType: |
| 95 | // CEL follows the proto3 to JSON conversion which formats as an RFC 3339 encoded JSON |
| 96 | // string. |
| 97 | v := t.ConvertToType(StringType) |
| 98 | if IsError(v) { |
| 99 | return nil, v.(*Err) |
| 100 | } |
| 101 | return structpb.NewStringValue(string(v.(String))), nil |
| 102 | case timestampValueType: |
| 103 | // Unwrap the underlying tpb.Timestamp. |
| 104 | return tpb.New(t.Time), nil |
| 105 | } |
| 106 | return nil, fmt.Errorf("type conversion error from 'Timestamp' to '%v'", typeDesc) |
| 107 | } |
| 108 | |
| 109 | // ConvertToType implements ref.Val.ConvertToType. |
| 110 | func (t Timestamp) ConvertToType(typeVal ref.Type) ref.Val { |
| 111 | switch typeVal { |
| 112 | case StringType: |
| 113 | return String(t.Format(time.RFC3339Nano)) |
| 114 | case IntType: |
| 115 | // Return the Unix time in seconds since 1970 |
| 116 | return Int(t.Unix()) |
| 117 | case TimestampType: |
| 118 | return t |
| 119 | case TypeType: |
| 120 | return TimestampType |
| 121 | } |
| 122 | return NewErr("type conversion error from '%s' to '%s'", TimestampType, typeVal) |
| 123 | } |
| 124 | |
| 125 | // Equal implements ref.Val.Equal. |
| 126 | func (t Timestamp) Equal(other ref.Val) ref.Val { |
| 127 | otherTime, ok := other.(Timestamp) |
| 128 | return Bool(ok && t.Time.Equal(otherTime.Time)) |
| 129 | } |
| 130 | |
| 131 | // IsZeroValue returns true if the timestamp is epoch 0. |
| 132 | func (t Timestamp) IsZeroValue() bool { |
| 133 | return t.IsZero() |
| 134 | } |
| 135 | |
| 136 | // Receive implements traits.Receiver.Receive. |
| 137 | func (t Timestamp) Receive(function string, overload string, args []ref.Val) ref.Val { |
| 138 | switch len(args) { |
| 139 | case 0: |
| 140 | if f, found := timestampZeroArgOverloads[function]; found { |
| 141 | return f(t.Time) |
| 142 | } |
| 143 | case 1: |
| 144 | if f, found := timestampOneArgOverloads[function]; found { |
| 145 | return f(t.Time, args[0]) |
| 146 | } |
| 147 | } |
| 148 | return NoSuchOverloadErr() |
| 149 | } |
| 150 | |
| 151 | // Subtract implements traits.Subtractor.Subtract. |
| 152 | func (t Timestamp) Subtract(subtrahend ref.Val) ref.Val { |
| 153 | switch subtrahend.Type() { |
| 154 | case DurationType: |
| 155 | dur := subtrahend.(Duration) |
| 156 | val, err := subtractTimeDurationChecked(t.Time, dur.Duration) |
| 157 | if err != nil { |
| 158 | return WrapErr(err) |
| 159 | } |
| 160 | return timestampOf(val) |
| 161 | case TimestampType: |
| 162 | t2 := subtrahend.(Timestamp).Time |
| 163 | val, err := subtractTimeChecked(t.Time, t2) |
| 164 | if err != nil { |
| 165 | return WrapErr(err) |
| 166 | } |
| 167 | return durationOf(val) |
| 168 | } |
| 169 | return MaybeNoSuchOverloadErr(subtrahend) |
| 170 | } |
| 171 | |
| 172 | // Type implements ref.Val.Type. |
| 173 | func (t Timestamp) Type() ref.Type { |
| 174 | return TimestampType |
| 175 | } |
| 176 | |
| 177 | // Value implements ref.Val.Value. |
| 178 | func (t Timestamp) Value() any { |
| 179 | return t.Time |
| 180 | } |
| 181 | |
| 182 | func (t Timestamp) format(sb *strings.Builder) { |
| 183 | fmt.Fprintf(sb, `timestamp("%s")`, t.Time.UTC().Format(time.RFC3339Nano)) |
| 184 | } |
| 185 | |
| 186 | var ( |
| 187 | timestampValueType = reflect.TypeOf(&tpb.Timestamp{}) |
| 188 | |
| 189 | timestampZeroArgOverloads = map[string]func(time.Time) ref.Val{ |
| 190 | overloads.TimeGetFullYear: timestampGetFullYear, |
| 191 | overloads.TimeGetMonth: timestampGetMonth, |
| 192 | overloads.TimeGetDayOfYear: timestampGetDayOfYear, |
| 193 | overloads.TimeGetDate: timestampGetDayOfMonthOneBased, |
| 194 | overloads.TimeGetDayOfMonth: timestampGetDayOfMonthZeroBased, |
| 195 | overloads.TimeGetDayOfWeek: timestampGetDayOfWeek, |
| 196 | overloads.TimeGetHours: timestampGetHours, |
| 197 | overloads.TimeGetMinutes: timestampGetMinutes, |
| 198 | overloads.TimeGetSeconds: timestampGetSeconds, |
| 199 | overloads.TimeGetMilliseconds: timestampGetMilliseconds} |
| 200 | |
| 201 | timestampOneArgOverloads = map[string]func(time.Time, ref.Val) ref.Val{ |
| 202 | overloads.TimeGetFullYear: timestampGetFullYearWithTz, |
| 203 | overloads.TimeGetMonth: timestampGetMonthWithTz, |
| 204 | overloads.TimeGetDayOfYear: timestampGetDayOfYearWithTz, |
| 205 | overloads.TimeGetDate: timestampGetDayOfMonthOneBasedWithTz, |
| 206 | overloads.TimeGetDayOfMonth: timestampGetDayOfMonthZeroBasedWithTz, |
| 207 | overloads.TimeGetDayOfWeek: timestampGetDayOfWeekWithTz, |
| 208 | overloads.TimeGetHours: timestampGetHoursWithTz, |
| 209 | overloads.TimeGetMinutes: timestampGetMinutesWithTz, |
| 210 | overloads.TimeGetSeconds: timestampGetSecondsWithTz, |
| 211 | overloads.TimeGetMilliseconds: timestampGetMillisecondsWithTz} |
| 212 | ) |
| 213 | |
| 214 | type timestampVisitor func(time.Time) ref.Val |
| 215 | |
| 216 | func timestampGetFullYear(t time.Time) ref.Val { |
| 217 | return Int(t.Year()) |
| 218 | } |
| 219 | func timestampGetMonth(t time.Time) ref.Val { |
| 220 | // CEL spec indicates that the month should be 0-based, but the Time value |
| 221 | // for Month() is 1-based. |
| 222 | return Int(t.Month() - 1) |
| 223 | } |
| 224 | func timestampGetDayOfYear(t time.Time) ref.Val { |
| 225 | return Int(t.YearDay() - 1) |
| 226 | } |
| 227 | func timestampGetDayOfMonthZeroBased(t time.Time) ref.Val { |
| 228 | return Int(t.Day() - 1) |
| 229 | } |
| 230 | func timestampGetDayOfMonthOneBased(t time.Time) ref.Val { |
| 231 | return Int(t.Day()) |
| 232 | } |
| 233 | func timestampGetDayOfWeek(t time.Time) ref.Val { |
| 234 | return Int(t.Weekday()) |
| 235 | } |
| 236 | func timestampGetHours(t time.Time) ref.Val { |
| 237 | return Int(t.Hour()) |
| 238 | } |
| 239 | func timestampGetMinutes(t time.Time) ref.Val { |
| 240 | return Int(t.Minute()) |
| 241 | } |
| 242 | func timestampGetSeconds(t time.Time) ref.Val { |
| 243 | return Int(t.Second()) |
| 244 | } |
| 245 | func timestampGetMilliseconds(t time.Time) ref.Val { |
| 246 | return Int(t.Nanosecond() / 1000000) |
| 247 | } |
| 248 | |
| 249 | func timestampGetFullYearWithTz(t time.Time, tz ref.Val) ref.Val { |
| 250 | return timeZone(tz, timestampGetFullYear)(t) |
| 251 | } |
| 252 | func timestampGetMonthWithTz(t time.Time, tz ref.Val) ref.Val { |
| 253 | return timeZone(tz, timestampGetMonth)(t) |
| 254 | } |
| 255 | func timestampGetDayOfYearWithTz(t time.Time, tz ref.Val) ref.Val { |
| 256 | return timeZone(tz, timestampGetDayOfYear)(t) |
| 257 | } |
| 258 | func timestampGetDayOfMonthZeroBasedWithTz(t time.Time, tz ref.Val) ref.Val { |
| 259 | return timeZone(tz, timestampGetDayOfMonthZeroBased)(t) |
| 260 | } |
| 261 | func timestampGetDayOfMonthOneBasedWithTz(t time.Time, tz ref.Val) ref.Val { |
| 262 | return timeZone(tz, timestampGetDayOfMonthOneBased)(t) |
| 263 | } |
| 264 | func timestampGetDayOfWeekWithTz(t time.Time, tz ref.Val) ref.Val { |
| 265 | return timeZone(tz, timestampGetDayOfWeek)(t) |
| 266 | } |
| 267 | func timestampGetHoursWithTz(t time.Time, tz ref.Val) ref.Val { |
| 268 | return timeZone(tz, timestampGetHours)(t) |
| 269 | } |
| 270 | func timestampGetMinutesWithTz(t time.Time, tz ref.Val) ref.Val { |
| 271 | return timeZone(tz, timestampGetMinutes)(t) |
| 272 | } |
| 273 | func timestampGetSecondsWithTz(t time.Time, tz ref.Val) ref.Val { |
| 274 | return timeZone(tz, timestampGetSeconds)(t) |
| 275 | } |
| 276 | func timestampGetMillisecondsWithTz(t time.Time, tz ref.Val) ref.Val { |
| 277 | return timeZone(tz, timestampGetMilliseconds)(t) |
| 278 | } |
| 279 | |
| 280 | func timeZone(tz ref.Val, visitor timestampVisitor) timestampVisitor { |
| 281 | return func(t time.Time) ref.Val { |
| 282 | if StringType != tz.Type() { |
| 283 | return MaybeNoSuchOverloadErr(tz) |
| 284 | } |
| 285 | val := string(tz.(String)) |
| 286 | ind := strings.Index(val, ":") |
| 287 | if ind == -1 { |
| 288 | loc, err := time.LoadLocation(val) |
| 289 | if err != nil { |
| 290 | return WrapErr(err) |
| 291 | } |
| 292 | return visitor(t.In(loc)) |
| 293 | } |
| 294 | |
| 295 | // If the input is not the name of a timezone (for example, 'US/Central'), it should be a numerical offset from UTC |
| 296 | // in the format ^(+|-)(0[0-9]|1[0-4]):[0-5][0-9]$. The numerical input is parsed in terms of hours and minutes. |
| 297 | hr, err := strconv.Atoi(string(val[0:ind])) |
| 298 | if err != nil { |
| 299 | return WrapErr(err) |
| 300 | } |
| 301 | min, err := strconv.Atoi(string(val[ind+1:])) |
| 302 | if err != nil { |
| 303 | return WrapErr(err) |
| 304 | } |
| 305 | var offset int |
| 306 | if string(val[0]) == "-" { |
| 307 | offset = hr*60 - min |
| 308 | } else { |
| 309 | offset = hr*60 + min |
| 310 | } |
| 311 | secondsEastOfUTC := int((time.Duration(offset) * time.Minute).Seconds()) |
| 312 | timezone := time.FixedZone("", secondsEastOfUTC) |
| 313 | return visitor(t.In(timezone)) |
| 314 | } |
| 315 | } |