Skip to content
pi-c Documentation
Login

Documentation

/* Free checks of a key. See keyprobe.h. The network half runs in threads
 * that touch nothing shared: each holds its own copy of one key and one
 * connection. Everything that reads the credential store or writes health
 * runs on the calling thread. */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "cred.h"
#include "http.h"
#include "keyprobe.h"
#include "models.h"
#include "net.h"
#include "platform.h"
#include "provider_http.h"
#include "userdb.h"

#define KP_MAX_JOBS 64
#define KP_BODY_CAP 65536
#define KP_MAX_HEADERS 16

typedef struct {
    char provider[PIC_CRED_PROVIDER_CAP], name[PIC_CRED_NAME_CAP];
    pic_model model;
    const pic_provider_probe *ops;
    char url[512];
    char auth_line[PIC_CRED_TOKEN_CAP + 32], model_headers[1024];
    const char *headers[KP_MAX_HEADERS];
    size_t nheaders;
    int deadline;
    /* the answer, filled by the worker */
    int answered; /* the reply arrived whole */
    int status;
    char *body;
    size_t len;
    char ratelimit[1024], retry_after[32];
    int done;
    pthread_t thread;
} kp_job;

typedef struct {
    pthread_mutex_t lock;
    pthread_cond_t cond;
} kp_waker;

static kp_waker kp_wake = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};

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

static int kp_body(void *ctx, const char *bytes, size_t n) {
    kp_job *j = ctx;
    if (j->len + n >= KP_BODY_CAP) {
        return -1;
    }
    char *grown = realloc(j->body, j->len + n + 1);
    if (!grown) {
        return -1;
    }
    j->body = grown;
    memcpy(j->body + j->len, bytes, n);
    j->len += n;
    j->body[j->len] = '\0';
    return 0;
}

static void *kp_worker(void *arg) {
    kp_job *j = arg;
    char err[160] = "", neterr[160];
    pic_net *net = pic_net_new(neterr, sizeof neterr);
    pic_http_resp resp;
    if (net) {
        pic_http_resp_init(&resp, kp_body, j);
        if (pic_http_get(net, j->url, j->headers, j->nheaders, &resp, j->deadline, j->deadline, err, sizeof err) == 0 &&
            resp.status > 0) {
            j->answered = 1;
            j->status = resp.status;
            (void)snprintf(j->ratelimit, sizeof j->ratelimit, "%s", resp.ratelimit);
            (void)snprintf(j->retry_after, sizeof j->retry_after, "%s", resp.retry_after);
            if (j->body && strrchr(j->auth_line, ' ')) { /* a refusal may quote the key */
                pic_cred_scrub(j->body, strrchr(j->auth_line, ' ') + 1);
            }
        }
        pic_net_free(net);
    }
    pic_cred_wipe(j->auth_line, sizeof j->auth_line);
    (void)pthread_mutex_lock(&kp_wake.lock);
    j->done = 1;
    (void)pthread_cond_signal(&kp_wake.cond);
    (void)pthread_mutex_unlock(&kp_wake.lock);
    return NULL;
}

/* "requests left: 99" from the rate-limit header lines, or "". */
static void kp_ratelimit(const char *lines, char *out, size_t cap) {
    out[0] = '\0';
    for (const char *line = lines; *line;) {
        const char *nl = strchr(line, '\n'), *colon = memchr(line, ':', nl ? (size_t)(nl - line) : strlen(line));
        size_t n = colon ? (size_t)(colon - line) : 0;
        char name[96];
        if (n > 0 && n < sizeof name) {
            memcpy(name, line, n);
            name[n] = '\0';
            if (strstr(name, "request") && strstr(name, "remaining")) {
                long long left = strtoll(colon + 1, NULL, 10);
                (void)snprintf(out, cap, "requests left: %lld", left);
                return;
            }
        }
        line = nl ? nl + 1 : line + strlen(line);
    }
}

