fnlb 1.1.10 → 1.1.12

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/dist/index.d.ts CHANGED
@@ -14,6 +14,7 @@ export interface LogsMessage {
14
14
  }
15
15
  export interface FNLBConfig {
16
16
  clusterName?: string;
17
+ fnlbPath?: string;
17
18
  onLogMessage?: (message: LogsMessage) => any;
18
19
  onSubProcessLogMessage?: (message: LogsMessage) => any;
19
20
  disableLogs?: boolean;
@@ -40,6 +41,7 @@ declare class FNLB {
40
41
  private readonly config?;
41
42
  private readonly activeProcesses;
42
43
  private readonly packageName;
44
+ private readonly fnlbDir;
43
45
  private isLoaded;
44
46
  private shouldRestart;
45
47
  private runId;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{fork as m}from"node:child_process";import{createHash as u}from"node:crypto";import{mkdir as w,readFile as S,writeFile as L}from"node:fs/promises";import{resolve as g}from"node:path";class l{static wait(t){return new Promise((e)=>setTimeout(e,t))}}class f{config;activeProcesses=new Map;packageName=`${process.versions.bun?"zenith-bun":"zenith"}`;isLoaded=!1;shouldRestart=!0;runId=0;constructor(t){this.config=t}async start(t){await this.stop(),this.shouldRestart=!0,this.runId++;let e=this.runId;if(!t?.apiToken)throw new Error("[FNLB ShardingManager] Please provide a FNLB API token.");await this.update();let i=t.numberOfShards??1,h=(~~(Math.random()*1e4)).toString(36)+"fnlb"+(~~(Date.now()/1000)).toString(36);for(let r=0;r<i;r++){let a=`${h}-${r.toString().padStart(2,"0")}`,n=await this.startShard(t,a,e);this.activeProcesses.set(a,n)}}async stop(){if(this.shouldRestart=!1,this.runId++,this.activeProcesses.size===0)return;this.log("Stopping all active shards...");for(let[t,e]of this.activeProcesses)this.log(`Stopping shard with ID: ${t}`),e.kill();this.activeProcesses.clear(),this.log("All shards stopped.")}async startShard(t,e,i){if(await this.update(),!t?.apiToken||t.apiToken.length<10)throw new Error("[FNLB ShardingManager] Please provide a valid FNLB API token.");this.log("Starting shard with ID:",e);let h=m(`./.fnlb/${this.packageName}.mjs`,[],{env:{...process.env,FORCE_COLOR:"1",SHARD_ID:e,API_TOKEN:t.apiToken,CATEGORIES:t.categories?.join(","),BOTS_PER_SHARD:(t.botsPerShard??1).toString(),HIDE_USERNAMES:t.hideUsernames?"true":"false",HIDE_EMAILS:t.hideEmails?"true":"false",LOG_LEVEL:t.logLevel,CLUSTER_ID:this.config?.clusterName?.trim().replace(/ +(?= )/g,"").toLowerCase().replaceAll(" ","-")??"unknown",CLUSTER_NAME:this.config?.clusterName?.trim()},stdio:["inherit","pipe","pipe","ipc"]});if(!this.config?.disableSubProcessLogs)h.stdout?.on("data",(r)=>{let a=r.toString("utf8");process.stdout.write(a),this.config?.onSubProcessLogMessage?.({timestamp:Date.now(),content:a,format:0})});if(!this.config?.disableSubProcessErrorLogs)h.stderr?.on("data",(r)=>{let a=r.toString("utf8");process.stderr.write(a),this.config?.onSubProcessLogMessage?.({timestamp:Date.now(),content:a,format:4})});return h.on("close",async(r)=>{if(this.activeProcesses.delete(e),this.shouldRestart&&i===this.runId){if(r===0)this.warn("Shard exited with code:",r);else this.error("Shard exited with code:",r?.toString()??"none");this.log("Trying to restart shard..."),await l.wait(1e4);let a=await this.startShard(t,e,i);this.activeProcesses.set(e,a)}else this.log(`Shard ${e} stopped.`)}),h}async update(){if(this.isLoaded)return;let t=g(".fnlb"),e=g(t,`${this.packageName}.mjs`),i=await S(e,"utf-8").catch(()=>null),h=this.config?.maxDownloadRetries||1/0,r=this.config?.maxBackoffMs||60000;this.log(i?"Checking for updates...":"Downloading FNLB...");let a=`https://dist.fnlb.net/packages/${this.packageName}/release`,n,c=0,d=1000;while(c<h)try{let s=await fetch(a);if(!s.ok)throw new Error(`Status code: ${s.status}`);n=await s.json();break}catch(s){let o=Math.min(d*2,r);if(c++,this.error("Update error:",s),this.warn(`Check for updates attempt ${c} failed: ${s.message}. Retrying in ${o>=60000?`${~~(o/60000)}m`:`${~~(o/1000)}s`}...`),c>=h)break;await new Promise((p)=>setTimeout(p,d)),d=o}if(!n){if(i){this.warn("Failed to check for updates. Using existing local version."),this.isLoaded=!0,this.success("Loaded existing FNLB version");return}throw new Error("[FNLB ShardingManager] Failed to check for updates and no local file found.")}if(i){if(u("sha256").update(i).digest("hex")===n.hash){this.success(`FNLB v${n.version} is up to date`),this.isLoaded=!0,this.success(`Finished loading FNLB v${n.version}`);return}this.log(`Downloading update for FNLB v${n.version}`)}c=0,d=1000;while(c<h)try{let s=await fetch(n.url);if(!s.ok)throw new Error(`Download failed with status ${s.status}`);let o=await s.text();if(u("sha256").update(o).digest("hex")!==n.hash)throw new Error("Downloaded file hash mismatch...");await w(t,{recursive:!0}).catch(()=>{throw new Error(`Failed to create .fnlb the directory on ${t}`)}),await L(e,o),this.isLoaded=!0,this.success(`Finished loading FNLB v${n.version}`);return}catch(s){let o=Math.min(d*2,r);c++,this.error("Download error:",s),this.warn(`Download attempt ${c} failed: ${s.message}. Retrying in ${o>=60000?`${~~(o/60000)}m`:`${~~(o/1000)}s`}...`),await l.wait(d),d=o}if(i){this.warn("Max retries reached. Using existing local version."),this.isLoaded=!0,this.success("Loaded existing FNLB version");return}throw new Error(`[FNLB ShardingManager] Failed to download and verify update after ${c} attempts`)}log(...t){if(!this.config?.disableLogs)console.log("[FNLB ShardingManager]",...t),this.config?.onLogMessage?.({timestamp:Date.now(),content:t.join(" "),format:0})}success(...t){if(!this.config?.disableLogs)console.log("[FNLB ShardingManager] [OK]",...t),this.config?.onLogMessage?.({timestamp:Date.now(),content:t.join(" "),format:1})}warn(...t){if(!this.config?.disableErrorLogs)console.warn("[FNLB ShardingManager] [WRN]",...t),this.config?.onLogMessage?.({timestamp:Date.now(),content:t.join(" "),format:3})}error(...t){if(!this.config?.disableErrorLogs)console.error("[FNLB ShardingManager] [ERR]",...t),this.config?.onLogMessage?.({timestamp:Date.now(),content:t.join(" "),format:4})}}var v;((i)=>{i.Info="INFO";i.Debug="DEBUG"})(v||={});var C=f;export{C as default,v as LogLevel};
1
+ import{fork as g}from"node:child_process";import{createHash as u}from"node:crypto";import{mkdir as w,readFile as m,writeFile as S}from"node:fs/promises";import{resolve as d}from"node:path";class l{static wait(t){return new Promise((r)=>setTimeout(r,t))}}class f{config;activeProcesses=new Map;packageName=`${process.versions.bun?"zenith-bun":"zenith"}`;fnlbDir;isLoaded=!1;shouldRestart=!0;runId=0;constructor(t){this.config=t,this.fnlbDir=t?.fnlbPath?d(t?.fnlbPath,".fnlb"):d(process.cwd(),".fnlb")}async start(t){await this.stop(),this.shouldRestart=!0,this.runId++;let r=this.runId;if(!t?.apiToken)throw new Error("[FNLB ShardingManager] Please provide a FNLB API token.");await this.update();let o=t.numberOfShards??1,h=(~~(Math.random()*1e4)).toString(36)+"fnlb"+(~~(Date.now()/1000)).toString(36);for(let i=0;i<o;i++){let e=`${h}-${i.toString().padStart(2,"0")}`,n=await this.startShard(t,e,r);this.activeProcesses.set(e,n)}}async stop(){if(this.shouldRestart=!1,this.runId++,this.activeProcesses.size===0)return;this.log("Stopping all active shards...");for(let[t,r]of this.activeProcesses)this.log(`Stopping shard with ID: ${t}`),r.kill();this.activeProcesses.clear(),this.log("All shards stopped.")}async startShard(t,r,o){if(await this.update(),!t?.apiToken||t.apiToken.length<10)throw new Error("[FNLB ShardingManager] Please provide a valid FNLB API token.");this.log("Starting shard with ID:",r);let h=g(d(this.fnlbDir,`${this.packageName}.mjs`),[],{env:{...process.env,FORCE_COLOR:"1",SHARD_ID:r,API_TOKEN:t.apiToken,CATEGORIES:t.categories?.join(","),BOTS_PER_SHARD:(t.botsPerShard??1).toString(),HIDE_USERNAMES:t.hideUsernames?"true":"false",HIDE_EMAILS:t.hideEmails?"true":"false",LOG_LEVEL:t.logLevel,CLUSTER_ID:this.config?.clusterName?.trim().replace(/ +(?= )/g,"").toLowerCase().replaceAll(" ","-")??"unknown",CLUSTER_NAME:this.config?.clusterName?.trim(),FNLB_DIR:this.fnlbDir},stdio:["inherit","pipe","pipe","ipc"]});if(!this.config?.disableSubProcessLogs)h.stdout?.on("data",(i)=>{let e=i.toString("utf8");process.stdout.write(e),this.config?.onSubProcessLogMessage?.({timestamp:Date.now(),content:e,format:0})});if(!this.config?.disableSubProcessErrorLogs)h.stderr?.on("data",(i)=>{let e=i.toString("utf8");process.stderr.write(e),this.config?.onSubProcessLogMessage?.({timestamp:Date.now(),content:e,format:4})});return h.on("close",async(i)=>{if(this.activeProcesses.delete(r),this.shouldRestart&&o===this.runId){if(i===0)this.warn("Shard exited with code:",i);else this.error("Shard exited with code:",i?.toString()??"none");this.log("Trying to restart shard..."),await l.wait(1e4);let e=await this.startShard(t,r,o);this.activeProcesses.set(r,e)}else this.log(`Shard ${r} stopped.`)}),h}async update(){if(this.isLoaded)return;let t=d(this.fnlbDir,`${this.packageName}.mjs`),r=await m(t,"utf-8").catch(()=>null),o=this.config?.maxDownloadRetries||1/0,h=this.config?.maxBackoffMs||60000;this.log(r?"Checking for updates...":"Downloading FNLB...");let i=`https://dist.fnlb.net/packages/${this.packageName}/release`,e,n=0,c=1000;while(n<o)try{let s=await fetch(i);if(!s.ok)throw new Error(`Status code: ${s.status}`);e=await s.json();break}catch(s){let a=Math.min(c*2,h);if(n++,this.error("Update error:",s),this.warn(`Check for updates attempt ${n} failed: ${s.message}. Retrying in ${a>=60000?`${~~(a/60000)}m`:`${~~(a/1000)}s`}...`),n>=o)break;await new Promise((p)=>setTimeout(p,c)),c=a}if(!e){if(r){this.warn("Failed to check for updates. Using existing local version."),this.isLoaded=!0,this.success("Loaded existing FNLB version");return}throw new Error("[FNLB ShardingManager] Failed to check for updates and no local file found.")}if(r){if(u("sha256").update(r).digest("hex")===e.hash){this.success(`FNLB v${e.version} is up to date`),this.isLoaded=!0,this.success(`Finished loading FNLB v${e.version}`);return}this.log(`Downloading update for FNLB v${e.version}`)}n=0,c=1000;while(n<o)try{let s=await fetch(e.url);if(!s.ok)throw new Error(`Download failed with status ${s.status}`);let a=await s.text();if(u("sha256").update(a).digest("hex")!==e.hash)throw new Error("Downloaded file hash mismatch...");await w(this.fnlbDir,{recursive:!0}).catch(()=>{throw new Error(`Failed to create the .fnlb directory on ${this.fnlbDir}`)}),await S(t,a),this.isLoaded=!0,this.success(`Finished loading FNLB v${e.version}`);return}catch(s){let a=Math.min(c*2,h);n++,this.error("Download error:",s),this.warn(`Download attempt ${n} failed: ${s.message}. Retrying in ${a>=60000?`${~~(a/60000)}m`:`${~~(a/1000)}s`}...`),await l.wait(c),c=a}if(r){this.warn("Max retries reached. Using existing local version."),this.isLoaded=!0,this.success("Loaded existing FNLB version");return}throw new Error(`[FNLB ShardingManager] Failed to download and verify update after ${n} attempts`)}log(...t){if(!this.config?.disableLogs)console.log("[FNLB ShardingManager]",...t),this.config?.onLogMessage?.({timestamp:Date.now(),content:t.join(" "),format:0})}success(...t){if(!this.config?.disableLogs)console.log("[FNLB ShardingManager] [OK]",...t),this.config?.onLogMessage?.({timestamp:Date.now(),content:t.join(" "),format:1})}warn(...t){if(!this.config?.disableErrorLogs)console.warn("[FNLB ShardingManager] [WRN]",...t),this.config?.onLogMessage?.({timestamp:Date.now(),content:t.join(" "),format:3})}error(...t){if(!this.config?.disableErrorLogs)console.error("[FNLB ShardingManager] [ERR]",...t),this.config?.onLogMessage?.({timestamp:Date.now(),content:t.join(" "),format:4})}}var b;((o)=>{o.Info="INFO";o.Debug="DEBUG"})(b||={});var M=f;export{M as default,b as LogLevel};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fnlb",
3
- "version": "1.1.10",
3
+ "version": "1.1.12",
4
4
  "author": "FNLB",
5
5
  "main": "dist/index.js",
6
6
  "homepage": "https://fnlb.net",