@kaynooo/cli-wait 0.14.0 → 0.14.1

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.
Files changed (2) hide show
  1. package/dist/slot-cli.js +1 -1
  2. package/package.json +1 -1
package/dist/slot-cli.js CHANGED
@@ -8,4 +8,4 @@ A slotted command running slot again does not wait for a second slot, preventing
8
8
 
9
9
  --json prints {slots, busy, entries}, each entry as {state, resource, pid, session, command, cwd, since}.`,SLOTS={type:"string",short:"n",description:"how many commands may hold a slot at once (config.jsonc#slot.slots, else half CPU count)"},RUN_OPTIONS={lock:{type:"string",short:"l",multiple:!0,description:"a named lock to hold as well, for what must not run twice at once (shop-test-db)"},"no-slot":{type:"boolean",description:"take the --lock alone, without a slot"},weight:{type:"string",short:"w",description:"how many slots this command reserves at once (1)"},exclusive:{type:"boolean",short:"x",description:"reserve all slots at once (same as --weight <slots>)"},slots:SLOTS,timeout:{type:"string",short:"t",description:"how long to wait before giving up (30s, 5m, 1h, a bare number in seconds), forever by default"}},LS_OPTIONS={slots:SLOTS,json:jsonOption()},POLL=250,COMMAND_WIDTH=60,LOCK_NAME=/^\w[\w.-]*$/,HOLDING="SLOT_HOLDING";function defaultSlots(){return configuredNumber("slot","slots",Math.max(1,Math.floor(availableParallelism()/2)))}async function stateDir(){let dir=process2.env.SLOT_DIR??await privateLogDirectory("slot");for(let sub of["slots","locks","waiters"])mkdirSync(join(dir,sub),{recursive:!0,mode:448});return dir}function readHolder(path){try{let holder=JSON.parse(readFileSync(path,"utf8"));return typeof holder.pid==="number"&&typeof holder.command==="string"?{pid:holder.pid,command:holder.command,cwd:holder.cwd??"",since:holder.since??0,...holder.session===void 0?{}:{session:holder.session},...holder.resource===void 0?{}:{resource:holder.resource}}:void 0}catch{return}}function pathOf(dir,kind,name){return join(dir,kind==="slot"?"slots":"locks",name)}function candidates(dir,{kind,name,count}){if(kind==="lock")return[{path:pathOf(dir,"lock",name),resource:`lock ${name}`}];return Array.from({length:count},(_,index)=>({path:pathOf(dir,"slot",String(index)),resource:`slot ${index+1}`}))}function attempt(dir,wanted){let taken=[];for(let{path,resource}of candidates(dir,wanted)){let held=tryLock(path);if(held!==void 0){if(taken.push({held,resource}),taken.length===wanted.weight)return taken}}for(let{held}of taken)held.release();return}function who(holder){return`${holder.session??`pid ${holder.pid}`} running ${truncate(holder.command,COMMAND_WIDTH)} for ${formatDuration(Date.now()-holder.since)}`}function waitingLine(dir,wanted){let holders=candidates(dir,wanted).map(({path})=>readHolder(path)).filter((holder)=>holder!==void 0).sort((a,b)=>a.since-b.since),oldest=holders[0],by=oldest===void 0?"another process":who(oldest);if(wanted.kind==="lock")return`slot: waiting for lock ${wanted.name}, held by ${by}`;return`slot: waiting for ${wanted.weight>1?`${wanted.weight} slots`:"a slot"} (${holders.length} of ${wanted.count} busy), the oldest held by ${by}`}async function holderOf(command){let session=await currentSession(await liveSessions());return{pid:process2.pid,command:command.join(" "),cwd:process2.cwd(),since:Date.now(),...session===void 0?{}:{session:session.name}}}var waiterCount=0;function resourceLabel(wanted){return wanted.kind==="lock"?`lock ${wanted.name}`:"slot"}function hasOlderWaiter(dir,myName,resources){let folder=join(dir,"waiters");if(!existsSync(folder))return!1;let wantedLabels=new Set(resources.map(resourceLabel));for(let name of readdirSync(folder).sort()){if(myName!==void 0&&name>=myName)break;let path=join(folder,name),probe=tryLock(path);if(probe!==void 0){rmSync(path,{force:!0}),probe.release();continue}let holder=readHolder(path);if(holder===void 0||holder.resource===void 0||wantedLabels.has(holder.resource))return!0}return!1}async function acquire(dir,resources,holder,deadline,timeoutMs){let waiter,region,currentBusy=resources[0],started=Date.now(),{dim}=paint(process2.stderr);try{for(;;){let blockedByQueue=hasOlderWaiter(dir,waiter?.name,resources),taken=[],busy=blockedByQueue?resources[0]:void 0;if(!blockedByQueue)for(let wanted of resources){let got=attempt(dir,wanted);if(got===void 0){busy=wanted;break}taken.push(...got)}if(busy===void 0){for(let{held}of taken)writeHeld(held,JSON.stringify(holder));return taken}for(let{held}of taken)held.release();currentBusy=busy;let resource=resourceLabel(busy);if(waiter===void 0){let name=`${String(Date.now()).padStart(15,"0")}-${String(process2.pid).padStart(8,"0")}-${waiterCount++}`,path=join(dir,"waiters",name),held=tryLock(path);if(held!==void 0)writeHeld(held,JSON.stringify({...holder,resource})),waiter={held,path,name,resource};if(process2.stderr.isTTY)region=liveRegion((spinner)=>[`${spinner} ${waitingLine(dir,currentBusy)} ${dim(formatElapsed(Date.now()-started))}`]);else writeErr(waitingLine(dir,busy))}else if(waiter.resource!==resource)writeHeld(waiter.held,JSON.stringify({...holder,resource})),waiter.resource=resource;if(Date.now()>=deadline)fail(`gave up after ${formatDuration(timeoutMs)} waiting for ${busy.kind==="lock"?`lock ${busy.name}`:"a slot"}`);await Bun.sleep(POLL)}}finally{if(region?.stop(),waiter!==void 0)rmSync(waiter.path,{force:!0}),waiter.held.release()}}function withSeparator(args){let takesValue=(word)=>Object.entries(RUN_OPTIONS).some(([name,option])=>option.type==="string"&&(word===`--${name}`||("short"in option)&&word===`-${option.short}`));for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")return args;if(!word.startsWith("-"))return[...args.slice(0,at),"--",...args.slice(at)];if(takesValue(word))at++}return args}async function runSlotted(given){let args=withSeparator(given),parsed=parse(args,RUN_USAGE,RUN_OPTIONS,{rest:!0,exits:RUN_EXITS,replaces:"flock wrappers, hand-written heavy.sh queues and parallel runs fighting over one test database",examples:[["slot -- bunx vue-tsc","wait for a free slot, then type-check"],["slot --lock shop-test-db -- vendor/bin/phpunit","one phpunit at a time on the shared test database"],["slot -w 2 -- bun test","reserve 2 slots for a heavy test run"],"slot ls"]}),{values,rest}=parsed;if(rest===void 0||rest.length===0)fail(`give the command after --
