This repository has been archived by the owner on Dec 17, 2024. It is now read-only.
forked from lizan/service-control-client-cxx
-
Notifications
You must be signed in to change notification settings - Fork 10
/
service_control_client_impl_quota_test.cc
508 lines (408 loc) · 17.9 KB
/
service_control_client_impl_quota_test.cc
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/* Copyright 2017 Google Inc. All Rights Reserved.
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
http://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.
==============================================================================*/
#include <chrono>
#include <thread>
#include "src/mock_transport.h"
namespace google {
namespace service_control_client {
namespace {
const char kServiceName[] = "library.googleapis.com";
const char kServiceConfigId[] = "2016-09-19r0";
const char kRequest1[] = R"(
service_name: "library.googleapis.com"
allocate_operation {
operation_id: "operation-1"
method_name: "methodname"
consumer_id: "consumerid"
quota_metrics {
metric_name: "metric_first"
metric_values {
int64_value: 1
}
}
quota_metrics {
metric_name: "metric_second"
metric_values {
int64_value: 1
}
}
quota_mode: BEST_EFFORT
}
service_config_id: "2016-09-19r0"
)";
const char kSuccessResponse1[] = R"(
operation_id: "operation-1"
quota_metrics {
metric_name: "serviceruntime.googleapis.com/api/consumer/quota_used_count"
metric_values {
labels {
key: "/quota_name"
value: "metric_first"
}
int64_value: 1
}
metric_values {
labels {
key: "/quota_name"
value: "metric_first"
}
int64_value: 1
}
}
service_config_id: "2016-09-19r0"
)";
const char kErrorResponse1[] = R"(
operation_id: "operation-1"
allocate_errors {
code: RESOURCE_EXHAUSTED
subject: "user:integration_test_user"
}
)";
} // namespace
class ServiceControlClientImplQuotaTest : public testing::Test {
public:
void SetUp() {
ASSERT_TRUE(TextFormat::ParseFromString(kRequest1, "a_request1_));
ASSERT_TRUE(
TextFormat::ParseFromString(kSuccessResponse1, &pass_quota_response1_));
ASSERT_TRUE(
TextFormat::ParseFromString(kErrorResponse1, &error_quota_response1_));
// Initialize the client instance with cache enabled
ServiceControlClientOptions cached_options(
CheckAggregationOptions(10 /*entries */, 500 /* refresh_interval_ms */,
1000 /* expiration_ms */),
QuotaAggregationOptions(10 /*entries */, 500 /* refresh_interval_ms */),
ReportAggregationOptions(10 /* entries */, 500 /*flush_interval_ms*/));
cached_options.quota_transport = mock_quota_transport_.GetFunc();
cached_client_ = CreateServiceControlClient(kServiceName, kServiceConfigId,
cached_options);
// Initialize the client instance with cache disabled
ServiceControlClientOptions noncached_options(
CheckAggregationOptions(0, 500, 1000), QuotaAggregationOptions(0, 500),
ReportAggregationOptions(0, 500));
noncached_options.quota_transport = mock_quota_transport_.GetFunc();
noncached_client_ = CreateServiceControlClient(
kServiceName, kServiceConfigId, noncached_options);
}
AllocateQuotaRequest quota_request1_;
AllocateQuotaResponse pass_quota_response1_;
AllocateQuotaResponse error_quota_response1_;
// Store some commonly used variables as member variables to prevent
// use-after-destruction in tests.
AllocateQuotaResponse quota_response_;
// Clients must be the second to be destructed.
// During destruction, the internal caches will be flushed and results will
// be written to the variables above.
std::unique_ptr<ServiceControlClient> cached_client_;
std::unique_ptr<ServiceControlClient> noncached_client_;
// Transports must be first to be destructed.
// During destruction, threads will complete and results will be written to
// the caches above.
MockQuotaTransport mock_quota_transport_;
};
// Error on different service name
TEST_F(ServiceControlClientImplQuotaTest, TestQuotaWithInvalidServiceName) {
ServiceControlClientOptions options(CheckAggregationOptions(10, 500, 1000),
QuotaAggregationOptions(10, 500),
ReportAggregationOptions(10, 500));
options.quota_transport = mock_quota_transport_.GetFunc();
std::unique_ptr<ServiceControlClient> client =
CreateServiceControlClient("unknown", kServiceConfigId, options);
absl::Status done_status = absl::UnknownError("");
AllocateQuotaResponse quota_response;
client->Quota(quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
EXPECT_EQ(
done_status,
absl::Status(
absl::StatusCode::kInvalidArgument,
"Invalid service name: library.googleapis.com Expecting: unknown"));
// count store callback
EXPECT_EQ(mock_quota_transport_.on_done_vector_.size(), 0);
Statistics stat;
absl::Status stat_status = client->GetStatistics(&stat);
EXPECT_EQ(stat_status, absl::OkStatus());
EXPECT_EQ(stat.total_called_quotas, 1);
EXPECT_EQ(stat.send_quotas_by_flush, 0);
EXPECT_EQ(stat.send_quotas_in_flight, 0);
}
// Error on default callback is not assigned
TEST_F(ServiceControlClientImplQuotaTest,
TestQuotaWithNoDefaultQuotaTransport) {
ServiceControlClientOptions options(CheckAggregationOptions(10, 500, 1000),
QuotaAggregationOptions(10, 500),
ReportAggregationOptions(10, 500));
options.quota_transport = nullptr;
absl::Status done_status = absl::UnknownError("");
AllocateQuotaResponse quota_response;
std::unique_ptr<ServiceControlClient> client =
CreateServiceControlClient("unknown", kServiceConfigId, options);
client->Quota(quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
EXPECT_EQ(done_status, absl::Status(absl::StatusCode::kInvalidArgument,
"transport is NULL."));
// count store callback
EXPECT_EQ(mock_quota_transport_.on_done_vector_.size(), 0);
Statistics stat;
absl::Status stat_status = client->GetStatistics(&stat);
EXPECT_EQ(stat_status, absl::OkStatus());
EXPECT_EQ(stat.total_called_quotas, 1);
EXPECT_EQ(stat.send_quotas_by_flush, 0);
EXPECT_EQ(stat.send_quotas_in_flight, 0);
}
// Cached: false, Callback: stored
TEST_F(ServiceControlClientImplQuotaTest,
TestNonCachedQuotaWithStoredCallbackMultipleReqeusts) {
EXPECT_CALL(mock_quota_transport_, Quota(_, _, _))
.WillRepeatedly(
Invoke(&mock_quota_transport_,
&MockQuotaTransport::AllocateQuotaWithStoredCallback));
absl::Status done_status = absl::UnknownError("");
AllocateQuotaResponse quota_response;
// call Quota 10 times
for (int i = 0; i < 10; i++) {
noncached_client_->Quota(
quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
EXPECT_EQ(done_status, absl::UnknownError(""));
}
// count store callback
EXPECT_EQ(mock_quota_transport_.on_done_vector_.size(), 10);
// execute stored callback
for (auto callback : mock_quota_transport_.on_done_vector_) {
done_status = absl::UnknownError("");
callback(absl::OkStatus());
EXPECT_EQ(done_status, absl::OkStatus());
}
Statistics stat;
absl::Status stat_status = noncached_client_->GetStatistics(&stat);
EXPECT_EQ(stat_status, absl::OkStatus());
EXPECT_EQ(stat.total_called_quotas, 10);
EXPECT_EQ(stat.send_quotas_by_flush, 0);
EXPECT_EQ(stat.send_quotas_in_flight, 10);
}
TEST_F(ServiceControlClientImplQuotaTest, TestCachedQuotaRefreshGotHTTPError) {
// Set callback function to return the negative response
mock_quota_transport_.quota_response_ = &error_quota_response1_;
mock_quota_transport_.done_status_ = absl::OkStatus();
EXPECT_CALL(mock_quota_transport_, Quota(_, _, _))
.WillRepeatedly(
Invoke(&mock_quota_transport_,
&MockQuotaTransport::AllocateQuotaWithInplaceCallback));
absl::Status done_status = absl::UnknownError("");
AllocateQuotaResponse quota_response;
// Triggers the initial AllocateQuotaRequset and insert a temporary positive
// response to quota cache.
cached_client_->Quota(
quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
EXPECT_EQ(done_status, absl::OkStatus());
// Check quota_response is positive
EXPECT_EQ(quota_response.allocate_errors_size(), 0);
// AllocateQuotaFlushCallback replaces the cached response with the
// negative response, QUOTA_EXHAUSTED
// Set the callback function to return a fail-close negative status, e.g.
// absl::CancelledError, to simulate HTTP error. A fail-close negative status
// will be cached as a negative response.
absl::Status cancelledError = absl::CancelledError("cancelled error");
mock_quota_transport_.done_status_ = cancelledError;
// Wait 600ms to let the cached response expire.
// This sleep will not trigger a remote quota call since test did not provide
// a timer object. The refresh remote quota call is triggered by cache lookup
// in the "Quota" call, for an expired entry, if it has aggregated cost or it
// is negative, make a remote quota call.
std::this_thread::sleep_for(std::chrono::milliseconds(600));
// Next Quota call reads the cached negative response, QUOTA_EXHAUSTED, and
// triggers the quota cache refresh. Theabsl::CancelledError response will be
// cached after this.
cached_client_->Quota(
quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
// Check the cached response is the first cached response - QUOTA_EXHAUSTED.
EXPECT_EQ(quota_response.allocate_errors_size(), 1);
EXPECT_EQ(quota_response.allocate_errors()[0].code(),
error_quota_response1_.allocate_errors()[0].code());
// AllocateQuotaFlushCallback replaces the cached negative response with
// the newly cached negative response -absl::CancelledError.
// Set the callback function to return a fail-open negative status, e.g.
// InternalError. A fail-open dummy response will be cached as a positive
// response.
mock_quota_transport_.done_status_ = absl::InternalError("internal error");
// Wait 600ms to let the cached response expire.
std::this_thread::sleep_for(std::chrono::milliseconds(600));
// Read the previously cachedabsl::CancelledError response, since it is a
// negative response, it will trigger a new remote quota call. The new
// fail-open InternalError response will be cached right after.
cached_client_->Quota(
quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
// Check the returned response is the previously cachedabsl::CancelledError
// response. A fail-close error response is cached as:
// AllocateQuoteResponse{allocate_errors:[QuotaError{code:UNSPECIFIED,status:error_status}]}
EXPECT_EQ(quota_response.allocate_errors_size(), 1);
EXPECT_EQ(quota_response.allocate_errors()[0].status().code(),
(int)cancelledError.code());
EXPECT_EQ(quota_response.allocate_errors()[0].status().message(),
cancelledError.message());
// Read the newly cached positive dummy response for fail-open.
// The dummy response contains no allocate errors.
cached_client_->Quota(
quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
EXPECT_EQ(quota_response.allocate_errors_size(), 0);
Statistics stat;
absl::Status stat_status = cached_client_->GetStatistics(&stat);
EXPECT_EQ(stat_status, absl::OkStatus());
EXPECT_EQ(stat.total_called_quotas, 4);
EXPECT_EQ(stat.send_quotas_by_flush, 3);
EXPECT_EQ(stat.send_quotas_in_flight, 0);
}
// Cached: true, Callback: stored
TEST_F(ServiceControlClientImplQuotaTest, TestCachedQuotaWithStoredCallback) {
EXPECT_CALL(mock_quota_transport_, Quota(_, _, _))
.WillOnce(Invoke(&mock_quota_transport_,
&MockQuotaTransport::AllocateQuotaWithStoredCallback));
absl::Status done_status = absl::UnknownError("");
AllocateQuotaResponse quota_response;
cached_client_->Quota(
quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
EXPECT_EQ(done_status, absl::OkStatus());
// call Quota 10 times
for (int i = 0; i < 10; i++) {
absl::Status cached_done_status = absl::UnknownError("");
AllocateQuotaResponse cached_quota_response;
cached_client_->Quota(quota_request1_, &cached_quota_response,
[&cached_done_status](absl::Status status) {
cached_done_status = status;
});
EXPECT_EQ(cached_done_status, absl::OkStatus());
}
// count stored callback
EXPECT_EQ(mock_quota_transport_.on_done_vector_.size(), 1);
// execute stored callback
mock_quota_transport_.on_done_vector_[0](absl::OkStatus());
EXPECT_EQ(done_status, absl::OkStatus());
Statistics stat;
absl::Status stat_status = cached_client_->GetStatistics(&stat);
EXPECT_EQ(stat_status, absl::OkStatus());
EXPECT_EQ(stat.total_called_quotas, 11);
EXPECT_EQ(stat.send_quotas_by_flush, 1);
EXPECT_EQ(stat.send_quotas_in_flight, 0);
}
// Cached: false, Callback: in place
TEST_F(ServiceControlClientImplQuotaTest,
TestNonCachedQuotaWithInPlaceCallbackMultipleReqeusts) {
EXPECT_CALL(mock_quota_transport_, Quota(_, _, _))
.WillRepeatedly(
Invoke(&mock_quota_transport_,
&MockQuotaTransport::AllocateQuotaWithInplaceCallback));
// call Quota 10 times
for (int i = 0; i < 10; i++) {
AllocateQuotaResponse quota_response;
absl::Status done_status = absl::UnknownError("");
noncached_client_->Quota(
quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
EXPECT_EQ(done_status, absl::OkStatus());
}
// count store callback
EXPECT_EQ(mock_quota_transport_.on_done_vector_.size(), 0);
Statistics stat;
absl::Status stat_status = noncached_client_->GetStatistics(&stat);
EXPECT_EQ(stat_status, absl::OkStatus());
EXPECT_EQ(stat.total_called_quotas, 10);
EXPECT_EQ(stat.send_quotas_by_flush, 0);
EXPECT_EQ(stat.send_quotas_in_flight, 10);
}
// Cached: true, Callback: in place
TEST_F(ServiceControlClientImplQuotaTest, TestCachedQuotaWithInPlaceCallback) {
EXPECT_CALL(mock_quota_transport_, Quota(_, _, _))
.WillRepeatedly(
Invoke(&mock_quota_transport_,
&MockQuotaTransport::AllocateQuotaWithInplaceCallback));
absl::Status done_status = absl::UnknownError("");
AllocateQuotaResponse quota_response;
cached_client_->Quota(
quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
EXPECT_EQ(done_status, absl::OkStatus());
// call Quota 10 times
for (int i = 0; i < 10; i++) {
cached_client_->Quota(
quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
EXPECT_EQ(done_status, absl::OkStatus());
}
// count store callback
EXPECT_EQ(mock_quota_transport_.on_done_vector_.size(), 0);
Statistics stat;
absl::Status stat_status = cached_client_->GetStatistics(&stat);
EXPECT_EQ(stat_status, absl::OkStatus());
EXPECT_EQ(stat.total_called_quotas, 11);
EXPECT_EQ(stat.send_quotas_by_flush, 1);
EXPECT_EQ(stat.send_quotas_in_flight, 0);
}
// Cached: false, Callback: local in place
TEST_F(ServiceControlClientImplQuotaTest,
TestNonCachedQuotaWithLocalInPlaceCallback) {
absl::Status done_status = absl::UnknownError("");
AllocateQuotaResponse quota_response;
int callbackExecuteCount = 0;
noncached_client_->Quota(
quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; },
[&callbackExecuteCount](const AllocateQuotaRequest& request,
AllocateQuotaResponse* response,
TransportDoneFunc on_done) {
callbackExecuteCount++;
on_done(absl::OkStatus());
});
EXPECT_EQ(done_status, absl::OkStatus());
EXPECT_EQ(callbackExecuteCount, 1);
// count store callback
EXPECT_EQ(mock_quota_transport_.on_done_vector_.size(), 0);
Statistics stat;
absl::Status stat_status = noncached_client_->GetStatistics(&stat);
EXPECT_EQ(stat_status, absl::OkStatus());
EXPECT_EQ(stat.total_called_quotas, 1);
EXPECT_EQ(stat.send_quotas_by_flush, 0);
EXPECT_EQ(stat.send_quotas_in_flight, 1);
}
// Cached: false, Callback: in place
TEST_F(ServiceControlClientImplQuotaTest,
TestNonCachedQuotaWithInplaceCallbackNetworkErrorFailOpen) {
// Set the callback function to return a gRPC error. When there's a gRPC
// error, we consider it a fail-open network error.
mock_quota_transport_.done_status_ = absl::CancelledError("cancelled error");
EXPECT_CALL(mock_quota_transport_, Quota(_, _, _))
.WillOnce(Invoke(&mock_quota_transport_,
&MockQuotaTransport::AllocateQuotaWithInplaceCallback));
absl::Status done_status = absl::OkStatus();
AllocateQuotaResponse quota_response;
noncached_client_->Quota(
quota_request1_, "a_response,
[&done_status](absl::Status status) { done_status = status; });
// done_status should be set toabsl::CancelledError immediately since there's
// no cache.
EXPECT_EQ(done_status, absl::CancelledError("cancelled error"));
// Since errors are fail-open, quota_response should contain no error.
EXPECT_EQ(quota_response.allocate_errors_size(), 0);
Statistics stat;
absl::Status stat_status = noncached_client_->GetStatistics(&stat);
EXPECT_EQ(stat_status, absl::OkStatus());
EXPECT_EQ(stat.total_called_quotas, 1);
EXPECT_EQ(stat.send_quotas_by_flush, 0);
EXPECT_EQ(stat.send_quotas_in_flight, 1);
}
} // namespace service_control_client
} // namespace google