@notis_ai/cli 0.2.25 → 0.2.27
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 +186 -5
- package/config/notis_app_design_rules.json +36 -14
- package/config/portal-route-roots.json +1 -0
- package/dist/agent-hooks/notis-agent-hook.mjs +2866 -553
- package/dist/base-skills/notis-cli/.notis-base-skill.json +1 -1
- package/dist/base-skills/notis-cli/references/intelligence.md +1 -1
- package/dist/base-skills/notis-query/.notis-base-skill.json +1 -1
- package/dist/base-skills/notis-query/SKILL.md +0 -1
- package/dist/base-skills/notis-query/references/documents.md +7 -0
- package/dist/base-skills/notis-query/references/query.md +1 -0
- package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
- package/dist/base-skills/notis-spaces/SKILL.md +96 -24
- package/dist/base-skills/notis-spaces/references/architecture.md +4 -3
- package/dist/base-skills/notis-spaces/references/context.md +3 -0
- package/dist/base-skills/notis-spaces/references/design.md +37 -18
- package/dist/base-skills/notis-spaces/references/reading.md +8 -1
- package/dist/base-skills/notis-spaces/references/reports.md +6 -6
- package/dist/base-skills/notis-spaces/references/sdk.md +71 -7
- package/dist/base-skills/notis-spaces/references/store.md +22 -13
- package/dist/base-skills/notis-spaces/references/views.md +99 -6
- package/dist/sdk/package.json +3 -0
- package/dist/sdk/src/cloudComputerWords.ts +53 -0
- package/dist/sdk/src/components/Audience.tsx +76 -0
- package/dist/sdk/src/components/DocumentPage.tsx +15 -4
- package/dist/sdk/src/components/MarkdownEditor.tsx +44 -14
- package/dist/sdk/src/components/MultiSelectActionBar.tsx +16 -5
- package/dist/sdk/src/components/NotisSelectionBoundary.tsx +79 -25
- package/dist/sdk/src/components/Skeleton.tsx +162 -6
- package/dist/sdk/src/hooks/useAction.ts +12 -2
- package/dist/sdk/src/hooks/useAgentQueue.ts +125 -0
- package/dist/sdk/src/hooks/useCloudComputerJob.ts +142 -0
- package/dist/sdk/src/hooks/useCloudComputerService.ts +388 -0
- package/dist/sdk/src/hooks/useCloudComputerShell.ts +95 -7
- package/dist/sdk/src/hooks/useCollectionInteractions.ts +40 -2
- package/dist/sdk/src/hooks/useItemThread.ts +58 -0
- package/dist/sdk/src/hooks/useMarqueeSelection.ts +6 -1
- package/dist/sdk/src/hooks/useNativeDocuments.ts +61 -8
- package/dist/sdk/src/hooks/useNotisNavigation.ts +31 -8
- package/dist/sdk/src/hooks/useQuery.ts +67 -10
- package/dist/sdk/src/hooks/useViewParams.ts +47 -11
- package/dist/sdk/src/index.ts +31 -4
- package/dist/sdk/src/interactions.ts +2 -0
- package/dist/sdk/src/nativeData.ts +2 -0
- package/dist/sdk/src/optimisticRows.ts +329 -0
- package/dist/sdk/src/perf.ts +188 -0
- package/dist/sdk/src/provider.tsx +2 -1
- package/dist/sdk/src/queryCache.ts +366 -17
- package/dist/sdk/src/runtime.ts +55 -4
- package/dist/sdk/src/skeleton.ts +103 -0
- package/dist/sdk/src/space.ts +662 -28
- package/dist/sdk/src/spacePublicUI.ts +36 -0
- package/dist/sdk/src/ui/engine/step.ts +54 -0
- package/dist/sdk/src/ui/icons.tsx +3 -1
- package/dist/sdk/src/words/shell.ts +1 -0
- package/dist/skill-sync/index.js +88 -13
- package/dist/skill-sync-worker.mjs +127 -38
- package/dist/space-harness/host.js +272 -105
- package/dist/space-sdk/dist/chunk-BWHAORT4.js +5 -0
- package/dist/space-sdk/dist/index.js +9 -4
- package/dist/space-sdk/dist/ui.js +12 -12
- package/dist/space-sdk/package.json +3 -0
- package/dist/space-sdk/src/cloudComputerWords.d.ts +34 -0
- package/dist/space-sdk/src/components/Audience.d.ts +46 -0
- package/dist/space-sdk/src/components/DocumentPage.d.ts +3 -1
- package/dist/space-sdk/src/components/MarkdownEditor.d.ts +21 -0
- package/dist/space-sdk/src/components/MultiSelectActionBar.d.ts +5 -1
- package/dist/space-sdk/src/components/NotisSelectionBoundary.d.ts +19 -2
- package/dist/space-sdk/src/components/Skeleton.d.ts +7 -2
- package/dist/space-sdk/src/hooks/useAction.d.ts +8 -1
- package/dist/space-sdk/src/hooks/useAgentQueue.d.ts +61 -0
- package/dist/space-sdk/src/hooks/useCloudComputerJob.d.ts +35 -0
- package/dist/space-sdk/src/hooks/useCloudComputerService.d.ts +75 -0
- package/dist/space-sdk/src/hooks/useCloudComputerShell.d.ts +36 -3
- package/dist/space-sdk/src/hooks/useCollectionInteractions.d.ts +6 -0
- package/dist/space-sdk/src/hooks/useItemThread.d.ts +32 -0
- package/dist/space-sdk/src/hooks/useMarqueeSelection.d.ts +2 -1
- package/dist/space-sdk/src/hooks/useNativeDocumentBody.d.ts +1 -0
- package/dist/space-sdk/src/hooks/useNativeDocuments.d.ts +20 -5
- package/dist/space-sdk/src/hooks/useNotisNavigation.d.ts +11 -2
- package/dist/space-sdk/src/hooks/useQuery.d.ts +24 -2
- package/dist/space-sdk/src/hooks/useViewParams.d.ts +2 -0
- package/dist/space-sdk/src/index.d.ts +24 -4
- package/dist/space-sdk/src/nativeData.d.ts +6 -0
- package/dist/space-sdk/src/queryCache.d.ts +97 -2
- package/dist/space-sdk/src/runtime.d.ts +53 -4
- package/dist/space-sdk/src/skeleton.d.ts +42 -0
- package/dist/space-sdk/src/space.ts +662 -28
- package/dist/space-sdk/src/tailwind-candidates.d.ts +761 -6
- package/dist/space-sdk/src/ui/cloud/CloudComputerFrame.d.ts +29 -0
- package/dist/space-sdk/src/ui/cloud/CloudComputerWaking.d.ts +20 -0
- package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +15 -2
- package/dist/space-sdk/src/ui/comments/PassageComments.d.ts +50 -0
- package/dist/space-sdk/src/ui/comments/commentFiles.d.ts +64 -0
- package/dist/space-sdk/src/ui/comments/commentModel.d.ts +49 -1
- package/dist/space-sdk/src/ui/comments/commentWords.d.ts +26 -0
- package/dist/space-sdk/src/ui/comments/index.d.ts +4 -0
- package/dist/space-sdk/src/ui/comments/passageModel.d.ts +82 -0
- package/dist/space-sdk/src/ui/comments/useComments.d.ts +34 -4
- package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +67 -0
- package/dist/space-sdk/src/ui/engine/index.d.ts +2 -2
- package/dist/space-sdk/src/ui/engine/step.d.ts +9 -0
- package/dist/space-sdk/src/ui/fields/fields.d.ts +2 -1
- package/dist/space-sdk/src/ui/index.d.ts +4 -0
- package/dist/space-sdk/src/ui/layout/Panels.d.ts +9 -2
- package/dist/space-sdk/src/ui/layout/SidePane.d.ts +42 -0
- package/dist/space-sdk/src/ui/layout/index.d.ts +2 -1
- package/dist/space-sdk/src/ui/layout/panelMath.d.ts +11 -2
- package/dist/space-sdk/src/ui/list/ListReader.d.ts +38 -7
- package/dist/space-sdk/src/ui/list/Row.d.ts +4 -0
- package/dist/space-sdk/src/ui/list/SelectionBar.d.ts +9 -4
- package/dist/space-sdk/src/ui/list/useListKeys.d.ts +4 -0
- package/dist/space-sdk/src/words/shell.ts +1 -0
- package/dist/view-renderer/dist/host.js +355 -188
- package/dist/view-renderer/dist/theme.css +1 -1
- package/dist/view-renderer/src/dom.js +15 -2
- package/dist/view-renderer/src/host.tsx +4 -1
- package/dist/view-renderer/src/index.js +3 -0
- package/dist/view-renderer/src/pool.js +8 -4
- package/dist/view-renderer/src/renderer.js +92 -23
- package/dist/view-renderer/src/skeleton.js +450 -0
- package/package.json +4 -4
- package/skills/notis-cli/AGENT_INSTRUCTIONS.md +8 -4
- package/skills/notis-onboarding/BRIEF.md +15 -9
- package/skills/notis-spaces/cli.md +43 -4
- package/src/command-specs/auth.js +5 -3
- package/src/command-specs/cc.js +410 -0
- package/src/command-specs/computer.js +320 -0
- package/src/command-specs/diagnostics.js +2 -13
- package/src/command-specs/documents.js +22 -4
- package/src/command-specs/index.js +7 -0
- package/src/command-specs/onboarding.js +127 -7
- package/src/command-specs/skills.js +2 -2
- package/src/command-specs/spaces.js +162 -30
- package/src/command-specs/tools.js +26 -8
- package/src/command-specs/views.js +4 -1
- package/src/runtime/agent-setup.js +20 -2
- package/src/runtime/app-boundary-validator.js +2 -1
- package/src/runtime/app-platform.js +13 -0
- package/src/runtime/auth-recovery.js +5 -0
- package/src/runtime/channel.js +16 -2
- package/src/runtime/cloud-transfer.js +587 -0
- package/src/runtime/computer-ssh.js +127 -0
- package/src/runtime/oauth.js +50 -4
- package/src/runtime/skill-sync/cloud-client.ts +98 -15
- package/src/runtime/skill-sync/index.ts +42 -4
- package/src/runtime/skill-sync/local-scanner.ts +1 -0
- package/src/runtime/skill-sync/types.ts +6 -0
- package/src/runtime/space-audience.js +94 -0
- package/src/runtime/space-collection-scaffold.js +2 -1
- package/src/runtime/space-fixture-broker.js +2 -1
- package/src/runtime/space-lock.js +1 -4
- package/src/runtime/space-platform.js +18 -2
- package/src/runtime/space-source.js +105 -7
- package/src/runtime/space-test-server.js +13 -2
- package/src/runtime/space-verification.js +99 -6
- package/src/runtime/space-view-manifest.js +22 -4
- package/src/runtime/sync-skills.js +24 -20
- package/src/runtime/transport.js +19 -0
- package/src/runtime/view-render.js +2 -2
- package/src/skill-sync-worker.js +5 -1
- package/template/.harness/index.html.tmpl +1 -1
- package/dist/skill-sync/index.js.map +0 -7
- package/dist/space-sdk/dist/chunk-SVZATGZB.js +0 -5
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Direct Cloud Computer transfers for `notis cc push` and `notis cc pull`.
|
|
3
|
+
*
|
|
4
|
+
* The Notis API only opens the session (POST /portal_spaces/cloud-transfer): it decides the folder,
|
|
5
|
+
* wakes the machine and signs a short transfer pass. The bytes go straight between this computer and
|
|
6
|
+
* the machine's gate (https://...on.boat.dev/t/<session>/...), never through Notis servers.
|
|
7
|
+
*
|
|
8
|
+
* Push: a manifest of every file (sha256, size, path) is sent first; files at or below the session's
|
|
9
|
+
* small-file size travel whole in tar batches, larger ones in chunks over parallel streams. The gate
|
|
10
|
+
* journals each chunk once it is on disk, so a rerun (or a dropped link) asks the gate what it already
|
|
11
|
+
* has and sends only the rest. Commit checks every sha256 on the machine and moves the files into place.
|
|
12
|
+
*
|
|
13
|
+
* Pull: the gate lists the remote files with their sha256; each is downloaded with Range requests into
|
|
14
|
+
* a `.notis-part` file beside its target, resumed from what is already there, checked, then renamed.
|
|
15
|
+
*/
|
|
16
|
+
import { createHash } from 'node:crypto';
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import fsp from 'node:fs/promises';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { CliError, EXIT_CODES, usageError } from './errors.js';
|
|
21
|
+
import { CONFIG_DIR } from './profiles.js';
|
|
22
|
+
import { httpRequest } from './transport.js';
|
|
23
|
+
|
|
24
|
+
export const PARALLEL_STREAMS = 8;
|
|
25
|
+
const LEASE_RENEW_MS = 60 * 1000;
|
|
26
|
+
const PROGRESS_EVERY_MS = 2000;
|
|
27
|
+
const MAX_ATTEMPTS = 8;
|
|
28
|
+
const BEGIN_ATTEMPTS = 4;
|
|
29
|
+
const BEGIN_RETRY_MS = 5000;
|
|
30
|
+
const MAX_FILES_PER_BATCH = 4000;
|
|
31
|
+
const STATE_VERSION = 1;
|
|
32
|
+
const PULL_CHUNK = 32 * 1024 * 1024;
|
|
33
|
+
|
|
34
|
+
const sleepFor = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
35
|
+
const STREAM_BODY_MIN = 1024 * 1024;
|
|
36
|
+
const STREAM_SLICE = 256 * 1024;
|
|
37
|
+
const SEND_IDLE_MS = 180_000;
|
|
38
|
+
const ANSWER_IDLE_MS = 60_000;
|
|
39
|
+
|
|
40
|
+
/** An abort signal that fires once nothing moved for `ms`; `touch` re-arms it, `stop` disarms it. */
|
|
41
|
+
export function idleWatchdog(ms) {
|
|
42
|
+
const controller = new AbortController();
|
|
43
|
+
let timer = null;
|
|
44
|
+
const touch = (next = ms) => {
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
timer = setTimeout(() => controller.abort(new Error('send_idle')), next);
|
|
47
|
+
timer.unref?.();
|
|
48
|
+
};
|
|
49
|
+
touch();
|
|
50
|
+
return { signal: controller.signal, touch, stop: () => clearTimeout(timer) };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The bytes as a stream read slice by slice, so each slice taken by the socket counts as progress. */
|
|
54
|
+
export function streamBody(data, onPull) {
|
|
55
|
+
let offset = 0;
|
|
56
|
+
return new ReadableStream({
|
|
57
|
+
pull(controller) {
|
|
58
|
+
if (offset >= data.length) {
|
|
59
|
+
controller.close();
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const end = Math.min(data.length, offset + STREAM_SLICE);
|
|
63
|
+
controller.enqueue(data.subarray(offset, end));
|
|
64
|
+
offset = end;
|
|
65
|
+
onPull();
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function stateDir() {
|
|
71
|
+
return process.env.NOTIS_TRANSFER_STATE_DIR || path.join(CONFIG_DIR, 'transfers');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The same rule the server and the gate apply: relative, no empty, '.', '..' or control characters. */
|
|
75
|
+
export function validRelative(value) {
|
|
76
|
+
if (typeof value !== 'string' || !value || value.length > 4096 || value.startsWith('/') || value.endsWith('/')) return false;
|
|
77
|
+
if (/[\u0000-\u001f\u007f\\]/.test(value)) return false;
|
|
78
|
+
return value.split('/').every(part => part && part !== '.' && part !== '..');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function manifestText(files) {
|
|
82
|
+
return files.map(file => `${file.sha256} ${file.size} ${file.path}\n`).join('');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function digestOf(text) {
|
|
86
|
+
return createHash('sha256').update(text).digest('hex');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function formatBytes(bytes) {
|
|
90
|
+
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
91
|
+
let value = Number(bytes) || 0;
|
|
92
|
+
let unit = 0;
|
|
93
|
+
while (value >= 1000 && unit < units.length - 1) { value /= 1000; unit += 1; }
|
|
94
|
+
return `${value.toFixed(value >= 100 || unit === 0 ? 0 : 1)} ${units[unit]}`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Every regular file under `local` (or `local` itself), following links like scp does. A link loop
|
|
99
|
+
* or a link to a folder already walked is skipped once.
|
|
100
|
+
*/
|
|
101
|
+
export async function collectFiles(local, { followLinks = true } = {}) {
|
|
102
|
+
const top = await (followLinks ? fsp.stat(local) : fsp.lstat(local));
|
|
103
|
+
if (top.isFile()) {
|
|
104
|
+
return { kind: 'file', files: [{ abs: path.resolve(local), path: path.basename(local), size: top.size, mtimeMs: Math.floor(top.mtimeMs) }], skipped: [] };
|
|
105
|
+
}
|
|
106
|
+
if (!top.isDirectory()) throw usageError(`${local} is not a file or folder.`);
|
|
107
|
+
const files = [];
|
|
108
|
+
const skipped = [];
|
|
109
|
+
const seen = new Set();
|
|
110
|
+
const walk = async (dir, prefix) => {
|
|
111
|
+
const real = await fsp.realpath(dir);
|
|
112
|
+
const id = await fsp.stat(real);
|
|
113
|
+
const key = `${id.dev}:${id.ino}`;
|
|
114
|
+
if (seen.has(key)) { skipped.push({ path: prefix || '.', reason: 'link_loop' }); return; }
|
|
115
|
+
seen.add(key);
|
|
116
|
+
const entries = (await fsp.readdir(dir, { withFileTypes: true })).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
117
|
+
for (const entry of entries) {
|
|
118
|
+
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
119
|
+
const abs = path.join(dir, entry.name);
|
|
120
|
+
if (!validRelative(relative)) { skipped.push({ path: relative, reason: 'name' }); continue; }
|
|
121
|
+
let stat;
|
|
122
|
+
try {
|
|
123
|
+
stat = entry.isSymbolicLink() ? (followLinks ? await fsp.stat(abs) : null) : await fsp.lstat(abs);
|
|
124
|
+
} catch {
|
|
125
|
+
skipped.push({ path: relative, reason: 'broken_link' });
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (!stat) { skipped.push({ path: relative, reason: 'link' }); continue; }
|
|
129
|
+
if (stat.isDirectory()) await walk(abs, relative);
|
|
130
|
+
else if (stat.isFile()) files.push({ abs, path: relative, size: stat.size, mtimeMs: Math.floor(stat.mtimeMs) });
|
|
131
|
+
else skipped.push({ path: relative, reason: 'not_a_regular_file' });
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
await walk(path.resolve(local), '');
|
|
135
|
+
return { kind: 'dir', files, skipped };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function hashFile(abs) {
|
|
139
|
+
const hash = createHash('sha256');
|
|
140
|
+
await new Promise((resolve, reject) => {
|
|
141
|
+
fs.createReadStream(abs, { highWaterMark: 4 * 1024 * 1024 }).on('data', data => hash.update(data))
|
|
142
|
+
.on('error', reject).on('end', resolve);
|
|
143
|
+
});
|
|
144
|
+
return hash.digest('hex');
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function statePath(key) {
|
|
148
|
+
return path.join(stateDir(), `${digestOf(key).slice(0, 32)}.json`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function readState(key) {
|
|
152
|
+
try {
|
|
153
|
+
const state = JSON.parse(fs.readFileSync(statePath(key), 'utf8'));
|
|
154
|
+
return state.version === STATE_VERSION ? state : null;
|
|
155
|
+
} catch {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function writeState(key, state) {
|
|
161
|
+
fs.mkdirSync(stateDir(), { recursive: true, mode: 0o700 });
|
|
162
|
+
const file = statePath(key);
|
|
163
|
+
fs.writeFileSync(`${file}.tmp`, JSON.stringify({ ...state, version: STATE_VERSION }), { mode: 0o600 });
|
|
164
|
+
fs.renameSync(`${file}.tmp`, file);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** sha256 of every file, reusing the ones a previous run computed for the same size and time. */
|
|
168
|
+
async function hashAll(files, cache, onProgress) {
|
|
169
|
+
let done = 0;
|
|
170
|
+
const queue = [...files];
|
|
171
|
+
const work = async () => {
|
|
172
|
+
for (let file = queue.shift(); file; file = queue.shift()) {
|
|
173
|
+
const known = cache[file.path];
|
|
174
|
+
file.sha256 = known && known.size === file.size && known.mtimeMs === file.mtimeMs ? known.sha256 : await hashFile(file.abs);
|
|
175
|
+
done += file.size;
|
|
176
|
+
onProgress(done);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
await Promise.all(Array.from({ length: 4 }, work));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** One ustar archive of whole files, each entry named by its index in the manifest. */
|
|
183
|
+
export function tarBatch(entries) {
|
|
184
|
+
const blocks = [];
|
|
185
|
+
for (const { index, data } of entries) {
|
|
186
|
+
const header = Buffer.alloc(512);
|
|
187
|
+
header.write(String(index), 0, 100, 'utf8');
|
|
188
|
+
header.write('0000644\0', 100, 'ascii');
|
|
189
|
+
header.write('0000000\0', 108, 'ascii');
|
|
190
|
+
header.write('0000000\0', 116, 'ascii');
|
|
191
|
+
header.write(`${data.length.toString(8).padStart(11, '0')}\0`, 124, 'ascii');
|
|
192
|
+
header.write(`${Math.floor(Date.now() / 1000).toString(8).padStart(11, '0')}\0`, 136, 'ascii');
|
|
193
|
+
header.write(' ', 148, 'ascii');
|
|
194
|
+
header.write('0', 156, 'ascii');
|
|
195
|
+
header.write('ustar\0', 257, 'ascii');
|
|
196
|
+
header.write('00', 263, 'ascii');
|
|
197
|
+
let sum = 0;
|
|
198
|
+
for (const byte of header) sum += byte;
|
|
199
|
+
header.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 'ascii');
|
|
200
|
+
blocks.push(header, data);
|
|
201
|
+
const pad = (512 - (data.length % 512)) % 512;
|
|
202
|
+
if (pad) blocks.push(Buffer.alloc(pad));
|
|
203
|
+
}
|
|
204
|
+
blocks.push(Buffer.alloc(1024));
|
|
205
|
+
return Buffer.concat(blocks);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function readRange(abs, offset, length) {
|
|
209
|
+
const handle = await fsp.open(abs, 'r');
|
|
210
|
+
try {
|
|
211
|
+
const buffer = Buffer.allocUnsafe(length);
|
|
212
|
+
let read = 0;
|
|
213
|
+
while (read < length) {
|
|
214
|
+
const { bytesRead } = await handle.read(buffer, read, length - read, offset + read);
|
|
215
|
+
if (!bytesRead) throw new Error('file_changed');
|
|
216
|
+
read += bytesRead;
|
|
217
|
+
}
|
|
218
|
+
return buffer;
|
|
219
|
+
} finally {
|
|
220
|
+
await handle.close();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function transferError(code, message, details = {}) {
|
|
225
|
+
return new CliError({ code, message, exitCode: EXIT_CODES.backend, details });
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** The API side of a session: begin, status (fresh pass), commit, abort. */
|
|
229
|
+
async function api(ctx, body) {
|
|
230
|
+
// A machine still pausing or slow to start answers a retryable error: begin tries again before giving up.
|
|
231
|
+
const attempts = body.action === 'begin' ? BEGIN_ATTEMPTS : 1;
|
|
232
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
233
|
+
try {
|
|
234
|
+
const result = await httpRequest({ runtime: { ...ctx.runtime, timeoutMs: Math.max(ctx.runtime.timeoutMs || 0, 600_000) },
|
|
235
|
+
method: 'POST', path: '/portal_spaces/cloud-transfer', body, spacesProtocol: true });
|
|
236
|
+
return result.payload || {};
|
|
237
|
+
} catch (error) {
|
|
238
|
+
if (attempt >= attempts || !(error instanceof CliError) || !error.retryable) throw error;
|
|
239
|
+
ctx.output.emitProgress({ phase: 'wait', message: 'Your Cloud Computer is starting, trying again' });
|
|
240
|
+
await sleepFor(BEGIN_RETRY_MS * attempt);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** A gate session whose pass is refreshed in the background and re-begun when the machine stopped. */
|
|
246
|
+
class GateSession {
|
|
247
|
+
constructor(ctx, begun, beginBody) {
|
|
248
|
+
this.ctx = ctx;
|
|
249
|
+
this.beginBody = beginBody;
|
|
250
|
+
this.apply(begun);
|
|
251
|
+
this.refreshing = null;
|
|
252
|
+
// Renewing more often than the server's 120 s transfer lease keeps the idle pause waiting while bytes flow,
|
|
253
|
+
// even when the gate's own activity reports cannot reach Notis.
|
|
254
|
+
this.timer = setInterval(() => { this.refresh().catch(() => {}); }, LEASE_RENEW_MS);
|
|
255
|
+
this.timer.unref?.();
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
apply(answer) {
|
|
259
|
+
this.answer = answer;
|
|
260
|
+
this.id = answer.session_id;
|
|
261
|
+
this.url = answer.transfer_url;
|
|
262
|
+
this.pass = answer.pass;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async refresh() {
|
|
266
|
+
if (!this.refreshing) {
|
|
267
|
+
this.refreshing = api(this.ctx, { action: 'status', session_id: this.id }).then(answer => this.apply(answer))
|
|
268
|
+
.finally(() => { this.refreshing = null; });
|
|
269
|
+
}
|
|
270
|
+
return this.refreshing;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Wake the machine again (it may have stopped) and resume the same session. */
|
|
274
|
+
async rebegin() {
|
|
275
|
+
if (!this.rebeginning) {
|
|
276
|
+
this.rebeginning = api(this.ctx, { ...this.beginBody, session_id: this.id }).then(answer => this.apply(answer))
|
|
277
|
+
.finally(() => { this.rebeginning = null; });
|
|
278
|
+
}
|
|
279
|
+
return this.rebeginning;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
close() {
|
|
283
|
+
clearInterval(this.timer);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** One gate request with retries: a 401 refreshes the pass, a dead link wakes the machine. */
|
|
287
|
+
async fetch(route, init = {}, { expect = [200], attempts = MAX_ATTEMPTS } = {}) {
|
|
288
|
+
let lastError = null;
|
|
289
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
290
|
+
let response;
|
|
291
|
+
let watchdog = null;
|
|
292
|
+
try {
|
|
293
|
+
const body = typeof init.body === 'function' ? await init.body() : init.body;
|
|
294
|
+
// A part or batch is given as long as its bytes keep leaving: on a slow link, 8 streams of 32 MiB
|
|
295
|
+
// can take far longer than any fixed limit, and restarting them only sends the same bytes again.
|
|
296
|
+
const streamed = body instanceof Uint8Array && body.length > STREAM_BODY_MIN ? body : null;
|
|
297
|
+
let signal = AbortSignal.timeout(init.timeoutMs || 300_000);
|
|
298
|
+
if (streamed) {
|
|
299
|
+
watchdog = idleWatchdog(SEND_IDLE_MS);
|
|
300
|
+
signal = watchdog.signal;
|
|
301
|
+
}
|
|
302
|
+
response = await fetch(`${this.url}/${route}`, { ...init, redirect: 'manual',
|
|
303
|
+
body: streamed ? streamBody(streamed, () => watchdog.touch()) : body, ...(streamed ? { duplex: 'half' } : {}),
|
|
304
|
+
headers: { ...(init.headers || {}), authorization: `Bearer ${this.pass}`,
|
|
305
|
+
...(streamed ? { 'content-length': String(streamed.length) } : {}) }, signal });
|
|
306
|
+
// Bytes all sent: the gate now checks the part and answers; give that its own limit.
|
|
307
|
+
watchdog?.touch(ANSWER_IDLE_MS);
|
|
308
|
+
} catch (error) {
|
|
309
|
+
watchdog?.stop();
|
|
310
|
+
lastError = error;
|
|
311
|
+
await sleepFor(Math.min(30_000, 500 * 2 ** attempt));
|
|
312
|
+
if (attempt >= 2) await this.rebegin().catch(() => {});
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
if (response.status === 401) {
|
|
316
|
+
await response.arrayBuffer().catch(() => {});
|
|
317
|
+
await this.refresh();
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
if ([301, 302, 303, 307, 308, 502, 503, 504].includes(response.status)) {
|
|
321
|
+
// A stopped machine answers the provider's redirect or a gateway error: wake it and go on.
|
|
322
|
+
await response.arrayBuffer().catch(() => {});
|
|
323
|
+
lastError = new Error(`gate_${response.status}`);
|
|
324
|
+
await sleepFor(Math.min(30_000, 1000 * attempt));
|
|
325
|
+
await this.rebegin().catch(() => {});
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
if (expect.includes(response.status)) return response;
|
|
329
|
+
let body = {};
|
|
330
|
+
try { body = await response.json(); } catch { body = {}; }
|
|
331
|
+
if (response.status >= 500 && attempt < attempts && body.error !== 'disk_full') {
|
|
332
|
+
lastError = new Error(body.error || `gate_${response.status}`);
|
|
333
|
+
await sleepFor(Math.min(30_000, 1000 * attempt));
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
throw transferError(body.error === 'disk_full' ? 'cloud_computer_disk_full' : `cloud_transfer_${body.error || response.status}`,
|
|
337
|
+
body.error === 'disk_full' ? 'Your Cloud Computer is out of disk space.' : `The Cloud Computer refused the transfer (${body.error || response.status}).`, body);
|
|
338
|
+
}
|
|
339
|
+
throw transferError('cloud_computer_unreachable', 'Your Cloud Computer stopped answering. Run the same command again to resume.',
|
|
340
|
+
{ reason: lastError?.message || lastError?.name });
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async json(route, init, options) {
|
|
344
|
+
const response = await this.fetch(route, init, options);
|
|
345
|
+
return response.json();
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function progressReporter(ctx, label, total) {
|
|
350
|
+
const started = Date.now();
|
|
351
|
+
let last = 0;
|
|
352
|
+
let sent = 0;
|
|
353
|
+
const report = (force = false) => {
|
|
354
|
+
const now = Date.now();
|
|
355
|
+
if (!force && now - last < PROGRESS_EVERY_MS) return;
|
|
356
|
+
last = now;
|
|
357
|
+
const seconds = Math.max(0.001, (now - started) / 1000);
|
|
358
|
+
const rate = sent / seconds;
|
|
359
|
+
const percent = total ? Math.floor((sent / total) * 100) : 100;
|
|
360
|
+
ctx.output.emitProgress({ phase: label, message: `${formatBytes(sent)} of ${formatBytes(total)} (${percent}%), ${formatBytes(rate)}/s` });
|
|
361
|
+
};
|
|
362
|
+
return {
|
|
363
|
+
add(bytes) { sent += bytes; report(); },
|
|
364
|
+
done() { report(true); return { bytes: sent, seconds: (Date.now() - started) / 1000 }; },
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async function pool(tasks, size, run) {
|
|
369
|
+
const queue = [...tasks];
|
|
370
|
+
let failure = null;
|
|
371
|
+
const worker = async () => {
|
|
372
|
+
while (queue.length && !failure) {
|
|
373
|
+
const task = queue.shift();
|
|
374
|
+
try { await run(task); } catch (error) { failure = failure || error; }
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
await Promise.all(Array.from({ length: Math.min(size, Math.max(1, queue.length)) }, worker));
|
|
378
|
+
if (failure) throw failure;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Push `local` to the Cloud Computer. `target` is { spaceId, dest } (dest inside the Space folder) or
|
|
383
|
+
* { path } (a folder on the machine). Answers a summary with sizes, times and the session id.
|
|
384
|
+
*/
|
|
385
|
+
export async function push(ctx, local, target, { streams = PARALLEL_STREAMS, followLinks = true } = {}) {
|
|
386
|
+
const collected = await collectFiles(local, { followLinks });
|
|
387
|
+
const files = collected.files;
|
|
388
|
+
if (!files.length) throw usageError(`${local} has no files to send.`);
|
|
389
|
+
if (files.length > 200_000) throw usageError('Send at most 200000 files at once.');
|
|
390
|
+
const key = JSON.stringify(['push', ctx.runtime.apiBase, ctx.runtime.profileName, path.resolve(local), target]);
|
|
391
|
+
const saved = readState(key) || {};
|
|
392
|
+
const total = files.reduce((sum, file) => sum + file.size, 0);
|
|
393
|
+
ctx.output.emitProgress({ phase: 'scan', message: `${files.length} files, ${formatBytes(total)}${collected.skipped.length ? `, ${collected.skipped.length} skipped` : ''}` });
|
|
394
|
+
|
|
395
|
+
const hashing = progressReporter(ctx, 'hash', total);
|
|
396
|
+
let hashed = 0;
|
|
397
|
+
await hashAll(files, saved.hashes || {}, done => { hashing.add(done - hashed); hashed = done; });
|
|
398
|
+
const hashTime = hashing.done();
|
|
399
|
+
const hashes = Object.fromEntries(files.map(file => [file.path, { size: file.size, mtimeMs: file.mtimeMs, sha256: file.sha256 }]));
|
|
400
|
+
const text = manifestText(files);
|
|
401
|
+
const digest = digestOf(text);
|
|
402
|
+
|
|
403
|
+
const beginBody = { action: 'begin', direction: 'push', manifest_digest: digest, file_count: files.length, total_bytes: total,
|
|
404
|
+
...(target.spaceId ? { space_id: target.spaceId, dest: { space: target.dest || 'files' } } : { path: target.path }) };
|
|
405
|
+
let begun = null;
|
|
406
|
+
if (saved.session_id && saved.manifest_digest === digest) {
|
|
407
|
+
try {
|
|
408
|
+
begun = await api(ctx, { ...beginBody, session_id: saved.session_id });
|
|
409
|
+
} catch (error) {
|
|
410
|
+
if (!['cloud_transfer_conflict', 'cloud_transfer_closed', 'cloud_transfer_unknown', 'cloud_transfer_machine_changed'].includes(error.code)) throw error;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
if (!begun) begun = await api(ctx, beginBody);
|
|
414
|
+
writeState(key, { session_id: begun.session_id, manifest_digest: digest, hashes });
|
|
415
|
+
const summary = { session_id: begun.session_id, root: begun.root, files: files.length, total_bytes: total,
|
|
416
|
+
skipped: collected.skipped, resumed: Boolean(begun.resumed), hash_seconds: hashTime.seconds };
|
|
417
|
+
if (begun.status === 'committed') return { ...summary, status: 'committed', already_committed: true, sent_bytes: 0 };
|
|
418
|
+
|
|
419
|
+
const session = new GateSession(ctx, begun, beginBody);
|
|
420
|
+
try {
|
|
421
|
+
let state = await session.json('manifest', { method: 'PUT', body: Buffer.from(text), headers: { 'content-type': 'text/plain' } });
|
|
422
|
+
const smallLimit = begun.small_file_bytes;
|
|
423
|
+
const batchLimit = begun.batch_bytes;
|
|
424
|
+
const chunkSize = begun.chunk_size;
|
|
425
|
+
const already = state.received_bytes || 0;
|
|
426
|
+
if (already) ctx.output.emitProgress({ phase: 'resume', message: `${formatBytes(already)} already on the Cloud Computer` });
|
|
427
|
+
const progress = progressReporter(ctx, 'send', total - already);
|
|
428
|
+
const timings = { small: { bytes: 0, ms: 0 }, large: { bytes: 0, ms: 0 } };
|
|
429
|
+
const largeStarted = { at: null, end: null };
|
|
430
|
+
const smallStarted = { at: null, end: null };
|
|
431
|
+
|
|
432
|
+
for (let round = 1; round <= 3; round += 1) {
|
|
433
|
+
const complete = new Set(state.complete || []);
|
|
434
|
+
const chunks = state.chunks || {};
|
|
435
|
+
const tasks = [];
|
|
436
|
+
let batch = [];
|
|
437
|
+
let batchBytes = 0;
|
|
438
|
+
const flush = () => {
|
|
439
|
+
if (batch.length) tasks.push({ kind: 'batch', items: batch, bytes: batchBytes });
|
|
440
|
+
batch = [];
|
|
441
|
+
batchBytes = 0;
|
|
442
|
+
};
|
|
443
|
+
files.forEach((file, index) => {
|
|
444
|
+
if (complete.has(index)) return;
|
|
445
|
+
if (file.size <= smallLimit) {
|
|
446
|
+
if (batchBytes + file.size > batchLimit || batch.length >= MAX_FILES_PER_BATCH) flush();
|
|
447
|
+
batch.push(index);
|
|
448
|
+
batchBytes += file.size;
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
const have = new Set(chunks[index] || []);
|
|
452
|
+
for (let chunk = 0; chunk * chunkSize < file.size; chunk += 1) {
|
|
453
|
+
if (!have.has(chunk)) tasks.push({ kind: 'chunk', index, chunk, bytes: Math.min(chunkSize, file.size - chunk * chunkSize) });
|
|
454
|
+
}
|
|
455
|
+
});
|
|
456
|
+
flush();
|
|
457
|
+
// Big chunks first, so the long tail is small batches running beside each other.
|
|
458
|
+
tasks.sort((a, b) => (a.kind === b.kind ? 0 : a.kind === 'chunk' ? -1 : 1));
|
|
459
|
+
await pool(tasks, streams, async task => {
|
|
460
|
+
const started = Date.now();
|
|
461
|
+
if (task.kind === 'chunk') {
|
|
462
|
+
largeStarted.at = largeStarted.at ?? started;
|
|
463
|
+
const file = files[task.index];
|
|
464
|
+
const offset = task.chunk * chunkSize;
|
|
465
|
+
const data = await readRange(file.abs, offset, task.bytes);
|
|
466
|
+
await session.fetch(`f/${task.index}?offset=${offset}`, { method: 'PUT', body: data,
|
|
467
|
+
headers: { 'x-notis-sha256': createHash('sha256').update(data).digest('hex'), 'content-type': 'application/octet-stream' } });
|
|
468
|
+
timings.large.bytes += task.bytes;
|
|
469
|
+
largeStarted.end = Date.now();
|
|
470
|
+
} else {
|
|
471
|
+
smallStarted.at = smallStarted.at ?? started;
|
|
472
|
+
const entries = [];
|
|
473
|
+
for (const index of task.items) entries.push({ index, data: await readRange(files[index].abs, 0, files[index].size) });
|
|
474
|
+
const answer = await session.json('batch', { method: 'POST', body: tarBatch(entries), headers: { 'content-type': 'application/x-tar' } },
|
|
475
|
+
{ expect: [200, 422] });
|
|
476
|
+
if (answer.rejected?.length) {
|
|
477
|
+
throw transferError('cloud_transfer_rejected', `${answer.rejected.length} files changed while they were sent. Run the same command again.`, answer);
|
|
478
|
+
}
|
|
479
|
+
timings.small.bytes += task.bytes;
|
|
480
|
+
smallStarted.end = Date.now();
|
|
481
|
+
}
|
|
482
|
+
progress.add(task.bytes);
|
|
483
|
+
});
|
|
484
|
+
const committed = await api(ctx, { action: 'commit', session_id: session.id });
|
|
485
|
+
if (committed.status === 'committed') {
|
|
486
|
+
const sent = progress.done();
|
|
487
|
+
writeState(key, { session_id: session.id, manifest_digest: digest, hashes, committed: true });
|
|
488
|
+
const rate = (bytes, window) => (window.at && window.end > window.at ? bytes / ((window.end - window.at) / 1000) : null);
|
|
489
|
+
return { ...summary, status: 'committed', committed_bytes: committed.committed_bytes, wire_bytes: committed.wire_bytes,
|
|
490
|
+
sent_bytes: sent.bytes, seconds: sent.seconds, resumed_from_bytes: already,
|
|
491
|
+
large: { bytes: timings.large.bytes, bytes_per_second: rate(timings.large.bytes, largeStarted) },
|
|
492
|
+
small: { bytes: timings.small.bytes, bytes_per_second: rate(timings.small.bytes, smallStarted) } };
|
|
493
|
+
}
|
|
494
|
+
state = await session.json('state', { method: 'GET' });
|
|
495
|
+
}
|
|
496
|
+
throw transferError('cloud_transfer_incomplete', 'Some files did not arrive. Run the same command again to send the rest.');
|
|
497
|
+
} finally {
|
|
498
|
+
session.close();
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** Pull `remote` (a file or folder on the machine) into `local`, resumable. */
|
|
503
|
+
export async function pull(ctx, target, local, { streams = PARALLEL_STREAMS } = {}) {
|
|
504
|
+
const beginBody = { action: 'begin', direction: 'pull',
|
|
505
|
+
...(target.spaceId ? { space_id: target.spaceId, dest: { space: target.dest } } : { path: target.path }) };
|
|
506
|
+
const begun = await api(ctx, beginBody);
|
|
507
|
+
const session = new GateSession(ctx, begun, beginBody);
|
|
508
|
+
try {
|
|
509
|
+
const listing = await session.json('list?hash=1', { method: 'GET', timeoutMs: 1_800_000 });
|
|
510
|
+
const single = listing.kind === 'file';
|
|
511
|
+
let destination = path.resolve(local);
|
|
512
|
+
if (single) {
|
|
513
|
+
const isDir = fs.existsSync(destination) && fs.statSync(destination).isDirectory();
|
|
514
|
+
if (isDir || local.endsWith('/')) destination = path.join(destination, path.basename(begun.root));
|
|
515
|
+
}
|
|
516
|
+
const files = listing.files.map(file => ({ ...file, local: single ? destination : path.join(destination, ...file.path.split('/')) }));
|
|
517
|
+
for (const file of files) {
|
|
518
|
+
if (!single && !validRelative(file.path)) throw transferError('cloud_transfer_bad_path', `The Cloud Computer listed an unsafe path: ${file.path}`);
|
|
519
|
+
}
|
|
520
|
+
const total = files.reduce((sum, file) => sum + file.size, 0);
|
|
521
|
+
ctx.output.emitProgress({ phase: 'scan', message: `${files.length} files, ${formatBytes(total)}` });
|
|
522
|
+
const progress = progressReporter(ctx, 'receive', total);
|
|
523
|
+
let skippedSame = 0;
|
|
524
|
+
const tasks = [];
|
|
525
|
+
for (const file of files) {
|
|
526
|
+
if (fs.existsSync(file.local) && fs.statSync(file.local).size === file.size && await hashFile(file.local) === file.sha256) {
|
|
527
|
+
skippedSame += 1;
|
|
528
|
+
progress.add(file.size);
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
tasks.push(file);
|
|
532
|
+
}
|
|
533
|
+
await pool(tasks, streams, file => pullFile(session, file, progress, streams));
|
|
534
|
+
const sent = progress.done();
|
|
535
|
+
await api(ctx, { action: 'commit', session_id: session.id }).catch(() => ({}));
|
|
536
|
+
return { session_id: session.id, root: begun.root, local: destination, files: files.length, total_bytes: total,
|
|
537
|
+
unchanged_files: skippedSame, skipped: listing.skipped || [], seconds: sent.seconds, status: 'received' };
|
|
538
|
+
} finally {
|
|
539
|
+
session.close();
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
async function pullFile(session, file, progress, streams) {
|
|
544
|
+
await fsp.mkdir(path.dirname(file.local), { recursive: true });
|
|
545
|
+
const part = `${file.local}.notis-part`;
|
|
546
|
+
const sidecar = `${part}.json`;
|
|
547
|
+
const query = `file?path=${encodeURIComponent(file.path)}`;
|
|
548
|
+
let meta = {};
|
|
549
|
+
try { meta = JSON.parse(fs.readFileSync(sidecar, 'utf8')); } catch { meta = {}; }
|
|
550
|
+
if (meta.sha256 !== file.sha256 || meta.size !== file.size) {
|
|
551
|
+
meta = { sha256: file.sha256, size: file.size, done: [] };
|
|
552
|
+
await fsp.rm(part, { force: true });
|
|
553
|
+
}
|
|
554
|
+
const handle = await fsp.open(part, fs.existsSync(part) ? 'r+' : 'w+');
|
|
555
|
+
try {
|
|
556
|
+
const chunks = Math.max(1, Math.ceil(file.size / PULL_CHUNK));
|
|
557
|
+
const done = new Set(meta.done);
|
|
558
|
+
for (const chunk of done) progress.add(Math.min(PULL_CHUNK, file.size - chunk * PULL_CHUNK));
|
|
559
|
+
const todo = [];
|
|
560
|
+
for (let chunk = 0; chunk < chunks; chunk += 1) if (!done.has(chunk) && file.size > 0) todo.push(chunk);
|
|
561
|
+
let saving = Promise.resolve();
|
|
562
|
+
await pool(todo, file.size > PULL_CHUNK ? Math.min(streams, 4) : 1, async chunk => {
|
|
563
|
+
const start = chunk * PULL_CHUNK;
|
|
564
|
+
const end = Math.min(file.size, start + PULL_CHUNK) - 1;
|
|
565
|
+
const response = await session.fetch(query, { method: 'GET', headers: { range: `bytes=${start}-${end}` } }, { expect: [206, 200] });
|
|
566
|
+
const data = Buffer.from(await response.arrayBuffer());
|
|
567
|
+
const expected = end - start + 1;
|
|
568
|
+
const slice = response.status === 200 ? data.subarray(start, end + 1) : data;
|
|
569
|
+
if (slice.length !== expected) throw transferError('cloud_transfer_short_read', `A part of ${file.path} came back short. Run the same command again.`);
|
|
570
|
+
await handle.write(slice, 0, slice.length, start);
|
|
571
|
+
done.add(chunk);
|
|
572
|
+
progress.add(slice.length);
|
|
573
|
+
saving = saving.then(() => fsp.writeFile(sidecar, JSON.stringify({ ...meta, done: [...done] })));
|
|
574
|
+
await saving;
|
|
575
|
+
});
|
|
576
|
+
await handle.sync();
|
|
577
|
+
} finally {
|
|
578
|
+
await handle.close();
|
|
579
|
+
}
|
|
580
|
+
if (await hashFile(part) !== file.sha256) {
|
|
581
|
+
await fsp.rm(part, { force: true });
|
|
582
|
+
await fsp.rm(sidecar, { force: true });
|
|
583
|
+
throw transferError('cloud_transfer_sha256_mismatch', `${file.path} did not match its sha256. Run the same command again.`);
|
|
584
|
+
}
|
|
585
|
+
await fsp.rename(part, file.local);
|
|
586
|
+
await fsp.rm(sidecar, { force: true });
|
|
587
|
+
}
|