|
| 1 | +// Copyright 2026 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +using Google.Cloud.Spanner.V1.Internal.Logging; |
| 16 | +using Google.Protobuf.WellKnownTypes; |
| 17 | +using Grpc.Core; |
| 18 | +using System; |
| 19 | +using System.Linq; |
| 20 | +using System.Threading; |
| 21 | +using System.Threading.Tasks; |
| 22 | +using Xunit; |
| 23 | +using static Google.Cloud.Spanner.V1.Tests.MetricsCapture; |
| 24 | +using static Google.Cloud.Spanner.V1.Tests.SpannerBuiltInMetricsInterceptorTests; |
| 25 | +using static Google.Cloud.Spanner.V1.Tests.SpannerBuiltInMetricsWrapperTests; |
| 26 | + |
| 27 | +namespace Google.Cloud.Spanner.V1.Tests; |
| 28 | + |
| 29 | +public class SpannerBuiltInMetricsInstrumentedOperationStreamReaderTests |
| 30 | +{ |
| 31 | + private static readonly SpannerBuiltInMetrics.ClientIdentity s_readerClientIdentity = SpannerBuiltInMetrics.Labeler.GenerateIdentity(); |
| 32 | + private static readonly ExecuteSqlRequest s_request = new() { SessionAsSessionName = s_sessionName }; |
| 33 | + |
| 34 | + public static TheoryData<int[]> StreamItemCases => new() |
| 35 | + { |
| 36 | + { [] }, |
| 37 | + { [1] }, |
| 38 | + { [1, 2, 3] }, |
| 39 | + }; |
| 40 | + |
| 41 | + public static TheoryData<Exception, StatusCode> InnerExceptionCases => new() |
| 42 | + { |
| 43 | + { new RpcException(new Status(StatusCode.NotFound, "Test")), StatusCode.NotFound }, |
| 44 | + { new RpcException(new Status(StatusCode.DeadlineExceeded, "Test")), StatusCode.DeadlineExceeded }, |
| 45 | + { new RpcException(new Status(StatusCode.Cancelled, "Cancelled")), StatusCode.Cancelled }, |
| 46 | + { new OperationCanceledException("Operation was cancelled."), StatusCode.Unknown }, |
| 47 | + { new InvalidOperationException("Test"), StatusCode.Unknown }, |
| 48 | + }; |
| 49 | + |
| 50 | + [Theory] |
| 51 | + [MemberData(nameof(StreamItemCases))] |
| 52 | + public async Task ConsumedStream_NoException_EmitsMetrics(int[] values) |
| 53 | + { |
| 54 | + var (reader, stopwatch) = CreateReader(values); |
| 55 | + |
| 56 | + var measurements = await RunWithMeterListenerAsync(() => ConsumeReaderAsync(reader)); |
| 57 | + |
| 58 | + AssertRecordedData(measurements, s_readerClientIdentity.Id, "ExecuteStreamingSql", StatusCode.OK.ToString()); |
| 59 | + Assert.True(stopwatch.Stopped); |
| 60 | + } |
| 61 | + |
| 62 | + [Theory] |
| 63 | + [MemberData(nameof(InnerExceptionCases))] |
| 64 | + public async Task ConsumedStream_InnerException_EmitsMetrics(Exception exception, StatusCode expectedStatus) |
| 65 | + { |
| 66 | + var (reader, stopwatch) = CreateReader(exception: exception); |
| 67 | + |
| 68 | + var measurements = await RunWithMeterListenerAsync(async () => |
| 69 | + { |
| 70 | + var thrown = await Assert.ThrowsAnyAsync<Exception>(() => ConsumeReaderAsync(reader)); |
| 71 | + Assert.Same(exception, thrown); |
| 72 | + }); |
| 73 | + |
| 74 | + AssertRecordedData(measurements, s_readerClientIdentity.Id, "ExecuteStreamingSql", expectedStatus.ToString()); |
| 75 | + Assert.True(stopwatch.Stopped); |
| 76 | + } |
| 77 | + |
| 78 | + [Fact] |
| 79 | + public async Task ClosedBeforeCompletion_Emits() |
| 80 | + { |
| 81 | + var (reader, stopwatch) = CreateReader(); |
| 82 | + |
| 83 | + var measurements = await RunWithMeterListenerAsync(async () => |
| 84 | + { |
| 85 | + await reader.NextAsync(CancellationToken.None); |
| 86 | + reader.Close(); |
| 87 | + }); |
| 88 | + |
| 89 | + AssertRecordedData(measurements, s_readerClientIdentity.Id, "ExecuteStreamingSql", StatusCode.Unknown.ToString()); |
| 90 | + Assert.True(stopwatch.Stopped); |
| 91 | + } |
| 92 | + |
| 93 | + [Fact] |
| 94 | + public async Task DisposedBeforeCompletion_Emits() |
| 95 | + { |
| 96 | + var (reader, stopwatch) = CreateReader(); |
| 97 | + |
| 98 | + var measurements = await RunWithMeterListenerAsync(async () => |
| 99 | + { |
| 100 | + await reader.NextAsync(CancellationToken.None); |
| 101 | + reader.Dispose(); |
| 102 | + }); |
| 103 | + |
| 104 | + AssertRecordedData(measurements, s_readerClientIdentity.Id, "ExecuteStreamingSql", StatusCode.Unknown.ToString()); |
| 105 | + Assert.True(stopwatch.Stopped); |
| 106 | + } |
| 107 | + |
| 108 | + [Fact] |
| 109 | + public async Task ClosedAfterCompletion_EmitsOnce() |
| 110 | + { |
| 111 | + var (reader, stopwatch) = CreateReader(); |
| 112 | + |
| 113 | + var measurements = await RunWithMeterListenerAsync(async () => |
| 114 | + { |
| 115 | + // Only the first call should result in metrics being emitted |
| 116 | + await ConsumeReaderAsync(reader); |
| 117 | + reader.Close(); |
| 118 | + reader.Dispose(); |
| 119 | + }); |
| 120 | + |
| 121 | + AssertRecordedData(measurements, s_readerClientIdentity.Id, "ExecuteStreamingSql", StatusCode.OK.ToString()); |
| 122 | + Assert.True(stopwatch.Stopped); |
| 123 | + } |
| 124 | + |
| 125 | + [Fact] |
| 126 | + public void Disposed_DisposesInnerStream() |
| 127 | + { |
| 128 | + var inner = new DisposableAsyncStreamReader(); |
| 129 | + var instrumentedStream = new SpannerBuiltInMetrics.InstrumentedOperationStreamReader( |
| 130 | + inner, |
| 131 | + s_stopwatchProvider.StartNew(), |
| 132 | + "ExecuteStreamingSql", |
| 133 | + s_request, |
| 134 | + s_readerClientIdentity); |
| 135 | + |
| 136 | + instrumentedStream.Dispose(); |
| 137 | + |
| 138 | + Assert.True(inner.Disposed); |
| 139 | + } |
| 140 | + |
| 141 | + /// <summary> |
| 142 | + /// Creates a reader over a stream with one <see cref="PartialResultSet"/> per value in <paramref name="values"/>. |
| 143 | + /// </summary> |
| 144 | + private static (ReliableStreamReader reader, FakeStopwatch stopwatch) CreateReader(int[] values = null, Exception exception = null) |
| 145 | + { |
| 146 | + var stopwatch = (FakeStopwatch) s_stopwatchProvider.StartNew(); |
| 147 | + var resultSets = (values ?? [1]).Select(value => new PartialResultSet |
| 148 | + { |
| 149 | + // Spanner encodes INT64 values as strings. |
| 150 | + Values = { Value.ForString(value.ToString()) }, |
| 151 | + Metadata = new ResultSetMetadata |
| 152 | + { |
| 153 | + RowType = new StructType |
| 154 | + { |
| 155 | + Fields = { new StructType.Types.Field { Name = "col1", Type = new Type { Code = TypeCode.Int64 } } } |
| 156 | + } |
| 157 | + } |
| 158 | + }).ToList(); |
| 159 | + |
| 160 | + var fakeStream = new FakeAsyncStreamReader<PartialResultSet>(resultSets, exception); |
| 161 | + var instrumentedStream = new SpannerBuiltInMetrics.InstrumentedOperationStreamReader( |
| 162 | + fakeStream, |
| 163 | + stopwatch, |
| 164 | + "ExecuteStreamingSql", |
| 165 | + s_request, |
| 166 | + s_readerClientIdentity); |
| 167 | + var reader = new ReliableStreamReader(instrumentedStream, Logger.DefaultLogger); |
| 168 | + return (reader, stopwatch); |
| 169 | + } |
| 170 | + |
| 171 | + private static async Task ConsumeReaderAsync(ReliableStreamReader reader) |
| 172 | + { |
| 173 | + while (await reader.NextAsync(CancellationToken.None) != null) |
| 174 | + { |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + private sealed class DisposableAsyncStreamReader : IAsyncStreamReader<PartialResultSet>, IDisposable |
| 179 | + { |
| 180 | + public bool Disposed { get; private set; } |
| 181 | + |
| 182 | + public PartialResultSet Current => null; |
| 183 | + |
| 184 | + public Task<bool> MoveNext(CancellationToken cancellationToken) => Task.FromResult(false); |
| 185 | + |
| 186 | + public void Dispose() => Disposed = true; |
| 187 | + } |
| 188 | +} |
0 commit comments