dewctl 0.6.5 → 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/examples/AGENTS.md +3 -0
- package/package.json +1 -1
- package/src/client.js +119 -16
- package/src/hash.js +82 -0
- package/src/main.js +5 -1
- package/src/project.js +50 -56
- package/src/watch.js +52 -19
package/examples/AGENTS.md
CHANGED
|
@@ -83,6 +83,9 @@ The code ([limits](https://alpha.dewdrop.world/docs/limits)):
|
|
|
83
83
|
Web Audio; `<audio>` and `<video>` make no sound.
|
|
84
84
|
- `localStorage` and `indexedDB` throw. Storage is `saves.storage` and `saves.indexedDB` from `dewdrop-sdk`, open
|
|
85
85
|
once `await saves.load()` is done, and kept only by `await saves.save()` ([saves](https://alpha.dewdrop.world/docs/saves)).
|
|
86
|
+
- `sessionStorage`, `location` navigation, and `alert`, `confirm` and `prompt` throw: keep state in memory, restart in the
|
|
87
|
+
game or call `session.exit()`, and draw dialogs on the page. The console warns once about anything else that isn't
|
|
88
|
+
available; [what works](https://alpha.dewdrop.world/docs/limits) lists it.
|
|
86
89
|
- Keep `three` at 0.185.1, which Dewdrop provides ([project](https://alpha.dewdrop.world/docs/project)).
|
|
87
90
|
|
|
88
91
|
## 4. The working loop
|
package/package.json
CHANGED
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,12 @@ 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;
|
|
25
|
+
// How long a poll asks the platform to hold it for news (`Prefer: wait`), under what the edge holds a request open.
|
|
26
|
+
const WAIT_S=25;
|
|
19
27
|
// `chunks` cut into runs of exactly `bytes`, but the last, which is what remains and never empty: an archive given
|
|
20
28
|
// as a run of buffers of any lengths is sent in parts of one size, holding about one part at a time.
|
|
21
29
|
export function* parts(chunks,bytes=PART_BYTES) {
|
|
@@ -31,7 +39,11 @@ export function* parts(chunks,bytes=PART_BYTES) {
|
|
|
31
39
|
}
|
|
32
40
|
export class Client {
|
|
33
41
|
// `partBytes` is for the tests, which cut at a few bytes; an upload is sent in parts of PART_BYTES.
|
|
34
|
-
|
|
42
|
+
// `pollMs` is the least a wait on the platform takes a round: a platform that holds the request answers when there
|
|
43
|
+
// is news, within WAIT_S; one that answers at once instead is asked again after that long.
|
|
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();}
|
|
35
47
|
// A request signed in with `token`. When Dewdrop can't be reached the failure is marked transient, which a watcher
|
|
36
48
|
// or a sign-in waits out; a refused token asks for a new sign-in, whatever Dewdrop's words.
|
|
37
49
|
async request(path,{method='GET',body,token,signal,type,prefer}={}) {
|
|
@@ -48,8 +60,8 @@ export class Client {
|
|
|
48
60
|
const contentType=response.headers.get('content-type')??'';
|
|
49
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.`);
|
|
50
62
|
const data=await response.json();
|
|
51
|
-
if(response.status===401&&token)throw new ApiError(401,`Your sign-in has ended: it expired or was signed out. Run ${RUN} login
|
|
52
|
-
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);
|
|
53
65
|
return data;
|
|
54
66
|
}
|
|
55
67
|
// The session this computer holds, or why there is none to use.
|
|
@@ -73,15 +85,76 @@ export class Client {
|
|
|
73
85
|
throw error;
|
|
74
86
|
}
|
|
75
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
|
+
}
|
|
76
154
|
// Uploads a build of a claimed game under its id — its archive read through again as `bundle.chunks()` gives it,
|
|
77
155
|
// cut into parts of PART_BYTES, so a bundle of gigabytes is never held whole; what is sent is hashed as it goes,
|
|
78
156
|
// 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.
|
|
157
|
+
// it with the number of parts. Dewdrop must confirm the same id.
|
|
85
158
|
async upload(game,bundle,signal,progress) {
|
|
86
159
|
let count=0;
|
|
87
160
|
const hash=createHash('sha256');
|
|
@@ -90,15 +163,25 @@ export class Client {
|
|
|
90
163
|
await this.api(`/v1/games/${game}/releases/${bundle.id}/parts/${count++}`,{method:'PUT',body:part,signal});
|
|
91
164
|
}
|
|
92
165
|
if(hash.digest('hex')!==bundle.id)throw new Error('The build\'s output changed while it was being uploaded. Try again.');
|
|
93
|
-
const
|
|
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;
|
|
94
176
|
let result=await this.api(path,{method:'POST',body:{parts:count},signal,prefer:'respond-async'}),phase;
|
|
95
177
|
while(result.bytes===undefined) {
|
|
96
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.`);
|
|
97
|
-
await sleep(this.pollMs,signal);
|
|
98
|
-
result=await this.api(path,{signal});
|
|
99
179
|
if(result.phase!==undefined&&result.phase!==phase){phase=result.phase;progress?.(phase);}
|
|
180
|
+
// Held by the platform until the completion ends, or answered at once by one that does not hold a poll.
|
|
181
|
+
const asked=Date.now();
|
|
182
|
+
result=await this.api(path,{signal,prefer:`wait=${WAIT_S}`});
|
|
183
|
+
if(result.bytes===undefined)await this.#rest(asked,signal);
|
|
100
184
|
}
|
|
101
|
-
if(result.release!==bundle.id)throw new Error('Dewdrop stored a different release than was uploaded, so nothing was changed. Try again.');
|
|
102
185
|
return result;
|
|
103
186
|
}
|
|
104
187
|
activate(game,release,signal,started){return this.point(game,'dev',release,signal,started);}
|
|
@@ -117,10 +200,30 @@ export class Client {
|
|
|
117
200
|
if(current.error)throw new Error(current.error);
|
|
118
201
|
if(current.ready)return state;
|
|
119
202
|
if(Date.now()>=deadline)throw new Error(`${doing} is taking longer than three minutes. Run ${RUN} status to follow it.`);
|
|
120
|
-
|
|
121
|
-
state=await this.
|
|
203
|
+
const asked=Date.now();
|
|
204
|
+
state=await this.held(game,version,signal);
|
|
205
|
+
// An answer with news is acted on at once; one without is asked again after the round.
|
|
206
|
+
const seen=state[version];
|
|
207
|
+
if(seen.release===release&&!seen.ready&&!seen.error)await this.#rest(asked,signal);
|
|
122
208
|
}
|
|
123
209
|
}
|
|
210
|
+
// The game as the platform answers it once `version` is ready or refused, holding the request for it; a platform from
|
|
211
|
+
// before that route answers the game as it stands, and is asked that way from then on.
|
|
212
|
+
async held(game,version,signal) {
|
|
213
|
+
if(!this.holds)return this.game(game,signal);
|
|
214
|
+
try{return await this.api(`/v1/games/${game}/${version}`,{signal,prefer:`wait=${WAIT_S}`});}
|
|
215
|
+
catch(error){
|
|
216
|
+
if(error.status!==405&&error.status!==404)throw error;
|
|
217
|
+
this.holds=false;
|
|
218
|
+
return this.game(game,signal);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
// The rest of a round that came back at once: a platform holding the request has answered with news, one that
|
|
222
|
+
// answered at once is asked again `pollMs` after it was asked.
|
|
223
|
+
async #rest(asked,signal) {
|
|
224
|
+
const left=this.pollMs-(Date.now()-asked);
|
|
225
|
+
if(left>0)await sleep(left,signal);
|
|
226
|
+
}
|
|
124
227
|
// Sets the game's thumbnail to the image, sent as itself under its type.
|
|
125
228
|
thumbnail(game,bytes,type,signal){return this.api(`/v1/games/${game}/thumbnail`,{method:'PUT',body:bytes,type,signal});}
|
|
126
229
|
async member(game,email,on,signal) {
|
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
|
|
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
|
|
2
|
-
import {readFileSync, writeFileSync, existsSync, lstatSync, readdirSync,
|
|
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';
|
|
@@ -31,6 +28,14 @@ export function projectPath(root, path) {
|
|
|
31
28
|
if (!file.startsWith(`${resolve(root)}/`)) throw new Error(`Path leaves the project: ${path}`);
|
|
32
29
|
return file;
|
|
33
30
|
}
|
|
31
|
+
// Whether a change at `path`, relative to the project's root, is one `dev --watch` follows: the walk's rule by path —
|
|
32
|
+
// not under the bundle folder, node_modules, dist or target, and no name starting with a dot.
|
|
33
|
+
export function followed(project, path) {
|
|
34
|
+
const names = path.split(/[\\/]/);
|
|
35
|
+
if (names.some(name => name.startsWith('.') || ignored.has(name))) return false;
|
|
36
|
+
const output = relative(project.root, projectPath(project.root, project.bundle)).split('\\').join('/'), joined = names.join('/');
|
|
37
|
+
return joined !== output && !joined.startsWith(`${output}/`);
|
|
38
|
+
}
|
|
34
39
|
export function readProject(root = process.cwd()) {
|
|
35
40
|
root = realpathSync(root);
|
|
36
41
|
const file = join(root,'dewdrop.json');
|
|
@@ -46,43 +51,14 @@ export function readProject(root = process.cwd()) {
|
|
|
46
51
|
return {...config,root};
|
|
47
52
|
}
|
|
48
53
|
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
if (!actual.startsWith(`${root}/`) || actual !== file) throw new Error(`Symlinks cannot be uploaded: ${file}`);
|
|
54
|
-
const fd = openSync(file,constants.O_RDONLY|constants.O_NOFOLLOW);
|
|
55
|
-
try {
|
|
56
|
-
const stat=fstatSync(fd);
|
|
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);
|
|
59
|
-
} finally { closeSync(fd); }
|
|
60
|
-
}
|
|
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);
|
|
77
|
-
}
|
|
78
|
-
// Every regular file under `start`, by its path under `root`, with its size: what is walked is not read, so a
|
|
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
|
|
81
|
-
// 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.
|
|
82
58
|
function walk(root, start, files, {watch = false, output, budget = {bytes:0}} = {}) {
|
|
83
59
|
if (watch && (start === output || start.startsWith(`${output}/`))) return;
|
|
84
60
|
if (!existsSync(start)) return;
|
|
85
|
-
const stat=lstatSync(start);
|
|
61
|
+
const stat=lstatSync(start,{bigint:true});
|
|
86
62
|
if (stat.isSymbolicLink()) {
|
|
87
63
|
if (watch) return;
|
|
88
64
|
throw new Error(`Symlinks cannot be uploaded: ${start}`);
|
|
@@ -94,22 +70,28 @@ function walk(root, start, files, {watch = false, output, budget = {bytes:0}} =
|
|
|
94
70
|
}
|
|
95
71
|
} else {
|
|
96
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.');
|
|
97
|
-
|
|
98
|
-
|
|
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}`});
|
|
99
76
|
}
|
|
100
77
|
}
|
|
101
|
-
// The project's files as one digest of their paths and
|
|
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.
|
|
102
80
|
export function fingerprint(project) {
|
|
103
81
|
const files=new Map();
|
|
104
82
|
walk(project.root,project.root,files,{watch:true,output:projectPath(project.root,project.bundle)});
|
|
105
83
|
const digest=createHash('sha256');
|
|
106
|
-
for (const [path,{
|
|
107
|
-
digest.update(`${path}\0${size}\0`);
|
|
108
|
-
for (const chunk of opened(file,project.root,fd=>readFrom(fd,size))) digest.update(chunk);
|
|
109
|
-
}
|
|
84
|
+
for (const [path,{stamp}] of [...files].sort(([a],[b])=>a<b?-1:1)) digest.update(`${path}\0${stamp}\0`);
|
|
110
85
|
return digest.digest('hex');
|
|
111
86
|
}
|
|
112
|
-
|
|
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) {
|
|
113
95
|
const directory=projectPath(project.root,project.bundle);
|
|
114
96
|
if (!existsSync(directory)) throw new Error(project.build
|
|
115
97
|
? `The build wrote no ${project.bundle} folder. Set "bundle" in dewdrop.json to the folder your build (vite build) writes.`
|
|
@@ -126,16 +108,28 @@ export function snapshot(project) {
|
|
|
126
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.`);
|
|
127
109
|
}
|
|
128
110
|
let bytes=0;
|
|
129
|
-
|
|
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}])=>{
|
|
130
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.`);
|
|
131
114
|
bytes+=size;
|
|
132
|
-
return {path,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)};
|
|
133
123
|
});
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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
|
+
}};
|
|
139
133
|
}
|
|
140
134
|
export async function build(project, signal) {
|
|
141
135
|
if (!project.build) return;
|
|
@@ -172,7 +166,7 @@ export async function build(project, signal) {
|
|
|
172
166
|
const STARTER_FILES=['package.json','src','index.html','vite.config.js'];
|
|
173
167
|
// The SDK a new game depends on — the range moves with the SDK's minor, since a caret on 0.x stays within one —
|
|
174
168
|
// and this CLI, at its own version.
|
|
175
|
-
const SDK_RANGE='^0.
|
|
169
|
+
const SDK_RANGE='^0.8.0';
|
|
176
170
|
const CLI_RANGE=`^${JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version}`;
|
|
177
171
|
// The games a new one can start from: Blank, which ships with this CLI, and the starter games in the public
|
|
178
172
|
// starter-templates repository, a folder each, at the commit this release pins.
|
package/src/watch.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Poll the project's files across edits, deletions and atomic saves; only one build and activation runs at a time.
|
|
2
|
-
import {
|
|
3
|
-
import {fingerprint,build,snapshot} from './project.js';
|
|
2
|
+
import {watch as watchDirectory} from 'node:fs';
|
|
3
|
+
import {fingerprint,build,snapshot,followed} from './project.js';
|
|
4
4
|
import {devPlayUrl} from './play.js';
|
|
5
5
|
import {RUN} from './command.js';
|
|
6
6
|
|
|
@@ -12,37 +12,69 @@ export function size(bytes) {
|
|
|
12
12
|
}
|
|
13
13
|
// What Dewdrop is doing with an upload that takes a while, by the phase the client sees it in.
|
|
14
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…'};
|
|
15
|
-
|
|
16
|
-
//
|
|
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.
|
|
17
27
|
export async function deploy(project,client,{signal,log=console.log}={}) {
|
|
18
|
-
await client.claim(project.game,signal);
|
|
19
28
|
const before=fingerprint(project);
|
|
20
29
|
log('Building…');
|
|
21
30
|
await build(project,signal);
|
|
22
31
|
if(fingerprint(project)!==before)return {changed:true};
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
log(`Uploading ${bundle.files} file${bundle.files===1?'':'s'} (${size(bundle.bytes)})${parts>1?` in ${parts} parts`:''}…`);
|
|
26
|
-
await client.upload(project.game,bundle,signal,phase=>log(PHASES[phase]??`Dewdrop is ${phase} the upload…`));
|
|
27
|
-
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)}`));
|
|
28
34
|
log('Ready to play.');
|
|
29
35
|
return {changed:false};
|
|
30
36
|
}
|
|
31
37
|
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
38
|
+
// Follows the tree of the project `current` gives by the system's file events, calling `changed` on each event in a
|
|
39
|
+
// file dev follows (`followed`, judged by the project as dewdrop.json says it at the event, so a bundle folder renamed
|
|
40
|
+
// is left out from the next build on), and `lost` should the watch fail later; null where the tree cannot be watched,
|
|
41
|
+
// when dev looks the files over instead.
|
|
42
|
+
export function watchTree(current,changed,lost=()=>{}) {
|
|
43
|
+
try {
|
|
44
|
+
const watcher=watchDirectory(current().root,{recursive:true,persistent:false},(event,filename)=>{
|
|
45
|
+
if(filename===null||followed(current(),filename.toString()))changed();
|
|
46
|
+
});
|
|
47
|
+
watcher.on('error',()=>{watcher.close();lost();});
|
|
48
|
+
return watcher;
|
|
49
|
+
}catch{return null;}
|
|
50
|
+
}
|
|
51
|
+
// Rebuilds on every save: told of each by the system's file events, a save settled EVENT_DEBOUNCE_MS after its last
|
|
52
|
+
// event — an editor writes a file in several steps, and a save-all many files — or, where the tree cannot be watched,
|
|
53
|
+
// by looking the files over every `pollMs`, a save settled `debounceMs` after the last change found. `reread` gives
|
|
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
|
|
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.
|
|
57
|
+
export const EVENT_DEBOUNCE_MS=100;
|
|
58
|
+
export async function watch(project,client,{signal,log=console.log,deployGame=deploy,readFingerprint=fingerprint,reread=()=>project,watchFiles=watchTree,pollMs=200,debounceMs=500}={}) {
|
|
59
|
+
let changedAt=Date.now()-debounceMs,dirty=true;
|
|
60
|
+
let running=null,claimed=null;
|
|
61
|
+
const noted=()=>{changedAt=Date.now();dirty=true;};
|
|
62
|
+
let watching=watchFiles?.(()=>project,noted,()=>{watching=null;observed=readFingerprint(project);});
|
|
63
|
+
let observed=watching?null:readFingerprint(project);
|
|
37
64
|
log(`Watching ${project.game} for changes. Ctrl-C stops.`);
|
|
38
65
|
while(!signal?.aborted) {
|
|
39
66
|
try {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
67
|
+
if(!watching) {
|
|
68
|
+
const next=readFingerprint(project);
|
|
69
|
+
if(next!==observed){observed=next;noted();}
|
|
70
|
+
}
|
|
71
|
+
if(dirty&&!running&&Date.now()-changedAt>=(watching?EVENT_DEBOUNCE_MS:debounceMs)) {
|
|
43
72
|
dirty=false;
|
|
44
73
|
project=reread();
|
|
45
|
-
running=
|
|
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=>{
|
|
46
78
|
if(result.changed)dirty=true;
|
|
47
79
|
}).catch(error=>{
|
|
48
80
|
if(signal?.aborted)return;
|
|
@@ -56,5 +88,6 @@ export async function watch(project,client,{signal,log=console.log,deployGame=de
|
|
|
56
88
|
await new Promise(resolve=>setTimeout(resolve,pollMs));
|
|
57
89
|
}
|
|
58
90
|
await running;
|
|
91
|
+
watching?.close();
|
|
59
92
|
log('Stopped watching. The dev version keeps running.');
|
|
60
93
|
}
|