aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/grpc/src/core/ext/xds/xds_client.cc
blob: 93dfec69b8f68cf3df09b612cb347cae4dcc638b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
//
// Copyright 2018 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#include <grpc/support/port_platform.h>

#include "src/core/ext/xds/xds_client.h"

#include <inttypes.h>
#include <string.h>

#include <algorithm>
#include <type_traits>

#include "y_absl/strings/match.h"
#include "y_absl/strings/str_cat.h"
#include "y_absl/strings/str_join.h"
#include "y_absl/strings/str_split.h"
#include "y_absl/strings/string_view.h"
#include "y_absl/strings/strip.h"
#include "y_absl/types/optional.h"
#include "upb/arena.h"

#include <grpc/event_engine/event_engine.h>
#include <grpc/support/log.h>

#include "src/core/ext/xds/xds_api.h"
#include "src/core/ext/xds/xds_bootstrap.h"
#include "src/core/ext/xds/xds_client_stats.h"
#include "src/core/lib/backoff/backoff.h"
#include "src/core/lib/gprpp/debug_location.h"
#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/uri/uri_parser.h"

#define GRPC_XDS_INITIAL_CONNECT_BACKOFF_SECONDS 1
#define GRPC_XDS_RECONNECT_BACKOFF_MULTIPLIER 1.6
#define GRPC_XDS_RECONNECT_MAX_BACKOFF_SECONDS 120
#define GRPC_XDS_RECONNECT_JITTER 0.2
#define GRPC_XDS_MIN_CLIENT_LOAD_REPORTING_INTERVAL_MS 1000

namespace grpc_core {

using ::grpc_event_engine::experimental::EventEngine;

TraceFlag grpc_xds_client_trace(false, "xds_client");
TraceFlag grpc_xds_client_refcount_trace(false, "xds_client_refcount");

//
// Internal class declarations
//

// An xds call wrapper that can restart a call upon failure. Holds a ref to
// the xds channel. The template parameter is the kind of wrapped xds call.
template <typename T>
class XdsClient::ChannelState::RetryableCall
    : public InternallyRefCounted<RetryableCall<T>> {
 public:
  explicit RetryableCall(WeakRefCountedPtr<ChannelState> chand);

  // Disable thread-safety analysis because this method is called via
  // OrphanablePtr<>, but there's no way to pass the lock annotation
  // through there.
  void Orphan() override Y_ABSL_NO_THREAD_SAFETY_ANALYSIS;

  void OnCallFinishedLocked() Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);

  T* calld() const { return calld_.get(); }
  ChannelState* chand() const { return chand_.get(); }

  bool IsCurrentCallOnChannel() const;

 private:
  void StartNewCallLocked();
  void StartRetryTimerLocked() Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);

  void OnRetryTimer();

  // The wrapped xds call that talks to the xds server. It's instantiated
  // every time we start a new call. It's null during call retry backoff.
  OrphanablePtr<T> calld_;
  // The owning xds channel.
  WeakRefCountedPtr<ChannelState> chand_;

  // Retry state.
  BackOff backoff_;
  y_absl::optional<EventEngine::TaskHandle> timer_handle_
      Y_ABSL_GUARDED_BY(&XdsClient::mu_);

  bool shutting_down_ = false;
};

// Contains an ADS call to the xds server.
class XdsClient::ChannelState::AdsCallState
    : public InternallyRefCounted<AdsCallState> {
 public:
  // The ctor and dtor should not be used directly.
  explicit AdsCallState(RefCountedPtr<RetryableCall<AdsCallState>> parent);

  void Orphan() override;

  RetryableCall<AdsCallState>* parent() const { return parent_.get(); }
  ChannelState* chand() const { return parent_->chand(); }
  XdsClient* xds_client() const { return chand()->xds_client(); }
  bool seen_response() const { return seen_response_; }

  void SubscribeLocked(const XdsResourceType* type, const XdsResourceName& name,
                       bool delay_send)
      Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);
  void UnsubscribeLocked(const XdsResourceType* type,
                         const XdsResourceName& name, bool delay_unsubscription)
      Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);

  bool HasSubscribedResources() const;

 private:
  class AdsResponseParser : public XdsApi::AdsResponseParserInterface {
   public:
    struct Result {
      const XdsResourceType* type;
      TString type_url;
      TString version;
      TString nonce;
      std::vector<TString> errors;
      std::map<TString /*authority*/, std::set<XdsResourceKey>>
          resources_seen;
      bool have_valid_resources = false;
    };

    explicit AdsResponseParser(AdsCallState* ads_call_state)
        : ads_call_state_(ads_call_state) {}

    y_absl::Status ProcessAdsResponseFields(AdsResponseFields fields) override
        Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);

    void ParseResource(upb_Arena* arena, size_t idx, y_absl::string_view type_url,
                       y_absl::string_view resource_name,
                       y_absl::string_view serialized_resource) override
        Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);

    void ResourceWrapperParsingFailed(size_t idx) override;

    Result TakeResult() { return std::move(result_); }

   private:
    XdsClient* xds_client() const { return ads_call_state_->xds_client(); }

    AdsCallState* ads_call_state_;
    const Timestamp update_time_ = Timestamp::Now();
    Result result_;
  };

  class ResourceTimer : public InternallyRefCounted<ResourceTimer> {
   public:
    ResourceTimer(const XdsResourceType* type, const XdsResourceName& name)
        : type_(type), name_(name) {}

    // Disable thread-safety analysis because this method is called via
    // OrphanablePtr<>, but there's no way to pass the lock annotation
    // through there.
    void Orphan() override Y_ABSL_NO_THREAD_SAFETY_ANALYSIS {
      MaybeCancelTimer();
      Unref(DEBUG_LOCATION, "Orphan");
    }

    void MarkSubscriptionSendStarted()
        Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) {
      subscription_sent_ = true;
    }

    void MaybeMarkSubscriptionSendComplete(
        RefCountedPtr<AdsCallState> ads_calld)
        Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) {
      if (subscription_sent_) MaybeStartTimer(std::move(ads_calld));
    }

    void MarkSeen() Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) {
      resource_seen_ = true;
      MaybeCancelTimer();
    }

    void MaybeCancelTimer() Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) {
      if (timer_handle_.has_value() &&
          ads_calld_->xds_client()->engine()->Cancel(*timer_handle_)) {
        timer_handle_.reset();
      }
    }

   private:
    void MaybeStartTimer(RefCountedPtr<AdsCallState> ads_calld)
        Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) {
      // Don't start timer if we've already either seen the resource or
      // marked it as non-existing.
      // Note: There are edge cases where we can have seen the resource
      // before we have sent the initial subscription request, such as
      // when we unsubscribe and then resubscribe to a given resource
      // and then get a response containing that resource, all while a
      // send_message op is in flight.
      if (resource_seen_) return;
      // Don't start timer if we haven't yet sent the initial subscription
      // request for the resource.
      if (!subscription_sent_) return;
      // Don't start timer if it's already running.
      if (timer_handle_.has_value()) return;
      // Check if we already have a cached version of this resource
      // (i.e., if this is the initial request for the resource after an
      // ADS stream restart).  If so, we don't start the timer, because
      // (a) we already have the resource and (b) the server may
      // optimize by not resending the resource that we already have.
      auto& authority_state =
          ads_calld->xds_client()->authority_state_map_[name_.authority];
      ResourceState& state = authority_state.resource_map[type_][name_.key];
      if (state.resource != nullptr) return;
      // Start timer.
      ads_calld_ = std::move(ads_calld);
      timer_handle_ = ads_calld_->xds_client()->engine()->RunAfter(
          ads_calld_->xds_client()->request_timeout_,
          [self = Ref(DEBUG_LOCATION, "timer")]() {
            ApplicationCallbackExecCtx callback_exec_ctx;
            ExecCtx exec_ctx;
            self->OnTimer();
          });
    }

    void OnTimer() {
      if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
        gpr_log(GPR_INFO,
                "[xds_client %p] xds server %s: timeout obtaining resource "
                "{type=%s name=%s} from xds server",
                ads_calld_->xds_client(),
                ads_calld_->chand()->server_.server_uri().c_str(),
                TString(type_->type_url()).c_str(),
                XdsClient::ConstructFullXdsResourceName(
                    name_.authority, type_->type_url(), name_.key)
                    .c_str());
      }
      {
        MutexLock lock(&ads_calld_->xds_client()->mu_);
        timer_handle_.reset();
        resource_seen_ = true;
        auto& authority_state =
            ads_calld_->xds_client()->authority_state_map_[name_.authority];
        ResourceState& state = authority_state.resource_map[type_][name_.key];
        state.meta.client_status = XdsApi::ResourceMetadata::DOES_NOT_EXIST;
        ads_calld_->xds_client()->NotifyWatchersOnResourceDoesNotExist(
            state.watchers);
      }
      ads_calld_->xds_client()->work_serializer_.DrainQueue();
      ads_calld_.reset();
    }

    const XdsResourceType* type_;
    const XdsResourceName name_;

    RefCountedPtr<AdsCallState> ads_calld_;
    // True if we have sent the initial subscription request for this
    // resource on this ADS stream.
    bool subscription_sent_ Y_ABSL_GUARDED_BY(&XdsClient::mu_) = false;
    // True if we have either (a) seen the resource in a response on this
    // stream or (b) declared the resource to not exist due to the timer
    // firing.
    bool resource_seen_ Y_ABSL_GUARDED_BY(&XdsClient::mu_) = false;
    y_absl::optional<EventEngine::TaskHandle> timer_handle_
        Y_ABSL_GUARDED_BY(&XdsClient::mu_);
  };

  class StreamEventHandler
      : public XdsTransportFactory::XdsTransport::StreamingCall::EventHandler {
   public:
    explicit StreamEventHandler(RefCountedPtr<AdsCallState> ads_calld)
        : ads_calld_(std::move(ads_calld)) {}

    void OnRequestSent(bool ok) override { ads_calld_->OnRequestSent(ok); }
    void OnRecvMessage(y_absl::string_view payload) override {
      ads_calld_->OnRecvMessage(payload);
    }
    void OnStatusReceived(y_absl::Status status) override {
      ads_calld_->OnStatusReceived(std::move(status));
    }

   private:
    RefCountedPtr<AdsCallState> ads_calld_;
  };

  struct ResourceTypeState {
    // Nonce and status for this resource type.
    TString nonce;
    y_absl::Status status;

    // Subscribed resources of this type.
    std::map<TString /*authority*/,
             std::map<XdsResourceKey, OrphanablePtr<ResourceTimer>>>
        subscribed_resources;
  };

  void SendMessageLocked(const XdsResourceType* type)
      Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);

  void OnRequestSent(bool ok);
  void OnRecvMessage(y_absl::string_view payload);
  void OnStatusReceived(y_absl::Status status);

  bool IsCurrentCallOnChannel() const;

  // Constructs a list of resource names of a given type for an ADS
  // request.  Also starts the timer for each resource if needed.
  std::vector<TString> ResourceNamesForRequest(const XdsResourceType* type)
      Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);

  // The owning RetryableCall<>.
  RefCountedPtr<RetryableCall<AdsCallState>> parent_;

  OrphanablePtr<XdsTransportFactory::XdsTransport::StreamingCall> call_;

  bool sent_initial_message_ = false;
  bool seen_response_ = false;

  const XdsResourceType* send_message_pending_
      Y_ABSL_GUARDED_BY(&XdsClient::mu_) = nullptr;

  // Resource types for which requests need to be sent.
  std::set<const XdsResourceType*> buffered_requests_;

  // State for each resource type.
  std::map<const XdsResourceType*, ResourceTypeState> state_map_;
};

