# Caching Code Consolidation Plan

## Goal

Move all caching_relay source code into a `caching/` directory inside c-relay-pg,
and switch the launcher to use PostgreSQL mode (`-p <pg-conn>`) so all config
comes from the c-relay-pg config table — no JSON config file needed.

## Key Finding

The caching_relay binary **already supports PG mode** via `-p <pg-conn>`. Its
`pg_config.c` reads the same config table keys the caching page sets
(`caching_root_npubs`, `caching_bootstrap_relays`, `caching_kinds`, etc.), and
`pg_inbox.c` writes fetched events to the `caching_event_inbox` table. The PG
schema tables already exist in `src/pg_schema.sql`.

## Steps

### Step 1: Create `caching/` directory and copy source files

Copy all `src/*.c` and `src/*.h` from `/home/user/lt/caching_relay/src/` into
`caching/src/` in this repo. Also copy the Makefile, build_static.sh,
Dockerfile.alpine-musl, and VERSION.

Files to copy:
- src/main.c, src/main.h
- src/config.c, src/config.h (legacy JSON config — kept for fallback)
- src/pg_config.c, src/pg_config.h (PG config reader)
- src/pg_inbox.c, src/pg_inbox.h (PG inbox writer)
- src/backfill.c, src/backfill.h
- src/follow_graph.c, src/follow_graph.h
- src/live_subscriber.c, src/live_subscriber.h
- src/relay_sink.c, src/relay_sink.h (legacy WebSocket sink — kept for fallback)
- src/relay_discovery.c, src/relay_discovery.h
- src/state.c, src/state.h
- src/debug.c, src/debug.h
- src/jsonc_strip.c, src/jsonc_strip.h
- Makefile
- VERSION

### Step 2: Adapt the Makefile

Update `caching/Makefile` to:
- Point `NOSTR_CORE_DIR` at `../nostr_core_lib` (sibling in this repo)
- Output binary to `caching/caching_relay` or `build/caching_relay`

### Step 3: Update the launcher to use PG mode

Update `src/caching_service_launcher.c`:
- Change `caching_service_start_fork()` to pass `-p <pg_conn>` instead of
  `-c <config_path>`
- Update `caching_service_start()` to read `caching_service_pg_conn` from config
  table instead of `caching_service_config_path`

### Step 4: Remove config_path from defaults and UI

- Remove `caching_service_config_path` from `src/default_config_event.h`
- Remove the "Caching Service Config Path" field from `api/index.html`
- Remove the field from `CACHING_CONFIG_FIELDS` in `api/index.js`
- Update `caching_service_binary_path` default to point at the new build
  location (`./caching/caching_relay` or `./build/caching_relay`)

### Step 5: Build and test

- Build the caching_relay binary from the new `caching/` directory
- Build c-relay-pg with the updated launcher
- Test: set caching config on the page, apply, start service, verify it runs
  in PG mode reading config from the database

### Step 6: Push

Run `./increment_and_push.sh` with a descriptive commit message.
