[code] [blog] [Repos] [GPS Tracker] [Music] [VNC] [Restart VNC] [E-Mail me]

browse files at this commit · zip

commit 22b9c506157d70c71e36c460b0f56af109021b5a
Author: apol <apol@mail.com>
Date:   Sun Oct 25 14:10:33 2026 +0100

    STATS: readings with their own time, merged into the stats file in order
    
    A device that buffers while offline (the Twizy dashboard records a
    sample every 30 s with or without WiFi) uploads its readings late. The
    stats file must stay sorted - the web app binary-searches it and stops
    at the first line past the window - so late rows cannot be appended.
    
    STATS;imei;name,name,...;time,value,...|time,value,...  carries unix
    times. write_stats_batch appends a batch that is not older than the
    file's last line, and otherwise writes a copy with the batch merged in
    by time (existing rows first on a tie) and renames it over the file,
    with trim_file_tail's locking, catch-up copy and rename. Unregistered
    devices (capped) are appended as before.
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---
 device_server/device/basic_protocol.c |  65 +++++++
 device_server/logfiles.c              | 352 ++++++++++++++++++++++++++++++++++
 device_server/logfiles.h              |  14 ++
 3 files changed, 431 insertions(+)

diff --git a/device_server/device/basic_protocol.c b/device_server/device/basic_protocol.c
index bc5e81c..4ae2327 100644
--- a/device_server/device/basic_protocol.c
+++ b/device_server/device/basic_protocol.c
@@ -6,6 +6,7 @@
 #include <sys/types.h>
 #include <stdarg.h>
 #include <math.h>
+#include <stdlib.h>
 
 #include "../util.h"
 #include "../config.h"
@@ -114,6 +115,70 @@ void basic_process_message(connection * conn, char * string, size_t length) {
         return;
     }
 
