Coverage Report

Created: 2026-08-13 12:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/service/http/action/stream_load.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "service/http/action/stream_load.h"
19
20
// use string iequal
21
#include <event2/buffer.h>
22
#include <event2/http.h>
23
#include <gen_cpp/FrontendService.h>
24
#include <gen_cpp/FrontendService_types.h>
25
#include <gen_cpp/HeartbeatService_types.h>
26
#include <gen_cpp/PaloInternalService_types.h>
27
#include <gen_cpp/PlanNodes_types.h>
28
#include <gen_cpp/Types_types.h>
29
#include <sys/time.h>
30
#include <thrift/protocol/TDebugProtocol.h>
31
32
#include <algorithm>
33
#include <cstdint>
34
#include <cstdlib>
35
#include <ctime>
36
#include <functional>
37
#include <future>
38
#include <sstream>
39
#include <stdexcept>
40
#include <utility>
41
42
#include "cloud/config.h"
43
#include "common/config.h"
44
#include "common/consts.h"
45
#include "common/logging.h"
46
#include "common/metrics/doris_metrics.h"
47
#include "common/metrics/metrics.h"
48
#include "common/status.h"
49
#include "common/utils.h"
50
#include "io/fs/stream_load_pipe.h"
51
#include "load/group_commit/group_commit_mgr.h"
52
#include "load/load_path_mgr.h"
53
#include "load/message_body_sink.h"
54
#include "load/stream_load/new_load_stream_mgr.h"
55
#include "load/stream_load/stream_load_context.h"
56
#include "load/stream_load/stream_load_executor.h"
57
#include "load/stream_load/stream_load_recorder.h"
58
#include "runtime/cluster_info.h"
59
#include "runtime/exec_env.h"
60
#include "service/http/http_channel.h"
61
#include "service/http/http_common.h"
62
#include "service/http/http_headers.h"
63
#include "service/http/http_request.h"
64
#include "service/http/utils.h"
65
#include "storage/storage_engine.h"
66
#include "util/byte_buffer.h"
67
#include "util/client_cache.h"
68
#include "util/load_util.h"
69
#include "util/string_util.h"
70
#include "util/thrift_rpc_helper.h"
71
#include "util/time.h"
72
#include "util/uid_util.h"
73
#include "util/url_coding.h"
74
75
namespace doris {
76
using namespace ErrorCode;
77
78
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(streaming_load_requests_total, MetricUnit::REQUESTS);
79
DEFINE_COUNTER_METRIC_PROTOTYPE_2ARG(streaming_load_duration_ms, MetricUnit::MILLISECONDS);
80
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(streaming_load_current_processing, MetricUnit::REQUESTS);
81
82
bvar::LatencyRecorder g_stream_load_receive_data_latency_ms("stream_load_receive_data_latency_ms");
83
bvar::LatencyRecorder g_stream_load_commit_and_publish_latency_ms("stream_load",
84
                                                                  "commit_and_publish_ms");
85
86
static constexpr size_t MIN_CHUNK_SIZE = 64 * 1024;
87
static constexpr size_t MEBIBYTE = 1024 * 1024;
88
static const std::string CHUNK = "chunked";
89
static const std::string OFF_MODE = "off_mode";
90
static const std::string SYNC_MODE = "sync_mode";
91
static const std::string ASYNC_MODE = "async_mode";
92
93
#ifdef BE_TEST
94
TStreamLoadPutResult k_stream_load_put_result;
95
#endif
96
97
3
StreamLoadAction::StreamLoadAction(ExecEnv* exec_env) : _exec_env(exec_env) {
98
    // Stream load forwards the parsed HTTP credentials to FE load RPCs, where LOAD
99
    // privilege is checked against the actual db/table/txn. A generic BE HTTP
100
    // pre-check cannot model every stream-load variant and would duplicate that
101
    // resource-scoped authorization.
102
3
    _stream_load_entity =
103
3
            DorisMetrics::instance()->metric_registry()->register_entity("stream_load");
104
3
    INT_COUNTER_METRIC_REGISTER(_stream_load_entity, streaming_load_requests_total);
105
3
    INT_COUNTER_METRIC_REGISTER(_stream_load_entity, streaming_load_duration_ms);
106
3
    INT_GAUGE_METRIC_REGISTER(_stream_load_entity, streaming_load_current_processing);
107
3
}
108
109
3
StreamLoadAction::~StreamLoadAction() {
110
3
    DorisMetrics::instance()->metric_registry()->deregister_entity(_stream_load_entity);
111
3
}
112
113
0
void StreamLoadAction::handle(HttpRequest* req) {
114
0
    std::shared_ptr<StreamLoadContext> ctx =
115
0
            std::static_pointer_cast<StreamLoadContext>(req->handler_ctx());
116
0
    if (ctx == nullptr) {
117
0
        return;
118
0
    }
119
120
0
    {
121
0
        std::unique_lock<std::mutex> lock1(ctx->_send_reply_lock);
122
0
        ctx->_can_send_reply = true;
123
0
        ctx->_can_send_reply_cv.notify_all();
124
0
    }
125
126
    // status already set to fail
127
0
    if (ctx->status.ok()) {
128
0
        ctx->status = _handle(ctx, req);
129
0
        if (!ctx->status.ok() && !ctx->status.is<PUBLISH_TIMEOUT>()) {
130
0
            _send_reply(ctx, req);
131
0
        }
132
0
    }
133
0
}
134
135
0
Status StreamLoadAction::_handle(std::shared_ptr<StreamLoadContext> ctx, HttpRequest* req) {
136
0
    if (ctx->body_bytes > 0 && ctx->receive_bytes != ctx->body_bytes) {
137
0
        LOG(WARNING) << "recevie body don't equal with body bytes, body_bytes=" << ctx->body_bytes
138
0
                     << ", receive_bytes=" << ctx->receive_bytes << ", id=" << ctx->id;
139
0
        return Status::Error<ErrorCode::NETWORK_ERROR>("receive body don't equal with body bytes");
140
0
    }
141
142
    // if we use non-streaming, MessageBodyFileSink.finish will close the file
143
0
    RETURN_IF_ERROR(ctx->body_sink->finish());
144
0
    if (!ctx->use_streaming) {
145
        // we need to close file first, then execute_plan_fragment here
146
0
        ctx->body_sink.reset();
147
0
        TPipelineFragmentParamsList mocked;
148
0
        RETURN_IF_ERROR(_exec_env->stream_load_executor()->execute_plan_fragment(
149
0
                ctx, mocked,
150
0
                [req, this](std::shared_ptr<StreamLoadContext> ctx) { _on_finish(ctx, req); }));
151
0
    }
152
153
0
    return Status::OK();
154
0
}
155
156
0
void StreamLoadAction::_on_finish(std::shared_ptr<StreamLoadContext> ctx, HttpRequest* req) {
157
0
    ctx->status = ctx->load_status_future.get();
158
0
    if (ctx->status.ok()) {
159
0
        if (ctx->group_commit) {
160
0
            LOG(INFO) << "skip commit because this is group commit, pipe_id="
161
0
                      << ctx->id.to_string();
162
0
        } else if (ctx->two_phase_commit) {
163
0
            int64_t pre_commit_start_time = MonotonicNanos();
164
0
            ctx->status = _exec_env->stream_load_executor()->pre_commit_txn(ctx.get());
165
0
            ctx->pre_commit_txn_cost_nanos = MonotonicNanos() - pre_commit_start_time;
166
0
        } else {
167
            // If put file success we need commit this load
168
0
            int64_t commit_and_publish_start_time = MonotonicNanos();
169
0
            ctx->status = _exec_env->stream_load_executor()->commit_txn(ctx.get());
170
0
            ctx->commit_and_publish_txn_cost_nanos =
171
0
                    MonotonicNanos() - commit_and_publish_start_time;
172
0
            g_stream_load_commit_and_publish_latency_ms
173
0
                    << ctx->commit_and_publish_txn_cost_nanos / 1000000;
174
0
        }
175
0
    }
176
0
    _send_reply(ctx, req);
177
0
}
178
179
0
void StreamLoadAction::_send_reply(std::shared_ptr<StreamLoadContext> ctx, HttpRequest* req) {
180
0
    std::unique_lock<std::mutex> lock1(ctx->_send_reply_lock);
181
    // 1. _can_send_reply: ensure `send_reply` is invoked only after on_header/handle complete,
182
    //    avoid client errors (e.g., broken pipe).
183
    // 2. _finish_send_reply: Prevent duplicate reply sending; skip reply if HTTP request is canceled
184
    //    due to long import execution time.
185
0
    while (!ctx->_finish_send_reply && !ctx->_can_send_reply) {
186
0
        ctx->_can_send_reply_cv.wait(lock1);
187
0
    }
188
0
    if (ctx->_finish_send_reply) {
189
0
        return;
190
0
    }
191
0
    DCHECK(ctx->_can_send_reply);
192
0
    ctx->_finish_send_reply = true;
193
0
    ctx->_can_send_reply_cv.notify_all();
194
0
    ctx->load_cost_millis = UnixMillis() - ctx->start_millis;
195
196
0
    if (!ctx->status.ok() && !ctx->status.is<PUBLISH_TIMEOUT>()) {
197
0
        LOG(WARNING) << "handle streaming load failed, id=" << ctx->id
198
0
                     << ", errmsg=" << ctx->status;
199
0
        if (ctx->need_rollback) {
200
0
            _exec_env->stream_load_executor()->rollback_txn(ctx.get());
201
0
            ctx->need_rollback = false;
202
0
        }
203
0
        if (ctx->body_sink != nullptr) {
204
0
            ctx->body_sink->cancel(ctx->status.to_string());
205
0
        }
206
0
    }
207
208
0
    auto str = ctx->to_json();
209
    // add new line at end
210
0
    str = str + '\n';
211
212
#ifndef BE_TEST
213
    if (config::enable_stream_load_record || config::enable_stream_load_record_to_audit_log_table) {
214
        if (req->header(HTTP_SKIP_RECORD_TO_AUDIT_LOG_TABLE).empty()) {
215
            str = ctx->prepare_stream_load_record(str);
216
            _save_stream_load_record(ctx, str);
217
        }
218
    }
219
#endif
220
221
0
    HttpChannel::send_reply(req, str);
222
223
0
    LOG(INFO) << "finished to execute stream load. label=" << ctx->label
224
0
              << ", txn_id=" << ctx->txn_id << ", query_id=" << ctx->id
225
0
              << ", load_cost_ms=" << ctx->load_cost_millis << ", receive_data_cost_ms="
226
0
              << (ctx->receive_and_read_data_cost_nanos - ctx->read_data_cost_nanos) / 1000000
227
0
              << ", read_data_cost_ms=" << ctx->read_data_cost_nanos / 1000000
228
0
              << ", write_data_cost_ms=" << ctx->write_data_cost_nanos / 1000000
229
0
              << ", commit_and_publish_txn_cost_ms="
230
0
              << ctx->commit_and_publish_txn_cost_nanos / 1000000
231
0
              << ", number_total_rows=" << ctx->number_total_rows
232
0
              << ", number_loaded_rows=" << ctx->number_loaded_rows
233
0
              << ", receive_bytes=" << ctx->receive_bytes << ", loaded_bytes=" << ctx->loaded_bytes
234
0
              << ", error_url=" << ctx->error_url;
235
236
    // update statistics
237
0
    streaming_load_requests_total->increment(1);
238
0
    streaming_load_duration_ms->increment(ctx->load_cost_millis);
239
0
    if (!ctx->data_saved_path.empty()) {
240
0
        _exec_env->load_path_mgr()->clean_tmp_files(ctx->data_saved_path);
241
0
    }
242
0
}
243
244
0
int StreamLoadAction::on_header(HttpRequest* req) {
245
0
    req->mark_send_reply();
246
247
0
    streaming_load_current_processing->increment(1);
248
249
0
    std::shared_ptr<StreamLoadContext> ctx = std::make_shared<StreamLoadContext>(_exec_env);
250
0
    req->set_handler_ctx(ctx);
251
252
0
    ctx->load_type = TLoadType::MANUL_LOAD;
253
0
    ctx->load_src_type = TLoadSourceType::RAW;
254
255
0
    url_decode(req->param(HTTP_DB_KEY), &ctx->db);
256
0
    url_decode(req->param(HTTP_TABLE_KEY), &ctx->table);
257
0
    ctx->label = req->header(HTTP_LABEL_KEY);
258
0
    ctx->two_phase_commit = req->header(HTTP_TWO_PHASE_COMMIT) == "true";
259
0
    Status st = _handle_group_commit(req, ctx);
260
0
    if (!ctx->group_commit && ctx->label.empty()) {
261
0
        ctx->label = generate_uuid_string();
262
0
    }
263
264
0
    LOG(INFO) << "new income streaming load request." << ctx->brief() << ", db=" << ctx->db
265
0
              << ", tbl=" << ctx->table << ", group_commit=" << ctx->group_commit
266
0
              << ", group_commit_mode=" << ctx->group_commit_mode
267
0
              << ", HTTP headers=" << req->get_all_headers();
268
0
    ctx->begin_receive_and_read_data_cost_nanos = MonotonicNanos();
269
270
0
    if (st.ok()) {
271
0
        st = _on_header(req, ctx);
272
0
        LOG(INFO) << "finished to handle HTTP header, " << ctx->brief();
273
0
    }
274
0
    if (!st.ok()) {
275
0
        ctx->status = std::move(st);
276
0
        {
277
0
            std::unique_lock<std::mutex> lock1(ctx->_send_reply_lock);
278
0
            ctx->_can_send_reply = true;
279
0
            ctx->_can_send_reply_cv.notify_all();
280
0
        }
281
0
        _send_reply(ctx, req);
282
0
        return -1;
283
0
    }
284
0
    return 0;
285
0
}
286
287
2
Status StreamLoadAction::_on_header(HttpRequest* http_req, std::shared_ptr<StreamLoadContext> ctx) {
288
    // auth information
289
2
    if (!parse_basic_auth(*http_req, &ctx->auth)) {
290
0
        LOG(WARNING) << "parse basic authorization failed." << ctx->brief();
291
0
        return Status::NotAuthorized("no valid Basic authorization");
292
0
    }
293
294
    // get format of this put
295
2
    std::string format_str = http_req->header(HTTP_FORMAT_KEY);
296
2
    if (iequal(format_str, BeConsts::CSV_WITH_NAMES) ||
297
2
        iequal(format_str, BeConsts::CSV_WITH_NAMES_AND_TYPES)) {
298
0
        ctx->header_type = format_str;
299
        //treat as CSV
300
0
        format_str = BeConsts::CSV;
301
0
    }
302
2
    LoadUtil::parse_format(format_str, http_req->header(HTTP_COMPRESS_TYPE), &ctx->format,
303
2
                           &ctx->compress_type);
304
2
    if (ctx->format == TFileFormatType::FORMAT_UNKNOWN) {
305
0
        return Status::Error<ErrorCode::DATA_FILE_TYPE_ERROR>("unknown data format, format={}",
306
0
                                                              http_req->header(HTTP_FORMAT_KEY));
307
0
    }
308
309
    // check content length
310
2
    ctx->body_bytes = 0;
311
2
    const auto csv_max_body_mb = config::streaming_load_max_mb;
312
2
    size_t csv_max_body_bytes = csv_max_body_mb * MEBIBYTE;
313
2
    const auto json_max_body_mb = config::streaming_load_json_max_mb;
314
2
    size_t json_max_body_bytes = json_max_body_mb * MEBIBYTE;
315
2
    bool read_json_by_line = false;
316
2
    if (!http_req->header(HTTP_READ_JSON_BY_LINE).empty()) {
317
0
        if (iequal(http_req->header(HTTP_READ_JSON_BY_LINE), "true")) {
318
0
            read_json_by_line = true;
319
0
        }
320
0
    }
321
2
    if (!http_req->header(HttpHeaders::CONTENT_LENGTH).empty()) {
322
2
        try {
323
2
            ctx->body_bytes = std::stol(http_req->header(HttpHeaders::CONTENT_LENGTH));
324
2
        } catch (const std::exception& e) {
325
0
            return Status::InvalidArgument("invalid HTTP header CONTENT_LENGTH={}: {}",
326
0
                                           http_req->header(HttpHeaders::CONTENT_LENGTH), e.what());
327
0
        }
328
        // json max body size
329
2
        if ((ctx->format == TFileFormatType::FORMAT_JSON) &&
330
2
            (ctx->body_bytes > json_max_body_bytes) && !read_json_by_line) {
331
1
            return Status::Error<ErrorCode::EXCEEDED_LIMIT>(
332
1
                    "json body size {} bytes ({:.2f} MiB) exceeds the limit of {} bytes ({} MiB) "
333
1
                    "set by BE's conf streaming_load_json_max_mb. Increase it if you are sure "
334
1
                    "this load is reasonable",
335
1
                    ctx->body_bytes, static_cast<double>(ctx->body_bytes) / MEBIBYTE,
336
1
                    json_max_body_bytes, json_max_body_mb);
337
1
        }
338
        // csv max body size
339
1
        else if (ctx->body_bytes > csv_max_body_bytes) {
340
1
            LOG(WARNING) << "body exceed max size." << ctx->brief();
341
1
            return Status::Error<ErrorCode::EXCEEDED_LIMIT>(
342
1
                    "body size {} bytes ({:.2f} MiB) exceeds the limit of {} bytes ({} MiB) set "
343
1
                    "by BE's conf streaming_load_max_mb. Increase it if you are sure this load is "
344
1
                    "reasonable",
345
1
                    ctx->body_bytes, static_cast<double>(ctx->body_bytes) / MEBIBYTE,
346
1
                    csv_max_body_bytes, csv_max_body_mb);
347
1
        }
348
2
    } else {
349
#ifndef BE_TEST
350
        evhttp_connection_set_max_body_size(
351
                evhttp_request_get_connection(http_req->get_evhttp_request()), csv_max_body_bytes);
352
#endif
353
0
    }
354
355
0
    if (!http_req->header(HttpHeaders::TRANSFER_ENCODING).empty()) {
356
0
        if (http_req->header(HttpHeaders::TRANSFER_ENCODING).find(CHUNK) != std::string::npos) {
357
0
            ctx->is_chunked_transfer = true;
358
0
        }
359
0
    }
360
0
    if (UNLIKELY((http_req->header(HttpHeaders::CONTENT_LENGTH).empty() &&
361
0
                  !ctx->is_chunked_transfer))) {
362
0
        LOG(WARNING) << "content_length is empty and transfer-encoding!=chunked, please set "
363
0
                        "content_length or transfer-encoding=chunked";
364
0
        return Status::InvalidArgument(
365
0
                "content_length is empty and transfer-encoding!=chunked, please set content_length "
366
0
                "or transfer-encoding=chunked");
367
0
    } else if (UNLIKELY(!http_req->header(HttpHeaders::CONTENT_LENGTH).empty() &&
368
0
                        ctx->is_chunked_transfer)) {
369
0
        LOG(WARNING) << "please do not set both content_length and transfer-encoding";
370
0
        return Status::InvalidArgument(
371
0
                "please do not set both content_length and transfer-encoding");
372
0
    }
373
374
0
    if (!http_req->header(HTTP_TIMEOUT).empty()) {
375
0
        ctx->timeout_second = DORIS_TRY(safe_stoi(http_req->header(HTTP_TIMEOUT), HTTP_TIMEOUT));
376
0
    }
377
0
    if (!http_req->header(HTTP_COMMENT).empty()) {
378
0
        ctx->load_comment = http_req->header(HTTP_COMMENT);
379
0
    }
380
    // begin transaction
381
0
    if (!ctx->group_commit) {
382
0
        int64_t begin_txn_start_time = MonotonicNanos();
383
0
        RETURN_IF_ERROR(_exec_env->stream_load_executor()->begin_txn(ctx.get()));
384
0
        ctx->begin_txn_cost_nanos = MonotonicNanos() - begin_txn_start_time;
385
0
        if (ctx->group_commit) {
386
0
            RETURN_IF_ERROR(_check_wal_space(ctx->group_commit_mode, ctx->body_bytes));
387
0
        }
388
0
    }
389
390
    // process put file
391
0
    return _process_put(http_req, ctx);
392
0
}
393
394
0
void StreamLoadAction::on_chunk_data(HttpRequest* req) {
395
0
    std::shared_ptr<StreamLoadContext> ctx =
396
0
            std::static_pointer_cast<StreamLoadContext>(req->handler_ctx());
397
0
    if (ctx == nullptr || !ctx->status.ok()) {
398
0
        return;
399
0
    }
400
401
0
    struct evhttp_request* ev_req = req->get_evhttp_request();
402
0
    auto evbuf = evhttp_request_get_input_buffer(ev_req);
403
404
0
    SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->stream_load_pipe_tracker());
405
406
0
    int64_t start_read_data_time = MonotonicNanos();
407
0
    while (evbuffer_get_length(evbuf) > 0) {
408
0
        ByteBufferPtr bb;
409
0
        Status st = ByteBuffer::allocate(128 * 1024, &bb);
410
0
        if (!st.ok()) {
411
0
            ctx->status = st;
412
0
            return;
413
0
        }
414
0
        auto remove_bytes = evbuffer_remove(evbuf, bb->ptr, bb->capacity);
415
0
        bb->pos = remove_bytes;
416
0
        bb->flip();
417
0
        st = ctx->body_sink->append(bb);
418
0
        if (!st.ok()) {
419
0
            LOG(WARNING) << "append body content failed. errmsg=" << st << ", " << ctx->brief();
420
0
            ctx->status = st;
421
0
            return;
422
0
        }
423
0
        ctx->receive_bytes += remove_bytes;
424
0
    }
425
0
    int64_t read_data_time = MonotonicNanos() - start_read_data_time;
426
0
    int64_t last_receive_and_read_data_cost_nanos = ctx->receive_and_read_data_cost_nanos;
427
0
    ctx->read_data_cost_nanos += read_data_time;
428
0
    ctx->receive_and_read_data_cost_nanos =
429
0
            MonotonicNanos() - ctx->begin_receive_and_read_data_cost_nanos;
430
0
    g_stream_load_receive_data_latency_ms
431
0
            << (ctx->receive_and_read_data_cost_nanos - last_receive_and_read_data_cost_nanos -
432
0
                read_data_time) /
433
0
                       1000000;
434
0
}
435
436
0
void StreamLoadAction::free_handler_ctx(std::shared_ptr<void> param) {
437
0
    std::shared_ptr<StreamLoadContext> ctx = std::static_pointer_cast<StreamLoadContext>(param);
438
0
    if (ctx == nullptr) {
439
0
        return;
440
0
    }
441
    // sender is gone, make receiver know it
442
0
    if (ctx->body_sink != nullptr) {
443
0
        ctx->body_sink->cancel("sender is gone");
444
0
    }
445
    // remove stream load context from stream load manager and the resource will be released
446
0
    ctx->exec_env()->new_load_stream_mgr()->remove(ctx->id);
447
0
    streaming_load_current_processing->increment(-1);
448
0
}
449
450
Status StreamLoadAction::_process_put(HttpRequest* http_req,
451
0
                                      std::shared_ptr<StreamLoadContext> ctx) {
452
    // Now we use stream
453
0
    ctx->use_streaming = LoadUtil::is_format_support_streaming(ctx->format);
454
455
    // put request
456
0
    TStreamLoadPutRequest request;
457
0
    set_request_auth(&request, ctx->auth);
458
0
    request.db = ctx->db;
459
0
    request.tbl = ctx->table;
460
0
    request.txnId = ctx->txn_id;
461
0
    request.formatType = ctx->format;
462
0
    request.__set_compress_type(ctx->compress_type);
463
0
    request.__set_header_type(ctx->header_type);
464
0
    request.__set_loadId(ctx->id.to_thrift());
465
0
    if (ctx->use_streaming) {
466
0
        std::shared_ptr<io::StreamLoadPipe> pipe;
467
0
        if (ctx->is_chunked_transfer) {
468
0
            pipe = std::make_shared<io::StreamLoadPipe>(
469
0
                    io::kMaxPipeBufferedBytes /* max_buffered_bytes */);
470
0
            pipe->set_is_chunked_transfer(true);
471
0
        } else {
472
0
            pipe = std::make_shared<io::StreamLoadPipe>(
473
0
                    io::kMaxPipeBufferedBytes /* max_buffered_bytes */,
474
0
                    MIN_CHUNK_SIZE /* min_chunk_size */, ctx->body_bytes /* total_length */);
475
0
        }
476
0
        request.fileType = TFileType::FILE_STREAM;
477
0
        ctx->body_sink = pipe;
478
0
        ctx->pipe = pipe;
479
0
        RETURN_IF_ERROR(_exec_env->new_load_stream_mgr()->put(ctx->id, ctx));
480
0
    } else {
481
0
        RETURN_IF_ERROR(_data_saved_path(http_req, &request.path, ctx->body_bytes));
482
0
        auto file_sink = std::make_shared<MessageBodyFileSink>(request.path);
483
0
        RETURN_IF_ERROR(file_sink->open());
484
0
        request.__isset.path = true;
485
0
        request.fileType = TFileType::FILE_LOCAL;
486
0
        request.__set_file_size(ctx->body_bytes);
487
0
        ctx->body_sink = file_sink;
488
0
        ctx->data_saved_path = request.path;
489
0
    }
490
0
    if (!http_req->header(HTTP_COLUMNS).empty()) {
491
0
        request.__set_columns(http_req->header(HTTP_COLUMNS));
492
0
    }
493
0
    if (!http_req->header(HTTP_WHERE).empty()) {
494
0
        request.__set_where(http_req->header(HTTP_WHERE));
495
0
    }
496
0
    if (!http_req->header(HTTP_COLUMN_SEPARATOR).empty()) {
497
0
        request.__set_columnSeparator(http_req->header(HTTP_COLUMN_SEPARATOR));
498
0
    }
499
0
    if (!http_req->header(HTTP_LINE_DELIMITER).empty()) {
500
0
        request.__set_line_delimiter(http_req->header(HTTP_LINE_DELIMITER));
501
0
    }
502
0
    if (!http_req->header(HTTP_ENCLOSE).empty() && !http_req->header(HTTP_ENCLOSE).empty()) {
503
0
        const auto& enclose_str = http_req->header(HTTP_ENCLOSE);
504
0
        if (enclose_str.length() != 1) {
505
0
            return Status::InvalidArgument("enclose must be single-char, actually is {}",
506
0
                                           enclose_str);
507
0
        }
508
0
        request.__set_enclose(http_req->header(HTTP_ENCLOSE)[0]);
509
0
    }
510
0
    if (!http_req->header(HTTP_ESCAPE).empty() && !http_req->header(HTTP_ESCAPE).empty()) {
511
0
        const auto& escape_str = http_req->header(HTTP_ESCAPE);
512
0
        if (escape_str.length() != 1) {
513
0
            return Status::InvalidArgument("escape must be single-char, actually is {}",
514
0
                                           escape_str);
515
0
        }
516
0
        request.__set_escape(http_req->header(HTTP_ESCAPE)[0]);
517
0
    }
518
0
    if (!http_req->header(HTTP_PARTITIONS).empty()) {
519
0
        request.__set_partitions(http_req->header(HTTP_PARTITIONS));
520
0
        request.__set_isTempPartition(false);
521
0
        if (!http_req->header(HTTP_TEMP_PARTITIONS).empty()) {
522
0
            return Status::InvalidArgument(
523
0
                    "Can not specify both partitions and temporary partitions");
524
0
        }
525
0
    }
526
0
    if (!http_req->header(HTTP_TEMP_PARTITIONS).empty()) {
527
0
        request.__set_partitions(http_req->header(HTTP_TEMP_PARTITIONS));
528
0
        request.__set_isTempPartition(true);
529
0
        if (!http_req->header(HTTP_PARTITIONS).empty()) {
530
0
            return Status::InvalidArgument(
531
0
                    "Can not specify both partitions and temporary partitions");
532
0
        }
533
0
    }
534
0
    if (!http_req->header(HTTP_NEGATIVE).empty() && http_req->header(HTTP_NEGATIVE) == "true") {
535
0
        request.__set_negative(true);
536
0
    } else {
537
0
        request.__set_negative(false);
538
0
    }
539
0
    bool strictMode = false;
540
0
    if (!http_req->header(HTTP_STRICT_MODE).empty()) {
541
0
        if (iequal(http_req->header(HTTP_STRICT_MODE), "false")) {
542
0
            strictMode = false;
543
0
        } else if (iequal(http_req->header(HTTP_STRICT_MODE), "true")) {
544
0
            strictMode = true;
545
0
        } else {
546
0
            return Status::InvalidArgument("Invalid strict mode format. Must be bool type");
547
0
        }
548
0
        request.__set_strictMode(strictMode);
549
0
    }
550
    // timezone first. if not, try system time_zone
551
0
    if (!http_req->header(HTTP_TIMEZONE).empty()) {
552
0
        request.__set_timezone(http_req->header(HTTP_TIMEZONE));
553
0
    } else if (!http_req->header(HTTP_TIME_ZONE).empty()) {
554
0
        request.__set_timezone(http_req->header(HTTP_TIME_ZONE));
555
0
    }
556
0
    if (!http_req->header(HTTP_EXEC_MEM_LIMIT).empty()) {
557
0
        try {
558
0
            request.__set_execMemLimit(std::stoll(http_req->header(HTTP_EXEC_MEM_LIMIT)));
559
0
        } catch (const std::invalid_argument& e) {
560
0
            return Status::InvalidArgument("Invalid mem limit format, {}", e.what());
561
0
        }
562
0
    }
563
0
    if (!http_req->header(HTTP_JSONPATHS).empty()) {
564
0
        request.__set_jsonpaths(http_req->header(HTTP_JSONPATHS));
565
0
    }
566
0
    if (!http_req->header(HTTP_JSONROOT).empty()) {
567
0
        request.__set_json_root(http_req->header(HTTP_JSONROOT));
568
0
    }
569
0
    if (!http_req->header(HTTP_STRIP_OUTER_ARRAY).empty()) {
570
0
        if (iequal(http_req->header(HTTP_STRIP_OUTER_ARRAY), "true")) {
571
0
            request.__set_strip_outer_array(true);
572
0
        } else {
573
0
            request.__set_strip_outer_array(false);
574
0
        }
575
0
    } else {
576
0
        request.__set_strip_outer_array(false);
577
0
    }
578
579
0
    if (!http_req->header(HTTP_READ_JSON_BY_LINE).empty()) {
580
0
        if (iequal(http_req->header(HTTP_READ_JSON_BY_LINE), "true")) {
581
0
            request.__set_read_json_by_line(true);
582
0
        } else {
583
0
            request.__set_read_json_by_line(false);
584
0
        }
585
0
    } else {
586
0
        request.__set_read_json_by_line(false);
587
0
    }
588
589
0
    if (http_req->header(HTTP_READ_JSON_BY_LINE).empty() &&
590
0
        http_req->header(HTTP_STRIP_OUTER_ARRAY).empty()) {
591
0
        request.__set_read_json_by_line(true);
592
0
        request.__set_strip_outer_array(false);
593
0
    }
594
595
0
    if (!http_req->header(HTTP_NUM_AS_STRING).empty()) {
596
0
        if (iequal(http_req->header(HTTP_NUM_AS_STRING), "true")) {
597
0
            request.__set_num_as_string(true);
598
0
        } else {
599
0
            request.__set_num_as_string(false);
600
0
        }
601
0
    } else {
602
0
        request.__set_num_as_string(false);
603
0
    }
604
0
    if (!http_req->header(HTTP_FUZZY_PARSE).empty()) {
605
0
        if (iequal(http_req->header(HTTP_FUZZY_PARSE), "true")) {
606
0
            request.__set_fuzzy_parse(true);
607
0
        } else {
608
0
            request.__set_fuzzy_parse(false);
609
0
        }
610
0
    } else {
611
0
        request.__set_fuzzy_parse(false);
612
0
    }
613
614
0
    if (!http_req->header(HTTP_FUNCTION_COLUMN + "." + HTTP_SEQUENCE_COL).empty()) {
615
0
        request.__set_sequence_col(
616
0
                http_req->header(HTTP_FUNCTION_COLUMN + "." + HTTP_SEQUENCE_COL));
617
0
    }
618
619
0
    if (!http_req->header(HTTP_SEND_BATCH_PARALLELISM).empty()) {
620
0
        int parallelism = DORIS_TRY(safe_stoi(http_req->header(HTTP_SEND_BATCH_PARALLELISM),
621
0
                                              HTTP_SEND_BATCH_PARALLELISM));
622
0
        request.__set_send_batch_parallelism(parallelism);
623
0
    }
624
625
0
    if (!http_req->header(HTTP_LOAD_TO_SINGLE_TABLET).empty()) {
626
0
        if (iequal(http_req->header(HTTP_LOAD_TO_SINGLE_TABLET), "true")) {
627
0
            request.__set_load_to_single_tablet(true);
628
0
        } else {
629
0
            request.__set_load_to_single_tablet(false);
630
0
        }
631
0
    }
632
633
0
    if (ctx->timeout_second != -1) {
634
0
        request.__set_timeout(ctx->timeout_second);
635
0
    }
636
0
    request.__set_thrift_rpc_timeout_ms(config::thrift_rpc_timeout_ms);
637
0
    TMergeType::type merge_type = TMergeType::APPEND;
638
0
    StringCaseMap<TMergeType::type> merge_type_map = {{"APPEND", TMergeType::APPEND},
639
0
                                                      {"DELETE", TMergeType::DELETE},
640
0
                                                      {"MERGE", TMergeType::MERGE}};
641
0
    if (!http_req->header(HTTP_MERGE_TYPE).empty()) {
642
0
        std::string merge_type_str = http_req->header(HTTP_MERGE_TYPE);
643
0
        auto iter = merge_type_map.find(merge_type_str);
644
0
        if (iter != merge_type_map.end()) {
645
0
            merge_type = iter->second;
646
0
        } else {
647
0
            return Status::InvalidArgument("Invalid merge type {}", merge_type_str);
648
0
        }
649
0
        if (merge_type == TMergeType::MERGE && http_req->header(HTTP_DELETE_CONDITION).empty()) {
650
0
            return Status::InvalidArgument("Excepted DELETE ON clause when merge type is MERGE.");
651
0
        } else if (merge_type != TMergeType::MERGE &&
652
0
                   !http_req->header(HTTP_DELETE_CONDITION).empty()) {
653
0
            return Status::InvalidArgument(
654
0
                    "Not support DELETE ON clause when merge type is not MERGE.");
655
0
        }
656
0
    }
657
0
    request.__set_merge_type(merge_type);
658
0
    if (!http_req->header(HTTP_DELETE_CONDITION).empty()) {
659
0
        request.__set_delete_condition(http_req->header(HTTP_DELETE_CONDITION));
660
0
    }
661
662
0
    if (!http_req->header(HTTP_MAX_FILTER_RATIO).empty()) {
663
0
        ctx->max_filter_ratio = strtod(http_req->header(HTTP_MAX_FILTER_RATIO).c_str(), nullptr);
664
0
        request.__set_max_filter_ratio(ctx->max_filter_ratio);
665
0
    }
666
667
0
    if (!http_req->header(HTTP_HIDDEN_COLUMNS).empty()) {
668
0
        request.__set_hidden_columns(http_req->header(HTTP_HIDDEN_COLUMNS));
669
0
    }
670
0
    if (!http_req->header(HTTP_TRIM_DOUBLE_QUOTES).empty()) {
671
0
        if (iequal(http_req->header(HTTP_TRIM_DOUBLE_QUOTES), "true")) {
672
0
            request.__set_trim_double_quotes(true);
673
0
        } else {
674
0
            request.__set_trim_double_quotes(false);
675
0
        }
676
0
    }
677
0
    if (!http_req->header(HTTP_SKIP_LINES).empty()) {
678
0
        int skip_lines = DORIS_TRY(safe_stoi(http_req->header(HTTP_SKIP_LINES), HTTP_SKIP_LINES));
679
0
        if (skip_lines < 0) {
680
0
            return Status::InvalidArgument("Invalid 'skip_lines': {}", skip_lines);
681
0
        }
682
0
        request.__set_skip_lines(skip_lines);
683
0
    }
684
0
    if (!http_req->header(HTTP_ENABLE_PROFILE).empty()) {
685
0
        if (iequal(http_req->header(HTTP_ENABLE_PROFILE), "true")) {
686
0
            request.__set_enable_profile(true);
687
0
        } else {
688
0
            request.__set_enable_profile(false);
689
0
        }
690
0
    }
691
692
0
    if (!http_req->header(HTTP_UNIQUE_KEY_UPDATE_MODE).empty()) {
693
0
        static const StringCaseMap<TUniqueKeyUpdateMode::type> unique_key_update_mode_map = {
694
0
                {"UPSERT", TUniqueKeyUpdateMode::UPSERT},
695
0
                {"UPDATE_FIXED_COLUMNS", TUniqueKeyUpdateMode::UPDATE_FIXED_COLUMNS},
696
0
                {"UPDATE_FLEXIBLE_COLUMNS", TUniqueKeyUpdateMode::UPDATE_FLEXIBLE_COLUMNS}};
697
0
        std::string unique_key_update_mode_str = http_req->header(HTTP_UNIQUE_KEY_UPDATE_MODE);
698
0
        auto iter = unique_key_update_mode_map.find(unique_key_update_mode_str);
699
0
        if (iter != unique_key_update_mode_map.end()) {
700
0
            TUniqueKeyUpdateMode::type unique_key_update_mode = iter->second;
701
0
            if (unique_key_update_mode == TUniqueKeyUpdateMode::UPDATE_FLEXIBLE_COLUMNS) {
702
                // check constraints when flexible partial update is enabled
703
0
                if (ctx->format != TFileFormatType::FORMAT_JSON) {
704
0
                    return Status::InvalidArgument(
705
0
                            "flexible partial update only support json format as input file "
706
0
                            "currently");
707
0
                }
708
0
                if (!http_req->header(HTTP_FUZZY_PARSE).empty() &&
709
0
                    iequal(http_req->header(HTTP_FUZZY_PARSE), "true")) {
710
0
                    return Status::InvalidArgument(
711
0
                            "Don't support flexible partial update when 'fuzzy_parse' is enabled");
712
0
                }
713
0
                if (!http_req->header(HTTP_COLUMNS).empty()) {
714
0
                    return Status::InvalidArgument(
715
0
                            "Don't support flexible partial update when 'columns' is specified");
716
0
                }
717
0
                if (!http_req->header(HTTP_JSONPATHS).empty()) {
718
0
                    return Status::InvalidArgument(
719
0
                            "Don't support flexible partial update when 'jsonpaths' is specified");
720
0
                }
721
0
                if (!http_req->header(HTTP_HIDDEN_COLUMNS).empty()) {
722
0
                    return Status::InvalidArgument(
723
0
                            "Don't support flexible partial update when 'hidden_columns' is "
724
0
                            "specified");
725
0
                }
726
0
                if (!http_req->header(HTTP_FUNCTION_COLUMN + "." + HTTP_SEQUENCE_COL).empty()) {
727
0
                    return Status::InvalidArgument(
728
0
                            "Don't support flexible partial update when "
729
0
                            "'function_column.sequence_col' is specified");
730
0
                }
731
0
                if (!http_req->header(HTTP_MERGE_TYPE).empty()) {
732
0
                    return Status::InvalidArgument(
733
0
                            "Don't support flexible partial update when "
734
0
                            "'merge_type' is specified");
735
0
                }
736
0
                if (!http_req->header(HTTP_WHERE).empty()) {
737
0
                    return Status::InvalidArgument(
738
0
                            "Don't support flexible partial update when "
739
0
                            "'where' is specified");
740
0
                }
741
0
            }
742
0
            request.__set_unique_key_update_mode(unique_key_update_mode);
743
0
        } else {
744
0
            return Status::InvalidArgument(
745
0
                    "Invalid unique_key_partial_mode {}, must be one of 'UPSERT', "
746
0
                    "'UPDATE_FIXED_COLUMNS' or 'UPDATE_FLEXIBLE_COLUMNS'",
747
0
                    unique_key_update_mode_str);
748
0
        }
749
0
    }
750
751
0
    if (http_req->header(HTTP_UNIQUE_KEY_UPDATE_MODE).empty() &&
752
0
        !http_req->header(HTTP_PARTIAL_COLUMNS).empty()) {
753
        // only consider `partial_columns` parameter when `unique_key_update_mode` is not set
754
0
        if (iequal(http_req->header(HTTP_PARTIAL_COLUMNS), "true")) {
755
0
            request.__set_unique_key_update_mode(TUniqueKeyUpdateMode::UPDATE_FIXED_COLUMNS);
756
            // for backward compatibility
757
0
            request.__set_partial_update(true);
758
0
        }
759
0
    }
760
761
0
    if (!http_req->header(HTTP_PARTIAL_UPDATE_NEW_ROW_POLICY).empty()) {
762
0
        static const std::map<std::string, TPartialUpdateNewRowPolicy::type> policy_map {
763
0
                {"APPEND", TPartialUpdateNewRowPolicy::APPEND},
764
0
                {"ERROR", TPartialUpdateNewRowPolicy::ERROR}};
765
766
0
        auto policy_name = http_req->header(HTTP_PARTIAL_UPDATE_NEW_ROW_POLICY);
767
0
        std::transform(policy_name.begin(), policy_name.end(), policy_name.begin(),
768
0
                       [](unsigned char c) { return std::toupper(c); });
769
0
        auto it = policy_map.find(policy_name);
770
0
        if (it == policy_map.end()) {
771
0
            return Status::InvalidArgument(
772
0
                    "Invalid partial_update_new_key_behavior {}, must be one of {'APPEND', "
773
0
                    "'ERROR'}",
774
0
                    policy_name);
775
0
        }
776
0
        request.__set_partial_update_new_key_policy(it->second);
777
0
    }
778
779
0
    if (!http_req->header(HTTP_MEMTABLE_ON_SINKNODE).empty()) {
780
0
        bool value = iequal(http_req->header(HTTP_MEMTABLE_ON_SINKNODE), "true");
781
0
        request.__set_memtable_on_sink_node(value);
782
0
    }
783
0
    if (!http_req->header(HTTP_LOAD_STREAM_PER_NODE).empty()) {
784
0
        int stream_per_node = DORIS_TRY(
785
0
                safe_stoi(http_req->header(HTTP_LOAD_STREAM_PER_NODE), HTTP_LOAD_STREAM_PER_NODE));
786
0
        request.__set_stream_per_node(stream_per_node);
787
0
    }
788
0
    if (ctx->group_commit) {
789
0
        request.__set_group_commit_mode(ctx->group_commit_mode);
790
0
    }
791
792
    // Keep cloud_cluster for compatibility with old FEs during rolling upgrade. New FEs use
793
    // backend_id below to bind planning to the compute group of the receiving BE.
794
0
    if (!http_req->header(HTTP_COMPUTE_GROUP).empty()) {
795
0
        request.__set_cloud_cluster(http_req->header(HTTP_COMPUTE_GROUP));
796
0
    } else if (!http_req->header(HTTP_CLOUD_CLUSTER).empty()) {
797
0
        request.__set_cloud_cluster(http_req->header(HTTP_CLOUD_CLUSTER));
798
0
    }
799
800
0
    if (_exec_env->cluster_info()->backend_id != 0) {
801
0
        request.__set_backend_id(_exec_env->cluster_info()->backend_id);
802
0
    } else {
803
0
        LOG(WARNING) << "_exec_env->cluster_info not set backend_id";
804
0
    }
805
806
0
    if (!http_req->header(HTTP_EMPTY_FIELD_AS_NULL).empty()) {
807
0
        if (iequal(http_req->header(HTTP_EMPTY_FIELD_AS_NULL), "true")) {
808
0
            request.__set_empty_field_as_null(true);
809
0
        }
810
0
    }
811
812
#ifndef BE_TEST
813
    // plan this load
814
    TNetworkAddress master_addr = _exec_env->cluster_info()->master_fe_addr;
815
    int64_t stream_load_put_start_time = MonotonicNanos();
816
    RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
817
            master_addr.hostname, master_addr.port,
818
            [&request, ctx](FrontendServiceConnection& client) {
819
                client->streamLoadPut(ctx->put_result, request);
820
            }));