// Contains an LRS call to the xds server.
class XdsClient::ChannelState::LrsCallState
    : public InternallyRefCounted<LrsCallState> {
 public:
  // The ctor and dtor should not be used directly.
  explicit LrsCallState(RefCountedPtr<RetryableCall<LrsCallState>> parent);

  void Orphan() override;

  void MaybeStartReportingLocked()
      Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);

  RetryableCall<LrsCallState>* parent() { return parent_.get(); }
  ChannelState* chand() const { return parent_->chand(); }
  XdsClient* xds_client() const { return chand()->xds_client(); }
  bool seen_response() const { return seen_response_; }

 private:
  class StreamEventHandler
      : public XdsTransportFactory::XdsTransport::StreamingCall::EventHandler {
   public:
    explicit StreamEventHandler(RefCountedPtr<LrsCallState> lrs_calld)
        : lrs_calld_(std::move(lrs_calld)) {}

    void OnRequestSent(bool ok) override { lrs_calld_->OnRequestSent(ok); }
    void OnRecvMessage(y_absl::string_view payload) override {
      lrs_calld_->OnRecvMessage(payload);
    }
    void OnStatusReceived(y_absl::Status status) override {
      lrs_calld_->OnStatusReceived(std::move(status));
    }

   private:
    RefCountedPtr<LrsCallState> lrs_calld_;
  };

  // Reports client-side load stats according to a fixed interval.
  class Reporter : public InternallyRefCounted<Reporter> {
   public:
    Reporter(RefCountedPtr<LrsCallState> parent, Duration report_interval)
        : parent_(std::move(parent)), report_interval_(report_interval) {
      ScheduleNextReportLocked();
    }

    // Disable thread-safety analysis because this method is called via
    // OrphanablePtr<>, but there's no way to pass the lock annotation
    // through there.
    void Orphan() override Y_ABSL_NO_THREAD_SAFETY_ANALYSIS;

    void OnReportDoneLocked() Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);

   private:
    void ScheduleNextReportLocked()
        Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);
    bool OnNextReportTimer();
    bool SendReportLocked() Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_);

    bool IsCurrentReporterOnCall() const {
      return this == parent_->reporter_.get();
    }
    XdsClient* xds_client() const { return parent_->xds_client(); }

    // The owning LRS call.
    RefCountedPtr<LrsCallState> parent_;

    // The load reporting state.
    const Duration report_interval_;
    bool last_report_counters_were_zero_ = false;
    y_absl::optional<EventEngine::TaskHandle> timer_handle_
        Y_ABSL_GUARDED_BY(&XdsClient::mu_);
  };

  void OnRequestSent(bool ok);
  void OnRecvMessage(y_absl::string_view payload);
  void OnStatusReceived(y_absl::Status status);

  bool IsCurrentCallOnChannel() const;

  // The owning RetryableCall<>.
  RefCountedPtr<RetryableCall<LrsCallState>> parent_;

  OrphanablePtr<XdsTransportFactory::XdsTransport::StreamingCall> call_;

  bool seen_response_ = false;
  bool send_message_pending_ Y_ABSL_GUARDED_BY(&XdsClient::mu_) = false;

  // Load reporting state.
  bool send_all_clusters_ = false;
  std::set<TString> cluster_names_;  // Asked for by the LRS server.
  Duration load_reporting_interval_;
  OrphanablePtr<Reporter> reporter_;
};

//
// XdsClient::ChannelState
//

XdsClient::ChannelState::ChannelState(WeakRefCountedPtr<XdsClient> xds_client,
                                      const XdsBootstrap::XdsServer& server)
    : DualRefCounted<ChannelState>(
          GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_refcount_trace)
              ? "ChannelState"
              : nullptr),
      xds_client_(std::move(xds_client)),
      server_(server) {
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO, "[xds_client %p] creating channel to %s",
            xds_client_.get(), server.server_uri().c_str());
  }
  y_absl::Status status;
  transport_ = xds_client_->transport_factory_->Create(
      server,
      [self = WeakRef(DEBUG_LOCATION, "OnConnectivityFailure")](
          y_absl::Status status) {
        self->OnConnectivityFailure(std::move(status));
      },
      &status);
  GPR_ASSERT(transport_ != nullptr);
  if (!status.ok()) SetChannelStatusLocked(std::move(status));
}

XdsClient::ChannelState::~ChannelState() {
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO, "[xds_client %p] destroying xds channel %p for server %s",
            xds_client(), this, server_.server_uri().c_str());
  }
  xds_client_.reset(DEBUG_LOCATION, "ChannelState");
}

// This method should only ever be called when holding the lock, but we can't
// use a Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED annotation, because Orphan() will be
// called from DualRefCounted::Unref, which cannot have a lock annotation for
// a lock in this subclass.
void XdsClient::ChannelState::Orphan() Y_ABSL_NO_THREAD_SAFETY_ANALYSIS {
  shutting_down_ = true;
  transport_.reset();
  // At this time, all strong refs are removed, remove from channel map to
  // prevent subsequent subscription from trying to use this ChannelState as
  // it is shutting down.
  xds_client_->xds_server_channel_map_.erase(&server_);
  ads_calld_.reset();
  lrs_calld_.reset();
}

void XdsClient::ChannelState::ResetBackoff() { transport_->ResetBackoff(); }

XdsClient::ChannelState::AdsCallState* XdsClient::ChannelState::ads_calld()
    const {
  return ads_calld_->calld();
}

XdsClient::ChannelState::LrsCallState* XdsClient::ChannelState::lrs_calld()
    const {
  return lrs_calld_->calld();
}

void XdsClient::ChannelState::MaybeStartLrsCall() {
  if (lrs_calld_ != nullptr) return;
  lrs_calld_.reset(new RetryableCall<LrsCallState>(
      WeakRef(DEBUG_LOCATION, "ChannelState+lrs")));
}

void XdsClient::ChannelState::StopLrsCallLocked() {
  xds_client_->xds_load_report_server_map_.erase(&server_);
  lrs_calld_.reset();
}

void XdsClient::ChannelState::SubscribeLocked(const XdsResourceType* type,
                                              const XdsResourceName& name) {
  if (ads_calld_ == nullptr) {
    // Start the ADS call if this is the first request.
    ads_calld_.reset(new RetryableCall<AdsCallState>(
        WeakRef(DEBUG_LOCATION, "ChannelState+ads")));
    // Note: AdsCallState's ctor will automatically subscribe to all
    // resources that the XdsClient already has watchers for, so we can
    // return here.
    return;
  }
  // If the ADS call is in backoff state, we don't need to do anything now
  // because when the call is restarted it will resend all necessary requests.
  if (ads_calld() == nullptr) return;
  // Subscribe to this resource if the ADS call is active.
  ads_calld()->SubscribeLocked(type, name, /*delay_send=*/false);
}

void XdsClient::ChannelState::UnsubscribeLocked(const XdsResourceType* type,
                                                const XdsResourceName& name,
                                                bool delay_unsubscription) {
  if (ads_calld_ != nullptr) {
    auto* calld = ads_calld_->calld();
    if (calld != nullptr) {
      calld->UnsubscribeLocked(type, name, delay_unsubscription);
      if (!calld->HasSubscribedResources()) {
        ads_calld_.reset();
      }
    }
  }
}

void XdsClient::ChannelState::OnConnectivityFailure(y_absl::Status status) {
  {
    MutexLock lock(&xds_client_->mu_);
    SetChannelStatusLocked(std::move(status));
  }
  xds_client_->work_serializer_.DrainQueue();
}

