aboutsummaryrefslogtreecommitdiffstats
path: root/yt/cpp/mapreduce/raw_client/raw_batch_request.cpp
blob: 4e60959059071fbca8ae4f6f573014243b7102a1 (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
#include "raw_batch_request.h"

#include "raw_requests.h"
#include "rpc_parameters_serialization.h"

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

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

#include <yt/cpp/mapreduce/interface/client.h>
#include <yt/cpp/mapreduce/interface/errors.h>
#include <yt/cpp/mapreduce/interface/serialize.h>

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

#include <yt/cpp/mapreduce/http/context.h>
#include <yt/cpp/mapreduce/http/retry_request.h>

#include <util/generic/guid.h>
#include <util/string/builder.h>

#include <exception>

namespace NYT::NDetail::NRawClient {

using NThreading::TFuture;
using NThreading::TPromise;
using NThreading::NewPromise;

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

static TString RequestInfo(const TNode& request)
{
    return ::TStringBuilder()
        << request["command"].AsString() << ' ' << NodeToYsonString(request["parameters"]);
}

static void EnsureNothing(const TMaybe<TNode>& node)
{
    Y_ENSURE(!node, "Internal error: expected to have no response, but got response of type " << node->GetType());
}

static void EnsureSomething(const TMaybe<TNode>& node)
{
    Y_ENSURE(node, "Internal error: expected to have response of any type, but got no response.");
}

static void EnsureType(const TNode& node, TNode::EType type)
{
    Y_ENSURE(node.GetType() == type, "Internal error: unexpected response type. "
        << "Expected: " << type << ", actual: " << node.GetType());
}

static void EnsureType(const TMaybe<TNode>& node, TNode::EType type)
{
    Y_ENSURE(node, "Internal error: expected to have response of type " << type << ", but got no response.");
    EnsureType(*node, type);
}

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

template <typename TReturnType>
class TResponseParserBase
    : public TRawBatchRequest::IResponseItemParser
{
public:
    using TFutureResult = TFuture<TReturnType>;

public:
    TResponseParserBase()
        : Result_(NewPromise<TReturnType>())
    { }

    void SetException(std::exception_ptr e) override
    {
        Result_.SetException(std::move(e));
    }

    TFuture<TReturnType> GetFuture()
    {
        return Result_.GetFuture();
    }

protected:
    TPromise<TReturnType> Result_;
};

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


class TGetResponseParser
    : public TResponseParserBase<TNode>
{
public:
    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureSomething(node);
        Result_.SetValue(std::move(*node));
    }
};

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

class TVoidResponseParser
    : public TResponseParserBase<void>
{
public:
    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureNothing(node);
        Result_.SetValue();
    }
};

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

class TListResponseParser
    : public TResponseParserBase<TNode::TListType>
{
public:
    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureType(node, TNode::List);
        Result_.SetValue(std::move(node->AsList()));
    }
};

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

class TExistsResponseParser
    : public TResponseParserBase<bool>
{
public:
    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureType(node, TNode::Bool);
        Result_.SetValue(std::move(node->AsBool()));
    }
};

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

class TGuidResponseParser
    : public TResponseParserBase<TGUID>
{
public:
    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureType(node, TNode::String);
        Result_.SetValue(GetGuid(node->AsString()));
    }
};

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

class TCanonizeYPathResponseParser
    : public TResponseParserBase<TRichYPath>
{
public:
    explicit TCanonizeYPathResponseParser(TString pathPrefix, const TRichYPath& original)
        : OriginalNode_(PathToNode(original))
        , PathPrefix_(std::move(pathPrefix))
    { }

    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureType(node, TNode::String);

        for (const auto& item : OriginalNode_.GetAttributes().AsMap()) {
            node->Attributes()[item.first] = item.second;
        }
        TRichYPath result;
        Deserialize(result, *node);
        result.Path_ = AddPathPrefix(result.Path_, PathPrefix_);
        Result_.SetValue(result);
    }

