-
Notifications
You must be signed in to change notification settings - Fork 478
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
180 changed files
with
6,381 additions
and
770 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,3 @@ | ||
import { Trawler, Nocapd, RestApi } from './queues.js' | ||
import { Scheduler as NWScheduler } from './scheduler.js' | ||
|
||
export default { | ||
NWQueues: { | ||
Trawler, | ||
Nocapd, | ||
RestApi | ||
}, | ||
NWScheduler | ||
} | ||
export { SyncQueue, TrawlQueue, NocapdQueue, RestApiQueue, QueueInit, BullMQ } from './src/queues.js' | ||
export { Scheduler } from './src/scheduler.js' | ||
export { RetryManager } from './src/retry.js' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import dotenv from 'dotenv' | ||
import { Queue, QueueEvents, Worker } from 'bullmq'; | ||
import { RedisConnectionDetails } from '@nostrwatch/utils' | ||
|
||
dotenv.config() | ||
|
||
const $ = {} | ||
|
||
export const TrawlQueue = (qopts={}) => { | ||
return QueueInit('TrawlQueue', qopts) | ||
} | ||
|
||
export const NocapdQueue = (qopts={}) => { | ||
return QueueInit('NocapdQueue', qopts) | ||
} | ||
|
||
export const SyncQueue = (qopts={}) => { | ||
return QueueInit('SyncQueue', qopts) | ||
} | ||
|
||
export const RestApiQueue = (qopts={}) => { | ||
return QueueInit('RestApiQueue', qopts) | ||
} | ||
|
||
export const QueueInit = (key, qopts={}) => { | ||
if($?.[key]) return $[key] | ||
qopts = { connection: RedisConnectionDetails(), ...qopts } | ||
const $Queue = new Queue(key, qopts) | ||
const $QueueEvents = new QueueEvents($Queue.name, { connection: RedisConnectionDetails() } ) | ||
$[key] = { $Queue, $QueueEvents, Worker } | ||
return $[key] | ||
} | ||
|
||
export const BullMQ = { | ||
Queue, | ||
QueueEvents, | ||
Worker | ||
} | ||
|
||
export default { | ||
SyncQueue, | ||
TrawlQueue, | ||
NocapdQueue, | ||
RestApiQueue, | ||
QueueInit, | ||
BullMQ | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
import relaycache from '@nostrwatch/relaycache' | ||
import { capitalize, loadConfig } from "@nostrwatch/utils" | ||
|
||
const rcache = relaycache(process.env.NWCACHE_PATH) | ||
|
||
const config = await loadConfig() | ||
|
||
export class RetryManager { | ||
|
||
constructor(caller, action, relays) { | ||
if(!caller) throw new Error('caller is required') | ||
if(!action) throw new Error('action is required') | ||
this.caller = caller | ||
this.action = action | ||
this.relays = relays? relays : [] | ||
this.retries = [] | ||
this.config = config?.[caller]?.[action] | ||
} | ||
|
||
|
||
cacheId(url){ | ||
return `${capitalize(this.caller)}:${url}` | ||
} | ||
|
||
async init(){ | ||
const relays = this.relays.length? this.relays: await rcache.relays.get.all() | ||
const persisted = [] | ||
for await(const relay of relays) { | ||
const url = relay.url | ||
const retries = rcache.retry.get( this.cacheId(url) ) | ||
if(retries === null) | ||
persisted.push(await rcache.retry.set(this.cacheId(url), 0)) | ||
} | ||
return persisted | ||
} | ||
|
||
expiry(retries){ | ||
if(retries === null) return 0 | ||
let map | ||
if(this.config?.expiry && this.config.expiry instanceof Array ) | ||
map = this.config.expiry.map( entry => { return { max: entry.max, delay: parseInt(eval(entry.delay)) } } ) | ||
else | ||
map = [ | ||
{ max: 3, delay: 1000 * 60 * 60 }, | ||
{ max: 6, delay: 1000 * 60 * 60 * 24 }, | ||
{ max: 13, delay: 1000 * 60 * 60 * 24 * 7 }, | ||
{ max: 17, delay: 1000 * 60 * 60 * 24 * 28 }, | ||
{ max: 29, delay: 1000 * 60 * 60 * 24 * 90 } | ||
]; | ||
const found = map.find(entry => retries <= entry.max); | ||
return found ? found.delay : map[map.length - 1].delay; | ||
}; | ||
|
||
async getExpiredRelays(lastCheckedFn, relays=[]){ | ||
relays = relays?.length? relays: this.relays?.length? this.relays: await rcache.relays.get.all() | ||
if(!(lastCheckedFn instanceof Function)) throw new Error('lastCheckedFn (arg[1]) must be a function') | ||
const relayStatuses = await Promise.all(relays.map(async relay => { | ||
const url = relay.url; | ||
const lastChecked = rcache.cachetime.get.one(lastCheckedFn(url)) | ||
if (!lastChecked) return { relay, isExpired: true }; | ||
const retries = await rcache.retry.get(this.cacheId(url)); | ||
const isExpired = lastChecked < Date.now() - this.expiry(retries); | ||
return { relay, isExpired }; | ||
})); | ||
return relayStatuses.filter(r => r.isExpired).map(r => r.relay); | ||
} | ||
|
||
async getRetries( url ){ | ||
return await rcache.retry.get(this.cacheId(url)) | ||
} | ||
|
||
async setRetries( url, success ){ | ||
let id | ||
if(success) { | ||
this.log?.debug(`${url} did not require a retry`) | ||
id = await rcache.retry.set(this.cacheId(url), 0) | ||
} else { | ||
this.log?.debug(`${url} required a retry`) | ||
id = await rcache.retry.increment(this.cacheId(url)) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
import schedule from 'node-schedule' | ||
|
||
export class Scheduler { | ||
constructor(workers) { | ||
this.workers = workers; | ||
this.analysis = {}; | ||
this.schedules = {}; | ||
this.analyzeAndCacheWorkers(); | ||
this.createSchedules(); | ||
} | ||
|
||
analyzeAndCacheWorkers() { | ||
this.workers.sort((a, b) => a.interval - b.interval); | ||
const totalInterval = this.workers.reduce((sum, worker) => sum + worker.interval, 0); | ||
let cumulativeOffset = 0; | ||
this.workers.forEach(worker => { | ||
// console.log(worker) | ||
this.analysis[worker.name] = { | ||
interval: worker.interval, | ||
offset: this.calculateBestOffset(worker, cumulativeOffset, totalInterval), | ||
handler: worker.handler | ||
}; | ||
cumulativeOffset += this.analysis[worker.name].offset; | ||
}); | ||
} | ||
|
||
calculateBestOffset(worker, currentOffset, totalInterval) { | ||
// Calculate an ideal gap between tasks | ||
const idealGap = totalInterval / this.workers.length; | ||
// Start by proposing an offset that spaces out the tasks evenly | ||
let proposedOffset = currentOffset + idealGap; | ||
// Adjust the proposed offset to avoid as much overlap as possible | ||
// This loop tries to find a spot where the current task is least likely to collide with others | ||
while (this.isCollision(proposedOffset, worker.interval, totalInterval)) { | ||
proposedOffset = (proposedOffset + worker.interval) % totalInterval; | ||
} | ||
return proposedOffset % totalInterval; | ||
} | ||
|
||
isCollision(proposedOffset, interval, totalInterval) { | ||
// Check if the proposed offset collides with other tasks | ||
for (let otherWorkerName in this.analysis) { | ||
const otherWorker = this.analysis[otherWorkerName]; | ||
if (this.doIntervalsOverlap(proposedOffset, interval, otherWorker.offset, otherWorker.interval, totalInterval)) { | ||
return true; | ||
} | ||
} | ||
return false; | ||
} | ||
|
||
doIntervalsOverlap(start1, length1, start2, length2, totalLength) { | ||
// Simplified check for overlap between two intervals on a circular timeline | ||
const end1 = (start1 + length1) % totalLength; | ||
const end2 = (start2 + length2) % totalLength; | ||
if (start1 <= end1) { | ||
// Case 1: Interval 1 does not wrap around | ||
return (start2 < end1 && end2 > start1); | ||
} else { | ||
// Case 2: Interval 1 wraps around | ||
return (start2 < end1 || end2 > start1); | ||
} | ||
} | ||
|
||
|
||
createSchedules() { | ||
Object.keys(this.analysis).forEach(name => { | ||
const worker = this.analysis[name]; | ||
// Calculate the initial start time based on the current time and the offset | ||
const startTime = new Date(Date.now() + worker.offset); | ||
// Define the rule for scheduling | ||
const rule = new schedule.RecurrenceRule(); | ||
rule.start = startTime; // Set the start time | ||
rule.rule = `*/${Math.round(worker.interval / 1000)} * * * * *`; // Set the interval in seconds | ||
// Schedule the job | ||
this.schedules[name] = schedule.scheduleJob(rule, this.analysis[name].handler); | ||
}); | ||
} | ||
|
||
getAll() { | ||
return this.schedules; | ||
} | ||
|
||
get(name) { | ||
return this.schedules[name]; | ||
} | ||
|
||
gracefulShutdown() { | ||
Object.values(this.schedules).forEach(job => { | ||
schedule.gracefulShutdown(job); | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.