static void kp_message(const char *body, char *msg, size_t cap) {
    msg[0] = '\0';
    if (!body || (pic_json_get(body, "$.error.message", msg, cap) != 0 && pic_json_get(body, "$.message", msg, cap) != 0)) {
        msg[0] = '\0';
    }
}

/* Records what kp_job J learnt, as a request's reply would, on this thread. */
static void kp_apply(kp_job *j) {
    long long now = kp_now_ms();
    pic_key_health h, before;
    char msg[320];
    (void)pic_cred_health_of(j->name, &before);
    memset(&h, 0, sizeof h);
    h.checked_ms = h.probed_ms = now;
    if (!j->answered) {
        (void)pic_cred_health_probed(j->name, now, 0, "no answer in time");
        return;
    }
    h.status = j->status;
    if (j->status == 200) {
        h.state = PIC_KEY_OK;
        kp_ratelimit(j->ratelimit, h.reason, sizeof h.reason);
        if (j->ops->read) {
            j->ops->read(&j->model, j->body ? j->body : "", &h);
        }
        /* A models list cannot say that credit came back or a limit lifted: what a real
         * failure taught stays until a reply, or a check that reports a balance, says otherwise. */
        if (!h.has_remaining && (before.state == PIC_KEY_CREDIT || (before.state == PIC_KEY_LIMITED && before.until_ms > now))) {
            (void)pic_cred_health_probed(j->name, now, 0, "");
            return;
        }
        (void)pic_cred_health_note(j->name, &h);
        return;
    }
    kp_message(j->body, msg, sizeof msg);
    pic_cred_classify(j->provider, j->status, j->body, msg, j->ratelimit, j->retry_after, now, &h);
    h.probed_ms = now;
    if (h.state == PIC_KEY_INVALID || h.state == PIC_KEY_CREDIT || h.state == PIC_KEY_LIMITED) {
        (void)pic_cred_health_note(j->name, &h);
    } else {
        (void)pic_cred_health_probed(j->name, now, j->status, "");
    }
}

typedef struct {
    const pic_keyprobe_opts *o;
    long long now;
    kp_job *jobs;
    size_t n;
    const pic_model *model;
    const pic_provider_probe *ops;
    int deadline;
} kp_gather;

static int kp_fresh(const pic_key_health *h, long long now) {
    long long at = h->probed_ms;
    if (h->state == PIC_KEY_OK && h->checked_ms > at) {
        at = h->checked_ms;
    }
    return at > 0 && now - at < PIC_KEYPROBE_FRESH_MS;
}

static int kp_entry(void *ctx, const pic_cred_entry *e) {
    kp_gather *g = ctx;
    pic_key_health h;
    pic_probe_request req;
    char key[PIC_CRED_TOKEN_CAP], err[256];
    size_t nh = 0;
    kp_job *j;
    int got;
    if (g->n >= KP_MAX_JOBS || strcmp(e->kind, "oauth") == 0 || (g->o->active_only && !e->active)) {
        return 0; /* a subscription's token goes only where its sign-in was granted */
    }
    (void)pic_cred_health_of(e->name, &h);
    if (!g->o->force && kp_fresh(&h, g->now)) {
        return 0;
    }
    if (g->o->no_prompt && (strcmp(e->kind, "api_key") == 0) && pic_cred_state() != PIC_CRED_OPEN) {
        return 0;
    }
    pic_cred_override(e->provider, e->label);
    got = pic_cred_get_as(e->provider, g->model->key_env, g->model->key_literal, key, sizeof key, NULL, err, sizeof err);
    pic_cred_override(e->provider, NULL);
    if (got != 0) {
        return 0;
    }
    j = &g->jobs[g->n];
    memset(j, 0, sizeof *j);
    j->model = *g->model;
    j->ops = g->ops;
    j->deadline = g->deadline;
    (void)snprintf(j->provider, sizeof j->provider, "%s", e->provider);
    (void)snprintf(j->name, sizeof j->name, "%s", e->name);
    memset(&req, 0, sizeof req);
    g->ops->request(g->model, &req);
    (void)snprintf(j->url, sizeof j->url, "%s%s", g->model->base_url, req.path);
    pic_auth_line(req.auth, key, j->auth_line, sizeof j->auth_line);
    pic_cred_wipe(key, sizeof key);
    j->headers[nh++] = j->auth_line;
    for (size_t i = 0; i < req.nextra && nh < KP_MAX_HEADERS; i++) {
        j->headers[nh++] = req.extra[i];
    }
    (void)snprintf(j->model_headers, sizeof j->model_headers, "%s", g->model->headers);
    for (char *line = j->model_headers; *line && nh < KP_MAX_HEADERS;) {
        char *nl = strchr(line, '\n');
        if (nl) {
            *nl = '\0';
        }
        j->headers[nh++] = line;
        if (!nl) {
            break;
        }
        line = nl + 1;
    }
    j->nheaders = nh;
    g->n++;
    return 0;
}