private:
    TNode OriginalNode_;
    TString PathPrefix_;
};

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

class TGetOperationResponseParser
    : public TResponseParserBase<TOperationAttributes>
{
public:
    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureType(node, TNode::Map);
        Result_.SetValue(ParseOperationAttributes(*node));
    }
};

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

class TTableColumnarStatisticsParser
    : public TResponseParserBase<TVector<TTableColumnarStatistics>>
{
public:
    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureType(node, TNode::List);
        TVector<TTableColumnarStatistics> statistics;
        Deserialize(statistics, *node);
        Result_.SetValue(std::move(statistics));
    }
};

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

class TTablePartitionsParser
    : public TResponseParserBase<TMultiTablePartitions>
{
public:
    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureType(node, TNode::Map);
        TMultiTablePartitions partitions;
        Deserialize(partitions, *node);
        Result_.SetValue(std::move(partitions));
    }
};

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

class TGetFileFromCacheParser
    : public TResponseParserBase<TMaybe<TYPath>>
{
public:
    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureType(node, TNode::String);
        if (node->AsString().empty()) {
            Result_.SetValue(Nothing());
        } else {
            Result_.SetValue(node->AsString());
        }
    }
};

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

class TYPathParser
    : public TResponseParserBase<TYPath>
{
public:
    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureType(node, TNode::String);
        Result_.SetValue(node->AsString());
    }
};

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

class TCheckPermissionParser
    : public TResponseParserBase<TCheckPermissionResponse>
{
public:
    void SetResponse(TMaybe<TNode> node) override
    {
        EnsureType(node, TNode::Map);
        Result_.SetValue(ParseCheckPermissionResponse(*node));
    }
};

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

TRawBatchRequest::TBatchItem::TBatchItem(TNode parameters, ::TIntrusivePtr<IResponseItemParser> responseParser)
    : Parameters(std::move(parameters))
    , ResponseParser(std::move(responseParser))
    , NextTry()
{ }

TRawBatchRequest::TBatchItem::TBatchItem(const TBatchItem& batchItem, TInstant nextTry)
    : Parameters(batchItem.Parameters)
    , ResponseParser(batchItem.ResponseParser)
    , NextTry(nextTry)
{ }

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

TRawBatchRequest::TRawBatchRequest(const TConfigPtr& config)
    : Config_(config)
{ }

TRawBatchRequest::~TRawBatchRequest() = default;

bool TRawBatchRequest::IsExecuted() const
{
    return Executed_;
}

void TRawBatchRequest::MarkExecuted()
{
    Executed_ = true;
}

template <typename TResponseParser>
typename TResponseParser::TFutureResult TRawBatchRequest::AddRequest(
    const TString& command,
    TNode parameters,
    TMaybe<TNode> input)
{
    return AddRequest(command, parameters, input, MakeIntrusive<TResponseParser>());
}

template <typename TResponseParser>
typename TResponseParser::TFutureResult TRawBatchRequest::AddRequest(
    const TString& command,
    TNode parameters,
    TMaybe<TNode> input,
    ::TIntrusivePtr<TResponseParser> parser)
{
    Y_ENSURE(!Executed_, "Cannot add request: batch request is already executed");
    TNode request;
    request["command"] = command;
    request["parameters"] = std::move(parameters);
    if (input) {
        request["input"] = std::move(*input);
    }
    BatchItemList_.emplace_back(std::move(request), parser);
    return parser->GetFuture();
}

void TRawBatchRequest::AddRequest(TBatchItem batchItem)
{
    Y_ENSURE(!Executed_, "Cannot add request: batch request is already executed");
    BatchItemList_.push_back(batchItem);
}

TFuture<TNodeId> TRawBatchRequest::Create(
    const TTransactionId& transaction,
    const TYPath& path,
    ENodeType type,
    const TCreateOptions& options)
{
    return AddRequest<TGuidResponseParser>(
        "create",
        SerializeParamsForCreate(transaction, Config_->Prefix, path, type, options),
        Nothing());
}

