aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/udfs/common/streaming/streaming_udf.cpp
blob: bd01935321eefe9d4da32d054bb3ac4bc5947d4f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
#include <yql/essentials/public/udf/udf_value.h>
#include <yql/essentials/public/udf/udf_registrator.h>
#include <yql/essentials/public/udf/udf_type_builder.h>
#include <yql/essentials/public/udf/udf_value_builder.h>
#include <yql/essentials/public/udf/udf_terminator.h>

#include <util/generic/buffer.h>
#include <util/generic/mem_copy.h>
#include <util/generic/maybe.h>
#include <util/generic/ptr.h>
#include <util/string/builder.h>
#include <util/stream/mem.h>
#include <library/cpp/deprecated/kmp/kmp.h>
#include <util/string/strip.h>
#include <util/system/condvar.h>
#include <util/system/shellcommand.h>
#include <util/system/tempfile.h>
#include <util/system/sysstat.h>

#include <functional>

using namespace NKikimr;
using namespace NUdf;

namespace {
    // Cyclic Read-Write buffer.
    // Not thread safe, synchronization between reader and writer threads
    // should be managed externally.
    class TCyclicRWBuffer {
    public:
        TCyclicRWBuffer(size_t capacity)
            : Buffer(capacity)
            , Finished(false)
            , DataStart(0)
            , DataSize(0)
        {
            Buffer.Resize(capacity);
        }

        bool IsFinished() const {
            return Finished;
        }

        void Finish() {
            Finished = true;
        }

        bool HasData() const {
            return DataSize > 0;
        }

        size_t GetDataSize() const {
            return DataSize;
        }

        void GetData(const char*& ptr, size_t& len) const {
            size_t readSize = GetDataRegionSize(DataStart, DataSize);
            ptr = Buffer.Data() + DataStart;
            len = readSize;
        }

        void CommitRead(size_t len) {
            Y_DEBUG_ABORT_UNLESS(len <= GetDataRegionSize(DataStart, DataSize));

            DataStart = GetBufferPosition(DataStart + len);
            DataSize -= len;
        }

        bool CanWrite() const {
            return WriteSize() > 0;
        }

        size_t WriteSize() const {
            return Buffer.Size() - DataSize;
        }

        size_t Write(const char*& ptr, size_t& len) {
            if (!CanWrite()) {
                return 0;
            }

            size_t bytesWritten = 0;
            size_t bytesToWrite = std::min(len, WriteSize());
            while (bytesToWrite > 0) {
                size_t writeStart = GetWriteStart();
                size_t writeSize = GetDataRegionSize(writeStart, bytesToWrite);

                MemCopy(Data(writeStart), ptr, writeSize);

                DataSize += writeSize;
                bytesWritten += writeSize;
                bytesToWrite -= writeSize;

                ptr += writeSize;
                len -= writeSize;
            }

            return bytesWritten;
        }

        size_t Write(IZeroCopyInput& input) {
            const void* ptr;
            size_t dataLen = input.Next(&ptr, WriteSize());
            const char* dataPtr = reinterpret_cast<const char*>(ptr);
            return Write(dataPtr, dataLen);
        }

    private:
        size_t GetBufferPosition(size_t pos) const {
            return pos % Buffer.Size();
        }

        size_t GetDataRegionSize(size_t start, size_t size) const {
            Y_DEBUG_ABORT_UNLESS(start < Buffer.Size());

            return std::min(size, Buffer.Size() - start);
        }

        size_t GetWriteStart() const {
            return GetBufferPosition(DataStart + DataSize);
        }

        char* Data(size_t pos) {
            Y_DEBUG_ABORT_UNLESS(pos < Buffer.Size());

            return (Buffer.Data() + pos);
        }

    private:
        TBuffer Buffer;

        bool Finished;

        size_t DataStart;
        size_t DataSize;
    };

