diff --git a/AGENTS.md b/AGENTS.md index 63a52c5..5de2bd2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,6 +40,7 @@ A Go CLI tool (`gorp`) and library (`pkg/gorp`) for [ReportPortal](https://repor | `oauth2.go` | Password-grant token source, `WithPasswordOwnerGrantAuth` | | `quality_gate.go` | `ParseQualityGate` from launch metadata | | `multipart.go` | `Multipart` interface + `FileMultipart`/`ReaderMultipart` | +| `limits.go` | Server limits (`MaxItemNameLength`, …), `Truncate`, `TruncateAttributes`, `BoundedID` β€” all in UTF-16 code units | | `model_api.go`, `model_enums.go` | Hand-written request/response types, `Statuses`, `TestItemTypes`, `LaunchModes`, log levels | ### CLI command tree diff --git a/README.md b/README.md index b7bc454..b99283c 100644 --- a/README.md +++ b/README.md @@ -491,6 +491,32 @@ func report(ctx context.Context) error { } ``` +### Server limits + +The server rejects a request with a name that is too long and silently cuts long descriptions. +`pkg/gorp` has the limits as constants and helpers that shorten values the way the server counts them +(UTF-16 code units, never splitting a character): + +```go +name := gorp.Truncate(name, gorp.MaxItemNameLength) // "…long name..." +desc := gorp.Truncate(desc, gorp.MaxDescriptionLength) +attrs := gorp.TruncateAttributes(attrs) // keys, values and the number of attributes +id := gorp.BoundedID(uniqueID, gorp.MaxUniqueIDLength) // "…prefix~1f3a9c0b7d2e4a68" +``` + +| Constant | Value | Over the limit | +|----------|-------|----------------| +| `MaxLaunchNameLength` | 256 | request fails with 400 | +| `MaxItemNameLength` | 1024 | request fails with 400 | +| `MaxDescriptionLength` | 2048 | the server keeps the first 2048 (ReportPortal 6) | +| `MaxUniqueIDLength` | 1024 | request fails with 400 | +| `MaxTestCaseIDLength` | 1024 | the server keeps the first 1011 and appends a hash of the rest | +| `MaxAttributes` | 256 | request fails with 400 | +| `MaxAttributeLength` | 128 | a convention of ReportPortal agents; the server cuts keys and values to 512 without an error | + +Use `BoundedID`, not `Truncate`, for identifiers: it ends the shortened ID with a hash of the whole ID, so +two long IDs that start the same stay different and the same ID always gives the same result. + ### Read client (launch queries) `Client` wraps the full generated OpenAPI client and adds higher-level helpers. diff --git a/pkg/gorp/limits.go b/pkg/gorp/limits.go new file mode 100644 index 0000000..89bd3f7 --- /dev/null +++ b/pkg/gorp/limits.go @@ -0,0 +1,151 @@ +package gorp + +import ( + "crypto/sha256" + "encoding/hex" + + "github.com/reportportal/goRP/v5/pkg/openapi" +) + +// Limits of the reporting API. The server measures strings the way Java does, in UTF-16 code units: +// a character outside the Basic Multilingual Plane (most emoji) counts as two. The functions of this +// file count the same way. +// +// What the server does with a longer value differs per field, see each constant. +const ( + // MaxLaunchNameLength is the longest launch name. A longer one fails the request with HTTP 400. + MaxLaunchNameLength = 256 + // MaxItemNameLength is the longest test item name. A longer one fails the request with HTTP 400. + MaxItemNameLength = 1024 + // MaxDescriptionLength is what the server keeps of a launch or test item description: it trims + // the description and silently drops the rest. The description given when a launch finishes is + // appended to the one from the start, and the limit applies to both together. + // + // This is the limit of the ReportPortal 6 server. The Java client still lets item descriptions + // of up to 65536 through, which suggests that older servers kept more. + MaxDescriptionLength = 2048 + // MaxUniqueIDLength is the longest uniqueId of a test item. A longer one fails the request with HTTP 400. + MaxUniqueIDLength = 1024 + // MaxTestCaseIDLength is the longest testCaseId the server stores. A longer one is not an error: + // the server keeps its first 1011 characters and appends a 32-bit hash of the rest in brackets. + // Shorten it with [BoundedID] to decide yourself what is stored. + MaxTestCaseIDLength = 1024 + // MaxAttributes is the largest number of attributes of a launch or a test item. + // More fail the request with HTTP 400. + MaxAttributes = 256 + // MaxAttributeLength is the longest attribute key or value ReportPortal agents send. It is a convention + // of the clients (the default of the Java client). The server itself cuts longer keys and values to 512 + // UTF-16 units without an error, and may split a surrogate pair there. + MaxAttributeLength = 128 +) + +const ( + // truncationMark ends a truncated string, the same one as the Java client uses + truncationMark = "..." + // idHashLength is the number of hex digits of the hash in a bounded ID + idHashLength = 16 + // idHashSeparator is between the kept part of an ID and its hash + idHashSeparator = "~" +) + +// Truncate shortens s to at most limit UTF-16 code units, the unit of the server's limits, and marks +// the cut with "...". A string within the limit is returned as is. The cut never splits a character. +// +// A limit too small for the mark gives the beginning of s without it; a limit of zero or less gives "". +// +// name = gorp.Truncate(name, gorp.MaxItemNameLength) +// +// Don't use it for identifiers: two long IDs with the same beginning become equal. See [BoundedID]. +func Truncate(s string, limit int) string { + if limit <= 0 { + return "" + } + // every character takes at least one byte in UTF-8 and at most two units in UTF-16 + if len(s) <= limit || utf16Len(s) <= limit { + return s + } + if limit <= len(truncationMark) { + return utf16Prefix(s, limit) + } + + return utf16Prefix(s, limit-len(truncationMark)) + truncationMark +} + +// BoundedID shortens an identifier (testCaseId, uniqueId) to at most limit UTF-16 code units and keeps it +// unique and stable: the kept beginning is followed by "~" and a hash of the whole ID, so two long IDs +// that differ only after the cut stay different, and the same ID always gives the same result. +// An ID within the limit is returned as is. +// +// rq.UniqueId = openapi.PtrString(gorp.BoundedID(id, gorp.MaxUniqueIDLength)) +// +// A limit that leaves no room for the hash (17 units) gives the beginning of the hash alone. +func BoundedID(id string, limit int) string { + if limit <= 0 { + return "" + } + if len(id) <= limit || utf16Len(id) <= limit { + return id + } + + sum := sha256.Sum256([]byte(id)) + hash := hex.EncodeToString(sum[:])[:idHashLength] + suffix := idHashSeparator + hash + if limit <= len(suffix) { + return hash[:min(limit, len(hash))] + } + + return utf16Prefix(id, limit-len(suffix)) + suffix +} + +// TruncateAttributes returns attributes that fit the limits: at most [MaxAttributes] of them, in the +// given order, with keys and values of at most [MaxAttributeLength]. The input is not modified. +func TruncateAttributes(attributes []openapi.ItemAttributesRQ) []openapi.ItemAttributesRQ { + if attributes == nil { + return nil + } + + res := make([]openapi.ItemAttributesRQ, 0, min(len(attributes), MaxAttributes)) + for _, attr := range attributes[:min(len(attributes), MaxAttributes)] { + if attr.Key != nil { + attr.Key = openapi.PtrString(Truncate(*attr.Key, MaxAttributeLength)) + } + attr.Value = Truncate(attr.Value, MaxAttributeLength) + res = append(res, attr) + } + + return res +} + +// utf16Len is the length of s in UTF-16 code units, i.e. what String.length() gives in Java. +// Bytes that aren't valid UTF-8 count as one unit each: encoding/json sends each as U+FFFD. +func utf16Len(s string) int { + n := 0 + for _, r := range s { + n += utf16Width(r) + } + + return n +} + +// utf16Prefix returns the longest prefix of s that takes at most limit UTF-16 code units +// and ends at a character boundary. +func utf16Prefix(s string, limit int) string { + n := 0 + for i, r := range s { + n += utf16Width(r) + if n > limit { + return s[:i] + } + } + + return s +} + +func utf16Width(r rune) int { + const firstSupplementary = 0x10000 + if r >= firstSupplementary { + return 2 //nolint:mnd // a surrogate pair + } + + return 1 +} diff --git a/pkg/gorp/limits_test.go b/pkg/gorp/limits_test.go new file mode 100644 index 0000000..31252b2 --- /dev/null +++ b/pkg/gorp/limits_test.go @@ -0,0 +1,214 @@ +package gorp + +import ( + "strings" + "testing" + "unicode/utf16" + "unicode/utf8" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/reportportal/goRP/v5/pkg/openapi" +) + +// javaLength is String.length() of Java, computed independently of the code under test +func javaLength(s string) int { + return len(utf16.Encode([]rune(s))) +} + +func TestTruncate(t *testing.T) { + t.Parallel() + + const emoji = "πŸ˜€" // U+1F600: 4 bytes in UTF-8, a surrogate pair (2 units) in UTF-16 + + tests := []struct { + name string + in string + limit int + want string + }{ + {name: "empty", in: "", limit: 10, want: ""}, + {name: "shorter than the limit", in: "abc", limit: 10, want: "abc"}, + {name: "exactly the limit", in: "abcdefghij", limit: 10, want: "abcdefghij"}, + {name: "one over the limit", in: "abcdefghijk", limit: 10, want: "abcdefg..."}, + {name: "zero limit", in: "abc", limit: 0, want: ""}, + {name: "negative limit", in: "abc", limit: -1, want: ""}, + { + name: "limit of the mark size has no room for the mark", + in: "abcdef", + limit: 3, + want: "abc", + }, + {name: "limit one above the mark size", in: "abcdef", limit: 4, want: "a..."}, + // 3 bytes each in UTF-8 but one UTF-16 unit: byte length must not trigger a cut + { + name: "BMP characters count as one", + in: strings.Repeat("я", 10), + limit: 10, + want: strings.Repeat("я", 10), + }, + { + name: "BMP characters are cut by units", + in: strings.Repeat("θͺž", 11), + limit: 10, + want: strings.Repeat("θͺž", 7) + "...", + }, + // 5 emoji = 10 units: fits + { + name: "emoji count as two", + in: strings.Repeat(emoji, 5), + limit: 10, + want: strings.Repeat(emoji, 5), + }, + // 6 emoji = 12 units, budget 7 units: 3 emoji (6 units), the 4th would be split + { + name: "a surrogate pair is not split", + in: strings.Repeat(emoji, 6), + limit: 10, + want: strings.Repeat(emoji, 3) + "...", + }, + { + name: "odd budget with mixed text", + in: "ab" + strings.Repeat(emoji, 5), + limit: 10, + want: "ab" + emoji + emoji + "...", + }, + { + name: "no room for the mark and a pair at the cut", + in: "a" + emoji + "b", + limit: 2, + want: "a", + }, + { + name: "invalid UTF-8 counts as one unit per byte", + in: "ab\xff\xfecdef", + limit: 7, + want: "ab\xff\xfe...", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got := Truncate(tt.in, tt.limit) + assert.Equal(t, tt.want, got) + assert.LessOrEqual(t, javaLength(got), max(tt.limit, 0)) + if utf8.ValidString(tt.in) { + assert.True(t, utf8.ValidString(got), "the cut must not split a character") + } + }) + } +} + +func TestTruncateAtServerLimits(t *testing.T) { + t.Parallel() + + for _, limit := range []int{MaxLaunchNameLength, MaxItemNameLength, MaxDescriptionLength, MaxAttributeLength} { + for _, filler := range []string{"a", "я", "πŸ˜€", "aπŸ˜€"} { + long := strings.Repeat(filler, limit+1) + got := Truncate(long, limit) + assert.LessOrEqual(t, javaLength(got), limit) + // at most one unit is lost to an unsplittable pair + assert.GreaterOrEqual(t, javaLength(got), limit-1) + assert.True(t, strings.HasSuffix(got, "...")) + assert.True(t, utf8.ValidString(got)) + assert.True(t, strings.HasPrefix(long, strings.TrimSuffix(got, "..."))) + + fits := strings.Repeat("a", limit) + assert.Equal(t, fits, Truncate(fits, limit)) + } + } +} + +func TestBoundedID(t *testing.T) { + t.Parallel() + + short := "pkg/path.TestName" + assert.Equal(t, short, BoundedID(short, MaxTestCaseIDLength)) + exact := strings.Repeat("x", MaxTestCaseIDLength) + assert.Equal(t, exact, BoundedID(exact, MaxTestCaseIDLength)) + assert.Empty(t, BoundedID("abc", 0)) + + common := strings.Repeat("x", 2000) + a := BoundedID(common+"a", MaxTestCaseIDLength) + b := BoundedID(common+"b", MaxTestCaseIDLength) + assert.Len(t, a, MaxTestCaseIDLength) + assert.NotEqual(t, a, b, "IDs that differ after the cut must stay different") + assert.Equal(t, a, BoundedID(common+"a", MaxTestCaseIDLength), "the result must be stable") + assert.Equal(t, strings.Repeat("x", 1007), a[:1007]) + assert.Regexp(t, `^~[0-9a-f]{16}$`, a[1007:]) +} + +// knownHashOf30A is the beginning of `printf %s aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | shasum -a 256` +const knownHashOf30A = "3a54fc0cbc0b0ef4" + +// The result is a contract: a change would break the history of every test with a long ID. +func TestBoundedIDKnownValue(t *testing.T) { + t.Parallel() + + got := BoundedID(strings.Repeat("a", 30), 20) + require.Len(t, got, 20) + assert.Equal(t, "aaa~"+knownHashOf30A, got) +} + +func TestBoundedIDCountsUTF16(t *testing.T) { + t.Parallel() + + // 600 emoji are 2400 bytes but 1200 units: over the limit of 1024 + id := strings.Repeat("πŸ˜€", 600) + got := BoundedID(id, MaxUniqueIDLength) + // budget 1024-17 = 1007 units: 503 emoji (1006 units), the next one would be split + assert.Equal(t, strings.Repeat("πŸ˜€", 503), got[:strings.Index(got, "~")]) + assert.Equal(t, 1006+17, javaLength(got)) + assert.True(t, utf8.ValidString(got)) + + // 1000 three-byte characters are 3000 bytes but 1000 units: within the limit, untouched + bmp := strings.Repeat("θͺž", 1000) + assert.Equal(t, bmp, BoundedID(bmp, MaxUniqueIDLength)) +} + +func TestBoundedIDTinyLimit(t *testing.T) { + t.Parallel() + + id := strings.Repeat("a", 30) + assert.Equal(t, knownHashOf30A[:5], BoundedID(id, 5)) + assert.Equal(t, knownHashOf30A, BoundedID(id, 16)) + assert.Equal(t, knownHashOf30A, BoundedID(id, 17)) + assert.Equal(t, "a~"+knownHashOf30A, BoundedID(id, 18)) +} + +func TestTruncateAttributes(t *testing.T) { + t.Parallel() + + assert.Nil(t, TruncateAttributes(nil)) + assert.Empty(t, TruncateAttributes([]openapi.ItemAttributesRQ{})) + + longKey := strings.Repeat("k", 200) + longValue := strings.Repeat("πŸ˜€", 100) // 200 units + in := []openapi.ItemAttributesRQ{ + {Key: openapi.PtrString("os"), Value: "linux"}, + {Value: "no-key", System: openapi.PtrBool(true)}, + {Key: openapi.PtrString(longKey), Value: longValue}, + } + got := TruncateAttributes(in) + + require.Len(t, got, 3) + assert.Equal(t, in[0], got[0]) + assert.Equal(t, in[1], got[1]) + assert.Equal(t, strings.Repeat("k", 125)+"...", *got[2].Key) + // budget 125 units: 62 emoji (124 units) + assert.Equal(t, strings.Repeat("πŸ˜€", 62)+"...", got[2].Value) + // the input stays as it was + assert.Equal(t, longKey, *in[2].Key) + assert.Equal(t, longValue, in[2].Value) + + many := make([]openapi.ItemAttributesRQ, MaxAttributes+10) + for i := range many { + many[i].Value = strings.Repeat("v", i+1) + } + got = TruncateAttributes(many) + require.Len(t, got, MaxAttributes) + assert.Equal(t, "v", got[0].Value) + assert.Equal(t, strings.Repeat("v", 125)+"...", got[MaxAttributes-1].Value) +}