diff --git a/migrations/20261124120000_scenes_relations_sharing.js b/migrations/20261124120000_scenes_relations_sharing.js index 35574764..34eda16c 100644 --- a/migrations/20261124120000_scenes_relations_sharing.js +++ b/migrations/20261124120000_scenes_relations_sharing.js @@ -2,11 +2,11 @@ // sharing is a one-time copy through revisions, these only preselect the options in the relation dialog const shareDefaults = { rerelease: { actors: 'both', tags: 'both', duration: 'source' }, - variant: { actors: 'both', tags: 'both' }, remaster: { actors: 'source', tags: 'source' }, reedit: { actors: 'source', tags: 'source' }, bts: { actors: 'source' }, compilation: { actors: 'source' }, + // variant shares nothing by default }; exports.up = async function(knex) { diff --git a/seeds/00_tags.js b/seeds/00_tags.js index 0325cac7..85b59e68 100755 --- a/seeds/00_tags.js +++ b/seeds/00_tags.js @@ -3259,18 +3259,26 @@ const aliases = [ name: 'boobs - natural', for: 'natural-boobs', }, + { + name: 'boobs - small tits', + for: 'small-boobs', + }, { name: 'cumshot - facial', for: 'facial', }, { - name: 'ethnicity - caucasion', + name: 'ethnicity - caucasian', for: 'white', }, { name: 'boobs - fake', for: 'fake-tits', }, + { + name: 'cumshot - on pussy', + for: 'cum-on-pussy', + }, ]; const priorities = [ // higher index is higher priority diff --git a/seeds/09_manyvids.js b/seeds/09_manyvids.js index b2cd5624..8178309f 100644 --- a/seeds/09_manyvids.js +++ b/seeds/09_manyvids.js @@ -39,7 +39,7 @@ exports.seed = async function (knex) { .first(); if (!manyvidsNetwork) { - throw new Error('ManyVids found, did the network migration run?'); + throw new Error('ManyVids not found, did the network migration run?'); } const result = await knex('entities') diff --git a/src/app.js b/src/app.js index ee783c33..50199b33 100755 --- a/src/app.js +++ b/src/app.js @@ -5,20 +5,24 @@ const startTime = new Date(); const config = require('config'); const util = require('util'); const unprint = require('unprint'); -const log = require('why-is-node-running').default; const Inspector = require('inspector-api'); const fs = require('fs').promises; const { format, intervalToDuration } = require('date-fns'); const argv = require('./argv'); +// importing why-is-node-running enables an async hook that captures a stack trace for every async resource, only pay for that when asked +// required before the other modules, so it tracks the resources they create +const log = argv.logActive ? require('why-is-node-running').default : null; // eslint-disable-line global-require + const logger = require('./logger')(__filename); const knex = require('./knex'); const redis = require('./redis'); const fetchUpdates = require('./updates'); const { fetchScenes, fetchMovies } = require('./deep'); +const { streamScenes } = require('./stream'); const { storeScenes, storeMovies, associateMovieScenes } = require('./store-releases'); -const { updateSceneSearch, updateMovieSearch } = require('./update-search'); +const { updateSceneSearch, updateMovieSearch, refreshSearchViews } = require('./update-search'); const { scrapeActors, deleteActors, @@ -122,6 +126,23 @@ async function startMemorySample(snapshotTriggers = []) { }, config.memorySampling.sampleDuration); } +async function closeStep(name, fn, timeout) { + let timer; + + try { + await Promise.race([ + Promise.resolve().then(fn), + new Promise((resolve, reject) => { + timer = setTimeout(() => reject(new Error(`timed out after ${timeout / 1000}s`)), timeout); + }), + ]); + } catch (error) { + logger.warn(`Failed to close ${name}: ${error.message}`); + } finally { + clearTimeout(timer); + } +} + async function testProxy() { if (config.proxy.enable && argv.testProxy) { const res = await unprint.get(argv.testProxy, { useProxy: true }); @@ -145,10 +166,7 @@ async function init() { } if (argv.updateSearch) { - await Promise.all([ - updateSceneSearch(), - updateMovieSearch(), - ]); + await refreshSearchViews(); } if (argv.interpolateProfiles) { @@ -230,21 +248,26 @@ async function init() { const actors = (argv.actors || argv.actorsUpdate || argv.actorsFile) && await scrapeActors(actorNames); const actorBaseScenes = argv.actors && argv.actorScenes && actors.map((actor) => actor.scenes).flat().filter(Boolean); - const updateBaseScenes = (argv.latest || argv.upcoming || argv.channels || argv.networks || argv.movies) && await fetchUpdates(); - const scenesFromFile = argv.scenesFile && await getFileEntries(argv.scenesFile); const sceneUrls = (argv.scene || []).concat(scenesFromFile || []); - const deepScenes = argv.deep - ? await fetchScenes([...(sceneUrls), ...(updateBaseScenes || []), ...(actorBaseScenes || [])]) - : [...(updateBaseScenes || []), ...(actorBaseScenes || [])]; + // streamed scenes are stored as they go, only what the movie step needs comes back + const streamed = argv.stream ? await streamScenes([...sceneUrls, ...(actorBaseScenes || [])]) : null; - const storedScenes = argv.save ? await storeScenes(deepScenes) : []; + const updateBaseScenes = !argv.stream && (argv.latest || argv.upcoming || argv.channels || argv.networks || argv.movies) && await fetchUpdates(); + + const deepScenes = (!argv.stream && (argv.deep + ? await fetchScenes([...(sceneUrls), ...(updateBaseScenes || []), ...(actorBaseScenes || [])]) + : [...(updateBaseScenes || []), ...(actorBaseScenes || [])])) || []; + + const storedScenes = (argv.stream && streamed.movieScenes) || (argv.save ? await storeScenes(deepScenes) : []); const moviesFromFile = argv.moviesFile && await getFileEntries(argv.moviesFile); const movieUrls = (argv.movie || []).concat(moviesFromFile || []); - const sceneMovies = deepScenes && argv.sceneMovies ? deepScenes.filter((scene) => scene.movie).map((scene) => ({ ...scene.movie, entity: scene.entity })) : []; + const sceneMovies = argv.sceneMovies + ? (streamed?.movieScenes || deepScenes).filter((scene) => scene.movie).map((scene) => ({ ...scene.movie, entity: scene.entity })) + : []; const deepMovies = movieUrls.length > 0 || sceneMovies.length > 0 ? await fetchMovies([...movieUrls, ...sceneMovies]) : sceneMovies; const movieScenes = argv.movieScenes ? deepMovies.map((movie) => movie.scenes?.map((scene) => ({ ...scene, movie, entity: movie.entity }))).flat().filter(Boolean) : []; @@ -256,16 +279,20 @@ async function init() { } if (argv.save) { - const storedMovies = await storeMovies(deepMovies, storedScenes[0]?.batchId); - const storedMovieScenes = await storeScenes(deepMovieScenes, storedScenes[0]?.batchId); + const batchId = streamed?.batchId || storedScenes[0]?.batchId; + const storedMovies = await storeMovies(deepMovies, batchId); + const storedMovieScenes = await storeScenes(deepMovieScenes, batchId); const allScenes = [...storedScenes, ...storedMovieScenes]; await associateMovieScenes(storedMovies, allScenes); + // streamed scenes were already added to search as they were stored + const unsearchedScenes = argv.stream ? storedMovieScenes : allScenes; + // refreshing the materialized views is slow, skip when nothing was stored (e.g. --request) - if (allScenes.length > 0) { - await updateSceneSearch(allScenes.map((scene) => scene.id)); + if (unsearchedScenes.length > 0) { + await updateSceneSearch(unsearchedScenes.map((scene) => scene.id)); } if (storedMovies.length > 0) { @@ -280,17 +307,29 @@ async function init() { } catch (error) { console.trace(error); logger.error(error); + + process.exitCode = 1; } - await unprint.closeAllBrowsers(); - await unprint.closeAgents(); - - await waitForBiometrics(); - - knex.destroy(); - redis.destroy(); + // each step is time limited, a step that never resolves used to keep the later ones, including closing the database pool, from running at all + await closeStep('browsers', () => unprint.closeAllBrowsers(), 30_000); + await closeStep('agents', () => unprint.closeAgents(), 30_000); + await closeStep('biometrics', () => waitForBiometrics(), 600_000); // courtesy, but they need the database + await closeStep('database', () => knex.destroy(), 30_000); + await closeStep('redis', () => redis.destroy(), 10_000); done = true; + + // everything should be closed now, if something still keeps the process running, report it and exit anyway + setTimeout(() => { + logger.warn(`Process did not exit after closing, still active: ${process.getActiveResourcesInfo().join(', ')}${argv.logActive ? '' : ', use --log-active for details'}`); + + if (log) { + log({ error: (message) => logger.warn(message) }); + } + + process.exit(); + }, 10_000).unref(); // unref, so the timer itself doesn't keep the process running when everything else is closed } module.exports = init; diff --git a/src/argv.js b/src/argv.js index 33cd89ed..41a76971 100755 --- a/src/argv.js +++ b/src/argv.js @@ -145,6 +145,51 @@ const { argv } = yargs(hideBin(process.argv)) type: 'boolean', default: true, }) + .option('stream', { + describe: 'Deep scrape, store and fetch media for each scene as soon as it is listed, instead of finishing each stage for all scenes first', + type: 'boolean', + default: false, + }) + .option('stream-concurrency', { + describe: 'Maximum amount of scenes deep scraped in parallel when streaming', + type: 'number', + default: 5, + }) + .option('stream-channel-concurrency', { + describe: 'Maximum amount of scenes deep scraped in parallel per site when streaming', + type: 'number', + default: 1, + }) + .option('stream-pending', { + describe: 'Maximum amount of listed scenes queued for deep scraping when streaming, listing pauses when full', + type: 'number', + default: 100, + }) + .option('stream-store-size', { + describe: 'Amount of scenes stored at once when streaming', + type: 'number', + default: 20, + }) + .option('stream-store-interval', { + describe: 'Seconds before storing an incomplete group of scenes when streaming', + type: 'number', + default: 30, + }) + .option('stream-scene-timeout', { + describe: 'Seconds before giving up on deep scraping a scene and using its listing data when streaming', + type: 'number', + default: 300, + }) + .option('stream-search-interval', { + describe: 'Seconds between search updates when streaming', + type: 'number', + default: 300, + }) + .option('refresh-pre-data', { + describe: 'Recompute beforeFetchScenes data for every scene when streaming, to test scrapers don\'t rely on it staying the same', + type: 'boolean', + default: false, + }) .option('latest', { describe: 'Scrape latest releases if available', type: 'boolean', diff --git a/src/deep.js b/src/deep.js index d6af6a9d..da467bb7 100755 --- a/src/deep.js +++ b/src/deep.js @@ -249,6 +249,85 @@ async function scrapeReleases(baseReleases, entitiesByHostname, type) { ); } +function deepFreeze(value) { + if (value && typeof value === 'object' && !Object.isFrozen(value)) { + Object.freeze(value); + Object.values(value).forEach((child) => deepFreeze(child)); + } + + return value; +} + +// streaming counterpart of scrapeReleases, fetches one release at a time as stubs come in +// beforeFetchScenes data is a snapshot: it's cached per entity, recomputed when the scraper's beforeFetchScenesTtl (ms) expires or with --refresh-pre-data, +// and frozen, so scrapers can't keep state in it or rely on it being the same object for the entire run +function createReleaseFetcher(type = 'scene') { + const entitiesById = {}; + const entitiesByHostname = {}; + const preDataByEntityId = new Map(); + + async function addEntities(baseReleases) { + const fetchedEntitiesByHostname = await fetchReleaseEntities(baseReleases, { appendBySlug: false }); + + Object.assign(entitiesByHostname, fetchedEntitiesByHostname); + + [...Object.values(fetchedEntitiesByHostname), ...baseReleases.map((baseRelease) => baseRelease.entity)] + .filter(Boolean) + .forEach((entity) => { entitiesById[entity.id] = entity; }); + } + + async function getPreData(entity) { + if (!entity.scraper?.beforeFetchScenes) { + return null; + } + + const cached = preDataByEntityId.get(entity.id); + + if (cached && !argv.refreshPreData && (!cached.expiresAt || cached.expiresAt > Date.now())) { + return cached.promise; + } + + const ttl = entity.scraper.beforeFetchScenesTtl; + const promise = entity.scraper.beforeFetchScenes(entity, getRecursiveParameters(entity)).then((preData) => deepFreeze(preData)); + + preDataByEntityId.set(entity.id, { promise, expiresAt: ttl ? Date.now() + ttl : null }); + + promise.catch(() => { + // retry after a minute, rather than for every scene + preDataByEntityId.set(entity.id, { promise, expiresAt: Date.now() + 60_000 }); + }); + + return promise; + } + + async function fetchRelease(baseRelease) { + const entity = entitiesById[baseRelease.entity?.id] + || entitiesByHostname[urlToHostname(baseRelease.url)] + || baseRelease.entity; + + if (!entity || !shouldDeepScrape(baseRelease)) { + return scrapeRelease(baseRelease, { byId: entitiesById, byHostname: entitiesByHostname }, type); + } + + try { + const preData = await getPreData(entity); + const entityWithPreData = { ...entity, preData }; + + // the release may have been resolved by hostname, attach the entity so scrapeRelease uses the one with the pre-data + return await scrapeRelease({ ...baseRelease, entity: entityWithPreData }, { + byId: { [entity.id]: entityWithPreData }, + byHostname: {}, + }, type); + } catch (error) { + logger.error(`Failed to prepare deep scrape for ${baseRelease.url}: ${error.message}`); + + return baseRelease; + } + } + + return { addEntities, fetchRelease }; +} + async function fetchReleases(baseReleasesOrUrls, type = 'scene') { const baseReleases = toBaseReleases(baseReleasesOrUrls); const entitiesByHostname = await fetchReleaseEntities(baseReleases, { appendBySlug: false }); @@ -269,6 +348,7 @@ async function fetchMovies(baseReleasesOrUrls) { } module.exports = { + createReleaseFetcher, fetchReleases, fetchScenes, fetchMovies, diff --git a/src/stream.js b/src/stream.js new file mode 100644 index 00000000..c8593d58 --- /dev/null +++ b/src/stream.js @@ -0,0 +1,304 @@ +'use strict'; + +const util = require('util'); + +const argv = require('./argv'); +const logger = require('./logger')(__filename); +const knex = require('./knex'); +const fetchUpdates = require('./updates'); +const { createReleaseFetcher, toBaseReleases } = require('./deep'); +const { storeScenes } = require('./store-releases'); +const { updateSceneSearch } = require('./update-search'); +const { urlToHostname } = require('./entities'); + +// --stream: instead of listing everything, then deep scraping everything, then storing everything, each scene flows through on its own: +// listing (per channel, unchanged) → deep scrape pool (per scene) → store buffer → single store worker (small groups, incl. associations and media) → periodic search update +// memory stays bounded by backpressure, a failure only loses its own group, and media URLs are fetched minutes after they were scraped + +// resolves waiters whenever the pipeline state changes, until() re-checks its condition on every change +function createSignal() { + let waiters = []; + + function wait() { + return new Promise((resolve) => { waiters.push(resolve); }); + } + + return { + wake() { + const current = waiters; + + waiters = []; + current.forEach((resolve) => resolve()); + }, + async until(predicate) { + while (!predicate()) { + await wait(); // eslint-disable-line no-await-in-loop + } + }, + }; +} + +// per site rather than per channel entity, channels of one network often share a site +function getChannelKey(stub) { + return (stub.url && urlToHostname(stub.url)) || stub.entity?.id || 'unknown'; +} + +function createSceneStream({ batchId }) { + const options = { + concurrency: argv.streamConcurrency, + channelConcurrency: argv.streamChannelConcurrency, + maxPending: argv.streamPending, + storeSize: argv.streamStoreSize, + maxBuffered: argv.streamStoreSize * 2, + storeInterval: argv.streamStoreInterval * 1000, + sceneTimeout: argv.streamSceneTimeout * 1000, + searchInterval: argv.streamSearchInterval * 1000, + }; + + const fetcher = createReleaseFetcher('scene'); + const signal = createSignal(); + + const pending = []; + const buffer = []; + const activeByChannel = new Map(); + + const sceneIds = []; + const unsearchedIds = []; + const movieScenes = []; + const failed = []; + + let active = 0; + let added = 0; + let processed = 0; + let storing = false; + let storeTimer = null; + let lastSearch = Date.now(); + + async function updateSearch() { + const ids = unsearchedIds.splice(0); + + lastSearch = Date.now(); + + if (ids.length === 0) { + return; + } + + try { + await updateSceneSearch(ids); + } catch (error) { + logger.error(`Failed to update search for ${ids.length} scenes: ${error.message}`); + } + } + + async function storeGroup(group) { + if (argv.save) { + try { + const storedScenes = await storeScenes(group, batchId); + + storedScenes.forEach((scene) => { + sceneIds.push(scene.id); + unsearchedIds.push(scene.id); + + if (argv.sceneMovies && scene.movie) { + // only what movie association needs, not the full scene + movieScenes.push({ + id: scene.id, + entity: scene.entity, + movie: scene.movie, + sceneIndex: scene.sceneIndex, + batchId, + }); + } + }); + } catch (error) { + logger.error(`Failed to store ${group.length} scenes, continuing: ${error.message}`); + + if (argv.debug) { + console.trace(error); + } + + failed.push(...group.map((scene) => scene.url || `${scene.entity?.slug}:${scene.entryId}`)); + } + } + + processed += group.length; + + logger.info(`Streamed ${processed}/${added} scenes, ${pending.length} queued, ${active} fetching, ${buffer.length} waiting to be stored`); + + if (Date.now() - lastSearch > options.searchInterval) { + await updateSearch(); + } + } + + // single worker, so actor, series and media deduplication never race + async function runStore(flush = false) { + if (storing) { + return; + } + + storing = true; + clearTimeout(storeTimer); + storeTimer = null; + + while (buffer.length >= options.storeSize || (flush && buffer.length > 0)) { + const group = buffer.splice(0, options.storeSize); + + signal.wake(); + pump(); // eslint-disable-line no-use-before-define + await storeGroup(group); // eslint-disable-line no-await-in-loop + } + + storing = false; + signal.wake(); + + scheduleStore(); // eslint-disable-line no-use-before-define + } + + // store full groups right away, store a partial group once it's been waiting for the interval + function scheduleStore() { + if (storing) { + return; + } + + if (buffer.length >= options.storeSize) { + runStore(); + return; + } + + if (buffer.length > 0 && !storeTimer) { + storeTimer = setTimeout(() => runStore(true), options.storeInterval); + } + } + + async function fetchWithDeadline(stub) { + let timer; + + const deadline = new Promise((resolve) => { + timer = setTimeout(() => { + logger.warn(`Deep scrape timed out after ${options.sceneTimeout / 1000}s, using listing data for ${stub.url || stub.entryId}`); + resolve(stub); // like a failed deep scrape, the abandoned request may still finish in the background + }, options.sceneTimeout); + }); + + const fetch = fetcher.fetchRelease(stub).catch((error) => { + logger.error(`Deep scrape failed for ${stub.url}: ${error.message}`); + return stub; + }); + + try { + return await Promise.race([fetch, deadline]); + } finally { + clearTimeout(timer); + } + } + + async function fetchStub(stub, channelKey) { + const release = await fetchWithDeadline(stub); + + active -= 1; + activeByChannel.set(channelKey, activeByChannel.get(channelKey) - 1); + + if (release) { + if (argv.report) { + console.log(util.inspect(release, { depth: Infinity, colors: true })); + } + + buffer.push(release); + } else { + processed += 1; // dropped, e.g. no entry ID + } + + signal.wake(); + scheduleStore(); + pump(); // eslint-disable-line no-use-before-define + } + + // start fetching queued stubs while there's capacity, skipping channels that are at their own limit, so one slow site can't take every slot + function pump() { + while (active < options.concurrency && buffer.length < options.maxBuffered) { + const index = pending.findIndex((stub) => (activeByChannel.get(getChannelKey(stub)) || 0) < options.channelConcurrency); + + if (index === -1) { + return; + } + + const [stub] = pending.splice(index, 1); + const channelKey = getChannelKey(stub); + + active += 1; + activeByChannel.set(channelKey, (activeByChannel.get(channelKey) || 0) + 1); + + fetchStub(stub, channelKey); + signal.wake(); // room in the queue + } + } + + // resolves once the stubs are queued, not processed, so listing pauses while the queue is full + async function add(baseReleasesOrUrls) { + const stubs = toBaseReleases(baseReleasesOrUrls); + + if (stubs.length === 0) { + return; + } + + await fetcher.addEntities(stubs); + + await stubs.reduce(async (chain, stub) => { + await chain; + await signal.until(() => pending.length < options.maxPending); + + pending.push(stub); + added += 1; + + pump(); + }, Promise.resolve()); + } + + async function finish() { + await signal.until(() => pending.length === 0 && active === 0); + await signal.until(() => !storing); + await runStore(true); + await signal.until(() => !storing && buffer.length === 0); + + clearTimeout(storeTimer); + + await updateSearch(); + + logger.info(`Streamed ${processed} scenes, stored ${sceneIds.length}${failed.length > 0 ? `, failed to store ${failed.length}` : ''}`); + + if (failed.length > 0) { + logger.warn(`Failed to store:\n${failed.join('\n')}`); + } + + return { + sceneIds, + movieScenes, + failed, + }; + } + + return { add, finish }; +} + +async function streamScenes(baseScenes = []) { + const [{ id: batchId }] = argv.save + ? await knex('batches').insert({ showcased: argv.showcased, comment: null }).returning('id') + : [{ id: null }]; + + const stream = createSceneStream({ batchId }); + + await stream.add(baseScenes); + + if (argv.latest || argv.upcoming || argv.channels || argv.networks || argv.movies) { + await fetchUpdates((channelStubs) => stream.add(channelStubs)); + } + + const result = await stream.finish(); + + return { ...result, batchId }; +} + +module.exports = { + createSceneStream, + streamScenes, +}; diff --git a/src/update-search.js b/src/update-search.js index 01f74801..42a95fae 100644 --- a/src/update-search.js +++ b/src/update-search.js @@ -22,31 +22,34 @@ async function syncWeb(domain, ids) { } } +// traxxx-web refreshes the materialized views it needs (scenes_meta, movies_meta, actors_meta) before it indexes the queued items, so queueing them is enough +// keeps a slow full view refresh off the scraper's path async function updateSceneSearch(releaseIds) { - await knex.raw('REFRESH MATERIALIZED VIEW scenes_meta;'); - await knex.raw('REFRESH MATERIALIZED VIEW releases_summaries;'); - await syncWeb('scene', releaseIds); } -// queue scenes for resync without refreshing the materialized views, for changes the views don't depend on, e.g. actor genders +// kept for callers that queue scenes after changes the views don't depend on, e.g. actor genders, now the same as updateSceneSearch async function resyncSceneSearch(releaseIds) { await syncWeb('scene', releaseIds); } async function updateMovieSearch(releaseIds) { - await knex.raw('REFRESH MATERIALIZED VIEW movies_meta;'); - await syncWeb('movie', releaseIds); } async function updateActorSearch(actorIds) { - await knex.raw('REFRESH MATERIALIZED VIEW actors_meta;'); - await syncWeb('actor', actorIds); } +// manual full refresh, i.e. --update-search +async function refreshSearchViews() { + await knex.raw('REFRESH MATERIALIZED VIEW scenes_meta;'); + await knex.raw('REFRESH MATERIALIZED VIEW releases_summaries;'); + await knex.raw('REFRESH MATERIALIZED VIEW movies_meta;'); +} + module.exports = { + refreshSearchViews, updateSceneSearch, resyncSceneSearch, updateMovieSearch, diff --git a/src/updates.js b/src/updates.js index d3bed9ac..f27502f3 100755 --- a/src/updates.js +++ b/src/updates.js @@ -266,13 +266,18 @@ async function scrapeChannel(channelEntity, accNetworkReleases, beforeNetwork) { } } -async function scrapeNetworkSequential(networkEntity) { +async function scrapeNetworkSequential(networkEntity, onChannel) { const releases = await Promise.reduce( networkEntity.includedChildren, async (chain, channelEntity) => { const accNetworkReleases = await chain; const { uniqueReleases, duplicateReleases } = await scrapeChannel(channelEntity, accNetworkReleases); + if (onChannel) { + // the stubs are still accumulated, the next channel's listing may depend on them + await onChannel(uniqueReleases, channelEntity); + } + return { uniqueReleases: accNetworkReleases.uniqueReleases.concat(uniqueReleases), duplicateReleases: accNetworkReleases.duplicateReleases.concat(duplicateReleases), @@ -281,7 +286,7 @@ async function scrapeNetworkSequential(networkEntity) { Promise.resolve(emptyReleases), ); - return releases.uniqueReleases; + return onChannel ? [] : releases.uniqueReleases; } async function getBeforeNetwork(networkEntity) { @@ -297,7 +302,7 @@ async function getBeforeNetwork(networkEntity) { } } -async function scrapeNetworkParallel(networkEntity) { +async function scrapeNetworkParallel(networkEntity, onChannel) { const beforeNetwork = await getBeforeNetwork(networkEntity); return Promise.map( @@ -305,20 +310,28 @@ async function scrapeNetworkParallel(networkEntity) { async (channelEntity) => { const { uniqueReleases } = await scrapeChannel(channelEntity, null, beforeNetwork); + if (onChannel) { + await onChannel(uniqueReleases, channelEntity); + + return []; + } + return uniqueReleases; }, { concurrency: 3 }, ); } -async function fetchUpdates() { +// onChannel(uniqueReleases, channelEntity) receives each channel's stubs as soon as they're listed instead of returning them all at the end, +// listing the next channel waits until it resolves +async function fetchUpdates(onChannel) { const includedNetworks = await fetchIncludedEntities(); const scrapedNetworks = await Promise.map( includedNetworks, async (networkEntity) => (networkEntity.parameters?.sequential - ? scrapeNetworkSequential(networkEntity) - : scrapeNetworkParallel(networkEntity)), + ? scrapeNetworkSequential(networkEntity, onChannel) + : scrapeNetworkParallel(networkEntity, onChannel)), { concurrency: 5 }, );