    struct TStreamingParams {
    public:
        const size_t DefaultProcessPollLatencyMs = 5 * 1000;          // 5 seconds
        const size_t DefaultInputBufferSizeBytes = 4 * 1024 * 1024;   // 4MB
        const size_t DefaultOutputBufferSizeBytes = 16 * 1024 * 1024; // 16MB
        const char* DefaultInputDelimiter = "\n";
        const char* DefaultOutputDelimiter = "\n";

    public:
        TUnboxedValue InputStreamObj;
        TString CommandLine;
        TUnboxedValue ArgumentsList;
        TString InputDelimiter;
        TString OutputDelimiter;
        size_t InputBufferSizeBytes;
        size_t OutputBufferSizeBytes;
        size_t ProcessPollLatencyMs;

        TStreamingParams()
            : InputDelimiter(DefaultInputDelimiter)
            , OutputDelimiter(DefaultOutputDelimiter)
            , InputBufferSizeBytes(DefaultInputBufferSizeBytes)
            , OutputBufferSizeBytes(DefaultOutputBufferSizeBytes)
            , ProcessPollLatencyMs(DefaultProcessPollLatencyMs)
        {
        }
    };

    struct TThreadSyncData {
        TMutex BuffersMutex;
        TCondVar InputBufferCanReadCond;
        TCondVar MainThreadHasWorkCond;
        TCondVar OutputBufferCanWriteCond;
    };

    class TStringListBufferedInputStream: public IInputStream {
    public:
        TStringListBufferedInputStream(TUnboxedValue rowsStream, const TString& delimiter, size_t bufferSizeBytes,
                                       TThreadSyncData& syncData, TSourcePosition pos)
            : RowsStream(rowsStream)
            , Delimiter(delimiter)
            , SyncData(syncData)
            , Pos_(pos)
            , DelimiterMatcher(delimiter)
            , DelimiterInput(delimiter)
            , Buffer(bufferSizeBytes)
            , CurReadMode(ReadMode::Start)
        {
        }

        TStringListBufferedInputStream(const TStringListBufferedInputStream&) = delete;
        TStringListBufferedInputStream& operator=(const TStringListBufferedInputStream&) = delete;

        TCyclicRWBuffer& GetBuffer() {
            return Buffer;
        }

        // Fetch input from upstream list iterator to the buffer.
        // Called from Main thread.
        EFetchStatus FetchInput() {
            with_lock (SyncData.BuffersMutex) {
                Y_DEBUG_ABORT_UNLESS(!Buffer.HasData());
                Y_DEBUG_ABORT_UNLESS(Buffer.CanWrite());

                bool receivedYield = false;

                while (Buffer.CanWrite() && CurReadMode != ReadMode::Done && !receivedYield) {
                    switch (CurReadMode) {
                        case ReadMode::Start: {
                            auto status = ReadNextString();
                            if (status == EFetchStatus::Yield) {
                                receivedYield = true;
                                break;
                            }

                            CurReadMode = (status == EFetchStatus::Ok)
                                              ? ReadMode::String
                                              : ReadMode::Done;

                            break;
                        }

                        case ReadMode::String:
                            if (CurStringInput.Exhausted()) {
                                DelimiterInput.Reset(Delimiter.data(), Delimiter.size());
                                CurReadMode = ReadMode::Delimiter;
                                break;
                            }

                            Buffer.Write(CurStringInput);
                            break;

                        case ReadMode::Delimiter:
                            if (DelimiterInput.Exhausted()) {
                                CurReadMode = ReadMode::Start;
                                break;
                            }

                            Buffer.Write(DelimiterInput);
                            break;

                        default:
                            break;
                    }
                }

                if (CurReadMode == ReadMode::Done) {
                    Buffer.Finish();
                }

                SyncData.InputBufferCanReadCond.Signal();
                return receivedYield ? EFetchStatus::Yield : EFetchStatus::Ok;
            }
        }

