dewctl 0.6.4 → 0.6.5

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.
@@ -81,6 +81,8 @@ The code ([limits](https://alpha.dewdrop.world/docs/limits)):
81
81
  `color-scheme: dark`. Put what the page shows under `public/ui/`, or import it.
82
82
  - `fetch` reads only the game's own files. WebSocket, WebRTC and workers aren't available. Sound plays through
83
83
  Web Audio; `<audio>` and `<video>` make no sound.
84
+ - `localStorage` and `indexedDB` throw. Storage is `saves.storage` and `saves.indexedDB` from `dewdrop-sdk`, open
85
+ once `await saves.load()` is done, and kept only by `await saves.save()` ([saves](https://alpha.dewdrop.world/docs/saves)).
84
86
  - Keep `three` at 0.185.1, which Dewdrop provides ([project](https://alpha.dewdrop.world/docs/project)).
85
87
 
86
88
  ## 4. The working loop
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dewctl",
3
- "version": "0.6.4",
3
+ "version": "0.6.5",
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,4 +1,5 @@
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
3
  import {RUN} from './command.js';
3
4
  export class ApiError extends Error {
4
5
  constructor(status,message){super(message);this.status=status;}
@@ -15,16 +16,30 @@ export function sleep(ms,signal) {
15
16
  }
16
17
  // An upload is sent in parts of at most this many bytes.
17
18
  export const PART_BYTES=32*1024*1024;
19
+ // `chunks` cut into runs of exactly `bytes`, but the last, which is what remains and never empty: an archive given
20
+ // as a run of buffers of any lengths is sent in parts of one size, holding about one part at a time.
21
+ export function* parts(chunks,bytes=PART_BYTES) {
22
+ let part=Buffer.allocUnsafe(bytes),filled=0;
23
+ for(let chunk of chunks) {
24
+ while(chunk.length) {
25
+ const taken=chunk.copy(part,filled,0,Math.min(chunk.length,bytes-filled));
26
+ filled+=taken;chunk=chunk.subarray(taken);
27
+ if(filled===bytes){yield part;part=Buffer.allocUnsafe(bytes);filled=0;}
28
+ }
29
+ }
30
+ if(filled)yield part.subarray(0,filled);
31
+ }
18
32
  export class Client {
19
- constructor(origin,credentials,{fetcher=fetch,pollMs=1000,timeoutMs=180000}={}){this.origin=origin;this.credentials=credentials;this.fetcher=fetcher;this.pollMs=pollMs;this.timeoutMs=timeoutMs;}
33
+ // `partBytes` is for the tests, which cut at a few bytes; an upload is sent in parts of PART_BYTES.
34
+ 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;}
20
35
  // A request signed in with `token`. When Dewdrop can't be reached the failure is marked transient, which a watcher
21
36
  // or a sign-in waits out; a refused token asks for a new sign-in, whatever Dewdrop's words.
22
- async request(path,{method='GET',body,token,signal,type}={}) {
37
+ async request(path,{method='GET',body,token,signal,type,prefer}={}) {
23
38
  if(!path.startsWith('/v1/'))throw new Error('Invalid API path.');
24
39
  const bytes=Buffer.isBuffer(body);
25
40
  let response;
26
41
  try {
27
- response=await this.fetcher(this.origin+path,{method,redirect:'error',signal:signal?AbortSignal.any([signal,AbortSignal.timeout(120000)]):AbortSignal.timeout(120000),headers:{...(token?{authorization:`Bearer ${token}`}:{}),...(body!==undefined?{'content-type':type??(bytes?'application/octet-stream':'application/json')}:{})},body:body===undefined?undefined:bytes||typeof body==='string'?body:JSON.stringify(body)});
42
+ response=await this.fetcher(this.origin+path,{method,redirect:'error',signal:signal?AbortSignal.any([signal,AbortSignal.timeout(120000)]):AbortSignal.timeout(120000),headers:{...(token?{authorization:`Bearer ${token}`}:{}),...(body!==undefined?{'content-type':type??(bytes?'application/octet-stream':'application/json')}:{}),...(prefer?{prefer}:{})},body:body===undefined?undefined:bytes||typeof body==='string'?body:JSON.stringify(body)});
28
43
  } catch(error) {
29
44
  if(signal?.aborted)throw error;
30
45
  const reason=error.name==='TimeoutError'?'no answer in two minutes':error.cause?.code??error.cause?.message??error.message;
@@ -58,14 +73,31 @@ export class Client {
58
73
  throw error;
59
74
  }
60
75
  }
61
- // Uploads a build of a claimed game under its id, in parts of PART_BYTES, then completes it with the number of
62
- // parts; Dewdrop must confirm the same id.
63
- async upload(game,bundle,signal) {
64
- const parts=Math.max(1,Math.ceil(bundle.body.length/PART_BYTES));
65
- for(let index=0;index<parts;index++) {
66
- await this.api(`/v1/games/${game}/releases/${bundle.id}/parts/${index}`,{method:'PUT',body:bundle.body.subarray(index*PART_BYTES,(index+1)*PART_BYTES),signal});
76
+ // Uploads a build of a claimed game under its id — its archive read through again as `bundle.chunks()` gives it,
77
+ // cut into parts of PART_BYTES, so a bundle of gigabytes is never held whole; what is sent is hashed as it goes,
78
+ // and an archive that no longer hashes to the id changed since the id was taken, and is refused — then completes
79
+ // it with the number of parts,
80
+ // asking for the answer at once: Dewdrop takes a large release in over minutes, longer than a request stays
81
+ // open, so an answer at once names the `phase` it is in, and this follows at the release's address, telling
82
+ // `progress` each phase it sees, until Dewdrop records the release — the answer with its `bytes` — or refuses it.
83
+ // A Dewdrop from before the answer at once records the release in the request itself. Dewdrop must confirm the
84
+ // same id.
85
+ async upload(game,bundle,signal,progress) {
86
+ let count=0;
87
+ const hash=createHash('sha256');
88
+ for(const part of parts(bundle.chunks(),this.partBytes)) {
89
+ hash.update(part);
90
+ await this.api(`/v1/games/${game}/releases/${bundle.id}/parts/${count++}`,{method:'PUT',body:part,signal});
91
+ }
92
+ if(hash.digest('hex')!==bundle.id)throw new Error('The build\'s output changed while it was being uploaded. Try again.');
93
+ const path=`/v1/games/${game}/releases/${bundle.id}`,deadline=Date.now()+this.storeMs;
94
+ let result=await this.api(path,{method:'POST',body:{parts:count},signal,prefer:'respond-async'}),phase;
95
+ while(result.bytes===undefined) {
96
+ 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.`);
97
+ await sleep(this.pollMs,signal);
98
+ result=await this.api(path,{signal});
99
+ if(result.phase!==undefined&&result.phase!==phase){phase=result.phase;progress?.(phase);}
67
100
  }
68
- const result=await this.api(`/v1/games/${game}/releases/${bundle.id}`,{method:'POST',body:{parts},signal});
69
101
  if(result.release!==bundle.id)throw new Error('Dewdrop stored a different release than was uploaded, so nothing was changed. Try again.');
70
102
  return result;
71
103
  }
package/src/project.js CHANGED
@@ -6,12 +6,14 @@ 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 {packTar,readTar} from './tar.js';
9
+ import {tarChunks,tarLength,readTar} from './tar.js';
10
10
  import {RUN} from './command.js';
11
11
 
12
- const MAX_BYTES = 1024 * 1024 * 1024;
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;
13
16
  const ignored = new Set(['node_modules','dist','target']);
14
- const hash = bytes => createHash('sha256').update(bytes).digest('hex');
15
17
  const GAME_NAME = /^[a-z][a-z0-9-]{0,47}$/;
16
18
  export const DEWDROP = 'https://alpha.dewdrop.world';
17
19
  // Dewdrop's address, or the one DEWDROP_PLATFORM names: an https:// origin, or plain http:// to this
@@ -44,35 +46,38 @@ export function readProject(root = process.cwd()) {
44
46
  return {...config,root};
45
47
  }
46
48
 
47
- // Opens a file of the project as a regular file under `root` and no symlink, hands `fn` its descriptor, and closes it.
48
- function opened(file, root, fn) {
49
+ // Opens a file of the project as a regular file under `root` and no symlink, gives out the run of buffers `fn` reads
50
+ // from its descriptor and stat, and closes it once the run is taken, or left early.
51
+ function* opened(file, root, fn) {
49
52
  const actual = realpathSync(file);
50
53
  if (!actual.startsWith(`${root}/`) || actual !== file) throw new Error(`Symlinks cannot be uploaded: ${file}`);
51
54
  const fd = openSync(file,constants.O_RDONLY|constants.O_NOFOLLOW);
52
55
  try {
53
56
  const stat=fstatSync(fd);
54
- if (!stat.isFile() || stat.size > MAX_BYTES) throw new Error(`Not a regular file under 1 GiB: ${file}`);
55
- return fn(fd,stat);
57
+ if (!stat.isFile() || stat.size > MAX_BYTES) throw new Error(`Not a regular file of at most 5 GiB: ${file}`);
58
+ yield* fn(fd,stat);
56
59
  } finally { closeSync(fd); }
57
60
  }
58
- const readRegular=(file,root)=>opened(file,root,fd=>readFileSync(fd));
59
- // Copies the file's `size` bytes into `target` at `offset`, straight from the descriptor, and answers how many it
60
- // copied: a file whose size changed since it was walked copies another number, and the archive refuses it.
61
- function readInto(file, root, size, target, offset) {
62
- return opened(file,root,(fd,stat)=>{
63
- if (stat.size!==size) return stat.size;
64
- let copied=0;
65
- while (copied<size) {
66
- const count=readSync(fd,target,offset+copied,size-copied,copied);
67
- if (count===0) break;
68
- copied+=count;
69
- }
70
- return copied;
71
- });
61
+ // The first `size` bytes of the descriptor, a chunk at a time, stopping where the file ends.
62
+ function* readFrom(fd, size) {
63
+ for (let offset=0;offset<size;) {
64
+ const chunk=Buffer.allocUnsafe(Math.min(CHUNK_BYTES,size-offset)),count=readSync(fd,chunk,0,chunk.length,offset);
65
+ if (count===0) return;
66
+ yield count<chunk.length?chunk.subarray(0,count):chunk;
67
+ offset+=count;
68
+ }
69
+ }
70
+ const changed=path=>new Error(`${path} changed while it was being uploaded. Try again.`);
71
+ // 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
72
+ // cut short under the read, has changed since the walk, and the upload is refused rather than sent with it.
73
+ function* entryBytes(path, file, root, size) {
74
+ let count=0;
75
+ 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; }
76
+ if (count!==size) throw changed(path);
72
77
  }
73
78
  // Every regular file under `start`, by its path under `root`, with its size: what is walked is not read, so a
74
- // bundle over the budget is refused on its sizes alone and the files are read once, into the archive. Names starting
75
- // with a dot are always left out; watching also leaves out the bundle folder, node_modules, dist and target, and
79
+ // bundle over the budget is refused on its sizes alone, before any file is opened. Names starting with a dot are
80
+ // always left out; watching also leaves out the bundle folder, node_modules, dist and target, and
76
81
  // passes over the symlinks an upload refuses.
77
82
  function walk(root, start, files, {watch = false, output, budget = {bytes:0}} = {}) {
78
83
  if (watch && (start === output || start.startsWith(`${output}/`))) return;
@@ -89,7 +94,7 @@ function walk(root, start, files, {watch = false, output, budget = {bytes:0}} =
89
94
  }
90
95
  } else {
91
96
  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.');
92
- if (!watch && (budget.bytes += stat.size) > MAX_BYTES) throw new Error('The build\'s output is over 1 GiB, the most Dewdrop takes.');
97
+ if (!watch && (budget.bytes += stat.size) > MAX_BYTES) throw new Error('The build\'s output is over 5 GiB, the most Dewdrop takes.');
93
98
  files.set(relative(root,start).split('\\').join('/'),{file:start,size:stat.size});
94
99
  }
95
100
  }
@@ -98,7 +103,10 @@ export function fingerprint(project) {
98
103
  const files=new Map();
99
104
  walk(project.root,project.root,files,{watch:true,output:projectPath(project.root,project.bundle)});
100
105
  const digest=createHash('sha256');
101
- for (const [path,{file}] of [...files].sort(([a],[b])=>a<b?-1:1)) { const data=readRegular(file,project.root); digest.update(`${path}\0${data.length}\0`).update(data); }
106
+ for (const [path,{file,size}] of [...files].sort(([a],[b])=>a<b?-1:1)) {
107
+ digest.update(`${path}\0${size}\0`);
108
+ for (const chunk of opened(file,project.root,fd=>readFrom(fd,size))) digest.update(chunk);
109
+ }
102
110
  return digest.digest('hex');
103
111
  }
104
112
  export function snapshot(project) {
@@ -121,11 +129,13 @@ export function snapshot(project) {
121
129
  const entries=[...files].map(([path,{file,size}])=>{
122
130
  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.`);
123
131
  bytes+=size;
124
- return {path,size,read:(target,offset)=>readInto(file,root,size,target,offset)};
132
+ return {path,size,read:()=>entryBytes(path,file,root,size)};
125
133
  });
126
- // The same files always make the same bytes, which give the upload its id.
127
- const body=packTar(entries);
128
- return {body,id:hash(body),bytes,files:files.size};
134
+ // The same files always make the same bytes, which give the upload its id: `chunks` is the archive as a run of
135
+ // buffers, read through here for the id and again by the upload that sends it, `size` bytes in all.
136
+ const chunks=()=>tarChunks(entries),digest=createHash('sha256');
137
+ for (const chunk of chunks()) digest.update(chunk);
138
+ return {id:digest.digest('hex'),size:tarLength(entries),bytes,files:files.size,chunks};
129
139
  }
130
140
  export async function build(project, signal) {
131
141
  if (!project.build) return;
@@ -162,7 +172,7 @@ export async function build(project, signal) {
162
172
  const STARTER_FILES=['package.json','src','index.html','vite.config.js'];
163
173
  // The SDK a new game depends on — the range moves with the SDK's minor, since a caret on 0.x stays within one —
164
174
  // and this CLI, at its own version.
165
- const SDK_RANGE='^0.6.0';
175
+ const SDK_RANGE='^0.7.0';
166
176
  const CLI_RANGE=`^${JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version}`;
167
177
  // The games a new one can start from: Blank, which ships with this CLI, and the starter games in the public
168
178
  // starter-templates repository, a folder each, at the commit this release pins.
package/src/tar.js CHANGED
@@ -29,23 +29,24 @@ function header(path,size) {
29
29
  return block;
30
30
  }
31
31
 
32
- // One archive of `entries` — `{path, size, read}` each, `read(target, offset)` copying the file's `size` bytes into
33
- // `target` at `offset` and answering how many it copied — in path order, with no owner, time or mode but the fixed
34
- // ones. The archive is one buffer the size of the whole, each file read straight into its place, so an upload is
35
- // held in memory once however large it is.
32
+ // One archive of `entries` — `{path, size, read}` each, `read()` giving the file's `size` bytes as a run of buffers —
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.
36
36
  const padded=size=>size+(size%BLOCK?BLOCK-size%BLOCK:0);
37
- export function packTar(entries) {
37
+ export function* tarChunks(entries) {
38
38
  const sorted=[...entries].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
39
- const out=Buffer.alloc(sorted.reduce((sum,{size})=>sum+BLOCK+padded(size),0)+2*BLOCK);
40
- let offset=0;
41
39
  for(const {path,size,read} of sorted) {
42
- header(path,size).copy(out,offset);
43
- offset+=BLOCK;
44
- if(read(out,offset)!==size)throw new Error(`${path} changed while it was being uploaded. Try again.`);
45
- offset+=padded(size);
40
+ yield header(path,size);
41
+ yield* read();
42
+ if(padded(size)>size)yield Buffer.alloc(padded(size)-size);
46
43
  }
47
- return out;
44
+ yield Buffer.alloc(2*BLOCK);
48
45
  }
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
+ // The archive as one buffer, for the small ones the tests make.
49
+ export const packTar=entries=>Buffer.concat([...tarChunks(entries)]);
49
50
 
50
51
  // The regular files of a ustar archive, such as a GitHub tarball, as `{path, data}` with the archive's one top-level
51
52
  // folder taken off each path. Folders and pax headers are passed over, but for the path a pax header gives the file
package/src/watch.js CHANGED
@@ -10,6 +10,8 @@ export function size(bytes) {
10
10
  const [value,unit]=bytes<1024**2?[bytes/1024,'KB']:bytes<1024**3?[bytes/1024**2,'MB']:[bytes/1024**3,'GB'];
11
11
  return `${value<10?value.toFixed(1):Math.round(value)} ${unit}`;
12
12
  }
13
+ // What Dewdrop is doing with an upload that takes a while, by the phase the client sees it in.
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…'};
13
15
  // Claims the game before building, so a name someone else has or an ended sign-in is known at once; then builds,
14
16
  // uploads and plays the build as the dev version.
15
17
  export async function deploy(project,client,{signal,log=console.log}={}) {
@@ -19,9 +21,9 @@ export async function deploy(project,client,{signal,log=console.log}={}) {
19
21
  await build(project,signal);
20
22
  if(fingerprint(project)!==before)return {changed:true};
21
23
  const bundle=snapshot(project);
22
- const parts=Math.max(1,Math.ceil(bundle.body.length/PART_BYTES));
24
+ const parts=Math.max(1,Math.ceil(bundle.size/PART_BYTES));
23
25
  log(`Uploading ${bundle.files} file${bundle.files===1?'':'s'} (${size(bundle.bytes)})${parts>1?` in ${parts} parts`:''}…`);
24
- await client.upload(project.game,bundle,signal);
26
+ await client.upload(project.game,bundle,signal,phase=>log(PHASES[phase]??`Dewdrop is ${phase} the upload…`));
25
27
  await client.activate(project.game,bundle.id,signal,game=>log(`Starting ${bundle.id.slice(0,12)} at ${devPlayUrl(game)}`));
26
28
  log('Ready to play.');
27
29
  return {changed:false};