@karlis-vagalis/pi-flare 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -17
- package/dist/backup.js +50 -3
- package/dist/index.js +42 -6
- package/dist/manager.js +27 -22
- package/dist/restore.js +2 -11
- package/dist/schema.js +3 -0
- package/docs/runtime.md +45 -20
- package/package.json +2 -3
package/README.md
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
# pi-flare
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Small web apps and static artifacts, straight from your [Pi](https://pi.dev/) session.
|
|
4
4
|
|
|
5
|
-
Flare gives
|
|
6
|
-
|
|
7
|
-
agent can edit them, and the changes go live without a deployment step.
|
|
5
|
+
Flare gives the agent a place to serve small apps, HTML pages, reports, and
|
|
6
|
+
previews, so it can hand you a URL to open in your browser.
|
|
8
7
|
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
It runs locally on [celld](https://celld.dev/), borrowing ideas from Cloudflare
|
|
9
|
+
Workers, Durable Objects, and Wrangler. Use static hosting for artifacts, a
|
|
10
|
+
Worker for backend code, or a durable app for saved state. Edit the files
|
|
11
|
+
directly; changes go live without a deployment step.
|
|
12
|
+
|
|
13
|
+
If needed, you can later adapt an app for Cloudflare or another host.
|
|
11
14
|
|
|
12
15
|
## Requirements
|
|
13
16
|
|
|
@@ -26,7 +29,7 @@ Install from the [pi-mono repository](https://github.com/karlis-vagalis/pi-mono)
|
|
|
26
29
|
pi install git:github.com/karlis-vagalis/pi-mono
|
|
27
30
|
```
|
|
28
31
|
|
|
29
|
-
To install only Flare from npm
|
|
32
|
+
To install only Flare from npm:
|
|
30
33
|
|
|
31
34
|
```bash
|
|
32
35
|
pi install npm:@karlis-vagalis/pi-flare
|
|
@@ -42,6 +45,10 @@ something:
|
|
|
42
45
|
|
|
43
46
|
> Create a small counter app with Flare. Save the count so it survives restarts.
|
|
44
47
|
|
|
48
|
+
Or ask for a static artifact:
|
|
49
|
+
|
|
50
|
+
> Turn this analysis into an HTML report and host it with Flare so I can view it in my browser.
|
|
51
|
+
|
|
45
52
|
Open [127.0.0.1:53762](http://127.0.0.1:53762/) to browse your apps. Source files
|
|
46
53
|
live under `~/.pi/flare/<app-id>/`. Static file edits are served immediately;
|
|
47
54
|
backend edits trigger a rebuild. Reload the browser to see frontend changes.
|
|
@@ -57,20 +64,50 @@ Pi gets five tools:
|
|
|
57
64
|
| `flare_delete` | Remove its source files, keeping durable data |
|
|
58
65
|
|
|
59
66
|
Apps stay until you delete them unless you set a lifetime with `ttl_seconds`.
|
|
60
|
-
|
|
61
|
-
|
|
67
|
+
Closing Pi does not stop Flare: apps and artifacts keep serving, and file watching
|
|
68
|
+
and scheduled backups continue. Run `/flare stop` when you want to shut down the
|
|
69
|
+
shared runtime. It keeps your files and data; the next Flare command or tool call
|
|
70
|
+
starts it again.
|
|
62
71
|
|
|
63
72
|
## Backups and settings
|
|
64
73
|
|
|
65
74
|
Flare backs up app files and durable data every 12 hours while it is running.
|
|
66
|
-
Backups go to `~/.pi/flare-backups
|
|
75
|
+
Backups go to `~/.pi/flare-backups`. By default, all backups are kept. To keep only
|
|
76
|
+
the newest completed backup for each Flare home:
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
PI_FLARE_BACKUP_KEEP=1 pi
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Older backups are pruned only after a new backup succeeds. The limit applies to
|
|
83
|
+
scheduled backups, manual backups, and restore recovery snapshots.
|
|
67
84
|
- `/flare backup` makes a backup now.
|
|
68
85
|
- `/flare restore <backup>` restores all apps and durable data, after saving a
|
|
69
86
|
recovery backup of the current state.
|
|
70
87
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
88
|
+
### Environment variables
|
|
89
|
+
|
|
90
|
+
Set these before starting Pi. Sessions sharing a runtime must use the same settings.
|
|
91
|
+
|
|
92
|
+
| Variable | Default | What it changes |
|
|
93
|
+
| -------------------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
94
|
+
| `PI_FLARE_HOME` | `~/.pi/flare` | Where app files, durable data, and runtime files are stored. |
|
|
95
|
+
| `PI_FLARE_HOST` | `127.0.0.1` | IPv4 or IPv6 address the app server listens on. |
|
|
96
|
+
| `PI_FLARE_PORT` | `53762` | Port used to serve apps and the app directory. |
|
|
97
|
+
| `PI_FLARE_CONTROL_PORT` | `53763` | Private manager port, always bound to `127.0.0.1`. |
|
|
98
|
+
| `PI_FLARE_PUBLIC_URL` | Derived from host and port | Base URL returned by the tools, for example when using a reverse proxy. Does not change the bind address. |
|
|
99
|
+
| `PI_FLARE_BACKUP_DIR` | `~/.pi/flare-backups` | Where backups are saved. Must be outside the app home, including through symlinks. |
|
|
100
|
+
| `PI_FLARE_BACKUP_INTERVAL_HOURS` | `12` | Hours between scheduled backups. Must be positive; fractions such as `0.5` work. |
|
|
101
|
+
| `PI_FLARE_BACKUP_KEEP` | `0` (unlimited) | Number of completed backups to keep per Flare home. Set to `1` to keep only the latest. |
|
|
102
|
+
| `PI_FLARE_CELLD` | `celld` | Command or executable path used to start celld. |
|
|
103
|
+
| `CELLD_ESBUILD` | `esbuild` | Command or executable path used to bundle Worker code. |
|
|
104
|
+
|
|
105
|
+
The two ports must be different and between `1024` and `65535`. Run `/flare stop`
|
|
106
|
+
and close sessions using Flare before changing its environment, then start Pi again.
|
|
107
|
+
For a separate app home, choose separate public and control ports too.
|
|
108
|
+
|
|
109
|
+
See the [reference](docs/runtime.md) for routing examples, backup details, and
|
|
110
|
+
runtime limits.
|
|
74
111
|
|
|
75
112
|
## Local use
|
|
76
113
|
|
|
@@ -88,12 +125,8 @@ From the repository root:
|
|
|
88
125
|
bun install
|
|
89
126
|
bun run --filter @karlis-vagalis/pi-flare check
|
|
90
127
|
bun run --filter @karlis-vagalis/pi-flare build
|
|
91
|
-
bun run --filter @karlis-vagalis/pi-flare smoke
|
|
92
128
|
```
|
|
93
129
|
|
|
94
|
-
The smoke check requires celld and esbuild. It uses temporary apps and ports,
|
|
95
|
-
not your existing Flare data.
|
|
96
|
-
|
|
97
130
|
Releases use the same version as the other extensions in this repository.
|
|
98
131
|
Maintainers can publish all packages locally with `just publish` from the root,
|
|
99
132
|
or push a `v*` tag to use the GitHub workflow.
|
package/dist/backup.js
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import { Database } from "bun:sqlite";
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
-
import { copyFile, cp, mkdir, open as promises_open, readdir, realpath, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { copyFile, cp, lstat, mkdir, open as promises_open, readFile, readdir, realpath, rename, rm, writeFile } from "node:fs/promises";
|
|
4
4
|
import { resolve } from "node:path";
|
|
5
5
|
import { z } from "zod";
|
|
6
|
-
import { containsPath } from "./schema.js";
|
|
6
|
+
import { containsPath, message } from "./schema.js";
|
|
7
7
|
import { appIds } from "./storage.js";
|
|
8
8
|
const SnapshotTimeSchema = z.string().regex(/^backup-\d+-[a-f0-9-]{36}$/).transform((name)=>Number(name.split("-")[1])).pipe(z.number().int().nonnegative());
|
|
9
|
+
const BackupMetadataSchema = z.object({
|
|
10
|
+
version: z.union([
|
|
11
|
+
z.literal(1),
|
|
12
|
+
z.literal(2)
|
|
13
|
+
]),
|
|
14
|
+
root: z.string(),
|
|
15
|
+
completedAt: z.number().int().nonnegative()
|
|
16
|
+
});
|
|
9
17
|
const sqliteHeader = Buffer.from("SQLite format 3\0");
|
|
10
18
|
function backupRoot(settings) {
|
|
11
19
|
const key = createHash("sha256").update(settings.root).digest("hex").slice(0, 16);
|
|
@@ -28,6 +36,37 @@ async function latestBackup(settings) {
|
|
|
28
36
|
return;
|
|
29
37
|
}
|
|
30
38
|
}
|
|
39
|
+
async function pruneBackups(settings, newest) {
|
|
40
|
+
if (0 === settings.backupKeep) return;
|
|
41
|
+
const base = backupRoot(settings);
|
|
42
|
+
const previous = [];
|
|
43
|
+
for (const entry of (await readdir(base, {
|
|
44
|
+
withFileTypes: true
|
|
45
|
+
}))){
|
|
46
|
+
const time = SnapshotTimeSchema.safeParse(entry.name);
|
|
47
|
+
if (!entry.isDirectory() || !time.success) continue;
|
|
48
|
+
const path = resolve(base, entry.name);
|
|
49
|
+
if (path !== newest.path) try {
|
|
50
|
+
const metadataPath = resolve(path, "backup.json");
|
|
51
|
+
if (!(await lstat(metadataPath)).isFile()) continue;
|
|
52
|
+
const metadata = BackupMetadataSchema.safeParse(JSON.parse(await readFile(metadataPath, "utf8")));
|
|
53
|
+
if (metadata.success && metadata.data.root === settings.root && metadata.data.completedAt === time.data) previous.push({
|
|
54
|
+
path,
|
|
55
|
+
completedAt: metadata.data.completedAt
|
|
56
|
+
});
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (!(error instanceof SyntaxError) && "ENOENT" !== error.code) throw error;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
previous.sort((a, b)=>b.completedAt - a.completedAt || b.path.localeCompare(a.path));
|
|
62
|
+
for (const snapshot of previous.slice(settings.backupKeep - 1)){
|
|
63
|
+
await rm(snapshot.path, {
|
|
64
|
+
recursive: true,
|
|
65
|
+
force: true
|
|
66
|
+
});
|
|
67
|
+
console.log(`FLARE_BACKUP_PRUNE ${snapshot.path}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
31
70
|
async function copyState(source, destination) {
|
|
32
71
|
await mkdir(destination, {
|
|
33
72
|
recursive: true,
|
|
@@ -108,6 +147,14 @@ async function createBackup(settings) {
|
|
|
108
147
|
const path = resolve(base, `backup-${completedAt}-${randomUUID()}`);
|
|
109
148
|
await rename(temporary, path);
|
|
110
149
|
console.log(`FLARE_BACKUP ${path}`);
|
|
150
|
+
try {
|
|
151
|
+
await pruneBackups(settings, {
|
|
152
|
+
path,
|
|
153
|
+
completedAt
|
|
154
|
+
});
|
|
155
|
+
} catch (error) {
|
|
156
|
+
console.error(`Flare backup retention: ${message(error)}`);
|
|
157
|
+
}
|
|
111
158
|
return {
|
|
112
159
|
path,
|
|
113
160
|
completedAt
|
|
@@ -153,4 +200,4 @@ class Backups {
|
|
|
153
200
|
await this.running;
|
|
154
201
|
}
|
|
155
202
|
}
|
|
156
|
-
export { Backups, SnapshotTimeSchema, backupRoot, createBackup };
|
|
203
|
+
export { BackupMetadataSchema, Backups, SnapshotTimeSchema, backupRoot, createBackup };
|
package/dist/index.js
CHANGED
|
@@ -45,7 +45,7 @@ async function probe(secret) {
|
|
|
45
45
|
const parsed = HealthSchema.safeParse(await response.json());
|
|
46
46
|
if (!parsed.success) throw new Error("Unrecognized Flare manager; refusing to replace its owner");
|
|
47
47
|
const health = parsed.data;
|
|
48
|
-
if (health.root !== config.root || health.host !== config.host || health.port !== config.port || health.sourceRoot !== sourceRoot || health.publicUrl !== publicUrl || (health.backupDirectory ?? defaultBackupDirectory) !== config.backupDirectory || (health.backupIntervalMs ?? defaultBackupIntervalMs) !== config.backupIntervalMs) throw new Error("Another Flare configuration owns this control port; use matching settings or different ports");
|
|
48
|
+
if (health.root !== config.root || health.host !== config.host || health.port !== config.port || health.sourceRoot !== sourceRoot || health.publicUrl !== publicUrl || (health.backupDirectory ?? defaultBackupDirectory) !== config.backupDirectory || (health.backupIntervalMs ?? defaultBackupIntervalMs) !== config.backupIntervalMs || (health.backupKeep ?? 0) !== config.backupKeep) throw new Error("Another Flare configuration owns this control port; use matching settings or different ports");
|
|
49
49
|
return {
|
|
50
50
|
kind: "ready",
|
|
51
51
|
health
|
|
@@ -159,6 +159,11 @@ function src(pi) {
|
|
|
159
159
|
});
|
|
160
160
|
return starting;
|
|
161
161
|
}
|
|
162
|
+
async function disconnect(release = true) {
|
|
163
|
+
const current = connection;
|
|
164
|
+
connection = void 0;
|
|
165
|
+
await current?.close(release);
|
|
166
|
+
}
|
|
162
167
|
async function request(method, path, body, schema, signal, timeoutMs = 30000) {
|
|
163
168
|
signal?.throwIfAborted();
|
|
164
169
|
const secret = await ensure();
|
|
@@ -220,10 +225,43 @@ function src(pi) {
|
|
|
220
225
|
removed: z.literal(true)
|
|
221
226
|
}), "DELETE", ({ id })=>`/apps/${id}`);
|
|
222
227
|
pi.registerCommand("flare", {
|
|
223
|
-
description: "Show apps,
|
|
228
|
+
description: "Show apps, stop the runtime, back up, or restore: /flare [stop | backup | restore <name-or-path>]",
|
|
224
229
|
handler: async (args, ctx)=>{
|
|
225
230
|
try {
|
|
226
231
|
const input = args.trim();
|
|
232
|
+
if ("stop" === input) {
|
|
233
|
+
if (!ctx.isIdle()) throw new Error("Wait for the agent to finish before stopping Flare");
|
|
234
|
+
let secret;
|
|
235
|
+
try {
|
|
236
|
+
secret = connection?.secret ?? TokenSchema.parse(await readFile(tokenPath, "utf8"));
|
|
237
|
+
} catch (error) {
|
|
238
|
+
if ("ENOENT" !== error.code) throw error;
|
|
239
|
+
if (ctx.hasUI) ctx.ui.notify("Flare is not running", "info");
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
const current = await probe(secret);
|
|
243
|
+
if ("missing" === current.kind) {
|
|
244
|
+
await disconnect(false);
|
|
245
|
+
if (ctx.hasUI) ctx.ui.notify("Flare is not running", "info");
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if ("ready" !== current.kind) throw new Error("Flare is starting, stopping, or refreshing; retry shortly");
|
|
249
|
+
if (ctx.hasUI && !await ctx.ui.confirm("Stop Flare?", "Stop serving all apps and artifacts for every connected Pi session? Files and saved data will be kept.")) return;
|
|
250
|
+
const response = await fetch(`${controlUrl}/stop`, {
|
|
251
|
+
method: "POST",
|
|
252
|
+
headers: {
|
|
253
|
+
authorization: `Bearer ${secret}`
|
|
254
|
+
},
|
|
255
|
+
signal: AbortSignal.timeout(2000)
|
|
256
|
+
});
|
|
257
|
+
if (!response.ok) throw new Error(await response.text());
|
|
258
|
+
z.object({
|
|
259
|
+
stopping: z.literal(true)
|
|
260
|
+
}).parse(await response.json());
|
|
261
|
+
await disconnect(false);
|
|
262
|
+
if (ctx.hasUI) ctx.ui.notify("Flare is stopping. Your apps and data are kept; the next Flare command or tool call starts it again.", "info");
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
227
265
|
if ("backup" === input) {
|
|
228
266
|
const snapshot = await request("POST", "/backup", void 0, BackupInfoSchema, void 0, 300000);
|
|
229
267
|
if (ctx.hasUI) ctx.ui.notify(`Flare backup: ${snapshot.path}\nRestore with /flare restore ${basename(snapshot.path)}`, "info");
|
|
@@ -240,7 +278,7 @@ function src(pi) {
|
|
|
240
278
|
if (ctx.hasUI) ctx.ui.notify(`Restored ${result.restored.path}; Flare is restarting.\nRecovery backup: ${result.recovery.path}`, "info");
|
|
241
279
|
return;
|
|
242
280
|
}
|
|
243
|
-
if (input) throw new Error("Usage: /flare [backup | restore <backup-name-or-path>]");
|
|
281
|
+
if (input) throw new Error("Usage: /flare [stop | backup | restore <backup-name-or-path>]");
|
|
244
282
|
const apps = await request("GET", "/apps", void 0, z.array(InfoSchema));
|
|
245
283
|
if (ctx.hasUI) ctx.ui.notify(apps.length ? apps.map((app)=>`${app.id}: ${app.url} (${app.deployment.status})`).join("\n") : "Flare is running; use flare_create to create an app", "info");
|
|
246
284
|
} catch (error) {
|
|
@@ -256,9 +294,7 @@ function src(pi) {
|
|
|
256
294
|
});
|
|
257
295
|
pi.on("session_shutdown", async ()=>{
|
|
258
296
|
closed = true;
|
|
259
|
-
|
|
260
|
-
connection = void 0;
|
|
261
|
-
await current?.close().catch(()=>{});
|
|
297
|
+
await disconnect().catch(()=>{});
|
|
262
298
|
});
|
|
263
299
|
}
|
|
264
300
|
export default src;
|
package/dist/manager.js
CHANGED
|
@@ -36,10 +36,10 @@ let watcher;
|
|
|
36
36
|
let ready = false;
|
|
37
37
|
let stopping = false;
|
|
38
38
|
let finishing = false;
|
|
39
|
+
let shutdownRequested = false;
|
|
39
40
|
const backups = new Backups(config, mutate);
|
|
40
41
|
let backupCheck;
|
|
41
42
|
const leases = new Map();
|
|
42
|
-
let idle;
|
|
43
43
|
function mutate(action) {
|
|
44
44
|
const result = mutations.then(action);
|
|
45
45
|
mutations = result.then(()=>{}, ()=>{});
|
|
@@ -80,7 +80,7 @@ async function expiration(id) {
|
|
|
80
80
|
return lastPublished(id)?.manifest.expiresAt ?? null;
|
|
81
81
|
}
|
|
82
82
|
}
|
|
83
|
-
const
|
|
83
|
+
const expired = (expiresAt)=>null !== expiresAt && expiresAt <= Date.now();
|
|
84
84
|
async function removeApp(id) {
|
|
85
85
|
await rm(await directory(id), {
|
|
86
86
|
recursive: true
|
|
@@ -91,7 +91,7 @@ async function removeApp(id) {
|
|
|
91
91
|
function cleanup() {
|
|
92
92
|
cleaning ??= mutate(async ()=>{
|
|
93
93
|
for (const id of (await appIds(config.root)))try {
|
|
94
|
-
if (
|
|
94
|
+
if (expired(LifetimeSchema.parse(await appJson(id)).expiresAt)) await removeApp(id);
|
|
95
95
|
} catch (error) {
|
|
96
96
|
if (!(error instanceof z.ZodError || error instanceof SyntaxError) && "ENOENT" !== error.code) console.error(`Flare cleanup ${id}: ${message(error)}`);
|
|
97
97
|
}
|
|
@@ -191,7 +191,7 @@ async function listApps() {
|
|
|
191
191
|
const apps = await Promise.all([
|
|
192
192
|
...deployments.keys()
|
|
193
193
|
].sort().map(info));
|
|
194
|
-
return apps.filter((app)=>!
|
|
194
|
+
return apps.filter((app)=>!expired(app.expiresAt));
|
|
195
195
|
});
|
|
196
196
|
}
|
|
197
197
|
const html = '<!doctype html>\n<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>Flare app</title><h1>Your app is ready</h1><p>Edit public/index.html to make it yours.</p></html>\n';
|
|
@@ -248,7 +248,7 @@ callApi().catch(showError);
|
|
|
248
248
|
}
|
|
249
249
|
async function refreshRuntime() {
|
|
250
250
|
const next = await signature();
|
|
251
|
-
if (reloading || restoring || stopping || next === loadedSignature || next === rejected) return;
|
|
251
|
+
if (shutdownRequested || reloading || restoring || stopping || next === loadedSignature || next === rejected) return;
|
|
252
252
|
reloading = true;
|
|
253
253
|
const checkDirectory = resolve(project, `.refresh-${randomUUID()}`);
|
|
254
254
|
try {
|
|
@@ -318,6 +318,7 @@ api.get("/health", (c)=>ready ? c.json({
|
|
|
318
318
|
leases: leases.size,
|
|
319
319
|
backupDirectory: config.backupDirectory,
|
|
320
320
|
backupIntervalMs: config.backupIntervalMs,
|
|
321
|
+
backupKeep: config.backupKeep,
|
|
321
322
|
...reloadError ? {
|
|
322
323
|
reloadError: reloadError
|
|
323
324
|
} : {}
|
|
@@ -330,18 +331,24 @@ api.post("/restart", (c)=>{
|
|
|
330
331
|
});
|
|
331
332
|
api.put("/lease/:id", (c)=>{
|
|
332
333
|
leases.set(LeaseIdSchema.parse(c.req.param("id")), Date.now() + 15000);
|
|
333
|
-
clearTimeout(idle);
|
|
334
334
|
return c.text("ok");
|
|
335
335
|
});
|
|
336
336
|
api.delete("/lease/:id", (c)=>{
|
|
337
337
|
leases.delete(LeaseIdSchema.parse(c.req.param("id")));
|
|
338
|
-
if (0 === leases.size && !stopping) idle = setTimeout(stop, 1500);
|
|
339
338
|
return c.text("ok");
|
|
340
339
|
});
|
|
341
340
|
api.use("*", async (c, next)=>{
|
|
342
|
-
if (stopping || reloading || restoring) return c.text("Flare is refreshing or restoring; retry shortly", 503);
|
|
341
|
+
if (stopping || shutdownRequested || reloading || restoring) return c.text("Flare is stopping, refreshing, or restoring; retry shortly", 503);
|
|
343
342
|
await next();
|
|
344
343
|
});
|
|
344
|
+
api.post("/stop", (c)=>{
|
|
345
|
+
shutdownRequested = true;
|
|
346
|
+
ready = false;
|
|
347
|
+
setTimeout(stop, 100).unref();
|
|
348
|
+
return c.json({
|
|
349
|
+
stopping: true
|
|
350
|
+
}, 202);
|
|
351
|
+
});
|
|
345
352
|
api.post("/backup", async (c)=>c.json(await mutate(()=>createBackup(config))));
|
|
346
353
|
api.post("/restore", async (c)=>{
|
|
347
354
|
const input = RestoreSchema.parse(await c.req.json());
|
|
@@ -450,7 +457,7 @@ api.get("/bundle/:id", async (c)=>{
|
|
|
450
457
|
const id = IdSchema.parse(c.req.param("id"));
|
|
451
458
|
const deployment = deployments.get(id);
|
|
452
459
|
if (!deployment) return c.text("Not found", 404);
|
|
453
|
-
if (
|
|
460
|
+
if (expired(await expiration(id))) return c.text("App expired", 404);
|
|
454
461
|
const app = lastPublished(id);
|
|
455
462
|
return app ? c.json(app) : c.text("Build failed", 503);
|
|
456
463
|
});
|
|
@@ -459,7 +466,7 @@ api.on([
|
|
|
459
466
|
"HEAD"
|
|
460
467
|
], "/assets/:id/*", async (c)=>{
|
|
461
468
|
const id = IdSchema.parse(c.req.param("id"));
|
|
462
|
-
if (
|
|
469
|
+
if (expired(await expiration(id))) return c.text("App expired", 404);
|
|
463
470
|
const relative = decodeURIComponent(new URL(c.req.url).pathname.split("/").slice(3).join("/"));
|
|
464
471
|
const path = await file(resolve(await directory(id), "public"), relative.endsWith("/") || !relative ? `${relative}index.html` : relative);
|
|
465
472
|
const content = await readFile(path);
|
|
@@ -488,12 +495,15 @@ async function pauseChild() {
|
|
|
488
495
|
current.kill("SIGTERM");
|
|
489
496
|
});
|
|
490
497
|
}
|
|
498
|
+
function shutdown() {
|
|
499
|
+
shutdownRequested = true;
|
|
500
|
+
stop();
|
|
501
|
+
}
|
|
491
502
|
function stop() {
|
|
492
503
|
if (stopping) return;
|
|
493
504
|
stopping = true;
|
|
494
505
|
ready = false;
|
|
495
506
|
watcher?.close();
|
|
496
|
-
clearTimeout(idle);
|
|
497
507
|
for (const timer of debounce.values())clearTimeout(timer);
|
|
498
508
|
if (!child || null !== child.exitCode || null !== child.signalCode) return void finish(0);
|
|
499
509
|
child.once("exit", ()=>{
|
|
@@ -510,7 +520,8 @@ async function finish(code) {
|
|
|
510
520
|
finishing = true;
|
|
511
521
|
await backups.wait().catch(()=>{});
|
|
512
522
|
await mutations;
|
|
513
|
-
|
|
523
|
+
const restart = reloading && !shutdownRequested && 0 === code;
|
|
524
|
+
if (restart) {
|
|
514
525
|
const now = Date.now();
|
|
515
526
|
await atomic(handoffPath, [
|
|
516
527
|
...leases
|
|
@@ -521,7 +532,7 @@ async function finish(code) {
|
|
|
521
532
|
}
|
|
522
533
|
server.close();
|
|
523
534
|
if ("closeAllConnections" in server) server.closeAllConnections();
|
|
524
|
-
if (
|
|
535
|
+
if (restart) {
|
|
525
536
|
const replacement = spawn("bun", [
|
|
526
537
|
managerPath
|
|
527
538
|
], {
|
|
@@ -552,14 +563,8 @@ async function start() {
|
|
|
552
563
|
} catch (error) {
|
|
553
564
|
if ("ENOENT" !== error.code) throw error;
|
|
554
565
|
}
|
|
555
|
-
idle = setTimeout(stop, 30000);
|
|
556
566
|
setInterval(()=>{
|
|
557
|
-
|
|
558
|
-
for (const [id, expires] of leases)if (expires <= Date.now()) {
|
|
559
|
-
leases.delete(id);
|
|
560
|
-
expired = true;
|
|
561
|
-
}
|
|
562
|
-
if (expired && 0 === leases.size && !stopping) idle = setTimeout(stop, 1500);
|
|
567
|
+
for (const [id, expires] of leases)if (expires <= Date.now()) leases.delete(id);
|
|
563
568
|
if (ready && !stopping) {
|
|
564
569
|
cleanup().catch((error)=>console.error(error));
|
|
565
570
|
checkSource();
|
|
@@ -697,5 +702,5 @@ server.on("error", (error)=>{
|
|
|
697
702
|
console.error("EADDRINUSE" === error.code ? "Flare manager already bound; another session won startup" : error);
|
|
698
703
|
process.exit("EADDRINUSE" === error.code ? 0 : 1);
|
|
699
704
|
});
|
|
700
|
-
process.on("SIGTERM",
|
|
701
|
-
process.on("SIGINT",
|
|
705
|
+
process.on("SIGTERM", shutdown);
|
|
706
|
+
process.on("SIGINT", shutdown);
|
package/dist/restore.js
CHANGED
|
@@ -1,22 +1,13 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { cp, lstat, mkdir, readFile, realpath, rename, rm, stat } from "node:fs/promises";
|
|
3
3
|
import { basename, dirname, resolve } from "node:path";
|
|
4
|
-
import {
|
|
5
|
-
import { SnapshotTimeSchema, backupRoot, createBackup } from "./backup.js";
|
|
4
|
+
import { BackupMetadataSchema, SnapshotTimeSchema, backupRoot, createBackup } from "./backup.js";
|
|
6
5
|
import { appIds } from "./storage.js";
|
|
7
|
-
const MetadataSchema = z.object({
|
|
8
|
-
version: z.union([
|
|
9
|
-
z.literal(1),
|
|
10
|
-
z.literal(2)
|
|
11
|
-
]),
|
|
12
|
-
root: z.string(),
|
|
13
|
-
completedAt: z.number().int().nonnegative()
|
|
14
|
-
});
|
|
15
6
|
async function readBackup(settings, name) {
|
|
16
7
|
const base = await realpath(backupRoot(settings));
|
|
17
8
|
const path = await realpath(resolve(base, name));
|
|
18
9
|
if (dirname(path) !== base || !SnapshotTimeSchema.safeParse(basename(path)).success) throw new Error("Choose a backup from this Flare home's backup directory");
|
|
19
|
-
const metadata =
|
|
10
|
+
const metadata = BackupMetadataSchema.parse(JSON.parse(await readFile(resolve(path, "backup.json"), "utf8")));
|
|
20
11
|
if (metadata.root !== settings.root) throw new Error("This backup belongs to a different Flare home");
|
|
21
12
|
const apps = 1 === metadata.version ? resolve(path, "apps") : path;
|
|
22
13
|
const state = resolve(path, "runtime/.celld/dev");
|
package/dist/schema.js
CHANGED
|
@@ -100,6 +100,7 @@ const HealthSchema = z.object({
|
|
|
100
100
|
leases: z.number().int().nonnegative(),
|
|
101
101
|
backupDirectory: z.string().optional(),
|
|
102
102
|
backupIntervalMs: z.number().int().positive().optional(),
|
|
103
|
+
backupKeep: z.number().int().nonnegative().optional(),
|
|
103
104
|
reloadError: z.string().optional()
|
|
104
105
|
});
|
|
105
106
|
const port = z.coerce.number().int().min(1024).max(65535);
|
|
@@ -118,6 +119,7 @@ const ConfigSchema = z.object({
|
|
|
118
119
|
controlPort: port.default(53763),
|
|
119
120
|
publicUrl: baseUrl.optional(),
|
|
120
121
|
backupDirectory: z.string().trim().min(1).default(defaultBackupDirectory).transform((value)=>resolve(value)),
|
|
122
|
+
backupKeep: z.coerce.number().int().nonnegative().default(0),
|
|
121
123
|
backupIntervalHours: z.coerce.number().positive().default(12).transform((hours)=>Math.round(60 * hours * 60000)).pipe(z.number().int().positive()).brand()
|
|
122
124
|
}).refine((value)=>value.port !== value.controlPort, "Flare ports must differ").refine((value)=>!containsPath(value.root, value.backupDirectory), "Flare backups must be stored outside PI_FLARE_HOME").transform(({ backupIntervalHours, ...settings })=>({
|
|
123
125
|
...settings,
|
|
@@ -130,6 +132,7 @@ const config = ConfigSchema.parse({
|
|
|
130
132
|
controlPort: process.env.PI_FLARE_CONTROL_PORT,
|
|
131
133
|
publicUrl: process.env.PI_FLARE_PUBLIC_URL,
|
|
132
134
|
backupDirectory: process.env.PI_FLARE_BACKUP_DIR,
|
|
135
|
+
backupKeep: process.env.PI_FLARE_BACKUP_KEEP,
|
|
133
136
|
backupIntervalHours: process.env.PI_FLARE_BACKUP_INTERVAL_HOURS
|
|
134
137
|
});
|
|
135
138
|
const BackupInfoSchema = z.object({
|
package/docs/runtime.md
CHANGED
|
@@ -98,8 +98,20 @@ Backups are private, timestamped directories grouped by a hash of the Flare home
|
|
|
98
98
|
SQLite databases are snapshotted through SQLite, including committed WAL data;
|
|
99
99
|
raw live database files and their transient WAL/SHM/journal sidecars are not copied.
|
|
100
100
|
Snapshots are published only after all files have been written. Credentials,
|
|
101
|
-
leases, logs, and generated runtime code are excluded.
|
|
102
|
-
|
|
101
|
+
leases, logs, and generated runtime code are excluded. Backups are kept indefinitely
|
|
102
|
+
by default. Set `PI_FLARE_BACKUP_KEEP` to the number of completed backups to keep
|
|
103
|
+
per Flare home: `1` keeps only the latest; `0` (the default) keeps all of them.
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
PI_FLARE_BACKUP_KEEP=1 pi
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Retention runs only after a new backup is fully written and published. It applies
|
|
110
|
+
to scheduled backups, `/flare backup`, and recovery snapshots made by restore.
|
|
111
|
+
Existing backups are not pruned if the new snapshot fails. Lowering the limit
|
|
112
|
+
takes effect at the next successful backup; use `/flare backup` to apply it now.
|
|
113
|
+
Incomplete or unrecognized snapshots, symlinks, and backups from other homes are
|
|
114
|
+
left alone. Cleanup errors are logged without invalidating the new backup.
|
|
103
115
|
A local backup protects against accidental changes, not loss of the whole disk;
|
|
104
116
|
choose another disk or a backed-up mount for stronger protection.
|
|
105
117
|
|
|
@@ -133,7 +145,9 @@ state**, then replaces the app and durable-state trees rather than merging them
|
|
|
133
145
|
with stale databases. A failed replacement attempts to roll back the old trees.
|
|
134
146
|
The shared runtime restarts afterward, briefly interrupting every connected Flare
|
|
135
147
|
session and any live WebSocket connections. The command reports the recovery
|
|
136
|
-
snapshot, which can itself be restored to undo the operation.
|
|
148
|
+
snapshot, which can itself be restored to undo the operation. Retention can prune
|
|
149
|
+
the selected source backup after it has been copied into staging; with a limit
|
|
150
|
+
of `1`, the new recovery snapshot is the one kept.
|
|
137
151
|
|
|
138
152
|
The manager token, configuration, and unrelated root directories stay unchanged.
|
|
139
153
|
A restored app cannot overwrite an unrelated directory with the same name.
|
|
@@ -266,10 +280,17 @@ recreating the same directory ID and manifest can reuse it.
|
|
|
266
280
|
|
|
267
281
|
The runtime starts lazily on `/flare` or the first Flare tool call. Each Pi instance
|
|
268
282
|
that uses Flare renews a short-lived lease with one manager. Concurrent starts
|
|
269
|
-
race for its control port; only the winner starts celld. Closing
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
283
|
+
race for its control port; only the winner starts celld. Closing Pi, including the
|
|
284
|
+
last connected session, does not stop the runtime. Apps and artifacts stay
|
|
285
|
+
available, file watching continues, and scheduled backups keep running. After an
|
|
286
|
+
unexpected Pi exit, its lease expires within 15 seconds without affecting serving.
|
|
287
|
+
|
|
288
|
+
Run `/flare stop` to shut down the shared manager and celld for all sessions.
|
|
289
|
+
Interactive sessions ask for confirmation, and the current agent must be idle.
|
|
290
|
+
App files, durable data, and backups are retained. The next Flare command or tool
|
|
291
|
+
call starts the runtime again. Stopping an already-stopped runtime does not start
|
|
292
|
+
it just to stop it. Flare does not install a system service or start itself after
|
|
293
|
+
a machine reboot; start it from Pi again when needed.
|
|
273
294
|
|
|
274
295
|
### Automatic extension refresh
|
|
275
296
|
|
|
@@ -279,7 +300,8 @@ It waits for pending writes/builds and celld shutdown before handing off the
|
|
|
279
300
|
control port. Active session leases are transferred through a private temporary
|
|
280
301
|
file, so multiple Pi instances stay attached without competing restarts. App
|
|
281
302
|
source and durable databases are retained; the manager rebuilds apps from disk.
|
|
282
|
-
|
|
303
|
+
Refresh also works when no Pi sessions are connected. There can be a brief
|
|
304
|
+
interruption to requests and live WebSocket connections.
|
|
283
305
|
|
|
284
306
|
Invalid extension syntax leaves the current runtime serving; `/health` reports
|
|
285
307
|
`reloadError` and `runtime.log` records the failure. Fixing the source retries
|
|
@@ -297,17 +319,18 @@ migration for version-numbered development managers is included.
|
|
|
297
319
|
Set these variables before starting Pi. Connected instances must use the same
|
|
298
320
|
settings; mismatches fail without killing an existing process.
|
|
299
321
|
|
|
300
|
-
| Variable | Default
|
|
301
|
-
| -------------------------------- |
|
|
302
|
-
| `PI_FLARE_HOME` | `~/.pi/flare`
|
|
303
|
-
| `PI_FLARE_HOST` | `127.0.0.1` (public listener's IPv4 or IPv6 bind address)
|
|
304
|
-
| `PI_FLARE_PORT` | `53762`
|
|
305
|
-
| `PI_FLARE_CONTROL_PORT` | `53763`
|
|
306
|
-
| `PI_FLARE_PUBLIC_URL` | URL derived from the bind address and public port
|
|
307
|
-
| `PI_FLARE_BACKUP_INTERVAL_HOURS` | `12` (positive hours; fractions supported)
|
|
308
|
-
| `
|
|
309
|
-
| `
|
|
310
|
-
| `
|
|
322
|
+
| Variable | Default |
|
|
323
|
+
| -------------------------------- | ----------------------------------------------------------- |
|
|
324
|
+
| `PI_FLARE_HOME` | `~/.pi/flare` |
|
|
325
|
+
| `PI_FLARE_HOST` | `127.0.0.1` (public listener's IPv4 or IPv6 bind address) |
|
|
326
|
+
| `PI_FLARE_PORT` | `53762` |
|
|
327
|
+
| `PI_FLARE_CONTROL_PORT` | `53763` |
|
|
328
|
+
| `PI_FLARE_PUBLIC_URL` | URL derived from the bind address and public port |
|
|
329
|
+
| `PI_FLARE_BACKUP_INTERVAL_HOURS` | `12` (positive hours; fractions supported) |
|
|
330
|
+
| `PI_FLARE_BACKUP_KEEP` | `0` (unlimited; `1` keeps only the latest completed backup) |
|
|
331
|
+
| `PI_FLARE_BACKUP_DIR` | `~/.pi/flare-backups` (outside the live home) |
|
|
332
|
+
| `PI_FLARE_CELLD` | `celld` |
|
|
333
|
+
| `CELLD_ESBUILD` | `esbuild` |
|
|
311
334
|
|
|
312
335
|
`PI_FLARE_HOST` controls the public celld listener; the private control listener
|
|
313
336
|
always stays on `127.0.0.1`. Wildcard addresses `0.0.0.0` and `::` advertise
|
|
@@ -322,7 +345,9 @@ Binding to a non-loopback address exposes the app directory and all apps to the
|
|
|
322
345
|
network **without browser authentication**. Use trusted networks or an
|
|
323
346
|
authenticated reverse proxy. `PI_FLARE_PUBLIC_URL` changes returned URLs only;
|
|
324
347
|
it does not create a proxy or change the bind address. Environment changes require
|
|
325
|
-
a fresh shared runtime;
|
|
348
|
+
a fresh shared runtime; run `/flare stop` and close sessions using Flare before
|
|
349
|
+
starting Pi with new settings. Automatic source refresh preserves the runtime's
|
|
350
|
+
launch environment.
|
|
326
351
|
For another independent Flare home, choose different public and control ports too.
|
|
327
352
|
Inspect `runtime.log`
|
|
328
353
|
for startup, Worker, build, backup, restore, and automatic refresh errors. Runtime source updates
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@karlis-vagalis/pi-flare",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Build small web apps and serve HTML pages, reports, and other browser-ready artifacts from your Pi session.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Kārlis Vagalis",
|
|
@@ -50,7 +50,6 @@
|
|
|
50
50
|
"check": "biome check . && bun run typecheck && bun run test",
|
|
51
51
|
"typecheck": "tsc --noEmit",
|
|
52
52
|
"test": "bun test",
|
|
53
|
-
"smoke": "bun run scripts/smoke.ts",
|
|
54
53
|
"format": "biome format --write .",
|
|
55
54
|
"lint": "biome lint .",
|
|
56
55
|
"fix": "biome check --write .",
|