void XdsClient::ChannelState::SetChannelStatusLocked(y_absl::Status status) {
  if (shutting_down_) return;
  status = y_absl::Status(status.code(), y_absl::StrCat("xDS channel for server ",
                                                    server_.server_uri(), ": ",
                                                    status.message()));
  gpr_log(GPR_INFO, "[xds_client %p] %s", xds_client(),
          status.ToString().c_str());
  // If the node ID is set, append that to the status message that we send to
  // the watchers, so that it will appear in log messages visible to users.
  const auto* node = xds_client_->bootstrap_->node();
  if (node != nullptr) {
    status = y_absl::Status(
        status.code(),
        y_absl::StrCat(status.message(),
                     " (node ID:", xds_client_->bootstrap_->node()->id(), ")"));
  }
  // Save status in channel, so that we can immediately generate an
  // error for any new watchers that may be started.
  status_ = status;
  // Find all watchers for this channel.
  std::set<RefCountedPtr<ResourceWatcherInterface>> watchers;
  for (const auto& a : xds_client_->authority_state_map_) {  // authority
    if (a.second.channel_state != this) continue;
    for (const auto& t : a.second.resource_map) {  // type
      for (const auto& r : t.second) {             // resource id
        for (const auto& w : r.second.watchers) {  // watchers
          watchers.insert(w.second);
        }
      }
    }
  }
  // Enqueue notification for the watchers.
  xds_client_->work_serializer_.Schedule(
      [watchers = std::move(watchers), status = std::move(status)]()
          Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(xds_client_->work_serializer_) {
            for (const auto& watcher : watchers) {
              watcher->OnError(status);
            }
          },
      DEBUG_LOCATION);
}

//
// XdsClient::ChannelState::RetryableCall<>
//

template <typename T>
XdsClient::ChannelState::RetryableCall<T>::RetryableCall(
    WeakRefCountedPtr<ChannelState> chand)
    : chand_(std::move(chand)),
      backoff_(BackOff::Options()
                   .set_initial_backoff(Duration::Seconds(
                       GRPC_XDS_INITIAL_CONNECT_BACKOFF_SECONDS))
                   .set_multiplier(GRPC_XDS_RECONNECT_BACKOFF_MULTIPLIER)
                   .set_jitter(GRPC_XDS_RECONNECT_JITTER)
                   .set_max_backoff(Duration::Seconds(
                       GRPC_XDS_RECONNECT_MAX_BACKOFF_SECONDS))) {
  StartNewCallLocked();
}

template <typename T>
void XdsClient::ChannelState::RetryableCall<T>::Orphan() {
  shutting_down_ = true;
  calld_.reset();
  if (timer_handle_.has_value()) {
    chand()->xds_client()->engine()->Cancel(*timer_handle_);
    timer_handle_.reset();
  }
  this->Unref(DEBUG_LOCATION, "RetryableCall+orphaned");
}

template <typename T>
void XdsClient::ChannelState::RetryableCall<T>::OnCallFinishedLocked() {
  // If we saw a response on the current stream, reset backoff.
  if (calld_->seen_response()) backoff_.Reset();
  calld_.reset();
  // Start retry timer.
  StartRetryTimerLocked();
}

template <typename T>
void XdsClient::ChannelState::RetryableCall<T>::StartNewCallLocked() {
  if (shutting_down_) return;
  GPR_ASSERT(chand_->transport_ != nullptr);
  GPR_ASSERT(calld_ == nullptr);
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO,
            "[xds_client %p] xds server %s: start new call from retryable "
            "call %p",
            chand()->xds_client(), chand()->server_.server_uri().c_str(), this);
  }
  calld_ = MakeOrphanable<T>(
      this->Ref(DEBUG_LOCATION, "RetryableCall+start_new_call"));
}

template <typename T>
void XdsClient::ChannelState::RetryableCall<T>::StartRetryTimerLocked() {
  if (shutting_down_) return;
  const Timestamp next_attempt_time = backoff_.NextAttemptTime();
  const Duration timeout =
      std::max(next_attempt_time - Timestamp::Now(), Duration::Zero());
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO,
            "[xds_client %p] xds server %s: call attempt failed; "
            "retry timer will fire in %" PRId64 "ms.",
            chand()->xds_client(), chand()->server_.server_uri().c_str(),
            timeout.millis());
  }
  timer_handle_ = chand()->xds_client()->engine()->RunAfter(
      timeout,
      [self = this->Ref(DEBUG_LOCATION, "RetryableCall+retry_timer_start")]() {
        ApplicationCallbackExecCtx callback_exec_ctx;
        ExecCtx exec_ctx;
        self->OnRetryTimer();
      });
}

template <typename T>
void XdsClient::ChannelState::RetryableCall<T>::OnRetryTimer() {
  MutexLock lock(&chand_->xds_client()->mu_);
  if (timer_handle_.has_value()) {
    timer_handle_.reset();
    if (shutting_down_) return;
    if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
      gpr_log(GPR_INFO,
              "[xds_client %p] xds server %s: retry timer fired (retryable "
              "call: %p)",
              chand()->xds_client(), chand()->server_.server_uri().c_str(),
              this);
    }
    StartNewCallLocked();
  }
}

//
// XdsClient::ChannelState::AdsCallState::AdsResponseParser
//

y_absl::Status XdsClient::ChannelState::AdsCallState::AdsResponseParser::
    ProcessAdsResponseFields(AdsResponseFields fields) {
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(
        GPR_INFO,
        "[xds_client %p] xds server %s: received ADS response: type_url=%s, "
        "version=%s, nonce=%s, num_resources=%" PRIuPTR,
        ads_call_state_->xds_client(),
        ads_call_state_->chand()->server_.server_uri().c_str(),
        fields.type_url.c_str(), fields.version.c_str(), fields.nonce.c_str(),
        fields.num_resources);
  }
  result_.type =
      ads_call_state_->xds_client()->GetResourceTypeLocked(fields.type_url);
  if (result_.type == nullptr) {
    return y_absl::InvalidArgumentError(
        y_absl::StrCat("unknown resource type ", fields.type_url));
  }
  result_.type_url = std::move(fields.type_url);
  result_.version = std::move(fields.version);
  result_.nonce = std::move(fields.nonce);
  return y_absl::OkStatus();
}

namespace {

// Build a resource metadata struct for ADS result accepting methods and CSDS.
XdsApi::ResourceMetadata CreateResourceMetadataAcked(
    TString serialized_proto, TString version, Timestamp update_time) {
  XdsApi::ResourceMetadata resource_metadata;
  resource_metadata.serialized_proto = std::move(serialized_proto);
  resource_metadata.update_time = update_time;
  resource_metadata.version = std::move(version);
  resource_metadata.client_status = XdsApi::ResourceMetadata::ACKED;
  return resource_metadata;
}

// Update resource_metadata for NACK.
void UpdateResourceMetadataNacked(const TString& version,
                                  const TString& details,
                                  Timestamp update_time,
                                  XdsApi::ResourceMetadata* resource_metadata) {
  resource_metadata->client_status = XdsApi::ResourceMetadata::NACKED;
  resource_metadata->failed_version = version;
  resource_metadata->failed_details = details;
  resource_metadata->failed_update_time = update_time;
}

}  // namespace

void XdsClient::ChannelState::AdsCallState::AdsResponseParser::ParseResource(
    upb_Arena* arena, size_t idx, y_absl::string_view type_url,
    y_absl::string_view resource_name, y_absl::string_view serialized_resource) {
  TString error_prefix = y_absl::StrCat(
      "resource index ", idx, ": ",
      resource_name.empty() ? "" : y_absl::StrCat(resource_name, ": "));
  // Check the type_url of the resource.
  if (result_.type_url != type_url) {
    result_.errors.emplace_back(
        y_absl::StrCat(error_prefix, "incorrect resource type \"", type_url,
                     "\" (should be \"", result_.type_url, "\")"));
    return;
  }
  // Parse the resource.
  XdsResourceType::DecodeContext context = {
      xds_client(), ads_call_state_->chand()->server_, &grpc_xds_client_trace,
      xds_client()->symtab_.ptr(), arena};
  XdsResourceType::DecodeResult decode_result =
      result_.type->Decode(context, serialized_resource);
  // If we didn't already have the resource name from the Resource
  // wrapper, try to get it from the decoding result.
  if (resource_name.empty()) {
    if (decode_result.name.has_value()) {
      resource_name = *decode_result.name;
      error_prefix =
          y_absl::StrCat("resource index ", idx, ": ", resource_name, ": ");
    } else {
      // We don't have any way of determining the resource name, so
      // there's nothing more we can do here.
      result_.errors.emplace_back(y_absl::StrCat(
          error_prefix, decode_result.resource.status().ToString()));
      return;
    }
  }
  // If decoding failed, make sure we include the error in the NACK.
  const y_absl::Status& decode_status = decode_result.resource.status();
  if (!decode_status.ok()) {
    result_.errors.emplace_back(
        y_absl::StrCat(error_prefix, decode_status.ToString()));
  }
  // Check the resource name.
  auto parsed_resource_name =
      xds_client()->ParseXdsResourceName(resource_name, result_.type);
  if (!parsed_resource_name.ok()) {
    result_.errors.emplace_back(
        y_absl::StrCat(error_prefix, "Cannot parse xDS resource name"));
    return;
  }
  // Cancel resource-does-not-exist timer, if needed.
  auto timer_it = ads_call_state_->state_map_.find(result_.type);
  if (timer_it != ads_call_state_->state_map_.end()) {
    auto it = timer_it->second.subscribed_resources.find(
        parsed_resource_name->authority);
    if (it != timer_it->second.subscribed_resources.end()) {
      auto res_it = it->second.find(parsed_resource_name->key);
      if (res_it != it->second.end()) {
        res_it->second->MarkSeen();
      }
    }
  }
  // Lookup the authority in the cache.
  auto authority_it =
      xds_client()->authority_state_map_.find(parsed_resource_name->authority);
  if (authority_it == xds_client()->authority_state_map_.end()) {
    return;  // Skip resource -- we don't have a subscription for it.
  }
  // Found authority, so look up type.
  AuthorityState& authority_state = authority_it->second;
  auto type_it = authority_state.resource_map.find(result_.type);
  if (type_it == authority_state.resource_map.end()) {
    return;  // Skip resource -- we don't have a subscription for it.
  }
  auto& type_map = type_it->second;
  // Found type, so look up resource key.
  auto it = type_map.find(parsed_resource_name->key);
  if (it == type_map.end()) {
    return;  // Skip resource -- we don't have a subscription for it.
  }
  ResourceState& resource_state = it->second;
  // If needed, record that we've seen this resource.
  if (result_.type->AllResourcesRequiredInSotW()) {
    result_.resources_seen[parsed_resource_name->authority].insert(
        parsed_resource_name->key);
  }
  // If we previously ignored the resource's deletion, log that we're
  // now re-adding it.
  if (resource_state.ignored_deletion) {
    gpr_log(GPR_INFO,
            "[xds_client %p] xds server %s: server returned new version of "
            "resource for which we previously ignored a deletion: type %s "
            "name %s",
            xds_client(),
            ads_call_state_->chand()->server_.server_uri().c_str(),
            TString(type_url).c_str(), TString(resource_name).c_str());
    resource_state.ignored_deletion = false;
  }
  // Update resource state based on whether the resource is valid.
  if (!decode_status.ok()) {
    xds_client()->NotifyWatchersOnErrorLocked(
        resource_state.watchers,
        y_absl::UnavailableError(
            y_absl::StrCat("invalid resource: ", decode_status.ToString())));
    UpdateResourceMetadataNacked(result_.version, decode_status.ToString(),
                                 update_time_, &resource_state.meta);
    return;
  }
  // Resource is valid.
  result_.have_valid_resources = true;
  // If it didn't change, ignore it.
  if (resource_state.resource != nullptr &&
      result_.type->ResourcesEqual(resource_state.resource.get(),
                                   decode_result.resource->get())) {
    if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
      gpr_log(GPR_INFO,
              "[xds_client %p] %s resource %s identical to current, ignoring.",
              xds_client(), result_.type_url.c_str(),
              TString(resource_name).c_str());
    }
    return;
  }
  // Update the resource state.
  resource_state.resource = std::move(*decode_result.resource);
  resource_state.meta = CreateResourceMetadataAcked(
      TString(serialized_resource), result_.version, update_time_);
  // Notify watchers.
  auto& watchers_list = resource_state.watchers;
  auto* value =
      result_.type->CopyResource(resource_state.resource.get()).release();
  xds_client()->work_serializer_.Schedule(
      [watchers_list, value]()
          Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&xds_client()->work_serializer_) {
            for (const auto& p : watchers_list) {
              p.first->OnGenericResourceChanged(value);
            }
            delete value;
          },
      DEBUG_LOCATION);
}

