Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
/*
 * DBMS_VECTOR / DBMS_VECTOR_CHAIN shared REST/credential core (see
 * dbms_vector_rest.hpp).  Moved out of dbms_vector.cpp verbatim; the SQL
 * facades and future shared text consumers link this single implementation.
 */
 
#include "dbms_vector_rest.hpp"
#include "dbms_vector_common.hpp"
 
#include <cstring>
#include <string>
 
#include <curl/curl.h>
 
extern "C"
{
 
#include "catalog/pg_type.h"
#include "executor/spi.h"
#include "fmgr.h"
#include "utils/builtins.h"
 
/// Версия RUDB пакета DBMS_VECTOR (Oracle DBMS_VECTOR пакет)
#define RUDB_DBMS_VECTOR_VERSION "0.7.0"
 
/*
 * Максимальный размер ответа провайдера (защита от неограниченного чтения).
 */
#define DBMS_VECTOR_HTTP_MAX_RESPONSE_BYTES (64 * 1024 * 1024)
 
} // extern "C"
 
/*
 * Parse the jsonb params of a REST call: provider (default 'database',
 * lowercased), url, model, credential_name and transfer_timeout
 * (default 60 s, pls:270).
 */
void
dbms_vector_rest_parse_params(Jsonb *params, DbmsVectorRestParams &out)
{
    out = DbmsVectorRestParams();
 
    if (params == nullptr)
        return;
 
    JsonbContainer *container = &params->root;
 
    if (!JsonContainerIsObject(container))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("params must be a JSON object"),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
 
    std::string provider;
    if (dbms_vector_param_string(container, "provider", "PROVIDER", provider))
        out.provider = dbms_vector_ascii_lower(provider);
 
    dbms_vector_param_string(container, "url", "URL", out.url);
    dbms_vector_param_string(container, "model", "MODEL", out.model);
    dbms_vector_param_string(container, "credential_name", "CREDENTIAL_NAME",
                             out.credential_name);
 
    JsonbValue buffer;
    JsonbValue *found = dbms_vector_getobjectfield(container,
                                                   "transfer_timeout",
                                                   &buffer);
    if (found != nullptr)
    {
        int32_t timeout;
 
        if (found->type != jbvNumeric)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("invalid value for transfer_timeout parameter"),
                     errdetail("Oracle error: ORA-29225.")));
 
        PG_TRY();
        {
            timeout = DatumGetInt32(DirectFunctionCall1(
                numeric_int4, NumericGetDatum(found->val.numeric)));
        }
        PG_CATCH();
        {
            FlushErrorState();
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("invalid value for transfer_timeout parameter"),
                     errdetail("Oracle error: ORA-29225.")));
        }
        PG_END_TRY();
 
        if (timeout < 0)
            ereport(ERROR,
                    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                     errmsg("invalid value for transfer_timeout parameter"),
                     errdetail("Oracle error: ORA-29225.")));
 
        out.transfer_timeout = timeout;
    }
}
 
/*
 * CHECK_REST_PARAMS parity (pls:3639): url, model and credential_name are
 * required.
 */
void
dbms_vector_rest_check_params(const DbmsVectorRestParams &params)
{
    if (params.url.empty())
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("missing URL parameter"),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
 
    if (params.model.empty())
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("missing MODEL parameter"),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
 
    if (params.credential_name.empty())
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("missing CREDENTIAL_NAME parameter"),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
}
 
bool
dbms_vector_rest_is_reserved_key(const char *key, int len)
{
    static const char *reserved[] = {
        "provider", "credential_name", "url", "model",
        "transfer_timeout", "batch_size",
    };
 
    for (const char *candidate : reserved)
        if ((int) strlen(candidate) == len &&
            strncmp(candidate, key, len) == 0)
            return true;
 
    return false;
}
 
void
dbms_vector_rest_push_passthrough(JsonbInState *state, Jsonb *params)
{
    if (params == nullptr || !JsonContainerIsObject(&params->root))
        return;
 
    JsonbIterator *iterator = JsonbIteratorInit(&params->root);
    JsonbValue passthrough_key;
    JsonbValue passthrough_value;
    JsonbIteratorToken token;
 
    while ((token = JsonbIteratorNext(&iterator, &passthrough_key,
                                      true)) != WJB_DONE)
    {
        if (token != WJB_KEY)
            continue;
 
        bool reserved = dbms_vector_rest_is_reserved_key(
            passthrough_key.val.string.val,
            passthrough_key.val.string.len);
 
        if (JsonbIteratorNext(&iterator, &passthrough_value, true) !=
            WJB_VALUE)
            break; /* malformed object; jsonb guarantees a value next */
 
        if (!reserved)
        {
            pushJsonbValue(state, WJB_KEY, &passthrough_key);
            pushJsonbValue(state, WJB_VALUE, &passthrough_value);
        }
    }
}
 
