Skip to content
pi-c Artifact [35612f77e1]
Login

Artifact [35612f77e1]

Artifact 35612f77e11aec5729a6da30f97d4bdc2c1be3a4717977a430d540f201eea609:


/* The streaming POST every adapter uses, and the table of registered
 * adapters a model's API is looked up in. See provider_http.h for the retry
 * rules and the seam. */
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "cred.h"
#include "events.h"
#include "net.h"
#include "userdb.h"
#include "platform.h"
#include "http.h"
#include "provider_http.h"

#define HTTP_TRIES 4
#define IDLE_SECONDS 120     /* a stream may pause while the model thinks */

/* IDLE_SECONDS, or PIC_IDLE_SECONDS when it is a positive number (tests). */
static int idle_seconds(void) {
    const char *v = getenv("PIC_IDLE_SECONDS");
    int n = v ? atoi(v) : 0;
    return n > 0 ? n : IDLE_SECONDS;
}
#define DEADLINE_SECONDS 900 /* one whole request */
#define ERROR_BODY_CAP 8192
#define KEY_CAP PIC_CRED_TOKEN_CAP
#define MAX_HEADERS 32

char *pic_strdup(const char *s) {
    size_t n = strlen(s) + 1;
    char *p = malloc(n);
    if (p) {
        memcpy(p, s, n);
    }
    return p;
}

typedef struct {
    pic_http_resp *resp;
    pic_sse *sse;
    char error_body[ERROR_BODY_CAP];
    size_t error_len;
    int stream_failed;
} phttp_sink;

static int on_body(void *ctx, const char *bytes, size_t n) {
    phttp_sink *k = ctx;
    if (k->resp->status == 200) {
        int rc = pic_sse_feed(k->sse, bytes, n);
        if (rc != 0) {
            k->stream_failed = 1;
        }
        return rc;
    }
    if (n > sizeof k->error_body - 1 - k->error_len) {
        n = sizeof k->error_body - 1 - k->error_len;
    }
    memcpy(k->error_body + k->error_len, bytes, n);
    k->error_len += n;
    k->error_body[k->error_len] = '\0';
    return 0;
}

