Skip to content

The only tool you need to know what is happening and how to fix it.

feat(profiling): OTLP-compliant profiles ingestion endpoint (PR 2) (#214)

FrameAutomata8c6ef547b05e
diff --git a/CLAUDE.md b/CLAUDE.md
index ddd5f32f..d754fa1d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -539,6 +539,7 @@ backend/
| POST | `/api/otel/v1/traces` | Client | OTLP/HTTP trace ingestion |
| POST | `/api/otel/v1/metrics` | Client | OTLP/HTTP metric ingestion |
| POST | `/api/otel/v1/logs` | Client | OTLP/HTTP log ingestion |
+| POST | `/api/otel/v1development/profiles` | Client | OTLP/HTTP profile ingestion (development signal) |
**Auth & Registration**
| Method | Endpoint | Auth | Purpose |
diff --git a/backend/app/controllers/otelcontrollers/codec.go b/backend/app/controllers/otelcontrollers/codec.go
index 0f6585e2..5eb3d029 100644
--- a/backend/app/controllers/otelcontrollers/codec.go
+++ b/backend/app/controllers/otelcontrollers/codec.go
@@ -10,6 +10,7 @@ import (
"github.com/gin-gonic/gin"
collogspb "go.opentelemetry.io/proto/otlp/collector/logs/v1"
colmetricspb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
+ colprofilespb "go.opentelemetry.io/proto/otlp/collector/profiles/v1development"
coltracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
@@ -93,6 +94,36 @@ func writeMetricsResponse(c *gin.Context) {
}
}
+func decodeProfilesPayload(c *gin.Context) ([]byte, int, error) {
+ body, err := readBody(c)
+ if err != nil {
+ return nil, 0, err
+ }
+ if isProtobuf(c) {
+ return body, len(body), nil
+ }
+ req := &colprofilespb.ExportProfilesServiceRequest{}
+ if err := protojson.Unmarshal(body, req); err != nil {
+ return nil, 0, fmt.Errorf("failed to unmarshal JSON: %w", err)
+ }
+ binary, err := proto.Marshal(req)
+ if err != nil {
+ return nil, 0, fmt.Errorf("failed to re-encode profiles request: %w", err)
+ }
+ return binary, len(body), nil
+}
+
+func writeProfilesResponse(c *gin.Context) {
+ resp := &colprofilespb.ExportProfilesServiceResponse{}
+ if isProtobuf(c) {
+ data, _ := proto.Marshal(resp)
+ c.Data(http.StatusOK, "application/x-protobuf", data)
+ } else {
+ data, _ := protojson.Marshal(resp)
+ c.Data(http.StatusOK, "application/json", data)
+ }
+}
+
func decodeLogsRequest(c *gin.Context) (*collogspb.ExportLogsServiceRequest, int, error) {
body, err := readBody(c)
if err != nil {
diff --git a/backend/app/controllers/otelcontrollers/otel.controller.go b/backend/app/controllers/otelcontrollers/otel.controller.go
index 56d0a6b5..ff2cd978 100644
--- a/backend/app/controllers/otelcontrollers/otel.controller.go
+++ b/backend/app/controllers/otelcontrollers/otel.controller.go
@@ -12,6 +12,7 @@ import (
"github.com/tracewayapp/traceway/backend/app/middleware"
"github.com/tracewayapp/traceway/backend/app/models"
"github.com/tracewayapp/traceway/backend/app/monitoring"
+ "github.com/tracewayapp/traceway/backend/app/profiling"
"github.com/tracewayapp/traceway/backend/app/repositories"
"github.com/tracewayapp/traceway/backend/app/services"
"github.com/tracewayapp/traceway/backend/app/storage"
@@ -266,3 +267,64 @@ func (o otelController) ExportLogs(c *gin.Context) {
writeLogsResponse(c)
}
+
+func (o otelController) ExportProfiles(c *gin.Context) {
+ monitoring.IngestStarted()
+ defer monitoring.IngestFinished()
+
+ projectId, err := middleware.GetProjectId(c)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("UseClientAuth middleware must be applied: %w", err))
+ return
+ }
+
+ if project, exists := c.Get(middleware.ProjectContextKey); exists {
+ if p, ok := project.(*models.Project); ok && p.OrganizationId != nil {
+ if attrs := traceway.GetAttributesFromContext(c); attrs != nil {
+ attrs.SetTag("organization_id", fmt.Sprintf("%d", *p.OrganizationId))
+ }
+ if !hooks.CanReport(*p.OrganizationId) {
+ monitoring.RecordRateLimited(*p.OrganizationId)
+ c.AbortWithStatus(http.StatusTooManyRequests)
+ return
+ }
+ }
+ }
+
+ payload, bodyBytes, err := decodeProfilesPayload(c)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+
+ convertStart := time.Now()
+ decoded, err := profiling.OTLPDecoder{}.Decode(profiling.IngestContext{
+ ProjectId: projectId,
+ ReceivedAt: time.Now().UTC(),
+ }, payload)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+ stacks, samples, profiles := profiling.BuildRows(projectId, decoded)
+ convertMs := msSince(convertStart)
+
+ insertStart := time.Now()
+ if err := repositories.ProfileRepository.InsertStacksAsync(c, stacks); err != nil {
+ c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL profiling stacks: %w", err))
+ return
+ }
+ if err := repositories.ProfileRepository.InsertSamplesAsync(c, samples); err != nil {
+ c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL profiling samples: %w", err))
+ return
+ }
+ if err := repositories.ProfileRepository.InsertProfilesAsync(c, profiles); err != nil {
+ c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL profiles: %w", err))
+ return
+ }
+ insertMs := msSince(insertStart)
+
+ monitoring.RecordIngestBatch(monitoring.SignalProfiles, "profiling_samples", convertMs, insertMs, len(samples), bodyBytes)
+
+ writeProfilesResponse(c)
+}
diff --git a/backend/app/controllers/otelcontrollers/profiles_codec_test.go b/backend/app/controllers/otelcontrollers/profiles_codec_test.go
new file mode 100644
index 00000000..1ebd630f
--- /dev/null
+++ b/backend/app/controllers/otelcontrollers/profiles_codec_test.go
@@ -0,0 +1,148 @@
+package otelcontrollers
+
+import (
+ "bytes"
+ "compress/gzip"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ colprofilespb "go.opentelemetry.io/proto/otlp/collector/profiles/v1development"
+ profilespb "go.opentelemetry.io/proto/otlp/profiles/v1development"
+ "google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/proto"
+)
+
+func sampleProfilesRequest() *colprofilespb.ExportProfilesServiceRequest {
+ return &colprofilespb.ExportProfilesServiceRequest{
+ Dictionary: &profilespb.ProfilesDictionary{
+ StringTable: []string{"", "main.main", "cpu", "nanoseconds"},
+ FunctionTable: []*profilespb.Function{{}, {NameStrindex: 1}},
+ LocationTable: []*profilespb.Location{{}, {Lines: []*profilespb.Line{{FunctionIndex: 1}}}},
+ StackTable: []*profilespb.Stack{{}, {LocationIndices: []int32{1}}},
+ },
+ ResourceProfiles: []*profilespb.ResourceProfiles{{
+ ScopeProfiles: []*profilespb.ScopeProfiles{{
+ Profiles: []*profilespb.Profile{{
+ SampleType: &profilespb.ValueType{TypeStrindex: 2, UnitStrindex: 3},
+ Samples: []*profilespb.Sample{{StackIndex: 1, Values: []int64{100}}},
+ }},
+ }},
+ }},
+ }
+}
+
+func newProfilesCtx(t *testing.T, body []byte, contentType, contentEncoding string) *gin.Context {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ req := httptest.NewRequest("POST", "/otel/v1development/profiles", bytes.NewReader(body))
+ req.Header.Set("Content-Type", contentType)
+ if contentEncoding != "" {
+ req.Header.Set("Content-Encoding", contentEncoding)
+ }
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = req
+ return c
+}
+
+func assertDecodedMatches(t *testing.T, payload []byte) {
+ t.Helper()
+ got := &colprofilespb.ExportProfilesServiceRequest{}
+ if err := proto.Unmarshal(payload, got); err != nil {
+ t.Fatalf("returned payload is not valid protobuf: %v", err)
+ }
+ if !proto.Equal(got, sampleProfilesRequest()) {
+ t.Errorf("decoded payload does not match original request")
+ }
+}
+
+func TestDecodeProfilesPayload_Protobuf(t *testing.T) {
+ body, err := proto.Marshal(sampleProfilesRequest())
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ c := newProfilesCtx(t, body, "application/x-protobuf", "")
+ payload, n, err := decodeProfilesPayload(c)
+ if err != nil {
+ t.Fatalf("decodeProfilesPayload: %v", err)
+ }
+ if n != len(body) {
+ t.Errorf("reported body size = %d, want %d", n, len(body))
+ }
+ assertDecodedMatches(t, payload)
+}
+
+func TestDecodeProfilesPayload_ProtoJSON(t *testing.T) {
+ body, err := protojson.Marshal(sampleProfilesRequest())
+ if err != nil {
+ t.Fatalf("marshal json: %v", err)
+ }
+ c := newProfilesCtx(t, body, "application/json", "")
+ payload, _, err := decodeProfilesPayload(c)
+ if err != nil {
+ t.Fatalf("decodeProfilesPayload: %v", err)
+ }
+ assertDecodedMatches(t, payload)
+}
+
+func TestDecodeProfilesPayload_Gzip(t *testing.T) {
+ raw, err := proto.Marshal(sampleProfilesRequest())
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ var buf bytes.Buffer
+ gw := gzip.NewWriter(&buf)
+ if _, err := gw.Write(raw); err != nil {
+ t.Fatalf("gzip write: %v", err)
+ }
+ gw.Close()
+
+ c := newProfilesCtx(t, buf.Bytes(), "application/x-protobuf", "gzip")
+ payload, _, err := decodeProfilesPayload(c)
+ if err != nil {
+ t.Fatalf("decodeProfilesPayload: %v", err)
+ }
+ assertDecodedMatches(t, payload)
+}
+
+func TestWriteProfilesResponse_Protobuf(t *testing.T) {
+ rec := httptest.NewRecorder()
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/otel/v1development/profiles", nil)
+ c.Request.Header.Set("Content-Type", "application/x-protobuf")
+
+ writeProfilesResponse(c)
+
+ if rec.Code != 200 {
+ t.Fatalf("status = %d, want 200", rec.Code)
+ }
+ if ct := rec.Header().Get("Content-Type"); ct != "application/x-protobuf" {
+ t.Errorf("content-type = %q, want application/x-protobuf", ct)
+ }
+ resp := &colprofilespb.ExportProfilesServiceResponse{}
+ if err := proto.Unmarshal(rec.Body.Bytes(), resp); err != nil {
+ t.Errorf("response not valid protobuf ExportProfilesServiceResponse: %v", err)
+ }
+}
+
+func TestWriteProfilesResponse_JSON(t *testing.T) {
+ rec := httptest.NewRecorder()
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/otel/v1development/profiles", nil)
+ c.Request.Header.Set("Content-Type", "application/json")
+
+ writeProfilesResponse(c)
+
+ if rec.Code != 200 {
+ t.Fatalf("status = %d, want 200", rec.Code)
+ }
+ if ct := rec.Header().Get("Content-Type"); ct != "application/json" {
+ t.Errorf("content-type = %q, want application/json", ct)
+ }
+ resp := &colprofilespb.ExportProfilesServiceResponse{}
+ if err := protojson.Unmarshal(rec.Body.Bytes(), resp); err != nil {
+ t.Errorf("response not valid protojson ExportProfilesServiceResponse: %v", err)
+ }
+}
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index 43277914..9f612bad 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -36,9 +36,11 @@ func RegisterControllers(router *gin.RouterGroup) {
otelGroup.OPTIONS("/v1/traces", middleware.CORSReport)
otelGroup.OPTIONS("/v1/metrics", middleware.CORSReport)
otelGroup.OPTIONS("/v1/logs", middleware.CORSReport)
+ otelGroup.OPTIONS("/v1development/profiles", middleware.CORSReport)
otelGroup.POST("/v1/traces", middleware.CORSReport, middleware.UseClientAuth, otelcontrollers.OtelController.ExportTraces)
otelGroup.POST("/v1/metrics", middleware.CORSReport, middleware.UseClientAuth, otelcontrollers.OtelController.ExportMetrics)
otelGroup.POST("/v1/logs", middleware.CORSReport, middleware.UseClientAuth, otelcontrollers.OtelController.ExportLogs)
+ otelGroup.POST("/v1development/profiles", middleware.CORSReport, middleware.UseClientAuth, otelcontrollers.OtelController.ExportProfiles)
router.GET("/projects", middleware.UseAppAuth, ProjectController.ListProjects)
router.POST("/projects", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, ProjectController.CreateProject)
diff --git a/backend/app/monitoring/metrics.go b/backend/app/monitoring/metrics.go
index 220a4ef1..cef4fe22 100644
--- a/backend/app/monitoring/metrics.go
+++ b/backend/app/monitoring/metrics.go
@@ -8,10 +8,11 @@ import (
)
const (
- SignalTraces = "traces"
- SignalMetrics = "metrics"
- SignalLogs = "logs"
- SignalNative = "native"
+ SignalTraces = "traces"
+ SignalMetrics = "metrics"
+ SignalLogs = "logs"
+ SignalProfiles = "profiles"
+ SignalNative = "native"
)
var inFlightIngest atomic.Int64
diff --git a/backend/app/profiling/model.go b/backend/app/profiling/model.go
index 61e1e950..5e7c22c5 100644
--- a/backend/app/profiling/model.go
+++ b/backend/app/profiling/model.go
@@ -3,8 +3,6 @@ package profiling
import (
"hash/fnv"
"time"
-
- "github.com/google/uuid"
)
const (
@@ -31,7 +29,6 @@ type Sample struct {
}
type Meta struct {
- ProfileId uuid.UUID
ServiceName string
Start time.Time
End time.Time
@@ -56,3 +53,9 @@ func HashFrames(frames []string) uint64 {
}
return h.Sum64()
}
+
+func reverseInPlace(s []string) {
+ for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
+ s[i], s[j] = s[j], s[i]
+ }
+}
diff --git a/backend/app/profiling/otlp_decoder.go b/backend/app/profiling/otlp_decoder.go
new file mode 100644
index 00000000..f73908dc
--- /dev/null
+++ b/backend/app/profiling/otlp_decoder.go
@@ -0,0 +1,183 @@
+package profiling
+
+import (
+ "fmt"
+ "time"
+
+ colprofilespb "go.opentelemetry.io/proto/otlp/collector/profiles/v1development"
+ commonpb "go.opentelemetry.io/proto/otlp/common/v1"
+ profilespb "go.opentelemetry.io/proto/otlp/profiles/v1development"
+ "google.golang.org/protobuf/proto"
+)
+
+type OTLPDecoder struct{}
+
+func (OTLPDecoder) Decode(ctx IngestContext, payload []byte) ([]Decoded, error) {
+ req := &colprofilespb.ExportProfilesServiceRequest{}
+ if err := proto.Unmarshal(payload, req); err != nil {
+ return nil, fmt.Errorf("profiling: unmarshal otlp profiles: %w", err)
+ }
+ if req.Dictionary == nil {
+ return nil, nil
+ }
+ resolver := newStackResolver(req.Dictionary)
+
+ var out []Decoded
+ for _, rp := range req.ResourceProfiles {
+ serviceName := ctx.DefaultServiceName
+ if rp.Resource != nil {
+ if sn := resourceServiceName(rp.Resource.Attributes); sn != "" {
+ serviceName = sn
+ }
+ }
+ for _, sp := range rp.ScopeProfiles {
+ for _, p := range sp.Profiles {
+ if decoded, ok := decodeProfile(ctx, serviceName, resolver, p); ok {
+ out = append(out, decoded)
+ }
+ }
+ }
+ }
+ return out, nil
+}
+
+func decodeProfile(ctx IngestContext, serviceName string, resolver *stackResolver, p *profilespb.Profile) (Decoded, bool) {
+ if p.SampleType == nil {
+ return Decoded{}, false
+ }
+ internalType, ok := keptSampleTypes[resolver.stringAt(p.SampleType.TypeStrindex)]
+ if !ok {
+ return Decoded{}, false
+ }
+
+ start := ctx.ReceivedAt
+ if p.TimeUnixNano > 0 {
+ start = time.Unix(0, int64(p.TimeUnixNano)).UTC()
+ }
+ end := start
+ if dur := int64(p.DurationNano); dur > 0 {
+ end = start.Add(time.Duration(dur))
+ }
+
+ values := make(map[uint64]int64)
+ stacks := make(map[uint64][]string)
+ for _, s := range p.Samples {
+ rs := resolver.lookup(s.StackIndex)
+ if len(rs.frames) == 0 {
+ continue
+ }
+ var v int64
+ if len(s.Values) == 0 {
+ v = int64(len(s.TimestampsUnixNano))
+ } else {
+ for _, val := range s.Values {
+ v += val
+ }
+ }
+ if v == 0 {
+ continue
+ }
+ values[rs.hash] += v
+ stacks[rs.hash] = rs.frames
+ }
+
+ decoded := Decoded{Meta: Meta{
+ ServiceName: serviceName,
+ ServerName: ctx.ServerName,
+ AppVersion: ctx.AppVersion,
+ Start: start,
+ End: end,
+ }}
+ decoded.Stacks = make([]Stack, 0, len(stacks))
+ decoded.Samples = make([]Sample, 0, len(values))
+ for hash, frames := range stacks {
+ decoded.Stacks = append(decoded.Stacks, Stack{Hash: hash, Frames: frames})
+ }
+ for hash, v := range values {
+ decoded.Samples = append(decoded.Samples, Sample{Type: internalType, StackHash: hash, Value: v})
+ }
+ return decoded, true
+}
+
+func resourceServiceName(attrs []*commonpb.KeyValue) string {
+ for _, kv := range attrs {
+ if kv.Key == "service.name" && kv.Value != nil {
+ if sv, ok := kv.Value.Value.(*commonpb.AnyValue_StringValue); ok {
+ return sv.StringValue
+ }
+ }
+ }
+ return ""
+}
+
+type resolvedStack struct {
+ frames []string
+ hash uint64
+}
+
+type stackResolver struct {
+ dict *profilespb.ProfilesDictionary
+ cache map[int32]resolvedStack
+}
+
+func newStackResolver(dict *profilespb.ProfilesDictionary) *stackResolver {
+ return &stackResolver{dict: dict, cache: make(map[int32]resolvedStack)}
+}
+
+func (r *stackResolver) stringAt(i int32) string {
+ if i < 0 || int(i) >= len(r.dict.StringTable) {
+ return ""
+ }
+ return r.dict.StringTable[i]
+}
+
+func (r *stackResolver) lookup(stackIndex int32) resolvedStack {
+ if cached, ok := r.cache[stackIndex]; ok {
+ return cached
+ }
+ frames := r.resolve(stackIndex)
+ rs := resolvedStack{frames: frames}
+ if len(frames) > 0 {
+ rs.hash = HashFrames(frames)
+ }
+ r.cache[stackIndex] = rs
+ return rs
+}
+
+func (r *stackResolver) resolve(stackIndex int32) []string {
+ if stackIndex <= 0 || int(stackIndex) >= len(r.dict.StackTable) {
+ return nil
+ }
+ stack := r.dict.StackTable[stackIndex]
+ if stack == nil {
+ return nil
+ }
+ var leafToRoot []string
+ for _, locIdx := range stack.LocationIndices {
+ if locIdx <= 0 || int(locIdx) >= len(r.dict.LocationTable) {
+ continue
+ }
+ loc := r.dict.LocationTable[locIdx]
+ if loc == nil {
+ continue
+ }
+ for _, line := range loc.Lines {
+ if name := r.functionName(line.FunctionIndex); name != "" {
+ leafToRoot = append(leafToRoot, name)
+ }
+ }
+ }
+ reverseInPlace(leafToRoot)
+ return leafToRoot
+}
+
+func (r *stackResolver) functionName(funcIndex int32) string {
+ if funcIndex <= 0 || int(funcIndex) >= len(r.dict.FunctionTable) {
+ return ""
+ }
+ fn := r.dict.FunctionTable[funcIndex]
+ if fn == nil {
+ return ""
+ }
+ return r.stringAt(fn.NameStrindex)
+}
diff --git a/backend/app/profiling/otlp_decoder_test.go b/backend/app/profiling/otlp_decoder_test.go
new file mode 100644
index 00000000..43560753
--- /dev/null
+++ b/backend/app/profiling/otlp_decoder_test.go
@@ -0,0 +1,414 @@
+package profiling
+
+import (
+ "math"
+ "testing"
+ "time"
+
+ "github.com/google/pprof/profile"
+ commonpb "go.opentelemetry.io/proto/otlp/common/v1"
+ colprofilespb "go.opentelemetry.io/proto/otlp/collector/profiles/v1development"
+ profilespb "go.opentelemetry.io/proto/otlp/profiles/v1development"
+ resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
+ "google.golang.org/protobuf/proto"
+)
+
+type otlpBuilder struct {
+ serviceName string
+ strings []string
+ functions []*profilespb.Function
+ locations []*profilespb.Location
+ stacks []*profilespb.Stack
+ profiles []*profilespb.Profile
+}
+
+func newOTLPBuilder() *otlpBuilder {
+ return &otlpBuilder{
+ strings: []string{""},
+ functions: []*profilespb.Function{{}},
+ locations: []*profilespb.Location{{}},
+ stacks: []*profilespb.Stack{{}},
+ }
+}
+
+func (b *otlpBuilder) str(s string) int32 {
+ for i, existing := range b.strings {
+ if existing == s {
+ return int32(i)
+ }
+ }
+ b.strings = append(b.strings, s)
+ return int32(len(b.strings) - 1)
+}
+
+func (b *otlpBuilder) fn(name string) int32 {
+ idx := int32(len(b.functions))
+ b.functions = append(b.functions, &profilespb.Function{
+ NameStrindex: b.str(name),
+ SystemNameStrindex: b.str(name),
+ })
+ return idx
+}
+
+func (b *otlpBuilder) loc(fnIdx int32) int32 {
+ idx := int32(len(b.locations))
+ b.locations = append(b.locations, &profilespb.Location{
+ Lines: []*profilespb.Line{{FunctionIndex: fnIdx}},
+ })
+ return idx
+}
+
+func (b *otlpBuilder) frameStack(rootFirst ...string) int32 {
+ var locsLeafFirst []int32
+ for i := len(rootFirst) - 1; i >= 0; i-- {
+ locsLeafFirst = append(locsLeafFirst, b.loc(b.fn(rootFirst[i])))
+ }
+ idx := int32(len(b.stacks))
+ b.stacks = append(b.stacks, &profilespb.Stack{LocationIndices: locsLeafFirst})
+ return idx
+}
+
+func (b *otlpBuilder) inlinedStack(rootFirst ...string) int32 {
+ var lines []*profilespb.Line
+ for i := len(rootFirst) - 1; i >= 0; i-- {
+ lines = append(lines, &profilespb.Line{FunctionIndex: b.fn(rootFirst[i])})
+ }
+ locIdx := int32(len(b.locations))
+ b.locations = append(b.locations, &profilespb.Location{Lines: lines})
+ idx := int32(len(b.stacks))
+ b.stacks = append(b.stacks, &profilespb.Stack{LocationIndices: []int32{locIdx}})
+ return idx
+}
+
+func (b *otlpBuilder) profile(typeName, unit string, timeNanos, durNanos uint64, samples ...*profilespb.Sample) {
+ b.profiles = append(b.profiles, &profilespb.Profile{
+ SampleType: &profilespb.ValueType{TypeStrindex: b.str(typeName), UnitStrindex: b.str(unit)},
+ TimeUnixNano: timeNanos,
+ DurationNano: durNanos,
+ Samples: samples,
+ })
+}
+
+func (b *otlpBuilder) build(t *testing.T) []byte {
+ t.Helper()
+ var res *resourcepb.Resource
+ if b.serviceName != "" {
+ res = &resourcepb.Resource{Attributes: []*commonpb.KeyValue{{
+ Key: "service.name",
+ Value: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: b.serviceName}},
+ }}}
+ }
+ req := &colprofilespb.ExportProfilesServiceRequest{
+ Dictionary: &profilespb.ProfilesDictionary{
+ StringTable: b.strings,
+ FunctionTable: b.functions,
+ LocationTable: b.locations,
+ StackTable: b.stacks,
+ },
+ ResourceProfiles: []*profilespb.ResourceProfiles{{
+ Resource: res,
+ ScopeProfiles: []*profilespb.ScopeProfiles{{
+ Profiles: b.profiles,
+ }},
+ }},
+ }
+ data, err := proto.Marshal(req)
+ if err != nil {
+ t.Fatalf("marshal export request: %v", err)
+ }
+ return data
+}
+
+func otlpSample(stackIdx int32, value int64) *profilespb.Sample {
+ return &profilespb.Sample{StackIndex: stackIdx, Values: []int64{value}}
+}
+
+func decodeOTLPAll(t *testing.T, payload []byte) []Decoded {
+ t.Helper()
+ out, err := OTLPDecoder{}.Decode(testIngest, payload)
+ if err != nil {
+ t.Fatalf("OTLPDecoder.Decode error: %v", err)
+ }
+ return out
+}
+
+func flattenStacks(ds []Decoded) map[uint64][]string {
+ out := map[uint64][]string{}
+ for _, d := range ds {
+ for _, s := range d.Stacks {
+ out[s.Hash] = s.Frames
+ }
+ }
+ return out
+}
+
+func flattenSamples(ds []Decoded) map[sampleKey]int64 {
+ out := map[sampleKey]int64{}
+ for _, d := range ds {
+ for _, s := range d.Samples {
+ out[sampleKey{typ: s.Type, stackHash: s.StackHash}] += s.Value
+ }
+ }
+ return out
+}
+
+func TestOTLPDecoder_CPU_ExplodesDistinctStacks(t *testing.T) {
+ b := newOTLPBuilder()
+ b.serviceName = "checkout"
+ sWork := b.frameStack("main.main", "main.work")
+ sIdle := b.frameStack("main.main", "main.idle")
+ b.profile("cpu", "nanoseconds", 1_700_000_000_000_000_000, 5_000_000_000,
+ otlpSample(sWork, 300), otlpSample(sIdle, 100))
+
+ out := decodeOTLPAll(t, b.build(t))
+ stacks := flattenStacks(out)
+ samples := flattenSamples(out)
+
+ if len(stacks) != 2 {
+ t.Fatalf("expected 2 unique stacks, got %d", len(stacks))
+ }
+ if len(samples) != 2 {
+ t.Fatalf("expected 2 cpu samples, got %d", len(samples))
+ }
+
+ wantWork := HashFrames([]string{"main.main", "main.work"})
+ wantIdle := HashFrames([]string{"main.main", "main.idle"})
+ if samples[sampleKey{TypeCPUNanos, wantWork}] != 300 {
+ t.Errorf("main->work cpu = %d, want 300", samples[sampleKey{TypeCPUNanos, wantWork}])
+ }
+ if samples[sampleKey{TypeCPUNanos, wantIdle}] != 100 {
+ t.Errorf("main->idle cpu = %d, want 100", samples[sampleKey{TypeCPUNanos, wantIdle}])
+ }
+ if got := stacks[wantWork]; len(got) != 2 || got[0] != "main.main" || got[1] != "main.work" {
+ t.Errorf("frames = %v, want [main.main main.work] (root-first)", got)
+ }
+}
+
+func TestOTLPDecoder_DedupesIdenticalStacks(t *testing.T) {
+ b := newOTLPBuilder()
+ b.serviceName = "checkout"
+ s := b.frameStack("main.main", "main.work")
+ b.profile("cpu", "nanoseconds", 1_700_000_000_000_000_000, 1_000_000_000,
+ otlpSample(s, 200), otlpSample(s, 50))
+
+ out := decodeOTLPAll(t, b.build(t))
+ stacks := flattenStacks(out)
+ samples := flattenSamples(out)
+
+ if len(stacks) != 1 {
+ t.Errorf("expected 1 unique stack, got %d", len(stacks))
+ }
+ if len(samples) != 1 {
+ t.Fatalf("expected 1 deduped sample, got %d", len(samples))
+ }
+ want := HashFrames([]string{"main.main", "main.work"})
+ if samples[sampleKey{TypeCPUNanos, want}] != 250 {
+ t.Errorf("summed value = %d, want 250", samples[sampleKey{TypeCPUNanos, want}])
+ }
+}
+
+func TestOTLPDecoder_Heap_KeepsSpaceTypesOnly(t *testing.T) {
+ b := newOTLPBuilder()
+ b.serviceName = "checkout"
+ s := b.frameStack("main.main", "main.allocate")
+ b.profile("inuse_space", "bytes", 1_700_000_000_000_000_000, 0, otlpSample(s, 2048))
+ b.profile("alloc_space", "bytes", 1_700_000_000_000_000_000, 0, otlpSample(s, 4096))
+ b.profile("inuse_objects", "count", 1_700_000_000_000_000_000, 0, otlpSample(s, 2))
+
+ out := decodeOTLPAll(t, b.build(t))
+ samples := flattenSamples(out)
+
+ want := HashFrames([]string{"main.main", "main.allocate"})
+ if samples[sampleKey{TypeHeapInuseSpace, want}] != 2048 {
+ t.Errorf("inuse_space = %d, want 2048", samples[sampleKey{TypeHeapInuseSpace, want}])
+ }
+ if samples[sampleKey{TypeHeapAllocSpace, want}] != 4096 {
+ t.Errorf("alloc_space = %d, want 4096", samples[sampleKey{TypeHeapAllocSpace, want}])
+ }
+ for k := range samples {
+ if k.typ != TypeHeapInuseSpace && k.typ != TypeHeapAllocSpace {
+ t.Errorf("unexpected sample type emitted: %q", k.typ)
+ }
+ }
+}
+
+func TestOTLPDecoder_UnsupportedTypeYieldsNoSamples(t *testing.T) {
+ b := newOTLPBuilder()
+ b.serviceName = "checkout"
+ s := b.frameStack("main.main")
+ b.profile("goroutine", "count", 1_700_000_000_000_000_000, 0, otlpSample(s, 7))
+
+ out := decodeOTLPAll(t, b.build(t))
+ if got := len(flattenSamples(out)); got != 0 {
+ t.Errorf("expected 0 samples for unsupported type, got %d", got)
+ }
+}
+
+func TestOTLPDecoder_TimestampsOnlySampleCountsTimestamps(t *testing.T) {
+ b := newOTLPBuilder()
+ b.serviceName = "checkout"
+ s := b.frameStack("main.main", "main.work")
+ b.profile("cpu", "nanoseconds", 1_700_000_000_000_000_000, 1_000_000_000,
+ &profilespb.Sample{StackIndex: s, TimestampsUnixNano: []uint64{1, 2, 3}})
+
+ out := decodeOTLPAll(t, b.build(t))
+ samples := flattenSamples(out)
+ want := HashFrames([]string{"main.main", "main.work"})
+ if samples[sampleKey{TypeCPUNanos, want}] != 3 {
+ t.Errorf("value = %d, want 3 (one per timestamp when Values is empty)", samples[sampleKey{TypeCPUNanos, want}])
+ }
+}
+
+func TestOTLPDecoder_HugeDurationDoesNotGoNegative(t *testing.T) {
+ b := newOTLPBuilder()
+ b.serviceName = "checkout"
+ start := uint64(1_700_000_000_000_000_000)
+ s := b.frameStack("main.main")
+ b.profile("cpu", "nanoseconds", start, math.MaxUint64, otlpSample(s, 100))
+
+ out := decodeOTLPAll(t, b.build(t))
+ if len(out) != 1 {
+ t.Fatalf("expected 1 decoded profile, got %d", len(out))
+ }
+ if out[0].Meta.End.Before(out[0].Meta.Start) {
+ t.Errorf("end %v is before start %v on overflowing duration", out[0].Meta.End, out[0].Meta.Start)
+ }
+}
+
+func TestOTLPDecoder_InlinedFramesExpand(t *testing.T) {
+ b := newOTLPBuilder()
+ b.serviceName = "checkout"
+ s := b.inlinedStack("fmt.Printf", "runtime.memmove")
+ b.profile("cpu", "nanoseconds", 1_700_000_000_000_000_000, 1_000_000_000, otlpSample(s, 100))
+
+ out := decodeOTLPAll(t, b.build(t))
+ stacks := flattenStacks(out)
+ want := HashFrames([]string{"fmt.Printf", "runtime.memmove"})
+ got, ok := stacks[want]
+ if !ok || len(got) != 2 || got[0] != "fmt.Printf" || got[1] != "runtime.memmove" {
+ t.Errorf("frames = %v, want [fmt.Printf runtime.memmove] (root-first within location)", got)
+ }
+}
+
+func TestOTLPDecoder_Metadata(t *testing.T) {
+ b := newOTLPBuilder()
+ b.serviceName = "orders"
+ start := uint64(1_700_000_000_000_000_000)
+ dur := uint64(30_000_000_000)
+ s := b.frameStack("main.main")
+ b.profile("cpu", "nanoseconds", start, dur, otlpSample(s, 100))
+
+ out := decodeOTLPAll(t, b.build(t))
+ if len(out) != 1 {
+ t.Fatalf("expected 1 decoded profile, got %d", len(out))
+ }
+ meta := out[0].Meta
+ if meta.ServiceName != "orders" {
+ t.Errorf("service name = %q, want orders (resource wins over default)", meta.ServiceName)
+ }
+ if meta.ServerName != "pod-abc" || meta.AppVersion != "1.2.3" {
+ t.Errorf("server/version not carried from ingest context: %+v", meta)
+ }
+ wantStart := time.Unix(0, int64(start)).UTC()
+ if !meta.Start.Equal(wantStart) {
+ t.Errorf("start = %v, want %v", meta.Start.UTC(), wantStart)
+ }
+ if !meta.End.Equal(wantStart.Add(30 * time.Second)) {
+ t.Errorf("end = %v, want start+30s", meta.End.UTC())
+ }
+}
+
+func TestOTLPDecoder_NoServiceNameFallsBackToDefault(t *testing.T) {
+ b := newOTLPBuilder()
+ s := b.frameStack("main.main")
+ b.profile("cpu", "nanoseconds", 1_700_000_000_000_000_000, 0, otlpSample(s, 100))
+
+ out := decodeOTLPAll(t, b.build(t))
+ if len(out) != 1 {
+ t.Fatalf("expected 1 decoded profile, got %d", len(out))
+ }
+ if out[0].Meta.ServiceName != testIngest.DefaultServiceName {
+ t.Errorf("service name = %q, want fallback %q", out[0].Meta.ServiceName, testIngest.DefaultServiceName)
+ }
+}
+
+func TestOTLPDecoder_NoTimestampFallsBackToReceivedAt(t *testing.T) {
+ b := newOTLPBuilder()
+ b.serviceName = "checkout"
+ s := b.frameStack("main.main")
+ b.profile("cpu", "nanoseconds", 0, 0, otlpSample(s, 100))
+
+ out := decodeOTLPAll(t, b.build(t))
+ if len(out) != 1 {
+ t.Fatalf("expected 1 decoded profile, got %d", len(out))
+ }
+ if !out[0].Meta.Start.Equal(testIngest.ReceivedAt) {
+ t.Errorf("start = %v, want fallback to ReceivedAt %v", out[0].Meta.Start, testIngest.ReceivedAt)
+ }
+}
+
+func TestOTLPDecoder_RejectsGarbage(t *testing.T) {
+ if _, err := (OTLPDecoder{}).Decode(testIngest, []byte("not a valid export request")); err == nil {
+ t.Fatalf("expected error decoding garbage, got nil")
+ }
+}
+
+func TestDecoderParity_PprofVsOTLP(t *testing.T) {
+ main := fn(1, "main.main", "main.go")
+ work := fn(2, "main.work", "work.go")
+ idle := fn(3, "main.idle", "idle.go")
+ lMain := loc(1, profile.Line{Function: main, Line: 10})
+ lWork := loc(2, profile.Line{Function: work, Line: 20})
+ lIdle := loc(3, profile.Line{Function: idle, Line: 30})
+ pprofSamples := []*profile.Sample{
+ {Location: []*profile.Location{lWork, lMain}, Value: []int64{1, 300}},
+ {Location: []*profile.Location{lIdle, lMain}, Value: []int64{1, 100}},
+ }
+ pprofBytes := cpuProfile(t, 1_700_000_000_000_000_000, 5_000_000_000, pprofSamples,
+ []*profile.Function{main, work, idle}, []*profile.Location{lMain, lWork, lIdle})
+
+ b := newOTLPBuilder()
+ b.serviceName = "checkout"
+ sWork := b.frameStack("main.main", "main.work")
+ sIdle := b.frameStack("main.main", "main.idle")
+ b.profile("cpu", "nanoseconds", 1_700_000_000_000_000_000, 5_000_000_000,
+ otlpSample(sWork, 300), otlpSample(sIdle, 100))
+
+ fromPprof := decodeOne(t, pprofBytes)
+ fromOTLP := decodeOTLPAll(t, b.build(t))
+
+ pprofStacks := flattenStacks([]Decoded{fromPprof})
+ otlpStacks := flattenStacks(fromOTLP)
+ if !stacksEqual(pprofStacks, otlpStacks) {
+ t.Errorf("stack rows differ:\npprof=%v\notlp=%v", pprofStacks, otlpStacks)
+ }
+
+ pprofSmpl := flattenSamples([]Decoded{fromPprof})
+ otlpSmpl := flattenSamples(fromOTLP)
+ if len(pprofSmpl) != len(otlpSmpl) {
+ t.Fatalf("sample count differs: pprof=%d otlp=%d", len(pprofSmpl), len(otlpSmpl))
+ }
+ for k, v := range pprofSmpl {
+ if otlpSmpl[k] != v {
+ t.Errorf("sample %+v: pprof=%d otlp=%d", k, v, otlpSmpl[k])
+ }
+ }
+}
+
+func stacksEqual(a, b map[uint64][]string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for h, fa := range a {
+ fb, ok := b[h]
+ if !ok || len(fa) != len(fb) {
+ return false
+ }
+ for i := range fa {
+ if fa[i] != fb[i] {
+ return false
+ }
+ }
+ }
+ return true
+}
diff --git a/backend/app/profiling/pprof_decoder.go b/backend/app/profiling/pprof_decoder.go
index f7228b03..05d579a4 100644
--- a/backend/app/profiling/pprof_decoder.go
+++ b/backend/app/profiling/pprof_decoder.go
@@ -6,7 +6,6 @@ import (
"time"
"github.com/google/pprof/profile"
- "github.com/google/uuid"
)
type PprofDecoder struct{}
@@ -34,7 +33,6 @@ func (PprofDecoder) Decode(ctx IngestContext, payload []byte) ([]Decoded, error)
}
meta := Meta{
- ProfileId: uuid.New(),
ServiceName: ctx.DefaultServiceName,
ServerName: ctx.ServerName,
AppVersion: ctx.AppVersion,
@@ -95,8 +93,6 @@ func rootFirstFrames(s *profile.Sample) []string {
leafToRoot = append(leafToRoot, line.Function.Name)
}
}
- for i, j := 0, len(leafToRoot)-1; i < j; i, j = i+1, j-1 {
- leafToRoot[i], leafToRoot[j] = leafToRoot[j], leafToRoot[i]
- }
+ reverseInPlace(leafToRoot)
return leafToRoot
}
diff --git a/backend/app/profiling/pprof_decoder_test.go b/backend/app/profiling/pprof_decoder_test.go
index 940826c3..59140ebf 100644
--- a/backend/app/profiling/pprof_decoder_test.go
+++ b/backend/app/profiling/pprof_decoder_test.go
@@ -253,9 +253,6 @@ func TestPprofDecoder_Metadata(t *testing.T) {
if !d.Meta.End.Equal(wantStart.Add(30 * time.Second)) {
t.Errorf("end = %v, want start+30s", d.Meta.End.UTC())
}
- if d.Meta.ProfileId == uuid.Nil {
- t.Errorf("expected a non-nil ProfileId")
- }
}
func TestPprofDecoder_DropsZeroValueSamples(t *testing.T) {
diff --git a/backend/app/profiling/rows.go b/backend/app/profiling/rows.go
new file mode 100644
index 00000000..4d522082
--- /dev/null
+++ b/backend/app/profiling/rows.go
@@ -0,0 +1,68 @@
+package profiling
+
+import (
+ "github.com/google/uuid"
+ "github.com/tracewayapp/traceway/backend/app/models"
+)
+
+func BuildRows(projectId uuid.UUID, decoded []Decoded) ([]models.ProfileStack, []models.ProfileSample, []models.Profile) {
+ var totalStacks, totalSamples int
+ for _, d := range decoded {
+ totalStacks += len(d.Stacks)
+ totalSamples += len(d.Samples)
+ }
+ stacks := make([]models.ProfileStack, 0, totalStacks)
+ samples := make([]models.ProfileSample, 0, totalSamples)
+ var profiles []models.Profile
+
+ for _, d := range decoded {
+ for _, s := range d.Stacks {
+ stacks = append(stacks, models.ProfileStack{
+ ProjectId: projectId,
+ ServiceName: d.Meta.ServiceName,
+ StackHash: s.Hash,
+ Stack: s.Frames,
+ LastSeen: d.Meta.End,
+ })
+ }
+
+ byType := make(map[string][]Sample)
+ for _, s := range d.Samples {
+ byType[s.Type] = append(byType[s.Type], s)
+ }
+
+ for typ, group := range byType {
+ profileId := uuid.New()
+ var total int64
+ for _, s := range group {
+ total += s.Value
+ samples = append(samples, models.ProfileSample{
+ ProjectId: projectId,
+ ProfileId: profileId,
+ ServiceName: d.Meta.ServiceName,
+ Type: typ,
+ Start: d.Meta.Start,
+ End: d.Meta.End,
+ StackHash: s.StackHash,
+ Value: s.Value,
+ ServerName: d.Meta.ServerName,
+ AppVersion: d.Meta.AppVersion,
+ })
+ }
+ profiles = append(profiles, models.Profile{
+ Id: profileId,
+ ProjectId: projectId,
+ RecordedAt: d.Meta.Start,
+ Duration: d.Meta.End.Sub(d.Meta.Start),
+ ServiceName: d.Meta.ServiceName,
+ ProfileType: typ,
+ SampleCount: uint64(len(group)),
+ TotalValue: total,
+ ServerName: d.Meta.ServerName,
+ AppVersion: d.Meta.AppVersion,
+ })
+ }
+ }
+
+ return stacks, samples, profiles
+}
diff --git a/backend/app/profiling/rows_test.go b/backend/app/profiling/rows_test.go
new file mode 100644
index 00000000..e953cc93
--- /dev/null
+++ b/backend/app/profiling/rows_test.go
@@ -0,0 +1,136 @@
+package profiling
+
+import (
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/tracewayapp/traceway/backend/app/models"
+)
+
+func profileByType(profiles []models.Profile, typ string) (models.Profile, bool) {
+ for _, p := range profiles {
+ if p.ProfileType == typ {
+ return p, true
+ }
+ }
+ return models.Profile{}, false
+}
+
+func TestBuildRows_SingleType(t *testing.T) {
+ projectId := uuid.New()
+ start := time.Unix(1_700_000_000, 0).UTC()
+ h1 := HashFrames([]string{"main.main", "main.work"})
+ h2 := HashFrames([]string{"main.main", "main.idle"})
+
+ d := Decoded{
+ Meta: Meta{
+ ServiceName: "checkout", ServerName: "pod-a", AppVersion: "1.2.3",
+ Start: start, End: start.Add(30 * time.Second),
+ },
+ Stacks: []Stack{
+ {Hash: h1, Frames: []string{"main.main", "main.work"}},
+ {Hash: h2, Frames: []string{"main.main", "main.idle"}},
+ },
+ Samples: []Sample{
+ {Type: TypeCPUNanos, StackHash: h1, Value: 300},
+ {Type: TypeCPUNanos, StackHash: h2, Value: 100},
+ },
+ }
+
+ stacks, samples, profiles := BuildRows(projectId, []Decoded{d})
+
+ if len(stacks) != 2 {
+ t.Fatalf("stacks = %d, want 2", len(stacks))
+ }
+ for _, s := range stacks {
+ if s.ProjectId != projectId || s.ServiceName != "checkout" {
+ t.Errorf("stack project/service wrong: %+v", s)
+ }
+ if !s.LastSeen.Equal(d.Meta.End) {
+ t.Errorf("stack LastSeen = %v, want %v", s.LastSeen, d.Meta.End)
+ }
+ }
+
+ if len(profiles) != 1 {
+ t.Fatalf("profiles = %d, want 1", len(profiles))
+ }
+ p := profiles[0]
+ if p.ProfileType != TypeCPUNanos || p.SampleCount != 2 || p.TotalValue != 400 {
+ t.Errorf("profile = (%s, count=%d, total=%d), want (cpu, 2, 400)", p.ProfileType, p.SampleCount, p.TotalValue)
+ }
+ if p.ServiceName != "checkout" || p.ServerName != "pod-a" || p.AppVersion != "1.2.3" {
+ t.Errorf("profile metadata not carried: %+v", p)
+ }
+ if !p.RecordedAt.Equal(start) || p.Duration != 30*time.Second {
+ t.Errorf("profile time = (%v, %v), want (%v, 30s)", p.RecordedAt, p.Duration, start)
+ }
+ if p.Id == uuid.Nil || p.ProjectId != projectId {
+ t.Errorf("profile id/project wrong: %+v", p)
+ }
+
+ if len(samples) != 2 {
+ t.Fatalf("samples = %d, want 2", len(samples))
+ }
+ for _, s := range samples {
+ if s.ProfileId != p.Id {
+ t.Errorf("sample ProfileId = %v, want %v", s.ProfileId, p.Id)
+ }
+ if s.Type != TypeCPUNanos || s.ProjectId != projectId || s.ServiceName != "checkout" {
+ t.Errorf("sample fields wrong: %+v", s)
+ }
+ if !s.Start.Equal(start) || !s.End.Equal(d.Meta.End) {
+ t.Errorf("sample time = (%v, %v), want (%v, %v)", s.Start, s.End, start, d.Meta.End)
+ }
+ }
+}
+
+func TestBuildRows_MultiTypeSplitsProfiles(t *testing.T) {
+ projectId := uuid.New()
+ start := time.Unix(1_700_000_000, 0).UTC()
+ h1 := HashFrames([]string{"main.main", "main.work"})
+
+ d := Decoded{
+ Meta: Meta{ServiceName: "checkout", Start: start, End: start},
+ Stacks: []Stack{{Hash: h1, Frames: []string{"main.main", "main.work"}}},
+ Samples: []Sample{
+ {Type: TypeCPUNanos, StackHash: h1, Value: 300},
+ {Type: TypeHeapInuseSpace, StackHash: h1, Value: 2048},
+ },
+ }
+
+ _, samples, profiles := BuildRows(projectId, []Decoded{d})
+
+ if len(profiles) != 2 {
+ t.Fatalf("profiles = %d, want 2 (one per type)", len(profiles))
+ }
+ cpu, ok := profileByType(profiles, TypeCPUNanos)
+ if !ok {
+ t.Fatalf("no cpu profile row")
+ }
+ heap, ok := profileByType(profiles, TypeHeapInuseSpace)
+ if !ok {
+ t.Fatalf("no heap profile row")
+ }
+ if cpu.Id == heap.Id {
+ t.Errorf("expected distinct ProfileIds per type, both = %v", cpu.Id)
+ }
+ if cpu.TotalValue != 300 || heap.TotalValue != 2048 {
+ t.Errorf("totals = (cpu=%d, heap=%d), want (300, 2048)", cpu.TotalValue, heap.TotalValue)
+ }
+
+ for _, s := range samples {
+ switch s.Type {
+ case TypeCPUNanos:
+ if s.ProfileId != cpu.Id {
+ t.Errorf("cpu sample linked to %v, want %v", s.ProfileId, cpu.Id)
+ }
+ case TypeHeapInuseSpace:
+ if s.ProfileId != heap.Id {
+ t.Errorf("heap sample linked to %v, want %v", s.ProfileId, heap.Id)
+ }
+ default:
+ t.Errorf("unexpected sample type %q", s.Type)
+ }
+ }
+}
diff --git a/backend/go.mod b/backend/go.mod
index cb48690a..26bc52e2 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -25,6 +25,8 @@ require (
go.opentelemetry.io/collector/processor v1.60.0
go.opentelemetry.io/collector/processor/processorhelper v0.154.0
go.opentelemetry.io/collector/processor/processortest v0.154.0
+ go.opentelemetry.io/proto/otlp/collector/profiles/v1development v0.3.0
+ go.opentelemetry.io/proto/otlp/profiles/v1development v0.3.0
go.tracewayapp.com v1.0.2
go.tracewayapp.com/tracewaygin v1.0.2
go.uber.org/zap v1.28.0
@@ -56,7 +58,7 @@ require (
github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect
github.com/googleapis/gax-go/v2 v2.15.0 // indirect
github.com/gorilla/mux v1.7.4 // indirect
- github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
+ github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
github.com/hashicorp/go-version v1.9.0 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect
@@ -148,7 +150,7 @@ require (
github.com/ugorji/go/codec v1.3.0 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
- go.opentelemetry.io/proto/otlp v1.9.0
+ go.opentelemetry.io/proto/otlp v1.10.0
go.uber.org/mock v0.5.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/arch v0.20.0 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index de86820f..28669b77 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -196,8 +196,8 @@ github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kX
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
-github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU=
-github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs=
+github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
+github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA=
github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
@@ -359,8 +359,12 @@ go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRk
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
-go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
-go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
+go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
+go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
+go.opentelemetry.io/proto/otlp/collector/profiles/v1development v0.3.0 h1:AWBLtJn3ajH399gyOuJdqPsC9w152x3xGVVO/UK3vyM=
+go.opentelemetry.io/proto/otlp/collector/profiles/v1development v0.3.0/go.mod h1:kCdbxyM9kfmv3v4ZQzZ2pACxoQ6lE0IsjP+UcZwQnr4=
+go.opentelemetry.io/proto/otlp/profiles/v1development v0.3.0 h1:ZQs05qo3Yh4KUHeVH6v89xErwmsvgA/cLX2/w5Ikp+k=
+go.opentelemetry.io/proto/otlp/profiles/v1development v0.3.0/go.mod h1:3iiRVKaCfVo0UI1ZaSMm5WbCBbINRqVlD9SUmvyBNrY=
go.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=
go.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=
go.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=