dewctl 0.6.6 → 0.7.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.7.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,10 @@
1
1
  // Requests to Dewdrop, only ever to the address in dewdrop.json, signed in with the session login stored.
2
2
  import {createHash} from 'node:crypto';
3
+ import {tarChunks} from './tar.js';
3
4
  import {RUN} from './command.js';
5
+ // A refusal as Dewdrop answered it: its status, its words, and the whole answer for what else it says.
4
6
  export class ApiError extends Error {
5
- constructor(status,message){super(message);this.status=status;}
7
+ constructor(status,message,body){super(message);this.status=status;this.body=body;}
6
8
  }
7
9
  // A member's address becomes a path segment; refuse anything that could reach another route.
8
10
  const EMAIL=/^[^\s@/?#%]+@[^\s@/?#%]+\.[^\s@/?#%]+$/;
@@ -16,6 +18,10 @@ export function sleep(ms,signal) {
16
18
  }
17
19
  // An upload is sent in parts of at most this many bytes.
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
27
  // `chunks` cut into runs of exactly `bytes`, but the last, which is what remains and never empty: an archive given
@@ -35,7 +41,9 @@ export class Client {
35
41
  // `partBytes` is for the tests, which cut at a few bytes; an upload is sent in parts of 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
+ // `pushes` is whether Dewdrop takes a release as its tree, until its answer says otherwise; `confirmed` holds the
45
+ // hashes of the files it has been seen to have, for this run.
46
+ 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.pushes=true;this.confirmed=new Set();}
39
47
  // A request signed in with `token`. When Dewdrop can't be reached the failure is marked transient, which a watcher
40
48
  // or a sign-in waits out; a refused token asks for a new sign-in, whatever Dewdrop's words.
41
49
  async request(path,{method='GET',body,token,signal,type,prefer}={}) {
@@ -52,8 +60,8 @@ export class Client {
52
60
  const contentType=response.headers.get('content-type')??'';
53
61
  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
62
  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}`);
63
+ if(response.status===401&&token)throw new ApiError(401,`Your sign-in has ended: it expired or was signed out. Run ${RUN} login.`,data);
64
+ if(!response.ok)throw new ApiError(response.status,data.error??`HTTP ${response.status}`,data);
57
65
  return data;
58
66
  }
59
67
  // The session this computer holds, or why there is none to use.
@@ -77,15 +85,76 @@ export class Client {
77
85
  throw error;
78
86
  }
79
87
  }
88
+ // Pushes a build of a claimed game as the tree its manifest names: the manifest goes up under its hash, with the
89
+ // files Dewdrop may lack when they are few — else alone — and Dewdrop answers either that the release is recorded
90
+ // or which of the manifest's files it still lacks for this game, sent in further requests of PART_BYTES of files —
91
+ // only those, never a file it did not ask for — until it records the release, which must carry the same id. A file
92
+ // over PART_BYTES goes up on its own first, in parts. The files Dewdrop confirms, by recording the release or by not
93
+ // asking for them again, are remembered for the run, so the next push's first request carries only what changed; a
94
+ // Dewdrop from before trees refuses the first request, and takes the release whole from then on. `progress` is told
95
+ // what is being sent or checked, what Dewdrop turned out to lack, and each phase of a file stored over minutes.
96
+ async push(game,bundle,signal,progress) {
97
+ if(!this.pushes)return this.whole(game,bundle,signal,progress);
98
+ const path=`/v1/games/${game}/releases/${bundle.id}`;
99
+ // `.manifest` sorts before every path a manifest allows, so the writer puts it first.
100
+ const manifest={path:'.manifest',size:bundle.manifest.length,read:()=>[bundle.manifest]};
101
+ const byHash=new Map(bundle.entries.map(entry=>[entry.sha256,entry]));
102
+ let pending=[...byHash.values()].filter(({sha256})=>!this.confirmed.has(sha256)),lacking=Infinity;
103
+ const unconfirmed=pending.reduce((sum,{size})=>sum+size,0),probing=unconfirmed>PROBE_BYTES;
104
+ progress?.(probing?{checking:pending.length,bytes:unconfirmed}:{files:pending.length,bytes:unconfirmed});
105
+ for(let first=true;;first=false) {
106
+ // What fits one request, largest first; a file over a request goes on its own once Dewdrop has asked for it.
107
+ pending.sort((a,b)=>b.size-a.size);
108
+ const sent=[];
109
+ let room=this.partBytes;
110
+ for(const entry of pending) {
111
+ if(first&&probing)break;
112
+ if(entry.size>this.partBytes){if(!first){await this.blob(game,entry,signal,progress);sent.push(entry);}}
113
+ else if(entry.size<=room){room-=entry.size;sent.push(entry);}
114
+ }
115
+ const body=Buffer.concat([...tarChunks([manifest,...sent.filter(({size})=>size<=this.partBytes)])]);
116
+ let result;
117
+ try { result=await this.api(path,{method:'PUT',body,type:'application/x-tar',signal}); }
118
+ catch(error) {
119
+ if(first&&[405,413,415].includes(error.status)){this.pushes=false;return this.whole(game,bundle,signal,progress);}
120
+ if(error.status!==409||!Array.isArray(error.body?.missing))throw error;
121
+ const missing=new Set(error.body.missing);
122
+ for(const {sha256} of sent)if(!missing.has(sha256))this.confirmed.add(sha256);
123
+ // Each answer must ask for less than the one before, or what was sent is not being kept.
124
+ if(missing.size>=lacking||!missing.size)throw new Error('Dewdrop didn\'t keep the files it was sent, so nothing was changed. Try again.');
125
+ lacking=missing.size;
126
+ pending=[...missing].map(sha256=>{
127
+ if(!byHash.has(sha256))throw new Error('Dewdrop asked for a file that isn\'t in the build, so nothing was changed. Try again.');
128
+ return byHash.get(sha256);
129
+ });
130
+ if(first)progress?.({missing:pending.length,bytes:pending.reduce((sum,{size})=>sum+size,0)});
131
+ continue;
132
+ }
133
+ if(result.release!==bundle.id)throw new Error('Dewdrop stored a different release than was uploaded, so nothing was changed. Try again.');
134
+ for(const sha256 of byHash.keys())this.confirmed.add(sha256);
135
+ return result;
136
+ }
137
+ }
138
+ // A file over PART_BYTES, sent on its own under its hash: in parts, as a release is, completed and followed the same
139
+ // way, and Dewdrop must confirm the same hash.
140
+ async blob(game,entry,signal,progress) {
141
+ const path=`/v1/games/${game}/blobs/${entry.sha256}`;
142
+ let count=0;
143
+ for(const part of parts(entry.read(),this.partBytes))await this.api(`${path}/parts/${count++}`,{method:'PUT',body:part,signal});
144
+ const result=await this.#complete(path,count,signal,phase=>progress?.({phase}));
145
+ if(result.blob!==entry.sha256)throw new Error('Dewdrop stored a different file than was uploaded, so nothing was changed. Try again.');
146
+ return result;
147
+ }
148
+ // The release sent whole, as a Dewdrop from before trees takes it: the archive of every file, in parts.
149
+ whole(game,bundle,signal,progress) {
150
+ const archive=bundle.archive();
151
+ progress?.({whole:Math.max(1,Math.ceil(archive.size/this.partBytes)),files:bundle.files,bytes:bundle.bytes});
152
+ return this.upload(game,archive,signal,phase=>progress?.({phase}));
153
+ }
80
154
  // Uploads a build of a claimed game under its id — its archive read through again as `bundle.chunks()` gives it,
81
155
  // cut into parts of PART_BYTES, so a bundle of gigabytes is never held whole; what is sent is hashed as it goes,
82
156
  // 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.
157
+ // it with the number of parts. Dewdrop must confirm the same id.
89
158
  async upload(game,bundle,signal,progress) {
90
159
  let count=0;
91
160
  const hash=createHash('sha256');
@@ -94,7 +163,16 @@ export class Client {
94
163
  await this.api(`/v1/games/${game}/releases/${bundle.id}/parts/${count++}`,{method:'PUT',body:part,signal});
95
164
  }
96
165
  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;
166
+ const result=await this.#complete(`/v1/games/${game}/releases/${bundle.id}`,count,signal,progress);
167
+ if(result.release!==bundle.id)throw new Error('Dewdrop stored a different release than was uploaded, so nothing was changed. Try again.');
168
+ return result;
169
+ }
170
+ // Completes an upload at `path` with the number of its parts, asking for the answer at once: Dewdrop takes a large
171
+ // one in over minutes, longer than a request stays open, so an answer at once names the `phase` it is in, and this
172
+ // follows at the same address, telling `progress` each phase it sees, until Dewdrop records the upload — the answer
173
+ // with its `bytes` — or refuses it. A Dewdrop from before the answer at once records it in the request itself.
174
+ async #complete(path,count,signal,progress) {
175
+ const deadline=Date.now()+this.storeMs;
98
176
  let result=await this.api(path,{method:'POST',body:{parts:count},signal,prefer:'respond-async'}),phase;
99
177
  while(result.bytes===undefined) {
100
178
  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 +182,6 @@ export class Client {
104
182
  result=await this.api(path,{signal,prefer:`wait=${WAIT_S}`});
105
183
  if(result.bytes===undefined)await this.#rest(asked,signal);
106
184
  }
107
- if(result.release!==bundle.id)throw new Error('Dewdrop stored a different release than was uploaded, so nothing was changed. Try again.');
108
185
  return result;
109
186
  }
110
187
  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,5 +1,5 @@
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';
@@ -7,12 +7,9 @@ import {fileURLToPath} from 'node:url';
7
7
  import {gunzipSync} from 'node:zlib';
8
8
  import {createInterface} from 'node:readline';
9
9
  import {tarChunks,tarLength,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,28 @@ 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, and the
93
+ // archive of them all for a Dewdrop that takes releases whole.
94
+ export async function snapshot(project) {
121
95
  const directory=projectPath(project.root,project.bundle);
122
96
  if (!existsSync(directory)) throw new Error(project.build
123
97
  ? `The build wrote no ${project.bundle} folder. Set "bundle" in dewdrop.json to the folder your build (vite build) writes.`
@@ -134,16 +108,28 @@ export function snapshot(project) {
134
108
  : `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
109
  }
136
110
  let bytes=0;
137
- const entries=[...files].map(([path,{file,size}])=>{
111
+ // The paths are ASCII, so their order as strings is the order of their bytes, the manifest's order.
112
+ const listed=[...files].sort(([a],[b])=>a<b?-1:1).map(([path,{file,size,stamp}])=>{
138
113
  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
114
  bytes+=size;
140
- return {path,size,read:()=>entryBytes(path,file,root,size)};
115
+ return {path,size,file,key:`${file}\0${stamp}`};
116
+ });
117
+ // The files not hashed as they stand are read now; then the hashes kept are the bundle's files alone.
118
+ const fresh=await hashFiles(listed.filter(({key})=>!hashes.has(key)).map(({path,file,size})=>({path,file,root,size})));
119
+ hashes=new Map(listed.map(entry=>[entry.key,hashes.get(entry.key)??fresh.get(entry.path)]));
120
+ const entries=listed.map(({path,size,file,key})=>{
121
+ const sha256=hashes.get(key);
122
+ return {path,size,sha256,read:()=>entryBytes(path,file,root,size,sha256)};
141
123
  });
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};
124
+ const manifest=Buffer.from(entries.map(({sha256,size,path})=>`${sha256} ${size} ${path}\n`).join(''));
125
+ return {id:createHash('sha256').update(manifest).digest('hex'),bytes,files:entries.length,manifest,entries,
126
+ // The same files always make the same archive, which names it: `chunks` is the archive as a run of buffers,
127
+ // read through here for the id and again by the upload that sends it, `size` bytes in all.
128
+ archive() {
129
+ const chunks=()=>tarChunks(entries),digest=createHash('sha256');
130
+ for (const chunk of chunks()) digest.update(chunk);
131
+ return {id:digest.digest('hex'),size:tarLength(entries),chunks};
132
+ }};
147
133
  }
148
134
  export async function build(project, signal) {
149
135
  if (!project.build) return;
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,25 @@ 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, each phase of an upload stored over minutes, and a Dewdrop that takes the release whole.
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.whole!==undefined)log(`Dewdrop takes the release whole here: uploading ${count(event.files,'file')} (${size(event.bytes)})${event.whole>1?` in ${event.whole} parts`:''}…`);
23
+ else if(event.files===0)log('Dewdrop has every file of the build; recording the release…');
24
+ else log(`Uploading ${count(event.files,'file')} (${size(event.bytes)})…`);
25
+ };
26
+ // Builds, pushes and plays the build of a claimed game as the dev version, under the id Dewdrop recorded it by.
18
27
  export async function deploy(project,client,{signal,log=console.log}={}) {
19
- await client.claim(project.game,signal);
20
28
  const before=fingerprint(project);
21
29
  log('Building…');
22
30
  await build(project,signal);
23
31
  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)}`));
32
+ const {release}=await client.push(project.game,await snapshot(project),signal,telling(log));
33
+ await client.activate(project.game,release,signal,game=>log(`Starting ${release.slice(0,12)} at ${devPlayUrl(game)}`));
29
34
  log('Ready to play.');
30
35
  return {changed:false};
31
36
  }
@@ -47,11 +52,12 @@ export function watchTree(current,changed,lost=()=>{}) {
47
52
  // event — an editor writes a file in several steps, and a save-all many files — or, where the tree cannot be watched,
48
53
  // by looking the files over every `pollMs`, a save settled `debounceMs` after the last change found. `reread` gives
49
54
  // 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.
55
+ // reads waits, like a failed build, for the next save. The game is claimed once for the session, before its first
56
+ // 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
57
  export const EVENT_DEBOUNCE_MS=100;
52
58
  export async function watch(project,client,{signal,log=console.log,deployGame=deploy,readFingerprint=fingerprint,reread=()=>project,watchFiles=watchTree,pollMs=200,debounceMs=500}={}) {
53
59
  let changedAt=Date.now()-debounceMs,dirty=true;
54
- let running=null;
60
+ let running=null,claimed=null;
55
61
  const noted=()=>{changedAt=Date.now();dirty=true;};
56
62
  let watching=watchFiles?.(()=>project,noted,()=>{watching=null;observed=readFingerprint(project);});
57
63
  let observed=watching?null:readFingerprint(project);
@@ -65,7 +71,10 @@ export async function watch(project,client,{signal,log=console.log,deployGame=de
65
71
  if(dirty&&!running&&Date.now()-changedAt>=(watching?EVENT_DEBOUNCE_MS:debounceMs)) {
66
72
  dirty=false;
67
73
  project=reread();
68
- running=deployGame(project,client,{signal,log}).then(result=>{
74
+ running=(async()=>{
75
+ if(project.game!==claimed){await client.claim(project.game,signal);claimed=project.game;}
76
+ return deployGame(project,client,{signal,log});
77
+ })().then(result=>{
69
78
  if(result.changed)dirty=true;
70
79
  }).catch(error=>{
71
80
  if(signal?.aborted)return;