aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/dnsresolver/dnsresolver_caching.cpp
blob: a1688854c4ffab7e90f3e904608631095438e5fc (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
#include "dnsresolver.h" 
 
#include <library/cpp/actors/core/hfunc.h> 
#include <util/generic/intrlist.h> 
 
#include <ares.h> 
 
#include <queue> 
 
namespace NActors { 
namespace NDnsResolver { 
 
    class TCachingDnsResolver : public TActor<TCachingDnsResolver> { 
    public: 
        struct TMonCounters { 
            NMonitoring::TDynamicCounters::TCounterPtr OutgoingInFlightV4; 
            NMonitoring::TDynamicCounters::TCounterPtr OutgoingInFlightV6; 
            NMonitoring::TDynamicCounters::TCounterPtr OutgoingErrorsV4; 
            NMonitoring::TDynamicCounters::TCounterPtr OutgoingErrorsV6; 
            NMonitoring::TDynamicCounters::TCounterPtr OutgoingTotalV4; 
            NMonitoring::TDynamicCounters::TCounterPtr OutgoingTotalV6; 
 
            NMonitoring::TDynamicCounters::TCounterPtr IncomingInFlight; 
            NMonitoring::TDynamicCounters::TCounterPtr IncomingErrors; 
            NMonitoring::TDynamicCounters::TCounterPtr IncomingTotal; 
 
            NMonitoring::TDynamicCounters::TCounterPtr CacheSize; 
            NMonitoring::TDynamicCounters::TCounterPtr CacheHits; 
            NMonitoring::TDynamicCounters::TCounterPtr CacheMisses; 
 
            TMonCounters(const NMonitoring::TDynamicCounterPtr& counters) 
                : OutgoingInFlightV4(counters->GetCounter("DnsResolver/Outgoing/InFlight/V4", false)) 
                , OutgoingInFlightV6(counters->GetCounter("DnsResolver/Outgoing/InFlight/V6", false)) 
                , OutgoingErrorsV4(counters->GetCounter("DnsResolver/Outgoing/Errors/V4", true)) 
                , OutgoingErrorsV6(counters->GetCounter("DnsResolver/Outgoing/Errors/V6", true)) 
                , OutgoingTotalV4(counters->GetCounter("DnsResolver/Outgoing/Total/V4", true)) 
                , OutgoingTotalV6(counters->GetCounter("DnsResolver/Outgoing/Total/V6", true)) 
                , IncomingInFlight(counters->GetCounter("DnsResolver/Incoming/InFlight", false)) 
                , IncomingErrors(counters->GetCounter("DnsResolver/Incoming/Errors", true)) 
                , IncomingTotal(counters->GetCounter("DnsResolver/Incoming/Total", true)) 
                , CacheSize(counters->GetCounter("DnsResolver/Cache/Size", false)) 
                , CacheHits(counters->GetCounter("DnsResolver/Cache/Hits", true)) 
                , CacheMisses(counters->GetCounter("DnsResolver/Cache/Misses", true)) 
            { } 
        }; 
 
    public: 
        TCachingDnsResolver(TActorId upstream, TCachingDnsResolverOptions options) 
            : TActor(&TThis::StateWork) 
            , Upstream(upstream) 
            , Options(std::move(options)) 
            , MonCounters(Options.MonCounters ? new TMonCounters(Options.MonCounters) : nullptr) 
        { } 
 
        static constexpr EActivityType ActorActivityType() { 
            return DNS_RESOLVER; 
        } 
 
    private: 
        STRICT_STFUNC(StateWork, { 
            hFunc(TEvents::TEvPoison, Handle); 
            hFunc(TEvDns::TEvGetHostByName, Handle); 
            hFunc(TEvDns::TEvGetAddr, Handle); 
            hFunc(TEvDns::TEvGetHostByNameResult, Handle); 
            hFunc(TEvents::TEvUndelivered, Handle); 
        }); 
 
        void Handle(TEvents::TEvPoison::TPtr&) { 
            DropPending(ARES_ECANCELLED); 
            PassAway(); 
        } 
 
        void Handle(TEvDns::TEvGetHostByName::TPtr& ev) { 
            auto req = MakeHolder<TIncomingRequest>(); 
            req->Type = EIncomingRequestType::GetHostByName; 
            req->Sender = ev->Sender; 
            req->Cookie = ev->Cookie; 
            req->Name = std::move(ev->Get()->Name); 
            req->Family = ev->Get()->Family; 
            EnqueueRequest(std::move(req)); 
        } 
 
        void Handle(TEvDns::TEvGetAddr::TPtr& ev) { 
            auto req = MakeHolder<TIncomingRequest>(); 
            req->Type = EIncomingRequestType::GetAddr; 
            req->Sender = ev->Sender; 
            req->Cookie = ev->Cookie; 
            req->Name = std::move(ev->Get()->Name); 
            req->Family = ev->Get()->Family; 
            EnqueueRequest(std::move(req)); 
        } 
 
        void Handle(TEvDns::TEvGetHostByNameResult::TPtr& ev) { 
            auto waitingIt = WaitingRequests.find(ev->Cookie); 
            Y_VERIFY(waitingIt != WaitingRequests.end(), "Unexpected reply, reqId=%" PRIu64, ev->Cookie); 
            auto waitingInfo = waitingIt->second; 
            WaitingRequests.erase(waitingIt); 
 
            switch (waitingInfo.Family) { 
                case AF_INET6: 
                    if (ev->Get()->Status) { 
                        ProcessErrorV6(waitingInfo.Position, ev->Get()->Status, std::move(ev->Get()->ErrorText)); 
                    } else { 
                        ProcessAddrsV6(waitingInfo.Position, std::move(ev->Get()->AddrsV6)); 
                    } 
                    break; 
 
                case AF_INET: 
                    if (ev->Get()->Status) { 
                        ProcessErrorV4(waitingInfo.Position, ev->Get()->Status, std::move(ev->Get()->ErrorText)); 
                    } else { 
                        ProcessAddrsV4(waitingInfo.Position, std::move(ev->Get()->AddrsV4)); 
                    } 
                    break; 
 
                default: 
                    Y_FAIL("Unexpected request family %d", waitingInfo.Family); 
            } 
        } 
 
        void Handle(TEvents::TEvUndelivered::TPtr& ev) { 
            switch (ev->Get()->SourceType) { 
                case TEvDns::TEvGetHostByName::EventType: { 
                    auto waitingIt = WaitingRequests.find(ev->Cookie); 
                    Y_VERIFY(waitingIt != WaitingRequests.end(), "Unexpected TEvUndelivered, reqId=%" PRIu64, ev->Cookie); 
                    auto waitingInfo = waitingIt->second; 
                    WaitingRequests.erase(waitingIt); 
 
                    switch (waitingInfo.Family) { 
                        case AF_INET6: 
                            ProcessErrorV6(waitingInfo.Position, ARES_ENOTINITIALIZED, "Caching dns resolver cannot deliver to the underlying resolver"); 
                            break; 
                        case AF_INET: 
                            ProcessErrorV4(waitingInfo.Position, ARES_ENOTINITIALIZED, "Caching dns resolver cannot deliver to the underlying resolver"); 
                            break; 
                        default: 
                            Y_FAIL("Unexpected request family %d", waitingInfo.Family); 
                    } 
 
                    break; 
                } 
 
                default: 
                    Y_FAIL("Unexpected TEvUndelievered, type=%" PRIu32, ev->Get()->SourceType); 
            } 
        } 
 
    private: 
        enum EIncomingRequestType { 
            GetHostByName, 
            GetAddr, 
        }; 
 
        struct TIncomingRequest : public TIntrusiveListItem<TIncomingRequest> { 
            EIncomingRequestType Type; 
            TActorId Sender; 
            ui64 Cookie; 
            TString Name; 
            int Family; 
        }; 
 
        using TIncomingRequestList = TIntrusiveListWithAutoDelete<TIncomingRequest, TDelete>; 
 
        void EnqueueRequest(THolder<TIncomingRequest> req) { 
            if (MonCounters) { 
                ++*MonCounters->IncomingTotal; 
            } 
 
            CleanupExpired(TActivationContext::Now()); 
 
            switch (req->Family) { 
                case AF_UNSPEC: 
                    if (Options.AllowIPv6) { 
                        EnqueueRequestIPv6(std::move(req)); 
                        return; 
                    } 
                    if (Options.AllowIPv4) { 
                        EnqueueRequestIPv4(std::move(req)); 
                        return; 
                    } 
                    break; 
 
                case AF_INET6: 
                    if (Options.AllowIPv6) { 
                        EnqueueRequestIPv6(std::move(req)); 
                        return; 
                    } 
                    break; 
 
                case AF_INET: 
                    if (Options.AllowIPv4) { 
                        EnqueueRequestIPv4(std::move(req)); 
                        return; 
                    } 
                    break; 
            } 
 
            ReplyWithError(std::move(req), ARES_EBADFAMILY); 
        } 
 
        void EnqueueRequestIPv6(THolder<TIncomingRequest> req) { 
            auto now = TActivationContext::Now(); 
 
            auto& fullState = NameToState[req->Name]; 
            if (MonCounters) { 
                *MonCounters->CacheSize = NameToState.size(); 
            } 
 
            auto& state = fullState.StateIPv6; 
            EnsureRequest(state, req->Name, AF_INET6, now); 
 
            if (state.IsHardExpired(now)) { 
                Y_VERIFY(state.Waiting); 
                if (MonCounters) { 
                    ++*MonCounters->CacheMisses; 
                } 
                // We need to wait for ipv6 reply, schedule ipv4 request in parallel if needed 
                if (Options.AllowIPv4) { 
                    EnsureRequest(fullState.StateIPv4, req->Name, AF_INET, now); 
                } 
                state.WaitingRequests.PushBack(req.Release()); 
                return; 
            } 
 
            // We want to retry AF_UNSPEC with IPv4 in some cases 
            if (req->Family == AF_UNSPEC && Options.AllowIPv4 && state.RetryUnspec()) { 
                EnqueueRequestIPv4(std::move(req)); 
                return; 
            } 
 
            if (MonCounters) { 
                ++*MonCounters->CacheHits; 
            } 
 
            if (state.Status != 0) { 
                ReplyWithError(std::move(req), state.Status, state.ErrorText); 
            } else { 
                ReplyWithAddrs(std::move(req), fullState.AddrsIPv6); 
            } 
        } 
 
        void EnqueueRequestIPv4(THolder<TIncomingRequest> req, bool isCacheMiss = false) { 
            auto now = TActivationContext::Now(); 
 
            auto& fullState = NameToState[req->Name]; 
            if (MonCounters) { 
                *MonCounters->CacheSize = NameToState.size(); 
            } 
 
            auto& state = fullState.StateIPv4; 
            EnsureRequest(state, req->Name, AF_INET, now); 
 
            if (state.IsHardExpired(now)) { 
                Y_VERIFY(state.Waiting); 
                if (MonCounters && !isCacheMiss) { 
                    ++*MonCounters->CacheMisses; 
                } 
                state.WaitingRequests.PushBack(req.Release()); 
                return; 
            } 
 
            if (MonCounters && !isCacheMiss) { 
                ++*MonCounters->CacheHits; 
            } 
 
            if (state.Status != 0) { 
                ReplyWithError(std::move(req), state.Status, state.ErrorText); 
            } else { 
                ReplyWithAddrs(std::move(req), fullState.AddrsIPv4); 
            } 
        } 
 
    private: 
        struct TFamilyState { 
            TIncomingRequestList WaitingRequests; 
            TInstant SoftDeadline; 
            TInstant HardDeadline; 
            TInstant NextSoftDeadline; 
            TInstant NextHardDeadline; 
            TString ErrorText; 
            int Status = -1; // never requested before 
            bool InSoftHeap = false; 
            bool InHardHeap = false; 
            bool Waiting = false; 
 
            bool Needed() const { 
                return InSoftHeap || InHardHeap || Waiting; 
            } 
 
            bool RetryUnspec() const { 
                return ( 
                    Status == ARES_ENODATA || 
                    Status == ARES_EBADRESP || 
                    Status == ARES_ETIMEOUT); 
            } 
 
            bool ServerReplied() const { 
                return ServerReplied(Status); 
            } 
 
            bool IsSoftExpired(TInstant now) const { 
                return !InSoftHeap || NextSoftDeadline < now; 
            } 
 
            bool IsHardExpired(TInstant now) const { 
                return !InHardHeap || NextHardDeadline < now; 
            } 
 
            static bool ServerReplied(int status) { 
                return ( 
                    status == ARES_SUCCESS || 
                    status == ARES_ENODATA || 
                    status == ARES_ENOTFOUND); 
            } 
        }; 
 
        struct TState { 
            TFamilyState StateIPv6; 
            TFamilyState StateIPv4; 
            TVector<struct in6_addr> AddrsIPv6; 
            TVector<struct in_addr> AddrsIPv4; 
 
            bool Needed() const { 
                return StateIPv6.Needed() || StateIPv4.Needed(); 
            } 
        }; 
 
        using TNameToState = THashMap<TString, TState>; 
 
        template<const TFamilyState TState::* StateToFamily, 
                 const TInstant TFamilyState::* FamilyToDeadline> 
        struct THeapCompare { 
            // returns true when b < a 
            bool operator()(TNameToState::iterator a, TNameToState::iterator b) const { 
                const TState& aState = a->second; 
                const TState& bState = b->second; 
                const TFamilyState& aFamily = aState.*StateToFamily; 
                const TFamilyState& bFamily = bState.*StateToFamily; 
                const TInstant& aDeadline = aFamily.*FamilyToDeadline; 
                const TInstant& bDeadline = bFamily.*FamilyToDeadline; 
                return bDeadline < aDeadline; 
            } 
        }; 
 
        template<const TFamilyState TState::* StateToFamily, 
                 const TInstant TFamilyState::* FamilyToDeadline> 
        using TStateHeap = std::priority_queue< 
                TNameToState::iterator, 
                std::vector<TNameToState::iterator>, 
                THeapCompare<StateToFamily, FamilyToDeadline> 
        >; 
 
        struct TWaitingInfo { 
            TNameToState::iterator Position; 
            int Family; 
        }; 
 
    private: 
        void EnsureRequest(TFamilyState& state, const TString& name, int family, TInstant now) { 
            if (state.Waiting) { 
                return; // request is already pending 
            } 
 
            if (!state.IsSoftExpired(now) && !state.IsHardExpired(now)) { 
                return; // response is not expired yet 
            } 
 
            if (MonCounters) { 
                switch (family) { 
                    case AF_INET6: 
                        ++*MonCounters->OutgoingInFlightV6; 
                        ++*MonCounters->OutgoingTotalV6; 
                        break; 
                    case AF_INET: 
                        ++*MonCounters->OutgoingInFlightV4; 
                        ++*MonCounters->OutgoingTotalV4; 
                        break; 
                } 
            } 
 
            ui64 reqId = ++LastRequestId; 
            auto& req = WaitingRequests[reqId]; 
            req.Position = NameToState.find(name); 
            req.Family = family; 
            Y_VERIFY(req.Position != NameToState.end()); 
 
            Send(Upstream, new TEvDns::TEvGetHostByName(name, family), IEventHandle::FlagTrackDelivery, reqId); 
            state.Waiting = true; 
        } 
 
        template<TFamilyState TState::* StateToFamily, 
                 TInstant TFamilyState::* FamilyToDeadline, 
                 TInstant TFamilyState::* FamilyToNextDeadline, 
                 bool TFamilyState::* FamilyToFlag, 
                 class THeap> 
        void PushToHeap(THeap& heap, TNameToState::iterator it, TInstant newDeadline) { 
            auto& family = it->second.*StateToFamily; 
            TInstant& deadline = family.*FamilyToDeadline; 
            TInstant& nextDeadline = family.*FamilyToNextDeadline; 
            bool& flag = family.*FamilyToFlag; 
            nextDeadline = newDeadline; 
            if (!flag) { 
                deadline = newDeadline; 
                heap.push(it); 
                flag = true; 
            } 
        } 
 
        void PushSoftV6(TNameToState::iterator it, TInstant newDeadline) { 
            PushToHeap<&TState::StateIPv6, &TFamilyState::SoftDeadline, &TFamilyState::NextSoftDeadline, &TFamilyState::InSoftHeap>(SoftHeapIPv6, it, newDeadline); 
        } 
 
        void PushHardV6(TNameToState::iterator it, TInstant newDeadline) { 
            PushToHeap<&TState::StateIPv6, &TFamilyState::HardDeadline, &TFamilyState::NextHardDeadline, &TFamilyState::InHardHeap>(HardHeapIPv6, it, newDeadline); 
        } 
 
        void PushSoftV4(TNameToState::iterator it, TInstant newDeadline) { 
            PushToHeap<&TState::StateIPv4, &TFamilyState::SoftDeadline, &TFamilyState::NextSoftDeadline, &TFamilyState::InSoftHeap>(SoftHeapIPv4, it, newDeadline); 
        } 
 
        void PushHardV4(TNameToState::iterator it, TInstant newDeadline) { 
            PushToHeap<&TState::StateIPv4, &TFamilyState::HardDeadline, &TFamilyState::NextHardDeadline, &TFamilyState::InHardHeap>(HardHeapIPv4, it, newDeadline); 
        } 
 
        void ProcessErrorV6(TNameToState::iterator it, int status, TString errorText) { 
            auto now = TActivationContext::Now(); 
            if (MonCounters) { 
                --*MonCounters->OutgoingInFlightV6; 
                ++*MonCounters->OutgoingErrorsV6; 
            } 
 
            auto& state = it->second.StateIPv6; 
            Y_VERIFY(state.Waiting, "Got error for a state we are not waiting"); 
            state.Waiting = false; 
 
            // When we have a cached positive reply, don't overwrite it with spurious errors 
            const bool serverReplied = TFamilyState::ServerReplied(status); 
            if (!serverReplied && state.ServerReplied() && !state.IsHardExpired(now)) { 
                PushSoftV6(it, now + Options.SoftNegativeExpireTime); 
                if (state.Status == ARES_SUCCESS) { 
                    SendAddrsV6(it); 
                } else { 
                    SendErrorsV6(it, now); 
                } 
                return; 
            } 
 
            state.Status = status; 
            state.ErrorText = std::move(errorText); 
            PushSoftV6(it, now + Options.SoftNegativeExpireTime); 
            if (serverReplied) { 
                // Server actually replied, so keep it cached for longer 
                PushHardV6(it, now + Options.HardPositiveExpireTime); 
            } else { 
                PushHardV6(it, now + Options.HardNegativeExpireTime); 
            } 
 
            SendErrorsV6(it, now); 
        } 
 
        void SendErrorsV6(TNameToState::iterator it, TInstant now) { 
            bool cleaned = false; 
            auto& state = it->second.StateIPv6; 
            while (state.WaitingRequests) { 
                THolder<TIncomingRequest> req(state.WaitingRequests.PopFront()); 
                if (req->Family == AF_UNSPEC && Options.AllowIPv4 && state.RetryUnspec()) { 
                    if (!cleaned) { 
                        CleanupExpired(now); 
                        cleaned = true; 
                    } 
                    EnqueueRequestIPv4(std::move(req), /* isCacheMiss */ true); 
                } else { 
                    ReplyWithError(std::move(req), state.Status, state.ErrorText); 
                } 
            } 
        } 
 
        void ProcessErrorV4(TNameToState::iterator it, int status, TString errorText) { 
            auto now = TActivationContext::Now(); 
            if (MonCounters) { 
                --*MonCounters->OutgoingInFlightV4; 
                ++*MonCounters->OutgoingErrorsV4; 
            } 
 
            auto& state = it->second.StateIPv4; 
            Y_VERIFY(state.Waiting, "Got error for a state we are not waiting"); 
            state.Waiting = false; 
 
            // When we have a cached positive reply, don't overwrite it with spurious errors 
            const bool serverReplied = TFamilyState::ServerReplied(status); 
            if (!serverReplied && state.ServerReplied() && !state.IsHardExpired(now)) { 
                PushSoftV4(it, now + Options.SoftNegativeExpireTime); 
                if (state.Status == ARES_SUCCESS) { 
                    SendAddrsV4(it); 
                } else { 
                    SendErrorsV4(it); 
                } 
                return; 
            } 
 
            state.Status = status; 
            state.ErrorText = std::move(errorText); 
            PushSoftV4(it, now + Options.SoftNegativeExpireTime); 
            if (serverReplied) { 
                // Server actually replied, so keep it cached for longer 
                PushHardV4(it, now + Options.HardPositiveExpireTime); 
            } else { 
                PushHardV4(it, now + Options.HardNegativeExpireTime); 
            } 
 
            SendErrorsV4(it); 
        } 
 
        void SendErrorsV4(TNameToState::iterator it) { 
            auto& state = it->second.StateIPv4; 
            while (state.WaitingRequests) { 
                THolder<TIncomingRequest> req(state.WaitingRequests.PopFront()); 
                ReplyWithError(std::move(req), state.Status, state.ErrorText); 
            } 
        } 
 
        void ProcessAddrsV6(TNameToState::iterator it, TVector<struct in6_addr> addrs) { 
            if (Y_UNLIKELY(addrs.empty())) { 
                // Probably unnecessary: we don't want to deal with empty address lists 
                return ProcessErrorV6(it, ARES_ENODATA, ares_strerror(ARES_ENODATA)); 
            } 
 
            auto now = TActivationContext::Now(); 
            if (MonCounters) { 
                --*MonCounters->OutgoingInFlightV6; 
            } 
 
            auto& state = it->second.StateIPv6; 
            Y_VERIFY(state.Waiting, "Got reply for a state we are not waiting"); 
            state.Waiting = false; 
 
            state.Status = ARES_SUCCESS; 
            it->second.AddrsIPv6 = std::move(addrs); 
            PushSoftV6(it, now + Options.SoftPositiveExpireTime); 
            PushHardV6(it, now + Options.HardPositiveExpireTime); 
 
            SendAddrsV6(it); 
        } 
 
        void SendAddrsV6(TNameToState::iterator it) { 
            auto& state = it->second.StateIPv6; 
            while (state.WaitingRequests) { 
                THolder<TIncomingRequest> req(state.WaitingRequests.PopFront()); 
                ReplyWithAddrs(std::move(req), it->second.AddrsIPv6); 
            } 
        } 
 
        void ProcessAddrsV4(TNameToState::iterator it, TVector<struct in_addr> addrs) { 
            if (Y_UNLIKELY(addrs.empty())) { 
                // Probably unnecessary: we don't want to deal with empty address lists 
                return ProcessErrorV4(it, ARES_ENODATA, ares_strerror(ARES_ENODATA)); 
            } 
 
            auto now = TActivationContext::Now(); 
            if (MonCounters) { 
                --*MonCounters->OutgoingInFlightV4; 
            } 
 
            auto& state = it->second.StateIPv4; 
            Y_VERIFY(state.Waiting, "Got reply for a state we are not waiting"); 
            state.Waiting = false; 
 
            state.Status = ARES_SUCCESS; 
            it->second.AddrsIPv4 = std::move(addrs); 
            PushSoftV4(it, now + Options.SoftPositiveExpireTime); 
            PushHardV4(it, now + Options.HardPositiveExpireTime); 
 
            SendAddrsV4(it); 
        } 
 
        void SendAddrsV4(TNameToState::iterator it) { 
            auto& state = it->second.StateIPv4; 
            while (state.WaitingRequests) { 
                THolder<TIncomingRequest> req(state.WaitingRequests.PopFront()); 
                ReplyWithAddrs(std::move(req), it->second.AddrsIPv4); 
            } 
        } 
 
    private: 
        template<TFamilyState TState::*StateToFamily, 
                 TInstant TFamilyState::* FamilyToDeadline, 
                 TInstant TFamilyState::* FamilyToNextDeadline, 
                 bool TFamilyState::* FamilyToFlag> 
        void DoCleanupExpired(TStateHeap<StateToFamily, FamilyToDeadline>& heap, TInstant now) { 
            while (!heap.empty()) { 
                auto it = heap.top(); 
                auto& family = it->second.*StateToFamily; 
                TInstant& deadline = family.*FamilyToDeadline; 
                if (now <= deadline) { 
                    break; 
                } 
 
                bool& flag = family.*FamilyToFlag; 
                Y_VERIFY(flag); 
                heap.pop(); 
                flag = false; 
 
                TInstant& nextDeadline = family.*FamilyToNextDeadline; 
                if (now < nextDeadline) { 
                    deadline = nextDeadline; 
                    heap.push(it); 
                    flag = true; 
                    continue; 
                } 
 
                // Remove unnecessary items 
                if (!it->second.Needed()) { 
                    NameToState.erase(it); 
                    if (MonCounters) { 
                        *MonCounters->CacheSize = NameToState.size(); 
                    } 
                } 
            } 
        } 
 
        void CleanupExpired(TInstant now) { 
            DoCleanupExpired<&TState::StateIPv6, &TFamilyState::SoftDeadline, &TFamilyState::NextSoftDeadline, &TFamilyState::InSoftHeap>(SoftHeapIPv6, now); 
            DoCleanupExpired<&TState::StateIPv6, &TFamilyState::HardDeadline, &TFamilyState::NextHardDeadline, &TFamilyState::InHardHeap>(HardHeapIPv6, now); 
            DoCleanupExpired<&TState::StateIPv4, &TFamilyState::SoftDeadline, &TFamilyState::NextSoftDeadline, &TFamilyState::InSoftHeap>(SoftHeapIPv4, now); 
            DoCleanupExpired<&TState::StateIPv4, &TFamilyState::HardDeadline, &TFamilyState::NextHardDeadline, &TFamilyState::InHardHeap>(HardHeapIPv4, now); 
        } 
 
        template<class TEvent> 
        void SendError(TActorId replyTo, ui64 cookie, int status, const TString& errorText) { 
            auto reply = MakeHolder<TEvent>(); 
            reply->Status = status; 
            reply->ErrorText = errorText; 
            this->Send(replyTo, reply.Release(), 0, cookie); 
        } 
 
        void ReplyWithError(THolder<TIncomingRequest> req, int status, const TString& errorText) { 
            if (MonCounters) { 
                ++*MonCounters->IncomingErrors; 
            } 
            switch (req->Type) { 
                case EIncomingRequestType::GetHostByName: { 
                    SendError<TEvDns::TEvGetHostByNameResult>(req->Sender, req->Cookie, status, errorText); 
                    break; 
                } 
                case EIncomingRequestType::GetAddr: { 
                    SendError<TEvDns::TEvGetAddrResult>(req->Sender, req->Cookie, status, errorText); 
                    break; 
                } 
            } 
        } 
 
        void ReplyWithAddrs(THolder<TIncomingRequest> req, const TVector<struct in6_addr>& addrs) { 
            switch (req->Type) { 
                case EIncomingRequestType::GetHostByName: { 
                    auto reply = MakeHolder<TEvDns::TEvGetHostByNameResult>(); 
                    reply->AddrsV6 = addrs; 
                    Send(req->Sender, reply.Release(), 0, req->Cookie); 
                    break; 
                } 
                case EIncomingRequestType::GetAddr: { 
                    Y_VERIFY(!addrs.empty()); 
                    auto reply = MakeHolder<TEvDns::TEvGetAddrResult>(); 
                    reply->Addr = addrs.front(); 
                    Send(req->Sender, reply.Release(), 0, req->Cookie); 
                    break; 
                } 
            } 
        } 
 
        void ReplyWithAddrs(THolder<TIncomingRequest> req, const TVector<struct in_addr>& addrs) { 
            switch (req->Type) { 
                case EIncomingRequestType::GetHostByName: { 
                    auto reply = MakeHolder<TEvDns::TEvGetHostByNameResult>(); 
                    reply->AddrsV4 = addrs; 
                    Send(req->Sender, reply.Release(), 0, req->Cookie); 
                    break; 
                } 
                case EIncomingRequestType::GetAddr: { 
                    Y_VERIFY(!addrs.empty()); 
                    auto reply = MakeHolder<TEvDns::TEvGetAddrResult>(); 
                    reply->Addr = addrs.front(); 
                    Send(req->Sender, reply.Release(), 0, req->Cookie); 
                    break; 
                } 
            } 
        } 
 
        void ReplyWithError(THolder<TIncomingRequest> req, int status) { 
            ReplyWithError(std::move(req), status, ares_strerror(status)); 
        } 
 
        void DropPending(TIncomingRequestList& list, int status, const TString& errorText) { 
            while (list) { 
                THolder<TIncomingRequest> req(list.PopFront()); 
                ReplyWithError(std::move(req), status, errorText); 
            } 
        } 
 
        void DropPending(int status, const TString& errorText) { 
            for (auto& [name, state] : NameToState) { 
                DropPending(state.StateIPv6.WaitingRequests, status, errorText); 
                DropPending(state.StateIPv4.WaitingRequests, status, errorText); 
            } 
        } 
 
        void DropPending(int status) { 
            DropPending(status, ares_strerror(status)); 
        } 
 
    private: 
        const TActorId Upstream; 
        const TCachingDnsResolverOptions Options; 
        const THolder<TMonCounters> MonCounters; 
 
        TNameToState NameToState; 
        TStateHeap<&TState::StateIPv6, &TFamilyState::SoftDeadline> SoftHeapIPv6; 
        TStateHeap<&TState::StateIPv6, &TFamilyState::HardDeadline> HardHeapIPv6; 
        TStateHeap<&TState::StateIPv4, &TFamilyState::SoftDeadline> SoftHeapIPv4; 
        TStateHeap<&TState::StateIPv4, &TFamilyState::HardDeadline> HardHeapIPv4; 
 
        THashMap<ui64, TWaitingInfo> WaitingRequests; 
        ui64 LastRequestId = 0; 
    }; 
 
    IActor* CreateCachingDnsResolver(TActorId upstream, TCachingDnsResolverOptions options) { 
        return new TCachingDnsResolver(upstream, std::move(options)); 
    } 
 
} // namespace NDnsResolver 
} // namespace NActors