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
|
#include "yql_udf_resolver_with_index.h"
#include <yql/essentials/providers/common/schema/expr/yql_expr_schema.h>
#include <yql/essentials/core/yql_type_annotation.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 <util/generic/hash_set.h>
#include <util/generic/hash.h>
#include <util/generic/map.h>
#include <util/generic/set.h>
#include <util/generic/string.h>
#include <util/system/guard.h>
#include <util/system/mutex.h>
namespace NYql {
namespace NCommon {
using namespace NKikimr;
using namespace NKikimr::NMiniKQL;
class TUdfResolverWithIndex : public IUdfResolver {
class TResourceFile : public TThrRefBase {
public:
typedef TIntrusivePtr<TResourceFile> TPtr;
public:
TResourceFile(TString alias, const TVector<TString>& modules, TFileLinkPtr link)
: Link(std::move(link))
{
Import.FileAlias = alias;
Import.Block = &Block;
Import.Modules = MakeMaybe(modules);
Block.Type = EUserDataType::PATH;
Block.Data = Link->GetPath();
Block.Usage.Set(EUserDataBlockUsage::Udf);
Block.FrozenFile = Link;
}
static TResourceFile::TPtr Create(const TString& packageName, const TSet<TString>& modules, TFileLinkPtr link) {
// assume package name has no bad symbols for file name
TString basename = link->GetPath().Basename();
TString alias = basename.StartsWith("lib") ? basename : ("lib_" + packageName + "_udf.so");
alias.to_lower();
return MakeIntrusive<TResourceFile>(std::move(alias), TVector<TString>(modules.begin(), modules.end()), std::move(link));
}
public:
TFileLinkPtr Link;
TUserDataBlock Block;
TImport Import;
};
public:
TUdfResolverWithIndex(TUdfIndex::TPtr udfIndex, IUdfResolver::TPtr fallback, TFileStoragePtr fileStorage)
: UdfIndex_(udfIndex)
, Fallback_(fallback)
, FileStorage_(fileStorage)
{
Y_ENSURE(UdfIndex_);
Y_ENSURE(FileStorage_);
// fallback is required only to handle type aware functions and loading rich metadata
Y_ENSURE(Fallback_);
}
TMaybe<TFilePathWithMd5> GetSystemModulePath(const TStringBuf& moduleName) const override {
with_lock(Lock_) {
TString moduleNameStr(moduleName);
if (!UdfIndex_->ContainsModuleStrict(moduleNameStr)) {
return Nothing();
}
auto file = DownloadFileWithModule(moduleNameStr);
return MakeMaybe<TFilePathWithMd5>(file->Link->GetPath(), file->Link->GetMd5());
}
}
bool LoadMetadata(const TVector<TImport*>& imports, const TVector<TFunction*>& functions,
TExprContext& ctx, NUdf::ELogLevel logLevel, THoldingFileStorage& storage) const override {
with_lock(Lock_) {
bool hasErrors = false;
THashSet<TString> requiredModules;
TVector<TFunction*> fallbackFunctions;
TVector<TImport*> fallbackImports = imports;
TSet<TImport*> additionalImports; // avoid duplicates
for (auto udfPtr : functions) {
TImport* additionalImport = nullptr;
TFunction* fallbackFunction = nullptr;
if (!LoadFunctionMetadata(*udfPtr, ctx, fallbackFunction, additionalImport)) {
hasErrors = true;
continue;
}
if (additionalImport) {
additionalImports.insert(additionalImport);
}
if (fallbackFunction) {
fallbackFunctions.push_back(fallbackFunction);
}
}
fallbackImports.insert(fallbackImports.end(), additionalImports.begin(), additionalImports.end());
return Fallback_->LoadMetadata(fallbackImports, fallbackFunctions, ctx, logLevel, storage) && !hasErrors;
}
}
TResolveResult LoadRichMetadata(const TVector<TImport>& imports, NUdf::ELogLevel logLevel, THoldingFileStorage& storage) const override {
return Fallback_->LoadRichMetadata(imports, logLevel, storage);
}
bool ContainsModule(const TStringBuf& moduleName) const override {
TString moduleNameStr = TString(moduleName);
if (UdfIndex_->ContainsModuleStrict(moduleNameStr)) {
return true;
}
return Fallback_->ContainsModule(moduleName);
}
private:
bool LoadFunctionMetadata(TFunction& function, TExprContext& ctx, TFunction*& fallbackFunction, TImport*& additionalImport) const {
TStringBuf moduleName, funcName;
if (!SplitUdfName(function.Name, moduleName, funcName) || moduleName.empty() || funcName.empty()) {
ctx.AddError(TIssue(function.Pos, TStringBuilder() << "Incorrect format of function name: " << function.Name));
return false;
}
/*
the order is really important:
1) check we have such module
no-> fallback function
2) check we have such function
no -> error
3) download resource file
fail -> error
4) if polymorphic function -> fallback function with additional Import for downloaded file
*/
TString moduleNameStr = TString(moduleName);
auto moduleStatus = UdfIndex_->ContainsModule(moduleNameStr);
if (moduleStatus == TUdfIndex::EStatus::NotFound) {
fallbackFunction = &function;
return true;
}
if (moduleStatus == TUdfIndex::EStatus::Ambigious) {
ctx.AddError(TIssue(function.Pos, TStringBuilder() << "Ambigious module name: " << moduleName));
return false;
}
TFunctionInfo info;
auto functionStatus = UdfIndex_->FindFunction(moduleNameStr, function.Name, info);
if (functionStatus == TUdfIndex::EStatus::NotFound) {
ctx.AddError(TIssue(function.Pos, TStringBuilder() << "Function not found: " << function.Name));
return false;
}
if (functionStatus == TUdfIndex::EStatus::Ambigious) {
ctx.AddError(TIssue(function.Pos, TStringBuilder() << "Ambigious function: " << function.Name));
return false;
}
TResourceFile::TPtr file = DownloadFileWithModule(moduleName, function.Pos, ctx);
if (!file) {
return false;
}
additionalImport = &file->Import;
if (info.IsTypeAwareness) {
function.Name = info.Name;
fallbackFunction = &function;
return true;
}
if (!info.CallableType) {
ctx.AddError(TIssue(function.Pos, TStringBuilder() << "CallableType for function " << function.Name << " is empty. Check UDF source code for errors."));
return false;
}
function.NormalizedName = info.Name;
function.CallableType = ParseTypeFromYson(TStringBuf{info.CallableType}, ctx, function.Pos);
if (!function.CallableType) {
ctx.AddError(TIssue(function.Pos, TStringBuilder() << "Failed to build callable type from YSON for function " << function.Name));
return false;
}
if (info.RunConfigType) {
function.RunConfigType = ParseTypeFromYson(TStringBuf{info.RunConfigType}, ctx, function.Pos);
if (!function.RunConfigType) {
ctx.AddError(TIssue(function.Pos, TStringBuilder() << "Failed to build run config type from YSON for function " << function.Name));
return false;
}
} else {
function.RunConfigType = std::get<0>(ctx.SingletonTypeCache);
}
function.NormalizedUserType = std::get<0>(ctx.SingletonTypeCache);
function.IsStrict = info.IsStrict;
function.SupportsBlocks = info.SupportsBlocks;
function.Messages = info.Messages;
function.MinLangVer = info.MinLangVer;
function.MaxLangVer = info.MaxLangVer;
return true;
}
TResourceFile::TPtr DownloadFileWithModule(const TStringBuf& module, const TPosition& pos, TExprContext& ctx) const {
try {
return DownloadFileWithModule(module);
} catch (const std::exception& e) {
ctx.AddError(ExceptionToIssue(e, pos));
}
return nullptr;
}
TResourceFile::TPtr DownloadFileWithModule(const TStringBuf& module) const {
TString moduleName(module);
auto resource = UdfIndex_->FindResourceByModule(moduleName);
if (!resource) {
ythrow yexception() << "No resource has been found for registered module " << moduleName;
}
auto canonizedModuleName = moduleName;
Y_ENSURE(UdfIndex_->CanonizeModule(canonizedModuleName));
const auto it = DownloadedFiles_.find(canonizedModuleName);
if (it != DownloadedFiles_.end()) {
return it->second;
}
// token is empty for urls for now
// assumption: file path is frozen already, no need to put into file storage
const TDownloadLink& downloadLink = resource->Link;
TFileLinkPtr link = downloadLink.IsUrl ? FileStorage_->PutUrl(downloadLink.Path, {}) : CreateFakeFileLink(downloadLink.Path, downloadLink.Md5);
TResourceFile::TPtr file = TResourceFile::Create(canonizedModuleName, resource->Modules, link);
for (auto& d : resource->Modules) {
auto p = DownloadedFiles_.emplace(d, file);
if (!p.second) {
// should not happen because UdfIndex handles conflicts
ythrow yexception() << "file already downloaded for module " << canonizedModuleName << ", conflicting path " << downloadLink.Path << ", existing local file " << p.first->second->Link->GetPath();
}
}
return file;
}
private:
mutable TMutex Lock_;
const TUdfIndex::TPtr UdfIndex_;
const IUdfResolver::TPtr Fallback_;
const TFileStoragePtr FileStorage_;
// module -> downloaded resource file
mutable TMap<TString, TResourceFile::TPtr> DownloadedFiles_;
};
IUdfResolver::TPtr CreateUdfResolverWithIndex(TUdfIndex::TPtr udfIndex, IUdfResolver::TPtr fallback, TFileStoragePtr fileStorage) {
return new TUdfResolverWithIndex(udfIndex, fallback, fileStorage);
}
} // namespace NCommon
} // namespace NYql
|