TFuture<void> TRawBatchRequest::Remove(
    const TTransactionId& transaction,
    const TYPath& path,
    const TRemoveOptions& options)
{
    return AddRequest<TVoidResponseParser>(
        "remove",
        SerializeParamsForRemove(transaction, Config_->Prefix, path, options),
        Nothing());
}

TFuture<bool> TRawBatchRequest::Exists(
    const TTransactionId& transaction,
    const TYPath& path,
    const TExistsOptions& options)
{
    return AddRequest<TExistsResponseParser>(
        "exists",
        SerializeParamsForExists(transaction, Config_->Prefix, path, options),
        Nothing());
}

TFuture<TNode> TRawBatchRequest::Get(
    const TTransactionId& transaction,
    const TYPath& path,
    const TGetOptions& options)
{
    return AddRequest<TGetResponseParser>(
        "get",
        SerializeParamsForGet(transaction, Config_->Prefix, path, options),
        Nothing());
}

TFuture<void> TRawBatchRequest::Set(
    const TTransactionId& transaction,
    const TYPath& path,
    const TNode& node,
    const TSetOptions& options)
{
    return AddRequest<TVoidResponseParser>(
        "set",
        SerializeParamsForSet(transaction, Config_->Prefix, path, options),
        node);
}

TFuture<TNode::TListType> TRawBatchRequest::List(
    const TTransactionId& transaction,
    const TYPath& path,
    const TListOptions& options)
{
    return AddRequest<TListResponseParser>(
        "list",
        SerializeParamsForList(transaction, Config_->Prefix, path, options),
        Nothing());
}

TFuture<TNodeId> TRawBatchRequest::Copy(
    const TTransactionId& transaction,
    const TYPath& sourcePath,
    const TYPath& destinationPath,
    const TCopyOptions& options)
{
    return AddRequest<TGuidResponseParser>(
        "copy",
        SerializeParamsForCopy(transaction, Config_->Prefix, sourcePath, destinationPath, options),
        Nothing());
}

TFuture<TNodeId> TRawBatchRequest::Move(
    const TTransactionId& transaction,
    const TYPath& sourcePath,
    const TYPath& destinationPath,
    const TMoveOptions& options)
{
    return AddRequest<TGuidResponseParser>(
        "move",
        SerializeParamsForMove(transaction, Config_->Prefix, sourcePath, destinationPath, options),
        Nothing());
}

TFuture<TNodeId> TRawBatchRequest::Link(
    const TTransactionId& transaction,
    const TYPath& targetPath,
    const TYPath& linkPath,
    const TLinkOptions& options)
{
    return AddRequest<TGuidResponseParser>(
        "link",
        SerializeParamsForLink(transaction, Config_->Prefix, targetPath, linkPath, options),
        Nothing());
}

TFuture<TLockId> TRawBatchRequest::Lock(
    const TTransactionId& transaction,
    const TYPath& path,
    ELockMode mode,
    const TLockOptions& options)
{
    return AddRequest<TGuidResponseParser>(
        "lock",
        SerializeParamsForLock(transaction, Config_->Prefix, path, mode, options),
        Nothing());
}

TFuture<void> TRawBatchRequest::Unlock(
    const TTransactionId& transaction,
    const TYPath& path,
    const TUnlockOptions& options)
{
    return AddRequest<TVoidResponseParser>(
        "unlock",
        SerializeParamsForUnlock(transaction, Config_->Prefix, path, options),
        Nothing());
}

TFuture<TMaybe<TYPath>> TRawBatchRequest::GetFileFromCache(
    const TTransactionId& transactionId,
    const TString& md5Signature,
    const TYPath& cachePath,
    const TGetFileFromCacheOptions& options)
{
    return AddRequest<TGetFileFromCacheParser>(
        "get_file_from_cache",
        SerializeParamsForGetFileFromCache(transactionId, md5Signature, cachePath, options),
        Nothing());
}

