Coverage Report

Created: 2026-04-08 18:35

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