Debian Codegraph @

test/core/xds/xds_client_test.cc

raw
1 //
2 // Copyright 2022 gRPC authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 // TODO(roth): Add the following tests:
18 // - tests for DumpClientConfigBinary()
19 // - tests for load-reporting APIs? (or maybe move those out of XdsClient?)
20
21 #include "src/core/ext/xds/xds_client.h"
22
23 #include <stdint.h>
24
25 #include <algorithm>
26 #include <deque>
27 #include <map>
28 #include <memory>
29 #include <string>
30
31 #include <google/protobuf/any.pb.h>
32 #include <google/protobuf/struct.pb.h>
33
34 #include "absl/strings/str_cat.h"
35 #include "absl/time/time.h"
36 #include "absl/types/optional.h"
37 #include "absl/types/variant.h"
38 #include "gmock/gmock.h"
39 #include "gtest/gtest.h"
40 #include "upb/def.h"
41
42 #include <grpc/grpc.h>
43 #include <grpc/support/log.h>
44 #include <grpcpp/impl/codegen/config_protobuf.h>
45
46 #include "src/core/ext/xds/xds_bootstrap.h"
47 #include "src/core/ext/xds/xds_resource_type_impl.h"
48 #include "src/core/lib/gprpp/debug_location.h"
49 #include "src/core/lib/gprpp/env.h"
50 #include "src/core/lib/gprpp/sync.h"
51 #include "src/core/lib/json/json.h"
52 #include "src/core/lib/json/json_args.h"
53 #include "src/core/lib/json/json_object_loader.h"
54 #include "src/proto/grpc/testing/xds/v3/base.pb.h"
55 #include "src/proto/grpc/testing/xds/v3/discovery.pb.h"
56 #include "test/core/util/test_config.h"
57 #include "test/core/xds/xds_transport_fake.h"
58
59 // IWYU pragma: no_include <google/protobuf/message.h>
60 // IWYU pragma: no_include <google/protobuf/stubs/status.h>
61 // IWYU pragma: no_include <google/protobuf/unknown_field_set.h>
62 // IWYU pragma: no_include <google/protobuf/util/json_util.h>
63
64 using envoy::service::discovery::v3::DiscoveryRequest;
65 using envoy::service::discovery::v3::DiscoveryResponse;
66
67 namespace grpc_core {
68 namespace testing {
69 namespace {
70
71 class XdsClientTest : public ::testing::Test {
72 protected:
73 // A fake bootstrap implementation that allows tests to populate the
74 // fields however they want.
75 class FakeXdsBootstrap : public XdsBootstrap {
76 public:
77 class FakeNode : public Node {
78 public:
79 const std::string& id() const override { return id_; }
80 const std::string& cluster() const override { return cluster_; }
81 const std::string& locality_region() const override {
82 return locality_region_;
83 }
84 const std::string& locality_zone() const override {
85 return locality_zone_;
86 }
87 const std::string& locality_sub_zone() const override {
88 return locality_sub_zone_;
89 }
90 const Json::Object& metadata() const override { return metadata_; }
91
92 void set_id(std::string id) { id_ = std::move(id); }
93 void set_cluster(std::string cluster) { cluster_ = std::move(cluster); }
94 void set_locality_region(std::string locality_region) {
95 locality_region_ = std::move(locality_region);
96 }
97 void set_locality_zone(std::string locality_zone) {
98 locality_zone_ = std::move(locality_zone);
99 }
100 void set_locality_sub_zone(std::string locality_sub_zone) {
101 locality_sub_zone_ = std::move(locality_sub_zone);
102 }
103 void set_metadata(Json::Object metadata) {
104 metadata_ = std::move(metadata);
105 }
106
107 private:
108 std::string id_ = "xds_client_test";
109 std::string cluster_;
110 std::string locality_region_;
111 std::string locality_zone_;
112 std::string locality_sub_zone_;
113 Json::Object metadata_;
114 };
115
116 class FakeXdsServer : public XdsServer {
117 public:
118 const std::string& server_uri() const override { return server_uri_; }
119 bool IgnoreResourceDeletion() const override {
120 return ignore_resource_deletion_;
121 }
122 bool Equals(const XdsServer& other) const override {
123 const auto& o = static_cast<const FakeXdsServer&>(other);
124 return server_uri_ == o.server_uri_ &&
125 ignore_resource_deletion_ == o.ignore_resource_deletion_;
126 }
127
128 void set_server_uri(std::string server_uri) {
129 server_uri_ = std::move(server_uri);
130 }
131 void set_ignore_resource_deletion(bool ignore_resource_deletion) {
132 ignore_resource_deletion_ = ignore_resource_deletion;
133 }
134
135 private:
136 std::string server_uri_ = "default_xds_server";
137 bool ignore_resource_deletion_ = false;
138 };
139
140 class FakeAuthority : public Authority {
141 public:
142 const XdsServer* server() const override {
143 return server_.has_value() ? &*server_ : nullptr;
144 }
145
146 void set_server(absl::optional<FakeXdsServer> server) {
147 server_ = std::move(server);
148 }
149
150 private:
151 absl::optional<FakeXdsServer> server_;
152 };
153
154 class Builder {
155 public:
156 Builder() { node_.emplace(); }
157
158 Builder& set_node_id(std::string id) {
159 if (!node_.has_value()) node_.emplace();
160 node_->set_id(std::move(id));
161 return *this;
162 }
163 Builder& AddAuthority(std::string name, FakeAuthority authority) {
164 authorities_[std::move(name)] = std::move(authority);
165 return *this;
166 }
167 Builder& set_ignore_resource_deletion(bool ignore_resource_deletion) {
168 server_.set_ignore_resource_deletion(ignore_resource_deletion);
169 return *this;
170 }
171 std::unique_ptr<XdsBootstrap> Build() {
172 auto bootstrap = std::make_unique<FakeXdsBootstrap>();
173 bootstrap->server_ = std::move(server_);
174 bootstrap->node_ = std::move(node_);
175 bootstrap->authorities_ = std::move(authorities_);
176 return bootstrap;
177 }
178
179 private:
180 FakeXdsServer server_;
181 absl::optional<FakeNode> node_;
182 std::map<std::string, FakeAuthority> authorities_;
183 };
184
185 std::string ToString() const override { return "<fake>"; }
186
187 const XdsServer& server() const override { return server_; }
188 const Node* node() const override {
189 return node_.has_value() ? &*node_ : nullptr;
190 }
191 const Authority* LookupAuthority(const std::string& name) const override {
192 auto it = authorities_.find(name);
193 if (it == authorities_.end()) return nullptr;
194 return &it->second;
195 }
196 const XdsServer* FindXdsServer(const XdsServer& server) const override {
197 const auto& fake_server = static_cast<const FakeXdsServer&>(server);
198 if (fake_server == server_) return &server_;
199 for (const auto& p : authorities_) {
200 const auto* authority_server =
201 static_cast<const FakeXdsServer*>(p.second.server());
202 if (authority_server != nullptr && *authority_server == fake_server) {
203 return authority_server;
204 }
205 }
206 return nullptr;
207 }
208
209 private:
210 FakeXdsServer server_;
211 absl::optional<FakeNode> node_;
212 std::map<std::string, FakeAuthority> authorities_;
213 };
214
215 // A template for a test xDS resource type with an associated watcher impl.
216 // For simplicity, we use JSON instead of proto for serialization.
217 //
218 // The specified ResourceStruct must provide the following:
219 // - a static JsonLoader() method, as described in json_object_loader.h
220 // - an AsJsonString() method that returns the object in JSON string form
221 // - a static TypeUrl() method that returns the resource type
222 //
223 // The all_resources_required_in_sotw parameter indicates the value
224 // that should be returned by the AllResourcesRequiredInSotW() method.
225 template <typename ResourceStruct, bool all_resources_required_in_sotw>
226 class XdsTestResourceType
227 : public XdsResourceTypeImpl<
228 XdsTestResourceType<ResourceStruct, all_resources_required_in_sotw>,
229 ResourceStruct> {
230 public:
231 using ResourceStructType = ResourceStruct;
232
233 // A watcher implementation that queues delivered watches.
234 class Watcher : public XdsResourceTypeImpl<
235 XdsTestResourceType<ResourceStruct,
236 all_resources_required_in_sotw>,
237 ResourceStruct>::WatcherInterface {
238 public:
239 // Returns true if no event is received during the timeout period.
240 bool ExpectNoEvent(absl::Duration timeout) {
241 MutexLock lock(&mu_);
242 return !WaitForEventLocked(timeout);
243 }
244
245 bool HasEvent() {
246 MutexLock lock(&mu_);
247 return !queue_.empty();
248 }
249
250 absl::optional<ResourceStruct> WaitForNextResource(
251 absl::Duration timeout = absl::Seconds(1),
252 SourceLocation location = SourceLocation()) {
253 MutexLock lock(&mu_);
254 if (!WaitForEventLocked(timeout)) return absl::nullopt;
255 Event& event = queue_.front();
256 if (!absl::holds_alternative<ResourceStruct>(event)) {
257 EXPECT_TRUE(false)
258 << "got unexpected event "
259 << (absl::holds_alternative<absl::Status>(event)
260 ? "error"
261 : "does-not-exist")
262 << " at " << location.file() << ":" << location.line();
263 return absl::nullopt;
264 }
265 ResourceStruct foo = std::move(absl::get<ResourceStruct>(event));
266 queue_.pop_front();
267 return std::move(foo);
268 }
269
270 absl::optional<absl::Status> WaitForNextError(
271 absl::Duration timeout = absl::Seconds(1),
272 SourceLocation location = SourceLocation()) {
273 MutexLock lock(&mu_);
274 if (!WaitForEventLocked(timeout)) return absl::nullopt;
275 Event& event = queue_.front();
276 if (!absl::holds_alternative<absl::Status>(event)) {
277 EXPECT_TRUE(false)
278 << "got unexpected event "
279 << (absl::holds_alternative<ResourceStruct>(event)
280 ? "resource"
281 : "does-not-exist")
282 << " at " << location.file() << ":" << location.line();
283 return absl::nullopt;
284 }
285 absl::Status error = std::move(absl::get<absl::Status>(event));
286 queue_.pop_front();
287 return std::move(error);
288 }
289
290 bool WaitForDoesNotExist(absl::Duration timeout,
291 SourceLocation location = SourceLocation()) {
292 MutexLock lock(&mu_);
293 if (!WaitForEventLocked(timeout)) return false;
294 Event& event = queue_.front();
295 if (!absl::holds_alternative<DoesNotExist>(event)) {
296 EXPECT_TRUE(false)
297 << "got unexpected event "
298 << (absl::holds_alternative<ResourceStruct>(event) ? "resource"
299 : "error")
300 << " at " << location.file() << ":" << location.line();
301 return false;
302 }
303 queue_.pop_front();
304 return true;
305 }
306
307 private:
308 struct DoesNotExist {};
309 using Event = absl::variant<ResourceStruct, absl::Status, DoesNotExist>;
310
311 void OnResourceChanged(ResourceStruct foo) override {
312 MutexLock lock(&mu_);
313 queue_.push_back(std::move(foo));
314 cv_.Signal();
315 }
316 void OnError(absl::Status status) override {
317 MutexLock lock(&mu_);
318 queue_.push_back(std::move(status));
319 cv_.Signal();
320 }
321 void OnResourceDoesNotExist() override {
322 MutexLock lock(&mu_);
323 queue_.push_back(DoesNotExist());
324 cv_.Signal();
325 }
326
327 // Returns true if an event was received, or false if the timeout
328 // expires before any event is received.
329 bool WaitForEventLocked(absl::Duration timeout)
330 ABSL_EXCLUSIVE_LOCKS_REQUIRED(&mu_) {
331 while (queue_.empty()) {
332 if (cv_.WaitWithTimeout(&mu_,
333 timeout * grpc_test_slowdown_factor())) {
334 return false;
335 }
336 }
337 return true;
338 }
339
340 Mutex mu_;
341 CondVar cv_;
342 std::deque<Event> queue_ ABSL_GUARDED_BY(&mu_);
343 };
344
345 absl::string_view type_url() const override {
346 return ResourceStruct::TypeUrl();
347 }
348 XdsResourceType::DecodeResult Decode(
349 const XdsResourceType::DecodeContext& /*context*/,
350 absl::string_view serialized_resource) const override {
351 auto json = Json::Parse(serialized_resource);
352 XdsResourceType::DecodeResult result;
353 if (!json.ok()) {
354 result.resource = json.status();
355 } else {
356 absl::StatusOr<ResourceStruct> foo =
357 LoadFromJson<ResourceStruct>(*json);
358 if (!foo.ok()) {
359 auto it = json->object_value().find("name");
360 if (it != json->object_value().end()) {
361 result.name = it->second.string_value();
362 }
363 result.resource = foo.status();
364 } else {
365 result.name = foo->name;
366 result.resource = std::make_unique<ResourceStruct>(std::move(*foo));
367 }
368 }
369 return result;
370 }
371 bool AllResourcesRequiredInSotW() const override {
372 return all_resources_required_in_sotw;
373 }
374 void InitUpbSymtab(XdsClient*, upb_DefPool* /*symtab*/) const override {}
375
376 static google::protobuf::Any EncodeAsAny(const ResourceStruct& resource) {
377 google::protobuf::Any any;
378 any.set_type_url(
379 absl::StrCat("type.googleapis.com/", ResourceStruct::TypeUrl()));
380 any.set_value(resource.AsJsonString());
381 return any;
382 }
383 };
384
385 // A fake "Foo" xDS resource type.
386 struct XdsFooResource : public XdsResourceType::ResourceData {
387 std::string name;
388 uint32_t value;
389
390 XdsFooResource() = default;
391 XdsFooResource(std::string name, uint32_t value)
392 : name(std::move(name)), value(value) {}
393
394 bool operator==(const XdsFooResource& other) const {
395 return name == other.name && value == other.value;
396 }
397
398 std::string AsJsonString() const {
399 return absl::StrCat("{\"name\":\"", name, "\",\"value\":", value, "}");
400 }
401
402 static const JsonLoaderInterface* JsonLoader(const JsonArgs&) {
403 static const auto* loader = JsonObjectLoader<XdsFooResource>()
404 .Field("name", &XdsFooResource::name)
405 .Field("value", &XdsFooResource::value)
406 .Finish();
407 return loader;
408 }
409
410 static absl::string_view TypeUrl() { return "test.v3.foo"; }
411 };
412 using XdsFooResourceType = XdsTestResourceType<XdsFooResource, false>;
413
414 // A fake "Bar" xDS resource type.
415 struct XdsBarResource : public XdsResourceType::ResourceData {
416 std::string name;
417 std::string value;
418
419 XdsBarResource() = default;
420 XdsBarResource(std::string name, std::string value)
421 : name(std::move(name)), value(std::move(value)) {}
422
423 bool operator==(const XdsBarResource& other) const {
424 return name == other.name && value == other.value;
425 }
426
427 std::string AsJsonString() const {
428 return absl::StrCat("{\"name\":\"", name, "\",\"value\":\"", value,
429 "\"}");
430 }
431
432 static const JsonLoaderInterface* JsonLoader(const JsonArgs&) {
433 static const auto* loader = JsonObjectLoader<XdsBarResource>()
434 .Field("name", &XdsBarResource::name)
435 .Field("value", &XdsBarResource::value)
436 .Finish();
437 return loader;
438 }
439
440 static absl::string_view TypeUrl() { return "test.v3.bar"; }
441 };
442 using XdsBarResourceType = XdsTestResourceType<XdsBarResource, false>;
443
444 // A fake "WildcardCapable" xDS resource type.
445 // This resource type return true for AllResourcesRequiredInSotW(),
446 // just like LDS and CDS.
447 struct XdsWildcardCapableResource : public XdsResourceType::ResourceData {
448 std::string name;
449 uint32_t value;
450
451 XdsWildcardCapableResource() = default;
452 XdsWildcardCapableResource(std::string name, uint32_t value)
453 : name(std::move(name)), value(value) {}
454
455 bool operator==(const XdsWildcardCapableResource& other) const {
456 return name == other.name && value == other.value;
457 }
458
459 std::string AsJsonString() const {
460 return absl::StrCat("{\"name\":\"", name, "\",\"value\":\"", value,
461 "\"}");
462 }
463
464 static const JsonLoaderInterface* JsonLoader(const JsonArgs&) {
465 static const auto* loader =
466 JsonObjectLoader<XdsWildcardCapableResource>()
467 .Field("name", &XdsWildcardCapableResource::name)
468 .Field("value", &XdsWildcardCapableResource::value)
469 .Finish();
470 return loader;
471 }
472
473 static absl::string_view TypeUrl() { return "test.v3.wildcard_capable"; }
474 };
475 using XdsWildcardCapableResourceType =
476 XdsTestResourceType<XdsWildcardCapableResource,
477 /*all_resources_required_in_sotw=*/true>;
478
479 // A helper class to build and serialize a DiscoveryResponse.
480 class ResponseBuilder {
481 public:
482 explicit ResponseBuilder(absl::string_view type_url) {
483 response_.set_type_url(absl::StrCat("type.googleapis.com/", type_url));
484 }
485
486 ResponseBuilder& set_version_info(absl::string_view version_info) {
487 response_.set_version_info(std::string(version_info));
488 return *this;
489 }
490 ResponseBuilder& set_nonce(absl::string_view nonce) {
491 response_.set_nonce(std::string(nonce));
492 return *this;
493 }
494
495 template <typename ResourceType>
496 ResponseBuilder& AddResource(
497 const typename ResourceType::ResourceStructType& resource,
498 bool in_resource_wrapper = false) {
499 auto* res = response_.add_resources();
500 *res = ResourceType::EncodeAsAny(resource);
501 if (in_resource_wrapper) {
502 envoy::service::discovery::v3::Resource resource_wrapper;
503 resource_wrapper.set_name(resource.name);
504 *resource_wrapper.mutable_resource() = std::move(*res);
505 res->PackFrom(resource_wrapper);
506 }
507 return *this;
508 }
509
510 ResponseBuilder& AddFooResource(const XdsFooResource& resource,
511 bool in_resource_wrapper = false) {
512 return AddResource<XdsFooResourceType>(resource, in_resource_wrapper);
513 }
514
515 ResponseBuilder& AddBarResource(const XdsBarResource& resource,
516 bool in_resource_wrapper = false) {
517 return AddResource<XdsBarResourceType>(resource, in_resource_wrapper);
518 }
519
520 ResponseBuilder& AddWildcardCapableResource(
521 const XdsWildcardCapableResource& resource,
522 bool in_resource_wrapper = false) {
523 return AddResource<XdsWildcardCapableResourceType>(resource,
524 in_resource_wrapper);
525 }
526
527 ResponseBuilder& AddInvalidResource(
528 absl::string_view type_url, absl::string_view value,
529 absl::string_view resource_wrapper_name = "") {
530 auto* res = response_.add_resources();
531 res->set_type_url(absl::StrCat("type.googleapis.com/", type_url));
532 res->set_value(std::string(value));
533 if (!resource_wrapper_name.empty()) {
534 envoy::service::discovery::v3::Resource resource_wrapper;
535 resource_wrapper.set_name(std::string(resource_wrapper_name));
536 *resource_wrapper.mutable_resource() = std::move(*res);
537 res->PackFrom(resource_wrapper);
538 }
539 return *this;
540 }
541
542 std::string Serialize() {
543 std::string serialized_response;
544 EXPECT_TRUE(response_.SerializeToString(&serialized_response));
545 return serialized_response;
546 }
547
548 private:
549 DiscoveryResponse response_;
550 };
551
552 class ScopedExperimentalEnvVar {
553 public:
554 explicit ScopedExperimentalEnvVar(const char* env_var) : env_var_(env_var) {
555 SetEnv(env_var_, "true");
556 }
557
558 ~ScopedExperimentalEnvVar() { UnsetEnv(env_var_); }
559
560 private:
561 const char* env_var_;
562 };
563
564 // Sets transport_factory_ and initializes xds_client_ with the
565 // specified bootstrap config.
566 void InitXdsClient(
567 FakeXdsBootstrap::Builder bootstrap_builder = FakeXdsBootstrap::Builder(),
568 Duration resource_request_timeout = Duration::Seconds(15)) {
569 auto transport_factory = MakeOrphanable<FakeXdsTransportFactory>();
570 transport_factory_ = transport_factory->Ref();
571 xds_client_ = MakeRefCounted<XdsClient>(
572 bootstrap_builder.Build(), std::move(transport_factory),
573 resource_request_timeout * grpc_test_slowdown_factor());
574 }
575
576 // Starts and cancels a watch for a Foo resource.
577 RefCountedPtr<XdsFooResourceType::Watcher> StartFooWatch(
578 absl::string_view resource_name) {
579 auto watcher = MakeRefCounted<XdsFooResourceType::Watcher>();
580 XdsFooResourceType::StartWatch(xds_client_.get(), resource_name, watcher);
581 return watcher;
582 }
583 void CancelFooWatch(XdsFooResourceType::Watcher* watcher,
584 absl::string_view resource_name,
585 bool delay_unsubscription = false) {
586 XdsFooResourceType::CancelWatch(xds_client_.get(), resource_name, watcher,
587 delay_unsubscription);
588 }
589
590 // Starts and cancels a watch for a Bar resource.
591 RefCountedPtr<XdsBarResourceType::Watcher> StartBarWatch(
592 absl::string_view resource_name) {
593 auto watcher = MakeRefCounted<XdsBarResourceType::Watcher>();
594 XdsBarResourceType::StartWatch(xds_client_.get(), resource_name, watcher);
595 return watcher;
596 }
597 void CancelBarWatch(XdsBarResourceType::Watcher* watcher,
598 absl::string_view resource_name,
599 bool delay_unsubscription = false) {
600 XdsBarResourceType::CancelWatch(xds_client_.get(), resource_name, watcher,
601 delay_unsubscription);
602 }
603
604 // Starts and cancels a watch for a WildcardCapable resource.
605 RefCountedPtr<XdsWildcardCapableResourceType::Watcher>
606 StartWildcardCapableWatch(absl::string_view resource_name) {
607 auto watcher = MakeRefCounted<XdsWildcardCapableResourceType::Watcher>();
608 XdsWildcardCapableResourceType::StartWatch(xds_client_.get(), resource_name,
609 watcher);
610 return watcher;
611 }
612 void CancelWildcardCapableWatch(
613 XdsWildcardCapableResourceType::Watcher* watcher,
614 absl::string_view resource_name, bool delay_unsubscription = false) {
615 XdsWildcardCapableResourceType::CancelWatch(
616 xds_client_.get(), resource_name, watcher, delay_unsubscription);
617 }
618
619 RefCountedPtr<FakeXdsTransportFactory::FakeStreamingCall> WaitForAdsStream(
620 const XdsBootstrap::XdsServer& server,
621 absl::Duration timeout = absl::Seconds(5)) {
622 const auto* xds_server = xds_client_->bootstrap().FindXdsServer(server);
623 GPR_ASSERT(xds_server != nullptr);
624 return transport_factory_->WaitForStream(
625 *xds_server, FakeXdsTransportFactory::kAdsMethod,
626 timeout * grpc_test_slowdown_factor());
627 }
628
629 void TriggerConnectionFailure(const XdsBootstrap::XdsServer& server,
630 absl::Status status) {
631 const auto* xds_server = xds_client_->bootstrap().FindXdsServer(server);
632 GPR_ASSERT(xds_server != nullptr);
633 transport_factory_->TriggerConnectionFailure(*xds_server,
634 std::move(status));
635 }
636
637 RefCountedPtr<FakeXdsTransportFactory::FakeStreamingCall> WaitForAdsStream(
638 absl::Duration timeout = absl::Seconds(5)) {
639 return WaitForAdsStream(xds_client_->bootstrap().server(), timeout);
640 }
641
642 // Gets the latest request sent to the fake xDS server.
643 absl::optional<DiscoveryRequest> WaitForRequest(
644 FakeXdsTransportFactory::FakeStreamingCall* stream,
645 absl::Duration timeout = absl::Seconds(3),
646 SourceLocation location = SourceLocation()) {
647 auto message =
648 stream->WaitForMessageFromClient(timeout * grpc_test_slowdown_factor());
649 if (!message.has_value()) return absl::nullopt;
650 DiscoveryRequest request;
651 bool success = request.ParseFromString(*message);
652 EXPECT_TRUE(success) << "Failed to deserialize DiscoveryRequest at "
653 << location.file() << ":" << location.line();
654 if (!success) return absl::nullopt;
655 return std::move(request);
656 }
657
658 // Helper function to check the fields of a DiscoveryRequest.
659 void CheckRequest(const DiscoveryRequest& request, absl::string_view type_url,
660 absl::string_view version_info,
661 absl::string_view response_nonce, absl::Status error_detail,
662 std::set<absl::string_view> resource_names,
663 SourceLocation location = SourceLocation()) {
664 EXPECT_EQ(request.type_url(),
665 absl::StrCat("type.googleapis.com/", type_url))
666 << location.file() << ":" << location.line();
667 EXPECT_EQ(request.version_info(), version_info)
668 << location.file() << ":" << location.line();
669 EXPECT_EQ(request.response_nonce(), response_nonce)
670 << location.file() << ":" << location.line();
671 if (error_detail.ok()) {
672 EXPECT_FALSE(request.has_error_detail())
673 << location.file() << ":" << location.line();
674 } else {
675 EXPECT_EQ(request.error_detail().code(),
676 static_cast<int>(error_detail.code()))
677 << location.file() << ":" << location.line();
678 EXPECT_EQ(request.error_detail().message(), error_detail.message())
679 << location.file() << ":" << location.line();
680 }
681 EXPECT_THAT(request.resource_names(),
682 ::testing::UnorderedElementsAreArray(resource_names))
683 << location.file() << ":" << location.line();
684 }
685
686 // Helper function to check the contents of the node message in a
687 // request against the client's node info.
688 void CheckRequestNode(const DiscoveryRequest& request,
689 SourceLocation location = SourceLocation()) {
690 // These fields come from the bootstrap config.
691 EXPECT_EQ(request.node().id(), xds_client_->bootstrap().node()->id())
692 << location.file() << ":" << location.line();
693 EXPECT_EQ(request.node().cluster(),
694 xds_client_->bootstrap().node()->cluster())
695 << location.file() << ":" << location.line();
696 EXPECT_EQ(request.node().locality().region(),
697 xds_client_->bootstrap().node()->locality_region())
698 << location.file() << ":" << location.line();
699 EXPECT_EQ(request.node().locality().zone(),
700 xds_client_->bootstrap().node()->locality_zone())
701 << location.file() << ":" << location.line();
702 EXPECT_EQ(request.node().locality().sub_zone(),
703 xds_client_->bootstrap().node()->locality_sub_zone())
704 << location.file() << ":" << location.line();
705 if (xds_client_->bootstrap().node()->metadata().empty()) {
706 EXPECT_FALSE(request.node().has_metadata())
707 << location.file() << ":" << location.line();
708 } else {
709 std::string metadata_json_str;
710 auto status =
711 MessageToJsonString(request.node().metadata(), &metadata_json_str,
712 GRPC_CUSTOM_JSONUTIL::JsonPrintOptions());
713 ASSERT_TRUE(status.ok())
714 << status << " on " << location.file() << ":" << location.line();
715 auto metadata_json = Json::Parse(metadata_json_str);
716 ASSERT_TRUE(metadata_json.ok())
717 << metadata_json.status() << " on " << location.file() << ":"
718 << location.line();
719 EXPECT_EQ(*metadata_json, xds_client_->bootstrap().node()->metadata())
720 << location.file() << ":" << location.line() << ":\nexpected: "
721 << Json{xds_client_->bootstrap().node()->metadata()}.Dump()
722 << "\nactual: " << metadata_json->Dump();
723 }
724 // These are hard-coded by XdsClient.
725 EXPECT_EQ(request.node().user_agent_name(),
726 absl::StrCat("gRPC C-core ", GPR_PLATFORM_STRING))
727 << location.file() << ":" << location.line();
728 EXPECT_EQ(request.node().user_agent_version(),
729 absl::StrCat("C-core ", grpc_version_string()))
730 << location.file() << ":" << location.line();
731 }
732
733 RefCountedPtr<FakeXdsTransportFactory> transport_factory_;
734 RefCountedPtr<XdsClient> xds_client_;
735 };
736
737 TEST_F(XdsClientTest, BasicWatch) {
738 InitXdsClient();
739 // Start a watch for "foo1".
740 auto watcher = StartFooWatch("foo1");
741 // Watcher should initially not see any resource reported.
742 EXPECT_FALSE(watcher->HasEvent());
743 // XdsClient should have created an ADS stream.
744 auto stream = WaitForAdsStream();
745 ASSERT_TRUE(stream != nullptr);
746 // XdsClient should have sent a subscription request on the ADS stream.
747 auto request = WaitForRequest(stream.get());
748 ASSERT_TRUE(request.has_value());
749 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
750 /*version_info=*/"", /*response_nonce=*/"",
751 /*error_detail=*/absl::OkStatus(),
752 /*resource_names=*/{"foo1"});
753 CheckRequestNode(*request); // Should be present on the first request.
754 // Send a response.
755 stream->SendMessageToClient(
756 ResponseBuilder(XdsFooResourceType::Get()->type_url())
757 .set_version_info("1")
758 .set_nonce("A")
759 .AddFooResource(XdsFooResource("foo1", 6))
760 .Serialize());
761 // XdsClient should have delivered the response to the watcher.
762 auto resource = watcher->WaitForNextResource();
763 ASSERT_TRUE(resource.has_value());
764 EXPECT_EQ(resource->name, "foo1");
765 EXPECT_EQ(resource->value, 6);
766 // XdsClient should have sent an ACK message to the xDS server.
767 request = WaitForRequest(stream.get());
768 ASSERT_TRUE(request.has_value());
769 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
770 /*version_info=*/"1", /*response_nonce=*/"A",
771 /*error_detail=*/absl::OkStatus(),
772 /*resource_names=*/{"foo1"});
773 // Cancel watch.
774 CancelFooWatch(watcher.get(), "foo1");
775 // The XdsClient may or may not send an unsubscription message
776 // before it closes the transport, depending on callback timing.
777 request = WaitForRequest(stream.get());
778 if (request.has_value()) {
779 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
780 /*version_info=*/"1", /*response_nonce=*/"A",
781 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
782 }
783 }
784
785 TEST_F(XdsClientTest, UpdateFromServer) {
786 InitXdsClient();
787 // Start a watch for "foo1".
788 auto watcher = StartFooWatch("foo1");
789 // Watcher should initially not see any resource reported.
790 EXPECT_FALSE(watcher->HasEvent());
791 // XdsClient should have created an ADS stream.
792 auto stream = WaitForAdsStream();
793 ASSERT_TRUE(stream != nullptr);
794 // XdsClient should have sent a subscription request on the ADS stream.
795 auto request = WaitForRequest(stream.get());
796 ASSERT_TRUE(request.has_value());
797 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
798 /*version_info=*/"", /*response_nonce=*/"",
799 /*error_detail=*/absl::OkStatus(),
800 /*resource_names=*/{"foo1"});
801 CheckRequestNode(*request); // Should be present on the first request.
802 // Send a response.
803 stream->SendMessageToClient(
804 ResponseBuilder(XdsFooResourceType::Get()->type_url())
805 .set_version_info("1")
806 .set_nonce("A")
807 .AddFooResource(XdsFooResource("foo1", 6))
808 .Serialize());
809 // XdsClient should have delivered the response to the watcher.
810 auto resource = watcher->WaitForNextResource();
811 ASSERT_TRUE(resource.has_value());
812 EXPECT_EQ(resource->name, "foo1");
813 EXPECT_EQ(resource->value, 6);
814 // XdsClient should have sent an ACK message to the xDS server.
815 request = WaitForRequest(stream.get());
816 ASSERT_TRUE(request.has_value());
817 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
818 /*version_info=*/"1", /*response_nonce=*/"A",
819 /*error_detail=*/absl::OkStatus(),
820 /*resource_names=*/{"foo1"});
821 // Server sends an updated version of the resource.
822 stream->SendMessageToClient(
823 ResponseBuilder(XdsFooResourceType::Get()->type_url())
824 .set_version_info("2")
825 .set_nonce("B")
826 .AddFooResource(XdsFooResource("foo1", 9))
827 .Serialize());
828 // XdsClient should have delivered the response to the watcher.
829 resource = watcher->WaitForNextResource();
830 ASSERT_TRUE(resource.has_value());
831 EXPECT_EQ(resource->name, "foo1");
832 EXPECT_EQ(resource->value, 9);
833 // XdsClient should have sent an ACK message to the xDS server.
834 request = WaitForRequest(stream.get());
835 ASSERT_TRUE(request.has_value());
836 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
837 /*version_info=*/"2", /*response_nonce=*/"B",
838 /*error_detail=*/absl::OkStatus(),
839 /*resource_names=*/{"foo1"});
840 // Cancel watch.
841 CancelFooWatch(watcher.get(), "foo1");
842 // The XdsClient may or may not send an unsubscription message
843 // before it closes the transport, depending on callback timing.
844 request = WaitForRequest(stream.get());
845 if (request.has_value()) {
846 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
847 /*version_info=*/"2", /*response_nonce=*/"B",
848 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
849 }
850 }
851
852 TEST_F(XdsClientTest, MultipleWatchersForSameResource) {
853 InitXdsClient();
854 // Start a watch for "foo1".
855 auto watcher = StartFooWatch("foo1");
856 // Watcher should initially not see any resource reported.
857 EXPECT_FALSE(watcher->HasEvent());
858 // XdsClient should have created an ADS stream.
859 auto stream = WaitForAdsStream();
860 ASSERT_TRUE(stream != nullptr);
861 // XdsClient should have sent a subscription request on the ADS stream.
862 auto request = WaitForRequest(stream.get());
863 ASSERT_TRUE(request.has_value());
864 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
865 /*version_info=*/"", /*response_nonce=*/"",
866 /*error_detail=*/absl::OkStatus(),
867 /*resource_names=*/{"foo1"});
868 CheckRequestNode(*request); // Should be present on the first request.
869 // Send a response.
870 stream->SendMessageToClient(
871 ResponseBuilder(XdsFooResourceType::Get()->type_url())
872 .set_version_info("1")
873 .set_nonce("A")
874 .AddFooResource(XdsFooResource("foo1", 6))
875 .Serialize());
876 // XdsClient should have delivered the response to the watcher.
877 auto resource = watcher->WaitForNextResource();
878 ASSERT_TRUE(resource.has_value());
879 EXPECT_EQ(resource->name, "foo1");
880 EXPECT_EQ(resource->value, 6);
881 // XdsClient should have sent an ACK message to the xDS server.
882 request = WaitForRequest(stream.get());
883 ASSERT_TRUE(request.has_value());
884 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
885 /*version_info=*/"1", /*response_nonce=*/"A",
886 /*error_detail=*/absl::OkStatus(),
887 /*resource_names=*/{"foo1"});
888 // Start a second watcher for the same resource.
889 auto watcher2 = StartFooWatch("foo1");
890 // This watcher should get an immediate notification, because the
891 // resource is already cached.
892 resource = watcher2->WaitForNextResource();
893 ASSERT_TRUE(resource.has_value());
894 EXPECT_EQ(resource->name, "foo1");
895 EXPECT_EQ(resource->value, 6);
896 // Server should not have seen another request from the client.
897 ASSERT_FALSE(stream->HaveMessageFromClient());
898 // Server sends an updated version of the resource.
899 stream->SendMessageToClient(
900 ResponseBuilder(XdsFooResourceType::Get()->type_url())
901 .set_version_info("2")
902 .set_nonce("B")
903 .AddFooResource(XdsFooResource("foo1", 9))
904 .Serialize());
905 // XdsClient should deliver the response to both watchers.
906 resource = watcher->WaitForNextResource();
907 ASSERT_TRUE(resource.has_value());
908 EXPECT_EQ(resource->name, "foo1");
909 EXPECT_EQ(resource->value, 9);
910 resource = watcher2->WaitForNextResource();
911 ASSERT_TRUE(resource.has_value());
912 EXPECT_EQ(resource->name, "foo1");
913 EXPECT_EQ(resource->value, 9);
914 // XdsClient should have sent an ACK message to the xDS server.
915 request = WaitForRequest(stream.get());
916 ASSERT_TRUE(request.has_value());
917 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
918 /*version_info=*/"2", /*response_nonce=*/"B",
919 /*error_detail=*/absl::OkStatus(),
920 /*resource_names=*/{"foo1"});
921 // Cancel one of the watchers.
922 CancelFooWatch(watcher.get(), "foo1");
923 // The server should not see any new request.
924 ASSERT_FALSE(WaitForRequest(stream.get()));
925 // Now cancel the second watcher.
926 CancelFooWatch(watcher2.get(), "foo1");
927 // The XdsClient may or may not send an unsubscription message
928 // before it closes the transport, depending on callback timing.
929 request = WaitForRequest(stream.get());
930 if (request.has_value()) {
931 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
932 /*version_info=*/"2", /*response_nonce=*/"B",
933 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
934 }
935 }
936
937 TEST_F(XdsClientTest, SubscribeToMultipleResources) {
938 InitXdsClient();
939 // Start a watch for "foo1".
940 auto watcher = StartFooWatch("foo1");
941 // Watcher should initially not see any resource reported.
942 EXPECT_FALSE(watcher->HasEvent());
943 // XdsClient should have created an ADS stream.
944 auto stream = WaitForAdsStream();
945 ASSERT_TRUE(stream != nullptr);
946 // XdsClient should have sent a subscription request on the ADS stream.
947 auto request = WaitForRequest(stream.get());
948 ASSERT_TRUE(request.has_value());
949 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
950 /*version_info=*/"", /*response_nonce=*/"",
951 /*error_detail=*/absl::OkStatus(),
952 /*resource_names=*/{"foo1"});
953 CheckRequestNode(*request); // Should be present on the first request.
954 // Send a response.
955 stream->SendMessageToClient(
956 ResponseBuilder(XdsFooResourceType::Get()->type_url())
957 .set_version_info("1")
958 .set_nonce("A")
959 .AddFooResource(XdsFooResource("foo1", 6))
960 .Serialize());
961 // XdsClient should have delivered the response to the watcher.
962 auto resource = watcher->WaitForNextResource();
963 ASSERT_TRUE(resource.has_value());
964 EXPECT_EQ(resource->name, "foo1");
965 EXPECT_EQ(resource->value, 6);
966 // XdsClient should have sent an ACK message to the xDS server.
967 request = WaitForRequest(stream.get());
968 ASSERT_TRUE(request.has_value());
969 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
970 /*version_info=*/"1", /*response_nonce=*/"A",
971 /*error_detail=*/absl::OkStatus(),
972 /*resource_names=*/{"foo1"});
973 // Start a watch for "foo2".
974 auto watcher2 = StartFooWatch("foo2");
975 // XdsClient should have sent a subscription request on the ADS stream.
976 request = WaitForRequest(stream.get());
977 ASSERT_TRUE(request.has_value());
978 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
979 /*version_info=*/"1", /*response_nonce=*/"A",
980 /*error_detail=*/absl::OkStatus(),
981 /*resource_names=*/{"foo1", "foo2"});
982 // Send a response.
983 stream->SendMessageToClient(
984 ResponseBuilder(XdsFooResourceType::Get()->type_url())
985 .set_version_info("1")
986 .set_nonce("B")
987 .AddFooResource(XdsFooResource("foo2", 7))
988 .Serialize());
989 // XdsClient should have delivered the response to the watcher.
990 resource = watcher2->WaitForNextResource();
991 ASSERT_TRUE(resource.has_value());
992 EXPECT_EQ(resource->name, "foo2");
993 EXPECT_EQ(resource->value, 7);
994 // XdsClient should have sent an ACK message to the xDS server.
995 request = WaitForRequest(stream.get());
996 ASSERT_TRUE(request.has_value());
997 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
998 /*version_info=*/"1", /*response_nonce=*/"B",
999 /*error_detail=*/absl::OkStatus(),
1000 /*resource_names=*/{"foo1", "foo2"});
1001 // Cancel watch for "foo1".
1002 CancelFooWatch(watcher.get(), "foo1");
1003 // XdsClient should send an unsubscription request.
1004 request = WaitForRequest(stream.get());
1005 ASSERT_TRUE(request.has_value());
1006 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1007 /*version_info=*/"1", /*response_nonce=*/"B",
1008 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{"foo2"});
1009 // Now cancel watch for "foo2".
1010 CancelFooWatch(watcher2.get(), "foo2");
1011 // The XdsClient may or may not send another unsubscription message
1012 // before it closes the transport, depending on callback timing.
1013 request = WaitForRequest(stream.get());
1014 if (request.has_value()) {
1015 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1016 /*version_info=*/"1", /*response_nonce=*/"B",
1017 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
1018 }
1019 }
1020
1021 TEST_F(XdsClientTest, UpdateContainsOnlyChangedResource) {
1022 InitXdsClient();
1023 // Start a watch for "foo1".
1024 auto watcher = StartFooWatch("foo1");
1025 // Watcher should initially not see any resource reported.
1026 EXPECT_FALSE(watcher->HasEvent());
1027 // XdsClient should have created an ADS stream.
1028 auto stream = WaitForAdsStream();
1029 ASSERT_TRUE(stream != nullptr);
1030 // XdsClient should have sent a subscription request on the ADS stream.
1031 auto request = WaitForRequest(stream.get());
1032 ASSERT_TRUE(request.has_value());
1033 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1034 /*version_info=*/"", /*response_nonce=*/"",
1035 /*error_detail=*/absl::OkStatus(),
1036 /*resource_names=*/{"foo1"});
1037 CheckRequestNode(*request); // Should be present on the first request.
1038 // Send a response.
1039 stream->SendMessageToClient(
1040 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1041 .set_version_info("1")
1042 .set_nonce("A")
1043 .AddFooResource(XdsFooResource("foo1", 6))
1044 .Serialize());
1045 // XdsClient should have delivered the response to the watcher.
1046 auto resource = watcher->WaitForNextResource();
1047 ASSERT_TRUE(resource.has_value());
1048 EXPECT_EQ(resource->name, "foo1");
1049 EXPECT_EQ(resource->value, 6);
1050 // XdsClient should have sent an ACK message to the xDS server.
1051 request = WaitForRequest(stream.get());
1052 ASSERT_TRUE(request.has_value());
1053 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1054 /*version_info=*/"1", /*response_nonce=*/"A",
1055 /*error_detail=*/absl::OkStatus(),
1056 /*resource_names=*/{"foo1"});
1057 // Start a watch for "foo2".
1058 auto watcher2 = StartFooWatch("foo2");
1059 // XdsClient should have sent a subscription request on the ADS stream.
1060 request = WaitForRequest(stream.get());
1061 ASSERT_TRUE(request.has_value());
1062 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1063 /*version_info=*/"1", /*response_nonce=*/"A",
1064 /*error_detail=*/absl::OkStatus(),
1065 /*resource_names=*/{"foo1", "foo2"});
1066 // Send a response.
1067 stream->SendMessageToClient(
1068 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1069 .set_version_info("1")
1070 .set_nonce("B")
1071 .AddFooResource(XdsFooResource("foo2", 7))
1072 .Serialize());
1073 // XdsClient should have delivered the response to the watcher.
1074 resource = watcher2->WaitForNextResource();
1075 ASSERT_TRUE(resource.has_value());
1076 EXPECT_EQ(resource->name, "foo2");
1077 EXPECT_EQ(resource->value, 7);
1078 // XdsClient should have sent an ACK message to the xDS server.
1079 request = WaitForRequest(stream.get());
1080 ASSERT_TRUE(request.has_value());
1081 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1082 /*version_info=*/"1", /*response_nonce=*/"B",
1083 /*error_detail=*/absl::OkStatus(),
1084 /*resource_names=*/{"foo1", "foo2"});
1085 // Server sends an update for "foo1". The response does not contain "foo2".
1086 stream->SendMessageToClient(
1087 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1088 .set_version_info("2")
1089 .set_nonce("C")
1090 .AddFooResource(XdsFooResource("foo1", 9))
1091 .Serialize());
1092 // XdsClient should have delivered the response to the watcher.
1093 resource = watcher->WaitForNextResource();
1094 ASSERT_TRUE(resource.has_value());
1095 EXPECT_EQ(resource->name, "foo1");
1096 EXPECT_EQ(resource->value, 9);
1097 // XdsClient should have sent an ACK message to the xDS server.
1098 request = WaitForRequest(stream.get());
1099 ASSERT_TRUE(request.has_value());
1100 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1101 /*version_info=*/"2", /*response_nonce=*/"C",
1102 /*error_detail=*/absl::OkStatus(),
1103 /*resource_names=*/{"foo1", "foo2"});
1104 // Cancel watch for "foo1".
1105 CancelFooWatch(watcher.get(), "foo1");
1106 // XdsClient should send an unsubscription request.
1107 request = WaitForRequest(stream.get());
1108 ASSERT_TRUE(request.has_value());
1109 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1110 /*version_info=*/"2", /*response_nonce=*/"C",
1111 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{"foo2"});
1112 // Now cancel watch for "foo2".
1113 CancelFooWatch(watcher2.get(), "foo2");
1114 // The XdsClient may or may not send another unsubscription message
1115 // before it closes the transport, depending on callback timing.
1116 request = WaitForRequest(stream.get());
1117 if (request.has_value()) {
1118 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1119 /*version_info=*/"2", /*response_nonce=*/"C",
1120 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
1121 }
1122 }
1123
1124 TEST_F(XdsClientTest, ResourceValidationFailure) {
1125 InitXdsClient();
1126 // Start a watch for "foo1".
1127 auto watcher = StartFooWatch("foo1");
1128 // Watcher should initially not see any resource reported.
1129 EXPECT_FALSE(watcher->HasEvent());
1130 // XdsClient should have created an ADS stream.
1131 auto stream = WaitForAdsStream();
1132 ASSERT_TRUE(stream != nullptr);
1133 // XdsClient should have sent a subscription request on the ADS stream.
1134 auto request = WaitForRequest(stream.get());
1135 ASSERT_TRUE(request.has_value());
1136 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1137 /*version_info=*/"", /*response_nonce=*/"",
1138 /*error_detail=*/absl::OkStatus(),
1139 /*resource_names=*/{"foo1"});
1140 CheckRequestNode(*request); // Should be present on the first request.
1141 // Send a response containing an invalid resource.
1142 stream->SendMessageToClient(
1143 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1144 .set_version_info("1")
1145 .set_nonce("A")
1146 .AddInvalidResource(XdsFooResourceType::Get()->type_url(),
1147 "{\"name\":\"foo1\",\"value\":[]}")
1148 .Serialize());
1149 // XdsClient should deliver an error to the watcher.
1150 auto error = watcher->WaitForNextError();
1151 ASSERT_TRUE(error.has_value());
1152 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
1153 EXPECT_EQ(error->message(),
1154 "invalid resource: INVALID_ARGUMENT: errors validating JSON: "
1155 "[field:value error:is not a number] (node ID:xds_client_test)")
1156 << *error;
1157 // XdsClient should NACK the update.
1158 // Note that version_info is not populated in the request.
1159 request = WaitForRequest(stream.get());
1160 ASSERT_TRUE(request.has_value());
1161 CheckRequest(
1162 *request, XdsFooResourceType::Get()->type_url(),
1163 /*version_info=*/"", /*response_nonce=*/"A",
1164 /*error_detail=*/
1165 absl::InvalidArgumentError(
1166 "xDS response validation errors: ["
1167 "resource index 0: foo1: INVALID_ARGUMENT: errors validating JSON: "
1168 "[field:value error:is not a number]]"),
1169 /*resource_names=*/{"foo1"});
1170 // Start a second watch for the same resource. It should immediately
1171 // receive the same error.
1172 auto watcher2 = StartFooWatch("foo1");
1173 error = watcher2->WaitForNextError();
1174 ASSERT_TRUE(error.has_value());
1175 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
1176 EXPECT_EQ(error->message(),
1177 "invalid resource: INVALID_ARGUMENT: errors validating JSON: "
1178 "[field:value error:is not a number] (node ID:xds_client_test)")
1179 << *error;
1180 // Now server sends an updated version of the resource.
1181 stream->SendMessageToClient(
1182 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1183 .set_version_info("2")
1184 .set_nonce("B")
1185 .AddFooResource(XdsFooResource("foo1", 9))
1186 .Serialize());
1187 // XdsClient should deliver the response to both watchers.
1188 auto resource = watcher->WaitForNextResource();
1189 ASSERT_TRUE(resource.has_value());
1190 EXPECT_EQ(resource->name, "foo1");
1191 EXPECT_EQ(resource->value, 9);
1192 resource = watcher2->WaitForNextResource();
1193 ASSERT_TRUE(resource.has_value());
1194 EXPECT_EQ(resource->name, "foo1");
1195 EXPECT_EQ(resource->value, 9);
1196 // XdsClient should have sent an ACK message to the xDS server.
1197 request = WaitForRequest(stream.get());
1198 ASSERT_TRUE(request.has_value());
1199 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1200 /*version_info=*/"2", /*response_nonce=*/"B",
1201 /*error_detail=*/absl::OkStatus(),
1202 /*resource_names=*/{"foo1"});
1203 // Cancel watch.
1204 CancelFooWatch(watcher.get(), "foo1");
1205 CancelFooWatch(watcher2.get(), "foo1");
1206 // The XdsClient may or may not send an unsubscription message
1207 // before it closes the transport, depending on callback timing.
1208 request = WaitForRequest(stream.get());
1209 if (request.has_value()) {
1210 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1211 /*version_info=*/"2", /*response_nonce=*/"B",
1212 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
1213 }
1214 }
1215
1216 TEST_F(XdsClientTest, ResourceValidationFailureMultipleResources) {
1217 InitXdsClient();
1218 // Start a watch for "foo1".
1219 auto watcher = StartFooWatch("foo1");
1220 // Watcher should initially not see any resource reported.
1221 EXPECT_FALSE(watcher->HasEvent());
1222 // XdsClient should have created an ADS stream.
1223 auto stream = WaitForAdsStream();
1224 ASSERT_TRUE(stream != nullptr);
1225 // XdsClient should have sent a subscription request on the ADS stream.
1226 auto request = WaitForRequest(stream.get());
1227 ASSERT_TRUE(request.has_value());
1228 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1229 /*version_info=*/"", /*response_nonce=*/"",
1230 /*error_detail=*/absl::OkStatus(),
1231 /*resource_names=*/{"foo1"});
1232 CheckRequestNode(*request); // Should be present on the first request.
1233 // Before the server responds, add a watch for another resource.
1234 auto watcher2 = StartFooWatch("foo2");
1235 // Client should send another request.
1236 request = WaitForRequest(stream.get());
1237 ASSERT_TRUE(request.has_value());
1238 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1239 /*version_info=*/"", /*response_nonce=*/"",
1240 /*error_detail=*/absl::OkStatus(),
1241 /*resource_names=*/{"foo1", "foo2"});
1242 // Add a watch for a third resource.
1243 auto watcher3 = StartFooWatch("foo3");
1244 // Client should send another request.
1245 request = WaitForRequest(stream.get());
1246 ASSERT_TRUE(request.has_value());
1247 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1248 /*version_info=*/"", /*response_nonce=*/"",
1249 /*error_detail=*/absl::OkStatus(),
1250 /*resource_names=*/{"foo1", "foo2", "foo3"});
1251 // Add a watch for a fourth resource.
1252 auto watcher4 = StartFooWatch("foo4");
1253 // Client should send another request.
1254 request = WaitForRequest(stream.get());
1255 ASSERT_TRUE(request.has_value());
1256 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1257 /*version_info=*/"", /*response_nonce=*/"",
1258 /*error_detail=*/absl::OkStatus(),
1259 /*resource_names=*/{"foo1", "foo2", "foo3", "foo4"});
1260 // Server sends a response containing three invalid resources and one
1261 // valid resource.
1262 stream->SendMessageToClient(
1263 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1264 .set_version_info("1")
1265 .set_nonce("A")
1266 // foo1: JSON parsing succeeds, so we know the resource name,
1267 // but validation fails.
1268 .AddInvalidResource(XdsFooResourceType::Get()->type_url(),
1269 "{\"name\":\"foo1\",\"value\":[]}")
1270 // foo2: JSON parsing fails, and not wrapped in a Resource
1271 // wrapper, so we don't actually know the resource's name.
1272 .AddInvalidResource(XdsFooResourceType::Get()->type_url(),
1273 "{\"name\":\"foo2,\"value\":6}")
1274 // foo3: JSON parsing fails, but it is wrapped in a Resource
1275 // wrapper, so we do know the resource's name.
1276 .AddInvalidResource(XdsFooResourceType::Get()->type_url(),
1277 "{\"name\":\"foo3,\"value\":6}",
1278 /*resource_wrapper_name=*/"foo3")
1279 // foo4: valid resource.
1280 .AddFooResource(XdsFooResource("foo4", 5))
1281 .Serialize());
1282 // XdsClient should deliver an error to the watchers for foo1 and foo3.
1283 auto error = watcher->WaitForNextError();
1284 ASSERT_TRUE(error.has_value());
1285 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
1286 EXPECT_EQ(error->message(),
1287 "invalid resource: INVALID_ARGUMENT: errors validating JSON: "
1288 "[field:value error:is not a number] (node ID:xds_client_test)")
1289 << *error;
1290 error = watcher3->WaitForNextError();
1291 ASSERT_TRUE(error.has_value());
1292 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
1293 EXPECT_EQ(error->message(),
1294 "invalid resource: INVALID_ARGUMENT: JSON parsing failed: "
1295 "[JSON parse error at index 15] (node ID:xds_client_test)")
1296 << *error;
1297 // It cannot delivery an error for foo2, because the client doesn't know
1298 // that that resource in the response was actually supposed to be foo2.
1299 EXPECT_FALSE(watcher2->HasEvent());
1300 // It will delivery a valid resource update for foo4.
1301 auto resource = watcher4->WaitForNextResource();
1302 ASSERT_TRUE(resource.has_value());
1303 EXPECT_EQ(resource->name, "foo4");
1304 EXPECT_EQ(resource->value, 5);
1305 // XdsClient should NACK the update.
1306 // There was one good resource, so the version will be updated.
1307 request = WaitForRequest(stream.get());
1308 ASSERT_TRUE(request.has_value());
1309 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1310 /*version_info=*/"1", /*response_nonce=*/"A",
1311 /*error_detail=*/
1312 absl::InvalidArgumentError(
1313 "xDS response validation errors: ["
1314 // foo1
1315 "resource index 0: foo1: "
1316 "INVALID_ARGUMENT: errors validating JSON: "
1317 "[field:value error:is not a number]; "
1318 // foo2 (name not known)
1319 "resource index 1: INVALID_ARGUMENT: JSON parsing failed: "
1320 "[JSON parse error at index 15]; "
1321 // foo3
1322 "resource index 2: foo3: "
1323 "INVALID_ARGUMENT: JSON parsing failed: "
1324 "[JSON parse error at index 15]]"),
1325 /*resource_names=*/{"foo1", "foo2", "foo3", "foo4"});
1326 // Cancel watches.
1327 CancelFooWatch(watcher.get(), "foo1", /*delay_unsubscription=*/true);
1328 CancelFooWatch(watcher.get(), "foo2", /*delay_unsubscription=*/true);
1329 CancelFooWatch(watcher.get(), "foo3", /*delay_unsubscription=*/true);
1330 CancelFooWatch(watcher.get(), "foo4");
1331 // The XdsClient may or may not send an unsubscription message
1332 // before it closes the transport, depending on callback timing.
1333 request = WaitForRequest(stream.get());
1334 if (request.has_value()) {
1335 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1336 /*version_info=*/"1", /*response_nonce=*/"A",
1337 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
1338 }
1339 }
1340
1341 TEST_F(XdsClientTest, ResourceValidationFailureForCachedResource) {
1342 InitXdsClient();
1343 // Start a watch for "foo1".
1344 auto watcher = StartFooWatch("foo1");
1345 // Watcher should initially not see any resource reported.
1346 EXPECT_FALSE(watcher->HasEvent());
1347 // XdsClient should have created an ADS stream.
1348 auto stream = WaitForAdsStream();
1349 ASSERT_TRUE(stream != nullptr);
1350 // XdsClient should have sent a subscription request on the ADS stream.
1351 auto request = WaitForRequest(stream.get());
1352 ASSERT_TRUE(request.has_value());
1353 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1354 /*version_info=*/"", /*response_nonce=*/"",
1355 /*error_detail=*/absl::OkStatus(),
1356 /*resource_names=*/{"foo1"});
1357 CheckRequestNode(*request); // Should be present on the first request.
1358 // Send a response.
1359 stream->SendMessageToClient(
1360 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1361 .set_version_info("1")
1362 .set_nonce("A")
1363 .AddFooResource(XdsFooResource("foo1", 6))
1364 .Serialize());
1365 // XdsClient should have delivered the response to the watcher.
1366 auto resource = watcher->WaitForNextResource();
1367 ASSERT_TRUE(resource.has_value());
1368 EXPECT_EQ(resource->name, "foo1");
1369 EXPECT_EQ(resource->value, 6);
1370 // XdsClient should have sent an ACK message to the xDS server.
1371 request = WaitForRequest(stream.get());
1372 ASSERT_TRUE(request.has_value());
1373 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1374 /*version_info=*/"1", /*response_nonce=*/"A",
1375 /*error_detail=*/absl::OkStatus(),
1376 /*resource_names=*/{"foo1"});
1377 // Send an update containing an invalid resource.
1378 stream->SendMessageToClient(
1379 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1380 .set_version_info("2")
1381 .set_nonce("B")
1382 .AddInvalidResource(XdsFooResourceType::Get()->type_url(),
1383 "{\"name\":\"foo1\",\"value\":[]}")
1384 .Serialize());
1385 // XdsClient should deliver an error to the watcher.
1386 auto error = watcher->WaitForNextError();
1387 ASSERT_TRUE(error.has_value());
1388 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
1389 EXPECT_EQ(error->message(),
1390 "invalid resource: INVALID_ARGUMENT: errors validating JSON: "
1391 "[field:value error:is not a number] (node ID:xds_client_test)")
1392 << *error;
1393 // XdsClient should NACK the update.
1394 // Note that version_info is set to the previous version in this request,
1395 // because there were no valid resources in it.
1396 request = WaitForRequest(stream.get());
1397 ASSERT_TRUE(request.has_value());
1398 CheckRequest(
1399 *request, XdsFooResourceType::Get()->type_url(),
1400 /*version_info=*/"1", /*response_nonce=*/"B",
1401 /*error_detail=*/
1402 absl::InvalidArgumentError(
1403 "xDS response validation errors: ["
1404 "resource index 0: foo1: INVALID_ARGUMENT: errors validating JSON: "
1405 "[field:value error:is not a number]]"),
1406 /*resource_names=*/{"foo1"});
1407 // Start a second watcher for the same resource. Even though the last
1408 // update was a NACK, we should still deliver the cached resource to
1409 // the watcher.
1410 // TODO(roth): Consider what the right behavior is here. It seems
1411 // inconsistent that the watcher sees the error if it had started
1412 // before the error was seen but does not if it was started afterwards.
1413 // One option is to not send errors at all for already-cached resources;
1414 // another option is to send the errors even for newly started watchers.
1415 auto watcher2 = StartFooWatch("foo1");
1416 resource = watcher2->WaitForNextResource();
1417 ASSERT_TRUE(resource.has_value());
1418 EXPECT_EQ(resource->name, "foo1");
1419 EXPECT_EQ(resource->value, 6);
1420 // Cancel watches.
1421 CancelFooWatch(watcher.get(), "foo1", /*delay_unsubscription=*/true);
1422 CancelFooWatch(watcher2.get(), "foo1");
1423 // The XdsClient may or may not send an unsubscription message
1424 // before it closes the transport, depending on callback timing.
1425 request = WaitForRequest(stream.get());
1426 if (request.has_value()) {
1427 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1428 /*version_info=*/"1", /*response_nonce=*/"B",
1429 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
1430 }
1431 }
1432
1433 // This tests resource removal triggered by the server when using a
1434 // resource type that requires all resources to be present in every
1435 // response, similar to LDS and CDS.
1436 TEST_F(XdsClientTest, ResourceDeletion) {
1437 InitXdsClient();
1438 // Start a watch for "wc1".
1439 auto watcher = StartWildcardCapableWatch("wc1");
1440 // Watcher should initially not see any resource reported.
1441 EXPECT_FALSE(watcher->HasEvent());
1442 // XdsClient should have created an ADS stream.
1443 auto stream = WaitForAdsStream();
1444 ASSERT_TRUE(stream != nullptr);
1445 // XdsClient should have sent a subscription request on the ADS stream.
1446 auto request = WaitForRequest(stream.get());
1447 ASSERT_TRUE(request.has_value());
1448 CheckRequest(*request, XdsWildcardCapableResourceType::Get()->type_url(),
1449 /*version_info=*/"", /*response_nonce=*/"",
1450 /*error_detail=*/absl::OkStatus(),
1451 /*resource_names=*/{"wc1"});
1452 CheckRequestNode(*request); // Should be present on the first request.
1453 // Server sends a response.
1454 stream->SendMessageToClient(
1455 ResponseBuilder(XdsWildcardCapableResourceType::Get()->type_url())
1456 .set_version_info("1")
1457 .set_nonce("A")
1458 .AddWildcardCapableResource(XdsWildcardCapableResource("wc1", 6))
1459 .Serialize());
1460 // XdsClient should have delivered the response to the watcher.
1461 auto resource = watcher->WaitForNextResource();
1462 ASSERT_TRUE(resource.has_value());
1463 EXPECT_EQ(resource->name, "wc1");
1464 EXPECT_EQ(resource->value, 6);
1465 // XdsClient should have sent an ACK message to the xDS server.
1466 request = WaitForRequest(stream.get());
1467 ASSERT_TRUE(request.has_value());
1468 CheckRequest(*request, XdsWildcardCapableResourceType::Get()->type_url(),
1469 /*version_info=*/"1", /*response_nonce=*/"A",
1470 /*error_detail=*/absl::OkStatus(),
1471 /*resource_names=*/{"wc1"});
1472 // Server now sends a response without the resource, thus indicating
1473 // it's been deleted.
1474 stream->SendMessageToClient(
1475 ResponseBuilder(XdsWildcardCapableResourceType::Get()->type_url())
1476 .set_version_info("2")
1477 .set_nonce("B")
1478 .Serialize());
1479 // Watcher should see the does-not-exist event.
1480 EXPECT_TRUE(watcher->WaitForDoesNotExist(absl::Seconds(1)));
1481 // Start a new watcher for the same resource. It should immediately
1482 // receive the same does-not-exist notification.
1483 auto watcher2 = StartWildcardCapableWatch("wc1");
1484 EXPECT_TRUE(watcher2->WaitForDoesNotExist(absl::Seconds(1)));
1485 // XdsClient should have sent an ACK message to the xDS server.
1486 request = WaitForRequest(stream.get());
1487 ASSERT_TRUE(request.has_value());
1488 CheckRequest(*request, XdsWildcardCapableResourceType::Get()->type_url(),
1489 /*version_info=*/"2", /*response_nonce=*/"B",
1490 /*error_detail=*/absl::OkStatus(),
1491 /*resource_names=*/{"wc1"});
1492 // Server sends the resource again.
1493 stream->SendMessageToClient(
1494 ResponseBuilder(XdsWildcardCapableResourceType::Get()->type_url())
1495 .set_version_info("3")
1496 .set_nonce("C")
1497 .AddWildcardCapableResource(XdsWildcardCapableResource("wc1", 7))
1498 .Serialize());
1499 // XdsClient should have delivered the response to the watchers.
1500 resource = watcher->WaitForNextResource();
1501 ASSERT_TRUE(resource.has_value());
1502 EXPECT_EQ(resource->name, "wc1");
1503 EXPECT_EQ(resource->value, 7);
1504 resource = watcher2->WaitForNextResource();
1505 ASSERT_TRUE(resource.has_value());
1506 EXPECT_EQ(resource->name, "wc1");
1507 EXPECT_EQ(resource->value, 7);
1508 // XdsClient should have sent an ACK message to the xDS server.
1509 request = WaitForRequest(stream.get());
1510 ASSERT_TRUE(request.has_value());
1511 CheckRequest(*request, XdsWildcardCapableResourceType::Get()->type_url(),
1512 /*version_info=*/"3", /*response_nonce=*/"C",
1513 /*error_detail=*/absl::OkStatus(),
1514 /*resource_names=*/{"wc1"});
1515 // Cancel watch.
1516 CancelWildcardCapableWatch(watcher.get(), "wc1");
1517 CancelWildcardCapableWatch(watcher2.get(), "wc1");
1518 // The XdsClient may or may not send an unsubscription message
1519 // before it closes the transport, depending on callback timing.
1520 request = WaitForRequest(stream.get());
1521 if (request.has_value()) {
1522 CheckRequest(*request, XdsWildcardCapableResourceType::Get()->type_url(),
1523 /*version_info=*/"3", /*response_nonce=*/"C",
1524 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
1525 }
1526 }
1527
1528 // This tests that when we ignore resource deletions from the server
1529 // when configured to do so.
1530 TEST_F(XdsClientTest, ResourceDeletionIgnoredWhenConfigured) {
1531 InitXdsClient(FakeXdsBootstrap::Builder().set_ignore_resource_deletion(true));
1532 // Start a watch for "wc1".
1533 auto watcher = StartWildcardCapableWatch("wc1");
1534 // Watcher should initially not see any resource reported.
1535 EXPECT_FALSE(watcher->HasEvent());
1536 // XdsClient should have created an ADS stream.
1537 auto stream = WaitForAdsStream();
1538 ASSERT_TRUE(stream != nullptr);
1539 // XdsClient should have sent a subscription request on the ADS stream.
1540 auto request = WaitForRequest(stream.get());
1541 ASSERT_TRUE(request.has_value());
1542 CheckRequest(*request, XdsWildcardCapableResourceType::Get()->type_url(),
1543 /*version_info=*/"", /*response_nonce=*/"",
1544 /*error_detail=*/absl::OkStatus(),
1545 /*resource_names=*/{"wc1"});
1546 CheckRequestNode(*request); // Should be present on the first request.
1547 // Server sends a response.
1548 stream->SendMessageToClient(
1549 ResponseBuilder(XdsWildcardCapableResourceType::Get()->type_url())
1550 .set_version_info("1")
1551 .set_nonce("A")
1552 .AddWildcardCapableResource(XdsWildcardCapableResource("wc1", 6))
1553 .Serialize());
1554 // XdsClient should have delivered the response to the watcher.
1555 auto resource = watcher->WaitForNextResource();
1556 ASSERT_TRUE(resource.has_value());
1557 EXPECT_EQ(resource->name, "wc1");
1558 EXPECT_EQ(resource->value, 6);
1559 // XdsClient should have sent an ACK message to the xDS server.
1560 request = WaitForRequest(stream.get());
1561 ASSERT_TRUE(request.has_value());
1562 CheckRequest(*request, XdsWildcardCapableResourceType::Get()->type_url(),
1563 /*version_info=*/"1", /*response_nonce=*/"A",
1564 /*error_detail=*/absl::OkStatus(),
1565 /*resource_names=*/{"wc1"});
1566 // Server now sends a response without the resource, thus indicating
1567 // it's been deleted.
1568 stream->SendMessageToClient(
1569 ResponseBuilder(XdsWildcardCapableResourceType::Get()->type_url())
1570 .set_version_info("2")
1571 .set_nonce("B")
1572 .Serialize());
1573 // Watcher should not see any update, since we should have ignored the
1574 // deletion.
1575 EXPECT_TRUE(watcher->ExpectNoEvent(absl::Seconds(1)));
1576 // Start a new watcher for the same resource. It should immediately
1577 // receive the cached resource.
1578 auto watcher2 = StartWildcardCapableWatch("wc1");
1579 resource = watcher2->WaitForNextResource();
1580 ASSERT_TRUE(resource.has_value());
1581 EXPECT_EQ(resource->name, "wc1");
1582 EXPECT_EQ(resource->value, 6);
1583 // XdsClient should have sent an ACK message to the xDS server.
1584 request = WaitForRequest(stream.get());
1585 ASSERT_TRUE(request.has_value());
1586 CheckRequest(*request, XdsWildcardCapableResourceType::Get()->type_url(),
1587 /*version_info=*/"2", /*response_nonce=*/"B",
1588 /*error_detail=*/absl::OkStatus(),
1589 /*resource_names=*/{"wc1"});
1590 // Server sends a new value for the resource.
1591 stream->SendMessageToClient(
1592 ResponseBuilder(XdsWildcardCapableResourceType::Get()->type_url())
1593 .set_version_info("3")
1594 .set_nonce("C")
1595 .AddWildcardCapableResource(XdsWildcardCapableResource("wc1", 7))
1596 .Serialize());
1597 // XdsClient should have delivered the response to the watchers.
1598 resource = watcher->WaitForNextResource();
1599 ASSERT_TRUE(resource.has_value());
1600 EXPECT_EQ(resource->name, "wc1");
1601 EXPECT_EQ(resource->value, 7);
1602 resource = watcher2->WaitForNextResource();
1603 ASSERT_TRUE(resource.has_value());
1604 EXPECT_EQ(resource->name, "wc1");
1605 EXPECT_EQ(resource->value, 7);
1606 // XdsClient should have sent an ACK message to the xDS server.
1607 request = WaitForRequest(stream.get());
1608 ASSERT_TRUE(request.has_value());
1609 CheckRequest(*request, XdsWildcardCapableResourceType::Get()->type_url(),
1610 /*version_info=*/"3", /*response_nonce=*/"C",
1611 /*error_detail=*/absl::OkStatus(),
1612 /*resource_names=*/{"wc1"});
1613 // Cancel watch.
1614 CancelWildcardCapableWatch(watcher.get(), "wc1");
1615 CancelWildcardCapableWatch(watcher2.get(), "wc1");
1616 // The XdsClient may or may not send an unsubscription message
1617 // before it closes the transport, depending on callback timing.
1618 request = WaitForRequest(stream.get());
1619 if (request.has_value()) {
1620 CheckRequest(*request, XdsWildcardCapableResourceType::Get()->type_url(),
1621 /*version_info=*/"3", /*response_nonce=*/"C",
1622 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
1623 }
1624 }
1625
1626 TEST_F(XdsClientTest, StreamClosedByServer) {
1627 InitXdsClient();
1628 // Start a watch for "foo1".
1629 auto watcher = StartFooWatch("foo1");
1630 // Watcher should initially not see any resource reported.
1631 EXPECT_FALSE(watcher->HasEvent());
1632 // XdsClient should have created an ADS stream.
1633 auto stream = WaitForAdsStream();
1634 ASSERT_TRUE(stream != nullptr);
1635 // XdsClient should have sent a subscription request on the ADS stream.
1636 auto request = WaitForRequest(stream.get());
1637 ASSERT_TRUE(request.has_value());
1638 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1639 /*version_info=*/"", /*response_nonce=*/"",
1640 /*error_detail=*/absl::OkStatus(),
1641 /*resource_names=*/{"foo1"});
1642 CheckRequestNode(*request); // Should be present on the first request.
1643 // Server sends a response.
1644 stream->SendMessageToClient(
1645 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1646 .set_version_info("1")
1647 .set_nonce("A")
1648 .AddFooResource(XdsFooResource("foo1", 6))
1649 .Serialize());
1650 // XdsClient should have delivered the response to the watcher.
1651 auto resource = watcher->WaitForNextResource();
1652 ASSERT_TRUE(resource.has_value());
1653 EXPECT_EQ(resource->name, "foo1");
1654 EXPECT_EQ(resource->value, 6);
1655 // XdsClient should have sent an ACK message to the xDS server.
1656 request = WaitForRequest(stream.get());
1657 ASSERT_TRUE(request.has_value());
1658 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1659 /*version_info=*/"1", /*response_nonce=*/"A",
1660 /*error_detail=*/absl::OkStatus(),
1661 /*resource_names=*/{"foo1"});
1662 // Now server closes the stream.
1663 stream->MaybeSendStatusToClient(absl::OkStatus());
1664 // XdsClient should NOT report error to watcher, because we saw a
1665 // response on the stream before it failed.
1666 // XdsClient should create a new stream.
1667 stream = WaitForAdsStream();
1668 ASSERT_TRUE(stream != nullptr);
1669 // XdsClient sends a subscription request.
1670 // Note that the version persists from the previous stream, but the
1671 // nonce does not.
1672 request = WaitForRequest(stream.get());
1673 ASSERT_TRUE(request.has_value());
1674 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1675 /*version_info=*/"1", /*response_nonce=*/"",
1676 /*error_detail=*/absl::OkStatus(),
1677 /*resource_names=*/{"foo1"});
1678 CheckRequestNode(*request); // Should be present on the first request.
1679 // Before the server resends the resource, start a new watcher for the
1680 // same resource. This watcher should immediately receive the cached
1681 // resource.
1682 auto watcher2 = StartFooWatch("foo1");
1683 resource = watcher2->WaitForNextResource();
1684 ASSERT_TRUE(resource.has_value());
1685 EXPECT_EQ(resource->name, "foo1");
1686 EXPECT_EQ(resource->value, 6);
1687 // Server now sends the requested resource.
1688 stream->SendMessageToClient(
1689 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1690 .set_version_info("1")
1691 .set_nonce("B")
1692 .AddFooResource(XdsFooResource("foo1", 6))
1693 .Serialize());
1694 // Watcher does NOT get an update, since the resource has not changed.
1695 EXPECT_FALSE(watcher->WaitForNextResource());
1696 // XdsClient sends an ACK.
1697 request = WaitForRequest(stream.get());
1698 ASSERT_TRUE(request.has_value());
1699 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1700 /*version_info=*/"1", /*response_nonce=*/"B",
1701 /*error_detail=*/absl::OkStatus(),
1702 /*resource_names=*/{"foo1"});
1703 // Cancel watcher.
1704 CancelFooWatch(watcher.get(), "foo1");
1705 // The XdsClient may or may not send an unsubscription message
1706 // before it closes the transport, depending on callback timing.
1707 request = WaitForRequest(stream.get());
1708 if (request.has_value()) {
1709 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1710 /*version_info=*/"1", /*response_nonce=*/"B",
1711 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
1712 }
1713 }
1714
1715 TEST_F(XdsClientTest, StreamClosedByServerWithoutSeeingResponse) {
1716 InitXdsClient();
1717 // Start a watch for "foo1".
1718 auto watcher = StartFooWatch("foo1");
1719 // Watcher should initially not see any resource reported.
1720 EXPECT_FALSE(watcher->HasEvent());
1721 // XdsClient should have created an ADS stream.
1722 auto stream = WaitForAdsStream();
1723 ASSERT_TRUE(stream != nullptr);
1724 // XdsClient should have sent a subscription request on the ADS stream.
1725 auto request = WaitForRequest(stream.get());
1726 ASSERT_TRUE(request.has_value());
1727 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1728 /*version_info=*/"", /*response_nonce=*/"",
1729 /*error_detail=*/absl::OkStatus(),
1730 /*resource_names=*/{"foo1"});
1731 CheckRequestNode(*request); // Should be present on the first request.
1732 // Server closes the stream without sending a response.
1733 stream->MaybeSendStatusToClient(absl::UnavailableError("ugh"));
1734 // XdsClient should report an error to the watcher.
1735 auto error = watcher->WaitForNextError();
1736 ASSERT_TRUE(error.has_value());
1737 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
1738 EXPECT_EQ(error->message(),
1739 "xDS channel for server default_xds_server: xDS call failed "
1740 "with no responses received; status: UNAVAILABLE: ugh "
1741 "(node ID:xds_client_test)")
1742 << *error;
1743 // XdsClient should create a new stream.
1744 stream = WaitForAdsStream();
1745 ASSERT_TRUE(stream != nullptr);
1746 // XdsClient sends a subscription request.
1747 request = WaitForRequest(stream.get());
1748 ASSERT_TRUE(request.has_value());
1749 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1750 /*version_info=*/"", /*response_nonce=*/"",
1751 /*error_detail=*/absl::OkStatus(),
1752 /*resource_names=*/{"foo1"});
1753 CheckRequestNode(*request); // Should be present on the first request.
1754 // Server now sends the requested resource.
1755 stream->SendMessageToClient(
1756 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1757 .set_version_info("1")
1758 .set_nonce("A")
1759 .AddFooResource(XdsFooResource("foo1", 6))
1760 .Serialize());
1761 // Watcher gets the resource.
1762 auto resource = watcher->WaitForNextResource();
1763 ASSERT_TRUE(resource.has_value());
1764 EXPECT_EQ(resource->name, "foo1");
1765 EXPECT_EQ(resource->value, 6);
1766 // XdsClient sends an ACK.
1767 request = WaitForRequest(stream.get());
1768 ASSERT_TRUE(request.has_value());
1769 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1770 /*version_info=*/"1", /*response_nonce=*/"A",
1771 /*error_detail=*/absl::OkStatus(),
1772 /*resource_names=*/{"foo1"});
1773 // Cancel watcher.
1774 CancelFooWatch(watcher.get(), "foo1");
1775 // The XdsClient may or may not send an unsubscription message
1776 // before it closes the transport, depending on callback timing.
1777 request = WaitForRequest(stream.get());
1778 if (request.has_value()) {
1779 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1780 /*version_info=*/"1", /*response_nonce=*/"A",
1781 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
1782 }
1783 }
1784
1785 TEST_F(XdsClientTest, ConnectionFails) {
1786 // Lower resources-does-not-exist timeout, to make sure that we're not
1787 // triggering that here.
1788 InitXdsClient(FakeXdsBootstrap::Builder(), Duration::Seconds(3));
1789 // Tell transport to let us manually trigger completion of the
1790 // send_message ops to XdsClient.
1791 transport_factory_->SetAutoCompleteMessagesFromClient(false);
1792 // Start a watch for "foo1".
1793 auto watcher = StartFooWatch("foo1");
1794 // Watcher should initially not see any resource reported.
1795 EXPECT_FALSE(watcher->HasEvent());
1796 // XdsClient should have created an ADS stream.
1797 auto stream = WaitForAdsStream();
1798 ASSERT_TRUE(stream != nullptr);
1799 // XdsClient should have sent a subscription request on the ADS stream.
1800 auto request = WaitForRequest(stream.get());
1801 ASSERT_TRUE(request.has_value());
1802 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1803 /*version_info=*/"", /*response_nonce=*/"",
1804 /*error_detail=*/absl::OkStatus(),
1805 /*resource_names=*/{"foo1"});
1806 CheckRequestNode(*request); // Should be present on the first request.
1807 // Transport reports connection failure.
1808 TriggerConnectionFailure(xds_client_->bootstrap().server(),
1809 absl::UnavailableError("connection failed"));
1810 // XdsClient should report an error to the watcher.
1811 auto error = watcher->WaitForNextError();
1812 ASSERT_TRUE(error.has_value());
1813 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
1814 EXPECT_EQ(error->message(),
1815 "xDS channel for server default_xds_server: "
1816 "connection failed (node ID:xds_client_test)")
1817 << *error;
1818 // We should not see a resource-does-not-exist event, because the
1819 // timer should not be running while the channel is disconnected.
1820 EXPECT_TRUE(watcher->ExpectNoEvent(absl::Seconds(4)));
1821 // Start a new watch. This watcher should be given the same error,
1822 // since we have not yet recovered.
1823 auto watcher2 = StartFooWatch("foo1");
1824 error = watcher2->WaitForNextError();
1825 ASSERT_TRUE(error.has_value());
1826 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
1827 EXPECT_EQ(error->message(),
1828 "xDS channel for server default_xds_server: "
1829 "connection failed (node ID:xds_client_test)")
1830 << *error;
1831 // Second watcher should not see resource-does-not-exist either.
1832 EXPECT_FALSE(watcher2->HasEvent());
1833 // The ADS stream uses wait_for_ready inside the XdsTransport interface,
1834 // so when the channel reconnects, the already-started stream will proceed.
1835 stream->CompleteSendMessageFromClient();
1836 // Server sends a response.
1837 stream->SendMessageToClient(
1838 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1839 .set_version_info("1")
1840 .set_nonce("A")
1841 .AddFooResource(XdsFooResource("foo1", 6))
1842 .Serialize());
1843 // XdsClient should have delivered the response to the watchers.
1844 auto resource = watcher->WaitForNextResource();
1845 ASSERT_TRUE(resource.has_value());
1846 EXPECT_EQ(resource->name, "foo1");
1847 EXPECT_EQ(resource->value, 6);
1848 resource = watcher2->WaitForNextResource();
1849 ASSERT_TRUE(resource.has_value());
1850 EXPECT_EQ(resource->name, "foo1");
1851 EXPECT_EQ(resource->value, 6);
1852 // XdsClient should have sent an ACK message to the xDS server.
1853 request = WaitForRequest(stream.get());
1854 ASSERT_TRUE(request.has_value());
1855 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1856 /*version_info=*/"1", /*response_nonce=*/"A",
1857 /*error_detail=*/absl::OkStatus(),
1858 /*resource_names=*/{"foo1"});
1859 stream->CompleteSendMessageFromClient();
1860 // Cancel watches.
1861 CancelFooWatch(watcher.get(), "foo1");
1862 CancelFooWatch(watcher2.get(), "foo1");
1863 // The XdsClient may or may not send an unsubscription message
1864 // before it closes the transport, depending on callback timing.
1865 request = WaitForRequest(stream.get());
1866 if (request.has_value()) {
1867 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1868 /*version_info=*/"1", /*response_nonce=*/"A",
1869 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
1870 stream->CompleteSendMessageFromClient();
1871 }
1872 }
1873
1874 TEST_F(XdsClientTest, ResourceDoesNotExistUponTimeout) {
1875 InitXdsClient(FakeXdsBootstrap::Builder(), Duration::Seconds(1));
1876 // Start a watch for "foo1".
1877 auto watcher = StartFooWatch("foo1");
1878 // Watcher should initially not see any resource reported.
1879 EXPECT_FALSE(watcher->HasEvent());
1880 // XdsClient should have created an ADS stream.
1881 auto stream = WaitForAdsStream();
1882 ASSERT_TRUE(stream != nullptr);
1883 // XdsClient should have sent a subscription request on the ADS stream.
1884 auto request = WaitForRequest(stream.get());
1885 ASSERT_TRUE(request.has_value());
1886 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1887 /*version_info=*/"", /*response_nonce=*/"",
1888 /*error_detail=*/absl::OkStatus(),
1889 /*resource_names=*/{"foo1"});
1890 CheckRequestNode(*request); // Should be present on the first request.
1891 // Do not send a response, but wait for the resource to be reported as
1892 // not existing.
1893 EXPECT_TRUE(watcher->WaitForDoesNotExist(absl::Seconds(5)));
1894 // Start a new watcher for the same resource. It should immediately
1895 // receive the same does-not-exist notification.
1896 auto watcher2 = StartFooWatch("foo1");
1897 EXPECT_TRUE(watcher2->WaitForDoesNotExist(absl::Seconds(1)));
1898 // Now server sends a response.
1899 stream->SendMessageToClient(
1900 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1901 .set_version_info("1")
1902 .set_nonce("A")
1903 .AddFooResource(XdsFooResource("foo1", 6))
1904 .Serialize());
1905 // XdsClient should have delivered the response to the watchers.
1906 auto resource = watcher->WaitForNextResource();
1907 ASSERT_TRUE(resource.has_value());
1908 EXPECT_EQ(resource->name, "foo1");
1909 EXPECT_EQ(resource->value, 6);
1910 resource = watcher2->WaitForNextResource();
1911 ASSERT_TRUE(resource.has_value());
1912 EXPECT_EQ(resource->name, "foo1");
1913 EXPECT_EQ(resource->value, 6);
1914 // XdsClient should have sent an ACK message to the xDS server.
1915 request = WaitForRequest(stream.get());
1916 ASSERT_TRUE(request.has_value());
1917 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1918 /*version_info=*/"1", /*response_nonce=*/"A",
1919 /*error_detail=*/absl::OkStatus(),
1920 /*resource_names=*/{"foo1"});
1921 // Cancel watch.
1922 CancelFooWatch(watcher.get(), "foo1");
1923 CancelFooWatch(watcher2.get(), "foo1");
1924 // The XdsClient may or may not send an unsubscription message
1925 // before it closes the transport, depending on callback timing.
1926 request = WaitForRequest(stream.get());
1927 if (request.has_value()) {
1928 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1929 /*version_info=*/"1", /*response_nonce=*/"A",
1930 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
1931 }
1932 }
1933
1934 TEST_F(XdsClientTest, ResourceDoesNotExistAfterStreamRestart) {
1935 // Lower resources-does-not-exist timeout so test finishes faster.
1936 InitXdsClient(FakeXdsBootstrap::Builder(), Duration::Seconds(3));
1937 // Start a watch for "foo1".
1938 auto watcher = StartFooWatch("foo1");
1939 // Watcher should initially not see any resource reported.
1940 EXPECT_FALSE(watcher->HasEvent());
1941 // XdsClient should have created an ADS stream.
1942 auto stream = WaitForAdsStream();
1943 ASSERT_TRUE(stream != nullptr);
1944 // XdsClient should have sent a subscription request on the ADS stream.
1945 auto request = WaitForRequest(stream.get());
1946 ASSERT_TRUE(request.has_value());
1947 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1948 /*version_info=*/"", /*response_nonce=*/"",
1949 /*error_detail=*/absl::OkStatus(),
1950 /*resource_names=*/{"foo1"});
1951 CheckRequestNode(*request); // Should be present on the first request.
1952 // Stream fails.
1953 stream->MaybeSendStatusToClient(absl::UnavailableError("ugh"));
1954 // XdsClient should report error to watcher.
1955 auto error = watcher->WaitForNextError();
1956 ASSERT_TRUE(error.has_value());
1957 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
1958 EXPECT_EQ(error->message(),
1959 "xDS channel for server default_xds_server: xDS call failed "
1960 "with no responses received; status: UNAVAILABLE: ugh "
1961 "(node ID:xds_client_test)")
1962 << *error;
1963 // XdsClient should create a new stream.
1964 stream = WaitForAdsStream();
1965 ASSERT_TRUE(stream != nullptr);
1966 // XdsClient sends a subscription request.
1967 request = WaitForRequest(stream.get());
1968 ASSERT_TRUE(request.has_value());
1969 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1970 /*version_info=*/"", /*response_nonce=*/"",
1971 /*error_detail=*/absl::OkStatus(),
1972 /*resource_names=*/{"foo1"});
1973 CheckRequestNode(*request); // Should be present on the first request.
1974 // Server does NOT send a response immediately.
1975 // Client should receive a resource does-not-exist.
1976 ASSERT_TRUE(watcher->WaitForDoesNotExist(absl::Seconds(4)));
1977 // Server now sends the requested resource.
1978 stream->SendMessageToClient(
1979 ResponseBuilder(XdsFooResourceType::Get()->type_url())
1980 .set_version_info("1")
1981 .set_nonce("A")
1982 .AddFooResource(XdsFooResource("foo1", 6))
1983 .Serialize());
1984 // The resource is delivered to the watcher.
1985 auto resource = watcher->WaitForNextResource();
1986 ASSERT_TRUE(resource.has_value());
1987 EXPECT_EQ(resource->name, "foo1");
1988 EXPECT_EQ(resource->value, 6);
1989 // XdsClient sends an ACK.
1990 request = WaitForRequest(stream.get());
1991 ASSERT_TRUE(request.has_value());
1992 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
1993 /*version_info=*/"1", /*response_nonce=*/"A",
1994 /*error_detail=*/absl::OkStatus(),
1995 /*resource_names=*/{"foo1"});
1996 // Cancel watcher.
1997 CancelFooWatch(watcher.get(), "foo1");
1998 // The XdsClient may or may not send an unsubscription message
1999 // before it closes the transport, depending on callback timing.
2000 request = WaitForRequest(stream.get());
2001 if (request.has_value()) {
2002 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2003 /*version_info=*/"1", /*response_nonce=*/"A",
2004 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2005 }
2006 }
2007
2008 TEST_F(XdsClientTest, DoesNotExistTimerNotStartedUntilSendCompletes) {
2009 // Lower resources-does-not-exist timeout, to make sure that we're not
2010 // triggering that here.
2011 InitXdsClient(FakeXdsBootstrap::Builder(), Duration::Seconds(3));
2012 // Tell transport to let us manually trigger completion of the
2013 // send_message ops to XdsClient.
2014 transport_factory_->SetAutoCompleteMessagesFromClient(false);
2015 // Start a watch for "foo1".
2016 auto watcher = StartFooWatch("foo1");
2017 // Watcher should initially not see any resource reported.
2018 EXPECT_FALSE(watcher->HasEvent());
2019 // XdsClient should have created an ADS stream.
2020 auto stream = WaitForAdsStream();
2021 ASSERT_TRUE(stream != nullptr);
2022 // XdsClient should have sent a subscription request on the ADS stream.
2023 auto request = WaitForRequest(stream.get());
2024 ASSERT_TRUE(request.has_value());
2025 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2026 /*version_info=*/"", /*response_nonce=*/"",
2027 /*error_detail=*/absl::OkStatus(),
2028 /*resource_names=*/{"foo1"});
2029 CheckRequestNode(*request); // Should be present on the first request.
2030 // Server does NOT send a response.
2031 // We should not see a resource-does-not-exist event, because the
2032 // timer should not be running while the channel is disconnected.
2033 EXPECT_TRUE(watcher->ExpectNoEvent(absl::Seconds(4)));
2034 // The ADS stream uses wait_for_ready inside the XdsTransport interface,
2035 // so when the channel connects, the already-started stream will proceed.
2036 stream->CompleteSendMessageFromClient();
2037 // Server does NOT send a response.
2038 // Watcher should see a does-not-exist event.
2039 EXPECT_TRUE(watcher->WaitForDoesNotExist(absl::Seconds(4)));
2040 // Now server sends a response.
2041 stream->SendMessageToClient(
2042 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2043 .set_version_info("1")
2044 .set_nonce("A")
2045 .AddFooResource(XdsFooResource("foo1", 6))
2046 .Serialize());
2047 // XdsClient should have delivered the response to the watcher.
2048 auto resource = watcher->WaitForNextResource();
2049 ASSERT_TRUE(resource.has_value());
2050 EXPECT_EQ(resource->name, "foo1");
2051 EXPECT_EQ(resource->value, 6);
2052 // XdsClient should have sent an ACK message to the xDS server.
2053 request = WaitForRequest(stream.get());
2054 ASSERT_TRUE(request.has_value());
2055 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2056 /*version_info=*/"1", /*response_nonce=*/"A",
2057 /*error_detail=*/absl::OkStatus(),
2058 /*resource_names=*/{"foo1"});
2059 stream->CompleteSendMessageFromClient();
2060 // Cancel watch.
2061 CancelFooWatch(watcher.get(), "foo1");
2062 // The XdsClient may or may not send an unsubscription message
2063 // before it closes the transport, depending on callback timing.
2064 request = WaitForRequest(stream.get());
2065 if (request.has_value()) {
2066 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2067 /*version_info=*/"1", /*response_nonce=*/"A",
2068 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2069 stream->CompleteSendMessageFromClient();
2070 }
2071 }
2072
2073 // In https://github.com/grpc/grpc/issues/29583, we ran into a case
2074 // where we wound up starting a timer after we had already received the
2075 // resource, thus incorrectly reporting the resource as not existing.
2076 // This happened when unsubscribing and then resubscribing to the same
2077 // resource a send_message op was already in flight and then receiving an
2078 // update containing that resource.
2079 TEST_F(XdsClientTest,
2080 ResourceDoesNotExistUnsubscribeAndResubscribeWhileSendMessagePending) {
2081 InitXdsClient(FakeXdsBootstrap::Builder(), Duration::Seconds(1));
2082 // Tell transport to let us manually trigger completion of the
2083 // send_message ops to XdsClient.
2084 transport_factory_->SetAutoCompleteMessagesFromClient(false);
2085 // Start a watch for "foo1".
2086 auto watcher = StartFooWatch("foo1");
2087 // Watcher should initially not see any resource reported.
2088 EXPECT_FALSE(watcher->HasEvent());
2089 // XdsClient should have created an ADS stream.
2090 auto stream = WaitForAdsStream();
2091 ASSERT_TRUE(stream != nullptr);
2092 // XdsClient should have sent a subscription request on the ADS stream.
2093 auto request = WaitForRequest(stream.get());
2094 ASSERT_TRUE(request.has_value());
2095 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2096 /*version_info=*/"", /*response_nonce=*/"",
2097 /*error_detail=*/absl::OkStatus(),
2098 /*resource_names=*/{"foo1"});
2099 CheckRequestNode(*request); // Should be present on the first request.
2100 stream->CompleteSendMessageFromClient();
2101 // Server sends a response.
2102 stream->SendMessageToClient(
2103 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2104 .set_version_info("1")
2105 .set_nonce("A")
2106 .AddFooResource(XdsFooResource("foo1", 6))
2107 .Serialize());
2108 // XdsClient should have delivered the response to the watchers.
2109 auto resource = watcher->WaitForNextResource();
2110 ASSERT_TRUE(resource.has_value());
2111 EXPECT_EQ(resource->name, "foo1");
2112 EXPECT_EQ(resource->value, 6);
2113 // XdsClient should have sent an ACK message to the xDS server.
2114 request = WaitForRequest(stream.get());
2115 ASSERT_TRUE(request.has_value());
2116 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2117 /*version_info=*/"1", /*response_nonce=*/"A",
2118 /*error_detail=*/absl::OkStatus(),
2119 /*resource_names=*/{"foo1"});
2120 stream->CompleteSendMessageFromClient();
2121 // Start a watch for a second resource.
2122 auto watcher2 = StartFooWatch("foo2");
2123 // Watcher should initially not see any resource reported.
2124 EXPECT_FALSE(watcher2->HasEvent());
2125 // XdsClient sends a request to subscribe to the new resource.
2126 request = WaitForRequest(stream.get());
2127 ASSERT_TRUE(request.has_value());
2128 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2129 /*version_info=*/"1", /*response_nonce=*/"A",
2130 /*error_detail=*/absl::OkStatus(),
2131 /*resource_names=*/{"foo1", "foo2"});
2132 // NOTE: We do NOT yet tell the XdsClient that the send_message op is
2133 // complete.
2134 // Unsubscribe from foo1 and then re-subscribe to it.
2135 CancelFooWatch(watcher.get(), "foo1");
2136 watcher = StartFooWatch("foo1");
2137 // Now send a response from the server containing both foo1 and foo2.
2138 stream->SendMessageToClient(
2139 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2140 .set_version_info("1")
2141 .set_nonce("B")
2142 .AddFooResource(XdsFooResource("foo1", 6))
2143 .AddFooResource(XdsFooResource("foo2", 7))
2144 .Serialize());
2145 // The watcher for foo1 will receive an update even if the resource
2146 // has not changed, since the previous value was removed from the
2147 // cache when we unsubscribed.
2148 resource = watcher->WaitForNextResource();
2149 ASSERT_TRUE(resource.has_value());
2150 EXPECT_EQ(resource->name, "foo1");
2151 EXPECT_EQ(resource->value, 6);
2152 // For foo2, the watcher should receive notification for the new resource.
2153 resource = watcher2->WaitForNextResource();
2154 ASSERT_TRUE(resource.has_value());
2155 EXPECT_EQ(resource->name, "foo2");
2156 EXPECT_EQ(resource->value, 7);
2157 // Now we finally tell XdsClient that its previous send_message op is
2158 // complete.
2159 stream->CompleteSendMessageFromClient();
2160 // XdsClient should send an ACK with the updated subscription list
2161 // (which happens to be identical to the old list), and it should not
2162 // restart the does-not-exist timer.
2163 request = WaitForRequest(stream.get());
2164 ASSERT_TRUE(request.has_value());
2165 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2166 /*version_info=*/"1", /*response_nonce=*/"B",
2167 /*error_detail=*/absl::OkStatus(),
2168 /*resource_names=*/{"foo1", "foo2"});
2169 stream->CompleteSendMessageFromClient();
2170 // Make sure the watcher for foo1 does not see a does-not-exist event.
2171 EXPECT_TRUE(watcher->ExpectNoEvent(absl::Seconds(5)));
2172 // Cancel watches.
2173 CancelFooWatch(watcher.get(), "foo1", /*delay_unsubscription=*/true);
2174 CancelFooWatch(watcher2.get(), "foo2");
2175 // The XdsClient may or may not send an unsubscription message
2176 // before it closes the transport, depending on callback timing.
2177 request = WaitForRequest(stream.get());
2178 if (request.has_value()) {
2179 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2180 /*version_info=*/"1", /*response_nonce=*/"B",
2181 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2182 stream->CompleteSendMessageFromClient();
2183 }
2184 }
2185
2186 TEST_F(XdsClientTest, DoNotSendDoesNotExistForCachedResource) {
2187 // Lower resources-does-not-exist timeout, to make sure that we're not
2188 // triggering that here.
2189 InitXdsClient(FakeXdsBootstrap::Builder(), Duration::Seconds(3));
2190 // Start a watch for "foo1".
2191 auto watcher = StartFooWatch("foo1");
2192 // Watcher should initially not see any resource reported.
2193 EXPECT_FALSE(watcher->HasEvent());
2194 // XdsClient should have created an ADS stream.
2195 auto stream = WaitForAdsStream();
2196 ASSERT_TRUE(stream != nullptr);
2197 // XdsClient should have sent a subscription request on the ADS stream.
2198 auto request = WaitForRequest(stream.get());
2199 ASSERT_TRUE(request.has_value());
2200 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2201 /*version_info=*/"", /*response_nonce=*/"",
2202 /*error_detail=*/absl::OkStatus(),
2203 /*resource_names=*/{"foo1"});
2204 CheckRequestNode(*request); // Should be present on the first request.
2205 // Server sends a response.
2206 stream->SendMessageToClient(
2207 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2208 .set_version_info("1")
2209 .set_nonce("A")
2210 .AddFooResource(XdsFooResource("foo1", 6))
2211 .Serialize());
2212 // XdsClient should have delivered the response to the watcher.
2213 auto resource = watcher->WaitForNextResource();
2214 ASSERT_TRUE(resource.has_value());
2215 EXPECT_EQ(resource->name, "foo1");
2216 EXPECT_EQ(resource->value, 6);
2217 // XdsClient should have sent an ACK message to the xDS server.
2218 request = WaitForRequest(stream.get());
2219 ASSERT_TRUE(request.has_value());
2220 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2221 /*version_info=*/"1", /*response_nonce=*/"A",
2222 /*error_detail=*/absl::OkStatus(),
2223 /*resource_names=*/{"foo1"});
2224 // Stream fails because of transport disconnection.
2225 stream->MaybeSendStatusToClient(absl::UnavailableError("connection failed"));
2226 // XdsClient should NOT report error to watcher, because we saw a
2227 // response on the stream before it failed.
2228 // XdsClient creates a new stream.
2229 stream = WaitForAdsStream();
2230 ASSERT_TRUE(stream != nullptr);
2231 // XdsClient should have sent a subscription request on the ADS stream.
2232 request = WaitForRequest(stream.get());
2233 ASSERT_TRUE(request.has_value());
2234 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2235 /*version_info=*/"1", /*response_nonce=*/"",
2236 /*error_detail=*/absl::OkStatus(),
2237 /*resource_names=*/{"foo1"});
2238 CheckRequestNode(*request); // Should be present on the first request.
2239 // Server does NOT send a response.
2240 // We should not see a resource-does-not-exist event, because the
2241 // resource was already cached, so the server can optimize by not
2242 // resending it.
2243 EXPECT_TRUE(watcher->ExpectNoEvent(absl::Seconds(4)));
2244 // Now server sends a response.
2245 stream->SendMessageToClient(
2246 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2247 .set_version_info("1")
2248 .set_nonce("A")
2249 .AddFooResource(XdsFooResource("foo1", 6))
2250 .Serialize());
2251 // Watcher will not see any update, since the resource is unchanged.
2252 EXPECT_TRUE(watcher->ExpectNoEvent(absl::Seconds(1)));
2253 // XdsClient should have sent an ACK message to the xDS server.
2254 request = WaitForRequest(stream.get());
2255 ASSERT_TRUE(request.has_value());
2256 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2257 /*version_info=*/"1", /*response_nonce=*/"A",
2258 /*error_detail=*/absl::OkStatus(),
2259 /*resource_names=*/{"foo1"});
2260 // Cancel watch.
2261 CancelFooWatch(watcher.get(), "foo1");
2262 // The XdsClient may or may not send an unsubscription message
2263 // before it closes the transport, depending on callback timing.
2264 request = WaitForRequest(stream.get());
2265 if (request.has_value()) {
2266 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2267 /*version_info=*/"1", /*response_nonce=*/"A",
2268 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2269 }
2270 }
2271
2272 TEST_F(XdsClientTest, ResourceWrappedInResourceMessage) {
2273 InitXdsClient();
2274 // Start a watch for "foo1".
2275 auto watcher = StartFooWatch("foo1");
2276 // Watcher should initially not see any resource reported.
2277 EXPECT_FALSE(watcher->HasEvent());
2278 // XdsClient should have created an ADS stream.
2279 auto stream = WaitForAdsStream();
2280 ASSERT_TRUE(stream != nullptr);
2281 // XdsClient should have sent a subscription request on the ADS stream.
2282 auto request = WaitForRequest(stream.get());
2283 ASSERT_TRUE(request.has_value());
2284 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2285 /*version_info=*/"", /*response_nonce=*/"",
2286 /*error_detail=*/absl::OkStatus(),
2287 /*resource_names=*/{"foo1"});
2288 CheckRequestNode(*request); // Should be present on the first request.
2289 // Send a response with the resource wrapped in a Resource message.
2290 stream->SendMessageToClient(
2291 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2292 .set_version_info("1")
2293 .set_nonce("A")
2294 .AddFooResource(XdsFooResource("foo1", 6),
2295 /*in_resource_wrapper=*/true)
2296 .Serialize());
2297 // XdsClient should have delivered the response to the watcher.
2298 auto resource = watcher->WaitForNextResource();
2299 ASSERT_TRUE(resource.has_value());
2300 EXPECT_EQ(resource->name, "foo1");
2301 EXPECT_EQ(resource->value, 6);
2302 // XdsClient should have sent an ACK message to the xDS server.
2303 request = WaitForRequest(stream.get());
2304 ASSERT_TRUE(request.has_value());
2305 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2306 /*version_info=*/"1", /*response_nonce=*/"A",
2307 /*error_detail=*/absl::OkStatus(),
2308 /*resource_names=*/{"foo1"});
2309 // Cancel watch.
2310 CancelFooWatch(watcher.get(), "foo1");
2311 // The XdsClient may or may not send an unsubscription message
2312 // before it closes the transport, depending on callback timing.
2313 request = WaitForRequest(stream.get());
2314 if (request.has_value()) {
2315 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2316 /*version_info=*/"1", /*response_nonce=*/"A",
2317 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2318 }
2319 }
2320
2321 TEST_F(XdsClientTest, MultipleResourceTypes) {
2322 InitXdsClient();
2323 // Start a watch for "foo1".
2324 auto watcher = StartFooWatch("foo1");
2325 // Watcher should initially not see any resource reported.
2326 EXPECT_FALSE(watcher->HasEvent());
2327 // XdsClient should have created an ADS stream.
2328 auto stream = WaitForAdsStream();
2329 ASSERT_TRUE(stream != nullptr);
2330 // XdsClient should have sent a subscription request on the ADS stream.
2331 auto request = WaitForRequest(stream.get());
2332 ASSERT_TRUE(request.has_value());
2333 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2334 /*version_info=*/"", /*response_nonce=*/"",
2335 /*error_detail=*/absl::OkStatus(),
2336 /*resource_names=*/{"foo1"});
2337 CheckRequestNode(*request); // Should be present on the first request.
2338 // Send a response.
2339 stream->SendMessageToClient(
2340 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2341 .set_version_info("1")
2342 .set_nonce("A")
2343 .AddFooResource(XdsFooResource("foo1", 6))
2344 .Serialize());
2345 // XdsClient should have delivered the response to the watcher.
2346 auto resource = watcher->WaitForNextResource();
2347 ASSERT_TRUE(resource.has_value());
2348 EXPECT_EQ(resource->name, "foo1");
2349 EXPECT_EQ(resource->value, 6);
2350 // XdsClient should have sent an ACK message to the xDS server.
2351 request = WaitForRequest(stream.get());
2352 ASSERT_TRUE(request.has_value());
2353 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2354 /*version_info=*/"1", /*response_nonce=*/"A",
2355 /*error_detail=*/absl::OkStatus(),
2356 /*resource_names=*/{"foo1"});
2357 // Start a watch for "bar1".
2358 auto watcher2 = StartBarWatch("bar1");
2359 // XdsClient should have sent a subscription request on the ADS stream.
2360 // Note that version and nonce here do NOT use the values for Foo,
2361 // since each resource type has its own state.
2362 request = WaitForRequest(stream.get());
2363 ASSERT_TRUE(request.has_value());
2364 CheckRequest(*request, XdsBarResourceType::Get()->type_url(),
2365 /*version_info=*/"", /*response_nonce=*/"",
2366 /*error_detail=*/absl::OkStatus(),
2367 /*resource_names=*/{"bar1"});
2368 // Send a response.
2369 stream->SendMessageToClient(
2370 ResponseBuilder(XdsBarResourceType::Get()->type_url())
2371 .set_version_info("2")
2372 .set_nonce("B")
2373 .AddBarResource(XdsBarResource("bar1", "whee"))
2374 .Serialize());
2375 // XdsClient should have delivered the response to the watcher.
2376 auto resource2 = watcher2->WaitForNextResource();
2377 ASSERT_TRUE(resource2.has_value());
2378 EXPECT_EQ(resource2->name, "bar1");
2379 EXPECT_EQ(resource2->value, "whee");
2380 // XdsClient should have sent an ACK message to the xDS server.
2381 request = WaitForRequest(stream.get());
2382 ASSERT_TRUE(request.has_value());
2383 CheckRequest(*request, XdsBarResourceType::Get()->type_url(),
2384 /*version_info=*/"2", /*response_nonce=*/"B",
2385 /*error_detail=*/absl::OkStatus(),
2386 /*resource_names=*/{"bar1"});
2387 // Cancel watch for "foo1".
2388 CancelFooWatch(watcher.get(), "foo1");
2389 // XdsClient should send an unsubscription request.
2390 request = WaitForRequest(stream.get());
2391 ASSERT_TRUE(request.has_value());
2392 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2393 /*version_info=*/"1", /*response_nonce=*/"A",
2394 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2395 // Now cancel watch for "bar1".
2396 CancelBarWatch(watcher2.get(), "bar1");
2397 // The XdsClient may or may not send another unsubscription message
2398 // before it closes the transport, depending on callback timing.
2399 request = WaitForRequest(stream.get());
2400 if (request.has_value()) {
2401 CheckRequest(*request, XdsBarResourceType::Get()->type_url(),
2402 /*version_info=*/"2", /*response_nonce=*/"B",
2403 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2404 }
2405 }
2406
2407 TEST_F(XdsClientTest, Federation) {
2408 ScopedExperimentalEnvVar env_var("GRPC_EXPERIMENTAL_XDS_FEDERATION");
2409 constexpr char kAuthority[] = "xds.example.com";
2410 const std::string kXdstpResourceName = absl::StrCat(
2411 "xdstp://", kAuthority, "/", XdsFooResource::TypeUrl(), "/foo2");
2412 FakeXdsBootstrap::FakeXdsServer authority_server;
2413 authority_server.set_server_uri("other_xds_server");
2414 FakeXdsBootstrap::FakeAuthority authority;
2415 authority.set_server(authority_server);
2416 InitXdsClient(
2417 FakeXdsBootstrap::Builder().AddAuthority(kAuthority, authority));
2418 // Start a watch for "foo1".
2419 auto watcher = StartFooWatch("foo1");
2420 // Watcher should initially not see any resource reported.
2421 EXPECT_FALSE(watcher->HasEvent());
2422 // XdsClient should have created an ADS stream to the top-level xDS server.
2423 auto stream = WaitForAdsStream(xds_client_->bootstrap().server());
2424 ASSERT_TRUE(stream != nullptr);
2425 // XdsClient should have sent a subscription request on the ADS stream.
2426 auto request = WaitForRequest(stream.get());
2427 ASSERT_TRUE(request.has_value());
2428 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2429 /*version_info=*/"", /*response_nonce=*/"",
2430 /*error_detail=*/absl::OkStatus(),
2431 /*resource_names=*/{"foo1"});
2432 CheckRequestNode(*request); // Should be present on the first request.
2433 // Send a response.
2434 stream->SendMessageToClient(
2435 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2436 .set_version_info("1")
2437 .set_nonce("A")
2438 .AddFooResource(XdsFooResource("foo1", 6))
2439 .Serialize());
2440 // XdsClient should have delivered the response to the watcher.
2441 auto resource = watcher->WaitForNextResource();
2442 ASSERT_TRUE(resource.has_value());
2443 EXPECT_EQ(resource->name, "foo1");
2444 EXPECT_EQ(resource->value, 6);
2445 // XdsClient should have sent an ACK message to the xDS server.
2446 request = WaitForRequest(stream.get());
2447 ASSERT_TRUE(request.has_value());
2448 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2449 /*version_info=*/"1", /*response_nonce=*/"A",
2450 /*error_detail=*/absl::OkStatus(),
2451 /*resource_names=*/{"foo1"});
2452 // Start a watch for the xdstp resource name.
2453 auto watcher2 = StartFooWatch(kXdstpResourceName);
2454 // Watcher should initially not see any resource reported.
2455 EXPECT_FALSE(watcher2->HasEvent());
2456 // XdsClient will create a new stream to the server for this authority.
2457 auto stream2 = WaitForAdsStream(authority_server);
2458 ASSERT_TRUE(stream2 != nullptr);
2459 // XdsClient should have sent a subscription request on the ADS stream.
2460 // Note that version and nonce here do NOT use the values for Foo,
2461 // since each authority has its own state.
2462 request = WaitForRequest(stream2.get());
2463 ASSERT_TRUE(request.has_value());
2464 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2465 /*version_info=*/"", /*response_nonce=*/"",
2466 /*error_detail=*/absl::OkStatus(),
2467 /*resource_names=*/{kXdstpResourceName});
2468 CheckRequestNode(*request); // Should be present on the first request.
2469 // Send a response.
2470 stream2->SendMessageToClient(
2471 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2472 .set_version_info("2")
2473 .set_nonce("B")
2474 .AddFooResource(XdsFooResource(kXdstpResourceName, 3))
2475 .Serialize());
2476 // XdsClient should have delivered the response to the watcher.
2477 resource = watcher2->WaitForNextResource();
2478 ASSERT_TRUE(resource.has_value());
2479 EXPECT_EQ(resource->name, kXdstpResourceName);
2480 EXPECT_EQ(resource->value, 3);
2481 // XdsClient should have sent an ACK message to the xDS server.
2482 request = WaitForRequest(stream2.get());
2483 ASSERT_TRUE(request.has_value());
2484 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2485 /*version_info=*/"2", /*response_nonce=*/"B",
2486 /*error_detail=*/absl::OkStatus(),
2487 /*resource_names=*/{kXdstpResourceName});
2488 // Cancel watch for "foo1".
2489 CancelFooWatch(watcher.get(), "foo1");
2490 // The XdsClient may or may not send the unsubscription message
2491 // before it closes the transport, depending on callback timing.
2492 request = WaitForRequest(stream.get());
2493 if (request.has_value()) {
2494 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2495 /*version_info=*/"1", /*response_nonce=*/"A",
2496 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2497 }
2498 // Now cancel watch for xdstp resource name.
2499 CancelFooWatch(watcher2.get(), kXdstpResourceName);
2500 // The XdsClient may or may not send the unsubscription message
2501 // before it closes the transport, depending on callback timing.
2502 request = WaitForRequest(stream2.get());
2503 if (request.has_value()) {
2504 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2505 /*version_info=*/"2", /*response_nonce=*/"B",
2506 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2507 }
2508 }
2509
2510 TEST_F(XdsClientTest, FederationAuthorityDefaultsToTopLevelXdsServer) {
2511 ScopedExperimentalEnvVar env_var("GRPC_EXPERIMENTAL_XDS_FEDERATION");
2512 constexpr char kAuthority[] = "xds.example.com";
2513 const std::string kXdstpResourceName = absl::StrCat(
2514 "xdstp://", kAuthority, "/", XdsFooResource::TypeUrl(), "/foo2");
2515 // Authority does not specify any xDS servers, so XdsClient will use
2516 // the top-level xDS server in the bootstrap config for this authority.
2517 InitXdsClient(FakeXdsBootstrap::Builder().AddAuthority(
2518 kAuthority, FakeXdsBootstrap::FakeAuthority()));
2519 // Start a watch for "foo1".
2520 auto watcher = StartFooWatch("foo1");
2521 // Watcher should initially not see any resource reported.
2522 EXPECT_FALSE(watcher->HasEvent());
2523 // XdsClient should have created an ADS stream to the top-level xDS server.
2524 auto stream = WaitForAdsStream(xds_client_->bootstrap().server());
2525 ASSERT_TRUE(stream != nullptr);
2526 // XdsClient should have sent a subscription request on the ADS stream.
2527 auto request = WaitForRequest(stream.get());
2528 ASSERT_TRUE(request.has_value());
2529 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2530 /*version_info=*/"", /*response_nonce=*/"",
2531 /*error_detail=*/absl::OkStatus(),
2532 /*resource_names=*/{"foo1"});
2533 CheckRequestNode(*request); // Should be present on the first request.
2534 // Send a response.
2535 stream->SendMessageToClient(
2536 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2537 .set_version_info("1")
2538 .set_nonce("A")
2539 .AddFooResource(XdsFooResource("foo1", 6))
2540 .Serialize());
2541 // XdsClient should have delivered the response to the watcher.
2542 auto resource = watcher->WaitForNextResource();
2543 ASSERT_TRUE(resource.has_value());
2544 EXPECT_EQ(resource->name, "foo1");
2545 EXPECT_EQ(resource->value, 6);
2546 // XdsClient should have sent an ACK message to the xDS server.
2547 request = WaitForRequest(stream.get());
2548 ASSERT_TRUE(request.has_value());
2549 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2550 /*version_info=*/"1", /*response_nonce=*/"A",
2551 /*error_detail=*/absl::OkStatus(),
2552 /*resource_names=*/{"foo1"});
2553 // Start a watch for the xdstp resource name.
2554 auto watcher2 = StartFooWatch(kXdstpResourceName);
2555 // Watcher should initially not see any resource reported.
2556 EXPECT_FALSE(watcher2->HasEvent());
2557 // XdsClient will send a subscription request on the ADS stream that
2558 // includes both resources, since both are being obtained from the
2559 // same server.
2560 request = WaitForRequest(stream.get());
2561 ASSERT_TRUE(request.has_value());
2562 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2563 /*version_info=*/"1", /*response_nonce=*/"A",
2564 /*error_detail=*/absl::OkStatus(),
2565 /*resource_names=*/{"foo1", kXdstpResourceName});
2566 // Send a response.
2567 stream->SendMessageToClient(
2568 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2569 .set_version_info("2")
2570 .set_nonce("B")
2571 .AddFooResource(XdsFooResource(kXdstpResourceName, 3))
2572 .Serialize());
2573 // XdsClient should have delivered the response to the watcher.
2574 resource = watcher2->WaitForNextResource();
2575 ASSERT_TRUE(resource.has_value());
2576 EXPECT_EQ(resource->name, kXdstpResourceName);
2577 EXPECT_EQ(resource->value, 3);
2578 // XdsClient should have sent an ACK message to the xDS server.
2579 request = WaitForRequest(stream.get());
2580 ASSERT_TRUE(request.has_value());
2581 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2582 /*version_info=*/"2", /*response_nonce=*/"B",
2583 /*error_detail=*/absl::OkStatus(),
2584 /*resource_names=*/{"foo1", kXdstpResourceName});
2585 // Cancel watch for "foo1".
2586 CancelFooWatch(watcher.get(), "foo1");
2587 // XdsClient should send an unsubscription request.
2588 request = WaitForRequest(stream.get());
2589 ASSERT_TRUE(request.has_value());
2590 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2591 /*version_info=*/"2", /*response_nonce=*/"B",
2592 /*error_detail=*/absl::OkStatus(),
2593 /*resource_names=*/{kXdstpResourceName});
2594 // Now cancel watch for xdstp resource name.
2595 CancelFooWatch(watcher2.get(), kXdstpResourceName);
2596 // The XdsClient may or may not send the unsubscription message
2597 // before it closes the transport, depending on callback timing.
2598 request = WaitForRequest(stream.get());
2599 if (request.has_value()) {
2600 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2601 /*version_info=*/"2", /*response_nonce=*/"B",
2602 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2603 }
2604 }
2605
2606 TEST_F(XdsClientTest, FederationWithUnknownAuthority) {
2607 ScopedExperimentalEnvVar env_var("GRPC_EXPERIMENTAL_XDS_FEDERATION");
2608 constexpr char kAuthority[] = "xds.example.com";
2609 const std::string kXdstpResourceName = absl::StrCat(
2610 "xdstp://", kAuthority, "/", XdsFooResource::TypeUrl(), "/foo2");
2611 // Note: Not adding authority to bootstrap config.
2612 InitXdsClient();
2613 // Start a watch for the xdstp resource name.
2614 auto watcher = StartFooWatch(kXdstpResourceName);
2615 // Watcher should immediately get an error about the unknown authority.
2616 auto error = watcher->WaitForNextError();
2617 ASSERT_TRUE(error.has_value());
2618 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
2619 EXPECT_EQ(error->message(),
2620 "authority \"xds.example.com\" not present in bootstrap config")
2621 << *error;
2622 }
2623
2624 TEST_F(XdsClientTest, FederationWithUnparseableXdstpResourceName) {
2625 ScopedExperimentalEnvVar env_var("GRPC_EXPERIMENTAL_XDS_FEDERATION");
2626 // Note: Not adding authority to bootstrap config.
2627 InitXdsClient();
2628 // Start a watch for the xdstp resource name.
2629 auto watcher = StartFooWatch("xdstp://x");
2630 // Watcher should immediately get an error about the unknown authority.
2631 auto error = watcher->WaitForNextError();
2632 ASSERT_TRUE(error.has_value());
2633 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
2634 EXPECT_EQ(error->message(), "Unable to parse resource name xdstp://x")
2635 << *error;
2636 }
2637
2638 TEST_F(XdsClientTest, FederationDisabledWithNewStyleName) {
2639 // We will use this xdstp name, whose authority is not present in
2640 // the bootstrap config. But since federation is not enabled, we
2641 // will treat this as an opaque old-style name, so we'll send it to
2642 // the default server.
2643 constexpr char kXdstpResourceName[] =
2644 "xdstp://xds.example.com/test.v3.foo/foo1";
2645 InitXdsClient();
2646 // Start a watch for the xdstp name.
2647 auto watcher = StartFooWatch(kXdstpResourceName);
2648 // Watcher should initially not see any resource reported.
2649 EXPECT_FALSE(watcher->HasEvent());
2650 // XdsClient should have created an ADS stream.
2651 auto stream = WaitForAdsStream();
2652 ASSERT_TRUE(stream != nullptr);
2653 // XdsClient should have sent a subscription request on the ADS stream.
2654 auto request = WaitForRequest(stream.get());
2655 ASSERT_TRUE(request.has_value());
2656 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2657 /*version_info=*/"", /*response_nonce=*/"",
2658 /*error_detail=*/absl::OkStatus(),
2659 /*resource_names=*/{kXdstpResourceName});
2660 CheckRequestNode(*request); // Should be present on the first request.
2661 // Send a response.
2662 stream->SendMessageToClient(
2663 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2664 .set_version_info("1")
2665 .set_nonce("A")
2666 .AddFooResource(XdsFooResource(kXdstpResourceName, 6))
2667 .Serialize());
2668 // XdsClient should have delivered the response to the watcher.
2669 auto resource = watcher->WaitForNextResource();
2670 ASSERT_TRUE(resource.has_value());
2671 EXPECT_EQ(resource->name, kXdstpResourceName);
2672 EXPECT_EQ(resource->value, 6);
2673 // XdsClient should have sent an ACK message to the xDS server.
2674 request = WaitForRequest(stream.get());
2675 ASSERT_TRUE(request.has_value());
2676 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2677 /*version_info=*/"1", /*response_nonce=*/"A",
2678 /*error_detail=*/absl::OkStatus(),
2679 /*resource_names=*/{kXdstpResourceName});
2680 // Cancel watch.
2681 CancelFooWatch(watcher.get(), kXdstpResourceName);
2682 // The XdsClient may or may not send an unsubscription message
2683 // before it closes the transport, depending on callback timing.
2684 request = WaitForRequest(stream.get());
2685 if (request.has_value()) {
2686 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2687 /*version_info=*/"1", /*response_nonce=*/"A",
2688 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2689 }
2690 }
2691
2692 TEST_F(XdsClientTest, FederationChannelFailureReportedToWatchers) {
2693 ScopedExperimentalEnvVar env_var("GRPC_EXPERIMENTAL_XDS_FEDERATION");
2694 constexpr char kAuthority[] = "xds.example.com";
2695 const std::string kXdstpResourceName = absl::StrCat(
2696 "xdstp://", kAuthority, "/", XdsFooResource::TypeUrl(), "/foo2");
2697 FakeXdsBootstrap::FakeXdsServer authority_server;
2698 authority_server.set_server_uri("other_xds_server");
2699 FakeXdsBootstrap::FakeAuthority authority;
2700 authority.set_server(authority_server);
2701 InitXdsClient(
2702 FakeXdsBootstrap::Builder().AddAuthority(kAuthority, authority));
2703 // Start a watch for "foo1".
2704 auto watcher = StartFooWatch("foo1");
2705 // Watcher should initially not see any resource reported.
2706 EXPECT_FALSE(watcher->HasEvent());
2707 // XdsClient should have created an ADS stream to the top-level xDS server.
2708 auto stream = WaitForAdsStream(xds_client_->bootstrap().server());
2709 ASSERT_TRUE(stream != nullptr);
2710 // XdsClient should have sent a subscription request on the ADS stream.
2711 auto request = WaitForRequest(stream.get());
2712 ASSERT_TRUE(request.has_value());
2713 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2714 /*version_info=*/"", /*response_nonce=*/"",
2715 /*error_detail=*/absl::OkStatus(),
2716 /*resource_names=*/{"foo1"});
2717 CheckRequestNode(*request); // Should be present on the first request.
2718 // Send a response.
2719 stream->SendMessageToClient(
2720 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2721 .set_version_info("1")
2722 .set_nonce("A")
2723 .AddFooResource(XdsFooResource("foo1", 6))
2724 .Serialize());
2725 // XdsClient should have delivered the response to the watcher.
2726 auto resource = watcher->WaitForNextResource();
2727 ASSERT_TRUE(resource.has_value());
2728 EXPECT_EQ(resource->name, "foo1");
2729 EXPECT_EQ(resource->value, 6);
2730 // XdsClient should have sent an ACK message to the xDS server.
2731 request = WaitForRequest(stream.get());
2732 ASSERT_TRUE(request.has_value());
2733 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2734 /*version_info=*/"1", /*response_nonce=*/"A",
2735 /*error_detail=*/absl::OkStatus(),
2736 /*resource_names=*/{"foo1"});
2737 // Start a watch for the xdstp resource name.
2738 auto watcher2 = StartFooWatch(kXdstpResourceName);
2739 // Watcher should initially not see any resource reported.
2740 EXPECT_FALSE(watcher2->HasEvent());
2741 // XdsClient will create a new stream to the server for this authority.
2742 auto stream2 = WaitForAdsStream(authority_server);
2743 ASSERT_TRUE(stream2 != nullptr);
2744 // XdsClient should have sent a subscription request on the ADS stream.
2745 // Note that version and nonce here do NOT use the values for Foo,
2746 // since each authority has its own state.
2747 request = WaitForRequest(stream2.get());
2748 ASSERT_TRUE(request.has_value());
2749 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2750 /*version_info=*/"", /*response_nonce=*/"",
2751 /*error_detail=*/absl::OkStatus(),
2752 /*resource_names=*/{kXdstpResourceName});
2753 CheckRequestNode(*request); // Should be present on the first request.
2754 // Send a response.
2755 stream2->SendMessageToClient(
2756 ResponseBuilder(XdsFooResourceType::Get()->type_url())
2757 .set_version_info("2")
2758 .set_nonce("B")
2759 .AddFooResource(XdsFooResource(kXdstpResourceName, 3))
2760 .Serialize());
2761 // XdsClient should have delivered the response to the watcher.
2762 resource = watcher2->WaitForNextResource();
2763 ASSERT_TRUE(resource.has_value());
2764 EXPECT_EQ(resource->name, kXdstpResourceName);
2765 EXPECT_EQ(resource->value, 3);
2766 // XdsClient should have sent an ACK message to the xDS server.
2767 request = WaitForRequest(stream2.get());
2768 ASSERT_TRUE(request.has_value());
2769 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2770 /*version_info=*/"2", /*response_nonce=*/"B",
2771 /*error_detail=*/absl::OkStatus(),
2772 /*resource_names=*/{kXdstpResourceName});
2773 // Now cause a channel failure on the stream to the authority's xDS server.
2774 TriggerConnectionFailure(authority_server,
2775 absl::UnavailableError("connection failed"));
2776 // The watcher for the xdstp resource name should see the error.
2777 auto error = watcher2->WaitForNextError();
2778 ASSERT_TRUE(error.has_value());
2779 EXPECT_EQ(error->code(), absl::StatusCode::kUnavailable);
2780 EXPECT_EQ(error->message(),
2781 "xDS channel for server other_xds_server: connection failed "
2782 "(node ID:xds_client_test)")
2783 << *error;
2784 // The watcher for "foo1" should not see any error.
2785 EXPECT_FALSE(watcher->HasEvent());
2786 // Cancel watch for "foo1".
2787 CancelFooWatch(watcher.get(), "foo1");
2788 // The XdsClient may or may not send the unsubscription message
2789 // before it closes the transport, depending on callback timing.
2790 request = WaitForRequest(stream.get());
2791 if (request.has_value()) {
2792 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2793 /*version_info=*/"1", /*response_nonce=*/"A",
2794 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2795 }
2796 // Now cancel watch for xdstp resource name.
2797 CancelFooWatch(watcher2.get(), kXdstpResourceName);
2798 // The XdsClient may or may not send the unsubscription message
2799 // before it closes the transport, depending on callback timing.
2800 request = WaitForRequest(stream2.get());
2801 if (request.has_value()) {
2802 CheckRequest(*request, XdsFooResourceType::Get()->type_url(),
2803 /*version_info=*/"2", /*response_nonce=*/"B",
2804 /*error_detail=*/absl::OkStatus(), /*resource_names=*/{});
2805 }
2806 }
2807
2808 } // namespace
2809 } // namespace testing
2810 } // namespace grpc_core
2811
2812 int main(int argc, char** argv) {
2813 ::testing::InitGoogleTest(&argc, argv);
2814 grpc::testing::TestEnvironment env(&argc, argv);
2815 grpc_init();
2816 int ret = RUN_ALL_TESTS();
2817 grpc_shutdown();
2818 return ret;
2819 }