void XdsClient::ChannelState::AdsCallState::AdsResponseParser::
    ResourceWrapperParsingFailed(size_t idx) {
  result_.errors.emplace_back(y_absl::StrCat(
      "resource index ", idx, ": Can't decode Resource proto wrapper"));
}

//
// XdsClient::ChannelState::AdsCallState
//

XdsClient::ChannelState::AdsCallState::AdsCallState(
    RefCountedPtr<RetryableCall<AdsCallState>> parent)
    : InternallyRefCounted<AdsCallState>(
          GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_refcount_trace)
              ? "AdsCallState"
              : nullptr),
      parent_(std::move(parent)) {
  GPR_ASSERT(xds_client() != nullptr);
  // Init the ADS call.
  const char* method =
      "/envoy.service.discovery.v3.AggregatedDiscoveryService/"
      "StreamAggregatedResources";
  call_ = chand()->transport_->CreateStreamingCall(
      method, std::make_unique<StreamEventHandler>(
                  // Passing the initial ref here.  This ref will go away when
                  // the StreamEventHandler is destroyed.
                  RefCountedPtr<AdsCallState>(this)));
  GPR_ASSERT(call_ != nullptr);
  // Start the call.
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO,
            "[xds_client %p] xds server %s: starting ADS call "
            "(calld: %p, call: %p)",
            xds_client(), chand()->server_.server_uri().c_str(), this,
            call_.get());
  }
  // If this is a reconnect, add any necessary subscriptions from what's
  // already in the cache.
  for (const auto& a : xds_client()->authority_state_map_) {
    const TString& authority = a.first;
    // Skip authorities that are not using this xDS channel.
    if (a.second.channel_state != chand()) continue;
    for (const auto& t : a.second.resource_map) {
      const XdsResourceType* type = t.first;
      for (const auto& r : t.second) {
        const XdsResourceKey& resource_key = r.first;
        SubscribeLocked(type, {authority, resource_key}, /*delay_send=*/true);
      }
    }
  }
  // Send initial message if we added any subscriptions above.
  for (const auto& p : state_map_) {
    SendMessageLocked(p.first);
  }
}

void XdsClient::ChannelState::AdsCallState::Orphan() {
  state_map_.clear();
  // Note that the initial ref is held by the StreamEventHandler, which
  // will be destroyed when call_ is destroyed, which may not happen
  // here, since there may be other refs held to call_ by internal callbacks.
  call_.reset();
}

void XdsClient::ChannelState::AdsCallState::SendMessageLocked(
    const XdsResourceType* type)
    Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&XdsClient::mu_) {
  // Buffer message sending if an existing message is in flight.
  if (send_message_pending_ != nullptr) {
    buffered_requests_.insert(type);
    return;
  }
  auto& state = state_map_[type];
  TString serialized_message = xds_client()->api_.CreateAdsRequest(
      type->type_url(), chand()->resource_type_version_map_[type], state.nonce,
      ResourceNamesForRequest(type), state.status, !sent_initial_message_);
  sent_initial_message_ = true;
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO,
            "[xds_client %p] xds server %s: sending ADS request: type=%s "
            "version=%s nonce=%s error=%s",
            xds_client(), chand()->server_.server_uri().c_str(),
            TString(type->type_url()).c_str(),
            chand()->resource_type_version_map_[type].c_str(),
            state.nonce.c_str(), state.status.ToString().c_str());
  }
  state.status = y_absl::OkStatus();
  call_->SendMessage(std::move(serialized_message));
  send_message_pending_ = type;
}

void XdsClient::ChannelState::AdsCallState::SubscribeLocked(
    const XdsResourceType* type, const XdsResourceName& name, bool delay_send) {
  auto& state = state_map_[type].subscribed_resources[name.authority][name.key];
  if (state == nullptr) {
    state = MakeOrphanable<ResourceTimer>(type, name);
    if (!delay_send) SendMessageLocked(type);
  }
}

void XdsClient::ChannelState::AdsCallState::UnsubscribeLocked(
    const XdsResourceType* type, const XdsResourceName& name,
    bool delay_unsubscription) {
  auto& type_state_map = state_map_[type];
  auto& authority_map = type_state_map.subscribed_resources[name.authority];
  authority_map.erase(name.key);
  if (authority_map.empty()) {
    type_state_map.subscribed_resources.erase(name.authority);
  }
  // Don't need to send unsubscription message if this was the last
  // resource we were subscribed to, since we'll be closing the stream
  // immediately in that case.
  if (!delay_unsubscription && HasSubscribedResources()) {
    SendMessageLocked(type);
  }
}

bool XdsClient::ChannelState::AdsCallState::HasSubscribedResources() const {
  for (const auto& p : state_map_) {
    if (!p.second.subscribed_resources.empty()) return true;
  }
  return false;
}

void XdsClient::ChannelState::AdsCallState::OnRequestSent(bool ok) {
  MutexLock lock(&xds_client()->mu_);
  // For each resource that was in the message we just sent, start the
  // resource timer if needed.
  if (ok) {
    auto& resource_type_state = state_map_[send_message_pending_];
    for (const auto& p : resource_type_state.subscribed_resources) {
      for (auto& q : p.second) {
        q.second->MaybeMarkSubscriptionSendComplete(
            Ref(DEBUG_LOCATION, "ResourceTimer"));
      }
    }
  }
  send_message_pending_ = nullptr;
  if (ok && IsCurrentCallOnChannel()) {
    // Continue to send another pending message if any.
    // TODO(roth): The current code to handle buffered messages has the
    // advantage of sending only the most recent list of resource names for
    // each resource type (no matter how many times that resource type has
    // been requested to send while the current message sending is still
    // pending). But its disadvantage is that we send the requests in fixed
    // order of resource types. We need to fix this if we are seeing some
    // resource type(s) starved due to frequent requests of other resource
    // type(s).
    auto it = buffered_requests_.begin();
    if (it != buffered_requests_.end()) {
      SendMessageLocked(*it);
      buffered_requests_.erase(it);
    }
  }
}

