diff --git a/docs/architecture/graphql-api-surface.txt b/docs/architecture/graphql-api-surface.txt index 5857b247..97635895 100644 --- a/docs/architecture/graphql-api-surface.txt +++ b/docs/architecture/graphql-api-surface.txt @@ -5,7 +5,7 @@ # capability artifacts. # Update only after review with: # ./gradlew :adapter:inbound:graphql:updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange -# types: 161 +# types: 163 dev.caskeleton.adapter.inbound.graphql.HealthGraphqlController dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationId @@ -130,6 +130,7 @@ dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlCostBudgetHandler dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataFetcherExceptionResolver +dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataLoaderObservationConventionAdapter dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDeadlineInstrumentation dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDocumentAuthorizationHandler dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionChain @@ -143,6 +144,7 @@ dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformWebInterceptor dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPreparsedDocumentAdapter dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPrincipalResolver dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlRequestObservationConventionAdapter +dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlResolverObservationConventionAdapter dev.caskeleton.adapter.inbound.graphql.runtime.servlet.GraphQlRequestBodyLimitFilter dev.caskeleton.adapter.inbound.graphql.scalar.BigDecimalScalar dev.caskeleton.adapter.inbound.graphql.scalar.DateScalar diff --git a/docs/registries/metrics.yaml b/docs/registries/metrics.yaml index 4722c3ba..bb399bc6 100644 --- a/docs/registries/metrics.yaml +++ b/docs/registries/metrics.yaml @@ -622,13 +622,17 @@ metrics: - name: graphql.outcome cardinality_limit: 5 - name: error.type - # 오류가 있을 때만 붙는다. + # 오류 분류(REQUEST·INTERNAL), 오류가 없으면 NONE. 요청마다 같은 key 셋을 단다(Prometheus는 key 묶음이 + # 다른 meter를 버린다). cardinality_limit: 10 - name: graphql.complexity.bucket - # 복잡도를 셌을 때만 붙는다. + # 복잡도 구간, 복잡도를 세기 전에 끝난 요청은 unknown. cardinality_limit: 6 - name: graphql.depth.bucket cardinality_limit: 6 + - name: error + # Micrometer가 observation timer마다 단다: 예외 클래스의 단순 이름, 없으면 none. + cardinality_limit: 50 percentiles: null histogram_buckets: null alert_severity_thresholds: {} @@ -640,21 +644,26 @@ metrics: constant: GraphQlObservationNames.REQUEST registered_by: "src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlRequestObservationConvention.java" - # Spring for GraphQL 기본 observation. tag는 Spring 기본 convention(DefaultDataFetcherObservationConvention) - # 그대로다. 이 저장소의 convention bean은 이 두 observation에 붙지 않는다. + # resolver·DataLoader observation. Spring for GraphQL이 내고, tag는 플랫폼 convention이 정한다 + # (GraphQlResolverObservationConventionAdapter·GraphQlDataLoaderObservationConventionAdapter, 상한은 + # GraphQlMetricCardinalityPolicy 허용 목록). response path와 batch key는 싣지 않는다. - name: graphql.datafetcher type: timer unit: seconds tags: + - name: graphql.schema.coordinate + # schema 좌표(Type.field). schema의 field 수가 상한이다. 좌표로 이름 붙일 수 없는 field는 unnamed. + cardinality_limit: 500 - name: graphql.outcome cardinality_limit: 2 allowed_values: [SUCCESS, ERROR] - - name: graphql.field.name - # schema의 field 이름. schema의 field 수가 상한이다. - cardinality_limit: 500 - - name: graphql.error.type - # 예외 클래스의 단순 이름, 없으면 NONE. - cardinality_limit: 20 + - name: graphql.resolver.weight + # cost 단계가 매긴 resolver 무게(등록 안 한 field는 EXTERNAL_BATCH). + cardinality_limit: 6 + allowed_values: [PROPERTY, INDEXED_LOOKUP, BATCHED_RELATION, BOUNDED_AGGREGATION, EXTERNAL_BATCH, EXTERNAL_PER_OBJECT] + - name: error + # Micrometer가 observation timer마다 단다: 예외 클래스의 단순 이름, 없으면 none. + cardinality_limit: 50 percentiles: null histogram_buckets: null alert_severity_thresholds: {} @@ -662,21 +671,27 @@ metrics: log_field_mapping: [] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - source: "framework: Spring for GraphQL observation(이름은 GraphQlObservationNames와 같다)" + source: "src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlObservationNames.java" + constant: GraphQlObservationNames.RESOLVER + registered_by: "src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlResolverObservationConvention.java" - name: graphql.dataloader type: timer unit: seconds tags: + - name: graphql.dataloader.name + # 등록한 loader 이름, 또는 Spring이 @BatchMapping loader에 붙이는 schema 좌표(Book.author). + # 둘 다 아니면(클래스 이름 등) unknown. 등록한 loader와 schema field 수가 상한이다. + cardinality_limit: 500 - name: graphql.outcome cardinality_limit: 2 allowed_values: [SUCCESS, ERROR] - - name: graphql.loader.name - # 등록한 DataLoader 이름, 모르면 unknown. + - name: graphql.batch.size.bucket + cardinality_limit: 4 + allowed_values: ["1", "2-10", "11-100", "100+"] + - name: error + # Micrometer가 observation timer마다 단다: 예외 클래스의 단순 이름, 없으면 none. cardinality_limit: 50 - - name: graphql.error.type - # 예외 클래스의 단순 이름, 없으면 NONE. - cardinality_limit: 20 percentiles: null histogram_buckets: null alert_severity_thresholds: {} @@ -684,7 +699,9 @@ metrics: log_field_mapping: [] compatibility_impact: additive required_test: contract-verification:metrics-cardinality - source: "framework: Spring for GraphQL observation(이름은 GraphQlObservationNames와 같다)" + source: "src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlObservationNames.java" + constant: GraphQlObservationNames.DATA_LOADER + registered_by: "src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlDataLoaderObservationConvention.java" # DataLoader 없이 부모마다 풀린 field. 임계를 넘은 요청에 한 번 기록한다(GraphQlPerParentFetchInstrumentation). - name: graphql.per.parent.fetch @@ -693,6 +710,9 @@ metrics: tags: - name: graphql.schema.coordinate cardinality_limit: 200 + - name: error + # Micrometer가 observation timer마다 단다: 예외 클래스의 단순 이름, 없으면 none. + cardinality_limit: 50 percentiles: null histogram_buckets: null alert_severity_thresholds: {} diff --git a/docs/upgrade/2026-11-round9-followups.md b/docs/upgrade/2026-11-round9-followups.md new file mode 100644 index 00000000..ac635d37 --- /dev/null +++ b/docs/upgrade/2026-11-round9-followups.md @@ -0,0 +1,21 @@ +# 업그레이드 안내 — 2026-11 GraphQL 관측 tag·안 쓰는 헤더 상수·인증 설정 runbook 이름 + +- 범위: 2026-11-12 전체 리뷰를 고친 뒤 남은 후속. GraphQL resolver·DataLoader 지표가 플랫폼 tag를 달고, GraphQL 지표가 요청마다 같은 tag key를 단다. +- 근거: 2026-11-12 전체 리뷰(`docs/reviews/2026-11-12-round9-review/`)의 관측·인증 묶음을 고칠 때 범위 밖으로 남긴 후속 + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 특히 GraphQL을 켜고 그 지표로 대시보드를 만든 서비스다. + +## 2. 할 일 + +| # | 바뀐 것 | 할 일 | 안 하면 | 해당 서비스 | +| --- | --- | --- | --- | --- | +| 1 | `graphql.request` timer는 모든 요청에 `error.type`·`graphql.complexity.bucket`을 단다. 오류가 없으면 `error.type=NONE`, 복잡도를 세기 전에 끝난 요청은 `graphql.complexity.bucket=unknown`이다. 전에는 두 tag가 빠진 series가 따로 있었고, Prometheus registry는 이름이 같고 key 묶음이 다른 meter를 버리므로 성공이나 실패 한쪽이 `/actuator/prometheus`에 나오지 않았다 | `error.type`이 없는 series로 성공을 세던 질의를 `error.type="NONE"`으로 바꾼다 | 그 질의가 빈 값을 본다 | GraphQL을 켠 서비스 | +| 2 | `graphql.datafetcher` timer의 tag가 Spring 기본값(`graphql.field.name`, `graphql.error.type`, `graphql.outcome`)에서 `graphql.schema.coordinate`(`Type.field`, 좌표로 이름 붙일 수 없는 field는 `unnamed`), `graphql.outcome`, `graphql.resolver.weight`(cost 단계의 resolver 무게, 등록 안 한 field는 `EXTERNAL_BATCH`)로 바뀌었다. Micrometer가 다는 `error` tag(예외 클래스의 단순 이름, 없으면 `none`)는 그대로 있다. 지표 이름은 그대로다 | `graphql.field.name`으로 거른 패널·경보를 `graphql.schema.coordinate`로, `graphql.error.type`으로 거른 것을 `error`로 바꾼다 | 그 패널이 비고 경보가 울리지 않는다 | GraphQL을 켠 서비스 | +| 3 | `graphql.dataloader` timer의 tag가 Spring 기본값(`graphql.loader.name`, `graphql.error.type`, `graphql.outcome`)에서 `graphql.dataloader.name`, `graphql.outcome`, `graphql.batch.size.bucket`(`1`·`2-10`·`11-100`·`100+`)으로 바뀌었다. loader 이름은 등록한 이름이거나 Spring이 `@BatchMapping` loader에 붙이는 schema 좌표(`Book.author`)다. 클래스 이름으로 등록한 loader(`forTypePair`)와 이름 문법 밖의 loader는 `unknown` 하나로 묶인다. `error` tag는 그대로 있다 | `graphql.loader.name`으로 거른 패널·경보를 `graphql.dataloader.name`으로 바꾼다. 클래스 이름 loader를 따로 보려면 이름을 주어 등록한다(`BatchLoaderRegistry`의 `forName(…)`이나 `forTypePair(…).withName(…)`) | 그 패널이 비고, 클래스 이름 loader가 `unknown`에 섞인다 | DataLoader를 쓰는 GraphQL 서비스 | +| 4 | `GraphQlResolverObservationConvention`이 내는 무게 tag 이름이 `graphql.operation.type`에서 `graphql.resolver.weight`로, `GraphQlDataLoaderObservationConvention`의 batch 크기 tag가 `graphql.complexity.bucket`에서 `graphql.batch.size.bucket`으로 바뀌었다. 두 convention은 이제 `DataFetcherObservationConvention`·`DataLoaderObservationConvention` bean(adapter)으로 Spring observation에 붙는다 | 두 convention의 `tags(...)`를 직접 불러 옛 key를 읽던 코드를 새 key로 바꾼다. 자기 `DataFetcherObservationConvention`·`DataLoaderObservationConvention` bean을 둔 서비스는 그 bean이 쓰이고 위 2·3번 tag가 붙지 않는다 | 옛 key를 찾는 코드가 빈 값을 본다 | 두 convention을 직접 쓰거나 바꾼 서비스 | + +## 3. 바뀌지 않은 것 + +- 지표 이름(`graphql.request`, `graphql.datafetcher`, `graphql.dataloader`)과 GraphQL 응답 모양은 그대로다. diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index 5688b224..0ae3569a 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -400,7 +400,7 @@ feature GraphQL schema/resolver 는 여전히 이 leaf 밖이다(스켈레톤은 | preparsed document cache (`execution/`) | `wired` | `GraphQlPreparsedDocumentAdapter` + 같은 테스트의 캐시 hit 케이스 | | 커스텀 scalar (`scalar/`) | `wired` | 같은 테스트의 scalar coercion 케이스 | | 요청 크기 (`http/`, body limit filter) | `wired` | `runtime/GraphQlPlatformWebInterceptorRequestBoundsTest`(auto-configured interceptor 로 byte·shape·extension 거부), `http/GraphQlRequestBoundsTest` | -| 관측 tag cardinality (`observation/`) | `wired` | `runtime/GraphQlRequestObservationConventionAdapter` 가 Spring 의 `ExecutionRequestObservationConvention` 을 구현해 Boot 의 `GraphQlObservationAutoConfiguration` 이 이 컨벤션을 가져간다. `autoconfigure/GraphQlObservationWiringTest`(프레임워크가 실제로 해석), `runtime/GraphQlRequestObservationConventionAdapterTest`(실제 `MeterRegistry` 에 임의 이름 10,000개 → series 1개) | +| 관측 tag cardinality (`observation/`) | `wired` | `runtime/GraphQlRequestObservationConventionAdapter`·`GraphQlResolverObservationConventionAdapter`·`GraphQlDataLoaderObservationConventionAdapter` 가 Spring 의 `ExecutionRequestObservationConvention`·`DataFetcherObservationConvention`·`DataLoaderObservationConvention` 을 구현해 Boot 의 `GraphQlObservationAutoConfiguration` 이 세 컨벤션을 가져간다(`graphql.request`·`graphql.datafetcher`·`graphql.dataloader`). `autoconfigure/GraphQlObservationWiringTest`(프레임워크가 실제로 해석), `runtime/GraphQlRequestObservationConventionAdapterTest`(실제 `MeterRegistry` 에 임의 이름 10,000개 → series 1개), resolver·DataLoader 어댑터 시험(좌표·무게·batch 구간 tag) | | object 인가 (`security/`) | `modelled` | 답하는 계약은 중립 `dev.caskeleton.application.security.ObjectAccessPolicy` 가 소유하고 이 leaf 는 `ApplicationObjectAuthorization` 매핑만 가진다. 실행 경로에 연결하는 configuration 은 없다 | | DataLoader/batching (`dataloader/`) | `wired` | `runtime/GraphQlBatchLoaderRegistrationTest` (실제 graphql-java 실행 + Spring `BatchLoaderRegistry`, 50 parent → 3 downstream 호출), `dataloader/GraphQlBatchContractTest` | | 요청 deadline (`maxExecutionTime`) | `wired` | `systemTest/runtime/GraphQlRequestDeadlineTest`(virtual thread: deadline 근처 `REQUEST_TIMEOUT`, 하위 필드 미실행), `GraphQlRequestDeadlineOnRequestThreadTest`(요청 스레드: 느린 resolver 가 끝난 뒤 응답 — 한계). 이미 도는 resolver 는 끊지 않는다(README 「요청 deadline」) | diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationConfiguration.java index 2503c234..4f03909f 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationConfiguration.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationConfiguration.java @@ -1,15 +1,21 @@ package dev.caskeleton.adapter.inbound.graphql.autoconfigure; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlDataLoaderObservationConvention; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlMetricCardinalityPolicy; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlOperationNameCardinality; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlRequestObservationConvention; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlResolverObservationConvention; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlSensitiveAttributeFilter; +import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataLoaderObservationConventionAdapter; import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlRequestObservationConventionAdapter; +import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlResolverObservationConventionAdapter; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.graphql.observation.DataFetcherObservationConvention; +import org.springframework.graphql.observation.DataLoaderObservationConvention; import org.springframework.graphql.observation.ExecutionRequestObservationConvention; /** Bounded-cardinality observation conventions for requests, resolvers and DataLoaders. */ @@ -77,6 +83,22 @@ class GraphQlObservationConfiguration { return new GraphQlResolverObservationConvention(filter); } + /** + * Hands the bounded resolver tags to Spring for GraphQL's {@code graphql.datafetcher} + * observation, as the request adapter above does for {@code graphql.request}. + * + * @param convention the platform's bounded resolver tags + * @param costs the registered resolver weights; none registered means every field is charged the + * default weight + */ + @Bean + @ConditionalOnMissingBean(DataFetcherObservationConvention.class) + GraphQlResolverObservationConventionAdapter graphQlDataFetcherObservationConvention( + GraphQlResolverObservationConvention convention, ObjectProvider costs) { + return new GraphQlResolverObservationConventionAdapter( + convention, costs.getIfAvailable(() -> GraphQlCostCatalog.of())); + } + /** The DataLoader observation convention. */ @Bean @ConditionalOnMissingBean @@ -84,4 +106,16 @@ class GraphQlObservationConfiguration { GraphQlSensitiveAttributeFilter filter) { return new GraphQlDataLoaderObservationConvention(filter); } + + /** + * Hands the bounded loader tags to Spring for GraphQL's {@code graphql.dataloader} observation. + * + * @param convention the platform's bounded loader tags + */ + @Bean + @ConditionalOnMissingBean(DataLoaderObservationConvention.class) + GraphQlDataLoaderObservationConventionAdapter graphQlDataLoaderObservationConventionAdapter( + GraphQlDataLoaderObservationConvention convention) { + return new GraphQlDataLoaderObservationConventionAdapter(convention); + } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlDataLoaderObservationConvention.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlDataLoaderObservationConvention.java index 87582f3b..cd4ea0d5 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlDataLoaderObservationConvention.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlDataLoaderObservationConvention.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.inbound.graphql.observation; +import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchObservation; import java.util.LinkedHashMap; import java.util.Map; @@ -44,10 +45,27 @@ public final class GraphQlDataLoaderObservationConvention { * @param outcome bounded outcome name */ public Map tags(GraphQlBatchObservation observation, String outcome) { + return tags(observation.loaderName().value(), observation.batchSize(), outcome); + } + + /** + * Builds the tags of the loader Spring registers for a {@code @BatchMapping} field. Spring names + * that loader after the field's schema coordinate, which is as static as a registered name. + * + * @param batchMappedField the field the loader batches + * @param batchSize keys in the batch + * @param outcome bounded outcome name + */ + public Map tags( + GraphQlSchemaCoordinate batchMappedField, int batchSize, String outcome) { + return tags(batchMappedField.value(), batchSize, outcome); + } + + private Map tags(String loaderName, int batchSize, String outcome) { Map tags = new LinkedHashMap<>(); - tags.put("graphql.dataloader.name", observation.loaderName().value()); + tags.put("graphql.dataloader.name", loaderName); tags.put("graphql.outcome", outcome); - tags.put("graphql.complexity.bucket", batchSizeBucket(observation.batchSize())); + tags.put("graphql.batch.size.bucket", batchSizeBucket(batchSize)); return filter.filter(tags); } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicy.java index 81b48d75..e9cabeba 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicy.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicy.java @@ -24,6 +24,8 @@ public final class GraphQlMetricCardinalityPolicy { "graphql.outcome", "graphql.complexity.bucket", "graphql.depth.bucket", + "graphql.resolver.weight", + "graphql.batch.size.bucket", "error.type"); /** Attributes that must never become metric tags or general trace attributes. */ diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlRequestObservationConvention.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlRequestObservationConvention.java index cdd5263b..89bdc82b 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlRequestObservationConvention.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlRequestObservationConvention.java @@ -18,9 +18,20 @@ import java.util.Map; *

