From e490c4d534ff9aca2e39b3edebc99dcf5d85928a Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 21:35:25 -0600 Subject: [PATCH 1/8] feat(timestreamquery): the documented function reference, interval arithmetic, non-finite doubles, guarded constants Adds the documented functions the engine lacked (array set operations, zip, repeat, shuffle, base conversion, bit operations, skewness and regression aggregates, n-ary max_by and min_by, weighted percentiles, quantified comparisons, VALUES lists and more) and asserts the reference examples. Intervals add, subtract, scale and compare. NaN and Infinity come out of every producing expression consistently. A constant inside an untaken branch is no longer evaluated. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/timestreamquery/PARITY.md | 34 +- services/timestreamquery/query_execution.go | 4 +- services/timestreamquery/ts_aggs.go | 2 +- services/timestreamquery/ts_aggs_set.go | 421 +++++++++++++ services/timestreamquery/ts_arith.go | 152 ++++- .../timestreamquery/ts_arith_corpus_test.go | 2 +- services/timestreamquery/ts_cast.go | 19 +- .../timestreamquery/ts_doc_functions_test.go | 558 ++++++++++++++++++ services/timestreamquery/ts_duration.go | 138 +++++ services/timestreamquery/ts_engine.go | 2 +- services/timestreamquery/ts_funcs.go | 73 ++- services/timestreamquery/ts_funcs_array.go | 299 ++++++++++ services/timestreamquery/ts_funcs_clock.go | 176 ++++++ services/timestreamquery/ts_funcs_text.go | 251 ++++++++ services/timestreamquery/ts_functions_test.go | 7 + services/timestreamquery/ts_infer.go | 5 + services/timestreamquery/ts_infer_checked.go | 329 ++++++++++- services/timestreamquery/ts_infer_funcs.go | 23 +- .../ts_infer_robust_internal_test.go | 16 + services/timestreamquery/ts_regexp_lambda.go | 166 ++++++ services/timestreamquery/ts_render.go | 2 +- services/timestreamquery/ts_rewrite.go | 13 + services/timestreamquery/ts_series.go | 18 +- services/timestreamquery/ts_sqlexpr.go | 14 +- services/timestreamquery/ts_sqllex.go | 13 +- services/timestreamquery/ts_sqlparse.go | 2 +- services/timestreamquery/ts_syntax_rewrite.go | 330 +++++++++++ .../ts_value_rewrite_internal_test.go | 229 +++++++ .../ts_value_semantics_test.go | 222 +++++++ services/timestreamquery/ts_values.go | 249 ++++++++ services/timestreamquery/unload.go | 4 +- 31 files changed, 3710 insertions(+), 63 deletions(-) create mode 100644 services/timestreamquery/ts_aggs_set.go create mode 100644 services/timestreamquery/ts_doc_functions_test.go create mode 100644 services/timestreamquery/ts_funcs_array.go create mode 100644 services/timestreamquery/ts_funcs_clock.go create mode 100644 services/timestreamquery/ts_funcs_text.go create mode 100644 services/timestreamquery/ts_regexp_lambda.go create mode 100644 services/timestreamquery/ts_syntax_rewrite.go create mode 100644 services/timestreamquery/ts_value_rewrite_internal_test.go create mode 100644 services/timestreamquery/ts_value_semantics_test.go create mode 100644 services/timestreamquery/ts_values.go diff --git a/services/timestreamquery/PARITY.md b/services/timestreamquery/PARITY.md index d655c98b0e..137327e89d 100644 --- a/services/timestreamquery/PARITY.md +++ b/services/timestreamquery/PARITY.md @@ -42,10 +42,9 @@ items_still_open: - "Static type inference (ts_infer.go) types every select-list expression before execution; a query it cannot parse or type keeps the older value-based column typing (and syntactic boolean/interval typing, ts_boolean.go), an empty result of such a column reports VARCHAR, and the checked arithmetic and casts below do not apply to it (SQLite semantics: integer overflow widens, CAST(double AS bigint) truncates, TRY_CAST of an unparsable string yields 0, division by zero yields NULL). Remaining sites: positional ? markers (PrepareQuery reports them as param1.. VARCHAR; the PrepareQuery page documents only @identifier names); an @name in the select list or compared with another untyped operand (its type depends on a value no request supplies; PrepareQuery reports VARCHAR); lambdas outside filter, transform, reduce, zip_with, the *_match functions and the regexp_replace lambda; transform() over a timeseries (the engine has no implementation); map-typed functions (map, map_agg, map_keys, map_values, histogram); a row field name that does not exist and row[i] with a non-literal i; any function without a return-type rule (SQLite built-ins outside the Timestream function list)" - "Unverified against the service: integer literals are typed INTEGER when they fit 32 bits else BIGINT (supported-data-types.html lists int and bigint but not which a literal gets; the SDK ScalarType enum has INTEGER, appended after UNKNOWN, and string-functions.html lists codepoint as integer, so the service emits it for something, but no recorded real response in the repo or the documentation shows a literal's ColumnInfo), and typeof() prints array(T), row(name T, ...) and timeseries(T) for nested types (array-functions.html writes output types as array(bigint), array(varchar), array(timestamp) and array(row), which is notation for function signatures, not typeof output; no page shows typeof of a row or timeseries)" - "Checked arithmetic and casts: the error type (ValidationException) and message wording (\"bigint addition overflow: A + B\", \"Division by zero\", \"Cannot cast 'x' to BIGINT\", \"Out of range for integer: N\", \"Value cannot be cast to timestamp: x\") follow the Presto/Trino family from memory; no Timestream page quotes them. CAST(double AS bigint) rounds half away from zero on the same basis. try() maps a failure anywhere inside its argument to NULL for the failing operation, which differs from the family only when a NULL changes a surrounding coalesce or CASE" - - "Documented functions the engine does not implement (calls fail with 'Function not registered' or 'wrong number of arguments'; return-type rules exist): array_intersect, array_union, array_except, shuffle, repeat, zip, from_base, to_base, strrpos, bitwise_and_agg, bitwise_or_agg, skewness, regexp_replace with a lambda, max_by/min_by(x, y, n) and approx_percentile with weights. max(x, n), min(x, n) and approx_percentile(x, ARRAY[...]) return the documented arrays (n largest or smallest first, the value at each percentage in order, NULL for no input); their n bound (1-10000), percentage range (0-1) and error wording are from the engine family, not a Timestream page, and they are not usable as window functions" - - "NaN has no SQLite representation, so DOUBLE division or modulo by zero yields NaN as the text 'NaN' only where the result is rendered (a top-level select item), under a CAST to anything but DOUBLE and as the argument of is_nan, is_finite and is_infinite; anywhere else a NaN is NULL, as before checked arithmetic, and CAST('NaN' AS double) travels as text so arithmetic and comparisons on it are wrong. Infinity and -Infinity are real doubles and behave normally" - - "A checked arithmetic or cast rewrite that fails to translate or prepare (anything but a checked function rejecting a value) reruns the query without the checked rewrites, so such a query keeps the older semantics (overflow widens, division by zero is NULL, casts truncate) instead of failing; constant subexpressions such as a division by a literal zero are evaluated before any CASE or AND that would guard them" - - "Interval arithmetic between two intervals (SELECT 1h + 30m, ago(2m + 30s)) fails with TYPE_MISMATCH; the checked rewrite does not touch these operators" + - "Documented functions: every function on the Timestream mathematical, string, array, bitwise, regular expression, date/time, aggregate, window, conditional, comparison and time series pages is implemented except one example: parse_datetime with a zone-abbreviation pattern (date-time-functions.html: parse_datetime('2019-12-29 10:10 PST', 'uuuu-LL-dd HH:mm z') returns 2019-12-29 18:10:00.000000000) fails with 'Invalid format' because the base engine's parser has no zone abbreviations. max(x, n), min(x, n) and approx_percentile(x, ARRAY[...]) are not usable as window functions (they raise a clear error); the aggregates added in the reference function pass are. Argument bounds and error wording come from the engine family, not a Timestream page, for: max(x, n)/min(x, n) n 1-10000, max_by/min_by(x, y, n) n 1-10000 ('third argument of max_by must be a positive integer'), approx_percentile percentage range 0-1 and weight/accuracy checks, approx_distinct(x, e) with e in [0.0040625, 0.26] (the e range itself is on aggregate-functions.html), repeat count 0-10000, zip of 2 to 5 arrays, from_base/to_base radix 2-36, strpos/strrpos with overlapping matches and 'instance' must be a positive number, strpos/strrpos(x, '') = 1, skewness and the regr_* functions returning NULL for fewer than 3 rows or no variance in x, replace(x, '', y) inserting y between characters" + - "NaN has no SQLite representation (a NaN stored in a REAL column becomes NULL), so a NaN DOUBLE is the text 'NaN' only where it is rendered (a top-level select item with no CTE), under a CAST to anything but DOUBLE, as the argument of is_nan/is_finite/is_infinite, or as an operand of DOUBLE arithmetic or comparison that is itself rewritten (an operand subtree containing nan(), infinity(), a division, a modulo, a CAST/typed literal to DOUBLE, or sqrt/ln/log10/log2/acos/asin/acosh/atanh/power/pow); there nan(), CAST('NaN' AS double), 0e0/0e0, sqrt(-1), ln(-1), infinity() - infinity() and nan() + 1 give NaN, ln(0) gives -Infinity, nan() = nan() is false and nan() <> nan() is true. Everywhere else a NaN is NULL: a NaN passed through a subquery or CTE column, ORDER BY, GROUP BY, DISTINCT, an aggregate (sum, min, max, avg over a NaN is not NaN), a window function, sign(), abs(), round() and similar numeric functions, or arithmetic whose operands the rewrite cannot see (a column holding a NaN, which the engine cannot store). NaN ordering (last, greatest) therefore does not hold. Infinity and -Infinity are real doubles and behave normally; a DOUBLE function rewritten for NaN is a Go function, not the native SQLite one, so its last digit can differ from SQLite's libm" + - "A checked arithmetic or cast rewrite that fails to translate or prepare (anything but a checked function rejecting a value) reruns the query without the checked rewrites, so such a query keeps the older semantics (overflow widens, division by zero is NULL, casts truncate) instead of failing" structural_gaps: - "CreateScheduledQuery KmsKeyId is stored and echoed, but there is no at-rest encryption layer to apply it to." @@ -120,7 +119,7 @@ string-functions.html (output types), mathematical-functions.html (e(), rand(), - When the static types of both operands are integral the rewriter emits ts_add/sub/mul/div/mod32|64 (ts_neg, ts_abs, mod() likewise, ts_sum for SUM over an integral argument, windows included): overflow, and division or modulo by zero, fail the query; division truncates toward zero and modulo follows the dividend. DOUBLE division and modulo go through ts_ddiv/ts_dmod (Infinity, -Infinity, NaN as the family does; NaN travels as - the text "NaN" because SQLite stores NaN as NULL); other DOUBLE arithmetic still runs natively. CAST/TRY_CAST between integer, bigint, double, + the text "NaN" because SQLite stores NaN as NULL); other DOUBLE arithmetic runs natively unless an operand can be NaN or infinite (see the NaN clause). CAST/TRY_CAST between integer, bigint, double, boolean, varchar and from varchar to timestamp/date/time go through ts_cast (ts_cast.go); typed literals such as bigint 'x' do too. try() marks everything inside it non-failing. The functions return an error or NULL for NULL, text or otherwise unexpected arguments and never panic. - random(n) returns the argument's integer type, random()/rand() DOUBLE, e() is registered. codepoint() is INTEGER (string-functions.html). @@ -130,6 +129,13 @@ string-functions.html (output types), mathematical-functions.html (e(), rand(), ## Emulator choices where the vendor is silent +- Not-found behaviours added with the reference function pass, each checked against the Timestream pages (they give signatures and one example, no + edge cases) and taken from the Presto/Trino family: array_union/array_intersect/array_except keep the first occurrence order of x then y and + treat 1 and 1.0 as equal; shuffle is a uniform permutation; a negative interval renders as `-0 01:00:00.000000000`; interval * or / a double + rounds to a whole nanosecond and interval / 0 is a ValidationException "Division by zero"; timestamp +/- a computed interval fails on int64 + overflow; date_add/date_diff on TIME wrap around midnight and accept millisecond..hour only; quantified comparisons + (`x op ALL|ANY|SOME (subquery)`) follow SQL three-valued logic over a single-column subquery; position(x IN y) is strpos(y, x); the + sequence() size cap stays at the existing 1,000,000 elements because no Timestream page states a limit (the family caps at 10,000). - Time bounds come from comparisons, BETWEEN and AND of constants built from now(), ago(), bin(), literals and interval arithmetic; a side the WHERE clause leaves open is the table's earliest queryable record (lower) or the query clock (upper), because the pages give only the 365-day example without saying how an open side is measured. A table with no queryable records and an open lower side reports 0. @@ -138,6 +144,24 @@ string-functions.html (output types), mathematical-functions.html (e(), rand(), - The ThrottlingException message text is not specified. - Queries the engine runs are not rejected for operand type mismatches (for example varchar = bigint); the pages give no message or rule to copy. +## Reference function pass (2026-11-21) + +Sources: the Timestream Developer Guide query language reference pages (mathematical, string, array, bitwise, regex, date/time, aggregate, window, +conditional, comparison functions and the time series interpolation, derivative, integral, correlation and filter/reduce pages), fetched as page +text; every documented signature and example result is a case in ts_doc_functions_test.go (TestQuery_ReferenceFunctionExamples) and the new +functions are exercised through the SDK (TestSDKQuery_ReferenceFunctions). + +- Added: array_intersect, array_union, array_except, arrays_overlap, shuffle, repeat, zip, reverse(array), concat(array, ...), sequence descending and + timestamp default step, from_base, to_base, strpos/strrpos with an instance, hamming_distance, bit_count, bitwise_not, replace(x, y), + position(x IN y), extract(DOW|DOY|YOW|QUARTER|WEEK|DAY_OF_*), hour/minute/second/millisecond/nanosecond of TIME and of interval day to second, + day/day_of_month of an interval, date_add/date_diff on TIME, infinity(), nan(), bitwise_and_agg, bitwise_or_agg, skewness, regr_slope, + regr_intercept, approx_distinct(x, e), max_by/min_by(x, y, n), weighted approx_percentile, regexp_replace with a lambda, ALL/ANY/SOME, scalar + and row-form VALUES lists, year/month interval literals (1year, 12month), interval +, -, *, / and unary minus, timestamp +/- a computed + interval. Buffered aggregates (ts_aggs_set.go) keep their rows and so work as window functions. +- Checked functions (arithmetic, casts, the new raising functions) are registered non-deterministic so SQLite no longer evaluates a constant call + before the AND or CASE guarding it; `SELECT 1/0` still raises, `WHERE host = 'x' AND 1/0 > 1` raises only when a row reaches the right side. + A 100,000-row scan with constant subexpressions showed no measurable slowdown. + ## Notes **2026-10-10 (realism pass):** Query and PrepareQuery reject statements that cannot parse (unknown leading keyword, unbalanced parentheses, unterminated literal) with ValidationException; this is a shallow check, not a SQL parser. CreateScheduledQuery validates Name (1-64 of letters, digits, `_`, `.`, `-`) and the query text; ListScheduledQueries tokens are opaque and malformed ones, or MaxResults over 1000, return ValidationException. Tests: TestQuerySyntaxValidation, TestScheduledQueryPagingAndNames. diff --git a/services/timestreamquery/query_execution.go b/services/timestreamquery/query_execution.go index eff1cb0670..dc0bc47b2c 100644 --- a/services/timestreamquery/query_execution.go +++ b/services/timestreamquery/query_execution.go @@ -855,7 +855,7 @@ func (b *InMemoryBackend) staticColumns(ctx context.Context, queryString string) return nil, false } - q := strings.TrimSpace(strings.TrimRight(strings.TrimSpace(stripSQLComments(queryString)), ";")) + q := normalizeQuery(queryString) tables, _, err := loadSourceTables(getRegion(ctx, b.defaultRegion), b.recordSource(), q, b.clock()) if err != nil { @@ -882,7 +882,7 @@ func (b *InMemoryBackend) staticColumns(ctx context.Context, queryString string) // namedParameters lists a query's @identifier parameters; one with no contextual type is VARCHAR. func (b *InMemoryBackend) namedParameters(ctx context.Context, queryString string) []ColumnInfo { - q := strings.TrimSpace(strings.TrimRight(strings.TrimSpace(stripSQLComments(queryString)), ";")) + q := normalizeQuery(queryString) tables := loadedSet{} if src := b.recordSource(); src != nil { diff --git a/services/timestreamquery/ts_aggs.go b/services/timestreamquery/ts_aggs.go index a53ce21cfb..b5fc5a57ee 100644 --- a/services/timestreamquery/ts_aggs.go +++ b/services/timestreamquery/ts_aggs.go @@ -63,7 +63,7 @@ func arrayElem(v driver.Value) string { return quoteJSON(x) } - return "null" + return kwNull } func quoteJSON(s string) string { diff --git a/services/timestreamquery/ts_aggs_set.go b/services/timestreamquery/ts_aggs_set.go new file mode 100644 index 0000000000..50d446470c --- /dev/null +++ b/services/timestreamquery/ts_aggs_set.go @@ -0,0 +1,421 @@ +package timestreamquery + +import ( + "database/sql/driver" + "fmt" + "math" + "slices" + "strconv" + + sqlitedriver "modernc.org/sqlite" +) + +const ( + minApproxError = 0.0040625 + maxApproxError = 0.26 + minSkewRows = 3 + skewTwo = 2.0 + skewPower = 1.5 +) + +type aggRow = []driver.Value + +// bufferedAgg keeps every input row so the result can be recomputed after a window frame drops one. +type bufferedAgg struct { + finish func(rows []aggRow) (driver.Value, error) + check func(args aggRow) error + rows []aggRow +} + +func cloneArgs(args []driver.Value) aggRow { + out := make(aggRow, len(args)) + + for i, a := range args { + if b, ok := a.([]byte); ok { + a = slices.Clone(b) + } + + out[i] = a + } + + return out +} + +func sameRow(a, b aggRow) bool { + return slices.EqualFunc(a, b, func(x, y driver.Value) bool { + bx, okX := x.([]byte) + by, okY := y.([]byte) + + if okX || okY { + return okX && okY && slices.Equal(bx, by) + } + + return x == y + }) +} + +func (a *bufferedAgg) Step(_ *fnCtx, args []driver.Value) error { + if a.check != nil { + if err := a.check(args); err != nil { + return err + } + } + + a.rows = append(a.rows, cloneArgs(args)) + + return nil +} + +func (a *bufferedAgg) WindowInverse(_ *fnCtx, args []driver.Value) error { + row := cloneArgs(args) + + if i := slices.IndexFunc(a.rows, func(r aggRow) bool { return sameRow(r, row) }); i >= 0 { + a.rows = slices.Delete(a.rows, i, i+1) + } + + return nil +} + +func (a *bufferedAgg) WindowValue(*fnCtx) (driver.Value, error) { return a.finish(a.rows) } + +func (*bufferedAgg) Final(*fnCtx) {} + +func registerBuffered(name string, nargs int32, check func(aggRow) error, finish func([]aggRow) (driver.Value, error)) { + sqlitedriver.MustRegisterFunction(name, &sqlitedriver.FunctionImpl{ + NArgs: nargs, Deterministic: true, + MakeAggregate: func(_ fnCtx) (sqlitedriver.AggregateFunction, error) { + return &bufferedAgg{finish: finish, check: check}, nil + }, + }) +} + +func nonNull(rows []aggRow, cols ...int) []aggRow { + return slices.DeleteFunc(slices.Clone(rows), func(r aggRow) bool { + for _, c := range cols { + if r[c] == nil { + return true + } + } + + return false + }) +} + +func floatColumn(rows []aggRow, col int) ([]float64, error) { + out := make([]float64, len(rows)) + + for i, r := range rows { + f, ok := toFloat64(r[col]) + if !ok { + return nil, errOperandType + } + + out[i] = f + } + + return out, nil +} + +func bitwiseAgg(apply func(a, b int64) int64) func([]aggRow) (driver.Value, error) { + return func(rows []aggRow) (driver.Value, error) { + rows = nonNull(rows, 0) + if len(rows) == 0 { + return nil, nil + } + + acc, ok := toInt64(rows[0][0]) + if !ok { + return nil, errOperandType + } + + for _, r := range rows[1:] { + n, isInt := toInt64(r[0]) + if !isInt { + return nil, errOperandType + } + + acc = apply(acc, n) + } + + return acc, nil + } +} + +// skewnessOf follows the streaming central-moment update used for the population skewness. +func skewnessOf(rows []aggRow) (driver.Value, error) { + xs, err := floatColumn(nonNull(rows, 0), 0) + if err != nil { + return nil, err + } + + if len(xs) < minSkewRows { + return nil, nil //nolint:nilnil // SQL NULL + } + + var n, mean, m2, m3 float64 + + for _, x := range xs { + n++ + + delta := x - mean + deltaN := delta / n + m3 += -3*deltaN*m2 + delta*deltaN*deltaN*(n-1)*(n-skewTwo) + m2 += delta * deltaN * (n - 1) + mean += deltaN + } + + return math.Sqrt(n) * m3 / math.Pow(m2, skewPower), nil +} + +// regression returns slope and intercept of y on x, or ok=false when x has no variance. +func regression(rows []aggRow) (float64, float64, bool, error) { + rows = nonNull(rows, 0, 1) + + ys, err := floatColumn(rows, 0) + if err != nil { + return 0, 0, false, err + } + + xs, err := floatColumn(rows, 1) + if err != nil { + return 0, 0, false, err + } + + var n, meanX, meanY, c2, m2x float64 + + for i := range xs { + n++ + + dx := xs[i] - meanX + meanX += dx / n + meanY += (ys[i] - meanY) / n + c2 += dx * (ys[i] - meanY) + m2x += dx * (xs[i] - meanX) + } + + if n == 0 || m2x == 0 { + return 0, 0, false, nil + } + + slope := c2 / m2x + + return slope, meanY - slope*meanX, true, nil +} + +func regressionAgg(intercept bool) func([]aggRow) (driver.Value, error) { + return func(rows []aggRow) (driver.Value, error) { + slope, icpt, ok, err := regression(rows) + if err != nil || !ok { + return nil, err + } + + if intercept { + return icpt, nil + } + + return slope, nil + } +} + +func checkApproxError(args aggRow) error { + if args[1] == nil { + return nil + } + + e, ok := toFloat64(args[1]) + if !ok { + return errOperandType + } + + if math.IsNaN(e) || e < minApproxError || e > maxApproxError { + return evalError("Max standard error must be in [0.0040625, 0.26000]: " + javaDouble(e)) + } + + return nil +} + +func approxDistinct(rows []aggRow) (driver.Value, error) { + seen := map[string]bool{} + + for _, r := range nonNull(rows, 0) { + seen[fmt.Sprintf("%T:%v", r[0], r[0])] = true + } + + return int64(len(seen)), nil +} + +func topByKey(largest bool) func([]aggRow) (driver.Value, error) { + return func(rows []aggRow) (driver.Value, error) { + rows = nonNull(rows, 1) + if len(rows) == 0 { + return nil, nil + } + + n, _ := toInt64(rows[0][argsTwo]) + + slices.SortStableFunc(rows, func(a, b aggRow) int { + if largest { + return compareValues(b[1], a[1]) + } + + return compareValues(a[1], b[1]) + }) + + vals := make([]driver.Value, 0, min(int(n), len(rows))) + for _, r := range rows[:min(int(n), len(rows))] { + vals = append(vals, r[0]) + } + + return arrayText(vals), nil + } +} + +func checkTopN(name string) func(aggRow) error { + return func(args aggRow) error { + n, ok := toInt64(args[argsTwo]) + if !ok { + return evalError("third argument of " + name + " must be an integer") + } + + if n <= 0 { + return evalError("third argument of " + name + " must be a positive integer") + } + + if n > maxTopN { + return evalError("third argument of " + name + " must be less than or equal to " + + strconv.Itoa(maxTopN) + "; found " + strconv.FormatInt(n, 10)) + } + + return nil + } +} + +func checkWeight(args aggRow) error { + if args[1] == nil { + return nil + } + + w, ok := toInt64(args[1]) + if !ok || w < 1 { + return evalError("weight must be an integer of at least one") + } + + return nil +} + +func percentileTargets(args aggRow) ([]float64, bool, error) { + if s, ok := textOf(args[argsTwo]); ok { + ps, err := percentageList(s) + + return ps, true, err + } + + p, ok := toFloat64(args[argsTwo]) + if !ok || math.IsNaN(p) || p < 0 || p > 1 { + return nil, false, evalError("percentage must be between 0 and 1") + } + + return []float64{p}, false, nil +} + +func checkAccuracy(args aggRow) error { + if len(args) <= argsThree || args[argsThree] == nil { + return nil + } + + acc, ok := toFloat64(args[argsThree]) + if !ok || acc <= 0 || acc >= 1 { + return evalError("accuracy must be greater than 0 and less than 1") + } + + return nil +} + +func checkWeightedPercentile(args aggRow) error { + if err := checkWeight(args); err != nil { + return err + } + + if err := checkAccuracy(args); err != nil { + return err + } + + if args[argsTwo] == nil { + return nil + } + + _, _, err := percentileTargets(args) + + return err +} + +type weighted struct { + val driver.Value + w int64 +} + +func weightedPercentile(rows []aggRow) (driver.Value, error) { + rows = nonNull(rows, 0, 1) + if len(rows) == 0 { + return nil, nil //nolint:nilnil // SQL NULL + } + + ps, isArray, err := percentileTargets(rows[0]) + if err != nil { + return nil, err + } + + items := make([]weighted, len(rows)) + + var total int64 + + for i, r := range rows { + w, _ := toInt64(r[1]) + items[i] = weighted{val: r[0], w: w} + + if total > math.MaxInt64-w { + return nil, evalError("total weight overflow") + } + + total += w + } + + slices.SortStableFunc(items, func(a, b weighted) int { return compareValues(a.val, b.val) }) + + out := make([]driver.Value, len(ps)) + for i, p := range ps { + out[i] = valueAtRank(items, max(1, int64(math.Ceil(p*float64(total))))) + } + + if isArray { + return arrayText(out), nil + } + + return out[0], nil +} + +func valueAtRank(items []weighted, rank int64) driver.Value { + var cum int64 + + for _, it := range items { + cum += it.w + if cum >= rank { + return it.val + } + } + + return items[len(items)-1].val +} + +func registerSetAggs() { + registerBuffered("bitwise_and_agg", 1, nil, bitwiseAgg(func(a, b int64) int64 { return a & b })) + registerBuffered("bitwise_or_agg", 1, nil, bitwiseAgg(func(a, b int64) int64 { return a | b })) + registerBuffered("skewness", 1, nil, skewnessOf) + registerBuffered("regr_slope", argsTwo, nil, regressionAgg(false)) + registerBuffered("regr_intercept", argsTwo, nil, regressionAgg(true)) + registerBuffered("ts_approx_distinct", argsTwo, checkApproxError, approxDistinct) + registerBuffered("ts_max_by_n", argsThree, checkTopN("max_by"), topByKey(true)) + registerBuffered("ts_min_by_n", argsThree, checkTopN("min_by"), topByKey(false)) + registerBuffered("ts_approx_percentile_w", argsThree, checkWeightedPercentile, weightedPercentile) + registerBuffered("ts_approx_percentile_wa", argsFour, checkWeightedPercentile, weightedPercentile) +} diff --git a/services/timestreamquery/ts_arith.go b/services/timestreamquery/ts_arith.go index 688aa9da95..f8ea0b3806 100644 --- a/services/timestreamquery/ts_arith.go +++ b/services/timestreamquery/ts_arith.go @@ -126,7 +126,7 @@ func checkedOps() []checkedOp { func arithFailure(try bool, format string, args ...any) (driver.Value, error) { if try { - return nil, nil //nolint:nilnil // try() maps failures to SQL NULL + return nil, nil //nolint:nilnil // SQL NULL } return nil, evalError(fmt.Sprintf(format, args...)) @@ -229,6 +229,11 @@ func checkedAbs(bits int, try bool) scalarImpl { } } +// floatBinary is DOUBLE addition, subtraction or multiplication that tolerates NaN passed as text. +func floatBinary(op func(a, b float64) float64, keepNaN bool) scalarImpl { + return domainMath(func(a []float64) float64 { return op(a[0], a[1]) }, keepNaN) +} + // floatDivide is DOUBLE division; NaN is text only where keepNaN says the result is rendered, else NULL like SQLite. func floatDivide(mod, keepNaN bool) scalarImpl { return func(_ *fnCtx, args []driver.Value) (driver.Value, error) { @@ -273,6 +278,110 @@ func udfRandom(_ *fnCtx, args []driver.Value) (driver.Value, error) { return rand.Int64N(n), nil //nolint:gosec // not security sensitive } +func domainMath(apply func(args []float64) float64, keepNaN bool) scalarImpl { + return func(_ *fnCtx, args []driver.Value) (driver.Value, error) { + fs := make([]float64, len(args)) + + for i, a := range args { + if a == nil { + return nil, nil + } + + f, ok := toFloat64(a) + if !ok { + return nil, errOperandType + } + + fs[i] = f + } + + r := apply(fs) + if math.IsNaN(r) { + if keepNaN { + return nanText, nil + } + + return nil, nil + } + + return r, nil + } +} + +// floatCompare compares two DOUBLE values with IEEE semantics: every comparison with NaN is false except <>. +func floatCompare(test func(a, b float64) bool) scalarImpl { + return func(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil { + return nil, nil + } + + a, okA := toFloat64(args[0]) + b, okB := toFloat64(args[1]) + + if !okA || !okB { + return nil, errOperandType + } + + return boolInt(test(a, b)), nil + } +} + +func domainMathFuncs() []scalarFunc { + unary := map[string]func(float64) float64{ + "sqrt": math.Sqrt, "ln": math.Log, "log10": math.Log10, "log2": math.Log2, "acos": math.Acos, + "asin": math.Asin, "acosh": math.Acosh, "atanh": math.Atanh, + } + + var out []scalarFunc + + for _, keep := range []bool{true, false} { + suffix := "" + if !keep { + suffix = "n" + } + + for name, f := range unary { + out = append( + out, + raisingFn("ts_"+name+suffix, 1, domainMath(func(a []float64) float64 { return f(a[0]) }, keep)), + ) + } + + out = append( + out, + raisingFn( + "ts_power"+suffix, + argsTwo, + domainMath(func(a []float64) float64 { return math.Pow(a[0], a[1]) }, keep), + ), + ) + } + + for _, keep := range []bool{true, false} { + suffix := "" + if !keep { + suffix = "n" + } + + out = append(out, + raisingFn("ts_dadd"+suffix, argsTwo, floatBinary(func(a, b float64) float64 { return a + b }, keep)), + raisingFn("ts_dsub"+suffix, argsTwo, floatBinary(func(a, b float64) float64 { return a - b }, keep)), + raisingFn("ts_dmul"+suffix, argsTwo, floatBinary(func(a, b float64) float64 { return a * b }, keep)), + ) + } + + out = append(out, + raisingFn("ts_deq", argsTwo, floatCompare(func(a, b float64) bool { return a == b })), + raisingFn("ts_dne", argsTwo, floatCompare(func(a, b float64) bool { return a != b })), + raisingFn("ts_dlt", argsTwo, floatCompare(func(a, b float64) bool { return a < b })), + raisingFn("ts_dle", argsTwo, floatCompare(func(a, b float64) bool { return a <= b })), + raisingFn("ts_dgt", argsTwo, floatCompare(func(a, b float64) bool { return a > b })), + raisingFn("ts_dge", argsTwo, floatCompare(func(a, b float64) bool { return a >= b })), + ) + + return append(out, raisingFn("ts_nann", 0, func(*fnCtx, []driver.Value) (driver.Value, error) { return nil, nil })) +} + func floatClass(test func(float64) bool) scalarImpl { return func(_ *fnCtx, args []driver.Value) (driver.Value, error) { if args[0] == nil { @@ -316,27 +425,40 @@ func tsArithFuncs() []scalarFunc { for _, bits := range []int{bits32, bits64} { for _, try := range []bool{false, true} { for _, op := range checkedOps() { - out = append(out, scalarFn(arithName(op.name, bits, try), argsTwo, checkedBinary(op, bits, try))) + out = append(out, raisingFn(arithName(op.name, bits, try), argsTwo, checkedBinary(op, bits, try))) } out = append(out, - scalarFn(arithName("div", bits, try), argsTwo, checkedDivide(bits, false, try)), - scalarFn(arithName("mod", bits, try), argsTwo, checkedDivide(bits, true, try)), - scalarFn(arithName("neg", bits, try), 1, checkedNegate(bits, try)), - scalarFn(arithName("abs", bits, try), 1, checkedAbs(bits, try)), + raisingFn(arithName("div", bits, try), argsTwo, checkedDivide(bits, false, try)), + raisingFn(arithName("mod", bits, try), argsTwo, checkedDivide(bits, true, try)), + raisingFn(arithName("neg", bits, try), 1, checkedNegate(bits, try)), + raisingFn(arithName("abs", bits, try), 1, checkedAbs(bits, try)), ) } } + out = append(out, domainMathFuncs()...) + out = append(out, + raisingFn("ts_ivadd", argsTwo, udfIntervalAdd(1)), + raisingFn("ts_ivsub", argsTwo, udfIntervalAdd(-1)), + raisingFn("ts_ivneg", 1, udfIntervalNegate), + raisingFn("ts_tsadd", argsTwo, udfTimestampShift(1, false)), + raisingFn("ts_tssub", argsTwo, udfTimestampShift(-1, false)), + raisingFn("ts_tsaddr", argsTwo, udfTimestampShift(1, true)), + raisingFn("ts_ivmul", argsTwo, udfIntervalScale(false, false)), + raisingFn("ts_ivmulr", argsTwo, udfIntervalScale(false, true)), + raisingFn("ts_ivdiv", argsTwo, udfIntervalScale(true, false)), + ) + return append(out, - scalarFn("ts_ddiv", argsTwo, floatDivide(false, true)), - scalarFn("ts_dmod", argsTwo, floatDivide(true, true)), - scalarFn("ts_ddivn", argsTwo, floatDivide(false, false)), - scalarFn("ts_dmodn", argsTwo, floatDivide(true, false)), + raisingFn("ts_ddiv", argsTwo, floatDivide(false, true)), + raisingFn("ts_dmod", argsTwo, floatDivide(true, true)), + raisingFn("ts_ddivn", argsTwo, floatDivide(false, false)), + raisingFn("ts_dmodn", argsTwo, floatDivide(true, false)), scalarFn("e", 0, udfE), - scalarFn("ts_is_nan", 1, floatClass(math.IsNaN)), - scalarFn("ts_is_infinite", 1, floatClass(func(f float64) bool { return math.IsInf(f, 0) })), - scalarFn("ts_is_finite", 1, floatClass(func(f float64) bool { return !math.IsNaN(f) && !math.IsInf(f, 0) })), + raisingFn("ts_is_nan", 1, floatClass(math.IsNaN)), + raisingFn("ts_is_infinite", 1, floatClass(func(f float64) bool { return math.IsInf(f, 0) })), + raisingFn("ts_is_finite", 1, floatClass(func(f float64) bool { return !math.IsNaN(f) && !math.IsInf(f, 0) })), ) } @@ -385,7 +507,7 @@ func (a *sumAgg) WindowInverse(_ *fnCtx, args []driver.Value) error { func (a *sumAgg) WindowValue(_ *fnCtx) (driver.Value, error) { if a.count == 0 { - return nil, nil //nolint:nilnil // SUM of no rows is NULL + return nil, nil //nolint:nilnil // SQL NULL } return a.total, nil @@ -395,7 +517,7 @@ func (*sumAgg) Final(_ *fnCtx) {} func registerArithFuncs() { for _, f := range tsArithFuncs() { - sqlitedriver.MustRegisterDeterministicScalarFunction(f.name, f.nargs, f.impl) + registerScalar(f) } registerAggFuncs() diff --git a/services/timestreamquery/ts_arith_corpus_test.go b/services/timestreamquery/ts_arith_corpus_test.go index 0177b3a05e..b7d9f29ed8 100644 --- a/services/timestreamquery/ts_arith_corpus_test.go +++ b/services/timestreamquery/ts_arith_corpus_test.go @@ -315,7 +315,7 @@ func TestArithCorpus_Positions(t *testing.T) { { "nan is null downstream", `SELECT sum(x), 0.0/0 + 1, x > 1.0, x = x FROM (SELECT 0.0/0 AS x)`, - "null|null|null|null", + "null|NaN|null|null", "", }, { diff --git a/services/timestreamquery/ts_cast.go b/services/timestreamquery/ts_cast.go index fead5bb173..ff14f12503 100644 --- a/services/timestreamquery/ts_cast.go +++ b/services/timestreamquery/ts_cast.go @@ -54,6 +54,16 @@ func udfCast(_ *fnCtx, args []driver.Value) (driver.Value, error) { return castValue(args[0], src, dst, try != 0) } +// udfCastNoNaN is udfCast for a DOUBLE result that is not rendered or classified: NaN has no SQLite value, so NULL. +func udfCastNoNaN(c *fnCtx, args []driver.Value) (driver.Value, error) { + v, err := udfCast(c, args) + if s, ok := v.(string); ok && s == nanText { + return nil, err + } + + return v, err +} + func castValue(v driver.Value, src, dst string, try bool) (driver.Value, error) { switch dst { case kwInteger: @@ -171,9 +181,9 @@ func castToBool(v driver.Value, src string, try bool) (driver.Value, error) { s, _ := textOf(v) switch strings.ToLower(s) { - case "true", "t", "1": + case kwTrue, "t", "1": return int64(1), nil - case "false", "f", "0": + case kwFalse, "f", "0": return int64(0), nil } @@ -244,7 +254,7 @@ func castToTemporal(v driver.Value, dst string, try bool) (driver.Value, error) s, _ := textOf(v) if dst == colTime { - for _, l := range []string{"15:04:05.999999999", "15:04:05"} { + for _, l := range []string{layoutClockFrac, layoutClock} { if t, err := time.Parse(l, strings.TrimSpace(s)); err == nil { return t.Format("15:04:05.000000000"), nil } @@ -266,5 +276,6 @@ func castToTemporal(v driver.Value, dst string, try bool) (driver.Value, error) } func registerCastFuncs() { - sqlitedriver.MustRegisterDeterministicScalarFunction("ts_cast", argsFour, udfCast) + sqlitedriver.MustRegisterScalarFunction("ts_cast", argsFour, udfCast) + sqlitedriver.MustRegisterScalarFunction("ts_castn", argsFour, udfCastNoNaN) } diff --git a/services/timestreamquery/ts_doc_functions_test.go b/services/timestreamquery/ts_doc_functions_test.go new file mode 100644 index 0000000000..a7f75bd3b3 --- /dev/null +++ b/services/timestreamquery/ts_doc_functions_test.go @@ -0,0 +1,558 @@ +package timestreamquery_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/timestreamquery" +) + +const docVals = `FROM (VALUES 1, 2, 3, 4) AS t(c)` + +const docPairs = `FROM (VALUES (('a', 1)), (('b', 2)), (('c', 3)), (('d', 4))) AS t(c1, c2)` + +const docXY = `FROM (VALUES ((1, 1)), ((2, 2)), ((3, 3)), ((4, 4))) AS t(c1, c2)` + +// Examples and results come from the Timestream Developer Guide function reference pages. +func TestQuery_ReferenceFunctionExamples(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + }{ + {"abs", `SELECT abs(-3)`, "3"}, + {"cbrt", `SELECT cbrt(27)`, "3.0"}, + {"ceil", `SELECT ceil(1.2)`, "2.0"}, + {"degrees", `SELECT degrees(pi())`, "180.0"}, + {"from_base", `SELECT from_base('ff', 16)`, "255"}, + {"from_base neg", `SELECT from_base('-101', 2)`, "-5"}, + {"to_base", `SELECT to_base(255, 16)`, "ff"}, + {"to_base neg", `SELECT to_base(-5, 2)`, "-101"}, + {"log2", `SELECT log2(8)`, "3.0"}, + {"mod", `SELECT mod(7, 3)`, "1"}, + {"sign", `SELECT sign(-4)`, "-1"}, + {"truncate", `SELECT truncate(2.7)`, "2.0"}, + {"infinity", `SELECT infinity()`, "Infinity"}, + {"is_nan", `SELECT is_nan(nan())`, "true"}, + {"strrpos", `SELECT strrpos('abcabc', 'b')`, "5"}, + {"strrpos inst", `SELECT strrpos('abcabcabc', 'b', 2)`, "5"}, + {"strrpos miss", `SELECT strrpos('abc', 'z')`, "0"}, + {"strpos inst", `SELECT strpos('abcabcabc', 'b', 2)`, "5"}, + {"hamming", `SELECT hamming_distance('abc', 'abd')`, "1"}, + {"split limit", `SELECT split('a,b,c', ',', 2)`, "[a, b,c]"}, + {"reverse str", `SELECT reverse('abc')`, "cba"}, + {"replace 2", `SELECT replace('abcb', 'b')`, "ac"}, + {"array_distinct", `SELECT array_distinct(ARRAY[1,2,2,3])`, "[1, 2, 3]"}, + {"array_intersect", `SELECT array_intersect(ARRAY[1,2,3], ARRAY[3,4,5])`, "[3]"}, + {"array_union", `SELECT array_union(ARRAY[1,2,3], ARRAY[3,4,5])`, "[1, 2, 3, 4, 5]"}, + {"array_except", `SELECT array_except(ARRAY[1,2,3], ARRAY[3,4,5])`, "[1, 2]"}, + {"array_join", `SELECT array_join(ARRAY[1,2,3], ';', '')`, "1;2;3"}, + {"array_max", `SELECT array_max(ARRAY[1,2,3])`, "3"}, + {"array_min", `SELECT array_min(ARRAY[1,2,3])`, "1"}, + {"array_position", `SELECT array_position(ARRAY[3,4,5,9], 5)`, "3"}, + {"array_remove", `SELECT array_remove(ARRAY[3,4,5,9], 4)`, "[3, 5, 9]"}, + {"array_sort", `SELECT array_sort(ARRAY[6,8,2,9,3])`, "[2, 3, 6, 8, 9]"}, + {"arrays_overlap", `SELECT arrays_overlap(ARRAY[6,8,2,9,3], ARRAY[6,8])`, "true"}, + {"cardinality", `SELECT cardinality(ARRAY[6,8,2,9,3])`, "5"}, + { + "concat arrays", + `SELECT concat(ARRAY[6,8,2,9,3], ARRAY[11,32], ARRAY[6,8,2,0,14])`, + "[6, 8, 2, 9, 3, 11, 32, 6, 8, 2, 0, 14]", + }, + {"element_at", `SELECT element_at(ARRAY[6,8,2,9,3], 1)`, "6"}, + {"repeat", `SELECT repeat(1, 3)`, "[1, 1, 1]"}, + {"reverse arr", `SELECT reverse(ARRAY[6,8,2,9,3])`, "[3, 9, 2, 8, 6]"}, + {"sequence 2", `SELECT sequence(3, 8)`, "[3, 4, 5, 6, 7, 8]"}, + {"sequence down", `SELECT sequence(8, 3)`, "[8, 7, 6, 5, 4, 3]"}, + {"sequence 3", `SELECT sequence(3, 15, 2)`, "[3, 5, 7, 9, 11, 13, 15]"}, + { + "sequence ts 1d", + `SELECT sequence('2023-04-02 19:26:12.941000000', '2023-04-04 19:26:12.941000000', 1d)`, + "[2023-04-02 19:26:12.941000000, 2023-04-03 19:26:12.941000000, 2023-04-04 19:26:12.941000000]", + }, + {"slice", `SELECT slice(ARRAY[6,8,2,9,3], 1, 3)`, "[6, 8, 2]"}, + { + "zip", + `SELECT zip(ARRAY[6,8,2,9,3], ARRAY[15,24])`, + "[(6, 15), (8, 24), (2, ), (9, ), (3, )]", + }, + {"bit_count", `SELECT bit_count(19, 8)`, "3"}, + {"bitwise_and", `SELECT bitwise_and(12, 7)`, "4"}, + {"bitwise_not", `SELECT bitwise_not(12)`, "-13"}, + {"bitwise_or", `SELECT bitwise_or(12, 7)`, "15"}, + {"bitwise_xor", `SELECT bitwise_xor(12, 7)`, "11"}, + {"regexp_extract_all", `SELECT regexp_extract_all('example expect complex', 'ex\w')`, "[exa, exp]"}, + {"regexp_extract_all g", `SELECT regexp_extract_all('example expect complex', '(ex)(\w)', 2)`, "[a, p]"}, + {"regexp_extract", `SELECT regexp_extract('example expect', 'ex\w')`, "exa"}, + {"regexp_extract g", `SELECT regexp_extract('example expect', '(ex)(\w)', 2)`, "a"}, + {"regexp_like", `SELECT regexp_like('example', 'ex')`, "true"}, + {"regexp_replace 2", `SELECT regexp_replace('example expect', 'expect')`, "example "}, + {"regexp_replace 3", `SELECT regexp_replace('example expect', 'expect', 'surprise')`, "example surprise"}, + {"regexp_replace lambda", `SELECT regexp_replace('example', '(\w)', x -> upper(x[1]))`, "EXAMPLE"}, + {"regexp_split", `SELECT regexp_split('example', 'x')`, "[e, ample]"}, + {"arbitrary", `SELECT arbitrary(t.c) ` + docVals, "1"}, + {"array_agg", `SELECT array_agg(t.c) ` + docVals, "[1, 2, 3, 4]"}, + {"avg", `SELECT avg(t.c) ` + docVals, "2.5"}, + {"bool_and", `SELECT bool_and(t.c) FROM (VALUES true, true, false, true) AS t(c)`, "false"}, + {"bool_or", `SELECT bool_or(t.c) FROM (VALUES true, true, false, true) AS t(c)`, "true"}, + {"every", `SELECT every(t.c) FROM (VALUES true, true, false, true) AS t(c)`, "false"}, + {"count_if", `SELECT count_if(t.c) FROM (VALUES true, true, false, true) AS t(c)`, "3"}, + {"geometric_mean", `SELECT geometric_mean(t.c) ` + docVals, "2.213363839400643"}, + {"max_by", `SELECT max_by(t.c1, t.c2) ` + docPairs, "d"}, + {"max_by n", `SELECT max_by(t.c1, t.c2, 2) ` + docPairs, "[d, c]"}, + {"min_by", `SELECT min_by(t.c1, t.c2) ` + docPairs, "a"}, + {"min_by n", `SELECT min_by(t.c1, t.c2, 2) ` + docPairs, "[a, b]"}, + {"max n", `SELECT max(t.c, 2) ` + docVals, "[4, 3]"}, + {"min n", `SELECT min(t.c, 2) ` + docVals, "[1, 2]"}, + {"sum", `SELECT sum(t.c) ` + docVals, "10"}, + {"bitwise_and_agg", `SELECT bitwise_and_agg(t.c) FROM (VALUES 1, -3) AS t(c)`, "1"}, + {"bitwise_or_agg", `SELECT bitwise_or_agg(t.c) FROM (VALUES 1, -3) AS t(c)`, "-3"}, + {"approx_distinct", `SELECT approx_distinct(t.c) FROM (VALUES 1, 2, 3, 4, 8) AS t(c)`, "5"}, + {"approx_distinct e", `SELECT approx_distinct(t.c, 0.2) FROM (VALUES 1, 2, 3, 4, 8) AS t(c)`, "5"}, + {"approx_percentile", `SELECT approx_percentile(t.c, 0.4) ` + docVals, "2"}, + {"approx_percentile arr", `SELECT approx_percentile(t.c, ARRAY[0.1, 0.8, 0.8]) ` + docVals, "[1, 4, 4]"}, + {"approx_percentile w", `SELECT approx_percentile(t.c, 1, 0.1) ` + docVals, "1"}, + {"approx_percentile w arr", `SELECT approx_percentile(t.c, 1, ARRAY[0.1, 0.8, 0.8]) ` + docVals, "[1, 4, 4]"}, + {"approx_percentile w acc", `SELECT approx_percentile(t.c, 1, 0.1, 0.5) ` + docVals, "1"}, + {"corr", `SELECT corr(t.c1, t.c2) ` + docXY, "1.0"}, + {"covar_pop", `SELECT covar_pop(t.c1, t.c2) ` + docXY, "1.25"}, + {"covar_samp", `SELECT covar_samp(t.c1, t.c2) ` + docXY, "1.6666666666666667"}, + {"regr_intercept", `SELECT regr_intercept(t.c1, t.c2) ` + docXY, "0.0"}, + {"regr_slope", `SELECT regr_slope(t.c1, t.c2) ` + docXY, "1.0"}, + {"skewness", `SELECT skewness(t.c1) FROM (VALUES 1, 2, 3, 4, 8) AS t(c1)`, "0.8978957037987335"}, + {"stddev_pop", `SELECT stddev_pop(t.c1) FROM (VALUES 1, 2, 3, 4, 8) AS t(c1)`, "2.4166091947189146"}, + {"stddev_samp", `SELECT stddev_samp(t.c1) FROM (VALUES 1, 2, 3, 4, 8) AS t(c1)`, "2.701851217221259"}, + {"stddev", `SELECT stddev(t.c1) FROM (VALUES 1, 2, 3, 4, 8) AS t(c1)`, "2.701851217221259"}, + {"var_pop", `SELECT var_pop(t.c1) FROM (VALUES 1, 2, 3, 4, 8) AS t(c1)`, "5.840000000000001"}, + {"var_samp", `SELECT var_samp(t.c1) FROM (VALUES 1, 2, 3, 4, 8) AS t(c1)`, "7.300000000000001"}, + {"variance", `SELECT variance(t.c1) FROM (VALUES 1, 2, 3, 4, 8) AS t(c1)`, "7.300000000000001"}, + {"greatest", `SELECT greatest(1, 5, 3)`, "5"}, + {"least", `SELECT least(4, 2, 3)`, "2"}, + {"nullif", `SELECT nullif(1, 1)`, ""}, + {"to_unixtime", `SELECT to_unixtime(TIMESTAMP '2022-06-17 17:44:43.771000000')`, "1.6554878837710001E9"}, + {"cume_dist", `SELECT cume_dist() OVER (ORDER BY t.c) ` + docVals + ` ORDER BY t.c LIMIT 1`, "0.25"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rows, _ := runFn(t, tt.query) + require.Len(t, rows, 1) + assert.Equal(t, tt.want, rows[0][0]) + }) + } +} + +func runFnErr(t *testing.T, q string) error { + t.Helper() + + _, err := fnBackend(t).QueryWithOptions(t.Context(), timestreamquery.QueryOptions{QueryString: q}) + + return err +} + +func TestQuery_ReferenceFunctionEdges(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + }{ + {"union null", `SELECT array_union(NULL, ARRAY[1])`, ""}, + {"intersect null", `SELECT array_intersect(ARRAY[1], NULL)`, ""}, + {"except dups", `SELECT array_except(ARRAY[1,1,2,2], ARRAY[3])`, "[1, 2]"}, + {"intersect order", `SELECT array_intersect(ARRAY[3,2,1,2], ARRAY[2,3])`, "[3, 2]"}, + {"union text", `SELECT array_union(ARRAY['a'], ARRAY['b','a'])`, "[a, b]"}, + {"intersect numeric eq", `SELECT array_intersect(ARRAY[1.0], ARRAY[1.0, 2.0])`, "[1.0]"}, + {"overlap null elem", `SELECT arrays_overlap(ARRAY[1, NULL], ARRAY[2])`, ""}, + {"overlap hit with null", `SELECT arrays_overlap(ARRAY[1, NULL], ARRAY[1])`, "true"}, + {"overlap none", `SELECT arrays_overlap(ARRAY[1], ARRAY[2])`, "false"}, + {"overlap null arg", `SELECT arrays_overlap(NULL, ARRAY[2])`, ""}, + {"repeat null elem", `SELECT repeat(NULL, 2)`, "[, ]"}, + {"repeat null count", `SELECT repeat(1, NULL)`, ""}, + {"repeat zero", `SELECT repeat(1, 0)`, "[]"}, + {"repeat limit", `SELECT cardinality(repeat(1, 10000))`, "10000"}, + {"repeat string", `SELECT repeat('ab', 2)`, "[ab, ab]"}, + {"shuffle size", `SELECT cardinality(shuffle(ARRAY[1,2,3,4]))`, "4"}, + {"shuffle null", `SELECT shuffle(NULL)`, ""}, + {"zip three", `SELECT zip(ARRAY[1], ARRAY[2], ARRAY[3])`, "[(1, 2, 3)]"}, + {"zip null", `SELECT zip(ARRAY[1], NULL)`, ""}, + {"reverse string", `SELECT reverse('abc')`, "cba"}, + {"concat strings", `SELECT concat('a', 'b')`, "ab"}, + {"concat empty arrays", `SELECT concat(ARRAY[1], ARRAY[2])`, "[1, 2]"}, + {"from_base upper", `SELECT from_base('FF', 16)`, "255"}, + {"from_base null", `SELECT from_base(NULL, 16)`, ""}, + {"to_base null", `SELECT to_base(NULL, 16)`, ""}, + {"to_base 36", `SELECT to_base(35, 36)`, "z"}, + {"strrpos empty", `SELECT strrpos('abc', '')`, "1"}, + {"strrpos null", `SELECT strrpos(NULL, 'a')`, ""}, + {"strrpos unicode", `SELECT strrpos('héllo hé', 'hé')`, "7"}, + {"strpos instance miss", `SELECT strpos('abc', 'b', 2)`, "0"}, + {"replace null", `SELECT replace('abc', NULL)`, ""}, + {"replace empty", `SELECT replace('abc', '', '-')`, "-a-b-c-"}, + {"hamming null", `SELECT hamming_distance(NULL, 'a')`, ""}, + {"bit_count neg", `SELECT bit_count(-1, 8)`, "8"}, + {"bit_count max", `SELECT bit_count(-1, 64)`, "64"}, + {"bit_count null", `SELECT bit_count(NULL, 8)`, ""}, + {"bitwise_not null", `SELECT bitwise_not(NULL)`, ""}, + {"sequence one", `SELECT sequence(2, 2)`, "[2]"}, + {"sequence neg step", `SELECT sequence(5, 1, -2)`, "[5, 3, 1]"}, + { + "sequence ts default step", + `SELECT sequence(TIMESTAMP '2023-04-02 00:00:00', TIMESTAMP '2023-04-03 00:00:00')`, + "[2023-04-02 00:00:00.000000000, 2023-04-03 00:00:00.000000000]", + }, + {"bitwise_and_agg null", `SELECT bitwise_and_agg(c) FROM (VALUES 6, NULL, 3) AS t(c)`, "2"}, + {"bitwise_or_agg empty", `SELECT bitwise_or_agg(c) FROM (VALUES 6) AS t(c) WHERE c > 10`, ""}, + { + "bitwise_and_agg group", + `SELECT bitwise_and_agg(c) FROM (VALUES (1, 3), (1, 5), (2, 7)) AS t(g, c) GROUP BY g ORDER BY g`, + "1", + }, + {"bitwise_or_agg filter", `SELECT bitwise_or_agg(c) FILTER (WHERE c < 4) FROM (VALUES 1, 2, 8) AS t(c)`, "3"}, + {"bitwise_or_agg distinct", `SELECT bitwise_or_agg(DISTINCT c) FROM (VALUES 1, 1, 2) AS t(c)`, "3"}, + { + "bitwise_and_agg window", + `SELECT bitwise_and_agg(c) OVER (ORDER BY c ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) ` + + `FROM (VALUES 3, 6, 5) AS t(c) ORDER BY c DESC LIMIT 1`, + "4", + }, + {"skewness two rows", `SELECT skewness(c) FROM (VALUES 1, 2) AS t(c)`, ""}, + {"skewness ignores null", `SELECT skewness(c) FROM (VALUES 1, 2, 3, 4, 8, NULL) AS t(c)`, "0.8978957037987335"}, + {"regr_slope no variance", `SELECT regr_slope(y, x) FROM (VALUES (1, 2), (2, 2)) AS t(y, x)`, ""}, + { + "regr_slope null pair", + `SELECT regr_slope(y, x) FROM (VALUES (1, 1), (2, 2), (NULL, 9), (3, 3)) AS t(y, x)`, + "1.0", + }, + {"regr_intercept", `SELECT regr_intercept(y, x) FROM (VALUES (3, 1), (5, 2), (7, 3)) AS t(y, x)`, "1.0"}, + { + "regr_slope group", + `SELECT regr_slope(y, x) FROM (VALUES (1, 1, 1), (2, 2, 1), (4, 1, 2), (8, 2, 2)) AS t(y, x, g) ` + + `GROUP BY g ORDER BY g`, + "1.0", + }, + { + "max_by n null key", + `SELECT max_by(a, b, 2) FROM (VALUES ('x', 1), ('y', NULL), ('z', 3)) AS t(a, b)`, + "[z, x]", + }, + {"max_by n more than rows", `SELECT max_by(a, b, 5) FROM (VALUES ('x', 1), ('z', 3)) AS t(a, b)`, "[z, x]"}, + {"min_by n empty", `SELECT min_by(a, b, 2) FROM (VALUES ('x', 1)) AS t(a, b) WHERE b > 5`, ""}, + { + "min_by n group", + `SELECT min_by(a, b, 1) FROM (VALUES ('x', 1, 1), ('y', 2, 1), ('z', 0, 2)) AS t(a, b, g) GROUP BY g ORDER BY g`, + "[x]", + }, + {"weighted pct", `SELECT approx_percentile(c, w, 0.5) FROM (VALUES (1, 1), (10, 9)) AS t(c, w)`, "10"}, + {"weighted pct heavy low", `SELECT approx_percentile(c, w, 0.5) FROM (VALUES (1, 9), (10, 1)) AS t(c, w)`, "1"}, + { + "weighted pct array", + `SELECT approx_percentile(c, w, ARRAY[0.05, 0.95]) FROM (VALUES (1, 1), (10, 9)) AS t(c, w)`, + "[1, 10]", + }, + {"weighted pct accuracy", `SELECT approx_percentile(c, 1, 0.5, 0.01) FROM (VALUES 1, 2, 3) AS t(c)`, "2"}, + {"weighted pct empty", `SELECT approx_percentile(c, 1, 0.5) FROM (VALUES 1) AS t(c) WHERE c > 5`, ""}, + {"weighted pct null value", `SELECT approx_percentile(c, 1, 0.5) FROM (VALUES 1, NULL, 3) AS t(c)`, "1"}, + {"approx_distinct nulls", `SELECT approx_distinct(c, 0.1) FROM (VALUES 1, 1, NULL, 2) AS t(c)`, "2"}, + {"approx_distinct text", `SELECT approx_distinct(c, 0.05) FROM (VALUES 'a', 'b', 'a') AS t(c)`, "2"}, + {"approx_distinct empty", `SELECT approx_distinct(c, 0.05) FROM (VALUES 'a') AS t(c) WHERE c = 'z'`, "0"}, + { + "regexp lambda groups", + `SELECT regexp_replace('a1b22', '([a-z])(\d+)', x -> x[2] || x[1])`, "1a22b", + }, + {"regexp lambda null subject", `SELECT regexp_replace(NULL, 'a', x -> 'z')`, ""}, + {"regexp lambda no match", `SELECT regexp_replace('abc', '(z)', x -> upper(x[1]))`, "abc"}, + { + "regexp lambda nested", + `SELECT regexp_replace('ab', '(a)', x -> regexp_replace(x[1], '(a)', y -> 'Z'))`, + "Zb", + }, + {"regexp lambda literal", `SELECT regexp_replace('x -> (a)', '(a)', y -> 'b')`, "x -> (b)"}, + {"extract dow", `SELECT extract(DOW FROM TIMESTAMP '2019-10-12 23:10:34')`, "6"}, + {"extract yow", `SELECT extract(YOW FROM TIMESTAMP '2019-01-01 00:00:00')`, "2019"}, + {"extract quarter", `SELECT extract(QUARTER FROM TIMESTAMP '2019-10-12 23:10:34')`, "4"}, + {"extract week", `SELECT extract(WEEK FROM TIMESTAMP '2019-10-12 23:10:34')`, "41"}, + {"extract doy", `SELECT extract(DOY FROM TIMESTAMP '2019-10-12 23:10:34')`, "285"}, + {"extract day_of_year", `SELECT extract(DAY_OF_YEAR FROM TIMESTAMP '2019-10-12 23:10:34')`, "285"}, + {"extract day_of_month", `SELECT extract(DAY_OF_MONTH FROM TIMESTAMP '2019-10-12 23:10:34')`, "12"}, + {"extract day_of_week", `SELECT extract(DAY_OF_WEEK FROM DATE '2019-10-12')`, "6"}, + {"extract nested", `SELECT extract(QUARTER FROM date_add('month', 3, TIMESTAMP '2019-10-12 23:10:34'))`, "1"}, + {"extract literal", `SELECT 'extract(DOW FROM x)'`, "extract(DOW FROM x)"}, + {"position", `SELECT position('b' IN 'abc')`, "2"}, + {"position missing", `SELECT position('z' IN 'abc')`, "0"}, + {"position expr", `SELECT position(lower('B') IN upper('abc') || 'b')`, "4"}, + {"position literal", `SELECT 'position(a IN b)'`, "position(a IN b)"}, + {"hour of time", `SELECT hour(TIME '10:20:30.5')`, "10"}, + {"minute of time", `SELECT minute(TIME '10:20:30')`, "20"}, + {"second of time", `SELECT second(TIME '10:20:30')`, "30"}, + {"millisecond of time", `SELECT millisecond(TIME '10:20:30.5')`, "500"}, + {"nanosecond of time", `SELECT nanosecond(TIME '10:20:30.5')`, "500000000"}, + {"day of interval", `SELECT day(1d + 2h)`, "1"}, + {"day_of_month of interval", `SELECT day_of_month(3d)`, "3"}, + {"hour of interval", `SELECT hour(1d + 2h)`, "2"}, + {"minute of interval", `SELECT minute(90m)`, "30"}, + {"second of interval", `SELECT second(90s)`, "30"}, + {"millisecond of interval", `SELECT millisecond(1500ms)`, "500"}, + {"nanosecond of interval", `SELECT nanosecond(5ns)`, "5"}, + {"hour of negative interval", `SELECT hour(-36h)`, "-12"}, + {"month of interval", `SELECT month(14month)`, "2"}, + {"year of interval", `SELECT year(14month)`, "1"}, + {"date_add time", `SELECT date_add('hour', 1, TIME '10:00:00')`, "11:00:00.000000000"}, + {"date_add time wraps", `SELECT date_add('hour', 30, TIME '10:00:00')`, "16:00:00.000000000"}, + {"date_add time negative", `SELECT date_add('minute', -61, TIME '00:30:00')`, "23:29:00.000000000"}, + {"date_add time null", `SELECT date_add('hour', NULL, TIME '10:00:00')`, ""}, + {"date_diff time", `SELECT date_diff('second', TIME '10:00:00', TIME '10:01:00')`, "60"}, + {"date_diff time negative", `SELECT date_diff('hour', TIME '10:00:00', TIME '08:30:00')`, "-1"}, + {"all true", `SELECT 1 < ALL (VALUES 2, 3)`, "true"}, + {"all false", `SELECT 3 > ALL (VALUES 1, 5)`, "false"}, + {"all empty", `SELECT 3 > ALL (SELECT 1 WHERE false)`, "true"}, + {"all null", `SELECT 3 > ALL (VALUES 1, NULL)`, ""}, + {"all false beats null", `SELECT 3 > ALL (VALUES 5, NULL)`, "false"}, + {"any true", `SELECT 5 > ANY (VALUES 2, 9)`, "true"}, + {"any empty", `SELECT 3 > ANY (SELECT 1 WHERE false)`, "false"}, + {"any null", `SELECT 3 > ANY (VALUES 5, NULL)`, ""}, + {"any true beats null", `SELECT 3 > ANY (VALUES 1, NULL)`, "true"}, + {"some equal", `SELECT 1 = SOME (VALUES 1, 2)`, "true"}, + {"any select", `SELECT 'a' = ANY (SELECT host FROM db.t)`, "true"}, + { + "all in where", + `SELECT count(*) FROM db.t WHERE measure_value::double >= ALL (SELECT measure_value::double FROM db.t)`, + "1", + }, + { + "all with and", + `SELECT count(*) FROM db.t WHERE host = 'a' AND measure_value::double < ANY (VALUES 15, 25)`, + "2", + }, + {"quantified literal", `SELECT 'x > ALL (VALUES 1)'`, "x > ALL (VALUES 1)"}, + {"values scalar rows", `SELECT sum(c) FROM (VALUES 1, 2, 3) AS t(c)`, "6"}, + {"values row rows", `SELECT sum(a * b) FROM (VALUES (1, 2), (3, 4)) AS t(a, b)`, "14"}, + {"values paired rows", `SELECT sum(a * b) FROM (VALUES ((1, 2)), ((3, 4))) AS t(a, b)`, "14"}, + {"values expr rows", `SELECT sum(c) FROM (VALUES (1 + 2) * 3, 4) AS t(c)`, "13"}, + {"values string with comma", `SELECT count(*) FROM (VALUES 'a, b', 'c') AS t(c)`, "2"}, + {"values in literal", `SELECT 'VALUES 1, 2'`, "VALUES 1, 2"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rows, _ := runFn(t, tt.query) + require.NotEmpty(t, rows) + assert.Equal(t, tt.want, rows[0][0]) + }) + } +} + +func TestQuery_ReferenceFunctionErrors(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + }{ + { + "repeat negative", + `SELECT repeat(1, -1)`, + "count argument of repeat function must be greater than or equal to 0", + }, + {"repeat too big", `SELECT repeat(1, 10001)`, "must be less than or equal to 10000"}, + {"array_union scalar", `SELECT array_union(1, ARRAY[1])`, "operand does not match its static type"}, + {"zip one array", `SELECT zip(ARRAY[1])`, "wrong number of arguments"}, + { + "zip six arrays", + `SELECT zip(ARRAY[1], ARRAY[1], ARRAY[1], ARRAY[1], ARRAY[1], ARRAY[1])`, + "wrong number of arguments", + }, + {"from_base bad digit", `SELECT from_base('zz', 16)`, "Not a valid base-16 number: zz"}, + {"from_base overflow", `SELECT from_base('ffffffffffffffffff', 16)`, "Not a valid base-16 number"}, + {"from_base radix", `SELECT from_base('1', 1)`, "Radix must be between 2 and 36"}, + {"to_base radix", `SELECT to_base(1, 37)`, "Radix must be between 2 and 36"}, + {"strrpos instance", `SELECT strrpos('a', 'a', 0)`, "'instance' must be a positive number"}, + {"strpos instance", `SELECT strpos('a', 'a', -1)`, "'instance' must be a positive number"}, + {"hamming length", `SELECT hamming_distance('a', 'ab')`, "must have the same length"}, + { + "bit_count range", + `SELECT bit_count(19, 2)`, + "Number must be representable with the bits specified. 19 can not be represented with 2 bits", + }, + {"bit_count bits low", `SELECT bit_count(1, 1)`, "Bits specified in bit_count must be between 2 and 64, got 1"}, + { + "bit_count bits high", + `SELECT bit_count(1, 65)`, + "Bits specified in bit_count must be between 2 and 64, got 65", + }, + { + "max_by n zero", + `SELECT max_by(a, b, 0) FROM (VALUES ('x', 1)) AS t(a, b)`, + "third argument of max_by must be a positive integer", + }, + { + "min_by n big", + `SELECT min_by(a, b, 10001) FROM (VALUES ('x', 1)) AS t(a, b)`, + "third argument of min_by must be less than or equal to 10000; found 10001", + }, + { + "weight zero", + `SELECT approx_percentile(c, 0, 0.5) FROM (VALUES 1) AS t(c)`, + "weight must be an integer of at least one", + }, + { + "weighted percentage", + `SELECT approx_percentile(c, 1, 1.5) FROM (VALUES 1) AS t(c)`, + "percentage must be between 0 and 1", + }, + { + "weighted accuracy", + `SELECT approx_percentile(c, 1, 0.5, 1.0) FROM (VALUES 1) AS t(c)`, + "accuracy must be greater than 0 and less than 1", + }, + { + "approx_distinct error", + `SELECT approx_distinct(c, 0.001) FROM (VALUES 1) AS t(c)`, + "Max standard error must be in [0.0040625, 0.26000]: 0.001", + }, + {"regexp bad pattern", `SELECT regexp_replace('a', '(', x -> 'b')`, "Invalid regular expression"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + err := runFnErr(t, tt.query) + require.Error(t, err) + assert.Contains(t, err.Error(), tt.want) + }) + } +} + +func TestSDKQuery_ReferenceFunctions(t *testing.T) { + t.Parallel() + + client := newSDKQueryClient(t) + + tests := []struct { + name string + query string + typ string + value string + }{ + {"array_intersect", `SELECT array_intersect(ARRAY[1,2,3], ARRAY[3,4,5])`, "ARRAY(INTEGER)", "[3]"}, + {"array_union", `SELECT array_union(ARRAY['a'], ARRAY['b','a'])`, "ARRAY(VARCHAR)", "[a,b]"}, + {"array_except", `SELECT array_except(ARRAY[1,2,3], ARRAY[3])`, "ARRAY(INTEGER)", "[1,2]"}, + {"repeat", `SELECT repeat('ab', 2)`, "ARRAY(VARCHAR)", "[ab,ab]"}, + {"repeat double", `SELECT repeat(1.5, 2)`, "ARRAY(DOUBLE)", "[1.5,1.5]"}, + {"zip", `SELECT zip(ARRAY[1,2], ARRAY['a'])`, "ARRAY(ROW(:INTEGER,:VARCHAR))", "[(1,a),(2,null)]"}, + {"from_base", `SELECT from_base('ff', 16)`, "BIGINT", "255"}, + {"to_base", `SELECT to_base(255, 2)`, "VARCHAR", "11111111"}, + {"strrpos", `SELECT strrpos('abcabc', 'b')`, "BIGINT", "5"}, + {"strpos instance", `SELECT strpos('abcabc', 'b', 2)`, "BIGINT", "5"}, + {"bit_count", `SELECT bit_count(9, 64)`, "BIGINT", "2"}, + {"quantified all", `SELECT 1 < ALL (VALUES 2, 3)`, "BOOLEAN", "true"}, + {"position", `SELECT position('b' IN 'abc')`, "BIGINT", "2"}, + {"extract dow", `SELECT extract(DOW FROM TIMESTAMP '2019-10-12 23:10:34')`, "BIGINT", "6"}, + {"hour of time", `SELECT hour(TIME '10:20:30')`, "BIGINT", "10"}, + {"hour of interval", `SELECT hour(1d + 2h)`, "BIGINT", "2"}, + {"date_add time", `SELECT date_add('hour', 1, TIME '10:00:00')`, "TIME", "11:00:00.000000000"}, + {"bitwise_not", `SELECT bitwise_not(0)`, "BIGINT", "-1"}, + {"hamming_distance", `SELECT hamming_distance('a','b')`, "BIGINT", "1"}, + {"arrays_overlap", `SELECT arrays_overlap(ARRAY[1], ARRAY[2])`, "BOOLEAN", "false"}, + {"infinity", `SELECT infinity()`, "DOUBLE", "Infinity"}, + {"nan", `SELECT nan()`, "DOUBLE", "NaN"}, + {"nan arithmetic", `SELECT nan() + 1`, "DOUBLE", "NaN"}, + {"nan compare", `SELECT nan() = nan()`, "BOOLEAN", "false"}, + {"sqrt negative", `SELECT sqrt(-1)`, "DOUBLE", "NaN"}, + {"ln zero", `SELECT ln(0)`, "DOUBLE", "-Infinity"}, + {"inf minus inf", `SELECT infinity() - infinity()`, "DOUBLE", "NaN"}, + {"replace two args", `SELECT replace('abc','b')`, "VARCHAR", "ac"}, + {"reverse array", `SELECT reverse(ARRAY[1,2,3])`, "ARRAY(INTEGER)", "[3,2,1]"}, + {"concat arrays", `SELECT concat(ARRAY[1], ARRAY[2])`, "ARRAY(INTEGER)", "[1,2]"}, + {"sequence down", `SELECT sequence(3, 1)`, "ARRAY(INTEGER)", "[3,2,1]"}, + {"regexp_replace lambda", `SELECT regexp_replace('abc', '(b)', x -> upper(x[1]))`, "VARCHAR", "aBc"}, + { + "bitwise_and_agg", + `SELECT bitwise_and_agg(measure_value::bigint) FROM db.t WHERE measure_name = 'n'`, + "BIGINT", + "7", + }, + { + "bitwise_or_agg", + `SELECT bitwise_or_agg(measure_value::bigint) FROM db.t WHERE measure_name = 'n'`, + "BIGINT", + "7", + }, + { + "skewness", + `SELECT skewness(measure_value::double) FROM db.t WHERE measure_name = 'cpu'`, + "DOUBLE", + "0.4261133876306897", + }, + { + "regr_slope", + `SELECT regr_slope(measure_value::double, measure_value::double) FROM db.t WHERE measure_name = 'cpu'`, + "DOUBLE", + "1.0", + }, + { + "regr_intercept", + `SELECT regr_intercept(measure_value::double, measure_value::double) FROM db.t WHERE measure_name = 'cpu'`, + "DOUBLE", + "0.0", + }, + { + "max_by n", + `SELECT max_by(measure_value::double, time, 2) FROM db.t WHERE measure_name = 'cpu'`, + "ARRAY(DOUBLE)", + "[30.0,10.0]", + }, + { + "min_by n", + `SELECT min_by(measure_value::double, time, 2) FROM db.t WHERE measure_name = 'cpu'`, + "ARRAY(DOUBLE)", + "[1.0,10.0]", + }, + { + "approx_percentile weight", + `SELECT approx_percentile(measure_value::double, 2, 0.5) FROM db.t WHERE measure_name = 'cpu'`, + "DOUBLE", + "10.0", + }, + { + "approx_percentile weight array", + `SELECT approx_percentile(measure_value::double, 1, ARRAY[0.1, 0.9]) FROM db.t WHERE measure_name = 'cpu'`, + "ARRAY(DOUBLE)", + "[1.0,30.0]", + }, + { + "approx_distinct error bound", + `SELECT approx_distinct(host, 0.1) FROM db.t WHERE measure_name = 'cpu'`, + "BIGINT", + "1", + }, + {"interval add", `SELECT 1h + 30m`, "INTERVAL_DAY_TO_SECOND", "0 01:30:00.000000000"}, + {"interval sub", `SELECT 1h - 90m`, "INTERVAL_DAY_TO_SECOND", "-0 00:30:00.000000000"}, + {"interval mul", `SELECT 2 * 1h`, "INTERVAL_DAY_TO_SECOND", "0 02:00:00.000000000"}, + {"interval div", `SELECT 1h / 4`, "INTERVAL_DAY_TO_SECOND", "0 00:15:00.000000000"}, + {"interval year month", `SELECT 1year + 2month`, "INTERVAL_YEAR_TO_MONTH", "1-2"}, + {"interval month literal", `SELECT 12month`, "INTERVAL_YEAR_TO_MONTH", "1-0"}, + {"ago interval sum", `SELECT ago(2m + 30s)`, "TIMESTAMP", "2026-10-31 11:57:30.000000000"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + typ, value := queryLabels(t, client, tt.query) + assert.Equal(t, tt.typ, typ) + assert.Equal(t, tt.value, value) + }) + } +} diff --git a/services/timestreamquery/ts_duration.go b/services/timestreamquery/ts_duration.go index 6422c2822a..67ed68ead7 100644 --- a/services/timestreamquery/ts_duration.go +++ b/services/timestreamquery/ts_duration.go @@ -3,6 +3,7 @@ package timestreamquery import ( "database/sql/driver" "fmt" + "math" "regexp" "strconv" "strings" @@ -72,3 +73,140 @@ func udfParseDuration(_ *fnCtx, args []driver.Value) (driver.Value, error) { return formatInterval(int64(n * float64(unitNanos(m[2])))), nil } + +// intervalNanos reads an interval day to second held as nanoseconds, "d hh:mm:ss.nnnnnnnnn" text or an interval blob. +func intervalNanos(v driver.Value) (int64, bool) { + switch x := v.(type) { + case int64: + return x, true + case string: + return parseIntervalText(x) + case []byte: + if kind, n, isIv := decodeIntervalBlob(x); isIv { + return n * msToNs, kind == 'D' + } + + return parseIntervalText(string(x)) + } + + return 0, false +} + +func intervalPair(args []driver.Value) (int64, int64, bool, error) { + if args[0] == nil || args[1] == nil { + return 0, 0, true, nil + } + + a, okA := intervalNanos(args[0]) + b, okB := intervalNanos(args[1]) + + if !okA || !okB { + return 0, 0, false, errOperandType + } + + return a, b, false, nil +} + +func udfIntervalAdd(sign int64) scalarImpl { + return func(_ *fnCtx, args []driver.Value) (driver.Value, error) { + a, b, isNull, err := intervalPair(args) + if err != nil || isNull { + return nil, err + } + + if sign < 0 { + if r, ok := subExact(a, b); ok { + return r, nil + } + + return nil, evalError(fmt.Sprintf("interval day to second subtraction overflow: %d - %d", a, b)) + } + + if r, ok := addExact(a, b); ok { + return r, nil + } + + return nil, evalError(fmt.Sprintf("interval day to second addition overflow: %d + %d", a, b)) + } +} + +func udfIntervalNegate(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil { + return nil, nil //nolint:nilnil // SQL NULL + } + + n, ok := intervalNanos(args[0]) + if !ok { + return nil, errOperandType + } + + if n == math.MinInt64 { + return nil, evalError("interval day to second negation overflow") + } + + return -n, nil +} + +// udfIntervalScale is interval * factor (divide=false) or interval / factor, rounded to a whole nanosecond. +func udfIntervalScale(divide, factorFirst bool) scalarImpl { + return func(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil { + return nil, nil + } + + ivArg, factorArg := args[0], args[1] + if factorFirst { + ivArg, factorArg = factorArg, ivArg + } + + n, okN := intervalNanos(ivArg) + f, okF := toFloat64(factorArg) + + if !okN || !okF || math.IsNaN(f) { + return nil, errOperandType + } + + if divide && f == 0 { + return nil, evalError("Division by zero") + } + + r := float64(n) * f + if divide { + r = float64(n) / f + } + + if math.IsInf(r, 0) || math.Abs(r) >= twoPow63 { + return nil, evalError("interval day to second out of range") + } + + return int64(math.Round(r)), nil + } +} + +// udfTimestampShift is timestamp + interval (sign 1), timestamp - interval (sign -1), or interval + timestamp. +func udfTimestampShift(sign int64, intervalFirst bool) scalarImpl { + return func(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil { + return nil, nil + } + + tsArg, ivArg := args[0], args[1] + if intervalFirst { + tsArg, ivArg = ivArg, tsArg + } + + t, okT := parseTSValue(tsArg) + n, okN := intervalNanos(ivArg) + + if !okT || !okN { + return nil, errOperandType + } + + shifted := t.UnixNano() + sign*n + if (sign*n > 0 && shifted < t.UnixNano()) || (sign*n < 0 && shifted > t.UnixNano()) { + return nil, evalError("timestamp out of range") + } + + return formatTS(time.Unix(0, shifted)), nil + } +} diff --git a/services/timestreamquery/ts_engine.go b/services/timestreamquery/ts_engine.go index b2ee499e64..63ebef76d8 100644 --- a/services/timestreamquery/ts_engine.go +++ b/services/timestreamquery/ts_engine.go @@ -54,7 +54,7 @@ func (b *InMemoryBackend) execute( func (b *InMemoryBackend) executeStatement( ctx context.Context, query string, vars map[string]string, queryID string, ) (*resultSet, error) { - query = strings.TrimSpace(strings.TrimRight(strings.TrimSpace(stripSQLComments(query)), ";")) + query = normalizeQuery(query) region := getRegion(ctx, b.defaultRegion) switch firstWord(query) { diff --git a/services/timestreamquery/ts_funcs.go b/services/timestreamquery/ts_funcs.go index c9927b4fd5..b0881c3c80 100644 --- a/services/timestreamquery/ts_funcs.go +++ b/services/timestreamquery/ts_funcs.go @@ -3,6 +3,7 @@ package timestreamquery import ( "database/sql/driver" "errors" + "slices" "sync" "time" @@ -131,10 +132,8 @@ func toUnit(per func(time.Time) int64) func(*sqlitedriver.FunctionContext, []dri return nil, nil } - if txt, isText := textOf(args[0]); isText { - if ns, isInterval := parseIntervalText(txt); isInterval { - return per(time.Unix(0, ns).UTC()) - per(time.Unix(0, 0).UTC()), nil - } + if ns, isInterval := intervalNanos(args[0]); isInterval { + return per(time.Unix(0, ns).UTC()) - per(time.Unix(0, 0).UTC()), nil } t, ok := parseTSValue(args[0]) @@ -152,12 +151,29 @@ type scalarFunc struct { impl scalarImpl name string nargs int32 + // volatile keeps SQLite from evaluating a constant call ahead of the guard around it. + volatile bool } func scalarFn(name string, nargs int32, impl scalarImpl) scalarFunc { return scalarFunc{name: name, nargs: nargs, impl: impl} } +// raisingFn is scalarFn for a function that can fail the query, so it is evaluated only where the query reaches it. +func raisingFn(name string, nargs int32, impl scalarImpl) scalarFunc { + return scalarFunc{name: name, nargs: nargs, impl: impl, volatile: true} +} + +func registerScalar(f scalarFunc) { + if f.volatile { + sqlitedriver.MustRegisterScalarFunction(f.name, f.nargs, f.impl) + + return + } + + sqlitedriver.MustRegisterDeterministicScalarFunction(f.name, f.nargs, f.impl) +} + // tsScalarFuncs lists the scalar functions this package registers with the engine. func tsScalarFuncs() []scalarFunc { isoYear := toUnit(func(t time.Time) int64 { @@ -166,7 +182,7 @@ func tsScalarFuncs() []scalarFunc { return int64(y) }) - return []scalarFunc{ + return slices.Concat([]scalarFunc{ scalarFn("ts_bin", argsTwo, udfBin), scalarFn("ts_ago", argsTwo, udfAgo), scalarFn("ts_tsdiff", argsTwo, udfTimestampDiff), @@ -184,11 +200,52 @@ func tsScalarFuncs() []scalarFunc { scalarFn("interpolate_fill", argsThree, udfInterpolateFill), scalarFn("derivative_linear", argsTwo, udfDerivative(false)), scalarFn("non_negative_derivative_linear", argsTwo, udfDerivative(true)), - scalarFn("integral_trapezoidal", -1, udfIntegral), + raisingFn("integral_trapezoidal", -1, udfIntegral), scalarFn("correlate_pearson", argsTwo, udfCorrelate(false)), scalarFn("correlate_spearman", argsTwo, udfCorrelate(true)), scalarFn("sequence", -1, udfSequence), scalarFn("ts_series_json", 1, udfSeriesJSON), + }, tsTextFuncs(), tsArrayFuncs(), clockFuncs()) +} + +// withMaxArgs guards a variadic registration against calls with fewer than two or more than hi arguments. +func withMaxArgs(hi int, impl scalarImpl) scalarImpl { + return func(c *fnCtx, args []driver.Value) (driver.Value, error) { + if len(args) < argsTwo || len(args) > hi { + return nil, evalError("wrong number of arguments") + } + + return impl(c, args) + } +} + +func tsTextFuncs() []scalarFunc { + return []scalarFunc{ + raisingFn("from_base", argsTwo, udfFromBase), + raisingFn("to_base", argsTwo, udfToBase), + raisingFn("bitwise_not", 1, udfBitwiseNot), + raisingFn("bit_count", argsTwo, udfBitCount), + raisingFn("hamming_distance", argsTwo, udfHamming), + raisingFn("strrpos", -1, withMaxArgs(argsThree, positionOf(true))), + raisingFn("ts_strpos", -1, withMaxArgs(argsThree, positionOf(false))), + raisingFn("ts_replace", -1, withMaxArgs(argsThree, udfReplace)), + scalarFn("infinity", 0, udfInfinity), + scalarFn("nan", 0, func(*fnCtx, []driver.Value) (driver.Value, error) { return nanText, nil }), + } +} + +func tsArrayFuncs() []scalarFunc { + return []scalarFunc{ + raisingFn("array_intersect", argsTwo, setOp(func(inY bool) bool { return inY }, false)), + raisingFn("array_union", argsTwo, setOp(func(bool) bool { return true }, true)), + raisingFn("array_except", argsTwo, setOp(func(inY bool) bool { return !inY }, false)), + raisingFn("arrays_overlap", argsTwo, udfArraysOverlap), + raisingFn("repeat", argsTwo, udfRepeat), + raisingFn("zip", -1, withMaxArgs(maxZipArrays, udfZip)), + raisingFn("ts_reverse_array", 1, udfReverseArray), + raisingFn("ts_regexp_groups", argsTwo, udfRegexpGroups), + raisingFn("ts_regexp_splice", argsThree, udfRegexpSplice), + raisingFn("ts_concat_array", -1, udfConcatArrays), } } @@ -213,9 +270,11 @@ func registerTimestreamFuncs() { registerUnnestModule() registerArithFuncs() registerCastFuncs() + registerSetAggs() + sqlitedriver.MustRegisterScalarFunction("shuffle", 1, udfShuffle) for _, f := range tsScalarFuncs() { - sqlitedriver.MustRegisterDeterministicScalarFunction(f.name, f.nargs, f.impl) + registerScalar(f) } sqlitedriver.MustRegisterFunction("create_time_series", &sqlitedriver.FunctionImpl{ diff --git a/services/timestreamquery/ts_funcs_array.go b/services/timestreamquery/ts_funcs_array.go new file mode 100644 index 0000000000..0557ec6bf0 --- /dev/null +++ b/services/timestreamquery/ts_funcs_array.go @@ -0,0 +1,299 @@ +package timestreamquery + +import ( + "database/sql/driver" + "encoding/json/jsontext" + "encoding/json/v2" + "math" + "math/rand/v2" + "strconv" + "strings" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" +) + +const maxRepeatCount = 10000 + +const maxZipArrays = 5 + +type rawElems []string + +func decodeRawArray(v driver.Value) (rawElems, bool, error) { + if v == nil { + return nil, true, nil + } + + s, ok := textOf(v) + if !ok || !strings.HasPrefix(s, arrayMark+"[") { + return nil, false, errOperandType + } + + var items []jsontext.Value + + if err := json.Unmarshal([]byte(strings.TrimPrefix(s, arrayMark)), &items, jsonx.V1()); err != nil { + return nil, false, errOperandType + } + + out := make(rawElems, len(items)) + for i, it := range items { + out[i] = string(it) + } + + return out, false, nil +} + +func (r rawElems) text() string { return "[" + strings.Join(r, ",") + "]" } + +func (r rawElems) encode() driver.Value { return arrayMark + r.text() } + +func elemKey(raw string) string { + raw = strings.TrimSpace(raw) + + switch { + case strings.HasPrefix(raw, `"`): + var s string + if json.Unmarshal([]byte(raw), &s, jsonx.V1()) == nil { + return "s" + s + } + case raw == kwNull, raw == kwTrue, raw == kwFalse: + return raw + default: + if f, err := strconv.ParseFloat(raw, 64); err == nil { + return "n" + strconv.FormatFloat(f, 'g', -1, bits64) + } + } + + return "j" + raw +} + +func distinctRaw(in rawElems) rawElems { + seen := make(map[string]bool, len(in)) + out := rawElems{} + + for _, e := range in { + if k := elemKey(e); !seen[k] { + seen[k] = true + out = append(out, e) + } + } + + return out +} + +func keySet(in rawElems) map[string]bool { + set := make(map[string]bool, len(in)) + for _, e := range in { + set[elemKey(e)] = true + } + + return set +} + +// setOp is a two-array set function: array_union, array_intersect or array_except. +func setOp(keep func(inY bool) bool, includeY bool) scalarImpl { + return func(_ *fnCtx, args []driver.Value) (driver.Value, error) { + x, nullX, err := decodeRawArray(args[0]) + if err != nil { + return nil, err + } + + y, nullY, err := decodeRawArray(args[1]) + if err != nil { + return nil, err + } + + if nullX || nullY { + return nil, nil + } + + inY := keySet(y) + + var out rawElems + + for _, e := range x { + if keep(inY[elemKey(e)]) { + out = append(out, e) + } + } + + if includeY { + out = append(out, y...) + } + + return distinctRaw(out).encode(), nil + } +} + +func udfArraysOverlap(_ *fnCtx, args []driver.Value) (driver.Value, error) { + x, nullX, err := decodeRawArray(args[0]) + if err != nil { + return nil, err + } + + y, nullY, err := decodeRawArray(args[1]) + if err != nil { + return nil, err + } + + if nullX || nullY { + return nil, nil //nolint:nilnil // SQL NULL + } + + inY := keySet(y) + hasNull := inY[kwNull] + + for _, e := range x { + k := elemKey(e) + if k == kwNull { + hasNull = true + + continue + } + + if inY[k] { + return int64(1), nil + } + } + + if hasNull { + return nil, nil //nolint:nilnil // SQL NULL + } + + return int64(0), nil +} + +func udfShuffle(_ *fnCtx, args []driver.Value) (driver.Value, error) { + x, isNull, err := decodeRawArray(args[0]) + if err != nil || isNull { + return nil, err + } + + rand.Shuffle(len(x), func(i, j int) { x[i], x[j] = x[j], x[i] }) //nolint:gosec // not security sensitive + + return x.encode(), nil +} + +// jsonRaw renders an engine value as the JSON text of one array element. +func jsonRaw(v driver.Value) string { + if v == nil { + return kwNull + } + + if s, ok := textOf(v); ok && strings.HasPrefix(s, arrayMark) { + return strings.TrimPrefix(s, arrayMark) + } + + if f, ok := v.(float64); ok && (math.IsNaN(f) || math.IsInf(f, 0)) { + return quoteJSON(javaDouble(f)) + } + + return arrayElem(v) +} + +func udfRepeat(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[1] == nil { + return nil, nil //nolint:nilnil // SQL NULL + } + + n, ok := toInt64(args[1]) + if !ok { + return nil, errOperandType + } + + if n < 0 { + return nil, evalError("count argument of repeat function must be greater than or equal to 0") + } + + if n > maxRepeatCount { + return nil, evalError("count argument of repeat function must be less than or equal to " + + strconv.Itoa(maxRepeatCount)) + } + + elem := jsonRaw(args[0]) + out := make(rawElems, n) + + for i := range out { + out[i] = elem + } + + return out.encode(), nil +} + +func udfZip(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if len(args) < argsTwo || len(args) > maxZipArrays { + return nil, evalError("zip takes between 2 and 5 arrays") + } + + arrays := make([]rawElems, len(args)) + width := 0 + + for i, a := range args { + arr, isNull, err := decodeRawArray(a) + if err != nil { + return nil, err + } + + if isNull { + return nil, nil //nolint:nilnil // SQL NULL + } + + arrays[i] = arr + width = max(width, len(arr)) + } + + rows := make(rawElems, width) + + for r := range rows { + fields := make([]string, len(arrays)) + + for c, arr := range arrays { + val := kwNull + if r < len(arr) { + val = arr[r] + } + + fields[c] = quoteJSON("\x00"+strconv.Itoa(c)) + ":" + val + } + + rows[r] = "{" + strings.Join(fields, ",") + "}" + } + + return rows.encode(), nil +} + +func udfReverseArray(_ *fnCtx, args []driver.Value) (driver.Value, error) { + x, isNull, err := decodeRawArray(args[0]) + if err != nil || isNull { + return nil, err + } + + out := make(rawElems, len(x)) + for i, e := range x { + out[len(x)-1-i] = e + } + + return out.encode(), nil +} + +func udfConcatArrays(_ *fnCtx, args []driver.Value) (driver.Value, error) { + var out rawElems + + for _, a := range args { + arr, isNull, err := decodeRawArray(a) + if err != nil { + return nil, err + } + + if isNull { + return nil, nil //nolint:nilnil // SQL NULL + } + + out = append(out, arr...) + } + + if out == nil { + out = rawElems{} + } + + return out.encode(), nil +} diff --git a/services/timestreamquery/ts_funcs_clock.go b/services/timestreamquery/ts_funcs_clock.go new file mode 100644 index 0000000000..588250c649 --- /dev/null +++ b/services/timestreamquery/ts_funcs_clock.go @@ -0,0 +1,176 @@ +package timestreamquery + +import ( + "database/sql/driver" + "fmt" + "time" +) + +const ( + unitDay = "day" + unitHour = "hour" + unitMinute = "minute" + unitSecond = "second" + unitMillisecond = "millisecond" + unitNanosecond = "nanosecond" + layoutClock = "15:04:05" + layoutClockFrac = "15:04:05.999999999" + kwHaving = "having" + kwLimit = "limit" + kwWhere = "where" + unitDayOfMonth = "day_of_month" + nsPerSecond = int64(time.Second) + nsPerDay = int64(hoursInDay) * int64(time.Hour) + clockFormat = "15:04:05.000000000" +) + +func parseClock(v driver.Value) (int64, bool) { + s, ok := textOf(v) + if !ok { + return 0, false + } + + for _, l := range []string{layoutClockFrac, layoutClock, "15:04"} { + if t, err := time.Parse(l, s); err == nil { + return int64(t.Hour())*int64(time.Hour) + int64(t.Minute())*int64(time.Minute) + + int64(t.Second())*nsPerSecond + int64(t.Nanosecond()), true + } + } + + return 0, false +} + +func formatClock(ns int64) string { + return time.Unix(0, floorMod(ns, nsPerDay)).UTC().Format(clockFormat) +} + +type clockPart struct { + extract func(ns int64) int64 + name string +} + +func clockParts() []clockPart { + return []clockPart{ + {name: unitHour, extract: func(ns int64) int64 { return ns % nsPerDay / int64(time.Hour) }}, + {name: unitMinute, extract: func(ns int64) int64 { return ns / int64(time.Minute) % minutesInHour }}, + {name: unitSecond, extract: func(ns int64) int64 { return ns / nsPerSecond % minutesInHour }}, + {name: unitMillisecond, extract: func(ns int64) int64 { return ns % nsPerSecond / int64(time.Millisecond) }}, + {name: unitNanosecond, extract: func(ns int64) int64 { return ns % nsPerSecond }}, + } +} + +func timePartFunc(extract func(int64) int64) scalarImpl { + return func(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil { + return nil, nil + } + + ns, ok := parseClock(args[0]) + if !ok { + return nil, errOperandType + } + + return extract(ns), nil + } +} + +func intervalPartFunc(extract func(int64) int64) scalarImpl { + return func(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil { + return nil, nil + } + + ns, ok := intervalNanos(args[0]) + if !ok { + return nil, errOperandType + } + + return extract(ns), nil + } +} + +func clockFuncs() []scalarFunc { + out := make([]scalarFunc, 0, 2*len(clockParts())+argsThree) + + for _, p := range clockParts() { + out = append(out, + raisingFn("ts_time_"+p.name, 1, timePartFunc(p.extract)), + raisingFn("ts_iv_"+p.name, 1, intervalPartFunc(p.extract)), + ) + } + + out = append(out, + raisingFn("ts_iv_"+unitDay, 1, intervalPartFunc(func(ns int64) int64 { return ns / nsPerDay })), + raisingFn("ts_time_add", argsThree, udfTimeAdd), + raisingFn("ts_time_diff", argsThree, udfTimeDiff), + ) + + return out +} + +func clockUnit(v driver.Value) (int64, error) { + u, ok := textOf(v) + if !ok { + return 0, errOperandType + } + + switch u { + case unitMillisecond: + return int64(time.Millisecond), nil + case unitSecond: + return nsPerSecond, nil + case unitMinute: + return int64(time.Minute), nil + case unitHour: + return int64(time.Hour), nil + } + + return 0, evalError(fmt.Sprintf("'%s' is not a valid TIME field", u)) +} + +// udfTimeAdd is date_add(unit, n, time): the time of day wraps around midnight. +func udfTimeAdd(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil || args[argsTwo] == nil { + return nil, nil //nolint:nilnil // SQL NULL + } + + unit, err := clockUnit(args[0]) + if err != nil { + return nil, err + } + + n, okN := toInt64(args[1]) + base, okT := parseClock(args[argsTwo]) + + if !okN || !okT { + return nil, errOperandType + } + + step, ok := mulExact(n%(nsPerDay/unit), unit) + if !ok { + return nil, evalError("time addition overflow") + } + + return formatClock(base + step), nil +} + +// udfTimeDiff is date_diff(unit, time, time): whole units from the first time to the second. +func udfTimeDiff(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil || args[argsTwo] == nil { + return nil, nil //nolint:nilnil // SQL NULL + } + + unit, err := clockUnit(args[0]) + if err != nil { + return nil, err + } + + a, okA := parseClock(args[1]) + b, okB := parseClock(args[argsTwo]) + + if !okA || !okB { + return nil, errOperandType + } + + return (b - a) / unit, nil +} diff --git a/services/timestreamquery/ts_funcs_text.go b/services/timestreamquery/ts_funcs_text.go new file mode 100644 index 0000000000..c438172ff2 --- /dev/null +++ b/services/timestreamquery/ts_funcs_text.go @@ -0,0 +1,251 @@ +package timestreamquery + +import ( + "database/sql/driver" + "math" + "math/bits" + "strconv" + "strings" +) + +const ( + minRadix = 2 + maxRadix = 36 + minBitCount = 2 + maxBitCount = 64 + hammingMessage = "The input strings to hamming_distance function must have the same length" +) + +func textArgs(args []driver.Value) ([]string, bool, error) { + out := make([]string, len(args)) + + for i, a := range args { + if a == nil { + return nil, true, nil + } + + s, ok := textOf(a) + if !ok { + return nil, false, errOperandType + } + + out[i] = s + } + + return out, false, nil +} + +func checkRadix(v driver.Value) (int, error) { + r, ok := toInt64(v) + if !ok { + return 0, errOperandType + } + + if r < minRadix || r > maxRadix { + return 0, evalError("Radix must be between 2 and 36") + } + + return int(r), nil +} + +func udfFromBase(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil { + return nil, nil //nolint:nilnil // SQL NULL + } + + s, ok := textOf(args[0]) + if !ok { + return nil, errOperandType + } + + radix, err := checkRadix(args[1]) + if err != nil { + return nil, err + } + + n, parseErr := strconv.ParseInt(s, radix, bits64) + if parseErr != nil { + return nil, evalError("Not a valid base-" + strconv.Itoa(radix) + " number: " + s) + } + + return n, nil +} + +func udfToBase(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil { + return nil, nil //nolint:nilnil // SQL NULL + } + + n, ok := toInt64(args[0]) + if !ok { + return nil, errOperandType + } + + radix, err := checkRadix(args[1]) + if err != nil { + return nil, err + } + + return strconv.FormatInt(n, radix), nil +} + +func udfBitwiseNot(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil { + return nil, nil //nolint:nilnil // SQL NULL + } + + n, ok := toInt64(args[0]) + if !ok { + return nil, errOperandType + } + + return ^n, nil +} + +func udfBitCount(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil { + return nil, nil //nolint:nilnil // SQL NULL + } + + n, ok1 := toInt64(args[0]) + width, ok2 := toInt64(args[1]) + + if !ok1 || !ok2 { + return nil, errOperandType + } + + if width < minBitCount || width > maxBitCount { + return nil, evalError( + "Bits specified in bit_count must be between 2 and 64, got " + strconv.FormatInt(width, 10), + ) + } + + mask := ^uint64(0) + if width < maxBitCount { + limit := int64(1) << (width - 1) + if n < -limit || n >= limit { + return nil, evalError("Number must be representable with the bits specified. " + + strconv.FormatInt(n, 10) + " can not be represented with " + strconv.FormatInt(width, 10) + " bits") + } + + mask = uint64(1)< argsTwo { + n, ok := toInt64(args[argsTwo]) + if !ok { + return nil, errOperandType + } + + if n <= 0 { + return nil, evalError("'instance' must be a positive number") + } + + instance = n + } + + if len(sub) == 0 { + return int64(1), nil + } + + idx := runeIndexes(s, sub) + if fromEnd { + slicesReverse(idx) + } + + if instance > int64(len(idx)) { + return int64(0), nil + } + + return int64(idx[instance-1] + 1), nil + } +} + +func slicesReverse(s []int) { + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + s[i], s[j] = s[j], s[i] + } +} + +func argText(v driver.Value) string { + switch x := v.(type) { + case string: + return x + case []byte: + return string(x) + case int64: + return strconv.FormatInt(x, 10) + case float64: + return javaDouble(x) + } + + return "" +} + +// udfReplace is replace(s, search[, replacement]); a missing replacement removes every match. +func udfReplace(_ *fnCtx, args []driver.Value) (driver.Value, error) { + for _, a := range args { + if a == nil { + return nil, nil //nolint:nilnil // SQL NULL + } + } + + repl := "" + if len(args) > argsTwo { + repl = argText(args[argsTwo]) + } + + return strings.ReplaceAll(argText(args[0]), argText(args[1]), repl), nil +} + +func udfInfinity(*fnCtx, []driver.Value) (driver.Value, error) { return math.Inf(1), nil } diff --git a/services/timestreamquery/ts_functions_test.go b/services/timestreamquery/ts_functions_test.go index 57d7e6c4f4..21d3419de4 100644 --- a/services/timestreamquery/ts_functions_test.go +++ b/services/timestreamquery/ts_functions_test.go @@ -32,6 +32,13 @@ func renderDatum(d timestreamquery.Datum) string { } return "[" + strings.Join(parts, ", ") + "]" + case d.RowValue != nil: + parts := make([]string, 0, len(d.RowValue.Data)) + for _, e := range d.RowValue.Data { + parts = append(parts, renderDatum(e)) + } + + return "(" + strings.Join(parts, ", ") + ")" default: return "" } diff --git a/services/timestreamquery/ts_infer.go b/services/timestreamquery/ts_infer.go index e3937454a6..aacb45b873 100644 --- a/services/timestreamquery/ts_infer.go +++ b/services/timestreamquery/ts_infer.go @@ -307,6 +307,8 @@ func (inf *inferrer) inferRowCtor(n *node, sc *scope) tsType { } func (inf *inferrer) inferOperator(n *node, sc *scope) tsType { + inf.markNaNOperands(n) + args := inf.inferAll(n.args, sc) inf.bindParams(n.args, args) @@ -322,6 +324,8 @@ func (inf *inferrer) inferOperator(n *node, sc *scope) tsType { switch n.name { case opAnd, "OR", "=", "<>", "!=", "<", ">", "<=", ">=", "IS DISTINCT": + inf.rewriteCompare(n, args[0], args[1]) + return scalar(tyBoolean) case "||": return concatType(args[0], args[1]) @@ -336,6 +340,7 @@ func (inf *inferrer) inferOperator(n *node, sc *scope) tsType { } res := arithType(n.name, args[0], args[1]) + inf.rewriteIntervalArith(n, args[0], args[1]) inf.rewriteArith(n, args[0], args[1], res) return res diff --git a/services/timestreamquery/ts_infer_checked.go b/services/timestreamquery/ts_infer_checked.go index 824102942a..833f03efa8 100644 --- a/services/timestreamquery/ts_infer_checked.go +++ b/services/timestreamquery/ts_infer_checked.go @@ -1,10 +1,16 @@ package timestreamquery import ( + "slices" "strconv" "strings" ) +const ( + fnNaN = "nan" + fnApproxPercentile = "approx_percentile" +) + func isIntegral(t tsType) bool { return t.kind == tyInteger || t.kind == tyBigint } func intBits(t tsType) int { @@ -54,7 +60,7 @@ func (inf *inferrer) rewriteArith(n *node, a, b, res tsType) { switch { case isIntegral(a) && isIntegral(b): fn = arithName(base, intBits(res), inf.inTry()) - case res.kind == tyDouble && a.isNumeric() && b.isNumeric() && (n.name == "/" || n.name == "%"): + case res.kind == tyDouble && a.isNumeric() && b.isNumeric() && nanAwareArith(n): fn = "ts_d" + base if !inf.nanRoots[n] { fn += "n" @@ -68,9 +74,11 @@ func (inf *inferrer) rewriteArith(n *node, a, b, res tsType) { inf.checkedClose(")", n.end) } -// keepNaN marks a division whose NaN result is rendered or classified, the only places NaN may travel as text. +func nanAwareArith(n *node) bool { return n.name == "/" || n.name == "%" || hasNonFiniteSource(n) } + +// keepNaN marks a NaN expression whose result is rendered or classified, the only places NaN may travel as text. func (inf *inferrer) keepNaN(n *node) { - if n.kind != nBinary || (n.name != "/" && n.name != "%") { + if !isNaNSource(n) { return } @@ -81,7 +89,207 @@ func (inf *inferrer) keepNaN(n *node) { inf.nanRoots[n] = true } +func isNaNSource(n *node) bool { + switch n.kind { + case nBinary: + if n.name == "+" || n.name == "-" || n.name == "*" { + return hasNonFiniteSource(n) + } + + return n.name == "/" || n.name == "%" + case nCast: + return n.typ.kind == tyDouble + case nTypedLit: + return n.typ.kind == tyDouble + case nCall: + lw := strings.ToLower(n.name) + + return lw == fnNaN || isDomainMath(lw) + default: + } + + return false +} + +// hasNonFiniteSource reports whether a subtree can yield NaN or an infinity from finite or unparsed inputs. +func hasNonFiniteSource(n *node) bool { + switch n.kind { + case nCall: + lw := strings.ToLower(n.name) + if lw == "infinity" || lw == fnNaN || isDomainMath(lw) { + return true + } + case nCast, nTypedLit: + if n.typ.kind == tyDouble { + return true + } + case nBinary: + if n.name == "/" || n.name == "%" { + return true + } + default: + } + + return slices.ContainsFunc(n.args, hasNonFiniteSource) +} + +func compareFuncName(op string) (string, bool) { + switch op { + case "=": + return "ts_deq", true + case "<>", "!=": + return "ts_dne", true + case "<": + return "ts_dlt", true + case "<=": + return "ts_dle", true + case ">": + return "ts_dgt", true + case ">=": + return "ts_dge", true + } + + return "", false +} + +// rewriteCompare routes DOUBLE comparisons that may see NaN through functions where NaN is unordered. +func (inf *inferrer) rewriteCompare(n *node, a, b tsType) { + fn, ok := compareFuncName(n.name) + if !ok || n.kind != nBinary || !a.isNumeric() || !b.isNumeric() || !hasNonFiniteSource(n) { + return + } + + inf.checkedEdit(fn+"(", n.start, n.start) + inf.checkedEdit(",", n.opStart, n.opEnd) + inf.checkedClose(")", n.end) +} + +// markNaNOperands lets the operands of a NaN-aware arithmetic node pass NaN to it as text. +func (inf *inferrer) markNaNOperands(n *node) { + if n.kind != nBinary || !hasNonFiniteSource(n) { + return + } + + _, isArith := arithFuncName(n.name) + if _, isCompare := compareFuncName(n.name); !isArith && !isCompare { + return + } + + for _, a := range n.args { + inf.keepNaN(a) + } +} + +// domainMath lists the DOUBLE functions that yield NaN or an infinity outside their domain. +func isDomainMath(lw string) bool { + switch lw { + case "sqrt", "ln", "log10", "log2", "acos", "asin", "acosh", "atanh", "power", "pow": + return true + } + + return false +} + +func (inf *inferrer) rewriteDomainMath(lw string, n *node, args []tsType) { + if lw == fnNaN && len(args) == 0 && !inf.nanRoots[n] { + inf.renameCall(n, "ts_nann") + + return + } + + if !isDomainMath(lw) || len(args) == 0 || !slices.ContainsFunc(args, tsType.isNumeric) { + return + } + + name := "ts_" + lw + if lw == "pow" { + name = "ts_power" + } + + if !inf.nanRoots[n] { + name += "n" + } + + inf.renameCall(n, name) +} + +func isIntervalDS(t tsType) bool { return t.kind == tyIntervalDS } + +// intervalFunc names the function that evaluates an interval operator on operands of types a and b. +func intervalFunc(op string, a, b tsType, computed [2]bool) string { + switch op { + case "+": + return intervalAddFunc(a, b, computed) + case "-": + return intervalSubFunc(a, b, computed) + case "*": + return intervalScaleFunc(a, b) + case "/": + if isIntervalDS(a) && b.isNumeric() { + return "ts_ivdiv" + } + } + + return "" +} + +func intervalSubFunc(a, b tsType, computed [2]bool) string { + switch { + case a.kind == tyTimestamp && isIntervalDS(b) && computed[1]: + return "ts_tssub" + case isIntervalDS(a) && isIntervalDS(b): + return "ts_ivsub" + } + + return "" +} + +func intervalScaleFunc(a, b tsType) string { + switch { + case isIntervalDS(a) && b.isNumeric(): + return "ts_ivmul" + case a.isNumeric() && isIntervalDS(b): + return "ts_ivmulr" + } + + return "" +} + +func intervalAddFunc(a, b tsType, computed [2]bool) string { + switch { + case a.kind == tyTimestamp && isIntervalDS(b) && computed[1]: + return "ts_tsadd" + case isIntervalDS(a) && b.kind == tyTimestamp && computed[0]: + return "ts_tsaddr" + case isIntervalDS(a) && isIntervalDS(b): + return "ts_ivadd" + } + + return "" +} + +// rewriteIntervalArith routes interval day to second arithmetic through functions that accept every interval form. +func (inf *inferrer) rewriteIntervalArith(n *node, a, b tsType) { + isComputed := func(x *node) bool { return x.kind != nLiteral && x.kind != nInterval } + + fn := intervalFunc(n.name, a, b, [2]bool{isComputed(n.args[0]), isComputed(n.args[1])}) + if fn == "" { + return + } + + inf.edit(fn+"(", n.start, n.start) + inf.edit(",", n.opStart, n.opEnd) + inf.closeEdit(")", n.end) +} + func (inf *inferrer) rewriteNegate(n *node, arg tsType) { + if n.name == "-" && isIntervalDS(arg) { + inf.edit("ts_ivneg(", n.start, n.start+1) + inf.closeEdit(")", n.end) + + return + } + if n.name != "-" || !isIntegral(arg) || n.args[0].kind == nLiteral { return } @@ -100,23 +308,119 @@ func (inf *inferrer) rewriteCast(n *node, src tsType) { try = 1 } - inf.checkedEdit("ts_cast(", n.start, n.headEnd) + fn := "ts_cast(" + if n.typ.kind == tyDouble && !inf.nanRoots[n] { + fn = "ts_castn(" + } + + inf.checkedEdit(fn, n.start, n.headEnd) tail := ", '" + scalarTypeofName(src.kind) + "', '" + scalarTypeofName(n.typ.kind) + "', " + strconv.Itoa(try) + ")" inf.checkedEdit(tail, n.opStart, n.end) } -// rewriteArrayAgg routes max(x, n), min(x, n) and approx_percentile(x, ARRAY[...]) to their array-returning forms. +// aggRename names the registered form of an aggregate call the base engine lacks, or "" when it handles the call. +func aggRename(lw string, n *node, args []tsType) string { + switch lw { + case "max", "min": + if len(args) == argsTwo && !n.over && !n.distinct { + return "ts_" + lw + "_n" + } + case "max_by", "min_by": + if len(args) == argsThree { + return "ts_" + lw + "_n" + } + case fnApproxPercentile: + return percentileRename(n, args) + case "approx_distinct": + if len(args) == argsTwo { + return "ts_approx_distinct" + } + } + + return "" +} + +func percentileRename(n *node, args []tsType) string { + switch len(args) { + case argsTwo: + if args[1].kind == tyArray && !n.over { + return "ts_approx_percentile_array" + } + case argsThree: + return "ts_approx_percentile_w" + case argsFour: + return "ts_approx_percentile_wa" + } + + return "" +} + +// rewriteArrayAgg routes the aggregate forms the base engine lacks to their registered implementations. func (inf *inferrer) rewriteArrayAgg(lw string, n *node, args []tsType) { + if to := aggRename(lw, n, args); to != "" { + inf.edit(to, n.start, n.start+len(n.name)) + } +} + +// clockRename routes time-of-day and interval inputs of the extraction and date functions to their own forms. +func clockRename(lw string, args []tsType) string { + switch lw { + case unitHour, unitMinute, unitSecond, unitMillisecond, unitNanosecond, unitDay, unitDayOfMonth: + if len(args) != 1 { + return "" + } + + part := lw + if lw == unitDayOfMonth { + part = unitDay + } + + switch args[0].kind { + case tyTime: + if part != unitDay { + return "ts_time_" + part + } + case tyIntervalDS: + return "ts_iv_" + part + default: + } + case "date_add": + if len(args) == argsThree && args[argsTwo].kind == tyTime { + return "ts_time_add" + } + case "date_diff": + if len(args) == argsThree && args[1].kind == tyTime { + return "ts_time_diff" + } + } + + return "" +} + +// rewriteTypedCall routes calls whose behaviour depends on argument types or count to their registered forms. +func (inf *inferrer) rewriteTypedCall(lw string, n *node, args []tsType) { + rename := func(to string) { inf.edit(to, n.start, n.start+len(n.name)) } + switch { - case (lw == "max" || lw == "min") && len(args) == argsTwo && !n.over && !n.distinct: - inf.edit("ts_"+lw+"_n", n.start, n.start+len(n.name)) - case lw == "approx_percentile" && len(args) == argsTwo && args[1].kind == tyArray && !n.over: - inf.edit("ts_approx_percentile_array", n.start, n.start+len(n.name)) + case lw == "reverse" && len(args) == 1 && args[0].kind == tyArray: + rename("ts_reverse_array") + case lw == "concat" && slices.ContainsFunc(args, func(t tsType) bool { return t.kind == tyArray }): + rename("ts_concat_array") + case lw == "replace" && (len(args) == argsTwo || len(args) == argsThree): + rename("ts_replace") + case lw == "strpos" && len(args) == argsThree: + rename("ts_strpos") + default: + if to := clockRename(lw, args); to != "" { + rename(to) + } } } func (inf *inferrer) rewriteCheckedCall(lw string, n *node, args []tsType) { inf.rewriteArrayAgg(lw, n, args) + inf.rewriteTypedCall(lw, n, args) + inf.rewriteDomainMath(lw, n, args) switch { case len(args) == 1 && args[0].kind == tyDouble && isFloatClassFunc(lw): @@ -153,7 +457,12 @@ func (inf *inferrer) rewriteTypedLiteral(n *node) { try = "1" } - inf.checkedEdit("ts_cast("+lit+", 'varchar', '"+scalarTypeofName(n.typ.kind)+"', "+try+")", n.start, n.end) + fn := "ts_cast(" + if n.typ.kind == tyDouble && !inf.nanRoots[n] { + fn = "ts_castn(" + } + + inf.checkedEdit(fn+lit+", 'varchar', '"+scalarTypeofName(n.typ.kind)+"', "+try+")", n.start, n.end) } } diff --git a/services/timestreamquery/ts_infer_funcs.go b/services/timestreamquery/ts_infer_funcs.go index b814507791..70c5b34836 100644 --- a/services/timestreamquery/ts_infer_funcs.go +++ b/services/timestreamquery/ts_infer_funcs.go @@ -191,7 +191,7 @@ func percentileRule(c *callCtx) tsType { func aggregateRules() map[string]funcRule { return map[string]funcRule{ "max_by": nthRule(argsThree), "min_by": nthRule(argsThree), "max": nthRule(argsTwo), "min": nthRule(argsTwo), - "approx_percentile": percentileRule, + fnApproxPercentile: percentileRule, } } @@ -235,7 +235,9 @@ func bigintRules() map[string]funcRule { "year month day day_of_month hour minute second millisecond quarter week week_of_year day_of_week dow "+ "day_of_year doy year_of_week yow nanosecond to_milliseconds to_nanoseconds date_diff regexp_count "+ "bitwise_and bitwise_or bitwise_xor bitwise_not bit_count crc32 row_number rank dense_rank ntile "+ - "array_position extract width_bucket bitwise_and_agg bitwise_or_agg", + "array_position extract width_bucket bitwise_and_agg bitwise_or_agg ts_strpos ts_approx_distinct "+ + "ts_time_hour ts_time_minute ts_time_second ts_time_millisecond ts_time_nanosecond "+ + "ts_iv_hour ts_iv_minute ts_iv_second ts_iv_millisecond ts_iv_nanosecond ts_iv_day ts_time_diff", ), ) } @@ -254,7 +256,7 @@ func varcharRules() map[string]funcRule { "from_utf8 date_format format_datetime to_iso8601 json_format json_extract_scalar json_extract json_parse "+ "typeof to_base url_extract_fragment url_extract_host url_extract_parameter url_extract_path "+ "url_extract_protocol url_extract_query chr array_join format current_timezone concat_ws "+ - "printf hex char quote group_concat string_agg listagg soundex json_array json_object"), + "printf hex char quote group_concat string_agg listagg soundex json_array json_object ts_replace"), map[string]funcRule{"concat": concatRule}, ) } @@ -272,7 +274,13 @@ func temporalRules() map[string]funcRule { ruleSet(fixed(tyDate), "current_date from_iso8601_date to_date date last_day_of_month"), ruleSet(fixed(tyTime), "current_time localtime"), ruleSet(fixed(tyIntervalDS), "parse_duration ts_tsdiff"), - map[string]funcRule{"date_trunc": same(1), "date_add": same(argsTwo), "bin": binRule, "ts_bin": binRule}, + map[string]funcRule{ + "date_trunc": same(1), + "date_add": same(argsTwo), + "ts_time_add": same(argsTwo), + "bin": binRule, + "ts_bin": binRule, + }, ) } @@ -288,7 +296,12 @@ func passThroughRules() map[string]funcRule { func collectionRules() map[string]funcRule { return union( - ruleSet(same(0), "array_distinct array_sort array_remove slice reverse array_concat shuffle"), + ruleSet(same(0), "array_distinct array_sort array_remove slice reverse array_concat shuffle ts_reverse_array"), + ruleSet(superAll, "ts_concat_array"), + map[string]funcRule{ + "ts_regexp_groups": func(*callCtx) tsType { return arrayOf(arrayOf(scalar(tyVarchar))) }, + "ts_regexp_splice": fixed(tyVarchar), + }, ruleSet(superAll, "array_intersect array_union array_except"), map[string]funcRule{"zip": zipRule, "repeat": arrayOfFirstArg}, ruleSet(arrayOfKind(tyVarchar), "split regexp_extract_all regexp_split"), diff --git a/services/timestreamquery/ts_infer_robust_internal_test.go b/services/timestreamquery/ts_infer_robust_internal_test.go index 87ed26b427..c46726cf55 100644 --- a/services/timestreamquery/ts_infer_robust_internal_test.go +++ b/services/timestreamquery/ts_infer_robust_internal_test.go @@ -109,12 +109,28 @@ func FuzzAnnotateQuery(f *testing.F) { "SELECT max(v, 2), min(v, 2), approx_percentile(v, ARRAY[0.5, 0.9]), is_nan(0.0 / 0), -(a - -b)", "SELECT transform(ARRAY[1, 2], x -> reduce(ARRAY[1], 0, (s, y) -> s + y * x, s -> s)) FROM t WHERE a IN (1 + 2, 3)", "SELECT 'a+b' || CAST(1 + 1 AS varchar), \"col-1\" * 2 FROM t HAVING sum(a) / count(*) > 1", + "SELECT avg(c) FROM (VALUES 1, 2, 3) AS t(c)", "SELECT corr(a, b) FROM (VALUES ((1, 1)), ((2, 3))) AS t(a, b)", + "SELECT * FROM (VALUES 'a, (b', 'c') AS t(x) ORDER BY x", "SELECT 'VALUES 1, 2', \"VALUES\" FROM t", + "SELECT regexp_replace('ab', '(a)', x -> regexp_replace(x[1], '(a)', y -> 'Z'))", + "SELECT array_union(ARRAY[1], ARRAY[2]), zip(ARRAY[1], ARRAY[2]), repeat(1, 3), shuffle(ARRAY[1])", + "SELECT from_base('ff', 16), to_base(255, 16), strrpos('a', 'a', 1), bit_count(1, 8), bitwise_not(1)", + "SELECT max_by(a, b, 2), min_by(a, b, 2), approx_percentile(a, 1, 0.5), approx_percentile(a, 1, ARRAY[0.5], 0.1)", + "SELECT approx_distinct(a, 0.1), skewness(a), regr_slope(a, b), bitwise_and_agg(a) FROM t", + "SELECT 1h + 30m, ago(2m + 30s), 2 * 1h, 1h / 2, -1h, 1year + 2month, now() - (1h + 30m)", + "SELECT nan() + 1, infinity() - infinity(), sqrt(-1) < 1, ln(0), is_nan(nan()), CAST('NaN' AS double) = nan()", + "SELECT 1 < ALL (VALUES 2, 3), a = ANY (SELECT b FROM t), position('a' IN b), extract(DOW FROM t), hour(TIME '1:2')", + "SELECT reverse(ARRAY[1]), concat(ARRAY[1], ARRAY[2]), replace('a', 'b'), strpos('a', 'a', 1)", } { f.Add(s) } f.Fuzz(func(_ *testing.T, q string) { _ = stripSQLComments(q) + _ = normalizeValues(q) + _ = rewriteValuesAliases(q) + _ = rewriteRegexpLambdas(q) + _ = rewriteFunctionSyntax(q) + _ = rewriteQuantified(q) _, _ = parseSQL(q) _ = buildAnnotation(q, loadedSet{}, time.Time{}, nil) }) diff --git a/services/timestreamquery/ts_regexp_lambda.go b/services/timestreamquery/ts_regexp_lambda.go new file mode 100644 index 0000000000..77d63f7ac2 --- /dev/null +++ b/services/timestreamquery/ts_regexp_lambda.go @@ -0,0 +1,166 @@ +package timestreamquery + +import ( + "database/sql/driver" + "encoding/json/jsontext" + "encoding/json/v2" + "regexp" + "strings" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" +) + +const maxRegexpMatches = 100000 + +var reRegexpReplace = regexp.MustCompile(`(?i)\bregexp_replace\s*\(`) + +// rewriteRegexpLambdas turns regexp_replace(s, p, x -> body) into a splice of transform() over the match groups. +func rewriteRegexpLambdas(q string) string { + if !reRegexpReplace.MatchString(q) { + return q + } + + mask := quoteMask(q) + + var ( + sb strings.Builder + pos int + ) + + for _, loc := range reRegexpReplace.FindAllStringIndex(q, -1) { + if loc[0] < pos || mask[loc[0]] { + continue + } + + open := loc[1] - 1 + + closeAt := closeParen(q, open) + if closeAt < 0 { + continue + } + + args := splitTop(q[open+1 : closeAt]) + if len(args) != argsThree || reLambdaOne.FindStringSubmatch(args[argsTwo]) == nil { + continue + } + + subject, pattern := rewriteRegexpLambdas(args[0]), rewriteRegexpLambdas(args[1]) + lam := rewriteRegexpLambdas(args[argsTwo]) + + sb.WriteString(q[pos:loc[0]]) + sb.WriteString("ts_regexp_splice(" + subject + "," + pattern + ", transform(ts_regexp_groups(" + + subject + "," + pattern + "), " + lam + "))") + + pos = closeAt + 1 + } + + sb.WriteString(q[pos:]) + + return sb.String() +} + +func compileJava(pattern string) (*regexp.Regexp, error) { + re, err := regexp.Compile(pattern) + if err != nil { + return nil, evalError("Invalid regular expression: " + pattern) + } + + return re, nil +} + +func regexpArgs(args []driver.Value) (string, *regexp.Regexp, bool, error) { + if args[0] == nil || args[1] == nil { + return "", nil, true, nil + } + + s, ok1 := textOf(args[0]) + p, ok2 := textOf(args[1]) + + if !ok1 || !ok2 { + return "", nil, false, errOperandType + } + + re, err := compileJava(p) + + return s, re, false, err +} + +// udfRegexpGroups is the capturing groups (numbered from one) of every match, as an array of arrays. +func udfRegexpGroups(_ *fnCtx, args []driver.Value) (driver.Value, error) { + s, re, isNull, err := regexpArgs(args) + if err != nil || isNull { + return nil, err + } + + matches := re.FindAllStringSubmatchIndex(s, maxRegexpMatches) + out := make(rawElems, len(matches)) + + for i, m := range matches { + groups := make(rawElems, 0, len(m)/argsTwo) + + for g := 1; g < len(m)/argsTwo; g++ { + if m[g*argsTwo] < 0 { + groups = append(groups, kwNull) + + continue + } + + groups = append(groups, quoteJSON(s[m[g*argsTwo]:m[g*argsTwo+1]])) + } + + out[i] = groups.text() + } + + return out.encode(), nil +} + +// udfRegexpSplice replaces each match of the pattern in the subject with the matching replacement. +func udfRegexpSplice(_ *fnCtx, args []driver.Value) (driver.Value, error) { + s, re, isNull, err := regexpArgs(args[:argsTwo]) + if err != nil || isNull || args[argsTwo] == nil { + return nil, err + } + + repl, null, err := decodeRawArray(args[argsTwo]) + if err != nil || null { + return nil, err + } + + matches := re.FindAllStringIndex(s, maxRegexpMatches) + if len(matches) != len(repl) { + return nil, errOperandType + } + + var sb strings.Builder + + cur := 0 + + for i, m := range matches { + text, isNil := replacementText(repl[i]) + if isNil { + return nil, nil //nolint:nilnil // a null replacement makes the result SQL NULL + } + + sb.WriteString(s[cur:m[0]]) + sb.WriteString(text) + + cur = m[1] + } + + sb.WriteString(s[cur:]) + + return sb.String(), nil +} + +func replacementText(raw string) (string, bool) { + if raw == kwNull { + return "", true + } + + var s string + if json.Unmarshal([]byte(raw), &s, jsonx.V1()) == nil { + return s, false + } + + return string(jsontext.Value(raw)), false +} diff --git a/services/timestreamquery/ts_render.go b/services/timestreamquery/ts_render.go index 55d5c2d544..74387d1dbf 100644 --- a/services/timestreamquery/ts_render.go +++ b/services/timestreamquery/ts_render.go @@ -168,7 +168,7 @@ func renderTimeOfDay(v any) Datum { return renderText(v) } - for _, l := range []string{"15:04:05.999999999", "15:04:05"} { + for _, l := range []string{layoutClockFrac, layoutClock} { if t, err := time.Parse(l, s); err == nil { return ScalarDatum(t.Format("15:04:05.000000000")) } diff --git a/services/timestreamquery/ts_rewrite.go b/services/timestreamquery/ts_rewrite.go index b223303350..98236b2e69 100644 --- a/services/timestreamquery/ts_rewrite.go +++ b/services/timestreamquery/ts_rewrite.go @@ -13,6 +13,7 @@ var ( reMeasureCol = regexp.MustCompile(`(?i)\bmeasure_value::(double|bigint|varchar|boolean|timestamp)\b`) reDuration = regexp.MustCompile( `(?i)\b(\d+)(nanoseconds?|ns|microseconds?|us|milliseconds?|ms|seconds?|s|minutes?|m|hours?|h|days?|d)\b`) + reYearMonth = regexp.MustCompile(`(?i)\b(\d+)(years?|y|months?)\b`) reSignedDur = regexp.MustCompile( `(?i)([+\-])\s*(\d+)(nanoseconds?|ns|microseconds?|us|milliseconds?|ms|seconds?|s|minutes?|m|hours?|h|days?|d)\b`, ) @@ -61,6 +62,8 @@ func durationNanos(n, unit string) string { // measure_value::T columns, @scheduled_runtime) into the Trino subset the SQLite // engine translates. String literals and quoted identifiers are left untouched. func rewriteTimestream(q string, now time.Time, vars map[string]string) string { + q = rewriteValuesAliases(q) + q = rewriteRegexpLambdas(q) q = reTypedLiteral.ReplaceAllString(q, "CAST('$2' AS $1)") q = reIntervalCall.ReplaceAllStringFunc(q, func(m string) string { g := reIntervalCall.FindStringSubmatch(m) @@ -144,6 +147,16 @@ func rewriteCode(seg, nowLit, dateLit, timeLit string, vars map[string]string) s } seg = reMeasureCol.ReplaceAllString(seg, `"measure_value::$1"`) + seg = reYearMonth.ReplaceAllStringFunc(seg, func(m string) string { + g := reYearMonth.FindStringSubmatch(m) + unit := "month" + + if lw := strings.ToLower(g[2]); lw == "y" || strings.HasPrefix(lw, "year") { + unit = "year" + } + + return "INTERVAL '" + g[1] + "' " + unit + }) seg = reSignedDur.ReplaceAllStringFunc(seg, func(m string) string { g := reSignedDur.FindStringSubmatch(m) diff --git a/services/timestreamquery/ts_series.go b/services/timestreamquery/ts_series.go index 2f4adefedf..8e9bb163af 100644 --- a/services/timestreamquery/ts_series.go +++ b/services/timestreamquery/ts_series.go @@ -131,7 +131,7 @@ func encodeJSONScalar(v any) string { return strconv.FormatInt(x, 10) case float64: if math.IsNaN(x) || math.IsInf(x, 0) { - return "null" + return kwNull } s := strconv.FormatFloat(x, 'g', -1, 64) @@ -628,12 +628,19 @@ func udfSequence(_ *fnCtx, args []driver.Value) (driver.Value, error) { func sequenceOfTimes(start time.Time, args []driver.Value) (driver.Value, error) { stop, ok := parseTSValue(args[1]) - if !ok || len(args) <= argsTwo { + if !ok { return nil, errBadSeq } - step, ok := intArg(args[argsTwo]) - if !ok || step == 0 { + step := int64(hoursInDay * time.Hour) + + if len(args) > argsTwo { + if step, ok = intArg(args[argsTwo]); !ok { + return nil, errBadSeq + } + } + + if step == 0 { return nil, errBadSeq } @@ -644,6 +651,9 @@ func sequenceOfInts(args []driver.Value) (driver.Value, error) { lo, ok1 := intArg(args[0]) hi, ok2 := intArg(args[1]) step := int64(1) + if ok1 && ok2 && lo > hi { + step = -1 + } if len(args) > argsTwo { var ok3 bool diff --git a/services/timestreamquery/ts_sqlexpr.go b/services/timestreamquery/ts_sqlexpr.go index c917e5284b..2ffa926b68 100644 --- a/services/timestreamquery/ts_sqlexpr.go +++ b/services/timestreamquery/ts_sqlexpr.go @@ -142,6 +142,7 @@ func (p *sqlParser) parsePredicate() (*node, error) { } l = p.binary(t.text, l, r) + l.opStart, l.opEnd = t.start, t.end case t.is("is"): if l, err = p.parseIs(l); err != nil { return nil, err @@ -413,7 +414,16 @@ func (p *sqlParser) parsePrimary() (*node, error) { case tkDuration: p.pos++ - return &node{kind: nLiteral, name: t.text, typ: scalar(tyIntervalDS), start: t.start, end: t.end}, nil + k := tyIntervalDS + if i := strings.IndexFunc( + t.text, + func(r rune) bool { return r < '0' || r > '9' }, + ); i >= 0 && + isYearMonthUnit(t.text[i:]) { + k = tyIntervalYM + } + + return &node{kind: nLiteral, name: t.text, typ: scalar(k), start: t.start, end: t.end}, nil case tkString: p.pos++ @@ -777,7 +787,7 @@ func (p *sqlParser) parseArrayCtor() (*node, error) { func isIntervalUnit(u string) bool { switch strings.ToLower(u) { - case kwYear, kwMonth, "day", "hour", "minute", "second": + case kwYear, kwMonth, unitDay, unitHour, unitMinute, unitSecond: return true } diff --git a/services/timestreamquery/ts_sqllex.go b/services/timestreamquery/ts_sqllex.go index d1fd915c88..ecca59c240 100644 --- a/services/timestreamquery/ts_sqllex.go +++ b/services/timestreamquery/ts_sqllex.go @@ -142,8 +142,17 @@ func lexNumber(q string, i int) int { func isDurationUnit(w string) bool { switch strings.ToLower(w) { - case "ns", "us", "ms", "s", "m", "h", "d", "nanosecond", "microsecond", "millisecond", "second", "minute", - "hour", "day", "nanoseconds", "microseconds", "milliseconds", "seconds", "minutes", "hours", "days": + case "ns", "us", "ms", "s", "m", "h", "d", unitNanosecond, "microsecond", unitMillisecond, unitSecond, unitMinute, + unitHour, unitDay, "nanoseconds", "microseconds", "milliseconds", "seconds", "minutes", "hours", "days": + return true + } + + return isYearMonthUnit(w) +} + +func isYearMonthUnit(w string) bool { + switch strings.ToLower(w) { + case "y", "year", "years", "month", "months": return true } diff --git a/services/timestreamquery/ts_sqlparse.go b/services/timestreamquery/ts_sqlparse.go index f67d56a04b..fa52cd2ba4 100644 --- a/services/timestreamquery/ts_sqlparse.go +++ b/services/timestreamquery/ts_sqlparse.go @@ -100,7 +100,7 @@ func (p *sqlParser) leave() { p.depth-- } func isReservedWord(lw string) bool { switch lw { - case "from", "where", "group", "having", "order", "limit", "offset", "union", "intersect", "except", "on", + case "from", kwWhere, "group", kwHaving, "order", kwLimit, "offset", "union", "intersect", "except", "on", "using", "join", "inner", "left", "right", "full", "cross", "natural", "window", "fetch", "as", "when", "then", "else", "end", "and", "or", opNotLower, "is", "in", "between", "like", "select", "with", "over": return true diff --git a/services/timestreamquery/ts_syntax_rewrite.go b/services/timestreamquery/ts_syntax_rewrite.go new file mode 100644 index 0000000000..999e5ce90d --- /dev/null +++ b/services/timestreamquery/ts_syntax_rewrite.go @@ -0,0 +1,330 @@ +package timestreamquery + +import ( + "regexp" + "strconv" + "strings" +) + +var ( + rePosition = regexp.MustCompile(`(?i)\bposition\s*\(`) + reExtract = regexp.MustCompile( + `(?i)\bextract\s*\(\s*(dow|doy|yow|quarter|week|day_of_year|day_of_month|day_of_week)\s+from\s`) +) + +func extractFunction(field string) string { + switch strings.ToLower(field) { + case "dow", "day_of_week": + return "day_of_week" + case "doy", "day_of_year": + return "day_of_year" + case "yow": + return "year_of_week" + case unitDayOfMonth: + return unitDay + } + + return strings.ToLower(field) +} + +// rewriteFunctionSyntax rewrites position(x IN y) and the extract fields the base engine lacks into plain calls. +func rewriteFunctionSyntax(q string) string { + lq := strings.ToLower(q) + if !strings.Contains(lq, "position") && !strings.Contains(lq, "extract") { + return q + } + + q = rewriteCalls(q, rePosition, func(_ []string, inner string) (string, bool) { + parts := splitTopWord(inner, "in") + if len(parts) != argsTwo { + return "", false + } + + return "strpos(" + parts[1] + ", " + parts[0] + ")", true + }) + + return rewriteCalls(q, reExtract, func(g []string, inner string) (string, bool) { + return extractFunction(g[1]) + "(" + inner + ")", true + }) +} + +// rewriteCalls replaces each match of re (which ends just before the call's arguments or at its opening parenthesis) +// with the text replace returns for the argument text. +func rewriteCalls(q string, re *regexp.Regexp, replace func(groups []string, inner string) (string, bool)) string { + mask := quoteMask(q) + + var ( + sb strings.Builder + pos int + ) + + for _, loc := range re.FindAllStringSubmatchIndex(q, -1) { + if loc[0] < pos || mask[loc[0]] { + continue + } + + open := loc[0] + strings.Index(q[loc[0]:loc[1]], "(") + + closeAt := closeParen(q, open) + if closeAt < 0 { + continue + } + + out, ok := replace(submatches(q, loc), q[max(open+1, loc[1]):closeAt]) + if !ok { + continue + } + + sb.WriteString(q[pos:loc[0]]) + sb.WriteString(out) + + pos = closeAt + 1 + } + + sb.WriteString(q[pos:]) + + return sb.String() +} + +func submatches(q string, loc []int) []string { + groups := make([]string, 0, len(loc)/argsTwo) + + for i := 0; i+1 < len(loc); i += argsTwo { + if loc[i] >= 0 { + groups = append(groups, q[loc[i]:loc[i+1]]) + } else { + groups = append(groups, "") + } + } + + return groups +} + +// splitTopWord splits s around the first top-level occurrence of the keyword word. +func splitTopWord(s, word string) []string { + mask := quoteMask(s) + depth := 0 + + for i := range len(s) { + switch { + case mask[i]: + case s[i] == '(' || s[i] == '[': + depth++ + case s[i] == ')' || s[i] == ']': + depth-- + case depth == 0 && isWordAt(s, i, word): + return []string{strings.TrimSpace(s[:i]), strings.TrimSpace(s[i+len(word):])} + } + } + + return []string{s} +} + +func isWordAt(s string, i int, word string) bool { + if i+len(word) > len(s) || !strings.EqualFold(s[i:i+len(word)], word) { + return false + } + + before := i == 0 || !isIdentPart(s[i-1]) + after := i+len(word) == len(s) || !isIdentPart(s[i+len(word)]) + + return before && after +} + +func isQuantifier(t token) bool { return t.is("all") || t.is("any") || t.is("some") } + +func operandBoundary(t token) bool { + if t.kind == tkOp { + return t.text == "," || isCmpOp(t.text) + } + + if t.kind != tkIdent { + return false + } + + switch strings.ToLower(t.text) { + case "select", "distinct", "where", "and", "or", "not", "on", kwHaving, "when", "then", "else", "case", "by", + kwLimit, "using": + return true + } + + return false +} + +// operandStart returns the offset where the expression ending before toks[opIdx] begins, or -1. +func operandStart(toks []token, opIdx int) int { + depth := 0 + start := -1 + + for j := opIdx - 1; j >= 0; j-- { + t := toks[j] + + switch { + case t.isOp(")"): + depth++ + case t.isOp("("): + if depth == 0 { + return start + } + + depth-- + case depth == 0 && operandBoundary(t): + return start + } + + start = t.start + } + + return start +} + +// rewriteQuantified rewrites `x op ALL|ANY|SOME (query)` into a scalar subquery over the query's rows. +func rewriteQuantified(q string) string { + lq := strings.ToLower(q) + if !strings.Contains(lq, "all") && !strings.Contains(lq, "any") && !strings.Contains(lq, "some") { + return q + } + + toks, err := tokenizeSQL(q) + if err != nil { + return q + } + + var ( + sb strings.Builder + cur int + counter int + ) + + for i := 1; i+2 < len(toks); i++ { + repl, operand, end, ok := quantifiedAt(q, toks, i, counter) + if !ok || operand < cur { + continue + } + + sb.WriteString(q[cur:operand]) + sb.WriteString(repl) + + counter++ + cur = end + + for i+1 < len(toks) && toks[i+1].start < cur { + i++ + } + } + + sb.WriteString(q[cur:]) + + return sb.String() +} + +// quantifiedAt rewrites the quantified comparison whose operator is toks[i]; operand and end are its source span. +func quantifiedAt(q string, toks []token, i, counter int) (string, int, int, bool) { + t := toks[i] + if t.kind != tkOp || !isCmpOp(t.text) || !isQuantifier(toks[i+1]) || !toks[i+argsTwo].isOp("(") { + return "", 0, 0, false + } + + operand := operandStart(toks, i) + open := toks[i+argsTwo].start + closeAt := closeParen(q, open) + + if operand < 0 || closeAt < 0 { + return "", 0, 0, false + } + + aliased, ok := aliasFirstColumn(rewriteQuantified(q[open+1 : closeAt])) + if !ok { + return "", 0, 0, false + } + + repl := quantifiedSQL( + strings.TrimSpace(q[operand:t.start]), + t.text, + strings.ToLower(toks[i+1].text), + aliased, + counter, + ) + + return repl, operand, closeAt + 1, true +} + +// aliasFirstColumn names the single output column of a quantified subquery "_v". +func aliasFirstColumn(sub string) (string, bool) { + toks, err := tokenizeSQL(sub) + if err != nil || len(toks) < argsTwo { + return "", false + } + + if toks[0].is("values") { + return "SELECT column1 AS \"_v\" FROM (" + sub + ")", true + } + + if !toks[0].is("select") { + return "", false + } + + return aliasSelectItem(sub, toks) +} + +func aliasSelectItem(sub string, toks []token) (string, bool) { + i := 1 + if toks[i].is("distinct") || toks[i].is("all") { + i++ + } + + depth := 0 + itemStart := toks[i].start + + for j := i; j < len(toks); j++ { + t := toks[j] + + switch { + case t.isOp("("): + depth++ + case t.isOp(")"): + depth-- + case depth == 0 && endsSelectItem(t): + return aliasItem(sub, toks, i, j, itemStart), !t.isOp(",") + } + } + + return "", false +} + +func endsSelectItem(t token) bool { + return t.is("from") || t.isOp(",") || t.kind == tkEOF || t.is("union") || t.is(kwWhere) +} + +func aliasItem(sub string, toks []token, from, to, itemStart int) string { + end := toks[to].start + if to > from+1 && toks[to-2].is("as") { + return sub[:toks[to-2].start] + `AS "_v"` + sub[toks[to-1].end:] + } + + return sub[:itemStart] + strings.TrimRight(sub[itemStart:end], " \t\r\n") + ` AS "_v" ` + sub[end:] +} + +func quantifiedSQL(operand, op, mode, sub string, n int) string { + aliased, ok := aliasFirstColumn(sub) + if !ok { + return "(" + operand + ") " + op + " " + strings.ToUpper(mode) + " (" + sub + ")" + } + + rel := `(` + aliased + `) AS "_q` + strconv.Itoa(n) + `"` + cmp := "(" + operand + ") " + op + ` "_v"` + + all := `SELECT CASE WHEN count(*) = 0 THEN 1 ` + + `WHEN max(CASE WHEN NOT (` + cmp + `) THEN 1 ELSE 0 END) = 1 THEN 0 ` + + `WHEN max(CASE WHEN (` + cmp + `) IS NULL THEN 1 ELSE 0 END) = 1 THEN NULL ELSE 1 END FROM ` + rel + + some := `SELECT CASE WHEN max(CASE WHEN (` + cmp + `) THEN 1 ELSE 0 END) = 1 THEN 1 ` + + `WHEN count(*) = 0 THEN 0 ` + + `WHEN max(CASE WHEN (` + cmp + `) IS NULL THEN 1 ELSE 0 END) = 1 THEN NULL ELSE 0 END FROM ` + rel + + if mode == "all" { + return "((" + all + ") = 1)" + } + + return "((" + some + ") = 1)" +} diff --git a/services/timestreamquery/ts_value_rewrite_internal_test.go b/services/timestreamquery/ts_value_rewrite_internal_test.go new file mode 100644 index 0000000000..2268009f7a --- /dev/null +++ b/services/timestreamquery/ts_value_rewrite_internal_test.go @@ -0,0 +1,229 @@ +package timestreamquery + +import ( + "database/sql/driver" + "math" + "slices" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNormalizeValues(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + }{ + {"scalar rows", "SELECT c FROM (VALUES 1, 2, 3) AS t(c)", "SELECT c FROM (VALUES (1), (2), (3)) AS t(c)"}, + { + "row rows unchanged", + "SELECT 1 FROM (VALUES (1, 2), (3, 4)) AS t(a, b)", + "SELECT 1 FROM (VALUES (1, 2), (3, 4)) AS t(a, b)", + }, + {"paired rows", "VALUES ((1, 2)), ((3, 4))", "VALUES (1, 2), (3, 4)"}, + {"expression rows", "VALUES (1 + 2) * 3, 4", "VALUES ((1 + 2) * 3), (4)"}, + {"call row", "VALUES f(1, 2), 3", "VALUES (f(1, 2)), (3)"}, + { + "string commas", + "SELECT 1 FROM (VALUES 'a, b', 'c') AS t(x)", + "SELECT 1 FROM (VALUES ('a, b'), ('c')) AS t(x)", + }, + {"order by after", "VALUES 2, 1 ORDER BY 1", "VALUES (2), (1) ORDER BY 1"}, + {"literal untouched", "SELECT 'VALUES 1, 2'", "SELECT 'VALUES 1, 2'"}, + {"quoted identifier untouched", `SELECT "values" FROM t`, `SELECT "values" FROM t`}, + {"no values", "SELECT 1", "SELECT 1"}, + {"bare keyword", "SELECT values FROM t", "SELECT values FROM t"}, + {"unterminated", "VALUES 1, 'a", "VALUES 1, 'a"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tt.want, normalizeValues(tt.query)) + }) + } +} + +func TestRewriteValuesAliases(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + }{ + { + "column list", + "SELECT c FROM (VALUES (1), (2)) AS t(c)", + "SELECT c FROM (SELECT column1 AS c FROM (VALUES (1), (2))) AS t", + }, + { + "two columns no as", + "SELECT a FROM (VALUES (1, 2)) t(a, b)", + "SELECT a FROM (SELECT column1 AS a, column2 AS b FROM (VALUES (1, 2))) AS t", + }, + {"no column list", "SELECT * FROM (VALUES (1)) AS t", "SELECT * FROM (VALUES (1)) AS t"}, + {"literal untouched", "SELECT '(VALUES (1)) AS t(c)'", "SELECT '(VALUES (1)) AS t(c)'"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tt.want, rewriteValuesAliases(tt.query)) + }) + } +} + +func TestRewriteRegexpLambdas(t *testing.T) { + t.Parallel() + + got := rewriteRegexpLambdas("SELECT regexp_replace(a, '(x)', y -> upper(y[1])), regexp_replace(b, 'q', 'r')") + assert.Contains(t, got, "ts_regexp_splice(a, '(x)'") + assert.Contains(t, got, "regexp_replace(b, 'q', 'r')") + assert.Equal( + t, + "SELECT 'regexp_replace(a, p, x -> x)'", + rewriteRegexpLambdas("SELECT 'regexp_replace(a, p, x -> x)'"), + ) +} + +func TestFiniteDoubleSQLStaysNative(t *testing.T) { + t.Parallel() + + for _, q := range []string{ + "SELECT 1.5 + 2.5 * 3.0, 1.5 < 2.5, 1.5 - 0.5", + "SELECT sum(1.5 + 2.5), avg(2.0 * 3.0)", + } { + ann := annotateQuery(q, loadedSet{}, time.Time{}, nil) + require.True(t, ann.ok, q) + assert.NotContains(t, ann.query, "ts_d", q) + assert.Equal(t, q, ann.query, q) + } +} + +func TestNewFunctionsTolerateAnyArgument(t *testing.T) { + t.Parallel() + + values := []driver.Value{ + nil, int64(0), int64(-1), int64(math.MinInt64), int64(math.MaxInt64), 1.5, math.NaN(), math.Inf(1), + "", "x", "NaN", arrayMark + "[1,2]", arrayMark + "[", arrayMark + "{}", []byte{0xff, 0}, true, + } + + funcs := slices.Concat(tsTextFuncs(), tsArrayFuncs(), domainMathFuncs()) + + for _, f := range funcs { + t.Run(f.name, func(t *testing.T) { + t.Parallel() + + for _, a := range values { + for _, b := range values { + arities := []int{int(f.nargs)} + if f.nargs < 0 { + arities = []int{0, 1, argsTwo, argsThree, maxZipArrays + 1} + } + + for _, arity := range arities { + args := []driver.Value{a, b, a, b, a, b}[:arity] + + assert.NotPanics(t, func() { _, _ = f.impl(nil, args) }, "%s %v %v", f.name, a, b) + } + } + } + }) + } +} + +func TestBufferedAggregatesTolerateAnyArgument(t *testing.T) { + t.Parallel() + + values := []driver.Value{nil, int64(0), int64(-5), 2.5, "x", "NaN", arrayMark + "[0.5]", []byte{1}, true} + + rows := make([][]driver.Value, 0, len(values)) + for _, v := range values { + rows = append(rows, []driver.Value{v, v, v, v}) + } + + finishers := []func([]aggRow) (driver.Value, error){ + bitwiseAgg(func(a, b int64) int64 { return a & b }), skewnessOf, regressionAgg(false), regressionAgg(true), + approxDistinct, topByKey(true), topByKey(false), weightedPercentile, + } + + for _, fin := range finishers { + assert.NotPanics(t, func() { + _, _ = fin(rows) + _, _ = fin(nil) + }) + } + + for _, chk := range []func(aggRow) error{ + checkApproxError, checkTopN("max_by"), checkWeightedPercentile, checkWeight, checkAccuracy, + } { + for _, r := range rows { + assert.NotPanics(t, func() { _ = chk(r) }) + } + } + + assert.True(t, strings.HasPrefix(arrayMark, "\x01")) +} + +func TestRewriteFunctionSyntax(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + }{ + {"position", "SELECT position('b' IN 'abc')", "SELECT strpos('abc', 'b')"}, + {"position nested", "SELECT position(lower(x) IN a || b) FROM t", "SELECT strpos(a || b, lower(x)) FROM t"}, + {"position without in", "SELECT position(a) FROM t", "SELECT position(a) FROM t"}, + {"extract dow", "SELECT extract(DOW FROM t)", "SELECT day_of_week(t)"}, + {"extract yow", "SELECT extract( yow FROM time)", "SELECT year_of_week(time)"}, + { + "extract nested", + "SELECT extract(QUARTER FROM date_add('day', 1, t))", + "SELECT quarter(date_add('day', 1, t))", + }, + {"extract supported untouched", "SELECT extract(YEAR FROM t)", "SELECT extract(YEAR FROM t)"}, + { + "literal untouched", + "SELECT 'position(a IN b) extract(DOW FROM x)'", + "SELECT 'position(a IN b) extract(DOW FROM x)'", + }, + {"identifier untouched", `SELECT "position(a IN b)" FROM t`, `SELECT "position(a IN b)" FROM t`}, + {"unbalanced", "SELECT position(a IN b", "SELECT position(a IN b"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tt.want, rewriteFunctionSyntax(tt.query)) + }) + } +} + +func TestRewriteQuantified(t *testing.T) { + t.Parallel() + + for _, q := range []string{ + "SELECT 'x > ALL (VALUES 1)'", "SELECT a FROM t WHERE a > 1", `SELECT "all" > 1`, "SELECT x > ALL (a)", + } { + assert.Equal(t, q, rewriteQuantified(q), q) + } + + got := rewriteQuantified("SELECT a FROM t WHERE b + 1 >= ALL (SELECT c FROM u) AND d = 1") + assert.Contains(t, got, `SELECT c AS "_v" FROM u`) + assert.Contains(t, got, "(b + 1) >= \"_v\"") + assert.True(t, strings.HasSuffix(got, ") AND d = 1"), got) + + assert.Contains(t, rewriteQuantified("SELECT 1 = ANY (VALUES 1, 2)"), `SELECT column1 AS "_v" FROM (VALUES 1, 2)`) +} diff --git a/services/timestreamquery/ts_value_semantics_test.go b/services/timestreamquery/ts_value_semantics_test.go new file mode 100644 index 0000000000..970c001bb7 --- /dev/null +++ b/services/timestreamquery/ts_value_semantics_test.go @@ -0,0 +1,222 @@ +package timestreamquery_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestQuery_NonFiniteDoubles(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + }{ + {"sqrt negative", `SELECT sqrt(-1)`, "NaN"}, + {"ln negative", `SELECT ln(-1)`, "NaN"}, + {"acos range", `SELECT acos(2)`, "NaN"}, + {"power negative base", `SELECT power(-1, 0.5)`, "NaN"}, + {"cast text nan", `SELECT CAST('NaN' AS double)`, "NaN"}, + {"zero over zero", `SELECT 0e0/0e0`, "NaN"}, + {"nan function", `SELECT nan()`, "NaN"}, + {"is_nan sqrt", `SELECT is_nan(sqrt(-1))`, "true"}, + {"is_nan cast", `SELECT is_nan(CAST('NaN' AS double))`, "true"}, + {"is_nan nan", `SELECT is_nan(nan())`, "true"}, + {"is_nan finite", `SELECT is_nan(1.5)`, "false"}, + {"ln zero", `SELECT ln(0)`, "-Infinity"}, + {"log10 zero", `SELECT log10(0)`, "-Infinity"}, + {"negated ln zero", `SELECT -ln(0)`, "Infinity"}, + {"is_infinite ln zero", `SELECT is_infinite(ln(0))`, "true"}, + {"is_finite division", `SELECT is_finite(1e0/0e0)`, "false"}, + {"infinity minus infinity", `SELECT infinity() - infinity()`, "NaN"}, + {"infinity times zero", `SELECT infinity() * 0e0`, "NaN"}, + {"nan plus", `SELECT nan() + 1`, "NaN"}, + {"nan chain", `SELECT nan() + 1 + 2`, "NaN"}, + {"division chain", `SELECT 0e0/0e0 + 1`, "NaN"}, + {"is_nan arithmetic", `SELECT is_nan(nan() * 2)`, "true"}, + {"nan equals nan", `SELECT nan() = nan()`, "false"}, + {"nan differs", `SELECT nan() <> nan()`, "true"}, + {"nan less", `SELECT nan() < 1`, "false"}, + {"nan greater equal", `SELECT nan() >= 1`, "false"}, + {"infinity greater", `SELECT infinity() > 1e308`, "true"}, + {"cast text infinity compare", `SELECT CAST('Infinity' AS double) > 1`, "true"}, + {"negative infinity", `SELECT -infinity()`, "-Infinity"}, + {"nan to varchar", `SELECT CAST(CAST('NaN' AS double) AS varchar)`, "NaN"}, + {"finite sum", `SELECT 1.5 + 2.5`, "4.0"}, + {"null sqrt", `SELECT sqrt(NULL)`, ""}, + {"filter drops nan", `SELECT count(*) FROM db.t WHERE nan() > 1`, "0"}, + {"filter keeps infinity", `SELECT count(*) FROM db.t WHERE infinity() > 1`, "6"}, + {"try cast nan", `SELECT TRY_CAST('abc' AS double)`, ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rows, _ := runFn(t, tt.query) + require.Len(t, rows, 1) + assert.Equal(t, tt.want, rows[0][0]) + }) + } +} + +func TestQuery_IntervalArithmetic(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + typ string + }{ + {"add", `SELECT 1h + 30m`, "0 01:30:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + {"add days", `SELECT 1d + 1h`, "1 01:00:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + {"sub", `SELECT 1h - 30m`, "0 00:30:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + {"sub negative", `SELECT 1h - 2h`, "-0 01:00:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + {"mul", `SELECT 1h * 2`, "0 02:00:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + {"mul left", `SELECT 2 * 1h`, "0 02:00:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + {"mul double", `SELECT 1h * 1.5`, "0 01:30:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + {"div", `SELECT 1h / 2`, "0 00:30:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + {"negate", `SELECT -1h`, "-0 01:00:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + {"typeof", `SELECT typeof(1h + 30m)`, "interval day to second", "VARCHAR"}, + {"parse_duration add", `SELECT parse_duration('1h') + 1m`, "0 01:01:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + { + "sql literal add", + `SELECT interval '1' hour + interval '30' minute`, + "0 01:30:00.000000000", + "INTERVAL_DAY_TO_SECOND", + }, + {"mixed literal add", `SELECT interval '1' hour + 30m`, "0 01:30:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + {"nested", `SELECT (1h + 30m) * 2 - 1h`, "0 02:00:00.000000000", "INTERVAL_DAY_TO_SECOND"}, + {"null operand", `SELECT 1h + CAST(NULL AS interval day to second)`, "", "INTERVAL_DAY_TO_SECOND"}, + {"compare sum", `SELECT 1h + 30m > 80m`, "true", "BOOLEAN"}, + {"compare equal", `SELECT 1h + 30m = 90m`, "true", "BOOLEAN"}, + {"compare less", `SELECT 1h - 30m < 1h`, "true", "BOOLEAN"}, + {"between", `SELECT 1h BETWEEN 30m AND 2h`, "true", "BOOLEAN"}, + {"ago sum", `SELECT ago(2m + 30s)`, "2026-10-31 11:57:30.000000000", "TIMESTAMP"}, + {"ago product", `SELECT ago(2 * 1h)`, "2026-10-31 10:00:00.000000000", "TIMESTAMP"}, + {"ago sql literal sum", `SELECT ago(interval '1' hour + 30m)`, "2026-10-31 10:30:00.000000000", "TIMESTAMP"}, + {"bin computed", `SELECT bin(now(), 5m + 5m)`, "2026-10-31 12:00:00.000000000", "TIMESTAMP"}, + {"timestamp plus sum", `SELECT now() + (1h + 30m)`, "2026-10-31 13:30:00.000000000", "TIMESTAMP"}, + {"timestamp chain", `SELECT now() + 1h + 30m`, "2026-10-31 13:30:00.000000000", "TIMESTAMP"}, + {"to_milliseconds sum", `SELECT to_milliseconds(1h + 30m)`, "5400000", "BIGINT"}, + {"to_nanoseconds sum", `SELECT to_nanoseconds(1m + 1s)`, "61000000000", "BIGINT"}, + {"date_add amount", `SELECT date_add('second', 2 * 30, now())`, "2026-10-31 12:01:00.000000000", "TIMESTAMP"}, + { + "date_add column amount", + `SELECT date_add('minute', length('abc') + 1, now())`, + "2026-10-31 12:04:00.000000000", + "TIMESTAMP", + }, + { + "date_add interval ratio", + `SELECT date_add('second', to_milliseconds(1h + 30m) / 1000, now())`, + "2026-10-31 13:30:00.000000000", + "TIMESTAMP", + }, + {"year month add", `SELECT 1year + 2month`, "1-2", "INTERVAL_YEAR_TO_MONTH"}, + {"year month mul", `SELECT 1year * 2`, "2-0", "INTERVAL_YEAR_TO_MONTH"}, + {"months literal", `SELECT 12month`, "1-0", "INTERVAL_YEAR_TO_MONTH"}, + {"eight months", `SELECT 8month`, "0-8", "INTERVAL_YEAR_TO_MONTH"}, + {"year literal", `SELECT 1year`, "1-0", "INTERVAL_YEAR_TO_MONTH"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rows, types := runFn(t, tt.query) + require.Len(t, rows, 1) + assert.Equal(t, tt.want, rows[0][0]) + assert.Equal(t, tt.typ, types[0]) + }) + } +} + +func TestQuery_IntervalArithmeticErrors(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + }{ + {"divide by zero", `SELECT 1h / 0`, "Division by zero"}, + {"mul overflow", `SELECT 100000000d * 100000000`, "out of range"}, + {"add overflow", `SELECT 70000d + 70000d`, "overflow"}, + {"day and year month", `SELECT 1h + 1year`, "TYPE_MISMATCH"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + err := runFnErr(t, tt.query) + require.Error(t, err) + assert.Contains(t, err.Error(), tt.want) + }) + } +} + +func TestQuery_GuardedConstantsAreNotEvaluatedEarly(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + }{ + {"and guard", `SELECT count(*) FROM db.t WHERE host = 'zzz' AND 1/0 > 1`, "0"}, + {"and false literal", `SELECT count(*) FROM db.t WHERE false AND 1/0 > 1`, "0"}, + {"and cast guard", `SELECT count(*) FROM db.t WHERE host = 'zzz' AND CAST('x' AS bigint) > 1`, "0"}, + {"and overflow guard", `SELECT count(*) FROM db.t WHERE host = 'zzz' AND 9223372036854775807 + 1 > 1`, "0"}, + {"and mod guard", `SELECT count(*) FROM db.t WHERE host = 'zzz' AND mod(1, 0) > 1`, "0"}, + {"and abs guard", `SELECT count(*) FROM db.t WHERE host = 'zzz' AND abs(-9223372036854775807 - 1) > 1`, "0"}, + {"case false", `SELECT CASE WHEN false THEN 1/0 ELSE 0 END`, "0"}, + {"case row guard", `SELECT CASE WHEN host = 'zzz' THEN 1/0 ELSE 5 END FROM db.t LIMIT 1`, "5"}, + {"case cast guard", `SELECT CASE WHEN false THEN CAST('x' AS bigint) ELSE 0 END`, "0"}, + {"coalesce guard", `SELECT coalesce(1, 1/0)`, "1"}, + {"if guard", `SELECT if(false, 1/0, 3)`, "3"}, + {"try guard", `SELECT try(1/0)`, ""}, + {"nested case", `SELECT CASE WHEN 1 = 2 THEN 1/0 WHEN 2 = 2 THEN 7 ELSE 1/0 END`, "7"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + rows, _ := runFn(t, tt.query) + require.NotEmpty(t, rows) + assert.Equal(t, tt.want, rows[0][0]) + }) + } +} + +func TestQuery_ReachedConstantsStillRaise(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + query string + want string + }{ + {"select list", `SELECT 1/0`, "Division by zero"}, + {"or reaches", `SELECT count(*) FROM db.t WHERE host = 'a' OR 1/0 > 1`, "Division by zero"}, + {"where reaches", `SELECT count(*) FROM db.t WHERE 1/0 > 1`, "Division by zero"}, + {"and reaches", `SELECT count(*) FROM db.t WHERE host = 'a' AND 1/0 > 1`, "Division by zero"}, + {"cast reaches", `SELECT CAST('x' AS bigint)`, "Cannot cast 'x' to BIGINT"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + err := runFnErr(t, tt.query) + require.Error(t, err) + assert.Contains(t, err.Error(), tt.want) + }) + } +} diff --git a/services/timestreamquery/ts_values.go b/services/timestreamquery/ts_values.go new file mode 100644 index 0000000000..56c4798b10 --- /dev/null +++ b/services/timestreamquery/ts_values.go @@ -0,0 +1,249 @@ +package timestreamquery + +import ( + "strconv" + "strings" +) + +func endsValues(t token) bool { + if t.kind == tkEOF { + return true + } + + if t.kind != tkIdent { + return false + } + + switch strings.ToLower(t.text) { + case "from", "order", kwLimit, "offset", "union", "intersect", "except", "fetch", kwWhere, "group", kwHaving, "as": + return true + } + + return false +} + +// normalizeQuery strips comments and the trailing semicolon, then rewrites bare VALUES rows. +func normalizeQuery(q string) string { + q = strings.TrimSpace(strings.TrimRight(strings.TrimSpace(stripSQLComments(q)), ";")) + + return rewriteQuantified(rewriteFunctionSyntax(normalizeValues(q))) +} + +// normalizeValues rewrites `VALUES 1, 2` to `VALUES (1), (2)` and `VALUES ((a, b))` to `VALUES (a, b)`. +func normalizeValues(q string) string { + if !strings.Contains(strings.ToLower(q), "values") { + return q + } + + toks, err := tokenizeSQL(q) + if err != nil { + return q + } + + var ( + sb strings.Builder + cur int + ) + + for i := 0; i < len(toks); i++ { + if !toks[i].is("values") { + continue + } + + end, items := valuesItems(q, toks, i+1) + if len(items) == 0 { + continue + } + + sb.WriteString(q[cur:toks[i].end]) + sb.WriteString(" ") + sb.WriteString(strings.Join(items, ", ")) + + cur = end + i = skipTokensTo(toks, i, end) + } + + sb.WriteString(q[cur:]) + + return sb.String() +} + +func skipTokensTo(toks []token, from, end int) int { + i := from + + for i+1 < len(toks) && toks[i+1].start < end { + i++ + } + + return i +} + +// valuesItems splits the row list that starts at toks[from]; end is the offset just past the last row. +func valuesItems(q string, toks []token, from int) (int, []string) { + var ( + items []string + depth int + start = -1 + end = -1 + ) + + flush := func(stop int) { + if start >= 0 && stop > start { + items = append(items, normalizeValuesRow(strings.TrimSpace(q[start:stop]))) + } + + start = -1 + } + + for i := from; i < len(toks); i++ { + t := toks[i] + + if depth == 0 && endsValues(t) { + flush(toks[i].start) + + return finishValues(q, items, toks[i].start, end) + } + + switch { + case t.isOp("("): + depth++ + case t.isOp(")"): + depth-- + if depth < 0 { + flush(t.start) + + return finishValues(q, items, t.start, end) + } + case t.isOp(",") && depth == 0: + flush(t.start) + + continue + } + + if start < 0 { + start = t.start + } + + end = t.end + } + + return len(q), nil +} + +func finishValues(q string, items []string, stop, end int) (int, []string) { + if len(items) == 0 { + return len(q), nil + } + + if end < 0 || end > stop { + end = stop + } + + return end, items +} + +func normalizeValuesRow(item string) string { + if group, ok := parenGroup(item); ok { + if inner, isGroup := parenGroup(strings.TrimSpace(group)); isGroup && hasTopComma(inner) { + return "(" + inner + ")" + } + + return item + } + + return "(" + item + ")" +} + +// parenGroup returns the text inside s when s is exactly one parenthesised group. +func parenGroup(s string) (string, bool) { + if len(s) < argsTwo || s[0] != '(' || closeParen(s, 0) != len(s)-1 { + return "", false + } + + return s[1 : len(s)-1], true +} + +func hasTopComma(s string) bool { return len(splitTop(s)) > 1 } + +// rewriteValuesAliases turns `(VALUES ...) AS t(a, b)` into a SELECT that names the columns SQLite numbers itself. +func rewriteValuesAliases(q string) string { + if !strings.Contains(strings.ToLower(q), "values") { + return q + } + + toks, err := tokenizeSQL(q) + if err != nil { + return q + } + + var ( + sb strings.Builder + cur int + ) + + for i := 1; i+1 < len(toks); i++ { + if !toks[i].is("values") || !toks[i-1].isOp("(") || toks[i-1].start < cur { + continue + } + + closeAt := closeParen(q, toks[i-1].start) + if closeAt < 0 { + continue + } + + alias, names, end := valuesAlias(q, toks, closeAt) + if alias == "" { + continue + } + + cols := make([]string, len(names)) + for k, n := range names { + cols[k] = "column" + strconv.Itoa(k+1) + " AS " + n + } + + sb.WriteString(q[cur:toks[i-1].start]) + sb.WriteString( + "(SELECT " + strings.Join(cols, ", ") + " FROM " + q[toks[i-1].start:closeAt+1] + ") AS " + alias, + ) + + cur = end + } + + sb.WriteString(q[cur:]) + + return sb.String() +} + +// valuesAlias reads `[AS] name (c1, c2)` following the parenthesis at closeAt. +func valuesAlias(q string, toks []token, closeAt int) (string, []string, int) { + k := 0 + for k < len(toks) && toks[k].start <= closeAt { + k++ + } + + if k < len(toks) && toks[k].is("as") { + k++ + } + + if k+1 >= len(toks) || (toks[k].kind != tkIdent && toks[k].kind != tkQuoted) || !toks[k+1].isOp("(") { + return "", nil, 0 + } + + alias := q[toks[k].start:toks[k].end] + + var names []string + + for j := k + argsTwo; j < len(toks); j++ { + switch { + case toks[j].isOp(")"): + return alias, names, toks[j].end + case toks[j].isOp(","): + case toks[j].kind == tkIdent || toks[j].kind == tkQuoted: + names = append(names, q[toks[j].start:toks[j].end]) + default: + return "", nil, 0 + } + } + + return "", nil, 0 +} diff --git a/services/timestreamquery/unload.go b/services/timestreamquery/unload.go index 6c8029b683..d4e1009b17 100644 --- a/services/timestreamquery/unload.go +++ b/services/timestreamquery/unload.go @@ -212,9 +212,9 @@ func (o *unloadOptions) setString(name, s string) error { o.kmsKey = s case "include_header": switch strings.ToLower(s) { - case "true": + case kwTrue: o.includeHeader = true - case "false": + case kwFalse: o.includeHeader = false default: return unloadErr("option 'include_header' must be 'true' or 'false'") From 2531a286bab0724f55cdf536fe4e3d5812b810df Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 22:02:06 -0600 Subject: [PATCH 2/8] fix: SQL engines register their functions at init under their own prefix; Timestream sequence and interval edge cases The SQLite driver iterates its function table without a lock when a connection opens, so one engine registering lazily while another opened a connection could end the process with a concurrent map fault. Athena, BigQuery and Timestream now register during package init. Timestream's remaining plain-named functions move under its prefix and calls are qualified before execution; a guard and a cross-engine test keep every engine's names apart. Zero-argument sequence and integral calls hung, extreme sequence bounds ran away, a negated year-month interval was zero and log10 was off by one ulp at exact powers of ten. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/athena/engine_funcs.go | 6 +- services/gcpbigquery/bqsql/udf.go | 3 + services/timestreamquery/PARITY.md | 5 +- services/timestreamquery/ts_aggs_set.go | 2 +- services/timestreamquery/ts_arith.go | 14 +- services/timestreamquery/ts_duration.go | 10 + services/timestreamquery/ts_engine.go | 2 +- services/timestreamquery/ts_funcs.go | 27 +- services/timestreamquery/ts_funcs_names.go | 73 +++ .../ts_funcs_names_internal_test.go | 87 +++ .../ts_funcs_robust_internal_test.go | 113 ++++ .../ts_function_edge_internal_test.go | 99 ++++ services/timestreamquery/ts_infer_checked.go | 2 +- .../ts_infer_robust_internal_test.go | 4 + services/timestreamquery/ts_render.go | 9 + services/timestreamquery/ts_series.go | 30 +- ...yntax_rewrite_adversarial_internal_test.go | 71 +++ test/crossengine/function_namespace_test.go | 189 +++++++ .../sqlite_function_namespace_guard_test.go | 518 ++++++++++++++++++ 19 files changed, 1242 insertions(+), 22 deletions(-) create mode 100644 services/timestreamquery/ts_funcs_names.go create mode 100644 services/timestreamquery/ts_funcs_names_internal_test.go create mode 100644 services/timestreamquery/ts_funcs_robust_internal_test.go create mode 100644 services/timestreamquery/ts_function_edge_internal_test.go create mode 100644 services/timestreamquery/ts_syntax_rewrite_adversarial_internal_test.go create mode 100644 test/crossengine/function_namespace_test.go create mode 100644 test/guards/sqlite_function_namespace_guard_test.go diff --git a/services/athena/engine_funcs.go b/services/athena/engine_funcs.go index 31ff74c411..02f9370414 100644 --- a/services/athena/engine_funcs.go +++ b/services/athena/engine_funcs.go @@ -29,8 +29,10 @@ var errBadUnit = errors.New("invalid unit") func sqlNull() driver.Value { return nil } -// registerEngineFuncs installs the athena_* scalar functions the SQL -// translator targets; the driver registry is process-wide. +//nolint:gochecknoinits // the driver reads its registry unlocked on Open; lazy registration crashes +func init() { registerEngineFuncs() } + +// registerEngineFuncs installs the athena_* scalar functions the SQL translator targets. func registerEngineFuncs() { registerFuncsOnce.Do(func() { reg := registerScalar diff --git a/services/gcpbigquery/bqsql/udf.go b/services/gcpbigquery/bqsql/udf.go index 99c4f918d6..a2944456df 100644 --- a/services/gcpbigquery/bqsql/udf.go +++ b/services/gcpbigquery/bqsql/udf.go @@ -36,6 +36,9 @@ func errBQ(format string, args ...any) error { return fmt.Errorf("%w: %s", errBQBase, fmt.Sprintf(format, args...)) } +//nolint:gochecknoinits // the driver reads its registry unlocked on Open; lazy registration crashes +func init() { registerUDFs() } + func registerUDFs() { registerOnce.Do(func() { defs := map[string]udfDef{} diff --git a/services/timestreamquery/PARITY.md b/services/timestreamquery/PARITY.md index 137327e89d..3f87e73c2a 100644 --- a/services/timestreamquery/PARITY.md +++ b/services/timestreamquery/PARITY.md @@ -44,6 +44,8 @@ items_still_open: - "Checked arithmetic and casts: the error type (ValidationException) and message wording (\"bigint addition overflow: A + B\", \"Division by zero\", \"Cannot cast 'x' to BIGINT\", \"Out of range for integer: N\", \"Value cannot be cast to timestamp: x\") follow the Presto/Trino family from memory; no Timestream page quotes them. CAST(double AS bigint) rounds half away from zero on the same basis. try() maps a failure anywhere inside its argument to NULL for the failing operation, which differs from the family only when a NULL changes a surrounding coalesce or CASE" - "Documented functions: every function on the Timestream mathematical, string, array, bitwise, regular expression, date/time, aggregate, window, conditional, comparison and time series pages is implemented except one example: parse_datetime with a zone-abbreviation pattern (date-time-functions.html: parse_datetime('2019-12-29 10:10 PST', 'uuuu-LL-dd HH:mm z') returns 2019-12-29 18:10:00.000000000) fails with 'Invalid format' because the base engine's parser has no zone abbreviations. max(x, n), min(x, n) and approx_percentile(x, ARRAY[...]) are not usable as window functions (they raise a clear error); the aggregates added in the reference function pass are. Argument bounds and error wording come from the engine family, not a Timestream page, for: max(x, n)/min(x, n) n 1-10000, max_by/min_by(x, y, n) n 1-10000 ('third argument of max_by must be a positive integer'), approx_percentile percentage range 0-1 and weight/accuracy checks, approx_distinct(x, e) with e in [0.0040625, 0.26] (the e range itself is on aggregate-functions.html), repeat count 0-10000, zip of 2 to 5 arrays, from_base/to_base radix 2-36, strpos/strrpos with overlapping matches and 'instance' must be a positive number, strpos/strrpos(x, '') = 1, skewness and the regr_* functions returning NULL for fewer than 3 rows or no variance in x, replace(x, '', y) inserting y between characters" - "NaN has no SQLite representation (a NaN stored in a REAL column becomes NULL), so a NaN DOUBLE is the text 'NaN' only where it is rendered (a top-level select item with no CTE), under a CAST to anything but DOUBLE, as the argument of is_nan/is_finite/is_infinite, or as an operand of DOUBLE arithmetic or comparison that is itself rewritten (an operand subtree containing nan(), infinity(), a division, a modulo, a CAST/typed literal to DOUBLE, or sqrt/ln/log10/log2/acos/asin/acosh/atanh/power/pow); there nan(), CAST('NaN' AS double), 0e0/0e0, sqrt(-1), ln(-1), infinity() - infinity() and nan() + 1 give NaN, ln(0) gives -Infinity, nan() = nan() is false and nan() <> nan() is true. Everywhere else a NaN is NULL: a NaN passed through a subquery or CTE column, ORDER BY, GROUP BY, DISTINCT, an aggregate (sum, min, max, avg over a NaN is not NaN), a window function, sign(), abs(), round() and similar numeric functions, or arithmetic whose operands the rewrite cannot see (a column holding a NaN, which the engine cannot store). NaN ordering (last, greatest) therefore does not hold. Infinity and -Infinity are real doubles and behave normally; a DOUBLE function rewritten for NaN is a Go function, not the native SQLite one, so its last digit can differ from SQLite's libm" + - "Unverified against the service: the argument bounds and error wording of the reference functions come from the Presto/Trino family because no Timestream page states them: repeat count 0..10000, max_by/min_by n 1..10000, sequence() at most 1,000,000 elements (the family caps at 10,000), zip 2..5 arrays, from_base/to_base radix 2..36, bit_count bits 2..64, approx_distinct error 0.0040625..0.26, lpad/rpad length at most 16,777,216" + - "INTERVAL YEAR TO MONTH arithmetic lives in the shared SQL engine (services/athena engine_interval.go) and does not range-check: `1year * 9223372036854775807` wraps instead of failing, and `TIMESTAMP + 9999999999999year` renders a year far beyond 9999" - "A checked arithmetic or cast rewrite that fails to translate or prepare (anything but a checked function rejecting a value) reruns the query without the checked rewrites, so such a query keeps the older semantics (overflow widens, division by zero is NULL, casts truncate) instead of failing" structural_gaps: @@ -134,8 +136,7 @@ string-functions.html (output types), mathematical-functions.html (e(), rand(), treat 1 and 1.0 as equal; shuffle is a uniform permutation; a negative interval renders as `-0 01:00:00.000000000`; interval * or / a double rounds to a whole nanosecond and interval / 0 is a ValidationException "Division by zero"; timestamp +/- a computed interval fails on int64 overflow; date_add/date_diff on TIME wrap around midnight and accept millisecond..hour only; quantified comparisons - (`x op ALL|ANY|SOME (subquery)`) follow SQL three-valued logic over a single-column subquery; position(x IN y) is strpos(y, x); the - sequence() size cap stays at the existing 1,000,000 elements because no Timestream page states a limit (the family caps at 10,000). + (`x op ALL|ANY|SOME (subquery)`) follow SQL three-valued logic over a single-column subquery; position(x IN y) is strpos(y, x). - Time bounds come from comparisons, BETWEEN and AND of constants built from now(), ago(), bin(), literals and interval arithmetic; a side the WHERE clause leaves open is the table's earliest queryable record (lower) or the query clock (upper), because the pages give only the 365-day example without saying how an open side is measured. A table with no queryable records and an open lower side reports 0. diff --git a/services/timestreamquery/ts_aggs_set.go b/services/timestreamquery/ts_aggs_set.go index 50d446470c..800af5fe89 100644 --- a/services/timestreamquery/ts_aggs_set.go +++ b/services/timestreamquery/ts_aggs_set.go @@ -81,7 +81,7 @@ func (a *bufferedAgg) WindowValue(*fnCtx) (driver.Value, error) { return a.finis func (*bufferedAgg) Final(*fnCtx) {} func registerBuffered(name string, nargs int32, check func(aggRow) error, finish func([]aggRow) (driver.Value, error)) { - sqlitedriver.MustRegisterFunction(name, &sqlitedriver.FunctionImpl{ + sqlitedriver.MustRegisterFunction(engineFunc(name), &sqlitedriver.FunctionImpl{ NArgs: nargs, Deterministic: true, MakeAggregate: func(_ fnCtx) (sqlitedriver.AggregateFunction, error) { return &bufferedAgg{finish: finish, check: check}, nil diff --git a/services/timestreamquery/ts_arith.go b/services/timestreamquery/ts_arith.go index f8ea0b3806..e871e9d542 100644 --- a/services/timestreamquery/ts_arith.go +++ b/services/timestreamquery/ts_arith.go @@ -326,9 +326,21 @@ func floatCompare(test func(a, b float64) bool) scalarImpl { } } +// log10 is math.Log10 made exact at powers of ten, where Go's log2-based form is off by an ulp (log10(0.1)). +func log10(x float64) float64 { + r := math.Log10(x) + n := math.Round(r) + + if r != n && math.Abs(r-n) < 1e-9 && math.Pow10(int(n)) == x { + return n + } + + return r +} + func domainMathFuncs() []scalarFunc { unary := map[string]func(float64) float64{ - "sqrt": math.Sqrt, "ln": math.Log, "log10": math.Log10, "log2": math.Log2, "acos": math.Acos, + "sqrt": math.Sqrt, "ln": math.Log, "log10": log10, "log2": math.Log2, "acos": math.Acos, "asin": math.Asin, "acosh": math.Acosh, "atanh": math.Atanh, } diff --git a/services/timestreamquery/ts_duration.go b/services/timestreamquery/ts_duration.go index 67ed68ead7..b8e3cd6d68 100644 --- a/services/timestreamquery/ts_duration.go +++ b/services/timestreamquery/ts_duration.go @@ -135,6 +135,16 @@ func udfIntervalNegate(_ *fnCtx, args []driver.Value) (driver.Value, error) { return nil, nil //nolint:nilnil // SQL NULL } + if b, isBlob := args[0].([]byte); isBlob { + if kind, months, isIv := decodeIntervalBlob(b); isIv && kind == 'Y' { + if months == math.MinInt64 { + return nil, evalError("interval year to month negation overflow") + } + + return encodeIntervalBlob(kind, -months), nil + } + } + n, ok := intervalNanos(args[0]) if !ok { return nil, errOperandType diff --git a/services/timestreamquery/ts_engine.go b/services/timestreamquery/ts_engine.go index 63ebef76d8..4da7b5e664 100644 --- a/services/timestreamquery/ts_engine.go +++ b/services/timestreamquery/ts_engine.go @@ -270,7 +270,7 @@ func runTranslated(ctx context.Context, q string, set loadedSet, ann annotation) } } - rows, err := conn.QueryContext(ctx, q) + rows, err := conn.QueryContext(ctx, qualifyEngineFuncs(q)) if err != nil { return nil, mapEngineError(err) } diff --git a/services/timestreamquery/ts_funcs.go b/services/timestreamquery/ts_funcs.go index b0881c3c80..a1df42a16b 100644 --- a/services/timestreamquery/ts_funcs.go +++ b/services/timestreamquery/ts_funcs.go @@ -3,6 +3,7 @@ package timestreamquery import ( "database/sql/driver" "errors" + "math" "slices" "sync" "time" @@ -166,12 +167,12 @@ func raisingFn(name string, nargs int32, impl scalarImpl) scalarFunc { func registerScalar(f scalarFunc) { if f.volatile { - sqlitedriver.MustRegisterScalarFunction(f.name, f.nargs, f.impl) + sqlitedriver.MustRegisterScalarFunction(engineFunc(f.name), f.nargs, f.impl) return } - sqlitedriver.MustRegisterDeterministicScalarFunction(f.name, f.nargs, f.impl) + sqlitedriver.MustRegisterDeterministicScalarFunction(engineFunc(f.name), f.nargs, f.impl) } // tsScalarFuncs lists the scalar functions this package registers with the engine. @@ -200,18 +201,18 @@ func tsScalarFuncs() []scalarFunc { scalarFn("interpolate_fill", argsThree, udfInterpolateFill), scalarFn("derivative_linear", argsTwo, udfDerivative(false)), scalarFn("non_negative_derivative_linear", argsTwo, udfDerivative(true)), - raisingFn("integral_trapezoidal", -1, udfIntegral), + raisingFn("integral_trapezoidal", -1, withArgRange(1, argsTwo, udfIntegral)), scalarFn("correlate_pearson", argsTwo, udfCorrelate(false)), scalarFn("correlate_spearman", argsTwo, udfCorrelate(true)), - scalarFn("sequence", -1, udfSequence), + scalarFn("sequence", -1, withArgRange(argsTwo, argsThree, udfSequence)), scalarFn("ts_series_json", 1, udfSeriesJSON), }, tsTextFuncs(), tsArrayFuncs(), clockFuncs()) } -// withMaxArgs guards a variadic registration against calls with fewer than two or more than hi arguments. -func withMaxArgs(hi int, impl scalarImpl) scalarImpl { +// withArgRange guards a variadic registration against calls with fewer than lo or more than hi arguments. +func withArgRange(lo, hi int, impl scalarImpl) scalarImpl { return func(c *fnCtx, args []driver.Value) (driver.Value, error) { - if len(args) < argsTwo || len(args) > hi { + if len(args) < lo || len(args) > hi { return nil, evalError("wrong number of arguments") } @@ -219,6 +220,9 @@ func withMaxArgs(hi int, impl scalarImpl) scalarImpl { } } +// withMaxArgs guards a variadic registration against calls with fewer than two or more than hi arguments. +func withMaxArgs(hi int, impl scalarImpl) scalarImpl { return withArgRange(argsTwo, hi, impl) } + func tsTextFuncs() []scalarFunc { return []scalarFunc{ raisingFn("from_base", argsTwo, udfFromBase), @@ -245,7 +249,7 @@ func tsArrayFuncs() []scalarFunc { raisingFn("ts_reverse_array", 1, udfReverseArray), raisingFn("ts_regexp_groups", argsTwo, udfRegexpGroups), raisingFn("ts_regexp_splice", argsThree, udfRegexpSplice), - raisingFn("ts_concat_array", -1, udfConcatArrays), + raisingFn("ts_concat_array", -1, withArgRange(1, math.MaxInt, udfConcatArrays)), } } @@ -265,19 +269,22 @@ func udfTimestampDiff(_ *sqlitedriver.FunctionContext, args []driver.Value) (dri return formatInterval(a.Sub(b).Nanoseconds()), nil } +//nolint:gochecknoinits // the driver reads its registry unlocked on Open; lazy registration crashes +func init() { registerTimestreamFuncs() } + func registerTimestreamFuncs() { registerFuncsOnce.Do(func() { registerUnnestModule() registerArithFuncs() registerCastFuncs() registerSetAggs() - sqlitedriver.MustRegisterScalarFunction("shuffle", 1, udfShuffle) + sqlitedriver.MustRegisterScalarFunction(engineFunc("shuffle"), 1, udfShuffle) for _, f := range tsScalarFuncs() { registerScalar(f) } - sqlitedriver.MustRegisterFunction("create_time_series", &sqlitedriver.FunctionImpl{ + sqlitedriver.MustRegisterFunction(engineFunc("create_time_series"), &sqlitedriver.FunctionImpl{ NArgs: argsTwo, MakeAggregate: func(_ fnCtx) (sqlitedriver.AggregateFunction, error) { return &seriesAgg{}, nil diff --git a/services/timestreamquery/ts_funcs_names.go b/services/timestreamquery/ts_funcs_names.go new file mode 100644 index 0000000000..96ce0c88df --- /dev/null +++ b/services/timestreamquery/ts_funcs_names.go @@ -0,0 +1,73 @@ +package timestreamquery + +import "strings" + +// funcPrefix namespaces every SQLite function this package registers: the driver registry is process-wide and +// shared with every other engine, so a plain name would be callable (or shadow a built-in) everywhere. +const funcPrefix = "ts_" + +// plainFuncs holds the documented Timestream names registered under funcPrefix; written only during registration. +// +//nolint:gochecknoglobals // filled once at init, read-only afterwards +var plainFuncs = map[string]struct{}{} + +// engineFunc returns the registered SQLite name for a Timestream function and records the plain name. +func engineFunc(name string) string { + if strings.HasPrefix(name, funcPrefix) { + return name + } + + plainFuncs[name] = struct{}{} + + return funcPrefix + name +} + +// qualifyEngineFuncs renames calls to Timestream-only functions in engine SQL to their prefixed registrations, +// leaving string literals, quoted identifiers, comments and member access alone. +func qualifyEngineFuncs(q string) string { + var b strings.Builder + + for i := 0; i < len(q); { + switch c := q[i]; { + case c == '\'' || c == '"' || c == '`': + j := closingQuote(q, i) + b.WriteString(q[i:j]) + i = j + case skipComment(q, i) != i: + j := skipComment(q, i) + b.WriteString(q[i:j]) + i = j + case isIdentStart(c): + j := i + 1 + for j < len(q) && isIdentPart(q[j]) { + j++ + } + + word := q[i:j] + if _, ok := plainFuncs[strings.ToLower(word)]; ok && calledAt(q, i, j) { + b.WriteString(funcPrefix) + } + + b.WriteString(word) + i = j + default: + b.WriteByte(c) + i++ + } + } + + return b.String() +} + +// calledAt reports whether q[start:end] is a bare function name: followed by "(" and not a member of something. +func calledAt(q string, start, end int) bool { + if start > 0 && q[start-1] == '.' { + return false + } + + for end < len(q) && isSpaceByte(q[end]) { + end++ + } + + return end < len(q) && q[end] == '(' +} diff --git a/services/timestreamquery/ts_funcs_names_internal_test.go b/services/timestreamquery/ts_funcs_names_internal_test.go new file mode 100644 index 0000000000..62c52a7066 --- /dev/null +++ b/services/timestreamquery/ts_funcs_names_internal_test.go @@ -0,0 +1,87 @@ +package timestreamquery + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/athena" +) + +func TestQualifyEngineFuncs(t *testing.T) { + t.Parallel() + + registerTimestreamFuncs() + + tests := []struct { + name string + in string + want string + }{ + {"plain call", `SELECT repeat(1, 2)`, `SELECT ts_repeat(1, 2)`}, + {"upper case", `SELECT REPEAT(1, 2)`, `SELECT ts_REPEAT(1, 2)`}, + {"space before paren", "SELECT zip\n (a, b)", "SELECT ts_zip\n (a, b)"}, + { + "nested", + `SELECT nan(), cardinality(shuffle(sequence(1, 3)))`, + `SELECT ts_nan(), cardinality(ts_shuffle(ts_sequence(1, 3)))`, + }, + {"string literal", `SELECT 'repeat(1, 2)'`, `SELECT 'repeat(1, 2)'`}, + {"escaped quote", `SELECT 'it''s zip(a)', zip(a)`, `SELECT 'it''s zip(a)', ts_zip(a)`}, + {"quoted identifier", `SELECT "repeat"(1) FROM t`, `SELECT "repeat"(1) FROM t`}, + {"column named like a function", `SELECT repeat, nan FROM t`, `SELECT repeat, nan FROM t`}, + {"member access", `SELECT t.repeat(1)`, `SELECT t.repeat(1)`}, + {"comment", "SELECT 1 -- zip(a)\n, repeat(1,2)", "SELECT 1 -- zip(a)\n, ts_repeat(1,2)"}, + {"block comment", `SELECT /* nan() */ nan()`, `SELECT /* nan() */ ts_nan()`}, + {"already prefixed", `SELECT ts_sum(x), athena_array(1)`, `SELECT ts_sum(x), athena_array(1)`}, + { + "longer identifier", + `SELECT repeat_x(1), xrepeat(1), repeat1(2)`, + `SELECT repeat_x(1), xrepeat(1), repeat1(2)`, + }, + { + "sqlite builtin", + `SELECT replace('a', 'b', 'c'), reverse('a'), abs(1)`, + `SELECT replace('a', 'b', 'c'), reverse('a'), abs(1)`, + }, + {"unterminated string", `SELECT 'repeat(`, `SELECT 'repeat(`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tt.want, qualifyEngineFuncs(tt.in)) + }) + } +} + +func TestEveryPlainFunctionIsRegisteredPrefixed(t *testing.T) { + t.Parallel() + + registerTimestreamFuncs() + require.NotEmpty(t, plainFuncs) + + registered := map[string]bool{} + for _, f := range registeredTimestreamFuncs(t) { + registered[f.name] = true + } + + for plain := range plainFuncs { + assert.True(t, registered[funcPrefix+plain], plain) + } + + db, err := athena.OpenEngineDB() + require.NoError(t, err) + + defer db.Close() + + for plain := range plainFuncs { + var n int + + require.NoError(t, db.QueryRowContext(t.Context(), + "SELECT count(*) FROM pragma_function_list WHERE name = ?", plain).Scan(&n)) + assert.Zero(t, n, "%s must not be callable unprefixed", plain) + } +} diff --git a/services/timestreamquery/ts_funcs_robust_internal_test.go b/services/timestreamquery/ts_funcs_robust_internal_test.go new file mode 100644 index 0000000000..00e4f3f6c6 --- /dev/null +++ b/services/timestreamquery/ts_funcs_robust_internal_test.go @@ -0,0 +1,113 @@ +package timestreamquery + +import ( + "fmt" + "math" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/athena" +) + +type registeredFunc struct { + name string + narg int + aggFn bool +} + +func registeredTimestreamFuncs(t *testing.T) []registeredFunc { + t.Helper() + + db, err := athena.OpenEngineDB() + require.NoError(t, err) + + defer db.Close() + + rows, err := db.QueryContext(t.Context(), + "SELECT name, narg, type FROM pragma_function_list WHERE builtin = 0 AND name LIKE 'ts\\_%' ESCAPE '\\'") + require.NoError(t, err) + + defer rows.Close() + + var out []registeredFunc + + for rows.Next() { + var ( + f registeredFunc + typ string + ) + + require.NoError(t, rows.Scan(&f.name, &f.narg, &typ)) + + f.aggFn = typ == "a" + out = append(out, f) + } + + require.NoError(t, rows.Err()) + + return out +} + +// Every registered function must reject hostile arguments with an error or NULL, never panic or run away. +func TestRegisteredFunctionsSurviveHostileArguments(t *testing.T) { + t.Parallel() + + funcs := registeredTimestreamFuncs(t) + require.Greater(t, len(funcs), 100) + + args := []struct { + val any + name string + }{ + {nil, "null"}, + {[]byte{0xF3, 'i', 'v', 0x1D, 'Y', 1, 2}, "blob"}, + {int64(math.MaxInt64), "huge int"}, + {int64(math.MinInt64), "min int"}, + {"NaN", "nan text"}, + {"", "empty text"}, + {strings.Repeat("ab", 1000), "long text"}, + {1e300, "float"}, + {`[1,2,3]`, "json"}, + } + + for _, f := range funcs { + arities := []int{f.narg} + if f.narg < 0 { + arities = []int{0, 1, 2, 3, 4} + } + + for _, n := range arities { + t.Run(fmt.Sprintf("%s/%d", f.name, n), func(t *testing.T) { + t.Parallel() + + db, err := athena.OpenEngineDB() + require.NoError(t, err) + + defer db.Close() + + marks := strings.TrimSuffix(strings.Repeat("?,", n), ",") + q := fmt.Sprintf("SELECT %s(%s)", f.name, marks) + + for _, a := range args { + params := make([]any, n) + for i := range params { + params[i] = a.val + } + + start := time.Now() + + assert.NotPanics(t, func() { + var v any + + _ = db.QueryRowContext(t.Context(), q, params...).Scan(&v) + }, a.name) + assert.Less(t, time.Since(start), 5*time.Second, a.name) + } + }) + } + } +} diff --git a/services/timestreamquery/ts_function_edge_internal_test.go b/services/timestreamquery/ts_function_edge_internal_test.go new file mode 100644 index 0000000000..bae91fee4d --- /dev/null +++ b/services/timestreamquery/ts_function_edge_internal_test.go @@ -0,0 +1,99 @@ +package timestreamquery + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func scalarOf(t *testing.T, expr string) (string, error) { + t.Helper() + + b := NewInMemoryBackend("000000000000", "us-east-1") + + pg, err := b.QueryWithOptions(t.Context(), QueryOptions{QueryString: "SELECT " + expr}) + if err != nil { + return "", err + } + + require.Len(t, pg.Rows, 1) + + return datumText(pg.Rows[0].Data[0]), nil +} + +func datumText(d Datum) string { + switch { + case d.ScalarValue != nil: + return *d.ScalarValue + case d.NullValue != nil: + return "NULL" + } + + parts := make([]string, len(d.ArrayValue)) + for i, e := range d.ArrayValue { + parts[i] = datumText(e) + } + + return "[" + strings.Join(parts, ",") + "]" +} + +func TestFunctionEdgeCases(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + expr string + want string + wantErr string + }{ + {name: "negate year", expr: "-1year", want: "-1-0"}, + {name: "negate month sum", expr: "-1month + 3month", want: "0-2"}, + {name: "negate month operand", expr: "5month - -1year", want: "1-5"}, + { + name: "negate month shift", + expr: "TIMESTAMP '2024-03-31 00:00:00' + -1month", + want: "2024-02-29 00:00:00.000000000", + }, + {name: "negate interval keyword", expr: "-INTERVAL '2' YEAR", want: "-2-0"}, + {name: "log10 tenth", expr: "log10(0.1)", want: "-1.0"}, + {name: "log10 1e15", expr: "log10(1e15)", want: "15.0"}, + {name: "log10 1e-4", expr: "log10(0.0001)", want: "-4.0"}, + {name: "log10 non power", expr: "log10(2.0)", want: "0.3010299956639812"}, + { + name: "sequence full int range", + expr: "sequence(-9223372036854775807-1, 9223372036854775807)", + wantErr: "invalid sequence bounds", + }, + { + name: "sequence ends at max", + expr: "sequence(9223372036854775806, 9223372036854775807)", + want: "[9223372036854775806,9223372036854775807]", + }, + {name: "sequence step overflow", expr: "sequence(9223372036854775807, 9223372036854775800, -3)", + want: "[9223372036854775807,9223372036854775804,9223372036854775801]"}, + {name: "sequence step away", expr: "sequence(1, 5, -1)", want: "[]"}, + {name: "sequence no args", expr: "sequence()", wantErr: "wrong number of arguments"}, + {name: "sequence one arg", expr: "sequence(1)", wantErr: "wrong number of arguments"}, + {name: "integral no args", expr: "integral_trapezoidal()", wantErr: "wrong number of arguments"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got, err := scalarOf(t, tt.expr) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + + return + } + + require.NoError(t, err) + + assert.Equal(t, tt.want, got) + }) + } +} diff --git a/services/timestreamquery/ts_infer_checked.go b/services/timestreamquery/ts_infer_checked.go index 833f03efa8..93266447b9 100644 --- a/services/timestreamquery/ts_infer_checked.go +++ b/services/timestreamquery/ts_infer_checked.go @@ -283,7 +283,7 @@ func (inf *inferrer) rewriteIntervalArith(n *node, a, b tsType) { } func (inf *inferrer) rewriteNegate(n *node, arg tsType) { - if n.name == "-" && isIntervalDS(arg) { + if n.name == "-" && (isIntervalDS(arg) || arg.kind == tyIntervalYM) { inf.edit("ts_ivneg(", n.start, n.start+1) inf.closeEdit(")", n.end) diff --git a/services/timestreamquery/ts_infer_robust_internal_test.go b/services/timestreamquery/ts_infer_robust_internal_test.go index c46726cf55..6701ab88a5 100644 --- a/services/timestreamquery/ts_infer_robust_internal_test.go +++ b/services/timestreamquery/ts_infer_robust_internal_test.go @@ -120,6 +120,10 @@ func FuzzAnnotateQuery(f *testing.F) { "SELECT nan() + 1, infinity() - infinity(), sqrt(-1) < 1, ln(0), is_nan(nan()), CAST('NaN' AS double) = nan()", "SELECT 1 < ALL (VALUES 2, 3), a = ANY (SELECT b FROM t), position('a' IN b), extract(DOW FROM t), hour(TIME '1:2')", "SELECT reverse(ARRAY[1]), concat(ARRAY[1], ARRAY[2]), replace('a', 'b'), strpos('a', 'a', 1)", + "SELECT 'position(a IN b)', \"position\", position FROM t WHERE \"all\" = 1 AND 'x IN y' <> ''", + "SELECT a FROM t WHERE a NOT IN (VALUES 1, 2) AND b = ANY (SELECT c FROM u) AND d < ALL (ARRAY[1])", + "SELECT position(position('a' IN b) IN c), extract(DOW FROM extract(DOY FROM t))", + "SELECT -1year, -(1month + 1year), 5month - -1year, sequence(1, 9223372036854775807)", } { f.Add(s) } diff --git a/services/timestreamquery/ts_render.go b/services/timestreamquery/ts_render.go index 74387d1dbf..45a29b189a 100644 --- a/services/timestreamquery/ts_render.go +++ b/services/timestreamquery/ts_render.go @@ -77,6 +77,15 @@ func decodeIntervalBlob(b []byte) (byte, int64, bool) { return b[ivKindOffset], int64(raw), true //nolint:gosec // offset-binary payload, wrap-around intended } +func encodeIntervalBlob(kind byte, n int64) []byte { + out := make([]byte, ivBlobLen) + copy(out, ivBlobMagic()) + out[ivKindOffset] = kind + binary.BigEndian.PutUint64(out[ivKindOffset+1:], uint64(n)^ivSignFlip) //nolint:gosec // offset-binary payload + + return out +} + func renderIntervalBlob(kind byte, n int64) Datum { if kind == 'Y' { return ScalarDatum(fmt.Sprintf("%d-%d", n/monthsPerYear, n%monthsPerYear)) diff --git a/services/timestreamquery/ts_series.go b/services/timestreamquery/ts_series.go index 8e9bb163af..b446313ecc 100644 --- a/services/timestreamquery/ts_series.go +++ b/services/timestreamquery/ts_series.go @@ -662,13 +662,18 @@ func sequenceOfInts(args []driver.Value) (driver.Value, error) { } } - if !ok1 || !ok2 || step == 0 || (hi-lo)/step >= maxSeqLen { + if !ok1 || !ok2 || step == 0 { return nil, errBadSeq } - var vals []int64 - for v := lo; (step > 0 && v <= hi) || (step < 0 && v >= hi); v += step { - vals = append(vals, v) + count, ok := sequenceLen(lo, hi, step) + if !ok { + return nil, errBadSeq + } + + vals := make([]int64, 0, count) + for i := range count { + vals = append(vals, lo+int64(i)*step) } b, _ := json.Marshal(vals, jsonx.V1()) @@ -676,6 +681,23 @@ func sequenceOfInts(args []driver.Value) (driver.Value, error) { return arrayMark + string(b), nil } +// sequenceLen is the element count from lo toward hi, computed in uint64 so the span cannot overflow; +// ok=false when it would reach maxSeqLen. A step pointing away from hi yields no elements. +func sequenceLen(lo, hi, step int64) (uint64, bool) { + if (step > 0 && lo > hi) || (step < 0 && lo < hi) { + return 0, true + } + + span, width := uint64(hi)-uint64(lo), uint64(step) //nolint:gosec // two's-complement distance and magnitude + if step < 0 { + span, width = uint64(lo)-uint64(hi), -uint64(step) //nolint:gosec // two's-complement distance and magnitude + } + + n := span / width + + return n + 1, n < maxSeqLen +} + func sequenceTimes(start, stop time.Time, stepNs int64) (driver.Value, error) { step := time.Duration(stepNs) if int64(stop.Sub(start)/step) >= maxSeqLen { diff --git a/services/timestreamquery/ts_syntax_rewrite_adversarial_internal_test.go b/services/timestreamquery/ts_syntax_rewrite_adversarial_internal_test.go new file mode 100644 index 0000000000..ba52c00990 --- /dev/null +++ b/services/timestreamquery/ts_syntax_rewrite_adversarial_internal_test.go @@ -0,0 +1,71 @@ +package timestreamquery + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNormalizeQueryLeavesLookalikesAlone(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + q string + }{ + {"position in string", `SELECT 'position(a IN b)'`}, + {"extract in string", `SELECT 'extract(dow FROM t)'`}, + {"in keyword string", `SELECT 'x IN y'`}, + {"quantifier in string", `SELECT 'a = ANY (SELECT 1)'`}, + {"values in string", `SELECT 'VALUES 1, 2'`}, + {"values quoted identifier", `SELECT "values", "all", "position" FROM t`}, + {"column named position", `SELECT position FROM t WHERE position > 1`}, + {"column named all", `SELECT "all" FROM t WHERE "any" = 1`}, + {"column named values", `SELECT values FROM t`}, + {"regexp lambda in string", `SELECT 'regexp_replace(a, b, x -> x)'`}, + {"escaped quote", `SELECT 'it''s position(a IN b)'`}, + {"position one arg", `SELECT position(a) FROM t`}, + {"extract plain field", `SELECT extract(year FROM time) FROM t`}, + {"in list", `SELECT a IN (1, 2) FROM t`}, + {"unterminated", `SELECT position(a IN b`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tt.q, normalizeQuery(tt.q)) + }) + } +} + +func TestNormalizeQueryRewrites(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + q string + want string + }{ + {"position", `SELECT position('a' IN b)`, `SELECT strpos(b, 'a')`}, + {"position newline", "SELECT position(\n'a'\nIN\nb)", "SELECT strpos(b, 'a')"}, + { + "position nested paren", + `SELECT position('a' IN concat(b, 'in', c))`, + `SELECT strpos(concat(b, 'in', c), 'a')`, + }, + {"position string with in", `SELECT position('x in y' IN b)`, `SELECT strpos(b, 'x in y')`}, + {"extract dow", `SELECT extract(DOW FROM t)`, `SELECT day_of_week(t)`}, + {"values bare", `SELECT * FROM (VALUES 1, 2) AS t(c)`, `SELECT * FROM (VALUES (1), (2)) AS t(c)`}, + {"comment keyword", "SELECT 1 -- position(a IN b)", "SELECT 1"}, + {"not in values", `SELECT 1 WHERE a NOT IN (VALUES 1, 2)`, `SELECT 1 WHERE a NOT IN (VALUES (1), (2))`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tt.want, normalizeQuery(tt.q)) + }) + } +} diff --git a/test/crossengine/function_namespace_test.go b/test/crossengine/function_namespace_test.go new file mode 100644 index 0000000000..4e9546caa8 --- /dev/null +++ b/test/crossengine/function_namespace_test.go @@ -0,0 +1,189 @@ +package crossengine_test + +import ( + "database/sql" + "fmt" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + _ "modernc.org/sqlite" + + "github.com/blackbirdworks/gopherstack/services/athena" + "github.com/blackbirdworks/gopherstack/services/gcpbigquery/bqsql" + "github.com/blackbirdworks/gopherstack/services/timestreamquery" +) + +func appFuncs(t *testing.T) []string { + t.Helper() + + db, err := sql.Open("sqlite", ":memory:") + require.NoError(t, err) + + defer db.Close() + + rows, err := db.QueryContext(t.Context(), "SELECT DISTINCT name FROM pragma_function_list WHERE builtin = 0") + require.NoError(t, err) + + defer rows.Close() + + var out []string + + for rows.Next() { + var n string + require.NoError(t, rows.Scan(&n)) + + out = append(out, n) + } + + require.NoError(t, rows.Err()) + + return out +} + +type noCatalog struct{} + +func (noCatalog) Table(bqsql.TableRef) (*bqsql.TableData, bool) { return nil, false } +func (noCatalog) DatasetExists(string, string) bool { return true } + +func bigQueryValue(t *testing.T, expr string) string { + t.Helper() + + st, err := bqsql.ParseStatement("SELECT " + expr) + require.NoError(t, err) + + res, err := bqsql.Run(t.Context(), st, &bqsql.Input{Catalog: noCatalog{}, Project: "p", Dataset: "ds"}, false) + require.NoError(t, err, expr) + require.Len(t, res.Rows, 1) + + return fmt.Sprint(bqsql.Row(res.Fields, res.Rows[0])["f"].([]map[string]any)[0]["v"]) +} + +func athenaValue(t *testing.T, expr string) string { + t.Helper() + + q, _, err := athena.TranslateTrino("SELECT "+expr, func([]string) (string, string, bool) { return "", "", false }) + require.NoError(t, err, expr) + + db, err := athena.OpenEngineDB() + require.NoError(t, err) + + defer db.Close() + + var v any + + require.NoError(t, db.QueryRowContext(t.Context(), q).Scan(&v), q) + + return fmt.Sprint(v) +} + +func timestreamValue(t *testing.T, expr string) string { + t.Helper() + + b := timestreamquery.NewInMemoryBackend("000000000000", "us-east-1") + pg, err := b.QueryWithOptions(t.Context(), timestreamquery.QueryOptions{QueryString: "SELECT " + expr}) + require.NoError(t, err, expr) + require.Len(t, pg.Rows, 1) + + d := pg.Rows[0].Data[0] + if d.ScalarValue == nil { + return "NULL" + } + + return *d.ScalarValue +} + +func TestEnginesKeepTheirOwnFunctionSemantics(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + expr string + engine string + want string + }{ + {"bq replace", "REPLACE('abc', 'b', 'X')", "bq", "aXc"}, + {"bq repeat", "REPEAT('ab', 3)", "bq", "ababab"}, + {"bq reverse", "REVERSE('abc')", "bq", "cba"}, + {"bq sqrt", "SQRT(16.0)", "bq", "4.0"}, + {"bq ln", "LN(1.0)", "bq", "0.0"}, + {"bq log10", "LOG10(1000.0)", "bq", "3.0"}, + {"bq pow", "POW(2, 10)", "bq", "1024.0"}, + {"bq abs", "ABS(-3)", "bq", "3"}, + {"bq sign", "SIGN(-2)", "bq", "-1"}, + {"bq round", "ROUND(2.5)", "bq", "3.0"}, + {"bq strpos", "STRPOS('abc', 'c')", "bq", "3"}, + {"bq concat", "CONCAT('a', 'b')", "bq", "ab"}, + {"athena replace", "replace('abc', 'b', 'X')", "athena", "aXc"}, + {"athena lpad", "lpad('a', 3, 'x')", "athena", "xxa"}, + {"athena reverse", "reverse('abc')", "athena", "cba"}, + {"athena sqrt", "sqrt(16)", "athena", "4"}, + {"athena ln", "ln(1)", "athena", "0"}, + {"athena log10", "log10(1000)", "athena", "3"}, + {"athena pow", "pow(2, 10)", "athena", "1024"}, + {"athena abs", "abs(-3)", "athena", "3"}, + {"athena sign", "sign(-2)", "athena", "-1"}, + {"athena round", "round(2.5)", "athena", "3"}, + {"athena strpos", "strpos('abc', 'c')", "athena", "3"}, + {"athena concat", "concat('a', 'b')", "athena", "ab"}, + {"timestream replace", "replace('abc', 'b', 'X')", "ts", "aXc"}, + {"timestream reverse", "reverse('abc')", "ts", "cba"}, + {"timestream repeat", "cardinality(repeat('a', 3))", "ts", "3"}, + {"timestream zip", "cardinality(zip(ARRAY[1,2], ARRAY[3,4]))", "ts", "2"}, + {"timestream sqrt", "sqrt(16.0)", "ts", "4.0"}, + {"timestream strpos", "strpos('abc', 'c')", "ts", "3"}, + {"timestream concat", "concat('a', 'b')", "ts", "ab"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + var got string + + switch tt.engine { + case "bq": + got = bigQueryValue(t, tt.expr) + case "athena": + got = athenaValue(t, tt.expr) + default: + got = timestreamValue(t, tt.expr) + } + + assert.Equal(t, tt.want, got) + }) + } +} + +// Runs before any parallel test: the driver reads its function registry unlocked on every connection open, so +// every engine must have registered by init, not lazily on first use. +func TestEngineFunctionsRegisteredAtInit(t *testing.T) { //nolint:paralleltest // must precede every engine call + got := appFuncs(t) + + for _, name := range []string{"ts_sum", "athena_date_trunc", "bq_upper"} { + assert.Contains(t, got, name) + } +} + +// Every engine's functions live under its own prefix; plain names belong to SQLite alone. +func TestEngineFunctionsArePrefixed(t *testing.T) { + t.Parallel() + + engine := []string{"ts_", "athena_", "bq_"} + // SQLite's own optional modules (FTS5, GeoPoly, R-tree) report as application-defined. + sqliteModules := []string{"fts5", "geopoly_", "rtree", "bm25", "highlight", "snippet", "match"} + + var stray []string + + for _, name := range appFuncs(t) { + hasPrefix := func(p string) bool { return strings.HasPrefix(name, p) } + if !slices.ContainsFunc(engine, hasPrefix) && !slices.ContainsFunc(sqliteModules, hasPrefix) { + stray = append(stray, name) + } + } + + slices.Sort(stray) + assert.Empty(t, stray, "functions registered without an engine prefix are visible to every engine in the process") +} diff --git a/test/guards/sqlite_function_namespace_guard_test.go b/test/guards/sqlite_function_namespace_guard_test.go new file mode 100644 index 0000000000..ef006a5597 --- /dev/null +++ b/test/guards/sqlite_function_namespace_guard_test.go @@ -0,0 +1,518 @@ +package guards_test + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + sqliteImport = "modernc.org/sqlite" + vtabImport = "modernc.org/sqlite/vtab" +) + +// sqliteEnginePrefixes maps each package that registers process-global SQLite functions to its own prefix. +// The driver registry is shared by every sql.Open("sqlite") in the process and keyed by name alone, so a plain +// name shadows a built-in or another engine's function. +func sqliteEnginePrefixes() map[string]string { + return map[string]string{ + "services/athena": "athena_", + "services/gcpbigquery/bqsql": "bq_", + "services/timestreamquery": "ts_", + } +} + +// sqlitePrefixHelpers are functions whose result is always prefixed by the calling package. +func sqlitePrefixHelpers() map[string]string { + return map[string]string{ + "engineFunc": "services/timestreamquery: prepends funcPrefix", + "record": "services/athena: funcRegistry.record returns prefixedFuncName(name)", + "prefixedFuncName": "services/athena: prepends funcPrefix", + } +} + +// sqliteDynamicExemptions lists registrations whose name is a parameter, keyed "dir/file.go:func". +func sqliteDynamicExemptions() map[string]string { + return map[string]string{ + "services/gcpbigquery/bqsql/udf.go:register": "every caller passes \"bq_\"+name", + } +} + +func sqliteRegisterFuncs() []string { + return []string{ + "RegisterFunction", "MustRegisterFunction", + "RegisterScalarFunction", "MustRegisterScalarFunction", + "RegisterDeterministicScalarFunction", "MustRegisterDeterministicScalarFunction", + "RegisterCollationUtf8", "MustRegisterCollationUtf8", "RegisterModule", + } +} + +type sqliteReg struct { + where string + name string + err string +} + +type sqlitePkg struct { + fset *token.FileSet + dir string + files []*ast.File +} + +func parsePkg(t *testing.T, dir string, sources map[string]string) sqlitePkg { + t.Helper() + + p := sqlitePkg{fset: token.NewFileSet(), dir: dir} + + if sources == nil { + paths, err := filepath.Glob(filepath.Join(dir, "*.go")) + require.NoError(t, err) + + sources = map[string]string{} + + for _, path := range paths { + if !strings.HasSuffix(path, "_test.go") { + sources[path] = "" + } + } + } + + for path, src := range sources { + var in any + if src != "" { + in = src + } + + f, err := parser.ParseFile(p.fset, path, in, parser.SkipObjectResolution) + require.NoError(t, err) + + p.files = append(p.files, f) + } + + return p +} + +func sqliteAliases(f *ast.File) map[string]bool { + out := map[string]bool{} + + for _, imp := range f.Imports { + path, _ := strconv.Unquote(imp.Path.Value) + if path != sqliteImport && path != vtabImport { + continue + } + + name := filepath.Base(path) + if imp.Name != nil { + name = imp.Name.Name + } + + out[name] = true + } + + return out +} + +func stringConsts(files []*ast.File) map[string]string { + out := map[string]string{} + + for _, f := range files { + for _, d := range f.Decls { + gd, ok := d.(*ast.GenDecl) + if !ok || gd.Tok != token.CONST { + continue + } + + for _, s := range gd.Specs { + vs, _ := s.(*ast.ValueSpec) + for i, n := range vs.Names { + if i >= len(vs.Values) { + continue + } + + if lit, isLit := vs.Values[i].(*ast.BasicLit); isLit && lit.Kind == token.STRING { + out[n.Name], _ = strconv.Unquote(lit.Value) + } + } + } + } + } + + return out +} + +// staticName resolves the leading literal of a registered name; ok=false means it is not statically known. +func staticName(e ast.Expr, consts map[string]string) (string, bool) { + switch x := e.(type) { + case *ast.BasicLit: + if x.Kind == token.STRING { + s, _ := strconv.Unquote(x.Value) + + return s, true + } + case *ast.BinaryExpr: + if x.Op == token.ADD { + return staticName(x.X, consts) + } + case *ast.Ident: + s, ok := consts[x.Name] + + return s, ok + case *ast.ParenExpr: + return staticName(x.X, consts) + } + + return "", false +} + +func callsPrefixHelper(e ast.Expr) bool { + call, ok := e.(*ast.CallExpr) + if !ok { + return false + } + + var name string + + switch fn := call.Fun.(type) { + case *ast.Ident: + name = fn.Name + case *ast.SelectorExpr: + name = fn.Sel.Name + } + + _, isHelper := sqlitePrefixHelpers()[name] + + return isHelper +} + +// assignedPrefixed reports whether every value assigned to ident in fn is a literal carrying prefix. +func assignedPrefixed(fn *ast.FuncDecl, ident, prefix string) bool { + found, allOK := false, true + + ast.Inspect(fn, func(n ast.Node) bool { + as, ok := n.(*ast.AssignStmt) + if !ok { + return true + } + + for i, lhs := range as.Lhs { + if id, isIdent := lhs.(*ast.Ident); !isIdent || id.Name != ident || i >= len(as.Rhs) { + continue + } + + found = true + + if s, known := staticName(as.Rhs[i], nil); !known || !strings.HasPrefix(s, prefix) { + allOK = false + } + } + + return true + }) + + return found && allOK +} + +// rangedKeysPrefixed reports whether ident is the key of a range over a map literal in fn whose keys all carry prefix. +func rangedKeysPrefixed(fn *ast.FuncDecl, ident, prefix string) bool { + found, allOK := false, true + + ast.Inspect(fn, func(n ast.Node) bool { + rs, ok := n.(*ast.RangeStmt) + if !ok { + return true + } + + if k, isIdent := rs.Key.(*ast.Ident); !isIdent || k.Name != ident { + return true + } + + lit, isLit := rs.X.(*ast.CompositeLit) + if !isLit { + return true + } + + found = true + + for _, el := range lit.Elts { + kv, isKV := el.(*ast.KeyValueExpr) + if !isKV { + allOK = false + + continue + } + + if s, known := staticName(kv.Key, nil); !known || !strings.HasPrefix(s, prefix) { + allOK = false + } + } + + return true + }) + + return found && allOK +} + +func registrationName(sel *ast.SelectorExpr, call *ast.CallExpr) (ast.Expr, bool) { + if !slices.Contains(sqliteRegisterFuncs(), sel.Sel.Name) { + return nil, false + } + + idx := 0 + if sel.Sel.Name == "RegisterModule" { + idx = 1 + } + + if len(call.Args) <= idx { + return nil, false + } + + return call.Args[idx], true +} + +// sqliteRegistrations lists the process-global registrations in p with the reason each one is unsafe, if any. +func sqliteRegistrations(p sqlitePkg, prefix string, exempt map[string]string) []sqliteReg { + consts := stringConsts(p.files) + + var out []sqliteReg + + for _, f := range p.files { + aliases := sqliteAliases(f) + + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + + ast.Inspect(fn.Body, func(n ast.Node) bool { + call, isCall := n.(*ast.CallExpr) + if !isCall { + return true + } + + sel, isSel := call.Fun.(*ast.SelectorExpr) + if !isSel { + return true + } + + if id, isIdent := sel.X.(*ast.Ident); !isIdent || !aliases[id.Name] { + return true + } + + pos := p.fset.Position(call.Pos()) + where := pos.Filename + ":" + strconv.Itoa(pos.Line) + + if sel.Sel.Name == "RegisterConnectionHook" { + out = append( + out, + sqliteReg{ + where: where, + err: "RegisterConnectionHook applies to every connection in the process", + }, + ) + + return true + } + + if nameArg, isReg := registrationName(sel, call); isReg { + key := pos.Filename + ":" + fn.Name.Name + out = append(out, classify(prefix, where, key, fn, nameArg, consts, exempt)) + } + + return true + }) + } + } + + return out +} + +func classify( + prefix, where, exemptKey string, fn *ast.FuncDecl, nameArg ast.Expr, consts, exempt map[string]string, +) sqliteReg { + if prefix == "" { + return sqliteReg{ + where: where, + err: "package registers process-global SQLite functions but has no sqliteEnginePrefixes entry", + } + } + + if callsPrefixHelper(nameArg) { + return sqliteReg{where: where} + } + + if s, ok := staticName(nameArg, consts); ok { + if strings.HasPrefix(s, prefix) { + return sqliteReg{where: where, name: s} + } + + return sqliteReg{where: where, name: s, err: "name " + strconv.Quote(s) + " lacks prefix " + prefix} + } + + if id, isIdent := nameArg.(*ast.Ident); isIdent && + (rangedKeysPrefixed(fn, id.Name, prefix) || assignedPrefixed(fn, id.Name, prefix)) { + return sqliteReg{where: where} + } + + if _, ok := exempt[exemptKey]; ok { + return sqliteReg{where: where} + } + + return sqliteReg{where: where, err: "name is not statically prefixed with " + prefix} +} + +func TestSqliteRegistrationClassifier(t *testing.T) { + t.Parallel() + + const head = "package p\nimport sqlitedriver \"modernc.org/sqlite\"\nconst modName = \"ts_mod\"\n" + + tests := []struct { + exempt map[string]string + name string + body string + wantErr bool + none bool + }{ + {name: "prefixed literal", body: `func f() { sqlitedriver.MustRegisterScalarFunction("ts_a", 1, nil) }`}, + { + name: "plain literal", + body: `func f() { sqlitedriver.MustRegisterScalarFunction("repeat", 1, nil) }`, + wantErr: true, + }, + { + name: "builtin override", + body: `func f() { sqlitedriver.MustRegisterDeterministicScalarFunction("replace", 3, nil) }`, + wantErr: true, + }, + { + name: "other engine prefix", + body: `func f() { sqlitedriver.MustRegisterFunction("bq_x", nil) }`, + wantErr: true, + }, + {name: "helper", body: `func f() { sqlitedriver.MustRegisterFunction(engineFunc("x"), nil) }`}, + {name: "concat prefixed", body: `func f(n string) { sqlitedriver.MustRegisterFunction("ts_"+n, nil) }`}, + { + name: "concat plain", + body: `func f(n string) { sqlitedriver.MustRegisterFunction(n+"_x", nil) }`, + wantErr: true, + }, + {name: "const", body: `func f() { sqlitedriver.RegisterScalarFunction(modName, 0, nil) }`}, + { + name: "ranged prefixed keys", + body: `func f() { for n := range map[string]int{"ts_a": 1, "ts_b": 2} { + sqlitedriver.MustRegisterFunction(n, nil) } }`, + }, + { + name: "ranged plain key", + body: `func f() { for n := range map[string]int{"ts_a": 1, "b": 2} { + sqlitedriver.MustRegisterFunction(n, nil) } }`, + wantErr: true, + }, + {name: "dynamic", body: `func f(n string) { sqlitedriver.MustRegisterFunction(n, nil) }`, wantErr: true}, + { + name: "dynamic exempt", + body: `func f(n string) { sqlitedriver.MustRegisterFunction(n, nil) }`, + exempt: map[string]string{"x/a.go:f": "caller prefixes"}, + }, + {name: "global hook", body: `func f() { sqlitedriver.RegisterConnectionHook(nil) }`, wantErr: true}, + { + name: "unrelated receiver", + body: `func f(r interface{ MustRegisterFunction(string) }) { r.MustRegisterFunction("repeat") }`, + none: true, + }, + { + name: "assigned prefixed", + body: `func f() { n := "ts_a"; n = "ts_b"; sqlitedriver.MustRegisterFunction(n, nil) }`, + }, + { + name: "assigned plain", + body: `func f() { n := "ts_a"; n = "b"; sqlitedriver.MustRegisterFunction(n, nil) }`, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + p := parsePkg(t, "x", map[string]string{"x/a.go": head + tt.body}) + regs := sqliteRegistrations(p, "ts_", tt.exempt) + + if tt.none { + assert.Empty(t, regs) + + return + } + + require.NotEmpty(t, regs, "the registration must be found") + + var errs []string + + for _, r := range regs { + if r.err != "" { + errs = append(errs, r.err) + } + } + + if tt.wantErr { + assert.NotEmpty(t, errs) + } else { + assert.Empty(t, errs) + } + }) + } +} + +func TestSqliteFunctionsArePrefixedPerPackage(t *testing.T) { + t.Parallel() + + prefixes := sqliteEnginePrefixes() + + for a, pa := range prefixes { + for b, pb := range prefixes { + if a != b { + assert.False(t, strings.HasPrefix(pa, pb), "%s and %s prefixes overlap", a, b) + } + } + } + + var offenders []string + + owner := map[string]string{} + + err := filepath.WalkDir("services", func(path string, d fs.DirEntry, err error) error { + if err != nil || !d.IsDir() { + return err + } + + p := parsePkg(t, path, nil) + + for _, r := range sqliteRegistrations(p, prefixes[filepath.ToSlash(path)], sqliteDynamicExemptions()) { + if r.err != "" { + offenders = append(offenders, r.where+": "+r.err) + } + + if prev, dup := owner[r.name]; r.name != "" && dup && prev != path { + offenders = append(offenders, r.where+": "+r.name+" is also registered by "+prev) + } + + if r.name != "" { + owner[r.name] = path + } + } + + return nil + }) + require.NoError(t, err) + + assert.Empty(t, offenders) +} From 0123c6a9ef48462c5d45dbdace820d2940c7e863 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 22:08:04 -0600 Subject: [PATCH 3/8] feat(servicequotas): usage and opt-in enforcement for 51 more resource-count quotas CloudWatch Logs, KMS, EventBridge, Step Functions, Route 53, ECR, Auto Scaling, EFS, Firehose, Cognito and the EC2 and VPC resource quotas report live usage. With --enforce-service-quotas the create operations whose API documents a limit error fail at the applied value. Every catalogued quota is classified, and a guard fails when a counted quota has no counter. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- internal/app/service_quotas_counters.go | 149 + internal/app/service_quotas_guard_test.go | 127 + .../app/service_quotas_limits_core_test.go | 582 ++ .../app/service_quotas_limits_ec2_test.go | 254 + .../app/service_quotas_limits_harness_test.go | 192 + .../app/service_quotas_limits_more_test.go | 215 + internal/app/service_quotas_wiring.go | 30 +- .../app/testdata/service_quota_classes.json | 5490 +++++++++++++++++ services/autoscaling/auto_scaling_groups.go | 8 + services/autoscaling/handler.go | 1 + services/autoscaling/launch_configurations.go | 8 + services/autoscaling/quota.go | 75 + services/autoscaling/regions.go | 1 + services/autoscaling/store.go | 4 + services/cloudwatchlogs/handler.go | 2 +- services/cloudwatchlogs/log_groups.go | 5 + services/cloudwatchlogs/quota.go | 56 + services/cloudwatchlogs/store.go | 3 + services/cognitoidentity/handler.go | 1 + services/cognitoidentity/identity_pools.go | 5 + services/cognitoidentity/quota.go | 48 + services/cognitoidentity/store.go | 3 + services/cognitoidp/quota.go | 51 + services/cognitoidp/regions.go | 1 + services/cognitoidp/store.go | 4 + services/cognitoidp/user_pools.go | 12 + services/ec2/handler.go | 3 + services/ec2/nat_gateways.go | 6 + services/ec2/network_interfaces.go | 6 + services/ec2/quota_vpc.go | 217 + services/ec2/route_spec.go | 6 + services/ecr/handler.go | 2 + services/ecr/quota.go | 61 + services/ecr/repositories.go | 7 +- services/ecr/store.go | 4 + services/efs/file_systems.go | 6 +- services/efs/quota.go | 36 + services/efs/replication.go | 5 +- services/efs/store.go | 3 + services/eventbridge/api_destinations.go | 6 + services/eventbridge/connections.go | 6 + services/eventbridge/endpoints.go | 6 + services/eventbridge/event_buses.go | 17 +- services/eventbridge/quota.go | 186 + services/eventbridge/rules.go | 6 +- services/eventbridge/store.go | 3 + services/firehose/delivery_streams.go | 6 +- services/firehose/handler.go | 2 + services/firehose/quota.go | 64 + services/firehose/store.go | 3 + services/kms/aliases.go | 9 +- services/kms/grants.go | 6 +- services/kms/keys.go | 12 +- services/kms/quota.go | 180 + services/kms/store.go | 3 + services/route53/cidr_collections.go | 6 + services/route53/handler.go | 4 + services/route53/health_checks.go | 5 + services/route53/hosted_zones.go | 5 + services/route53/quota.go | 118 + services/route53/reusable_delegation_sets.go | 7 + services/route53/store.go | 3 + services/route53/traffic_policies.go | 6 + services/servicequotas/PARITY.md | 14 +- services/stepfunctions/activities.go | 5 + services/stepfunctions/aliases.go | 7 + services/stepfunctions/handler.go | 3 + services/stepfunctions/quota.go | 107 + .../stepfunctions/state_machine_versions.go | 8 + services/stepfunctions/state_machines.go | 5 + services/stepfunctions/store.go | 3 + 71 files changed, 8463 insertions(+), 47 deletions(-) create mode 100644 internal/app/service_quotas_counters.go create mode 100644 internal/app/service_quotas_guard_test.go create mode 100644 internal/app/service_quotas_limits_core_test.go create mode 100644 internal/app/service_quotas_limits_ec2_test.go create mode 100644 internal/app/service_quotas_limits_harness_test.go create mode 100644 internal/app/service_quotas_limits_more_test.go create mode 100644 internal/app/testdata/service_quota_classes.json create mode 100644 services/autoscaling/quota.go create mode 100644 services/cloudwatchlogs/quota.go create mode 100644 services/cognitoidentity/quota.go create mode 100644 services/cognitoidp/quota.go create mode 100644 services/ec2/quota_vpc.go create mode 100644 services/ecr/quota.go create mode 100644 services/efs/quota.go create mode 100644 services/eventbridge/quota.go create mode 100644 services/firehose/quota.go create mode 100644 services/kms/quota.go create mode 100644 services/route53/quota.go create mode 100644 services/stepfunctions/quota.go diff --git a/internal/app/service_quotas_counters.go b/internal/app/service_quotas_counters.go new file mode 100644 index 0000000000..2daa9a1473 --- /dev/null +++ b/internal/app/service_quotas_counters.go @@ -0,0 +1,149 @@ +package app + +import ( + asbackend "github.com/blackbirdworks/gopherstack/services/autoscaling" + cwlogsbackend "github.com/blackbirdworks/gopherstack/services/cloudwatchlogs" + cognitoidentitybackend "github.com/blackbirdworks/gopherstack/services/cognitoidentity" + cognitoidpbackend "github.com/blackbirdworks/gopherstack/services/cognitoidp" + ec2backend "github.com/blackbirdworks/gopherstack/services/ec2" + ecrbackend "github.com/blackbirdworks/gopherstack/services/ecr" + efsbackend "github.com/blackbirdworks/gopherstack/services/efs" + ebbackend "github.com/blackbirdworks/gopherstack/services/eventbridge" + firehosebackend "github.com/blackbirdworks/gopherstack/services/firehose" + kmsbackend "github.com/blackbirdworks/gopherstack/services/kms" + route53backend "github.com/blackbirdworks/gopherstack/services/route53" + sfnbackend "github.com/blackbirdworks/gopherstack/services/stepfunctions" +) + +// counted adapts a typed handler read to a quotaCounter; a quota is untracked while its service is not wired. +func counted[H any](read func(h H, account, region string) int) quotaCounter { + return func(a *quotaUsageAdapter, account, region string) (int, bool) { + for _, r := range a.byName { + if h, ok := r.(H); ok { + return read(h, account, region), true + } + } + + return 0, false + } +} + +func eventsCounted(read func(c ebbackend.QuotaCounter, region string) int) quotaCounter { + return counted(func(h *ebbackend.Handler, _, region string) int { + if c := h.QuotaCounts(); c != nil { + return read(c, region) + } + + return 0 + }) +} + +func route53Counted(read func(c route53backend.QuotaCounter) int) quotaCounter { + return counted(func(h *route53backend.Handler, _, _ string) int { + if c := h.QuotaCounts(); c != nil { + return read(c) + } + + return 0 + }) +} + +type ec2QuotaCounter interface{ QuotaCount(code string) (int, bool) } + +func ec2Counted(code string) quotaCounter { + return counted(func(h *ec2backend.Handler, _, region string) int { + if c, ok := h.BackendFor(region).(ec2QuotaCounter); ok { + n, _ := c.QuotaCount(code) + + return n + } + + return 0 + }) +} + +func serviceQuotaCounters() map[string]quotaCounter { + return map[string]quotaCounter{ + "logs/L-C7B9AAAB": counted(func(h *cwlogsbackend.Handler, _, rgn string) int { return h.LogGroupCount(rgn) }), + + "kms/L-C2F1777E": counted(func(h *kmsbackend.Handler, _, rgn string) int { return h.KeyCount(rgn) }), + "kms/L-340F62FB": counted(func(h *kmsbackend.Handler, _, rgn string) int { return h.MaxAliasesPerKey(rgn) }), + "kms/L-D594A657": counted(func(h *kmsbackend.Handler, _, rgn string) int { return h.MaxGrantsPerKey(rgn) }), + + "events/L-244521F2": eventsCounted( + func(c ebbackend.QuotaCounter, rgn string) int { return c.MaxRulesPerBus(rgn) }, + ), + "events/L-658A4FD9": eventsCounted( + func(c ebbackend.QuotaCounter, rgn string) int { return c.CustomBusCount(rgn) }, + ), + "events/L-595D6D42": eventsCounted( + func(c ebbackend.QuotaCounter, rgn string) int { return c.ConnectionsInRegion(rgn) }, + ), + "events/L-EAC9A2AC": eventsCounted( + func(c ebbackend.QuotaCounter, rgn string) int { return c.EndpointsInRegion(rgn) }, + ), + "events/L-FB1C3A6D": eventsCounted( + func(c ebbackend.QuotaCounter, rgn string) int { return c.APIDestinationsInRegion(rgn) }, + ), + + "states/L-B66B0F91": counted( + func(h *sfnbackend.Handler, _, rgn string) int { return h.StateMachineCount(rgn) }, + ), + "states/L-A9562A73": counted(func(h *sfnbackend.Handler, _, rgn string) int { return h.ActivityCount(rgn) }), + "states/L-6AFCB355": counted( + func(h *sfnbackend.Handler, _, rgn string) int { return h.MaxVersionsPerStateMachine(rgn) }, + ), + "states/L-C1D5EBBB": counted( + func(h *sfnbackend.Handler, _, rgn string) int { return h.MaxAliasesPerStateMachine(rgn) }, + ), + + "route53/L-4EA4796A": route53Counted(func(c route53backend.QuotaCounter) int { return c.HostedZoneCount() }), + "route53/L-ACB674F3": route53Counted(func(c route53backend.QuotaCounter) int { return c.HealthCheckCount() }), + "route53/L-A72C7724": route53Counted(func(c route53backend.QuotaCounter) int { return c.DelegationSetCount() }), + "route53/L-FC688E7C": route53Counted(func(c route53backend.QuotaCounter) int { return c.TrafficPolicyCount() }), + "route53/L-AD61772F": route53Counted( + func(c route53backend.QuotaCounter) int { return c.CidrCollectionCount() }, + ), + "route53/L-E209CC9F": route53Counted( + func(c route53backend.QuotaCounter) int { return c.MaxRecordsPerHostedZone() }, + ), + + "vpc/L-407747CB": ec2Counted("L-407747CB"), + "vpc/L-A4707A72": ec2Counted("L-A4707A72"), + "vpc/L-FE5A380F": ec2Counted("L-FE5A380F"), + "vpc/L-DF5E4CA3": ec2Counted("L-DF5E4CA3"), + "vpc/L-E79EC296": ec2Counted("L-E79EC296"), + "vpc/L-0EA8095F": ec2Counted("L-0EA8095F"), + "vpc/L-589F43AA": ec2Counted("L-589F43AA"), + "vpc/L-93826ACB": ec2Counted("L-93826ACB"), + "ec2/L-1216C47A": ec2Counted("L-1216C47A"), + "ec2/L-DB2E81BA": ec2Counted("L-DB2E81BA"), + "ec2/L-417A185B": ec2Counted("L-417A185B"), + "ec2/L-74FC7D96": ec2Counted("L-74FC7D96"), + "ec2/L-7295265B": ec2Counted("L-7295265B"), + "ec2/L-1945791B": ec2Counted("L-1945791B"), + "ec2/L-43DA4232": ec2Counted("L-43DA4232"), + "ec2/L-34B43A08": ec2Counted("L-34B43A08"), + "ec2/L-7212CCBC": ec2Counted("L-7212CCBC"), + "ec2/L-3819A6DF": ec2Counted("L-3819A6DF"), + + "autoscaling/L-CDE20ADC": counted(func(h *asbackend.Handler, _, rgn string) int { return h.GroupCount(rgn) }), + "autoscaling/L-6B80B8FA": counted( + func(h *asbackend.Handler, _, rgn string) int { return h.LaunchConfigurationCount(rgn) }, + ), + "elasticfilesystem/L-848C634D": counted(func(h *efsbackend.Handler, _, rgn string) int { + return h.FileSystemCount(rgn) + }), + "firehose/L-14BB0BE7": counted(func(h *firehosebackend.Handler, _, rgn string) int { + return h.DeliveryStreamCount(rgn) + }), + "cognito-identity/L-8692CE1C": counted(func(h *cognitoidentitybackend.Handler, _, rgn string) int { + return h.IdentityPoolCount(rgn) + }), + "cognito-idp/L-66E6DF30": counted(func(h *cognitoidpbackend.Handler, _, rgn string) int { + return h.UserPoolCount(rgn) + }), + + "ecr/L-CFEB8E8D": counted(func(h *ecrbackend.Handler, _, rgn string) int { return h.RepositoryCount(rgn) }), + } +} diff --git a/internal/app/service_quotas_guard_test.go b/internal/app/service_quotas_guard_test.go new file mode 100644 index 0000000000..82d388a616 --- /dev/null +++ b/internal/app/service_quotas_guard_test.go @@ -0,0 +1,127 @@ +package app + +import ( + _ "embed" // quota classification table + "encoding/json/v2" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" + servicequotasbackend "github.com/blackbirdworks/gopherstack/services/servicequotas" +) + +//go:embed testdata/service_quota_classes.json +var quotaClassesJSON []byte + +// quotaClassEntry classifies the catalogued quotas of one service: +// c counted (has a live counter), e count-of-resources without a counter (Reason says why), +// s per-resource size or length limit, r rate or concurrency, o not derivable in an emulator. +type quotaClassEntry struct { + Quotas map[string]string `json:"quotas"` + Reason string `json:"reason"` +} + +func loadQuotaClasses(t *testing.T) map[string]quotaClassEntry { + t.Helper() + + var classes map[string]quotaClassEntry + require.NoError(t, json.Unmarshal(quotaClassesJSON, &classes, jsonx.V1())) + + return classes +} + +func catalogQuotaKeys(t *testing.T) map[string]bool { + t.Helper() + + b := servicequotasbackend.NewInMemoryBackend(quotaTestAccount, quotaTestRegion) + keys := map[string]bool{} + token := "" + + for { + pg, err := b.ListServices(token, nil) + require.NoError(t, err) + + for _, svc := range pg.Data { + for _, q := range svc.Quotas { + keys[svc.Code+"/"+q.Code] = true + } + } + + if pg.Next == "" { + return keys + } + + token = pg.Next + } +} + +func TestQuotaClassificationCoversCatalog(t *testing.T) { + t.Parallel() + + classes := loadQuotaClasses(t) + catalog := catalogQuotaKeys(t) + classified := map[string]string{} + + for svc, entry := range classes { + hasExempt := false + + for code, class := range entry.Quotas { + require.Contains(t, []string{"c", "e", "s", "r", "o"}, class, "%s/%s", svc, code) + classified[svc+"/"+code] = class + hasExempt = hasExempt || class == "e" + } + + if hasExempt { + assert.NotEmpty(t, entry.Reason, "%s has count quotas without a counter and no reason", svc) + } + } + + for k := range catalog { + assert.Contains( + t, + classified, + k, + "catalogued quota %s is not classified in testdata/service_quota_classes.json", + k, + ) + } + + for k := range classified { + assert.True(t, catalog[k], "classified quota %s is not catalogued", k) + } +} + +func TestQuotaCountersMatchClassification(t *testing.T) { + t.Parallel() + + classes := loadQuotaClasses(t) + counters := map[string]bool{} + + for k := range quotaCounters { + counters[k] = true + } + + for k := range extraQuotaCounters { + counters[k] = true + } + + counted := map[string]bool{} + + for svc, entry := range classes { + for code, class := range entry.Quotas { + if class == "c" { + counted[svc+"/"+code] = true + } + } + } + + for k := range counted { + assert.True(t, counters[k], "%s is classified as counted but has no counter in quotaCounters", k) + } + + for k := range counters { + assert.True(t, counted[k], "%s has a counter but is not classified as counted", k) + } +} diff --git a/internal/app/service_quotas_limits_core_test.go b/internal/app/service_quotas_limits_core_test.go new file mode 100644 index 0000000000..9ea23e7777 --- /dev/null +++ b/internal/app/service_quotas_limits_core_test.go @@ -0,0 +1,582 @@ +package app + +import ( + "context" + "errors" + "slices" + "strconv" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs" + "github.com/aws/aws-sdk-go-v2/service/ecr" + "github.com/aws/aws-sdk-go-v2/service/eventbridge" + ebtypes "github.com/aws/aws-sdk-go-v2/service/eventbridge/types" + "github.com/aws/aws-sdk-go-v2/service/kms" + kmstypes "github.com/aws/aws-sdk-go-v2/service/kms/types" + "github.com/aws/aws-sdk-go-v2/service/route53" + r53types "github.com/aws/aws-sdk-go-v2/service/route53/types" + "github.com/aws/aws-sdk-go-v2/service/sfn" + sfntypes "github.com/aws/aws-sdk-go-v2/service/sfn/types" + + "github.com/blackbirdworks/gopherstack/pkgs/service" + cwlogsbackend "github.com/blackbirdworks/gopherstack/services/cloudwatchlogs" + ecrbackend "github.com/blackbirdworks/gopherstack/services/ecr" + ebbackend "github.com/blackbirdworks/gopherstack/services/eventbridge" + kmsbackend "github.com/blackbirdworks/gopherstack/services/kms" + route53backend "github.com/blackbirdworks/gopherstack/services/route53" + sfnbackend "github.com/blackbirdworks/gopherstack/services/stepfunctions" +) + +const limitTestTrafficPolicy = `{"AWSPolicyFormatVersion":"2015-10-01","RecordType":"A",` + + `"Endpoints":{"e":{"Type":"value","Value":"192.0.2.1"}},"StartEndpoint":"e"}` + +const ( + limitTestRole = "arn:aws:iam::000000000000:role/limit" + limitTestDefinition = `{"StartAt":"P","States":{"P":{"Type":"Pass","End":true}}}` +) + +func name(prefix string, i int) string { return prefix + qnum(i) } + +func qnum(i int) string { return strconv.Itoa(i) } + +func logsClient(e limitEnv) *cloudwatchlogs.Client { + return cloudwatchlogs.NewFromConfig(e.cfg, func(o *cloudwatchlogs.Options) { o.BaseEndpoint = e.endpoint() }) +} + +func kmsClient(e limitEnv) *kms.Client { + return kms.NewFromConfig(e.cfg, func(o *kms.Options) { o.BaseEndpoint = e.endpoint() }) +} + +func eventsClient(e limitEnv) *eventbridge.Client { + return eventbridge.NewFromConfig(e.cfg, func(o *eventbridge.Options) { o.BaseEndpoint = e.endpoint() }) +} + +func sfnClient(e limitEnv) *sfn.Client { + return sfn.NewFromConfig(e.cfg, func(o *sfn.Options) { o.BaseEndpoint = e.endpoint() }) +} + +func route53Client(e limitEnv) *route53.Client { + return route53.NewFromConfig(e.cfg, func(o *route53.Options) { o.BaseEndpoint = e.endpoint() }) +} + +func ecrClient(e limitEnv) *ecr.Client { + return ecr.NewFromConfig(e.cfg, func(o *ecr.Options) { o.BaseEndpoint = e.endpoint() }) +} + +func kmsTargetKey(ctx context.Context, c *kms.Client) (string, error) { + list, err := c.ListKeys(ctx, &kms.ListKeysInput{}) + if err != nil { + return "", err + } + + if len(list.Keys) > 0 { + return aws.ToString(list.Keys[0].KeyId), nil + } + + out, err := c.CreateKey(ctx, &kms.CreateKeyInput{}) + if err != nil { + return "", err + } + + return aws.ToString(out.KeyMetadata.KeyId), nil +} + +func kmsCases() []limitCase { + handler := func(*testing.T) service.Registerable { + return kmsbackend.NewHandler(kmsbackend.NewInMemoryBackendWithConfig(quotaTestAccount, quotaTestRegion)) + } + + return []limitCase{ + { + name: "kms keys", svc: "kms", quota: "L-C2F1777E", + code: "LimitExceededException", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, _ int) error { + _, err := kmsClient(e).CreateKey(ctx, &kms.CreateKeyInput{}) + + return err + }, + }, + { + name: "kms aliases per key", svc: "kms", quota: "L-340F62FB", + code: "LimitExceededException", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + c := kmsClient(e) + + key, err := kmsTargetKey(ctx, c) + if err != nil { + return err + } + + _, err = c.CreateAlias( + ctx, + &kms.CreateAliasInput{AliasName: aws.String("alias/" + name("a", i)), TargetKeyId: &key}, + ) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := kmsClient( + e, + ).DeleteAlias(ctx, &kms.DeleteAliasInput{AliasName: aws.String("alias/" + name("a", i))}) + + return err + }, + }, + { + name: "kms grants per key", svc: "kms", quota: "L-D594A657", + code: "LimitExceededException", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + c := kmsClient(e) + + key, err := kmsTargetKey(ctx, c) + if err != nil { + return err + } + + _, err = c.CreateGrant(ctx, &kms.CreateGrantInput{ + KeyId: &key, Name: aws.String(name("g", i)), + GranteePrincipal: aws.String(limitTestRole), + Operations: []kmstypes.GrantOperation{kmstypes.GrantOperationEncrypt}, + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := kmsClient(e) + + key, err := kmsTargetKey(ctx, c) + if err != nil { + return err + } + + grants, err := c.ListGrants(ctx, &kms.ListGrantsInput{KeyId: &key}) + if err != nil || len(grants.Grants) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.RevokeGrant(ctx, &kms.RevokeGrantInput{KeyId: &key, GrantId: grants.Grants[0].GrantId}) + + return err + }, + }, + } +} + +func logsAndECRCases() []limitCase { + return []limitCase{ + { + name: "log groups", svc: "logs", quota: "L-C7B9AAAB", + code: "LimitExceededException", limit: 2, + handler: func(*testing.T) service.Registerable { + return cwlogsbackend.NewHandler( + cwlogsbackend.NewInMemoryBackendWithConfig(quotaTestAccount, quotaTestRegion), + ) + }, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := logsClient( + e, + ).CreateLogGroup(ctx, &cloudwatchlogs.CreateLogGroupInput{LogGroupName: aws.String(name("g", i))}) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := logsClient( + e, + ).DeleteLogGroup(ctx, &cloudwatchlogs.DeleteLogGroupInput{LogGroupName: aws.String(name("g", i))}) + + return err + }, + }, + { + name: "ecr repositories", svc: "ecr", quota: "L-CFEB8E8D", + code: "LimitExceededException", limit: 2, + handler: func(*testing.T) service.Registerable { + return ecrbackend.NewHandler(ecrbackend.NewInMemoryBackend(quotaTestAccount, quotaTestRegion, ""), nil) + }, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := ecrClient( + e, + ).CreateRepository(ctx, &ecr.CreateRepositoryInput{RepositoryName: aws.String(name("r", i))}) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := ecrClient( + e, + ).DeleteRepository(ctx, &ecr.DeleteRepositoryInput{RepositoryName: aws.String(name("r", i))}) + + return err + }, + }, + } +} + +func eventsCases() []limitCase { + handler := func(*testing.T) service.Registerable { + return ebbackend.NewHandler(ebbackend.NewInMemoryBackendWithConfig(quotaTestAccount, quotaTestRegion)) + } + apiKey := &ebtypes.CreateConnectionAuthRequestParameters{ + ApiKeyAuthParameters: &ebtypes.CreateConnectionApiKeyAuthRequestParameters{ + ApiKeyName: aws.String("k"), ApiKeyValue: aws.String("v"), + }, + } + createConn := func(ctx context.Context, e limitEnv, n string) (*eventbridge.CreateConnectionOutput, error) { + return eventsClient(e).CreateConnection(ctx, &eventbridge.CreateConnectionInput{ + Name: aws.String(n), AuthorizationType: ebtypes.ConnectionAuthorizationTypeApiKey, AuthParameters: apiKey, + }) + } + + return []limitCase{ + { + name: "event buses", svc: "events", quota: "L-658A4FD9", + code: "LimitExceededException", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := eventsClient( + e, + ).CreateEventBus(ctx, &eventbridge.CreateEventBusInput{Name: aws.String(name("b", i))}) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := eventsClient( + e, + ).DeleteEventBus(ctx, &eventbridge.DeleteEventBusInput{Name: aws.String(name("b", i))}) + + return err + }, + }, + { + name: "event rules per bus", svc: "events", quota: "L-244521F2", + code: "LimitExceededException", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := eventsClient(e).PutRule(ctx, &eventbridge.PutRuleInput{ + Name: aws.String(name("r", i)), EventPattern: aws.String(`{"source":["a"]}`), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := eventsClient(e).DeleteRule(ctx, &eventbridge.DeleteRuleInput{Name: aws.String(name("r", i))}) + + return err + }, + }, + { + name: "event connections", svc: "events", quota: "L-595D6D42", + code: "LimitExceededException", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := createConn(ctx, e, name("c", i)) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := eventsClient( + e, + ).DeleteConnection(ctx, &eventbridge.DeleteConnectionInput{Name: aws.String(name("c", i))}) + + return err + }, + }, + { + name: "event api destinations", svc: "events", quota: "L-FB1C3A6D", + code: "LimitExceededException", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + conn, err := createConn(ctx, e, "base") + if err != nil { + out, derr := eventsClient( + e, + ).DescribeConnection(ctx, &eventbridge.DescribeConnectionInput{Name: aws.String("base")}) + if derr != nil { + return derr + } + + conn = &eventbridge.CreateConnectionOutput{ConnectionArn: out.ConnectionArn} + } + + _, err = eventsClient(e).CreateApiDestination(ctx, &eventbridge.CreateApiDestinationInput{ + Name: aws.String(name("d", i)), ConnectionArn: conn.ConnectionArn, + InvocationEndpoint: aws.String( + "https://example.com/hook", + ), HttpMethod: ebtypes.ApiDestinationHttpMethodPost, + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := eventsClient( + e, + ).DeleteApiDestination(ctx, &eventbridge.DeleteApiDestinationInput{Name: aws.String(name("d", i))}) + + return err + }, + }, + } +} + +func sfnCases() []limitCase { + handler := func(*testing.T) service.Registerable { + return sfnbackend.NewHandler(sfnbackend.NewInMemoryBackendWithConfig(quotaTestAccount, quotaTestRegion)) + } + smARN := func(n string) *string { + return aws.String("arn:aws:states:us-east-1:" + quotaTestAccount + ":stateMachine:" + n) + } + ensureMachine := func(ctx context.Context, e limitEnv) error { + _, err := sfnClient(e).CreateStateMachine(ctx, &sfn.CreateStateMachineInput{ + Name: aws.String("base"), Definition: aws.String(limitTestDefinition), RoleArn: aws.String(limitTestRole), + }) + + return err + } + + return []limitCase{ + { + name: "state machines", svc: "states", quota: "L-B66B0F91", + code: "StateMachineLimitExceeded", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := sfnClient(e).CreateStateMachine(ctx, &sfn.CreateStateMachineInput{ + Name: aws.String( + name("m", i), + ), Definition: aws.String(limitTestDefinition), RoleArn: aws.String(limitTestRole), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := sfnClient( + e, + ).DeleteStateMachine(ctx, &sfn.DeleteStateMachineInput{StateMachineArn: smARN(name("m", i))}) + + return err + }, + }, + { + name: "activities", svc: "states", quota: "L-A9562A73", + code: "ActivityLimitExceeded", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := sfnClient(e).CreateActivity(ctx, &sfn.CreateActivityInput{Name: aws.String(name("a", i))}) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := sfnClient(e).DeleteActivity(ctx, &sfn.DeleteActivityInput{ + ActivityArn: aws.String( + "arn:aws:states:us-east-1:" + quotaTestAccount + ":activity:" + name("a", i), + ), + }) + + return err + }, + }, + { + name: "state machine versions", svc: "states", quota: "L-6AFCB355", + code: "ServiceQuotaExceededException", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, _ int) error { + if err := ensureMachine(ctx, e); err != nil && quotaErrCode(err) != "StateMachineAlreadyExists" { + return err + } + + _, err := sfnClient( + e, + ).PublishStateMachineVersion(ctx, &sfn.PublishStateMachineVersionInput{StateMachineArn: smARN("base")}) + + return err + }, + }, + { + name: "state machine aliases", svc: "states", quota: "L-C1D5EBBB", + code: "ServiceQuotaExceededException", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + c := sfnClient(e) + + if err := ensureMachine(ctx, e); err != nil && quotaErrCode(err) != "StateMachineAlreadyExists" { + return err + } + + ver, err := c.PublishStateMachineVersion( + ctx, + &sfn.PublishStateMachineVersionInput{StateMachineArn: smARN("base")}, + ) + if err != nil { + return err + } + + _, err = c.CreateStateMachineAlias(ctx, &sfn.CreateStateMachineAliasInput{ + Name: aws.String(name("al", i)), + RoutingConfiguration: []sfntypes.RoutingConfigurationListItem{ + {StateMachineVersionArn: ver.StateMachineVersionArn, Weight: 100}, + }, + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := sfnClient(e).DeleteStateMachineAlias(ctx, &sfn.DeleteStateMachineAliasInput{ + StateMachineAliasArn: smARN("base:" + name("al", i)), + }) + + return err + }, + }, + } +} + +func route53Cases() []limitCase { + handler := func(*testing.T) service.Registerable { + return route53backend.NewHandler(route53backend.NewInMemoryBackend()) + } + + return []limitCase{ + { + name: "hosted zones", svc: "route53", quota: "L-4EA4796A", + code: "TooManyHostedZones", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := route53Client(e).CreateHostedZone(ctx, &route53.CreateHostedZoneInput{ + Name: aws.String(name("z", i) + ".example.com"), CallerReference: aws.String(name("c", i)), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := route53Client(e) + + zones, err := c.ListHostedZones(ctx, &route53.ListHostedZonesInput{}) + if err != nil || len(zones.HostedZones) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.DeleteHostedZone(ctx, &route53.DeleteHostedZoneInput{Id: zones.HostedZones[0].Id}) + + return err + }, + }, + { + name: "health checks", svc: "route53", quota: "L-ACB674F3", + code: "TooManyHealthChecks", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := route53Client(e).CreateHealthCheck(ctx, &route53.CreateHealthCheckInput{ + CallerReference: aws.String(name("c", i)), + HealthCheckConfig: &r53types.HealthCheckConfig{ + Type: r53types.HealthCheckTypeTcp, IPAddress: aws.String("192.0.2.1"), Port: aws.Int32(80), + }, + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := route53Client(e) + + list, err := c.ListHealthChecks(ctx, &route53.ListHealthChecksInput{}) + if err != nil || len(list.HealthChecks) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.DeleteHealthCheck( + ctx, + &route53.DeleteHealthCheckInput{HealthCheckId: list.HealthChecks[0].Id}, + ) + + return err + }, + }, + { + name: "delegation sets", svc: "route53", quota: "L-A72C7724", + code: "LimitsExceeded", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := route53Client(e).CreateReusableDelegationSet(ctx, &route53.CreateReusableDelegationSetInput{ + CallerReference: aws.String(name("c", i)), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := route53Client(e) + + list, err := c.ListReusableDelegationSets(ctx, &route53.ListReusableDelegationSetsInput{}) + if err != nil || len(list.DelegationSets) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.DeleteReusableDelegationSet( + ctx, + &route53.DeleteReusableDelegationSetInput{Id: list.DelegationSets[0].Id}, + ) + + return err + }, + }, + { + name: "traffic policies", svc: "route53", quota: "L-FC688E7C", + code: "TooManyTrafficPolicies", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := route53Client(e).CreateTrafficPolicy(ctx, &route53.CreateTrafficPolicyInput{ + Name: aws.String(name("p", i)), + Document: aws.String(limitTestTrafficPolicy), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := route53Client(e) + + list, err := c.ListTrafficPolicies(ctx, &route53.ListTrafficPoliciesInput{}) + if err != nil || len(list.TrafficPolicySummaries) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.DeleteTrafficPolicy(ctx, &route53.DeleteTrafficPolicyInput{ + Id: list.TrafficPolicySummaries[0].Id, Version: aws.Int32(1), + }) + + return err + }, + }, + { + name: "cidr collections", svc: "route53", quota: "L-AD61772F", + code: "LimitsExceeded", limit: 2, + handler: handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := route53Client(e).CreateCidrCollection(ctx, &route53.CreateCidrCollectionInput{ + Name: aws.String(name("cc", i)), CallerReference: aws.String(name("c", i)), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := route53Client(e) + + list, err := c.ListCidrCollections(ctx, &route53.ListCidrCollectionsInput{}) + if err != nil || len(list.CidrCollections) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.DeleteCidrCollection(ctx, &route53.DeleteCidrCollectionInput{Id: list.CidrCollections[0].Id}) + + return err + }, + }, + } +} + +func TestQuotaLimitsCoreServices(t *testing.T) { + t.Parallel() + + cases := slices.Concat(kmsCases(), logsAndECRCases(), eventsCases(), sfnCases(), route53Cases()) + + runLimitCases(t, cases) +} diff --git a/internal/app/service_quotas_limits_ec2_test.go b/internal/app/service_quotas_limits_ec2_test.go new file mode 100644 index 0000000000..65f1abfedf --- /dev/null +++ b/internal/app/service_quotas_limits_ec2_test.go @@ -0,0 +1,254 @@ +package app + +import ( + "context" + "errors" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" + + "github.com/blackbirdworks/gopherstack/pkgs/service" + ec2backend "github.com/blackbirdworks/gopherstack/services/ec2" +) + +func ec2Handler(*testing.T) service.Registerable { + return ec2backend.NewHandler(ec2backend.NewInMemoryBackend(quotaTestAccount, quotaTestRegion)) +} + +func ec2Client(e limitEnv) *ec2.Client { + return ec2.NewFromConfig(e.cfg, func(o *ec2.Options) { o.BaseEndpoint = e.endpoint() }) +} + +func defaultSubnet(ctx context.Context, c *ec2.Client) (*ec2types.Subnet, error) { + out, err := c.DescribeSubnets(ctx, &ec2.DescribeSubnetsInput{}) + if err != nil || len(out.Subnets) == 0 { + return nil, errors.Join(err, errNoQuotaTarget) + } + + return &out.Subnets[0], nil +} + +func ec2ByTag(name string) []ec2types.Filter { + return []ec2types.Filter{{Name: aws.String("tag:Name"), Values: []string{name}}} +} + +func ec2NameTag(rt ec2types.ResourceType, name string) []ec2types.TagSpecification { + return []ec2types.TagSpecification{{ + ResourceType: rt, Tags: []ec2types.Tag{{Key: aws.String("Name"), Value: aws.String(name)}}, + }} +} + +func routeCase() limitCase { + return limitCase{ + name: "routes per table", svc: "vpc", quota: "L-93826ACB", + code: "ResourceCountLimitExceeded", limit: 2, + handler: ec2Handler, + prepare: func(ctx context.Context, e limitEnv) error { + c := ec2Client(e) + + vpc, err := c.CreateVpc(ctx, &ec2.CreateVpcInput{ + CidrBlock: aws.String("10.77.0.0/16"), TagSpecifications: ec2NameTag(ec2types.ResourceTypeVpc, "lim"), + }) + if err != nil { + return err + } + + if _, err = c.CreateRouteTable(ctx, &ec2.CreateRouteTableInput{ + VpcId: vpc.Vpc.VpcId, TagSpecifications: ec2NameTag(ec2types.ResourceTypeRouteTable, "lim"), + }); err != nil { + return err + } + + igw, err := c.CreateInternetGateway(ctx, &ec2.CreateInternetGatewayInput{ + TagSpecifications: ec2NameTag(ec2types.ResourceTypeInternetGateway, "lim"), + }) + if err != nil { + return err + } + + _, err = c.AttachInternetGateway(ctx, &ec2.AttachInternetGatewayInput{ + InternetGatewayId: igw.InternetGateway.InternetGatewayId, VpcId: vpc.Vpc.VpcId, + }) + + return err + }, + create: func(ctx context.Context, e limitEnv, i int) error { + c := ec2Client(e) + + rt, err := c.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{Filters: ec2ByTag("lim")}) + if err != nil || len(rt.RouteTables) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + igw, err := c.DescribeInternetGateways(ctx, &ec2.DescribeInternetGatewaysInput{Filters: ec2ByTag("lim")}) + if err != nil || len(igw.InternetGateways) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.CreateRoute(ctx, &ec2.CreateRouteInput{ + RouteTableId: rt.RouteTables[0].RouteTableId, + DestinationCidrBlock: aws.String("192.168." + qnum(i) + ".0/24"), + GatewayId: igw.InternetGateways[0].InternetGatewayId, + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + rt, err := c.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{Filters: ec2ByTag("lim")}) + if err != nil || len(rt.RouteTables) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.DeleteRoute(ctx, &ec2.DeleteRouteInput{ + RouteTableId: rt.RouteTables[0].RouteTableId, DestinationCidrBlock: aws.String("192.168.0.0/24"), + }) + + return err + }, + } +} + +func ec2LimitCases() []limitCase { + return []limitCase{ + { + name: "network interfaces", svc: "vpc", quota: "L-DF5E4CA3", + code: "NetworkInterfaceLimitExceeded", limit: 2, + handler: ec2Handler, + create: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + sub, err := defaultSubnet(ctx, c) + if err != nil { + return err + } + + _, err = c.CreateNetworkInterface(ctx, &ec2.CreateNetworkInterfaceInput{SubnetId: sub.SubnetId}) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + out, err := c.DescribeNetworkInterfaces(ctx, &ec2.DescribeNetworkInterfacesInput{}) + if err != nil || len(out.NetworkInterfaces) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.DeleteNetworkInterface(ctx, &ec2.DeleteNetworkInterfaceInput{ + NetworkInterfaceId: out.NetworkInterfaces[0].NetworkInterfaceId, + }) + + return err + }, + }, + { + name: "nat gateways per zone", svc: "vpc", quota: "L-FE5A380F", + code: "NatGatewayLimitExceeded", limit: 2, + handler: ec2Handler, + create: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + sub, err := defaultSubnet(ctx, c) + if err != nil { + return err + } + + eip, err := c.AllocateAddress(ctx, &ec2.AllocateAddressInput{Domain: ec2types.DomainTypeVpc}) + if err != nil { + return err + } + + _, err = c.CreateNatGateway( + ctx, + &ec2.CreateNatGatewayInput{SubnetId: sub.SubnetId, AllocationId: eip.AllocationId}, + ) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + out, err := c.DescribeNatGateways(ctx, &ec2.DescribeNatGatewaysInput{}) + if err != nil || len(out.NatGateways) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.DeleteNatGateway( + ctx, + &ec2.DeleteNatGatewayInput{NatGatewayId: out.NatGateways[0].NatGatewayId}, + ) + + return err + }, + }, + routeCase(), + } +} + +func ec2CountCases() []countCase { + return []countCase{ + { + name: "subnets per vpc", svc: "vpc", quota: "L-407747CB", n: 1, handler: ec2Handler, + create: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + sub, err := defaultSubnet(ctx, c) + if err != nil { + return err + } + + _, err = c.CreateSubnet( + ctx, + &ec2.CreateSubnetInput{VpcId: sub.VpcId, CidrBlock: aws.String("172.31.200.0/24")}, + ) + + return err + }, + }, + { + name: "internet gateways", svc: "vpc", quota: "L-A4707A72", n: 3, handler: ec2Handler, + create: func(ctx context.Context, e limitEnv, _ int) error { + _, err := ec2Client(e).CreateInternetGateway(ctx, &ec2.CreateInternetGatewayInput{}) + + return err + }, + }, + { + name: "security groups", svc: "vpc", quota: "L-E79EC296", n: 3, handler: ec2Handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := ec2Client(e).CreateSecurityGroup(ctx, &ec2.CreateSecurityGroupInput{ + GroupName: aws.String("sg" + qnum(i)), Description: aws.String("d"), + }) + + return err + }, + }, + { + name: "on-demand standard vcpus", svc: "ec2", quota: "L-1216C47A", n: 2, step: 2, handler: ec2Handler, + create: func(ctx context.Context, e limitEnv, _ int) error { + _, err := ec2Client(e).RunInstances(ctx, &ec2.RunInstancesInput{ + ImageId: aws.String("ami-12345678"), InstanceType: ec2types.InstanceTypeM5Large, + MinCount: aws.Int32(1), MaxCount: aws.Int32(1), + }) + + return err + }, + }, + } +} + +func TestQuotaLimitsEC2(t *testing.T) { + t.Parallel() + + runLimitCases(t, ec2LimitCases()) +} + +func TestQuotaCountsEC2(t *testing.T) { + t.Parallel() + + runCountCases(t, ec2CountCases()) +} diff --git a/internal/app/service_quotas_limits_harness_test.go b/internal/app/service_quotas_limits_harness_test.go new file mode 100644 index 0000000000..2b67f0c04d --- /dev/null +++ b/internal/app/service_quotas_limits_harness_test.go @@ -0,0 +1,192 @@ +package app + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + awscfg "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/sdktest" + "github.com/blackbirdworks/gopherstack/pkgs/service" +) + +var errNoQuotaTarget = errors.New("no resource to act on") + +// limitEnv is what a limit case's create and remove functions get to call the emulated services with. +type limitEnv struct { + cfg aws.Config + url string +} + +// endpoint points one SDK client's options at the emulator; it works for every service's Options.BaseEndpoint. +func (e limitEnv) endpoint() *string { return aws.String(e.url) } + +type limitCase struct { + handler func(t *testing.T) service.Registerable + create func(ctx context.Context, e limitEnv, i int) error + remove func(ctx context.Context, e limitEnv, i int) error + prepare func(ctx context.Context, e limitEnv) error + name string + svc string + quota string + code string + limit int + // existing counts resources that exist before the case creates any. + existing int +} + +func (tc limitCase) fixedLimit() func(account, region, svc, code string) (float64, bool) { + return func(_, _, svc, code string) (float64, bool) { + return float64(tc.limit), svc == tc.svc && code == tc.quota + } +} + +func newLimitEnv(t *testing.T, tc limitCase, enforce bool) (limitEnv, *quotaUsageAdapter) { + t.Helper() + + h := tc.handler(t) + byName := map[string]service.Registerable{h.Name(): h} + adapter := newQuotaUsageAdapter(byName) + + if enforce { + enforceServiceQuotas(tc.fixedLimit(), adapter) + } + + url := sdktest.Serve(t, h) + cfg, err := awscfg.LoadDefaultConfig(t.Context(), awscfg.WithRegion("us-east-1"), + awscfg.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("test", "test", ""))) + require.NoError(t, err) + + return limitEnv{cfg: cfg, url: url}, adapter +} + +func (tc limitCase) setup(t *testing.T, e limitEnv) { + t.Helper() + + if tc.prepare != nil { + require.NoError(t, tc.prepare(t.Context(), e)) + } +} + +// countCase creates resources through the SDK and expects the quota usage to grow by exactly that many. +type countCase struct { + handler func(t *testing.T) service.Registerable + create func(ctx context.Context, e limitEnv, i int) error + name string + svc string + quota string + n int + step int +} + +func runCountCases(t *testing.T, cases []countCase) { + t.Helper() + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + lc := limitCase{handler: tc.handler, svc: tc.svc, quota: tc.quota} + e, adapter := newLimitEnv(t, lc, false) + before := lc.usage(t, adapter) + + for i := range tc.n { + require.NoError(t, tc.create(t.Context(), e, i)) + } + + step := max(tc.step, 1) + assert.InDelta(t, before+float64(tc.n*step), lc.usage(t, adapter), 0.001) + }) + } +} + +func (tc limitCase) usage(t *testing.T, a *quotaUsageAdapter) float64 { + t.Helper() + + got, ok := a.QuotaUsage(quotaTestAccount, "us-east-1", tc.svc, tc.quota) + require.True(t, ok, "%s/%s has no counter", tc.svc, tc.quota) + + return got +} + +func runLimitCases(t *testing.T, cases []limitCase) { + t.Helper() + + for _, tc := range cases { + t.Run(tc.name+" enforced", func(t *testing.T) { + t.Parallel() + + e, adapter := newLimitEnv(t, tc, true) + ctx := t.Context() + tc.setup(t, e) + + for i := range tc.limit - tc.existing { + require.NoError(t, tc.create(ctx, e, i)) + } + + assert.InDelta(t, float64(tc.limit), tc.usage(t, adapter), 0.001) + + err := tc.create(ctx, e, tc.limit) + require.Error(t, err) + assert.Equal(t, tc.code, quotaErrCode(err)) + + if tc.remove == nil { + return + } + + require.NoError(t, tc.remove(ctx, e, 0)) + require.NoError(t, tc.create(ctx, e, tc.limit)) + }) + + t.Run(tc.name+" open", func(t *testing.T) { + t.Parallel() + + e, adapter := newLimitEnv(t, tc, false) + ctx := t.Context() + tc.setup(t, e) + + for i := range tc.limit + 1 - tc.existing { + require.NoError(t, tc.create(ctx, e, i)) + } + + assert.InDelta(t, float64(tc.limit+1), tc.usage(t, adapter), 0.001) + }) + + t.Run(tc.name+" concurrent", func(t *testing.T) { + t.Parallel() + + e, _ := newLimitEnv(t, tc, true) + ctx := t.Context() + tc.setup(t, e) + + for i := range tc.limit - tc.existing - 1 { + require.NoError(t, tc.create(ctx, e, i)) + } + + var ( + won atomic.Int32 + wg sync.WaitGroup + ) + + base := tc.limit + + for i := range 6 { + wg.Go(func() { + if tc.create(ctx, e, base+i) == nil { + won.Add(1) + } + }) + } + + wg.Wait() + assert.Equal(t, int32(1), won.Load()) + }) + } +} diff --git a/internal/app/service_quotas_limits_more_test.go b/internal/app/service_quotas_limits_more_test.go new file mode 100644 index 0000000000..329ec2ec1f --- /dev/null +++ b/internal/app/service_quotas_limits_more_test.go @@ -0,0 +1,215 @@ +package app + +import ( + "context" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/autoscaling" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentity" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" + "github.com/aws/aws-sdk-go-v2/service/efs" + "github.com/aws/aws-sdk-go-v2/service/firehose" + fhtypes "github.com/aws/aws-sdk-go-v2/service/firehose/types" + + "github.com/blackbirdworks/gopherstack/pkgs/service" + asbackend "github.com/blackbirdworks/gopherstack/services/autoscaling" + cognitoidentitybackend "github.com/blackbirdworks/gopherstack/services/cognitoidentity" + cognitoidpbackend "github.com/blackbirdworks/gopherstack/services/cognitoidp" + efsbackend "github.com/blackbirdworks/gopherstack/services/efs" + firehosebackend "github.com/blackbirdworks/gopherstack/services/firehose" +) + +func moreLimitCases() []limitCase { + asHandler := func(*testing.T) service.Registerable { + return asbackend.NewHandler(asbackend.NewInMemoryBackendWithConfig(quotaTestAccount, quotaTestRegion)) + } + asClient := func(e limitEnv) *autoscaling.Client { + return autoscaling.NewFromConfig(e.cfg, func(o *autoscaling.Options) { o.BaseEndpoint = e.endpoint() }) + } + + return []limitCase{ + { + name: "auto scaling groups", svc: "autoscaling", quota: "L-CDE20ADC", + code: "LimitExceeded", limit: 2, + handler: asHandler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := asClient(e).CreateAutoScalingGroup(ctx, &autoscaling.CreateAutoScalingGroupInput{ + AutoScalingGroupName: aws.String(name("g", i)), MinSize: aws.Int32(0), MaxSize: aws.Int32(1), + AvailabilityZones: []string{"us-east-1a"}, + LaunchConfigurationName: aws.String("lc"), + }) + + return err + }, + prepare: func(ctx context.Context, e limitEnv) error { + _, err := asClient(e).CreateLaunchConfiguration(ctx, &autoscaling.CreateLaunchConfigurationInput{ + LaunchConfigurationName: aws.String("lc"), ImageId: aws.String("ami-12345678"), + InstanceType: aws.String("t3.micro"), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := asClient(e).DeleteAutoScalingGroup(ctx, &autoscaling.DeleteAutoScalingGroupInput{ + AutoScalingGroupName: aws.String(name("g", i)), + }) + + return err + }, + }, + { + name: "launch configurations", svc: "autoscaling", quota: "L-6B80B8FA", + code: "LimitExceeded", limit: 2, + handler: asHandler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := asClient(e).CreateLaunchConfiguration(ctx, &autoscaling.CreateLaunchConfigurationInput{ + LaunchConfigurationName: aws.String(name("lc", i)), ImageId: aws.String("ami-12345678"), + InstanceType: aws.String("t3.micro"), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := asClient(e).DeleteLaunchConfiguration(ctx, &autoscaling.DeleteLaunchConfigurationInput{ + LaunchConfigurationName: aws.String(name("lc", i)), + }) + + return err + }, + }, + { + name: "file systems", svc: "elasticfilesystem", quota: "L-848C634D", + code: "FileSystemLimitExceeded", limit: 2, + handler: func(*testing.T) service.Registerable { + return efsbackend.NewHandler(efsbackend.NewInMemoryBackend(quotaTestAccount, quotaTestRegion)) + }, + create: func(ctx context.Context, e limitEnv, i int) error { + c := efs.NewFromConfig(e.cfg, func(o *efs.Options) { o.BaseEndpoint = e.endpoint() }) + _, err := c.CreateFileSystem(ctx, &efs.CreateFileSystemInput{CreationToken: aws.String(name("t", i))}) + + return err + }, + }, + { + name: "delivery streams", svc: "firehose", quota: "L-14BB0BE7", + code: "LimitExceededException", limit: 2, + handler: func(*testing.T) service.Registerable { + return firehosebackend.NewHandler(firehosebackend.NewInMemoryBackend(quotaTestAccount, quotaTestRegion)) + }, + create: func(ctx context.Context, e limitEnv, i int) error { + c := firehose.NewFromConfig(e.cfg, func(o *firehose.Options) { o.BaseEndpoint = e.endpoint() }) + _, err := c.CreateDeliveryStream(ctx, &firehose.CreateDeliveryStreamInput{ + DeliveryStreamName: aws.String(name("s", i)), + ExtendedS3DestinationConfiguration: &fhtypes.ExtendedS3DestinationConfiguration{ + BucketARN: aws.String("arn:aws:s3:::b"), RoleARN: aws.String(limitTestRole), + }, + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + c := firehose.NewFromConfig(e.cfg, func(o *firehose.Options) { o.BaseEndpoint = e.endpoint() }) + _, err := c.DeleteDeliveryStream( + ctx, + &firehose.DeleteDeliveryStreamInput{DeliveryStreamName: aws.String(name("s", i))}, + ) + + return err + }, + }, + { + name: "identity pools", svc: "cognito-identity", quota: "L-8692CE1C", + code: "LimitExceededException", limit: 2, + handler: func(*testing.T) service.Registerable { + return cognitoidentitybackend.NewHandler( + cognitoidentitybackend.NewInMemoryBackend(quotaTestAccount, quotaTestRegion), quotaTestRegion) + }, + create: func(ctx context.Context, e limitEnv, i int) error { + c := cognitoidentity.NewFromConfig( + e.cfg, + func(o *cognitoidentity.Options) { o.BaseEndpoint = e.endpoint() }, + ) + _, err := c.CreateIdentityPool(ctx, &cognitoidentity.CreateIdentityPoolInput{ + IdentityPoolName: aws.String(name("p", i)), AllowUnauthenticatedIdentities: true, + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := cognitoidentity.NewFromConfig( + e.cfg, + func(o *cognitoidentity.Options) { o.BaseEndpoint = e.endpoint() }, + ) + + list, err := c.ListIdentityPools( + ctx, + &cognitoidentity.ListIdentityPoolsInput{MaxResults: aws.Int32(10)}, + ) + if err != nil { + return err + } + + _, err = c.DeleteIdentityPool( + ctx, + &cognitoidentity.DeleteIdentityPoolInput{IdentityPoolId: list.IdentityPools[0].IdentityPoolId}, + ) + + return err + }, + }, + { + name: "user pools", svc: "cognito-idp", quota: "L-66E6DF30", + code: "LimitExceededException", limit: 2, + handler: func(*testing.T) service.Registerable { + return cognitoidpbackend.NewHandler( + cognitoidpbackend.NewInMemoryBackend( + quotaTestAccount, + quotaTestRegion, + "http://localhost", + ), + quotaTestRegion, + ) + }, + create: func(ctx context.Context, e limitEnv, i int) error { + c := cognitoidentityprovider.NewFromConfig( + e.cfg, + func(o *cognitoidentityprovider.Options) { o.BaseEndpoint = e.endpoint() }, + ) + _, err := c.CreateUserPool( + ctx, + &cognitoidentityprovider.CreateUserPoolInput{PoolName: aws.String(name("u", i))}, + ) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := cognitoidentityprovider.NewFromConfig( + e.cfg, + func(o *cognitoidentityprovider.Options) { o.BaseEndpoint = e.endpoint() }, + ) + + list, err := c.ListUserPools( + ctx, + &cognitoidentityprovider.ListUserPoolsInput{MaxResults: aws.Int32(10)}, + ) + if err != nil { + return err + } + + _, err = c.DeleteUserPool( + ctx, + &cognitoidentityprovider.DeleteUserPoolInput{UserPoolId: list.UserPools[0].Id}, + ) + + return err + }, + }, + } +} + +func TestQuotaLimitsMoreServices(t *testing.T) { + t.Parallel() + + runLimitCases(t, moreLimitCases()) +} diff --git a/internal/app/service_quotas_wiring.go b/internal/app/service_quotas_wiring.go index 7f686bd988..c0d2d3cb96 100644 --- a/internal/app/service_quotas_wiring.go +++ b/internal/app/service_quotas_wiring.go @@ -19,6 +19,8 @@ import ( snsbackend "github.com/blackbirdworks/gopherstack/services/sns" ) +type quotaLimited interface{ SetQuotaLimiter(f quotalimit.Func) } + type quotaCounter func(a *quotaUsageAdapter, account, region string) (int, bool) // quotaCounters maps "service/quota" to the live resource count behind it. @@ -77,6 +79,8 @@ var quotaCounters = map[string]quotaCounter{ //nolint:gochecknoglobals // immuta }, } +var extraQuotaCounters = serviceQuotaCounters() //nolint:gochecknoglobals // immutable dispatch table + type iamKind int const ( @@ -99,11 +103,17 @@ type quotaUsageAdapter struct { cfn *cfnbackend.Handler elb *elbbackend.InMemoryBackend elbv2 *elbv2backend.Handler + + byName map[string]service.Registerable } // QuotaUsage implements servicequotas.UsageSource. func (a *quotaUsageAdapter) QuotaUsage(account, region, serviceCode, quotaCode string) (float64, bool) { count, ok := quotaCounters[serviceCode+"/"+quotaCode] + if !ok { + count, ok = extraQuotaCounters[serviceCode+"/"+quotaCode] + } + if !ok { return 0, false } @@ -197,7 +207,7 @@ func (n quotaSNSNotifier) Notify(ctx context.Context, topicArn, subject, message } func newQuotaUsageAdapter(byName map[string]service.Registerable) *quotaUsageAdapter { - a := "aUsageAdapter{} + a := "aUsageAdapter{byName: byName} if h, ok := byName["S3"].(*s3backend.S3Handler); ok { a.s3, _ = h.Backend.(*s3backend.InMemoryBackend) @@ -272,19 +282,13 @@ func enforceServiceQuotas(limit quotalimit.Func, a *quotaUsageAdapter) { a.eks.SetQuotaLimiter(limit) } - if a.rds != nil { - a.rds.SetQuotaLimiter(limit) - } - - if a.cfn != nil { - a.cfn.SetQuotaLimiter(limit) - } - - if a.elbv2 != nil { - a.elbv2.SetQuotaLimiter(limit) - } - if a.elb != nil { a.elb.SetQuotaLimiter(limit) } + + for _, r := range a.byName { + if q, ok := r.(quotaLimited); ok { + q.SetQuotaLimiter(limit) + } + } } diff --git a/internal/app/testdata/service_quota_classes.json b/internal/app/testdata/service_quota_classes.json new file mode 100644 index 0000000000..caab9a60b2 --- /dev/null +++ b/internal/app/testdata/service_quota_classes.json @@ -0,0 +1,5490 @@ +{ + "AWSCloudMap": { + "quotas": { + "L-0BA10AAE": "r", + "L-0FE3F50E": "e", + "L-514A639A": "r", + "L-76CF203B": "r", + "L-D95E8A57": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "access-analyzer": { + "quotas": { + "L-1E51937C": "e", + "L-6F85FE0C": "e", + "L-8750DAE0": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "acm": { + "quotas": { + "L-08DCE28B": "r", + "L-12943EEB": "r", + "L-183E8F71": "r", + "L-201D91CA": "r", + "L-24E5E876": "r", + "L-25850AC5": "r", + "L-2F0B3882": "r", + "L-3808DC70": "r", + "L-4C8B8B5F": "r", + "L-535A8003": "r", + "L-62A479C6": "r", + "L-67CE8F15": "r", + "L-69D109B1": "e", + "L-74BB4A99": "r", + "L-84FDD27E": "r", + "L-8849A1A8": "r", + "L-8976373F": "r", + "L-8E212782": "e", + "L-8F907C16": "r", + "L-A1BB525F": "r", + "L-A25FF1B0": "r", + "L-A7230D7D": "r", + "L-A7EF109F": "r", + "L-B54E258B": "r", + "L-B8583BD1": "r", + "L-B97889A6": "r", + "L-C1B13B11": "r", + "L-C71B9553": "r", + "L-CF670426": "r", + "L-D0E9B342": "r", + "L-D2CB7DE9": "e", + "L-DA1D8B98": "r", + "L-DD60D132": "r", + "L-E5BD64C4": "r", + "L-E6DBDBE9": "r", + "L-E8DE0414": "r", + "L-E9B74925": "e", + "L-E9F88106": "r", + "L-EF1F514F": "r", + "L-F141DD1D": "e", + "L-FB94F0B0": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "acm-pca": { + "quotas": { + "L-1725E639": "r", + "L-799883CD": "e", + "L-CAFB4993": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "airflow": { + "quotas": { + "L-4BA0CB82": "e", + "L-52DCDA32": "e", + "L-67D41C6B": "e", + "L-78AC1883": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "amplify": { + "quotas": { + "L-1BED97F3": "e", + "L-2A8ABB91": "r", + "L-4113FC04": "e", + "L-AD277529": "e", + "L-CE88B60E": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "apigateway": { + "quotas": { + "L-01C8A9E0": "e", + "L-05295E0B": "e", + "L-154598D1": "e", + "L-24E7E662": "e", + "L-379E48B0": "e", + "L-4D98A8A5": "e", + "L-608BDCD4": "e", + "L-65B5C802": "e", + "L-668C9B28": "e", + "L-68B79FF0": "e", + "L-824C9E42": "e", + "L-8A5B8E43": "r", + "L-8B81B02C": "s", + "L-985EB478": "e", + "L-9ED1E49A": "r", + "L-A4C7274F": "e", + "L-A93447B8": "e", + "L-A9DBC573": "r", + "L-E5AE38E3": "s", + "L-E8693075": "e", + "L-F8BD84D3": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "appconfig": { + "quotas": { + "L-08D2C632": "e", + "L-48F9B951": "s", + "L-A52E46BE": "e", + "L-A5FC0339": "s", + "L-B858C085": "e", + "L-EEB0151E": "e", + "L-F59D302B": "e", + "L-FA210A1F": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "application-autoscaling": { + "quotas": { + "L-17D5F681": "e", + "L-1A11EB4B": "e", + "L-1AAF0700": "e", + "L-297D9EC9": "e", + "L-4A11ECEB": "e", + "L-60E4E5E2": "e", + "L-782A3EE2": "e", + "L-799ACCDF": "e", + "L-800F6F7B": "e", + "L-8998F403": "e", + "L-9C25247C": "e", + "L-A1D42901": "e", + "L-A2AD6458": "e", + "L-D75CA9D2": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "appmesh": { + "quotas": { + "L-33E8F9C9": "e", + "L-50F6C35A": "e", + "L-606A910B": "e", + "L-87E74146": "e", + "L-AC861A39": "e", + "L-BB90B7FF": "e", + "L-DA7495A7": "e", + "L-E043DFB4": "e", + "L-F6F26D09": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "apprunner": { + "quotas": { + "L-1BDBAAB6": "e", + "L-1D8C5BDD": "e", + "L-69F96A0C": "e", + "L-A0B46A0C": "e", + "L-F7ADEB8C": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "appsync": { + "quotas": { + "L-10498098": "r", + "L-27770490": "r", + "L-39784425": "e", + "L-3B7F188C": "e", + "L-4DFA3D2F": "e", + "L-51A37BC6": "e", + "L-5DE70651": "r", + "L-A1B022A0": "r", + "L-AA33EB36": "e", + "L-C01DB6E6": "r", + "L-D19E6EC4": "e", + "L-D91E563A": "r", + "L-F643C244": "r", + "L-FC5E46D0": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "aps": { + "quotas": { + "L-0F151AA2": "e", + "L-2C2449DB": "e", + "L-3D15CDB4": "e", + "L-4340E931": "r", + "L-46D5E194": "e", + "L-5A151448": "e", + "L-719BEE64": "s", + "L-81B61A4A": "r", + "L-8491EB93": "r", + "L-8873DB23": "e", + "L-8DEDEE8E": "s", + "L-BDF9895D": "s", + "L-C15FCA36": "e", + "L-CDA4AB0F": "e", + "L-D5FD0534": "r", + "L-E3E60B3E": "e", + "L-E8D7B0D8": "r", + "L-E9CD1A4F": "e", + "L-EDA8C93C": "e", + "L-F4BCE0BA": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "athena": { + "quotas": { + "L-076245C0": "r", + "L-07F4444F": "r", + "L-3CE0BBA0": "e", + "L-41075247": "r", + "L-4FF11DD3": "r", + "L-52EFA794": "r", + "L-70FD91F7": "r", + "L-76AFE6F2": "r", + "L-82E47245": "r", + "L-9D86AA19": "r", + "L-D0D8C912": "r", + "L-E20AD6B8": "e", + "L-E80DC288": "s", + "L-EFB619E3": "r", + "L-FC5F6546": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "autoscaling": { + "quotas": { + "L-6B80B8FA": "c", + "L-CDE20ADC": "c" + } + }, + "backup": { + "quotas": { + "L-514878B6": "e", + "L-7705D2CB": "e", + "L-9122A82F": "e", + "L-B4021FB0": "e", + "L-BD69F607": "e", + "L-C0A8C14B": "e", + "L-C296F1F5": "e", + "L-E43E0ED6": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "bedrock": { + "quotas": { + "L-00F9DD5C": "s", + "L-00FF3314": "r", + "L-01A2DC4B": "e", + "L-01F37E14": "e", + "L-01F3CD81": "r", + "L-02D6293C": "s", + "L-02DFBB76": "r", + "L-031F46A7": "e", + "L-039AF68B": "r", + "L-059C1AAB": "e", + "L-06B03968": "r", + "L-072E11FC": "e", + "L-07844084": "e", + "L-07D3BCF0": "e", + "L-07D73971": "r", + "L-08036ECB": "r", + "L-086556D1": "r", + "L-090C78B9": "e", + "L-091EBF74": "e", + "L-0AD9BBE8": "r", + "L-0B2687F4": "r", + "L-0B66D421": "e", + "L-0CB120A9": "r", + "L-0D1F6A84": "e", + "L-0D70E8DA": "e", + "L-0E7AA8B7": "r", + "L-0ED8E85F": "e", + "L-0F2A24D7": "e", + "L-0F2ECB41": "r", + "L-0F6BA833": "r", + "L-102A1657": "r", + "L-1074C53D": "e", + "L-10F69CA1": "e", + "L-114ABFC3": "e", + "L-11C1CE94": "e", + "L-11DFF789": "r", + "L-121F4E1E": "e", + "L-124DCF3D": "r", + "L-127FC9D0": "s", + "L-12E68701": "e", + "L-13143995": "e", + "L-131D4EED": "e", + "L-135AE4B7": "e", + "L-137DD3C2": "r", + "L-1401504A": "e", + "L-142AED8F": "e", + "L-14A16430": "e", + "L-1570CF9E": "e", + "L-1579B4CD": "r", + "L-15830237": "r", + "L-15B51EC1": "e", + "L-15B8E632": "r", + "L-15CD18AC": "r", + "L-16711FC4": "e", + "L-1679CB40": "e", + "L-16941C66": "e", + "L-169A395B": "e", + "L-16E25672": "e", + "L-1870BD3C": "e", + "L-196A63C0": "e", + "L-1AC1CABC": "e", + "L-1AD2F2A2": "e", + "L-1BD3E8A2": "r", + "L-1C19AAE8": "e", + "L-1D2360E7": "e", + "L-1E2B9998": "e", + "L-1EF80F3E": "e", + "L-1F644C2A": "e", + "L-1F7657F1": "e", + "L-1F7ACACC": "e", + "L-1F923A43": "e", + "L-208A3F5C": "e", + "L-214BEB81": "e", + "L-21800074": "r", + "L-21EE8B55": "e", + "L-220B8A25": "e", + "L-23CF4444": "e", + "L-240F3183": "e", + "L-2438ED67": "r", + "L-250F1B4E": "r", + "L-2555C05B": "r", + "L-2590C31B": "e", + "L-259C746F": "e", + "L-268D592E": "e", + "L-273728E2": "e", + "L-274AA31F": "e", + "L-2767B9A9": "e", + "L-27989F42": "r", + "L-27C57EE8": "r", + "L-28258E5D": "e", + "L-28612175": "e", + "L-29BDACF9": "e", + "L-2A53927F": "r", + "L-2AD735F5": "r", + "L-2B5A3FA2": "r", + "L-2BB94F7C": "r", + "L-2D9A4D75": "e", + "L-2EBEF050": "e", + "L-3030E098": "e", + "L-315A9D5B": "r", + "L-31615887": "r", + "L-31AB82D0": "r", + "L-320BE465": "e", + "L-32F732DE": "e", + "L-34152C1D": "r", + "L-345B029F": "r", + "L-34C933D1": "e", + "L-35900968": "e", + "L-3632DE15": "e", + "L-37491D63": "r", + "L-37A44E24": "e", + "L-38EB0A61": "r", + "L-38EFD889": "e", + "L-391478D2": "e", + "L-391CEF89": "e", + "L-392F9C48": "s", + "L-3ABF6ACC": "r", + "L-3B60C1ED": "s", + "L-3B82104D": "e", + "L-3BD2251E": "e", + "L-3BE61D60": "e", + "L-3C5D1B25": "e", + "L-3CCB3548": "e", + "L-3CD2AF6F": "r", + "L-3DCCFAA4": "r", + "L-3DD46812": "r", + "L-3E961CAB": "r", + "L-3F0ECEDC": "e", + "L-3FE71326": "r", + "L-4064C85B": "r", + "L-40EC9882": "e", + "L-430C95DD": "e", + "L-437802FD": "s", + "L-43CD2FD9": "e", + "L-442924EC": "r", + "L-4532261E": "s", + "L-45B04988": "e", + "L-46EFABBA": "e", + "L-47520EB7": "r", + "L-478319B0": "e", + "L-479B647F": "r", + "L-4821684D": "e", + "L-48C95F85": "e", + "L-48DD3868": "e", + "L-495BEDE3": "r", + "L-4A0EAD70": "r", + "L-4A544964": "r", + "L-4A6BFAB1": "r", + "L-4A6D2F15": "e", + "L-4A832410": "e", + "L-4B26E44A": "r", + "L-4B3B250B": "r", + "L-4B4330A0": "e", + "L-4B9F76B0": "r", + "L-4BF37C17": "r", + "L-4C3F0FE6": "r", + "L-4D2272DC": "e", + "L-4D7537CF": "r", + "L-4DBDD5C9": "r", + "L-4DFF050E": "e", + "L-4E7DDF49": "e", + "L-4E7EE0B5": "e", + "L-4FCE27C7": "r", + "L-5056051A": "e", + "L-50CC5674": "r", + "L-50CC95A8": "e", + "L-51B0DEE7": "e", + "L-51CDA0E1": "r", + "L-51FF35D5": "r", + "L-526E1ECE": "r", + "L-5325EC5D": "e", + "L-532E6630": "r", + "L-53A144CD": "r", + "L-53B814D7": "e", + "L-54814DC6": "r", + "L-54FAADA6": "r", + "L-55F225F6": "e", + "L-564C017C": "e", + "L-574688BD": "r", + "L-5755FAB6": "r", + "L-57DC56A1": "e", + "L-58424D95": "r", + "L-58BE175A": "r", + "L-5A222661": "e", + "L-5A51050A": "e", + "L-5AB0EE48": "e", + "L-5BA88337": "e", + "L-5D367E5C": "e", + "L-5DAAE567": "e", + "L-5DAEA81C": "r", + "L-5DB28B7B": "r", + "L-5DD391B1": "r", + "L-5DF13F64": "r", + "L-5E29F315": "e", + "L-5E3E0013": "e", + "L-5E8692C5": "r", + "L-612AE448": "r", + "L-62E2A345": "e", + "L-63010E1B": "e", + "L-63020993": "e", + "L-6326A422": "r", + "L-63EC9D04": "e", + "L-6473F1D2": "r", + "L-64CF3679": "e", + "L-654787A4": "e", + "L-65D1D550": "e", + "L-67BD0D49": "e", + "L-68AE6C02": "e", + "L-697D688A": "e", + "L-69AC41C2": "e", + "L-6B2DA87E": "e", + "L-6B3D3DE4": "r", + "L-6B796A8E": "r", + "L-6CE4B557": "r", + "L-6D88F00E": "e", + "L-6E046197": "r", + "L-6E888CC2": "r", + "L-6EBFEB27": "e", + "L-6FAB43BE": "e", + "L-7007E9C9": "r", + "L-7089DC7D": "r", + "L-70AC14D9": "r", + "L-70B8359C": "e", + "L-70FC4C0E": "e", + "L-71A1F0FA": "e", + "L-71C69B70": "r", + "L-7334E629": "r", + "L-73573F44": "e", + "L-73951D97": "e", + "L-73BBA086": "e", + "L-7478F443": "e", + "L-749C38BD": "r", + "L-75A18A04": "e", + "L-78B4AF01": "e", + "L-78C12D54": "e", + "L-79BA683B": "e", + "L-7A8639EE": "e", + "L-7ABD27EC": "r", + "L-7B9A79C8": "e", + "L-7BE9625C": "e", + "L-7BEE40FB": "r", + "L-7C1813A6": "e", + "L-7C42E72A": "r", + "L-7C435546": "e", + "L-7D9F04A9": "r", + "L-7DCA4380": "e", + "L-7EAC9E78": "e", + "L-7F2C6F33": "e", + "L-8076814C": "e", + "L-811E997F": "e", + "L-8129BF10": "e", + "L-81E26054": "e", + "L-82EE9228": "e", + "L-8528F119": "r", + "L-852FB779": "e", + "L-8574D065": "e", + "L-864449ED": "e", + "L-8651ED26": "e", + "L-87594EB7": "r", + "L-87934C8F": "e", + "L-884C068A": "r", + "L-88DE0CAC": "e", + "L-89117837": "e", + "L-89197AE6": "e", + "L-895C7A6C": "r", + "L-897F8151": "e", + "L-89923E2C": "e", + "L-8A232422": "e", + "L-8A361B65": "e", + "L-8A643E07": "r", + "L-8A686BB7": "r", + "L-8B289D99": "r", + "L-8C5F762B": "r", + "L-8CBCC2C0": "r", + "L-8CC57EDA": "e", + "L-8CE8B022": "e", + "L-8D07E980": "e", + "L-8E752C84": "r", + "L-8EA73537": "r", + "L-8FD128CF": "r", + "L-901932B9": "r", + "L-9072D6F0": "r", + "L-90807536": "e", + "L-90DFE70F": "r", + "L-90E3E748": "r", + "L-9149A536": "e", + "L-91554672": "e", + "L-916C9264": "e", + "L-91E3DBE2": "e", + "L-921A310E": "e", + "L-92349F9F": "e", + "L-92E68994": "r", + "L-92E7FE32": "e", + "L-92F8A601": "e", + "L-9335BC45": "e", + "L-9342B636": "e", + "L-94A31E46": "r", + "L-95CACD43": "e", + "L-95CB8E2F": "e", + "L-962E1C58": "e", + "L-9782749C": "r", + "L-97A8CC77": "e", + "L-97D79C54": "e", + "L-9807BAA2": "r", + "L-982DE2DB": "e", + "L-990A2394": "e", + "L-9913DEEF": "r", + "L-99296DCD": "r", + "L-99471E7A": "r", + "L-99936FBF": "r", + "L-9A11C666": "r", + "L-9AA02BEF": "e", + "L-9B17C979": "r", + "L-9B258944": "r", + "L-9B651738": "e", + "L-9B9B20DB": "r", + "L-9C8C5911": "s", + "L-9D3DC9B2": "r", + "L-9D7C8A75": "r", + "L-9E38DD81": "e", + "L-9E3C255A": "r", + "L-9EDE6039": "e", + "L-9EF11C18": "e", + "L-9EF56DA1": "r", + "L-9F4DB459": "r", + "L-A02F87EC": "e", + "L-A0300844": "e", + "L-A052927A": "r", + "L-A0AAB785": "e", + "L-A103A344": "r", + "L-A32874E8": "r", + "L-A3425ABD": "r", + "L-A4430697": "r", + "L-A4EBFDE7": "e", + "L-A4F73742": "r", + "L-A63633C5": "e", + "L-A88E7250": "s", + "L-A94DA744": "e", + "L-A985813D": "e", + "L-A986092E": "e", + "L-AA411D03": "e", + "L-AA7FE948": "r", + "L-AAC5F6D6": "e", + "L-AB39D760": "r", + "L-AC096F71": "s", + "L-AC6F8476": "e", + "L-ADA98D8D": "e", + "L-AE040A57": "e", + "L-AE136EE5": "e", + "L-AF2A00BD": "e", + "L-AFD14A53": "r", + "L-AFE8E0CD": "e", + "L-B0F56DCF": "e", + "L-B1E11F5B": "e", + "L-B1E4F57A": "e", + "L-B3049E9B": "e", + "L-B370112A": "e", + "L-B38B530A": "r", + "L-B3C19043": "e", + "L-B46DD052": "e", + "L-B49AA29C": "e", + "L-B4B995D8": "e", + "L-B547321D": "e", + "L-B5C023CA": "r", + "L-B783C50B": "e", + "L-B7BF1255": "r", + "L-B8626674": "e", + "L-B90A0AF2": "s", + "L-BA72E406": "e", + "L-BAE2EB93": "e", + "L-BB255931": "e", + "L-BB313AA3": "e", + "L-BC23C04E": "r", + "L-BC3096B9": "r", + "L-BC9ED53F": "e", + "L-BD9FDA6F": "r", + "L-BDD176EF": "r", + "L-BE77399C": "r", + "L-BEE3FA31": "s", + "L-BF9B3702": "e", + "L-BFA0FE84": "e", + "L-C02E1E99": "e", + "L-C0326783": "r", + "L-C05EB25B": "e", + "L-C07B5EA2": "r", + "L-C0BA182F": "s", + "L-C0CACF50": "e", + "L-C0D53EFB": "r", + "L-C19807B8": "e", + "L-C2E494BA": "r", + "L-C2FA9AEC": "e", + "L-C39B6D57": "e", + "L-C4522D0D": "e", + "L-C4659D61": "e", + "L-C540484E": "e", + "L-C549AE85": "e", + "L-C587712D": "r", + "L-C5913DD6": "r", + "L-C593EA7C": "r", + "L-C6AAFCD0": "e", + "L-C6F5908D": "r", + "L-CA80888F": "e", + "L-CABD464E": "r", + "L-CB5B847D": "e", + "L-CC3FC244": "r", + "L-CCA5DF70": "r", + "L-CCC92354": "r", + "L-CD4E1CD6": "e", + "L-CDD9DC4A": "e", + "L-CDF99FD2": "e", + "L-CEEE0EE8": "e", + "L-CFCAAB0E": "r", + "L-D06938E7": "r", + "L-D1151D45": "e", + "L-D13C968B": "e", + "L-D1C9F3B9": "e", + "L-D30E6B4B": "e", + "L-D321719B": "e", + "L-D3D1200C": "e", + "L-D3E17A13": "e", + "L-D41E62E4": "e", + "L-D44E1D4E": "r", + "L-D4FBCF4E": "r", + "L-D56DF585": "e", + "L-D5F39C2F": "r", + "L-D67748AD": "r", + "L-D682535A": "e", + "L-D73B1244": "r", + "L-D8E451A7": "e", + "L-D94ECE3B": "r", + "L-D983F7C0": "r", + "L-D9E467C0": "e", + "L-DB84CE56": "r", + "L-DB99DCDB": "r", + "L-DBFC8DC8": "e", + "L-DC465F65": "e", + "L-DC7FF66C": "r", + "L-DCADBC78": "r", + "L-DCD79770": "r", + "L-DD0273B7": "s", + "L-DD7903AD": "e", + "L-DD84E5CA": "r", + "L-DE3FBBF4": "r", + "L-DE84A1A0": "e", + "L-DEE3A9C7": "e", + "L-DF09248F": "r", + "L-DF5FF3C8": "e", + "L-DFE5A893": "e", + "L-E038D932": "e", + "L-E0B2EE2A": "s", + "L-E1D21B18": "e", + "L-E293C7C7": "e", + "L-E2ED42E6": "e", + "L-E3C70889": "r", + "L-E3C8B9C9": "e", + "L-E453CCF3": "e", + "L-E455959C": "e", + "L-E48B7984": "s", + "L-E5084BBA": "r", + "L-E5197E26": "r", + "L-E5FD5C04": "e", + "L-E6489B37": "e", + "L-E83AC604": "e", + "L-E8940935": "r", + "L-E93C745B": "e", + "L-E953E4AB": "e", + "L-EA6F6B5F": "e", + "L-EA764586": "e", + "L-EA873E18": "e", + "L-EAD257E4": "r", + "L-EAFCD549": "e", + "L-EBB72C32": "e", + "L-EC6A6ABC": "e", + "L-EC77BD96": "e", + "L-ECA45411": "e", + "L-ECCE76C6": "e", + "L-ECD87E6C": "e", + "L-EDC225D2": "r", + "L-EDE20AF1": "e", + "L-EEE88DB2": "e", + "L-EF415EF6": "e", + "L-EF804815": "e", + "L-F02D918A": "e", + "L-F0AF140A": "r", + "L-F15FCC01": "e", + "L-F1613626": "e", + "L-F20FBC17": "r", + "L-F2107865": "e", + "L-F225D073": "e", + "L-F241D033": "r", + "L-F2469446": "e", + "L-F26CA8D1": "r", + "L-F2DCFA42": "r", + "L-F2E6F90D": "e", + "L-F30EAB98": "e", + "L-F361DF0F": "e", + "L-F424A1E3": "e", + "L-F4DDD3EB": "r", + "L-F5ACA0A6": "r", + "L-F6E116D7": "r", + "L-F7440010": "e", + "L-F77743B5": "e", + "L-F86AE9DD": "r", + "L-F879F645": "e", + "L-F8B0126D": "s", + "L-FA06C205": "e", + "L-FABEE48F": "e", + "L-FB43CE55": "e", + "L-FD4A6FF9": "e", + "L-FD509977": "e", + "L-FD7B3EB8": "e", + "L-FDE45816": "e", + "L-FE086D36": "e", + "L-FE130012": "e", + "L-FE24F76E": "e", + "L-FE44174A": "r", + "L-FF1F238B": "r", + "L-FF73AE42": "e", + "L-FF8B4E28": "r", + "L-FFFEDD8D": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "ce": { + "quotas": { + "L-3B4FC070": "e", + "L-563A19D7": "e", + "L-FE0E51D7": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "cleanrooms": { + "quotas": { + "L-08F7F01C": "e", + "L-093F1424": "r", + "L-0A3E7551": "r", + "L-0AD7EAD3": "r", + "L-0FB3F147": "r", + "L-133DD466": "r", + "L-14E81699": "e", + "L-18630DF3": "r", + "L-1BCDF035": "r", + "L-1F2FB8F2": "r", + "L-207110E9": "r", + "L-2222C6AC": "e", + "L-23D4B294": "r", + "L-25AC34A7": "e", + "L-26B93E43": "r", + "L-2BCA0376": "r", + "L-2F999FD7": "r", + "L-314AA705": "r", + "L-3159A189": "r", + "L-339A44FE": "r", + "L-37644F21": "r", + "L-39FE5CA0": "r", + "L-3CFEE53C": "r", + "L-40165B7B": "r", + "L-422E468C": "r", + "L-43C36E0F": "r", + "L-43DCB767": "r", + "L-44815395": "r", + "L-4596E0C1": "e", + "L-4678811D": "r", + "L-46ADBA29": "r", + "L-47C1561A": "r", + "L-4EFF30C3": "r", + "L-4FA6F2CA": "r", + "L-51EC588A": "r", + "L-53CCCC3A": "r", + "L-57B36CC8": "r", + "L-58076094": "r", + "L-59F4710C": "r", + "L-5B356E2B": "r", + "L-5D65AE8D": "r", + "L-5EDF6508": "r", + "L-60AA2A10": "r", + "L-60C9F5C8": "r", + "L-6359BE00": "e", + "L-659B47CC": "r", + "L-6CE5FF0C": "r", + "L-6EE33BE8": "r", + "L-6FE25843": "e", + "L-6FF866CD": "r", + "L-71F0D659": "r", + "L-73071115": "r", + "L-75B5199D": "r", + "L-7CEACCA0": "e", + "L-804ACCF8": "r", + "L-80DB73D7": "r", + "L-82F4A89C": "r", + "L-844B7ECC": "r", + "L-84D87AAE": "r", + "L-88914C24": "r", + "L-8B32F74B": "r", + "L-8C954508": "r", + "L-8CF613B7": "r", + "L-8EADB354": "r", + "L-971686CB": "r", + "L-978BC400": "r", + "L-98713D84": "r", + "L-98BDB219": "r", + "L-99A163CB": "e", + "L-9FC85564": "r", + "L-AA1FCC92": "r", + "L-AA83E042": "r", + "L-AF88CE55": "e", + "L-B45D79BC": "r", + "L-BA5CF250": "r", + "L-BAAD82E2": "r", + "L-BC5338D1": "r", + "L-C0D69AA0": "r", + "L-C176B0B6": "r", + "L-C21604A2": "r", + "L-C36D988B": "r", + "L-C3A930AB": "r", + "L-C5494CAA": "r", + "L-CDE3C47C": "r", + "L-CEBF94E4": "r", + "L-D04BF025": "e", + "L-D269978F": "r", + "L-D29A24D7": "r", + "L-D3626550": "r", + "L-D3DE47CF": "r", + "L-D4ACC820": "r", + "L-D90468BB": "r", + "L-DA8821F5": "r", + "L-DB68AF19": "r", + "L-DBDCEC0D": "e", + "L-DDC82272": "r", + "L-DF39885E": "r", + "L-DF3C63EF": "r", + "L-DF77CB1F": "r", + "L-E555FCAB": "r", + "L-E95B9B79": "r", + "L-EA789CE8": "r", + "L-ED22C809": "r", + "L-F0A87380": "r", + "L-F40A73B7": "e", + "L-F434A8C7": "r", + "L-F60C2030": "e", + "L-F7B26AF5": "e", + "L-F84196BB": "r", + "L-FA0B0432": "r", + "L-FB77D69E": "r", + "L-FD7BEEA1": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "cloudformation": { + "quotas": { + "L-0485CB21": "c", + "L-6A4B2F69": "r", + "L-7E146E2E": "e", + "L-9DE8E4FB": "e", + "L-9DE9F29D": "e", + "L-C8225BA5": "e", + "L-DCC58E6D": "e", + "L-EA1018E8": "e", + "L-EC62D81A": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "cloudfront": { + "quotas": { + "L-061D6ADD": "e", + "L-08884E5C": "e", + "L-0AB8CD5F": "e", + "L-0F1E9017": "r", + "L-1685304C": "e", + "L-1B2BD627": "e", + "L-20E1C672": "e", + "L-24B04930": "e", + "L-3FC44142": "e", + "L-4024A45A": "e", + "L-435C8433": "e", + "L-4B3F61D0": "e", + "L-4C99C1B4": "e", + "L-50C9D326": "e", + "L-5336F3E6": "e", + "L-584BB4D4": "e", + "L-59F2769C": "s", + "L-68CBA03E": "e", + "L-6A19EDFD": "e", + "L-6CCE0F1E": "e", + "L-7429AF8A": "s", + "L-779C7A0B": "e", + "L-7D134442": "e", + "L-7E654D79": "e", + "L-7EA57369": "e", + "L-8AB980CD": "e", + "L-8FE99263": "e", + "L-9D26CF6B": "e", + "L-9EBD26CA": "e", + "L-A2C80159": "r", + "L-A53701DE": "e", + "L-AAD4943E": "e", + "L-AECE9FA7": "s", + "L-B4048FB4": "e", + "L-B41C610F": "e", + "L-BE7788E4": "r", + "L-BEBABC60": "e", + "L-C19110C4": "e", + "L-C3659C43": "e", + "L-C57D59CB": "e", + "L-C646B44B": "e", + "L-CF0D4FC5": "e", + "L-D0422299": "e", + "L-D0C8D03A": "e", + "L-D2BD2B16": "e", + "L-D64DA6E2": "e", + "L-DA9DCC93": "r", + "L-E47A582D": "e", + "L-E55DEA80": "s", + "L-E7E9ACEB": "e", + "L-E9944CCE": "s", + "L-F432D044": "e", + "L-F5C19F1B": "e", + "L-F5EED448": "e", + "L-F6F30A7D": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "cloudhsm": { + "quotas": { + "L-4B16B391": "e", + "L-95BA35D1": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "codeartifact": { + "quotas": { + "L-0B362111": "r", + "L-3072382D": "r", + "L-308A4050": "r", + "L-3E27C79F": "r", + "L-6010CAF9": "r", + "L-6C12FB34": "r", + "L-86608C96": "e", + "L-A649E766": "r", + "L-AA0DC56D": "s", + "L-CBBCDF5C": "r", + "L-DD7208D3": "e", + "L-F39CF68A": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "codebuild": { + "quotas": { + "L-0397D009": "r", + "L-03FBB1ED": "r", + "L-049948E0": "r", + "L-04E5CA62": "r", + "L-0544DB6A": "r", + "L-0DED26C7": "r", + "L-1DFDD5F9": "r", + "L-1E43FDE0": "r", + "L-2C3490D7": "r", + "L-2DC20C30": "r", + "L-36AF3CA5": "r", + "L-39DB2B0B": "r", + "L-4135EDF8": "r", + "L-4DDC4A99": "r", + "L-546A802A": "r", + "L-596BEAB4": "r", + "L-5ED1D25B": "r", + "L-72045165": "r", + "L-8D06F3EA": "r", + "L-9D07B6EF": "r", + "L-ACCF6C0D": "e", + "L-B4157408": "r", + "L-C3D92D78": "r", + "L-D906BEE7": "r", + "L-DE99852F": "r", + "L-DF544FF3": "r", + "L-E692F494": "r", + "L-ECF1B2A0": "r", + "L-F1FE1B52": "r", + "L-F2D50796": "r", + "L-FD92223D": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "codecommit": { + "quotas": { + "L-81790602": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "codedeploy": { + "quotas": { + "L-3F19B6A5": "e", + "L-464411D9": "r", + "L-6BCCFC85": "e", + "L-6DACB4EE": "e", + "L-877B748B": "e", + "L-9F835576": "e", + "L-AB125F0B": "r", + "L-D9088B77": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "codeguru-reviewer": { + "quotas": { + "L-F5129FC6": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "codepipeline": { + "quotas": { + "L-447DD651": "s", + "L-519D5A90": "e", + "L-5AA45A27": "s", + "L-78D200AD": "e", + "L-87C878A5": "s", + "L-912817AD": "s", + "L-ABB870A7": "s", + "L-CE1F2EE9": "s", + "L-FE939BB2": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "cognito-identity": { + "quotas": { + "L-0BF99E8D": "r", + "L-0D31D6D2": "r", + "L-14403AD5": "e", + "L-50C9AAB8": "r", + "L-5AE9F13D": "r", + "L-8692CE1C": "c", + "L-A38ADA84": "r", + "L-DAF3EAFF": "r", + "L-DBF99350": "r", + "L-E97D135E": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "cognito-idp": { + "quotas": { + "L-026ADBA3": "r", + "L-1B44D826": "e", + "L-55545DC8": "r", + "L-5987B8A0": "r", + "L-5EAB0605": "e", + "L-66E6DF30": "c", + "L-681BB884": "e", + "L-7CDAF993": "e", + "L-BB3E7CCF": "r", + "L-D6BD5178": "r", + "L-F21F8BB4": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "comprehend": { + "quotas": { + "L-0C094DCD": "r", + "L-0ED4C5C8": "r", + "L-1666A7DF": "e", + "L-1F3990DA": "r", + "L-223FEB32": "r", + "L-2A73DEBC": "e", + "L-2B8ECCAB": "e", + "L-32ABBB12": "e", + "L-358FBC4F": "e", + "L-370FF492": "r", + "L-471B41D6": "e", + "L-4BDB4A9D": "e", + "L-4CF72A70": "r", + "L-55642075": "e", + "L-6823DD44": "r", + "L-70EC2949": "e", + "L-7AC96081": "e", + "L-7CC66BB8": "e", + "L-8F55B05C": "r", + "L-94042C4D": "e", + "L-A9C48D71": "r", + "L-AE5B911F": "e", + "L-BFFD1421": "e", + "L-C5F124CF": "r", + "L-C83B39C8": "r", + "L-D11AB353": "r", + "L-D88E2B98": "e", + "L-DFE056B4": "r", + "L-E65FE76A": "e", + "L-F2BED405": "e", + "L-F48BA15E": "r", + "L-F67A0803": "r", + "L-F7FB6495": "r", + "L-FD6FC352": "r", + "L-FD8F4873": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "connect": { + "quotas": { + "L-000B6A1A": "r", + "L-01980B0F": "r", + "L-020883A7": "r", + "L-02F9E992": "r", + "L-04A84DF5": "r", + "L-0648C74A": "r", + "L-0711FF1F": "r", + "L-0865B754": "e", + "L-08DF489D": "r", + "L-09AAE068": "r", + "L-0D791E12": "r", + "L-0D8D2259": "r", + "L-0E9EA5C5": "r", + "L-0F239EFE": "r", + "L-100FDD6A": "r", + "L-1210FC76": "r", + "L-125AA33D": "r", + "L-12900DCA": "r", + "L-12A6C748": "r", + "L-12AB7C57": "r", + "L-12D0511F": "r", + "L-1317E3B0": "r", + "L-1504D6C6": "r", + "L-159E202B": "r", + "L-1643345D": "r", + "L-16BF00C7": "r", + "L-1775C3F8": "r", + "L-17DC1373": "r", + "L-17E664CF": "r", + "L-18108401": "r", + "L-185BE3DB": "r", + "L-1955649E": "r", + "L-19755C7E": "e", + "L-19A87C94": "e", + "L-19D865C6": "r", + "L-1A44121A": "r", + "L-1AB8E9D9": "r", + "L-1AF438BB": "r", + "L-1F455046": "r", + "L-1F71CF54": "r", + "L-1FA68102": "r", + "L-20CD02F7": "e", + "L-21385E28": "r", + "L-221F1DF8": "r", + "L-22922690": "e", + "L-22C4CED1": "r", + "L-22F9A3D8": "r", + "L-230B11C5": "r", + "L-2463E7C2": "r", + "L-25E54F7C": "r", + "L-26D9F60B": "r", + "L-272F1E62": "r", + "L-2AADC77E": "r", + "L-2AF5EEF5": "r", + "L-2BDBF248": "r", + "L-2BE4D75F": "e", + "L-2C8C33D8": "r", + "L-2C9A399A": "r", + "L-2CCBA953": "r", + "L-2D464A68": "r", + "L-2DB48531": "r", + "L-2DE43297": "r", + "L-2E719449": "r", + "L-2F996DE6": "r", + "L-2FC23A76": "r", + "L-30488271": "r", + "L-30929A21": "r", + "L-3118109A": "r", + "L-3324D6A9": "r", + "L-346841E6": "r", + "L-3481440F": "r", + "L-34F440B5": "r", + "L-371095B8": "r", + "L-3741AF59": "r", + "L-379E909D": "r", + "L-37E92540": "r", + "L-3828FBF0": "e", + "L-38EB582F": "r", + "L-39D41E47": "r", + "L-3A7EFE53": "r", + "L-3D20C7A8": "r", + "L-3EEA2922": "r", + "L-3F3E67D1": "r", + "L-3F6301E8": "r", + "L-408DD6C6": "r", + "L-40BDE29F": "r", + "L-40C15531": "r", + "L-40F4B10D": "r", + "L-4161472A": "r", + "L-418ABD80": "r", + "L-41C7214A": "r", + "L-43B4F8CE": "r", + "L-4409B44A": "r", + "L-44302794": "r", + "L-44B5DA37": "r", + "L-44BB2CC5": "r", + "L-44D45586": "r", + "L-456FA19E": "r", + "L-45BAE507": "r", + "L-4641705A": "r", + "L-467CADD3": "r", + "L-476CE930": "r", + "L-4AAC8E79": "r", + "L-4AE2F6BF": "r", + "L-4C062DDC": "r", + "L-4E9BCC96": "r", + "L-4EA7C312": "r", + "L-4F2A229E": "r", + "L-4FBE591E": "r", + "L-50375162": "e", + "L-50B4DE11": "r", + "L-50C3EE60": "r", + "L-50D07AB9": "r", + "L-516BC0EB": "e", + "L-52794498": "r", + "L-53E03705": "r", + "L-56B34560": "r", + "L-5755F8EC": "r", + "L-579E0476": "r", + "L-57DF9146": "r", + "L-57EBCF95": "r", + "L-5A3065E6": "r", + "L-5AB302E1": "r", + "L-5AD48B1A": "r", + "L-5AF7EB96": "r", + "L-5B528FED": "r", + "L-5B601B18": "r", + "L-5C79A188": "r", + "L-5CB19903": "r", + "L-5CFC10A5": "r", + "L-5D8210C3": "r", + "L-5E9E65F2": "r", + "L-5F32FD78": "r", + "L-601C68F6": "r", + "L-60553137": "r", + "L-6271E27A": "r", + "L-62D9A3EA": "r", + "L-6402A996": "e", + "L-64B27051": "r", + "L-650BD10F": "r", + "L-66B5F86E": "r", + "L-6751163B": "r", + "L-6840C932": "r", + "L-68BBE2E8": "e", + "L-68E1D2C7": "r", + "L-6C658B70": "r", + "L-6DF53542": "r", + "L-6E6B18DB": "r", + "L-6F6E1C97": "r", + "L-6FB811CE": "r", + "L-731F613E": "r", + "L-735CD262": "e", + "L-7408C40F": "r", + "L-753B94AB": "r", + "L-75490F5A": "r", + "L-759067FC": "r", + "L-75ECE3E4": "r", + "L-75EE66CE": "r", + "L-76ACB3ED": "r", + "L-76EF4B62": "r", + "L-76F318C5": "r", + "L-77FC9923": "r", + "L-781E5E85": "r", + "L-78937F3A": "r", + "L-78A553AE": "r", + "L-790F20B4": "e", + "L-79564E52": "e", + "L-7A130C12": "r", + "L-7A99C4BD": "r", + "L-7AA5113F": "r", + "L-7B867368": "e", + "L-7DBD293C": "r", + "L-7F6CA594": "r", + "L-7FA26DC8": "r", + "L-80204DDC": "r", + "L-80A82D5F": "r", + "L-8157C163": "r", + "L-82C99962": "r", + "L-83963769": "r", + "L-839A2EDC": "r", + "L-84CCC70A": "r", + "L-8787723E": "r", + "L-87C02971": "r", + "L-89B2A386": "r", + "L-8B34D696": "r", + "L-8BFD043A": "r", + "L-8C43A191": "r", + "L-8CE99751": "r", + "L-8F812903": "e", + "L-8FE21897": "r", + "L-91A40F24": "r", + "L-93006646": "r", + "L-93412F17": "r", + "L-96329A5A": "r", + "L-986AE5E3": "e", + "L-98A4FE2C": "r", + "L-98C95556": "r", + "L-9959E55D": "r", + "L-9962AF53": "r", + "L-9A46857E": "e", + "L-9AA558F3": "r", + "L-9B84048E": "r", + "L-9CF39F22": "r", + "L-9DAC7B1B": "r", + "L-9E54B88B": "r", + "L-9EC4DA50": "r", + "L-A218697D": "r", + "L-A250B0F6": "r", + "L-A277A9A0": "r", + "L-A408782D": "r", + "L-A4A92651": "r", + "L-A59C54EE": "r", + "L-A60AB996": "r", + "L-A69B645E": "r", + "L-A6BE227D": "r", + "L-A84FDAD7": "r", + "L-A9886A7C": "r", + "L-AA17A6B9": "e", + "L-AA48CD49": "r", + "L-AAE06E27": "r", + "L-AE6CF6CD": "r", + "L-AEAF5C4B": "r", + "L-AEE2C982": "r", + "L-AEFB3FB7": "r", + "L-AF3C38D5": "r", + "L-AFE616A6": "r", + "L-B07B2C56": "r", + "L-B117F12F": "r", + "L-B1987D6A": "r", + "L-B1EC95D9": "r", + "L-B29D0CD1": "r", + "L-B52A644D": "r", + "L-B7E1268D": "r", + "L-B9220F3B": "r", + "L-B93A6612": "e", + "L-BA434818": "r", + "L-BBBDDEDC": "r", + "L-BC61DC58": "r", + "L-BD0B57EC": "r", + "L-BE2447CC": "r", + "L-C06273D6": "r", + "L-C1DA0AD4": "r", + "L-C260F37F": "r", + "L-C2A2F0C5": "r", + "L-C32AFAAE": "r", + "L-C422682D": "r", + "L-C56E3A3C": "r", + "L-C595FFE9": "r", + "L-C5C075CE": "r", + "L-C5C511CD": "r", + "L-C636B7F5": "r", + "L-C8237495": "r", + "L-C970C7E8": "e", + "L-CBDEE3E4": "r", + "L-CCC38177": "r", + "L-CCEA7427": "e", + "L-CDC861C1": "r", + "L-CEDB17C8": "r", + "L-D04B6FBE": "r", + "L-D14CF86E": "r", + "L-D2ECB451": "r", + "L-D3E7BE26": "e", + "L-D492D362": "e", + "L-D4BA6F6E": "r", + "L-D68AAAE4": "e", + "L-D6D4A2DA": "r", + "L-D7F21423": "r", + "L-D9BB0F83": "r", + "L-DA469EE8": "r", + "L-DA88F710": "e", + "L-DB5A7716": "r", + "L-DB5F63B4": "r", + "L-DB6D9FDC": "r", + "L-DC67C363": "r", + "L-DC695AA5": "r", + "L-DD5F6903": "r", + "L-DE99D78C": "r", + "L-DF4FC88B": "r", + "L-DFA239E1": "e", + "L-E09C4A84": "r", + "L-E0E93115": "r", + "L-E2244126": "r", + "L-E230854C": "r", + "L-E2C35CCE": "r", + "L-E3D2F503": "e", + "L-E621D747": "r", + "L-E6DB6D6D": "r", + "L-E704D621": "r", + "L-E74D74A6": "r", + "L-E8E90FC3": "r", + "L-E908C3A1": "r", + "L-EA358306": "r", + "L-EB8D7D10": "r", + "L-EC183450": "r", + "L-EC633E57": "r", + "L-EC99C986": "r", + "L-ED2B0490": "r", + "L-EE1EAE36": "r", + "L-EE6F0D82": "r", + "L-EF2F987D": "r", + "L-F001E5ED": "r", + "L-F161F141": "r", + "L-F2072D9F": "r", + "L-F325A715": "e", + "L-F4C86B27": "e", + "L-F6A85133": "r", + "L-F6C0B93F": "r", + "L-F6EB2DE1": "r", + "L-F7E8A253": "r", + "L-F93EF81F": "r", + "L-F97FEF0D": "r", + "L-FAC57D08": "r", + "L-FB6C6CA1": "r", + "L-FBA0478F": "r", + "L-FC15C865": "r", + "L-FC6A5030": "e", + "L-FE3C3BC3": "r", + "L-FF4585DE": "r", + "L-FFF609B4": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "databrew": { + "quotas": { + "L-0D2C4DFC": "e", + "L-131D2768": "e", + "L-5748848E": "e", + "L-640ABD4F": "e", + "L-935D4120": "r", + "L-940C8930": "e", + "L-955A1FA6": "e", + "L-A386FCB8": "e", + "L-B06AE58E": "e", + "L-BF3E0A94": "e", + "L-CE9E9D8D": "e", + "L-EE2782A4": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "dax": { + "quotas": { + "L-AB139030": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "dlm": { + "quotas": { + "L-5407D8DA": "e", + "L-DCA05F2F": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "dms": { + "quotas": { + "L-1AB41EE0": "e", + "L-2146F1FD": "e", + "L-27B24FAD": "e", + "L-4182EDE9": "e", + "L-7FD3593B": "e", + "L-9A47CA81": "e", + "L-BBDCBDC8": "s", + "L-C2341CDC": "e", + "L-D12045C2": "e", + "L-D97343A2": "e", + "L-DE63148C": "e", + "L-E17328E9": "e", + "L-E569F59D": "e", + "L-FBEA20FB": "e", + "L-FE918D88": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "docdb": { + "quotas": { + "L-02DEA053": "e", + "L-13F31459": "e", + "L-5BA57179": "e", + "L-739A3A85": "e", + "L-B2551F83": "e", + "L-F7FABF71": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "ds": { + "quotas": { + "L-092080C3": "e", + "L-25146888": "e", + "L-5B5620DE": "e", + "L-EF86B739": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "dsql": { + "quotas": { + "L-9A50E9F1": "s", + "L-AA07A0EE": "e", + "L-B3A4E51E": "e", + "L-DCF93F11": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "dynamodb": { + "quotas": { + "L-1BB77E89": "r", + "L-2A593B99": "r", + "L-34F6A552": "r", + "L-34F8CCC8": "r", + "L-923BEB7A": "r", + "L-AB614373": "r", + "L-CF0CBE56": "r", + "L-D98E8184": "r", + "L-F3CA5463": "r", + "L-F7858A77": "e", + "L-F98FE922": "c" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "ec2": { + "quotas": { + "L-0263D0A3": "c", + "L-0E3CBAB9": "e", + "L-1216C47A": "c", + "L-1945791B": "c", + "L-34B43A08": "c", + "L-3819A6DF": "c", + "L-417A185B": "c", + "L-43DA4232": "c", + "L-6917EF20": "e", + "L-70015FFA": "e", + "L-7212CCBC": "c", + "L-7295265B": "c", + "L-74FC7D96": "c", + "L-8FBBDF0C": "e", + "L-9A0B6E60": "r", + "L-B665C33B": "e", + "L-D0B7243C": "r", + "L-DB2E81BA": "c" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "ecr": { + "quotas": { + "L-03A36CE1": "e", + "L-16E70933": "r", + "L-44194860": "r", + "L-55A41110": "r", + "L-95B28F8D": "r", + "L-A1670B10": "r", + "L-A60A366D": "r", + "L-AD52DFB2": "r", + "L-B9173138": "r", + "L-CFEB8E8D": "c" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "ecr-public": { + "quotas": { + "L-1EDF7132": "r", + "L-33392ECC": "r", + "L-502CB705": "e", + "L-8FA37FDE": "r", + "L-A1FEAB1E": "r", + "L-B5773E0E": "r", + "L-B6387A7C": "r", + "L-EF0362CE": "r", + "L-F0CAD50B": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "ecs": { + "quotas": { + "L-1E6DEB89": "r", + "L-21C621EB": "c", + "L-22AE4B75": "r", + "L-281CBA4C": "r", + "L-29793C9D": "r", + "L-321A0372": "r", + "L-35D944A8": "r", + "L-3B4FAC68": "r", + "L-3CA4FC4A": "r", + "L-3E3D55FE": "r", + "L-40D1D4C5": "r", + "L-424FFC53": "r", + "L-42E25F2A": "r", + "L-43D4E76A": "r", + "L-4C90BDD4": "r", + "L-538D7426": "r", + "L-553993D4": "r", + "L-5A5FEADE": "r", + "L-62DC78F9": "r", + "L-64FE0575": "r", + "L-660A3A36": "r", + "L-678F155F": "r", + "L-80627E8A": "r", + "L-886BDC21": "r", + "L-8F66404D": "r", + "L-924E3D47": "r", + "L-9383BF97": "r", + "L-9440138C": "r", + "L-A04BC52C": "r", + "L-A2AA9478": "r", + "L-A2DBEAC1": "r", + "L-A8AC1C0F": "r", + "L-A9E5EB0F": "r", + "L-AA0D4951": "r", + "L-B45594D8": "r", + "L-B4EF2B3D": "r", + "L-C26103FB": "r", + "L-C3AEE9D2": "r", + "L-C5297B3A": "r", + "L-CA95243C": "r", + "L-CDF9F16B": "r", + "L-D5AA0F33": "r", + "L-D95BCB5D": "r" + } + }, + "eks": { + "quotas": { + "L-1194D53C": "c", + "L-23414FF3": "e", + "L-33415657": "e", + "L-5C12D558": "e", + "L-6AFFD1D8": "e", + "L-6D54EA21": "e", + "L-BD136A63": "e", + "L-D78D8AF8": "e", + "L-EA277FDC": "e", + "L-FDFA5F81": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "elasticache": { + "quotas": { + "L-3E7F7726": "e", + "L-3F15A733": "e", + "L-75A7B5A4": "r", + "L-80E085C7": "e", + "L-8C334AD1": "e", + "L-943F0F1C": "e", + "L-A87EE522": "e", + "L-AD484FC5": "e", + "L-AF354865": "e", + "L-BBCDAECC": "e", + "L-DFE45DF3": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "elasticbeanstalk": { + "quotas": { + "L-1CEABD17": "e", + "L-8EFC1C51": "e", + "L-9838E43F": "e", + "L-D64F1F14": "e", + "L-E593A077": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "elasticfilesystem": { + "quotas": { + "L-848C634D": "c", + "L-B34D07B4": "r" + } + }, + "elasticloadbalancing": { + "quotas": { + "L-53DA6B97": "c", + "L-69A177A2": "c", + "L-E9E9831D": "c" + } + }, + "elasticmapreduce": { + "quotas": { + "L-000BFD76": "r", + "L-0224B14B": "r", + "L-03AED1B3": "r", + "L-03EB6086": "r", + "L-0CF0BE91": "r", + "L-0E64D90C": "r", + "L-123EDE00": "r", + "L-154D9FF8": "r", + "L-160E516B": "r", + "L-16E4E927": "r", + "L-1A0534D7": "r", + "L-1ADA5AD8": "r", + "L-1EE7982C": "e", + "L-2266B3CF": "r", + "L-2268EC50": "r", + "L-2625B75B": "r", + "L-27ABC861": "r", + "L-27AD4F43": "r", + "L-283CCA2A": "r", + "L-2C4B0A7F": "r", + "L-361D364D": "r", + "L-3A2AEB6B": "r", + "L-3AD9CD3B": "r", + "L-3BF7624C": "r", + "L-3C932280": "r", + "L-40A3F1BE": "r", + "L-41AA02AE": "r", + "L-41EE964A": "r", + "L-432FAB44": "r", + "L-49AA2AC0": "r", + "L-49D80F39": "r", + "L-4A0D204E": "r", + "L-4C313B42": "r", + "L-4D731391": "r", + "L-5E87FF33": "r", + "L-5EE05F48": "r", + "L-600E341C": "r", + "L-62231AC0": "r", + "L-67E5FE4A": "r", + "L-67F4EC02": "r", + "L-68268EEB": "r", + "L-68E6373A": "r", + "L-6A661CC5": "r", + "L-72BCD5B1": "r", + "L-73E44B2E": "r", + "L-76CEF085": "r", + "L-77B909B1": "e", + "L-7A1644F9": "r", + "L-7D1BF903": "r", + "L-7E42A979": "r", + "L-8027FD2D": "r", + "L-8029315A": "r", + "L-815103CB": "r", + "L-81AF5123": "r", + "L-8273B16C": "r", + "L-84D58688": "r", + "L-85BA8360": "r", + "L-87EDCC64": "r", + "L-888B48A6": "r", + "L-8AF88BF0": "r", + "L-94B63BE5": "r", + "L-9547F71F": "r", + "L-985D82D4": "r", + "L-996E162C": "r", + "L-9C4B71C6": "r", + "L-9CCE25C7": "r", + "L-9EFF5880": "r", + "L-9F63B487": "r", + "L-A21DE5E2": "r", + "L-A3790607": "r", + "L-A3F7FDD2": "r", + "L-A3F85680": "r", + "L-A552C9A0": "r", + "L-A90C264E": "r", + "L-AA541BA8": "r", + "L-AE4BC073": "r", + "L-B79F3122": "r", + "L-B810434D": "r", + "L-BC4C3BE9": "r", + "L-BF4AD168": "r", + "L-C00B9F83": "r", + "L-C0B235E1": "r", + "L-C7C7D520": "r", + "L-C8E3FE22": "r", + "L-CCF40647": "r", + "L-D145AF1C": "r", + "L-D4DD1C91": "r", + "L-D53A0B88": "r", + "L-D74118B4": "r", + "L-D79F47D7": "r", + "L-E2886010": "r", + "L-E5202B33": "r", + "L-E594D186": "r", + "L-E6B8CC65": "r", + "L-EA1CF51E": "r", + "L-EB8F427D": "r", + "L-ECF78C67": "r", + "L-EF8FA005": "r", + "L-F06A869F": "r", + "L-F0B1A0AC": "r", + "L-F26C371C": "r", + "L-F285819B": "r", + "L-F5591F89": "r", + "L-F902E21E": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "es": { + "quotas": { + "L-076D529E": "e", + "L-6408ABDE": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "events": { + "quotas": { + "L-244521F2": "c", + "L-39263BDC": "e", + "L-5540C5E3": "r", + "L-595D6D42": "c", + "L-5D1D13E3": "s", + "L-658A4FD9": "c", + "L-664C5505": "s", + "L-755FD01C": "r", + "L-9B653E91": "r", + "L-D082A4F6": "e", + "L-DF788473": "e", + "L-EAC9A2AC": "c", + "L-FB1C3A6D": "c", + "L-FC354966": "s" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "firehose": { + "quotas": { + "L-14BB0BE7": "c", + "L-17D4EADE": "r", + "L-7681C790": "r", + "L-937C879B": "r" + } + }, + "forecast": { + "quotas": { + "L-02D995E1": "e", + "L-10DDC31D": "e", + "L-1306EC42": "e", + "L-235B11D6": "e", + "L-3154C698": "e", + "L-3DED4AA6": "e", + "L-407BD890": "e", + "L-4A218FD9": "e", + "L-5054D782": "e", + "L-561FC25E": "e", + "L-5EC8963B": "e", + "L-618F5043": "e", + "L-690B4DB2": "s", + "L-6AD28BD9": "e", + "L-762142D9": "e", + "L-884F7F75": "e", + "L-9C589A93": "e", + "L-B50F9B6C": "e", + "L-BDD6E332": "e", + "L-C4147F5F": "e", + "L-D613D53B": "e", + "L-E1AC300F": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "fsx": { + "quotas": { + "L-0CD18A5D": "r", + "L-15D9FE87": "s", + "L-4E6C2FB3": "s", + "L-4EDE4065": "r", + "L-57578687": "e", + "L-59D0763F": "e", + "L-5B89F9CE": "s", + "L-60836D3E": "e", + "L-736F3D6F": "s", + "L-7D5FDD38": "s", + "L-84EAF187": "s", + "L-88479C21": "s", + "L-8F1B9C74": "s", + "L-901C77F5": "s", + "L-9AFA1F09": "e", + "L-AD2FC696": "s", + "L-B7391FCE": "s", + "L-C28C1403": "e", + "L-C431DBA3": "e", + "L-C48231E5": "e", + "L-C5F860DD": "r", + "L-C8640C82": "s", + "L-CD5E0524": "e", + "L-DD0F7417": "e", + "L-E24B4DE4": "e", + "L-E2C89679": "s", + "L-E43BDB2E": "s", + "L-E94C1C19": "s", + "L-FD6F2F22": "e", + "L-FD89CA8A": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "globalaccelerator": { + "quotas": { + "L-2151CAA1": "e", + "L-3D1423D2": "e", + "L-6975C1FD": "e", + "L-7B7A9DD5": "e", + "L-83098BD3": "e", + "L-B7B05447": "e", + "L-BB449727": "e", + "L-BE074EF3": "e", + "L-C6F903E5": "e", + "L-E201D224": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "glue": { + "quotas": { + "L-04CEE988": "e", + "L-071ABE08": "e", + "L-08F3B322": "e", + "L-096DBB95": "e", + "L-11FA2C1A": "e", + "L-1DD415D5": "e", + "L-2C3F5401": "e", + "L-2E9FB93F": "r", + "L-337244C9": "e", + "L-3890A802": "r", + "L-4071B0E3": "r", + "L-4256D6D2": "e", + "L-4F4B522D": "s", + "L-5E4153CA": "r", + "L-611FDDE4": "e", + "L-76EC689B": "e", + "L-785C1F39": "e", + "L-7DD7C33A": "e", + "L-83192DBF": "e", + "L-83A59AA6": "r", + "L-87F5991C": "e", + "L-94D025B7": "e", + "L-958728D1": "r", + "L-A457CBAB": "e", + "L-A57B5BCE": "e", + "L-ACAC12B6": "r", + "L-B4840D4D": "r", + "L-B78896B9": "s", + "L-B8497671": "e", + "L-C3952F6C": "r", + "L-D90AC94B": "e", + "L-D987EC31": "e", + "L-DBA56E2F": "e", + "L-E15CE20A": "r", + "L-EAC30D24": "e", + "L-EEC98450": "e", + "L-F1653A6D": "e", + "L-F1AAB534": "e", + "L-F545C262": "e", + "L-F574AED9": "r", + "L-F953935E": "e", + "L-FB210BD9": "e", + "L-FEBBFA7A": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "grafana": { + "quotas": { + "L-2C2D5119": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "iam": { + "quotas": { + "L-0DA4ABF3": "c", + "L-4019AD8B": "e", + "L-6E65F664": "e", + "L-858F3967": "e", + "L-BF35879D": "c", + "L-C07B4B0D": "e", + "L-E95E4862": "c", + "L-F4A5425F": "c", + "L-F55AF5E4": "c", + "L-FE177D64": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "kafka": { + "quotas": { + "L-03FD6822": "e", + "L-36D29E8C": "e", + "L-8F940D28": "e", + "L-9B45E609": "e", + "L-B2FDE22A": "e", + "L-EDD31C36": "e", + "L-FAB9E493": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "kinesis": { + "quotas": { + "L-0918CF54": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "kinesisanalytics": { + "quotas": { + "L-3729A2EF": "e", + "L-3A88E041": "e", + "L-90BEDB9D": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "kinesisvideo": { + "quotas": { + "L-08F65F09": "r", + "L-2FC7D6B2": "r", + "L-32D5DC79": "r", + "L-354AF9F0": "r", + "L-8F974349": "e", + "L-B71421B8": "s", + "L-B71B4FEE": "r", + "L-B7F419CA": "e", + "L-BF0D282F": "r", + "L-EDC0C00D": "s", + "L-F06528A6": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "kms": { + "quotas": { + "L-0428A42E": "r", + "L-08932E37": "r", + "L-1233BF9B": "r", + "L-161E93A6": "r", + "L-16B46EF0": "r", + "L-171660E4": "r", + "L-19C26D0A": "r", + "L-1D966DA0": "r", + "L-1F75ADD1": "r", + "L-275D92F3": "r", + "L-2AC98190": "r", + "L-32B67F4A": "r", + "L-340F62FB": "c", + "L-3B372FA9": "r", + "L-3C995F2B": "r", + "L-515A0541": "r", + "L-635264CC": "r", + "L-6375F442": "r", + "L-6B8C93BD": "r", + "L-6E3AF000": "r", + "L-705B9E79": "r", + "L-74021A59": "r", + "L-77042783": "r", + "L-7851D255": "r", + "L-79E0D0AB": "r", + "L-7D6DE447": "r", + "L-88313D4A": "r", + "L-8A08DAEA": "r", + "L-99631835": "r", + "L-9D770618": "r", + "L-9DDDE6CA": "r", + "L-9F1FCF6D": "r", + "L-A2A30EC6": "r", + "L-A3828E1F": "r", + "L-AE57B391": "r", + "L-BD96F100": "r", + "L-BE799B67": "r", + "L-BF3F8F1D": "r", + "L-C2F1777E": "c", + "L-CE1DB614": "r", + "L-D2EEB5E0": "r", + "L-D39AB822": "r", + "L-D594A657": "c", + "L-D7711EF4": "r", + "L-DB3BF542": "r", + "L-DC14942D": "r", + "L-E1C93865": "r", + "L-E20AA94C": "r", + "L-E4FBCA5E": "r", + "L-E99520CB": "r", + "L-F20EBCB7": "r", + "L-F33DCFEB": "e", + "L-F7504F73": "r", + "L-F83AC7F7": "r", + "L-FAE8F084": "r", + "L-FB6513A2": "r", + "L-FCE4492D": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "lakeformation": { + "quotas": { + "L-1343AC0E": "e", + "L-3D55E97C": "s", + "L-3E3798DF": "e", + "L-47097528": "e", + "L-9F3EFFAB": "e", + "L-B0A837CA": "e", + "L-F165AF61": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "lambda": { + "quotas": { + "L-118C44B3": "r", + "L-133D658A": "r", + "L-139F9A48": "r", + "L-14320ECE": "r", + "L-25EEC0A4": "r", + "L-2ACBD22F": "s", + "L-2CCA0501": "r", + "L-2EBBB6B4": "r", + "L-4C4550DE": "r", + "L-50EA21A9": "r", + "L-535CA9B6": "r", + "L-6A3611ED": "r", + "L-72E0D058": "r", + "L-74787B8A": "r", + "L-7712260B": "r", + "L-7E8754C7": "r", + "L-88CBC2FA": "r", + "L-90045317": "r", + "L-91B95582": "r", + "L-942E56BE": "e", + "L-9A5E43A5": "r", + "L-9B52FC60": "r", + "L-9FEE3D26": "e", + "L-A0D6E196": "r", + "L-A723F9CC": "r", + "L-ABBF0CF3": "e", + "L-B78D2ECC": "r", + "L-B82A30EA": "r", + "L-B99A9384": "r", + "L-BA29C22B": "r", + "L-C9C2110E": "r", + "L-CD1C0CC4": "s", + "L-CE98C9E3": "r", + "L-D65D9F16": "r", + "L-DF87A8A6": "r", + "L-F864D568": "e", + "L-F8BECE9C": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "lightsail": { + "quotas": { + "L-4259AF9B": "e", + "L-BBF0F260": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "logs": { + "quotas": { + "L-07A912D5": "r", + "L-3F243AD0": "r", + "L-4284EEDE": "r", + "L-76507CEF": "r", + "L-7E1FAE88": "r", + "L-B53B9649": "e", + "L-C029A21C": "r", + "L-C7B9AAAB": "c", + "L-D2832119": "r", + "L-D6990B80": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "macie2": { + "quotas": { + "L-FEB8D34D": "r" + } + }, + "managedblockchain": { + "quotas": { + "L-56698730": "e", + "L-C71C12D1": "e", + "L-D3936217": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "mediaconvert": { + "quotas": { + "L-01D327FE": "r", + "L-0A485F3B": "r", + "L-0D03A2D6": "r", + "L-0EB971DE": "r", + "L-1018D354": "r", + "L-17F2DE2C": "r", + "L-19E96FB2": "r", + "L-1AE7DAF9": "e", + "L-1D14865F": "r", + "L-2C57B94C": "r", + "L-2D1D110F": "r", + "L-3316B9B0": "r", + "L-35F8C38D": "r", + "L-36B9CAA6": "r", + "L-3F17D407": "r", + "L-3FD3957B": "r", + "L-438B53F5": "r", + "L-44E8E4BC": "e", + "L-4922E007": "r", + "L-4CC56996": "r", + "L-4FAC0A2F": "r", + "L-54D5F5A5": "r", + "L-5663DECD": "r", + "L-5885B012": "r", + "L-593F5D32": "r", + "L-63007F37": "r", + "L-647EBFA7": "r", + "L-6960A8DA": "r", + "L-6CA5AFAC": "r", + "L-716F67B4": "r", + "L-75A471E3": "r", + "L-78B2D11D": "r", + "L-84EB285F": "r", + "L-8CFEB230": "e", + "L-94047106": "r", + "L-9ABC3758": "r", + "L-A0D28790": "r", + "L-A487133E": "r", + "L-A4F8DFA3": "r", + "L-A51E3FE2": "r", + "L-AA313626": "r", + "L-ACAF5652": "r", + "L-B152EC96": "r", + "L-B529BF7C": "r", + "L-BA1DE85F": "r", + "L-C043869B": "r", + "L-C36D2A6D": "r", + "L-CD746D2B": "r", + "L-CE9179D5": "r", + "L-CF93C968": "r", + "L-D35248DB": "r", + "L-E45A403C": "r", + "L-FFA964F8": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "medialive": { + "quotas": { + "L-019F695A": "e", + "L-05A796F2": "e", + "L-1F6E2FAF": "e", + "L-22ED1BEF": "e", + "L-3C46E17E": "e", + "L-3FDA265B": "e", + "L-4D7207DE": "e", + "L-63879FB4": "r", + "L-68E02936": "e", + "L-6A0116BB": "e", + "L-759E3395": "e", + "L-7BC53EAF": "e", + "L-8B49C5C1": "e", + "L-9E233AF7": "e", + "L-9E4BC4C0": "e", + "L-A4814CCC": "e", + "L-A825B11C": "e", + "L-AAFBD428": "e", + "L-B0CA93DC": "e", + "L-BDF24E14": "e", + "L-D1AFAF75": "e", + "L-DDE858F0": "e", + "L-FBCE2FC3": "e", + "L-FF7E5CAC": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "mediapackage": { + "quotas": { + "L-1E1258F1": "e", + "L-352B8598": "e", + "L-563EE697": "e", + "L-66FFDBE4": "e", + "L-7F7EDDDF": "e", + "L-B1B90B42": "r", + "L-F7CB14AC": "s" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "mediatailor": { + "quotas": { + "L-0F7265C4": "e", + "L-2290981E": "e", + "L-29DF1B92": "e", + "L-32FBC51C": "r", + "L-3BCD6A29": "e", + "L-680CE323": "e", + "L-7946CFE6": "e", + "L-7A79D9CE": "e", + "L-A32E8357": "e", + "L-B9D43015": "r", + "L-C13EFDBD": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "mgn": { + "quotas": { + "L-0336ACF5": "e", + "L-13A5D930": "e", + "L-47B06737": "e", + "L-50980698": "e", + "L-707AB944": "e", + "L-7959394C": "e", + "L-866BF8B4": "e", + "L-8EABFFBF": "e", + "L-9A599620": "e", + "L-D617A7E7": "e", + "L-DC1BBA2A": "e", + "L-FBAE4C1D": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "monitoring": { + "quotas": { + "L-05D334F0": "r", + "L-0720E68F": "r", + "L-0F4E28CA": "r", + "L-1F0C4E0C": "r", + "L-21CB40A4": "r", + "L-515B0B71": "r", + "L-59022E75": "r", + "L-5E141212": "r", + "L-6300B446": "r", + "L-6753900D": "r", + "L-69C44FFD": "r", + "L-6FCAAA2E": "r", + "L-73547960": "r", + "L-787E531D": "r", + "L-7D8B1BC8": "r", + "L-8445A443": "r", + "L-8A387C66": "r", + "L-8BC498D4": "r", + "L-A1710150": "r", + "L-A64F5500": "r", + "L-A6D89949": "r", + "L-B1A3FF67": "r", + "L-C1FE0F5C": "e", + "L-DBD11BCC": "e", + "L-E1508405": "r", + "L-E82C279D": "r", + "L-EE839489": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "mq": { + "quotas": { + "L-42B434B7": "e", + "L-4D525FD5": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "neptune": { + "quotas": { + "L-22818E49": "e", + "L-368A3E00": "e", + "L-463F8A01": "e", + "L-483F7912": "e", + "L-584DADE7": "e", + "L-5BB9A916": "e", + "L-6D17A5A2": "e", + "L-9AEE2A70": "e", + "L-A425F59F": "e", + "L-B3AC6773": "s", + "L-BF10548E": "r", + "L-D6543DBD": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "network-firewall": { + "quotas": { + "L-0814492B": "e", + "L-0A972525": "e", + "L-2D7A0EE2": "e", + "L-3EF9089F": "e", + "L-56D4232F": "e", + "L-7CE054B0": "e", + "L-801F8132": "e", + "L-CC7EC76F": "e", + "L-DBC1A782": "e", + "L-DE163D32": "e", + "L-E65239AF": "e", + "L-EAE8E19E": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "networkmonitor": { + "quotas": { + "L-A4298AB9": "e", + "L-A8FA6DFE": "e", + "L-F192A8D6": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "omics": { + "quotas": { + "L-01A419C5": "e", + "L-13B00733": "s", + "L-186D3DEB": "e", + "L-22E12079": "e", + "L-242998FB": "e", + "L-24A3B174": "r", + "L-25504C8C": "r", + "L-35CE76C9": "s", + "L-473E274D": "r", + "L-4E5B34A1": "e", + "L-7B9E5416": "s", + "L-7CAE62CF": "e", + "L-876AD0A2": "r", + "L-899DA104": "e", + "L-911E26A1": "r", + "L-A30FD31B": "r", + "L-AFB19B96": "e", + "L-B94B38A2": "s", + "L-BE38079A": "r", + "L-BE766427": "s", + "L-BFFBB2FD": "s", + "L-C9679DBC": "e", + "L-D91CDC5E": "e", + "L-E787EB79": "e", + "L-F34A3FC2": "s", + "L-F57A8D18": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "organizations": { + "quotas": { + "L-35422876": "s", + "L-DC9D128D": "e", + "L-E619E033": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "outposts": { + "quotas": { + "L-0B277C74": "e", + "L-3D389D34": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "personalize": { + "quotas": { + "L-052ECD67": "e", + "L-14011066": "e", + "L-69B72005": "e", + "L-8047B3A8": "r", + "L-9C16B368": "e", + "L-A11DBE93": "e", + "L-A6A4AB70": "e", + "L-A8FE1453": "e", + "L-B9CFBC8B": "e", + "L-C5A4FD57": "e", + "L-C71694DA": "e", + "L-D9DD83B7": "e", + "L-F1119DA2": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "pinpoint": { + "quotas": { + "L-39643E10": "r", + "L-6D703411": "e", + "L-9AE43654": "r", + "L-A7D30E78": "e", + "L-F179D122": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "polly": { + "quotas": { + "L-17639580": "s", + "L-18255867": "r", + "L-18474792": "s", + "L-3E095342": "r", + "L-43330D37": "r", + "L-511CA548": "r", + "L-77D5DB9E": "s", + "L-79B4630F": "s", + "L-7E184727": "r", + "L-9FB8AA30": "r", + "L-A65CEC2D": "r", + "L-B9A743A4": "r", + "L-C54DC08A": "r", + "L-D93DD9F2": "r" + } + }, + "quicksight": { + "quotas": { + "L-04458D9F": "e", + "L-264703A8": "r", + "L-29203CBA": "e", + "L-5FE00BED": "e", + "L-61EC97DA": "e", + "L-681A9699": "e", + "L-8D8B7044": "e", + "L-D75C2D48": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "ram": { + "quotas": { + "L-238C96EE": "e", + "L-2870BE9D": "e", + "L-4A6CEE66": "e", + "L-595828F9": "e", + "L-8491BF81": "e", + "L-9EBA15DD": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "rds": { + "quotas": { + "L-272F1212": "e", + "L-48C6BF61": "e", + "L-5BC124EF": "e", + "L-732153D0": "e", + "L-75AC651F": "e", + "L-78E853F4": "e", + "L-7ADDB58A": "s", + "L-7B6409FD": "c", + "L-9372BAB3": "e", + "L-952B80B8": "c", + "L-9B510759": "e", + "L-9FA33840": "e", + "L-A399AC0B": "e", + "L-A59F4C87": "e", + "L-D94C7EA3": "e", + "L-DD2301CA": "e", + "L-DE55804A": "e", + "L-E094F43D": "e", + "L-E4C808A8": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "resiliencehub": { + "quotas": { + "L-0076B5C6": "e", + "L-013E1BB6": "e", + "L-2652C3BC": "e", + "L-3275C9FD": "r", + "L-37EF5CB4": "r", + "L-3D296B58": "e", + "L-3DCDC079": "e", + "L-4EBD1E5A": "e", + "L-5EC6916A": "e", + "L-6799E097": "e", + "L-6BE17D5B": "e", + "L-985E582D": "e", + "L-BF1D24DC": "r", + "L-CB78A3C3": "s", + "L-CBE304D4": "e", + "L-CEF638A1": "e", + "L-D41E7350": "s", + "L-F9AC239A": "e", + "L-FC254984": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "resource-groups": { + "quotas": { + "L-2BAA18A0": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "route53": { + "quotas": { + "L-4EA4796A": "c", + "L-628D5A56": "e", + "L-84B40094": "e", + "L-945D15E5": "e", + "L-A72C7724": "c", + "L-ACB674F3": "c", + "L-AD61772F": "c", + "L-E209CC9F": "c", + "L-F767CB15": "e", + "L-FC688E7C": "c", + "L-FF06D527": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "route53resolver": { + "quotas": { + "L-02CC8B74": "e", + "L-1B2BDF0A": "e", + "L-4A669CC0": "e", + "L-51D8A1FB": "e", + "L-740A4B31": "e", + "L-8B4B9B75": "e", + "L-94E19253": "e", + "L-9FA3C0A4": "e", + "L-D2FE9758": "e", + "L-F763F4D9": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "rum": { + "quotas": { + "L-35851224": "r", + "L-3FB7EA17": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "s3": { + "quotas": { + "L-1A9B467F": "e", + "L-349AD9CA": "r", + "L-775A314D": "e", + "L-DC2B2D3D": "c", + "L-FAABEEBA": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "sagemaker": { + "quotas": { + "L-001567EF": "e", + "L-001EDCEF": "e", + "L-00247096": "e", + "L-005C1A21": "e", + "L-008FE00D": "e", + "L-00C0E80E": "e", + "L-00C91CB5": "e", + "L-00D14F83": "e", + "L-00D35293": "e", + "L-00DAC655": "e", + "L-00EAD02B": "e", + "L-0100B823": "e", + "L-01266753": "e", + "L-0132CA88": "e", + "L-0143D6A3": "e", + "L-014DC4EC": "e", + "L-01589929": "e", + "L-015B2121": "e", + "L-015EE8AB": "e", + "L-017831D5": "e", + "L-018036DB": "e", + "L-0183D091": "e", + "L-0190812E": "e", + "L-019DC79D": "e", + "L-01D91275": "e", + "L-01E4E529": "e", + "L-02134873": "e", + "L-023C70AC": "e", + "L-02535B10": "e", + "L-029CBCB1": "e", + "L-02BF14DD": "e", + "L-0307F515": "e", + "L-0309C694": "e", + "L-031C5EC5": "e", + "L-03304C28": "e", + "L-033B18EB": "e", + "L-03767DF9": "e", + "L-037F309A": "e", + "L-03C8E8AF": "e", + "L-03E19172": "e", + "L-03FD2ADF": "e", + "L-0407753C": "e", + "L-040D0B77": "e", + "L-04249782": "e", + "L-0439C368": "e", + "L-04421A63": "e", + "L-046836B9": "e", + "L-047DF2B4": "e", + "L-048C491E": "e", + "L-04956A25": "e", + "L-0496610F": "e", + "L-049F2CCC": "e", + "L-04A733DC": "e", + "L-04B64DBD": "e", + "L-04CD765C": "e", + "L-04CE2E67": "e", + "L-04EF76A3": "e", + "L-04F55E28": "e", + "L-050981C0": "e", + "L-05282267": "e", + "L-0544E72F": "e", + "L-0549E35C": "e", + "L-056831C6": "e", + "L-05BE88F0": "e", + "L-05BECF69": "e", + "L-05C4EFD5": "e", + "L-05CAAE0C": "e", + "L-05D004A9": "e", + "L-05EA3CC0": "e", + "L-06106111": "e", + "L-06438B0D": "e", + "L-064E954E": "e", + "L-065D610E": "e", + "L-0665041B": "e", + "L-068DB6B3": "e", + "L-069FAF5D": "e", + "L-06A1E8BB": "e", + "L-06AB0AAC": "e", + "L-06DD0DBC": "e", + "L-06EAD8FD": "e", + "L-070EBEA7": "e", + "L-074118C1": "e", + "L-0743994C": "e", + "L-0771FE64": "e", + "L-077DB28E": "e", + "L-07990A37": "e", + "L-079EEF64": "e", + "L-07B51BA0": "e", + "L-07BEB181": "e", + "L-07D0651D": "e", + "L-08020D35": "e", + "L-0808490E": "e", + "L-0817C279": "e", + "L-08553D92": "e", + "L-086A0843": "e", + "L-08AE20C2": "e", + "L-08EC0A2F": "e", + "L-08F097C3": "e", + "L-08F1F3D8": "e", + "L-08FEE190": "e", + "L-090C5671": "e", + "L-09249843": "e", + "L-095E8E17": "e", + "L-0973A7D7": "e", + "L-09A35F6E": "e", + "L-09A41608": "e", + "L-09B4A649": "e", + "L-09C9B23C": "e", + "L-09D3DD58": "e", + "L-09D56C4F": "e", + "L-09D57927": "e", + "L-09E63FAF": "e", + "L-09F79647": "e", + "L-0A241A0D": "e", + "L-0A29AACF": "e", + "L-0A37CD36": "e", + "L-0A5EF986": "e", + "L-0A6678C9": "e", + "L-0A6E4205": "e", + "L-0A9C6950": "e", + "L-0AB1AE17": "e", + "L-0AB69E2E": "e", + "L-0AC766BA": "e", + "L-0AFA3D20": "e", + "L-0AFBBD69": "e", + "L-0B2C2B96": "e", + "L-0B434972": "e", + "L-0B88B7B0": "e", + "L-0BCDE305": "e", + "L-0BE2F5A1": "e", + "L-0BEF44E8": "e", + "L-0C0D9F82": "e", + "L-0C0E7A62": "e", + "L-0C15A198": "e", + "L-0C42D1BC": "e", + "L-0C545830": "e", + "L-0C59E8F4": "e", + "L-0CE343FE": "e", + "L-0D245982": "e", + "L-0D323AED": "e", + "L-0D57F08E": "e", + "L-0D58D77C": "e", + "L-0D8465EB": "e", + "L-0DA2E7B0": "e", + "L-0DA5DE0D": "e", + "L-0DADC663": "e", + "L-0DB30DD8": "e", + "L-0E2A8BBF": "e", + "L-0E846ECD": "e", + "L-0E9335FF": "e", + "L-0EA47E2A": "e", + "L-0F0037B4": "e", + "L-0F109211": "e", + "L-0F2A8C63": "e", + "L-0F9E0C66": "e", + "L-0FCBFBBD": "e", + "L-0FEC7BB1": "e", + "L-10FFAC91": "e", + "L-1122D5DF": "e", + "L-11624F40": "e", + "L-1192647D": "e", + "L-11AFDCA2": "e", + "L-11D02DB4": "e", + "L-11FBFA2A": "e", + "L-1211C97B": "e", + "L-124C7910": "e", + "L-1252146D": "e", + "L-125B7142": "e", + "L-1271DF32": "e", + "L-12740493": "e", + "L-12798BAE": "e", + "L-127D4C65": "e", + "L-130E7B6B": "e", + "L-13147793": "e", + "L-1356CD75": "e", + "L-135CF62D": "e", + "L-1364D2E0": "e", + "L-138411EA": "e", + "L-138F29A9": "e", + "L-13B1ABA1": "e", + "L-13C9BAB3": "e", + "L-14042B18": "e", + "L-1410387A": "e", + "L-144A2794": "e", + "L-145764C5": "e", + "L-1474CE56": "e", + "L-1476E09A": "e", + "L-148FBB89": "e", + "L-14D776F4": "e", + "L-150039CA": "e", + "L-15047DF3": "e", + "L-1509B3BD": "e", + "L-152DC2E3": "r", + "L-15461E7B": "e", + "L-154D0022": "e", + "L-15A99B7E": "e", + "L-15BCD638": "e", + "L-15BF0640": "e", + "L-15E27A21": "e", + "L-15ECE899": "e", + "L-15F329FB": "e", + "L-15F3426F": "e", + "L-1619F5B7": "e", + "L-1623D0BE": "e", + "L-1630284B": "e", + "L-16486321": "e", + "L-164A270E": "e", + "L-16553FE9": "e", + "L-1686EE8B": "e", + "L-16AF71F1": "e", + "L-1747114E": "e", + "L-176526F4": "e", + "L-176880B1": "e", + "L-177AF1AD": "e", + "L-177D4E91": "e", + "L-17A0905E": "e", + "L-17CC37BB": "e", + "L-17CEAE74": "e", + "L-180A6F2D": "e", + "L-186C8C43": "e", + "L-18904FF8": "e", + "L-18B5AA0D": "e", + "L-18BF1E71": "e", + "L-18C64902": "e", + "L-18C9C439": "e", + "L-18E586D6": "e", + "L-1928E07B": "e", + "L-19321539": "e", + "L-194981EA": "e", + "L-195A207B": "e", + "L-19734703": "e", + "L-19938F1C": "e", + "L-199558F0": "e", + "L-19973BE2": "e", + "L-199FCA12": "e", + "L-19B6BAFC": "e", + "L-19BBECED": "e", + "L-19BC6A57": "e", + "L-19C2A697": "e", + "L-19CFBA14": "e", + "L-19E4BAD9": "e", + "L-1A35F5CB": "e", + "L-1A8A7BA2": "e", + "L-1AC02029": "e", + "L-1AE80ECF": "e", + "L-1B0FA8BF": "e", + "L-1B2B0D33": "e", + "L-1B353A48": "e", + "L-1B372F3F": "e", + "L-1B49FD35": "e", + "L-1B60238B": "e", + "L-1B687CD5": "e", + "L-1B7024B2": "e", + "L-1B9D297C": "e", + "L-1BAEE5A7": "e", + "L-1BF9151C": "e", + "L-1C2E1B03": "e", + "L-1C82AA0C": "e", + "L-1C84ABBF": "e", + "L-1CEA1A39": "e", + "L-1CF85412": "e", + "L-1D84B9D2": "e", + "L-1D8C6579": "e", + "L-1DA286AA": "e", + "L-1DA9A185": "e", + "L-1DD0FB59": "e", + "L-1DDB8D50": "e", + "L-1DE24427": "e", + "L-1DF5E6AF": "e", + "L-1E2072C0": "e", + "L-1E3225F6": "e", + "L-1E3B6E84": "e", + "L-1E4582F6": "e", + "L-1E48384D": "e", + "L-1EA94AB1": "e", + "L-1EC048AB": "e", + "L-1EC4D7FD": "e", + "L-1ED900F7": "e", + "L-1EDB26C2": "e", + "L-1F122E71": "e", + "L-1F4A5AAB": "e", + "L-1FF397C6": "e", + "L-203824E2": "e", + "L-204097CE": "e", + "L-2047A70E": "e", + "L-20546400": "e", + "L-205C8C77": "e", + "L-20700136": "e", + "L-2080C7F4": "e", + "L-20816B3A": "e", + "L-20A2026F": "e", + "L-20DF4E8E": "e", + "L-212B4A4E": "e", + "L-213CD3BC": "e", + "L-214DADDD": "e", + "L-21552510": "e", + "L-21962CDA": "e", + "L-21A0C1CA": "e", + "L-21A99C91": "e", + "L-21DCDF63": "e", + "L-21FC2F36": "e", + "L-225A30F8": "e", + "L-22890FE8": "e", + "L-22BC3627": "e", + "L-22E1BC00": "e", + "L-23412DF7": "e", + "L-23426920": "e", + "L-236AE59F": "e", + "L-23843F46": "e", + "L-239B242B": "e", + "L-239C18BD": "e", + "L-23A89612": "e", + "L-23B26C33": "e", + "L-23D6147A": "e", + "L-23E57EB1": "e", + "L-23F5AC7E": "e", + "L-23FC2F6E": "e", + "L-23FF30BF": "e", + "L-24029A4F": "e", + "L-240BED68": "e", + "L-243B2C0A": "e", + "L-2441079A": "e", + "L-2451F7E3": "e", + "L-24520F3F": "e", + "L-246C5638": "e", + "L-24B0ADC0": "e", + "L-24B12C23": "e", + "L-24BF08D5": "e", + "L-24CBBB5A": "e", + "L-24E5A1B2": "e", + "L-2524EF35": "e", + "L-252AB1C1": "e", + "L-255331C0": "e", + "L-255399BF": "e", + "L-2557FB75": "e", + "L-25865ABE": "e", + "L-25B13CE9": "e", + "L-25CD398E": "e", + "L-25EC3C78": "e", + "L-25FBE4E0": "e", + "L-260E95A6": "e", + "L-26101D2F": "e", + "L-2633C043": "r", + "L-266C4F52": "e", + "L-26A7D02E": "e", + "L-26EB4EC7": "e", + "L-2733D4D5": "e", + "L-2749810B": "e", + "L-2774E5C8": "e", + "L-27768634": "e", + "L-2782D709": "e", + "L-27FFF8C5": "e", + "L-283CDA96": "e", + "L-2856E86C": "e", + "L-286C98BC": "e", + "L-28BE5719": "e", + "L-28CF4381": "e", + "L-28F860BB": "e", + "L-28FEB563": "e", + "L-28FF72CA": "e", + "L-2908B1E9": "e", + "L-2930A179": "e", + "L-29508C65": "e", + "L-29512C0F": "e", + "L-2952557B": "e", + "L-29688C85": "e", + "L-296D2FC5": "e", + "L-2972CC1F": "e", + "L-299FAE98": "e", + "L-29B03627": "e", + "L-29C181D7": "e", + "L-29FEA462": "e", + "L-2A0763AF": "e", + "L-2A6ACFF7": "e", + "L-2A783E1C": "e", + "L-2A78AED4": "e", + "L-2AA3AA37": "e", + "L-2AC01FBD": "e", + "L-2AD0234B": "e", + "L-2AD4A712": "e", + "L-2AD5EFDD": "e", + "L-2B1E88AF": "e", + "L-2B2789AA": "e", + "L-2B2F8466": "e", + "L-2B64B575": "e", + "L-2B83056F": "e", + "L-2BAB231B": "e", + "L-2BAB3767": "e", + "L-2BE095E2": "e", + "L-2BEDFA2E": "e", + "L-2BEE7665": "e", + "L-2BF1C629": "e", + "L-2C0436FB": "e", + "L-2C06E55A": "e", + "L-2C080D31": "e", + "L-2C0E8383": "e", + "L-2C2598DC": "e", + "L-2C3AA41C": "e", + "L-2C505E76": "e", + "L-2C68B58D": "e", + "L-2CA31BFA": "e", + "L-2CABAAC7": "e", + "L-2CBC0A12": "e", + "L-2CBF0EDE": "e", + "L-2CE978FC": "e", + "L-2D1DF2F9": "e", + "L-2D2AAC6C": "e", + "L-2D4C4A2D": "e", + "L-2D6DEB3C": "e", + "L-2D83F796": "e", + "L-2D8CD70A": "e", + "L-2DD73636": "e", + "L-2DEC3E9A": "e", + "L-2E21A1FA": "e", + "L-2E243138": "e", + "L-2E2B5B49": "e", + "L-2E4F2577": "e", + "L-2EB460CE": "e", + "L-2ECAA15F": "e", + "L-2F10D2D2": "e", + "L-2F1EB012": "e", + "L-2F20345E": "e", + "L-2F3C7C63": "e", + "L-2F737F8D": "e", + "L-2F7823EE": "e", + "L-2F9D520B": "e", + "L-2FA5A219": "e", + "L-2FFC6F34": "e", + "L-300538CF": "e", + "L-30094123": "e", + "L-3036C9CA": "e", + "L-30ABD943": "e", + "L-30B99A16": "e", + "L-310E9FC8": "e", + "L-3112BA01": "e", + "L-3115BC6E": "e", + "L-3118B7E1": "e", + "L-31522FA6": "e", + "L-31679D7C": "e", + "L-31B2FB52": "e", + "L-31C211B7": "e", + "L-31EFB623": "e", + "L-31F66640": "e", + "L-320DF9E1": "e", + "L-3221855A": "e", + "L-3245CAF1": "e", + "L-326E6232": "e", + "L-32711015": "e", + "L-3296ED98": "e", + "L-329751EB": "e", + "L-32F895F6": "e", + "L-3308CCC7": "e", + "L-33471349": "e", + "L-334BD79D": "e", + "L-334DC079": "e", + "L-3358D120": "e", + "L-3360E714": "e", + "L-339123BF": "e", + "L-33A961FD": "e", + "L-33C62B99": "e", + "L-3402FFF8": "e", + "L-3408A20D": "e", + "L-34594662": "e", + "L-34601F10": "e", + "L-34757F79": "e", + "L-3482079F": "e", + "L-34866D05": "e", + "L-348D5C8F": "e", + "L-34AA6359": "e", + "L-34DBA194": "e", + "L-34E84A4C": "e", + "L-351B8709": "e", + "L-3523E641": "e", + "L-35292515": "e", + "L-35697161": "e", + "L-357DD322": "e", + "L-3597CD5B": "e", + "L-35ABC8BB": "e", + "L-35BBB2E3": "e", + "L-35E3D13A": "e", + "L-35E5433E": "e", + "L-363335BC": "e", + "L-3647EAE5": "e", + "L-3672157C": "e", + "L-36C029F9": "e", + "L-36C5FA8E": "e", + "L-36DD7CCA": "e", + "L-36F422F7": "e", + "L-36FB5B0A": "e", + "L-37059D02": "e", + "L-3727EAE2": "e", + "L-379E85A3": "e", + "L-37CA4776": "e", + "L-37D6136B": "e", + "L-3838EF5A": "e", + "L-3870264F": "e", + "L-3883646D": "e", + "L-3887CBE3": "e", + "L-391B02C7": "e", + "L-3933622B": "e", + "L-3947C8A6": "e", + "L-395315DA": "e", + "L-39579656": "e", + "L-3970BACE": "e", + "L-39AB5000": "e", + "L-39AD59DE": "e", + "L-39D2CC9D": "e", + "L-39DC8B41": "e", + "L-39F300D8": "e", + "L-39F5FD98": "e", + "L-39F81BFB": "e", + "L-3A00C403": "e", + "L-3A1C8CE1": "e", + "L-3A218EBD": "e", + "L-3A44AF4B": "e", + "L-3A549026": "e", + "L-3A5C6756": "e", + "L-3A6AD204": "e", + "L-3A8255D8": "e", + "L-3A8F8BA2": "e", + "L-3ACA1751": "e", + "L-3AE4911A": "e", + "L-3AFE687B": "e", + "L-3B21AA31": "e", + "L-3B4E727B": "e", + "L-3B769A17": "e", + "L-3B7F2FD0": "e", + "L-3B90E5BF": "e", + "L-3B9CD1B7": "e", + "L-3BBC35A9": "e", + "L-3BDCD216": "e", + "L-3BE68F11": "e", + "L-3C2DFC4F": "e", + "L-3C2EBC55": "e", + "L-3C3B7CCF": "e", + "L-3C6ABE1D": "e", + "L-3C87D093": "e", + "L-3D0727A9": "e", + "L-3D2A1F33": "e", + "L-3D412385": "e", + "L-3D416567": "e", + "L-3D46E1E0": "e", + "L-3D78EEB8": "e", + "L-3E1C9273": "e", + "L-3E534129": "e", + "L-3E65B286": "e", + "L-3E715088": "e", + "L-3E88B45D": "e", + "L-3E9F0918": "e", + "L-3ED158E9": "e", + "L-3ED20532": "e", + "L-3EF45BE2": "e", + "L-3F07589A": "e", + "L-3F25BA48": "e", + "L-3F39DE8C": "e", + "L-3F48ACC6": "e", + "L-3F53BF0F": "e", + "L-3F6F4D62": "e", + "L-3F81F9D2": "e", + "L-3FA71971": "e", + "L-3FD3F6D0": "e", + "L-3FD7013E": "e", + "L-3FF6507A": "e", + "L-3FFC0D3D": "e", + "L-40008568": "e", + "L-400C1D8A": "e", + "L-402598A2": "e", + "L-4027057F": "e", + "L-405E5091": "e", + "L-406AF559": "e", + "L-4089485C": "e", + "L-409296C1": "e", + "L-409A03CD": "e", + "L-40A7DC79": "e", + "L-40CEEDD2": "e", + "L-40D07D7F": "e", + "L-40D4D8E2": "e", + "L-40E8018C": "e", + "L-40F00B06": "e", + "L-40F27D43": "e", + "L-414BC21A": "e", + "L-41667179": "e", + "L-417A2184": "e", + "L-41BFBF41": "e", + "L-41C11899": "e", + "L-41CDD438": "e", + "L-41CEEA13": "e", + "L-41D07CEF": "e", + "L-41DD34AF": "e", + "L-4209F944": "e", + "L-42313123": "e", + "L-4253355C": "e", + "L-42980B67": "e", + "L-42C5B178": "e", + "L-42E4149B": "e", + "L-42EAE6FA": "e", + "L-432B3C23": "e", + "L-433C561A": "e", + "L-434233AD": "e", + "L-43562353": "e", + "L-439BD1E0": "e", + "L-439D1ABB": "e", + "L-43F5FC95": "e", + "L-440296EB": "e", + "L-44097F05": "e", + "L-4422BF16": "e", + "L-445A4466": "e", + "L-446A17A2": "e", + "L-4473605D": "e", + "L-447AFC67": "e", + "L-448C2416": "e", + "L-44A2C8FD": "e", + "L-44E32710": "e", + "L-452C73A2": "e", + "L-4530EDEE": "e", + "L-454A2443": "e", + "L-455D9184": "e", + "L-456B4C5F": "e", + "L-457BA053": "e", + "L-4581C083": "e", + "L-459D61D1": "e", + "L-45BD621D": "e", + "L-45DB9C66": "e", + "L-45DE7A7D": "e", + "L-45F58E7E": "e", + "L-462E7E5F": "e", + "L-46345DE5": "e", + "L-463C0E1F": "e", + "L-4645950E": "e", + "L-4689E606": "e", + "L-46DE4134": "e", + "L-46E6B311": "e", + "L-46EB709C": "e", + "L-47461EBA": "e", + "L-4755F613": "e", + "L-477D3300": "e", + "L-4780A458": "e", + "L-478B474F": "e", + "L-479D8F33": "e", + "L-47C7A96D": "e", + "L-47E0BC8F": "e", + "L-47F095C9": "e", + "L-481BAB34": "e", + "L-4831B514": "e", + "L-483BAD88": "e", + "L-484388A9": "e", + "L-484E50DA": "e", + "L-486519E6": "e", + "L-48CFA376": "e", + "L-4918D123": "e", + "L-495AAEE0": "e", + "L-49679826": "e", + "L-496E33B0": "e", + "L-49765109": "e", + "L-497B63D2": "e", + "L-498DD93A": "e", + "L-49DACEA0": "e", + "L-49E4D2AB": "e", + "L-49F254F3": "e", + "L-49F8B39E": "e", + "L-4A20E33E": "e", + "L-4A319ECB": "e", + "L-4A34520C": "e", + "L-4A354C53": "e", + "L-4A423436": "e", + "L-4A5B28AA": "e", + "L-4A823FAB": "e", + "L-4A8D754D": "e", + "L-4A9F5F15": "e", + "L-4ABE1E63": "e", + "L-4ACAC7A4": "e", + "L-4AEBC16B": "e", + "L-4B55E427": "e", + "L-4B852A69": "e", + "L-4B99D021": "e", + "L-4B9D3092": "e", + "L-4BAB566C": "e", + "L-4BCBE0A9": "e", + "L-4C22A9A1": "e", + "L-4C2FABCC": "e", + "L-4C5C5CA8": "e", + "L-4C75B82E": "e", + "L-4C7F99A0": "e", + "L-4CC2593C": "e", + "L-4CE49CA4": "e", + "L-4CEE6BA6": "e", + "L-4D27DFDD": "e", + "L-4D652BD4": "e", + "L-4D6B5DFA": "e", + "L-4D8467A8": "e", + "L-4DE197AF": "e", + "L-4DE27018": "e", + "L-4E1689B6": "e", + "L-4E39DDC4": "e", + "L-4E487FFF": "e", + "L-4E81EEAC": "e", + "L-4E89F558": "e", + "L-4E9EE949": "e", + "L-4EA24ACA": "e", + "L-4EE1482A": "e", + "L-4F185009": "e", + "L-4F240258": "e", + "L-4F2BEC71": "e", + "L-4F34820D": "e", + "L-4F5CA161": "e", + "L-4FA8B53C": "e", + "L-4FC1E99C": "e", + "L-4FC79063": "e", + "L-4FDB33AC": "e", + "L-4FF47108": "e", + "L-50222063": "e", + "L-503F0204": "e", + "L-505634D0": "e", + "L-5064185C": "e", + "L-50755EC1": "e", + "L-50AA109F": "e", + "L-50B5B169": "e", + "L-513D1D07": "e", + "L-51467CBD": "e", + "L-514B50A3": "e", + "L-514B723C": "e", + "L-518B9BE7": "e", + "L-51B72E7C": "e", + "L-51BF3F2F": "e", + "L-51DC12F9": "e", + "L-51E035C0": "e", + "L-52008469": "e", + "L-52109CA8": "e", + "L-52150E9C": "e", + "L-52170FCB": "e", + "L-524FDA45": "e", + "L-525AAB0A": "e", + "L-528EF552": "e", + "L-529379E4": "e", + "L-529E971B": "e", + "L-529F88CE": "e", + "L-52A56414": "e", + "L-52C8D816": "e", + "L-52DB9D33": "e", + "L-52FB7989": "e", + "L-53138E1F": "e", + "L-53505EA6": "e", + "L-53570353": "e", + "L-536D2DD2": "e", + "L-5392B59D": "e", + "L-539D704C": "e", + "L-53A389CA": "e", + "L-540196E8": "e", + "L-54106F23": "e", + "L-54232165": "e", + "L-545CE6C9": "e", + "L-5490EE0D": "e", + "L-5498A089": "e", + "L-5498EAEB": "e", + "L-549BBD50": "e", + "L-54E3D0FA": "e", + "L-54F5C02D": "e", + "L-551F1065": "e", + "L-553A7396": "e", + "L-55671A7C": "e", + "L-557C20FC": "e", + "L-558B6165": "e", + "L-55E494BC": "e", + "L-55F9C48A": "e", + "L-56245D0D": "e", + "L-566A905C": "e", + "L-56AE9D73": "e", + "L-56C564CA": "e", + "L-56D01B5B": "e", + "L-56E181D2": "e", + "L-570B0415": "e", + "L-574C8A05": "e", + "L-57850F1B": "e", + "L-57998C77": "e", + "L-57A53C2D": "e", + "L-57AC4E19": "e", + "L-57CC4D0B": "e", + "L-57D137CF": "e", + "L-57E5D94E": "e", + "L-58132C71": "e", + "L-582AE722": "e", + "L-5843585A": "e", + "L-58672BCE": "e", + "L-5869E902": "e", + "L-58707733": "e", + "L-5884171D": "e", + "L-588D5F24": "e", + "L-588F9D8D": "e", + "L-589B0DBC": "e", + "L-589CE341": "e", + "L-589D9467": "e", + "L-58B96098": "e", + "L-58FD3671": "e", + "L-593EF138": "e", + "L-5952A009": "e", + "L-596C3331": "e", + "L-59C3957D": "e", + "L-59E4D2FE": "e", + "L-59F3BE31": "e", + "L-5AA68A28": "e", + "L-5AA715AC": "e", + "L-5AF0D27D": "e", + "L-5B185A90": "e", + "L-5B3C00A2": "e", + "L-5B66C272": "e", + "L-5B6F63A4": "e", + "L-5B7CF402": "e", + "L-5B86ED31": "e", + "L-5B9B8573": "e", + "L-5BB0DC68": "e", + "L-5C31AAE1": "e", + "L-5C47EA70": "e", + "L-5C591B94": "e", + "L-5C59A967": "e", + "L-5C6C0A97": "e", + "L-5C7D77C7": "e", + "L-5C911603": "e", + "L-5C991C75": "e", + "L-5CED4195": "e", + "L-5D26156C": "e", + "L-5D321F81": "e", + "L-5D40BC9D": "e", + "L-5D41DCC9": "e", + "L-5D454ED8": "e", + "L-5D747920": "e", + "L-5D78CA2D": "e", + "L-5D8382CB": "e", + "L-5D884672": "e", + "L-5DB1A9F5": "e", + "L-5DB40C3B": "e", + "L-5DB70460": "e", + "L-5DF429C6": "e", + "L-5E027003": "e", + "L-5E232B14": "e", + "L-5E2EB366": "e", + "L-5E364879": "e", + "L-5E942007": "e", + "L-5ECDEA91": "e", + "L-5EEB65E6": "e", + "L-5F015F52": "e", + "L-5F0C4D2F": "e", + "L-5F11F714": "e", + "L-5F238DF4": "e", + "L-5F2D4124": "e", + "L-5F356922": "e", + "L-5F5255E9": "e", + "L-5F6138EA": "e", + "L-5F747AE6": "e", + "L-5F7EBBE8": "e", + "L-5F970171": "e", + "L-5FF4FD93": "e", + "L-60033CF6": "e", + "L-60208949": "e", + "L-60313EA3": "e", + "L-60470224": "e", + "L-605A110B": "e", + "L-6074B0D4": "e", + "L-6078D9A8": "e", + "L-608EFB1F": "e", + "L-60986E7E": "e", + "L-60995545": "e", + "L-60D2A6F0": "e", + "L-60EA3D74": "e", + "L-6100AC7F": "e", + "L-610D6F9B": "e", + "L-61116077": "e", + "L-611FA074": "e", + "L-614B09FD": "e", + "L-614CBE09": "e", + "L-6198DF25": "e", + "L-619D690E": "r", + "L-619D6E43": "e", + "L-61C1E88D": "e", + "L-61F9C762": "e", + "L-622CFD70": "e", + "L-623492E5": "e", + "L-623DE453": "e", + "L-62B3C4B8": "e", + "L-62BEAF82": "e", + "L-62EA4CCE": "e", + "L-633B282D": "e", + "L-63443CBC": "e", + "L-6362B48D": "e", + "L-6394029D": "e", + "L-63B78C3C": "e", + "L-63D6347F": "e", + "L-63F6725D": "e", + "L-64067773": "e", + "L-64211729": "e", + "L-6430FA94": "e", + "L-649885BF": "e", + "L-64A55F0E": "e", + "L-64ACD16E": "e", + "L-64BB8154": "e", + "L-64CEEC80": "e", + "L-64D52F6C": "e", + "L-64EE493C": "e", + "L-650D2DBD": "e", + "L-6534DCD1": "e", + "L-656A17FA": "e", + "L-6572F0CF": "e", + "L-659C9942": "e", + "L-65C4BD00": "e", + "L-65D1CFE4": "e", + "L-65DEC561": "e", + "L-660332DA": "e", + "L-660A18BE": "e", + "L-660E0683": "e", + "L-661EA218": "e", + "L-663B74F3": "e", + "L-66425F2A": "e", + "L-6665A739": "e", + "L-66959465": "e", + "L-669A1EF3": "e", + "L-66A9D66D": "e", + "L-66EDE70E": "e", + "L-66EEC93C": "e", + "L-670EF747": "e", + "L-673ED3E0": "e", + "L-674607CA": "e", + "L-676D5145": "e", + "L-67A4559B": "e", + "L-67BEA0AE": "e", + "L-67E7209D": "e", + "L-67FB3E67": "e", + "L-6821867B": "e", + "L-6829423A": "e", + "L-68480206": "e", + "L-68515813": "e", + "L-6865522E": "e", + "L-68803DFB": "e", + "L-68CFD09E": "e", + "L-68F1663F": "e", + "L-692AF693": "e", + "L-692B8304": "e", + "L-6958265E": "e", + "L-6995701D": "e", + "L-699A2417": "e", + "L-69AC3D57": "e", + "L-69ACE3A0": "e", + "L-69C6935E": "e", + "L-69CB6693": "e", + "L-69F0FD66": "e", + "L-69F95BD9": "e", + "L-6A1195AF": "e", + "L-6A1D833C": "e", + "L-6A3E5D65": "e", + "L-6A6E4B44": "e", + "L-6A77BD0A": "e", + "L-6A85BC13": "e", + "L-6AB46401": "e", + "L-6ABF7180": "e", + "L-6B08BAE2": "e", + "L-6B0B7E9C": "e", + "L-6B2D8331": "e", + "L-6B466E90": "e", + "L-6B4D5C65": "e", + "L-6B5E5FD1": "e", + "L-6B83CDAF": "e", + "L-6B852928": "e", + "L-6BC1B1A9": "e", + "L-6BC20E76": "e", + "L-6BC98A55": "e", + "L-6BE85179": "e", + "L-6BFE47CA": "e", + "L-6C1DCF33": "e", + "L-6C438A61": "e", + "L-6C44F58D": "e", + "L-6C5791AF": "e", + "L-6C6CBBDE": "e", + "L-6C73443F": "e", + "L-6C7C4F4E": "e", + "L-6C9165E8": "e", + "L-6C919CDA": "e", + "L-6CE24819": "e", + "L-6D0166BE": "e", + "L-6D248045": "e", + "L-6D2BF8A8": "e", + "L-6D51E38C": "e", + "L-6D8344B7": "e", + "L-6D865216": "e", + "L-6DA79B36": "e", + "L-6DACF132": "e", + "L-6DF60D19": "e", + "L-6E02BD88": "e", + "L-6EB47485": "e", + "L-6EF3AE05": "e", + "L-6F0044E7": "e", + "L-6F01766F": "e", + "L-6F0C387D": "e", + "L-6F0EC0FD": "e", + "L-6F1D5EF1": "e", + "L-6F258322": "e", + "L-6F300DAD": "e", + "L-6F46EF71": "e", + "L-6F5C80EF": "e", + "L-6F69996E": "e", + "L-6F6C723E": "e", + "L-6F6C8949": "e", + "L-6F947DE5": "e", + "L-6FA0D387": "e", + "L-6FA7C073": "e", + "L-6FCDFC95": "e", + "L-6FEE2118": "e", + "L-6FEE87BA": "e", + "L-6FF806F0": "s", + "L-70202030": "e", + "L-702CCDF6": "e", + "L-7036F14A": "e", + "L-7064D1BA": "e", + "L-70680787": "e", + "L-7090EA49": "e", + "L-709B83E7": "e", + "L-70A53B0D": "e", + "L-70D6AEA1": "e", + "L-70E251A3": "e", + "L-70FCDC93": "e", + "L-713F6743": "e", + "L-71602C2F": "e", + "L-716AE28A": "e", + "L-718F98E5": "e", + "L-719822E7": "e", + "L-71EA14AB": "e", + "L-71FAF417": "e", + "L-72017957": "e", + "L-721FFF7B": "e", + "L-723CA4FF": "e", + "L-72530F39": "e", + "L-72546128": "e", + "L-72C89816": "e", + "L-72EF9D60": "e", + "L-73081A3A": "e", + "L-732722E0": "e", + "L-73887D5F": "e", + "L-73BEF3A2": "e", + "L-73C1B556": "e", + "L-73CEF87D": "e", + "L-73EC964F": "e", + "L-73EF2FAD": "e", + "L-740B1EB1": "e", + "L-7412F8CF": "e", + "L-7432A529": "e", + "L-744ED636": "e", + "L-74B46909": "e", + "L-74C31E8C": "e", + "L-74F2FC79": "e", + "L-751BCA3E": "e", + "L-754870FD": "e", + "L-754B3F4D": "e", + "L-754E1E96": "e", + "L-757BF5DF": "e", + "L-75A970F1": "e", + "L-75B2C685": "e", + "L-75EB91B4": "e", + "L-76243C5D": "e", + "L-762E95F4": "e", + "L-763BE1DA": "e", + "L-76416BA5": "e", + "L-76501DC2": "e", + "L-7671BF83": "e", + "L-769D172E": "e", + "L-769E114F": "e", + "L-76A72DE0": "e", + "L-76A7309C": "e", + "L-76AB2C05": "e", + "L-76AF5271": "e", + "L-76D497CD": "e", + "L-77076358": "e", + "L-777AE4B1": "e", + "L-77A018DC": "e", + "L-77A19314": "e", + "L-77AB07C8": "e", + "L-77B8159A": "e", + "L-77C35A0F": "e", + "L-77F250EB": "e", + "L-78071778": "e", + "L-7812C452": "e", + "L-78134DD5": "e", + "L-78278E63": "e", + "L-786E9B47": "e", + "L-7877B3D0": "e", + "L-7882E313": "e", + "L-789B4081": "e", + "L-78B3DA25": "e", + "L-78F18862": "e", + "L-7939E4EC": "e", + "L-799BE65F": "e", + "L-79A1FE57": "e", + "L-7A2078B7": "e", + "L-7A3DF611": "e", + "L-7A3E0A2C": "e", + "L-7A45086A": "e", + "L-7A728BB1": "e", + "L-7AA0FEE8": "e", + "L-7AB35940": "e", + "L-7ACB52C8": "e", + "L-7AD98814": "e", + "L-7B0277D0": "e", + "L-7B0F0F3C": "e", + "L-7B131A59": "e", + "L-7B177AC5": "e", + "L-7B2FD69B": "e", + "L-7B594E29": "e", + "L-7B628106": "e", + "L-7B64C2AB": "e", + "L-7B7E548F": "e", + "L-7B952AC7": "e", + "L-7BADE66F": "e", + "L-7BD2C9FA": "e", + "L-7BDD9EA3": "e", + "L-7C414CEE": "e", + "L-7C455C9D": "e", + "L-7C5EE730": "e", + "L-7C9662F1": "e", + "L-7CAFE77E": "e", + "L-7D04AB42": "e", + "L-7D217E5D": "e", + "L-7D28AD75": "e", + "L-7D7D7FDC": "e", + "L-7D7E7979": "e", + "L-7DC6CDE9": "e", + "L-7E15CC53": "e", + "L-7E4516BC": "e", + "L-7E4BD8B0": "e", + "L-7E503C5F": "e", + "L-7E64AD11": "e", + "L-7E675D8C": "e", + "L-7E95878B": "e", + "L-7E9F3C5B": "e", + "L-7EB267B3": "e", + "L-7EE97E19": "e", + "L-7F2FEE7C": "e", + "L-7F87790B": "e", + "L-7FA2A64F": "e", + "L-7FA30C5D": "e", + "L-7FC7DB15": "e", + "L-7FCEC8AA": "e", + "L-7FD92B01": "e", + "L-7FEDBA4C": "e", + "L-7FFAF4CB": "e", + "L-802752F2": "e", + "L-80324B66": "e", + "L-804C2AFF": "e", + "L-8051418F": "e", + "L-80BD5FD2": "e", + "L-80F387A8": "e", + "L-8101A535": "e", + "L-812CA1D8": "e", + "L-813472D5": "e", + "L-81482A8C": "e", + "L-814FCB98": "e", + "L-815920B3": "e", + "L-81940D85": "e", + "L-819B4B27": "e", + "L-819FD5DE": "e", + "L-81AF96F3": "e", + "L-81CDC86A": "e", + "L-81DAAA90": "e", + "L-81F1B7AE": "e", + "L-822C5A39": "e", + "L-823DAB46": "e", + "L-823F5794": "e", + "L-824CD705": "e", + "L-82733FAD": "e", + "L-8276C21E": "e", + "L-82833386": "e", + "L-828518C2": "e", + "L-82BE9A32": "e", + "L-82BF4638": "e", + "L-82D4B920": "e", + "L-82E1C851": "e", + "L-82E48A74": "e", + "L-82E81781": "e", + "L-82FF331C": "e", + "L-8345B953": "e", + "L-834BF903": "e", + "L-835D2208": "e", + "L-83872361": "e", + "L-83A50567": "e", + "L-83AB5D73": "e", + "L-83B9E934": "e", + "L-840B9D15": "e", + "L-8424F042": "e", + "L-843BE5AB": "e", + "L-8442D925": "e", + "L-84597A27": "e", + "L-845DE61C": "e", + "L-8489026E": "e", + "L-8497E1A4": "e", + "L-84FD48DA": "e", + "L-8510FD88": "e", + "L-8536F2DB": "e", + "L-8541302D": "e", + "L-8553AE9A": "e", + "L-85573624": "e", + "L-85655586": "e", + "L-85870296": "e", + "L-85A2B166": "e", + "L-85D4BAF3": "e", + "L-85DBDADC": "e", + "L-85E60595": "e", + "L-85F71386": "e", + "L-8604A8F3": "e", + "L-860ED60D": "r", + "L-86177F8A": "e", + "L-862299A2": "e", + "L-862C1E14": "e", + "L-866A1DFA": "e", + "L-867702E6": "e", + "L-8679F6F3": "e", + "L-86822EDB": "e", + "L-86845C1F": "e", + "L-86B65D1A": "e", + "L-86BF447B": "e", + "L-86CB710A": "e", + "L-86F70267": "e", + "L-86FD5133": "e", + "L-87055470": "e", + "L-8716E6AE": "e", + "L-8728B705": "e", + "L-8733EEBD": "e", + "L-87545E46": "e", + "L-8762A75F": "e", + "L-878E276D": "e", + "L-87958880": "e", + "L-87989AE6": "e", + "L-87B4DF3C": "e", + "L-87F51045": "e", + "L-880B4961": "e", + "L-880D1D30": "e", + "L-88193F03": "e", + "L-881E6536": "e", + "L-88244E2D": "e", + "L-882F7F72": "e", + "L-88A9A89E": "e", + "L-88D186EC": "e", + "L-88E48241": "e", + "L-89737A45": "e", + "L-89855A04": "e", + "L-899C16F4": "e", + "L-899D2891": "e", + "L-89ECDAA9": "e", + "L-89F2FD35": "e", + "L-8A658090": "e", + "L-8A6C3F0E": "e", + "L-8A72B806": "e", + "L-8A9BC23B": "e", + "L-8AB02F72": "e", + "L-8ACE1754": "e", + "L-8ACE3F87": "e", + "L-8AF51A42": "e", + "L-8B04A568": "e", + "L-8B077C42": "e", + "L-8B308035": "e", + "L-8B72D8E1": "e", + "L-8B83C3A5": "e", + "L-8B9D0385": "e", + "L-8BACBF19": "e", + "L-8BB74069": "e", + "L-8BC5FA3F": "e", + "L-8BD17C20": "e", + "L-8BED04E5": "e", + "L-8BF5F502": "e", + "L-8C2C8B44": "e", + "L-8C4E467D": "e", + "L-8C616CCB": "e", + "L-8C9D5748": "e", + "L-8CB23490": "e", + "L-8CB3A099": "e", + "L-8CC2A52D": "e", + "L-8CCF67BD": "e", + "L-8CD1FE93": "e", + "L-8CE02637": "e", + "L-8D013305": "e", + "L-8D0356D0": "e", + "L-8D196E75": "e", + "L-8D2ED7BF": "e", + "L-8D386551": "e", + "L-8D49161D": "e", + "L-8D494B44": "e", + "L-8DCA2E97": "e", + "L-8DCEB521": "e", + "L-8DE26E59": "e", + "L-8E2DEB6B": "e", + "L-8E454C05": "e", + "L-8E5333B4": "e", + "L-8E5A292F": "e", + "L-8E6F4665": "e", + "L-8E9C8FDD": "e", + "L-8EE21F5A": "e", + "L-8EE25AE3": "e", + "L-8EEC3896": "e", + "L-8F13CFFD": "e", + "L-8F196256": "e", + "L-8F1E628E": "e", + "L-8F2081D3": "e", + "L-8F28AFFB": "e", + "L-8F6952F2": "e", + "L-8F818E82": "e", + "L-8F92321F": "e", + "L-8F99BDDC": "e", + "L-8FAD84BA": "e", + "L-8FE64BAB": "e", + "L-901586D2": "e", + "L-9025A0D4": "e", + "L-9037D736": "e", + "L-9055BEAC": "e", + "L-905FB1FD": "e", + "L-905FFCC4": "e", + "L-9072E86E": "e", + "L-90765203": "e", + "L-909CDAD7": "e", + "L-90CB5A12": "e", + "L-90D2ED40": "e", + "L-90ED9514": "e", + "L-91388851": "e", + "L-913947FA": "e", + "L-91413A4F": "e", + "L-91580987": "e", + "L-9164D5E4": "e", + "L-919688C1": "e", + "L-91B8A708": "e", + "L-91BE41FB": "e", + "L-91CDDDD6": "e", + "L-91EF989B": "e", + "L-9215A13F": "e", + "L-924D392D": "e", + "L-925D4671": "e", + "L-9260DE8C": "e", + "L-92BDBBEF": "r", + "L-92D1521D": "e", + "L-9333FCD3": "e", + "L-93490D80": "e", + "L-934B4E57": "e", + "L-93531071": "e", + "L-93536A4B": "e", + "L-9388DC01": "e", + "L-93958082": "e", + "L-9398D219": "e", + "L-93CA7384": "e", + "L-93DC53C2": "e", + "L-93E556F5": "e", + "L-940A662A": "e", + "L-941884ED": "e", + "L-9421DC3A": "e", + "L-944F78BB": "e", + "L-945D1F1D": "e", + "L-945D83D8": "e", + "L-9499D968": "e", + "L-94A6D751": "e", + "L-94B31A5D": "e", + "L-94C3A7A1": "e", + "L-94E271A3": "e", + "L-94E6B40C": "e", + "L-95233547": "e", + "L-954CE822": "e", + "L-955074FD": "e", + "L-95528A90": "e", + "L-956703D9": "e", + "L-95907AFF": "e", + "L-9592FA20": "e", + "L-95B12835": "e", + "L-95C2C3D0": "e", + "L-95C5728F": "e", + "L-95D01B50": "e", + "L-95E39457": "e", + "L-9614C779": "e", + "L-962247BA": "e", + "L-962705EA": "e", + "L-96300102": "e", + "L-9639CC81": "e", + "L-964887D9": "e", + "L-96866D65": "e", + "L-9691D529": "e", + "L-9694914A": "e", + "L-96A28D02": "e", + "L-96B75525": "e", + "L-96D8C574": "e", + "L-9723DD27": "e", + "L-9752E3B3": "e", + "L-9760E62B": "e", + "L-97623E1D": "e", + "L-9772863B": "e", + "L-9778E614": "e", + "L-978CD7EC": "e", + "L-97A2C724": "e", + "L-97AC1A59": "s", + "L-97C33A46": "e", + "L-97CDCF2E": "e", + "L-97CF11BE": "e", + "L-97CF460D": "e", + "L-982813E2": "e", + "L-982BF852": "e", + "L-98345D70": "e", + "L-9849A15E": "e", + "L-98560DD6": "e", + "L-98742DAD": "e", + "L-9883FE68": "e", + "L-988CE6C5": "e", + "L-989B6391": "e", + "L-98A71395": "e", + "L-98B8C60B": "e", + "L-98BDE811": "e", + "L-98BFB21C": "e", + "L-98D57156": "e", + "L-98E75A5B": "e", + "L-98E77032": "e", + "L-98F45D48": "e", + "L-9944ECC4": "e", + "L-9945B4DC": "e", + "L-994A48B1": "e", + "L-99850BD6": "e", + "L-99850E94": "e", + "L-99881E10": "e", + "L-99AD19BF": "e", + "L-99AEC235": "e", + "L-99E18227": "e", + "L-9A2C5AF9": "e", + "L-9A32E51C": "e", + "L-9A5FC4CF": "e", + "L-9A82FBCA": "e", + "L-9AB16BF2": "e", + "L-9AD04286": "e", + "L-9AD1D725": "e", + "L-9AD5A106": "e", + "L-9B0F550F": "e", + "L-9BA5373F": "e", + "L-9BB545D2": "e", + "L-9BCBBE07": "e", + "L-9BCF3CC1": "e", + "L-9BE199B8": "e", + "L-9BF41C0F": "e", + "L-9C193905": "e", + "L-9C2C5056": "e", + "L-9C33052B": "e", + "L-9C39178F": "e", + "L-9C72BEE2": "e", + "L-9C7D809E": "e", + "L-9C8CF3DC": "e", + "L-9CD2705A": "e", + "L-9CE6464D": "e", + "L-9D10CA98": "e", + "L-9D41067A": "e", + "L-9D578B5E": "e", + "L-9D9F9978": "e", + "L-9E017069": "e", + "L-9E17732C": "e", + "L-9E4D1B86": "e", + "L-9EB01111": "e", + "L-9EF527CA": "e", + "L-9EFE4FAD": "e", + "L-9F2E8F67": "e", + "L-9F390BA7": "e", + "L-9F3B1F91": "e", + "L-9F536CF3": "e", + "L-9F74539F": "e", + "L-9FA8FC21": "e", + "L-9FAC65F7": "e", + "L-9FB41A1C": "e", + "L-9FC178C2": "s", + "L-9FCA2A26": "e", + "L-9FE5CC2D": "e", + "L-9FEBBCCF": "e", + "L-A028E7A2": "e", + "L-A06D6E01": "e", + "L-A075DD71": "e", + "L-A077CE88": "e", + "L-A0AA96EC": "e", + "L-A0B4500D": "e", + "L-A0B632ED": "e", + "L-A0B6ED81": "e", + "L-A0C4F9CF": "e", + "L-A0C828DC": "e", + "L-A0E4DD54": "e", + "L-A0EDD8D6": "e", + "L-A1025C0C": "e", + "L-A1364089": "e", + "L-A139A306": "e", + "L-A1420A06": "e", + "L-A15DF696": "e", + "L-A16FEEFE": "e", + "L-A1E21094": "e", + "L-A2018E14": "e", + "L-A202A665": "e", + "L-A21B0713": "e", + "L-A24E5700": "e", + "L-A24FA80D": "e", + "L-A2512F8F": "e", + "L-A28AF48F": "e", + "L-A2987032": "e", + "L-A2A04122": "e", + "L-A2BBA421": "e", + "L-A2CBFCEB": "e", + "L-A2E4CEFE": "e", + "L-A2EAB650": "e", + "L-A31DE840": "e", + "L-A32DD430": "e", + "L-A373146E": "e", + "L-A37B67B0": "s", + "L-A3C7A675": "e", + "L-A4021168": "e", + "L-A40ED4BA": "e", + "L-A4176927": "e", + "L-A4213CB4": "e", + "L-A43A8354": "e", + "L-A4519BF1": "e", + "L-A4529C29": "e", + "L-A47E464A": "e", + "L-A48244DF": "e", + "L-A499F092": "e", + "L-A4A0DA1F": "e", + "L-A4B610DA": "e", + "L-A4BC6738": "e", + "L-A4C3B69F": "e", + "L-A4C63F0B": "e", + "L-A50827DD": "e", + "L-A50937E5": "e", + "L-A56EEC3D": "e", + "L-A581FF18": "e", + "L-A5D63399": "e", + "L-A60122FA": "e", + "L-A62BA7D5": "e", + "L-A6338E51": "e", + "L-A63CA0EB": "e", + "L-A6419EF6": "e", + "L-A68C3C9C": "e", + "L-A6D99163": "e", + "L-A72DDE21": "e", + "L-A7B1AACC": "e", + "L-A7C15116": "e", + "L-A7E8B111": "e", + "L-A810B462": "e", + "L-A81B1CDA": "e", + "L-A82A7A66": "e", + "L-A82B1FAA": "e", + "L-A82FD95C": "e", + "L-A8827666": "e", + "L-A886A53A": "e", + "L-A8A29A23": "e", + "L-A8D4F8F1": "e", + "L-A8D5B4AA": "e", + "L-A9165189": "e", + "L-A9527A17": "e", + "L-A956DBC1": "e", + "L-A97F0519": "e", + "L-A981C815": "e", + "L-A9984063": "e", + "L-A9CD2FA4": "e", + "L-A9CEE0B1": "r", + "L-A9F2A8B3": "e", + "L-A9FC6DCE": "e", + "L-AA009456": "e", + "L-AA088DA9": "e", + "L-AA22B8B9": "e", + "L-AA3D1CAF": "e", + "L-AA5E2462": "e", + "L-AA6A4B7A": "e", + "L-AA7135D4": "e", + "L-AA8CF8C4": "e", + "L-AA91CB2D": "e", + "L-AA934E56": "e", + "L-AABA5942": "e", + "L-AAEA9BBA": "e", + "L-AAFE580F": "e", + "L-AB07B9D7": "e", + "L-AB53E0CA": "e", + "L-AB6AF669": "e", + "L-ABAC207F": "e", + "L-ABB537FE": "e", + "L-ABFCF5A2": "e", + "L-AC014CFB": "e", + "L-AC01B100": "e", + "L-AC46C40F": "e", + "L-AC802292": "e", + "L-AC9EC023": "e", + "L-ACC42312": "e", + "L-ACC7B78A": "e", + "L-ACD9A4A4": "e", + "L-ACE0238D": "e", + "L-AD0A282D": "e", + "L-AD2803B7": "e", + "L-AD3B35FF": "e", + "L-AD4C1352": "e", + "L-AD4F8F19": "e", + "L-AD63F1D2": "e", + "L-AD673AF4": "e", + "L-AD872881": "e", + "L-ADA32A50": "e", + "L-ADBE66E5": "e", + "L-AE0B3C3D": "e", + "L-AE2F2D88": "e", + "L-AE3447AD": "e", + "L-AE407E8B": "e", + "L-AE505887": "e", + "L-AE77DC5F": "e", + "L-AE93C70E": "e", + "L-AE9844E7": "e", + "L-AE9BB280": "e", + "L-AEB45880": "e", + "L-AEC7560A": "e", + "L-AED8308D": "e", + "L-AF068A53": "e", + "L-AF19906B": "e", + "L-AF1BC9E1": "e", + "L-AF2D2EF0": "e", + "L-AF730FBA": "e", + "L-AFA9FE18": "e", + "L-AFB011B4": "e", + "L-AFE9C4DD": "e", + "L-AFEEB9EB": "e", + "L-B013C051": "e", + "L-B028B942": "e", + "L-B039EA8F": "e", + "L-B03C553E": "e", + "L-B03F1DF1": "e", + "L-B06EA6BA": "e", + "L-B0729CB4": "e", + "L-B08CBB5F": "e", + "L-B0935949": "e", + "L-B0A4992C": "e", + "L-B0E221DE": "e", + "L-B0F91871": "e", + "L-B1369D96": "e", + "L-B156D5EC": "e", + "L-B1845A48": "e", + "L-B18ED706": "e", + "L-B1A16872": "e", + "L-B1B56F28": "e", + "L-B1C4D018": "e", + "L-B21D8B36": "e", + "L-B232DF69": "e", + "L-B257AB01": "e", + "L-B25B9B93": "e", + "L-B2708489": "e", + "L-B271A5D9": "e", + "L-B2B3BA64": "e", + "L-B2D8E643": "e", + "L-B2E25E6A": "e", + "L-B307949A": "e", + "L-B3115215": "e", + "L-B32755B6": "e", + "L-B3737E03": "e", + "L-B38DFB56": "e", + "L-B3C459F9": "e", + "L-B3E8DB38": "e", + "L-B3FC00CD": "e", + "L-B41FBF28": "e", + "L-B45EB4FB": "e", + "L-B46EE84C": "e", + "L-B475E421": "e", + "L-B49B1A1D": "e", + "L-B49BE842": "e", + "L-B4C54251": "e", + "L-B5124877": "e", + "L-B538D5DB": "e", + "L-B54F7F84": "e", + "L-B55E0D86": "e", + "L-B5612E02": "e", + "L-B576EB07": "e", + "L-B581F102": "e", + "L-B5D1E461": "e", + "L-B5F303BE": "e", + "L-B615DA47": "e", + "L-B644CD97": "e", + "L-B6744048": "e", + "L-B67CFA0C": "e", + "L-B683BCB0": "e", + "L-B68C8DD7": "e", + "L-B6A274A9": "e", + "L-B6A6325E": "e", + "L-B6A7569B": "e", + "L-B6BF3EB3": "e", + "L-B6C81670": "e", + "L-B6CCB600": "e", + "L-B6D80D9C": "e", + "L-B6DC27DA": "e", + "L-B6F23298": "e", + "L-B7228EBF": "e", + "L-B7476528": "e", + "L-B74ED3C1": "e", + "L-B760DBE2": "e", + "L-B78A48C6": "e", + "L-B7A07BB4": "e", + "L-B7AC53F5": "e", + "L-B7AE5453": "e", + "L-B7E8699C": "e", + "L-B7EB1FFD": "e", + "L-B82FDF78": "e", + "L-B832721E": "e", + "L-B8378206": "e", + "L-B83BF0BE": "e", + "L-B861EF4F": "e", + "L-B87A968D": "e", + "L-B896E0F0": "e", + "L-B89C4B79": "e", + "L-B8A3B4CE": "e", + "L-B8C1F9B8": "e", + "L-B8C736D2": "e", + "L-B9080C32": "e", + "L-B95AAE44": "e", + "L-B9622553": "e", + "L-B9676308": "e", + "L-B9718876": "e", + "L-B984C7D5": "e", + "L-B98A08AE": "e", + "L-B99D4EA0": "e", + "L-B9D177E1": "e", + "L-BA1813FD": "e", + "L-BA5B2FC5": "e", + "L-BA5C7A54": "e", + "L-BA72913B": "e", + "L-BA8533D8": "e", + "L-BA8ED5F7": "e", + "L-BAC087B0": "e", + "L-BB4358AA": "e", + "L-BB48CD38": "e", + "L-BB5CBB0A": "e", + "L-BB6D1028": "e", + "L-BB72E7FA": "e", + "L-BB73F76A": "e", + "L-BBC55C18": "e", + "L-BBD8E270": "e", + "L-BC1C7D38": "e", + "L-BC53B882": "e", + "L-BC684567": "e", + "L-BC6B3288": "e", + "L-BC8DC54C": "e", + "L-BCA2C892": "e", + "L-BCA7D0DE": "e", + "L-BCBB517D": "e", + "L-BCBC84AA": "e", + "L-BCC8C118": "e", + "L-BCDEC7B7": "e", + "L-BD05AE89": "e", + "L-BD09952F": "e", + "L-BD5D7AC4": "e", + "L-BD94420E": "e", + "L-BD97DD7F": "e", + "L-BDDC56AF": "e", + "L-BDE6CD7C": "e", + "L-BDE9EBA6": "e", + "L-BE072D49": "e", + "L-BE30C13D": "e", + "L-BE44390B": "e", + "L-BE5CC080": "e", + "L-BE78F29C": "e", + "L-BE792A7A": "e", + "L-BE8887A6": "e", + "L-BE9444D9": "e", + "L-BEAAFC2A": "e", + "L-BEAB58FB": "e", + "L-BEAEADC8": "e", + "L-BEF3120E": "e", + "L-BF4FD612": "e", + "L-BF6C9DF0": "e", + "L-BF717A6B": "e", + "L-BFB30A8F": "e", + "L-BFB9CF17": "e", + "L-BFC791D3": "e", + "L-C03DE874": "e", + "L-C056993F": "e", + "L-C0592240": "e", + "L-C076FA77": "e", + "L-C087612A": "e", + "L-C0932422": "e", + "L-C0EE91EF": "e", + "L-C1031CE4": "e", + "L-C104F114": "e", + "L-C10DAD58": "e", + "L-C15ACFF4": "e", + "L-C177D66D": "e", + "L-C17B05C4": "e", + "L-C1971434": "e", + "L-C1AE5754": "e", + "L-C1AEC017": "e", + "L-C1B9A48D": "e", + "L-C1E1B95D": "e", + "L-C1E62DF0": "e", + "L-C1E6B202": "e", + "L-C1E99663": "e", + "L-C1EBA9C5": "e", + "L-C22BC883": "e", + "L-C2495BC4": "e", + "L-C24CB777": "e", + "L-C252BCE1": "e", + "L-C26F34DD": "e", + "L-C2764A80": "e", + "L-C2EE0881": "e", + "L-C2F29972": "e", + "L-C2F8103D": "e", + "L-C35F807B": "e", + "L-C376D770": "e", + "L-C398571A": "e", + "L-C3D4DF76": "e", + "L-C3D4FFD3": "e", + "L-C3E706F6": "e", + "L-C4008A6B": "e", + "L-C41D2F34": "e", + "L-C4557679": "e", + "L-C471285D": "e", + "L-C473817C": "e", + "L-C47C8B74": "e", + "L-C4888F30": "e", + "L-C491AA4E": "e", + "L-C4B5BAD2": "e", + "L-C4DFBAA1": "e", + "L-C4DFF0A4": "e", + "L-C51A0845": "e", + "L-C54D91F0": "e", + "L-C56471C1": "e", + "L-C56646C7": "e", + "L-C5747110": "e", + "L-C57B8181": "e", + "L-C5868C0C": "e", + "L-C5957AE3": "e", + "L-C5A266EB": "s", + "L-C5A57F3A": "e", + "L-C5B2C408": "e", + "L-C5B4EE09": "e", + "L-C6079701": "e", + "L-C623FF97": "e", + "L-C6383286": "e", + "L-C63F67EB": "e", + "L-C6475AE6": "e", + "L-C65F49F2": "e", + "L-C672D01A": "e", + "L-C691FBAD": "e", + "L-C6A59B44": "e", + "L-C6BBE00E": "e", + "L-C6D76AE4": "e", + "L-C720D775": "e", + "L-C7494E04": "e", + "L-C778D3A3": "e", + "L-C7B212A3": "e", + "L-C7BEBCB1": "e", + "L-C7DCB657": "e", + "L-C7DFB707": "e", + "L-C7E07AA3": "e", + "L-C8044861": "e", + "L-C80F4352": "e", + "L-C8435EBB": "e", + "L-C87FF004": "e", + "L-C88C8F13": "e", + "L-C8AB7CDA": "e", + "L-C8B8462D": "e", + "L-C92FFAA6": "e", + "L-C960C80D": "e", + "L-C987E47F": "e", + "L-C9ED4ED5": "e", + "L-CAEE7DB7": "e", + "L-CAF39894": "e", + "L-CB3AFEA8": "e", + "L-CB4A3655": "e", + "L-CB4B91F3": "e", + "L-CB91E77C": "e", + "L-CB950CCC": "e", + "L-CB985DC5": "e", + "L-CBBEA301": "e", + "L-CBC0DA93": "e", + "L-CBCD290E": "e", + "L-CBD538A0": "e", + "L-CC005C69": "e", + "L-CC2440A6": "e", + "L-CC2F569C": "e", + "L-CC3E5CD9": "e", + "L-CC43FB8C": "e", + "L-CC49F990": "e", + "L-CC51C2FF": "e", + "L-CC5B8B01": "e", + "L-CC5DE39F": "e", + "L-CC73B658": "e", + "L-CC8A31D8": "e", + "L-CCA2CA42": "e", + "L-CCCB6E3C": "e", + "L-CCE2AFA6": "e", + "L-CCE416BB": "e", + "L-CCE6D1FE": "e", + "L-CCEE4B8C": "e", + "L-CD017EBE": "e", + "L-CD2E4A56": "e", + "L-CD3B6B80": "e", + "L-CDC3B509": "e", + "L-CDED0ECA": "e", + "L-CDFDF9FD": "e", + "L-CE130130": "e", + "L-CE1EB492": "e", + "L-CE2C0A43": "e", + "L-CE3F2C41": "e", + "L-CE651AF3": "e", + "L-CE6894AA": "e", + "L-CE772A48": "e", + "L-CE8E42E7": "e", + "L-CEED8B6B": "e", + "L-CEEF9A6E": "e", + "L-CEF64FB3": "e", + "L-CF4A1BAE": "e", + "L-CF4CD130": "e", + "L-CF4F44AD": "e", + "L-CF81ED81": "e", + "L-CFB5DBA6": "e", + "L-CFC2D5B6": "r", + "L-CFF1A7E1": "e", + "L-D0327E29": "e", + "L-D04B88E2": "e", + "L-D0B132AA": "e", + "L-D0CF48EC": "e", + "L-D0DB93EE": "e", + "L-D0EA3DC8": "e", + "L-D12B1AA4": "e", + "L-D144443B": "e", + "L-D152CACC": "e", + "L-D19CD1B0": "e", + "L-D1AD4A42": "e", + "L-D1AFBF6F": "e", + "L-D1BB9472": "e", + "L-D1E4F16E": "e", + "L-D1F7791E": "e", + "L-D205D3F0": "e", + "L-D216E27D": "e", + "L-D21B7162": "e", + "L-D24A5F8F": "e", + "L-D25FCBA1": "e", + "L-D266139B": "e", + "L-D267F635": "e", + "L-D27958C4": "e", + "L-D2C0D965": "e", + "L-D2CAE1E9": "e", + "L-D327D87C": "e", + "L-D33B72B9": "e", + "L-D3405E53": "e", + "L-D35E48B2": "e", + "L-D36E23E0": "e", + "L-D371F6EE": "e", + "L-D39ED03D": "e", + "L-D3CC7B01": "e", + "L-D453A347": "e", + "L-D460D348": "e", + "L-D463F25C": "e", + "L-D470D954": "e", + "L-D4D7435A": "e", + "L-D4EE434E": "e", + "L-D5106C9A": "e", + "L-D51166BE": "e", + "L-D526E050": "e", + "L-D531C9E1": "e", + "L-D53933F5": "e", + "L-D589112D": "e", + "L-D59D021D": "e", + "L-D5B455AB": "e", + "L-D5D3B1E5": "e", + "L-D62610A9": "e", + "L-D630F51C": "e", + "L-D6B12C16": "e", + "L-D6B1EB0D": "e", + "L-D6EBD1A9": "e", + "L-D6EC8840": "e", + "L-D7137944": "e", + "L-D71E726A": "e", + "L-D7932DDD": "e", + "L-D79647DB": "e", + "L-D79CD3FC": "e", + "L-D7BEE2A3": "s", + "L-D7CE983F": "e", + "L-D7D166A0": "e", + "L-D7D29FB6": "e", + "L-D7D95295": "e", + "L-D7ED8DED": "e", + "L-D7FE33BF": "e", + "L-D7FF3362": "e", + "L-D86AAFA8": "e", + "L-D8830406": "e", + "L-D885850D": "e", + "L-D88B02E6": "e", + "L-D88DB51B": "e", + "L-D8A31F81": "e", + "L-D8A40472": "e", + "L-D8B97089": "e", + "L-D8CDAD21": "e", + "L-D8DFE05F": "e", + "L-D8FA228C": "e", + "L-D91735C4": "e", + "L-D948A761": "e", + "L-D94FCADC": "e", + "L-D980A66A": "e", + "L-D98C40FA": "e", + "L-D9B45548": "e", + "L-D9B5C786": "e", + "L-D9DCC153": "e", + "L-D9E59670": "e", + "L-D9F69758": "e", + "L-DA37C575": "e", + "L-DA5A09B2": "e", + "L-DA7C9B9C": "e", + "L-DA9E8BF2": "e", + "L-DAAB3C8A": "e", + "L-DAAEE9A4": "e", + "L-DAB12A9F": "e", + "L-DAB6AA41": "e", + "L-DABA7ED5": "e", + "L-DACE30FC": "e", + "L-DAE78A2A": "e", + "L-DAF97953": "e", + "L-DB00E0E3": "e", + "L-DB0AB79F": "e", + "L-DB171767": "e", + "L-DB43A281": "e", + "L-DB4D51CF": "e", + "L-DB5B82A8": "e", + "L-DB62C864": "e", + "L-DBE0C398": "e", + "L-DBEC91B5": "e", + "L-DBF210E3": "e", + "L-DC80BC07": "e", + "L-DC90E824": "e", + "L-DC93118C": "e", + "L-DCCEDB7D": "e", + "L-DCD507F0": "e", + "L-DCD9DBD1": "e", + "L-DCE2AE7E": "e", + "L-DD10B0D3": "e", + "L-DD18D5D6": "e", + "L-DD1D4232": "e", + "L-DD294D57": "e", + "L-DD362E80": "e", + "L-DD42D93D": "e", + "L-DD508305": "e", + "L-DD693DF2": "e", + "L-DD719846": "e", + "L-DD8C8B0B": "e", + "L-DD96EF94": "e", + "L-DDA99F78": "e", + "L-DDDC1D15": "e", + "L-DDEB547E": "e", + "L-DE02D088": "e", + "L-DE07CBDF": "e", + "L-DE22CE7F": "e", + "L-DE35AFB9": "e", + "L-DE40B39E": "e", + "L-DE54DBCE": "e", + "L-DE5F2160": "e", + "L-DE645582": "e", + "L-DE7D3776": "e", + "L-DE8FE3FA": "e", + "L-DE9841A6": "e", + "L-DEFA0B4D": "e", + "L-DF052B7B": "e", + "L-DF2B9D4C": "e", + "L-DF3F3E67": "e", + "L-DF42E6A6": "e", + "L-DF589F40": "e", + "L-DF759A63": "e", + "L-DF9C8FA3": "e", + "L-DFA2E588": "e", + "L-DFB10FDE": "e", + "L-DFC87F45": "e", + "L-DFDC4FAD": "e", + "L-DFEAA340": "e", + "L-DFF5258D": "e", + "L-DFF9A17E": "e", + "L-E0299BF7": "e", + "L-E0385488": "e", + "L-E05B041E": "e", + "L-E081156C": "e", + "L-E091038E": "e", + "L-E097084E": "e", + "L-E0A39AB4": "e", + "L-E0B29A94": "e", + "L-E0C458EA": "e", + "L-E1249695": "e", + "L-E13DF72A": "s", + "L-E157C95B": "e", + "L-E162FC62": "e", + "L-E17566B7": "e", + "L-E1A153C2": "e", + "L-E1ACD1F8": "e", + "L-E1AF5362": "e", + "L-E215EF33": "e", + "L-E2612040": "e", + "L-E2649D46": "e", + "L-E28416C6": "e", + "L-E28E8307": "e", + "L-E2A0AC0F": "e", + "L-E2BB44FE": "e", + "L-E2BDBB46": "e", + "L-E2C06CE2": "e", + "L-E2E710C5": "e", + "L-E2E903C6": "e", + "L-E312D77E": "e", + "L-E318A8A4": "e", + "L-E31E799C": "e", + "L-E32B7D30": "e", + "L-E3362D50": "e", + "L-E3646D22": "e", + "L-E38944CD": "e", + "L-E3970643": "e", + "L-E3A0825E": "e", + "L-E3C0D615": "e", + "L-E3DBCF21": "e", + "L-E3DC0252": "e", + "L-E3DCB664": "e", + "L-E3DFC4E9": "e", + "L-E4156D7D": "e", + "L-E4348ACD": "e", + "L-E4449A4C": "e", + "L-E4515972": "e", + "L-E45AD561": "e", + "L-E481E4F8": "e", + "L-E4B12EA2": "s", + "L-E4B23F6B": "e", + "L-E4F6EF77": "e", + "L-E511AAB3": "e", + "L-E5144DC4": "e", + "L-E555FB1E": "e", + "L-E5775070": "e", + "L-E5884D25": "e", + "L-E5A7A988": "e", + "L-E5FD58AB": "e", + "L-E60A61DF": "e", + "L-E64AC50E": "e", + "L-E64F3C7F": "e", + "L-E659D201": "e", + "L-E66CB646": "e", + "L-E66E2C21": "e", + "L-E67DEC5D": "e", + "L-E68656B8": "e", + "L-E6D074A3": "e", + "L-E6D7FB53": "e", + "L-E6F368D4": "e", + "L-E71BCC55": "e", + "L-E7898792": "e", + "L-E78A78C6": "e", + "L-E793924B": "e", + "L-E7E422AE": "e", + "L-E7F46671": "e", + "L-E80B8987": "e", + "L-E84ADEB3": "e", + "L-E854D418": "e", + "L-E863DCD3": "e", + "L-E8917BB7": "e", + "L-E8BFC0D5": "e", + "L-E8EADE50": "e", + "L-E8EAF30E": "e", + "L-E903B0D9": "e", + "L-E9136106": "e", + "L-E9225B85": "e", + "L-E95A65A3": "e", + "L-E9BB87E2": "e", + "L-E9EE5599": "e", + "L-EA346344": "e", + "L-EA47BDD3": "e", + "L-EA4EF175": "e", + "L-EA9871A7": "e", + "L-EAA40023": "e", + "L-EAB0CBAB": "e", + "L-EAC6F82B": "e", + "L-EAFD2C1A": "e", + "L-EB03CD8A": "e", + "L-EB0702E0": "e", + "L-EB0D19CE": "e", + "L-EB339E74": "e", + "L-EB3795E2": "e", + "L-EB77DBD3": "e", + "L-EB92BE12": "e", + "L-EB93283A": "e", + "L-EBB53C25": "e", + "L-EC104295": "e", + "L-EC351EF7": "e", + "L-EC374A06": "e", + "L-EC610D7A": "e", + "L-EC686150": "e", + "L-EC70AE82": "e", + "L-ECF9852B": "e", + "L-ECFD615A": "e", + "L-ED08A3E0": "e", + "L-ED17B2A1": "e", + "L-ED353621": "e", + "L-ED698555": "e", + "L-ED7BD217": "e", + "L-ED8DEE9B": "e", + "L-ED8F1994": "e", + "L-ED93A43F": "e", + "L-ED9E485B": "e", + "L-EDE09F63": "e", + "L-EDFF07E7": "e", + "L-EE4A2013": "e", + "L-EE5A3114": "e", + "L-EE718475": "e", + "L-EE75DBCF": "e", + "L-EEA21C8A": "e", + "L-EEA45187": "e", + "L-EEAD8B0D": "e", + "L-EEC4CFAE": "e", + "L-EEC7404F": "e", + "L-EECC878E": "e", + "L-EED7F51C": "e", + "L-EEE055D0": "e", + "L-EF089D40": "e", + "L-EF24FBDB": "e", + "L-EF2BF7DC": "e", + "L-EF33F9B9": "e", + "L-EF63AD79": "e", + "L-EF662387": "e", + "L-EFB2F063": "e", + "L-EFBC980A": "e", + "L-EFCA02A2": "e", + "L-EFF2BBEF": "e", + "L-F003DF95": "e", + "L-F0067944": "e", + "L-F0132B48": "e", + "L-F013C48A": "e", + "L-F0365EA9": "e", + "L-F03F0355": "e", + "L-F073E97F": "e", + "L-F087CCFC": "e", + "L-F08861C2": "e", + "L-F0C0F812": "e", + "L-F0C6E97A": "e", + "L-F0D9539F": "e", + "L-F11AF030": "e", + "L-F18C373F": "e", + "L-F19FE9CF": "e", + "L-F1AB2AEA": "e", + "L-F1ABFE8A": "e", + "L-F1B1085A": "e", + "L-F23B5C47": "e", + "L-F2A74B80": "e", + "L-F2B8E920": "e", + "L-F2CC767C": "e", + "L-F2F8BB60": "e", + "L-F30D287E": "e", + "L-F311B08F": "e", + "L-F314A0DD": "e", + "L-F330D906": "e", + "L-F361CE98": "e", + "L-F369E3CA": "e", + "L-F3993D98": "e", + "L-F3C955A3": "e", + "L-F3F4F82A": "e", + "L-F4145962": "e", + "L-F41659C8": "e", + "L-F4259A37": "e", + "L-F428110B": "e", + "L-F42F6842": "e", + "L-F43A1825": "e", + "L-F43F60C3": "e", + "L-F49350C0": "e", + "L-F4A811B3": "e", + "L-F4DB72A7": "e", + "L-F4F08D88": "e", + "L-F5012757": "e", + "L-F502E62D": "e", + "L-F526E899": "e", + "L-F5689004": "e", + "L-F573984A": "e", + "L-F5867A8D": "e", + "L-F5943914": "e", + "L-F594DE31": "e", + "L-F59A72DA": "e", + "L-F59AF3BF": "e", + "L-F5A3DB41": "e", + "L-F5A8815D": "e", + "L-F5C4F1F2": "e", + "L-F5DB1C0D": "e", + "L-F5F5C720": "e", + "L-F6003AEB": "e", + "L-F614EEE4": "e", + "L-F62D1B89": "e", + "L-F6352678": "e", + "L-F63839BF": "e", + "L-F63BAB3A": "e", + "L-F64ABEAB": "e", + "L-F6B8A3A3": "e", + "L-F6E868D7": "e", + "L-F70A2467": "e", + "L-F737A0D0": "e", + "L-F73C7DB9": "e", + "L-F742E2D7": "e", + "L-F75ED94D": "e", + "L-F761337C": "e", + "L-F78D2E48": "e", + "L-F7A5D0B8": "e", + "L-F7D04A63": "e", + "L-F81A365E": "e", + "L-F83EBEFC": "e", + "L-F88734E1": "e", + "L-F88776CD": "r", + "L-F8A539DE": "e", + "L-F8AE8304": "e", + "L-F8C60E1D": "e", + "L-F8D4977B": "e", + "L-F8D7F460": "e", + "L-F8E55BBB": "e", + "L-F8FBF4E5": "e", + "L-F9020869": "e", + "L-F9042956": "e", + "L-F93088C1": "e", + "L-F933CFF9": "e", + "L-F971E784": "e", + "L-F9734E26": "e", + "L-F975D5F5": "e", + "L-F978BE20": "e", + "L-F97C6864": "e", + "L-F97E700D": "e", + "L-F9989D2B": "e", + "L-F99AB51E": "e", + "L-FA13E20B": "e", + "L-FA6957DB": "e", + "L-FA6AE909": "e", + "L-FACF2A9A": "e", + "L-FAFAD311": "e", + "L-FB07A512": "e", + "L-FB715320": "e", + "L-FB830EC3": "e", + "L-FBA9FB4A": "e", + "L-FBAF9897": "e", + "L-FBB495B2": "e", + "L-FBB7E9CB": "e", + "L-FBB8E9C9": "e", + "L-FBB939FD": "e", + "L-FC06AA3D": "e", + "L-FC157D3E": "e", + "L-FC2BE3FC": "e", + "L-FC4D7F52": "e", + "L-FC6B95EF": "e", + "L-FC8415AB": "e", + "L-FCEDEAC6": "e", + "L-FCFCB581": "e", + "L-FD0C4091": "e", + "L-FD431820": "e", + "L-FD4AD312": "e", + "L-FD4BCA24": "e", + "L-FD5D56FC": "e", + "L-FD6F8A4D": "e", + "L-FD73C65F": "e", + "L-FD9E9507": "e", + "L-FDB47EBF": "e", + "L-FDB7A21A": "e", + "L-FDD19E2A": "e", + "L-FDD27A76": "e", + "L-FE159C34": "e", + "L-FE5D1DC0": "e", + "L-FE72E327": "e", + "L-FE7F0B12": "e", + "L-FE7F1F85": "e", + "L-FE869B40": "e", + "L-FE9C120B": "e", + "L-FEC35D99": "e", + "L-FEEC5811": "e", + "L-FEEF2E8A": "e", + "L-FEF755D6": "e", + "L-FF1224F9": "e", + "L-FF169B98": "e", + "L-FF28D040": "e", + "L-FF2BFCDC": "e", + "L-FF40225D": "e", + "L-FF5C9E31": "e", + "L-FF78806F": "e", + "L-FF8CA338": "e", + "L-FFABC174": "e", + "L-FFBD1638": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "scheduler": { + "quotas": { + "L-03C881B9": "r", + "L-1DC60392": "r", + "L-21ED5C4A": "r", + "L-44A0C1A0": "r", + "L-4F80D7BE": "r", + "L-53944E21": "r", + "L-66629D52": "r", + "L-6F4B17DE": "r", + "L-754C8BBA": "r", + "L-A632CD40": "e", + "L-B7845AAE": "r", + "L-E7A3E659": "r", + "L-EE5D6FF0": "e", + "L-F6D2596E": "r", + "L-FB03E819": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "serverlessrepo": { + "quotas": { + "L-38772E7B": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "servicecatalog": { + "quotas": { + "L-1639038A": "e", + "L-223F4C54": "e", + "L-360CDF2E": "e", + "L-3BC91705": "e", + "L-764CF6A1": "e", + "L-7C3CEC2B": "e", + "L-A5846085": "e", + "L-AB79E48B": "e", + "L-C533FF9A": "e", + "L-C6458716": "e", + "L-E8959660": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "ses": { + "quotas": { + "L-10E24536": "e", + "L-804C8AE8": "e", + "L-CDEF9B6B": "r", + "L-E7F21B4C": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "shield": { + "quotas": { + "L-0BACF966": "e", + "L-BBD47253": "e", + "L-DA881E16": "e", + "L-DC974CBB": "e", + "L-E3D64430": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "sso": { + "quotas": { + "L-0299121C": "e", + "L-3C8D41A0": "e", + "L-7E1D4E33": "e", + "L-89954265": "e", + "L-B44C7A29": "e", + "L-D519A297": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "states": { + "quotas": { + "L-0169882E": "r", + "L-06F91E3A": "r", + "L-0A0C3368": "r", + "L-0AA8035B": "r", + "L-0B6A3253": "r", + "L-0DC55683": "r", + "L-0DD5CC77": "r", + "L-0EE9C880": "r", + "L-11731986": "r", + "L-1342F2DA": "r", + "L-137B3F65": "r", + "L-144D81B0": "r", + "L-15419B47": "r", + "L-17571B08": "r", + "L-191B5A6B": "r", + "L-198B5406": "r", + "L-1B55A735": "r", + "L-1D8665FF": "r", + "L-20F3BB5B": "r", + "L-2225B7C3": "r", + "L-233C6A78": "r", + "L-25C72657": "r", + "L-2786AC1A": "r", + "L-29AE5D31": "r", + "L-2C798E2E": "r", + "L-31300AD4": "r", + "L-345D7ED2": "r", + "L-3D708175": "r", + "L-4A5FADE3": "r", + "L-53EFA4BD": "r", + "L-5AD63623": "s", + "L-5D565FF6": "r", + "L-623044A2": "r", + "L-630CF084": "r", + "L-631A2A16": "r", + "L-656FC223": "r", + "L-6AFCB355": "c", + "L-6B5F0D66": "r", + "L-6F348EF6": "r", + "L-718BBE49": "r", + "L-7A4BEE15": "r", + "L-7B25D42D": "r", + "L-7B8A8E4B": "r", + "L-7DC9CADD": "r", + "L-809F4173": "r", + "L-81549E4C": "r", + "L-818B33FC": "r", + "L-88A8339B": "r", + "L-898DDD72": "r", + "L-91DFCA1B": "r", + "L-9BACC576": "r", + "L-9E82C0BD": "r", + "L-A0B4DA4A": "r", + "L-A9562A73": "c", + "L-AD9B4E93": "r", + "L-B581C5F3": "r", + "L-B590C09A": "r", + "L-B66B0F91": "c", + "L-B82BF66D": "r", + "L-B8A5B662": "e", + "L-BE784273": "r", + "L-BF6A8A21": "r", + "L-C04F0C78": "r", + "L-C1D5EBBB": "c", + "L-C314E25C": "r", + "L-C96E1D3D": "r", + "L-CDF2E38B": "r", + "L-CE9F8059": "r", + "L-CFF7B006": "r", + "L-D282C59F": "r", + "L-DB101538": "r", + "L-DEAF517C": "r", + "L-E58E8A9B": "r", + "L-E6D39AA7": "r", + "L-EACE83FA": "r", + "L-F8B59CB5": "r", + "L-F965A8DF": "r", + "L-F9699A68": "r", + "L-FA23558C": "r", + "L-FAA4E8CB": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "swf": { + "quotas": { + "L-07B00041": "r", + "L-0F51A38F": "r", + "L-10B07C15": "r", + "L-10FD2791": "r", + "L-11796F0D": "r", + "L-1188DD51": "r", + "L-11BEBC6E": "r", + "L-125E0653": "r", + "L-158C01C8": "r", + "L-1B6B2394": "r", + "L-1EB8BFAC": "r", + "L-22059A3A": "r", + "L-23555C14": "r", + "L-23ED90FD": "r", + "L-28C5E3D9": "r", + "L-3E1AC395": "r", + "L-3E87B554": "r", + "L-418A961F": "r", + "L-420027E2": "r", + "L-45E4DED8": "r", + "L-464CCB53": "e", + "L-521D4B0C": "r", + "L-522BE746": "r", + "L-52452CEB": "r", + "L-52C0BE72": "e", + "L-541D480C": "r", + "L-542E1377": "r", + "L-54F7FCCE": "r", + "L-58183C51": "r", + "L-60ABAF6D": "r", + "L-613386B0": "r", + "L-664871FC": "r", + "L-67FCAFB0": "r", + "L-6ACC4529": "r", + "L-6B93B990": "r", + "L-6E67C23B": "r", + "L-6FACB0D5": "e", + "L-708CA9CD": "r", + "L-72A8322C": "r", + "L-7379A78A": "r", + "L-740FECBB": "r", + "L-778DA924": "r", + "L-78ABDAF0": "r", + "L-7B042585": "r", + "L-7CE7ADCD": "r", + "L-82178AAF": "r", + "L-85FB1745": "r", + "L-8746B166": "r", + "L-889726A2": "r", + "L-90E73253": "r", + "L-90F927AE": "r", + "L-91FA29FA": "r", + "L-967C6C00": "r", + "L-9889E41A": "r", + "L-9EB7B9D6": "r", + "L-9F857AB4": "r", + "L-A4249261": "r", + "L-A94186CB": "r", + "L-B1B7886E": "r", + "L-B59DD71F": "r", + "L-B61DF1D5": "r", + "L-B6B07F5F": "r", + "L-B80CE8BF": "r", + "L-BC8E42D6": "r", + "L-BE04F134": "r", + "L-BEE48758": "r", + "L-C0C38A8F": "r", + "L-C0F4576E": "r", + "L-C2741471": "r", + "L-C5FCA8F5": "r", + "L-C6E6D788": "r", + "L-C943B086": "r", + "L-C96251D8": "r", + "L-CBE45CF4": "r", + "L-CEE29E14": "r", + "L-D441B742": "r", + "L-D4B08332": "r", + "L-D699363F": "r", + "L-DE1A2EBB": "r", + "L-DFCD38D8": "r", + "L-E2260636": "r", + "L-E3E6B073": "r", + "L-E73B63BD": "r", + "L-E74A6FC5": "r", + "L-E75077A8": "r", + "L-EABBD6AB": "r", + "L-F5350037": "r", + "L-F649FC18": "r", + "L-FBF3CE2F": "r", + "L-FD69F8F8": "r", + "L-FFE46A4B": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "transcribe": { + "quotas": { + "L-00A7F8C0": "r", + "L-025543F3": "r", + "L-0599F82B": "r", + "L-072E1D50": "r", + "L-0781CA76": "r", + "L-0AC77AF0": "r", + "L-0B1BA16E": "r", + "L-0E2548E4": "r", + "L-1387188A": "r", + "L-14A2C961": "r", + "L-15554767": "r", + "L-1633BB4A": "r", + "L-1C614DC7": "r", + "L-25C67393": "s", + "L-293498CE": "e", + "L-2B06FDCC": "r", + "L-2BEAA2BD": "r", + "L-2D3A6732": "r", + "L-2E269322": "e", + "L-32E8E80E": "r", + "L-3445E3CD": "e", + "L-34961B81": "r", + "L-3A093139": "r", + "L-3AD094D8": "r", + "L-3B3E6B1C": "r", + "L-43B6F41B": "r", + "L-46A3BCB8": "r", + "L-49DA58C9": "r", + "L-4C7CC63C": "r", + "L-4D1443F5": "s", + "L-50052249": "r", + "L-50FAAE67": "r", + "L-58D7221C": "r", + "L-63677B99": "r", + "L-66FBE0A2": "r", + "L-68305688": "e", + "L-70937EBD": "r", + "L-70B0FC9B": "r", + "L-7D14E3E2": "r", + "L-82ABD676": "r", + "L-84B1C0BA": "r", + "L-85BCBEF8": "r", + "L-866105CB": "e", + "L-8797DC7C": "r", + "L-966BFC39": "r", + "L-99087B15": "r", + "L-9CDB9A91": "r", + "L-A34A9084": "r", + "L-A4098D0D": "r", + "L-B32D5B85": "r", + "L-B4C1AD62": "r", + "L-B7245D62": "r", + "L-B778F7B9": "r", + "L-B882C824": "r", + "L-BAA3E542": "r", + "L-C1AA6ACA": "r", + "L-C20EE45A": "r", + "L-C4B3DE72": "r", + "L-CB43679D": "e", + "L-D0C82002": "r", + "L-D2DDB5A5": "r", + "L-D41CCA67": "r", + "L-D644592E": "r", + "L-D8921821": "r", + "L-D8B4403C": "r", + "L-DBAF8F96": "r", + "L-DC7305D8": "r", + "L-E1BA3DF5": "r", + "L-E3EBEDF2": "e", + "L-F1486348": "r", + "L-F49C59E1": "r", + "L-F6E06B47": "r", + "L-F8CF3791": "r", + "L-FAEFB7B8": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "transfer": { + "quotas": { + "L-101C3D29": "e", + "L-2F6B27A1": "e", + "L-4963D6B7": "r", + "L-547461C3": "e", + "L-57D537DE": "r", + "L-6E386A05": "e", + "L-7E767654": "e", + "L-843894CE": "e", + "L-858EB316": "e", + "L-8A2575E3": "e", + "L-90797EDA": "e", + "L-B51E8407": "e", + "L-C08739CA": "e", + "L-C0FDC60E": "e", + "L-CFAB221D": "r", + "L-D0C40802": "e", + "L-E5F10FFD": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "translate": { + "quotas": { + "L-10DB0BCF": "r", + "L-2B2DC880": "e", + "L-4011ABD8": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "verifiedpermissions": { + "quotas": { + "L-1FC83DB7": "r", + "L-271BE7E8": "r", + "L-2AFF096D": "r", + "L-38A7DE67": "r", + "L-4E0E8AFD": "r", + "L-57660735": "r", + "L-5A76F227": "r", + "L-5CA93A13": "r", + "L-5EB73F6C": "r", + "L-645D3857": "r", + "L-6DD21905": "r", + "L-70239429": "r", + "L-771544C7": "r", + "L-7CE71035": "r", + "L-886D79EB": "r", + "L-8D5CB09F": "r", + "L-8E2326FF": "r", + "L-919F2C9C": "e", + "L-9647C866": "r", + "L-97BDA0CF": "e", + "L-9DB5CAA4": "r", + "L-B45950D5": "r", + "L-B49B9779": "r", + "L-C9736881": "r", + "L-D2870CD3": "r", + "L-D82415D2": "r", + "L-DC54B663": "r", + "L-DE99D97D": "r", + "L-E1924570": "r", + "L-F81CF58F": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "vpc": { + "quotas": { + "L-085A6257": "e", + "L-0EA8095F": "c", + "L-12E49864": "e", + "L-1B52E74A": "e", + "L-29B6F2EB": "e", + "L-2AEEBF1A": "e", + "L-2AFB9258": "e", + "L-2C462E13": "e", + "L-3B4E38D2": "e", + "L-407747CB": "c", + "L-44499CD2": "e", + "L-45FE3B85": "e", + "L-589F43AA": "c", + "L-5F53652F": "e", + "L-7E9ECCDB": "e", + "L-83CA0A9D": "e", + "L-93826ACB": "c", + "L-A272D574": "e", + "L-A4707A72": "c", + "L-B4A6D682": "e", + "L-BB24F6E5": "e", + "L-CA6CC422": "e", + "L-CD17FD4B": "e", + "L-DC9F7029": "r", + "L-DF5E4CA3": "c", + "L-DFA99DE7": "e", + "L-E79EC296": "c", + "L-F678F1CE": "c", + "L-FE5A380F": "c" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "vpc-lattice": { + "quotas": { + "L-0DCA4434": "e", + "L-3DEC3B9F": "e", + "L-5FF8F9B9": "e", + "L-6095700C": "e", + "L-620C821E": "e", + "L-73D0F278": "e", + "L-75D4A19E": "e", + "L-89DEA27F": "e", + "L-9BC96FEF": "e", + "L-9CAD07FB": "e", + "L-BB11C6B9": "e", + "L-CF78395E": "e", + "L-D64E952E": "e", + "L-D71303F3": "e", + "L-EF6E2D62": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "wafv2": { + "quotas": { + "L-08788A4E": "e", + "L-11D00F38": "e", + "L-24189897": "e", + "L-2B217866": "e", + "L-2D9CB303": "e", + "L-2EC3DE7B": "e", + "L-3A878263": "e", + "L-3D6A3ADF": "e", + "L-5B2F9B11": "e", + "L-71C2E81B": "e", + "L-7ADC517D": "e", + "L-85B5BC49": "e", + "L-8973BE90": "e", + "L-9E2A3B2D": "e", + "L-9FD4FE94": "e", + "L-A85235F6": "r", + "L-B32E8672": "e", + "L-BF0029B0": "e", + "L-C4A384E0": "e", + "L-C5BCD850": "e", + "L-C5E4D334": "e", + "L-D6DA96AE": "e", + "L-E4E414A8": "e", + "L-F65D5473": "e", + "L-F7AF7D03": "e", + "L-FE21FEF6": "r" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + }, + "xray": { + "quotas": { + "L-8C0C998A": "e" + }, + "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" + } +} \ No newline at end of file diff --git a/services/autoscaling/auto_scaling_groups.go b/services/autoscaling/auto_scaling_groups.go index 79fc4c1e0d..5c76b47038 100644 --- a/services/autoscaling/auto_scaling_groups.go +++ b/services/autoscaling/auto_scaling_groups.go @@ -142,6 +142,8 @@ func (b *InMemoryBackend) buildNewAutoScalingGroup( // CreateAutoScalingGroup creates a new Auto Scaling group. func (b *InMemoryBackend) CreateAutoScalingGroup(input CreateAutoScalingGroupInput) (*AutoScalingGroup, error) { + limit := b.quotaLimit(quotaGroups) + b.mu.Lock("CreateAutoScalingGroup") defer b.mu.Unlock() @@ -152,6 +154,12 @@ func (b *InMemoryBackend) CreateAutoScalingGroup(input CreateAutoScalingGroupInp input.AvailabilityZones = zones + if !b.groups.Has(input.AutoScalingGroupName) { + if qerr := quotaReached(limit, len(b.groups.All()), "Auto Scaling groups"); qerr != nil { + return nil, qerr + } + } + if input.HealthCheckType == "" { input.HealthCheckType = healthCheckTypeEC2 } diff --git a/services/autoscaling/handler.go b/services/autoscaling/handler.go index 70cdc13ebe..020099ad57 100644 --- a/services/autoscaling/handler.go +++ b/services/autoscaling/handler.go @@ -392,6 +392,7 @@ func errorMappings() []errorMapping { {ErrGroupAlreadyExists, "AlreadyExists"}, {ErrLaunchConfigurationNotFound, errValidationError}, {ErrLaunchConfigurationAlreadyExists, "AlreadyExists"}, + {ErrLimitExceeded, "LimitExceeded"}, {ErrInvalidParameter, errValidationError}, {ErrUnknownAction, "InvalidAction"}, {ErrInvalidNextToken, "InvalidNextToken"}, diff --git a/services/autoscaling/launch_configurations.go b/services/autoscaling/launch_configurations.go index 2a11c37c18..efff9f7b77 100644 --- a/services/autoscaling/launch_configurations.go +++ b/services/autoscaling/launch_configurations.go @@ -14,9 +14,17 @@ import ( func (b *InMemoryBackend) CreateLaunchConfiguration( input CreateLaunchConfigurationInput, ) (*LaunchConfiguration, error) { + limit := b.quotaLimit(quotaLaunchCfgs) + b.mu.Lock("CreateLaunchConfiguration") defer b.mu.Unlock() + if !b.launchConfigurations.Has(input.LaunchConfigurationName) { + if err := quotaReached(limit, len(b.launchConfigurations.All()), "launch configurations"); err != nil { + return nil, err + } + } + return b.createLaunchConfigurationLocked(input) } diff --git a/services/autoscaling/quota.go b/services/autoscaling/quota.go new file mode 100644 index 0000000000..c4dc3f0297 --- /dev/null +++ b/services/autoscaling/quota.go @@ -0,0 +1,75 @@ +package autoscaling + +import ( + "errors" + "fmt" + + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" +) + +const ( + quotaServiceCode = "autoscaling" + quotaGroups = "L-CDE20ADC" + quotaLaunchCfgs = "L-6B80B8FA" +) + +// ErrLimitExceeded is the LimitExceeded code CreateAutoScalingGroup and CreateLaunchConfiguration declare +// (autoscaling@v1.78.3 deserializers.go:1032, :1126). +var ErrLimitExceeded = errors.New("LimitExceeded") + +// SetQuotaLimiter makes the create operations honour Service Quotas in every Region; nil disables it. +func (h *Handler) SetQuotaLimiter(f quotalimit.Func) { + if b, ok := h.Backend.(*InMemoryBackend); ok { + b.quotaGate.Set(f) + } +} + +// GroupCount returns the Auto Scaling groups held in region. +func (h *Handler) GroupCount(region string) int { + if b := h.existingBackend(region); b != nil { + b.mu.RLock("GroupCount") + defer b.mu.RUnlock() + + return len(b.groups.All()) + } + + return 0 +} + +// LaunchConfigurationCount returns the launch configurations held in region. +func (h *Handler) LaunchConfigurationCount(region string) int { + if b := h.existingBackend(region); b != nil { + b.mu.RLock("LaunchConfigurationCount") + defer b.mu.RUnlock() + + return len(b.launchConfigurations.All()) + } + + return 0 +} + +func (h *Handler) existingBackend(region string) *InMemoryBackend { + if home, ok := h.Backend.(*InMemoryBackend); ok && (region == "" || region == home.region) { + return home + } + + for _, p := range h.peers.All() { + if b, ok := p.Backend.(*InMemoryBackend); ok && b.region == region { + return b + } + } + + return nil +} + +func (b *InMemoryBackend) quotaLimit(code string) quotalimit.Limit { + return b.quotaGate.Lookup(b.accountID, b.region, quotaServiceCode, code) +} + +func quotaReached(limit quotalimit.Limit, current int, kind string) error { + if limit.Reached(current) { + return fmt.Errorf("%w: the maximum number of %s (%.0f) has been reached", ErrLimitExceeded, kind, limit.Value) + } + + return nil +} diff --git a/services/autoscaling/regions.go b/services/autoscaling/regions.go index f90c41682d..773e9149a8 100644 --- a/services/autoscaling/regions.go +++ b/services/autoscaling/regions.go @@ -74,4 +74,5 @@ func (b *InMemoryBackend) inheritWiring(home *InMemoryBackend) { b.elbv2Registrar = home.elbv2Registrar b.elbRegistrar = home.elbRegistrar b.ec2Lookup = home.ec2Lookup + b.quotaGate = home.quotaGate } diff --git a/services/autoscaling/store.go b/services/autoscaling/store.go index 9d588b6ad6..3ea26efb81 100644 --- a/services/autoscaling/store.go +++ b/services/autoscaling/store.go @@ -5,6 +5,8 @@ import ( "sync/atomic" "time" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "github.com/blackbirdworks/gopherstack/pkgs/awsmeta" "github.com/blackbirdworks/gopherstack/pkgs/config" "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" @@ -93,6 +95,7 @@ type InMemoryBackend struct { registry *store.Registry instanceIndex map[string]string accountID string + quotaGate *quotalimit.Gate region string deletedActivities []ScalingActivity launchTimers []*time.Timer @@ -109,6 +112,7 @@ func NewInMemoryBackend() *InMemoryBackend { func NewInMemoryBackendWithConfig(accountID, region string) *InMemoryBackend { b := &InMemoryBackend{ accountID: accountID, + quotaGate: "alimit.Gate{}, region: region, activities: make(map[string][]ScalingActivity), instanceRefreshes: make(map[string][]*InstanceRefresh), diff --git a/services/cloudwatchlogs/handler.go b/services/cloudwatchlogs/handler.go index 275138af19..de5b7a2726 100644 --- a/services/cloudwatchlogs/handler.go +++ b/services/cloudwatchlogs/handler.go @@ -439,7 +439,7 @@ func (h *Handler) handleError(ctx context.Context, c *echo.Context, action strin case errors.Is(reqErr, ErrDeliveryDestinationInUse), errors.Is(reqErr, ErrDeliverySourceInUse): errType = "ConflictException" statusCode = http.StatusConflict - case errors.Is(reqErr, ErrSubscriptionFilterLimitExceed): + case errors.Is(reqErr, ErrSubscriptionFilterLimitExceed), errors.Is(reqErr, ErrLogGroupLimitExceeded): errType = "LimitExceededException" statusCode = http.StatusBadRequest case errors.Is(reqErr, ErrOperationAborted): diff --git a/services/cloudwatchlogs/log_groups.go b/services/cloudwatchlogs/log_groups.go index 2578e9ba58..f934fec308 100644 --- a/services/cloudwatchlogs/log_groups.go +++ b/services/cloudwatchlogs/log_groups.go @@ -53,6 +53,7 @@ func (b *InMemoryBackend) CreateLogGroup( } region := getRegion(ctx, b.region) + limit := b.logGroupLimit(region) b.mu.Lock("CreateLogGroup") defer b.mu.Unlock() @@ -61,6 +62,10 @@ func (b *InMemoryBackend) CreateLogGroup( return nil, fmt.Errorf("%w: Log group %s already exists", ErrLogGroupAlreadyExists, name) } + if err := b.checkLogGroupQuotaLocked(region, limit); err != nil { + return nil, err + } + g := &LogGroup{ CreationTime: time.Now().UnixMilli(), LogGroupName: name, diff --git a/services/cloudwatchlogs/quota.go b/services/cloudwatchlogs/quota.go new file mode 100644 index 0000000000..ae8f353694 --- /dev/null +++ b/services/cloudwatchlogs/quota.go @@ -0,0 +1,56 @@ +package cloudwatchlogs + +import ( + "errors" + "fmt" + + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" +) + +const ( + quotaServiceCode = "logs" + quotaLogGroups = "L-C7B9AAAB" +) + +// ErrLogGroupLimitExceeded is CreateLogGroup's LimitExceededException when the Service Quotas limit is reached. +var ErrLogGroupLimitExceeded = errors.New("LimitExceededException") + +// SetQuotaLimiter makes CreateLogGroup honour the Service Quotas log group limit; nil disables it. +func (h *Handler) SetQuotaLimiter(f quotalimit.Func) { + if b, ok := h.Backend.(*InMemoryBackend); ok { + b.quotaGate.Set(f) + } +} + +// LogGroupCount returns the log groups held in region; empty region means the backend's. +func (h *Handler) LogGroupCount(region string) int { + b, ok := h.Backend.(*InMemoryBackend) + if !ok { + return 0 + } + + if region == "" { + region = b.region + } + + b.mu.RLock("LogGroupCount") + defer b.mu.RUnlock() + + return len(b.groupsInRegion(region)) +} + +func (b *InMemoryBackend) logGroupLimit(region string) quotalimit.Limit { + return b.quotaGate.Lookup(b.accountID, region, quotaServiceCode, quotaLogGroups) +} + +func (b *InMemoryBackend) checkLogGroupQuotaLocked(region string, limit quotalimit.Limit) error { + if limit.Reached(len(b.groupsInRegion(region))) { + return fmt.Errorf( + "%w: the maximum number of log groups (%.0f) has been reached", + ErrLogGroupLimitExceeded, + limit.Value, + ) + } + + return nil +} diff --git a/services/cloudwatchlogs/store.go b/services/cloudwatchlogs/store.go index 6858825723..97b4c1135d 100644 --- a/services/cloudwatchlogs/store.go +++ b/services/cloudwatchlogs/store.go @@ -7,6 +7,8 @@ import ( "sync" "time" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "github.com/blackbirdworks/gopherstack/pkgs/awsmeta" "github.com/blackbirdworks/gopherstack/pkgs/config" "github.com/blackbirdworks/gopherstack/pkgs/cwmetric" @@ -191,6 +193,7 @@ type InMemoryBackend struct { cancel context.CancelFunc region string accountID string + quotaGate quotalimit.Gate queriesOrder []string parsedQueriesOrder []string wg sync.WaitGroup diff --git a/services/cognitoidentity/handler.go b/services/cognitoidentity/handler.go index 1a1d476a81..b0e98621ed 100644 --- a/services/cognitoidentity/handler.go +++ b/services/cognitoidentity/handler.go @@ -233,6 +233,7 @@ var cognitoIdentitySentinelErrors = []struct { //nolint:gochecknoglobals // pack }{ {ErrIdentityPoolNotFound, ErrIdentityPoolNotFound.Error()}, {ErrIdentityPoolAlreadyExists, ErrIdentityPoolAlreadyExists.Error()}, + {ErrLimitExceeded, ErrLimitExceeded.Error()}, {ErrInvalidParameter, ErrInvalidParameter.Error()}, {ErrNotAuthorized, ErrNotAuthorized.Error()}, {ErrResourceConflict, ErrResourceConflict.Error()}, diff --git a/services/cognitoidentity/identity_pools.go b/services/cognitoidentity/identity_pools.go index d307e54558..2fc3c881f6 100644 --- a/services/cognitoidentity/identity_pools.go +++ b/services/cognitoidentity/identity_pools.go @@ -25,6 +25,7 @@ func (b *InMemoryBackend) CreateIdentityPool( opts ...*PoolExtendedConfig, ) (*IdentityPool, error) { region := getRegion(ctx, b.region) + limit := b.identityPoolLimit(region) b.mu.Lock("CreateIdentityPool") defer b.mu.Unlock() @@ -45,6 +46,10 @@ func (b *InMemoryBackend) CreateIdentityPool( ) } + if err := b.checkIdentityPoolQuotaLocked(region, limit); err != nil { + return nil, err + } + poolID := region + ":" + uuid.New().String() arn := arn.Build("cognito-identity", region, b.accountID, fmt.Sprintf("identitypool/%s", poolID)) diff --git a/services/cognitoidentity/quota.go b/services/cognitoidentity/quota.go new file mode 100644 index 0000000000..3d8bee377a --- /dev/null +++ b/services/cognitoidentity/quota.go @@ -0,0 +1,48 @@ +package cognitoidentity + +import ( + "fmt" + + "github.com/blackbirdworks/gopherstack/pkgs/awserr" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" +) + +const ( + quotaServiceCode = "cognito-identity" + quotaIdentityPool = "L-8692CE1C" +) + +// ErrLimitExceeded is CreateIdentityPool's LimitExceededException (cognitoidentity@v1.36.4 deserializers.go:84). +var ErrLimitExceeded = awserr.New("LimitExceededException", awserr.ErrConflict) + +// SetQuotaLimiter makes CreateIdentityPool honour the Service Quotas identity pool limit; nil disables it. +func (h *Handler) SetQuotaLimiter(f quotalimit.Func) { h.Backend.quotaGate.Set(f) } + +// IdentityPoolCount returns the identity pools held in region; empty region means the backend's. +func (h *Handler) IdentityPoolCount(region string) int { + b := h.Backend + if region == "" { + region = b.region + } + + b.mu.RLock("IdentityPoolCount") + defer b.mu.RUnlock() + + return len(b.poolsByRegion.Get(region)) +} + +func (b *InMemoryBackend) identityPoolLimit(region string) quotalimit.Limit { + return b.quotaGate.Lookup(b.accountID, region, quotaServiceCode, quotaIdentityPool) +} + +func (b *InMemoryBackend) checkIdentityPoolQuotaLocked(region string, limit quotalimit.Limit) error { + if limit.Reached(len(b.poolsByRegion.Get(region))) { + return fmt.Errorf( + "%w: the maximum number of identity pools (%.0f) has been reached", + ErrLimitExceeded, + limit.Value, + ) + } + + return nil +} diff --git a/services/cognitoidentity/store.go b/services/cognitoidentity/store.go index dcfe1af002..f80038b2c3 100644 --- a/services/cognitoidentity/store.go +++ b/services/cognitoidentity/store.go @@ -4,6 +4,8 @@ import ( "context" "strings" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" "github.com/blackbirdworks/gopherstack/pkgs/store" ) @@ -97,6 +99,7 @@ type InMemoryBackend struct { keyResolver TokenKeyResolver mu *lockmetrics.RWMutex accountID string + quotaGate quotalimit.Gate region string } diff --git a/services/cognitoidp/quota.go b/services/cognitoidp/quota.go new file mode 100644 index 0000000000..2fdefd8b5a --- /dev/null +++ b/services/cognitoidp/quota.go @@ -0,0 +1,51 @@ +package cognitoidp + +import ( + "fmt" + + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" +) + +const ( + quotaServiceCode = "cognito-idp" + quotaUserPools = "L-66E6DF30" +) + +// SetQuotaLimiter makes CreateUserPool honour the Service Quotas user pool limit in every Region; nil disables it. +func (h *Handler) SetQuotaLimiter(f quotalimit.Func) { + h.Backend.quotaGate.Set(f) +} + +// UserPoolCount returns the user pools held in region; a Region never used holds none. +func (h *Handler) UserPoolCount(region string) int { + if region == "" || region == h.Backend.region { + return h.Backend.userPoolCount() + } + + for _, p := range h.peers.All() { + if p.Backend.region == region { + return p.Backend.userPoolCount() + } + } + + return 0 +} + +func (b *InMemoryBackend) userPoolCount() int { + b.mu.RLock("UserPoolCount") + defer b.mu.RUnlock() + + return len(b.pools.All()) +} + +func (b *InMemoryBackend) userPoolLimit() quotalimit.Limit { + return b.quotaGate.Lookup(b.accountID, b.region, quotaServiceCode, quotaUserPools) +} + +func (b *InMemoryBackend) checkUserPoolQuotaLocked(limit quotalimit.Limit) error { + if limit.Reached(len(b.pools.All())) { + return fmt.Errorf("%w: the maximum number of user pools (%.0f) has been reached", ErrLimitExceeded, limit.Value) + } + + return nil +} diff --git a/services/cognitoidp/regions.go b/services/cognitoidp/regions.go index 4022a6fcd0..73ab646c17 100644 --- a/services/cognitoidp/regions.go +++ b/services/cognitoidp/regions.go @@ -46,6 +46,7 @@ func (h *Handler) EnableRegions(ctx context.Context) { h.peers = regionpeers.New(h.Backend.region, func(region string) *Handler { nb := NewInMemoryBackend(h.Backend.accountID, region, h.Backend.endpoint) nb.inheritTriggerInvoker(h.Backend) + nb.quotaGate = h.Backend.quotaGate p := NewHandler(nb, region) diff --git a/services/cognitoidp/store.go b/services/cognitoidp/store.go index c068d216b4..c49e9fc7bd 100644 --- a/services/cognitoidp/store.go +++ b/services/cognitoidp/store.go @@ -3,6 +3,8 @@ package cognitoidp import ( "time" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "golang.org/x/crypto/bcrypt" "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" @@ -114,6 +116,7 @@ type InMemoryBackend struct { userPoolReplicasByPool *store.Index[UserPoolReplica] provisionedLimits map[string]int32 accountID string + quotaGate *quotalimit.Gate region string endpoint string tokenSeq int64 @@ -124,6 +127,7 @@ type InMemoryBackend struct { func NewInMemoryBackend(accountID, region, endpoint string) *InMemoryBackend { b := &InMemoryBackend{ mu: lockmetrics.New("cognitoidp"), + quotaGate: "alimit.Gate{}, registry: store.NewRegistry(), refreshTokens: make(map[string]*refreshTokenEntry), authCodes: make(map[string]*authCodeEntry), diff --git a/services/cognitoidp/user_pools.go b/services/cognitoidp/user_pools.go index 30cb275738..2a068126e4 100644 --- a/services/cognitoidp/user_pools.go +++ b/services/cognitoidp/user_pools.go @@ -19,9 +19,15 @@ const deletionProtectionActive = "ACTIVE" // CreateUserPool creates a new user pool with the given name. func (b *InMemoryBackend) CreateUserPool(name string) (*UserPool, error) { + limit := b.userPoolLimit() + b.mu.Lock("CreateUserPool") defer b.mu.Unlock() + if err := b.checkUserPoolQuotaLocked(limit); err != nil { + return nil, err + } + poolID := b.region + "_" + randomAlphanumeric(poolIDSuffixLen) issuerURL := fmt.Sprintf("%s/%s", b.endpoint, poolID) @@ -379,9 +385,15 @@ func validatePassword(policy *PasswordPolicy, password string) error { // CreateUserPoolWithOpts creates a user pool with optional PasswordPolicy and AutoVerifiedAttributes. func (b *InMemoryBackend) CreateUserPoolWithOpts(name string, opts UserPoolOptions) (*UserPool, error) { + limit := b.userPoolLimit() + b.mu.Lock("CreateUserPoolWithOpts") defer b.mu.Unlock() + if err := b.checkUserPoolQuotaLocked(limit); err != nil { + return nil, err + } + poolID, err := b.newPoolID(opts.PinnedPoolID) if err != nil { return nil, err diff --git a/services/ec2/handler.go b/services/ec2/handler.go index 9b0ad0b5b6..3b95aeb7af 100644 --- a/services/ec2/handler.go +++ b/services/ec2/handler.go @@ -712,6 +712,9 @@ var errCodeLookup = []struct { {ErrAddressNotFound, "InvalidAllocationID.NotFound"}, {ErrVpcLimitExceeded, "VpcLimitExceeded"}, {ErrAddressLimitExceeded, "AddressLimitExceeded"}, + {ErrNatGatewayLimitExceeded, "NatGatewayLimitExceeded"}, + {ErrNetworkInterfaceLimitExceeded, "NetworkInterfaceLimitExceeded"}, + {ErrResourceCountLimitExceeded, "ResourceCountLimitExceeded"}, {ErrInternetGatewayNotFound, "InvalidInternetGatewayID.NotFound"}, {ErrDhcpOptionsNotFound, "InvalidDhcpOptionsID.NotFound"}, {ErrSnapshotNotFound, "InvalidSnapshotID.NotFound"}, diff --git a/services/ec2/nat_gateways.go b/services/ec2/nat_gateways.go index 3c5b355892..0515764d95 100644 --- a/services/ec2/nat_gateways.go +++ b/services/ec2/nat_gateways.go @@ -106,6 +106,8 @@ func (b *InMemoryBackend) CreatePrivateNatGateway(subnetID string, tags map[stri func (b *InMemoryBackend) createNatGateway( subnetID, allocationID, connectivity string, tags map[string]string, ) (*NatGateway, error) { + limit := b.quotaLimit(quotaServiceVPC, quotaNATPerAZ) + b.mu.Lock("CreateNatGateway") defer b.mu.Unlock() @@ -114,6 +116,10 @@ func (b *InMemoryBackend) createNatGateway( return nil, fmt.Errorf("%w: %s", ErrSubnetNotFound, subnetID) } + if limit.Reached(b.natGatewaysInZoneLocked(subnet.AvailabilityZone)) { + return nil, quotaExceeded(ErrNatGatewayLimitExceeded, "NAT gateways in the Availability Zone", limit) + } + ngw := &NatGateway{ SubnetID: subnetID, VPCID: subnet.VPCID, diff --git a/services/ec2/network_interfaces.go b/services/ec2/network_interfaces.go index bf11e8c3a0..f50ccaccc8 100644 --- a/services/ec2/network_interfaces.go +++ b/services/ec2/network_interfaces.go @@ -122,6 +122,8 @@ func (b *InMemoryBackend) CreateNetworkInterfaceWithOptions( return nil, fmt.Errorf("%w: SubnetId is required", ErrInvalidParameter) } + limit := b.quotaLimit(quotaServiceVPC, quotaNetworkInterfaces) + b.mu.Lock("CreateNetworkInterface") defer b.mu.Unlock() @@ -130,6 +132,10 @@ func (b *InMemoryBackend) CreateNetworkInterfaceWithOptions( return nil, fmt.Errorf("%w: %s", ErrSubnetNotFound, subnetID) } + if limit.Reached(len(b.networkInterfaces.All())) { + return nil, quotaExceeded(ErrNetworkInterfaceLimitExceeded, "network interfaces", limit) + } + groups, err := b.resolveENIGroupsLocked(sub.VPCID, opts.SecurityGroupIDs) if err != nil { return nil, err diff --git a/services/ec2/quota_vpc.go b/services/ec2/quota_vpc.go new file mode 100644 index 0000000000..50f5e44fd9 --- /dev/null +++ b/services/ec2/quota_vpc.go @@ -0,0 +1,217 @@ +package ec2 + +import ( + "errors" + "strings" +) + +const ( + vcpuHighMemory = "highmem" + vcpuInf = "inf" + vcpuGVT = "gvt" + vcpuStandard = "standard" + vcpuP = "p" + vcpuF = "f" + vcpuX = "x" +) + +const ( + quotaSubnetsPerVPC = "L-407747CB" + quotaIGWs = "L-A4707A72" + quotaNATPerAZ = "L-FE5A380F" + quotaNetworkInterfaces = "L-DF5E4CA3" + quotaSecurityGroups = "L-E79EC296" + quotaRulesPerGroup = "L-0EA8095F" + quotaRouteTablesPerVPC = "L-589F43AA" + quotaRoutesPerTable = "L-93826ACB" + quotaOnDemandStandard = "L-1216C47A" + quotaOnDemandGVT = "L-DB2E81BA" + quotaOnDemandP = "L-417A185B" + quotaOnDemandF = "L-74FC7D96" + quotaOnDemandX = "L-7295265B" + quotaOnDemandInf = "L-1945791B" + quotaOnDemandHighMemory = "L-43DA4232" + quotaSpotStandard = "L-34B43A08" + quotaSpotP = "L-7212CCBC" + quotaSpotGVT = "L-3819A6DF" +) + +// The limit errors CreateNatGateway, CreateNetworkInterface and CreateRoute document in the EC2 error code +// reference (errors-overview.html: NatGatewayLimitExceeded, NetworkInterfaceLimitExceeded, +// ResourceCountLimitExceeded). +var ( + ErrNatGatewayLimitExceeded = errors.New("NatGatewayLimitExceeded") + ErrNetworkInterfaceLimitExceeded = errors.New("NetworkInterfaceLimitExceeded") + ErrResourceCountLimitExceeded = errors.New("ResourceCountLimitExceeded") +) + +// vcpuClass maps an instance type to the vCPU quota class the type is counted under. +func vcpuClass(instanceType string) string { + family, _, _ := strings.Cut(instanceType, ".") + + switch { + case strings.HasPrefix(family, "u-"): + return vcpuHighMemory + case strings.HasPrefix(family, vcpuInf): + return vcpuInf + case strings.HasPrefix(family, "vt"), strings.HasPrefix(family, "g"): + return vcpuGVT + case strings.HasPrefix(family, vcpuP): + return vcpuP + case strings.HasPrefix(family, vcpuF): + return vcpuF + case strings.HasPrefix(family, vcpuX): + return vcpuX + case family != "" && strings.ContainsRune("acdhimrtz", rune(family[0])): + return vcpuStandard + default: + return "" + } +} + +func (b *InMemoryBackend) typeVCPUs(instanceType string) int { + return int(instanceTypeCatalog[instanceType].vcpus) +} + +func (b *InMemoryBackend) onDemandVCPUsLocked(class string) int { + spotIDs := map[string]bool{} + for _, r := range b.spotRequests.All() { + if r.InstanceID != "" { + spotIDs[r.InstanceID] = true + } + } + + n := 0 + + for _, in := range b.instances.All() { + live := in.State.Name == StateRunning.Name || in.State.Name == StatePending.Name + if live && !spotIDs[in.ID] && vcpuClass(in.InstanceType) == class { + n += b.typeVCPUs(in.InstanceType) + } + } + + return n +} + +func (b *InMemoryBackend) spotVCPUsLocked(class string) int { + n := 0 + + for _, r := range b.spotRequests.All() { + if (r.State == stateActive || r.State == "open") && vcpuClass(r.LaunchSpec.InstanceType) == class { + n += b.typeVCPUs(r.LaunchSpec.InstanceType) + } + } + + return n +} + +func (b *InMemoryBackend) maxNATPerAZLocked() int { + perAZ := map[string]int{} + most := 0 + + for _, n := range b.natGateways.All() { + if n.State == natGatewayStateDeleted { + continue + } + + perAZ[n.AvailabilityZone]++ + most = max(most, perAZ[n.AvailabilityZone]) + } + + return most +} + +func maxGroupSize[T any](items []*T, key func(*T) string) int { + per := map[string]int{} + most := 0 + + for _, it := range items { + per[key(it)]++ + most = max(most, per[key(it)]) + } + + return most +} + +// QuotaCount returns the live usage of an EC2 or VPC quota in the backend's Region; ok is false for a quota +// this backend does not derive from its resources. +func (b *InMemoryBackend) QuotaCount(code string) (int, bool) { + b.mu.RLock("QuotaCount") + defer b.mu.RUnlock() + + if n, ok := b.vpcQuotaCountLocked(code); ok { + return n, true + } + + classes := map[string]string{ + quotaOnDemandStandard: vcpuStandard, quotaOnDemandGVT: vcpuGVT, quotaOnDemandP: vcpuP, quotaOnDemandF: vcpuF, + quotaOnDemandX: vcpuX, quotaOnDemandInf: vcpuInf, quotaOnDemandHighMemory: vcpuHighMemory, + } + if class, ok := classes[code]; ok { + return b.onDemandVCPUsLocked(class), true + } + + spot := map[string]string{quotaSpotStandard: vcpuStandard, quotaSpotP: vcpuP, quotaSpotGVT: vcpuGVT} + if class, ok := spot[code]; ok { + return b.spotVCPUsLocked(class), true + } + + return 0, false +} + +func (b *InMemoryBackend) vpcQuotaCountLocked(code string) (int, bool) { + switch code { + case quotaSubnetsPerVPC: + return maxGroupSize(b.subnets.All(), func(s *Subnet) string { return s.VPCID }), true + case quotaIGWs: + return len(b.internetGateways.All()), true + case quotaNATPerAZ: + return b.maxNATPerAZLocked(), true + case quotaNetworkInterfaces: + return len(b.networkInterfaces.All()), true + case quotaSecurityGroups: + return len(b.securityGroups.All()), true + case quotaRouteTablesPerVPC: + return maxGroupSize(b.routeTables.All(), func(r *RouteTable) string { return r.VPCID }), true + case quotaRoutesPerTable: + most := 0 + for _, rt := range b.routeTables.All() { + most = max(most, userRouteCount(rt)) + } + + return most, true + case quotaRulesPerGroup: + most := 0 + for _, sg := range b.securityGroups.All() { + most = max(most, len(sg.IngressRules), len(sg.EgressRules)) + } + + return most, true + default: + return 0, false + } +} + +func (b *InMemoryBackend) natGatewaysInZoneLocked(zone string) int { + n := 0 + + for _, g := range b.natGateways.All() { + if g.AvailabilityZone == zone && g.State != natGatewayStateDeleted { + n++ + } + } + + return n +} + +func userRouteCount(rt *RouteTable) int { + n := 0 + + for _, r := range rt.Routes { + if r.GatewayID != routeGatewayLocal { + n++ + } + } + + return n +} diff --git a/services/ec2/route_spec.go b/services/ec2/route_spec.go index 0cbe32a172..147ba1b63b 100644 --- a/services/ec2/route_spec.go +++ b/services/ec2/route_spec.go @@ -112,6 +112,8 @@ func (b *InMemoryBackend) validateRouteTargetLocked(rt *RouteTable, s RouteSpec) // CreateRouteSpec adds a route to a route table. func (b *InMemoryBackend) CreateRouteSpec(rtID string, spec RouteSpec) error { + limit := b.quotaLimit(quotaServiceVPC, quotaRoutesPerTable) + b.mu.Lock("CreateRoute") defer b.mu.Unlock() @@ -135,6 +137,10 @@ func (b *InMemoryBackend) CreateRouteSpec(rtID string, spec RouteSpec) error { return err } + if limit.Reached(userRouteCount(rt)) { + return quotaExceeded(ErrResourceCountLimitExceeded, "routes in the route table", limit) + } + rt.Routes = append(rt.Routes, spec.route(routeOriginCreateRoute)) return nil diff --git a/services/ecr/handler.go b/services/ecr/handler.go index 93ac699393..71dcae6ea8 100644 --- a/services/ecr/handler.go +++ b/services/ecr/handler.go @@ -73,6 +73,7 @@ func (h *Handler) EnableRegions(ctx context.Context) { nb := NewInMemoryBackend(home.accountID, region, home.ProxyEndpoint()) nb.replicationSettleDelay = home.replicationSettleDelay nb.endpoints = home.endpoints + nb.quotaGate = home.quotaGate p := NewHandler(nb, nil) if h.janitor == nil { @@ -576,6 +577,7 @@ func (h *Handler) classifyError(err error) (int, string) { {ErrTooManyTags, "TooManyTagsException", http.StatusBadRequest}, {ErrScanNotFoundException, "ScanNotFoundException", http.StatusBadRequest}, {ErrRepositoryAlreadyExists, "RepositoryAlreadyExistsException", http.StatusBadRequest}, + {ErrLimitExceeded, "LimitExceededException", http.StatusBadRequest}, {ErrRepositoryNotEmpty, "RepositoryNotEmptyException", http.StatusBadRequest}, {ErrImageTagAlreadyExists, "ImageTagAlreadyExistsException", http.StatusBadRequest}, {ErrLayerInaccessible, "LayerInaccessibleException", http.StatusBadRequest}, diff --git a/services/ecr/quota.go b/services/ecr/quota.go new file mode 100644 index 0000000000..7eec31cf38 --- /dev/null +++ b/services/ecr/quota.go @@ -0,0 +1,61 @@ +package ecr + +import ( + "fmt" + + "github.com/blackbirdworks/gopherstack/pkgs/awserr" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" +) + +const ( + quotaServiceCode = "ecr" + quotaRepos = "L-CFEB8E8D" +) + +// ErrLimitExceeded is CreateRepository's LimitExceededException (ecr@v1.64.0 deserializers.go:853). +var ErrLimitExceeded = awserr.New("LimitExceededException", awserr.ErrConflict) + +// SetQuotaLimiter makes CreateRepository honour the Service Quotas repository limit in every Region; nil disables it. +func (h *Handler) SetQuotaLimiter(f quotalimit.Func) { + if b, ok := h.Backend.(*InMemoryBackend); ok { + b.quotaGate.Set(f) + } +} + +// RepositoryCount returns the repositories held in region; a Region never used holds none. +func (h *Handler) RepositoryCount(region string) int { + if home, ok := h.Backend.(*InMemoryBackend); ok && (region == "" || region == home.region) { + return home.repositoryCount() + } + + for _, p := range h.peers.All() { + if b, ok := p.Backend.(*InMemoryBackend); ok && b.region == region { + return b.repositoryCount() + } + } + + return 0 +} + +func (b *InMemoryBackend) repositoryCount() int { + b.mu.RLock("RepositoryCount") + defer b.mu.RUnlock() + + return b.repos.Len() +} + +func (b *InMemoryBackend) repositoryLimit(region string) quotalimit.Limit { + return b.quotaGate.Lookup(b.accountID, region, quotaServiceCode, quotaRepos) +} + +func (b *InMemoryBackend) checkRepositoryQuotaLocked(limit quotalimit.Limit) error { + if limit.Reached(b.repos.Len()) { + return fmt.Errorf( + "%w: the maximum number of repositories (%.0f) has been reached", + ErrLimitExceeded, + limit.Value, + ) + } + + return nil +} diff --git a/services/ecr/repositories.go b/services/ecr/repositories.go index 35f8df0eb6..a7d94ff6c0 100644 --- a/services/ecr/repositories.go +++ b/services/ecr/repositories.go @@ -30,6 +30,9 @@ func (b *InMemoryBackend) CreateRepository( encryptionType = "AES256" } + region := b.regionFor(ctx) + limit := b.repositoryLimit(region) + b.mu.Lock("CreateRepository") defer b.mu.Unlock() @@ -37,7 +40,9 @@ func (b *InMemoryBackend) CreateRepository( return nil, fmt.Errorf("%w: %s", ErrRepositoryAlreadyExists, name) } - region := b.regionFor(ctx) + if err := b.checkRepositoryQuotaLocked(limit); err != nil { + return nil, err + } endpoint := b.registryHostLocked(region) diff --git a/services/ecr/store.go b/services/ecr/store.go index af5b2b4c2e..6504481404 100644 --- a/services/ecr/store.go +++ b/services/ecr/store.go @@ -5,6 +5,8 @@ import ( "fmt" "time" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "github.com/blackbirdworks/gopherstack/pkgs/awsmeta" "github.com/blackbirdworks/gopherstack/pkgs/endpointstrategy" "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" @@ -53,6 +55,7 @@ type InMemoryBackend struct { lifecycleLastEvaluated map[string]time.Time registryPolicy string accountID string + quotaGate *quotalimit.Gate region string endpoint string endpoints endpointstrategy.Config @@ -78,6 +81,7 @@ func NewInMemoryBackend(accountID, region, endpoint string) *InMemoryBackend { lifecycleLastEvaluated: make(map[string]time.Time), mu: lockmetrics.New("ecr"), accountID: accountID, + quotaGate: "alimit.Gate{}, region: region, endpoint: endpoint, } diff --git a/services/efs/file_systems.go b/services/efs/file_systems.go index 679fc4724a..b6c6a24509 100644 --- a/services/efs/file_systems.go +++ b/services/efs/file_systems.go @@ -185,6 +185,8 @@ func (b *InMemoryBackend) CreateFileSystem( return nil, err } + limit := b.fileSystemLimit(region) + b.mu.Lock("CreateFileSystem") defer b.mu.Unlock() @@ -195,8 +197,8 @@ func (b *InMemoryBackend) CreateFileSystem( return cp, idemErr } - if len(b.fileSystemsByRegion.Get(region)) >= b.limits.fileSystemsPerAccount { - return nil, fileSystemLimitExceededErr(b.limits.fileSystemsPerAccount) + if maxFS := b.fileSystemCap(limit); len(b.fileSystemsByRegion.Get(region)) >= maxFS { + return nil, fileSystemLimitExceededErr(maxFS) } id := awsid.New("fs-") diff --git a/services/efs/quota.go b/services/efs/quota.go new file mode 100644 index 0000000000..194b1db2ad --- /dev/null +++ b/services/efs/quota.go @@ -0,0 +1,36 @@ +package efs + +import "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + +const ( + quotaServiceCode = "elasticfilesystem" + quotaFileSystems = "L-848C634D" +) + +// SetQuotaLimiter makes CreateFileSystem honour the Service Quotas file system limit; nil restores the built-in cap. +func (h *Handler) SetQuotaLimiter(f quotalimit.Func) { h.Backend.quotaGate.Set(f) } + +// FileSystemCount returns the file systems held in region; empty region means the backend's. +func (h *Handler) FileSystemCount(region string) int { + b := h.Backend + if region == "" { + region = b.region + } + + b.mu.RLock("FileSystemCount") + defer b.mu.RUnlock() + + return len(b.fileSystemsByRegion.Get(region)) +} + +func (b *InMemoryBackend) fileSystemLimit(region string) quotalimit.Limit { + return b.quotaGate.Lookup(b.accountID, region, quotaServiceCode, quotaFileSystems) +} + +func (b *InMemoryBackend) fileSystemCap(limit quotalimit.Limit) int { + if limit.Set { + return int(limit.Value) + } + + return b.limits.fileSystemsPerAccount +} diff --git a/services/efs/replication.go b/services/efs/replication.go index 6e4db85f83..01353454f1 100644 --- a/services/efs/replication.go +++ b/services/efs/replication.go @@ -26,6 +26,7 @@ func (b *InMemoryBackend) CreateReplicationConfiguration( } region := getRegion(ctx, b.region) + limit := b.fileSystemLimit(region) b.mu.Lock("CreateReplicationConfiguration") defer b.mu.Unlock() @@ -50,8 +51,8 @@ func (b *InMemoryBackend) CreateReplicationConfiguration( // operations.CreateReplicationConfiguration.errors, see limits.go) because it // implicitly creates a destination file system, drawing on the same // per-account/region quota CreateFileSystem enforces. - if len(b.fileSystemsByRegion.Get(region)) >= b.limits.fileSystemsPerAccount { - return nil, fileSystemLimitExceededErr(b.limits.fileSystemsPerAccount) + if maxFS := b.fileSystemCap(limit); len(b.fileSystemsByRegion.Get(region)) >= maxFS { + return nil, fileSystemLimitExceededErr(maxFS) } creationTime := time.Now().UTC() diff --git a/services/efs/store.go b/services/efs/store.go index 5744262737..a1b91c051f 100644 --- a/services/efs/store.go +++ b/services/efs/store.go @@ -7,6 +7,8 @@ import ( "strings" "time" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" "github.com/blackbirdworks/gopherstack/pkgs/store" ) @@ -140,6 +142,7 @@ type InMemoryBackend struct { ec2Resolver EC2Resolver storageRoot string accountID string + quotaGate quotalimit.Gate region string // fsActivationDelay controls how long CreateFileSystem waits before transitioning // a file system from "creating" to "available". Zero (default) means the transition diff --git a/services/eventbridge/api_destinations.go b/services/eventbridge/api_destinations.go index ece79b8eac..ecd56f3237 100644 --- a/services/eventbridge/api_destinations.go +++ b/services/eventbridge/api_destinations.go @@ -38,6 +38,8 @@ func (b *InMemoryBackend) CreateAPIDestination(ctx context.Context, region := getRegionFromContext(ctx, b.region) + limit := b.quotaLimit(region, quotaAPIDestCount) + b.mu.Lock("CreateAPIDestination") defer b.mu.Unlock() @@ -53,6 +55,10 @@ func (b *InMemoryBackend) CreateAPIDestination(ctx context.Context, return nil, fmt.Errorf("%w: connection %s does not exist", ErrNotFound, input.ConnectionArn) } + if err := quotaReached(limit, b.apiDestinationsTable(region).Len(), "API destinations"); err != nil { + return nil, err + } + now := time.Now() dst := &APIDestination{ APIDestinationArn: b.apiDestinationARN(input.Name), diff --git a/services/eventbridge/connections.go b/services/eventbridge/connections.go index 0121bea34e..b1416968ce 100644 --- a/services/eventbridge/connections.go +++ b/services/eventbridge/connections.go @@ -27,6 +27,8 @@ func (b *InMemoryBackend) CreateConnection(ctx context.Context, input CreateConn region := getRegionFromContext(ctx, b.region) + limit := b.quotaLimit(region, quotaConnections) + b.mu.Lock("CreateConnection") defer b.mu.Unlock() @@ -34,6 +36,10 @@ func (b *InMemoryBackend) CreateConnection(ctx context.Context, input CreateConn return nil, fmt.Errorf("%w: connection %s already exists", ErrAlreadyExists, input.Name) } + if err := quotaReached(limit, b.connectionsTable(region).Len(), "connections"); err != nil { + return nil, err + } + now := time.Now() conn := &Connection{ ConnectionArn: b.connectionARN(input.Name), diff --git a/services/eventbridge/endpoints.go b/services/eventbridge/endpoints.go index d2665652d6..e1d946b766 100644 --- a/services/eventbridge/endpoints.go +++ b/services/eventbridge/endpoints.go @@ -16,6 +16,8 @@ func (b *InMemoryBackend) CreateEndpoint(ctx context.Context, input CreateEndpoi region := getRegionFromContext(ctx, b.region) + limit := b.quotaLimit(region, quotaEndpoints) + b.mu.Lock("CreateEndpoint") defer b.mu.Unlock() @@ -23,6 +25,10 @@ func (b *InMemoryBackend) CreateEndpoint(ctx context.Context, input CreateEndpoi return nil, fmt.Errorf("%w: endpoint %s already exists", ErrAlreadyExists, input.Name) } + if err := quotaReached(limit, b.endpointsTable(region).Len(), "endpoints"); err != nil { + return nil, err + } + now := time.Now() buses := input.EventBuses if buses == nil { diff --git a/services/eventbridge/event_buses.go b/services/eventbridge/event_buses.go index e406502a61..6fa271ae5d 100644 --- a/services/eventbridge/event_buses.go +++ b/services/eventbridge/event_buses.go @@ -61,6 +61,7 @@ func (b *InMemoryBackend) CreateEventBus(ctx context.Context, params CreateEvent } region := getRegionFromContext(ctx, b.region) + limit := b.quotaLimit(region, quotaEventBuses) b.mu.Lock("CreateEventBus") defer b.mu.Unlock() @@ -75,20 +76,8 @@ func (b *InMemoryBackend) CreateEventBus(ctx context.Context, params CreateEvent } // Count custom buses across all regions — the AWS limit is per-account, not per-region. - customBusCount := 0 - for _, regionBuses := range b.buses { - for _, bus := range regionBuses.All() { - if bus.Name != defaultEventBusName { - customBusCount++ - } - } - } - if customBusCount >= maxEventBusesPerAccount { - return nil, fmt.Errorf( - "%w: account has reached the maximum of %d custom event buses", - ErrResourceLimitExceeded, - maxEventBusesPerAccount, - ) + if err := b.checkBusQuotaLocked(region, limit); err != nil { + return nil, err } now := time.Now() diff --git a/services/eventbridge/quota.go b/services/eventbridge/quota.go new file mode 100644 index 0000000000..32b7880101 --- /dev/null +++ b/services/eventbridge/quota.go @@ -0,0 +1,186 @@ +package eventbridge + +import ( + "fmt" + + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "github.com/blackbirdworks/gopherstack/pkgs/store" +) + +const ( + quotaServiceCode = "events" + quotaRules = "L-244521F2" + quotaEventBuses = "L-658A4FD9" + quotaConnections = "L-595D6D42" + quotaEndpoints = "L-EAC9A2AC" + quotaAPIDestCount = "L-FB1C3A6D" +) + +// QuotaCounter is the read-only view of the backend that Service Quotas utilization reads. +type QuotaCounter interface { + CustomBusCount(region string) int + MaxRulesPerBus(region string) int + ConnectionsInRegion(region string) int + EndpointsInRegion(region string) int + APIDestinationsInRegion(region string) int +} + +// SetQuotaLimiter makes the create operations honour Service Quotas; nil disables it. +func (h *Handler) SetQuotaLimiter(f quotalimit.Func) { + if b, ok := h.Backend.(*InMemoryBackend); ok { + b.quotaGate.Set(f) + } +} + +// QuotaCounts returns the live counts behind the Service Quotas usage of this service. +func (h *Handler) QuotaCounts() QuotaCounter { + if b, ok := h.Backend.(*InMemoryBackend); ok { + return b + } + + return nil +} + +func (b *InMemoryBackend) regionOr(region string) string { + if region == "" { + return b.region + } + + return region +} + +func tableLenLocked[T any](b *InMemoryBackend, m map[string]*store.Table[T], region string) int { + b.tableMu.Lock() + t := m[region] + b.tableMu.Unlock() + + if t == nil { + return 0 + } + + return t.Len() +} + +func (b *InMemoryBackend) customBusCountLocked(region string) int { + b.tableMu.Lock() + t := b.buses[region] + b.tableMu.Unlock() + + if t == nil { + return 0 + } + + n := 0 + + for _, bus := range t.All() { + if bus.Name != defaultEventBusName { + n++ + } + } + + return n +} + +// CustomBusCount returns the custom event buses in region. +func (b *InMemoryBackend) CustomBusCount(region string) int { + b.mu.RLock("CustomBusCount") + defer b.mu.RUnlock() + + return b.customBusCountLocked(b.regionOr(region)) +} + +// MaxRulesPerBus returns the most rules any single event bus in region holds. +func (b *InMemoryBackend) MaxRulesPerBus(region string) int { + b.mu.RLock("MaxRulesPerBus") + defer b.mu.RUnlock() + + b.tableMu.Lock() + tables := make([]*store.Table[Rule], 0, len(b.rules[b.regionOr(region)])) + + for _, t := range b.rules[b.regionOr(region)] { + tables = append(tables, t) + } + b.tableMu.Unlock() + + most := 0 + for _, t := range tables { + most = max(most, t.Len()) + } + + return most +} + +// ConnectionsInRegion returns the connections in region. +func (b *InMemoryBackend) ConnectionsInRegion(region string) int { + b.mu.RLock("ConnectionsInRegion") + defer b.mu.RUnlock() + + return tableLenLocked(b, b.connections, b.regionOr(region)) +} + +// EndpointsInRegion returns the global endpoints in region. +func (b *InMemoryBackend) EndpointsInRegion(region string) int { + b.mu.RLock("EndpointsInRegion") + defer b.mu.RUnlock() + + return tableLenLocked(b, b.endpoints, b.regionOr(region)) +} + +// APIDestinationsInRegion returns the API destinations in region. +func (b *InMemoryBackend) APIDestinationsInRegion(region string) int { + b.mu.RLock("APIDestinationsInRegion") + defer b.mu.RUnlock() + + return tableLenLocked(b, b.apiDestinations, b.regionOr(region)) +} + +func (b *InMemoryBackend) quotaLimit(region, code string) quotalimit.Limit { + return b.quotaGate.Lookup(b.accountID, region, quotaServiceCode, code) +} + +func quotaReached(limit quotalimit.Limit, current int, kind string) error { + if limit.Reached(current) { + return fmt.Errorf( + "%w: the maximum number of %s (%.0f) has been reached", + ErrResourceLimitExceeded, + kind, + limit.Value, + ) + } + + return nil +} + +func ruleLimit(limit quotalimit.Limit) int { + if limit.Set { + return int(limit.Value) + } + + return maxRulesPerBus +} + +func (b *InMemoryBackend) checkBusQuotaLocked(region string, limit quotalimit.Limit) error { + if limit.Set { + return quotaReached(limit, b.customBusCountLocked(region), "event buses") + } + + customBusCount := 0 + + for _, regionBuses := range b.buses { + for _, bus := range regionBuses.All() { + if bus.Name != defaultEventBusName { + customBusCount++ + } + } + } + + if customBusCount >= maxEventBusesPerAccount { + return fmt.Errorf( + "%w: account has reached the maximum of %d custom event buses", + ErrResourceLimitExceeded, + maxEventBusesPerAccount, + ) + } + + return nil +} diff --git a/services/eventbridge/rules.go b/services/eventbridge/rules.go index 88cd327026..4476e9f460 100644 --- a/services/eventbridge/rules.go +++ b/services/eventbridge/rules.go @@ -116,6 +116,8 @@ func (b *InMemoryBackend) PutRule(ctx context.Context, input PutRuleInput) (*Rul return nil, awsErrorf(ErrInvalidParameter, "ScheduleExpression is supported only on the default event bus.") } + limit := b.quotaLimit(region, quotaRules) + b.mu.Lock("PutRule") defer b.mu.Unlock() @@ -134,12 +136,12 @@ func (b *InMemoryBackend) PutRule(ctx context.Context, input PutRuleInput) (*Rul // Enforce per-bus rule limit only for new rules (not updates). if !exists { - if ruleTable.Len() >= maxRulesPerBus { + if maxRules := ruleLimit(limit); ruleTable.Len() >= maxRules { return nil, fmt.Errorf( "%w: event bus %s has reached the maximum of %d rules", ErrResourceLimitExceeded, busName, - maxRulesPerBus, + maxRules, ) } } else if err := checkManagedRule(existing); err != nil { diff --git a/services/eventbridge/store.go b/services/eventbridge/store.go index 9e3774437d..446fca8b2e 100644 --- a/services/eventbridge/store.go +++ b/services/eventbridge/store.go @@ -8,6 +8,8 @@ import ( "sync/atomic" "time" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "github.com/blackbirdworks/gopherstack/pkgs/awsmeta" "github.com/blackbirdworks/gopherstack/pkgs/config" "github.com/blackbirdworks/gopherstack/pkgs/cwmetric" @@ -378,6 +380,7 @@ type InMemoryBackend struct { apiDestLimiters sync.Map region string accountID string + quotaGate quotalimit.Gate eventLog []EventLogEntry wg sync.WaitGroup shutdownTimeout time.Duration diff --git a/services/firehose/delivery_streams.go b/services/firehose/delivery_streams.go index adde89c1fd..a828865fc9 100644 --- a/services/firehose/delivery_streams.go +++ b/services/firehose/delivery_streams.go @@ -50,15 +50,15 @@ func (b *InMemoryBackend) CreateDeliveryStream( err error ) + limit := b.streamLimit(getRegionFromContext(ctx, b)) + func() { b.mu.Lock("CreateDeliveryStream") defer b.mu.Unlock() region = getRegionFromContext(ctx, b) - if _, ok := b.streams.Get(regionKey(region, input.Name)); ok { - err = fmt.Errorf("%w: stream %s already exists", ErrAlreadyExists, input.Name) - + if err = b.checkNewStreamLocked(region, input.Name, limit); err != nil { return } diff --git a/services/firehose/handler.go b/services/firehose/handler.go index 0172096361..114dbabacb 100644 --- a/services/firehose/handler.go +++ b/services/firehose/handler.go @@ -211,6 +211,8 @@ func (h *Handler) handleError(_ context.Context, c *echo.Context, _ string, err return respond(http.StatusNotFound, "ResourceNotFoundException") case errors.Is(err, ErrAlreadyExists): return respond(http.StatusBadRequest, "ResourceInUseException") + case errors.Is(err, ErrLimitExceeded): + return respond(http.StatusBadRequest, "LimitExceededException") case errors.Is(err, ErrConcurrentModification): return respond(http.StatusBadRequest, "ConcurrentModificationException") case errors.Is(err, errUnknownAction): diff --git a/services/firehose/quota.go b/services/firehose/quota.go new file mode 100644 index 0000000000..de9fae92d9 --- /dev/null +++ b/services/firehose/quota.go @@ -0,0 +1,64 @@ +package firehose + +import ( + "fmt" + + "github.com/blackbirdworks/gopherstack/pkgs/awserr" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" +) + +const ( + quotaServiceCode = "firehose" + quotaDeliveryStream = "L-14BB0BE7" +) + +// ErrLimitExceeded is CreateDeliveryStream's LimitExceededException (firehose@v1.46.4 deserializers.go:85). +var ErrLimitExceeded = awserr.New("LimitExceededException", awserr.ErrConflict) + +// SetQuotaLimiter makes CreateDeliveryStream honour the Service Quotas stream limit; nil disables it. +func (h *Handler) SetQuotaLimiter(f quotalimit.Func) { + if b, ok := h.Backend.(*InMemoryBackend); ok { + b.quotaGate.Set(f) + } +} + +// DeliveryStreamCount returns the delivery streams held in region; empty region means the backend's. +func (h *Handler) DeliveryStreamCount(region string) int { + b, ok := h.Backend.(*InMemoryBackend) + if !ok { + return 0 + } + + if region == "" { + region = b.region + } + + b.mu.RLock("DeliveryStreamCount") + defer b.mu.RUnlock() + + return len(b.streamsByRegion.Get(region)) +} + +func (b *InMemoryBackend) streamLimit(region string) quotalimit.Limit { + return b.quotaGate.Lookup(b.accountID, region, quotaServiceCode, quotaDeliveryStream) +} + +func (b *InMemoryBackend) checkStreamQuotaLocked(region string, limit quotalimit.Limit) error { + if limit.Reached(len(b.streamsByRegion.Get(region))) { + return fmt.Errorf( + "%w: the maximum number of delivery streams (%.0f) has been reached", + ErrLimitExceeded, + limit.Value, + ) + } + + return nil +} + +func (b *InMemoryBackend) checkNewStreamLocked(region, name string, limit quotalimit.Limit) error { + if _, ok := b.streams.Get(regionKey(region, name)); ok { + return fmt.Errorf("%w: stream %s already exists", ErrAlreadyExists, name) + } + + return b.checkStreamQuotaLocked(region, limit) +} diff --git a/services/firehose/store.go b/services/firehose/store.go index e1db6efb5a..695a30178d 100644 --- a/services/firehose/store.go +++ b/services/firehose/store.go @@ -3,6 +3,8 @@ package firehose import ( "context" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "github.com/blackbirdworks/gopherstack/pkgs/awsmeta" "github.com/blackbirdworks/gopherstack/pkgs/cwmetric" "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" @@ -50,6 +52,7 @@ type InMemoryBackend struct { // they are cancelled when the server shuts down rather than blocking indefinitely. svcCtx context.Context accountID string + quotaGate quotalimit.Gate region string } diff --git a/services/kms/aliases.go b/services/kms/aliases.go index 4194e85c1d..0f083b6641 100644 --- a/services/kms/aliases.go +++ b/services/kms/aliases.go @@ -53,11 +53,12 @@ func (b *InMemoryBackend) CreateAlias(ctx context.Context, input *CreateAliasInp ) } + region := getRegion(ctx, b.defaultRegion) + limit := b.quotaLimit(region, quotaAliasesKey) + b.mu.Lock("CreateAlias") defer b.mu.Unlock() - region := getRegion(ctx, b.defaultRegion) - if b.aliasesStore(region).Has(input.AliasName) { return fmt.Errorf("%w: An alias with the name %s already exists", ErrAliasAlreadyExists, gopherarn.Build("kms", region, b.accountID, input.AliasName)) @@ -74,6 +75,10 @@ func (b *InMemoryBackend) CreateAlias(ctx context.Context, input *CreateAliasInp return ErrKeyNotFound } + if err = b.checkAliasQuotaLocked(region, targetID, limit); err != nil { + return err + } + now := UnixTimeFloat(time.Now()) aliasArn := gopherarn.Build("kms", region, b.accountID, input.AliasName) b.aliasesStore(region).Put(&Alias{ diff --git a/services/kms/grants.go b/services/kms/grants.go index d4c3eaac22..a2efa1f970 100644 --- a/services/kms/grants.go +++ b/services/kms/grants.go @@ -116,6 +116,8 @@ func (b *InMemoryBackend) CreateGrant( } } + limit := b.quotaLimit(getRegion(ctx, b.defaultRegion), quotaGrantsKey) + b.mu.Lock("CreateGrant") defer b.mu.Unlock() @@ -141,11 +143,11 @@ func (b *InMemoryBackend) CreateGrant( grantsForKey := b.grantsRegion(region) - if len(grantsForKey.byKey.Get(keyID)) >= maxGrantsPerKey { + if maxGrants := grantsPerKeyLimit(limit); len(grantsForKey.byKey.Get(keyID)) >= maxGrants { return nil, fmt.Errorf( "%w: grant limit of %d exceeded for key %q", ErrLimitExceeded, - maxGrantsPerKey, + maxGrants, keyID, ) } diff --git a/services/kms/keys.go b/services/kms/keys.go index 4090d8ae26..5e3200de2a 100644 --- a/services/kms/keys.go +++ b/services/kms/keys.go @@ -204,14 +204,20 @@ func (b *InMemoryBackend) CreateKey( return nil, err } - b.mu.Lock("CreateKey") - defer b.mu.Unlock() - region := getRegion(ctx, b.defaultRegion) if input.Region != "" { region = input.Region } + limit := b.quotaLimit(region, quotaKeys) + + b.mu.Lock("CreateKey") + defer b.mu.Unlock() + + if err := b.checkKeyQuotaLocked(region, limit); err != nil { + return nil, err + } + // An inline policy, if supplied, must be a well-formed key policy document. if input.Policy != "" && !validKeyPolicyDoc(input.Policy) { return nil, ErrMalformedPolicyDocument diff --git a/services/kms/quota.go b/services/kms/quota.go new file mode 100644 index 0000000000..e52bf6c3fc --- /dev/null +++ b/services/kms/quota.go @@ -0,0 +1,180 @@ +package kms + +import ( + "fmt" + + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "github.com/blackbirdworks/gopherstack/pkgs/store" +) + +const ( + quotaServiceCode = "kms" + quotaKeys = "L-C2F1777E" + quotaAliasesKey = "L-340F62FB" + quotaGrantsKey = "L-D594A657" +) + +// SetQuotaLimiter makes CreateKey, CreateAlias and CreateGrant honour Service Quotas; nil disables it. +func (h *Handler) SetQuotaLimiter(f quotalimit.Func) { + if b, ok := h.Backend.(*InMemoryBackend); ok { + b.quotaGate.Set(f) + } +} + +// KeyCount returns the customer managed keys held in region; empty region means the backend's. +func (h *Handler) KeyCount(region string) int { + if b, ok := h.Backend.(*InMemoryBackend); ok { + return b.keyCount(region) + } + + return 0 +} + +// MaxAliasesPerKey returns the most aliases any single key in region has. +func (h *Handler) MaxAliasesPerKey(region string) int { + if b, ok := h.Backend.(*InMemoryBackend); ok { + return b.maxAliasesPerKey(region) + } + + return 0 +} + +// MaxGrantsPerKey returns the most grants any single key in region has. +func (h *Handler) MaxGrantsPerKey(region string) int { + if b, ok := h.Backend.(*InMemoryBackend); ok { + return b.maxGrantsPerKeyIn(region) + } + + return 0 +} + +func (b *InMemoryBackend) regionOr(region string) string { + if region == "" { + return b.defaultRegion + } + + return region +} + +func (b *InMemoryBackend) existingTable(region string) *store.Table[Key] { + b.tableMu.Lock() + defer b.tableMu.Unlock() + + return b.keys[region] +} + +func (b *InMemoryBackend) keyCount(region string) int { + t := b.existingTable(b.regionOr(region)) + if t == nil { + return 0 + } + + b.mu.RLock("KeyCount") + defer b.mu.RUnlock() + + return b.keyCountLocked(t) +} + +func (b *InMemoryBackend) keyCountLocked(t *store.Table[Key]) int { + n := 0 + + for _, k := range t.All() { + if !isAWSManagedKey(k) { + n++ + } + } + + return n +} + +func (b *InMemoryBackend) maxAliasesPerKey(region string) int { + b.tableMu.Lock() + t := b.aliases[b.regionOr(region)] + b.tableMu.Unlock() + + if t == nil { + return 0 + } + + b.mu.RLock("MaxAliasesPerKey") + defer b.mu.RUnlock() + + perKey := map[string]int{} + most := 0 + + for _, a := range t.All() { + perKey[a.TargetKeyID]++ + most = max(most, perKey[a.TargetKeyID]) + } + + return most +} + +func (b *InMemoryBackend) maxGrantsPerKeyIn(region string) int { + b.tableMu.Lock() + g := b.grants[b.regionOr(region)] + b.tableMu.Unlock() + + if g == nil { + return 0 + } + + b.mu.RLock("MaxGrantsPerKey") + defer b.mu.RUnlock() + + perKey := map[string]int{} + most := 0 + + for _, gr := range g.table.All() { + perKey[gr.KeyID]++ + most = max(most, perKey[gr.KeyID]) + } + + return most +} + +func (b *InMemoryBackend) quotaLimit(region, code string) quotalimit.Limit { + return b.quotaGate.Lookup(b.accountID, region, quotaServiceCode, code) +} + +func (b *InMemoryBackend) checkKeyQuotaLocked(region string, limit quotalimit.Limit) error { + t := b.existingTable(region) + if t == nil || !limit.Set { + return nil + } + + if limit.Reached(b.keyCountLocked(t)) { + return fmt.Errorf("%w: the maximum number of KMS keys (%.0f) has been reached", ErrLimitExceeded, limit.Value) + } + + return nil +} + +func (b *InMemoryBackend) checkAliasQuotaLocked(region, targetID string, limit quotalimit.Limit) error { + if !limit.Set { + return nil + } + + n := 0 + + for _, a := range b.aliasesStore(region).All() { + if a.TargetKeyID == targetID { + n++ + } + } + + if limit.Reached(n) { + return fmt.Errorf("%w: key %q already has the maximum number of aliases (%.0f)", + ErrLimitExceeded, targetID, limit.Value) + } + + return nil +} + +func grantsPerKeyLimit(limit quotalimit.Limit) int { + if limit.Set { + return int(limit.Value) + } + + return maxGrantsPerKey +} diff --git a/services/kms/store.go b/services/kms/store.go index 539941eb3c..6ffd7ebe68 100644 --- a/services/kms/store.go +++ b/services/kms/store.go @@ -8,6 +8,8 @@ import ( "sync" "time" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + awsarn "github.com/aws/aws-sdk-go-v2/aws/arn" "github.com/google/uuid" @@ -256,6 +258,7 @@ type InMemoryBackend struct { mu *lockmetrics.RWMutex lastUsage sync.Map importWrappingKeys sync.Map + quotaGate quotalimit.Gate defaultRegion string accountID string tableMu sync.Mutex diff --git a/services/route53/cidr_collections.go b/services/route53/cidr_collections.go index 9c945c4a91..6eac2516f4 100644 --- a/services/route53/cidr_collections.go +++ b/services/route53/cidr_collections.go @@ -16,6 +16,8 @@ func (b *InMemoryBackend) CreateCidrCollection( return nil, fmt.Errorf("%w: name is required", ErrInvalidInput) } + limit := b.quotaLimit(quotaCidrCollections) + b.mu.Lock("CreateCidrCollection") defer b.mu.Unlock() @@ -29,6 +31,10 @@ func (b *InMemoryBackend) CreateCidrCollection( } } + if err := quotaReached(limit, b.cidrCollections.Len(), ErrLimitsExceeded, "CIDR collections"); err != nil { + return nil, err + } + id := "Z" + randomZoneID() col := &CidrCollection{ ID: id, diff --git a/services/route53/handler.go b/services/route53/handler.go index 259290cf42..91857d94e4 100644 --- a/services/route53/handler.go +++ b/services/route53/handler.go @@ -980,6 +980,10 @@ var backendErrorTable = []backendErrorMapping{ {ErrLastVPCAssociation, "LastVPCAssociation", http.StatusBadRequest}, {ErrHostedZoneAlreadyExists, "HostedZoneAlreadyExists", http.StatusConflict}, {ErrHealthCheckAlreadyExists, "HealthCheckAlreadyExists", http.StatusConflict}, + {ErrTooManyHostedZones, "TooManyHostedZones", http.StatusBadRequest}, + {ErrTooManyHealthChecks, "TooManyHealthChecks", http.StatusBadRequest}, + {ErrTooManyTrafficPolicies, "TooManyTrafficPolicies", http.StatusBadRequest}, + {ErrLimitsExceeded, "LimitsExceeded", http.StatusBadRequest}, {ErrKeySigningKeyAlreadyExists, "KeySigningKeyAlreadyExists", http.StatusConflict}, {ErrTrafficPolicyInstanceAlreadyExists, "TrafficPolicyInstanceAlreadyExists", http.StatusConflict}, // AWS: CidrCollectionAlreadyExistsException has httpStatusCode 400 diff --git a/services/route53/health_checks.go b/services/route53/health_checks.go index 03e0763217..c6758b05d8 100644 --- a/services/route53/health_checks.go +++ b/services/route53/health_checks.go @@ -93,6 +93,7 @@ func (b *InMemoryBackend) CreateHealthCheck( } cfg = applyHealthCheckDefaults(cfg) + limit := b.quotaLimit(quotaHealthChecks) b.mu.Lock("CreateHealthCheck") defer b.mu.Unlock() @@ -120,6 +121,10 @@ func (b *InMemoryBackend) CreateHealthCheck( ) } + if err := quotaReached(limit, b.healthChecks.Len(), ErrTooManyHealthChecks, "health checks"); err != nil { + return nil, err + } + hc := &HealthCheck{ ID: randomHealthCheckID(), CallerReference: callerRef, diff --git a/services/route53/hosted_zones.go b/services/route53/hosted_zones.go index 65dc931c13..876b578c15 100644 --- a/services/route53/hosted_zones.go +++ b/services/route53/hosted_zones.go @@ -71,6 +71,7 @@ func (b *InMemoryBackend) CreateHostedZone( } name = normaliseName(name) + limit := b.quotaLimit(quotaHostedZones) b.mu.Lock("CreateHostedZone") defer b.mu.Unlock() @@ -80,6 +81,10 @@ func (b *InMemoryBackend) CreateHostedZone( return existing, err } + if err = quotaReached(limit, b.zones.Len(), ErrTooManyHostedZones, "hosted zones"); err != nil { + return nil, err + } + nameServers, err := b.resolveZoneNameServers(delegationSetID) if err != nil { return nil, err diff --git a/services/route53/quota.go b/services/route53/quota.go new file mode 100644 index 0000000000..ba5a7c2dd5 --- /dev/null +++ b/services/route53/quota.go @@ -0,0 +1,118 @@ +package route53 + +import ( + "errors" + "fmt" + + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" +) + +const ( + quotaServiceCode = "route53" + quotaHostedZones = "L-4EA4796A" + quotaHealthChecks = "L-ACB674F3" + quotaDelegationSets = "L-A72C7724" + quotaTrafficPolicies = "L-FC688E7C" + quotaCidrCollections = "L-AD61772F" + quotaRecordsPerZone = "L-E209CC9F" +) + +// The limit errors CreateHostedZone, CreateHealthCheck, CreateReusableDelegationSet, CreateTrafficPolicy and +// CreateCidrCollection declare (route53@v1.70.5 deserializers.go:1212, :1039, :1803, :1988, :863). +var ( + ErrTooManyHostedZones = errors.New("TooManyHostedZones") + ErrTooManyHealthChecks = errors.New("TooManyHealthChecks") + ErrTooManyTrafficPolicies = errors.New("TooManyTrafficPolicies") + ErrLimitsExceeded = errors.New("LimitsExceeded") +) + +// SetQuotaLimiter makes the create operations honour Service Quotas; nil disables it. +func (h *Handler) SetQuotaLimiter(f quotalimit.Func) { + if b, ok := h.Backend.(*InMemoryBackend); ok { + b.quotaGate.Set(f) + } +} + +// QuotaCounter is the read-only view of the backend that Service Quotas utilization reads. +type QuotaCounter interface { + HostedZoneCount() int + HealthCheckCount() int + DelegationSetCount() int + TrafficPolicyCount() int + CidrCollectionCount() int + MaxRecordsPerHostedZone() int +} + +// QuotaCounts returns the live counts behind the Service Quotas usage of this service. +func (h *Handler) QuotaCounts() QuotaCounter { + if b, ok := h.Backend.(*InMemoryBackend); ok { + return b + } + + return nil +} + +// HostedZoneCount returns the hosted zones of the account. +func (b *InMemoryBackend) HostedZoneCount() int { + b.mu.RLock("HostedZoneCount") + defer b.mu.RUnlock() + + return b.zones.Len() +} + +// HealthCheckCount returns the health checks of the account. +func (b *InMemoryBackend) HealthCheckCount() int { + b.mu.RLock("HealthCheckCount") + defer b.mu.RUnlock() + + return b.healthChecks.Len() +} + +// DelegationSetCount returns the reusable delegation sets of the account. +func (b *InMemoryBackend) DelegationSetCount() int { + b.mu.RLock("DelegationSetCount") + defer b.mu.RUnlock() + + return b.reusableDelegationSets.Len() +} + +// TrafficPolicyCount returns the traffic policies of the account. +func (b *InMemoryBackend) TrafficPolicyCount() int { + b.mu.RLock("TrafficPolicyCount") + defer b.mu.RUnlock() + + return len(b.trafficPolicies) +} + +// CidrCollectionCount returns the CIDR collections of the account. +func (b *InMemoryBackend) CidrCollectionCount() int { + b.mu.RLock("CidrCollectionCount") + defer b.mu.RUnlock() + + return b.cidrCollections.Len() +} + +// MaxRecordsPerHostedZone returns the most record sets any single hosted zone holds. +func (b *InMemoryBackend) MaxRecordsPerHostedZone() int { + b.mu.RLock("MaxRecordsPerHostedZone") + defer b.mu.RUnlock() + + most := 0 + for _, zd := range b.zones.All() { + most = max(most, len(zd.records)) + } + + return most +} + +func (b *InMemoryBackend) quotaLimit(code string) quotalimit.Limit { + return b.quotaGate.Lookup("", "", quotaServiceCode, code) +} + +func quotaReached(limit quotalimit.Limit, current int, sentinel error, kind string) error { + if limit.Reached(current) { + return fmt.Errorf("%w: the maximum number of %s (%.0f) has been reached", sentinel, kind, limit.Value) + } + + return nil +} diff --git a/services/route53/reusable_delegation_sets.go b/services/route53/reusable_delegation_sets.go index 0a6d5a9eec..8577e2190a 100644 --- a/services/route53/reusable_delegation_sets.go +++ b/services/route53/reusable_delegation_sets.go @@ -40,6 +40,8 @@ func (b *InMemoryBackend) CreateReusableDelegationSet( return nil, fmt.Errorf("%w: callerReference is required", ErrInvalidInput) } + limit := b.quotaLimit(quotaDelegationSets) + b.mu.Lock("CreateReusableDelegationSet") defer b.mu.Unlock() @@ -58,6 +60,11 @@ func (b *InMemoryBackend) CreateReusableDelegationSet( return nil, err } + err = quotaReached(limit, b.reusableDelegationSets.Len(), ErrLimitsExceeded, "reusable delegation sets") + if err != nil { + return nil, err + } + id := "/delegationset/N" + randomDelegationSetID() ds := &ReusableDelegationSet{ ID: id, diff --git a/services/route53/store.go b/services/route53/store.go index b44d07ace6..2cf1f746cb 100644 --- a/services/route53/store.go +++ b/services/route53/store.go @@ -4,6 +4,8 @@ import ( "crypto/rand" "encoding/binary" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" "github.com/blackbirdworks/gopherstack/pkgs/store" svcTags "github.com/blackbirdworks/gopherstack/pkgs/tags" @@ -47,6 +49,7 @@ type InMemoryBackend struct { changes *store.Table[ChangeInfo] tags map[string]*svcTags.Tags mu *lockmetrics.RWMutex + quotaGate quotalimit.Gate } // NewInMemoryBackend creates a new InMemoryBackend. diff --git a/services/route53/traffic_policies.go b/services/route53/traffic_policies.go index a5931d1aaa..3486b3f880 100644 --- a/services/route53/traffic_policies.go +++ b/services/route53/traffic_policies.go @@ -28,6 +28,8 @@ func (b *InMemoryBackend) CreateTrafficPolicy( return nil, fmt.Errorf("%w: document is required", ErrInvalidInput) } + limit := b.quotaLimit(quotaTrafficPolicies) + b.mu.Lock("CreateTrafficPolicy") defer b.mu.Unlock() @@ -41,6 +43,10 @@ func (b *InMemoryBackend) CreateTrafficPolicy( } } + if err := quotaReached(limit, len(b.trafficPolicies), ErrTooManyTrafficPolicies, "traffic policies"); err != nil { + return nil, err + } + id := randomTrafficPolicyID() tp := &TrafficPolicy{ ID: id, diff --git a/services/servicequotas/PARITY.md b/services/servicequotas/PARITY.md index 3924ee652a..10784fbd79 100644 --- a/services/servicequotas/PARITY.md +++ b/services/servicequotas/PARITY.md @@ -38,8 +38,8 @@ families: Reports: {status: ok, note: "The report snapshot is taken when the report completes."} AutoManagement: {status: ok, note: "One configuration per account and Region."} items_still_open: - - "QuotaUtilization: S3 buckets, EC2 Elastic IPs, VPCs, IAM roles/users/groups/customer managed policies/instance profiles, EKS clusters, DynamoDB tables, ECS clusters, RDS DB instances and clusters, CloudFormation stacks and ALB/NLB/Classic load balancers report usage; the other catalogued quotas (Lambda, CloudFormation stack sets, EC2 instance vCPUs and Spot requests, the other VPC quotas and every quota of the other documented services) have no live counter wired in internal/app/service_quotas_wiring.go quotaCounters" - - "AppliedQuotaEnforcement: opt-in (--enforce-service-quotas) for S3 buckets, EC2 Elastic IPs and VPCs, IAM roles/users/groups/customer managed policies/instance profiles, EKS clusters, DynamoDB tables, RDS DB instances and clusters, CloudFormation stacks and ALB/NLB/Classic load balancers only; ECS clusters are counted but not enforced (CreateCluster declares no limit exception), and the other catalogued quotas are never enforced" + - "QuotaUtilization: 61 count-of-resources quotas report live usage (internal/app/testdata/service_quota_classes.json class c); the other 3368 count-of-resources quotas (per-instance-type usage of SageMaker, Bedrock, Connect, Glue, CloudFront, Spot-fleet style quotas and the remaining quotas of every documented service) have no counter wired in internal/app/service_quotas_counters.go, and the 1413 rate, throughput and concurrency quotas report no usage because the emulator keeps no request-rate or concurrency meter" + - "AppliedQuotaEnforcement: opt-in (--enforce-service-quotas) for S3 buckets, EC2 Elastic IPs, VPCs, NAT gateways per AZ, network interfaces and routes per table, IAM roles/users/groups/customer managed policies/instance profiles, EKS clusters, DynamoDB tables, RDS DB instances and clusters, CloudFormation stacks, ALB/NLB/Classic load balancers, CloudWatch Logs log groups, KMS keys/aliases per key/grants per key, EventBridge buses/rules per bus/connections/endpoints/API destinations, Step Functions state machines/activities/versions/aliases, Route 53 hosted zones/health checks/delegation sets/traffic policies/CIDR collections, ECR repositories, Auto Scaling groups and launch configurations, EFS file systems, Firehose delivery streams and Cognito identity and user pools; counted but not enforced: ECS clusters (CreateCluster declares no limit exception), EC2 subnets/internet gateways/security groups/rules per group/route tables/vCPU and Spot quotas (the EC2 error code reference lists no limit code for them) and Route 53 records per hosted zone (ChangeResourceRecordSets declares none); rate quotas never throttle" gaps: [] structural_gaps: - "Support staff never review a case: a request still auto-approves on the lifecycle dwell unless its Support case is resolved first (CASE_CLOSED)." @@ -66,6 +66,16 @@ Emulator choices the SDK does not document: Quota request templates answer TemplatesNotAvailableInRegionException in opt-in, China and GovCloud Regions and hold at most 10 items (QuotaExceededException on the 11th); sources docs.aws.amazon.com/servicequotas/latest/userguide/organization-templates.html and docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html. +## Live usage and enforcement + +- Count quotas are classified one by one in `internal/app/testdata/service_quota_classes.json` (c counted, e count without counter, s size or length, r rate or concurrency); `TestQuotaClassificationCoversCatalog` fails for a catalogued quota missing from it and `TestQuotaCountersMatchClassification` for a counter and a class that disagree. The s/r/e split of the uncounted quotas is name-derived and was not reviewed quota by quota. +- Quotas scoped to a parent (subnets per VPC, rules per security group, aliases per KMS key, rules per event bus, routes per table, versions and aliases per state machine) report the largest count in any single parent in the Region, and enforce per parent. +- Enforcement reads the applied value before the owning backend takes its lock and compares it inside the same critical section as the create, so concurrent creates cannot overshoot; with the flag off nothing is consulted and the built-in caps (EventBridge 200 buses and 300 rules per bus, KMS 50,000 grants per key, EFS file system cap) are unchanged. +- Limit errors come from the SDK operation error lists (`deserializeOpError` of the pinned module versions) or, for EC2, from the EC2 error code reference (NatGatewayLimitExceeded, NetworkInterfaceLimitExceeded, ResourceCountLimitExceeded). +- EC2 vCPU quotas count pending and running On-Demand instances by instance family class and open or active Spot requests by requested type; instances launched by a Spot request are excluded from the On-Demand count. +- Route 53 is account-global: it consults the applied value of the Service Quotas backend's own account and Region. +- Rate, throughput and concurrency quotas (requests per second, concurrent executions) are catalogued with their values and never produce throttling; no usage is reported for them. + ## Primary-source checks (2026-11-13) - servicequotas: IAM reference_iam-quotas.html lists the maximum quotas per account as roles 10,000, customer managed policies 10,000, instance profiles 10,000 and groups 500 (catalog fixed from 5,000). diff --git a/services/stepfunctions/activities.go b/services/stepfunctions/activities.go index f468be7263..856500df69 100644 --- a/services/stepfunctions/activities.go +++ b/services/stepfunctions/activities.go @@ -80,6 +80,7 @@ func (b *InMemoryBackend) CreateActivity(ctx context.Context, name string) (*Act region := getRegionFromContext(ctx, b.region) actARN := b.activityARN(region, name) + limit := b.quotaLimit(region, quotaActivities) b.mu.Lock("CreateActivity") defer b.mu.Unlock() @@ -89,6 +90,10 @@ func (b *InMemoryBackend) CreateActivity(ctx context.Context, name string) (*Act return nil, fmt.Errorf("%w: %s", ErrActivityAlreadyExists, name) } + if err := quotaReached(limit, len(actIdx), ErrActivityLimitExceeded, "activities"); err != nil { + return nil, err + } + a := &Activity{ Name: name, ActivityArn: actARN, diff --git a/services/stepfunctions/aliases.go b/services/stepfunctions/aliases.go index 6491d04331..9de801f9e9 100644 --- a/services/stepfunctions/aliases.go +++ b/services/stepfunctions/aliases.go @@ -68,6 +68,8 @@ func (b *InMemoryBackend) CreateStateMachineAlias( return nil, err } + limit := b.quotaLimit(regionFromARN(routing[0].StateMachineVersionArn, b.region), quotaAliases) + b.mu.Lock("CreateStateMachineAlias") defer b.mu.Unlock() @@ -111,6 +113,11 @@ func (b *InMemoryBackend) CreateStateMachineAlias( return nil, fmt.Errorf("%w: %s", ErrStateMachineAliasAlreadyExists, name) } + err := quotaReached(limit, len(b.smAliases[smARN]), ErrServiceQuotaExceeded, "state machine aliases") + if err != nil { + return nil, err + } + now := epochNow() alias := &StateMachineAlias{ StateMachineAliasArn: aARN, diff --git a/services/stepfunctions/handler.go b/services/stepfunctions/handler.go index 22a28165d8..0660f3a10f 100644 --- a/services/stepfunctions/handler.go +++ b/services/stepfunctions/handler.go @@ -378,6 +378,9 @@ func errorMappings() []errorMapping { {ErrValidation, "ValidationException", http.StatusBadRequest}, {errUnknownOperation, "UnknownOperationException", http.StatusBadRequest}, {ErrInvalidToken, "InvalidToken", http.StatusBadRequest}, + {ErrStateMachineLimitExceeded, "StateMachineLimitExceeded", http.StatusBadRequest}, + {ErrActivityLimitExceeded, "ActivityLimitExceeded", http.StatusBadRequest}, + {ErrServiceQuotaExceeded, "ServiceQuotaExceededException", http.StatusBadRequest}, } } diff --git a/services/stepfunctions/quota.go b/services/stepfunctions/quota.go new file mode 100644 index 0000000000..92e9b10298 --- /dev/null +++ b/services/stepfunctions/quota.go @@ -0,0 +1,107 @@ +package stepfunctions + +import ( + "errors" + "fmt" + + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" +) + +const ( + quotaServiceCode = "states" + quotaStateMachines = "L-B66B0F91" + quotaActivities = "L-A9562A73" + quotaVersions = "L-6AFCB355" + quotaAliases = "L-C1D5EBBB" +) + +// The limit exceptions CreateStateMachine, CreateActivity, PublishStateMachineVersion and +// CreateStateMachineAlias declare (sfn@v1.49.0 deserializers.go:220, :88, :2812, :376). +var ( + ErrStateMachineLimitExceeded = errors.New("StateMachineLimitExceeded") + ErrActivityLimitExceeded = errors.New("ActivityLimitExceeded") + ErrServiceQuotaExceeded = errors.New("ServiceQuotaExceededException") +) + +// SetQuotaLimiter makes the create operations honour Service Quotas; nil disables it. +func (h *Handler) SetQuotaLimiter(f quotalimit.Func) { + if b, ok := h.Backend.(*InMemoryBackend); ok { + b.quotaGate.Set(f) + } +} + +// StateMachineCount returns the state machines held in region. +func (h *Handler) StateMachineCount(region string) int { + if b, ok := h.Backend.(*InMemoryBackend); ok { + return b.indexLen(b.nameIndex, region) + } + + return 0 +} + +// ActivityCount returns the activities held in region. +func (h *Handler) ActivityCount(region string) int { + if b, ok := h.Backend.(*InMemoryBackend); ok { + return b.indexLen(b.activityNameIndex, region) + } + + return 0 +} + +// MaxVersionsPerStateMachine returns the most versions any state machine in region has. +func (h *Handler) MaxVersionsPerStateMachine(region string) int { + if b, ok := h.Backend.(*InMemoryBackend); ok { + return b.maxPerStateMachine(region, func(arn string) int { return len(b.versionsByStateMachine.Get(arn)) }) + } + + return 0 +} + +// MaxAliasesPerStateMachine returns the most aliases any state machine in region has. +func (h *Handler) MaxAliasesPerStateMachine(region string) int { + if b, ok := h.Backend.(*InMemoryBackend); ok { + return b.maxPerStateMachine(region, func(arn string) int { return len(b.smAliases[arn]) }) + } + + return 0 +} + +func (b *InMemoryBackend) indexLen(m map[string]map[string]string, region string) int { + if region == "" { + region = b.region + } + + b.mu.RLock("QuotaCount") + defer b.mu.RUnlock() + + return len(m[region]) +} + +func (b *InMemoryBackend) maxPerStateMachine(region string, count func(arn string) int) int { + if region == "" { + region = b.region + } + + b.mu.RLock("QuotaCount") + defer b.mu.RUnlock() + + most := 0 + + for _, arn := range b.nameIndex[region] { + most = max(most, count(arn)) + } + + return most +} + +func (b *InMemoryBackend) quotaLimit(region, code string) quotalimit.Limit { + return b.quotaGate.Lookup(b.accountID, region, quotaServiceCode, code) +} + +func quotaReached(limit quotalimit.Limit, current int, sentinel error, kind string) error { + if limit.Reached(current) { + return fmt.Errorf("%w: the maximum number of %s (%.0f) has been reached", sentinel, kind, limit.Value) + } + + return nil +} diff --git a/services/stepfunctions/state_machine_versions.go b/services/stepfunctions/state_machine_versions.go index a04054506d..aef2f3fe96 100644 --- a/services/stepfunctions/state_machine_versions.go +++ b/services/stepfunctions/state_machine_versions.go @@ -9,6 +9,8 @@ import ( func (b *InMemoryBackend) PublishStateMachineVersion( smARN, description, revisionID string, ) (*StateMachineVersion, error) { + limit := b.quotaLimit(regionFromARN(smARN, b.region), quotaVersions) + b.mu.Lock("PublishStateMachineVersion") defer b.mu.Unlock() @@ -21,6 +23,12 @@ func (b *InMemoryBackend) PublishStateMachineVersion( return nil, fmt.Errorf("%w: %s", ErrStateMachineDeleting, smARN) } + if err := quotaReached( + limit, len(b.versionsByStateMachine.Get(smARN)), ErrServiceQuotaExceeded, "state machine versions", + ); err != nil { + return nil, err + } + versionNum := len(b.versionsByStateMachine.Get(smARN)) + 1 vARN := b.versionARN(smARN, sm.Name, versionNum) diff --git a/services/stepfunctions/state_machines.go b/services/stepfunctions/state_machines.go index 60026235d6..ca228e8a26 100644 --- a/services/stepfunctions/state_machines.go +++ b/services/stepfunctions/state_machines.go @@ -91,6 +91,7 @@ func (b *InMemoryBackend) CreateStateMachine( region := getRegionFromContext(ctx, b.region) smARN := b.smARN(region, name) + limit := b.quotaLimit(region, quotaStateMachines) b.mu.Lock("CreateStateMachine") defer b.mu.Unlock() @@ -121,6 +122,10 @@ func (b *InMemoryBackend) CreateStateMachine( return nil, fmt.Errorf("%w: %s", ErrStateMachineAlreadyExists, name) } + if err = quotaReached(limit, len(nameIdx), ErrStateMachineLimitExceeded, "state machines"); err != nil { + return nil, err + } + now := epochNow() sm := &StateMachine{ CreationDate: now, diff --git a/services/stepfunctions/store.go b/services/stepfunctions/store.go index edf8b52438..ca00db2be4 100644 --- a/services/stepfunctions/store.go +++ b/services/stepfunctions/store.go @@ -11,6 +11,8 @@ import ( "time" "unicode" + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" + "github.com/blackbirdworks/gopherstack/pkgs/arn" "github.com/blackbirdworks/gopherstack/pkgs/config" "github.com/blackbirdworks/gopherstack/pkgs/cwmetric" @@ -177,6 +179,7 @@ type InMemoryBackend struct { // make a status-keyed Index stale -- see store_setup.go. smExecsByStatus map[string]map[string][]string accountID string + quotaGate quotalimit.Gate region string settings Settings // mapChildSeq counts Distributed Map child executions spawned so far, From 1739626bb591783bc030d4de00b8a6f8b48f35a3 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 22:25:26 -0600 Subject: [PATCH 4/8] feat(athena): array set operations, sequence, repeat, zip, base conversion, bit and statistical aggregates and more Trino functions Several of these resolved in Athena only because another engine had registered them under plain names in the shared function table. Athena now implements them itself. Names that are not Trino functions stay unregistered. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/athena/PARITY.md | 20 +- services/athena/engine_bool.go | 3 +- services/athena/engine_funcs.go | 4 + services/athena/engine_funcs_agg_stat.go | 170 +++++++ services/athena/engine_funcs_array_ops.go | 430 ++++++++++++++++++ services/athena/engine_funcs_str.go | 15 +- services/athena/engine_funcs_trino_math.go | 305 +++++++++++++ services/athena/engine_funcs_trino_str.go | 103 +++++ .../athena/engine_trino_funcs_sdk_test.go | 330 ++++++++++++++ test/crossengine/function_namespace_test.go | 33 ++ 10 files changed, 1409 insertions(+), 4 deletions(-) create mode 100644 services/athena/engine_funcs_agg_stat.go create mode 100644 services/athena/engine_funcs_array_ops.go create mode 100644 services/athena/engine_funcs_trino_math.go create mode 100644 services/athena/engine_funcs_trino_str.go create mode 100644 services/athena/engine_trino_funcs_sdk_test.go diff --git a/services/athena/PARITY.md b/services/athena/PARITY.md index a923c8771f..8a2be16a33 100644 --- a/services/athena/PARITY.md +++ b/services/athena/PARITY.md @@ -54,7 +54,10 @@ families: pagination: {status: ok, note: "FIXED (2026-07-23) — WorkGroups/NamedQueries/DataCatalogs/PreparedStatements/(new) ListTagsForResource all sort + NextToken/MaxResults correctly, and an unrecognized/stale NextToken (e.g. its boundary item was deleted between calls) now resumes at the first surviving item at-or-after the boundary (pagination.paginationStart, mutation-stable via sort.Search) instead of silently restarting the page from offset 0 and re-emitting already-consumed results. Locked in by TestListWorkGroups_Pagination_StaleTokenResumesStably."} janitor/leaks: {status: clean, note: "worker.Group-based ticker with ctx cancellation; sweeps queryExecutions+queryResults, sessions, calculations under RLock-collect/Lock-delete with re-verification to avoid racing a concurrent revival. No goroutine leak risk found."} gaps: [] -items_still_open: [] +items_still_open: + - "Trino functions Athena v3 documents but the engine lacks (each fails 'Function not registered'): aggregates listagg, checksum, map_union, multimap_agg, approx_most_frequent, numeric_histogram, approx_set/merge, qdigest_agg, tdigest_agg, reduce_agg; arrays array_histogram, combinations, ngrams; vector/stat functions cosine_distance, cosine_similarity, dot_product, euclidean_distance, beta_cdf, normal_cdf, t_cdf, t_pdf, inverse_beta_cdf, inverse_normal_cdf, wilson_interval_lower/upper; width_bucket(x, bins array) overload; date/time at_timezone, with_timezone, timezone_hour, timezone_minute, current_timezone, now, localtimestamp, from_unixtime_nanos, from_iso8601_timestamp_nanos, human_readable_seconds; string/binary luhn_check, normalize, regexp_position, split_to_map, split_to_multimap, title_case, word_stem, soundex, to_base64url, from_base64url, hmac_md5/sha1/sha256/sha512, xxhash64, spooky_hash_v2_32/64, JSON json_array_contains, json_array_get, is_json_scalar; maps map_entries, map_from_entries, map_concat, multimap_from_entries; position(x IN y) and overlay(... PLACING ...) syntax." + - "nan() cannot be a real DOUBLE: SQLite stores NaN as NULL, so nan() yields the text NaN (ColumnInfo varchar, not double) that is_nan/is_finite/is_infinite recognise; arithmetic on it and NaN results of skewness/kurtosis with zero variance surface as NULL." + - "Aggregates over zero rows (bitwise_*_agg, skewness, kurtosis, regr_*) report ColumnInfo varchar, not bigint/double: result types are inferred from the first non-NULL value." structural_gaps: - "SQL is SQLite semantics behind a Presto/Trino translation layer, not Trino; TABLESAMPLE and multi-argument UNNEST fail as SYNTAX_ERROR." - "DeleteDataCatalogInput.DeleteCatalogOnly has no effect: a FEDERATED catalog's CFN Stack/Lambda/Glue Connection resources are not simulated." @@ -76,6 +79,21 @@ leaks: {status: clean, note: "janitor uses pkgs/worker.Group with proper ctx.Don - ROW(...) constructors, CAST(... AS ROW(a T, b U)) (also inside ARRAY(...)), name and subscript access, nesting in ARRAY/MAP, `{a=1, b=x}` / anonymous `[1, x]` rendering, ColumnInfo type `row`. Per trino.io/docs/current/language/types.html#row. - Table-less FROM (subquery or CTE over constants) now runs in the SQL engine instead of returning no rows. +### Trino collection, bitwise, base and statistics functions + +Added natively under the `athena_` prefix (no dependency on any other service engine): sequence (bigint, date and +timestamp with day-to-second / year-to-month steps, 10000-entry cap), repeat (count 0..10000), zip (2-5 arrays, null padded, +anonymous ROW elements), array_union/array_intersect/array_except/arrays_overlap, shuffle, array_first/array_last, flatten, +trim_array, contains_sequence, from_base/to_base, bit_count, bitwise_not, bitwise_left_shift/right_shift/right_shift_arithmetic, +hamming_distance, infinity, nan, e, is_infinite, year_of_week/yow, width_bucket (4-argument form), ends_with, translate, +url_encode/url_decode, and the aggregates bitwise_and_agg/bitwise_or_agg/bitwise_xor_agg, skewness, kurtosis, +regr_slope, regr_intercept. Signatures per trino.io/docs/current/functions/{array,math,bitwise,string,datetime,aggregate}.html. +Names Timestream Query registered plain that are NOT Trino functions (strrpos, from_milliseconds, from_nanoseconds, +to_nanoseconds, nanosecond) are deliberately not registered here: real Athena rejects them. Error wording for sequence, +repeat, from_base, bit_count and hamming_distance follows Trino's source; trim_array, width_bucket and the shift errors are +UNVERIFIED wording. skewness uses the sample-adjusted estimator and kurtosis the sample excess estimator (min 3 / 4 rows) +from memory of Trino's implementation: UNVERIFIED against live Athena. + ### 2026-11-06 booleans, Avro, Iceberg row-level DML Docs authority (fetched 2026-11-06): Athena user guide pages `optimize-statement`, `vacuum-statement`, diff --git a/services/athena/engine_bool.go b/services/athena/engine_bool.go index 6ae10b8499..d89a46576a 100644 --- a/services/athena/engine_bool.go +++ b/services/athena/engine_bool.go @@ -33,7 +33,8 @@ const ( func isBoolFunc(n string) bool { switch n { case "regexp_like", "starts_with", "contains", "is_nan", "is_finite", "is_infinite", "any_match", "all_match", - "none_match", "json_array_contains", "bool_and", "bool_or", "every", "arrays_overlap": + "none_match", "json_array_contains", "bool_and", "bool_or", "every", "arrays_overlap", "ends_with", + "contains_sequence": return true } diff --git a/services/athena/engine_funcs.go b/services/athena/engine_funcs.go index 02f9370414..6058fbc72b 100644 --- a/services/athena/engine_funcs.go +++ b/services/athena/engine_funcs.go @@ -49,6 +49,10 @@ func registerEngineFuncs() { registerExtraFuncs() registerComplexFuncs() registerAggregates() + registerStatAggregates() + registerArrayOpFuncs() + registerTrinoMathFuncs() + registerTrinoStringFuncs() registerRowCompareFuncs() registerUnnestModule() }) diff --git a/services/athena/engine_funcs_agg_stat.go b/services/athena/engine_funcs_agg_stat.go new file mode 100644 index 0000000000..50b4568541 --- /dev/null +++ b/services/athena/engine_funcs_agg_stat.go @@ -0,0 +1,170 @@ +package athena + +import ( + "database/sql/driver" + "math" +) + +const ( + minSkewnessRows = 3 + minKurtosisRows = 4 + momentThree = 3 + momentSix = 6 + momentFour = 4 + skewExponent = 1.5 +) + +func bitwiseAggregate(name string, apply func(a, b int64) int64) *aggState { + var ( + acc int64 + seen bool + ) + + return &aggState{ + step: func(args []driver.Value) error { + if args[0] == nil { + return nil + } + + n, ok := bigintArg(args[0]) + if !ok { + return errUnexpected(name) + } + + if seen { + acc = apply(acc, n) + } else { + acc, seen = n, true + } + + return nil + }, + final: func() driver.Value { + if !seen { + return sqlNull() + } + + return acc + }, + } +} + +// centralMoments keeps running central centralMoments (Pebay's one-pass update). +type centralMoments struct { + n, mean, m2, m3, m4 float64 +} + +func (m *centralMoments) add(x float64) { + prev := m.n + m.n++ + + delta := x - m.mean + deltaN := delta / m.n + deltaN2 := deltaN * deltaN + term := delta * deltaN * prev + + m.mean += deltaN + m.m4 += term*deltaN2*(m.n*m.n-momentThree*m.n+momentThree) + momentSix*deltaN2*m.m2 - + momentFour*deltaN*m.m3 + m.m3 += term*deltaN*(m.n-argsTwo) - momentThree*deltaN*m.m2 + m.m2 += term +} + +func (m *centralMoments) skewness() driver.Value { + if m.n < minSkewnessRows { + return sqlNull() + } + + return m.n * math.Sqrt(m.n-1) / (m.n - argsTwo) * m.m3 / math.Pow(m.m2, skewExponent) +} + +func (m *centralMoments) kurtosis() driver.Value { + if m.n < minKurtosisRows { + return sqlNull() + } + + n := m.n + denom := (n - argsTwo) * (n - argsThree) + + return (n-1)*n*(n+1)/denom*m.m4/(m.m2*m.m2) - momentThree*(n-1)*(n-1)/denom +} + +func momentAggregate(name string, result func(*centralMoments) driver.Value) *aggState { + var m centralMoments + + return &aggState{ + step: func(args []driver.Value) error { + if args[0] == nil { + return nil + } + + x, ok := toFloatArg(args[0]) + if !ok { + return errUnexpected(name) + } + + m.add(x) + + return nil + }, + final: func() driver.Value { return result(&m) }, + } +} + +// regressionAggregate regresses y (first argument) on x (second) over the rows where both are non-NULL. +func regressionAggregate(name string, intercept bool) *aggState { + var n, meanX, meanY, cxy, m2x float64 + + return &aggState{ + step: func(args []driver.Value) error { + if args[0] == nil || args[1] == nil { + return nil + } + + y, yok := toFloatArg(args[0]) + x, xok := toFloatArg(args[1]) + + if !yok || !xok { + return errUnexpected(name) + } + + n++ + + dx := x - meanX + meanX += dx / n + meanY += (y - meanY) / n + cxy += dx * (y - meanY) + m2x += dx * (x - meanX) + + return nil + }, + final: func() driver.Value { + if n == 0 || m2x == 0 { + return sqlNull() + } + + slope := cxy / m2x + if intercept { + return meanY - slope*meanX + } + + return slope + }, + } +} + +func registerStatAggregates() { + registerAgg("bitwise_and_agg", 1, func() *aggState { + return bitwiseAggregate("bitwise_and_agg", func(a, b int64) int64 { return a & b }) + }) + registerAgg("bitwise_or_agg", 1, func() *aggState { + return bitwiseAggregate("bitwise_or_agg", func(a, b int64) int64 { return a | b }) + }) + registerAgg("bitwise_xor_agg", 1, func() *aggState { + return bitwiseAggregate("bitwise_xor_agg", func(a, b int64) int64 { return a ^ b }) + }) + registerAgg("skewness", 1, func() *aggState { return momentAggregate("skewness", (*centralMoments).skewness) }) + registerAgg("kurtosis", 1, func() *aggState { return momentAggregate("kurtosis", (*centralMoments).kurtosis) }) + registerAgg("regr_slope", argsTwo, func() *aggState { return regressionAggregate("regr_slope", false) }) + registerAgg("regr_intercept", argsTwo, func() *aggState { return regressionAggregate("regr_intercept", true) }) +} diff --git a/services/athena/engine_funcs_array_ops.go b/services/athena/engine_funcs_array_ops.go new file mode 100644 index 0000000000..acbc0e2693 --- /dev/null +++ b/services/athena/engine_funcs_array_ops.go @@ -0,0 +1,430 @@ +package athena + +import ( + "database/sql/driver" + "encoding/json/v2" + "math/rand/v2" + "slices" + "time" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" +) + +const ( + maxSequenceEntries = 10000 + maxRepeatCount = 10000 + minZipArrays = 2 + maxZipArrays = 5 +) + +func elemKey(e any) string { + b, err := json.Marshal(e, jsonx.V1()) + if err != nil { + return kwNull + } + + return string(b) +} + +func keySet(a []any) map[string]bool { + out := make(map[string]bool, len(a)) + for _, e := range a { + out[elemKey(e)] = true + } + + return out +} + +func distinctElems(a []any) []any { + seen := make(map[string]bool, len(a)) + out := make([]any, 0, len(a)) + + for _, e := range a { + if k := elemKey(e); !seen[k] { + seen[k] = true + out = append(out, e) + } + } + + return out +} + +func twoArrays(args []driver.Value) ([]any, []any, bool) { + x, xok := asArray(args[0]) + y, yok := asArray(args[1]) + + return x, y, xok && yok +} + +func setOperation(keep func(inY bool) bool, includeY bool) scalarFn { + return func(_ *fnCtx, args []driver.Value) (driver.Value, error) { + x, y, ok := twoArrays(args) + if !ok { + return sqlNull(), nil + } + + inY := keySet(y) + out := make([]any, 0, len(x)+len(y)) + + for _, e := range x { + if keep(inY[elemKey(e)]) { + out = append(out, e) + } + } + + if includeY { + out = append(out, y...) + } + + return jsonText(distinctElems(out)), nil + } +} + +func udfArraysOverlap(_ *fnCtx, args []driver.Value) (driver.Value, error) { + x, y, ok := twoArrays(args) + if !ok { + return sqlNull(), nil + } + + inY := keySet(y) + sawNull := inY[kwNull] + + for _, e := range x { + k := elemKey(e) + if k == kwNull { + sawNull = true + + continue + } + + if inY[k] { + return int64(1), nil + } + } + + if sawNull { + return sqlNull(), nil + } + + return int64(0), nil +} + +func udfShuffle(_ *fnCtx, args []driver.Value) (driver.Value, error) { + a, ok := asArray(args[0]) + if !ok { + return sqlNull(), nil + } + + rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) //nolint:gosec // not security-sensitive + + return jsonText(a), nil +} + +func udfRepeat(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[1] == nil { + return sqlNull(), nil + } + + n, ok := toInt(args[1]) + if !ok { + return nil, errArg("Unexpected parameters for function repeat") + } + + switch { + case n < 0: + return nil, errArg("count argument of repeat function must be greater than or equal to 0") + case n > maxRepeatCount: + return nil, errArg("count argument of repeat function must be less than or equal to %d", maxRepeatCount) + } + + elem := jsonElem(args[0]) + out := make([]any, n) + + for i := range out { + out[i] = elem + } + + return jsonText(out), nil +} + +func udfZip(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if len(args) < minZipArrays || len(args) > maxZipArrays { + return nil, errArg("Unexpected parameters for function zip: expected between 2 and 5 arrays") + } + + arrays := make([][]any, len(args)) + width := 0 + + for i, a := range args { + arr, ok := asArray(a) + if !ok { + return sqlNull(), nil + } + + arrays[i] = arr + width = max(width, len(arr)) + } + + names := make([]string, len(arrays)) + rows := make([]any, width) + + for r := range rows { + vals := make([]any, len(arrays)) + + for c, arr := range arrays { + if r < len(arr) { + vals[c] = arr[r] + } + } + + rows[r] = newRow(names, vals) + } + + return jsonText(rows), nil +} + +func udfArrayFirst(_ *fnCtx, args []driver.Value) (driver.Value, error) { + a, ok := asArray(args[0]) + if !ok || len(a) == 0 { + return sqlNull(), nil + } + + return sqlValue(a[0]), nil +} + +func udfArrayLast(_ *fnCtx, args []driver.Value) (driver.Value, error) { + a, ok := asArray(args[0]) + if !ok || len(a) == 0 { + return sqlNull(), nil + } + + return sqlValue(a[len(a)-1]), nil +} + +func udfFlatten(_ *fnCtx, args []driver.Value) (driver.Value, error) { + a, ok := asArray(args[0]) + if !ok { + return sqlNull(), nil + } + + out := make([]any, 0, len(a)) + + for _, e := range a { + if e == nil { + continue + } + + inner, isArr := e.([]any) + if !isArr { + return nil, errArg("Unexpected parameters for function flatten: expected array(array(T))") + } + + out = append(out, inner...) + } + + return jsonText(out), nil +} + +func udfTrimArray(_ *fnCtx, args []driver.Value) (driver.Value, error) { + a, ok := asArray(args[0]) + n, nok := toInt(args[1]) + + if !ok || !nok { + return sqlNull(), nil + } + + switch { + case n < 0: + return nil, errArg("size must not be negative") + case n > int64(len(a)): + return nil, errArg("size must not exceed array length") + } + + return jsonText(a[:int64(len(a))-n]), nil +} + +func udfContainsSequence(_ *fnCtx, args []driver.Value) (driver.Value, error) { + x, y, ok := twoArrays(args) + if !ok { + return sqlNull(), nil + } + + for i := 0; i+len(y) <= len(x); i++ { + if slices.EqualFunc(x[i:i+len(y)], y, func(a, b any) bool { return elemKey(a) == elemKey(b) }) { + return int64(1), nil + } + } + + return int64(0), nil +} + +type sequenceSpec struct { + at func(i int64) time.Time + past func(t time.Time) bool + date bool +} + +func udfSequence(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if len(args) < argsTwo || len(args) > argsThree { + return nil, errArg("Unexpected parameters for function sequence") + } + + if slices.Contains(args, nil) { + return sqlNull(), nil + } + + if _, isInt := args[0].(int64); isInt { + return integerSequence(args) + } + + return temporalSequence(args) +} + +func integerSequence(args []driver.Value) (driver.Value, error) { + start, sok := args[0].(int64) + stop, eok := args[1].(int64) + + if !sok || !eok { + return nil, errArg("Unexpected parameters for function sequence") + } + + step := int64(1) + if start > stop { + step = -1 + } + + if len(args) == argsThree { + var ok bool + if step, ok = args[argsTwo].(int64); !ok { + return nil, errArg("Unexpected parameters for function sequence") + } + } + + if err := checkSequenceBounds(step, start > stop, start == stop); err != nil { + return nil, err + } + + var span uint64 + if start <= stop { + span = uint64(stop) - uint64(start) //nolint:gosec // two's-complement distance + } else { + span = uint64(start) - uint64(stop) //nolint:gosec // two's-complement distance + } + + stride := uint64(step) + if step < 0 { + stride = -uint64(step) + } + + if span/stride >= maxSequenceEntries { + return nil, errSequenceLength() + } + + out := make([]any, 0, span/stride+1) + for v, i := start, uint64(0); i <= span/stride; i++ { + out = append(out, v) + v += step + } + + return jsonText(out), nil +} + +func errSequenceLength() error { + return errArg("result of sequence function must not have more than %d entries", maxSequenceEntries) +} + +func checkSequenceBounds(step int64, descending, equal bool) error { + switch { + case step == 0: + return errArg("step must not be zero") + case !equal && ((step > 0) == descending): + return errArg("sequence stop value should be greater than or equal to start value if step is greater " + + "than zero otherwise stop should be less than or equal to start") + } + + return nil +} + +func temporalSequence(args []driver.Value) (driver.Value, error) { + start, sok := parseTS(args[0]) + stop, eok := parseTS(args[1]) + + if !sok || !eok { + return nil, errArg("Unexpected parameters for function sequence") + } + + date := isDateOnly(args[0]) + kind, step := ivKindDT, int64(millisPerDay) + + if len(args) == argsThree { + var ok bool + if kind, step, ok = ivArg(args[argsTwo]); !ok { + return nil, errArg("Unexpected parameters for function sequence") + } + } else if !date { + return nil, errArg("Unexpected parameters for function sequence") + } + + spec, err := newSequenceSpec(start, stop, kind, step, date) + if err != nil { + return nil, err + } + + out := make([]any, 0, argsThree) + + for i := range int64(maxSequenceEntries + 1) { + t := spec.at(i) + if spec.past(t) { + return jsonText(out), nil + } + + out = append(out, formatLike(t, spec.date)) + } + + return nil, errSequenceLength() +} + +func newSequenceSpec(start, stop time.Time, kind byte, step int64, date bool) (*sequenceSpec, error) { + if err := checkSequenceBounds(step, start.After(stop), start.Equal(stop)); err != nil { + return nil, err + } + + spec := &sequenceSpec{date: date} + + switch { + case kind == ivKindYM: + spec.at = func(i int64) time.Time { return addMonthsClamped(start, int(i*step)) } + case date: + if step%millisPerDay != 0 { + return nil, errArg("sequence step must be a day interval if start and end values are dates") + } + + spec.at = func(i int64) time.Time { return start.AddDate(0, 0, int(i*(step/millisPerDay))) } + default: + spec.at = func(i int64) time.Time { return start.Add(time.Duration(i*step) * time.Millisecond) } + } + + if step > 0 { + spec.past = func(t time.Time) bool { return t.After(stop) } + } else { + spec.past = func(t time.Time) bool { return t.Before(stop) } + } + + return spec, nil +} + +func registerArrayOpFuncs() { + registerNondeterministic("sequence", -1, udfSequence) + registerNondeterministic("repeat", argsTwo, udfRepeat) + registerNondeterministic("zip", -1, udfZip) + registerNondeterministic("shuffle", 1, udfShuffle) + registerNondeterministic("trim_array", argsTwo, udfTrimArray) + registerNondeterministic("flatten", 1, udfFlatten) + registerScalar("array_union", argsTwo, setOperation(func(bool) bool { return true }, true)) + registerScalar("array_intersect", argsTwo, setOperation(func(inY bool) bool { return inY }, false)) + registerScalar("array_except", argsTwo, setOperation(func(inY bool) bool { return !inY }, false)) + registerScalar("arrays_overlap", argsTwo, udfArraysOverlap) + registerScalar("array_first", 1, udfArrayFirst) + registerScalar("array_last", 1, udfArrayLast) + registerScalar("contains_sequence", argsTwo, udfContainsSequence) +} diff --git a/services/athena/engine_funcs_str.go b/services/athena/engine_funcs_str.go index 5589cef304..09f75e87b3 100644 --- a/services/athena/engine_funcs_str.go +++ b/services/athena/engine_funcs_str.go @@ -428,8 +428,19 @@ func toFloatArg(v driver.Value) (float64, bool) { } } +// nanText stands in for NaN, which SQLite cannot store: a double NaN is read back as NULL. +const nanText = "NaN" + +func floatOrNaN(v driver.Value) (float64, bool) { + if s, ok := v.(string); ok && s == nanText { + return math.NaN(), true + } + + return toFloatArg(v) +} + func udfIsNaN(_ *fnCtx, args []driver.Value) (driver.Value, error) { - f, ok := toFloatArg(args[0]) + f, ok := floatOrNaN(args[0]) if !ok { return sqlNull(), nil } @@ -438,7 +449,7 @@ func udfIsNaN(_ *fnCtx, args []driver.Value) (driver.Value, error) { } func udfIsFinite(_ *fnCtx, args []driver.Value) (driver.Value, error) { - f, ok := toFloatArg(args[0]) + f, ok := floatOrNaN(args[0]) if !ok { return sqlNull(), nil } diff --git a/services/athena/engine_funcs_trino_math.go b/services/athena/engine_funcs_trino_math.go new file mode 100644 index 0000000000..5f90eaa021 --- /dev/null +++ b/services/athena/engine_funcs_trino_math.go @@ -0,0 +1,305 @@ +package athena + +import ( + "database/sql/driver" + "math" + "math/bits" + "strconv" + "time" +) + +const ( + minRadix = 2 + maxRadix = 36 + minBitCount = 2 + maxBitCount = 64 + argsFour = 4 + int64Bits = 64 + hammingError = "The input strings to hamming_distance function must have the same length" +) + +func errUnexpected(fn string) error { + return errArg("Unexpected parameters for function %s", fn) +} + +// bigintArg accepts an integer value; SQLite hands whole doubles back for some expressions. +func bigintArg(v driver.Value) (int64, bool) { + switch t := v.(type) { + case int64: + return t, true + case float64: + return int64(t), t == math.Trunc(t) && math.Abs(t) < 1<<53 + default: + return 0, false + } +} + +func radixArg(v driver.Value) (int, error) { + r, ok := bigintArg(v) + if !ok { + return 0, errUnexpected("radix") + } + + if r < minRadix || r > maxRadix { + return 0, errArg("Radix must be between 2 and 36") + } + + return int(r), nil +} + +func udfFromBase(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil { + return sqlNull(), nil + } + + s, ok := asString(args[0]) + if !ok { + return nil, errUnexpected("from_base") + } + + radix, err := radixArg(args[1]) + if err != nil { + return nil, err + } + + n, perr := strconv.ParseInt(s, radix, int64Bits) + if perr != nil { + return nil, errArg("Not a valid base-%d number: %s", radix, s) + } + + return n, nil +} + +func udfToBase(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil { + return sqlNull(), nil + } + + n, ok := bigintArg(args[0]) + if !ok { + return nil, errUnexpected("to_base") + } + + radix, err := radixArg(args[1]) + if err != nil { + return nil, err + } + + return strconv.FormatInt(n, radix), nil +} + +func udfBitwiseNot(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil { + return sqlNull(), nil + } + + n, ok := bigintArg(args[0]) + if !ok { + return nil, errUnexpected("bitwise_not") + } + + return ^n, nil +} + +func udfBitCount(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if args[0] == nil || args[1] == nil { + return sqlNull(), nil + } + + n, nok := bigintArg(args[0]) + width, wok := bigintArg(args[1]) + + if !nok || !wok { + return nil, errUnexpected("bit_count") + } + + if width < minBitCount || width > maxBitCount { + return nil, errArg("Bits specified in bit_count must be between 2 and 64, got %d", width) + } + + mask := ^uint64(0) + + if width < maxBitCount { + limit := int64(1) << (width - 1) + if n < -limit || n >= limit { + return nil, errArg( + "Number must be representable with the bits specified. %d can not be represented with %d bits", + n, + width, + ) + } + + mask = uint64(1)<= int64Bits { + return 0 + } + + return v << by +} + +func shiftRight(v int64, by uint) int64 { + if by >= int64Bits { + return 0 + } + + return int64(uint64(v) >> by) //nolint:gosec // logical shift on the bit pattern +} + +func shiftRightArithmetic(v int64, by uint) int64 { + if by >= int64Bits { + by = int64Bits - 1 + } + + return v >> by +} + +func udfHammingDistance(_ *fnCtx, args []driver.Value) (driver.Value, error) { + a, aok := asString(args[0]) + b, bok := asString(args[1]) + + if !aok || !bok { + if args[0] == nil || args[1] == nil { + return sqlNull(), nil + } + + return nil, errUnexpected("hamming_distance") + } + + ra, rb := []rune(a), []rune(b) + if len(ra) != len(rb) { + return nil, errArg(hammingError) + } + + var diff int64 + + for i := range ra { + if ra[i] != rb[i] { + diff++ + } + } + + return diff, nil +} + +func isoYearOf(t time.Time) int64 { + y, _ := t.ISOWeek() + + return int64(y) +} + +func udfIsInfinite(_ *fnCtx, args []driver.Value) (driver.Value, error) { + f, ok := floatOrNaN(args[0]) + if !ok { + return sqlNull(), nil + } + + return boolInt(math.IsInf(f, 0)), nil +} + +func checkWidthBucket(x, b1, b2 float64, n int64) error { + switch { + case n <= 0: + return errArg("bucketCount must be greater than 0") + case math.IsNaN(x): + return errArg("operand must not be NaN") + case b1 == b2: + return errArg("bounds cannot equal each other") + case math.IsNaN(b1) || math.IsNaN(b2) || math.IsInf(b1, 0) || math.IsInf(b2, 0): + return errArg("first and second bound must be finite") + } + + return nil +} + +func udfWidthBucket(_ *fnCtx, args []driver.Value) (driver.Value, error) { + if slicesHasNil(args) { + return sqlNull(), nil + } + + x, xok := toFloatArg(args[0]) + b1, aok := toFloatArg(args[1]) + b2, bok := toFloatArg(args[argsTwo]) + n, nok := bigintArg(args[argsThree]) + + if !xok || !aok || !bok || !nok { + return nil, errUnexpected("width_bucket") + } + + if err := checkWidthBucket(x, b1, b2, n); err != nil { + return nil, err + } + + lo, hi, from := b1, b2, x + if b1 > b2 { + lo, hi, from = -b1, -b2, -x + } + + switch { + case from < lo: + return int64(0), nil + case from >= hi: + return n + 1, nil + } + + return int64(float64(n)*(from-lo)/(hi-lo)) + 1, nil +} + +func slicesHasNil(args []driver.Value) bool { + for _, a := range args { + if a == nil { + return true + } + } + + return false +} + +func constFunc(v float64) scalarFn { + return func(*fnCtx, []driver.Value) (driver.Value, error) { return v, nil } +} + +func registerTrinoMathFuncs() { + registerNondeterministic("from_base", argsTwo, udfFromBase) + registerNondeterministic("to_base", argsTwo, udfToBase) + registerNondeterministic("bit_count", argsTwo, udfBitCount) + registerNondeterministic("bitwise_not", 1, udfBitwiseNot) + registerNondeterministic("bitwise_left_shift", argsTwo, shiftFunc("bitwise_left_shift", shiftLeft)) + registerNondeterministic("bitwise_right_shift", argsTwo, shiftFunc("bitwise_right_shift", shiftRight)) + registerNondeterministic("bitwise_right_shift_arithmetic", argsTwo, + shiftFunc("bitwise_right_shift_arithmetic", shiftRightArithmetic)) + registerNondeterministic("hamming_distance", argsTwo, udfHammingDistance) + registerNondeterministic("width_bucket", argsFour, udfWidthBucket) + registerScalar("infinity", 0, constFunc(math.Inf(1))) + registerScalar("nan", 0, func(*fnCtx, []driver.Value) (driver.Value, error) { return nanText, nil }) + registerScalar("e", 0, constFunc(math.E)) + registerScalar("is_infinite", 1, udfIsInfinite) + registerScalar("year_of_week", 1, tsPart(isoYearOf)) + registerScalar("yow", 1, tsPart(isoYearOf)) +} diff --git a/services/athena/engine_funcs_trino_str.go b/services/athena/engine_funcs_trino_str.go new file mode 100644 index 0000000000..7214bbea18 --- /dev/null +++ b/services/athena/engine_funcs_trino_str.go @@ -0,0 +1,103 @@ +package athena + +import ( + "database/sql/driver" + "fmt" + "net/url" + "strings" +) + +const urlSafeMarks = ".-*_" + +func udfEndsWith(_ *fnCtx, args []driver.Value) (driver.Value, error) { + s, sok := asString(args[0]) + p, pok := asString(args[1]) + + if !sok || !pok { + return sqlNull(), nil + } + + return boolInt(strings.HasSuffix(s, p)), nil +} + +func udfTranslate(_ *fnCtx, args []driver.Value) (driver.Value, error) { + s, sok := asString(args[0]) + from, fok := asString(args[1]) + to, tok := asString(args[argsTwo]) + + if !sok || !fok || !tok { + return sqlNull(), nil + } + + toRunes := []rune(to) + mapping := map[rune]int{} + + for i, r := range []rune(from) { + if _, dup := mapping[r]; !dup { + mapping[r] = i + } + } + + var b strings.Builder + + for _, r := range s { + i, found := mapping[r] + + switch { + case !found: + b.WriteRune(r) + case i < len(toRunes): + b.WriteRune(toRunes[i]) + } + } + + return b.String(), nil +} + +func isURLPlain(c byte) bool { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || + strings.IndexByte(urlSafeMarks, c) >= 0 +} + +func udfURLEncode(_ *fnCtx, args []driver.Value) (driver.Value, error) { + s, ok := asString(args[0]) + if !ok { + return sqlNull(), nil + } + + var b strings.Builder + + for i := range len(s) { + switch c := s[i]; { + case isURLPlain(c): + b.WriteByte(c) + case c == ' ': + b.WriteByte('+') + default: + fmt.Fprintf(&b, "%%%02X", c) + } + } + + return b.String(), nil +} + +func udfURLDecode(_ *fnCtx, args []driver.Value) (driver.Value, error) { + s, ok := asString(args[0]) + if !ok { + return sqlNull(), nil + } + + out, err := url.QueryUnescape(s) + if err != nil { + return nil, errArg("url_decode: %s", err) + } + + return out, nil +} + +func registerTrinoStringFuncs() { + registerScalar("ends_with", argsTwo, udfEndsWith) + registerScalar("translate", argsThree, udfTranslate) + registerScalar("url_encode", 1, udfURLEncode) + registerNondeterministic("url_decode", 1, udfURLDecode) +} diff --git a/services/athena/engine_trino_funcs_sdk_test.go b/services/athena/engine_trino_funcs_sdk_test.go new file mode 100644 index 0000000000..2138d6b848 --- /dev/null +++ b/services/athena/engine_trino_funcs_sdk_test.go @@ -0,0 +1,330 @@ +package athena_test + +import ( + "testing" + + athenasdk "github.com/aws/aws-sdk-go-v2/service/athena" + "github.com/stretchr/testify/assert" + + "github.com/blackbirdworks/gopherstack/services/athena" +) + +const seriesData = `{"g":"a","x":1,"y":3} +{"g":"a","x":2,"y":5} +{"g":"a","x":3,"y":7} +{"g":"b","x":4,"y":9} +{"g":"b","x":12,"y":25} +` + +func seriesClient(t *testing.T) *athenasdk.Client { + t.Helper() + + return sdkClientFor(t, map[string][]byte{"lake/series/a.json": []byte(seriesData)}, + map[string]*athena.GlueTableDef{"shop/series": { + Name: "series", Location: "s3://lake/series/", SerdeLibrary: serdeJSON, + Columns: []athena.Column{ + {Name: "g", Type: "string"}, {Name: "x", Type: "int"}, {Name: "y", Type: "int"}, + }, + }}) +} + +func TestSDK_TrinoCollectionFunctions(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + sql string + typ string + want string + }{ + {"sequence up", "SELECT sequence(1, 5)", "array", "[1, 2, 3, 4, 5]"}, + {"sequence down", "SELECT sequence(5, 1)", "array", "[5, 4, 3, 2, 1]"}, + {"sequence step", "SELECT sequence(1, 10, 3)", "array", "[1, 4, 7, 10]"}, + {"sequence negative step", "SELECT sequence(10, 1, -4)", "array", "[10, 6, 2]"}, + {"sequence single", "SELECT sequence(3, 3)", "array", "[3]"}, + {"sequence null", "SELECT sequence(1, NULL)", "varchar", ""}, + { + "sequence dates", "SELECT sequence(DATE '2024-01-01', DATE '2024-01-03')", "array", + "[2024-01-01, 2024-01-02, 2024-01-03]", + }, + { + "sequence month steps", + "SELECT sequence(DATE '2024-01-31', DATE '2024-04-30', INTERVAL '1' MONTH)", + "array", + "[2024-01-31, 2024-02-29, 2024-03-31, 2024-04-30]", + }, + { + "sequence day interval", "SELECT sequence(DATE '2024-01-01', DATE '2024-01-07', INTERVAL '3' DAY)", "array", + "[2024-01-01, 2024-01-04, 2024-01-07]", + }, + { + "sequence timestamps", + "SELECT sequence(TIMESTAMP '2024-01-01 00:00:00', TIMESTAMP '2024-01-01 02:00:00', INTERVAL '1' HOUR)", + "array", "[2024-01-01 00:00:00.000, 2024-01-01 01:00:00.000, 2024-01-01 02:00:00.000]", + }, + {"repeat text", "SELECT repeat('a', 3)", "array", "[a, a, a]"}, + {"repeat zero", "SELECT repeat(1, 0)", "array", "[]"}, + {"repeat array", "SELECT repeat(ARRAY[1], 2)", "array", "[[1], [1]]"}, + {"repeat null count", "SELECT repeat(1, NULL)", "varchar", ""}, + {"zip pads", "SELECT zip(ARRAY[1, 2], ARRAY['a', 'b', 'c'])", "array", "[[1, a], [2, b], [null, c]]"}, + {"zip three", "SELECT zip(ARRAY[1], ARRAY[2], ARRAY[3])", "array", "[[1, 2, 3]]"}, + {"array_union", "SELECT array_union(ARRAY[1, 2, 3], ARRAY[3, 4, 4])", "array", "[1, 2, 3, 4]"}, + {"array_union dedupes", "SELECT array_union(ARRAY[1, 1], ARRAY[2, 2])", "array", "[1, 2]"}, + {"array_intersect", "SELECT array_intersect(ARRAY[1, 2, 2, 3], ARRAY[2, 3, 4])", "array", "[2, 3]"}, + {"array_except", "SELECT array_except(ARRAY[1, 2, 3, 3], ARRAY[2])", "array", "[1, 3]"}, + {"array_except text", "SELECT array_except(ARRAY['a', 'b'], ARRAY['b'])", "array", "[a]"}, + {"arrays_overlap true", "SELECT arrays_overlap(ARRAY[1, 2], ARRAY[2, 3])", "boolean", "true"}, + {"arrays_overlap false", "SELECT arrays_overlap(ARRAY[1], ARRAY[2])", "boolean", "false"}, + {"arrays_overlap null element", "SELECT arrays_overlap(ARRAY[1, NULL], ARRAY[2])", "boolean", ""}, + {"shuffle keeps elements", "SELECT array_sort(shuffle(ARRAY[3, 1, 2, 4]))", "array", "[1, 2, 3, 4]"}, + {"shuffle cardinality", "SELECT cardinality(shuffle(ARRAY[1, 2, 3]))", "bigint", "3"}, + {"array_first", "SELECT array_first(ARRAY[7, 8])", "bigint", "7"}, + {"array_last", "SELECT array_last(ARRAY[7, 8])", "bigint", "8"}, + {"flatten", "SELECT flatten(ARRAY[ARRAY[1, 2], ARRAY[3]])", "array", "[1, 2, 3]"}, + {"trim_array", "SELECT trim_array(ARRAY[1, 2, 3, 4], 2)", "array", "[1, 2]"}, + {"contains_sequence", "SELECT contains_sequence(ARRAY[1, 2, 3, 4], ARRAY[2, 3])", "boolean", "true"}, + {"contains_sequence gap", "SELECT contains_sequence(ARRAY[1, 2, 3, 4], ARRAY[2, 4])", "boolean", "false"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + got := sdkRun(t, docsClient(t), tc.sql) + assert.Equal(t, [][]string{{tc.want}}, got.rows) + assert.Equal(t, []string{tc.typ}, got.types) + }) + } +} + +func TestSDK_TrinoNumericFunctions(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + sql string + typ string + want string + }{ + {"from_base hex", "SELECT from_base('ff', 16)", "bigint", "255"}, + {"from_base upper", "SELECT from_base('FF', 16)", "bigint", "255"}, + {"from_base binary", "SELECT from_base('1011', 2)", "bigint", "11"}, + {"from_base negative", "SELECT from_base('-z', 36)", "bigint", "-35"}, + {"to_base hex", "SELECT to_base(255, 16)", "varchar", "ff"}, + {"to_base binary", "SELECT to_base(5, 2)", "varchar", "101"}, + {"to_base negative", "SELECT to_base(-255, 16)", "varchar", "-ff"}, + {"to_base null", "SELECT to_base(NULL, 2)", "varchar", ""}, + {"bit_count", "SELECT bit_count(9, 64)", "bigint", "2"}, + {"bit_count negative", "SELECT bit_count(-7, 64)", "bigint", "62"}, + {"bit_count narrow", "SELECT bit_count(-7, 8)", "bigint", "6"}, + {"bitwise_not", "SELECT bitwise_not(0)", "bigint", "-1"}, + {"bitwise_not value", "SELECT bitwise_not(5)", "bigint", "-6"}, + {"bitwise_left_shift", "SELECT bitwise_left_shift(1, 4)", "bigint", "16"}, + {"bitwise_right_shift", "SELECT bitwise_right_shift(16, 2)", "bigint", "4"}, + {"bitwise_right_shift negative", "SELECT bitwise_right_shift(-1, 63)", "bigint", "1"}, + {"bitwise_right_shift_arithmetic", "SELECT bitwise_right_shift_arithmetic(-16, 2)", "bigint", "-4"}, + {"hamming_distance", "SELECT hamming_distance('karolin', 'kathrin')", "bigint", "3"}, + {"hamming_distance equal", "SELECT hamming_distance('abc', 'abc')", "bigint", "0"}, + {"infinity", "SELECT infinity()", "double", "Infinity"}, + {"negative infinity", "SELECT -infinity()", "double", "-Infinity"}, + {"e", "SELECT e()", "double", "2.718281828459045"}, + {"is_infinite", "SELECT is_infinite(infinity())", "boolean", "true"}, + {"is_infinite finite", "SELECT is_infinite(1.5)", "boolean", "false"}, + {"is_nan of nan", "SELECT is_nan(nan())", "boolean", "true"}, + {"year_of_week", "SELECT year_of_week(DATE '2021-01-03')", "bigint", "2020"}, + {"yow", "SELECT yow(DATE '2024-12-30')", "bigint", "2025"}, + {"yow timestamp", "SELECT yow(TIMESTAMP '2024-12-30 10:00:00')", "bigint", "2025"}, + {"width_bucket", "SELECT width_bucket(5.5, 0, 10, 4)", "bigint", "3"}, + {"width_bucket below", "SELECT width_bucket(-1, 0, 10, 4)", "bigint", "0"}, + {"width_bucket above", "SELECT width_bucket(10, 0, 10, 4)", "bigint", "5"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + got := sdkRun(t, docsClient(t), tc.sql) + assert.Equal(t, [][]string{{tc.want}}, got.rows) + assert.Equal(t, []string{tc.typ}, got.types) + }) + } +} + +func TestSDK_TrinoStringFunctions(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + sql string + typ string + want string + }{ + {"ends_with", "SELECT ends_with('hello', 'llo')", "boolean", "true"}, + {"ends_with false", "SELECT ends_with('hello', 'he')", "boolean", "false"}, + {"translate", "SELECT translate('abcd', 'ac', 'xy')", "varchar", "xbyd"}, + {"translate delete", "SELECT translate('abcd', 'abc', 'x')", "varchar", "xd"}, + {"url_encode", "SELECT url_encode('a b&c')", "varchar", "a+b%26c"}, + {"url_decode", "SELECT url_decode('a+b%26c')", "varchar", "a b&c"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + got := sdkRun(t, docsClient(t), tc.sql) + assert.Equal(t, [][]string{{tc.want}}, got.rows) + assert.Equal(t, []string{tc.typ}, got.types) + }) + } +} + +func TestSDK_TrinoStatisticalAggregates(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + sql string + typ string + want [][]string + }{ + {"bitwise_and_agg", "SELECT bitwise_and_agg(x) FROM series", "bigint", [][]string{{"0"}}}, + {"bitwise_or_agg", "SELECT bitwise_or_agg(x) FROM series", "bigint", [][]string{{"15"}}}, + {"bitwise_xor_agg", "SELECT bitwise_xor_agg(x) FROM series", "bigint", [][]string{{"8"}}}, + { + "bitwise group", + "SELECT bitwise_or_agg(x) FROM series GROUP BY g ORDER BY g", + "bigint", + [][]string{{"3"}, {"12"}}, + }, + { + "bitwise filter", "SELECT bitwise_and_agg(x) FILTER (WHERE g = 'b') FROM series", "bigint", + [][]string{{"4"}}, + }, + {"bitwise distinct", "SELECT bitwise_xor_agg(DISTINCT x) FROM series", "bigint", [][]string{{"8"}}}, + {"bitwise empty", "SELECT bitwise_or_agg(x) FROM series WHERE g = 'z'", "varchar", [][]string{{""}}}, + {"regr_slope", "SELECT round(regr_slope(y, x), 6) FROM series WHERE g = 'a'", "double", [][]string{{"2.0"}}}, + { + "regr_intercept", + "SELECT round(regr_intercept(y, x), 6) FROM series WHERE g = 'a'", + "double", + [][]string{{"1.0"}}, + }, + { + "regr group", "SELECT round(regr_slope(y, x), 6) FROM series GROUP BY g ORDER BY g", "double", + [][]string{{"2.0"}, {"2.0"}}, + }, + {"regr no variance", "SELECT regr_slope(y, x) FROM series WHERE x = 1", "varchar", [][]string{{""}}}, + {"skewness", "SELECT round(skewness(x), 6) FROM series", "double", [][]string{{"1.882335"}}}, + {"skewness too few", "SELECT skewness(x) FROM series WHERE g = 'b'", "varchar", [][]string{{""}}}, + {"kurtosis", "SELECT round(kurtosis(x), 6) FROM series", "double", [][]string{{"3.768423"}}}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + got := sdkRun(t, seriesClient(t), tc.sql) + assert.Equal(t, tc.want, got.rows) + assert.Equal(t, []string{tc.typ}, got.types) + }) + } +} + +func TestSDK_TrinoFunctionErrors(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + sql string + reason string + }{ + {"sequence zero step", "SELECT sequence(1, 5, 0)", "step must not be zero"}, + { + "sequence wrong direction", "SELECT sequence(1, 5, -1)", + "sequence stop value should be greater than or equal to start value if step is greater than zero " + + "otherwise stop should be less than or equal to start", + }, + { + "sequence too long", "SELECT sequence(1, 10001)", + "result of sequence function must not have more than 10000 entries", + }, + { + "sequence date hour step", "SELECT sequence(DATE '2024-01-01', DATE '2024-01-03', INTERVAL '1' HOUR)", + "sequence step must be a day interval if start and end values are dates", + }, + { + "repeat negative", + "SELECT repeat(1, -1)", + "count argument of repeat function must be greater than or equal to 0", + }, + { + "repeat too many", "SELECT repeat(1, 10001)", + "count argument of repeat function must be less than or equal to 10000", + }, + {"from_base invalid", "SELECT from_base('zz', 16)", "Not a valid base-16 number: zz"}, + {"from_base radix", "SELECT from_base('1', 37)", "Radix must be between 2 and 36"}, + {"to_base radix", "SELECT to_base(1, 1)", "Radix must be between 2 and 36"}, + {"bit_count bits", "SELECT bit_count(1, 1)", "Bits specified in bit_count must be between 2 and 64, got 1"}, + { + "bit_count range", "SELECT bit_count(7, 3)", + "Number must be representable with the bits specified. 7 can not be represented with 3 bits", + }, + { + "hamming length", "SELECT hamming_distance('a', 'bb')", + "The input strings to hamming_distance function must have the same length", + }, + {"zip arity", "SELECT zip(ARRAY[1])", "Unexpected parameters for function zip"}, + {"trim_array too large", "SELECT trim_array(ARRAY[1], 2)", "size must not exceed array length"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + reason := sdkFailure(t, docsClient(t), tc.sql) + assert.Contains(t, reason, tc.reason) + }) + } +} + +func TestSDK_TimestreamOnlyFunctionsAreNotRegistered(t *testing.T) { + t.Parallel() + + fns := []string{ + "strrpos('a', 'a')", + "from_milliseconds(1)", + "from_nanoseconds(1)", + "to_nanoseconds(1)", + "nanosecond(1)", + } + + for _, fn := range fns { + t.Run(fn, func(t *testing.T) { + t.Parallel() + + assert.Contains(t, sdkFailure(t, docsClient(t), "SELECT "+fn), "not registered") + }) + } +} + +func TestSDK_TrinoNaN(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + sql string + want string + }{ + {"nan renders", "SELECT nan()", "NaN"}, + {"is_finite nan", "SELECT is_finite(nan())", "false"}, + {"is_infinite nan", "SELECT is_infinite(nan())", "false"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, [][]string{{tc.want}}, sdkRun(t, docsClient(t), tc.sql).rows) + }) + } +} diff --git a/test/crossengine/function_namespace_test.go b/test/crossengine/function_namespace_test.go index 4e9546caa8..b855489396 100644 --- a/test/crossengine/function_namespace_test.go +++ b/test/crossengine/function_namespace_test.go @@ -128,6 +128,39 @@ func TestEnginesKeepTheirOwnFunctionSemantics(t *testing.T) { {"athena round", "round(2.5)", "athena", "3"}, {"athena strpos", "strpos('abc', 'c')", "athena", "3"}, {"athena concat", "concat('a', 'b')", "athena", "ab"}, + {"athena sequence", "cardinality(sequence(1, 5))", "athena", "5"}, + {"athena repeat", "cardinality(repeat('a', 3))", "athena", "3"}, + {"athena zip", "cardinality(zip(ARRAY[1, 2], ARRAY[3, 4]))", "athena", "2"}, + {"athena array_union", "cardinality(array_union(ARRAY[1, 2], ARRAY[2, 3]))", "athena", "3"}, + {"athena array_intersect", "cardinality(array_intersect(ARRAY[1, 2], ARRAY[2, 3]))", "athena", "1"}, + {"athena array_except", "cardinality(array_except(ARRAY[1, 2], ARRAY[2, 3]))", "athena", "1"}, + {"athena arrays_overlap", "arrays_overlap(ARRAY[1, 2], ARRAY[2, 3])", "athena", "1"}, + {"athena shuffle", "cardinality(shuffle(ARRAY[1, 2, 3]))", "athena", "3"}, + {"athena from_base", "from_base('ff', 16)", "athena", "255"}, + {"athena to_base", "to_base(255, 16)", "athena", "ff"}, + {"athena bit_count", "bit_count(9, 64)", "athena", "2"}, + {"athena bitwise_not", "bitwise_not(5)", "athena", "-6"}, + {"athena hamming_distance", "hamming_distance('karolin', 'kathrin')", "athena", "3"}, + {"athena infinity", "infinity()", "athena", "+Inf"}, + {"athena nan", "nan()", "athena", "NaN"}, + {"athena e", "e()", "athena", "2.718281828459045"}, + {"athena year_of_week", "year_of_week(DATE '2021-01-03')", "athena", "2020"}, + {"athena yow", "yow(DATE '2024-12-30')", "athena", "2025"}, + {"athena bitwise_and_agg", "bitwise_and_agg(x) FROM (SELECT 7 AS x UNION ALL SELECT 3)", "athena", "3"}, + {"athena bitwise_or_agg", "bitwise_or_agg(x) FROM (SELECT 4 AS x UNION ALL SELECT 3)", "athena", "7"}, + { + "athena skewness", + "round(skewness(x), 4) FROM (SELECT 1 AS x UNION ALL SELECT 2 UNION ALL SELECT 9)", + "athena", + "1.6301", + }, + {"athena regr_slope", "regr_slope(y, x) FROM (SELECT 1 AS x, 3 AS y UNION ALL SELECT 2, 5)", "athena", "2"}, + { + "athena regr_intercept", + "regr_intercept(y, x) FROM (SELECT 1 AS x, 3 AS y UNION ALL SELECT 2, 5)", + "athena", + "1", + }, {"timestream replace", "replace('abc', 'b', 'X')", "ts", "aXc"}, {"timestream reverse", "reverse('abc')", "ts", "cba"}, {"timestream repeat", "cardinality(repeat('a', 3))", "ts", "3"}, From 012728ea1386ad2fbf97acdf41534e61d9f0e217 Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 22:48:42 -0600 Subject: [PATCH 5/8] fix(servicequotas): enforce the documented EC2 limit codes, read the KMS grant limit in the key's Region, pin the refresh delay in the Auto Scaling test EC2 documents limit codes for subnets, internet gateways, security groups and their rules, route tables and vCPUs, so those quotas are enforced under the flag as well as counted. CreateGrant looked up its limit in the request's Region. The instance refresh test raced a fixed 100ms transition. The quota classification data is corrected where a name pattern misfiled entries. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- internal/app/service_quotas_guard_test.go | 8 +- .../service_quotas_limits_ec2_more_test.go | 253 ++++++++++++++ .../app/service_quotas_limits_ec2_test.go | 20 +- .../app/service_quotas_limits_prior_test.go | 124 +++++++ .../app/testdata/service_quota_classes.json | 316 +++++++++--------- services/autoscaling/instance_refreshes.go | 15 +- ...ifecycle_scaling_and_notifications_test.go | 8 +- .../autoscaling/sdk_roundtrip_helper_test.go | 7 +- services/autoscaling/store.go | 3 +- services/ec2/handler.go | 7 + services/ec2/internet_gateways.go | 6 + services/ec2/quota_vpc.go | 89 +++++ services/ec2/route_tables.go | 6 + services/ec2/security_groups.go | 18 + services/ec2/spot_instances.go | 7 + services/ec2/store.go | 43 ++- services/ec2/subnet_options.go | 6 + services/kms/grant_quota_region_test.go | 61 ++++ services/kms/grants.go | 2 +- services/kms/quota.go | 14 + services/servicequotas/PARITY.md | 8 +- 21 files changed, 830 insertions(+), 191 deletions(-) create mode 100644 internal/app/service_quotas_limits_ec2_more_test.go create mode 100644 internal/app/service_quotas_limits_prior_test.go create mode 100644 services/kms/grant_quota_region_test.go diff --git a/internal/app/service_quotas_guard_test.go b/internal/app/service_quotas_guard_test.go index 82d388a616..fb0fe9231d 100644 --- a/internal/app/service_quotas_guard_test.go +++ b/internal/app/service_quotas_guard_test.go @@ -83,7 +83,8 @@ func TestQuotaClassificationCoversCatalog(t *testing.T) { t, classified, k, - "catalogued quota %s is not classified in testdata/service_quota_classes.json", + "catalogued quota %s is not classified: add it to testdata/service_quota_classes.json as c (and wire a counter in "+ + "service_quota_counters.go), e (count, no counter yet), s (size or length) or r (rate or concurrency)", k, ) } @@ -118,10 +119,11 @@ func TestQuotaCountersMatchClassification(t *testing.T) { } for k := range counted { - assert.True(t, counters[k], "%s is classified as counted but has no counter in quotaCounters", k) + assert.True(t, counters[k], + "%s is classified c but has no counter: add it to serviceQuotaCounters/quotaCounters or reclassify it e", k) } for k := range counters { - assert.True(t, counted[k], "%s has a counter but is not classified as counted", k) + assert.True(t, counted[k], "%s has a counter but is not classified c in testdata/service_quota_classes.json", k) } } diff --git a/internal/app/service_quotas_limits_ec2_more_test.go b/internal/app/service_quotas_limits_ec2_more_test.go new file mode 100644 index 0000000000..57748bc8bc --- /dev/null +++ b/internal/app/service_quotas_limits_ec2_more_test.go @@ -0,0 +1,253 @@ +package app + +import ( + "context" + "errors" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ec2" + ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" +) + +func limVPC(ctx context.Context, c *ec2.Client) (*string, error) { + out, err := c.DescribeVpcs(ctx, &ec2.DescribeVpcsInput{Filters: ec2ByTag()}) + if err != nil || len(out.Vpcs) == 0 { + return nil, errors.Join(err, errNoQuotaTarget) + } + + return out.Vpcs[0].VpcId, nil +} + +func prepareLimVPC(ctx context.Context, e limitEnv) error { + _, err := ec2Client(e).CreateVpc(ctx, &ec2.CreateVpcInput{ + CidrBlock: aws.String("10.88.0.0/16"), TagSpecifications: ec2NameTag(ec2types.ResourceTypeVpc), + }) + + return err +} + +func instanceCase(name, quota string, limit int, spot bool) limitCase { + code := "VcpuLimitExceeded" + if spot { + code = "MaxSpotInstanceCountExceeded" + } + + return limitCase{ + name: name, svc: "ec2", quota: quota, code: code, limit: limit, handler: ec2Handler, + create: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + if spot { + _, err := c.RequestSpotInstances(ctx, &ec2.RequestSpotInstancesInput{ + InstanceCount: aws.Int32(1), + LaunchSpecification: &ec2types.RequestSpotLaunchSpecification{ + ImageId: aws.String("ami-12345678"), InstanceType: ec2types.InstanceTypeT2Micro, + }, + }) + + return err + } + + _, err := c.RunInstances(ctx, &ec2.RunInstancesInput{ + ImageId: aws.String("ami-12345678"), InstanceType: ec2types.InstanceTypeT2Micro, + MinCount: aws.Int32(1), MaxCount: aws.Int32(1), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + if spot { + out, err := c.DescribeSpotInstanceRequests(ctx, &ec2.DescribeSpotInstanceRequestsInput{}) + if err != nil || len(out.SpotInstanceRequests) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.CancelSpotInstanceRequests(ctx, &ec2.CancelSpotInstanceRequestsInput{ + SpotInstanceRequestIds: []string{*out.SpotInstanceRequests[0].SpotInstanceRequestId}, + }) + + return err + } + + out, err := c.DescribeInstances(ctx, &ec2.DescribeInstancesInput{}) + if err != nil || len(out.Reservations) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.TerminateInstances(ctx, &ec2.TerminateInstancesInput{ + InstanceIds: []string{*out.Reservations[0].Instances[0].InstanceId}, + }) + + return err + }, + } +} + +func ec2ConfirmedCodeCases() []limitCase { + return []limitCase{ + { + name: "subnets per vpc", svc: "vpc", quota: "L-407747CB", code: "SubnetLimitExceeded", limit: 2, + handler: ec2Handler, prepare: prepareLimVPC, + create: func(ctx context.Context, e limitEnv, i int) error { + c := ec2Client(e) + + id, err := limVPC(ctx, c) + if err != nil { + return err + } + + _, err = c.CreateSubnet(ctx, &ec2.CreateSubnetInput{ + VpcId: id, CidrBlock: aws.String("10.88." + qnum(i) + ".0/24"), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + id, err := limVPC(ctx, c) + if err != nil { + return err + } + + out, err := c.DescribeSubnets(ctx, &ec2.DescribeSubnetsInput{ + Filters: []ec2types.Filter{{Name: aws.String("vpc-id"), Values: []string{*id}}}, + }) + if err != nil || len(out.Subnets) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.DeleteSubnet(ctx, &ec2.DeleteSubnetInput{SubnetId: out.Subnets[0].SubnetId}) + + return err + }, + }, + { + name: "route tables per vpc", svc: "vpc", quota: "L-589F43AA", code: "RouteTableLimitExceeded", + limit: 3, existing: 1, handler: ec2Handler, prepare: prepareLimVPC, + create: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + id, err := limVPC(ctx, c) + if err != nil { + return err + } + + _, err = c.CreateRouteTable(ctx, &ec2.CreateRouteTableInput{VpcId: id}) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + out, err := c.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{}) + if err != nil { + return err + } + + for _, rt := range out.RouteTables { + if len(rt.Associations) == 0 && rt.VpcId != nil { + if id, _ := limVPC(ctx, c); id != nil && *id == *rt.VpcId { + _, derr := c.DeleteRouteTable(ctx, &ec2.DeleteRouteTableInput{ + RouteTableId: rt.RouteTableId, + }) + + return derr + } + } + } + + return errNoQuotaTarget + }, + }, + { + name: "internet gateways", svc: "vpc", quota: "L-A4707A72", code: "InternetGatewayLimitExceeded", + limit: 3, handler: ec2Handler, + create: func(ctx context.Context, e limitEnv, _ int) error { + _, err := ec2Client(e).CreateInternetGateway(ctx, &ec2.CreateInternetGatewayInput{}) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + out, err := c.DescribeInternetGateways(ctx, &ec2.DescribeInternetGatewaysInput{}) + if err != nil || len(out.InternetGateways) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + for _, g := range out.InternetGateways { + if len(g.Attachments) == 0 { + _, derr := c.DeleteInternetGateway(ctx, &ec2.DeleteInternetGatewayInput{ + InternetGatewayId: g.InternetGatewayId, + }) + + return derr + } + } + + return errNoQuotaTarget + }, + }, + { + name: "security groups", svc: "vpc", quota: "L-E79EC296", code: "SecurityGroupLimitExceeded", + limit: 4, existing: 1, handler: ec2Handler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := ec2Client(e).CreateSecurityGroup(ctx, &ec2.CreateSecurityGroupInput{ + GroupName: aws.String("sg" + qnum(i)), Description: aws.String("d"), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, _ int) error { + _, err := ec2Client(e).DeleteSecurityGroup(ctx, &ec2.DeleteSecurityGroupInput{ + GroupName: aws.String("sg" + qnum(0)), + }) + + return err + }, + }, + { + name: "rules per security group", svc: "vpc", quota: "L-0EA8095F", + code: "RulesPerSecurityGroupLimitExceeded", limit: 3, handler: ec2Handler, + prepare: func(ctx context.Context, e limitEnv) error { + _, err := ec2Client(e).CreateSecurityGroup(ctx, &ec2.CreateSecurityGroupInput{ + GroupName: aws.String("rules"), Description: aws.String("d"), + TagSpecifications: ec2NameTag(ec2types.ResourceTypeSecurityGroup), + }) + + return err + }, + create: func(ctx context.Context, e limitEnv, i int) error { + c := ec2Client(e) + + out, err := c.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{Filters: ec2ByTag()}) + if err != nil || len(out.SecurityGroups) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.AuthorizeSecurityGroupIngress(ctx, &ec2.AuthorizeSecurityGroupIngressInput{ + GroupId: out.SecurityGroups[0].GroupId, + IpPermissions: []ec2types.IpPermission{{ + IpProtocol: aws.String("tcp"), + FromPort: aws.Int32(int32(1000 + i)), ToPort: aws.Int32(int32(1000 + i)), + IpRanges: []ec2types.IpRange{{CidrIp: aws.String("10.0.0.0/8")}}, + }}, + }) + + return err + }, + }, + instanceCase("on-demand standard vcpus", "L-1216C47A", 3, false), + instanceCase("spot standard vcpus", "L-34B43A08", 3, true), + } +} + +func TestQuotaLimitsEC2ConfirmedCodes(t *testing.T) { + t.Parallel() + + runLimitCases(t, ec2ConfirmedCodeCases()) +} diff --git a/internal/app/service_quotas_limits_ec2_test.go b/internal/app/service_quotas_limits_ec2_test.go index 65f1abfedf..d30eebd40d 100644 --- a/internal/app/service_quotas_limits_ec2_test.go +++ b/internal/app/service_quotas_limits_ec2_test.go @@ -30,13 +30,13 @@ func defaultSubnet(ctx context.Context, c *ec2.Client) (*ec2types.Subnet, error) return &out.Subnets[0], nil } -func ec2ByTag(name string) []ec2types.Filter { - return []ec2types.Filter{{Name: aws.String("tag:Name"), Values: []string{name}}} +func ec2ByTag() []ec2types.Filter { + return []ec2types.Filter{{Name: aws.String("tag:Name"), Values: []string{"lim"}}} } -func ec2NameTag(rt ec2types.ResourceType, name string) []ec2types.TagSpecification { +func ec2NameTag(rt ec2types.ResourceType) []ec2types.TagSpecification { return []ec2types.TagSpecification{{ - ResourceType: rt, Tags: []ec2types.Tag{{Key: aws.String("Name"), Value: aws.String(name)}}, + ResourceType: rt, Tags: []ec2types.Tag{{Key: aws.String("Name"), Value: aws.String("lim")}}, }} } @@ -49,20 +49,20 @@ func routeCase() limitCase { c := ec2Client(e) vpc, err := c.CreateVpc(ctx, &ec2.CreateVpcInput{ - CidrBlock: aws.String("10.77.0.0/16"), TagSpecifications: ec2NameTag(ec2types.ResourceTypeVpc, "lim"), + CidrBlock: aws.String("10.77.0.0/16"), TagSpecifications: ec2NameTag(ec2types.ResourceTypeVpc), }) if err != nil { return err } if _, err = c.CreateRouteTable(ctx, &ec2.CreateRouteTableInput{ - VpcId: vpc.Vpc.VpcId, TagSpecifications: ec2NameTag(ec2types.ResourceTypeRouteTable, "lim"), + VpcId: vpc.Vpc.VpcId, TagSpecifications: ec2NameTag(ec2types.ResourceTypeRouteTable), }); err != nil { return err } igw, err := c.CreateInternetGateway(ctx, &ec2.CreateInternetGatewayInput{ - TagSpecifications: ec2NameTag(ec2types.ResourceTypeInternetGateway, "lim"), + TagSpecifications: ec2NameTag(ec2types.ResourceTypeInternetGateway), }) if err != nil { return err @@ -77,12 +77,12 @@ func routeCase() limitCase { create: func(ctx context.Context, e limitEnv, i int) error { c := ec2Client(e) - rt, err := c.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{Filters: ec2ByTag("lim")}) + rt, err := c.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{Filters: ec2ByTag()}) if err != nil || len(rt.RouteTables) == 0 { return errors.Join(err, errNoQuotaTarget) } - igw, err := c.DescribeInternetGateways(ctx, &ec2.DescribeInternetGatewaysInput{Filters: ec2ByTag("lim")}) + igw, err := c.DescribeInternetGateways(ctx, &ec2.DescribeInternetGatewaysInput{Filters: ec2ByTag()}) if err != nil || len(igw.InternetGateways) == 0 { return errors.Join(err, errNoQuotaTarget) } @@ -98,7 +98,7 @@ func routeCase() limitCase { remove: func(ctx context.Context, e limitEnv, _ int) error { c := ec2Client(e) - rt, err := c.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{Filters: ec2ByTag("lim")}) + rt, err := c.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{Filters: ec2ByTag()}) if err != nil || len(rt.RouteTables) == 0 { return errors.Join(err, errNoQuotaTarget) } diff --git a/internal/app/service_quotas_limits_prior_test.go b/internal/app/service_quotas_limits_prior_test.go new file mode 100644 index 0000000000..e27eaf50bf --- /dev/null +++ b/internal/app/service_quotas_limits_prior_test.go @@ -0,0 +1,124 @@ +package app + +import ( + "context" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/eks" + ekstypes "github.com/aws/aws-sdk-go-v2/service/eks/types" + "github.com/aws/aws-sdk-go-v2/service/iam" + + "github.com/blackbirdworks/gopherstack/pkgs/service" + eksbackend "github.com/blackbirdworks/gopherstack/services/eks" + iambackend "github.com/blackbirdworks/gopherstack/services/iam" +) + +const limitTestTrust = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow",` + + `"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}` + +const limitTestPolicyDoc = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:*","Resource":"*"}]}` + +// priorLimitCases covers the quotas enforced before the generic SetQuotaLimiter wiring, so a refactor of +// enforceServiceQuotas that drops one fails here. +func priorLimitCases() []limitCase { + iamHandler := func(*testing.T) service.Registerable { + return iambackend.NewHandler(iambackend.NewInMemoryBackendWithConfig(quotaTestAccount)) + } + iamClient := func(e limitEnv) *iam.Client { + return iam.NewFromConfig(e.cfg, func(o *iam.Options) { o.BaseEndpoint = e.endpoint() }) + } + + return []limitCase{ + { + name: "iam roles", svc: "iam", quota: "L-F4A5425F", code: "LimitExceeded", limit: 2, + handler: iamHandler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := iamClient(e).CreateRole(ctx, &iam.CreateRoleInput{ + RoleName: aws.String(name("r", i)), AssumeRolePolicyDocument: aws.String(limitTestTrust), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := iamClient(e).DeleteRole(ctx, &iam.DeleteRoleInput{RoleName: aws.String(name("r", i))}) + + return err + }, + }, + { + name: "iam users", svc: "iam", quota: "L-F55AF5E4", code: "LimitExceeded", limit: 2, + handler: iamHandler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := iamClient(e).CreateUser(ctx, &iam.CreateUserInput{UserName: aws.String(name("u", i))}) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := iamClient(e).DeleteUser(ctx, &iam.DeleteUserInput{UserName: aws.String(name("u", i))}) + + return err + }, + }, + { + name: "iam customer managed policies", svc: "iam", quota: "L-0DA4ABF3", code: "LimitExceeded", limit: 2, + handler: iamHandler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := iamClient(e).CreatePolicy(ctx, &iam.CreatePolicyInput{ + PolicyName: aws.String(name("p", i)), PolicyDocument: aws.String(limitTestPolicyDoc), + }) + + return err + }, + }, + { + name: "iam instance profiles", svc: "iam", quota: "L-E95E4862", code: "LimitExceeded", limit: 2, + handler: iamHandler, + create: func(ctx context.Context, e limitEnv, i int) error { + _, err := iamClient(e).CreateInstanceProfile(ctx, &iam.CreateInstanceProfileInput{ + InstanceProfileName: aws.String(name("ip", i)), + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + _, err := iamClient(e).DeleteInstanceProfile(ctx, &iam.DeleteInstanceProfileInput{ + InstanceProfileName: aws.String(name("ip", i)), + }) + + return err + }, + }, + { + name: "eks clusters", svc: "eks", quota: "L-1194D53C", code: "ResourceLimitExceededException", limit: 2, + handler: func(t *testing.T) service.Registerable { + t.Helper() + + bk := eksbackend.NewInMemoryBackend(t.Context(), quotaTestAccount, quotaTestRegion) + + return eksbackend.NewHandler(bk) + }, + create: func(ctx context.Context, e limitEnv, i int) error { + c := eks.NewFromConfig(e.cfg, func(o *eks.Options) { o.BaseEndpoint = e.endpoint() }) + _, err := c.CreateCluster(ctx, &eks.CreateClusterInput{ + Name: aws.String(name("c", i)), RoleArn: aws.String(limitTestRole), + ResourcesVpcConfig: &ekstypes.VpcConfigRequest{}, + }) + + return err + }, + remove: func(ctx context.Context, e limitEnv, i int) error { + c := eks.NewFromConfig(e.cfg, func(o *eks.Options) { o.BaseEndpoint = e.endpoint() }) + _, err := c.DeleteCluster(ctx, &eks.DeleteClusterInput{Name: aws.String(name("c", i))}) + + return err + }, + }, + } +} + +func TestQuotaLimitsPreviouslyEnforcedServices(t *testing.T) { + t.Parallel() + + runLimitCases(t, priorLimitCases()) +} diff --git a/internal/app/testdata/service_quota_classes.json b/internal/app/testdata/service_quota_classes.json index caab9a60b2..4a1a102781 100644 --- a/internal/app/testdata/service_quota_classes.json +++ b/internal/app/testdata/service_quota_classes.json @@ -259,7 +259,7 @@ "quotas": { "L-00F9DD5C": "s", "L-00FF3314": "r", - "L-01A2DC4B": "e", + "L-01A2DC4B": "s", "L-01F37E14": "e", "L-01F3CD81": "r", "L-02D6293C": "s", @@ -268,7 +268,7 @@ "L-039AF68B": "r", "L-059C1AAB": "e", "L-06B03968": "r", - "L-072E11FC": "e", + "L-072E11FC": "s", "L-07844084": "e", "L-07D3BCF0": "e", "L-07D73971": "r", @@ -280,7 +280,7 @@ "L-0B2687F4": "r", "L-0B66D421": "e", "L-0CB120A9": "r", - "L-0D1F6A84": "e", + "L-0D1F6A84": "s", "L-0D70E8DA": "e", "L-0E7AA8B7": "r", "L-0ED8E85F": "e", @@ -290,46 +290,46 @@ "L-102A1657": "r", "L-1074C53D": "e", "L-10F69CA1": "e", - "L-114ABFC3": "e", - "L-11C1CE94": "e", + "L-114ABFC3": "s", + "L-11C1CE94": "s", "L-11DFF789": "r", - "L-121F4E1E": "e", + "L-121F4E1E": "s", "L-124DCF3D": "r", - "L-127FC9D0": "s", + "L-127FC9D0": "e", "L-12E68701": "e", "L-13143995": "e", - "L-131D4EED": "e", - "L-135AE4B7": "e", + "L-131D4EED": "s", + "L-135AE4B7": "s", "L-137DD3C2": "r", - "L-1401504A": "e", - "L-142AED8F": "e", + "L-1401504A": "s", + "L-142AED8F": "s", "L-14A16430": "e", "L-1570CF9E": "e", "L-1579B4CD": "r", "L-15830237": "r", - "L-15B51EC1": "e", + "L-15B51EC1": "s", "L-15B8E632": "r", "L-15CD18AC": "r", "L-16711FC4": "e", "L-1679CB40": "e", "L-16941C66": "e", - "L-169A395B": "e", - "L-16E25672": "e", + "L-169A395B": "s", + "L-16E25672": "s", "L-1870BD3C": "e", - "L-196A63C0": "e", + "L-196A63C0": "s", "L-1AC1CABC": "e", - "L-1AD2F2A2": "e", + "L-1AD2F2A2": "s", "L-1BD3E8A2": "r", "L-1C19AAE8": "e", - "L-1D2360E7": "e", - "L-1E2B9998": "e", + "L-1D2360E7": "s", + "L-1E2B9998": "s", "L-1EF80F3E": "e", - "L-1F644C2A": "e", + "L-1F644C2A": "s", "L-1F7657F1": "e", - "L-1F7ACACC": "e", - "L-1F923A43": "e", + "L-1F7ACACC": "s", + "L-1F923A43": "s", "L-208A3F5C": "e", - "L-214BEB81": "e", + "L-214BEB81": "s", "L-21800074": "r", "L-21EE8B55": "e", "L-220B8A25": "e", @@ -341,13 +341,13 @@ "L-2590C31B": "e", "L-259C746F": "e", "L-268D592E": "e", - "L-273728E2": "e", - "L-274AA31F": "e", - "L-2767B9A9": "e", + "L-273728E2": "s", + "L-274AA31F": "s", + "L-2767B9A9": "s", "L-27989F42": "r", "L-27C57EE8": "r", - "L-28258E5D": "e", - "L-28612175": "e", + "L-28258E5D": "s", + "L-28612175": "s", "L-29BDACF9": "e", "L-2A53927F": "r", "L-2AD735F5": "r", @@ -359,26 +359,26 @@ "L-315A9D5B": "r", "L-31615887": "r", "L-31AB82D0": "r", - "L-320BE465": "e", + "L-320BE465": "s", "L-32F732DE": "e", "L-34152C1D": "r", "L-345B029F": "r", "L-34C933D1": "e", - "L-35900968": "e", + "L-35900968": "s", "L-3632DE15": "e", "L-37491D63": "r", - "L-37A44E24": "e", + "L-37A44E24": "s", "L-38EB0A61": "r", - "L-38EFD889": "e", + "L-38EFD889": "s", "L-391478D2": "e", - "L-391CEF89": "e", + "L-391CEF89": "s", "L-392F9C48": "s", "L-3ABF6ACC": "r", "L-3B60C1ED": "s", "L-3B82104D": "e", - "L-3BD2251E": "e", + "L-3BD2251E": "s", "L-3BE61D60": "e", - "L-3C5D1B25": "e", + "L-3C5D1B25": "s", "L-3CCB3548": "e", "L-3CD2AF6F": "r", "L-3DCCFAA4": "r", @@ -392,57 +392,57 @@ "L-437802FD": "s", "L-43CD2FD9": "e", "L-442924EC": "r", - "L-4532261E": "s", + "L-4532261E": "e", "L-45B04988": "e", - "L-46EFABBA": "e", + "L-46EFABBA": "s", "L-47520EB7": "r", - "L-478319B0": "e", + "L-478319B0": "s", "L-479B647F": "r", - "L-4821684D": "e", + "L-4821684D": "s", "L-48C95F85": "e", - "L-48DD3868": "e", + "L-48DD3868": "s", "L-495BEDE3": "r", "L-4A0EAD70": "r", "L-4A544964": "r", "L-4A6BFAB1": "r", "L-4A6D2F15": "e", - "L-4A832410": "e", + "L-4A832410": "s", "L-4B26E44A": "r", "L-4B3B250B": "r", "L-4B4330A0": "e", "L-4B9F76B0": "r", "L-4BF37C17": "r", "L-4C3F0FE6": "r", - "L-4D2272DC": "e", + "L-4D2272DC": "s", "L-4D7537CF": "r", "L-4DBDD5C9": "r", - "L-4DFF050E": "e", + "L-4DFF050E": "s", "L-4E7DDF49": "e", "L-4E7EE0B5": "e", "L-4FCE27C7": "r", "L-5056051A": "e", "L-50CC5674": "r", "L-50CC95A8": "e", - "L-51B0DEE7": "e", + "L-51B0DEE7": "s", "L-51CDA0E1": "r", "L-51FF35D5": "r", "L-526E1ECE": "r", - "L-5325EC5D": "e", + "L-5325EC5D": "s", "L-532E6630": "r", "L-53A144CD": "r", "L-53B814D7": "e", "L-54814DC6": "r", "L-54FAADA6": "r", - "L-55F225F6": "e", + "L-55F225F6": "s", "L-564C017C": "e", "L-574688BD": "r", "L-5755FAB6": "r", - "L-57DC56A1": "e", + "L-57DC56A1": "s", "L-58424D95": "r", "L-58BE175A": "r", "L-5A222661": "e", - "L-5A51050A": "e", - "L-5AB0EE48": "e", + "L-5A51050A": "s", + "L-5AB0EE48": "s", "L-5BA88337": "e", "L-5D367E5C": "e", "L-5DAAE567": "e", @@ -451,22 +451,22 @@ "L-5DD391B1": "r", "L-5DF13F64": "r", "L-5E29F315": "e", - "L-5E3E0013": "e", + "L-5E3E0013": "s", "L-5E8692C5": "r", "L-612AE448": "r", "L-62E2A345": "e", - "L-63010E1B": "e", + "L-63010E1B": "s", "L-63020993": "e", "L-6326A422": "r", "L-63EC9D04": "e", "L-6473F1D2": "r", - "L-64CF3679": "e", + "L-64CF3679": "s", "L-654787A4": "e", - "L-65D1D550": "e", + "L-65D1D550": "s", "L-67BD0D49": "e", "L-68AE6C02": "e", "L-697D688A": "e", - "L-69AC41C2": "e", + "L-69AC41C2": "s", "L-6B2DA87E": "e", "L-6B3D3DE4": "r", "L-6B796A8E": "r", @@ -474,8 +474,8 @@ "L-6D88F00E": "e", "L-6E046197": "r", "L-6E888CC2": "r", - "L-6EBFEB27": "e", - "L-6FAB43BE": "e", + "L-6EBFEB27": "s", + "L-6FAB43BE": "s", "L-7007E9C9": "r", "L-7089DC7D": "r", "L-70AC14D9": "r", @@ -485,101 +485,101 @@ "L-71C69B70": "r", "L-7334E629": "r", "L-73573F44": "e", - "L-73951D97": "e", + "L-73951D97": "s", "L-73BBA086": "e", "L-7478F443": "e", "L-749C38BD": "r", "L-75A18A04": "e", "L-78B4AF01": "e", - "L-78C12D54": "e", + "L-78C12D54": "s", "L-79BA683B": "e", "L-7A8639EE": "e", "L-7ABD27EC": "r", "L-7B9A79C8": "e", - "L-7BE9625C": "e", + "L-7BE9625C": "s", "L-7BEE40FB": "r", - "L-7C1813A6": "e", + "L-7C1813A6": "s", "L-7C42E72A": "r", "L-7C435546": "e", "L-7D9F04A9": "r", - "L-7DCA4380": "e", - "L-7EAC9E78": "e", + "L-7DCA4380": "s", + "L-7EAC9E78": "s", "L-7F2C6F33": "e", "L-8076814C": "e", "L-811E997F": "e", "L-8129BF10": "e", - "L-81E26054": "e", + "L-81E26054": "s", "L-82EE9228": "e", "L-8528F119": "r", - "L-852FB779": "e", + "L-852FB779": "s", "L-8574D065": "e", "L-864449ED": "e", - "L-8651ED26": "e", + "L-8651ED26": "s", "L-87594EB7": "r", - "L-87934C8F": "e", + "L-87934C8F": "s", "L-884C068A": "r", "L-88DE0CAC": "e", "L-89117837": "e", - "L-89197AE6": "e", + "L-89197AE6": "s", "L-895C7A6C": "r", - "L-897F8151": "e", + "L-897F8151": "s", "L-89923E2C": "e", - "L-8A232422": "e", - "L-8A361B65": "e", + "L-8A232422": "s", + "L-8A361B65": "s", "L-8A643E07": "r", "L-8A686BB7": "r", "L-8B289D99": "r", "L-8C5F762B": "r", "L-8CBCC2C0": "r", "L-8CC57EDA": "e", - "L-8CE8B022": "e", - "L-8D07E980": "e", + "L-8CE8B022": "s", + "L-8D07E980": "s", "L-8E752C84": "r", "L-8EA73537": "r", "L-8FD128CF": "r", "L-901932B9": "r", "L-9072D6F0": "r", - "L-90807536": "e", + "L-90807536": "s", "L-90DFE70F": "r", "L-90E3E748": "r", "L-9149A536": "e", "L-91554672": "e", - "L-916C9264": "e", + "L-916C9264": "s", "L-91E3DBE2": "e", "L-921A310E": "e", - "L-92349F9F": "e", + "L-92349F9F": "s", "L-92E68994": "r", - "L-92E7FE32": "e", + "L-92E7FE32": "s", "L-92F8A601": "e", - "L-9335BC45": "e", + "L-9335BC45": "s", "L-9342B636": "e", "L-94A31E46": "r", - "L-95CACD43": "e", + "L-95CACD43": "s", "L-95CB8E2F": "e", - "L-962E1C58": "e", + "L-962E1C58": "s", "L-9782749C": "r", "L-97A8CC77": "e", "L-97D79C54": "e", "L-9807BAA2": "r", - "L-982DE2DB": "e", + "L-982DE2DB": "s", "L-990A2394": "e", "L-9913DEEF": "r", "L-99296DCD": "r", "L-99471E7A": "r", "L-99936FBF": "r", "L-9A11C666": "r", - "L-9AA02BEF": "e", + "L-9AA02BEF": "s", "L-9B17C979": "r", "L-9B258944": "r", - "L-9B651738": "e", + "L-9B651738": "s", "L-9B9B20DB": "r", - "L-9C8C5911": "s", + "L-9C8C5911": "e", "L-9D3DC9B2": "r", "L-9D7C8A75": "r", - "L-9E38DD81": "e", + "L-9E38DD81": "s", "L-9E3C255A": "r", - "L-9EDE6039": "e", - "L-9EF11C18": "e", + "L-9EDE6039": "s", + "L-9EF11C18": "s", "L-9EF56DA1": "r", "L-9F4DB459": "r", "L-A02F87EC": "e", @@ -595,49 +595,49 @@ "L-A63633C5": "e", "L-A88E7250": "s", "L-A94DA744": "e", - "L-A985813D": "e", + "L-A985813D": "s", "L-A986092E": "e", - "L-AA411D03": "e", + "L-AA411D03": "s", "L-AA7FE948": "r", - "L-AAC5F6D6": "e", + "L-AAC5F6D6": "s", "L-AB39D760": "r", - "L-AC096F71": "s", + "L-AC096F71": "e", "L-AC6F8476": "e", "L-ADA98D8D": "e", - "L-AE040A57": "e", - "L-AE136EE5": "e", + "L-AE040A57": "s", + "L-AE136EE5": "s", "L-AF2A00BD": "e", "L-AFD14A53": "r", - "L-AFE8E0CD": "e", + "L-AFE8E0CD": "s", "L-B0F56DCF": "e", "L-B1E11F5B": "e", - "L-B1E4F57A": "e", + "L-B1E4F57A": "s", "L-B3049E9B": "e", "L-B370112A": "e", "L-B38B530A": "r", "L-B3C19043": "e", "L-B46DD052": "e", "L-B49AA29C": "e", - "L-B4B995D8": "e", + "L-B4B995D8": "s", "L-B547321D": "e", "L-B5C023CA": "r", "L-B783C50B": "e", "L-B7BF1255": "r", - "L-B8626674": "e", + "L-B8626674": "s", "L-B90A0AF2": "s", "L-BA72E406": "e", - "L-BAE2EB93": "e", - "L-BB255931": "e", + "L-BAE2EB93": "s", + "L-BB255931": "s", "L-BB313AA3": "e", "L-BC23C04E": "r", "L-BC3096B9": "r", - "L-BC9ED53F": "e", + "L-BC9ED53F": "s", "L-BD9FDA6F": "r", "L-BDD176EF": "r", - "L-BE77399C": "r", + "L-BE77399C": "e", "L-BEE3FA31": "s", - "L-BF9B3702": "e", - "L-BFA0FE84": "e", + "L-BF9B3702": "s", + "L-BFA0FE84": "s", "L-C02E1E99": "e", "L-C0326783": "r", "L-C05EB25B": "e", @@ -645,12 +645,12 @@ "L-C0BA182F": "s", "L-C0CACF50": "e", "L-C0D53EFB": "r", - "L-C19807B8": "e", + "L-C19807B8": "s", "L-C2E494BA": "r", "L-C2FA9AEC": "e", - "L-C39B6D57": "e", + "L-C39B6D57": "s", "L-C4522D0D": "e", - "L-C4659D61": "e", + "L-C4659D61": "s", "L-C540484E": "e", "L-C549AE85": "e", "L-C587712D": "r", @@ -658,40 +658,40 @@ "L-C593EA7C": "r", "L-C6AAFCD0": "e", "L-C6F5908D": "r", - "L-CA80888F": "e", + "L-CA80888F": "s", "L-CABD464E": "r", "L-CB5B847D": "e", "L-CC3FC244": "r", "L-CCA5DF70": "r", "L-CCC92354": "r", - "L-CD4E1CD6": "e", + "L-CD4E1CD6": "s", "L-CDD9DC4A": "e", - "L-CDF99FD2": "e", - "L-CEEE0EE8": "e", + "L-CDF99FD2": "s", + "L-CEEE0EE8": "s", "L-CFCAAB0E": "r", "L-D06938E7": "r", - "L-D1151D45": "e", + "L-D1151D45": "s", "L-D13C968B": "e", "L-D1C9F3B9": "e", - "L-D30E6B4B": "e", + "L-D30E6B4B": "s", "L-D321719B": "e", "L-D3D1200C": "e", "L-D3E17A13": "e", - "L-D41E62E4": "e", + "L-D41E62E4": "s", "L-D44E1D4E": "r", "L-D4FBCF4E": "r", - "L-D56DF585": "e", + "L-D56DF585": "s", "L-D5F39C2F": "r", "L-D67748AD": "r", "L-D682535A": "e", "L-D73B1244": "r", - "L-D8E451A7": "e", + "L-D8E451A7": "s", "L-D94ECE3B": "r", "L-D983F7C0": "r", "L-D9E467C0": "e", "L-DB84CE56": "r", "L-DB99DCDB": "r", - "L-DBFC8DC8": "e", + "L-DBFC8DC8": "s", "L-DC465F65": "e", "L-DC7FF66C": "r", "L-DCADBC78": "r", @@ -700,83 +700,83 @@ "L-DD7903AD": "e", "L-DD84E5CA": "r", "L-DE3FBBF4": "r", - "L-DE84A1A0": "e", + "L-DE84A1A0": "s", "L-DEE3A9C7": "e", "L-DF09248F": "r", - "L-DF5FF3C8": "e", - "L-DFE5A893": "e", - "L-E038D932": "e", - "L-E0B2EE2A": "s", - "L-E1D21B18": "e", - "L-E293C7C7": "e", + "L-DF5FF3C8": "s", + "L-DFE5A893": "s", + "L-E038D932": "s", + "L-E0B2EE2A": "e", + "L-E1D21B18": "s", + "L-E293C7C7": "s", "L-E2ED42E6": "e", "L-E3C70889": "r", - "L-E3C8B9C9": "e", + "L-E3C8B9C9": "s", "L-E453CCF3": "e", "L-E455959C": "e", - "L-E48B7984": "s", + "L-E48B7984": "e", "L-E5084BBA": "r", "L-E5197E26": "r", "L-E5FD5C04": "e", - "L-E6489B37": "e", + "L-E6489B37": "s", "L-E83AC604": "e", "L-E8940935": "r", - "L-E93C745B": "e", + "L-E93C745B": "s", "L-E953E4AB": "e", "L-EA6F6B5F": "e", "L-EA764586": "e", "L-EA873E18": "e", "L-EAD257E4": "r", "L-EAFCD549": "e", - "L-EBB72C32": "e", + "L-EBB72C32": "s", "L-EC6A6ABC": "e", "L-EC77BD96": "e", - "L-ECA45411": "e", - "L-ECCE76C6": "e", - "L-ECD87E6C": "e", + "L-ECA45411": "s", + "L-ECCE76C6": "s", + "L-ECD87E6C": "s", "L-EDC225D2": "r", - "L-EDE20AF1": "e", + "L-EDE20AF1": "s", "L-EEE88DB2": "e", "L-EF415EF6": "e", - "L-EF804815": "e", + "L-EF804815": "s", "L-F02D918A": "e", "L-F0AF140A": "r", "L-F15FCC01": "e", "L-F1613626": "e", "L-F20FBC17": "r", - "L-F2107865": "e", - "L-F225D073": "e", + "L-F2107865": "s", + "L-F225D073": "s", "L-F241D033": "r", "L-F2469446": "e", "L-F26CA8D1": "r", "L-F2DCFA42": "r", - "L-F2E6F90D": "e", + "L-F2E6F90D": "s", "L-F30EAB98": "e", - "L-F361DF0F": "e", + "L-F361DF0F": "s", "L-F424A1E3": "e", "L-F4DDD3EB": "r", "L-F5ACA0A6": "r", "L-F6E116D7": "r", - "L-F7440010": "e", - "L-F77743B5": "e", + "L-F7440010": "s", + "L-F77743B5": "s", "L-F86AE9DD": "r", "L-F879F645": "e", "L-F8B0126D": "s", - "L-FA06C205": "e", - "L-FABEE48F": "e", - "L-FB43CE55": "e", + "L-FA06C205": "s", + "L-FABEE48F": "s", + "L-FB43CE55": "s", "L-FD4A6FF9": "e", - "L-FD509977": "e", - "L-FD7B3EB8": "e", - "L-FDE45816": "e", - "L-FE086D36": "e", + "L-FD509977": "s", + "L-FD7B3EB8": "s", + "L-FDE45816": "s", + "L-FE086D36": "s", "L-FE130012": "e", "L-FE24F76E": "e", - "L-FE44174A": "r", + "L-FE44174A": "e", "L-FF1F238B": "r", - "L-FF73AE42": "e", + "L-FF73AE42": "s", "L-FF8B4E28": "r", - "L-FFFEDD8D": "e" + "L-FFFEDD8D": "s" }, "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" }, @@ -1899,7 +1899,7 @@ "L-4EDE4065": "r", "L-57578687": "e", "L-59D0763F": "e", - "L-5B89F9CE": "s", + "L-5B89F9CE": "e", "L-60836D3E": "e", "L-736F3D6F": "s", "L-7D5FDD38": "s", @@ -1920,7 +1920,7 @@ "L-E24B4DE4": "e", "L-E2C89679": "s", "L-E43BDB2E": "s", - "L-E94C1C19": "s", + "L-E94C1C19": "e", "L-FD6F2F22": "e", "L-FD89CA8A": "r" }, @@ -2002,7 +2002,7 @@ "L-6E65F664": "e", "L-858F3967": "e", "L-BF35879D": "c", - "L-C07B4B0D": "e", + "L-C07B4B0D": "s", "L-E95E4862": "c", "L-F4A5425F": "c", "L-F55AF5E4": "c", @@ -2043,7 +2043,7 @@ "L-32D5DC79": "r", "L-354AF9F0": "r", "L-8F974349": "e", - "L-B71421B8": "s", + "L-B71421B8": "e", "L-B71B4FEE": "r", "L-B7F419CA": "e", "L-BF0D282F": "r", @@ -2385,7 +2385,7 @@ "L-6D17A5A2": "e", "L-9AEE2A70": "e", "L-A425F59F": "e", - "L-B3AC6773": "s", + "L-B3AC6773": "e", "L-BF10548E": "r", "L-D6543DBD": "e" }, @@ -2437,12 +2437,12 @@ "L-AFB19B96": "e", "L-B94B38A2": "s", "L-BE38079A": "r", - "L-BE766427": "s", - "L-BFFBB2FD": "s", + "L-BE766427": "e", + "L-BFFBB2FD": "e", "L-C9679DBC": "e", "L-D91CDC5E": "e", "L-E787EB79": "e", - "L-F34A3FC2": "s", + "L-F34A3FC2": "e", "L-F57A8D18": "r" }, "reason": "count-of-resources quota; the owning backend exposes no read-only count wired into quotaCounters yet" @@ -3641,7 +3641,7 @@ "L-6FCDFC95": "e", "L-6FEE2118": "e", "L-6FEE87BA": "e", - "L-6FF806F0": "s", + "L-6FF806F0": "e", "L-70202030": "e", "L-702CCDF6": "e", "L-7036F14A": "e", @@ -4022,7 +4022,7 @@ "L-9778E614": "e", "L-978CD7EC": "e", "L-97A2C724": "e", - "L-97AC1A59": "s", + "L-97AC1A59": "e", "L-97C33A46": "e", "L-97CDCF2E": "e", "L-97CF11BE": "e", @@ -4095,7 +4095,7 @@ "L-9FA8FC21": "e", "L-9FAC65F7": "e", "L-9FB41A1C": "e", - "L-9FC178C2": "s", + "L-9FC178C2": "e", "L-9FCA2A26": "e", "L-9FE5CC2D": "e", "L-9FEBBCCF": "e", diff --git a/services/autoscaling/instance_refreshes.go b/services/autoscaling/instance_refreshes.go index d85d592fbd..2562ae156a 100644 --- a/services/autoscaling/instance_refreshes.go +++ b/services/autoscaling/instance_refreshes.go @@ -191,7 +191,12 @@ func (b *InMemoryBackend) armRefreshTransition(refreshID, groupName, nextStatus GroupName: groupName, NextStatus: nextStatus, } - action.timer = time.AfterFunc(instanceRefreshTransitionDelay, func() { + delay := instanceRefreshTransitionDelay + if b.refreshDelay > 0 { + delay = b.refreshDelay + } + + action.timer = time.AfterFunc(delay, func() { b.resolveRefreshTransition(refreshID) }) b.pendingRefreshActions.Put(action) @@ -306,3 +311,11 @@ func (b *InMemoryBackend) applyDesiredConfiguration(groupName string, dc *Desire g.LaunchConfigurationName = "" } } + +// SetInstanceRefreshDelay sets the simulated delay before an instance refresh reaches a terminal status. +func (b *InMemoryBackend) SetInstanceRefreshDelay(d time.Duration) { + b.mu.Lock("SetInstanceRefreshDelay") + defer b.mu.Unlock() + + b.refreshDelay = d +} diff --git a/services/autoscaling/realclient_lifecycle_scaling_and_notifications_test.go b/services/autoscaling/realclient_lifecycle_scaling_and_notifications_test.go index 545de8411a..7054cfa235 100644 --- a/services/autoscaling/realclient_lifecycle_scaling_and_notifications_test.go +++ b/services/autoscaling/realclient_lifecycle_scaling_and_notifications_test.go @@ -9,6 +9,8 @@ import ( "github.com/aws/aws-sdk-go-v2/service/autoscaling/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/autoscaling" ) // TestRealClient_LifecycleScalingAndNotifications drives autoscaling's typed-coverage-blind ops @@ -365,7 +367,11 @@ func TestRealClient_LifecycleScalingAndNotifications(t *testing.T) { {name: "instance refresh cancel and rollback", run: func(t *testing.T) { t.Helper() - client := newTestHandlerAndClient(t) + backend := autoscaling.NewInMemoryBackend() + backend.SetInstanceRefreshDelay(time.Hour) + t.Cleanup(backend.Close) + + client := newTestClientFor(t, backend) ctx := t.Context() groupName := "s35-refresh-group" diff --git a/services/autoscaling/sdk_roundtrip_helper_test.go b/services/autoscaling/sdk_roundtrip_helper_test.go index ba34be19d5..0687b4a247 100644 --- a/services/autoscaling/sdk_roundtrip_helper_test.go +++ b/services/autoscaling/sdk_roundtrip_helper_test.go @@ -25,7 +25,12 @@ const rtTestRegion = "us-east-1" func newTestHandlerAndClient(t *testing.T) *assdk.Client { t.Helper() - backend := autoscaling.NewInMemoryBackend() + return newTestClientFor(t, autoscaling.NewInMemoryBackend()) +} + +func newTestClientFor(t *testing.T, backend *autoscaling.InMemoryBackend) *assdk.Client { + t.Helper() + h := autoscaling.NewHandler(backend) e := echo.New() diff --git a/services/autoscaling/store.go b/services/autoscaling/store.go index 3ea26efb81..9c164ff59b 100644 --- a/services/autoscaling/store.go +++ b/services/autoscaling/store.go @@ -72,6 +72,7 @@ const ( // InMemoryBackend implements StorageBackend using in-memory maps. type InMemoryBackend struct { + quotaGate *quotalimit.Gate ec2Launcher EC2Launcher instanceTypeResolver InstanceTypeResolver elbv2Registrar ELBv2TargetRegistrar @@ -95,11 +96,11 @@ type InMemoryBackend struct { registry *store.Registry instanceIndex map[string]string accountID string - quotaGate *quotalimit.Gate region string deletedActivities []ScalingActivity launchTimers []*time.Timer nextHookSeq int64 + refreshDelay time.Duration launchDelay atomic.Int64 } diff --git a/services/ec2/handler.go b/services/ec2/handler.go index 3b95aeb7af..20bf67ab92 100644 --- a/services/ec2/handler.go +++ b/services/ec2/handler.go @@ -715,6 +715,13 @@ var errCodeLookup = []struct { {ErrNatGatewayLimitExceeded, "NatGatewayLimitExceeded"}, {ErrNetworkInterfaceLimitExceeded, "NetworkInterfaceLimitExceeded"}, {ErrResourceCountLimitExceeded, "ResourceCountLimitExceeded"}, + {ErrSubnetLimitExceeded, "SubnetLimitExceeded"}, + {ErrInternetGatewayLimitExceeded, "InternetGatewayLimitExceeded"}, + {ErrSecurityGroupLimitExceeded, "SecurityGroupLimitExceeded"}, + {ErrRulesPerSecurityGroupLimitExceeded, "RulesPerSecurityGroupLimitExceeded"}, + {ErrRouteTableLimitExceeded, "RouteTableLimitExceeded"}, + {ErrVcpuLimitExceeded, "VcpuLimitExceeded"}, + {ErrMaxSpotInstanceCountExceeded, "MaxSpotInstanceCountExceeded"}, {ErrInternetGatewayNotFound, "InvalidInternetGatewayID.NotFound"}, {ErrDhcpOptionsNotFound, "InvalidDhcpOptionsID.NotFound"}, {ErrSnapshotNotFound, "InvalidSnapshotID.NotFound"}, diff --git a/services/ec2/internet_gateways.go b/services/ec2/internet_gateways.go index 4e2046af5b..a0867b1d15 100644 --- a/services/ec2/internet_gateways.go +++ b/services/ec2/internet_gateways.go @@ -22,9 +22,15 @@ type InternetGateway struct { // CreateInternetGateway creates a new Internet Gateway. func (b *InMemoryBackend) CreateInternetGateway() (*InternetGateway, error) { + limit := b.quotaLimit(quotaServiceVPC, quotaIGWs) + b.mu.Lock("CreateInternetGateway") defer b.mu.Unlock() + if limit.Reached(len(b.internetGateways.All())) { + return nil, quotaExceeded(ErrInternetGatewayLimitExceeded, "internet gateways", limit) + } + id := newInternetGatewayID() igw := &InternetGateway{ ID: id, diff --git a/services/ec2/quota_vpc.go b/services/ec2/quota_vpc.go index 50f5e44fd9..52427e6d79 100644 --- a/services/ec2/quota_vpc.go +++ b/services/ec2/quota_vpc.go @@ -3,6 +3,8 @@ package ec2 import ( "errors" "strings" + + "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" ) const ( @@ -43,8 +45,95 @@ var ( ErrNatGatewayLimitExceeded = errors.New("NatGatewayLimitExceeded") ErrNetworkInterfaceLimitExceeded = errors.New("NetworkInterfaceLimitExceeded") ErrResourceCountLimitExceeded = errors.New("ResourceCountLimitExceeded") + + ErrSubnetLimitExceeded = errors.New("SubnetLimitExceeded") + ErrInternetGatewayLimitExceeded = errors.New("InternetGatewayLimitExceeded") + ErrSecurityGroupLimitExceeded = errors.New("SecurityGroupLimitExceeded") + ErrRulesPerSecurityGroupLimitExceeded = errors.New("RulesPerSecurityGroupLimitExceeded") + ErrRouteTableLimitExceeded = errors.New("RouteTableLimitExceeded") + ErrVcpuLimitExceeded = errors.New("VcpuLimitExceeded") + ErrMaxSpotInstanceCountExceeded = errors.New("MaxSpotInstanceCountExceeded") ) +func onDemandQuotaCode(class string) string { + switch class { + case vcpuStandard: + return quotaOnDemandStandard + case vcpuGVT: + return quotaOnDemandGVT + case vcpuP: + return quotaOnDemandP + case vcpuF: + return quotaOnDemandF + case vcpuX: + return quotaOnDemandX + case vcpuInf: + return quotaOnDemandInf + case vcpuHighMemory: + return quotaOnDemandHighMemory + default: + return "" + } +} + +func spotQuotaCode(class string) string { + switch class { + case vcpuStandard: + return quotaSpotStandard + case vcpuP: + return quotaSpotP + case vcpuGVT: + return quotaSpotGVT + default: + return "" + } +} + +// vcpuLimit looks up the vCPU quota of instanceType's class; spot selects the Spot quota. +func (b *InMemoryBackend) vcpuLimit(instanceType string, spot bool) quotalimit.Limit { + class := vcpuClass(instanceType) + + code := onDemandQuotaCode(class) + if spot { + code = spotQuotaCode(class) + } + + if code == "" { + return quotalimit.Limit{} + } + + return b.quotaLimit(quotaServiceEC2, code) +} + +// addExceeds reports whether adding add units to current passes the limit. +func addExceeds(limit quotalimit.Limit, current, add int) bool { + return add > 0 && limit.Reached(current+add-1) +} + +func (b *InMemoryBackend) subnetsInVPCLocked(vpcID string) int { + n := 0 + + for _, s := range b.subnets.All() { + if s.VPCID == vpcID { + n++ + } + } + + return n +} + +func (b *InMemoryBackend) routeTablesInVPCLocked(vpcID string) int { + n := 0 + + for _, r := range b.routeTables.All() { + if r.VPCID == vpcID { + n++ + } + } + + return n +} + // vcpuClass maps an instance type to the vCPU quota class the type is counted under. func vcpuClass(instanceType string) string { family, _, _ := strings.Cut(instanceType, ".") diff --git a/services/ec2/route_tables.go b/services/ec2/route_tables.go index dfea3c4b11..8d1a1b14c5 100644 --- a/services/ec2/route_tables.go +++ b/services/ec2/route_tables.go @@ -89,6 +89,8 @@ type RouteTable struct { // CreateRouteTable creates a new route table in a VPC. func (b *InMemoryBackend) CreateRouteTable(vpcID string) (*RouteTable, error) { + limit := b.quotaLimit(quotaServiceVPC, quotaRouteTablesPerVPC) + b.mu.Lock("CreateRouteTable") defer b.mu.Unlock() @@ -97,6 +99,10 @@ func (b *InMemoryBackend) CreateRouteTable(vpcID string) (*RouteTable, error) { return nil, fmt.Errorf("%w: %s", ErrVPCNotFound, vpcID) } + if limit.Reached(b.routeTablesInVPCLocked(vpcID)) { + return nil, quotaExceeded(ErrRouteTableLimitExceeded, "route tables in the VPC", limit) + } + id := newRouteTableID() rt := &RouteTable{ ID: id, diff --git a/services/ec2/security_groups.go b/services/ec2/security_groups.go index d73952bed2..658a89eb28 100644 --- a/services/ec2/security_groups.go +++ b/services/ec2/security_groups.go @@ -13,6 +13,8 @@ func (b *InMemoryBackend) AuthorizeSecurityGroupIngress( groupID string, rules []SecurityGroupRule, ) error { + limit := b.quotaLimit(quotaServiceVPC, quotaRulesPerGroup) + b.mu.Lock("AuthorizeSecurityGroupIngress") defer b.mu.Unlock() @@ -29,6 +31,10 @@ func (b *InMemoryBackend) AuthorizeSecurityGroupIngress( return err } + if addExceeds(limit, len(sg.IngressRules), len(rules)) { + return quotaExceeded(ErrRulesPerSecurityGroupLimitExceeded, "rules in the security group", limit) + } + sg.IngressRules = append(sg.IngressRules, withRuleIDs(rules)...) return nil @@ -39,6 +45,8 @@ func (b *InMemoryBackend) AuthorizeSecurityGroupEgress( groupID string, rules []SecurityGroupRule, ) error { + limit := b.quotaLimit(quotaServiceVPC, quotaRulesPerGroup) + b.mu.Lock("AuthorizeSecurityGroupEgress") defer b.mu.Unlock() @@ -55,6 +63,10 @@ func (b *InMemoryBackend) AuthorizeSecurityGroupEgress( return err } + if addExceeds(limit, len(sg.EgressRules), len(rules)) { + return quotaExceeded(ErrRulesPerSecurityGroupLimitExceeded, "rules in the security group", limit) + } + sg.EgressRules = append(sg.EgressRules, withRuleIDs(rules)...) return nil @@ -713,6 +725,8 @@ func (b *InMemoryBackend) CreateSecurityGroupWithID( return nil, fmt.Errorf("%w: GroupName is required", ErrInvalidParameter) } + limit := b.quotaLimit(quotaServiceVPC, quotaSecurityGroups) + b.mu.Lock("CreateSecurityGroup") defer b.mu.Unlock() @@ -733,6 +747,10 @@ func (b *InMemoryBackend) CreateSecurityGroupWithID( } } + if limit.Reached(len(b.securityGroups.All())) { + return nil, quotaExceeded(ErrSecurityGroupLimitExceeded, "security groups", limit) + } + id := newSecurityGroupID() if pinnedID != "" { if err := validatePinnedEC2ID(pinnedID, "sg-"); err != nil { diff --git a/services/ec2/spot_instances.go b/services/ec2/spot_instances.go index ce148e3ba2..b41e025bb9 100644 --- a/services/ec2/spot_instances.go +++ b/services/ec2/spot_instances.go @@ -80,6 +80,9 @@ func (b *InMemoryBackend) RequestSpotInstances( count = 1 } + vcpus := b.typeVCPUs(instanceType) * count + limit := b.vcpuLimit(instanceType, true) + b.mu.Lock("RequestSpotInstances") defer b.mu.Unlock() @@ -89,6 +92,10 @@ func (b *InMemoryBackend) RequestSpotInstances( return nil, fmt.Errorf("%w: %s", ErrSubnetNotFound, subnetID) } + if addExceeds(limit, b.spotVCPUsLocked(vcpuClass(instanceType)), vcpus) { + return nil, quotaExceeded(ErrMaxSpotInstanceCountExceeded, "Spot vCPUs", limit) + } + // Allocate a backing instance immediately (mock fulfils spot requests instantly). vpcID := "" if sub, ok := b.subnets.Get(subnetID); ok { diff --git a/services/ec2/store.go b/services/ec2/store.go index 0e7bd85fff..06cccfa12c 100644 --- a/services/ec2/store.go +++ b/services/ec2/store.go @@ -1089,6 +1089,9 @@ func (b *InMemoryBackend) RunInstancesWithID( return nil, err } + vcpus := b.typeVCPUs(instanceType) * count + limit := b.vcpuLimit(instanceType, false) + b.mu.Lock("RunInstances") defer b.mu.Unlock() @@ -1118,23 +1121,19 @@ func (b *InMemoryBackend) RunInstancesWithID( outpostArn = sub.OutpostArn } + if addExceeds(limit, b.onDemandVCPUsLocked(vcpuClass(instanceType)), vcpus) { + return nil, quotaExceeded(ErrVcpuLimitExceeded, "On-Demand vCPUs", limit) + } + // Real AWS depletes an Outpost's configured instance-type capacity as // instances launch onto it (see services/outposts/capacity_ledger.go's // ConsumeCapacity doc comment). Reserve capacity for the WHOLE batch // before creating any instance, using pre-minted IDs, so a rejected // batch (Outpost gone, insufficient capacity) never creates an // ec2.Instance at all -- matches real RunInstances failing atomically. - instanceIDs := newOutpostReservedInstanceIDs(count) - if pinnedID != "" { - instanceIDs[0] = pinnedID - } - - if outpostArn != "" { - if outpostsBk, ok := b.outpostsBackend(); ok { - if capErr := outpostsBk.ConsumeCapacity(outpostArn, instanceType, b.AccountID, instanceIDs); capErr != nil { - return nil, translateOutpostsCapacityErr(capErr) - } - } + instanceIDs, err := b.reserveOutpostCapacityLocked(pinnedID, outpostArn, instanceType, count) + if err != nil { + return nil, err } // No capacity hint — user-derived values in the make capacity position @@ -1180,6 +1179,28 @@ func (b *InMemoryBackend) RunInstancesWithID( return out, nil } +// reserveOutpostCapacityLocked mints the instance IDs of a launch and consumes Outpost capacity for them. +func (b *InMemoryBackend) reserveOutpostCapacityLocked( + pinnedID, outpostArn, instanceType string, count int, +) ([]string, error) { + instanceIDs := newOutpostReservedInstanceIDs(count) + if pinnedID != "" { + instanceIDs[0] = pinnedID + } + + if outpostArn == "" { + return instanceIDs, nil + } + + if outpostsBk, ok := b.outpostsBackend(); ok { + if capErr := outpostsBk.ConsumeCapacity(outpostArn, instanceType, b.AccountID, instanceIDs); capErr != nil { + return nil, translateOutpostsCapacityErr(capErr) + } + } + + return instanceIDs, nil +} + // attachLaunchENILocked registers inst and gives it the primary network interface, placing both // in the VPC's default security group. func (b *InMemoryBackend) attachLaunchENILocked(inst *Instance) { diff --git a/services/ec2/subnet_options.go b/services/ec2/subnet_options.go index 75cf2daaa0..92995e6e69 100644 --- a/services/ec2/subnet_options.go +++ b/services/ec2/subnet_options.go @@ -79,6 +79,8 @@ func (b *InMemoryBackend) CreateSubnetWithOptions(p CreateSubnetParams) (*Subnet return nil, err } + limit := b.quotaLimit(quotaServiceVPC, quotaSubnetsPerVPC) + b.mu.Lock("CreateSubnet") defer b.mu.Unlock() @@ -87,6 +89,10 @@ func (b *InMemoryBackend) CreateSubnetWithOptions(p CreateSubnetParams) (*Subnet return nil, fmt.Errorf("%w: %s", ErrVPCNotFound, p.VPCID) } + if limit.Reached(b.subnetsInVPCLocked(p.VPCID)) { + return nil, quotaExceeded(ErrSubnetLimitExceeded, "subnets in the VPC", limit) + } + az, err := b.resolveSubnetAZLocked(p.VPCID, p.AvailabilityZone, p.AvailabilityZoneID) if err != nil { return nil, err diff --git a/services/kms/grant_quota_region_test.go b/services/kms/grant_quota_region_test.go new file mode 100644 index 0000000000..638549e5d5 --- /dev/null +++ b/services/kms/grant_quota_region_test.go @@ -0,0 +1,61 @@ +package kms_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/kms" +) + +func TestCreateGrant_QuotaUsesKeyRegion(t *testing.T) { + t.Parallel() + + const keyRegion = "eu-west-1" + + tests := []struct { + wantSecond error + name string + ctxRegion string + }{ + {name: "request in other region", ctxRegion: "us-east-1", wantSecond: kms.ErrLimitExceeded}, + {name: "request in key region", ctxRegion: keyRegion, wantSecond: kms.ErrLimitExceeded}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + b := kms.NewInMemoryBackendWithConfig("123456789012", "us-east-1") + h := kms.NewHandler(b) + h.SetQuotaLimiter(func(_, region, _, _ string) (float64, bool) { + if region == keyRegion { + return 1, true + } + + return 100, true + }) + + keyCtx := kms.WithRegion(t.Context(), keyRegion) + out, err := b.CreateKey(keyCtx, &kms.CreateKeyInput{}) + require.NoError(t, err) + + in := func(name string) *kms.CreateGrantInput { + return &kms.CreateGrantInput{ + KeyID: out.KeyMetadata.Arn, + GranteePrincipal: "arn:aws:iam::123456789012:role/g", + Operations: []string{"Encrypt"}, + Name: name, + } + } + + reqCtx := kms.WithRegion(t.Context(), tc.ctxRegion) + _, err = b.CreateGrant(reqCtx, in("one")) + require.NoError(t, err) + + _, err = b.CreateGrant(reqCtx, in("two")) + assert.ErrorIs(t, err, tc.wantSecond) + }) + } +} diff --git a/services/kms/grants.go b/services/kms/grants.go index a2efa1f970..30c1a7355a 100644 --- a/services/kms/grants.go +++ b/services/kms/grants.go @@ -116,7 +116,7 @@ func (b *InMemoryBackend) CreateGrant( } } - limit := b.quotaLimit(getRegion(ctx, b.defaultRegion), quotaGrantsKey) + limit := b.quotaLimit(b.grantKeyRegion(ctx, input.KeyID), quotaGrantsKey) b.mu.Lock("CreateGrant") defer b.mu.Unlock() diff --git a/services/kms/quota.go b/services/kms/quota.go index e52bf6c3fc..c623f60686 100644 --- a/services/kms/quota.go +++ b/services/kms/quota.go @@ -1,6 +1,7 @@ package kms import ( + "context" "fmt" "github.com/blackbirdworks/gopherstack/pkgs/quotalimit" @@ -133,6 +134,19 @@ func (b *InMemoryBackend) maxGrantsPerKeyIn(region string) int { return most } +// grantKeyRegion is the Region the key behind keyID lives in, which owns the grant quota; the request Region +// when the key does not resolve. +func (b *InMemoryBackend) grantKeyRegion(ctx context.Context, keyID string) string { + b.mu.RLock("GrantKeyRegion") + defer b.mu.RUnlock() + + if _, region, err := b.resolveKeyAndRegion(ctx, keyID, ErrInvalidArn); err == nil { + return region + } + + return getRegion(ctx, b.defaultRegion) +} + func (b *InMemoryBackend) quotaLimit(region, code string) quotalimit.Limit { return b.quotaGate.Lookup(b.accountID, region, quotaServiceCode, code) } diff --git a/services/servicequotas/PARITY.md b/services/servicequotas/PARITY.md index 10784fbd79..0f11676f07 100644 --- a/services/servicequotas/PARITY.md +++ b/services/servicequotas/PARITY.md @@ -38,8 +38,8 @@ families: Reports: {status: ok, note: "The report snapshot is taken when the report completes."} AutoManagement: {status: ok, note: "One configuration per account and Region."} items_still_open: - - "QuotaUtilization: 61 count-of-resources quotas report live usage (internal/app/testdata/service_quota_classes.json class c); the other 3368 count-of-resources quotas (per-instance-type usage of SageMaker, Bedrock, Connect, Glue, CloudFront, Spot-fleet style quotas and the remaining quotas of every documented service) have no counter wired in internal/app/service_quotas_counters.go, and the 1413 rate, throughput and concurrency quotas report no usage because the emulator keeps no request-rate or concurrency meter" - - "AppliedQuotaEnforcement: opt-in (--enforce-service-quotas) for S3 buckets, EC2 Elastic IPs, VPCs, NAT gateways per AZ, network interfaces and routes per table, IAM roles/users/groups/customer managed policies/instance profiles, EKS clusters, DynamoDB tables, RDS DB instances and clusters, CloudFormation stacks, ALB/NLB/Classic load balancers, CloudWatch Logs log groups, KMS keys/aliases per key/grants per key, EventBridge buses/rules per bus/connections/endpoints/API destinations, Step Functions state machines/activities/versions/aliases, Route 53 hosted zones/health checks/delegation sets/traffic policies/CIDR collections, ECR repositories, Auto Scaling groups and launch configurations, EFS file systems, Firehose delivery streams and Cognito identity and user pools; counted but not enforced: ECS clusters (CreateCluster declares no limit exception), EC2 subnets/internet gateways/security groups/rules per group/route tables/vCPU and Spot quotas (the EC2 error code reference lists no limit code for them) and Route 53 records per hosted zone (ChangeResourceRecordSets declares none); rate quotas never throttle" + - "QuotaUtilization: 61 of the 3307 count-of-resources quotas (internal/app/testdata/service_quota_classes.json classes c and e) report live usage; the other 3246 (per-instance-type usage of SageMaker, Bedrock, Connect, Glue, CloudFront, Spot-fleet style quotas and the remaining quotas of every documented service) have no counter in internal/app/service_quotas_counters.go; the 1411 rate, throughput and concurrency quotas (class r) report no usage because the emulator keeps no request-rate or concurrency meter, and the 217 size and length quotas (class s) are per-request limits with nothing to count" + - "AppliedQuotaEnforcement: opt-in (--enforce-service-quotas) for S3 buckets, EC2 Elastic IPs, VPCs, subnets per VPC, internet gateways, security groups, rules per security group, route tables per VPC, NAT gateways per AZ, network interfaces, routes per table and On-Demand vCPUs (RunInstances, every class) and Spot vCPUs (RequestSpotInstances, Standard, G and VT and P), IAM roles/users/groups/customer managed policies/instance profiles, EKS clusters, DynamoDB tables, RDS DB instances and clusters, CloudFormation stacks, ALB/NLB/Classic load balancers, CloudWatch Logs log groups, KMS keys/aliases per key/grants per key, EventBridge buses/rules per bus/connections/endpoints/API destinations, Step Functions state machines/activities/versions/aliases, Route 53 hosted zones/health checks/delegation sets/traffic policies/CIDR collections, ECR repositories, Auto Scaling groups and launch configurations, EFS file systems, Firehose delivery streams and Cognito identity and user pools; counted but not enforced: ECS clusters (CreateCluster declares no limit exception), Route 53 records per hosted zone (ChangeResourceRecordSets declares none), and vCPUs launched through Spot Fleet, Auto Scaling or launch templates (only RunInstances and RequestSpotInstances check them); rate quotas never throttle" gaps: [] structural_gaps: - "Support staff never review a case: a request still auto-approves on the lifecycle dwell unless its Support case is resolved first (CASE_CLOSED)." @@ -68,10 +68,10 @@ Quota request templates answer TemplatesNotAvailableInRegionException in opt-in, ## Live usage and enforcement -- Count quotas are classified one by one in `internal/app/testdata/service_quota_classes.json` (c counted, e count without counter, s size or length, r rate or concurrency); `TestQuotaClassificationCoversCatalog` fails for a catalogued quota missing from it and `TestQuotaCountersMatchClassification` for a counter and a class that disagree. The s/r/e split of the uncounted quotas is name-derived and was not reviewed quota by quota. +- Count quotas are classified one by one in `internal/app/testdata/service_quota_classes.json` (c counted, e count without counter, s size or length, r rate or concurrency); `TestQuotaClassificationCoversCatalog` fails for a catalogued quota missing from it and `TestQuotaCountersMatchClassification` for a counter and a class that disagree. The s/r/e split of the uncounted quotas is name-derived; a 150-entry stratified review (2026-11-21) corrected the systematic errors (Bedrock records per batch job, provisioned model units, SageMaker MLflow servers, Omics stores, FSx Windows file systems) but the rest was not reviewed quota by quota. - Quotas scoped to a parent (subnets per VPC, rules per security group, aliases per KMS key, rules per event bus, routes per table, versions and aliases per state machine) report the largest count in any single parent in the Region, and enforce per parent. - Enforcement reads the applied value before the owning backend takes its lock and compares it inside the same critical section as the create, so concurrent creates cannot overshoot; with the flag off nothing is consulted and the built-in caps (EventBridge 200 buses and 300 rules per bus, KMS 50,000 grants per key, EFS file system cap) are unchanged. -- Limit errors come from the SDK operation error lists (`deserializeOpError` of the pinned module versions) or, for EC2, from the EC2 error code reference (NatGatewayLimitExceeded, NetworkInterfaceLimitExceeded, ResourceCountLimitExceeded). +- Limit errors come from the SDK operation error lists (`deserializeOpError` of the pinned module versions) or, for EC2, from the EC2 error code reference (docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html): NatGatewayLimitExceeded, NetworkInterfaceLimitExceeded, ResourceCountLimitExceeded (routes), SubnetLimitExceeded, InternetGatewayLimitExceeded, SecurityGroupLimitExceeded, RulesPerSecurityGroupLimitExceeded, RouteTableLimitExceeded, VcpuLimitExceeded, MaxSpotInstanceCountExceeded, VpcLimitExceeded and AddressLimitExceeded. - EC2 vCPU quotas count pending and running On-Demand instances by instance family class and open or active Spot requests by requested type; instances launched by a Spot request are excluded from the On-Demand count. - Route 53 is account-global: it consults the applied value of the Service Quotas backend's own account and Region. - Rate, throughput and concurrency quotas (requests per second, concurrent executions) are catalogued with their values and never produce throttling; no usage is reported for them. From 3174e1feaa5ec37d247b95c47c502e3ebf50007a Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 23:41:07 -0600 Subject: [PATCH 6/8] fix(athena): an embedding engine keeps the functions it owns and sees none of the standalone-only ones Timestream runs on Athena's translator, which rewrote sequence, repeat, zip, skewness and other names to Athena's new implementations before Timestream could claim them, and exposed Athena-only functions to Timestream queries. The embedded entry point now takes the set of names the host owns and skips standalone-only functions. The Timestream parser no longer reads past the end of a truncated cast. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- services/athena/engine_embed.go | 16 ++- services/athena/engine_funcs.go | 10 +- services/athena/engine_funcs_registry.go | 75 +++++++++++--- .../engine_funcs_registry_internal_test.go | 10 +- services/athena/engine_sql.go | 23 +++-- services/timestreamquery/README.md | 11 ++- .../fuzz/FuzzAnnotateQuery/08b93146030a67cc | 2 + .../ts_embedded_funcs_internal_test.go | 98 +++++++++++++++++++ services/timestreamquery/ts_engine.go | 2 +- .../timestreamquery/ts_infer_internal_test.go | 20 +--- services/timestreamquery/ts_sqlparse.go | 2 +- test/crossengine/function_namespace_test.go | 36 +++++++ 12 files changed, 251 insertions(+), 54 deletions(-) create mode 100644 services/timestreamquery/testdata/fuzz/FuzzAnnotateQuery/08b93146030a67cc create mode 100644 services/timestreamquery/ts_embedded_funcs_internal_test.go diff --git a/services/athena/engine_embed.go b/services/athena/engine_embed.go index c75dceb832..87085bbeed 100644 --- a/services/athena/engine_embed.go +++ b/services/athena/engine_embed.go @@ -8,11 +8,23 @@ import "database/sql" func TranslateTrino( query string, resolve func(parts []string) (schema, name string, ok bool), ) (string, []string, error) { - return translateSQLFor(query, func(parts []string) resolvedRef { + return translateSQLFor(query, wrapResolve(resolve), false, nil) +} + +// TranslateEmbedded is TranslateTrino for a service that embeds the engine: names in owned are left +// for the host to resolve, and functions Athena adds beyond the shared set stay unresolved. +func TranslateEmbedded( + query string, resolve func(parts []string) (schema, name string, ok bool), owned map[string]struct{}, +) (string, []string, error) { + return translateSQLFor(query, wrapResolve(resolve), true, owned) +} + +func wrapResolve(resolve func(parts []string) (schema, name string, ok bool)) func([]string) resolvedRef { + return func(parts []string) resolvedRef { schema, name, ok := resolve(parts) return resolvedRef{schema: schema, name: name, found: ok} - }, true) + } } // OpenEngineDB opens a private in-memory SQLite database with the Trino function set registered. diff --git a/services/athena/engine_funcs.go b/services/athena/engine_funcs.go index 6058fbc72b..facc381522 100644 --- a/services/athena/engine_funcs.go +++ b/services/athena/engine_funcs.go @@ -49,10 +49,12 @@ func registerEngineFuncs() { registerExtraFuncs() registerComplexFuncs() registerAggregates() - registerStatAggregates() - registerArrayOpFuncs() - registerTrinoMathFuncs() - registerTrinoStringFuncs() + standaloneOnlyFuncs(func() { + registerStatAggregates() + registerArrayOpFuncs() + registerTrinoMathFuncs() + registerTrinoStringFuncs() + }) registerRowCompareFuncs() registerUnnestModule() }) diff --git a/services/athena/engine_funcs_registry.go b/services/athena/engine_funcs_registry.go index fdd7736f22..516bb9cac4 100644 --- a/services/athena/engine_funcs_registry.go +++ b/services/athena/engine_funcs_registry.go @@ -3,6 +3,7 @@ package athena import ( "strings" "sync" + "sync/atomic" sqlitedriver "modernc.org/sqlite" ) @@ -11,13 +12,19 @@ import ( // process-wide and shared with other services' engines. const funcPrefix = "athena_" +type funcEntry struct { + full string + standaloneOnly bool +} + type funcRegistry struct { - names map[string]string - mu sync.RWMutex + names map[string]funcEntry + mu sync.RWMutex + standaloneOnly atomic.Bool } //nolint:gochecknoglobals // the driver's function registry is process-wide -var funcNames = &funcRegistry{names: map[string]string{}} +var funcNames = &funcRegistry{names: map[string]funcEntry{}} func prefixedFuncName(name string) string { if strings.HasPrefix(name, funcPrefix) { @@ -31,19 +38,27 @@ func (r *funcRegistry) record(name string) string { full := prefixedFuncName(name) r.mu.Lock() - r.names[strings.ToLower(name)] = full + r.names[strings.ToLower(name)] = funcEntry{full: full, standaloneOnly: r.standaloneOnly.Load()} r.mu.Unlock() return full } -func (r *funcRegistry) lookup(lw string) (string, bool) { +func (r *funcRegistry) lookup(lw string) (funcEntry, bool) { r.mu.RLock() defer r.mu.RUnlock() - full, ok := r.names[lw] + e, ok := r.names[lw] - return full, ok + return e, ok +} + +// standaloneOnlyFuncs runs register with every function it records hidden from embedding services. +func standaloneOnlyFuncs(register func()) { + funcNames.standaloneOnly.Store(true) + defer funcNames.standaloneOnly.Store(false) + + register() } // registeredFuncNames lists the SQLite names this service registered. @@ -54,8 +69,26 @@ func registeredFuncNames() []string { defer funcNames.mu.RUnlock() out := make([]string, 0, len(funcNames.names)) - for _, full := range funcNames.names { - out = append(out, full) + for _, e := range funcNames.names { + out = append(out, e.full) + } + + return out +} + +// EmbeddedFuncNames lists the SQLite names an embedding service can reach through TranslateEmbedded. +func EmbeddedFuncNames() []string { + registerEngineFuncs() + + funcNames.mu.RLock() + defer funcNames.mu.RUnlock() + + out := make([]string, 0, len(funcNames.names)) + + for _, e := range funcNames.names { + if !e.standaloneOnly { + out = append(out, e.full) + } } return out @@ -65,7 +98,26 @@ func registeredFuncNames() []string { func athenaFunc(lw string) (string, bool) { registerEngineFuncs() - return funcNames.lookup(lw) + e, ok := funcNames.lookup(lw) + + return e.full, ok +} + +// embeddedFunc maps a Trino function name for an embedding service, skipping standalone-only names +// and the names the host owns. +func embeddedFunc(lw string, owned map[string]struct{}) (string, bool) { + registerEngineFuncs() + + if _, own := owned[lw]; own { + return "", false + } + + e, ok := funcNames.lookup(lw) + if !ok || e.standaloneOnly { + return "", false + } + + return e.full, true } func registerScalar(name string, nargs int32, fn scalarFn) { @@ -75,6 +127,3 @@ func registerScalar(name string, nargs int32, fn scalarFn) { func registerNondeterministic(name string, nargs int32, fn scalarFn) { sqlitedriver.MustRegisterScalarFunction(funcNames.record(name), nargs, fn) } - -// isEmbedderOwned names the Trino functions an embedding service registers under their plain names. -func isEmbedderOwned(lw string) bool { return lw == "to_milliseconds" || lw == "parse_duration" } diff --git a/services/athena/engine_funcs_registry_internal_test.go b/services/athena/engine_funcs_registry_internal_test.go index f3ba1e6898..cc96deef13 100644 --- a/services/athena/engine_funcs_registry_internal_test.go +++ b/services/athena/engine_funcs_registry_internal_test.go @@ -56,19 +56,23 @@ func TestEmbeddedTranslationKeepsOwnerFunctions(t *testing.T) { none := func([]string) resolvedRef { return resolvedRef{} } cases := []struct { + owned map[string]struct{} name string want string embedded bool }{ - {"athena", "SELECT athena_to_milliseconds(x), athena_reverse(y)", false}, - {"embedded", "SELECT to_milliseconds(x), athena_reverse(y)", true}, + {nil, "athena", "SELECT athena_to_milliseconds(x), athena_reverse(y)", false}, + { + map[string]struct{}{"to_milliseconds": {}}, "embedded", + "SELECT to_milliseconds(x), athena_reverse(y)", true, + }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { t.Parallel() - got, _, err := translateSQLFor("SELECT to_milliseconds(x), reverse(y)", none, tc.embedded) + got, _, err := translateSQLFor("SELECT to_milliseconds(x), reverse(y)", none, tc.embedded, tc.owned) require.NoError(t, err) assert.Equal(t, tc.want, got) }) diff --git a/services/athena/engine_sql.go b/services/athena/engine_sql.go index 67650c9c32..02bb9d4443 100644 --- a/services/athena/engine_sql.go +++ b/services/athena/engine_sql.go @@ -24,6 +24,7 @@ type translator struct { unnest map[string]unnestCol qualifiers map[string]bool structCols map[string]bool + owned map[string]struct{} unresolved []string unnestAliases []string nUnnest int @@ -180,12 +181,14 @@ func collectCTEs(toks []token) map[string]bool { // translateSQL rewrites Presto/Trino SQL into SQLite SQL and resolves every // table reference through resolve. func translateSQL(sql string, resolve func(parts []string) resolvedRef) (string, []string, error) { - return translateSQLFor(sql, resolve, false) + return translateSQLFor(sql, resolve, false, nil) } -// translateSQLFor translates for Athena or, when embedded, for another service that shares the engine -// and registers its own to_milliseconds and parse_duration. -func translateSQLFor(sql string, resolve func(parts []string) resolvedRef, embedded bool) (string, []string, error) { +// translateSQLFor translates for Athena or, when embedded, for a service that shares the engine and owns +// the function names in owned. +func translateSQLFor( + sql string, resolve func(parts []string) resolvedRef, embedded bool, owned map[string]struct{}, +) (string, []string, error) { toks, err := tokenize(sql) if err != nil { return "", nil, err @@ -204,7 +207,7 @@ func translateSQLFor(sql string, resolve func(parts []string) resolvedRef, embed toks = addNullsLast(toks) x := &translator{ - resolve: resolve, ctes: collectCTEs(toks), intervals: intervals, embedded: embedded, + resolve: resolve, ctes: collectCTEs(toks), intervals: intervals, embedded: embedded, owned: owned, qualifiers: map[string]bool{}, structCols: map[string]bool{}, } learnRowAliases(toks, x.structCols) @@ -380,13 +383,21 @@ func (x *translator) rewriteCall( return []token{{kind: tkWord, text: r}}, i, stack, true } - if r, ok := athenaFunc(lw); ok && (!x.embedded || !isEmbedderOwned(lw)) { + if r, ok := x.engineFunc(lw); ok { return []token{{kind: tkWord, text: r}}, i, stack, true } return nil, 0, stack, false } +func (x *translator) engineFunc(lw string) (string, bool) { + if x.embedded { + return embeddedFunc(lw, x.owned) + } + + return athenaFunc(lw) +} + // callWord rewrites CAST and EXTRACT calls; ok=false leaves the call to normal handling. func (x *translator) callWord(toks []token, lw string, open int) ([]token, int, bool) { var ( diff --git a/services/timestreamquery/README.md b/services/timestreamquery/README.md index 538f621ba8..2d7784698c 100644 --- a/services/timestreamquery/README.md +++ b/services/timestreamquery/README.md @@ -9,7 +9,7 @@ | --- | --- | | PARITY entries audited | 12 (12 ok) | | Feature families | 2 (1 ok, 1 deferred) | -| Known gaps | 7 | +| Known gaps | 8 | | Structural gaps (can't be emulated) | 1 | | Deferred items | 0 | | Resource leaks | clean | @@ -19,10 +19,11 @@ - Static type inference (ts_infer.go) types every select-list expression before execution; a query it cannot parse or type keeps the older value-based column typing (and syntactic boolean/interval typing, ts_boolean.go), an empty result of such a column reports VARCHAR, and the checked arithmetic and casts below do not apply to it (SQLite semantics: integer overflow widens, CAST(double AS bigint) truncates, TRY_CAST of an unparsable string yields 0, division by zero yields NULL). Remaining sites: positional ? markers (PrepareQuery reports them as param1.. VARCHAR; the PrepareQuery page documents only @identifier names); an @name in the select list or compared with another untyped operand (its type depends on a value no request supplies; PrepareQuery reports VARCHAR); lambdas outside filter, transform, reduce, zip_with, the *_match functions and the regexp_replace lambda; transform() over a timeseries (the engine has no implementation); map-typed functions (map, map_agg, map_keys, map_values, histogram); a row field name that does not exist and row[i] with a non-literal i; any function without a return-type rule (SQLite built-ins outside the Timestream function list) - Unverified against the service: integer literals are typed INTEGER when they fit 32 bits else BIGINT (supported-data-types.html lists int and bigint but not which a literal gets; the SDK ScalarType enum has INTEGER, appended after UNKNOWN, and string-functions.html lists codepoint as integer, so the service emits it for something, but no recorded real response in the repo or the documentation shows a literal's ColumnInfo), and typeof() prints array(T), row(name T, ...) and timeseries(T) for nested types (array-functions.html writes output types as array(bigint), array(varchar), array(timestamp) and array(row), which is notation for function signatures, not typeof output; no page shows typeof of a row or timeseries) - Checked arithmetic and casts: the error type (ValidationException) and message wording ("bigint addition overflow: A + B", "Division by zero", "Cannot cast 'x' to BIGINT", "Out of range for integer: N", "Value cannot be cast to timestamp: x") follow the Presto/Trino family from memory; no Timestream page quotes them. CAST(double AS bigint) rounds half away from zero on the same basis. try() maps a failure anywhere inside its argument to NULL for the failing operation, which differs from the family only when a NULL changes a surrounding coalesce or CASE -- Documented functions the engine does not implement (calls fail with 'Function not registered' or 'wrong number of arguments'; return-type rules exist): array_intersect, array_union, array_except, shuffle, repeat, zip, from_base, to_base, strrpos, bitwise_and_agg, bitwise_or_agg, skewness, regexp_replace with a lambda, max_by/min_by(x, y, n) and approx_percentile with weights. max(x, n), min(x, n) and approx_percentile(x, ARRAY[...]) return the documented arrays (n largest or smallest first, the value at each percentage in order, NULL for no input); their n bound (1-10000), percentage range (0-1) and error wording are from the engine family, not a Timestream page, and they are not usable as window functions -- NaN has no SQLite representation, so DOUBLE division or modulo by zero yields NaN as the text 'NaN' only where the result is rendered (a top-level select item), under a CAST to anything but DOUBLE and as the argument of is_nan, is_finite and is_infinite; anywhere else a NaN is NULL, as before checked arithmetic, and CAST('NaN' AS double) travels as text so arithmetic and comparisons on it are wrong. Infinity and -Infinity are real doubles and behave normally -- A checked arithmetic or cast rewrite that fails to translate or prepare (anything but a checked function rejecting a value) reruns the query without the checked rewrites, so such a query keeps the older semantics (overflow widens, division by zero is NULL, casts truncate) instead of failing; constant subexpressions such as a division by a literal zero are evaluated before any CASE or AND that would guard them -- Interval arithmetic between two intervals (SELECT 1h + 30m, ago(2m + 30s)) fails with TYPE_MISMATCH; the checked rewrite does not touch these operators +- Documented functions: every function on the Timestream mathematical, string, array, bitwise, regular expression, date/time, aggregate, window, conditional, comparison and time series pages is implemented except one example: parse_datetime with a zone-abbreviation pattern (date-time-functions.html: parse_datetime('2019-12-29 10:10 PST', 'uuuu-LL-dd HH:mm z') returns 2019-12-29 18:10:00.000000000) fails with 'Invalid format' because the base engine's parser has no zone abbreviations. max(x, n), min(x, n) and approx_percentile(x, ARRAY[...]) are not usable as window functions (they raise a clear error); the aggregates added in the reference function pass are. Argument bounds and error wording come from the engine family, not a Timestream page, for: max(x, n)/min(x, n) n 1-10000, max_by/min_by(x, y, n) n 1-10000 ('third argument of max_by must be a positive integer'), approx_percentile percentage range 0-1 and weight/accuracy checks, approx_distinct(x, e) with e in [0.0040625, 0.26] (the e range itself is on aggregate-functions.html), repeat count 0-10000, zip of 2 to 5 arrays, from_base/to_base radix 2-36, strpos/strrpos with overlapping matches and 'instance' must be a positive number, strpos/strrpos(x, '') = 1, skewness and the regr_* functions returning NULL for fewer than 3 rows or no variance in x, replace(x, '', y) inserting y between characters +- NaN has no SQLite representation (a NaN stored in a REAL column becomes NULL), so a NaN DOUBLE is the text 'NaN' only where it is rendered (a top-level select item with no CTE), under a CAST to anything but DOUBLE, as the argument of is_nan/is_finite/is_infinite, or as an operand of DOUBLE arithmetic or comparison that is itself rewritten (an operand subtree containing nan(), infinity(), a division, a modulo, a CAST/typed literal to DOUBLE, or sqrt/ln/log10/log2/acos/asin/acosh/atanh/power/pow); there nan(), CAST('NaN' AS double), 0e0/0e0, sqrt(-1), ln(-1), infinity() - infinity() and nan() + 1 give NaN, ln(0) gives -Infinity, nan() = nan() is false and nan() <> nan() is true. Everywhere else a NaN is NULL: a NaN passed through a subquery or CTE column, ORDER BY, GROUP BY, DISTINCT, an aggregate (sum, min, max, avg over a NaN is not NaN), a window function, sign(), abs(), round() and similar numeric functions, or arithmetic whose operands the rewrite cannot see (a column holding a NaN, which the engine cannot store). NaN ordering (last, greatest) therefore does not hold. Infinity and -Infinity are real doubles and behave normally; a DOUBLE function rewritten for NaN is a Go function, not the native SQLite one, so its last digit can differ from SQLite's libm +- Unverified against the service: the argument bounds and error wording of the reference functions come from the Presto/Trino family because no Timestream page states them: repeat count 0..10000, max_by/min_by n 1..10000, sequence() at most 1,000,000 elements (the family caps at 10,000), zip 2..5 arrays, from_base/to_base radix 2..36, bit_count bits 2..64, approx_distinct error 0.0040625..0.26, lpad/rpad length at most 16,777,216 +- INTERVAL YEAR TO MONTH arithmetic lives in the shared SQL engine (services/athena engine_interval.go) and does not range-check: `1year * 9223372036854775807` wraps instead of failing, and `TIMESTAMP + 9999999999999year` renders a year far beyond 9999 +- A checked arithmetic or cast rewrite that fails to translate or prepare (anything but a checked function rejecting a value) reruns the query without the checked rewrites, so such a query keeps the older semantics (overflow widens, division by zero is NULL, casts truncate) instead of failing ### Structural gaps diff --git a/services/timestreamquery/testdata/fuzz/FuzzAnnotateQuery/08b93146030a67cc b/services/timestreamquery/testdata/fuzz/FuzzAnnotateQuery/08b93146030a67cc new file mode 100644 index 0000000000..8418c81bd0 --- /dev/null +++ b/services/timestreamquery/testdata/fuzz/FuzzAnnotateQuery/08b93146030a67cc @@ -0,0 +1,2 @@ +go test fuzz v1 +string("SELECT CAST(''AS int (0") diff --git a/services/timestreamquery/ts_embedded_funcs_internal_test.go b/services/timestreamquery/ts_embedded_funcs_internal_test.go new file mode 100644 index 0000000000..58b6ed69d5 --- /dev/null +++ b/services/timestreamquery/ts_embedded_funcs_internal_test.go @@ -0,0 +1,98 @@ +package timestreamquery + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestEmbeddedTranslationKeepsEveryOwnedName(t *testing.T) { + t.Parallel() + + registerTimestreamFuncs() + + require.Greater(t, len(plainFuncs), 30) + + for name := range plainFuncs { + t.Run(name, func(t *testing.T) { + t.Parallel() + + out, err := translate("SELECT "+name+"(1)", loadedSet{}) + if err != nil { + t.Skipf("%s has special call syntax: %v", name, err) + } + + got := qualifyEngineFuncs(out) + assert.Contains(t, got, funcPrefix+name+"(", "Timestream must run its own %s", name) + assert.NotContains(t, got, "athena_"+name+"(") + }) + } +} + +func TestAthenaOnlyFunctionsAreUnknown(t *testing.T) { + t.Parallel() + + tests := []string{ + "flatten(ARRAY[ARRAY[1], ARRAY[2]])", + "array_first(ARRAY[1, 2])", + "array_last(ARRAY[1, 2])", + "trim_array(ARRAY[1, 2], 1)", + "contains_sequence(ARRAY[1, 2], ARRAY[1])", + "url_encode('a b')", + "url_decode('a%20b')", + "translate('abc', 'a', 'x')", + "ends_with('abc', 'c')", + "width_bucket(1.5, 0, 3, 3)", + "bitwise_left_shift(1, 2)", + "bitwise_right_shift(4, 1)", + "bitwise_right_shift_arithmetic(4, 1)", + "kurtosis(x) FROM (SELECT 1 AS x)", + "bitwise_xor_agg(x) FROM (SELECT 1 AS x)", + } + + for _, expr := range tests { + t.Run(strings.SplitN(expr, "(", 2)[0], func(t *testing.T) { + t.Parallel() + + b := NewInMemoryBackend("000000000000", "us-east-1") + _, err := b.QueryWithOptions(t.Context(), QueryOptions{QueryString: "SELECT " + expr}) + require.Error(t, err) + assert.Contains(t, strings.ToLower(err.Error()), strings.SplitN(expr, "(", 2)[0]) + }) + } +} + +func TestOwnedFunctionsKeepTimestreamResults(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + expr string + want string + }{ + {"skewness", "round(skewness(x), 4) FROM (SELECT 1 AS x UNION ALL SELECT 2 UNION ALL SELECT 9)", "0.6655"}, + {"infinity", "infinity()", "Infinity"}, + {"is_infinite", "is_infinite(infinity())", "true"}, + {"is_nan", "is_nan(nan())", "true"}, + {"arrays_overlap", "arrays_overlap(ARRAY[1, 2], ARRAY[2, 3])", "true"}, + { + "zip", "CAST(zip(ARRAY[1, 2], ARRAY['a', 'b']) AS VARCHAR)", + `[{"\u00000":1,"\u00001":"a"},{"\u00000":2,"\u00001":"b"}]`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + b := NewInMemoryBackend("000000000000", "us-east-1") + pg, err := b.QueryWithOptions(t.Context(), QueryOptions{QueryString: "SELECT " + tt.expr}) + require.NoError(t, err) + require.Len(t, pg.Rows, 1) + require.NotNil(t, pg.Rows[0].Data[0].ScalarValue) + assert.Equal(t, tt.want, strings.TrimPrefix(*pg.Rows[0].Data[0].ScalarValue, "\x01")) + }) + } +} diff --git a/services/timestreamquery/ts_engine.go b/services/timestreamquery/ts_engine.go index 4da7b5e664..b989cac504 100644 --- a/services/timestreamquery/ts_engine.go +++ b/services/timestreamquery/ts_engine.go @@ -214,7 +214,7 @@ func translate(q string, set loadedSet) (string, error) { return "main", t.sqlName, true } - out, unresolved, err := athena.TranslateTrino(q, resolve) + out, unresolved, err := athena.TranslateEmbedded(q, resolve, plainFuncs) if err != nil { return "", validationf("%s", err.Error()) } diff --git a/services/timestreamquery/ts_infer_internal_test.go b/services/timestreamquery/ts_infer_internal_test.go index 058ece804f..3c36089c08 100644 --- a/services/timestreamquery/ts_infer_internal_test.go +++ b/services/timestreamquery/ts_infer_internal_test.go @@ -16,30 +16,12 @@ func TestEveryEngineFunctionHasReturnTypeRule(t *testing.T) { registerTimestreamFuncs() - db, err := athena.OpenEngineDB() - require.NoError(t, err) - - t.Cleanup(func() { _ = db.Close() }) - - rows, err := db.QueryContext( - t.Context(), - `SELECT DISTINCT name FROM pragma_function_list WHERE name LIKE 'athena\_%' ESCAPE '\'`, - ) - require.NoError(t, err) - - defer func() { _ = rows.Close() }() - names := map[string]bool{"create_time_series": true} - for rows.Next() { - var n string - require.NoError(t, rows.Scan(&n)) - + for _, n := range athena.EmbeddedFuncNames() { names[strings.TrimPrefix(n, "athena_")] = true } - require.NoError(t, rows.Err()) - for _, f := range tsScalarFuncs() { names[f.name] = true } diff --git a/services/timestreamquery/ts_sqlparse.go b/services/timestreamquery/ts_sqlparse.go index fa52cd2ba4..936f8e3763 100644 --- a/services/timestreamquery/ts_sqlparse.go +++ b/services/timestreamquery/ts_sqlparse.go @@ -32,7 +32,7 @@ func parseSQL(q string) (*queryNode, error) { return qn, nil } -func (p *sqlParser) peek() token { return p.toks[p.pos] } +func (p *sqlParser) peek() token { return p.peekAt(0) } func (p *sqlParser) peekAt(n int) token { if p.pos+n >= len(p.toks) { diff --git a/test/crossengine/function_namespace_test.go b/test/crossengine/function_namespace_test.go index b855489396..ce26874746 100644 --- a/test/crossengine/function_namespace_test.go +++ b/test/crossengine/function_namespace_test.go @@ -95,6 +95,42 @@ func timestreamValue(t *testing.T, expr string) string { return *d.ScalarValue } +func TestSameFunctionNameKeepsEachEnginesResult(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + expr string + athena string + timestr string + }{ + { + "skewness", + "round(skewness(x), 4) FROM (SELECT 1 AS x UNION ALL SELECT 2 UNION ALL SELECT 9)", "1.6301", "0.6655", + }, + {"infinity", "infinity()", "+Inf", "Infinity"}, + {"is_infinite", "is_infinite(infinity())", "1", "true"}, + {"is_nan", "is_nan(nan())", "1", "true"}, + {"arrays_overlap", "arrays_overlap(ARRAY[1, 2], ARRAY[2, 3])", "1", "true"}, + { + "zip", "CAST(zip(ARRAY[1, 2], ARRAY['a', 'b']) AS VARCHAR)", + `[{"\u00000":1,"\u00001":"a","\u0000row":["\u00000","\u00001"]},` + + `{"\u00000":2,"\u00001":"b","\u0000row":["\u00000","\u00001"]}]`, + `[{"\u00000":1,"\u00001":"a"},{"\u00000":2,"\u00001":"b"}]`, + }, + {"sequence", "CAST(sequence(1, 3) AS VARCHAR)", "[1,2,3]", "[1,2,3]"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tt.athena, strings.TrimPrefix(athenaValue(t, tt.expr), "\x01"), "athena") + assert.Equal(t, tt.timestr, strings.TrimPrefix(timestreamValue(t, tt.expr), "\x01"), "timestream") + }) + } +} + func TestEnginesKeepTheirOwnFunctionSemantics(t *testing.T) { t.Parallel() From b6070974aae32d6562ec3f6a3d0c4c917d21b39d Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 23:41:07 -0600 Subject: [PATCH 7/8] docs: regenerate service READMEs Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- README.md | 4 ++-- services/athena/README.md | 8 +++++++- services/servicequotas/README.md | 4 ++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index fdc4225f56..b3de35c3cb 100644 --- a/README.md +++ b/README.md @@ -748,7 +748,7 @@ Every service links to its own page with a coverage breakdown — audited operat | [RDS Data](services/rdsdata/README.md) | A | 7 | 4 structural gaps | | [Redshift](services/redshift/README.md) | A | 9 | 5 structural gaps | | [Redshift Data](services/redshiftdata/README.md) | A | 12 | 4 structural gaps; 1 deferred | -| [Timestream Query](services/timestreamquery/README.md) | A | 12 | 7 gaps; 1 structural gap | +| [Timestream Query](services/timestreamquery/README.md) | A | 12 | 8 gaps; 1 structural gap | | [Timestream Write](services/timestreamwrite/README.md) | A | 19 | 1 structural gap | ### Networking & Content Delivery @@ -794,7 +794,7 @@ Every service links to its own page with a coverage breakdown — audited operat | Service | Parity | PARITY Entries | Notes | |---|---|---|---| -| [Athena](services/athena/README.md) | A | 27 | 6 structural gaps; 1 deferred | +| [Athena](services/athena/README.md) | A | 27 | 3 gaps; 6 structural gaps; 1 deferred | | [Clean Rooms](services/cleanrooms/README.md) | A | — | 18 families; 5 structural gaps | | [EMR](services/emr/README.md) | A | 65 | 7 structural gaps | | [EMR Serverless](services/emrserverless/README.md) | A | 22 | 1 structural gap | diff --git a/services/athena/README.md b/services/athena/README.md index 970f652019..da6c90bd1b 100644 --- a/services/athena/README.md +++ b/services/athena/README.md @@ -9,11 +9,17 @@ | --- | --- | | PARITY entries audited | 27 (26 ok, 1 partial) | | Feature families | 2 (2 ok) | -| Known gaps | none | +| Known gaps | 3 | | Structural gaps (can't be emulated) | 6 | | Deferred items | 1 | | Resource leaks | clean | +### Known gaps + +- Trino functions Athena v3 documents but the engine lacks (each fails 'Function not registered'): aggregates listagg, checksum, map_union, multimap_agg, approx_most_frequent, numeric_histogram, approx_set/merge, qdigest_agg, tdigest_agg, reduce_agg; arrays array_histogram, combinations, ngrams; vector/stat functions cosine_distance, cosine_similarity, dot_product, euclidean_distance, beta_cdf, normal_cdf, t_cdf, t_pdf, inverse_beta_cdf, inverse_normal_cdf, wilson_interval_lower/upper; width_bucket(x, bins array) overload; date/time at_timezone, with_timezone, timezone_hour, timezone_minute, current_timezone, now, localtimestamp, from_unixtime_nanos, from_iso8601_timestamp_nanos, human_readable_seconds; string/binary luhn_check, normalize, regexp_position, split_to_map, split_to_multimap, title_case, word_stem, soundex, to_base64url, from_base64url, hmac_md5/sha1/sha256/sha512, xxhash64, spooky_hash_v2_32/64, JSON json_array_contains, json_array_get, is_json_scalar; maps map_entries, map_from_entries, map_concat, multimap_from_entries; position(x IN y) and overlay(... PLACING ...) syntax. +- nan() cannot be a real DOUBLE: SQLite stores NaN as NULL, so nan() yields the text NaN (ColumnInfo varchar, not double) that is_nan/is_finite/is_infinite recognise; arithmetic on it and NaN results of skewness/kurtosis with zero variance surface as NULL. +- Aggregates over zero rows (bitwise_*_agg, skewness, kurtosis, regr_*) report ColumnInfo varchar, not bigint/double: result types are inferred from the first non-NULL value. + ### Structural gaps These do not block an A grade — no implementation could produce real data here because the underlying data source cannot exist in an emulator. diff --git a/services/servicequotas/README.md b/services/servicequotas/README.md index 121a24eed8..a0acb16b24 100644 --- a/services/servicequotas/README.md +++ b/services/servicequotas/README.md @@ -16,8 +16,8 @@ ### Known gaps -- QuotaUtilization: S3 buckets, EC2 Elastic IPs, VPCs, IAM roles/users/groups/customer managed policies/instance profiles, EKS clusters, DynamoDB tables, ECS clusters, RDS DB instances and clusters, CloudFormation stacks and ALB/NLB/Classic load balancers report usage; the other catalogued quotas (Lambda, CloudFormation stack sets, EC2 instance vCPUs and Spot requests, the other VPC quotas and every quota of the other documented services) have no live counter wired in internal/app/service_quotas_wiring.go quotaCounters -- AppliedQuotaEnforcement: opt-in (--enforce-service-quotas) for S3 buckets, EC2 Elastic IPs and VPCs, IAM roles/users/groups/customer managed policies/instance profiles, EKS clusters, DynamoDB tables, RDS DB instances and clusters, CloudFormation stacks and ALB/NLB/Classic load balancers only; ECS clusters are counted but not enforced (CreateCluster declares no limit exception), and the other catalogued quotas are never enforced +- QuotaUtilization: 61 of the 3307 count-of-resources quotas (internal/app/testdata/service_quota_classes.json classes c and e) report live usage; the other 3246 (per-instance-type usage of SageMaker, Bedrock, Connect, Glue, CloudFront, Spot-fleet style quotas and the remaining quotas of every documented service) have no counter in internal/app/service_quotas_counters.go; the 1411 rate, throughput and concurrency quotas (class r) report no usage because the emulator keeps no request-rate or concurrency meter, and the 217 size and length quotas (class s) are per-request limits with nothing to count +- AppliedQuotaEnforcement: opt-in (--enforce-service-quotas) for S3 buckets, EC2 Elastic IPs, VPCs, subnets per VPC, internet gateways, security groups, rules per security group, route tables per VPC, NAT gateways per AZ, network interfaces, routes per table and On-Demand vCPUs (RunInstances, every class) and Spot vCPUs (RequestSpotInstances, Standard, G and VT and P), IAM roles/users/groups/customer managed policies/instance profiles, EKS clusters, DynamoDB tables, RDS DB instances and clusters, CloudFormation stacks, ALB/NLB/Classic load balancers, CloudWatch Logs log groups, KMS keys/aliases per key/grants per key, EventBridge buses/rules per bus/connections/endpoints/API destinations, Step Functions state machines/activities/versions/aliases, Route 53 hosted zones/health checks/delegation sets/traffic policies/CIDR collections, ECR repositories, Auto Scaling groups and launch configurations, EFS file systems, Firehose delivery streams and Cognito identity and user pools; counted but not enforced: ECS clusters (CreateCluster declares no limit exception), Route 53 records per hosted zone (ChangeResourceRecordSets declares none), and vCPUs launched through Spot Fleet, Auto Scaling or launch templates (only RunInstances and RequestSpotInstances check them); rate quotas never throttle ### Structural gaps From ff6fc3f21981a48c576aac6db9d72db217cebd4a Mon Sep 17 00:00:00 2001 From: Witness Patrol Date: Sat, 21 Nov 2026 23:50:06 -0600 Subject: [PATCH 8/8] test(app): split the EC2 quota limit cases into named builders Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01NVwMjLknMM32Xje6Qik6wY --- .../service_quotas_limits_ec2_more_test.go | 302 ++++++++++-------- 1 file changed, 170 insertions(+), 132 deletions(-) diff --git a/internal/app/service_quotas_limits_ec2_more_test.go b/internal/app/service_quotas_limits_ec2_more_test.go index 57748bc8bc..9d85d0d2ae 100644 --- a/internal/app/service_quotas_limits_ec2_more_test.go +++ b/internal/app/service_quotas_limits_ec2_more_test.go @@ -88,164 +88,202 @@ func instanceCase(name, quota string, limit int, spot bool) limitCase { func ec2ConfirmedCodeCases() []limitCase { return []limitCase{ - { - name: "subnets per vpc", svc: "vpc", quota: "L-407747CB", code: "SubnetLimitExceeded", limit: 2, - handler: ec2Handler, prepare: prepareLimVPC, - create: func(ctx context.Context, e limitEnv, i int) error { - c := ec2Client(e) - - id, err := limVPC(ctx, c) - if err != nil { - return err - } + subnetsPerVPCCase(), + routeTablesPerVPCCase(), + internetGatewaysCase(), + securityGroupsCase(), + rulesPerSecurityGroupCase(), + instanceCase("on-demand standard vcpus", "L-1216C47A", 3, false), + instanceCase("spot standard vcpus", "L-34B43A08", 3, true), + } +} - _, err = c.CreateSubnet(ctx, &ec2.CreateSubnetInput{ - VpcId: id, CidrBlock: aws.String("10.88." + qnum(i) + ".0/24"), - }) +func subnetsPerVPCCase() limitCase { + return limitCase{ + name: "subnets per vpc", svc: "vpc", quota: "L-407747CB", code: "SubnetLimitExceeded", limit: 2, + handler: ec2Handler, prepare: prepareLimVPC, create: createLimSubnet, remove: removeLimSubnet, + } +} - return err - }, - remove: func(ctx context.Context, e limitEnv, _ int) error { - c := ec2Client(e) +func createLimSubnet(ctx context.Context, e limitEnv, i int) error { + c := ec2Client(e) - id, err := limVPC(ctx, c) - if err != nil { - return err - } + id, err := limVPC(ctx, c) + if err != nil { + return err + } - out, err := c.DescribeSubnets(ctx, &ec2.DescribeSubnetsInput{ - Filters: []ec2types.Filter{{Name: aws.String("vpc-id"), Values: []string{*id}}}, - }) - if err != nil || len(out.Subnets) == 0 { - return errors.Join(err, errNoQuotaTarget) - } + _, err = c.CreateSubnet(ctx, &ec2.CreateSubnetInput{ + VpcId: id, CidrBlock: aws.String("10.88." + qnum(i) + ".0/24"), + }) - _, err = c.DeleteSubnet(ctx, &ec2.DeleteSubnetInput{SubnetId: out.Subnets[0].SubnetId}) + return err +} - return err - }, - }, - { - name: "route tables per vpc", svc: "vpc", quota: "L-589F43AA", code: "RouteTableLimitExceeded", - limit: 3, existing: 1, handler: ec2Handler, prepare: prepareLimVPC, - create: func(ctx context.Context, e limitEnv, _ int) error { - c := ec2Client(e) - - id, err := limVPC(ctx, c) - if err != nil { - return err - } +func removeLimSubnet(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) - _, err = c.CreateRouteTable(ctx, &ec2.CreateRouteTableInput{VpcId: id}) + id, err := limVPC(ctx, c) + if err != nil { + return err + } - return err - }, - remove: func(ctx context.Context, e limitEnv, _ int) error { - c := ec2Client(e) + out, err := c.DescribeSubnets(ctx, &ec2.DescribeSubnetsInput{ + Filters: []ec2types.Filter{{Name: aws.String("vpc-id"), Values: []string{*id}}}, + }) + if err != nil || len(out.Subnets) == 0 { + return errors.Join(err, errNoQuotaTarget) + } - out, err := c.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{}) - if err != nil { - return err - } + _, err = c.DeleteSubnet(ctx, &ec2.DeleteSubnetInput{SubnetId: out.Subnets[0].SubnetId}) - for _, rt := range out.RouteTables { - if len(rt.Associations) == 0 && rt.VpcId != nil { - if id, _ := limVPC(ctx, c); id != nil && *id == *rt.VpcId { - _, derr := c.DeleteRouteTable(ctx, &ec2.DeleteRouteTableInput{ - RouteTableId: rt.RouteTableId, - }) + return err +} - return derr - } - } - } +func routeTablesPerVPCCase() limitCase { + return limitCase{ + name: "route tables per vpc", svc: "vpc", quota: "L-589F43AA", code: "RouteTableLimitExceeded", + limit: 3, existing: 1, handler: ec2Handler, prepare: prepareLimVPC, + create: createLimRouteTable, remove: removeLimRouteTable, + } +} - return errNoQuotaTarget - }, - }, - { - name: "internet gateways", svc: "vpc", quota: "L-A4707A72", code: "InternetGatewayLimitExceeded", - limit: 3, handler: ec2Handler, - create: func(ctx context.Context, e limitEnv, _ int) error { - _, err := ec2Client(e).CreateInternetGateway(ctx, &ec2.CreateInternetGatewayInput{}) +func createLimRouteTable(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) - return err - }, - remove: func(ctx context.Context, e limitEnv, _ int) error { - c := ec2Client(e) + id, err := limVPC(ctx, c) + if err != nil { + return err + } - out, err := c.DescribeInternetGateways(ctx, &ec2.DescribeInternetGatewaysInput{}) - if err != nil || len(out.InternetGateways) == 0 { - return errors.Join(err, errNoQuotaTarget) - } + _, err = c.CreateRouteTable(ctx, &ec2.CreateRouteTableInput{VpcId: id}) - for _, g := range out.InternetGateways { - if len(g.Attachments) == 0 { - _, derr := c.DeleteInternetGateway(ctx, &ec2.DeleteInternetGatewayInput{ - InternetGatewayId: g.InternetGatewayId, - }) + return err +} - return derr - } - } +func isLimVPCRouteTable(ctx context.Context, c *ec2.Client, rt ec2types.RouteTable) bool { + if len(rt.Associations) != 0 || rt.VpcId == nil { + return false + } - return errNoQuotaTarget - }, - }, - { - name: "security groups", svc: "vpc", quota: "L-E79EC296", code: "SecurityGroupLimitExceeded", - limit: 4, existing: 1, handler: ec2Handler, - create: func(ctx context.Context, e limitEnv, i int) error { - _, err := ec2Client(e).CreateSecurityGroup(ctx, &ec2.CreateSecurityGroupInput{ - GroupName: aws.String("sg" + qnum(i)), Description: aws.String("d"), - }) + id, _ := limVPC(ctx, c) - return err - }, - remove: func(ctx context.Context, e limitEnv, _ int) error { - _, err := ec2Client(e).DeleteSecurityGroup(ctx, &ec2.DeleteSecurityGroupInput{ - GroupName: aws.String("sg" + qnum(0)), - }) + return id != nil && *id == *rt.VpcId +} - return err - }, - }, - { - name: "rules per security group", svc: "vpc", quota: "L-0EA8095F", - code: "RulesPerSecurityGroupLimitExceeded", limit: 3, handler: ec2Handler, - prepare: func(ctx context.Context, e limitEnv) error { - _, err := ec2Client(e).CreateSecurityGroup(ctx, &ec2.CreateSecurityGroupInput{ - GroupName: aws.String("rules"), Description: aws.String("d"), - TagSpecifications: ec2NameTag(ec2types.ResourceTypeSecurityGroup), - }) +func removeLimRouteTable(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) - return err - }, - create: func(ctx context.Context, e limitEnv, i int) error { - c := ec2Client(e) + out, err := c.DescribeRouteTables(ctx, &ec2.DescribeRouteTablesInput{}) + if err != nil { + return err + } - out, err := c.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{Filters: ec2ByTag()}) - if err != nil || len(out.SecurityGroups) == 0 { - return errors.Join(err, errNoQuotaTarget) - } + for _, rt := range out.RouteTables { + if isLimVPCRouteTable(ctx, c, rt) { + _, derr := c.DeleteRouteTable(ctx, &ec2.DeleteRouteTableInput{RouteTableId: rt.RouteTableId}) - _, err = c.AuthorizeSecurityGroupIngress(ctx, &ec2.AuthorizeSecurityGroupIngressInput{ - GroupId: out.SecurityGroups[0].GroupId, - IpPermissions: []ec2types.IpPermission{{ - IpProtocol: aws.String("tcp"), - FromPort: aws.Int32(int32(1000 + i)), ToPort: aws.Int32(int32(1000 + i)), - IpRanges: []ec2types.IpRange{{CidrIp: aws.String("10.0.0.0/8")}}, - }}, - }) + return derr + } + } - return err - }, - }, - instanceCase("on-demand standard vcpus", "L-1216C47A", 3, false), - instanceCase("spot standard vcpus", "L-34B43A08", 3, true), + return errNoQuotaTarget +} + +func internetGatewaysCase() limitCase { + return limitCase{ + name: "internet gateways", svc: "vpc", quota: "L-A4707A72", code: "InternetGatewayLimitExceeded", + limit: 3, handler: ec2Handler, create: createLimIGW, remove: removeLimIGW, } } +func createLimIGW(ctx context.Context, e limitEnv, _ int) error { + _, err := ec2Client(e).CreateInternetGateway(ctx, &ec2.CreateInternetGatewayInput{}) + + return err +} + +func removeLimIGW(ctx context.Context, e limitEnv, _ int) error { + c := ec2Client(e) + + out, err := c.DescribeInternetGateways(ctx, &ec2.DescribeInternetGatewaysInput{}) + if err != nil || len(out.InternetGateways) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + for _, g := range out.InternetGateways { + if len(g.Attachments) == 0 { + _, derr := c.DeleteInternetGateway(ctx, &ec2.DeleteInternetGatewayInput{ + InternetGatewayId: g.InternetGatewayId, + }) + + return derr + } + } + + return errNoQuotaTarget +} + +func securityGroupsCase() limitCase { + return limitCase{ + name: "security groups", svc: "vpc", quota: "L-E79EC296", code: "SecurityGroupLimitExceeded", + limit: 4, existing: 1, handler: ec2Handler, create: createLimSG, remove: removeLimSG, + } +} + +func createLimSG(ctx context.Context, e limitEnv, i int) error { + _, err := ec2Client(e).CreateSecurityGroup(ctx, &ec2.CreateSecurityGroupInput{ + GroupName: aws.String("sg" + qnum(i)), Description: aws.String("d"), + }) + + return err +} + +func removeLimSG(ctx context.Context, e limitEnv, _ int) error { + _, err := ec2Client(e).DeleteSecurityGroup(ctx, &ec2.DeleteSecurityGroupInput{ + GroupName: aws.String("sg" + qnum(0)), + }) + + return err +} + +func rulesPerSecurityGroupCase() limitCase { + return limitCase{ + name: "rules per security group", svc: "vpc", quota: "L-0EA8095F", + code: "RulesPerSecurityGroupLimitExceeded", limit: 3, handler: ec2Handler, + prepare: prepareLimRulesSG, create: createLimSGRule, + } +} + +func prepareLimRulesSG(ctx context.Context, e limitEnv) error { + _, err := ec2Client(e).CreateSecurityGroup(ctx, &ec2.CreateSecurityGroupInput{ + GroupName: aws.String("rules"), Description: aws.String("d"), + TagSpecifications: ec2NameTag(ec2types.ResourceTypeSecurityGroup), + }) + + return err +} + +func createLimSGRule(ctx context.Context, e limitEnv, i int) error { + c := ec2Client(e) + + out, err := c.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{Filters: ec2ByTag()}) + if err != nil || len(out.SecurityGroups) == 0 { + return errors.Join(err, errNoQuotaTarget) + } + + _, err = c.AuthorizeSecurityGroupIngress(ctx, &ec2.AuthorizeSecurityGroupIngressInput{ + GroupId: out.SecurityGroups[0].GroupId, + IpPermissions: []ec2types.IpPermission{{ + IpProtocol: aws.String("tcp"), + FromPort: aws.Int32(int32(1000 + i)), ToPort: aws.Int32(int32(1000 + i)), + IpRanges: []ec2types.IpRange{{CidrIp: aws.String("10.0.0.0/8")}}, + }}, + }) + + return err +} + func TestQuotaLimitsEC2ConfirmedCodes(t *testing.T) { t.Parallel()