@north-light/cli 0.3.744 → 0.3.746
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 +2 -2
- package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +2 -2
- package/dist/builtin-memory/crouter-sdk/README.md +1 -1
- package/dist/builtin-memory/crouter-sdk/client.md +1 -1
- package/dist/builtin-memory/crouter-sdk/getting-started.md +3 -38
- package/dist/clients/attach/viewer.js +1 -1
- package/dist/commands/sys/provider-login.js +2 -2
- package/dist/commands/sys.js +1 -1
- package/dist/core/canvas/daemon-owner.d.ts +1 -1
- package/dist/core/canvas/paths.d.ts +1 -1
- package/dist/core/canvas/person-state.d.ts +3 -0
- package/dist/core/canvas/person-state.js +1 -1
- package/dist/core/canvas/person.d.ts +2 -3
- package/dist/core/canvas/person.js +7 -7
- package/dist/core/environments.d.ts +0 -10
- package/dist/core/environments.js +1 -1
- package/dist/core/import/load/prepare.d.ts +3 -0
- package/dist/core/import/load/prepare.js +14 -14
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/runtime/blaxel-environment.js +1 -1
- package/dist/core/secrets.d.ts +2 -4
- package/dist/core/secrets.js +1 -1
- package/dist/core/spaces/space.js +2 -2
- package/dist/core/user-settings.js +1 -1
- package/dist/daemon/api/environment-of.d.ts +1 -1
- package/dist/daemon/api/environment-of.js +3 -3
- package/dist/daemon/api/handlers/document-access.js +1 -1
- package/dist/daemon/api/router.d.ts +1 -1
- package/dist/daemon/crtrd-cli.js +1 -1
- package/dist/daemon/crtrd.d.ts +4 -2
- package/dist/daemon/crtrd.js +20 -20
- package/dist/daemon/manage.d.ts +0 -8
- package/dist/daemon/manage.js +3 -3
- package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/dist/daemon/reconcilers/storage-maintenance.d.ts +0 -2
- package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
- package/docs/concepts/scopes-and-trust.md +2 -2
- package/docs/public-api.md +1 -7
- package/docs/sdk/README.md +1 -1
- package/docs/sdk/client.md +1 -1
- package/docs/sdk/getting-started.md +3 -38
- package/package.json +3 -3
- package/packages/crouter-api/dist/commands/sys/provider-login.js +2 -2
- package/packages/crouter-api/dist/commands/sys.js +1 -3
- package/packages/crouter-api/dist/core/canvas/paths.js +1 -1
- package/packages/crouter-api/dist/core/canvas/person-state.js +4 -0
- package/packages/crouter-api/dist/core/canvas/person.js +2 -14
- package/packages/crouter-api/dist/core/environments.js +2 -38
- package/packages/crouter-api/dist/core/import/load/prepare.js +7 -0
- package/packages/crouter-api/dist/core/model-auth/daemon-login.js +2 -2
- package/packages/crouter-api/dist/core/runtime/blaxel-environment.js +3 -3
- package/packages/crouter-api/dist/core/secrets.js +1 -11
- package/packages/crouter-api/dist/core/spaces/space.js +2 -2
- package/packages/crouter-api/dist/core/user-settings.js +1 -1
- package/packages/crouter-api/dist/daemon/api/environment-of.js +7 -4
- package/packages/crouter-api/dist/daemon/manage.js +0 -4
- package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/commands/sys/connect.d.ts +0 -1
- package/dist/commands/sys/connect.js +0 -3
- package/dist/commands/sys/db.d.ts +0 -1
- package/dist/commands/sys/db.js +0 -1
- package/dist/core/canvas/export-sqlite.d.ts +0 -14
- package/dist/core/canvas/export-sqlite.js +0 -3
- package/dist/daemon/api/document-listener.d.ts +0 -7
- package/dist/daemon/api/document-listener.js +0 -1
- package/dist/daemon/api/document-secret.d.ts +0 -2
- package/dist/daemon/api/document-secret.js +0 -1
- package/dist/daemon/export-sqlite-run.d.ts +0 -1
- package/dist/daemon/export-sqlite-run.js +0 -4
- package/packages/crouter-api/dist/commands/sys/connect.js +0 -185
- package/packages/crouter-api/dist/commands/sys/db.js +0 -69
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
/** Why this daemon has no document listener, or undefined while one is bound. `/v1/documents/browser-access` refuses the secret while this is set, so a viewer never sends it to whatever process holds the port. */
|
|
2
|
-
export declare function documentListenerUnavailable(): string | undefined;
|
|
3
|
-
/** Dedicated localhost-only browser listener, independent of /v1 and its TCP bearer configuration. Every route except `/assets/` needs the per-install `secret`, carried by a cookie that `/r/<ref>?t=<secret>` sets. */
|
|
4
|
-
export declare function createDocumentListener(port: number, secret: string): {
|
|
5
|
-
ready: Promise<void>;
|
|
6
|
-
close: () => Promise<void>;
|
|
7
|
-
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var f=Object.defineProperty;var c=(n,r)=>f(n,"name",{value:r,configurable:!0});import{createHash as p,timingSafeEqual as v}from"node:crypto";import{createServer as g}from"node:http";import{cookieValue as S,documentNotFound as $,documentShell as y,error as d,messagePage as w,resolveDocument as P,serveDocumentApi as k,setPageHeaders as _}from"./document-page.js";function m(n,r){const l=c(s=>p("sha256").update(s).digest(),"digest");return v(l(n),l(r))}c(m,"sameSecret");const b=c(n=>n(),"inProcess");let h="the document listener has not started";function T(){return h}c(T,"documentListenerUnavailable");function W(n,r){const l=`crtr_doc_${n}`,s=g((t,e)=>{(async()=>{_(e);const a=[`127.0.0.1:${n}`,`localhost:${n}`];if(typeof t.headers.host!="string"||!a.includes(t.headers.host))return d(e,403,"forbidden","invalid Host");if(t.method==="POST"){if(!a.some(i=>t.headers.origin===`http://${i}`))return d(e,403,"forbidden","invalid Origin");if(t.headers["content-type"]!=="application/json")return d(e,415,"unsupported_media_type","Content-Type must be application/json")}const o=new URL(t.url??"/",`http://127.0.0.1:${n}`);if(!o.pathname.startsWith("/assets/")){const i=t.method==="GET"&&o.pathname.startsWith("/r/")?o.searchParams.get("t"):null;if(i!==null&&m(i,r))return o.searchParams.delete("t"),e.writeHead(303,{Location:`${o.pathname}${o.search}`,"Set-Cookie":`${l}=${r}; HttpOnly; SameSite=Strict; Path=/`,"Cache-Control":"no-store"}),e.end();const u=S(t.headers.cookie,l);if(i!==null||u===void 0||!m(u,r))return o.pathname.startsWith("/r/")?w(e,401,"Not authorized","Open this document from its link in the attach viewer."):d(e,401,"unauthorized","open the document link from the attach viewer")}if(t.method==="GET"&&o.pathname.startsWith("/r/")){let i;try{i=decodeURIComponent(o.pathname.slice(3))}catch{return d(e,400,"invalid_request","ref is not valid percent-encoding")}const u=await P(i);return u?y(e,i,u):$(e,i)}if(!await k(t,e,o,b))return d(e,404,"not_found","route not found")})().catch(a=>{e.headersSent?e.destroy():d(e,500,"server_failure",a instanceof Error?a.message:String(a))})});return{ready:new Promise((t,e)=>{s.once("error",a=>{h=`the document listener could not bind 127.0.0.1:${n}: ${a.message}`,e(a)}),s.listen(n,"127.0.0.1",()=>{s.removeAllListeners("error"),h=void 0,t()})}),close:c(()=>new Promise(t=>{h="the document listener is closed",s.closeAllConnections(),s.close(()=>t())}),"close")}}c(W,"createDocumentListener");export{W as createDocumentListener,T as documentListenerUnavailable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var n=Object.defineProperty;var o=(t,r)=>n(t,"name",{value:r,configurable:!0});import{randomBytes as c}from"node:crypto";import{readFileSync as m,writeFileSync as i}from"node:fs";import{join as d}from"node:path";import{crtrHome as a}from"../../core/canvas/paths.js";const s=/^[A-Za-z0-9_-]{43,}$/;function S(){const t=d(a(),"document-secret");try{i(t,c(32).toString("base64url"),{mode:384,flag:"wx"})}catch(e){if(e.code!=="EEXIST")throw e}const r=m(t,"utf8").trim();if(!s.test(r))throw new Error(`${t} does not hold a document secret; delete it and restart crtrd to mint a new one`);return r}o(S,"documentSecret");export{S as documentSecret};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare function runExportSqlite(): Promise<number>;
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var a=Object.defineProperty;var s=(e,r)=>a(e,"name",{value:r,configurable:!0});import{daemonOwnershipClaimed as i}from"../core/canvas/daemon-owner.js";import{closeAllDbs as n}from"../core/canvas/db.js";import{exportPostgresToSqlite as c}from"../core/canvas/export-sqlite.js";import{ensurePostgres as l,stopPostgres as p}from"./postgres/index.js";async function g(){let e=!1,r=0;try{const t=await l();e=t.started;const o=await c(t.url);process.stdout.write(`${JSON.stringify(o)}
|
|
2
|
-
`)}catch(t){process.stderr.write(`${t.message}
|
|
3
|
-
`),r=1}if(e)try{await p({claimed:s(async()=>{try{return await i()}finally{await n()}},"claimed")})}catch(t){process.stderr.write(`the export started Postgres and could not stop it: ${t.message}
|
|
4
|
-
`),r=1}return r}s(g,"runExportSqlite");export{g as runExportSqlite};
|
|
@@ -1,185 +0,0 @@
|
|
|
1
|
-
import { randomBytes } from 'node:crypto';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { defineLeaf } from '../../core/command.js';
|
|
4
|
-
import { readConfig, updateConfig } from '../../core/config.js';
|
|
5
|
-
import { emit, InputError, isJsonOutput } from '../../core/io.js';
|
|
6
|
-
import { renderResult } from '../../core/render.js';
|
|
7
|
-
import { addScopedApiToken, getApiToken, setApiToken } from '../../core/secrets.js';
|
|
8
|
-
import { ENFORCED } from '@north-light/identity';
|
|
9
|
-
import { envCrtrdTcp, envCrtrdToken, envNodeId } from '../../shared/env.js';
|
|
10
|
-
import { shellQuote } from '../../shared/shell-quote.js';
|
|
11
|
-
import { cliClient } from '../api-client.js';
|
|
12
|
-
const DEFAULT_TCP = '127.0.0.1:8787';
|
|
13
|
-
const LISTENER_WAIT_MS = 30_000;
|
|
14
|
-
const LISTENER_POLL_MS = 100;
|
|
15
|
-
function token() {
|
|
16
|
-
return randomBytes(32).toString('hex');
|
|
17
|
-
}
|
|
18
|
-
/** Parse `--scopes` into a non-empty validated list, or undefined when the
|
|
19
|
-
* flag was omitted (the owner token). */
|
|
20
|
-
function parseScopes(raw) {
|
|
21
|
-
if (raw === undefined)
|
|
22
|
-
return undefined;
|
|
23
|
-
const scopes = String(raw).split(',').map((scope) => scope.trim()).filter((scope) => scope !== '');
|
|
24
|
-
if (scopes.length === 0) {
|
|
25
|
-
throw new InputError({
|
|
26
|
-
error: 'empty_scopes',
|
|
27
|
-
message: '--scopes names no scope',
|
|
28
|
-
received: raw,
|
|
29
|
-
field: 'scopes',
|
|
30
|
-
next: `Pass a comma-separated list from ${[...ENFORCED].join(', ')}; omit the flag for the owner token.`,
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
for (const scope of scopes)
|
|
34
|
-
if (!ENFORCED.has(scope))
|
|
35
|
-
throw new InputError({ error: 'invalid_scope', message: `invalid scope: ${scope}`, field: 'scopes', received: scope, next: `Use one of ${[...ENFORCED].join(', ')}.` });
|
|
36
|
-
return scopes;
|
|
37
|
-
}
|
|
38
|
-
function printCredentials(result) {
|
|
39
|
-
if (isJsonOutput())
|
|
40
|
-
emit(result);
|
|
41
|
-
else
|
|
42
|
-
process.stdout.write(renderResult(result, sysConnectLeaf.help) + '\n');
|
|
43
|
-
}
|
|
44
|
-
function fixedTcpPort(tcp) {
|
|
45
|
-
const separator = tcp.lastIndexOf(':');
|
|
46
|
-
if (separator === -1 || Number(tcp.slice(separator + 1)) !== 0)
|
|
47
|
-
return tcp;
|
|
48
|
-
return `${tcp.slice(0, separator + 1)}8787`;
|
|
49
|
-
}
|
|
50
|
-
async function awaitTcpListener() {
|
|
51
|
-
const client = cliClient();
|
|
52
|
-
const deadline = Date.now() + LISTENER_WAIT_MS;
|
|
53
|
-
let lastError;
|
|
54
|
-
while (Date.now() < deadline) {
|
|
55
|
-
try {
|
|
56
|
-
const status = await client.status();
|
|
57
|
-
if (status.listeners.tcp !== null)
|
|
58
|
-
return status;
|
|
59
|
-
}
|
|
60
|
-
catch (error) {
|
|
61
|
-
lastError = error;
|
|
62
|
-
}
|
|
63
|
-
await new Promise((resolve) => setTimeout(resolve, LISTENER_POLL_MS));
|
|
64
|
-
}
|
|
65
|
-
throw new InputError({
|
|
66
|
-
error: 'listener_unavailable',
|
|
67
|
-
message: `the successor did not expose a TCP listener within ${LISTENER_WAIT_MS}ms${lastError instanceof Error ? `: ${lastError.message}` : ''}`,
|
|
68
|
-
next: 'Run `crtr sys daemon status` to inspect the daemon, then retry `crtr sys connect`.',
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
async function ensureProviderCredential(client, selectors) {
|
|
72
|
-
const readiness = await client.getModelAuthReadiness(selectors);
|
|
73
|
-
if (readiness.credential === 'ready')
|
|
74
|
-
return;
|
|
75
|
-
process.stderr.write(`Logging in to ${readiness.provider} for ${readiness.model}.\n`);
|
|
76
|
-
const { loginProvider, openProviderLoginRuntime, terminalAuthInteraction } = await import('./provider-login.js');
|
|
77
|
-
await loginProvider(await openProviderLoginRuntime(), readiness.provider, terminalAuthInteraction());
|
|
78
|
-
const confirmed = await client.getModelAuthReadiness(selectors);
|
|
79
|
-
if (confirmed.credential !== 'ready') {
|
|
80
|
-
throw new InputError({
|
|
81
|
-
error: 'provider_login_incomplete',
|
|
82
|
-
message: `provider ${confirmed.provider} credential is ${confirmed.credential} after login`,
|
|
83
|
-
next: `Run \`${connectCommand(selectors)}\` again and complete the provider login.`,
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
function connectCommand(selectors) {
|
|
88
|
-
return [
|
|
89
|
-
'crtr sys connect',
|
|
90
|
-
selectors.profile === undefined ? undefined : `--profile ${shellQuote(selectors.profile)}`,
|
|
91
|
-
selectors.cwd === undefined ? undefined : `--cwd ${shellQuote(selectors.cwd)}`,
|
|
92
|
-
selectors.kind === undefined ? undefined : `--kind ${shellQuote(selectors.kind)}`,
|
|
93
|
-
selectors.model === undefined ? undefined : `--model ${shellQuote(selectors.model)}`,
|
|
94
|
-
].filter((part) => part !== undefined).join(' ');
|
|
95
|
-
}
|
|
96
|
-
export const sysConnectLeaf = defineLeaf({
|
|
97
|
-
name: 'connect',
|
|
98
|
-
description: 'enable browser access to this daemon',
|
|
99
|
-
whenToUse: 'an application needs a browser-reachable daemon URL and bearer token; this enables the local TCP listener and reports the credentials to paste into that application. Add --app and --scopes to mint an app token instead of the owner token.',
|
|
100
|
-
help: {
|
|
101
|
-
name: 'sys connect',
|
|
102
|
-
summary: 'enable authenticated browser access and log in to the selected model provider when needed; a handover reports browser credentials before it begins',
|
|
103
|
-
params: [
|
|
104
|
-
{ kind: 'flag', name: 'app', type: 'string', required: false, constraint: 'App id for the new scoped token (without the app: prefix). Required with --scopes; omit both for the owner token.' },
|
|
105
|
-
{ kind: 'flag', name: 'scopes', type: 'string', required: false, constraint: `Comma-separated list from ${[...ENFORCED].join(', ')}. Requires --app; mints a NEW app bearer with this resolved scope set. Omit both flags for the owner token.` },
|
|
106
|
-
{ kind: 'flag', name: 'profile', type: 'string', required: false, constraint: 'Profile setting selecting the provider a root launch with these settings would use.' },
|
|
107
|
-
{ kind: 'flag', name: 'cwd', type: 'string', required: false, constraint: 'Directory setting selecting the provider a root launch with these settings would use. Default: this directory.' },
|
|
108
|
-
{ kind: 'flag', name: 'kind', type: 'string', required: false, constraint: 'Node kind setting selecting the provider a root launch with these settings would use.' },
|
|
109
|
-
{ kind: 'flag', name: 'model', type: 'string', required: false, constraint: 'Model setting selecting the provider a root launch with these settings would use.' },
|
|
110
|
-
],
|
|
111
|
-
output: [
|
|
112
|
-
{ name: 'base_url', type: 'string', required: true, constraint: 'The HTTP URL configured for the TCP listener.' },
|
|
113
|
-
{ name: 'token', type: 'string', required: true, constraint: 'The bearer token accepted by that listener: the owner token, or with --scopes the newly minted scoped token. Paste it only into the application that needs daemon access.' },
|
|
114
|
-
],
|
|
115
|
-
outputKind: 'object',
|
|
116
|
-
effects: [
|
|
117
|
-
'Stores a missing listener address in user settings and a missing owner bearer token in the 0600 user secrets store.',
|
|
118
|
-
'With --scopes, appends a new scoped token to that secrets store; there is no revoke verb yet, so removing one means editing the store by hand.',
|
|
119
|
-
'When the listener is not already up with both settings present, or a scoped token was minted (the daemon reads tokens only at boot), asks the daemon to hand over to a successor.',
|
|
120
|
-
'After the listener is available, resolves the provider selected by these params (default: this directory) and runs its existing OAuth login flow when that provider has no usable credential.',
|
|
121
|
-
],
|
|
122
|
-
},
|
|
123
|
-
run: async (input) => {
|
|
124
|
-
const selectors = {
|
|
125
|
-
profile: input['profile'],
|
|
126
|
-
cwd: path.resolve(input['cwd'] ?? process.cwd()),
|
|
127
|
-
kind: input['kind'],
|
|
128
|
-
model: input['model'],
|
|
129
|
-
};
|
|
130
|
-
const scopes = parseScopes(input['scopes']);
|
|
131
|
-
const app = input['app'];
|
|
132
|
-
if ((scopes === undefined) !== (app === undefined) || (app !== undefined && !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(String(app)))) {
|
|
133
|
-
throw new InputError({ error: 'invalid_app', message: '--app must name an app id and is required exactly when --scopes is set', field: 'app', received: app, next: 'Pass --app with an app id and --scopes together, or omit both for the owner token.' });
|
|
134
|
-
}
|
|
135
|
-
const callerNodeId = envNodeId();
|
|
136
|
-
const config = readConfig('user');
|
|
137
|
-
const storedTcp = config.api.tcp;
|
|
138
|
-
const storedToken = getApiToken('user');
|
|
139
|
-
const client = cliClient();
|
|
140
|
-
const status = await client.status();
|
|
141
|
-
if (storedTcp === '')
|
|
142
|
-
await updateConfig('user', (next) => { next.api.tcp = DEFAULT_TCP; });
|
|
143
|
-
else if (Number(storedTcp.slice(storedTcp.lastIndexOf(':') + 1)) === 0) {
|
|
144
|
-
await updateConfig('user', (next) => { next.api.tcp = fixedTcpPort(storedTcp); });
|
|
145
|
-
}
|
|
146
|
-
const tcp = envCrtrdTcp() ?? readConfig('user').api.tcp;
|
|
147
|
-
if (Number(tcp.slice(tcp.lastIndexOf(':') + 1)) === 0) {
|
|
148
|
-
throw new InputError({
|
|
149
|
-
error: 'dynamic_tcp_port',
|
|
150
|
-
message: 'CRTRD_TCP must use a fixed port for `crtr sys connect`',
|
|
151
|
-
next: 'Set CRTRD_TCP to a host and fixed port, then run `crtr sys connect` again.',
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
if (scopes === undefined && storedTcp !== '' && storedToken !== undefined && status.listeners.tcp !== null) {
|
|
155
|
-
await ensureProviderCredential(client, selectors);
|
|
156
|
-
return {
|
|
157
|
-
base_url: `http://${status.listeners.tcp}`,
|
|
158
|
-
token: envCrtrdToken() ?? storedToken,
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
if (storedToken === undefined)
|
|
162
|
-
setApiToken(token(), 'user');
|
|
163
|
-
const ownerToken = envCrtrdToken() ?? getApiToken('user');
|
|
164
|
-
if (ownerToken === undefined) {
|
|
165
|
-
throw new Error('TCP listener cannot start without a bearer token');
|
|
166
|
-
}
|
|
167
|
-
let issued = ownerToken;
|
|
168
|
-
if (scopes !== undefined) {
|
|
169
|
-
issued = token();
|
|
170
|
-
addScopedApiToken({ token: issued, grantee: `app:${String(app)}`, scopes, created: new Date().toISOString() }, 'user');
|
|
171
|
-
}
|
|
172
|
-
// Handover can replace the caller's broker before it receives a returned result.
|
|
173
|
-
printCredentials({ base_url: `http://${tcp}`, token: issued });
|
|
174
|
-
await client.restartDaemon();
|
|
175
|
-
await awaitTcpListener();
|
|
176
|
-
await ensureProviderCredential(client, selectors);
|
|
177
|
-
if (callerNodeId !== undefined) {
|
|
178
|
-
await client.sendMessage(callerNodeId, {
|
|
179
|
-
body: 'Browser access is ready.',
|
|
180
|
-
tier: 'urgent',
|
|
181
|
-
from: callerNodeId,
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
|
-
},
|
|
185
|
-
});
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
// `crtr sys db`: offline operations on the canvas database. Today one leaf: the rollback export to SQLite.
|
|
2
|
-
import { existsSync } from 'node:fs';
|
|
3
|
-
import { defineBranch, defineLeaf } from '../../core/command.js';
|
|
4
|
-
import { general } from '../../core/errors.js';
|
|
5
|
-
import { canvasDbPath } from '../../core/canvas/paths.js';
|
|
6
|
-
import { isDaemonRunning } from '../../daemon/pidfile.js';
|
|
7
|
-
import { runDaemonExportSqlite } from '../../daemon/manage.js';
|
|
8
|
-
const sysDbExportSqliteLeaf = defineLeaf({
|
|
9
|
-
name: 'export-sqlite',
|
|
10
|
-
description: 'write the Postgres canvas database back into a SQLite canvas.db, for rolling back to a generation that predates Postgres',
|
|
11
|
-
whenToUse: 'rolling back to a runtime generation that still uses SQLite, after `crtr sys daemon stop`. Not part of normal operation; the Postgres generation never needs it.',
|
|
12
|
-
help: {
|
|
13
|
-
name: 'sys db export-sqlite',
|
|
14
|
-
summary: 'copy the Postgres canvas database into a new runtime/canvas.db at the SQLite schema version the previous generation expects',
|
|
15
|
-
guide: 'Rollback sequence: `crtr sys daemon stop` (drains the daemon, releases its claim, stops the supervised Postgres), `crtr sys db export-sqlite` (this command starts the supervised Postgres by itself, copies every table with object ids mapped back to rowids, verifies row counts, and renames the result into place as runtime/canvas.db), select the previous runtime generation, `crtr sys daemon start`. If the export fails before publishing, canvas.db is not created and the Postgres data is untouched (only the export mark may be left, which keeps a later Postgres boot from importing a restored canvas.db over newer data): rename `runtime/canvas.db.imported` back to `runtime/canvas.db` to start the previous generation from the database as it was before the first Postgres boot, which loses every write made since. This command does not do that rename for you.',
|
|
16
|
-
params: [],
|
|
17
|
-
output: [
|
|
18
|
-
{ name: 'path', type: 'string', required: true, constraint: 'The canvas.db that was written.' },
|
|
19
|
-
{ name: 'rows', type: 'number', required: true, constraint: 'Rows copied across all tables.' },
|
|
20
|
-
{ name: 'user_version', type: 'number', required: true, constraint: 'The SQLite schema version of the written file.' },
|
|
21
|
-
{ name: 'ms', type: 'number', required: true, constraint: 'Wall time of the copy.' },
|
|
22
|
-
],
|
|
23
|
-
outputKind: 'object',
|
|
24
|
-
effects: [
|
|
25
|
-
'Starts the supervised Postgres if it is not running (or uses CRTR_DATABASE_URL), reads it in one read-only transaction, and writes runtime/canvas.db.exporting-<pid>, then renames it to runtime/canvas.db. Stops the Postgres again afterwards if this command started it.',
|
|
26
|
-
'Records an exported_to_sqlite mark in the Postgres canvas_meta before publishing runtime/canvas.db, so a later boot of the Postgres generation refuses to import this canvas.db over newer Postgres data.',
|
|
27
|
-
'Refuses while a daemon is running, and when runtime/canvas.db already exists.',
|
|
28
|
-
],
|
|
29
|
-
},
|
|
30
|
-
run: async () => {
|
|
31
|
-
if (isDaemonRunning()) {
|
|
32
|
-
throw general('a daemon is running; an export taken under it would miss writes made after the copy', {
|
|
33
|
-
next: 'Run `crtr sys daemon stop`, then `crtr sys db export-sqlite`.',
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
const target = canvasDbPath();
|
|
37
|
-
if (existsSync(target)) {
|
|
38
|
-
throw general(`${target} already exists`, {
|
|
39
|
-
next: `Move it aside (or delete it if it is a leftover) before exporting; ${target}.imported is the pre-Postgres database kept by the import.`,
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
try {
|
|
43
|
-
const result = await runDaemonExportSqlite();
|
|
44
|
-
return { path: result.path, rows: result.rows, user_version: result.userVersion, ms: result.ms };
|
|
45
|
-
}
|
|
46
|
-
catch (error) {
|
|
47
|
-
const message = `export failed: ${error.message}`;
|
|
48
|
-
if (existsSync(target)) {
|
|
49
|
-
throw general(`${message}; ${target} was published before the failure`, {
|
|
50
|
-
next: `${target} may be complete: inspect it before using it, or move it aside and rerun the export.`,
|
|
51
|
-
});
|
|
52
|
-
}
|
|
53
|
-
throw general(message, {
|
|
54
|
-
next: `Nothing was written to ${target}. To start the previous generation from the pre-Postgres database instead, rename ${target}.imported to ${target}; every write made since the Postgres import is lost.`,
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
},
|
|
58
|
-
});
|
|
59
|
-
export const sysDbBranch = defineBranch({
|
|
60
|
-
name: 'db',
|
|
61
|
-
description: 'offline operations on the canvas database',
|
|
62
|
-
whenToUse: 'rolling the canvas database back to SQLite after a Postgres soak fails',
|
|
63
|
-
help: {
|
|
64
|
-
name: 'sys db',
|
|
65
|
-
summary: 'offline canvas database operations',
|
|
66
|
-
model: 'The canvas lives in a supervised Postgres. These commands run with the daemon stopped and are for migration and rollback only.',
|
|
67
|
-
},
|
|
68
|
-
children: [sysDbExportSqliteLeaf],
|
|
69
|
-
});
|