void XdsClient::ChannelState::AdsCallState::OnRecvMessage(
    y_absl::string_view payload) {
  {
    MutexLock lock(&xds_client()->mu_);
    if (!IsCurrentCallOnChannel()) return;
    // Parse and validate the response.
    AdsResponseParser parser(this);
    y_absl::Status status = xds_client()->api_.ParseAdsResponse(payload, &parser);
    if (!status.ok()) {
      // Ignore unparsable response.
      gpr_log(GPR_ERROR,
              "[xds_client %p] xds server %s: error parsing ADS response (%s) "
              "-- ignoring",
              xds_client(), chand()->server_.server_uri().c_str(),
              status.ToString().c_str());
    } else {
      seen_response_ = true;
      chand()->status_ = y_absl::OkStatus();
      AdsResponseParser::Result result = parser.TakeResult();
      // Update nonce.
      auto& state = state_map_[result.type];
      state.nonce = result.nonce;
      // If we got an error, set state.status so that we'll NACK the update.
      if (!result.errors.empty()) {
        state.status = y_absl::UnavailableError(
            y_absl::StrCat("xDS response validation errors: [",
                         y_absl::StrJoin(result.errors, "; "), "]"));
        gpr_log(GPR_ERROR,
                "[xds_client %p] xds server %s: ADS response invalid for "
                "resource "
                "type %s version %s, will NACK: nonce=%s status=%s",
                xds_client(), chand()->server_.server_uri().c_str(),
                result.type_url.c_str(), result.version.c_str(),
                state.nonce.c_str(), state.status.ToString().c_str());
      }
      // Delete resources not seen in update if needed.
      if (result.type->AllResourcesRequiredInSotW()) {
        for (auto& a : xds_client()->authority_state_map_) {
          const TString& authority = a.first;
          AuthorityState& authority_state = a.second;
          // Skip authorities that are not using this xDS channel.
          if (authority_state.channel_state != chand()) continue;
          auto seen_authority_it = result.resources_seen.find(authority);
          // Find this resource type.
          auto type_it = authority_state.resource_map.find(result.type);
          if (type_it == authority_state.resource_map.end()) continue;
          // Iterate over resource ids.
          for (auto& r : type_it->second) {
            const XdsResourceKey& resource_key = r.first;
            ResourceState& resource_state = r.second;
            if (seen_authority_it == result.resources_seen.end() ||
                seen_authority_it->second.find(resource_key) ==
                    seen_authority_it->second.end()) {
              // If the resource was newly requested but has not yet been
              // received, we don't want to generate an error for the
              // watchers, because this ADS response may be in reaction to an
              // earlier request that did not yet request the new resource, so
              // its absence from the response does not necessarily indicate
              // that the resource does not exist.  For that case, we rely on
              // the request timeout instead.
              if (resource_state.resource == nullptr) continue;
              if (chand()->server_.IgnoreResourceDeletion()) {
                if (!resource_state.ignored_deletion) {
                  gpr_log(GPR_ERROR,
                          "[xds_client %p] xds server %s: ignoring deletion "
                          "for resource type %s name %s",
                          xds_client(), chand()->server_.server_uri().c_str(),
                          result.type_url.c_str(),
                          XdsClient::ConstructFullXdsResourceName(
                              authority, result.type_url.c_str(), resource_key)
                              .c_str());
                  resource_state.ignored_deletion = true;
                }
              } else {
                resource_state.resource.reset();
                resource_state.meta.client_status =
                    XdsApi::ResourceMetadata::DOES_NOT_EXIST;
                xds_client()->NotifyWatchersOnResourceDoesNotExist(
                    resource_state.watchers);
              }
            }
          }
        }
      }
      // If we had valid resources or the update was empty, update the version.
      if (result.have_valid_resources || result.errors.empty()) {
        chand()->resource_type_version_map_[result.type] =
            std::move(result.version);
        // Start load reporting if needed.
        auto& lrs_call = chand()->lrs_calld_;
        if (lrs_call != nullptr) {
          LrsCallState* lrs_calld = lrs_call->calld();
          if (lrs_calld != nullptr) lrs_calld->MaybeStartReportingLocked();
        }
      }
      // Send ACK or NACK.
      SendMessageLocked(result.type);
    }
  }
  xds_client()->work_serializer_.DrainQueue();
}

void XdsClient::ChannelState::AdsCallState::OnStatusReceived(
    y_absl::Status status) {
  {
    MutexLock lock(&xds_client()->mu_);
    if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
      gpr_log(GPR_INFO,
              "[xds_client %p] xds server %s: ADS call status received "
              "(chand=%p, ads_calld=%p, call=%p): %s",
              xds_client(), chand()->server_.server_uri().c_str(), chand(),
              this, call_.get(), status.ToString().c_str());
    }
    // Cancel any does-not-exist timers that may be pending.
    for (const auto& p : state_map_) {
      for (const auto& q : p.second.subscribed_resources) {
        for (auto& r : q.second) {
          r.second->MaybeCancelTimer();
        }
      }
    }
    // Ignore status from a stale call.
    if (IsCurrentCallOnChannel()) {
      // Try to restart the call.
      parent_->OnCallFinishedLocked();
      // If we didn't receive a response on the stream, report the
      // stream failure as a connectivity failure, which will report the
      // error to all watchers of resources on this channel.
      if (!seen_response_) {
        chand()->SetChannelStatusLocked(y_absl::UnavailableError(
            y_absl::StrCat("xDS call failed with no responses received; status: ",
                         status.ToString())));
      }
    }
  }
  xds_client()->work_serializer_.DrainQueue();
}

bool XdsClient::ChannelState::AdsCallState::IsCurrentCallOnChannel() const {
  // If the retryable ADS call is null (which only happens when the xds
  // channel is shutting down), all the ADS calls are stale.
  if (chand()->ads_calld_ == nullptr) return false;
  return this == chand()->ads_calld_->calld();
}

std::vector<TString>
XdsClient::ChannelState::AdsCallState::ResourceNamesForRequest(
    const XdsResourceType* type) {
  std::vector<TString> resource_names;
  auto it = state_map_.find(type);
  if (it != state_map_.end()) {
    for (auto& a : it->second.subscribed_resources) {
      const TString& authority = a.first;
      for (auto& p : a.second) {
        const XdsResourceKey& resource_key = p.first;
        resource_names.emplace_back(XdsClient::ConstructFullXdsResourceName(
            authority, type->type_url(), resource_key));
        OrphanablePtr<ResourceTimer>& resource_timer = p.second;
        resource_timer->MarkSubscriptionSendStarted();
      }
    }
  }
  return resource_names;
}

//
// XdsClient::ChannelState::LrsCallState::Reporter
//

void XdsClient::ChannelState::LrsCallState::Reporter::Orphan() {
  if (timer_handle_.has_value() &&
      xds_client()->engine()->Cancel(*timer_handle_)) {
    timer_handle_.reset();
    Unref(DEBUG_LOCATION, "Orphan");
  }
}

void XdsClient::ChannelState::LrsCallState::Reporter::
    ScheduleNextReportLocked() {
  timer_handle_ = xds_client()->engine()->RunAfter(report_interval_, [this]() {
    ApplicationCallbackExecCtx callback_exec_ctx;
    ExecCtx exec_ctx;
    if (OnNextReportTimer()) {
      Unref(DEBUG_LOCATION, "OnNextReportTimer()");
    }
  });
}

bool XdsClient::ChannelState::LrsCallState::Reporter::OnNextReportTimer() {
  MutexLock lock(&xds_client()->mu_);
  timer_handle_.reset();
  if (!IsCurrentReporterOnCall()) return true;
  SendReportLocked();
  return false;
}

namespace {

bool LoadReportCountersAreZero(const XdsApi::ClusterLoadReportMap& snapshot) {
  for (const auto& p : snapshot) {
    const XdsApi::ClusterLoadReport& cluster_snapshot = p.second;
    if (!cluster_snapshot.dropped_requests.IsZero()) return false;
    for (const auto& q : cluster_snapshot.locality_stats) {
      const XdsClusterLocalityStats::Snapshot& locality_snapshot = q.second;
      if (!locality_snapshot.IsZero()) return false;
    }
  }
  return true;
}

}  // namespace

bool XdsClient::ChannelState::LrsCallState::Reporter::SendReportLocked() {
  // Construct snapshot from all reported stats.
  XdsApi::ClusterLoadReportMap snapshot =
      xds_client()->BuildLoadReportSnapshotLocked(parent_->chand()->server_,
                                                  parent_->send_all_clusters_,
                                                  parent_->cluster_names_);
  // Skip client load report if the counters were all zero in the last
  // report and they are still zero in this one.
  const bool old_val = last_report_counters_were_zero_;
  last_report_counters_were_zero_ = LoadReportCountersAreZero(snapshot);
  if (old_val && last_report_counters_were_zero_) {
    auto it = xds_client()->xds_load_report_server_map_.find(
        &parent_->chand()->server_);
    if (it == xds_client()->xds_load_report_server_map_.end() ||
        it->second.load_report_map.empty()) {
      it->second.channel_state->StopLrsCallLocked();
      return true;
    }
    ScheduleNextReportLocked();
    return false;
  }
  // Send a request that contains the snapshot.
  TString serialized_payload =
      xds_client()->api_.CreateLrsRequest(std::move(snapshot));
  parent_->call_->SendMessage(std::move(serialized_payload));
  parent_->send_message_pending_ = true;
  return false;
}

void XdsClient::ChannelState::LrsCallState::Reporter::OnReportDoneLocked() {
  // If a reporter starts a send_message op, then the reporting interval
  // changes and we destroy that reporter and create a new one, and then
  // the send_message op started by the old reporter finishes, this
  // method will be called even though it was for a completion started
  // by the old reporter.  In that case, the timer will be pending, so
  // we just ignore the completion and wait for the timer to fire.
  if (timer_handle_.has_value()) return;
  // If there are no more registered stats to report, cancel the call.
  auto it = xds_client()->xds_load_report_server_map_.find(
      &parent_->chand()->server_);
  if (it == xds_client()->xds_load_report_server_map_.end()) return;
  if (it->second.load_report_map.empty()) {
    if (it->second.channel_state != nullptr) {
      it->second.channel_state->StopLrsCallLocked();
    }
    return;
  }
  // Otherwise, schedule the next load report.
  ScheduleNextReportLocked();
}

//
// XdsClient::ChannelState::LrsCallState
//

XdsClient::ChannelState::LrsCallState::LrsCallState(
    RefCountedPtr<RetryableCall<LrsCallState>> parent)
    : InternallyRefCounted<LrsCallState>(
          GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_refcount_trace)
              ? "LrsCallState"
              : nullptr),
      parent_(std::move(parent)) {
  // Init the LRS call. Note that the call will progress every time there's
  // activity in xds_client()->interested_parties_, which is comprised of
  // the polling entities from client_channel.
  GPR_ASSERT(xds_client() != nullptr);
  const char* method =
      "/envoy.service.load_stats.v3.LoadReportingService/StreamLoadStats";
  call_ = chand()->transport_->CreateStreamingCall(
      method, std::make_unique<StreamEventHandler>(
                  // Passing the initial ref here.  This ref will go away when
                  // the StreamEventHandler is destroyed.
                  RefCountedPtr<LrsCallState>(this)));
  GPR_ASSERT(call_ != nullptr);
  // Start the call.
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO,
            "[xds_client %p] xds server %s: starting LRS call (calld=%p, "
            "call=%p)",
            xds_client(), chand()->server_.server_uri().c_str(), this,
            call_.get());
  }
  // Send the initial request.
  TString serialized_payload = xds_client()->api_.CreateLrsInitialRequest();
  call_->SendMessage(std::move(serialized_payload));
  send_message_pending_ = true;
}