TFuture<TYPath> TRawBatchRequest::PutFileToCache(
    const TTransactionId& transactionId,
    const TYPath& filePath,
    const TString& md5Signature,
    const TYPath& cachePath,
    const TPutFileToCacheOptions& options)
{
    return AddRequest<TYPathParser>(
        "put_file_to_cache",
        SerializeParamsForPutFileToCache(transactionId, Config_->Prefix, filePath, md5Signature, cachePath, options),
        Nothing());
}

TFuture<TCheckPermissionResponse> TRawBatchRequest::CheckPermission(
    const TString& user,
    EPermission permission,
    const TYPath& path,
    const TCheckPermissionOptions& options)
{
    return AddRequest<TCheckPermissionParser>(
        "check_permission",
        SerializeParamsForCheckPermission(user, permission, Config_->Prefix, path, options),
        Nothing());
}

TFuture<TOperationAttributes> TRawBatchRequest::GetOperation(
    const TOperationId& operationId,
    const TGetOperationOptions& options)
{
    return AddRequest<TGetOperationResponseParser>(
        "get_operation",
        SerializeParamsForGetOperation(operationId, options),
        Nothing());
}

TFuture<void> TRawBatchRequest::AbortOperation(const TOperationId& operationId)
{
    return AddRequest<TVoidResponseParser>(
        "abort_op",
        SerializeParamsForAbortOperation(operationId),
        Nothing());
}

TFuture<void> TRawBatchRequest::CompleteOperation(const TOperationId& operationId)
{
    return AddRequest<TVoidResponseParser>(
        "complete_op",
        SerializeParamsForCompleteOperation(operationId),
        Nothing());
}
TFuture<void> TRawBatchRequest::SuspendOperation(
    const TOperationId& operationId,
    const TSuspendOperationOptions& options)
{
    return AddRequest<TVoidResponseParser>(
        "suspend_operation",
        SerializeParamsForSuspendOperation(operationId, options),
        Nothing());
}
TFuture<void> TRawBatchRequest::ResumeOperation(
    const TOperationId& operationId,
    const TResumeOperationOptions& options)
{
    return AddRequest<TVoidResponseParser>(
        "resume_operation",
        SerializeParamsForResumeOperation(operationId, options),
        Nothing());
}

TFuture<void> TRawBatchRequest::UpdateOperationParameters(
    const TOperationId& operationId,
    const TUpdateOperationParametersOptions& options)
{
    return AddRequest<TVoidResponseParser>(
        "update_op_parameters",
        SerializeParamsForUpdateOperationParameters(operationId, options),
        Nothing());
}

TFuture<TRichYPath> TRawBatchRequest::CanonizeYPath(const TRichYPath& path)
{
    TRichYPath result = path;
    // Out of the symbols in the canonization branch below, only '<' can appear in the beggining of a valid rich YPath.
    if (!result.Path_.StartsWith("<")) {
        result.Path_ = AddPathPrefix(result.Path_, Config_->Prefix);
    }

    if (result.Path_.find_first_of("<>{}[]") != TString::npos) {
        return AddRequest<TCanonizeYPathResponseParser>(
            "parse_ypath",
            SerializeParamsForParseYPath(result),
            Nothing(),
            MakeIntrusive<TCanonizeYPathResponseParser>(Config_->Prefix, result));
    }
    return NThreading::MakeFuture(result);
}

TFuture<TVector<TTableColumnarStatistics>> TRawBatchRequest::GetTableColumnarStatistics(
    const TTransactionId& transaction,
    const TVector<TRichYPath>& paths,
    const TGetTableColumnarStatisticsOptions& options)
{
    return AddRequest<TTableColumnarStatisticsParser>(
        "get_table_columnar_statistics",
        SerializeParamsForGetTableColumnarStatistics(transaction, paths, options),
        Nothing());
}

