Compare commits

..
2 Commits
Author SHA1 Message Date
Alexander Heldt 50947d077f Leave the overnight gap out of the Timing panel 2026-09-29 20:34:36 +00:00
Alexander Heldt 15211e32b0 Add a read-only integration feed of walks and meals
GET /api/integration/events?since=<unix ms> returns one account's walk
starts and meals that happened or changed since then, tombstones
included, for other services on the same host. It is authenticated
with a bearer token rather than a session and cannot write anything.

Enabled with -integration-token-file (services.puppy-tracker
.integration.tokenFile); -integration-user picks the account, and
defaults to the only one.
2026-09-29 19:13:28 +00:00
7 changed files with 242 additions and 10 deletions

No files matched your search

+29 -1
View File
@@ -63,6 +63,24 @@ in
'';
};
integration = {
tokenFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
example = "/run/agenix/schema-puppy-token";
description = ''
File holding a bearer token (just the token) that unlocks the
read-only GET /api/integration/events feed of walks and meals, used by
other services on this host. When null the endpoint doesn't exist.
'';
};
user = lib.mkOption {
type = lib.types.str;
default = "";
description = "Email of the account the feed exposes. Empty means the only account.";
};
};
package = lib.mkOption {
type = lib.types.package;
default = serverPkg;
@@ -90,7 +108,17 @@ in
"-addr ${cfg.address}:${toString cfg.port}"
"-static ${cfg.staticPackage}/share/puppy-tracker"
"-data /var/lib/puppy-tracker/puppy.db"
] ++ lib.optional cfg.secureCookies "-secure-cookies");
] ++ lib.optional cfg.secureCookies "-secure-cookies"
# %d is the unit's credentials directory (see LoadCredential below).
++ lib.optionals (cfg.integration.tokenFile != null) [
"-integration-token-file %d/integration-token"
"-integration-user ${lib.escapeShellArg cfg.integration.user}"
]);
# DynamicUser can't own the secret, so systemd reads it as root and
# hands the service a private copy.
LoadCredential = lib.optional (cfg.integration.tokenFile != null)
"integration-token:${toString cfg.integration.tokenFile}";
# Secrets (registration code, Web Push key) are read from env files kept
# out of the store, exposed to the server as PUPPY_INVITE_CODE and
+105
View File
@@ -0,0 +1,105 @@
package main
import (
"crypto/subtle"
"database/sql"
"encoding/json"
"errors"
"log"
"net/http"
"strconv"
"strings"
)
// Integration is a read-only, token-authenticated view of one account's walks
// and meals, for other services on the same host (the household planner,
// schema, ticks off its dog duties from it). It is not a session: there is no
// cookie, it sees one configured account, and it can't write anything.
type Integration struct {
db *sql.DB
token string
// email picks the account whose events are exposed. Empty means "the only
// account", and refuses to guess once there are several.
email string
}
type integrationEvent struct {
ID string `json:"id"`
Type string `json:"type"`
At int64 `json:"at"`
Deleted bool `json:"deleted,omitempty"`
}
func (in *Integration) userID() (string, error) {
if in.email != "" {
var id string
err := in.db.QueryRow(`SELECT id FROM users WHERE email = ? COLLATE NOCASE`, in.email).Scan(&id)
return id, err
}
rows, err := in.db.Query(`SELECT id FROM users LIMIT 2`)
if err != nil {
return "", err
}
defer rows.Close()
var ids []string
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return "", err
}
ids = append(ids, id)
}
if len(ids) != 1 {
return "", errors.New("set -integration-user: there is not exactly one account")
}
return ids[0], nil
}
// GET /api/integration/events?since=<unix ms> returns the account's walk
// starts and meals that happened, or were changed, since then — tombstones
// included, so a consumer can undo what a deleted event did.
func (in *Integration) handleEvents(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || subtle.ConstantTimeCompare([]byte(got), []byte(in.token)) != 1 {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
since, err := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
if err != nil {
http.Error(w, "since: want unix milliseconds", http.StatusBadRequest)
return
}
uid, err := in.userID()
if err != nil {
log.Printf("integration: %v", err)
http.Error(w, "no account to read from", http.StatusConflict)
return
}
rows, err := in.db.Query(`
SELECT id, type, at, deleted FROM events
WHERE user_id = ? AND type IN ('walk-start', 'eat') AND (at >= ? OR updated >= ?)
ORDER BY at`, uid, since, since)
if err != nil {
log.Printf("integration: %v", err)
http.Error(w, "server error", http.StatusInternalServerError)
return
}
defer rows.Close()
out := []integrationEvent{}
for rows.Next() {
var e integrationEvent
if err := rows.Scan(&e.ID, &e.Type, &e.At, &e.Deleted); err != nil {
log.Printf("integration: %v", err)
http.Error(w, "server error", http.StatusInternalServerError)
return
}
out = append(out, e)
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(map[string]any{"events": out})
}
+71
View File
@@ -0,0 +1,71 @@
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
)
func TestIntegrationEvents(t *testing.T) {
db, err := openDB(filepath.Join(t.TempDir(), "puppy.db"))
if err != nil {
t.Fatal(err)
}
defer db.Close()
db.Exec(`INSERT INTO users (id, email, password, created) VALUES ('u1', 'a@x', 'h', 0)`)
db.Exec(`INSERT INTO users (id, email, password, created) VALUES ('u2', 'b@x', 'h', 0)`)
store := newStore(db)
store.sync("u1", "", "", []Event{
{ID: "walk", Type: "walk-start", At: 1000, UpdatedAt: 1000},
{ID: "meal", Type: "eat", At: 2000, UpdatedAt: 2000},
{ID: "pee", Type: "pee", At: 2000, UpdatedAt: 2000},
{ID: "old", Type: "eat", At: 10, UpdatedAt: 10},
{ID: "gone", Type: "eat", At: 10, UpdatedAt: 3000, Deleted: true},
})
store.sync("u2", "", "", []Event{{ID: "theirs", Type: "eat", At: 2000, UpdatedAt: 2000}})
get := func(in *Integration, auth, since string) (int, []integrationEvent) {
req := httptest.NewRequest("GET", "/api/integration/events?since="+since, nil)
if auth != "" {
req.Header.Set("Authorization", "Bearer "+auth)
}
rec := httptest.NewRecorder()
in.handleEvents(rec, req)
var body struct{ Events []integrationEvent }
json.NewDecoder(rec.Body).Decode(&body)
return rec.Code, body.Events
}
in := &Integration{db: db, token: "tok", email: "A@x"}
if code, _ := get(in, "", "0"); code != http.StatusUnauthorized {
t.Errorf("no token = %d", code)
}
if code, _ := get(in, "nope", "0"); code != http.StatusUnauthorized {
t.Errorf("wrong token = %d", code)
}
code, evs := get(in, "tok", "500")
if code != 200 {
t.Fatalf("code = %d", code)
}
got := map[string]bool{}
for _, e := range evs {
got[e.ID] = e.Deleted
}
// Recent walks and meals, plus the tombstone updated since; not the pee,
// not the old meal, not the other account's.
if len(got) != 3 || !got["gone"] {
t.Errorf("events = %+v", evs)
}
for _, id := range []string{"walk", "meal"} {
if _, ok := got[id]; !ok {
t.Errorf("missing %s", id)
}
}
// With two accounts, no configured user is ambiguous.
if code, _ := get(&Integration{db: db, token: "tok"}, "tok", "0"); code != http.StatusConflict {
t.Errorf("ambiguous = %d", code)
}
}
+15
View File
@@ -864,6 +864,10 @@ func main() {
"mark session cookies Secure (enable when served over HTTPS / behind a TLS proxy)")
vapidKey := flag.String("vapid-key", os.Getenv("PUPPY_VAPID_KEY"),
"base64url P-256 private key for Web Push (env PUPPY_VAPID_KEY); generated next to the DB when unset")
integrationTokenFile := flag.String("integration-token-file", "",
"file holding the bearer token for the read-only /api/integration/events; unset disables it")
integrationUser := flag.String("integration-user", "",
"email of the account /api/integration/events exposes; empty means the only account")
flag.Parse()
db, err := openDB(*dataPath)
@@ -1096,6 +1100,17 @@ func main() {
mux.HandleFunc("/api/reminders", auth.requireOwner(scheduler.handleReminders))
}
// Read-only feed of walks and meals for other services on this host.
if *integrationTokenFile != "" {
raw, err := os.ReadFile(*integrationTokenFile)
token := strings.TrimSpace(string(raw))
if err != nil || token == "" {
log.Fatalf("integration token file %s: unreadable or empty (%v)", *integrationTokenFile, err)
}
in := &Integration{db: db, token: token, email: *integrationUser}
mux.HandleFunc("/api/integration/events", in.handleEvents)
}
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
+20 -8
View File
@@ -1041,13 +1041,18 @@
// "longest" figure far worse than the sparse day this feature exists to
// take out of the numbers.
if (spansExcluded(times[i - 1], times[i])) continue;
// The gap from a day's last event to the next day's first is the night,
// not how often he needs to go: it measures bedtime and a lie-in, and at
// eight-plus hours a night it made "longest" a sleep figure and pulled
// the typical gap up with it. Only gaps within one day are counted.
if (ymd(new Date(times[i - 1])) !== ymd(new Date(times[i]))) continue;
gaps.push(times[i] - times[i - 1]);
}
return gaps.sort((a, b) => a - b);
}
// Median is used for the "typical" gap because it ignores the single long
// overnight gap each day, so it reflects real daytime frequency.
// Median is used for the "typical" gap so that a single unusually long
// stretch — a long nap, a day out — doesn't drag it the way a mean would.
function median(sorted) {
if (sorted.length === 0) return null;
const mid = Math.floor(sorted.length / 2);
@@ -1072,11 +1077,11 @@
if (!svg || !note) continue;
const gaps = gapsBetween(events, row.type);
const last = lastEventOfType(events, row.type);
drawTimingChart(svg, note, row, gaps, last ? Math.max(0, Date.now() - last.at) : null);
drawTimingChart(svg, note, row, gaps, last ? Math.max(0, Date.now() - last.at) : null, events);
}
}
function drawTimingChart(svg, note, row, gaps, since) {
function drawTimingChart(svg, note, row, gaps, since, events) {
const typical = median(gaps);
const shortest = gaps[0] ?? null;
const longest = gaps[gaps.length - 1] ?? null;
@@ -1087,8 +1092,15 @@
svg.innerHTML = "";
svg.style.display = "none";
note.hidden = false;
// Several logged but none sharing a day (one meal a day, say) is a
// different case from one logged: every gap there was overnight.
const cutoff = startOfDay(new Date());
cutoff.setDate(cutoff.getDate() - (chartDays() - 1));
const inWindow = events.filter(e => e.type === row.type && e.at >= cutoff.getTime()).length;
note.textContent = since == null
? `No ${row.noun}s logged in the last ${chartDays()} days.`
: inWindow >= 2
? `No two ${row.noun}s on the same day in the last ${chartDays()} days — the gap overnight isn't counted, so there is nothing to measure yet.`
: `One ${row.noun} logged, ${formatDuration(since)} ago — log another to see the typical gap.`;
return;
}
@@ -1099,10 +1111,10 @@
const innerW = W - ML - MR;
const trackY = 20, trackH = 8;
// Gaps are heavily skewed: one long overnight gap a night sits alongside
// daytime gaps a tenth its length, and on a plain linear axis it squashes
// the everyday range — the part you actually read — into the first tenth of
// the track. So the axis is stretched, the way the sleep trend's is above
// Gaps are skewed: the odd long stretch (a long nap, an afternoon out) sits
// alongside everyday gaps a fraction its length, and on a plain linear axis
// it squashes the everyday range — the part you actually read — into the
// first stretch of the track. So the axis is stretched, the way the sleep trend's is above
// 10h: the typical gap is pinned to the middle, the shortest-to-typical
// stretch gets the left half and typical-to-longest the right. Reading it
// is then the same in every row — left of centre is sooner than usual,
+1
View File
@@ -1,4 +1,5 @@
[
{ "date": "2026-09-29", "text": "The Timing panel no longer counts the night. The gap from each day's last pee, poo or meal to the next morning's first was being measured like any other, so every window held several eight-hour-plus “gaps” that were really just bedtime — the longest figure was a sleep figure and the typical gap was pulled up with it. Only gaps within a single day are measured now, so the bars show how often he needs to go out while he's up and about. The “since the last one” marker is unchanged, so first thing in the morning it still reads as overdue — which, before the first trip out, it is" },
{ "date": "2026-09-26", "text": "Tapping the tab you are already on scrolls back to the top of the page, the way it does in most phone apps — handy after scrolling a long way down Habits or the history. Switching to a different tab still leaves you where you were, as before" },
{ "date": "2026-09-24", "text": "Kinds of food are now created in one place only — Settings → Food kinds. The Ate dialog no longer has a box for inventing one on the spot; it still lets you pick from the kinds you have, exactly as before. Making them mid-meal put a bit of list-keeping in the middle of logging, where the thing you actually came to do is record that the dog ate, and a kind typed in a hurry is easy to get slightly wrong — nothing stops two near-identical kinds existing, and clearing one up afterwards means relabelling every meal logged under it first" },
{ "date": "2026-09-22", "text": "Habits has a Meals log beside the Food (grams) chart: every meal you have logged, newest first, across every day rather than just the one you are looking at. It is there because a meal's amount and its kind are both optional — which is what makes them easy to lose track of. A meal with no kind sits in the grey band on the chart, a meal with no amount is quietly left out of it, and until now there was nowhere to go and see which ones those were. The filter chips carry their own counts, so “No kind 412” tells you the size of the gap before you tap anything, and picking a filter lists exactly those meals; tap any row to fill in what it is missing, in the same edit dialog as everywhere else. If you started using food kinds after months of logging, the “No kind” filter also offers to label the whole list at once: choose a kind and it sets it on every meal shown. Tick “Only before” a date first if you switched foods partway, so the older meals take one kind and the newer ones keep what they have — worth getting right, because there is no undo. The panel folds away by tapping its heading like any other, and appears only once you have logged a meal; the “No kind” filter and the bulk label appear only once you have created a kind, so nothing changes for anyone not using them. A guest can see the list but cannot relabel your meals" },
+1 -1
View File
@@ -383,7 +383,7 @@
</div>
<!-- The axis is stretched (see drawTimingChart), so say what the middle
of a bar means rather than leave it to be inferred. -->
<p class="muted-note">The middle of every bar is that type's typical gap: left of it is sooner than usual, right of it is longer, and the faded stretch runs out to the longest gap in the window.</p>
<p class="muted-note">The middle of every bar is that type's typical gap: left of it is sooner than usual, right of it is longer, and the faded stretch runs out to the longest gap in the window. The gap overnight, from each day's last to the next day's first, isn't counted.</p>
</section>
<!-- One panel for the three views of the same events: how many a day,