static size_t
dbms_vector_curl_write_cb(char *ptr, size_t size, size_t nmemb,
                          void *userdata)
{
    auto *response = static_cast<DbmsVectorRestResponse *>(userdata);
    size_t real = size * nmemb;
 
    if (response->body.size() + real >
        (size_t) DBMS_VECTOR_HTTP_MAX_RESPONSE_BYTES)
        return 0; /* aborts the transfer with CURLE_WRITE_ERROR */
 
    response->body.append(ptr, real);
    return real;
}
 
DbmsVectorRestResponse
dbms_vector_rest_call(const DbmsVectorRestParams &params,
                      const std::string &api_key, const char *body)
{
    static bool curl_inited = false;
 
    if (!curl_inited)
    {
        curl_global_init(CURL_GLOBAL_DEFAULT);
        curl_inited = true;
    }
 
    CURL *curl = curl_easy_init();
    if (curl == nullptr)
        ereport(ERROR,
                (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
                 errmsg("could not initialize libcurl")));
 
    DbmsVectorRestResponse response;
    struct curl_slist *headers = nullptr;
    std::string auth_header = "Authorization: Bearer " + api_key;
 
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, auth_header.c_str());
 
    curl_easy_setopt(curl, CURLOPT_URL, params.url.c_str());
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) strlen(body));
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
                     dbms_vector_curl_write_cb);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
    curl_easy_setopt(curl, CURLOPT_USERAGENT,
                     "RuDB-DBMS_VECTOR/" RUDB_DBMS_VECTOR_VERSION);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
 
    if (params.transfer_timeout > 0)
    {
        curl_easy_setopt(curl, CURLOPT_TIMEOUT,
                         (long) params.transfer_timeout);
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,
                         (long) params.transfer_timeout);
    }
 
    CURLcode rc = curl_easy_perform(curl);
 
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response.status_code);
 
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
 
    if (rc == CURLE_WRITE_ERROR &&
        response.body.size() >= (size_t) DBMS_VECTOR_HTTP_MAX_RESPONSE_BYTES)
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("provider response exceeds the maximum supported "
                        "size of %d bytes",
                        DBMS_VECTOR_HTTP_MAX_RESPONSE_BYTES)));
 
    if (rc != CURLE_OK)
        ereport(ERROR,
                (errcode(ERRCODE_CONNECTION_FAILURE),
                 errmsg("provider request failed: %s",
                        curl_easy_strerror(rc))));
 
    return response;
}
 
std::string
dbms_vector_rest_provider_error(const char *output)
{
    if (output == nullptr)
        return std::string();
 
    if (strlen(output) >= 512)
        return std::string(output);
 
    Jsonb *parsed = nullptr;
 
    PG_TRY();
    {
        parsed = DatumGetJsonbP(DirectFunctionCall1(
            jsonb_in, CStringGetDatum(output)));
    }
    PG_CATCH();
    {
        FlushErrorState();
        return std::string(output);
    }
    PG_END_TRY();
 
    std::string message;
    JsonbContainer *root = &parsed->root;
 
    if (JsonContainerIsObject(root))
    {
        JsonbValue buffer;
 
        if (dbms_vector_getobjectfield(root, "message", &buffer) != nullptr &&
            buffer.type == jbvString)
            message.assign(buffer.val.string.val, buffer.val.string.len);
 
        if (message.empty() &&
            dbms_vector_getobjectfield(root, "error", &buffer) != nullptr)
        {
            if (buffer.type == jbvBinary &&
                JsonContainerIsObject(buffer.val.binary.data))
            {
                JsonbValue nested;
 
                if (dbms_vector_getobjectfield(buffer.val.binary.data,
                                               "message", &nested) != nullptr &&
                    nested.type == jbvString)
                    message.assign(nested.val.string.val,
                                   nested.val.string.len);
            }
            else if (buffer.type == jbvBinary &&
                     JsonContainerIsArray(buffer.val.binary.data))
            {
                JsonbValue *first = getIthJsonbValueFromContainer(
                    buffer.val.binary.data, 0);
 
                if (first != nullptr && first->type == jbvString)
                    message.assign(first->val.string.val,
                                   first->val.string.len);
            }
            else if (buffer.type == jbvString)
                message.assign(buffer.val.string.val,
                               buffer.val.string.len);
        }
    }
 
    return message.empty() ? std::string(output) : message;
}
 