821
    ctx->stream_load_put_cost_nanos = MonotonicNanos() - stream_load_put_start_time;
822
#else
823
0
    ctx->put_result = k_stream_load_put_result;
824
0
#endif
825
0
    Status plan_status(Status::create(ctx->put_result.status));
826
0
    if (!plan_status.ok()) {
827
0
        LOG(WARNING) << "plan streaming load failed. errmsg=" << plan_status << ctx->brief();
828
0
        return plan_status;
829
0
    }
830
0
    DCHECK(ctx->put_result.__isset.pipeline_params);
831
0
    ctx->put_result.pipeline_params.query_options.__set_enable_strict_cast(false);
832
0
    ctx->put_result.pipeline_params.query_options.__set_enable_insert_strict(strictMode);
833
0
    if (config::is_cloud_mode() && ctx->two_phase_commit && ctx->is_mow_table()) {
834
0
        return Status::NotSupported("stream load 2pc is unsupported for mow table");
835
0
    }
836
0
    if (iequal(ctx->group_commit_mode, ASYNC_MODE)) {
837
        // FIXME find a way to avoid chunked stream load write large WALs
838
0
        size_t content_length = 0;
839
0
        if (!http_req->header(HttpHeaders::CONTENT_LENGTH).empty()) {
840
0
            try {
841
0
                content_length = std::stol(http_req->header(HttpHeaders::CONTENT_LENGTH));
842
0
            } catch (const std::exception& e) {
843
0
                return Status::InvalidArgument("invalid HTTP header CONTENT_LENGTH={}: {}",
844
0
                                               http_req->header(HttpHeaders::CONTENT_LENGTH),
845
0
                                               e.what());
846
0
            }
847
0
            if (LoadUtil::is_compressed_load(ctx->compress_type, ctx->format)) {
848
0
                content_length *= 3;
849
0
            }
850
0
        }
851
0
        ctx->put_result.pipeline_params.__set_content_length(content_length);
852
0
    }
