# Architecture

A short map for contributors: what runs where, how a command travels, and where to make a change.

## Overview

```
 Browser tab                                   Node server (app/server)               kvrocks / Redis
┌──────────────────────────┐   WebSocket /ws   ┌───────────────────────────┐   RESP   ┌──────────────┐
│ Vue 2 UI (app/src)       │  JSON RPC frames  │ Express: static UI, /api/* │  TCP     │ standalone,  │
│  components/*.vue        │ ───────────────▶  │ Session per socket         │ ───────▶ │ cluster,     │
│  web/remoteRedis.js      │ ◀───────────────  │  ioredis clients           │ ◀─────── │ sentinel     │
│  (ioredis look-alike)    │  replies, events  │  allow-list, read-only     │          │ (SSH / TLS)  │
└──────────────────────────┘                   │  keyStats (server-side)    │          └──────────────┘
                                               └───────────────────────────┘
```

The UI is Another Redis Desktop Manager's Electron renderer, unchanged where possible. A browser cannot open TCP
sockets, so every ioredis client lives in the server and the UI talks to it through `remoteRedis.js`, which
exposes the same methods ARDM's components already call.

## A command, end to end

1. A component calls `client.hgetall('key')` on a `RemoteClient` (`app/src/web/remoteRedis.js`).
2. `RemoteClient` sends `{ id, op: 'cmd', cid, nid?, method: 'hgetall', args: ['key'] }` over the tab's WebSocket.
   Buffers are tagged so binary keys and values survive JSON (`app/src/web/codec.js` ↔ `app/server/codec.mjs`).
3. The server (`app/server/index.mjs`, class `Session`) checks the method against the **allow-list** (every
   command ioredis knows, plus `call`/`callBuffer`) and, on read-only connections, against the **write-command
   rules**. Then it runs it on the connection's ioredis client (`nid` picks one node of a cluster).
4. The reply comes back as `{ id, ok: true, result }` or `{ id, ok: false, error }`. Client events
   (`ready`, `error`, `message`, `monitor`, cluster `nodes` changes) are pushed as `{ event, cid, args }`.

Connections belong to the socket that opened them and are closed when the tab closes.

## RPC operations

| `op` | What it does |
|---|---|
| `connect` | Create an ioredis client (standalone, cluster, sentinel; SSH tunnel and TLS via `redisFactory.mjs`) |
| `cmd` | Run one allowed method on a connection or a cluster node |
| `multi` | Run a list of commands in a MULTI/EXEC transaction |
| `duplicate` | Open a second connection with the same options (pub/sub) |
| `monitor` | Start MONITOR on a dedicated connection, streaming `monitor` events |
| `keyStats` | Scan the keyspace on the server and return the summary (`keyStats.mjs`) |
| `noRetry` | Stop reconnect attempts for a connection |
| `close` | Close a connection |

HTTP endpoints: `/healthz`, `/api/defaults` (connections offered on first launch), `/api/presets` (dataset presets).

## Where things are

| Path | What |
|---|---|
| `app/server/index.mjs` | HTTP + WebSocket server, sessions, allow-list, read-only rules, auth, origin check |
| `app/server/redisFactory.mjs` | ARDM's connection code (cluster, sentinel, SSH, TLS), moved server-side |
| `app/server/keyStats.mjs` | Key statistics: pipelined SCAN/TYPE/size, pattern grouping, index sorted sets |
| `app/server/codec.mjs`, `app/src/web/codec.js` | Buffer-safe JSON encoding, both sides |
| `app/src/web/remoteRedis.js` | The ioredis stand-in used by the UI |
| `app/src/web/{electron,fs,readline,child_process,files}.js` | Browser shims replacing Electron/Node modules (webpack aliases) |
| `app/src/web/presets.js`, `genericQueries.js` | Dataset presets: loading, detection, built-in General set |
| `app/src/components/KvrocksAdmin.vue`, `KeyStats.vue`, `SampleQueries.vue` | The kvrocks-specific tabs |
| `app/src/components/*` (others) | ARDM's UI: key tree, editors, console, status, settings |
| `app/presets/` | Preset folder served by the server (`KVGUI_PRESETS_DIR`) |
| `app/test/` | RPC smoke and cluster tests (run in CI) |
| `demo/vulnerability-lookup/` | Demo compose, seed script, preset, cluster init |

## Security boundaries

The server is a proxy that can reach anything its host can, so the protections live **on the server**:

- listens on `127.0.0.1` by default; optional HTTP basic auth (`KVGUI_PASSWORD`);
- WebSocket upgrades only from the same origin (blocks other sites from using your browser as a bridge);
- only ioredis command methods can be called, never arbitrary client methods;
- read-only connections refuse write and admin commands in the server, not just in the UI;
- reading certificate or key files from the server's disk is off unless `KVGUI_ALLOW_SERVER_FILES=1`;
- ARDM's custom formatters (which ran shell commands) are disabled.

Changes that touch any of these need a test in `app/test/rpc-smoke.mjs`.

## Key statistics in brief

`keyStats.mjs` scans each master node with `SCAN COUNT 1000`, pipelines `TYPE` and a size command per key, and
stops at the key limit. Key names are split on `:`; id-like segments (numbers, dates, UUIDs, `word-123`) become
`*`, then positions where a group of otherwise-equal keys has ten or more distinct values collapse to `*`. A
preset's `indexPattern` marks sorted sets to list as indexes (and keeps their names intact); without one the
largest sorted sets are listed.

## Making a change

- **UI-only change**: edit the component, run `npm run dev` in `app/` and check it in the browser, in both light and
  dark themes (Settings), and on a long page.
- **New server operation**: add a `case` in `Session.op`, a method in `remoteRedis.js`, and a test.
- **New preset**: a JSON file, see `app/presets/README.md`. No UI code needed.
- Before pushing: `npm run lint:check`, `npm run check:server`, `npm run build`, and the tests (see CONTRIBUTING.md).
