Skip to content
pi-c Documentation
Login

Documentation

/* Refreshing the model catalog from pi.dev (see catalog.h). */
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

#include "catalog.h"
#include "http.h"
#include "net.h"
#include "sqlite3.h"

#define REFRESH_MS (4LL * 3600 * 1000) /* Pi's REMOTE_CATALOG_REFRESH_INTERVAL_MS */
#define BODY_CAP (8u << 20)

static long long now_ms(void) { return (long long)time(NULL) * 1000; }

/* ---- refreshing from pi.dev -------------------------------------------- */

typedef struct {
    char *buf;
    size_t len;
    int too_big;
} body;

static int on_body(void *ctx, const char *bytes, size_t n) {
    body *b = ctx;
    char *grown;
    if (b->len + n > BODY_CAP) {
        b->too_big = 1;
        return 1;
    }
    if (!(grown = realloc(b->buf, b->len + n + 1))) {
        return 1;
    }
    b->buf = grown;
    memcpy(b->buf + b->len, bytes, n);
    b->len += n;
    b->buf[b->len] = '\0';
    return 0;
}

/* An HTTP date (Last-Modified) in ms, or 0. */
static long long http_date_ms(const char *s) {
    struct tm tm;
    memset(&tm, 0, sizeof tm);
    if (!s || !*s || !strptime(s, "%a, %d %b %Y %H:%M:%S GMT", &tm)) {
        return 0;
    }
    return (long long)timegm(&tm) * 1000;
}

/* Replaces the store entry of PROVIDER (store is updated in place). */
static int put_entry(sqlite3 *db, char **store, const char *provider, const char *models, long long checked,
                     long long modified, const char *etag) {
    sqlite3_stmt *q = NULL;
    int rc = -1;
    if (sqlite3_prepare_v2(db,
                           "SELECT json_set(CASE WHEN json_valid(?1) THEN ?1 ELSE '{}' END, '$.\"' || ?2 || '\"',"
                           " json_object('models', json(coalesce(?3, json_extract(?1, '$.\"' || ?2 || '\".models'), '[]')),"
                           " 'checkedAt', ?4, 'lastModified', ?5, 'etag', ?6))",
                           -1, &q, NULL) != SQLITE_OK) {
        return -1;
    }
    sqlite3_bind_text(q, 1, *store, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, provider, -1, SQLITE_STATIC);
    if (models) {
        sqlite3_bind_text(q, 3, models, -1, SQLITE_STATIC);
    }
    sqlite3_bind_int64(q, 4, checked);
    sqlite3_bind_int64(q, 5, modified);
    if (etag && *etag) {
        sqlite3_bind_text(q, 6, etag, -1, SQLITE_STATIC);
    }
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        char *next = strdup((const char *)sqlite3_column_text(q, 0));
        if (next) {
            free(*store);
            *store = next;
            rc = 0;
        }
    }
    sqlite3_finalize(q);
    return rc;
}

static long long entry_num(sqlite3 *db, const char *store, const char *provider, const char *field) {
    sqlite3_stmt *q = NULL;
    long long v = 0;
    char path[160];
    (void)snprintf(path, sizeof path, "$.\"%s\".%s", provider, field);
    if (sqlite3_prepare_v2(db, "SELECT coalesce(json_extract(?1, ?2), 0) WHERE json_valid(?1)", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, store, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            v = sqlite3_column_int64(q, 0);
        }
        sqlite3_finalize(q);
    }
    return v;
}

static void entry_text(sqlite3 *db, const char *store, const char *provider, const char *field, char *out, size_t cap) {
    sqlite3_stmt *q = NULL;
    char path[160];
    out[0] = '\0';
    (void)snprintf(path, sizeof path, "$.\"%s\".%s", provider, field);
    if (sqlite3_prepare_v2(db, "SELECT json_extract(?1, ?2) WHERE json_valid(?1)", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, store, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            (void)snprintf(out, cap, "%s", (const char *)sqlite3_column_text(q, 0));
        }
        sqlite3_finalize(q);
    }
}