10
10
 
11
- ${RUN_USAGE}`);let locks=[...new Set(values.lock??[])].sort();for(let name of locks)if(!LOCK_NAME.test(name))fail(`--lock ${name} is no lock name: letters, digits, dots, dashes and underscores`);if(values["no-slot"]===!0&&locks.length===0)fail("--no-slot takes the --lock alone, and none is given");if(values["no-slot"]===!0&&(values.weight!==void 0||values.exclusive===!0))fail("--weight and --exclusive cannot be used with --no-slot");if(values.weight!==void 0&&values.exclusive===!0)fail("give either --weight or --exclusive, not both");let count=wholeNumber(values.slots,"slots",defaultSlots()),weight=values.exclusive===!0?count:wholeNumber(values.weight,"weight",1,1);if(weight>count)fail(`--weight ${weight} exceeds total slots (${count})`);let timeoutMs=duration(values.timeout,"timeout",Number.POSITIVE_INFINITY),deadline=Date.now()+timeoutMs,holding=new Set((process2.env[HOLDING]??"").split(",").filter((token)=>token!=="")),wanted=[...locks.filter((name)=>!holding.has(`lock:${name}`)).map((name)=>({kind:"lock",name,count,weight:1})),...values["no-slot"]===!0||holding.has("slot")?[]:[{kind:"slot",name:"",count,weight}]],signals=holdSignals(()=>{return}),taken=[];try{if(wanted.length>0){let dir=await stateDir(),holder=await holderOf(rest);taken.push(...await acquire(dir,wanted,holder,deadline,timeoutMs))}let tokens=new Set([...holding,...locks.map((name)=>`lock:${name}`),...wanted.some((resource)=>resource.kind==="slot")?["slot"]:[]]),child;try{child=Bun.spawn(rest,{stdio:["inherit","inherit","inherit"],env:{...process2.env,[HOLDING]:[...tokens].join(",")}})}catch(error){fail(`cannot run ${rest[0]}: ${error instanceof Error?error.message:String(error)}`,127)}return signals.forward(child),await child.exited,exitCodeOf(child.exitCode,child.signalCode)}finally{signals.release();for(let{held}of taken)held.release()}}function scan(dir,state,kind){let folder=join(dir,kind),entries=[];for(let name of existsSync(folder)?readdirSync(folder):[]){let path=join(folder,name),probe=tryLock(path);if(probe!==void 0){if(kind==="waiters")rmSync(path,{force:!0});probe.release();continue}let holder=readHolder(path),resource=kind==="waiters"?holder?.resource??"slot":`${kind==="slots"?"slot":"lock"} ${kind==="slots"?Number(name)+1:name}`;entries.push({state,resource,pid:holder?.pid??0,command:holder?.command??"?",cwd:holder?.cwd??"",since:holder?.since??0,...holder?.session===void 0?{}:{session:holder.session}})}return entries}async function listSlots(args){let{values}=parse(args,LS_USAGE,LS_OPTIONS,{exits:[[0,"it listed them"],[2,"a usage error"]],examples:["slot ls","slot ls --json"]}),count=wholeNumber(values.slots,"slots",defaultSlots()),dir=await stateDir(),holding=[...scan(dir,"holding","slots"),...scan(dir,"holding","locks")].sort((a,b)=>a.since-b.since),waiting=scan(dir,"waiting","waiters").sort((a,b)=>a.since-b.since),entries=[...holding,...waiting],busy=holding.filter((entry)=>entry.resource.startsWith("slot ")).length;if(values.json===!0)return printJson({slots:count,busy,entries}),0;if(console.log(paint(process2.stdout).bold(`slots: ${busy} of ${count} busy`)),entries.length>0)console.log(table(entries.map((entry)=>[badge(entry.state,process2.stdout),entry.resource,entry.session??`pid ${entry.pid}`,truncate(entry.command,COMMAND_WIDTH),entry.since===0?"?":formatAge(entry.since)])));return 0}process3.exitCode=await runMain({name:"slot",run:async(args)=>args[0]==="ls"?listSlots(args.slice(1)):runSlotted(args)});
11
+ ${RUN_USAGE}`);let locks=[...new Set(values.lock??[])].sort();for(let name of locks)if(!LOCK_NAME.test(name))fail(`--lock ${name} is no lock name: letters, digits, dots, dashes and underscores`);if(values["no-slot"]===!0&&locks.length===0)fail("--no-slot takes the --lock alone, and none is given");if(values["no-slot"]===!0&&(values.weight!==void 0||values.exclusive===!0))fail("--weight and --exclusive cannot be used with --no-slot");if(values.weight!==void 0&&values.exclusive===!0)fail("give either --weight or --exclusive, not both");let count=wholeNumber(values.slots,"slots",defaultSlots()),weight=values.exclusive===!0?count:wholeNumber(values.weight,"weight",1,1);if(weight>count)fail(`--weight ${weight} exceeds total slots (${count})`);let timeoutMs=duration(values.timeout,"timeout",Number.POSITIVE_INFINITY),deadline=Date.now()+timeoutMs,holding=new Set((process2.env[HOLDING]??"").split(",").filter((token)=>token!=="")),wanted=[...locks.filter((name)=>!holding.has(`lock:${name}`)).map((name)=>({kind:"lock",name,count,weight:1})),...values["no-slot"]===!0||holding.has("slot")?[]:[{kind:"slot",name:"",count,weight}]],signals=holdSignals(()=>{return}),taken=[];try{if(wanted.length>0){let dir=await stateDir(),holder=await holderOf(rest);taken.push(...await acquire(dir,wanted,holder,deadline,timeoutMs))}let tokens=new Set([...holding,...locks.map((name)=>`lock:${name}`),...wanted.some((resource)=>resource.kind==="slot")?["slot"]:[]]),child;try{child=Bun.spawn(rest,{stdio:["inherit","inherit","inherit"],env:{...process2.env,[HOLDING]:[...tokens].join(",")}})}catch(error){fail(`cannot run ${rest[0]}: ${error instanceof Error?error.message:String(error)}`,127)}return signals.forward(child),await child.exited,exitCodeOf(child.exitCode,child.signalCode)}finally{signals.release();for(let{held}of taken)held.release()}}function scan(dir,state,kind){let folder=join(dir,kind),entries=[];for(let name of existsSync(folder)?readdirSync(folder):[]){let path=join(folder,name),probe=tryLock(path);if(probe!==void 0){if(kind==="waiters")rmSync(path,{force:!0});probe.release();continue}let holder=readHolder(path),resource=kind==="waiters"?holder?.resource??"slot":`${kind==="slots"?"slot":"lock"} ${kind==="slots"?Number(name)+1:name}`;entries.push({state,resource,pid:holder?.pid??0,command:holder?.command??"?",cwd:holder?.cwd??"",since:holder?.since??0,...holder?.session===void 0?{}:{session:holder.session}})}return entries}async function listSlots(args){let{values}=parse(args,LS_USAGE,LS_OPTIONS,{exits:[[0,"it listed them"],[2,"a usage error"]],examples:["slot ls","slot ls --json"]}),count=wholeNumber(values.slots,"slots",defaultSlots()),dir=await stateDir(),holding=[...scan(dir,"holding","slots"),...scan(dir,"holding","locks")].sort((a,b)=>a.since-b.since),waiting=scan(dir,"waiting","waiters").sort((a,b)=>a.since-b.since),entries=[...holding,...waiting],busy=holding.filter((entry)=>entry.resource.startsWith("slot ")).length;if(values.json===!0)return printJson({slots:count,busy,entries}),0;if(console.log(paint(process2.stdout).bold(`slots: ${busy} of ${count} busy`)),entries.length>0)console.log(table(entries.map((entry)=>[badge(entry.state,process2.stdout),entry.resource,entry.session??`pid ${entry.pid}`,truncate(entry.command,COMMAND_WIDTH),entry.since===0?"?":formatAge(entry.since)])));return 0}process3.exitCode=await runMain({name:"slot",run:async(args)=>args[0]==="ls"||args[0]==="list"?listSlots(args.slice(1)):runSlotted(args)});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-wait",
3
3
  "type": "module",
4
- "version": "0.14.0",
4
+ "version": "0.14.1",
5
5
  "description": "waitfor and slot: waits for a log line, a listening port or a URL answering, and queues heavy commands behind machine-wide slots and named locks, for Claude Code, instead of sleep and polling loops.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",