This repository was archived by the owner on Apr 7, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathXGoogSpannerRequestIdTest.java
More file actions
333 lines (294 loc) · 12.2 KB
/
XGoogSpannerRequestIdTest.java
File metadata and controls
333 lines (294 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor.MethodType;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class XGoogSpannerRequestIdTest {
public static long NON_DETERMINISTIC = -1;
@Test
public void testEquals() {
XGoogSpannerRequestId reqID1 = XGoogSpannerRequestId.of(1, 1, 1, 1);
XGoogSpannerRequestId reqID2 = XGoogSpannerRequestId.of(1, 1, 1, 1);
assertEquals(reqID1, reqID2);
assertEquals(reqID1, reqID1);
assertEquals(reqID2, reqID2);
XGoogSpannerRequestId reqID3 = XGoogSpannerRequestId.of(1, 1, 1, 2);
assertNotEquals(reqID1, reqID3);
assertNotEquals(reqID3, reqID1);
assertEquals(reqID3, reqID3);
}
@Test
public void testEnsureHexadecimalFormatForRandProcessID() {
String str = XGoogSpannerRequestId.of(1, 2, 3, 4).toString();
Matcher m = XGoogSpannerRequestId.REGEX.matcher(str);
assertTrue(m.matches());
}
public static class ServerHeaderEnforcer implements ServerInterceptor {
private Map<String, CopyOnWriteArrayList<XGoogSpannerRequestId>> unaryResults;
private Map<String, CopyOnWriteArrayList<XGoogSpannerRequestId>> streamingResults;
private List<String> gotValues;
private Set<String> checkMethods;
ServerHeaderEnforcer(Set<String> checkMethods) {
this.gotValues = new CopyOnWriteArrayList<>();
this.unaryResults = new ConcurrentHashMap<>();
this.streamingResults = new ConcurrentHashMap<>();
this.checkMethods = checkMethods;
}
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call,
final Metadata requestHeaders,
ServerCallHandler<ReqT, RespT> next) {
boolean isUnary = call.getMethodDescriptor().getType() == MethodType.UNARY;
String methodName = call.getMethodDescriptor().getFullMethodName();
String gotReqIdStr = requestHeaders.get(XGoogSpannerRequestId.REQUEST_HEADER_KEY);
if (!this.checkMethods.contains(methodName)) {
return next.startCall(call, requestHeaders);
}
Map<String, CopyOnWriteArrayList<XGoogSpannerRequestId>> saver = this.streamingResults;
if (isUnary) {
saver = this.unaryResults;
}
if (Objects.equals(gotReqIdStr, null) || Objects.equals(gotReqIdStr, "")) {
Status status =
Status.fromCode(Status.Code.INVALID_ARGUMENT)
.augmentDescription(
methodName + " lacks " + XGoogSpannerRequestId.REQUEST_HEADER_KEY);
call.close(status, requestHeaders);
return next.startCall(call, requestHeaders);
}
assertNotNull(gotReqIdStr);
// Firstly assert and validate that at least we've got a requestId.
Matcher m = XGoogSpannerRequestId.REGEX.matcher(gotReqIdStr);
assertTrue(m.matches());
XGoogSpannerRequestId reqId = XGoogSpannerRequestId.of(gotReqIdStr);
if (!saver.containsKey(methodName)) {
saver.put(methodName, new CopyOnWriteArrayList<XGoogSpannerRequestId>());
}
saver.get(methodName).add(reqId);
// Finally proceed with the call.
return next.startCall(call, requestHeaders);
}
public String[] accumulatedValues() {
return this.gotValues.toArray(new String[0]);
}
public void assertIntegrity() {
this.unaryResults.forEach(
(String method, CopyOnWriteArrayList<XGoogSpannerRequestId> values) -> {
assertMonotonicityOfIds(method, values);
});
this.streamingResults.forEach(
(String method, CopyOnWriteArrayList<XGoogSpannerRequestId> values) -> {
assertMonotonicityOfIds(method, values);
});
}
private void assertMonotonicityOfIds(String prefix, List<XGoogSpannerRequestId> reqIds) {
reqIds.sort(
(id1, id2) -> {
if (id1.equals(id2)) return 0;
return id1.isGreaterThan(id2) ? 1 : -1;
});
int size = reqIds.size();
List<String> violations = new ArrayList<>();
for (int i = 1; i < size; i++) {
XGoogSpannerRequestId prev = reqIds.get(i - 1);
XGoogSpannerRequestId curr = reqIds.get(i);
if (prev.isGreaterThan(curr)) {
violations.add(String.format("#%d(%s) > #%d(%s)", i - 1, prev, i, curr));
}
}
if (violations.isEmpty()) {
return;
}
throw new IllegalStateException(
prefix
+ " monotonicity violation:"
+ String.join("\n\t", violations.toArray(new String[0])));
}
public MethodAndRequestId[] accumulatedUnaryValues() {
List<MethodAndRequestId> accumulated = new ArrayList<>();
this.unaryResults.forEach(
(String method, CopyOnWriteArrayList<XGoogSpannerRequestId> values) -> {
for (int i = 0; i < values.size(); i++) {
accumulated.add(new MethodAndRequestId(method, values.get(i)));
}
});
return accumulated.toArray(new MethodAndRequestId[0]);
}
public MethodAndRequestId[] accumulatedStreamingValues() {
List<MethodAndRequestId> accumulated = new ArrayList<>();
this.streamingResults.forEach(
(String method, CopyOnWriteArrayList<XGoogSpannerRequestId> values) -> {
for (int i = 0; i < values.size(); i++) {
accumulated.add(new MethodAndRequestId(method, values.get(i)));
}
});
return accumulated.toArray(new MethodAndRequestId[0]);
}
public void checkExpectedUnaryXGoogRequestIds(MethodAndRequestId... wantUnaryValues) {
MethodAndRequestId[] gotUnaryValues = this.accumulatedUnaryValues();
sortValues(gotUnaryValues);
for (int i = 0; i < gotUnaryValues.length && false; i++) {
System.out.println("\033[33misUnary: #" + i + ":: " + gotUnaryValues[i] + "\033[00m");
}
assertEquals(wantUnaryValues, gotUnaryValues);
}
public void checkAtLeastHasExpectedUnaryXGoogRequestIds(MethodAndRequestId... wantUnaryValues) {
MethodAndRequestId[] gotUnaryValues = this.accumulatedUnaryValues();
sortValues(gotUnaryValues);
for (int i = 0; i < gotUnaryValues.length && false; i++) {
System.out.println("\033[33misUnary: #" + i + ":: " + gotUnaryValues[i] + "\033[00m");
}
if (wantUnaryValues.length < gotUnaryValues.length) {
MethodAndRequestId[] gotSliced =
Arrays.copyOfRange(gotUnaryValues, 0, wantUnaryValues.length);
assertEquals(wantUnaryValues, gotSliced);
} else {
assertEquals(wantUnaryValues, gotUnaryValues);
}
}
public void checkExpectedUnaryXGoogRequestIdsAsSuffixes(MethodAndRequestId... wantUnaryValues) {
MethodAndRequestId[] gotUnaryValues = this.accumulatedUnaryValues();
sortValues(gotUnaryValues);
for (int i = 0; i < gotUnaryValues.length && false; i++) {
System.out.println("\033[33misUnary: #" + i + ":: " + gotUnaryValues[i] + "\033[00m");
}
if (wantUnaryValues.length < gotUnaryValues.length) {
MethodAndRequestId[] gotSliced =
Arrays.copyOfRange(
gotUnaryValues,
gotUnaryValues.length - wantUnaryValues.length,
gotUnaryValues.length);
assertEquals(wantUnaryValues, gotSliced);
} else {
assertEquals(wantUnaryValues, gotUnaryValues);
}
}
private void sortValues(MethodAndRequestId[] values) {
massageValues(values);
Arrays.sort(values, new MethodAndRequestIdComparator());
}
public void checkExpectedStreamingXGoogRequestIds(MethodAndRequestId... wantStreamingValues) {
MethodAndRequestId[] gotStreamingValues = this.accumulatedStreamingValues();
for (int i = 0; i < gotStreamingValues.length && false; i++) {
System.out.println(
"\033[32misStreaming: #" + i + ":: " + gotStreamingValues[i] + "\033[00m");
}
sortValues(gotStreamingValues);
assertEquals(wantStreamingValues, gotStreamingValues);
}
public void reset() {
this.gotValues.clear();
this.unaryResults.clear();
this.streamingResults.clear();
}
}
public static class MethodAndRequestId {
String method;
XGoogSpannerRequestId requestId;
public MethodAndRequestId(String method, XGoogSpannerRequestId requestId) {
this.method = method;
this.requestId = requestId;
}
public String toString() {
return "{" + this.method + ":" + this.requestId.debugToString() + "}";
}
@Override
public boolean equals(Object o) {
if (!(o instanceof MethodAndRequestId)) {
return false;
}
MethodAndRequestId other = (MethodAndRequestId) o;
return Objects.equals(this.method, other.method)
&& Objects.equals(this.requestId, other.requestId);
}
}
static class MethodAndRequestIdComparator implements Comparator<MethodAndRequestId> {
@Override
public int compare(MethodAndRequestId mr1, MethodAndRequestId mr2) {
int cmpMethod = mr1.method.compareTo(mr2.method);
if (cmpMethod != 0) {
return cmpMethod;
}
if (Objects.equals(mr1.requestId, mr2.requestId)) {
return 0;
}
if (mr1.requestId.isGreaterThan(mr2.requestId)) {
return +1;
}
return -1;
}
}
static void massageValues(MethodAndRequestId[] mreqs) {
for (int i = 0; i < mreqs.length; i++) {
MethodAndRequestId mreq = mreqs[i];
// BatchCreateSessions is so hard to control as the round-robin doling out
// hence we might need to be able to scrub the nth_request that won't match
// nth_req in consecutive order of nth_client.
if (mreq.method.compareTo("google.spanner.v1.Spanner/BatchCreateSessions") == 0) {
mreqs[i] =
new MethodAndRequestId(
mreq.method,
mreq.requestId
.withNthRequest(NON_DETERMINISTIC)
.withChannelId(NON_DETERMINISTIC)
.withNthClientId(NON_DETERMINISTIC));
} else if (mreq.method.compareTo("google.spanner.v1.Spanner/BeginTransaction") == 0
|| mreq.method.compareTo("google.spanner.v1.Spanner/ExecuteStreamingSql") == 0
|| mreq.method.compareTo("google.spanner.v1.Spanner/ExecuteSql") == 0
|| mreq.method.compareTo("google.spanner.v1.Spanner/CreateSession") == 0
|| mreq.method.compareTo("google.spanner.v1.Spanner/Commit") == 0) {
mreqs[i] =
new MethodAndRequestId(
mreq.method,
mreq.requestId
.withNthClientId(NON_DETERMINISTIC)
.withChannelId(NON_DETERMINISTIC)
.withNthRequest(NON_DETERMINISTIC)
.withAttempt(NON_DETERMINISTIC));
}
}
}
public static MethodAndRequestId ofMethodAndRequestId(String method, String reqId) {
return new MethodAndRequestId(method, XGoogSpannerRequestId.of(reqId));
}
public static MethodAndRequestId ofMethodAndRequestId(
String method, XGoogSpannerRequestId reqId) {
return new MethodAndRequestId(method, reqId);
}
}