void XdsClient::ChannelState::LrsCallState::Orphan() {
  reporter_.reset();
  // Note that the initial ref is held by the StreamEventHandler, which
  // will be destroyed when call_ is destroyed, which may not happen
  // here, since there may be other refs held to call_ by internal callbacks.
  call_.reset();
}

void XdsClient::ChannelState::LrsCallState::MaybeStartReportingLocked() {
  // Don't start again if already started.
  if (reporter_ != nullptr) return;
  // Don't start if the previous send_message op (of the initial request or
  // the last report of the previous reporter) hasn't completed.
  if (call_ != nullptr && send_message_pending_) return;
  // Don't start if no LRS response has arrived.
  if (!seen_response()) return;
  // Don't start if the ADS call hasn't received any valid response. Note that
  // this must be the first channel because it is the current channel but its
  // ADS call hasn't seen any response.
  if (chand()->ads_calld_ == nullptr ||
      chand()->ads_calld_->calld() == nullptr ||
      !chand()->ads_calld_->calld()->seen_response()) {
    return;
  }
  // Start reporting.
  reporter_ = MakeOrphanable<Reporter>(
      Ref(DEBUG_LOCATION, "LRS+load_report+start"), load_reporting_interval_);
}

void XdsClient::ChannelState::LrsCallState::OnRequestSent(bool /*ok*/) {
  MutexLock lock(&xds_client()->mu_);
  send_message_pending_ = false;
  if (reporter_ != nullptr) {
    reporter_->OnReportDoneLocked();
  } else {
    MaybeStartReportingLocked();
  }
}

void XdsClient::ChannelState::LrsCallState::OnRecvMessage(
    y_absl::string_view payload) {
  MutexLock lock(&xds_client()->mu_);
  // If we're no longer the current call, ignore the result.
  if (!IsCurrentCallOnChannel()) return;
  // Parse the response.
  bool send_all_clusters = false;
  std::set<TString> new_cluster_names;
  Duration new_load_reporting_interval;
  y_absl::Status status = xds_client()->api_.ParseLrsResponse(
      payload, &send_all_clusters, &new_cluster_names,
      &new_load_reporting_interval);
  if (!status.ok()) {
    gpr_log(GPR_ERROR,
            "[xds_client %p] xds server %s: LRS response parsing failed: %s",
            xds_client(), chand()->server_.server_uri().c_str(),
            status.ToString().c_str());
    return;
  }
  seen_response_ = true;
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(
        GPR_INFO,
        "[xds_client %p] xds server %s: LRS response received, %" PRIuPTR
        " cluster names, send_all_clusters=%d, load_report_interval=%" PRId64
        "ms",
        xds_client(), chand()->server_.server_uri().c_str(),
        new_cluster_names.size(), send_all_clusters,
        new_load_reporting_interval.millis());
    size_t i = 0;
    for (const auto& name : new_cluster_names) {
      gpr_log(GPR_INFO, "[xds_client %p] cluster_name %" PRIuPTR ": %s",
              xds_client(), i++, name.c_str());
    }
  }
  if (new_load_reporting_interval <
      Duration::Milliseconds(GRPC_XDS_MIN_CLIENT_LOAD_REPORTING_INTERVAL_MS)) {
    new_load_reporting_interval =
        Duration::Milliseconds(GRPC_XDS_MIN_CLIENT_LOAD_REPORTING_INTERVAL_MS);
    if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
      gpr_log(GPR_INFO,
              "[xds_client %p] xds server %s: increased load_report_interval "
              "to minimum value %dms",
              xds_client(), chand()->server_.server_uri().c_str(),
              GRPC_XDS_MIN_CLIENT_LOAD_REPORTING_INTERVAL_MS);
    }
  }
  // Ignore identical update.
  if (send_all_clusters == send_all_clusters_ &&
      cluster_names_ == new_cluster_names &&
      load_reporting_interval_ == new_load_reporting_interval) {
    if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
      gpr_log(GPR_INFO,
              "[xds_client %p] xds server %s: incoming LRS response identical "
              "to current, ignoring.",
              xds_client(), chand()->server_.server_uri().c_str());
    }
    return;
  }
  // Stop current load reporting (if any) to adopt the new config.
  reporter_.reset();
  // Record the new config.
  send_all_clusters_ = send_all_clusters;
  cluster_names_ = std::move(new_cluster_names);
  load_reporting_interval_ = new_load_reporting_interval;
  // Try starting sending load report.
  MaybeStartReportingLocked();
}

void XdsClient::ChannelState::LrsCallState::OnStatusReceived(
    y_absl::Status status) {
  MutexLock lock(&xds_client()->mu_);
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO,
            "[xds_client %p] xds server %s: LRS call status received "
            "(chand=%p, calld=%p, call=%p): %s",
            xds_client(), chand()->server_.server_uri().c_str(), chand(), this,
            call_.get(), status.ToString().c_str());
  }
  // Ignore status from a stale call.
  if (IsCurrentCallOnChannel()) {
    // Try to restart the call.
    parent_->OnCallFinishedLocked();
  }
}

bool XdsClient::ChannelState::LrsCallState::IsCurrentCallOnChannel() const {
  // If the retryable LRS call is null (which only happens when the xds
  // channel is shutting down), all the LRS calls are stale.
  if (chand()->lrs_calld_ == nullptr) return false;
  return this == chand()->lrs_calld_->calld();
}

//
// XdsClient
//

XdsClient::XdsClient(
    std::unique_ptr<XdsBootstrap> bootstrap,
    OrphanablePtr<XdsTransportFactory> transport_factory,
    std::shared_ptr<grpc_event_engine::experimental::EventEngine> engine,
    TString user_agent_name, TString user_agent_version,
    Duration resource_request_timeout)
    : DualRefCounted<XdsClient>(
          GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_refcount_trace) ? "XdsClient"
                                                                  : nullptr),
      bootstrap_(std::move(bootstrap)),
      transport_factory_(std::move(transport_factory)),
      request_timeout_(resource_request_timeout),
      xds_federation_enabled_(XdsFederationEnabled()),
      api_(this, &grpc_xds_client_trace, bootstrap_->node(), &symtab_,
           std::move(user_agent_name), std::move(user_agent_version)),
      engine_(std::move(engine)) {
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO, "[xds_client %p] creating xds client", this);
  }
  GPR_ASSERT(bootstrap_ != nullptr);
  if (bootstrap_->node() != nullptr) {
    gpr_log(GPR_INFO, "[xds_client %p] xDS node ID: %s", this,
            bootstrap_->node()->id().c_str());
  }
}

XdsClient::~XdsClient() {
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO, "[xds_client %p] destroying xds client", this);
  }
}

void XdsClient::Orphan() {
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO, "[xds_client %p] shutting down xds client", this);
  }
  MutexLock lock(&mu_);
  shutting_down_ = true;
  // Clear cache and any remaining watchers that may not have been cancelled.
  authority_state_map_.clear();
  invalid_watchers_.clear();
  // We may still be sending lingering queued load report data, so don't
  // just clear the load reporting map, but we do want to clear the refs
  // we're holding to the ChannelState objects, to make sure that
  // everything shuts down properly.
  for (auto& p : xds_load_report_server_map_) {
    p.second.channel_state.reset(DEBUG_LOCATION, "XdsClient::Orphan()");
  }
}

RefCountedPtr<XdsClient::ChannelState> XdsClient::GetOrCreateChannelStateLocked(
    const XdsBootstrap::XdsServer& server, const char* reason) {
  auto it = xds_server_channel_map_.find(&server);
  if (it != xds_server_channel_map_.end()) {
    return it->second->Ref(DEBUG_LOCATION, reason);
  }
  // Channel not found, so create a new one.
  auto channel_state = MakeRefCounted<ChannelState>(
      WeakRef(DEBUG_LOCATION, "ChannelState"), server);
  xds_server_channel_map_[&server] = channel_state.get();
  return channel_state;
}

