Coverage Report

Created: 2026-07-31 07:36

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