/* Writes the store through a temporary file and a rename. */
static int write_store(const char *store) {
    char path[PATH_MAX], tmp[PATH_MAX + 16];
    FILE *f;
    int ok;
    if (pic_catalog_store_path(path, sizeof path, 1) != 0 || snprintf(tmp, sizeof tmp, "%s.%ld", path, (long)getpid()) >= (int)sizeof tmp ||
        !(f = fopen(tmp, "wb"))) {
        return -1;
    }
    ok = fputs(store, f) >= 0;
    ok = fclose(f) == 0 && ok;
    if (!ok || rename(tmp, path) != 0) {
        (void)unlink(tmp);
        return -1;
    }
    return 0;
}

int pic_catalog_refresh(int force, char *err, size_t errcap) {
    const char *mode = getenv("PIC_MODEL_CATALOG");
    sqlite3 *db = NULL;
    pic_net *net;
    char *store, neterr[256];
    int rc = 0, changed = 0;
    err[0] = '\0';
    if (mode && strcmp(mode, "offline") == 0) {
        return 0;
    }
    if (!(net = pic_net_new(neterr, sizeof neterr))) {
        (void)snprintf(err, errcap, "%s", neterr);
        return -1;
    }
    store = pic_catalog_read_store();
    if (sqlite3_open(":memory:", &db) != SQLITE_OK) {
        pic_net_free(net);
        free(store);
        return -1;
    }
    for (size_t p = 0; p < PIC_CATALOG_NPROVIDERS; p++) {
        const char *prov = pic_catalog_providers[p];
        long long checked = entry_num(db, store, prov, "checkedAt"), modified = entry_num(db, store, prov, "lastModified");
        char url[256], etag[160], inm[200], herr[256];
        const char *headers[3];
        size_t nh = 0;
        body b = {NULL, 0, 0};
        pic_http_resp r;
        if (!force && checked && modified && now_ms() - checked < REFRESH_MS) {
            continue;
        }
        entry_text(db, store, prov, "etag", etag, sizeof etag);
        (void)snprintf(url, sizeof url, "https://pi.dev/api/models/providers/%s?types=chat", prov);
        headers[nh++] = "Accept: application/json";
        headers[nh++] = "User-Agent: pic";
        if (etag[0]) {
            (void)snprintf(inm, sizeof inm, "If-None-Match: %s", etag);
            headers[nh++] = inm;
        }
        pic_http_resp_init(&r, on_body, &b);
        if (pic_http_get(net, url, headers, nh, &r, 4, 15, herr, sizeof herr) != 0) {
            if (!err[0]) {
                (void)snprintf(err, errcap, "%s: %s", prov, herr);
            }
            rc = -1;
        } else if (r.status == 200 && !b.too_big && b.buf) {
            sqlite3_stmt *v = NULL;
            int valid = 0;
            if (sqlite3_prepare_v2(db, "SELECT json_valid(?1) AND json_type(?1) = 'array'", -1, &v, NULL) == SQLITE_OK) {
                sqlite3_bind_text(v, 1, b.buf, -1, SQLITE_STATIC);
                valid = sqlite3_step(v) == SQLITE_ROW && sqlite3_column_int(v, 0);
                sqlite3_finalize(v);
            }
            if (valid && put_entry(db, &store, prov, b.buf, now_ms(), http_date_ms(r.last_modified), r.etag) == 0) {
                changed = 1;
            } else if (!err[0]) {
                (void)snprintf(err, errcap, "%s: the catalog was not a list of models", prov);
                rc = -1;
            }
        } else if (r.status == 304) {
            changed |= put_entry(db, &store, prov, NULL, now_ms(), modified, etag) == 0;
        } else if (r.status == 404 || r.status == 501) {
            changed |= put_entry(db, &store, prov, "[]", now_ms(), 0, NULL) == 0;
        } else {
            if (!err[0]) {
                (void)snprintf(err, errcap, "%s: HTTP %d", prov, r.status);
            }
            rc = -1;
        }
        free(b.buf);
    }
    if (changed && write_store(store) != 0) {
        if (!err[0]) {
            (void)snprintf(err, errcap, "cannot write ~/.pic/models-store.json");
        }
        rc = -1;
    }
    sqlite3_close(db);
    pic_net_free(net);
    free(store);
    return rc;
}