    private:
        // Read data to pass into the child process input pipe.
        // Called from Communicate thread.
        size_t DoRead(void* buf, size_t len) override {
            try {
                with_lock (SyncData.BuffersMutex) {
                    while (!Buffer.HasData() && !Buffer.IsFinished()) {
                        SyncData.MainThreadHasWorkCond.Signal();
                        SyncData.InputBufferCanReadCond.WaitI(SyncData.BuffersMutex);
                    }

                    if (!Buffer.HasData()) {
                        Y_DEBUG_ABORT_UNLESS(Buffer.IsFinished());
                        return 0;
                    }

                    const char* dataPtr;
                    size_t dataLen;
                    Buffer.GetData(dataPtr, dataLen);

                    size_t bytesRead = std::min(dataLen, len);
                    Y_DEBUG_ABORT_UNLESS(bytesRead > 0);
                    memcpy(buf, dataPtr, bytesRead);
                    Buffer.CommitRead(bytesRead);
                    return bytesRead;
                }

                ythrow yexception();
            } catch (const std::exception& e) {
                UdfTerminate((TStringBuilder() << Pos_ << " " << e.what()).data());
            }
        }

        EFetchStatus ReadNextString() {
            TUnboxedValue item;
            EFetchStatus status = RowsStream.Fetch(item);
            switch (status) {
                case EFetchStatus::Yield:
                case EFetchStatus::Finish:
                    return status;
                default:
                    break;
            }

            CurString = item.GetElement(0);
            CurStringInput.Reset(CurString.AsStringRef().Data(), CurString.AsStringRef().Size());

            // Check that input string doesn't contain delimiters
            const char* match;
            Y_UNUSED(match);
            if (DelimiterMatcher.SubStr(
                    CurString.AsStringRef().Data(),
                    CurString.AsStringRef().Data() + CurString.AsStringRef().Size(),
                    match))
            {
                ythrow yexception() << "Delimiter found in input string.";
            }

            return EFetchStatus::Ok;
        }

    private:
        enum class ReadMode {
            Start,
            String,
            Delimiter,
            Done
        };

        TUnboxedValue RowsStream;
        TString Delimiter;
        TThreadSyncData& SyncData;
        TSourcePosition Pos_;

        TKMPMatcher DelimiterMatcher;
        TUnboxedValue CurString;
        TMemoryInput CurStringInput;
        TMemoryInput DelimiterInput;

        TCyclicRWBuffer Buffer;

        ReadMode CurReadMode;
    };

    class TStringListBufferedOutputStream: public IOutputStream {
    public:
        TStringListBufferedOutputStream(const TString& delimiter, size_t stringBufferSizeBytes,
                                        TStringListBufferedInputStream& inputStream, TThreadSyncData& syncData)
            : Delimiter(delimiter)
            , InputStream(inputStream)
            , SyncData(syncData)
            , HasDelimiterMatch(false)
            , DelimiterMatcherCallback(HasDelimiterMatch)
            , DelimiterMatcher(delimiter.data(), delimiter.data() + delimiter.size(), &DelimiterMatcherCallback)
            , Buffer(stringBufferSizeBytes)
        {
        }

        TStringListBufferedOutputStream(const TStringListBufferedOutputStream&) = delete;
        TStringListBufferedOutputStream& operator=(const TStringListBufferedOutputStream&) = delete;

        // Get string record from buffer.
        // Called from Main thread.
        EFetchStatus FetchNextString(TString& str) {
            while (!HasDelimiterMatch) {
                with_lock (SyncData.BuffersMutex) {
                    bool inputHasData;
                    bool bufferNeedsData;

                    do {
                        inputHasData = InputStream.GetBuffer().HasData() || InputStream.GetBuffer().IsFinished();
                        bufferNeedsData = !Buffer.HasData() && !Buffer.IsFinished();

                        if (inputHasData && bufferNeedsData) {
                            SyncData.MainThreadHasWorkCond.WaitI(SyncData.BuffersMutex);
                        }
                    } while (inputHasData && bufferNeedsData);

                    if (!inputHasData) {
                        auto status = InputStream.FetchInput();
                        if (status == EFetchStatus::Yield) {
                            return EFetchStatus::Yield;
                        }
                    }

                    if (bufferNeedsData) {
                        continue;
                    }

                    if (!Buffer.HasData()) {
                        Y_DEBUG_ABORT_UNLESS(Buffer.IsFinished());
                        str = TString(TStringBuf(CurrentString.Data(), CurrentString.Size()));
                        CurrentString.Clear();
                        return str.empty() ? EFetchStatus::Finish : EFetchStatus::Ok;
                    }

                    const char* data;
                    size_t size;
                    Buffer.GetData(data, size);

                    size_t read = 0;
                    while (!HasDelimiterMatch && read < size) {
                        DelimiterMatcher.Push(data[read]);
                        ++read;
                    }

                    Y_DEBUG_ABORT_UNLESS(read > 0);
                    CurrentString.Append(data, read);
                    bool signalCanWrite = !Buffer.CanWrite();
                    Buffer.CommitRead(read);

                    if (signalCanWrite) {
                        SyncData.OutputBufferCanWriteCond.Signal();
                    }
                }
            }

            Y_DEBUG_ABORT_UNLESS(CurrentString.Size() >= Delimiter.size());
            str = TString(TStringBuf(CurrentString.Data(), CurrentString.Size() - Delimiter.size()));
            CurrentString.Clear();
            HasDelimiterMatch = false;

            return EFetchStatus::Ok;
        }

        TCyclicRWBuffer& GetBuffer() {
            return Buffer;
        }

    private:
        // Write data from child process output to buffer.
        // Called from Communicate thread.
        void DoWrite(const void* buf, size_t len) override {
            const char* curStrPos = reinterpret_cast<const char*>(buf);
            size_t curStrLen = len;

            while (curStrLen > 0) {
                with_lock (SyncData.BuffersMutex) {
                    while (!Buffer.CanWrite() && !Buffer.IsFinished()) {
                        SyncData.OutputBufferCanWriteCond.WaitI(SyncData.BuffersMutex);
                    }

                    if (Buffer.IsFinished()) {
                        return;
                    }

                    bool signalCanRead = !Buffer.HasData();
                    Buffer.Write(curStrPos, curStrLen);

                    if (signalCanRead) {
                        SyncData.MainThreadHasWorkCond.Signal();
                    }
                }
            }
        }

        void DoFinish() override {
            IOutputStream::DoFinish();

            with_lock (SyncData.BuffersMutex) {
                Buffer.Finish();
                SyncData.MainThreadHasWorkCond.Signal();
            }
        }

    private:
        class MatcherCallback: public TKMPStreamMatcher<char>::ICallback {
        public:
            MatcherCallback(bool& hasMatch)
                : HasMatch(hasMatch)
            {
            }

            void OnMatch(const char* begin, const char* end) override {
                Y_UNUSED(begin);
                Y_UNUSED(end);

                HasMatch = true;
            }

        private:
            bool& HasMatch;
        };

    private:
        TString Delimiter;
        TStringListBufferedInputStream& InputStream;
        TThreadSyncData& SyncData;

        bool HasDelimiterMatch;
        MatcherCallback DelimiterMatcherCallback;
        TKMPStreamMatcher<char> DelimiterMatcher;

        TBuffer CurrentString;

        TCyclicRWBuffer Buffer;
    };

    class TStreamingOutputListIterator {
    public:
        TStreamingOutputListIterator(const TStreamingParams& params, const IValueBuilder* valueBuilder, TSourcePosition pos)
            : StreamingParams(params)
            , ValueBuilder(valueBuilder)
            , Pos_(pos)
        {
        }

        TStreamingOutputListIterator(const TStreamingOutputListIterator&) = delete;
        TStreamingOutputListIterator& operator=(const TStreamingOutputListIterator&) = delete;

        ~TStreamingOutputListIterator() {
            if (ShellCommand) {
                Y_DEBUG_ABORT_UNLESS(InputStream && OutputStream);

                try {
                    ShellCommand->Terminate();
                } catch (const std::exception& e) {
                    Cerr << CurrentExceptionMessage();
                }

                // Let Communicate thread finish.
                with_lock (ThreadSyncData.BuffersMutex) {
                    InputStream->GetBuffer().Finish();
                    OutputStream->GetBuffer().Finish();
                    ThreadSyncData.InputBufferCanReadCond.Signal();
                    ThreadSyncData.OutputBufferCanWriteCond.Signal();
                }

                ShellCommand->Wait();
            }
        }

        EFetchStatus Fetch(TUnboxedValue& result) {
            try {
                EFetchStatus status = EFetchStatus::Ok;

                if (!ProcessStarted()) {
                    StartProcess();

                    // Don't try to fetch data if there was a problem starting the process,
                    // this causes infinite wait on Windows system due to incorrect ShellCommand behavior.
                    if (ShellCommand->GetStatus() != TShellCommand::SHELL_RUNNING && ShellCommand->GetStatus() != TShellCommand::SHELL_FINISHED) {
                        status = EFetchStatus::Finish;
                    }
                }

                if (status == EFetchStatus::Ok) {
                    status = OutputStream->FetchNextString(CurrentRecord);
                }

                if (status == EFetchStatus::Finish) {
                    switch (ShellCommand->GetStatus()) {
                        case TShellCommand::SHELL_FINISHED:
                            break;
                        case TShellCommand::SHELL_INTERNAL_ERROR:
                            ythrow yexception() << "Internal error running process: " << ShellCommand->GetInternalError();
                            break;
                        case TShellCommand::SHELL_ERROR:
                            ythrow yexception() << "Error running user process: " << ShellCommand->GetError();
                            break;
                        default:
                            ythrow yexception() << "Unexpected shell command status: " << (int)ShellCommand->GetStatus();
                    }
                    return EFetchStatus::Finish;
                }

                if (status == EFetchStatus::Ok) {
                    TUnboxedValue* items = nullptr;
                    result = ValueBuilder->NewArray(1, items);
                    *items = ValueBuilder->NewString(TStringRef(CurrentRecord.data(), CurrentRecord.size()));
                }

                return status;
            } catch (const std::exception& e) {
                UdfTerminate((TStringBuilder() << Pos_ << " " << e.what()).data());
            }
        }

    private:
        void StartProcess() {
            InputStream.Reset(new TStringListBufferedInputStream(
                StreamingParams.InputStreamObj, StreamingParams.InputDelimiter,
                StreamingParams.InputBufferSizeBytes, ThreadSyncData, Pos_));

            OutputStream.Reset(new TStringListBufferedOutputStream(
                StreamingParams.OutputDelimiter, StreamingParams.OutputBufferSizeBytes, *InputStream,
                ThreadSyncData));

            TShellCommandOptions opt;
            opt.SetAsync(true).SetUseShell(false).SetLatency(StreamingParams.ProcessPollLatencyMs).SetInputStream(InputStream.Get()).SetOutputStream(OutputStream.Get()).SetCloseStreams(true).SetCloseAllFdsOnExec(true);

            TList<TString> commandArguments;
            auto argumetsIterator = StreamingParams.ArgumentsList.GetListIterator();
            for (TUnboxedValue item; argumetsIterator.Next(item);) {
                commandArguments.emplace_back(TStringBuf(item.AsStringRef()));
            }

            ShellCommand.Reset(new TShellCommand(StreamingParams.CommandLine, commandArguments, opt));
            ShellCommand->Run();
        }

        bool ProcessStarted() const {
            return !!ShellCommand;
        }

    private:
        TStreamingParams StreamingParams;
        const IValueBuilder* ValueBuilder;
        TSourcePosition Pos_;

        TThreadSyncData ThreadSyncData;

        THolder<TShellCommand> ShellCommand;
        THolder<TStringListBufferedInputStream> InputStream;
        THolder<TStringListBufferedOutputStream> OutputStream;

        TString CurrentRecord;
    };

    class TStreamingOutput: public TBoxedValue {
    public:
        TStreamingOutput(const TStreamingParams& params, const IValueBuilder* valueBuilder, TSourcePosition pos)
            : StreamingParams(params)
            , ValueBuilder(valueBuilder)
            , Pos_(pos)
        {
        }

        TStreamingOutput(const TStreamingOutput&) = delete;
        TStreamingOutput& operator=(const TStreamingOutput&) = delete;

    private:
        EFetchStatus Fetch(TUnboxedValue& result) override {
            if (IsFinished) {
                return EFetchStatus::Finish;
            }

            if (!Iterator) {
                Iterator.Reset(new TStreamingOutputListIterator(StreamingParams, ValueBuilder, Pos_));
            }

            auto ret = Iterator->Fetch(result);

            if (ret == EFetchStatus::Finish) {
                IsFinished = true;
                Iterator.Reset();
            }

            return ret;
        }

        TStreamingParams StreamingParams;
        const IValueBuilder* ValueBuilder;
        TSourcePosition Pos_;
        bool IsFinished = false;
        THolder<TStreamingOutputListIterator> Iterator;
    };

    class TStreamingScriptOutput: public TStreamingOutput {
    public:
        TStreamingScriptOutput(const TStreamingParams& params, const IValueBuilder* valueBuilder,
                               TSourcePosition pos, const TString& script, const TString& scriptFilename)
            : TStreamingOutput(params, valueBuilder, pos)
            , ScriptFileHandle(scriptFilename)
        {
            auto scriptStripped = StripBeforeShebang(script);
            ScriptFileHandle.Write(scriptStripped.data(), scriptStripped.size());
            ScriptFileHandle.Close();

            if (Chmod(ScriptFileHandle.Name().c_str(), MODE0755) != 0) {
                ythrow yexception() << "Chmod failed for script file:" << ScriptFileHandle.Name()
                                    << " with error: " << LastSystemErrorText();
            }
        }

    private:
        static TString StripBeforeShebang(const TString& script) {
            auto shebangIndex = script.find("#!");
            if (shebangIndex != TString::npos) {
                auto scriptStripped = StripStringLeft(script);

                if (scriptStripped.size() == script.size() - shebangIndex) {
                    return scriptStripped;
                }
            }

            return script;
        }

        TTempFileHandle ScriptFileHandle;
    };

    class TStreamingProcess: public TBoxedValue {
    public:
        TStreamingProcess(TSourcePosition pos)
            : Pos_(pos)
        {}

    private:
        TUnboxedValue Run(const IValueBuilder* valueBuilder,
                          const TUnboxedValuePod* args) const override {
            auto inputListArg = args[0];
            auto commandLineArg = args[1].AsStringRef();
            auto argumentsArg = args[2];
            auto inputDelimiterArg = args[3];
            auto outputDelimiterArg = args[4];

            Y_DEBUG_ABORT_UNLESS(inputListArg.IsBoxed());

            TStreamingParams params;
            params.InputStreamObj = TUnboxedValuePod(inputListArg);
            params.CommandLine = TString(TStringBuf(commandLineArg));
            params.ArgumentsList = !argumentsArg
                                       ? valueBuilder->NewEmptyList()
                                       : TUnboxedValue(argumentsArg.GetOptionalValue());

            if (inputDelimiterArg) {
                params.InputDelimiter = TString(TStringBuf(inputDelimiterArg.AsStringRef()));
            }
            if (outputDelimiterArg) {
                params.OutputDelimiter = TString(TStringBuf(outputDelimiterArg.AsStringRef()));
            }

            return TUnboxedValuePod(new TStreamingOutput(params, valueBuilder, Pos_));
        }

    public:
        static TStringRef Name() {
            static auto name = TStringRef::Of("Process");
            return name;
        }

    private:
        TSourcePosition Pos_;
    };

    class TStreamingProcessInline: public TBoxedValue {
    public:
        TStreamingProcessInline(TSourcePosition pos)
            : Pos_(pos)
        {}

    private:
        TUnboxedValue Run(const IValueBuilder* valueBuilder,
                          const TUnboxedValuePod* args) const override {
            auto inputListArg = args[0];
            auto scriptArg = args[1].AsStringRef();
            auto argumentsArg = args[2];
            auto inputDelimiterArg = args[3];
            auto outputDelimiterArg = args[4];

            TString script(scriptArg);
            TString scriptFilename = MakeTempName(".");

            TStreamingParams params;
            params.InputStreamObj = TUnboxedValuePod(inputListArg);
            params.CommandLine = scriptFilename;
            params.ArgumentsList = !argumentsArg
                                       ? valueBuilder->NewEmptyList()
                                       : TUnboxedValue(argumentsArg.GetOptionalValue());

            if (inputDelimiterArg) {
                params.InputDelimiter = TString(TStringBuf(inputDelimiterArg.AsStringRef()));
            }
            if (outputDelimiterArg) {
                params.OutputDelimiter = TString(TStringBuf(outputDelimiterArg.AsStringRef()));
            }

            return TUnboxedValuePod(new TStreamingScriptOutput(params, valueBuilder, Pos_, script, scriptFilename));
        }

    public:
        static TStringRef Name() {
            static auto name = TStringRef::Of("ProcessInline");
            return name;
        }

    private:
        TSourcePosition Pos_;
    };

    class TStreamingModule: public IUdfModule {
    public:
        TStringRef Name() const {
            return TStringRef::Of("Streaming");
        }

        void CleanupOnTerminate() const final {
        }

        void GetAllFunctions(IFunctionsSink& sink) const final {
            sink.Add(TStreamingProcess::Name());
            sink.Add(TStreamingProcessInline::Name());
        }

        void BuildFunctionTypeInfo(
            const TStringRef& name,
            NUdf::TType* userType,
            const TStringRef& typeConfig,
            ui32 flags,
            IFunctionTypeInfoBuilder& builder) const override {
            try {
                Y_UNUSED(userType);
                Y_UNUSED(typeConfig);

                bool typesOnly = (flags & TFlags::TypesOnly);

                auto optionalStringType = builder.Optional()->Item<char*>().Build();
                auto rowType = builder.Struct(1)->AddField("Data", TDataType<char*>::Id, nullptr).Build();
                auto rowsType = builder.Stream()->Item(rowType).Build();
                auto stringListType = builder.List()->Item(TDataType<char*>::Id).Build();
                auto optionalStringListType = builder.Optional()->Item(stringListType).Build();

                if (TStreamingProcess::Name() == name) {
                    builder.Returns(rowsType).Args()->Add(rowsType).Add<char*>().Add(optionalStringListType).Add(optionalStringType).Add(optionalStringType).Done().OptionalArgs(3);

                    if (!typesOnly) {
                        builder.Implementation(new TStreamingProcess(builder.GetSourcePosition()));
                    }
                }

                if (TStreamingProcessInline::Name() == name) {
                    builder.Returns(rowsType).Args()->Add(rowsType).Add<char*>().Add(optionalStringListType).Add(optionalStringType).Add(optionalStringType).Done().OptionalArgs(3);

                    if (!typesOnly) {
                        builder.Implementation(new TStreamingProcessInline(builder.GetSourcePosition()));
                    }
                }
            } catch (const std::exception& e) {
                builder.SetError(CurrentExceptionMessage());
            }
        }
    };

}

REGISTER_MODULES(TStreamingModule)