+    /*
+     * STATS;imei;name,name,...;time,value,value,...|time,value,...
+     *
+     * Readings that carry the time they were taken - unix seconds - several at once: a device
+     * that buffers while it is offline (the Twizy dashboard) sends them when it is back, and a
+     * reading from a drive an hour ago belongs an hour ago, not now. The names come once and
+     * each row gives a value per name, in the same order; an empty value is no reading. Rows
+     * older than the end of the stats file are merged into it in time order (write_stats_batch).
+     */
+    if (strcmp(data_buffers[0], "STATS") == 0 && str_count >= 4) {
+        unsigned char stat_imei[18] = {0};
+        memcpy(stat_imei, data_buffers[1], min(strlen(data_buffers[1]), 16));
+        normalise_imei((char *)stat_imei);
+
+        if (strlen(conn->imei) <= 1 || strcmp(conn->imei, stat_imei) != 0) {
+            snprintf(conn->imei, sizeof(conn->imei), "%s", stat_imei);
+            init_imei(conn);
+        }
+
+        unsigned char * names[32] = {0};
+        size_t name_count = split_to(',', data_buffers[2], strlen(data_buffers[2]) + 1, names, 32);
+        unsigned char * row_split[64] = {0};
+        size_t row_count = split_to('|', data_buffers[3], strlen(data_buffers[3]) + 1, row_split, 64);
+        //one connection thread each: the rows are this message's own
+        stat_row * rows = malloc(sizeof(stat_row) * 64 * 32);
+        size_t n = 0;
+
+        if (!rows) {
+            return;
+        }
+
+        for (size_t r = 0; r < row_count && row_split[r]; r++) {
+            unsigned char * fields[33] = {0};
+            size_t field_count = split_to(',', row_split[r], strlen(row_split[r]) + 1, fields, 33);
+
+            if (field_count < 2 || !fields[0]) {
+                continue;
+            }
+
+            char * endp = NULL;
+            long long when = strtoll((char *)fields[0], &endp, 10);
+
+            if (endp == (char *)fields[0]) {
+                continue;
+            }
+
+            for (size_t k = 1; k < field_count && k - 1 < name_count; k++) {
+                if (!fields[k] || !fields[k][0] || !names[k - 1]) {
+                    continue;
+                }
+
+                rows[n].when = (time_t)when;
+                snprintf(rows[n].name, sizeof(rows[n].name), "%s", (char *)names[k - 1]);
+                rows[n].value = parse_float(fields[k]);
+                n++;
+            }
+        }
+
+        write_stats_batch(conn, rows, n);
+        free(rows);
+        conn->timeout_time = time(0) + BASIC_TIMEOUT;
+        return;
+    }
+
     /*
      * EVENT;imei;text - something the device wants in its event list, in its own words. A
      * controller or a phone has no alarm codes to map onto the watch's, and before this the
diff --git a/device_server/logfiles.c b/device_server/logfiles.c
index 99b0e5d..769be55 100644
--- a/device_server/logfiles.c
+++ b/device_server/logfiles.c
@@ -943,6 +943,358 @@ long long trim_file_tail(const char * path, size_t cap, size_t keep, size_t io_r
     return r;
 }
 
+/*
+ * Readings that carry their own time, written in time order even when they arrive late.
+ *
+ * The stats file has to stay sorted: the web app finds a time window in it by binary search
+ * (date_grep's find_start) and stops at the first line past the window, so one block of old
+ * rows appended at the end hides itself and everything after a search that lands in it. A
+ * device that buffers while it is offline - the Twizy's dashboard records a sample every 30
+ * seconds with or without WiFi - uploads hours of readings at once, all older than what the
+ * file already ends with.
+ *
+ * So a batch that is not older than the file's last line is appended as usual, and one that
+ * is goes into a copy of the file at its place: the rows up to the first line newer than the
+ * batch's oldest reading, then that tail and the batch merged by time (existing rows first on
+ * a tie), then whatever other connections appended meanwhile, and the copy renamed over the
+ * file. The copying, locking and renaming are trim_file_tail's (above), for the same reasons;
+ * only the tail is held in memory. A device that is not registered is capped (see
+ * unregistered_cap) and its rows are appended as they come.
+ */
+static long long stat_line_time(const char * s, size_t n) {
+    //YYYY-MM-DDTHH:MM:SSZ, as statsprintf writes it
+    if (n < 20 || s[4] != '-' || s[7] != '-' || s[10] != 'T' || s[13] != ':' || s[16] != ':' || s[19] != 'Z') {
+        return -1;
+    }
+
+    struct tm tm = {0};
+
+    for (int i = 0; i < 19; i++) {
+        if (i == 4 || i == 7 || i == 10 || i == 13 || i == 16) {
+            continue;
+        }
+
+        if (s[i] < '0' || s[i] > '9') {
+            return -1;
+        }
+    }
+
+    tm.tm_year = (s[0] - '0') * 1000 + (s[1] - '0') * 100 + (s[2] - '0') * 10 + (s[3] - '0') - 1900;
+    tm.tm_mon = (s[5] - '0') * 10 + (s[6] - '0') - 1;
+    tm.tm_mday = (s[8] - '0') * 10 + (s[9] - '0');
+    tm.tm_hour = (s[11] - '0') * 10 + (s[12] - '0');
+    tm.tm_min = (s[14] - '0') * 10 + (s[15] - '0');
+    tm.tm_sec = (s[17] - '0') * 10 + (s[18] - '0');
+    return (long long)timegm(&tm);
+}
+
+//the name as write_stat_at keeps it: [A-Za-z0-9_.-] only; false when nothing is left
+static bool stat_clean_name(const char * raw, char * out, size_t size) {
+    size_t w = 0;
+
+    for (size_t i = 0; raw && raw[i] && w + 1 < size; i++) {
+        unsigned char c = (unsigned char)raw[i];
+
+        if (isalnum(c) || c == '_' || c == '-' || c == '.') {
+            out[w++] = (char)c;
+        }
+    }
+
+    out[w] = 0;
+    return w > 0;
+}
+
+static int stat_line_format(char * buf, size_t size, const stat_row * r) {
+    struct tm tm = {0};
+    gmtime_r(&r->when, &tm);
+    return snprintf(buf, size, "%d-%02d-%02dT%02d:%02d:%02dZ,%s,%.2f\n", tm.tm_year + 1900, tm.tm_mon + 1,
+                    tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, r->name, r->value);
+}
+
+static int stat_row_cmp(const void * a, const void * b) {
+    const stat_row * x = a, * y = b;
+    return x->when < y->when ? -1 : x->when > y->when ? 1 : 0;
+}
+
+static bool write_all(int fd, const char * p, size_t n) {
+    while (n > 0) {
+        ssize_t w = write(fd, p, n);
+
+        if (w < 0) {
+            if (errno == EINTR) {
+                continue;
+            }
+
+            return false;
+        }
+
+        p += w;
+        n -= (size_t)w;
+    }
+
+    return true;
+}
+
+/*
+ * Where the batch goes: the offset of the first line newer than oldest (the file's size when
+ * there is none). Lines are read backwards from the end in blocks; a sorted file stops this as
+ * soon as it reaches a line that is not newer.
+ */
+static off_t stats_split(int fd, off_t end, time_t oldest) {
+    char buf[8192];
+    off_t pos = end;              //the start of the earliest whole line seen so far
+    off_t rd = end;               //everything from here on has been read
+    char * carry = NULL;          //the partial line at the front of the last block read
+    size_t carry_n = 0;
+
+    while (rd > 0) {
+        off_t from = rd > (off_t)sizeof(buf) ? rd - (off_t)sizeof(buf) : 0;
+        ssize_t got = pread(fd, buf, (size_t)(rd - from), from);
+
+        if (got <= 0) {
+            break;
+        }
+
+        //lines that start inside this block, last first; the first one may continue in carry
+        char * joined = malloc((size_t)got + carry_n + 1);
+
+        if (!joined) {
+            break;
+        }
+
+        memcpy(joined, buf, (size_t)got);
+        memcpy(joined + got, carry ? carry : "", carry_n);
+        size_t n = (size_t)got + carry_n;
+        free(carry);
+        carry = NULL;
+        carry_n = 0;
+        size_t line_end = n;
+
+        for (ssize_t i = (ssize_t)n - 1; i >= -1; i--) {
+            if (i >= 0 && joined[i] != '\n') {
+                continue;
+            }
+
+            size_t start = (size_t)(i + 1);
+
+            if (start < line_end) {
+                if (i < 0 && from > 0) {
+                    //starts before this block: finish it with the next block back
+                    carry_n = line_end - start;
+                    carry = malloc(carry_n);
+                    memcpy(carry, joined + start, carry_n);
+                    break;
+                }
+
+                long long t = stat_line_time(joined + start, line_end - start);
+
+                if (t >= 0 && t <= (long long)oldest) {
+                    free(joined);
+                    return from + (off_t)line_end + (line_end < n ? 1 : 0);
+                }
+
+                pos = from + (off_t)start;
+            }
+
+            line_end = i >= 0 ? (size_t)i : 0;
+        }
+
+        free(joined);
+        rd = from;
+    }
+
+    free(carry);
+    return pos;
+}
+
+static bool stats_merge_locked(connection * conn, stat_row * rows, size_t n) {
+    const char * path = conn->stats_file;
+    struct stat st;
+    int in = devfile_open(path, O_RDONLY, 0);
+
+    if (in < 0 || fstat(in, &st) != 0) {
+        if (in >= 0) {
+            close(in);
+        }
+
+        return false;
+    }
+
+    if (!lock_bounded(in, LOCK_EX, TRIM_LOCK_TIMEOUT_MS)) {
+        close(in);
+        return false;
+    }
+
+    off_t end = st.st_size;
+    off_t split = stats_split(in, end, rows[0].when);
+    size_t tail_n = (size_t)(end - split);
+    char * tail = malloc(tail_n + 1);
+    bool ok = tail != NULL && pread(in, tail, tail_n, split) == (ssize_t)tail_n;
+    static unsigned long counter = 0;
+    char tmp[FILENAME_MAX];
+    int out = -1;
+
+    for (int attempt = 0; ok && attempt < 8 && out < 0; attempt++) {
+        snprintf(tmp, sizeof(tmp), "%s.merge.%ld.%lu", path, (long)getpid(), __sync_fetch_and_add(&counter, 1));
+        out = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);
+
+        if (out < 0 && errno != EEXIST) {
+            break;
+        }
+    }
+
+    ok = ok && out >= 0;
+
+    if (ok && fchown(out, (uid_t) -1, st.st_gid) != 0) {
+        //not in that group: the directory's group stays, as for a new file
+    }
+
+    ok = ok && fchmod(out, st.st_mode & 0777) == 0;
+    struct timespec t0;
+    clock_gettime(CLOCK_MONOTONIC, &t0);
+    off_t copied = 0;
+    ok = ok && copy_range(in, out, 0, split, 0, &t0, &copied);
+
+    //the tail and the batch, by time; an existing row goes first on a tie
+    size_t ti = 0, ri = 0;
+    char line[256];
+
+    while (ok && (ti < tail_n || ri < n)) {
+        size_t le = ti;
+
+        while (le < tail_n && tail[le] != '\n') {
+            le++;
+        }
+
+        long long tt = ti < tail_n ? stat_line_time(tail + ti, le - ti) : -1;
+
+        if (ti < tail_n && (ri >= n || tt < 0 || tt <= (long long)rows[ri].when)) {
+            size_t len = le - ti + (le < tail_n ? 1 : 0);
+            ok = write_all(out, tail + ti, len);
+
+            if (le == tail_n && ok) {
+                ok = write_all(out, "\n", 1);   //an unterminated last line gets its newline
+            }
+
+            ti += len;
+        } else {
+            int len = stat_line_format(line, sizeof(line), &rows[ri++]);
+            ok = len > 0 && write_all(out, line, (size_t)len);
+        }
+    }
+
+    free(tail);
+
+    //appends that went in anyway (an append that cannot get the lock in time writes regardless)
+    if (ok) {
+        struct stat now;
+        ok = fstat(in, &now) == 0 && now.st_nlink > 0 && now.st_size >= end;
+        ok = ok && copy_range(in, out, end, now.st_size, 0, &t0, &copied);
+    }
+
+    ok = ok && fsync(out) == 0;
+
+    if (out >= 0) {
+        ok = (close(out) == 0) && ok;
+    }
+
+    if (!ok || rename(tmp, path) != 0) {
+        if (out >= 0) {
+            unlink(tmp);
+        }
+
+        close(in);
+        return false;
+    }
+
+    close(in);
+    //the connection's own append handle points at the old inode now; the next write reopens
+    if (conn->stats_filehandle) {
+        fclose(conn->stats_filehandle);
+        conn->stats_filehandle = NULL;
+    }
+
+    return true;
+}
+
+void write_stats_batch(connection * conn, stat_row * rows, size_t n) {
+    if (n == 0 || !conn->can_log || strlen(conn->stats_file) < 16 || !storage_disk_ok()) {
+        return;
+    }
+
+    //the same names and the same clock check as write_stat_at
+    time_t now = time(0);
+    size_t m = 0;
+
+    for (size_t i = 0; i < n; i++) {
+        char clean[64];
+
+        if (!stat_clean_name(rows[i].name, clean, sizeof(clean))) {
+            continue;
+        }
+
+        double drift = difftime(rows[i].when, now);
+
+        if (rows[i].when <= 0 || drift > STAT_CLOCK_SANITY || drift < -STAT_CLOCK_SANITY) {
+            rows[i].when = now;
+        }
+
+        rows[m] = rows[i];
+        snprintf(rows[m].name, sizeof(rows[m].name), "%s", clean);
+        m++;
+    }
+
+    if (m == 0) {
+        return;
+    }
+
+    qsort(rows, m, sizeof(stat_row), stat_row_cmp);
+
+    //the time of the file's last line: a batch no older than that is simply appended
+    long long last = -1;
+    int fd = devfile_open(conn->stats_file, O_RDONLY, 0);
+
+    if (fd >= 0) {
+        struct stat st;
+
+        if (fstat(fd, &st) == 0 && st.st_size > 0) {
+            char buf[512];
+            off_t from = st.st_size > (off_t)sizeof(buf) ? st.st_size - (off_t)sizeof(buf) : 0;
+            ssize_t got = pread(fd, buf, (size_t)(st.st_size - from), from);
+
+            for (ssize_t i = got - 2; i >= -1 && got > 0; i--) {
+                if (i < 0 || buf[i] == '\n') {
+                    last = stat_line_time(buf + i + 1, (size_t)(got - (i + 1)));
+                    break;
+                }
+            }
+        }
+
+        close(fd);
+    }
+
+    bool unregistered = conn->storage == STORAGE_UNREGISTERED || conn->storage == STORAGE_STUB;
+
+    if (!unregistered && last >= 0 && (long long)rows[0].when < last) {
+        pthread_mutex_lock(&trim_lock);
+        bool merged = stats_merge_locked(conn, rows, m);
+        pthread_mutex_unlock(&trim_lock);
+
+        if (merged) {
+            log_line(conn, "stats: merged %zu late readings into place\n", m);
+            return;
+        }
+
+        log_line(conn, "stats: could not merge %zu late readings - appended instead\n", m);
+    }
+
+    for (size_t i = 0; i < m; i++) {
+        char line[256];
+        stat_line_format(line, sizeof(line), &rows[i]);
+        statsprintf(conn, "%s", line);
+    }
+}
+
 /*
  * A connection's own append handle, checked against its cap. Below the cap this is one
  * fstat. Over it the file is trimmed (unless a trim is already running - the maintenance pass
diff --git a/device_server/logfiles.h b/device_server/logfiles.h
index 4ff10e0..5f7b90d 100644
--- a/device_server/logfiles.h
+++ b/device_server/logfiles.h
@@ -1,5 +1,6 @@
 #ifndef LOGFILES_H_INCLUDED
 #define LOGFILES_H_INCLUDED
+#include <time.h>
 #include "connection.h"
 void logvfprintf( connection * conn, const char * format, va_list arglist) ;
 void gpsvfprintf( connection * conn, const char * format, va_list arglist ) ;
@@ -23,6 +24,19 @@ void log_event(connection * conn, const unsigned char * response) ;
 void log_event_at(connection * conn, const unsigned char * response, float lat, float lon);
 void write_stat(connection * conn, char * value_name, float value);
 void write_stat_at(connection * conn, char * value_name, float value, time_t when);
+
+/*
+ * One reading of a batch: its own time, a name and a value. write_stats_batch() writes a batch
+ * the way write_stat_at() writes one, except that readings older than the end of the stats file
+ * are merged into it in time order instead of appended - see there.
+ */
+typedef struct {
+    time_t when;
+    char name[64];
+    float value;
+} stat_row;
+
+void write_stats_batch(connection * conn, stat_row * rows, size_t n);
 void write_sat_count(connection * conn, int position_type, int num_sats);
 void statsvfprintf( connection * conn, const char * format, va_list arglist);
 void statsprintf( connection * conn, const char * format, ... ) ;