void XdsClient::WatchResource(const XdsResourceType* type,
                              y_absl::string_view name,
                              RefCountedPtr<ResourceWatcherInterface> watcher) {
  ResourceWatcherInterface* w = watcher.get();
  // Lambda for handling failure cases.
  auto fail = [&](y_absl::Status status) mutable {
    {
      MutexLock lock(&mu_);
      MaybeRegisterResourceTypeLocked(type);
      invalid_watchers_[w] = watcher;
    }
    work_serializer_.Run(
        [watcher = std::move(watcher), status = std::move(status)]()
            Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) {
              watcher->OnError(status);
            },
        DEBUG_LOCATION);
  };
  auto resource_name = ParseXdsResourceName(name, type);
  if (!resource_name.ok()) {
    fail(y_absl::UnavailableError(
        y_absl::StrCat("Unable to parse resource name ", name)));
    return;
  }
  // Find server to use.
  const XdsBootstrap::XdsServer* xds_server = nullptr;
  y_absl::string_view authority_name = resource_name->authority;
  if (y_absl::ConsumePrefix(&authority_name, "xdstp:")) {
    auto* authority = bootstrap_->LookupAuthority(TString(authority_name));
    if (authority == nullptr) {
      fail(y_absl::UnavailableError(
          y_absl::StrCat("authority \"", authority_name,
                       "\" not present in bootstrap config")));
      return;
    }
    xds_server = authority->server();
  }
  if (xds_server == nullptr) xds_server = &bootstrap_->server();
  {
    MutexLock lock(&mu_);
    MaybeRegisterResourceTypeLocked(type);
    AuthorityState& authority_state =
        authority_state_map_[resource_name->authority];
    ResourceState& resource_state =
        authority_state.resource_map[type][resource_name->key];
    resource_state.watchers[w] = watcher;
    // If we already have a cached value for the resource, notify the new
    // watcher immediately.
    if (resource_state.resource != nullptr) {
      if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
        gpr_log(GPR_INFO,
                "[xds_client %p] returning cached listener data for %s", this,
                TString(name).c_str());
      }
      auto* value = type->CopyResource(resource_state.resource.get()).release();
      work_serializer_.Schedule(
          [watcher, value]() Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) {
            watcher->OnGenericResourceChanged(value);
            delete value;
          },
          DEBUG_LOCATION);
    } else if (resource_state.meta.client_status ==
               XdsApi::ResourceMetadata::DOES_NOT_EXIST) {
      if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
        gpr_log(GPR_INFO,
                "[xds_client %p] reporting cached does-not-exist for %s", this,
                TString(name).c_str());
      }
      work_serializer_.Schedule(
          [watcher]() Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) {
            watcher->OnResourceDoesNotExist();
          },
          DEBUG_LOCATION);
    } else if (resource_state.meta.client_status ==
               XdsApi::ResourceMetadata::NACKED) {
      if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
        gpr_log(
            GPR_INFO,
            "[xds_client %p] reporting cached validation failure for %s: %s",
            this, TString(name).c_str(),
            resource_state.meta.failed_details.c_str());
      }
      TString details = resource_state.meta.failed_details;
      const auto* node = bootstrap_->node();
      if (node != nullptr) {
        y_absl::StrAppend(&details, " (node ID:", bootstrap_->node()->id(), ")");
      }
      work_serializer_.Schedule(
          [watcher, details = std::move(details)]()
              Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) {
                watcher->OnError(y_absl::UnavailableError(
                    y_absl::StrCat("invalid resource: ", details)));
              },
          DEBUG_LOCATION);
    }
    // If the authority doesn't yet have a channel, set it, creating it if
    // needed.
    if (authority_state.channel_state == nullptr) {
      authority_state.channel_state =
          GetOrCreateChannelStateLocked(*xds_server, "start watch");
    }
    y_absl::Status channel_status = authority_state.channel_state->status();
    if (!channel_status.ok()) {
      if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
        gpr_log(GPR_INFO,
                "[xds_client %p] returning cached channel error for %s: %s",
                this, TString(name).c_str(),
                channel_status.ToString().c_str());
      }
      work_serializer_.Schedule(
          [watcher = std::move(watcher), status = std::move(channel_status)]()
              Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) mutable {
                watcher->OnError(std::move(status));
              },
          DEBUG_LOCATION);
    }
    authority_state.channel_state->SubscribeLocked(type, *resource_name);
  }
  work_serializer_.DrainQueue();
}

void XdsClient::CancelResourceWatch(const XdsResourceType* type,
                                    y_absl::string_view name,
                                    ResourceWatcherInterface* watcher,
                                    bool delay_unsubscription) {
  auto resource_name = ParseXdsResourceName(name, type);
  MutexLock lock(&mu_);
  // We cannot be sure whether the watcher is in invalid_watchers_ or in
  // authority_state_map_, so we check both, just to be safe.
  invalid_watchers_.erase(watcher);
  // Find authority.
  if (!resource_name.ok()) return;
  auto authority_it = authority_state_map_.find(resource_name->authority);
  if (authority_it == authority_state_map_.end()) return;
  AuthorityState& authority_state = authority_it->second;
  // Find type map.
  auto type_it = authority_state.resource_map.find(type);
  if (type_it == authority_state.resource_map.end()) return;
  auto& type_map = type_it->second;
  // Find resource key.
  auto resource_it = type_map.find(resource_name->key);
  if (resource_it == type_map.end()) return;
  ResourceState& resource_state = resource_it->second;
  // Remove watcher.
  resource_state.watchers.erase(watcher);
  // Clean up empty map entries, if any.
  if (resource_state.watchers.empty()) {
    if (resource_state.ignored_deletion) {
      gpr_log(GPR_INFO,
              "[xds_client %p] unsubscribing from a resource for which we "
              "previously ignored a deletion: type %s name %s",
              this, TString(type->type_url()).c_str(),
              TString(name).c_str());
    }
    authority_state.channel_state->UnsubscribeLocked(type, *resource_name,
                                                     delay_unsubscription);
    type_map.erase(resource_it);
    if (type_map.empty()) {
      authority_state.resource_map.erase(type_it);
      if (authority_state.resource_map.empty()) {
        authority_state.channel_state.reset();
      }
    }
  }
}

void XdsClient::MaybeRegisterResourceTypeLocked(
    const XdsResourceType* resource_type) {
  auto it = resource_types_.find(resource_type->type_url());
  if (it != resource_types_.end()) {
    GPR_ASSERT(it->second == resource_type);
    return;
  }
  resource_types_.emplace(resource_type->type_url(), resource_type);
  resource_type->InitUpbSymtab(this, symtab_.ptr());
}

const XdsResourceType* XdsClient::GetResourceTypeLocked(
    y_absl::string_view resource_type) {
  auto it = resource_types_.find(resource_type);
  if (it != resource_types_.end()) return it->second;
  return nullptr;
}

y_absl::StatusOr<XdsClient::XdsResourceName> XdsClient::ParseXdsResourceName(
    y_absl::string_view name, const XdsResourceType* type) {
  // Old-style names use the empty string for authority.
  // authority is prefixed with "old:" to indicate that it's an old-style
  // name.
  if (!xds_federation_enabled_ || !y_absl::StartsWith(name, "xdstp:")) {
    return XdsResourceName{"old:", {TString(name), {}}};
  }
  // New style name.  Parse URI.
  auto uri = URI::Parse(name);
  if (!uri.ok()) return uri.status();
  // Split the resource type off of the path to get the id.
  std::pair<y_absl::string_view, y_absl::string_view> path_parts = y_absl::StrSplit(
      y_absl::StripPrefix(uri->path(), "/"), y_absl::MaxSplits('/', 1));
  if (type->type_url() != path_parts.first) {
    return y_absl::InvalidArgumentError(
        "xdstp URI path must indicate valid xDS resource type");
  }
  // Canonicalize order of query params.
  std::vector<URI::QueryParam> query_params;
  for (const auto& p : uri->query_parameter_map()) {
    query_params.emplace_back(
        URI::QueryParam{TString(p.first), TString(p.second)});
  }
  return XdsResourceName{
      y_absl::StrCat("xdstp:", uri->authority()),
      {TString(path_parts.second), std::move(query_params)}};
}

TString XdsClient::ConstructFullXdsResourceName(
    y_absl::string_view authority, y_absl::string_view resource_type,
    const XdsResourceKey& key) {
  if (y_absl::ConsumePrefix(&authority, "xdstp:")) {
    auto uri = URI::Create("xdstp", TString(authority),
                           y_absl::StrCat("/", resource_type, "/", key.id),
                           key.query_params, /*fragment=*/"");
    GPR_ASSERT(uri.ok());
    return uri->ToString();
  }
  // Old-style name.
  return key.id;
}

RefCountedPtr<XdsClusterDropStats> XdsClient::AddClusterDropStats(
    const XdsBootstrap::XdsServer& xds_server, y_absl::string_view cluster_name,
    y_absl::string_view eds_service_name) {
  const auto* server = bootstrap_->FindXdsServer(xds_server);
  if (server == nullptr) return nullptr;
  auto key =
      std::make_pair(TString(cluster_name), TString(eds_service_name));
  RefCountedPtr<XdsClusterDropStats> cluster_drop_stats;
  {
    MutexLock lock(&mu_);
    // We jump through some hoops here to make sure that the const
    // XdsBootstrap::XdsServer& and y_absl::string_views
    // stored in the XdsClusterDropStats object point to the
    // XdsBootstrap::XdsServer and strings
    // in the load_report_map_ key, so that they have the same lifetime.
    auto server_it =
        xds_load_report_server_map_.emplace(server, LoadReportServer()).first;
    if (server_it->second.channel_state == nullptr) {
      server_it->second.channel_state = GetOrCreateChannelStateLocked(
          *server, "load report map (drop stats)");
    }
    auto load_report_it = server_it->second.load_report_map
                              .emplace(std::move(key), LoadReportState())
                              .first;
    LoadReportState& load_report_state = load_report_it->second;
    if (load_report_state.drop_stats != nullptr) {
      cluster_drop_stats = load_report_state.drop_stats->RefIfNonZero();
    }
    if (cluster_drop_stats == nullptr) {
      if (load_report_state.drop_stats != nullptr) {
        load_report_state.deleted_drop_stats +=
            load_report_state.drop_stats->GetSnapshotAndReset();
      }
      cluster_drop_stats = MakeRefCounted<XdsClusterDropStats>(
          Ref(DEBUG_LOCATION, "DropStats"), *server,
          load_report_it->first.first /*cluster_name*/,
          load_report_it->first.second /*eds_service_name*/);
      load_report_state.drop_stats = cluster_drop_stats.get();
    }
    server_it->second.channel_state->MaybeStartLrsCall();
  }
  work_serializer_.DrainQueue();
  return cluster_drop_stats;
}

void XdsClient::RemoveClusterDropStats(
    const XdsBootstrap::XdsServer& xds_server, y_absl::string_view cluster_name,
    y_absl::string_view eds_service_name,
    XdsClusterDropStats* cluster_drop_stats) {
  const auto* server = bootstrap_->FindXdsServer(xds_server);
  if (server == nullptr) return;
  MutexLock lock(&mu_);
  auto server_it = xds_load_report_server_map_.find(server);
  if (server_it == xds_load_report_server_map_.end()) return;
  auto load_report_it = server_it->second.load_report_map.find(
      std::make_pair(TString(cluster_name), TString(eds_service_name)));
  if (load_report_it == server_it->second.load_report_map.end()) return;
  LoadReportState& load_report_state = load_report_it->second;
  if (load_report_state.drop_stats == cluster_drop_stats) {
    // Record final snapshot in deleted_drop_stats, which will be
    // added to the next load report.
    load_report_state.deleted_drop_stats +=
        load_report_state.drop_stats->GetSnapshotAndReset();
    load_report_state.drop_stats = nullptr;
  }
}