TFuture<TMultiTablePartitions> TRawBatchRequest::GetTablePartitions(
    const TTransactionId& transaction,
    const TVector<TRichYPath>& paths,
    const TGetTablePartitionsOptions& options)
{
    return AddRequest<TTablePartitionsParser>(
        "partition_tables",
        SerializeParamsForGetTablePartitions(transaction, paths, options),
        Nothing());
}

void TRawBatchRequest::FillParameterList(size_t maxSize, TNode* result, TInstant* nextTry) const
{
    Y_ABORT_UNLESS(result);
    Y_ABORT_UNLESS(nextTry);

    *nextTry = TInstant();
    maxSize = Min(maxSize, BatchItemList_.size());
    *result = TNode::CreateList();
    for (size_t i = 0; i < maxSize; ++i) {
        YT_LOG_DEBUG("ExecuteBatch preparing: %v",
            RequestInfo(BatchItemList_[i].Parameters));

        result->Add(BatchItemList_[i].Parameters);
        if (BatchItemList_[i].NextTry > *nextTry) {
            *nextTry = BatchItemList_[i].NextTry;
        }
    }
}

void TRawBatchRequest::ParseResponse(
    const TResponseInfo& requestResult,
    const IRequestRetryPolicyPtr& retryPolicy,
    TRawBatchRequest* retryBatch,
    TInstant now)
{
    TNode node = NodeFromYsonString(requestResult.Response);
    return ParseResponse(node, requestResult.RequestId, retryPolicy, retryBatch, now);
}

void TRawBatchRequest::ParseResponse(
    TNode node,
    const TString& requestId,
    const IRequestRetryPolicyPtr& retryPolicy,
    TRawBatchRequest* retryBatch,
    TInstant now)
{
    Y_ABORT_UNLESS(retryBatch);

    EnsureType(node, TNode::List);
    auto& responseList = node.AsList();
    const auto size = responseList.size();
    Y_ENSURE(size <= BatchItemList_.size(),
        "Size of server response exceeds size of batch request;"
        " size of batch: " << BatchItemList_.size() <<
        " size of server response: " << size << '.');

    for (size_t i = 0; i != size; ++i) {
        try {
            EnsureType(responseList[i], TNode::Map);
            auto& responseNode = responseList[i].AsMap();
            const auto outputIt = responseNode.find("output");
            if (outputIt != responseNode.end()) {
                BatchItemList_[i].ResponseParser->SetResponse(std::move(outputIt->second));
            } else {
                const auto errorIt = responseNode.find("error");
                if (errorIt == responseNode.end()) {
                    BatchItemList_[i].ResponseParser->SetResponse(Nothing());
                } else {
                    TErrorResponse error(400, requestId);
                    error.SetError(TYtError(errorIt->second));
                    if (auto curInterval = IsRetriable(error) ? retryPolicy->OnRetriableError(error) : Nothing()) {
                        YT_LOG_INFO(
                            "Batch subrequest (%s) failed, will retry, error: %s",
                            RequestInfo(BatchItemList_[i].Parameters),
                            error.what());
                        retryBatch->AddRequest(TBatchItem(BatchItemList_[i], now + *curInterval));
                    } else {
                        YT_LOG_ERROR(
                            "Batch subrequest (%s) failed, error: %s",
                            RequestInfo(BatchItemList_[i].Parameters),
                            error.what());
                        BatchItemList_[i].ResponseParser->SetException(std::make_exception_ptr(error));
                    }
                }
            }
        } catch (const std::exception& e) {
            // We don't expect other exceptions, so we don't catch (...)
            BatchItemList_[i].ResponseParser->SetException(std::current_exception());
        }
    }
    BatchItemList_.erase(BatchItemList_.begin(), BatchItemList_.begin() + size);
}

void TRawBatchRequest::SetErrorResult(std::exception_ptr e) const
{
    for (const auto& batchItem : BatchItemList_) {
        batchItem.ResponseParser->SetException(e);
    }
}

size_t TRawBatchRequest::BatchSize() const
{
    return BatchItemList_.size();
}

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

} // namespace NYT::NDetail::NRawClient