The operation name was the exception, and it was the one that mattered: it was tagged raw, on * the strength of a regular expression that bounds its syntax and says nothing about how many * distinct names a client may invent. {@link GraphQlOperationNameCardinality} closes it. + * + *

Every request carries the same tag keys. A request without errors reports {@link #NO_ERROR} + * and one that never reached costing reports {@link #NOT_SCORED}, rather than leaving the tag out: + * the Prometheus registry keeps the first key set registered under a meter name and drops every + * meter whose keys differ, so an absent tag would make the failures (or the successes) vanish. */ public final class GraphQlRequestObservationConvention { + /** The {@code error.type} of a request that produced no error. */ + public static final String NO_ERROR = "NONE"; + + /** The {@code graphql.complexity.bucket} of a request that never reached costing. */ + public static final String NOT_SCORED = "unknown"; + private final GraphQlSensitiveAttributeFilter filter; private final GraphQlOperationNameCardinality operationNames; @@ -75,8 +86,8 @@ public final class GraphQlRequestObservationConvention { * @param clientProfile bounded client profile * @param persisted whether the operation came from the persisted registry * @param outcome bounded outcome name - * @param errorCategory bounded error category, or {@code null} - * @param complexity computed complexity, or {@code null} when the request never reached costing + * @param errorCategory bounded error category, or {@code null} for {@link #NO_ERROR} + * @param complexity computed complexity, or {@code null} for {@link #NOT_SCORED} * @param depth measured selection depth */ public Map tags( @@ -113,8 +124,8 @@ public final class GraphQlRequestObservationConvention { * @param clientProfile bounded client profile * @param persisted whether the operation came from the persisted registry * @param outcome bounded outcome name - * @param errorCategory bounded error category, or {@code null} - * @param complexity computed complexity, or {@code null} when the request never reached costing + * @param errorCategory bounded error category, or {@code null} for {@link #NO_ERROR} + * @param complexity computed complexity, or {@code null} for {@link #NOT_SCORED} * @param depth measured selection depth */ public Map tagsForWireName( @@ -154,12 +165,8 @@ public final class GraphQlRequestObservationConvention { tags.put("graphql.client.profile", clientProfile.value()); tags.put("graphql.persisted", Boolean.toString(persisted)); tags.put("graphql.outcome", outcome); - if (errorCategory != null) { - tags.put("error.type", errorCategory); - } - if (complexity != null) { - tags.put("graphql.complexity.bucket", complexity.bucket()); - } + tags.put("error.type", errorCategory == null ? NO_ERROR : errorCategory); + tags.put("graphql.complexity.bucket", complexity == null ? NOT_SCORED : complexity.bucket()); tags.put("graphql.depth.bucket", depthBucket(depth)); return filter.filter(tags); } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlResolverObservationConvention.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlResolverObservationConvention.java index 111986d9..1b9f064c 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlResolverObservationConvention.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlResolverObservationConvention.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.inbound.graphql.observation; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog; import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlResolverWeight; import java.util.LinkedHashMap; import java.util.Map; @@ -10,9 +11,16 @@ import java.util.Map; * *

Tagged by schema coordinate, not by response path. The coordinate is a static position in the * schema; a response path contains list indices and therefore grows without bound with the data. + * + *

A field no coordinate can name (a federation field such as {@code _Service.sdl}) is tagged + * {@link #UNNAMED_COORDINATE} with the same keys: the Prometheus registry drops a meter whose tag + * keys differ from the first one registered under its name. */ public final class GraphQlResolverObservationConvention { + /** The {@code graphql.schema.coordinate} of a field no schema coordinate can name. */ + public static final String UNNAMED_COORDINATE = "unnamed"; + private final GraphQlSensitiveAttributeFilter filter; /** @@ -41,17 +49,33 @@ public final class GraphQlResolverObservationConvention { * Builds the resolver tags. * * @param coordinate the resolved field - * @param weight the resolver's registered cost class + * @param weight the resolver's registered cost class, or {@code null} for the default weight * @param outcome bounded outcome name */ public Map tags( GraphQlSchemaCoordinate coordinate, GraphQlResolverWeight weight, String outcome) { + return tags(coordinate.value(), weight, outcome); + } + + /** + * Builds the tags of a resolver whose field no schema coordinate can name. + * + * @param weight the resolver's cost class, or {@code null} for the default weight + * @param outcome bounded outcome name + */ + public Map tagsForUnnamedField(GraphQlResolverWeight weight, String outcome) { + return tags(UNNAMED_COORDINATE, weight, outcome); + } + + private Map tags( + String coordinate, GraphQlResolverWeight weight, String outcome) { Map tags = new LinkedHashMap<>(); - tags.put("graphql.schema.coordinate", coordinate.value()); + tags.put("graphql.schema.coordinate", coordinate); tags.put("graphql.outcome", outcome); - if (weight != null) { - tags.put("graphql.operation.type", weight.name()); - } + // A missing weight is the cost stage's default, never a missing key: see the class comment. + tags.put( + "graphql.resolver.weight", + (weight == null ? GraphQlCostCatalog.DEFAULT_WEIGHT : weight).name()); return filter.filter(tags); } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapter.java new file mode 100644 index 00000000..f67f91fa --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapter.java @@ -0,0 +1,116 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; +import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchObservation; +import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName; +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlDataLoaderObservationConvention; +import io.micrometer.common.KeyValue; +import io.micrometer.common.KeyValues; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.springframework.graphql.observation.DataLoaderObservationContext; +import org.springframework.graphql.observation.DataLoaderObservationConvention; + +/** + * Makes the platform's bounded DataLoader tags the ones the {@code graphql.dataloader} meter gets. + * + *

The same gap as {@link GraphQlResolverObservationConventionAdapter}: the platform's loader + * convention was not a {@link DataLoaderObservationConvention}, so the framework used its own tags + * and the bounded batch-size bucket was computed for nobody (review 2026-11-13). + * + *

The tags are the loader's name, the outcome ({@code SUCCESS} or {@code ERROR}) and the bucket + * of the batch size. The name is a registered, validated one; or the schema coordinate Spring names + * a {@code @BatchMapping} loader after ({@code Book.author}); or {@link #UNKNOWN_LOADER}. All three + * are static. The keys are never reported: they are object identifiers. + */ +public final class GraphQlDataLoaderObservationConventionAdapter + implements DataLoaderObservationConvention { + + /** The name reported for a loader registered without a valid name. */ + public static final String UNKNOWN_LOADER = "unknown"; + + private final GraphQlDataLoaderObservationConvention convention; + + /** + * Creates the adapter. + * + * @param convention the platform's bounded loader tags + */ + public GraphQlDataLoaderObservationConventionAdapter( + GraphQlDataLoaderObservationConvention convention) { + this.convention = Objects.requireNonNull(convention, "loader convention is required"); + } + + @Override + public String getName() { + return convention.name(); + } + + @Override + public String getContextualName(DataLoaderObservationContext context) { + String name = rawName(context); + return "graphql dataloader " + + batchMappedField(name) + .map(GraphQlSchemaCoordinate::value) + .orElseGet(() -> loaderName(name).value()); + } + + @Override + public KeyValues getLowCardinalityKeyValues(DataLoaderObservationContext context) { + List keys = context.getKeys(); + int batchSize = keys == null ? 0 : keys.size(); + String outcome = + context.getError() == null + ? GraphQlResolverObservationConventionAdapter.OUTCOME_SUCCESS + : GraphQlResolverObservationConventionAdapter.OUTCOME_ERROR; + String name = rawName(context); + Map tags = + batchMappedField(name) + .map(field -> convention.tags(field, batchSize, outcome)) + .orElseGet( + () -> + convention.tags( + new GraphQlBatchObservation( + loaderName(name), batchSize, batchSize, 0, Duration.ZERO), + outcome)); + KeyValues keyValues = KeyValues.empty(); + for (Map.Entry tag : tags.entrySet()) { + keyValues = keyValues.and(KeyValue.of(tag.getKey(), tag.getValue())); + } + return keyValues; + } + + private static String rawName(DataLoaderObservationContext context) { + return context.getDataLoader() == null ? null : context.getDataLoader().getName(); + } + + /** + * The {@code @BatchMapping} field a loader is named after. A coordinate starts with an upper-case + * type name and a registered loader name with a lower-case letter, so the two never overlap. + */ + private static Optional batchMappedField(String name) { + if (name == null) { + return Optional.empty(); + } + try { + return Optional.of(GraphQlSchemaCoordinate.parse(name)); + } catch (IllegalArgumentException notACoordinate) { + // A class name (Spring's forTypePair loaders) or anything else: not a tag value. + return Optional.empty(); + } + } + + private static GraphQlDataLoaderName loaderName(String name) { + if (name != null) { + try { + return new GraphQlDataLoaderName(name); + } catch (IllegalArgumentException outsideTheGrammar) { + // A loader name outside the bounded grammar is not a tag value. + } + } + return new GraphQlDataLoaderName(UNKNOWN_LOADER); + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapter.java index ae312f8c..d6d1346b 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapter.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapter.java @@ -158,8 +158,8 @@ public final class GraphQlRequestObservationConventionAdapter ExecutionResult result = context.getExecutionResult(); List errors = result == null ? null : result.getErrors(); if (errors == null || errors.isEmpty()) { - // Absent rather than a "none" label: an outcome tag already says the request succeeded, and a - // second tag saying the same thing doubles the series for no extra answer. + // No error category: the convention reports NONE, so a success has the same tag keys as a + // failure and one series shape survives the Prometheus registry. return null; } return internal(errors) diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapter.java new file mode 100644 index 00000000..72ea52af --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapter.java @@ -0,0 +1,105 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlResolverWeight; +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlResolverObservationConvention; +import graphql.schema.DataFetchingEnvironment; +import graphql.schema.GraphQLNamedType; +import io.micrometer.common.KeyValue; +import io.micrometer.common.KeyValues; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.springframework.graphql.observation.DataFetcherObservationContext; +import org.springframework.graphql.observation.DataFetcherObservationConvention; + +/** + * Makes the platform's bounded resolver tags the ones the {@code graphql.datafetcher} meter gets. + * + *

Spring for GraphQL emits the observation from its own instrumentation and asks a {@link + * DataFetcherObservationConvention} bean what to tag it with. The platform's resolver convention + * did not implement that interface, so the framework used its own field-name tags and the bounded + * coordinate tags were computed for nobody (review 2026-11-13). This class translates, as {@link + * GraphQlRequestObservationConventionAdapter} does for requests. + * + *

Every tag is bounded: the schema coordinate (a static schema position, never the response + * path), the outcome ({@code SUCCESS} or {@code ERROR}) and the resolver weight the cost stage + * charged — the registered one, or {@link GraphQlCostCatalog#DEFAULT_WEIGHT}. A field whose type or + * field name a coordinate cannot express gets the same keys, with the coordinate {@link + * GraphQlResolverObservationConvention#UNNAMED_COORDINATE} and the default weight. Nothing is + * reported at high cardinality: the field path is on the platform's forbidden list. + */ +public final class GraphQlResolverObservationConventionAdapter + implements DataFetcherObservationConvention { + + /** Outcome of a resolver that returned without an error. */ + public static final String OUTCOME_SUCCESS = "SUCCESS"; + + /** Outcome of a resolver that failed. */ + public static final String OUTCOME_ERROR = "ERROR"; + + private final GraphQlResolverObservationConvention convention; + private final GraphQlCostCatalog costs; + + /** + * Creates the adapter. + * + * @param convention the platform's bounded resolver tags + * @param costs the registered resolver weights + */ + public GraphQlResolverObservationConventionAdapter( + GraphQlResolverObservationConvention convention, GraphQlCostCatalog costs) { + this.convention = Objects.requireNonNull(convention, "resolver convention is required"); + this.costs = Objects.requireNonNull(costs, "cost catalog is required"); + } + + @Override + public String getName() { + return convention.name(); + } + + @Override + public String getContextualName(DataFetcherObservationContext context) { + return coordinate(context.getEnvironment()) + .map(coordinate -> "graphql field " + coordinate.value()) + .orElse("graphql field"); + } + + @Override + public KeyValues getLowCardinalityKeyValues(DataFetcherObservationContext context) { + String outcome = context.getError() == null ? OUTCOME_SUCCESS : OUTCOME_ERROR; + Optional coordinate = coordinate(context.getEnvironment()); + Map tags = + coordinate + .map(named -> convention.tags(named, weight(named), outcome)) + .orElseGet( + () -> convention.tagsForUnnamedField(GraphQlCostCatalog.DEFAULT_WEIGHT, outcome)); + KeyValues keyValues = KeyValues.empty(); + for (Map.Entry tag : tags.entrySet()) { + keyValues = keyValues.and(KeyValue.of(tag.getKey(), tag.getValue())); + } + return keyValues; + } + + private GraphQlResolverWeight weight(GraphQlSchemaCoordinate coordinate) { + return costs.registered(coordinate.value()) + ? costs.require(coordinate.value()).resolverWeight() + : GraphQlCostCatalog.DEFAULT_WEIGHT; + } + + private static Optional coordinate(DataFetchingEnvironment environment) { + if (environment == null + || !(environment.getParentType() instanceof GraphQLNamedType parent) + || environment.getField() == null) { + return Optional.empty(); + } + try { + return Optional.of( + new GraphQlSchemaCoordinate(parent.getName(), environment.getField().getName())); + } catch (IllegalArgumentException inexpressible) { + // `_Service.sdl` and the like: no bounded coordinate names it, so it is not a tag value. + return Optional.empty(); + } + } +} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationWiringTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationWiringTest.java index 54c3bf74..f036ad60 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationWiringTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationWiringTest.java @@ -2,12 +2,16 @@ package dev.caskeleton.adapter.inbound.graphql.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataLoaderObservationConventionAdapter; import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlRequestObservationConventionAdapter; +import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlResolverObservationConventionAdapter; import io.micrometer.observation.ObservationRegistry; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.graphql.autoconfigure.observation.GraphQlObservationAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.graphql.observation.DataFetcherObservationConvention; +import org.springframework.graphql.observation.DataLoaderObservationConvention; import org.springframework.graphql.observation.ExecutionRequestObservationConvention; import org.springframework.graphql.observation.GraphQlObservationInstrumentation; @@ -39,6 +43,12 @@ class GraphQlObservationWiringTest { .getBean(ExecutionRequestObservationConvention.class) .as("the only convention the framework can resolve must be the bounded one") .isInstanceOf(GraphQlRequestObservationConventionAdapter.class); + assertThat(context) + .getBean(DataFetcherObservationConvention.class) + .isInstanceOf(GraphQlResolverObservationConventionAdapter.class); + assertThat(context) + .getBean(DataLoaderObservationConvention.class) + .isInstanceOf(GraphQlDataLoaderObservationConventionAdapter.class); }); } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java index 976474dd..ddd7d10b 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java @@ -7,6 +7,7 @@ import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationName; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlComplexityResult; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog; import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlResolverWeight; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchObservation; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderName; @@ -14,6 +15,7 @@ import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType; import java.time.Duration; import java.util.Map; import java.util.Set; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** Observation naming and cardinality control (Stable plan Task 45). */ @@ -100,9 +102,21 @@ class GraphQlMetricCardinalityPolicyTest { "SUCCESS"); assertThat(tags).containsEntry("graphql.schema.coordinate", "Order.items"); + assertThat(tags).containsEntry("graphql.resolver.weight", "BATCHED_RELATION"); assertThat(tags).doesNotContainKey("graphql.field.path"); } + @Test + @DisplayName("무게 없이 만든 resolver tag 도 graphql.resolver.weight 를 기본 무게로 단다 — key 묶음이 같아야 한다") + void resolverTagsWithoutAWeightCarryTheDefaultWeight() { + Map tags = + GraphQlResolverObservationConvention.standard() + .tags(GraphQlSchemaCoordinate.parse("Order.items"), null, "SUCCESS"); + + assertThat(tags) + .containsEntry("graphql.resolver.weight", GraphQlCostCatalog.DEFAULT_WEIGHT.name()); + } + @Test void loaderTagsCarryTheLoaderNameAndABucketedBatchSize() { Map tags = @@ -114,7 +128,7 @@ class GraphQlMetricCardinalityPolicyTest { assertThat(tags) .containsEntry("graphql.dataloader.name", "order.customer") - .containsEntry("graphql.complexity.bucket", "11-100"); + .containsEntry("graphql.batch.size.bucket", "11-100"); } @Test diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapterTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapterTest.java new file mode 100644 index 00000000..abcc9aa9 --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDataLoaderObservationConventionAdapterTest.java @@ -0,0 +1,124 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlDataLoaderObservationConvention; +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationNames; +import io.micrometer.common.KeyValue; +import io.micrometer.common.KeyValues; +import java.lang.reflect.Constructor; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.dataloader.BatchLoaderEnvironment; +import org.dataloader.DataLoader; +import org.dataloader.DataLoaderFactory; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.graphql.observation.DataLoaderObservationContext; + +class GraphQlDataLoaderObservationConventionAdapterTest { + + private final GraphQlDataLoaderObservationConventionAdapter adapter = + new GraphQlDataLoaderObservationConventionAdapter( + GraphQlDataLoaderObservationConvention.standard()); + + @Test + @DisplayName("graphql.dataloader 는 loader 이름·결과·batch 크기 구간으로 tag 를 단다 — key 는 싣지 않는다") + void aBatchIsTaggedByLoaderOutcomeAndSizeBucket() throws Exception { + // given + DataLoaderObservationContext context = + context(loader("order.customer"), IntStream.range(0, 42).boxed().toList()); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "graphql.dataloader.name", "order.customer", + "graphql.outcome", GraphQlResolverObservationConventionAdapter.OUTCOME_SUCCESS, + "graphql.batch.size.bucket", "11-100")); + } + + @Test + @DisplayName("이름 문법 밖의 loader 는 unknown 으로, 실패한 batch 는 ERROR 로 단다") + void aLoaderOutsideTheNameGrammarIsUnknownAndAFailureIsError() throws Exception { + // given + DataLoaderObservationContext context = context(loader("Bad Name!"), List.of(1)); + context.setError(new IllegalStateException("downstream")); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsEntry( + "graphql.dataloader.name", GraphQlDataLoaderObservationConventionAdapter.UNKNOWN_LOADER) + .containsEntry( + "graphql.outcome", GraphQlResolverObservationConventionAdapter.OUTCOME_ERROR); + } + + @Test + @DisplayName("Spring 이 @BatchMapping loader 에 붙이는 schema 좌표 이름(Book.author)은 그대로 loader 이름이다") + void aBatchMappingLoaderIsTaggedByItsFieldCoordinate() throws Exception { + // given + DataLoaderObservationContext context = context(loader("Book.author"), List.of(1, 2)); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "graphql.dataloader.name", "Book.author", + "graphql.outcome", GraphQlResolverObservationConventionAdapter.OUTCOME_SUCCESS, + "graphql.batch.size.bucket", "2-10")); + } + + @Test + @DisplayName("클래스 이름으로 등록한 loader(forTypePair)는 좌표가 아니므로 unknown 이다") + void aLoaderNamedAfterAClassIsUnknown() throws Exception { + // given + DataLoaderObservationContext context = context(loader("com.example.Book"), List.of(1)); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsEntry( + "graphql.dataloader.name", + GraphQlDataLoaderObservationConventionAdapter.UNKNOWN_LOADER); + } + + @Test + void theObservationNameMatchesTheOneSpringAlreadyEmits() { + assertThat(adapter.getName()).isEqualTo(GraphQlObservationNames.DATA_LOADER); + } + + private static Map tags(KeyValues keyValues) { + return keyValues.stream().collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue)); + } + + private static DataLoader loader(String name) { + return DataLoaderFactory.newDataLoader( + name, + keys -> CompletableFuture.completedFuture(keys.stream().map(String::valueOf).toList())); + } + + /** The framework builds this context; its constructor is package-private. */ + private static DataLoaderObservationContext context(DataLoader loader, List keys) + throws ReflectiveOperationException { + Constructor constructor = + DataLoaderObservationContext.class.getDeclaredConstructor( + DataLoader.class, List.class, BatchLoaderEnvironment.class); + constructor.setAccessible(true); + return constructor.newInstance( + loader, keys, BatchLoaderEnvironment.newBatchLoaderEnvironment().build()); + } +} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapterTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapterTest.java index 3501a98b..af04fdba 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapterTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlRequestObservationConventionAdapterTest.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.inbound.graphql.runtime; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationId; @@ -12,9 +13,12 @@ import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationName import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlOperationNameCardinality; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlRequestObservationConvention; import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlSensitiveAttributeFilter; +import graphql.ErrorType; import graphql.ExecutionInput; import graphql.ExecutionResult; +import graphql.GraphqlErrorBuilder; import io.micrometer.core.instrument.Meter; +import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.observation.DefaultMeterObservationHandler; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import io.micrometer.observation.Observation; @@ -25,6 +29,9 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.graphql.observation.ExecutionRequestObservationContext; @@ -118,6 +125,55 @@ class GraphQlRequestObservationConventionAdapterTest { assertThat(requestSeries().get(0).getTag("graphql.client.profile")).isEqualTo("anonymous"); } + @Test + @DisplayName("성공한 요청과 오류가 난 요청은 같은 tag key 셋을 단다 — Prometheus 는 key 묶음이 다른 meter 를 버린다") + void aFailedRequestCarriesTheSameTagKeysAsASuccessfulOne() { + // given + var adapter = new GraphQlRequestObservationConventionAdapter(collapsingConvention()); + observe(adapter, "Anything", null); + + // when + observe( + adapter, + "Anything", + null, + ExecutionResult.newExecutionResult() + .addError( + GraphqlErrorBuilder.newError() + .message("refused") + .errorType(ErrorType.ValidationError) + .build()) + .build()); + + // then + Set keys = + new TreeSet<>( + List.of( + "error", + "error.type", + "graphql.client.profile", + "graphql.complexity.bucket", + "graphql.depth.bucket", + "graphql.operation.name", + "graphql.operation.type", + "graphql.outcome", + "graphql.persisted")); + assertThat(requestSeries()) + .extracting( + id -> id.getTag("error.type"), + id -> id.getTag("graphql.complexity.bucket"), + id -> + id.getTags().stream() + .map(Tag::getKey) + .collect(Collectors.toCollection(TreeSet::new))) + .containsExactlyInAnyOrder( + tuple( + GraphQlRequestObservationConvention.NO_ERROR, + GraphQlRequestObservationConvention.NOT_SCORED, + keys), + tuple("REQUEST", GraphQlRequestObservationConvention.NOT_SCORED, keys)); + } + @Test void theObservationNameMatchesTheOneSpringAlreadyEmits() { var adapter = new GraphQlRequestObservationConventionAdapter(collapsingConvention()); @@ -133,6 +189,18 @@ class GraphQlRequestObservationConventionAdapterTest { GraphQlRequestObservationConventionAdapter adapter, String operationName, GraphQlRequestContext requestContext) { + observe( + adapter, + operationName, + requestContext, + ExecutionResult.newExecutionResult().data(Map.of()).build()); + } + + private void observe( + GraphQlRequestObservationConventionAdapter adapter, + String operationName, + GraphQlRequestContext requestContext, + ExecutionResult result) { ExecutionInput input = ExecutionInput.newExecutionInput("{ __typename }").operationName(operationName).build(); @@ -140,7 +208,7 @@ class GraphQlRequestObservationConventionAdapterTest { input.getGraphQLContext().put(GraphQlRequestContext.CONTEXT_KEY, requestContext); } var context = new ExecutionRequestObservationContext(input); - context.setExecutionResult(ExecutionResult.newExecutionResult().data(Map.of()).build()); + context.setExecutionResult(result); Observation.createNotStarted(adapter, () -> context, observations).observe(() -> {}); } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapterTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapterTest.java new file mode 100644 index 00000000..24237e71 --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlResolverObservationConventionAdapterTest.java @@ -0,0 +1,122 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlFieldCostDescriptor; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlResolverWeight; +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationNames; +import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlResolverObservationConvention; +import graphql.Scalars; +import graphql.execution.MergedField; +import graphql.language.Field; +import graphql.schema.DataFetchingEnvironment; +import graphql.schema.DataFetchingEnvironmentImpl; +import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLObjectType; +import io.micrometer.common.KeyValue; +import io.micrometer.common.KeyValues; +import java.lang.reflect.Constructor; +import java.util.Map; +import java.util.stream.Collectors; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.graphql.observation.DataFetcherObservationContext; + +class GraphQlResolverObservationConventionAdapterTest { + + private final GraphQlResolverObservationConventionAdapter adapter = + new GraphQlResolverObservationConventionAdapter( + GraphQlResolverObservationConvention.standard(), + GraphQlCostCatalog.of( + new GraphQlFieldCostDescriptor( + "Order.items", 2, GraphQlResolverWeight.BATCHED_RELATION, true))); + + @Test + @DisplayName("graphql.datafetcher 는 schema 좌표·결과·등록한 resolver 무게로 tag 를 단다") + void aResolverIsTaggedByItsCoordinateOutcomeAndRegisteredWeight() throws Exception { + // given + DataFetcherObservationContext context = context(environment("Order", "items")); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "graphql.schema.coordinate", "Order.items", + "graphql.outcome", GraphQlResolverObservationConventionAdapter.OUTCOME_SUCCESS, + "graphql.resolver.weight", "BATCHED_RELATION")); + } + + @Test + @DisplayName("등록하지 않은 field 는 cost 단계가 매기는 기본 무게로, 실패는 ERROR 로 단다") + void anUnregisteredFailingResolverCarriesTheDefaultWeightAndError() throws Exception { + // given + DataFetcherObservationContext context = context(environment("Query", "orders")); + context.setError(new IllegalStateException("boom")); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsEntry("graphql.outcome", GraphQlResolverObservationConventionAdapter.OUTCOME_ERROR) + .containsEntry("graphql.resolver.weight", GraphQlCostCatalog.DEFAULT_WEIGHT.name()); + } + + @Test + @DisplayName( + "좌표로 이름 붙일 수 없는 field(_Service.sdl)도 같은 tag key 셋을 unnamed·기본 무게로 단다" + + " — Prometheus 는 key 묶음이 다른 meter 를 버린다") + void aFieldNoCoordinateCanNameKeepsTheSameTagKeys() throws Exception { + // given + DataFetcherObservationContext context = context(environment("_Service", "sdl")); + + // when + Map tags = tags(adapter.getLowCardinalityKeyValues(context)); + + // then + assertThat(tags) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "graphql.schema.coordinate", + GraphQlResolverObservationConvention.UNNAMED_COORDINATE, + "graphql.outcome", + GraphQlResolverObservationConventionAdapter.OUTCOME_SUCCESS, + "graphql.resolver.weight", + GraphQlCostCatalog.DEFAULT_WEIGHT.name())); + } + + @Test + void theObservationNameMatchesTheOneSpringAlreadyEmits() { + assertThat(adapter.getName()).isEqualTo(GraphQlObservationNames.RESOLVER); + } + + private static Map tags(KeyValues keyValues) { + return keyValues.stream().collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue)); + } + + private static DataFetchingEnvironment environment(String type, String field) { + GraphQLObjectType parent = + GraphQLObjectType.newObject() + .name(type) + .field( + GraphQLFieldDefinition.newFieldDefinition().name(field).type(Scalars.GraphQLString)) + .build(); + return DataFetchingEnvironmentImpl.newDataFetchingEnvironment() + .parentType(parent) + .mergedField(MergedField.newMergedField(Field.newField(field).build()).build()) + .build(); + } + + /** The framework builds this context; its constructor is package-private. */ + private static DataFetcherObservationContext context(DataFetchingEnvironment environment) + throws ReflectiveOperationException { + Constructor constructor = + DataFetcherObservationContext.class.getDeclaredConstructor(DataFetchingEnvironment.class); + constructor.setAccessible(true); + return constructor.newInstance(environment); + } +}