RefCountedPtr<XdsClusterLocalityStats> XdsClient::AddClusterLocalityStats(
    const XdsBootstrap::XdsServer& xds_server, y_absl::string_view cluster_name,
    y_absl::string_view eds_service_name,
    RefCountedPtr<XdsLocalityName> locality) {
  const auto* server = bootstrap_->FindXdsServer(xds_server);
  if (server == nullptr) return nullptr;
  auto key =
      std::make_pair(TString(cluster_name), TString(eds_service_name));
  RefCountedPtr<XdsClusterLocalityStats> cluster_locality_stats;
  {
    MutexLock lock(&mu_);
    // We jump through some hoops here to make sure that the const
    // XdsBootstrap::XdsServer& and y_absl::string_views
    // stored in the XdsClusterDropStats object point to the
    // XdsBootstrap::XdsServer and strings
    // in the load_report_map_ key, so that they have the same lifetime.
    auto server_it =
        xds_load_report_server_map_.emplace(server, LoadReportServer()).first;
    if (server_it->second.channel_state == nullptr) {
      server_it->second.channel_state = GetOrCreateChannelStateLocked(
          *server, "load report map (locality stats)");
    }
    auto load_report_it = server_it->second.load_report_map
                              .emplace(std::move(key), LoadReportState())
                              .first;
    LoadReportState& load_report_state = load_report_it->second;
    LoadReportState::LocalityState& locality_state =
        load_report_state.locality_stats[locality];
    if (locality_state.locality_stats != nullptr) {
      cluster_locality_stats = locality_state.locality_stats->RefIfNonZero();
    }
    if (cluster_locality_stats == nullptr) {
      if (locality_state.locality_stats != nullptr) {
        locality_state.deleted_locality_stats +=
            locality_state.locality_stats->GetSnapshotAndReset();
      }
      cluster_locality_stats = MakeRefCounted<XdsClusterLocalityStats>(
          Ref(DEBUG_LOCATION, "LocalityStats"), *server,
          load_report_it->first.first /*cluster_name*/,
          load_report_it->first.second /*eds_service_name*/,
          std::move(locality));
      locality_state.locality_stats = cluster_locality_stats.get();
    }
    server_it->second.channel_state->MaybeStartLrsCall();
  }
  work_serializer_.DrainQueue();
  return cluster_locality_stats;
}

void XdsClient::RemoveClusterLocalityStats(
    const XdsBootstrap::XdsServer& xds_server, y_absl::string_view cluster_name,
    y_absl::string_view eds_service_name,
    const RefCountedPtr<XdsLocalityName>& locality,
    XdsClusterLocalityStats* cluster_locality_stats) {
  const auto* server = bootstrap_->FindXdsServer(xds_server);
  if (server == nullptr) return;
  MutexLock lock(&mu_);
  auto server_it = xds_load_report_server_map_.find(server);
  if (server_it == xds_load_report_server_map_.end()) return;
  auto load_report_it = server_it->second.load_report_map.find(
      std::make_pair(TString(cluster_name), TString(eds_service_name)));
  if (load_report_it == server_it->second.load_report_map.end()) return;
  LoadReportState& load_report_state = load_report_it->second;
  auto locality_it = load_report_state.locality_stats.find(locality);
  if (locality_it == load_report_state.locality_stats.end()) return;
  LoadReportState::LocalityState& locality_state = locality_it->second;
  if (locality_state.locality_stats == cluster_locality_stats) {
    // Record final snapshot in deleted_locality_stats, which will be
    // added to the next load report.
    locality_state.deleted_locality_stats +=
        locality_state.locality_stats->GetSnapshotAndReset();
    locality_state.locality_stats = nullptr;
  }
}

void XdsClient::ResetBackoff() {
  MutexLock lock(&mu_);
  for (auto& p : xds_server_channel_map_) {
    p.second->ResetBackoff();
  }
}

void XdsClient::NotifyWatchersOnErrorLocked(
    const std::map<ResourceWatcherInterface*,
                   RefCountedPtr<ResourceWatcherInterface>>& watchers,
    y_absl::Status status) {
  const auto* node = bootstrap_->node();
  if (node != nullptr) {
    status = y_absl::Status(
        status.code(),
        y_absl::StrCat(status.message(), " (node ID:", node->id(), ")"));
  }
  work_serializer_.Schedule(
      [watchers, status = std::move(status)]()
          Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) {
            for (const auto& p : watchers) {
              p.first->OnError(status);
            }
          },
      DEBUG_LOCATION);
}

void XdsClient::NotifyWatchersOnResourceDoesNotExist(
    const std::map<ResourceWatcherInterface*,
                   RefCountedPtr<ResourceWatcherInterface>>& watchers) {
  work_serializer_.Schedule(
      [watchers]() Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(&work_serializer_) {
        for (const auto& p : watchers) {
          p.first->OnResourceDoesNotExist();
        }
      },
      DEBUG_LOCATION);
}

XdsApi::ClusterLoadReportMap XdsClient::BuildLoadReportSnapshotLocked(
    const XdsBootstrap::XdsServer& xds_server, bool send_all_clusters,
    const std::set<TString>& clusters) {
  if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
    gpr_log(GPR_INFO, "[xds_client %p] start building load report", this);
  }
  XdsApi::ClusterLoadReportMap snapshot_map;
  auto server_it = xds_load_report_server_map_.find(&xds_server);
  if (server_it == xds_load_report_server_map_.end()) return snapshot_map;
  auto& load_report_map = server_it->second.load_report_map;
  for (auto load_report_it = load_report_map.begin();
       load_report_it != load_report_map.end();) {
    // Cluster key is cluster and EDS service name.
    const auto& cluster_key = load_report_it->first;
    LoadReportState& load_report = load_report_it->second;
    // If the CDS response for a cluster indicates to use LRS but the
    // LRS server does not say that it wants reports for this cluster,
    // then we'll have stats objects here whose data we're not going to
    // include in the load report.  However, we still need to clear out
    // the data from the stats objects, so that if the LRS server starts
    // asking for the data in the future, we don't incorrectly include
    // data from previous reporting intervals in that future report.
    const bool record_stats =
        send_all_clusters || clusters.find(cluster_key.first) != clusters.end();
    XdsApi::ClusterLoadReport snapshot;
    // Aggregate drop stats.
    snapshot.dropped_requests = std::move(load_report.deleted_drop_stats);
    if (load_report.drop_stats != nullptr) {
      snapshot.dropped_requests +=
          load_report.drop_stats->GetSnapshotAndReset();
      if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
        gpr_log(GPR_INFO,
                "[xds_client %p] cluster=%s eds_service_name=%s drop_stats=%p",
                this, cluster_key.first.c_str(), cluster_key.second.c_str(),
                load_report.drop_stats);
      }
    }
    // Aggregate locality stats.
    for (auto it = load_report.locality_stats.begin();
         it != load_report.locality_stats.end();) {
      const RefCountedPtr<XdsLocalityName>& locality_name = it->first;
      auto& locality_state = it->second;
      XdsClusterLocalityStats::Snapshot& locality_snapshot =
          snapshot.locality_stats[locality_name];
      locality_snapshot = std::move(locality_state.deleted_locality_stats);
      if (locality_state.locality_stats != nullptr) {
        locality_snapshot +=
            locality_state.locality_stats->GetSnapshotAndReset();
        if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
          gpr_log(GPR_INFO,
                  "[xds_client %p] cluster=%s eds_service_name=%s "
                  "locality=%s locality_stats=%p",
                  this, cluster_key.first.c_str(), cluster_key.second.c_str(),
                  locality_name->AsHumanReadableString().c_str(),
                  locality_state.locality_stats);
        }
      }
      // If the only thing left in this entry was final snapshots from
      // deleted locality stats objects, remove the entry.
      if (locality_state.locality_stats == nullptr) {
        it = load_report.locality_stats.erase(it);
      } else {
        ++it;
      }
    }
    // Compute load report interval.
    const Timestamp now = Timestamp::Now();
    snapshot.load_report_interval = now - load_report.last_report_time;
    load_report.last_report_time = now;
    // Record snapshot.
    if (record_stats) {
      snapshot_map[cluster_key] = std::move(snapshot);
    }
    // If the only thing left in this entry was final snapshots from
    // deleted stats objects, remove the entry.
    if (load_report.locality_stats.empty() &&
        load_report.drop_stats == nullptr) {
      load_report_it = load_report_map.erase(load_report_it);
    } else {
      ++load_report_it;
    }
  }
  return snapshot_map;
}

TString XdsClient::DumpClientConfigBinary() {
  MutexLock lock(&mu_);
  XdsApi::ResourceTypeMetadataMap resource_type_metadata_map;
  for (const auto& a : authority_state_map_) {  // authority
    const TString& authority = a.first;
    for (const auto& t : a.second.resource_map) {  // type
      const XdsResourceType* type = t.first;
      auto& resource_metadata_map =
          resource_type_metadata_map[type->type_url()];
      for (const auto& r : t.second) {  // resource id
        const XdsResourceKey& resource_key = r.first;
        const ResourceState& resource_state = r.second;
        resource_metadata_map[ConstructFullXdsResourceName(
            authority, type->type_url(), resource_key)] = &resource_state.meta;
      }
    }
  }
  // Assemble config dump messages
  return api_.AssembleClientConfig(resource_type_metadata_map);
}

}  // namespace grpc_core