dewctl 0.6.6 → 0.8.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dewctl",
3
- "version": "0.6.6",
3
+ "version": "0.8.0",
4
4
  "description": "Build and publish three.js games on Dewdrop.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/client.js CHANGED
@@ -1,8 +1,9 @@
1
1
  // Requests to Dewdrop, only ever to the address in dewdrop.json, signed in with the session login stored.
2
- import {createHash} from 'node:crypto';
2
+ import {tarChunks} from './tar.js';
3
3
  import {RUN} from './command.js';
4
+ // A refusal as Dewdrop answered it: its status, its words, and the whole answer for what else it says.
4
5
  export class ApiError extends Error {
5
- constructor(status,message){super(message);this.status=status;}
6
+ constructor(status,message,body){super(message);this.status=status;this.body=body;}
6
7
  }
7
8
  // A member's address becomes a path segment; refuse anything that could reach another route.
8
9
  const EMAIL=/^[^\s@/?#%]+@[^\s@/?#%]+\.[^\s@/?#%]+$/;
@@ -14,12 +15,17 @@ export function sleep(ms,signal) {
14
15
  if(signal?.aborted)cancel();else signal?.addEventListener('abort',cancel,{once:true});
15
16
  });
16
17
  }
17
- // An upload is sent in parts of at most this many bytes.
18
+ // A push's request carries at most this many bytes of files; a file over this many is sent on its own, in parts of
19
+ // at most this many.
18
20
  export const PART_BYTES=32*1024*1024;
21
+ // A push's first request carries the files not yet confirmed only up to this many bytes of them: a save's few changed
22
+ // files go in one round trip, while a run's first push — the whole game, which Dewdrop mostly has from the last run —
23
+ // sends the manifest alone and lets the answer name what is missing.
24
+ export const PROBE_BYTES=1024*1024;
19
25
  // How long a poll asks the platform to hold it for news (`Prefer: wait`), under what the edge holds a request open.
20
26
  const WAIT_S=25;