/*
 * Raw stored params of a credential (secrets included), honoring the
 * OWNER.NAME qualification rules and the owner-or-superuser access rule;
 * returns a copy of the params jsonb allocated in the caller's memory
 * context, or raises the ORA-20001 parity error.
 */
Jsonb *
dbms_vector_credential_lookup(const std::string &credential_name)
{
    std::string owner;
    std::string name;
 
    dbms_vector_parse_qualified_name(credential_name.c_str(), owner, name);
    dbms_vector_check_simple_name(name, "credential name");
    if (credential_name.find('.') != std::string::npos)
        dbms_vector_check_simple_name(owner, "credential owner");
 
    SPI_connect();
 
    Jsonb *result = nullptr;
 
    PG_TRY();
    {
        static const char *sql =
            "SELECT owner, params FROM \"SYS\".vector_credentials "
            "WHERE owner = $1 AND credential_name = $2";
        Oid argtypes[2] = {TEXTOID, TEXTOID};
        Datum values[2];
        char nulls[2] = {' ', ' '};
 
        values[0] = CStringGetTextDatum(owner.c_str());
        values[1] = CStringGetTextDatum(name.c_str());
 
        int rc = SPI_execute_with_args(sql, 2, argtypes, values, nulls, true, 1);
        if (rc != SPI_OK_SELECT)
            ereport(ERROR,
                    (errmsg("SPI_execute_with_args failed: %s (rc=%d)",
                            SPI_result_code_string(rc), rc)));
 
        if (SPI_processed == 0)
            ereport(ERROR,
                    (errcode(ERRCODE_UNDEFINED_OBJECT),
                     errmsg("credential %s does not exist",
                             name.c_str()),
                     errdetail("Oracle error: ORA-20001 (EXCP_CRED_NOT_EXIST).")));
 
        bool owner_isnull = false;
        bool params_isnull = false;
        Datum owner_datum = SPI_getbinval(SPI_tuptable->vals[0],
                                          SPI_tuptable->tupdesc, 1,
                                          &owner_isnull);
        Datum params_datum = SPI_getbinval(SPI_tuptable->vals[0],
                                           SPI_tuptable->tupdesc, 2,
                                           &params_isnull);
        if (params_isnull)
            ereport(ERROR,
                    (errmsg("params is NULL for credential %s",
                            name.c_str())));
 
        const char *row_owner = owner_isnull
            ? "" : TextDatumGetCString(owner_datum);
        if (strcmp(row_owner, GetUserNameFromId(GetUserId(), false)) != 0 &&
            !superuser())
            ereport(ERROR,
                    (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                     errmsg("permission denied for credential %s",
                             name.c_str())));
 
        /*
         * Detoast before copying: jsonb values in heap tuples may use the
         * short 1-byte varlena header, which is unusable as a Jsonb *.
         */
        Jsonb *params = DatumGetJsonbP(params_datum);
        result = (Jsonb *) SPI_palloc(VARSIZE(params));
        memcpy(result, params, VARSIZE(params));
    }
    PG_FINALLY();
    {
        SPI_finish();
    }
    PG_END_TRY();
 
    return result;
}
 
std::string
dbms_vector_rest_credential_key(Jsonb *credential,
                                const std::string &credential_name)
{
    JsonbContainer *container = &credential->root;
    DbmsVectorCredForm form = dbms_vector_credential_form(container);
 
    if (form == DBMS_VECTOR_CRED_USERPASS)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                  errmsg("username/password credentials cannot be used with "
                         "the openai provider"),
                  errdetail("Oracle providers always send the stored key as "
                            "a bearer token (pls:2253); a username/password "
                            "credential has no key.")));
 
    if (form == DBMS_VECTOR_CRED_OCI)
        ereport(ERROR,
                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                  errmsg("OCI request signing credentials are not supported "
                         "by the REST provider"),
                  errhint("Use an access_token credential with provider "
                          "'openai'.")));
 
    JsonbValue value;
    JsonbValue *found = dbms_vector_getobjectfield(container, "access_token",
                                                   &value);
    if (found == nullptr || found->type != jbvString ||
        found->val.string.len == 0)
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                  errmsg("credential %s does not specify a supported "
                         "authentication form",
                          credential_name.c_str())));
 
    return std::string(found->val.string.val, found->val.string.len);
}