853
854
0
    VLOG_NOTICE << "params is "
855
0
                << apache::thrift::ThriftDebugString(ctx->put_result.pipeline_params);
856
    // if we not use streaming, we must download total content before we begin
857
    // to process this load
858
0
    if (!ctx->use_streaming) {
859
0
        return Status::OK();
860
0
    }
861
862
0
    TPipelineFragmentParamsList mocked;
863
0
    return _exec_env->stream_load_executor()->execute_plan_fragment(
864
0
            ctx, mocked, [http_req, this](std::shared_ptr<StreamLoadContext> ctx) {
865
0
                _on_finish(ctx, http_req);
866
0
            });
867
0
}
868
869
Status StreamLoadAction::_data_saved_path(HttpRequest* req, std::string* file_path,
870
0
                                          int64_t file_bytes) {
871
0
    std::string prefix;
872
0
    RETURN_IF_ERROR(_exec_env->load_path_mgr()->allocate_dir(req->param(HTTP_DB_KEY), "", &prefix,
873
0
                                                             file_bytes));
874
0
    timeval tv;
875
0
    gettimeofday(&tv, nullptr);
876
0
    struct tm tm;
877
0
    time_t cur_sec = tv.tv_sec;
878
0
    localtime_r(&cur_sec, &tm);
879
0
    char buf[64];
880
0
    strftime(buf, 64, "%Y%m%d%H%M%S", &tm);
881
0
    std::stringstream ss;
882
0
    ss << prefix << "/" << req->param(HTTP_TABLE_KEY) << "." << buf << "." << tv.tv_usec;
883
0
    *file_path = ss.str();
884
0
    return Status::OK();
885
0
}
886
887
void StreamLoadAction::_save_stream_load_record(std::shared_ptr<StreamLoadContext> ctx,
888
0
                                                const std::string& str) {
889
0
    std::shared_ptr<StreamLoadRecorder> stream_load_recorder =
890
0
            ExecEnv::GetInstance()->storage_engine().get_stream_load_recorder();
891
892
0
    if (stream_load_recorder != nullptr) {
893
0
        std::string key =
894
0
                std::to_string(ctx->start_millis + ctx->load_cost_millis) + "_" + ctx->label;
895
0
        auto st = stream_load_recorder->put(key, str);
896
0
        if (st.ok()) {
897
0
            LOG(INFO) << "put stream_load_record rocksdb successfully. label: " << ctx->label
898
0
                      << ", key: " << key;
899
0
        }
900
0
    } else {
901
0
        LOG(WARNING) << "put stream_load_record rocksdb failed. stream_load_recorder is null.";
902
0
    }
903
0
}
904
905
Status StreamLoadAction::_check_wal_space(const std::string& group_commit_mode,
906
0
                                          int64_t content_length) {
907
0
    if (iequal(group_commit_mode, ASYNC_MODE) &&
908
0
        !load_size_smaller_than_wal_limit(content_length)) {
909
0
        std::stringstream ss;
910
0
        ss << "There is no space for group commit stream load async WAL. This stream load "
911
0
              "size is "
912
0
           << content_length
913
0
           << ". WAL dir info: " << ExecEnv::GetInstance()->wal_mgr()->get_wal_dirs_info_string();
914
0
        LOG(WARNING) << ss.str();
915
0
        return Status::Error<EXCEEDED_LIMIT>(ss.str());
916
0
    }
917
0
    return Status::OK();
918
0
}
919
920
Status StreamLoadAction::_can_group_commit(HttpRequest* req, std::shared_ptr<StreamLoadContext> ctx,
921
                                           std::string& group_commit_header,
922
0
                                           bool& can_group_commit) {
923
0
    int64_t content_length = 0;
924
0
    const auto& content_length_str = req->header(HttpHeaders::CONTENT_LENGTH);
925
0
    if (!content_length_str.empty()) {
926
0
        try {
927
0
            content_length = std::stoll(content_length_str);
928
0
        } catch (const std::exception& e) {
929
0
            return Status::InvalidArgument("invalid HTTP header CONTENT_LENGTH={}: {}",
930
0
                                           content_length_str, e.what());
931
0
        }
932
0
    }
933
0
    if (content_length < 0) {
934
0
        std::stringstream ss;
935
0
        ss << "This stream load content length <0 (" << content_length
936
0
           << "), please check your content length.";
937
0
        LOG(WARNING) << ss.str();
938
0
        return Status::InvalidArgument(ss.str());
939
0
    }
940
0
    auto is_chunk = !req->header(HttpHeaders::TRANSFER_ENCODING).empty() &&
941
0
                    req->header(HttpHeaders::TRANSFER_ENCODING).find(CHUNK) != std::string::npos;
942
0
    if (content_length == 0 && !is_chunk) {
943
        // off_mode and empty
944
0
        can_group_commit = false;
945
0
        return Status::OK();
946
0
    }
947
0
    if (is_chunk) {
948
0
        ctx->label = "";
949
0
    }
950
951
0
    auto partial_columns = !req->header(HTTP_PARTIAL_COLUMNS).empty() &&
952
0
                           iequal(req->header(HTTP_PARTIAL_COLUMNS), "true");
953
0
    auto temp_partitions = !req->header(HTTP_TEMP_PARTITIONS).empty();
954
0
    auto partitions = !req->header(HTTP_PARTITIONS).empty();
955
0
    auto update_mode =
956
0
            !req->header(HTTP_UNIQUE_KEY_UPDATE_MODE).empty() &&
957
0
            (iequal(req->header(HTTP_UNIQUE_KEY_UPDATE_MODE), "UPDATE_FIXED_COLUMNS") ||
958
0
             iequal(req->header(HTTP_UNIQUE_KEY_UPDATE_MODE), "UPDATE_FLEXIBLE_COLUMNS"));
959
0
    if (!partial_columns && !partitions && !temp_partitions && !ctx->two_phase_commit &&
960
0
        !update_mode) {
961
0
        if (!config::wait_internal_group_commit_finish && !group_commit_header.empty() &&
962
0
            !ctx->label.empty()) {
963
0
            return Status::InvalidArgument("label and group_commit can't be set at the same time");
964
0
        }
965
0
        RETURN_IF_ERROR(_check_wal_space(group_commit_header, content_length));
966
0
        can_group_commit = true;
967
0
    }
968
0
    return Status::OK();
969
0
}
970
971
Status StreamLoadAction::_handle_group_commit(HttpRequest* req,
972
0
                                              std::shared_ptr<StreamLoadContext> ctx) {
973
0
    std::string group_commit_header = req->header(HTTP_GROUP_COMMIT);
974
0
    if (!group_commit_header.empty() && !iequal(group_commit_header, SYNC_MODE) &&
975
0
        !iequal(group_commit_header, ASYNC_MODE) && !iequal(group_commit_header, OFF_MODE)) {
976
0
        return Status::InvalidArgument(
977
0
                "group_commit can only be [async_mode, sync_mode, off_mode]");
978
0
    }
979
0
    if (config::wait_internal_group_commit_finish) {
980
0
        group_commit_header = SYNC_MODE;
981
0
    }
982
983
    // if group_commit_header is off_mode, we will not use group commit
984
0
    if (iequal(group_commit_header, OFF_MODE)) {
985
0
        ctx->group_commit_mode = OFF_MODE;
986
0
        ctx->group_commit = false;
987
0
        return Status::OK();
988
0
    }
989
0
    bool can_group_commit = false;
990
0
    RETURN_IF_ERROR(_can_group_commit(req, ctx, group_commit_header, can_group_commit));
991
0
    if (!can_group_commit) {
992
0
        ctx->group_commit_mode = OFF_MODE;
993
0
        ctx->group_commit = false;
994
0
    } else {
995
0
        if (!group_commit_header.empty()) {
996
0
            ctx->group_commit_mode = group_commit_header;
997
0
            ctx->group_commit = true;
998
0
        } else {
999
            // use table property to decide group commit or not
1000
0
            ctx->group_commit_mode = "";
1001
0
            ctx->group_commit = false;
1002
0
        }
1003
0
    }
1004
0
    return Status::OK();
1005
0
}
1006
1007
} // namespace doris