/* error.message from an error body (both APIs nest it there) into msg, or "". */
static void error_message(pic_store *s, const char *body, char *msg, size_t cap) {
    sqlite3_stmt *q = NULL;
    msg[0] = '\0';
    if (sqlite3_prepare_v2(s->db,
                           "SELECT CASE WHEN json_valid(?1) THEN coalesce(json_extract(?1,'$.error.message'),"
                           " json_extract(?1,'$.message')) END",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, body, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            (void)snprintf(msg, cap, "%.300s", (const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
}

static long long phttp_now_ms(void) { return (long long)(pic_platform_get()->wall_ns() / 1000000); }

/* A refused request: what it says of the key (recorded against the key it
 * went with, s->credential), and the error a user reads, into err. 1 when it
 * is worth trying again as it is (a transient failure). */
static int refusal(pic_store *s, const pic_model *m, const pic_http_resp *r, const char *body, const char *auth_line,
                   char *err, size_t errcap) {
    char msg[320];
    pic_key_health h;
    long long now = phttp_now_ms();
    error_message(s, body, msg, sizeof msg);
    if (strrchr(auth_line, ' ')) { /* the value of the key's header line */
        pic_cred_scrub(msg, strrchr(auth_line, ' ') + 1);
    }
    pic_cred_classify(m->provider, r->status, body, msg, r->ratelimit, r->retry_after, now, &h);
    if (s->credential[0]) {
        (void)pic_cred_health_note(s->credential, &h);
    }
    s->key_state = (int)h.state;
    s->key_status = r->status;
    s->key_until_ms = h.until_ms;
    if (h.state == PIC_KEY_CREDIT || h.state == PIC_KEY_INVALID || h.state == PIC_KEY_LIMITED) {
        pic_cred_failure_message(m->provider, s->credential_label[0] ? s->credential_label : m->provider, &h, now, err,
                                 errcap);
    } else {
        (void)snprintf(err, errcap, "HTTP %d%s%.300s", r->status, msg[0] ? ": " : "", msg);
    }
    return h.state == PIC_KEY_TRANSIENT;
}

/* A reply came back: the key works. */
static void key_answered(pic_store *s) {
    pic_key_health h;
    memset(&h, 0, sizeof h);
    h.state = PIC_KEY_OK;
    h.status = 200;
    if (s->credential[0]) {
        (void)pic_cred_health_note(s->credential, &h);
    }
}

/* Waits ms, serving the side descriptor meanwhile; Ctrl-C (or Pi's
 * abort_retry) ends the wait. */
static void pause_ms(const pic_store *s, long ms) {
    uint64_t end = pic_platform_get()->mono_ns() + (uint64_t)ms * 1000000u;
    for (uint64_t now; !pic_interrupted && !(s && s->abort_retry) && (now = pic_platform_get()->mono_ns()) < end;) {
        long left = (long)((end - now) / 1000000u) + 1;
        if (pic_side_any()) {
            pic_side_poll((int)(left < 1000 ? left : 1000));
        } else {
            struct timespec ts = {left / 1000, (left % 1000) * 1000000L};
            (void)nanosleep(&ts, NULL);
        }
    }
}

/* Milliseconds to wait before try number `tryno` (1-based) after a failure. */
static long backoff_ms(const pic_http_resp *r, int tryno) {
    long ms = 500L << (tryno - 1);
    if (r && r->retry_after[0]) {
        char *end;
        long secs = strtol(r->retry_after, &end, 10);
        if (*end == '\0' && secs >= 0) {
            ms = secs * 1000;
        }
    }
    return ms > 30000 ? 30000 : ms;
}

void pic_auth_line(pic_auth_style auth, const char *key, char *out, size_t cap) {
    (void)snprintf(out, cap,
                   auth == PIC_AUTH_BEARER ? "Authorization: Bearer %s"
                   : auth == PIC_AUTH_X_GOOG_API_KEY ? "x-goog-api-key: %s"
                                                     : "x-api-key: %s",
                   key);
}

int pic_json_get(const char *json, const char *path, char *out, size_t cap) {
    sqlite3 *db = NULL;
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (sqlite3_open_v2(":memory:", &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_MEMORY, NULL) == SQLITE_OK &&
        sqlite3_prepare_v2(db, "SELECT CASE WHEN json_valid(?1) THEN json_extract(?1, ?2) END", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
            (void)snprintf(out, cap, "%s", (const char *)sqlite3_column_text(q, 0));
            rc = 0;
        }
    }
    sqlite3_finalize(q);
    sqlite3_close(db);
    return rc;
}

/* A request's headers: the key in AUTH's style (into auth_line, which the
 * caller wipes), EXTRA, then the model's own (copied into model_headers). */
static int request_headers(pic_store *s, const pic_model *m, const char *url, pic_auth_style auth, const char *const *extra,
                           size_t nextra, char *auth_line, size_t auth_cap, char *model_headers, size_t model_cap,
                           const char **headers, size_t *count, char *err, size_t errcap) {
    pic_cred_used used;
    char key[KEY_CAP];
    size_t nheaders = 0;
    int keyed;
    /* A subscription's token goes only where its sign-in was granted: never to
     * an endpoint the models file (or anything else) put in its place. */
    if (pic_cred_source_of(m->provider, m->key_env, m->key_literal) == PIC_CRED_STORED_OAUTH) {
        const char *origin = pic_cred_oauth_origin(m->provider);
        if (!origin || strncmp(url, origin, strlen(origin)) != 0) {
            (void)snprintf(err, errcap,
                           "the %s sign-in is sent only to %s, and this request goes to %.200s: remove the provider's"
                           " baseUrl override, or use an API key (pic auth login %s --api-key)",
                           m->provider, origin ? origin : "its own service", url, m->provider);
            return -1;
        }
    }
    keyed = pic_cred_get_as(m->provider, m->key_env, m->key_literal, key, sizeof key, &used, err, errcap);
    if (keyed < 0) {
        return -1;
    }
    /* Which key this request goes with, for the journal and its health. */
    (void)snprintf(s->credential, sizeof s->credential, "%s", keyed == 0 ? used.name : "");
    (void)snprintf(s->credential_label, sizeof s->credential_label, "%s", keyed == 0 ? used.label : "");
    (void)snprintf(s->credential_provider, sizeof s->credential_provider, "%s", m->provider);
    s->key_state = s->key_status = 0;
    s->key_until_ms = 0;
    auth_line[0] = '\0';
    if (keyed == 0) {
        pic_auth_line(auth, key, auth_line, auth_cap);
        headers[nheaders++] = auth_line;
    }
    pic_cred_wipe(key, sizeof key);
    for (size_t i = 0; i < nextra && nheaders < MAX_HEADERS; i++) {
        headers[nheaders++] = extra[i];
    }
    /* Headers from the models file, one per line. */
    (void)snprintf(model_headers, model_cap, "%s", m->headers);
    for (char *line = model_headers; *line && nheaders < MAX_HEADERS;) {
        char *nl = strchr(line, '\n');
        if (nl) {
            *nl = '\0';
        }
        headers[nheaders++] = line;
        if (!nl) {
            break;
        }
        line = nl + 1;
    }
    *count = nheaders;
    return 0;
}

/* A 401 for a request that sent a subscription's access token: the token is
 * refreshed (once per request, by the caller) and the auth line rewritten.
 * 1 to send again; 0 when this is not such a request; -1 with err when the
 * refresh failed. */
static int refresh_auth(const pic_model *m, pic_auth_style auth, char *auth_line, size_t auth_cap, char *err,
                        size_t errcap) {
    static const char bearer[] = "Authorization: Bearer ";
    char token[KEY_CAP];
    int rc;
    if (auth != PIC_AUTH_BEARER || strncmp(auth_line, bearer, sizeof bearer - 1) != 0 ||
        pic_cred_source_of(m->provider, m->key_env, m->key_literal) != PIC_CRED_STORED_OAUTH) {
        return 0;
    }
    rc = pic_cred_refresh(m->provider, auth_line + sizeof bearer - 1, token, sizeof token, err, errcap);
    if (rc == 0) {
        (void)snprintf(auth_line, auth_cap, "%s%s", bearer, token);
    }
    pic_cred_wipe(token, sizeof token);
    return rc == 0 ? 1 : -1;
}

int pic_stream_post(pic_net *net, pic_store *s, const pic_model *m, const char *url, pic_auth_style auth,
                    const char *const *extra, size_t nextra, const char *body, const pic_stream_decoder *dec,
                    char *request_id, size_t request_id_cap, int *retryable, char *err, size_t errcap) {
    char auth_line[KEY_CAP + 32], model_headers[sizeof m->headers];
    const char *headers[MAX_HEADERS];
    size_t nheaders = 0;
    int rc = -1, refreshed = 0;
    *retryable = 0;
    if (request_id_cap) {
        request_id[0] = '\0';
    }
    if (request_headers(s, m, url, auth, extra, nextra, auth_line, sizeof auth_line, model_headers, sizeof model_headers,
                        headers, &nheaders, err, errcap) != 0) {
        return -1;
    }
    for (int tryno = 1; tryno <= HTTP_TRIES; tryno++) {
        pic_http_resp resp;
        pic_sse sse;
        phttp_sink k;
        int post, transient;
        memset(&k, 0, sizeof k);
        if (dec->begin(dec->ctx) != 0 || pic_sse_init(&sse, 1u << 20, 16u << 20, dec->event, dec->ctx) != 0) {
            dec->end(dec->ctx);
            (void)snprintf(err, errcap, "out of memory");
            break;
        }
        k.resp = &resp;
        k.sse = &sse;
        pic_http_resp_init(&resp, on_body, &k);
        post = pic_http_post(net, url, headers, nheaders, body, strlen(body), &resp, idle_seconds(), DEADLINE_SECONDS,
                             err, errcap);
        pic_fault("after-response");
        if (resp.status == 200) {
            char why[320] = "";
            int complete = post == 0 && !k.stream_failed && pic_sse_pending(&sse) == 0 &&
                           dec->finish(dec->ctx, why, sizeof why) == 0;
            pic_sse_free(&sse);
            if (complete) {
                key_answered(s);
                if (request_id_cap) {
                    (void)snprintf(request_id, request_id_cap, "%s", resp.request_id);
                }
                rc = 0;
                break; /* the decoder stays live for the adapter */
            }
            /* The stream broke after it began: no retry here. */
            if (!why[0]) {
                (void)snprintf(why, sizeof why, "%s", post != 0 ? err : "incomplete stream");
            }
            dec->end(dec->ctx);
            *retryable = 1;
            (void)snprintf(err, errcap, "stream failed: %.300s", why);
            break;
        }
        pic_sse_free(&sse);
        dec->end(dec->ctx);
        if (post == 0 && resp.status == 401 && !refreshed) {
            int again;
            refreshed = 1;
            if ((again = refresh_auth(m, auth, auth_line, sizeof auth_line, err, errcap)) != 0) {
                if (again < 0) {
                    break;
                }
                tryno--; /* the refused try does not count */
                continue;
            }
        }
        /* A refusal that says the key is dead, spent or limited for long is
         * never tried again here: only a transient one is. */
        transient = post != 0 ? !pic_net_tls_failed(net) : refusal(s, m, &resp, k.error_body, auth_line, err, errcap);
        if (!transient) {
            break;
        }
        *retryable = 1;
        if (s->no_retry || s->abort_retry) {
            break;
        }
        if (tryno < HTTP_TRIES) {
            long ms = backoff_ms(post == 0 ? &resp : NULL, tryno);
            pic_ev_retry_wait(s, tryno + 1, HTTP_TRIES, ms, err);
            pause_ms(s, ms);
            if (s->abort_retry) {
                break;
            }
        }
    }
    pic_cred_wipe(auth_line, sizeof auth_line);
    if (rc == 0) {
        *retryable = 0;
    }
    return rc;
}

/* A plain JSON reply's body, gathered whatever the status. */
typedef struct {
    pic_http_resp *resp;
    char *buf;
    size_t len, cap;
    int full;
} gather;

static int on_json(void *ctx, const char *bytes, size_t n) {
    gather *g = ctx;
    if (g->len + n + 1 > g->cap) {
        size_t cap = g->cap ? g->cap : 4096;
        char *grown;
        while (cap < g->len + n + 1) {
            cap *= 2;
        }
        if (cap > (16u << 20) || !(grown = realloc(g->buf, cap))) {
            g->full = 1;
            return -1;
        }
        g->buf = grown;
        g->cap = cap;
    }
    memcpy(g->buf + g->len, bytes, n);
    g->len += n;
    g->buf[g->len] = '\0';
    return 0;
}

int pic_json_post(pic_net *net, pic_store *s, const pic_model *m, const char *url, pic_auth_style auth,
                  const char *const *extra, size_t nextra, const char *body, char **out, char *err, size_t errcap) {
    char auth_line[KEY_CAP + 32], model_headers[sizeof m->headers];
    const char *headers[MAX_HEADERS];
    size_t nheaders = 0;
    int rc = -1, refreshed = 0;
    *out = NULL;
    if (request_headers(s, m, url, auth, extra, nextra, auth_line, sizeof auth_line, model_headers, sizeof model_headers,
                        headers, &nheaders, err, errcap) != 0) {
        return -1;
    }
    for (int tryno = 1; tryno <= HTTP_TRIES; tryno++) {
        pic_http_resp resp;
        gather g;
        int post, transient;
        memset(&g, 0, sizeof g);
        g.resp = &resp;
        pic_http_resp_init(&resp, on_json, &g);
        post = pic_http_post(net, url, headers, nheaders, body, strlen(body), &resp, idle_seconds(), DEADLINE_SECONDS,
                             err, errcap);
        if (post == 0 && resp.status == 200 && g.buf) {
            key_answered(s);
            *out = g.buf;
            rc = 0;
            break;
        }
        if (post == 0 && resp.status == 401 && !refreshed) {
            int again;
            refreshed = 1;
            if ((again = refresh_auth(m, auth, auth_line, sizeof auth_line, err, errcap)) != 0) {
                free(g.buf);
                if (again < 0) {
                    break;
                }
                tryno--;
                continue;
            }
        }
        transient = post != 0 ? !pic_net_tls_failed(net) && !g.full
                              : refusal(s, m, &resp, g.buf ? g.buf : "", auth_line, err, errcap);
        free(g.buf);
        if (!transient) {
            break;
        }
        if (tryno < HTTP_TRIES) {
            pause_ms(s, backoff_ms(post == 0 ? &resp : NULL, tryno));
        }
    }
    pic_cred_wipe(auth_line, sizeof auth_line);
    return rc;
}

pic_cache pic_cache_retention(void) {
    char *v = pic_setting("cacheRetention");
    const char *env = getenv("PI_CACHE_RETENTION");
    pic_cache r = PIC_CACHE_SHORT;
    if (v && strcmp(v, "long") == 0) {
        r = PIC_CACHE_LONG;
    } else if (v && strcmp(v, "none") == 0) {
        r = PIC_CACHE_NONE;
    } else if (!(v && strcmp(v, "short") == 0) && env && strcmp(env, "long") == 0) {
        r = PIC_CACHE_LONG;
    }
    free(v);
    return r;
}

char *pic_session_id(pic_store *s, int64_t submission) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_int64(q, 1, submission);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        out = pic_strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}

#define MAX_ADAPTERS 16
static const pic_provider_adapter *adapters[MAX_ADAPTERS];
static size_t nadapters;

int pic_provider_register(const pic_provider_adapter *a) {
    for (size_t i = 0; i < nadapters; i++) {
        if (adapters[i]->api == a->api) {
            adapters[i] = a;
            return 0;
        }
    }
    if (nadapters == MAX_ADAPTERS) {
        return -1;
    }
    adapters[nadapters++] = a;
    return 0;
}

const pic_provider_adapter *pic_provider_adapter_for(pic_api api) {
    for (size_t i = 0; i < nadapters; i++) {
        if (adapters[i]->api == api) {
            return adapters[i];
        }
    }
    return NULL;
}

const pic_provider_adapter *pic_provider_adapter_named(const char *name) {
    for (size_t i = 0; name && i < nadapters; i++) {
        if (adapters[i]->name && strcmp(adapters[i]->name, name) == 0) {
            return adapters[i];
        }
    }
    return NULL;
}

/* Pi's own form: sessions, export and events carry every image as Pi does. */
static void pi_image(sqlite3_str *out, const char *mime, const char *data) {
    sqlite3_str_appendf(out, "{\"type\":\"image\",\"data\":\"%s\",\"mimeType\":\"%s\"}", data, mime);
}

static const pic_content_shape pi_shapes[] = {
    {"pi", PIC_SHAPE_BLOCKS, 0, 0, 0, 1, NULL, pi_image},
    {"pi-images", PIC_SHAPE_AFTER, 0, 0, 0, 1, NULL, pi_image},
};

const pic_content_shape *pic_content_shape_named(const char *name) {
    if (!name) {
        return NULL;
    }
    for (size_t i = 0; i < sizeof pi_shapes / sizeof pi_shapes[0]; i++) {
        if (strcmp(pi_shapes[i].name, name) == 0) {
            return &pi_shapes[i];
        }
    }
    for (size_t i = 0; i < nadapters; i++) {
        for (size_t j = 0; j < adapters[i]->nshapes; j++) {
            if (strcmp(adapters[i]->shapes[j].name, name) == 0) {
                return &adapters[i]->shapes[j];
            }
        }
    }
    return NULL;
}

void pic_id_sanitize(char *s) {
    for (; *s; s++) {
        char c = *s;
        if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-')) {
            *s = '_';
        }
    }
}

void pic_id_hash(const char *s, char out[9]) {
    uint32_t h = 2166136261u;
    for (; *s; s++) {
        h ^= (unsigned char)*s;
        h *= 16777619u;
    }
    (void)snprintf(out, 9, "%08x", h);
}

long pic_cache_seconds(const pic_model *model) {
    const pic_provider_adapter *a;
    pic_cache r = pic_cache_retention();
    if (r == PIC_CACHE_NONE) {
        return 0;
    }
    if (r == PIC_CACHE_SHORT || (model && !model->compat.supports_long_cache)) {
        return 300;
    }
    /* long: an hour (the scripted provider's too), unless the adapter says otherwise */
    a = model ? pic_provider_adapter_for(model->api) : NULL;
    return a && a->cache_long_seconds ? a->cache_long_seconds(model) : 3600;
}

int pic_provider_for_model(pic_provider *p, const pic_model *model, const char *thinking, const char *url,
                           const char *workspace, char *err, size_t errcap) {
    const pic_provider_adapter *a = pic_provider_adapter_for(model->api);
    p->cache_seconds = pic_cache_seconds(model);
    p->count = NULL;
    (void)snprintf(p->model, sizeof p->model, "%s/%s", model->provider, model->id);
    (void)snprintf(p->thinking, sizeof p->thinking, "%s",
                   pic_model_thinking_clamp(model, thinking && *thinking ? thinking : "medium"));
    if (!a || !a->open) {
        (void)snprintf(err, errcap, "provider %s: no adapter in this build speaks its API", model->provider);
        return -1;
    }
    return a->open(p, model, url, workspace, err, errcap);
}

/* The text blocks of a neutral content array, joined (malloc'd). */
char *pic_neutral_text(sqlite3 *db, const char *neutral) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(db,
                           "SELECT coalesce(group_concat(json_extract(value,'$.text'), char(10)), '') FROM json_each(?1)"
                           " WHERE json_extract(value,'$.type') = 'text'",
                           -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_text(q, 1, neutral, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        out = pic_strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}

/* A request body built by one SQL statement with text parameters. */
char *pic_json_body(sqlite3 *db, const char *sql, int nargs, ...) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    va_list ap;
    if (sqlite3_prepare_v2(db, sql, -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    va_start(ap, nargs);
    for (int i = 1; i <= nargs; i++) {
        sqlite3_bind_text(q, i, va_arg(ap, const char *), -1, SQLITE_TRANSIENT);
    }
    va_end(ap);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        out = pic_strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}