21
- // `chunks` cut into runs of exactly `bytes`, but the last, which is what remains and never empty: an archive given
22
- // as a run of buffers of any lengths is sent in parts of one size, holding about one part at a time.
27
+ // `chunks` cut into runs of exactly `bytes`, but the last, which is what remains and never empty: a file given as a
28
+ // run of buffers of any lengths is sent in parts of one size, holding about one part at a time.
23
29
  export function* parts(chunks,bytes=PART_BYTES) {
24
30
  let part=Buffer.allocUnsafe(bytes),filled=0;
25
31
  for(let chunk of chunks) {
@@ -32,10 +38,11 @@ export function* parts(chunks,bytes=PART_BYTES) {
32
38
  if(filled)yield part.subarray(0,filled);
33
39
  }
34
40
  export class Client {
35
- // `partBytes` is for the tests, which cut at a few bytes; an upload is sent in parts of PART_BYTES.
41
+ // `partBytes` is for the tests, which cut at a few bytes; a push's requests and a file's parts are PART_BYTES.
36
42
  // `pollMs` is the least a wait on the platform takes a round: a platform that holds the request answers when there
37
43
  // is news, within WAIT_S; one that answers at once instead is asked again after that long.
38
- constructor(origin,credentials,{fetcher=fetch,pollMs=1000,timeoutMs=180000,storeMs=15*60*1000,partBytes=PART_BYTES}={}){this.origin=origin;this.credentials=credentials;this.fetcher=fetcher;this.pollMs=pollMs;this.timeoutMs=timeoutMs;this.storeMs=storeMs;this.partBytes=partBytes;this.holds=true;}
44
+ // `confirmed` holds the hashes of the files Dewdrop has been seen to have, for this run.
45
+ constructor(origin,credentials,{fetcher=fetch,pollMs=1000,timeoutMs=180000,storeMs=15*60*1000,partBytes=PART_BYTES}={}){this.origin=origin;this.credentials=credentials;this.fetcher=fetcher;this.pollMs=pollMs;this.timeoutMs=timeoutMs;this.storeMs=storeMs;this.partBytes=partBytes;this.holds=true;this.confirmed=new Set();}
39
46
  // A request signed in with `token`. When Dewdrop can't be reached the failure is marked transient, which a watcher
40
47
  // or a sign-in waits out; a refused token asks for a new sign-in, whatever Dewdrop's words.
41
48
  async request(path,{method='GET',body,token,signal,type,prefer}={}) {
@@ -52,8 +59,8 @@ export class Client {
52
59
  const contentType=response.headers.get('content-type')??'';
53
60
  if(!contentType.includes('application/json'))throw new ApiError(response.status,`${this.origin} didn't answer as Dewdrop does (HTTP ${response.status}). Try again in a moment.`);
54
61
  const data=await response.json();
55
- if(response.status===401&&token)throw new ApiError(401,`Your sign-in has ended: it expired or was signed out. Run ${RUN} login.`);
56
- if(!response.ok)throw new ApiError(response.status,data.error??`HTTP ${response.status}`);
62
+ if(response.status===401&&token)throw new ApiError(401,`Your sign-in has ended: it expired or was signed out. Run ${RUN} login.`,data);
63
+ if(!response.ok)throw new ApiError(response.status,data.error??`HTTP ${response.status}`,data);
57
64
  return data;
58
65
  }
59
66
  // The session this computer holds, or why there is none to use.
@@ -77,24 +84,71 @@ export class Client {
77
84
  throw error;
78
85
  }
79
86
  }
80
- // Uploads a build of a claimed game under its id — its archive read through again as `bundle.chunks()` gives it,
81
- // cut into parts of PART_BYTES, so a bundle of gigabytes is never held whole; what is sent is hashed as it goes,
82
- // and an archive that no longer hashes to the id changed since the id was taken, and is refused — then completes
83
- // it with the number of parts,
84
- // asking for the answer at once: Dewdrop takes a large release in over minutes, longer than a request stays
85
- // open, so an answer at once names the `phase` it is in, and this follows at the release's address, telling
86
- // `progress` each phase it sees, until Dewdrop records the release — the answer with its `bytes` — or refuses it.
87
- // A Dewdrop from before the answer at once records the release in the request itself. Dewdrop must confirm the
88
- // same id.
89
- async upload(game,bundle,signal,progress) {
90
- let count=0;
91
- const hash=createHash('sha256');
92
- for(const part of parts(bundle.chunks(),this.partBytes)) {
93
- hash.update(part);
94
- await this.api(`/v1/games/${game}/releases/${bundle.id}/parts/${count++}`,{method:'PUT',body:part,signal});
87
+ // Pushes a build of a claimed game as the tree its manifest names: the manifest goes up under its hash, with the
88
+ // files Dewdrop may lack when they are few — else alone — and Dewdrop answers either that the release is recorded
89
+ // or which of the manifest's files it still lacks for this game, sent in further requests of PART_BYTES of files —
90
+ // only those, never a file it did not ask for — until it records the release, which must carry the same id. A file
91
+ // over PART_BYTES goes up on its own first, in parts. The files Dewdrop confirms, by recording the release or by not
92
+ // asking for them again, are remembered for the run, so the next push's first request carries only what changed. A
93
+ // Dewdrop from before trees refuses the first request, which is older than this dewctl. `progress` is told what is
94
+ // being sent or checked, what Dewdrop turned out to lack, and each phase of a file stored over minutes.
95
+ async push(game,bundle,signal,progress) {
96
+ const path=`/v1/games/${game}/releases/${bundle.id}`;
97
+ // `.manifest` sorts before every path a manifest allows, so the writer puts it first.
98
+ const manifest={path:'.manifest',size:bundle.manifest.length,read:()=>[bundle.manifest]};
99
+ const byHash=new Map(bundle.entries.map(entry=>[entry.sha256,entry]));
100
+ let pending=[...byHash.values()].filter(({sha256})=>!this.confirmed.has(sha256)),lacking=Infinity;
101
+ const unconfirmed=pending.reduce((sum,{size})=>sum+size,0),probing=unconfirmed>PROBE_BYTES;
102
+ progress?.(probing?{checking:pending.length,bytes:unconfirmed}:{files:pending.length,bytes:unconfirmed});
103
+ for(let first=true;;first=false) {
104
+ // What fits one request, largest first; a file over a request goes on its own once Dewdrop has asked for it.
105
+ pending.sort((a,b)=>b.size-a.size);
106
+ const sent=[];
107
+ let room=this.partBytes;
108
+ for(const entry of pending) {
109
+ if(first&&probing)break;
110
+ if(entry.size>this.partBytes){if(!first){await this.blob(game,entry,signal,progress);sent.push(entry);}}
111
+ else if(entry.size<=room){room-=entry.size;sent.push(entry);}
112
+ }
113
+ const body=Buffer.concat([...tarChunks([manifest,...sent.filter(({size})=>size<=this.partBytes)])]);
114
+ let result;
115
+ try { result=await this.api(path,{method:'PUT',body,type:'application/x-tar',signal}); }
116
+ catch(error) {
117
+ if(first&&[405,413,415].includes(error.status))throw new Error('This Dewdrop is older than this dewctl and can\'t take the release yet. Try again later.');
118
+ if(error.status!==409||!Array.isArray(error.body?.missing))throw error;
119
+ const missing=new Set(error.body.missing);
120
+ for(const {sha256} of sent)if(!missing.has(sha256))this.confirmed.add(sha256);
121
+ // Each answer must ask for less than the one before, or what was sent is not being kept.
122
+ if(missing.size>=lacking||!missing.size)throw new Error('Dewdrop didn\'t keep the files it was sent, so nothing was changed. Try again.');
123
+ lacking=missing.size;
124
+ pending=[...missing].map(sha256=>{
125
+ if(!byHash.has(sha256))throw new Error('Dewdrop asked for a file that isn\'t in the build, so nothing was changed. Try again.');
126
+ return byHash.get(sha256);
127
+ });
128
+ if(first)progress?.({missing:pending.length,bytes:pending.reduce((sum,{size})=>sum+size,0)});
129
+ continue;
130
+ }
131
+ if(result.release!==bundle.id)throw new Error('Dewdrop stored a different release than was uploaded, so nothing was changed. Try again.');
132
+ for(const sha256 of byHash.keys())this.confirmed.add(sha256);
133
+ return result;
95
134
  }
96
- if(hash.digest('hex')!==bundle.id)throw new Error('The build\'s output changed while it was being uploaded. Try again.');
97
- const path=`/v1/games/${game}/releases/${bundle.id}`,deadline=Date.now()+this.storeMs;
135
+ }
136
+ // A file over PART_BYTES, sent on its own under its hash: in parts, then completed and followed, and Dewdrop must
137
+ // confirm the same hash.
138
+ async blob(game,entry,signal,progress) {
139
+ const path=`/v1/games/${game}/blobs/${entry.sha256}`;
140
+ let count=0;
141
+ for(const part of parts(entry.read(),this.partBytes))await this.api(`${path}/parts/${count++}`,{method:'PUT',body:part,signal});
142
+ const result=await this.#complete(path,count,signal,phase=>progress?.({phase}));
143
+ if(result.blob!==entry.sha256)throw new Error('Dewdrop stored a different file than was uploaded, so nothing was changed. Try again.');
144
+ return result;
145
+ }
146
+ // Completes a file's upload at `path` with the number of its parts, asking for the answer at once: Dewdrop takes a
147
+ // large one in over minutes, longer than a request stays open, so an answer at once names the `phase` it is in, and
148
+ // this follows at the same address, telling `progress` each phase it sees, until Dewdrop records the file — the
149
+ // answer with its `bytes` — or refuses it. A Dewdrop that is done at once records it in the request itself.
150
+ async #complete(path,count,signal,progress) {
151
+ const deadline=Date.now()+this.storeMs;
98
152
  let result=await this.api(path,{method:'POST',body:{parts:count},signal,prefer:'respond-async'}),phase;
99
153
  while(result.bytes===undefined) {
100
154
  if(Date.now()>=deadline)throw new Error(`Dewdrop is taking longer than fifteen minutes to store the upload. Run ${RUN} releases to see whether it arrived.`);
@@ -104,7 +158,6 @@ export class Client {
104
158
  result=await this.api(path,{signal,prefer:`wait=${WAIT_S}`});
105
159
  if(result.bytes===undefined)await this.#rest(asked,signal);
106
160
  }
107
- if(result.release!==bundle.id)throw new Error('Dewdrop stored a different release than was uploaded, so nothing was changed. Try again.');
108
161
  return result;
109
162
  }
110
163
  activate(game,release,signal,started){return this.point(game,'dev',release,signal,started);}
package/src/hash.js ADDED
@@ -0,0 +1,82 @@
1
+ // The bundle's files read and hashed: each opened as a regular file under its root and no symlink, and the ones a
2
+ // snapshot has not hashed as they stand hashed in worker threads, each reading its file itself, when there are more
3
+ // than a few MiB of them. Started as a worker, this module hashes the files it is handed.
4
+ import {openSync,closeSync,fstatSync,readSync,constants,realpathSync} from 'node:fs';
5
+ import {createHash} from 'node:crypto';
6
+ import {Worker,isMainThread,parentPort} from 'node:worker_threads';
7
+ import {availableParallelism} from 'node:os';
8
+
9
+ // The most bytes a bundle holds, Dewdrop's bound: 5 GiB of files.
10
+ export const MAX_BYTES=5*1024**3;
11
+ // A file is read from its descriptor this many bytes at a time, so a bundle of gigabytes passes through a few MiB.
12
+ const CHUNK_BYTES=4*1024*1024;
13
+ // Under this many bytes to hash, the files are hashed here: starting worker threads costs more than hashing a few MiB.
14
+ const INLINE_BYTES=8*1024*1024;
15
+
16
+ // Opens a file of the project as a regular file under `root` and no symlink, gives out the run of buffers `fn` reads
17
+ // from its descriptor and stat, and closes it once the run is taken, or left early.
18
+ function* opened(file,root,fn) {
19
+ const actual=realpathSync(file);
20
+ if(!actual.startsWith(`${root}/`)||actual!==file)throw new Error(`Symlinks cannot be uploaded: ${file}`);
21
+ const fd=openSync(file,constants.O_RDONLY|constants.O_NOFOLLOW);
22
+ try {
23
+ const stat=fstatSync(fd);
24
+ if(!stat.isFile()||stat.size>MAX_BYTES)throw new Error(`Not a regular file of at most 5 GiB: ${file}`);
25
+ yield* fn(fd,stat);
26
+ } finally { closeSync(fd); }
27
+ }
28
+ // The first `size` bytes of the descriptor, a chunk at a time, stopping where the file ends.
29
+ function* readFrom(fd,size) {
30
+ for(let offset=0;offset<size;) {
31
+ const chunk=Buffer.allocUnsafe(Math.min(CHUNK_BYTES,size-offset)),count=readSync(fd,chunk,0,chunk.length,offset);
32
+ if(count===0)return;
33
+ yield count<chunk.length?chunk.subarray(0,count):chunk;
34
+ offset+=count;
35
+ }
36
+ }
37
+ const changed=path=>new Error(`${path} changed while it was being uploaded. Try again.`);
38
+ // The file's `size` bytes as the walk saw them, for the entry at `path`: a file of another size now, one cut short
39
+ // under the read, or one that no longer hashes to `sha256` when that is known, has changed since the walk, and the
40
+ // upload is refused rather than sent with it.
41
+ export function* entryBytes(path,file,root,size,sha256) {
42
+ let count=0;
43
+ const hash=sha256===undefined?null:createHash('sha256');
44
+ for(const chunk of opened(file,root,(fd,stat)=>{if(stat.size!==size)throw changed(path);return readFrom(fd,size);})) { count+=chunk.length;hash?.update(chunk);yield chunk; }
45
+ if(count!==size||hash&&hash.digest('hex')!==sha256)throw changed(path);
46
+ }
47
+ // The hash of one file, `{path, file, root, size}`, read here.
48
+ export function hashFile({path,file,root,size}) {
49
+ const hash=createHash('sha256');
50
+ for(const chunk of entryBytes(path,file,root,size))hash.update(chunk);
51
+ return hash.digest('hex');
52
+ }
53
+ // The hashes of `jobs`, by path: a few MiB are hashed here; more are shared out, largest first, among worker threads
54
+ // — one for every few MiB, up to one a core — each reading the files it is handed. Any file refused ends the work,
55
+ // with its reason.
56
+ export async function hashFiles(jobs) {
57
+ const hashes=new Map(),total=jobs.reduce((sum,{size})=>sum+size,0);
58
+ if(total<INLINE_BYTES) {
59
+ for(const job of jobs)hashes.set(job.path,hashFile(job));
60
+ return hashes;
61
+ }
62
+ const queue=[...jobs].sort((a,b)=>b.size-a.size);
63
+ let failed;
64
+ await Promise.all(Array.from({length:Math.min(availableParallelism(),queue.length,Math.ceil(total/INLINE_BYTES))},()=>new Promise((resolve,reject)=>{
65
+ const worker=new Worker(new URL(import.meta.url));
66
+ // The next file in line, or this worker's end: a refused file empties the line, so every worker stops at its next turn.
67
+ const next=()=>{const job=queue.shift();if(job)worker.postMessage(job);else worker.terminate().then(resolve,reject);};
68
+ worker.on('message',({path,sha256,error})=>{
69
+ if(error!==undefined){failed??=new Error(error);queue.length=0;}
70
+ else hashes.set(path,sha256);
71
+ next();
72
+ });
73
+ worker.on('error',error=>{failed??=error;queue.length=0;resolve();});
74
+ next();
75
+ })));
76
+ if(failed)throw failed;
77
+ return hashes;
78
+ }
79
+ if(!isMainThread&&parentPort)parentPort.on('message',job=>{
80
+ try { parentPort.postMessage({path:job.path,sha256:hashFile(job)}); }
81
+ catch(error) { parentPort.postMessage({path:job.path,error:error.message}); }
82
+ });
package/src/main.js CHANGED
@@ -193,6 +193,10 @@ async function main() {
193
193
  console.log('Ready to play.');return;
194
194
  }
195
195
  if(flags.watch)await watch(project,client,{signal,reread:()=>readProject(project.root)});
196
- else if((await deploy(project,client,{signal})).changed)throw new Error(`Files changed during the build, so nothing was uploaded. Run ${RUN} dev again, or ${RUN} dev --watch to rebuild on every save.`);
196
+ else {
197
+ // Claimed before the build, so a name someone else has or an ended sign-in is known at once.
198
+ await client.claim(game,signal);
199
+ if((await deploy(project,client,{signal})).changed)throw new Error(`Files changed during the build, so nothing was uploaded. Run ${RUN} dev again, or ${RUN} dev --watch to rebuild on every save.`);
200
+ }
197
201
  }
198
202
  main().catch(error=>{console.error(`dewctl: ${error.message}`);process.exitCode=1;});
package/src/project.js CHANGED
@@ -1,18 +1,15 @@
1
- // The project as dewdrop.json describes it, its build, and the archive its bundle folder is uploaded as.
2
- import {readFileSync, writeFileSync, existsSync, lstatSync, readdirSync, openSync, closeSync, fstatSync, readSync, constants, realpathSync, mkdirSync, rmSync} from 'node:fs';
1
+ // The project as dewdrop.json describes it, its build, and the manifest of its bundle folder's files it is uploaded as.
2
+ import {readFileSync, writeFileSync, existsSync, lstatSync, readdirSync, realpathSync, mkdirSync, rmSync} from 'node:fs';
3
3
  import {resolve, relative, join, isAbsolute, basename, dirname} from 'node:path';
4
4
  import {createHash,randomBytes} from 'node:crypto';
5
5
  import {spawn} from 'node:child_process';
6
6
  import {fileURLToPath} from 'node:url';
7
7
  import {gunzipSync} from 'node:zlib';
8
8
  import {createInterface} from 'node:readline';
9
- import {tarChunks,tarLength,readTar} from './tar.js';
9
+ import {readTar} from './tar.js';
10
+ import {MAX_BYTES,entryBytes,hashFiles} from './hash.js';
10
11
  import {RUN} from './command.js';
11
12
 
12
- // The most bytes a bundle holds, Dewdrop's bound: 5 GiB of files.
13
- const MAX_BYTES = 5 * 1024 ** 3;
14
- // A file is read from its descriptor this many bytes at a time, so a bundle of gigabytes passes through a few MiB.
15
- const CHUNK_BYTES = 4 * 1024 * 1024;
16
13
  const ignored = new Set(['node_modules','dist','target']);
17
14
  const GAME_NAME = /^[a-z][a-z0-9-]{0,47}$/;
18
15
  export const DEWDROP = 'https://alpha.dewdrop.world';
@@ -54,43 +51,14 @@ export function readProject(root = process.cwd()) {
54
51
  return {...config,root};
55
52
  }
56
53
 
57
- // Opens a file of the project as a regular file under `root` and no symlink, gives out the run of buffers `fn` reads
58
- // from its descriptor and stat, and closes it once the run is taken, or left early.
59
- function* opened(file, root, fn) {
60
- const actual = realpathSync(file);
61
- if (!actual.startsWith(`${root}/`) || actual !== file) throw new Error(`Symlinks cannot be uploaded: ${file}`);
62
- const fd = openSync(file,constants.O_RDONLY|constants.O_NOFOLLOW);
63
- try {
64
- const stat=fstatSync(fd);
65
- if (!stat.isFile() || stat.size > MAX_BYTES) throw new Error(`Not a regular file of at most 5 GiB: ${file}`);
66
- yield* fn(fd,stat);
67
- } finally { closeSync(fd); }
68
- }
69
- // The first `size` bytes of the descriptor, a chunk at a time, stopping where the file ends.
70
- function* readFrom(fd, size) {
71
- for (let offset=0;offset<size;) {
72
- const chunk=Buffer.allocUnsafe(Math.min(CHUNK_BYTES,size-offset)),count=readSync(fd,chunk,0,chunk.length,offset);
73
- if (count===0) return;
74
- yield count<chunk.length?chunk.subarray(0,count):chunk;
75
- offset+=count;
76
- }
77
- }
78
- const changed=path=>new Error(`${path} changed while it was being uploaded. Try again.`);
79
- // The file's `size` bytes as the walk saw them, for the archive's entry at `path`: a file of another size now, or one
80
- // cut short under the read, has changed since the walk, and the upload is refused rather than sent with it.
81
- function* entryBytes(path, file, root, size) {
82
- let count=0;
83
- for (const chunk of opened(file,root,(fd,stat)=>{if (stat.size!==size) throw changed(path);return readFrom(fd,size);})) { count+=chunk.length;yield chunk; }
84
- if (count!==size) throw changed(path);
85
- }
86
- // Every regular file under `start`, by its path under `root`, with its size: what is walked is not read, so a
87
- // bundle over the budget is refused on its sizes alone, before any file is opened. Names starting with a dot are
88
- // always left out; watching also leaves out the bundle folder, node_modules, dist and target, and
89
- // passes over the symlinks an upload refuses.
54
+ // Every regular file under `start`, by its path under `root`, with its size and its stamp — size, times and inode, which
55
+ // tell the file as it stands from any other write of it: what is walked is not read, so a bundle over the budget is
56
+ // refused on its sizes alone, before any file is opened. Names starting with a dot are always left out; watching also
57
+ // leaves out the bundle folder, node_modules, dist and target, and passes over the symlinks an upload refuses.
90
58
  function walk(root, start, files, {watch = false, output, budget = {bytes:0}} = {}) {
91
59
  if (watch && (start === output || start.startsWith(`${output}/`))) return;
92
60
  if (!existsSync(start)) return;
93
- const stat=lstatSync(start);
61
+ const stat=lstatSync(start,{bigint:true});
94
62
  if (stat.isSymbolicLink()) {
95
63
  if (watch) return;
96
64
  throw new Error(`Symlinks cannot be uploaded: ${start}`);
@@ -102,22 +70,27 @@ function walk(root, start, files, {watch = false, output, budget = {bytes:0}} =
102
70
  }
103
71
  } else {
104
72
  if (files.size >= 4096) throw new Error(watch ? 'More than 4096 files are in the project folder, too many for dev to follow. Move what the game doesn\'t need out of it (node_modules, dist, target, the bundle folder and names starting with a dot don\'t count).' : 'The build\'s output has more than 4096 files, the most Dewdrop takes.');
105
- if (!watch && (budget.bytes += stat.size) > MAX_BYTES) throw new Error('The build\'s output is over 5 GiB, the most Dewdrop takes.');
106
- files.set(relative(root,start).split('\\').join('/'),{file:start,size:stat.size});
73
+ const size=Number(stat.size);
74
+ if (!watch && (budget.bytes += size) > MAX_BYTES) throw new Error('The build\'s output is over 5 GiB, the most Dewdrop takes.');
75
+ files.set(relative(root,start).split('\\').join('/'),{file:start,size,stamp:`${size}\0${stat.mtimeNs}\0${stat.ctimeNs}\0${stat.ino}`});
107
76
  }
108
77
  }
109
- // The project's files as one digest of their paths and bytes, which changes whenever any file the walk follows does.
78
+ // The project's files as one digest of their paths and stamps, which changes whenever any file the walk follows is
79
+ // written, added or removed; no file is read for it.
110
80
  export function fingerprint(project) {
111
81
  const files=new Map();
112
82
  walk(project.root,project.root,files,{watch:true,output:projectPath(project.root,project.bundle)});
113
83
  const digest=createHash('sha256');
114
- for (const [path,{file,size}] of [...files].sort(([a],[b])=>a<b?-1:1)) {
115
- digest.update(`${path}\0${size}\0`);
116
- for (const chunk of opened(file,project.root,fd=>readFrom(fd,size))) digest.update(chunk);
117
- }
84
+ for (const [path,{stamp}] of [...files].sort(([a],[b])=>a<b?-1:1)) digest.update(`${path}\0${stamp}\0`);
118
85
  return digest.digest('hex');
119
86
  }
120
- export function snapshot(project) {
87
+ // The hashes of the files the last snapshot saw, each under its file and stamp, so a file as it stood then is not
88
+ // read again: a build's every write gives a file a new time or inode, which misses here and is hashed afresh.
89
+ let hashes=new Map();
90
+ export function forgetHashes() { hashes=new Map(); }
91
+ // The bundle as a release: the manifest of its files — a line each of hash, size and path, in the order of the
92
+ // paths' bytes — which names the release by its own hash, with each file's bytes to read for the upload.
93
+ export async function snapshot(project) {
121
94
  const directory=projectPath(project.root,project.bundle);
122
95
  if (!existsSync(directory)) throw new Error(project.build
123
96
  ? `The build wrote no ${project.bundle} folder. Set "bundle" in dewdrop.json to the folder your build (vite build) writes.`
@@ -134,16 +107,21 @@ export function snapshot(project) {
134
107
  : `There's no main.js in ${project.bundle}. Build with the Dewdrop plugin in vite.config.js (vite build), and set "bundle" in dewdrop.json to the folder that build writes.`);
135
108
  }
136
109
  let bytes=0;
137
- const entries=[...files].map(([path,{file,size}])=>{
110
+ // The paths are ASCII, so their order as strings is the order of their bytes, the manifest's order.
111
+ const listed=[...files].sort(([a],[b])=>a<b?-1:1).map(([path,{file,size,stamp}])=>{
138
112
  if (path.length>240 || !path.split('/').every(p=>/^[A-Za-z0-9_][A-Za-z0-9_. -]*$/.test(p)&&!p.endsWith('.')&&!p.endsWith(' '))) throw new Error(`Can't upload ${path}: a name in it must start with a letter, digit or _ and hold only letters, digits, _, ., - and spaces, and the whole path must be under 240 characters.`);
139
113
  bytes+=size;
140
- return {path,size,read:()=>entryBytes(path,file,root,size)};
114
+ return {path,size,file,key:`${file}\0${stamp}`};
115
+ });
116
+ // The files not hashed as they stand are read now; then the hashes kept are the bundle's files alone.
117
+ const fresh=await hashFiles(listed.filter(({key})=>!hashes.has(key)).map(({path,file,size})=>({path,file,root,size})));
118
+ hashes=new Map(listed.map(entry=>[entry.key,hashes.get(entry.key)??fresh.get(entry.path)]));
119
+ const entries=listed.map(({path,size,file,key})=>{
120
+ const sha256=hashes.get(key);
121
+ return {path,size,sha256,read:()=>entryBytes(path,file,root,size,sha256)};
141
122
  });
142
- // The same files always make the same bytes, which give the upload its id: `chunks` is the archive as a run of
143
- // buffers, read through here for the id and again by the upload that sends it, `size` bytes in all.
144
- const chunks=()=>tarChunks(entries),digest=createHash('sha256');
145
- for (const chunk of chunks()) digest.update(chunk);
146
- return {id:digest.digest('hex'),size:tarLength(entries),bytes,files:files.size,chunks};
123
+ const manifest=Buffer.from(entries.map(({sha256,size,path})=>`${sha256} ${size} ${path}\n`).join(''));
124
+ return {id:createHash('sha256').update(manifest).digest('hex'),bytes,files:entries.length,manifest,entries};
147
125
  }
148
126
  export async function build(project, signal) {
149
127
  if (!project.build) return;
package/src/tar.js CHANGED
@@ -1,4 +1,4 @@
1
- // The archive an upload is sent as: ustar, regular files only, written byte for byte the same for the same files.
1
+ // The archive a push's request is sent as: ustar, regular files only, written byte for byte the same for the same files.
2
2
  const BLOCK=512;
3
3
  const octal=(value,length)=>value.toString(8).padStart(length-1,'0')+'\0';
4
4
  const field=(block,offset,length,text)=>block.write(text,offset,length,'latin1');
@@ -31,8 +31,7 @@ function header(path,size) {
31
31
 
32
32
  // One archive of `entries` — `{path, size, read}` each, `read()` giving the file's `size` bytes as a run of buffers —
33
33
  // in path order, with no owner, time or mode but the fixed ones, as a run of buffers: each file's header, its bytes
34
- // as `read` gives them, and its padding, then the two blocks that end the archive. The run is read through once for
35
- // the archive's id and once more to send it, a few MiB at a time, so an upload of gigabytes is never held whole.
34
+ // as `read` gives them, and its padding, then the two blocks that end the archive.
36
35
  const padded=size=>size+(size%BLOCK?BLOCK-size%BLOCK:0);
37
36
  export function* tarChunks(entries) {
38
37
  const sorted=[...entries].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
@@ -43,8 +42,6 @@ export function* tarChunks(entries) {
43
42
  }
44
43
  yield Buffer.alloc(2*BLOCK);
45
44
  }
46
- // The archive's length, from its entries' sizes alone.
47
- export const tarLength=entries=>entries.reduce((sum,{size})=>sum+BLOCK+padded(size),0)+2*BLOCK;
48
45
  // The archive as one buffer, for the small ones the tests make.
49
46
  export const packTar=entries=>Buffer.concat([...tarChunks(entries)]);
50
47
 
package/src/watch.js CHANGED
@@ -1,6 +1,5 @@
1
1
  // Poll the project's files across edits, deletions and atomic saves; only one build and activation runs at a time.
2
2
  import {watch as watchDirectory} from 'node:fs';
3
- import {PART_BYTES} from './client.js';
4
3
  import {fingerprint,build,snapshot,followed} from './project.js';
5
4
  import {devPlayUrl} from './play.js';
6
5
  import {RUN} from './command.js';
@@ -13,19 +12,24 @@ export function size(bytes) {
13
12
  }
14
13
  // What Dewdrop is doing with an upload that takes a while, by the phase the client sees it in.
15
14
  const PHASES={waiting:'Waiting for Dewdrop to take the upload…',assembling:'Dewdrop is assembling the upload…',checking:'Dewdrop is checking the upload…',storing:'Dewdrop is storing the upload…',copying:'Dewdrop is copying the upload to its regions…',recording:'Dewdrop is recording the upload…'};
16
- // Claims the game before building, so a name someone else has or an ended sign-in is known at once; then builds,
17
- // uploads and plays the build as the dev version.
15
+ const count=(n,noun)=>`${n} ${noun}${n===1?'':'s'}`;
16
+ // What a push says as it goes, in the developer's terms: the files going up, or checked with Dewdrop first, the ones
17
+ // Dewdrop turned out to lack, and each phase of a file stored over minutes.
18
+ const telling=log=>event=>{
19
+ if(event.phase!==undefined)log(PHASES[event.phase]??`Dewdrop is ${event.phase} the upload…`);
20
+ else if(event.checking!==undefined)log(`Checking ${count(event.checking,'file')} (${size(event.bytes)}) with Dewdrop…`);
21
+ else if(event.missing!==undefined)log(`Uploading ${count(event.missing,'changed file')} (${size(event.bytes)})…`);
22
+ else if(event.files===0)log('Dewdrop has every file of the build; recording the release…');
23
+ else log(`Uploading ${count(event.files,'file')} (${size(event.bytes)})…`);
24
+ };
25
+ // Builds, pushes and plays the build of a claimed game as the dev version, under the id Dewdrop recorded it by.
18
26
  export async function deploy(project,client,{signal,log=console.log}={}) {
19
- await client.claim(project.game,signal);
20
27
  const before=fingerprint(project);
21
28
  log('Building…');
22
29
  await build(project,signal);
23
30
  if(fingerprint(project)!==before)return {changed:true};
24
- const bundle=snapshot(project);
25
- const parts=Math.max(1,Math.ceil(bundle.size/PART_BYTES));
26
- log(`Uploading ${bundle.files} file${bundle.files===1?'':'s'} (${size(bundle.bytes)})${parts>1?` in ${parts} parts`:''}…`);
27
- await client.upload(project.game,bundle,signal,phase=>log(PHASES[phase]??`Dewdrop is ${phase} the upload…`));
28
- await client.activate(project.game,bundle.id,signal,game=>log(`Starting ${bundle.id.slice(0,12)} at ${devPlayUrl(game)}`));
31
+ const {release}=await client.push(project.game,await snapshot(project),signal,telling(log));
32
+ await client.activate(project.game,release,signal,game=>log(`Starting ${release.slice(0,12)} at ${devPlayUrl(game)}`));
29
33
  log('Ready to play.');
30
34
  return {changed:false};
31
35
  }
@@ -47,11 +51,12 @@ export function watchTree(current,changed,lost=()=>{}) {
47
51
  // event — an editor writes a file in several steps, and a save-all many files — or, where the tree cannot be watched,
48
52
  // by looking the files over every `pollMs`, a save settled `debounceMs` after the last change found. `reread` gives
49
53
  // the project as dewdrop.json says it now, so an edit to it applies to the next build; a dewdrop.json that no longer
50
- // reads waits, like a failed build, for the next save.
54
+ // reads waits, like a failed build, for the next save. The game is claimed once for the session, before its first
55
+ // build, so a name someone else has or an ended sign-in is known at once, and again only for a game dewdrop.json renames.
51
56
  export const EVENT_DEBOUNCE_MS=100;
52
57
  export async function watch(project,client,{signal,log=console.log,deployGame=deploy,readFingerprint=fingerprint,reread=()=>project,watchFiles=watchTree,pollMs=200,debounceMs=500}={}) {
53
58
  let changedAt=Date.now()-debounceMs,dirty=true;
54
- let running=null;
59
+ let running=null,claimed=null;
55
60
  const noted=()=>{changedAt=Date.now();dirty=true;};
56
61
  let watching=watchFiles?.(()=>project,noted,()=>{watching=null;observed=readFingerprint(project);});
57
62
  let observed=watching?null:readFingerprint(project);
@@ -65,7 +70,10 @@ export async function watch(project,client,{signal,log=console.log,deployGame=de
65
70
  if(dirty&&!running&&Date.now()-changedAt>=(watching?EVENT_DEBOUNCE_MS:debounceMs)) {
66
71
  dirty=false;
67
72
  project=reread();
68
- running=deployGame(project,client,{signal,log}).then(result=>{
73
+ running=(async()=>{
74
+ if(project.game!==claimed){await client.claim(project.game,signal);claimed=project.game;}
75
+ return deployGame(project,client,{signal,log});
76
+ })().then(result=>{
69
77
  if(result.changed)dirty=true;
70
78
  }).catch(error=>{
71
79
  if(signal?.aborted)return;