diff --git a/index.js b/index.js index b98175b..0b815a8 100644 --- a/index.js +++ b/index.js @@ -10,14 +10,16 @@ try{if(fs.existsSync(packageFile))packageJson=JSON.parse(fs.readFileSync(package const version=packageJson.version||'unknown'; if(!fs.existsSync(envFile)&&fs.existsSync(envExample)){fs.copyFileSync(envExample,envFile);ok('Created .env from .env.example');} const packages=new Map(); -function packageName(spec){const value=String(spec).trim();if(value.startsWith('@')){const slash=value.indexOf('/');if(slash===-1)return value;const at=value.indexOf('@',slash);return at===-1?value:value.slice(0,at);}return value.split('@')[0].split(/[?#]/)[0];} +function packageName(spec){const value=String(spec).trim();if(value.startsWith('@')){const slash=value.indexOf('/');if(slash===-1)return value;const at=value.indexOf('@',slash);return at===-1?value:value.slice(0,slash+value.slice(slash+1).indexOf('@')+1);}} function addPackage(spec,source='module'){if(!spec)return;const value=String(spec).trim();if(!value)return;const name=packageName(value);if(!name)return;if(!packages.has(name))packages.set(name,{spec:value,source});} -function addDependencies(value,source){if(Array.isArray(value))for(const spec of value)addPackage(spec,source);else if(value&&typeof value==='object')for(const[spec,dependencyVersion]of Object.entries(value))addPackage(dependencyVersion?`${spec}@${dependencyVersion}`:spec,source);} +function addDependencies(value,source){if(Array.isArray(value))for(const spec of value)addPackage(spec,source);else if(value&&typeof value==='object')for(const[spec,dependencyVersion]of Object.entries(value))addPackage(spec,source);} addDependencies(packageJson.dependencies,'required'); function resolveInstalled(name){try{require.resolve(name,{paths:[root]});return true;}catch{return false;}} -function installMissing(entries){if(!entries.length)return true;rule();install(`Installing ${entries.length} missing package(s)...`);for(const entry of entries)info(`${entry.spec} [${entry.source}]`);const npm=process.env.npm_execpath||'npm';const npmArgs=['install','--no-save','--no-package-lock','--no-audit','--no-fund',...entries.map(x=>x.spec)];const useNode=String(npm).endsWith('.js');const command=useNode?process.execPath:npm;const commandArgs=useNode?[npm,...npmArgs]:npmArgs;const result=spawnSync(command,commandArgs,{cwd:root,stdio:'inherit'});if(result.error){error(`Dependency installation could not start: ${result.error.message}`);return false;}if(result.status!==0){error(`Dependency installation failed with exit code ${result.status??'unknown'}`);return false;}for(const entry of entries)ok(`Installed ${entry.spec}`);return true;} +function installMissing(entries){if(!entries.length)return true;rule();install(`Installing ${entries.length} missing package(s)...`);for(const entry of entries)info(`${entry.spec} [${entry.source}]`);const npm=process.env.npm_execpath||'npm';const args=['install',...entries.map(e=>e.spec)];const result=spawnSync(npm,args,{stdio:'inherit',cwd:root,env:process.env});if(result.status!==0){error(`Dependency install failed with exit code ${result.status}`);return false;}return true;} let requiredMissing=[];for(const[name,entry]of packages){if(resolveInstalled(name))ok(`${entry.spec} already installed`);else requiredMissing.push(entry);}if(!installMissing(requiredMissing))process.exit(1); require('dotenv').config({quiet:true}); +const {syncEnvSchema}=require('./lib/env-sync'); +syncEnvSchema({root,envExample,envFile}); let yaml;try{yaml=require('js-yaml');}catch(e){error(`Required dependency js-yaml is unavailable: ${e.message}`);process.exit(1);} let config;try{config=require('./lib/config').loadConfig();}catch(e){error(`Could not load config.yml: ${e.message}`);process.exit(1);} const panelEnabled=config.adminPanel?.enabled===true||config.dashboard?.enabled===true; @@ -25,21 +27,44 @@ if(panelEnabled){addPackage('@tailwindcss/cli@4.3.3','admin-panel');addPackage(' function moduleDirs(base){if(!fs.existsSync(base))return[];return fs.readdirSync(base,{withFileTypes:true}).filter(x=>x.isDirectory()).map(x=>path.join(base,x.name));} function readYaml(file){try{return yaml.load(fs.readFileSync(file,'utf8'))||{};}catch(e){warn(`Invalid YAML ${path.relative(root,file)}: ${e.message}`);return{};}} let enabledModules=0; -for(const dir of [...moduleDirs(path.join(root,'modules')),...moduleDirs(path.join(root,'custom-modules'))]){const name=path.basename(dir);const manifestFile=fs.existsSync(path.join(dir,'config.yml'))?path.join(dir,'config.yml'):path.join(dir,'module.yml');const manifest=fs.existsSync(manifestFile)?readYaml(manifestFile):{};const rootEnabled=config[name]?.enabled===true||(name==='dashboard'&&config.adminPanel?.enabled===true);if(!rootEnabled)continue;enabledModules++;addDependencies(manifest.dependencies,'module');if(manifest.advanced===true&&fs.existsSync(path.join(dir,'advanced.yml'))){const advanced=readYaml(path.join(dir,'advanced.yml'));addDependencies(advanced.module?.dependencies,'advanced');addDependencies(advanced.dependencies,'advanced');}} -if(config.database?.enabled===true){const provider=String(config.database.primary||'none').toLowerCase();if(provider==='sqlite')addPackage('better-sqlite3@13.0.3','database');if(provider==='mysql')addPackage('mysql2@3.24.4','database');if(provider==='postgres')addPackage('pg@8.23.0','database');if(provider==='mongodb')addPackage('mongodb@7.6.0','database');if(provider==='redis')addPackage('redis@6.2.1','database');} -const shardSetting=config.sharding?.enabled===true?(config.sharding?.totalShards==='auto'?'auto':String(config.sharding?.totalShards||1)):'off'; -banner({version,node:process.version,platform:`${process.platform}/${process.arch}`,modules:`${enabledModules} enabled`,database:String(config.database?.enabled===true?config.database?.primary||'enabled':'disabled'),shards:shardSetting}); -boot(`Working directory: ${root}`);boot(`Process: ${process.pid} | ${process.execPath}`);boot(`Configuration: ${path.basename(path.join(root,'config.yml'))} | release ${config.release||'unknown'}`); -const missing=[];let already=0;for(const[name,entry]of packages){if(resolveInstalled(name)){already++;if(entry.source!=='required')ok(`${entry.spec} already installed`);}else missing.push(entry);}if(!installMissing(missing))process.exit(1);info(`Dependencies: ${already} already present | ${missing.length} installed | ${packages.size} total`); -if(panelEnabled&&!fs.existsSync(path.join(root,'modules','dashboard','public','admin.css'))){info('Building local admin panel assets');const npm=process.env.npm_execpath||'npm';const args=['run','build:panel'];const useNode=String(npm).endsWith('.js');const result=spawnSync(useNode?process.execPath:npm,useNode?[npm,...args]:args,{cwd:root,stdio:'inherit'});if(result.status!==0){error('Admin panel CSS build failed');process.exit(1);}} -if(!process.env.DISCORD_TOKEN||process.env.DISCORD_TOKEN==='YOUR_BOT_TOKEN_HERE'){error('Set DISCORD_TOKEN in .env');process.exit(1);}ok('Dependency bootstrap complete');rule(); +for(const dir of [...moduleDirs(path.join(root,'modules')),...moduleDirs(path.join(root,'custom-modules'))]){const name=path.basename(dir);const manifestFile=fs.existsSync(path.join(dir,'config.yml'))?path.join(dir,'config.yml'):path.join(dir,'module.yml');if(fs.existsSync(manifestFile)){const manifest=readYaml(manifestFile);const isEnabled=(manifest.enabled===true)||(config[name]?.enabled===true);if(isEnabled)enabledModules++;}} +if(config.database?.enabled===true){const provider=String(config.database.primary||'none').toLowerCase();if(provider==='sqlite')addPackage('better-sqlite3@13.0.3','database');if(provider==='mysql')addPackage('mysql2@3.2.5','database');if(provider==='postgres')addPackage('pg@8.16.0','database');if(provider==='mongodb')addPackage('mongodb@6.10.0','database');if(provider==='redis')addPackage('redis@5.0.0','database');} +const shardSetting=config.sharding?.enabled===true?(config.sharding?.auto===true?'auto':'on'):'off'; +banner({version,node:process.version,platform:`${process.platform}/${process.arch}`,modules:`${enabledModules} enabled`,database:String(config.database?.enabled===true?config.database?.primary||'none':'none'),sharding:shardSetting}); +boot(`Working directory: ${root}`);boot(`Process: ${process.pid} | ${process.execPath}`);boot(`Configuration: ${path.basename(path.join(root,'config.yml'))} | release ${config.release||'unknown'}`);boot(`Booting with ${enabledModules} enabled modules`);rule(); +const missing=[];let already=0;for(const[name,entry]of packages){if(resolveInstalled(name)){already++;if(entry.source!=='required')ok(`${entry.spec} already installed`);}else missing.push(entry);}if(missing.length){error(`Missing dependencies: ${missing.map(x=>x.spec).join(', ')}`);process.exit(1);}ok('Dependency bootstrap complete');rule(); const {ShardingManager}=require('discord.js'); +const {createShardCoordinator,discoverDiscordShards}=require('./lib/sharding'); let manager=null; let shuttingDown=false; -function shutdownChildren(signal){if(shuttingDown)return;shuttingDown=true;if(manager?.respawn!==undefined)manager.respawn=false;const children=manager?.shards?Array.from(manager.shards.values()):[];if(!children.length)return;boot(`Forwarding ${signal} to ${children.length} shard process(es)...`);for(const shard of children){try{if(shard.process&&!shard.process.killed)shard.process.kill(signal);else shard.kill();}catch(e){warn(`Could not stop shard #${shard.id}: ${e.message}`);}}} +function shutdownChildren(signal){if(shuttingDown)return;shuttingDown=true;if(manager?.respawn!==undefined)manager.respawn=false;const children=manager?.shards?Array.from(manager.shards.values()):[];for(const child of children)child.kill(signal||'SIGTERM');} function shutdownSignal(signal){shutdownChildren(signal);setTimeout(()=>process.exit(signal==='SIGINT'?130:143),5000).unref?.();} process.once('SIGINT',()=>shutdownSignal('SIGINT')); process.once('SIGTERM',()=>shutdownSignal('SIGTERM')); -async function recommendedShards(){const response=await fetch('https://discord.com/api/v10/gateway/bot',{headers:{Authorization:`Bot ${process.env.DISCORD_TOKEN}`}});if(!response.ok)throw new Error(`Gateway discovery returned HTTP ${response.status}`);const body=await response.json();return Math.max(1,Number(body.shards||1));} -async function start(){const sharding=config.sharding||{};if(sharding.enabled===true){const remote=['redis','mongodb','mysql','postgres'].includes(String(config.database?.primary||'').toLowerCase());if((sharding.autoDetect===true||sharding.totalShards==='auto')&&!remote)throw new Error('Automatic shard detection requires a remote database: redis, mongodb, mysql, or postgres');let total=sharding.totalShards;if(sharding.autoDetect===true)total=await recommendedShards();if(total==null||total==='auto')total=1;boot(`Launching ${total} shard process(es)`);manager=new ShardingManager(path.join(root,'main.js'),{token:process.env.DISCORD_TOKEN,totalShards:total,shardList:Array.isArray(sharding.shardList)?sharding.shardList:undefined,respawn:sharding.respawn!==false,mode:'process'});manager.on('shardCreate',shard=>{ok(`Spawned shard #${shard.id}`);shard.on('death',process=>{if(shuttingDown)return;warn(`Shard #${shard.id} exited with code ${process.exitCode??'unknown'}`);});});await manager.spawn();return;}boot('Launching main process...');await require('./main').start();} +async function start(){ + const sharding=config.sharding||{}; + if(sharding.enabled===true){ + const token=process.env.DISCORD_TOKEN; + if(!token)throw new Error('DISCORD_TOKEN is missing'); + const providerName=String(config.database?.primary||'none').toLowerCase(); + const total=await discoverDiscordShards(token); + console.log('[Shard Coordinator] Discovering Discord shard count...'); + console.log(`[Shard Coordinator] Discord recommended shards: ${total}`); + console.log(`[Shard Coordinator] Provider: ${providerName}`); + const coordinator=await createShardCoordinator(config,{instanceId:`${require('node:os').hostname()}-${process.pid}`}); + const active=await coordinator.getActiveShards(); + console.log(`[Shard Coordinator] Active shards: ${active.map((item)=>item.shardId).join(',') || 'none'}`); + const claimed=[]; + for(let shardId=0;shardIdboot(`[BOOT] Launching shard ${shard.id}`)); + await manager.spawn({amount:Math.max(1,claimed.length)}); + return; + } + require('./main.js'); +} start().catch(e=>{error(`Start failed: ${e?.stack||e?.message||e}`);process.exit(1);}); diff --git a/lib/config.js b/lib/config.js index c6663da..7aae599 100644 --- a/lib/config.js +++ b/lib/config.js @@ -5,11 +5,39 @@ const root=path.join(__dirname,'..'); const configFile=path.join(root,'config.yml'); const exampleFile=path.join(root,'config.example.yml'); const moduleRoot=path.join(root,'modules'); -function deepMerge(base,extra){const out={...(base||{})};for(const[key,value]of Object.entries(extra||{})){if(value&&typeof value==='object'&&!Array.isArray(value))out[key]=deepMerge(out[key],value);else if(!(key in out))out[key]=value;}return out;} +function deepMerge(base,extra){const out={...(base||{})};for(const[key,value]of Object.entries(extra||{})){if(value&&typeof value==='object'&&!Array.isArray(value))out[key]=deepMerge(out[key],value);else out[key]=value;}return out;} function backup(file){if(!fs.existsSync(file))return;const backup=`${file}.backup.${Date.now()}`;fs.copyFileSync(file,backup);console.log(`[Config] Backup created: ${path.basename(backup)}`);} function write(file,data){fs.mkdirSync(path.dirname(file),{recursive:true});const tmp=`${file}.tmp`;fs.writeFileSync(tmp,data,'utf8');fs.renameSync(tmp,file);} const legacyAliases={aichat:'ai',honeypot:'security',commandDeployment:'commands'}; -function migrate(config){const oldVersion=Number(config.version||1),next={...config};if(next.commandDeployment&&!next.commands)next.commands=next.commandDeployment;if(next.aichat&&!next.ai)next.ai={...next.aichat};if(next.honeypot&&typeof next.honeypot==='object'){if(!next.security||typeof next.security!=='object')next.security={...next.honeypot};else{const legacy=next.honeypot;for(const[key,value]of Object.entries(legacy))if(!(key in next.security))next.security[key]=value;}}if(!next.permissions)next.permissions={};if(!next.runtime)next.runtime={environment:'production',gracefulShutdown:true,crashProtection:true};if(!next.prefix)next.prefix={enabled:false,prefixes:['!'],mentionPrefix:true};if(!next.database)next.database={enabled:false,primary:'none',fallbackToLocal:true};if(!next.sharding)next.sharding={enabled:false,autoDetect:false,totalShards:'auto',shardList:'auto',respawn:true};next.version=5;return{config:next,changed:oldVersion!==5,oldVersion};} -function migrateModuleConfigs(config){if(!fs.existsSync(moduleRoot))return false;let changed=false;for(const[oldName,newName]of Object.entries(legacyAliases)){const data=config[oldName];if(!data||typeof data!=='object')continue;const dir=path.join(moduleRoot,newName),file=path.join(dir,'config.yml');if(!fs.existsSync(dir)||fs.existsSync(file))continue;write(file,yaml.dump({...data,advanced:false},{noRefs:true,lineWidth:-1}));console.log(`[Migration] Created ${newName}/config.yml from legacy ${oldName}`);changed=true;}for(const entry of fs.readdirSync(moduleRoot,{withFileTypes:true}).filter(x=>x.isDirectory())){const name=entry.name,file=path.join(moduleRoot,name,'config.yml');if(!fs.existsSync(file))continue;let data;try{data=yaml.load(fs.readFileSync(file,'utf8'))||{};}catch(e){console.error(`[Migration] Failed to read ${name}/config.yml:`,e.message);continue;}if(!Object.prototype.hasOwnProperty.call(data,'enabled'))continue;const legacyEnabled=data.enabled;delete data.enabled;if(!config[name]||typeof config[name]!=='object')config[name]={};if(typeof config[name].enabled!=='boolean'&&typeof legacyEnabled==='boolean')config[name].enabled=legacyEnabled;backup(file);write(file,yaml.dump(data,{noRefs:true,lineWidth:-1}));console.log(`[Migration] Moved ${name}.enabled=${legacyEnabled} to root config and removed module enabled flag`);changed=true;}const honeypotFile=path.join(moduleRoot,'honeypot','config.yml'),securityFile=path.join(moduleRoot,'security','config.yml');if(fs.existsSync(honeypotFile)&&fs.existsSync(securityFile)){const honeypot=(()=>{try{return yaml.load(fs.readFileSync(honeypotFile,'utf8'))||{};}catch{return{};}})(),security=(()=>{try{return yaml.load(fs.readFileSync(securityFile,'utf8'))||{};}catch{return{};}})();let merged=false;for(const[key,value]of Object.entries(honeypot))if(key!=='aliasOf'&&key!=='enabled'&&!(key in security)){security[key]=value;merged=true;}if(merged){backup(securityFile);write(securityFile,yaml.dump(security,{noRefs:true,lineWidth:-1}));console.log('[Migration] Preserved legacy honeypot settings in security/config.yml');changed=true;}}return changed;} -function loadConfig(){if(!fs.existsSync(configFile)){if(!fs.existsSync(exampleFile))throw new Error('config.example.yml is missing');fs.copyFileSync(exampleFile,configFile);console.log('[Config] Created config.yml from config.example.yml');}let current;try{current=yaml.load(fs.readFileSync(configFile,'utf8'))||{};}catch(e){backup(configFile);current={};console.error('[Config] Invalid config:',e.message);}const example=yaml.load(fs.readFileSync(exampleFile,'utf8'))||{};const migration=migrate(current);const moduleChanged=migrateModuleConfigs(migration.config);const merged=deepMerge(migration.config,example);merged.version=5;if(migration.changed||moduleChanged){if(fs.existsSync(configFile))backup(configFile);write(configFile,yaml.dump(merged,{noRefs:true,lineWidth:-1}));if(migration.changed)console.log(`[Config] Migrated V${migration.oldVersion} -> V5`);if(moduleChanged)console.log('[Config] Module enable states are now controlled by root config.yml');}return merged;} +function migrate(config){ + const next={...(config||{})}; + if(next.commandDeployment&&!next.commands)next.commands=next.commandDeployment; + if(next.aichat&&!next.ai)next.ai=next.aichat; + if(next.honeypot&&!next.security)next.security=next.honeypot; + if(next.sharding && typeof next.sharding==='object'){ + const sharding=next.sharding; + const legacy = sharding.totalShards!==undefined || sharding.shardList!==undefined || sharding.maxConcurrency!==undefined || sharding.autoDetect!==undefined; + if(legacy){ + sharding.enabled = sharding.enabled !== false; + sharding.auto = true; + sharding.coordination = 'auto'; + sharding.heartbeatInterval = sharding.heartbeatInterval ?? 30000; + sharding.timeout = sharding.timeout ?? 120000; + delete sharding.totalShards; + delete sharding.shardList; + delete sharding.maxConcurrency; + delete sharding.autoDetect; + } + next.sharding = sharding; + } + return next; +} +function migrateModuleConfigs(config){if(!fs.existsSync(moduleRoot))return false;let changed=false;for(const[oldName,newName]of Object.entries(legacyAliases)){const data=config[oldName];if(!data||typeof data!=='object')continue;const target=config[newName]||{};config[newName]=deepMerge(target,data);delete config[oldName];changed=true;}return changed;} +function loadConfig(){if(!fs.existsSync(configFile)){if(!fs.existsSync(exampleFile))throw new Error('config.example.yml is missing');fs.copyFileSync(exampleFile,configFile);console.log('[Config] Created config.yml from config.example.yml');} +const raw=fs.readFileSync(configFile,'utf8'); +const config=raw.trim()?yaml.load(raw)||{}:{}; +const migrated=migrate(config); +const dirty=JSON.stringify(migrated)!==JSON.stringify(config); +if(dirty){backup(configFile);write(configFile,yaml.dump(migrated,{lineWidth:-1}));console.log('[Config] Migrated config.yml to sharding-safe schema');} +return migrated;} module.exports={loadConfig,migrate,deepMerge,migrateModuleConfigs}; diff --git a/lib/env-sync.js b/lib/env-sync.js new file mode 100644 index 0000000..02c4d3d --- /dev/null +++ b/lib/env-sync.js @@ -0,0 +1,83 @@ +const fs = require('node:fs'); +const path = require('node:path'); + +function parseEnvFile(content = '') { + const map = new Map(); + const lines = String(content).split(/\r?\n/); + for (const rawLine of lines) { + const line = rawLine.trim(); + if (!line || line.startsWith('#')) continue; + const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/); + if (!match) continue; + const [, key, value] = match; + map.set(key, value); + } + return map; +} + +function syncEnvSchema(options = {}) { + const root = options.root || process.cwd(); + const envExamplePath = options.envExample || path.join(root, '.env.example'); + const envPath = options.envFile || path.join(root, '.env'); + + if (!fs.existsSync(envExamplePath)) { + return { added: [], removed: [], updated: false }; + } + + if (!fs.existsSync(envPath)) { + fs.copyFileSync(envExamplePath, envPath); + console.log('[ENV] Checking .env schema...'); + console.log('[ENV] Updated successfully'); + return { added: [], removed: [], updated: true }; + } + + const exampleContent = fs.readFileSync(envExamplePath, 'utf8'); + const envContent = fs.readFileSync(envPath, 'utf8'); + const exampleVariables = parseEnvFile(exampleContent); + const envVariables = parseEnvFile(envContent); + + const added = []; + const removed = []; + const finalEntries = []; + const seen = new Set(); + + for (const [key] of exampleVariables.entries()) { + if (!envVariables.has(key)) { + added.push(key); + finalEntries.push(`${key}=`); + seen.add(key); + continue; + } + + const rawValue = envVariables.get(key); + finalEntries.push(`${key}=${rawValue ?? ''}`); + seen.add(key); + } + + for (const [key] of envVariables.entries()) { + if (!exampleVariables.has(key)) { + removed.push(key); + } + } + + const finalContent = `${finalEntries.join('\n')}\n`; + + if (added.length || removed.length) { + fs.writeFileSync(envPath, finalContent, 'utf8'); + } + + console.log('[ENV] Checking .env schema...'); + if (added.length) { + console.log('[ENV] Added:'); + for (const key of added) console.log(key); + } + if (removed.length) { + console.log('[ENV] Removed:'); + for (const key of removed) console.log(key); + } + console.log('[ENV] Updated successfully'); + + return { added, removed, updated: added.length > 0 || removed.length > 0 }; +} + +module.exports = { parseEnvFile, syncEnvSchema }; diff --git a/lib/sharding/coordinator.js b/lib/sharding/coordinator.js new file mode 100644 index 0000000..87b97d0 --- /dev/null +++ b/lib/sharding/coordinator.js @@ -0,0 +1,73 @@ +const os = require('node:os'); +const { randomUUID } = require('node:crypto'); + +function normalizeProviderName(value) { + return String(value || '').trim().toLowerCase(); +} + +function resolveProvider(config = {}) { + const provider = normalizeProviderName(config.database?.primary || 'sqlite'); + const registry = { + mongodb: './providers/mongodb', + redis: './providers/redis', + mysql: './providers/mysql', + postgres: './providers/postgres', + }; + + if (!registry[provider]) { + throw new Error('Shard coordination requires an external database provider. Set database.primary to mongodb, redis, mysql, or postgres.'); + } + + return require(registry[provider]); +} + +function createCoordinator(config = {}, options = {}) { + const Provider = resolveProvider(config); + const provider = new Provider(config, { + instanceId: options.instanceId || `${os.hostname()}-${process.pid}-${randomUUID()}`, + hostname: options.hostname || os.hostname(), + pid: options.pid || process.pid, + heartbeatInterval: Number(options.heartbeatInterval ?? config.sharding?.heartbeatInterval ?? 30000), + timeout: Number(options.timeout ?? config.sharding?.timeout ?? 120000), + key: options.key || 'realmsbot:shards', + }); + + return { + async init() { + await provider.connect?.(); + return this; + }, + + async claimShard(shardId) { + const id = Number(shardId); + if (!Number.isInteger(id)) { + throw new Error(`Invalid shard id: ${shardId}`); + } + return provider.claimShard(id, { + instanceId: provider.instanceId, + hostname: provider.hostname, + pid: provider.pid, + heartbeatInterval: provider.heartbeatInterval, + timeout: provider.timeout, + }); + }, + + async releaseShard(shardId) { + return provider.releaseShard(Number(shardId), provider.instanceId); + }, + + async heartbeat(shardId) { + return provider.heartbeat(Number(shardId), provider.instanceId); + }, + + async getActiveShards() { + return provider.getActiveShards(); + }, + + get provider() { + return provider; + }, + }; +} + +module.exports = { createCoordinator, normalizeProviderName, resolveProvider }; diff --git a/lib/sharding/index.js b/lib/sharding/index.js new file mode 100644 index 0000000..388cd26 --- /dev/null +++ b/lib/sharding/index.js @@ -0,0 +1,25 @@ +const { createCoordinator } = require('./coordinator'); + +async function createShardCoordinator(config = {}, options = {}) { + const coordinator = createCoordinator(config, options); + await coordinator.init(); + return coordinator; +} + +async function discoverDiscordShards(token) { + const response = await fetch('https://discord.com/api/v10/gateway/bot', { + headers: { + Authorization: `Bot ${token}`, + 'User-Agent': 'RealmsNetwork-Bot/1.0', + }, + }); + + if (!response.ok) { + throw new Error(`Discord gateway check failed: ${response.status}`); + } + + const data = await response.json(); + return Number(data.shards || 1); +} + +module.exports = { createShardCoordinator, discoverDiscordShards }; diff --git a/lib/sharding/providers/mongodb.js b/lib/sharding/providers/mongodb.js new file mode 100644 index 0000000..74a46af --- /dev/null +++ b/lib/sharding/providers/mongodb.js @@ -0,0 +1,74 @@ +class MongoShardProvider { + constructor(config = {}, options = {}) { + this.config = config; + this.instanceId = options.instanceId; + this.hostname = options.hostname || 'localhost'; + this.pid = options.pid || process.pid; + this.heartbeatInterval = Number(options.heartbeatInterval || config.sharding?.heartbeatInterval || 30000); + this.timeout = Number(options.timeout || config.sharding?.timeout || 120000); + this.key = options.key || 'realmsbot:shards'; + this.client = null; + this.collection = null; + } + + async connect() { + const { MongoClient } = require('mongodb'); + const uri = this.config.database?.mongodb?.url || process.env.MONGODB_URI; + if (!uri) throw new Error('MONGODB_URI is required for MongoDB shard coordination'); + this.client = new MongoClient(uri, { serverSelectionTimeoutMS: 5000 }); + await this.client.connect(); + const db = this.client.db(this.config.database?.mongodb?.database || 'realmsbot'); + this.collection = db.collection(this.key.replace(/[^a-zA-Z0-9_-]/g, '_')); + await this.collection.createIndex({ shardId: 1 }, { unique: true }); + await this.collection.createIndex({ heartbeat: 1 }); + } + + async claimShard(shardId, meta = {}) { + const now = Date.now(); + const record = await this.collection.findOne({ shardId }); + if (record && record.status === 'online' && (now - Number(record.heartbeat || 0)) < this.timeout) { + return false; + } + const next = { + shardId, + instanceId: meta.instanceId || this.instanceId, + hostname: meta.hostname || this.hostname, + pid: meta.pid || this.pid, + heartbeat: now, + status: 'online', + }; + await this.collection.updateOne({ shardId }, { $set: next }, { upsert: true }); + return true; + } + + async releaseShard(shardId, instanceId) { + await this.collection.deleteOne({ shardId, instanceId }); + return true; + } + + async heartbeat(shardId, instanceId) { + const now = Date.now(); + const result = await this.collection.updateOne( + { shardId, instanceId }, + { $set: { heartbeat: now, status: 'online', hostname: this.hostname, pid: this.pid } }, + ); + return result.modifiedCount > 0 || result.upsertedCount > 0; + } + + async getActiveShards() { + const cutoff = Date.now() - this.timeout; + const rows = await this.collection.find({ status: 'online', heartbeat: { $gte: cutoff } }).toArray(); + return rows + .map((row) => ({ + shardId: Number(row.shardId), + instanceId: row.instanceId, + hostname: row.hostname, + pid: Number(row.pid), + heartbeat: Number(row.heartbeat), + status: row.status || 'online', + })) + .sort((a, b) => a.shardId - b.shardId); + } +} + +module.exports = MongoShardProvider; diff --git a/lib/sharding/providers/mysql.js b/lib/sharding/providers/mysql.js new file mode 100644 index 0000000..3fc6544 --- /dev/null +++ b/lib/sharding/providers/mysql.js @@ -0,0 +1,56 @@ +class MySQLShardProvider { + constructor(config = {}, options = {}) { + this.config = config; + this.instanceId = options.instanceId; + this.hostname = options.hostname || 'localhost'; + this.pid = options.pid || process.pid; + this.heartbeatInterval = Number(options.heartbeatInterval || config.sharding?.heartbeatInterval || 30000); + this.timeout = Number(options.timeout || config.sharding?.timeout || 120000); + this.key = options.key || 'realmsbot_shards'; + this.pool = null; + } + + async connect() { + const mysql = require('mysql2/promise'); + const uri = this.config.database?.mysql?.url || process.env.MYSQL_URL; + if (!uri) throw new Error('MYSQL_URL is required for MySQL shard coordination'); + this.pool = mysql.createPool({ uri, waitForConnections: true, connectionLimit: this.config.database?.mysql?.connectionLimit || 5 }); + await this.pool.query(`CREATE TABLE IF NOT EXISTS ${this.key} (shard_id INT PRIMARY KEY, instance_id VARCHAR(255) NOT NULL, hostname VARCHAR(255) NOT NULL, pid INT NOT NULL, heartbeat BIGINT NOT NULL, status VARCHAR(32) NOT NULL)`); + } + + async claimShard(shardId, meta = {}) { + const now = Date.now(); + const [rows] = await this.pool.query(`SELECT * FROM ${this.key} WHERE shard_id = ?`, [shardId]); + if (rows[0] && rows[0].status === 'online' && (now - Number(rows[0].heartbeat || 0)) < this.timeout) { + return false; + } + await this.pool.query(`INSERT INTO ${this.key} (shard_id, instance_id, hostname, pid, heartbeat, status) VALUES (?, ?, ?, ?, ?, 'online') ON DUPLICATE KEY UPDATE instance_id = VALUES(instance_id), hostname = VALUES(hostname), pid = VALUES(pid), heartbeat = VALUES(heartbeat), status = VALUES(status)`, [shardId, meta.instanceId || this.instanceId, meta.hostname || this.hostname, meta.pid || this.pid, now]); + return true; + } + + async releaseShard(shardId, instanceId) { + await this.pool.query(`DELETE FROM ${this.key} WHERE shard_id = ? AND instance_id = ?`, [shardId, instanceId]); + return true; + } + + async heartbeat(shardId, instanceId) { + const now = Date.now(); + const [result] = await this.pool.query(`UPDATE ${this.key} SET heartbeat = ?, status = 'online', hostname = ?, pid = ? WHERE shard_id = ? AND instance_id = ?`, [now, this.hostname, this.pid, shardId, instanceId]); + return (result.affectedRows || 0) > 0; + } + + async getActiveShards() { + const cutoff = Date.now() - this.timeout; + const [rows] = await this.pool.query(`SELECT * FROM ${this.key} WHERE status = 'online' AND heartbeat >= ? ORDER BY shard_id ASC`, [cutoff]); + return rows.map((row) => ({ + shardId: Number(row.shard_id), + instanceId: row.instance_id, + hostname: row.hostname, + pid: Number(row.pid), + heartbeat: Number(row.heartbeat), + status: row.status || 'online', + })); + } +} + +module.exports = MySQLShardProvider; diff --git a/lib/sharding/providers/postgres.js b/lib/sharding/providers/postgres.js new file mode 100644 index 0000000..81bdcaf --- /dev/null +++ b/lib/sharding/providers/postgres.js @@ -0,0 +1,57 @@ +class PostgresShardProvider { + constructor(config = {}, options = {}) { + this.config = config; + this.instanceId = options.instanceId; + this.hostname = options.hostname || 'localhost'; + this.pid = options.pid || process.pid; + this.heartbeatInterval = Number(options.heartbeatInterval || config.sharding?.heartbeatInterval || 30000); + this.timeout = Number(options.timeout || config.sharding?.timeout || 120000); + this.key = options.key || 'realmsbot_shards'; + this.pool = null; + } + + async connect() { + const { Pool } = require('pg'); + const connectionString = this.config.database?.postgres?.url || process.env.DATABASE_URL; + if (!connectionString) throw new Error('DATABASE_URL is required for PostgreSQL shard coordination'); + this.pool = new Pool({ connectionString, max: this.config.database?.postgres?.maxConnections || 5 }); + await this.pool.query(`CREATE TABLE IF NOT EXISTS ${this.key} (shard_id INTEGER PRIMARY KEY, instance_id TEXT NOT NULL, hostname TEXT NOT NULL, pid INTEGER NOT NULL, heartbeat BIGINT NOT NULL, status TEXT NOT NULL)`); + } + + async claimShard(shardId, meta = {}) { + const now = Date.now(); + const { rows } = await this.pool.query(`SELECT * FROM ${this.key} WHERE shard_id = $1`, [shardId]); + const existing = rows[0]; + if (existing && existing.status === 'online' && (now - Number(existing.heartbeat || 0)) < this.timeout) { + return false; + } + await this.pool.query(`INSERT INTO ${this.key} (shard_id, instance_id, hostname, pid, heartbeat, status) VALUES ($1, $2, $3, $4, $5, 'online') ON CONFLICT (shard_id) DO UPDATE SET instance_id = EXCLUDED.instance_id, hostname = EXCLUDED.hostname, pid = EXCLUDED.pid, heartbeat = EXCLUDED.heartbeat, status = EXCLUDED.status`, [shardId, meta.instanceId || this.instanceId, meta.hostname || this.hostname, meta.pid || this.pid, now]); + return true; + } + + async releaseShard(shardId, instanceId) { + await this.pool.query(`DELETE FROM ${this.key} WHERE shard_id = $1 AND instance_id = $2`, [shardId, instanceId]); + return true; + } + + async heartbeat(shardId, instanceId) { + const now = Date.now(); + const res = await this.pool.query(`UPDATE ${this.key} SET heartbeat = $1, status = 'online', hostname = $2, pid = $3 WHERE shard_id = $4 AND instance_id = $5`, [now, this.hostname, this.pid, shardId, instanceId]); + return (res.rowCount || 0) > 0; + } + + async getActiveShards() { + const cutoff = Date.now() - this.timeout; + const { rows } = await this.pool.query(`SELECT * FROM ${this.key} WHERE status = 'online' AND heartbeat >= $1 ORDER BY shard_id ASC`, [cutoff]); + return rows.map((row) => ({ + shardId: Number(row.shard_id), + instanceId: row.instance_id, + hostname: row.hostname, + pid: Number(row.pid), + heartbeat: Number(row.heartbeat), + status: row.status || 'online', + })); + } +} + +module.exports = PostgresShardProvider; diff --git a/lib/sharding/providers/redis.js b/lib/sharding/providers/redis.js new file mode 100644 index 0000000..7801026 --- /dev/null +++ b/lib/sharding/providers/redis.js @@ -0,0 +1,82 @@ +class RedisShardProvider { + constructor(config = {}, options = {}) { + this.config = config; + this.instanceId = options.instanceId; + this.hostname = options.hostname || 'localhost'; + this.pid = options.pid || process.pid; + this.heartbeatInterval = Number(options.heartbeatInterval || config.sharding?.heartbeatInterval || 30000); + this.timeout = Number(options.timeout || config.sharding?.timeout || 120000); + this.key = options.key || 'realmsbot:shards'; + this.client = null; + } + + async connect() { + const { createClient } = require('redis'); + const url = this.config.database?.redis?.url || process.env.REDIS_URL || 'redis://127.0.0.1:6379'; + this.client = createClient({ url }); + this.client.on('error', () => {}); + await this.client.connect(); + } + + async claimShard(shardId, meta = {}) { + const now = Date.now(); + const entries = await this.getActiveShards(); + const existing = entries.find((entry) => Number(entry.shardId) === Number(shardId)); + if (existing && (now - Number(existing.heartbeat || 0)) < this.timeout) { + return false; + } + const record = { + shardId, + instanceId: meta.instanceId || this.instanceId, + hostname: meta.hostname || this.hostname, + pid: meta.pid || this.pid, + heartbeat: now, + status: 'online', + }; + await this.client.hSet(this.key, String(shardId), JSON.stringify(record)); + return true; + } + + async releaseShard(shardId, instanceId) { + const current = await this.client.hGet(this.key, String(shardId)); + if (!current) return true; + const record = JSON.parse(current); + if (record.instanceId === instanceId) await this.client.hDel(this.key, String(shardId)); + return true; + } + + async heartbeat(shardId, instanceId) { + const current = await this.client.hGet(this.key, String(shardId)); + if (!current) return false; + const record = JSON.parse(current); + if (record.instanceId !== instanceId) return false; + record.heartbeat = Date.now(); + record.status = 'online'; + record.hostname = this.hostname; + record.pid = this.pid; + await this.client.hSet(this.key, String(shardId), JSON.stringify(record)); + return true; + } + + async getActiveShards() { + const values = await this.client.hVals(this.key); + const cutoff = Date.now() - this.timeout; + return values + .map((value) => { + try { return JSON.parse(value); } catch { return null; } + }) + .filter(Boolean) + .filter((item) => item.status === 'online' && Number(item.heartbeat || 0) >= cutoff) + .map((item) => ({ + shardId: Number(item.shardId), + instanceId: item.instanceId, + hostname: item.hostname, + pid: Number(item.pid), + heartbeat: Number(item.heartbeat), + status: item.status || 'online', + })) + .sort((a, b) => a.shardId - b.shardId); + } +} + +module.exports = RedisShardProvider; diff --git a/test/sharding.test.js b/test/sharding.test.js new file mode 100644 index 0000000..9ed7f50 --- /dev/null +++ b/test/sharding.test.js @@ -0,0 +1,101 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { createCoordinator } = require('../lib/sharding/coordinator'); + +class MemoryShardProvider { + constructor(config = {}, options = {}) { + this.config = config; + this.instanceId = options.instanceId || 'instance-a'; + this.hostname = options.hostname || 'localhost'; + this.pid = options.pid || 1; + this.heartbeatInterval = Number(options.heartbeatInterval || config.sharding?.heartbeatInterval || 30000); + this.timeout = Number(options.timeout || config.sharding?.timeout || 120000); + this.registry = MemoryShardProvider.registry || new Map(); + MemoryShardProvider.registry = this.registry; + } + + async connect() {} + + async claimShard(shardId, meta = {}) { + const now = Date.now(); + const current = this.registry.get(String(shardId)); + if (current && current.status === 'online' && (now - Number(current.heartbeat || 0)) < this.timeout) { + return false; + } + this.registry.set(String(shardId), { + shardId: Number(shardId), + instanceId: meta.instanceId || this.instanceId, + hostname: meta.hostname || this.hostname, + pid: meta.pid || this.pid, + heartbeat: now, + status: 'online', + }); + return true; + } + + async releaseShard(shardId, instanceId) { + const current = this.registry.get(String(shardId)); + if (!current || current.instanceId !== instanceId) return true; + this.registry.delete(String(shardId)); + return true; + } + + async heartbeat(shardId, instanceId) { + const current = this.registry.get(String(shardId)); + if (!current || current.instanceId !== instanceId) return false; + current.heartbeat = Date.now(); + current.status = 'online'; + this.registry.set(String(shardId), current); + return true; + } + + async getActiveShards() { + const cutoff = Date.now() - this.timeout; + return [...this.registry.values()] + .filter((row) => row.status === 'online' && Number(row.heartbeat || 0) >= cutoff) + .map((row) => ({ ...row, shardId: Number(row.shardId), pid: Number(row.pid), heartbeat: Number(row.heartbeat) })) + .sort((a, b) => a.shardId - b.shardId); + } +} + +function makeConfig() { + return { + database: { primary: 'mongodb' }, + sharding: { heartbeatInterval: 30000, timeout: 120000 }, + }; +} + +test('single instance claims shard 0+', async () => { + const provider = new MemoryShardProvider(makeConfig(), { instanceId: 'instance-a' }); + assert.equal(await provider.claimShard(0, { instanceId: 'instance-a', hostname: 'host-a', pid: 123 }), true); + assert.equal(await provider.claimShard(1, { instanceId: 'instance-a', hostname: 'host-a', pid: 123 }), true); +}); + +test('same shard cannot be claimed twice while active', async () => { + const provider = new MemoryShardProvider(makeConfig(), { instanceId: 'instance-a' }); + await provider.claimShard(0, { instanceId: 'instance-a', hostname: 'host-a', pid: 123 }); + const second = await provider.claimShard(0, { instanceId: 'instance-b', hostname: 'host-b', pid: 456 }); + assert.equal(second, false); +}); + +test('dead shard can be reclaimed after timeout', async () => { + const provider = new MemoryShardProvider(makeConfig(), { instanceId: 'instance-a' }); + provider.timeout = 5; + await provider.claimShard(2, { instanceId: 'instance-a', hostname: 'host-a', pid: 123 }); + const stale = { ...provider.registry.get('2'), heartbeat: Date.now() - 2000 }; + provider.registry.set('2', stale); + const claimed = await provider.claimShard(2, { instanceId: 'instance-b', hostname: 'host-b', pid: 456 }); + assert.equal(claimed, true); +}); + +test('coordinator exposes the required API', async () => { + const coordinator = createCoordinator(makeConfig(), { instanceId: 'instance-1' }); + assert.ok(coordinator.claimShard); + assert.ok(coordinator.releaseShard); + assert.ok(coordinator.heartbeat); + assert.ok(coordinator.getActiveShards); + assert.equal(typeof coordinator.claimShard, 'function'); + assert.equal(typeof coordinator.releaseShard, 'function'); + assert.equal(typeof coordinator.heartbeat, 'function'); + assert.equal(typeof coordinator.getActiveShards, 'function'); +});