|
| 1 | +package perfinsights |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "strconv" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/ccoveille/go-safecast" |
| 10 | + "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors" |
| 11 | + "github.com/prometheus/client_golang/prometheus" |
| 12 | + "github.com/prometheus/client_golang/prometheus/promauto" |
| 13 | + "github.com/rs/zerolog/log" |
| 14 | + "go.opentelemetry.io/otel/trace" |
| 15 | + "google.golang.org/grpc" |
| 16 | + |
| 17 | + "github.com/authzed/ctxkey" |
| 18 | + "github.com/authzed/grpcutil" |
| 19 | + |
| 20 | + "github.com/authzed/spicedb/pkg/spiceerrors" |
| 21 | +) |
| 22 | + |
| 23 | +type APIShapeLabel string |
| 24 | + |
| 25 | +const ( |
| 26 | + ResourceTypeLabel APIShapeLabel = "resource_type" |
| 27 | + ResourceRelationLabel APIShapeLabel = "resource_relation" |
| 28 | + SubjectTypeLabel APIShapeLabel = "subject_type" |
| 29 | + SubjectRelationLabel APIShapeLabel = "subject_relation" |
| 30 | + NameLabel APIShapeLabel = "name" |
| 31 | + FilterLabel APIShapeLabel = "filter" |
| 32 | +) |
| 33 | + |
| 34 | +var allLabels = []string{ |
| 35 | + string(ResourceTypeLabel), |
| 36 | + string(ResourceRelationLabel), |
| 37 | + string(SubjectTypeLabel), |
| 38 | + string(SubjectRelationLabel), |
| 39 | + string(NameLabel), |
| 40 | + string(FilterLabel), |
| 41 | +} |
| 42 | + |
| 43 | +// APIShapeLabels is a map of APIShapeLabel to any value. |
| 44 | +type APIShapeLabels map[APIShapeLabel]any |
| 45 | + |
| 46 | +// NoLabels returns an empty APIShapeLabels map. |
| 47 | +func NoLabels() APIShapeLabels { |
| 48 | + return APIShapeLabels{} |
| 49 | +} |
| 50 | + |
| 51 | +// APIShapeLatency is the metric that SpiceDB uses to keep track of the latency |
| 52 | +// of API calls, by shape. The "shape" of an API call is defined as the portions |
| 53 | +// of the API call that are not the specific object IDs, e.g. the resource type, |
| 54 | +// the relation, the subject type, etc. |
| 55 | +// |
| 56 | +// NOTE: This metric is a *native* histogram, which means that instead of predefined |
| 57 | +// the buckets, it uses a factor to determine the buckets. This is useful for latency-based |
| 58 | +// metrics, as the latency can vary widely and having a fixed set of buckets can lead to |
| 59 | +// imprecise results. |
| 60 | +// |
| 61 | +// To use make use of native histograms, a special flag must be set on Prometheus: |
| 62 | +// https://prometheus.io/docs/prometheus/latest/feature_flags/#native-histograms |
| 63 | +var APIShapeLatency = promauto.NewHistogramVec(prometheus.HistogramOpts{ |
| 64 | + Namespace: "spicedb", |
| 65 | + Subsystem: "perf_insights", |
| 66 | + Name: "api_shape_latency_seconds", |
| 67 | + Help: "The latency of API calls, by shape", |
| 68 | + Buckets: nil, |
| 69 | + NativeHistogramBucketFactor: 1.1, |
| 70 | +}, append([]string{"api_kind"}, allLabels...)) |
| 71 | + |
| 72 | +// ShapeBuilder is a function that returns a slice of strings representing the shape of the API call. |
| 73 | +// This is used to report the shape of the API call to Prometheus. |
| 74 | +type ShapeBuilder func() APIShapeLabels |
| 75 | + |
| 76 | +// ObserveShapeLatency observes the latency of the API call with the given shape. |
| 77 | +func ObserveShapeLatency(ctx context.Context, methodName string, shape APIShapeLabels, duration time.Duration) { |
| 78 | + observeShapeLatency(ctx, APIShapeLatency, methodName, shape, duration) |
| 79 | +} |
| 80 | + |
| 81 | +func observeShapeLatency(ctx context.Context, metric *prometheus.HistogramVec, methodName string, shape APIShapeLabels, duration time.Duration) { |
| 82 | + labels := buildLabels(methodName, shape) |
| 83 | + if len(labels) == 0 { |
| 84 | + log.Warn().Str("method", methodName). |
| 85 | + Msg("ShapeBuilder returned an empty shape, skipping reporting") |
| 86 | + return |
| 87 | + } |
| 88 | + |
| 89 | + o := metric.WithLabelValues(labels...) |
| 90 | + if exemplarObserver, ok := o.(prometheus.ExemplarObserver); ok { |
| 91 | + if spanCtx := trace.SpanContextFromContext(ctx); spanCtx.HasTraceID() { |
| 92 | + traceID := prometheus.Labels{"traceID": spanCtx.TraceID().String()} |
| 93 | + exemplarObserver.ObserveWithExemplar(duration.Seconds(), traceID) |
| 94 | + return |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + o.Observe(duration.Seconds()) |
| 99 | +} |
| 100 | + |
| 101 | +func buildLabels(methodName string, shape APIShapeLabels) []string { |
| 102 | + labels := make([]string, len(allLabels)+1) |
| 103 | + labels[0] = methodName |
| 104 | + |
| 105 | + for index, label := range allLabels { |
| 106 | + shapeValue, ok := shape[APIShapeLabel(label)] |
| 107 | + if !ok { |
| 108 | + continue |
| 109 | + } |
| 110 | + |
| 111 | + switch t := shapeValue.(type) { |
| 112 | + case string: |
| 113 | + labels[index+1] = t |
| 114 | + |
| 115 | + case int: |
| 116 | + labels[index+1] = strconv.Itoa(t) |
| 117 | + |
| 118 | + case uint32: |
| 119 | + intValue, err := safecast.ToInt(t) |
| 120 | + if err != nil { |
| 121 | + log.Warn().Str("method", methodName). |
| 122 | + Str("key", label). |
| 123 | + Str("type", fmt.Sprintf("%T", t)). |
| 124 | + Msg("ShapeBuilder could not convert int, skipping reporting") |
| 125 | + return nil |
| 126 | + } |
| 127 | + labels[index+1] = strconv.Itoa(intValue) |
| 128 | + |
| 129 | + case int64: |
| 130 | + intValue, err := safecast.ToInt(t) |
| 131 | + if err != nil { |
| 132 | + log.Warn().Str("method", methodName). |
| 133 | + Str("key", label). |
| 134 | + Str("type", fmt.Sprintf("%T", t)). |
| 135 | + Msg("ShapeBuilder could not convert int, skipping reporting") |
| 136 | + return nil |
| 137 | + } |
| 138 | + labels[index+1] = strconv.Itoa(intValue) |
| 139 | + |
| 140 | + default: |
| 141 | + spiceerrors.DebugAssert(func() bool { return false }, "unsupported type %T", t) |
| 142 | + log.Warn().Str("method", methodName). |
| 143 | + Str("key", label). |
| 144 | + Str("type", fmt.Sprintf("%T", t)). |
| 145 | + Msg("ShapeBuilder returned an unsupported type, skipping reporting") |
| 146 | + return nil |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + return labels |
| 151 | +} |
| 152 | + |
| 153 | +type reporter struct { |
| 154 | + isEnabled bool |
| 155 | +} |
| 156 | + |
| 157 | +func (r *reporter) ServerReporter(ctx context.Context, callMeta interceptors.CallMeta) (interceptors.Reporter, context.Context) { |
| 158 | + if !r.isEnabled { |
| 159 | + return &interceptors.NoopReporter{}, ctx |
| 160 | + } |
| 161 | + |
| 162 | + _, methodName := grpcutil.SplitMethodName(callMeta.FullMethod()) |
| 163 | + ctx = contextWithHandle(ctx) |
| 164 | + return &serverReporter{ctx: ctx, methodName: methodName}, ctx |
| 165 | +} |
| 166 | + |
| 167 | +type serverReporter struct { |
| 168 | + interceptors.NoopReporter |
| 169 | + ctx context.Context |
| 170 | + methodName string |
| 171 | +} |
| 172 | + |
| 173 | +var ctxKey = ctxkey.NewBoxedWithDefault[ShapeBuilder](nil) |
| 174 | + |
| 175 | +func (r *serverReporter) PostCall(err error, duration time.Duration) { |
| 176 | + // Do not report if the call resulted in an error. |
| 177 | + if err != nil { |
| 178 | + return |
| 179 | + } |
| 180 | + |
| 181 | + shapeClosure := ctxKey.Value(r.ctx) |
| 182 | + spiceerrors.DebugAssertNotNil(shapeClosure, "ShapeBuilder should not be nil") |
| 183 | + |
| 184 | + // If not testing and nil, simply skip. |
| 185 | + if shapeClosure == nil { |
| 186 | + log.Warn().Str("method", r.methodName). |
| 187 | + Msg("ShapeBuilder is nil, skipping reporting") |
| 188 | + return |
| 189 | + } |
| 190 | + |
| 191 | + ObserveShapeLatency(r.ctx, r.methodName, shapeClosure(), duration) |
| 192 | +} |
| 193 | + |
| 194 | +// UnaryServerInterceptor returns a gRPC server-side interceptor that provides reporting for Unary RPCs. |
| 195 | +func UnaryServerInterceptor(isEnabled bool) grpc.UnaryServerInterceptor { |
| 196 | + return interceptors.UnaryServerInterceptor(&reporter{isEnabled: isEnabled}) |
| 197 | +} |
| 198 | + |
| 199 | +// StreamServerInterceptor returns a gRPC server-side interceptor that provides reporting for Streaming RPCs. |
| 200 | +func StreamServerInterceptor(isEnabled bool) grpc.StreamServerInterceptor { |
| 201 | + return interceptors.StreamServerInterceptor(&reporter{isEnabled: isEnabled}) |
| 202 | +} |
| 203 | + |
| 204 | +// SetInContext sets the ShapeBuilder in the context. |
| 205 | +func SetInContext(ctx context.Context, builder ShapeBuilder) { |
| 206 | + ctxKey.Set(ctx, builder) |
| 207 | +} |
| 208 | + |
| 209 | +// contextWithHandle returns a context with the ShapeBuilder set. |
| 210 | +// Should only be called by the server reporter or a test. |
| 211 | +func contextWithHandle(ctx context.Context) context.Context { |
| 212 | + return ctxKey.SetBox(ctx) |
| 213 | +} |
0 commit comments