static int kp_provider(void *ctx, const char *provider) {
    kp_gather *g = ctx;
    pic_model m;
    char name[128], err[256];
    const pic_provider_adapter *a;
    if (g->o->provider && strcmp(g->o->provider, provider) != 0) {
        return 0;
    }
    (void)snprintf(name, sizeof name, "%s/x", provider);
    if (pic_model_resolve(name, &m, err, sizeof err) != 0 || strcmp(m.provider, provider) != 0 ||
        !(a = pic_provider_adapter_named(m.api)) || !a->probe || !a->probe->request) {
        return 0;
    }
    g->model = &m;
    g->ops = a->probe;
    (void)pic_cred_entries(provider, m.key_env, m.key_literal, kp_entry, g);
    return 0;
}

int pic_keyprobe(const pic_keyprobe_opts *o) {
    kp_gather g;
    size_t started = 0, applied = 0;
    const char *env = getenv("PIC_PROBE_DEADLINE");
    int *taken;
    if (!pic_userdb(NULL, 0)) {
        return -1;
    }
    memset(&g, 0, sizeof g);
    g.o = o;
    g.now = kp_now_ms();
    g.deadline = o->deadline > 0 ? o->deadline : env && atoi(env) > 0 ? atoi(env) : PIC_KEYPROBE_DEADLINE;
    g.jobs = calloc(KP_MAX_JOBS, sizeof *g.jobs);
    taken = calloc(KP_MAX_JOBS, sizeof *taken);
    if (!g.jobs || !taken) {
        free(g.jobs);
        free(taken);
        return -1;
    }
    (void)pic_providers_each(kp_provider, &g);
    for (size_t i = 0; i < g.n; i++) {
        if (pthread_create(&g.jobs[i].thread, NULL, kp_worker, &g.jobs[i]) == 0) {
            started++;
            taken[i] = 1;
        } else {
            pic_cred_wipe(g.jobs[i].auth_line, sizeof g.jobs[i].auth_line);
        }
    }
    /* Each answer is recorded as it arrives, so a reader of the table sees rows fill in. */
    while (applied < started) {
        size_t ready[KP_MAX_JOBS], nready = 0;
        (void)pthread_mutex_lock(&kp_wake.lock);
        for (;;) {
            for (size_t i = 0; i < g.n; i++) {
                if (taken[i] == 1 && g.jobs[i].done) {
                    ready[nready++] = i;
                }
            }
            if (nready) {
                break;
            }
            (void)pthread_cond_wait(&kp_wake.cond, &kp_wake.lock);
        }
        (void)pthread_mutex_unlock(&kp_wake.lock);
        for (size_t r = 0; r < nready; r++) {
            kp_job *j = &g.jobs[ready[r]];
            (void)pthread_join(j->thread, NULL);
            kp_apply(j);
            free(j->body);
            taken[ready[r]] = 2;
            applied++;
        }
    }
    free(taken);
    free(g.jobs);
    return (int)started;
}