Skip to content

Commit cc8e02d

Browse files
authored
Merge pull request #431 from mayeaux/caching-update
Caching update
2 parents 4ae2116 + 06a2514 commit cc8e02d

File tree

5 files changed

+81
-29
lines changed

5 files changed

+81
-29
lines changed

caching/cachePopularUploads.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const Promise = require('bluebird');
22
const _ = require('lodash');
33
const View = require('../models/index').View;
44
const Upload = require('../models/index').Upload;
5+
const moment = require('moment');
56

67
const c = {
78
l : console.log
@@ -22,11 +23,11 @@ const logCaching = process.env.LOG_CACHING;
2223
async function getPopularUploads(){
2324

2425
if(logCaching == 'true'){
25-
c.l('Getting popular uploads');
26+
c.l('Beginning caching popular uploads, getting popular uploads from db');
27+
console.log(moment(new Date).format('hh:mm:ss A'))
2628
}
2729

2830
// TODO: have to have a job to update upload's view amounts
29-
3031
// TODO: have to build 4 arrays of ~1000
3132

3233
const searchQuery = {
@@ -37,14 +38,14 @@ async function getPopularUploads(){
3738
category : { $exists: true }
3839
};
3940

40-
const selectString = 'formattedDuration rating title views checkedViews uploader fileType thumbnailUrl ' +
41+
const selectString = 'formattedDuration rating title uploader fileType thumbnailUrl ' +
4142
'uploadUrl uniqueTag customThumbnailUrl fileExtension thumbnails reacts uncurated category subcategory description';
4243

4344
let popularUploads = await Upload.find(searchQuery).select(selectString).populate('uploader reacts')
4445
.lean();
4546

4647
if(logCaching == 'true'){
47-
c.l('Uploads received from database');
48+
c.l('Uploads received from database for popular calculating');
4849

4950
c.l(popularUploads.length);
5051
}
@@ -60,20 +61,19 @@ async function setPopularUploads(){
6061
return upload.uploader;
6162
});
6263

63-
// calculate view periods for each upload
64+
let formattedPopularUploads = [];
6465

65-
// TODO: why this promise all functionality? this is almost surely what's blowing everything up
66-
popularUploads = await Promise.all(popularUploads.map(async function(upload){
66+
console.log(moment(new Date).format('hh:mm:ss A'))
6767

68-
// get all valid views per upload
69-
const uploadViews = await View.find({ upload, validity: 'real' }).select('createdAt');
68+
for(const upload of popularUploads){
69+
const uploadViews = await View.find({ upload, validity: 'real' }).select('createdAt')
7070

71-
// calculate their views per period (last24h, lastweek)
72-
return calculateViewsByPeriod(upload, uploadViews);
73-
}));
71+
formattedPopularUploads.push(calculateViewsByPeriod(upload, uploadViews));
72+
}
7473

7574
if(logCaching == 'true'){
7675
c.l('Popular uploads have been calculated according to view periods');
76+
console.log(moment(new Date).format('hh:mm:ss A'))
7777
}
7878

7979
// build json objects representing uploads

caching/cacheRecentUploads.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ const _ = require('lodash');
33
const View = require('../models/index').View;
44
const Upload = require('../models/index').Upload;
55
const categories = require('../config/categories');
6+
const moment = require('moment');
67

78
const javascriptTimeAgo = require('javascript-time-ago');
89
javascriptTimeAgo.locale(require('javascript-time-ago/locales/en'));
@@ -21,12 +22,17 @@ const logCaching = process.env.LOG_CACHING;
2122
/** Get all recent uploads from the database per category and concat them **/
2223
async function getRecentUploads(){
2324

25+
if(logCaching == 'true'){
26+
console.log(`Beginning running recent uploads`);
27+
28+
}
29+
2430
let recentUploadsAllCategories = [];
2531

2632
for(const category of categories){
2733

2834
if(logCaching == 'true'){
29-
console.log(`Getting uploads for category: ${category.name}`);
35+
console.log(`Getting recent uploads for category: ${category.name}`);
3036
}
3137

3238
const searchQuery = {
@@ -61,6 +67,9 @@ async function getRecentUploads(){
6167
async function setRecentUploads(){
6268
let recentUploads = await getRecentUploads();
6369

70+
console.log(`Calculating view amounts`);
71+
console.log(moment(new Date).format('hh:mm:ss A'))
72+
6473
// calculate view periods for each upload
6574
recentUploads = await Promise.all(recentUploads.map(async function(upload){
6675

caching/calculateUploadViews.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const Promise = require('bluebird');
22
const _ = require('lodash');
33
const View = require('../models/index').View;
44
const Upload = require('../models/index').Upload;
5+
const moment = require('moment');
56

67
const c = {
78
l : console.log
@@ -22,7 +23,8 @@ const logCaching = process.env.LOG_CACHING;
2223
async function calculateViewAmounts(){
2324

2425
if(logCaching == 'true'){
25-
c.l('Getting popular uploads');
26+
c.l('Calculating view amounts for particular videos');
27+
console.log(moment(new Date).format('hh:mm:ss A'))
2628
}
2729

2830
// TODO: have to have a job to update upload's view amounts
@@ -40,13 +42,18 @@ async function calculateViewAmounts(){
4042
for(const upload of uploads){
4143
const amountOfViews = await View.countDocuments({ upload: upload.id, validity: 'real' });
4244

43-
console.log(upload.views);
45+
// console.log(upload.views);
4446

4547
upload.views = amountOfViews;
4648

4749
await upload.save();
4850
}
4951

52+
if(logCaching == 'true'){
53+
c.l('View amounts calculated');
54+
console.log(moment(new Date).format('hh:mm:ss A'))
55+
}
56+
5057
// if(logCaching == 'true'){
5158
// c.l('Uploads received from database');
5259
//

caching/helpers.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ var dayAgo = moment().subtract(24, 'hours').toDate();
5252
var hourAgo = moment().subtract(1, 'hours').toDate();
5353
var minuteAgo = moment().subtract(1, 'minutes').toDate();
5454

55-
async function calculateViewsByPeriod(upload, uploadViews){
55+
function calculateViewsByPeriod(upload, uploadViews){
5656
upload.viewsAllTime = uploadViews.length;
5757

5858
uploadViews = _.filter(uploadViews, function(uploadView){ return uploadView.createdAt > monthAgo; });
@@ -76,4 +76,4 @@ async function calculateViewsByPeriod(upload, uploadViews){
7676
module.exports = {
7777
calculateViewsByPeriod,
7878
buildObjects
79-
};
79+
};

caching/runCaching.js

Lines changed: 48 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,16 @@
11
const mongoose = require('mongoose');
22
const dotenv = require('dotenv');
3-
43
const logCaching = process.env.LOG_CACHING;
4+
const jsHelpers = require('../lib/helpers/js-helpers');
5+
6+
function sleep(ms) {
7+
return new Promise(resolve => setTimeout(resolve, ms));
8+
}
9+
10+
/** FOR FINDING ERRANT LOGS **/
11+
if(process.env.SHOW_LOG_LOCATION == 'true' || 1 == 2){
12+
jsHelpers.showLogLocation();
13+
}
514

615
process.on('uncaughtException', (err) => {
716
console.log('Uncaught Exception: ', err);
@@ -51,13 +60,11 @@ console.log(`CACHING IS RUNNING AGAINST: ${database} \n`);
5160

5261
const setCache = require('./setCache'); // index and daily stats
5362

63+
// functions to run caching jobs
5464
const cacheRecentUploads = require('./cacheRecentUploads'); // index and daily stats
5565
const cachePopularUploads = require('./cachePopularUploads'); // index and daily stats
56-
5766
const calculateUploadViews = require('./calculateUploadViews'); // index and daily stats
5867

59-
// const cacheRecentUploads = require('./cacheRecentAndPopularUploads');
60-
6168
async function cacheOnlyRecentUploads(){
6269

6370
try {
@@ -73,6 +80,7 @@ async function cacheOnlyRecentUploads(){
7380
async function cachePopularDailyStatsAndIndex(){
7481
try {
7582
await cachePopularUploads();
83+
await calculateUploadViews();
7684
await setCache.setDailyStats();
7785
await setCache.setIndexValues();
7886

@@ -95,24 +103,52 @@ const cacheIntervalInMs = cacheIntervalInMinutes * ( 1000 * 60 );
95103

96104
console.log(`CACHE POPULAR, DAILY STATS AND INDEXES INTERVAL IN MINUTES: ${cacheIntervalInMinutes} \n`);
97105

98-
async function main(){
106+
let cacheTotalViewsInterval = parseInt(process.env.CACHE_TOTAL_VIEW_INTERVAL) || 6;
99107

100-
setInterval(cacheOnlyRecentUploads, cacheRecentIntervalInMs);
108+
const cacheTotalViewsIntervalInMs = cacheTotalViewsInterval * ( 1000 * 60 );
101109

102-
setInterval(cachePopularDailyStatsAndIndex, cacheIntervalInMs);
110+
console.log(`CACHE TOTAL VIEW INTERVAL IN MINUTES: ${cacheIntervalInMinutes} \n`);
103111

104-
setInterval(calculateUploadViews, cacheIntervalInMs);
112+
// TODO: there is a bug here, where when times line up, they will run multiple jobs at once,
113+
// TODO: ideally, they should push into an array, run the most recent job in array, then delete it from array,
114+
// TODO: and run them sequentially
105115

116+
async function runRecentInterval(){
106117
// calculate and cache recent uploads every minute
107118
await cacheOnlyRecentUploads();
119+
await sleep(cacheRecentIntervalInMs)
120+
runRecentInterval();
121+
}
108122

109-
await cachePopularDailyStatsAndIndex();
110-
111-
await calculateUploadViews();
123+
runRecentInterval();
112124

125+
async function runOtherCaching(){
126+
await cachePopularDailyStatsAndIndex();
127+
await sleep(cacheIntervalInMs)
128+
runOtherCaching()
113129
}
114130

115-
main();
131+
runOtherCaching()
132+
133+
// async function main(){
134+
//
135+
// // setInterval(cacheOnlyRecentUploads, cacheRecentIntervalInMs);
136+
// //
137+
// // setInterval(cachePopularDailyStatsAndIndex, cacheIntervalInMs);
138+
// //
139+
// // // calculate total amount of views for channel display
140+
// // // TODO: couldn't this just be done during popular? maybe not because it doesn't do for sensitive?
141+
// // // TODO: then just do a separate job for
142+
// // setInterval(calculateUploadViews, cacheTotalViewsIntervalInMs);
143+
//
144+
// // calculate and cache recent uploads every minute
145+
// // await cacheOnlyRecentUploads();
146+
//
147+
// // also does total view amounts
148+
// await cachePopularDailyStatsAndIndex();
149+
// }
150+
151+
// main();
116152

117153
// calculateUploadViews()
118154

0 commit comments

Comments
 (0)