summaryrefslogtreecommitdiffstats
path: root/yt/cpp/mapreduce/client/client_reader.cpp
blob: 71d9c2df1c392447be0b6551624f1504ccf2cc35 (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
#include "client_reader.h"

#include "structured_table_formats.h"
#include "transaction.h"
#include "transaction_pinger.h"

#include <yt/cpp/mapreduce/common/helpers.h>
#include <yt/cpp/mapreduce/common/retry_lib.h>
#include <yt/cpp/mapreduce/common/retry_request.h>
#include <yt/cpp/mapreduce/common/trace_context.h>
#include <yt/cpp/mapreduce/common/wait_proxy.h>

#include <yt/cpp/mapreduce/interface/config.h>
#include <yt/cpp/mapreduce/interface/raw_client.h>
#include <yt/cpp/mapreduce/interface/tvm.h>

#include <yt/cpp/mapreduce/interface/logging/yt_log.h>

#include <yt/cpp/mapreduce/io/helpers.h>
#include <yt/cpp/mapreduce/io/yamr_table_reader.h>

#include <library/cpp/yson/node/serialize.h>

#include <util/random/random.h>
#include <util/stream/file.h>
#include <util/stream/str.h>
#include <util/string/builder.h>
#include <util/string/cast.h>

namespace NYT {

using ::ToString;

////////////////////////////////////////////////////////////////////////////////

TClientReader::TClientReader(
    const TRichYPath& path,
    const IRawClientPtr& rawClient,
    IClientRetryPolicyPtr clientRetryPolicy,
    ITransactionPingerPtr transactionPinger,
    const TClientContext& context,
    const TTransactionId& transactionId,
    const TFormat& format,
    const TTableReaderOptions& options,
    bool useFormatFromTableAttributes)
    : Path_(path)
    , RawClient_(rawClient)
    , ClientRetryPolicy_(std::move(clientRetryPolicy))
    , Context_(context)
    , ParentTransactionId_(transactionId)
    , Format_(format)
    , Options_(options)
    , ReadTransaction_(nullptr)
    , TraceContext_(NTracing::CreateTraceContext("TClientReader", context.Config))
{
    NTracing::TCurrentTraceContextGuard guard(TraceContext_->Ptr);

    if (options.CreateTransaction_) {
        Y_ABORT_UNLESS(transactionPinger, "Internal error: transactionPinger is null");
        ReadTransaction_ = std::make_unique<TPingableTransaction>(
            RawClient_,
            ClientRetryPolicy_,
            Context_,
            transactionId,
            transactionPinger->GetChildTxPinger(),
            TStartTransactionOptions());
        Path_.Path(Snapshot(
            RawClient_,
            ClientRetryPolicy_,
            ReadTransaction_->GetId(),
            path.Path_));
    }

    if (useFormatFromTableAttributes) {
        auto transactionId2 = ReadTransaction_ ? ReadTransaction_->GetId() : ParentTransactionId_;
        auto newFormat = GetTableFormat(ClientRetryPolicy_, RawClient_, Context_, transactionId2, Path_);
        if (newFormat) {
            Format_.Config = *newFormat;
        }
    }

    TransformYPath();
}

bool TClientReader::Retry(
    const TMaybe<ui32>& rangeIndex,
    const TMaybe<ui64>& rowIndex,
    const std::exception_ptr& error)
{
    NTracing::TCurrentTraceContextGuard guard(TraceContext_->Ptr);

    // We always stop retries if reader is aborted
    if (IAbortableInputStream::IsAbortedError(error)) {
        std::rethrow_exception(error);
    }

    if (CurrentRequestRetryPolicy_) {
        TMaybe<TDuration> backoffDuration;
        try {
            std::rethrow_exception(error);
        } catch (const TErrorResponse& ex) {
            if (!IsRetriable(ex)) {
                throw;
            }
            backoffDuration = CurrentRequestRetryPolicy_->OnRetriableError(ex);
        } catch (const std::exception& ex) {
            if (!IsRetriable(ex)) {
                throw;
            }
            backoffDuration = CurrentRequestRetryPolicy_->OnGenericError(ex);
        } catch (...) {
        }

        if (!backoffDuration) {
            return false;
        }

        NDetail::TWaitProxy::Get()->Sleep(*backoffDuration);
    }

    try {
        CreateRequest(rangeIndex, rowIndex);
        return true;
    } catch (const std::exception& ex) {
        YT_LOG_ERROR("Client reader retry failed: %v",
            ex.what());

        return false;
    }
}

void TClientReader::ResetRetries()
{
    CurrentRequestRetryPolicy_ = nullptr;
}

void TClientReader::Abort()
{
    auto g = Guard(Lock_);
    AbortRequested_ = true;
    if (Input_) {
        Input_->Abort();
    }
}

bool TClientReader::IsAborted() const
{
    auto g = Guard(Lock_);
    if (!Input_) {
        return AbortRequested_;
    }
    return Input_->IsAborted();
}

size_t TClientReader::DoRead(void* buf, size_t len)
{
    NTracing::TCurrentTraceContextGuard guard(TraceContext_->Ptr);

    EnsureInitialized();
    return Input_->Read(buf, len);
}

void TClientReader::TransformYPath()
{
    for (auto& range : Path_.MutableRangesView()) {
        auto& exact = range.Exact_;
        if (IsTrivial(exact)) {
            continue;
        }

        if (exact.RowIndex_) {
            range.LowerLimit(TReadLimit().RowIndex(*exact.RowIndex_));
            range.UpperLimit(TReadLimit().RowIndex(*exact.RowIndex_ + 1));
            exact.RowIndex_.Clear();

        } else if (exact.Key_) {
            range.LowerLimit(TReadLimit().Key(*exact.Key_));

            auto lastPart = TNode::CreateEntity();
            lastPart.Attributes() = TNode()("type", "max");
            exact.Key_->Parts_.push_back(lastPart);

            range.UpperLimit(TReadLimit().Key(*exact.Key_));
            exact.Key_.Clear();
        }
    }
}

void TClientReader::CreateRequest(const TMaybe<ui32>& rangeIndex, const TMaybe<ui64>& rowIndex)
{
    NTracing::TCurrentTraceContextGuard guard(TraceContext_->Ptr);

    if (!CurrentRequestRetryPolicy_) {
        CurrentRequestRetryPolicy_ = ClientRetryPolicy_->CreatePolicyForGenericRequest();
    }

    auto transactionId = (ReadTransaction_ ? ReadTransaction_->GetId() : ParentTransactionId_);

    if (rowIndex.Defined()) {
        auto& ranges = Path_.MutableRanges();
        if (ranges.Empty()) {
            ranges.ConstructInPlace(TVector{TReadRange()});
        } else {
            if (rangeIndex.GetOrElse(0) >= ranges->size()) {
                ythrow yexception()
                    << "range index " << rangeIndex.GetOrElse(0)
                    << " is out of range, input range count is " << ranges->size();
            }
            ranges->erase(ranges->begin(), ranges->begin() + rangeIndex.GetOrElse(0));
        }
        ranges->begin()->LowerLimit(TReadLimit().RowIndex(*rowIndex));
    }

    auto newInput = NDetail::RequestWithRetry<std::unique_ptr<IAbortableInputStream>>(
        CurrentRequestRetryPolicy_,
        [this, &transactionId] (TMutationId /*mutationId*/) {
            return RawClient_->ReadTable(transactionId, Path_, Format_, Options_);
        });

    auto g = Guard(Lock_);
    // NB: Abort could've been called while we are waiting for newInput
    if (AbortRequested_) {
        newInput->Abort();
    }

    Input_ = std::move(newInput);
}

void TClientReader::EnsureInitialized()
{
    if (Input_) {
        return;
    }

    {
        auto g = Guard(Lock_);
        if (AbortRequested_) {
            ythrow TInputStreamAbortedError() << "Stream was aborted";
        }
    }
    CreateRequest();
}

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT