aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/providers/common/udf_resolve/yql_simple_udf_resolver.cpp
blob: e8cad5736f8a2ad7a6327c4412b6948c7b3863c1 (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
#include "yql_simple_udf_resolver.h"

#include <yql/essentials/providers/common/mkql/yql_type_mkql.h>
#include <yql/essentials/core/yql_holding_file_storage.h>

#include <yql/essentials/minikql/mkql_node.h>
#include <yql/essentials/minikql/mkql_type_builder.h>
#include <yql/essentials/minikql/mkql_program_builder.h>
#include <yql/essentials/minikql/mkql_utils.h>
#include <yql/essentials/minikql/computation/mkql_computation_node.h>

#include <library/cpp/digest/md5/md5.h>

#include <util/generic/vector.h>
#include <util/generic/hash_set.h>
#include <util/generic/hash.h>
#include <util/generic/string.h>
#include <util/system/guard.h>
#include <util/system/spinlock.h>

namespace NYql {
namespace NCommon {

using namespace NKikimr;
using namespace NKikimr::NMiniKQL;

class TSimpleUdfResolver : public IUdfResolver {
public:
    TSimpleUdfResolver(const NKikimr::NMiniKQL::IFunctionRegistry* functionRegistry, const TFileStoragePtr& fileStorage, bool useFakeMD5)
        : FunctionRegistry_(functionRegistry)
        , FileStorage_(fileStorage)
        , TypeInfoHelper_(new TTypeInfoHelper)
        , UseFakeMD5_(useFakeMD5)
    {}

    TString GetMD5(const TString& path) const {
        if (UseFakeMD5_) {
            return MD5::Calc(path);
        } else {
            return {};
        }
    }

    TMaybe<TFilePathWithMd5> GetSystemModulePath(const TStringBuf& moduleName) const override {
        with_lock(Lock_) {
            auto path = FunctionRegistry_->FindUdfPath(moduleName);
            return path ? MakeMaybe<TFilePathWithMd5>(*path, GetMD5(*path)) : Nothing();
        }
    }

    bool LoadMetadata(const TVector<TImport*>& imports,
        const TVector<TFunction*>& functions, TExprContext& ctx) const override {

        with_lock(Lock_) {
            bool hasErrors = false;
            THashSet<TString> requiredModules;
            for (auto udfPtr : functions) {
                auto& udf = *udfPtr;
                TStringBuf moduleName, funcName;
                if (!SplitUdfName(udf.Name, moduleName, funcName) || moduleName.empty() || funcName.empty()) {
                    ctx.AddError(TIssue(udf.Pos, TStringBuilder() <<
                        "Incorrect format of function name: " << udf.Name));
                    hasErrors = true;
                } else {
                    requiredModules.insert(TString(moduleName));
                }
            }

            THoldingFileStorage holdingFileStorage(FileStorage_);
            auto newRegistry = FunctionRegistry_->Clone();
            THashMap<std::pair<TString, TString>, THashSet<TString>> cachedModules;
            for (auto import: imports) {
                if (import->Modules) {
                    bool needLibrary = false;
                    for (auto& m : *import->Modules) {
                        if (requiredModules.contains(m)) {
                            needLibrary = true;
                            break;
                        }
                    }

                    if (!needLibrary) {
                        continue;
                    }
                } else {
                    import->Modules.ConstructInPlace();
                }
                const TString& customUdfPrefix = import->Block->CustomUdfPrefix;
                try {
                    THashSet<TString> modules;
                    if (FileStorage_) {
                        auto link = holdingFileStorage.FreezeFile(*import->Block);
                        auto path = link->GetPath().GetPath();
                        auto [it, inserted] = cachedModules.emplace(std::make_pair(path, customUdfPrefix), THashSet<TString>());
                        if (inserted) {
                            newRegistry->LoadUdfs(
                                path,
                                {},
                                NUdf::IRegistrator::TFlags::TypesOnly,
                                customUdfPrefix,
                                &modules);
                            it->second = modules;
                        } else {
                            modules = it->second;
                        }
                    } else {
                        if (import->Block->Type != EUserDataType::PATH) {
                            ctx.AddError(TIssue(import->Pos, TStringBuilder() <<
                                "Only path file type is supported, cannot load file with alias: " << import->FileAlias));
                            hasErrors = true;
                            continue;
                        }
                        auto [it, inserted] = cachedModules.emplace(std::make_pair(import->Block->Data, customUdfPrefix), THashSet<TString>());
                        if (inserted) {
                            newRegistry->LoadUdfs(
                                import->Block->Data,
                                {},
                                NUdf::IRegistrator::TFlags::TypesOnly,
                                customUdfPrefix,
                                &modules);
                            it->second = modules;
                        } else {
                            modules = it->second;
                        }
                    }

                    import->Modules->assign(modules.begin(), modules.end());
                }
                catch (yexception& e) {
                    ctx.AddError(TIssue(import->Pos, TStringBuilder()
                        << "Internal error of loading udf module: " << import->FileAlias
                        << ", reason: " << e.what()));
                    hasErrors = true;
                }
            }

            hasErrors = !LoadFunctionsMetadata(functions, *newRegistry, TypeInfoHelper_, ctx) || hasErrors;
            return !hasErrors;
        }
    }

    TResolveResult LoadRichMetadata(const TVector<TImport>& imports) const override {
        Y_UNUSED(imports);
        ythrow yexception() << "LoadRichMetadata is not supported in SimpleUdfResolver";
    }

    bool ContainsModule(const TStringBuf& moduleName) const override {
        return FunctionRegistry_->IsLoadedUdfModule(moduleName);
    }

private:
    mutable TAdaptiveLock Lock_;
    const NKikimr::NMiniKQL::IFunctionRegistry* FunctionRegistry_;
    TFileStoragePtr FileStorage_;
    NUdf::ITypeInfoHelper::TPtr TypeInfoHelper_;
    const bool UseFakeMD5_;
};

IUdfResolver::TPtr CreateSimpleUdfResolver(
    const NKikimr::NMiniKQL::IFunctionRegistry* functionRegistry,
    const TFileStoragePtr& fileStorage,
    bool useFakeMD5
) {
    return new TSimpleUdfResolver(functionRegistry, fileStorage, useFakeMD5);
}

bool LoadFunctionsMetadata(const TVector<IUdfResolver::TFunction*>& functions,
    const NKikimr::NMiniKQL::IFunctionRegistry& functionRegistry,
    NUdf::ITypeInfoHelper::TPtr typeInfoHelper,
    TExprContext& ctx) {

    bool hasErrors = false;
    TScopedAlloc alloc(__LOCATION__);
    TTypeEnvironment env(alloc);

    for (auto udfPtr : functions) {
        auto& udf = *udfPtr;
        try {
            TType* mkqlUserType = nullptr;
            if (udf.UserType) {
                TStringStream err;
                mkqlUserType = BuildType(*udf.UserType, {env}, err);//
                if (!mkqlUserType) {
                    ctx.AddError(TIssue(udf.Pos, TStringBuilder() << "Invalid user type for function: "
                        << udf.Name << ", error: " << err.Str()));
                    hasErrors = true;
                    continue;
                }
            }

            auto secureParamsProvider = MakeSimpleSecureParamsProvider(udf.SecureParams);

            TFunctionTypeInfo funcInfo;
            auto status = functionRegistry.FindFunctionTypeInfo(env, typeInfoHelper, nullptr,
                udf.Name, mkqlUserType, udf.TypeConfig, NUdf::IUdfModule::TFlags::TypesOnly, {}, secureParamsProvider.get(), &funcInfo);
            if (!status.IsOk()) {
                ctx.AddError(TIssue(udf.Pos, TStringBuilder() << "Failed to find UDF function: " << udf.Name
                    << ", reason: " << status.GetError()));
                hasErrors = true;
                continue;
            }

            udf.NormalizedName = udf.Name;
            udf.CallableType = ConvertMiniKQLType(udf.Pos, funcInfo.FunctionType, ctx);
            YQL_ENSURE(udf.CallableType);
            if (funcInfo.RunConfigType) {
                udf.RunConfigType = ConvertMiniKQLType(udf.Pos, const_cast<TType*>(funcInfo.RunConfigType), ctx);
                YQL_ENSURE(udf.RunConfigType);
            }

            if (funcInfo.UserType) {
                udf.NormalizedUserType = ConvertMiniKQLType(udf.Pos, const_cast<TType*>(funcInfo.UserType), ctx);
                YQL_ENSURE(udf.NormalizedUserType);
            }

            udf.SupportsBlocks = funcInfo.SupportsBlocks;
            udf.IsStrict = funcInfo.IsStrict;
        } catch (const std::exception& e) {
            ctx.AddError(TIssue(udf.Pos, TStringBuilder()
                << "Internal error was found when udf metadata is loading for function: " << udf.Name
                << ", reason: " << e.what()));
            hasErrors = true;
        }
    }

    return !hasErrors;
}

} // namespace NCommon
} // namespace NYql