-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathManager.ts
1907 lines (1733 loc) · 87.6 KB
/
Manager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Snoowrap, {WikiPage} from "snoowrap";
import {Logger} from "winston";
import {SubmissionCheck} from "../Check/SubmissionCheck";
import {CommentCheck} from "../Check/CommentCheck";
import {
asComment,
asSubmission,
cacheStats,
createRetryHandler,
determineNewResults,
findLastIndex,
formatNumber,
frequencyEqualOrLargerThanMin,
generateFullWikiUrl,
getActivityAuthorName,
isComment,
isSubmission,
likelyJson5,
mergeArr,
normalizeName,
parseRedditEntity,
pollingInfo,
resultsSummary,
sleep,
totalFromMapStats,
triggeredIndicator,
} from "../util";
import {ConfigBuilder, buildPollingOptions} from "../ConfigBuilder";
import {
ActionedEvent,
ActionResult,
ActivityDispatch,
CheckResult,
CheckSummary,
DEFAULT_POLLING_INTERVAL,
DEFAULT_POLLING_LIMIT,
LogInfo,
ManagerOptions,
ManagerStateChangeOption,
ManagerStats,
NotificationEventPayload,
PAUSED,
PollingOptionsStrong,
PostBehavior,
ActivitySourceData,
RUNNING,
RunResult,
STOPPED,
SYSTEM,
USER, RuleResult, DatabaseStatisticsOperatorConfig
} from "../Common/interfaces";
import {Submission, Comment, Subreddit} from 'snoowrap/dist/objects';
import {activityIsRemoved, ItemContent, itemContentPeek} from "../Utils/SnoowrapUtils";
import LoggedError from "../Utils/LoggedError";
import {
SubredditResources
} from "./SubredditResources";
import {SPoll, UnmoderatedStream, ModQueueStream, SubmissionStream, CommentStream} from "./Streams";
import EventEmitter from "events";
import ConfigParseError from "../Utils/ConfigParseError";
import dayjs, {Dayjs as DayjsObj} from "dayjs";
import Action from "../Action";
import {queue, QueueObject} from 'async';
import {SubredditConfigHydratedData, SubredditConfigData} from "../SubredditConfigData";
import NotificationManager from "../Notification/NotificationManager";
import {createHistoricalDisplayDefaults} from "../Common/defaults";
import {ExtendedSnoowrap} from "../Utils/SnoowrapClients";
import {
CMError,
definesSeriousError,
isRateLimitError,
isSeriousError,
isStatusError,
RunProcessingError, SimpleError
} from "../Utils/Errors";
import {ErrorWithCause, stackWithCauses} from "pony-cause";
import {Run} from "../Run";
import got from "got";
import {Bot as BotEntity} from "../Common/Entities/Bot";
import {ManagerEntity as ManagerEntity, RunningStateEntities} from "../Common/Entities/ManagerEntity";
import {isRuleSet} from "../Rule/RuleSet";
import {RuleResultEntity} from "../Common/Entities/RuleResultEntity";
import {RunResultEntity} from "../Common/Entities/RunResultEntity";
import {Repository} from "typeorm";
import {Activity} from "../Common/Entities/Activity";
import { AuthorEntity } from "../Common/Entities/AuthorEntity";
import {CMEvent} from "../Common/Entities/CMEvent";
import {nanoid} from "nanoid";
import {ActivitySourceEntity} from "../Common/Entities/ActivitySourceEntity";
import {InvokeeType} from "../Common/Entities/InvokeeType";
import {RunStateType} from "../Common/Entities/RunStateType";
import {EntityRunState} from "../Common/Entities/EntityRunState/EntityRunState";
import {
ActivitySourceValue,
EventRetentionPolicyRange,
Invokee, POLLING_COMMENTS, POLLING_MODQUEUE, POLLING_SUBMISSIONS, POLLING_UNMODERATED,
PollOn, pollOnTypes,
recordOutputTypes,
RunState
} from "../Common/Infrastructure/Atomic";
import {parseFromJsonOrYamlToObject} from "../Common/Config/ConfigUtil";
import {FilterCriteriaDefaults} from "../Common/Infrastructure/Filters/FilterShapes";
import {InfluxClient} from "../Common/Influx/InfluxClient";
import { Point } from "@influxdata/influxdb-client";
import {NormalizedManagerResponse} from "../Web/Common/interfaces";
import {guestEntityToApiGuest} from "../Common/Entities/Guest/GuestEntity";
import {BotResourcesManager} from "../Bot/ResourcesManager";
import {SubredditResourceConfig} from "../Common/Subreddit/SubredditResourceInterfaces";
import objectHash from "object-hash";
export interface RunningState {
state: RunState,
causedBy: Invokee
}
export type RunningStateTypes = 'managerState' | 'eventsState' | 'queueState';
export type RunningStates = {
[key in RunningStateTypes]: RunningState
}
export interface runCheckOptions {
checkNames?: string[],
delayUntil?: number,
dryRun?: boolean,
refresh?: boolean,
force?: boolean,
gotoContext?: string
maxGotoDepth?: number
source: ActivitySourceValue
initialGoto?: string
activitySource: ActivitySourceData
disableDispatchDelays?: boolean
}
export interface CheckTask {
activity: (Submission | Comment),
options: runCheckOptions
}
export interface RuntimeManagerOptions extends Omit<ManagerOptions, 'filterCriteriaDefaults'> {
sharedStreams?: PollOn[];
wikiLocation?: string;
botName?: string;
maxWorkers?: number;
maxGotoDepth?: number
botEntity: BotEntity
managerEntity: ManagerEntity
filterCriteriaDefaults?: FilterCriteriaDefaults
statDefaults: DatabaseStatisticsOperatorConfig
influxClients: InfluxClient[]
}
interface QueuedIdentifier {
id: string,
shouldRefresh: boolean
state: 'queued' | 'processing'
}
export class Manager extends EventEmitter implements RunningStates {
subreddit: Subreddit;
botEntity: BotEntity;
managerEntity: ManagerEntity;
client: ExtendedSnoowrap;
logger: Logger;
logs: LogInfo[] = [];
botName: string;
pollOptions: PollingOptionsStrong[] = [];
get submissionChecks() {
return this.runs.map(x => x.submissionChecks).flat();
}
get commentChecks() {
return this.runs.map(x => x.commentChecks).flat();
}
runs: Run[] = []
resources!: SubredditResources;
wikiLocation: string;
lastWikiRevision?: DayjsObj
lastWikiCheck: DayjsObj = dayjs();
wikiFormat: ('yaml' | 'json') = 'yaml';
filterCriteriaDefaults?: FilterCriteriaDefaults
postCheckBehaviorDefaults?: PostBehavior
statDefaults: DatabaseStatisticsOperatorConfig
retentionOverride?: EventRetentionPolicyRange
//wikiUpdateRunning: boolean = false;
streams: Map<string, SPoll<Snoowrap.Submission | Snoowrap.Comment>> = new Map();
sharedStreamCallbacks: Map<string, any> = new Map();
pollingRetryHandler: Function;
dryRun?: boolean;
sharedStreams: PollOn[];
cacheManager: BotResourcesManager;
globalDryRun?: boolean;
queue: QueueObject<CheckTask>;
// firehose is used to ensure all activities from different polling streams are unique
// that is -- if the same activities is in both modqueue and unmoderated we don't want to process the activity twice or use stale data
//
// so all activities get queued to firehose, it keeps track of items by id (using queuedItemsMeta)
// and ensures that if any activities are ingested while they are ALSO currently queued or working then they are properly handled by either
// 1) if queued, do not re-queue but instead tell worker to refresh before processing
// 2) if currently processing then re-queue but also refresh before processing
firehose: QueueObject<CheckTask>;
queuedItemsMeta: QueuedIdentifier[] = [];
globalMaxWorkers: number;
subMaxWorkers?: number;
maxGotoDepth: number;
displayLabel: string;
currentLabels: string[] = [];
startedAt?: DayjsObj;
validConfigLoaded: boolean = false;
lastParseConfigHash?: string;
eventsState: RunningState = {
state: STOPPED,
causedBy: SYSTEM
};
queueState: RunningState = {
state: STOPPED,
causedBy: SYSTEM
};
managerState: RunningState = {
state: STOPPED,
causedBy: SYSTEM
}
notificationManager: NotificationManager;
modPermissions?: string[]
// use by api nanny to slow event consumption
delayBy?: number;
eventsSample: number[] = [];
eventsSampleInterval: any;
eventsRollingAvg: number = 0;
rulesUniqueSample: number[] = [];
rulesUniqueSampleInterval: any;
rulesUniqueRollingAvg: number = 0;
modqueueInterval: number = 0;
delayedQueueInterval: any;
processEmitter: EventEmitter = new EventEmitter();
activityRepo!: Repository<Activity>;
authorRepo!: Repository<AuthorEntity>
eventRepo!: Repository<CMEvent>;
influxClients: InfluxClient[] = [];
getStats = async (): Promise<ManagerStats> => {
const data: any = {
eventsAvg: formatNumber(this.eventsRollingAvg),
rulesAvg: formatNumber(this.rulesUniqueRollingAvg),
historical: createHistoricalDisplayDefaults(),
cache: {
provider: 'none',
currentKeyCount: 0,
isShared: false,
totalRequests: 0,
totalMiss: 0,
missPercent: '0%',
requestRate: 0,
types: cacheStats()
},
};
if (this.resources !== undefined) {
const resStats = await this.resources.getStats();
data.historical = this.resources.getHistoricalDisplayStats();
data.cache = resStats.cache;
data.cache.currentKeyCount = await this.resources.getCacheKeyCount();
data.cache.isShared = this.resources.cache.isDefaultCache;
data.cache.provider = this.resources.cache.providerOptions.store;
}
return data;
}
getDelayedSummary = (): any[] => {
if(this.resources === undefined) {
return [];
}
return this.resources.delayedItems.map((x) => {
return {
id: x.id,
activityId: x.activity.name,
permalink: x.activity.permalink, // TODO construct this without having to fetch activity
submissionId: asComment(x.activity) ? x.activity.link_id : undefined,
author: x.author,
queuedAt: x.queuedAt.unix(),
duration: x.delay.asSeconds(),
source: `${x.action}${x.identifier !== undefined ? ` (${x.identifier})` : ''}`,
subreddit: this.subreddit.display_name_prefixed
}
});
}
getCurrentLabels = () => {
return this.currentLabels;
}
getDisplay = () => {
return this.displayLabel;
}
constructor(sub: Subreddit, client: ExtendedSnoowrap, logger: Logger, cacheManager: BotResourcesManager, opts: RuntimeManagerOptions) {
super();
const {
dryRun,
sharedStreams = [],
wikiLocation = 'botconfig/contextbot',
botName = 'ContextMod',
maxWorkers = 1,
maxGotoDepth = 1,
filterCriteriaDefaults,
postCheckBehaviorDefaults,
botEntity,
managerEntity,
statDefaults,
retention,
influxClients,
} = opts || {};
this.displayLabel = opts.nickname || `${sub.display_name_prefixed}`;
const getLabels = this.getCurrentLabels;
const getDisplay = this.getDisplay;
// dynamic default meta for winston feasible using function getters
// https://github.com/winstonjs/winston/issues/1626#issuecomment-531142958
this.logger = logger.child({
get labels() {
return getLabels()
},
get subreddit() {
return getDisplay()
}
}, mergeArr);
this.logger.stream().on('log', (log: LogInfo) => {
if(log.subreddit !== undefined && log.subreddit === this.getDisplay()) {
this.logs.unshift(log);
if(this.logs.length > 300) {
// remove all elements starting from the 300th index (301st item)
this.logs.splice(300);
}
}
});
this.globalDryRun = dryRun;
this.wikiLocation = wikiLocation;
this.filterCriteriaDefaults = filterCriteriaDefaults;
this.postCheckBehaviorDefaults = postCheckBehaviorDefaults;
this.statDefaults = statDefaults;
this.retentionOverride = retention;
this.sharedStreams = sharedStreams;
this.pollingRetryHandler = createRetryHandler({maxRequestRetry: 3, maxOtherRetry: 2}, this.logger);
this.subreddit = sub;
this.botEntity = botEntity;
for(const client of influxClients) {
this.influxClients.push(client.childClient(this.logger, {manager: this.displayLabel, subreddit: sub.display_name_prefixed}));
}
this.managerEntity = managerEntity;
// always init in stopped state but use last invokee to determine if we should start the manager automatically afterwards
this.eventsState = this.setInitialRunningState(managerEntity, 'eventsState');
this.queueState = this.setInitialRunningState(managerEntity, 'queueState');
this.managerState = this.setInitialRunningState(managerEntity, 'managerState');
this.client = client;
this.botName = botName;
this.maxGotoDepth = maxGotoDepth;
this.globalMaxWorkers = maxWorkers;
this.notificationManager = new NotificationManager(this.logger, this.subreddit, this.displayLabel, botName);
this.cacheManager = cacheManager;
this.queue = this.generateQueue(this.getMaxWorkers(this.globalMaxWorkers));
this.queue.pause();
this.firehose = this.generateFirehose();
this.logger.info(`Max GOTO Depth: ${this.maxGotoDepth}`);
this.eventsSampleInterval = setInterval((function(self) {
return function() {
const et = self.resources !== undefined ? self.resources.subredditStats.stats.historical.eventsCheckedTotal : 0;
const rollingSample = self.eventsSample.slice(0, 7)
rollingSample.unshift(et)
self.eventsSample = rollingSample;
const diff = self.eventsSample.reduceRight((acc: number[], curr, index) => {
if(self.eventsSample[index + 1] !== undefined) {
const d = curr - self.eventsSample[index + 1];
if(d === 0) {
return [...acc, 0];
}
return [...acc, d/10];
}
return acc;
}, []);
self.eventsRollingAvg = diff.reduce((acc, curr) => acc + curr,0) / diff.length;
//self.logger.debug(`Event Rolling Avg: ${formatNumber(self.eventsRollingAvg)}/s`);
}
})(this), 10000);
this.rulesUniqueSampleInterval = setInterval((function(self) {
return function() {
const rollingSample = self.rulesUniqueSample.slice(0, 7)
const rt = self.resources !== undefined ? self.resources.subredditStats.stats.historical.rulesRunTotal - self.resources.subredditStats.stats.historical.rulesCachedTotal : 0;
rollingSample.unshift(rt);
self.rulesUniqueSample = rollingSample;
const diff = self.rulesUniqueSample.reduceRight((acc: number[], curr, index) => {
if(self.rulesUniqueSample[index + 1] !== undefined) {
const d = curr - self.rulesUniqueSample[index + 1];
if(d === 0) {
return [...acc, 0];
}
return [...acc, d/10];
}
return acc;
}, []);
self.rulesUniqueRollingAvg = diff.reduce((acc, curr) => acc + curr,0) / diff.length;
//self.logger.debug(`Unique Rules Run Rolling Avg: ${formatNumber(self.rulesUniqueRollingAvg)}/s`);
}
})(this), 10000);
this.delayedQueueInterval = setInterval((function(self) {
return function() {
if(!self.queue.paused && self.resources !== undefined) {
let index = 0;
let anyQueued = false;
for(const ar of self.resources.delayedItems) {
if(ar.queuedAt.add(ar.delay).isSameOrBefore(dayjs())) {
anyQueued = true;
self.logger.info(`Activity ${ar.activity.name} dispatched at ${ar.queuedAt.format('HH:mm:ss z')} (delayed for ${ar.delay.humanize()}) is now being queued.`, {leaf: 'Delayed Activities'});
self.firehose.push({
activity: ar.activity,
options: {
refresh: true,
// @ts-ignore
source: ar.identifier === undefined ? ar.type : `${ar.type}:${ar.identifier}`,
initialGoto: ar.goto,
activitySource: {
id: ar.id,
queuedAt: ar.queuedAt,
delay: ar.delay,
action: ar.action,
goto: ar.goto,
identifier: ar.identifier,
type: ar.type
},
dryRun: ar.dryRun,
}
});
self.resources.removeDelayedActivity(ar.id);
}
index++;
}
if(!anyQueued) {
self.logger.debug('No Activities ready to queue', {leaf: 'Delayed Activities'});
}
}
}
})(this), 5000); // every 5 seconds
this.processEmitter.on('notify', (payload: NotificationEventPayload) => {
this.notificationManager.handle(payload.type, payload.title, payload.body, payload.causedBy, payload.logLevel);
});
// relay check/run errors to bot for retry metrics
this.processEmitter.on('error', err => this.emit('error', err));
}
public async getModPermissions(): Promise<string[]> {
if(this.modPermissions !== undefined) {
return this.modPermissions as string[];
}
this.logger.debug('Retrieving mod permissions for bot');
try {
const userInfo = parseRedditEntity(this.botName, 'user');
const mods = this.subreddit.getModerators({name: userInfo.name});
// @ts-ignore
this.modPermissions = mods[0].mod_permissions;
} catch (e) {
const err = new ErrorWithCause('Unable to retrieve moderator permissions', {cause: e});
this.logger.error(err);
return [];
}
return this.modPermissions as string[];
}
protected getMaxWorkers(subMaxWorkers?: number) {
let maxWorkers = this.globalMaxWorkers;
if (subMaxWorkers !== undefined) {
if (subMaxWorkers > maxWorkers) {
this.logger.warn(`Config specified ${subMaxWorkers} max queue workers but global max is set to ${this.globalMaxWorkers} -- will use global max`);
} else {
maxWorkers = subMaxWorkers;
}
}
if (maxWorkers < 1) {
this.logger.warn(`Max queue workers must be greater than or equal to 1, specified: ${maxWorkers}. Will use 1.`);
maxWorkers = 1;
}
return maxWorkers;
}
protected generateFirehose() {
return queue(async (task: CheckTask, cb) => {
// items in queuedItemsMeta will be processing FIFO so earlier elements (by index) are older
//
// if we insert the same item again because it is currently being processed AND THEN we get the item AGAIN we only want to update the newest meta
// so search the array backwards to get the neweset only
const queuedItemIndex = findLastIndex(this.queuedItemsMeta, x => x.id === task.activity.name);
if(queuedItemIndex !== -1) {
const itemMeta = this.queuedItemsMeta[queuedItemIndex];
let msg = `Item ${itemMeta.id} is already ${itemMeta.state}.`;
if(itemMeta.state === 'queued') {
this.logger.debug(`${msg} Flagging to refresh data before processing.`);
this.queuedItemsMeta.splice(queuedItemIndex, 1, {...itemMeta, shouldRefresh: true});
} else {
this.logger.debug(`${msg} Re-queuing item but will also refresh data before processing.`);
this.queuedItemsMeta.push({id: task.activity.name, shouldRefresh: true, state: 'queued'});
this.queue.push(task);
}
} else {
this.queuedItemsMeta.push({id: task.activity.name, shouldRefresh: false, state: 'queued'});
this.queue.push(task);
}
if(!task.options.source.includes('dispatch')) {
// check for delayed items to cancel
const existingDelayedToCancel = this.resources.delayedItems.filter(x => {
if (x.activity.name === task.activity.name) {
const {cancelIfQueued = false} = x;
if(cancelIfQueued === false) {
return false;
} else if (cancelIfQueued === true) {
return true;
} else {
const cancelFrom = !Array.isArray(cancelIfQueued) ? [cancelIfQueued] : cancelIfQueued;
return cancelFrom.map(x => x.toLowerCase()).includes(task.options.source.toLowerCase());
}
}
});
if(existingDelayedToCancel.length > 0) {
this.logger.debug(`Cancelling existing delayed activities due to activity being queued from non-dispatch sources: ${existingDelayedToCancel.map((x, index) => `[${index + 1}] Queued At ${x.queuedAt.format('YYYY-MM-DD HH:mm:ssZ')} for ${x.delay.humanize()}`).join(' ')}`);
const toCancelIds = existingDelayedToCancel.map(x => x.id);
for(const id of toCancelIds) {
await this.resources.removeDelayedActivity(id);
}
}
}
}
, 1);
}
protected generateQueue(maxWorkers: number) {
if (maxWorkers > 1) {
this.logger.warn(`Setting max queue workers above 1 (specified: ${maxWorkers}) may have detrimental effects to log readability and api usage. Consult the documentation before using this advanced/experimental feature.`);
}
const q = queue(async (task: CheckTask, cb) => {
if (this.delayBy !== undefined) {
this.logger.debug(`SOFT API LIMIT MODE: Delaying Event run by ${this.delayBy} seconds`);
await sleep(this.delayBy * 1000);
}
const queuedItemIndex = this.queuedItemsMeta.findIndex(x => x.id === task.activity.name);
try {
const itemMeta = this.queuedItemsMeta[queuedItemIndex];
this.queuedItemsMeta.splice(queuedItemIndex, 1, {...itemMeta, state: 'processing'});
await this.handleActivity(task.activity, {
refresh: itemMeta.shouldRefresh,
...task.options,
// use dryRun specified in task options if it exists (usually from manual user invocation or from dispatched action)
dryRun: task.options.dryRun ?? this.dryRun
});
} finally {
// always remove item meta regardless of success or failure since we are done with it meow
this.queuedItemsMeta.splice(queuedItemIndex, 1);
}
}
, maxWorkers);
q.error((err, task) => {
this.logger.error('Encountered unhandled error while processing Activity, processing stopped early');
this.logger.error(err);
});
q.drain(() => {
this.logger.debug('All queued activities have been processed.');
});
this.logger.info(`Generated new Queue with ${maxWorkers} max workers`);
return q;
}
public getCommentChecks() {
return this.runs.map(x => x.commentChecks);
}
public getSubmissionChecks() {
return this.runs.map(x => x.commentChecks);
}
async setResourceManager(config: Partial<SubredditResourceConfig> = {}) {
const {
footer,
logger = this.logger,
subreddit = this.subreddit,
caching,
credentials,
client = this.client,
botEntity = this.botEntity,
managerEntity = this.managerEntity,
statFrequency = this.statDefaults.minFrequency,
retention = this.retentionOverride,
} = config;
this.resources = await this.cacheManager.set(this.subreddit.display_name, {
footer: footer === undefined && this.resources !== undefined ? this.resources.footer : footer,
logger,
subreddit,
caching,
credentials,
client,
botEntity,
managerEntity,
statFrequency,
retention,
});
}
protected async parseConfigurationFromObject(configObj: object, suppressChangeEvent: boolean = false) {
try {
const configBuilder = new ConfigBuilder({logger: this.logger});
const validJson = configBuilder.validateJson(configObj);
const {
polling = [{pollOn: POLLING_SUBMISSIONS, limit: DEFAULT_POLLING_LIMIT, interval: DEFAULT_POLLING_INTERVAL}],
caching,
credentials,
dryRun,
footer,
nickname,
databaseStatistics: {
frequency = this.statDefaults.frequency,
} = {},
notifications,
retention,
queue: {
maxWorkers = undefined,
} = {},
} = validJson || {};
this.pollOptions = buildPollingOptions(polling);
this.dryRun = this.globalDryRun || dryRun;
this.displayLabel = nickname || `${this.subreddit.display_name_prefixed}`;
this.subMaxWorkers = maxWorkers;
const realMax = this.getMaxWorkers(this.subMaxWorkers);
if(realMax !== this.queue.concurrency) {
this.queue = this.generateQueue(realMax);
this.queue.pause();
}
this.logger.info(`Dry Run: ${this.dryRun === true}`);
for (const p of this.pollOptions) {
this.logger.info(`Polling Info => ${pollingInfo(p)}`)
}
this.notificationManager = new NotificationManager(this.logger, this.subreddit, this.displayLabel, this.botName, notifications);
const {events, notifiers} = this.notificationManager.getStats();
const notifierContent = notifiers.length === 0 ? 'None' : notifiers.join(', ');
const eventContent = events.length === 0 ? 'None' : events.join(', ');
this.logger.info(`Notification Info => Providers: ${notifierContent} | Events: ${eventContent}`);
let realStatFrequency = frequency;
if(realStatFrequency !== false && !frequencyEqualOrLargerThanMin(realStatFrequency, this.statDefaults.minFrequency)) {
this.logger.warn(`Specified database statistic frequency of '${realStatFrequency}' is shorter than minimum enforced by operator of '${this.statDefaults.minFrequency}' -- will fallback to '${this.statDefaults.minFrequency}'`);
realStatFrequency = this.statDefaults.minFrequency;
}
let resourceConfig: SubredditResourceConfig = {
footer,
logger: this.logger,
subreddit: this.subreddit,
caching,
credentials,
client: this.client,
botEntity: this.botEntity,
managerEntity: this.managerEntity,
statFrequency: realStatFrequency,
retention: this.retentionOverride ?? retention
};
await this.setResourceManager(resourceConfig);
this.resources.setLogger(this.logger);
if (footer !== undefined && this.resources !== undefined) {
this.resources.footer = footer;
}
this.logger.info('Subreddit-specific options updated');
this.logger.info('Building Runs and Checks...');
const hydratedConfig = await configBuilder.hydrateConfig(validJson, this.resources);
this.lastParseConfigHash = objectHash.sha1(hydratedConfig);
const structuredRuns = await configBuilder.parseToStructured(hydratedConfig, this.filterCriteriaDefaults, this.postCheckBehaviorDefaults);
let runs: Run[] = [];
// TODO check that bot has permissions for subreddit for all specified actions
// can find permissions in this.subreddit.mod_permissions
let index = 1;
for (const r of structuredRuns) {
const {name = `Run${index}`, ...rest} = r;
const run = new Run({
name,
...rest,
logger: this.logger,
resources: this.resources,
subredditName: this.subreddit.display_name,
client: this.client,
emitter: this.processEmitter,
});
runs.push(run);
index++;
}
// make sure run names are unique
const rNames: string[] = [];
for(const r of runs) {
if(rNames.includes(normalizeName(r.name))) {
throw new Error(`Rule names must be unique. Duplicate name detected: ${r.name}`);
}
rNames.push(normalizeName(r.name));
}
this.runs = runs;
const runSummary = `Found ${runs.length} Runs with ${this.submissionChecks.length + this.commentChecks.length} Checks`;
if(this.runs.length === 0) {
this.logger.warn(runSummary);
} else {
this.logger.info(runSummary);
}
const checkSummary = `Found Checks -- Submission: ${this.submissionChecks.length} | Comment: ${this.commentChecks.length}`;
if (this.submissionChecks.length === 0 && this.commentChecks.length === 0) {
this.logger.warn(checkSummary);
} else {
this.logger.info(checkSummary);
}
this.validConfigLoaded = true;
// make sure all db related stuff gets initialized
for (const r of this.runs) {
await r.initialize();
for (const c of r.submissionChecks) {
await c.initialize();
for (const ru of c.rules) {
if (isRuleSet(ru)) {
for (const rule of ru.rules) {
await rule.initialize();
}
} else {
await ru.initialize();
}
}
for (const a of c.actions) {
await a.initialize();
}
}
for (const c of r.commentChecks) {
await c.initialize();
for (const ru of c.rules) {
if (isRuleSet(ru)) {
for (const rule of ru.rules) {
await rule.initialize();
}
} else {
await ru.initialize();
}
}
for (const a of c.actions) {
await a.initialize();
}
}
}
if(this.eventsState.state === RUNNING) {
// need to update polling, potentially
await this.buildPolling();
for(const stream of this.streams.values()) {
if(!stream.running) {
this.logger.debug(`Starting Polling for ${stream.name.toUpperCase()} ${stream.frequency / 1000}s interval`);
stream.startInterval();
}
}
}
if(!suppressChangeEvent) {
this.emit('configChange');
}
} catch (err: any) {
this.validConfigLoaded = false;
throw err;
}
}
async parseConfiguration(causedBy: Invokee = 'system', force: boolean = false, options?: ManagerStateChangeOption) {
const {reason, suppressNotification = false, suppressChangeEvent = false} = options || {};
if(this.resources === undefined) {
await this.setResourceManager();
}
//this.wikiUpdateRunning = true;
this.lastWikiCheck = dayjs();
let wikiPageChanged = false;
try {
let sourceData: string;
let wiki: WikiPage;
try {
try {
const {val, wikiPage} = await this.resources.getWikiPage({wiki: this.wikiLocation}, {force: true});
wiki = wikiPage as WikiPage;
//sourceData = val as string;
} catch (err: any) {
if(err.cause !== undefined && isStatusError(err.cause) && err.cause.statusCode === 404) {
// try to create it
try {
wiki = await this.writeConfig('', 'Empty configuration created for ContextMod');
} catch (e: any) {
throw new CMError(`Parsing config from wiki page failed because ${err.message} AND creating empty page failed`, {cause: e});
}
} else {
throw new CMError('Reading config from wiki failed', {cause: err});
}
}
const revisionDate = dayjs.unix(wiki.revision_date);
if(this.lastWikiRevision !== undefined) {
if(this.lastWikiRevision.isSame(revisionDate)) {
this.logger.verbose('Config wiki has not changed since last check, going ahead with other checks...');
} else {
wikiPageChanged = true;
this.logger.info(`Updating config due to stale wiki page (${dayjs.duration(dayjs().diff(revisionDate)).humanize()} old)`)
}
} else {
this.logger.info('Trying to load (new?) config now since there is no valid config loaded');
}
this.lastWikiRevision = revisionDate;
sourceData = await wiki.content_md;
} catch (err: any) {
throw err;
}
if (sourceData.replace('\r\n', '').trim() === '') {
this.logger.error(`Wiki page contents is empty. The bot cannot run until this subreddit's wiki page has a valid config added!`);
throw new ConfigParseError(`Wiki page contents is empty. The bot cannot run until this subreddit's wiki page has a valid config added!`);
}
const [format, configObj, jsonErr, yamlErr] = parseFromJsonOrYamlToObject(sourceData);
this.wikiFormat = format;
if (configObj === undefined) {
this.logger.error(`Could not parse wiki page contents as JSON or YAML. Looks like it should be ${this.wikiFormat}?`);
if (this.wikiFormat === 'json') {
this.logger.error(jsonErr);
this.logger.error('Check DEBUG output for yaml error');
this.logger.debug(yamlErr);
} else {
this.logger.error(yamlErr);
this.logger.error('Check DEBUG output for json error');
this.logger.debug(jsonErr);
}
throw new ConfigParseError('Could not parse wiki page contents as JSON or YAML')
}
if (!wikiPageChanged && this.validConfigLoaded && this.lastParseConfigHash !== undefined && !force) {
// need to check if hydrated is different from current
const hydratedRuns = await this.buildHydratedRuns(configObj.toJS());
const hydratedHash = objectHash.sha1(hydratedRuns);
if (hydratedHash === this.lastParseConfigHash) {
this.logger.info('Config is up to date');
return false;
} else {
this.logger.info('Hydrated config differed from wiki contents, continuing with update.');
}
}
if(this.queueState.state === RUNNING) {
this.logger.verbose('Waiting for activity processing queue to pause before continuing config update');
await this.pauseQueue(causedBy);
}
await this.parseConfigurationFromObject(configObj.toJS(), suppressChangeEvent);
this.logger.info('Checks updated');
if(!suppressNotification) {
this.notificationManager.handle('configUpdated', 'Configuration Updated', reason, causedBy)
}
return true;
} catch (err: any) {
if(this.resources === undefined) {
// if we fail to get a valid config and there is no existing resource then just create a default one
// -- also ensures that if one already exists we don't overwrite it
await this.setResourceManager()
}
this.validConfigLoaded = false;
throw new ErrorWithCause('Failed to parse subreddit configuration', {cause: err});
}
}
async buildHydratedRuns(configObj: object) {
const configBuilder = new ConfigBuilder({logger: this.logger});
const validJson = configBuilder.validateJson(configObj);
return await configBuilder.hydrateConfig(validJson, this.resources);
}
async handleActivity(activity: (Submission | Comment), options: runCheckOptions): Promise<void> {
const checkType = isSubmission(activity) ? 'Submission' : 'Comment';
let item = activity,
runtimeShouldRefresh = false;
const {
delayUntil,
refresh = false,
initialGoto = '',
activitySource,
force = false,
} = options;
const event = new CMEvent();
if(refresh) {
this.logger.verbose(`Refreshed data`);
// @ts-ignore
item = await activity.refresh();
}
let activityEntity: Activity;
const existingEntity = await this.activityRepo.findOneBy({_id: item.name});
/**
* Report Tracking
*
* Store ids for activities we process. Enables us to be sure of whether modqueue has been monitored since we've last seen the activity
*
* */
let lastKnownStateTimestamp = await this.resources.getActivityLastSeenDate(item.name);
if(lastKnownStateTimestamp !== undefined && lastKnownStateTimestamp.isBefore(this.startedAt)) {
// if we last saw this activity BEFORE we started event polling (modqueue) then it's not useful to us
lastKnownStateTimestamp = undefined;
}
await this.resources.setActivityLastSeenDate(item.name);
// if modqueue is running then we know we are checking for new reports every X seconds
if(options.activitySource.identifier === POLLING_MODQUEUE) {
// if the activity is from modqueue and only has one report then we know that report was just created
if(item.num_reports === 1
// otherwise if it has more than one report AND we have seen it (its only seen if it has already been stored (in below block))
// then we are reasonably sure that any reports created were in the last X seconds
|| (item.num_reports > 1 && lastKnownStateTimestamp !== undefined)) {
lastKnownStateTimestamp = dayjs().subtract(this.modqueueInterval, 'seconds');
}
}
// if activity is not from modqueue then known good timestamps for "time between last known report and now" is dependent on these things:
// 1) (most accurate) lastKnownStateTimestamp -- only available if activity either had 0 reports OR 1+ and existing reports have been stored (see below code)
// 2) last stored report time from Activity
// 3) create date of activity
let shouldPersistReports = false;
if (existingEntity === null) {
activityEntity = Activity.fromSnoowrapActivity(this.managerEntity.subreddit, activity, lastKnownStateTimestamp);
// always persist if activity is not already persisted and any reports exist
if (item.num_reports > 0) {
shouldPersistReports = true;
}
} else {
activityEntity = existingEntity;
// always persist if reports need to be updated
if (activityEntity.syncReports(item, lastKnownStateTimestamp)) {
shouldPersistReports = true;
}
}
if (shouldPersistReports) {
activityEntity = await this.activityRepo.save(activityEntity);
}
const itemId = await item.id;
if(await this.resources.hasRecentSelf(item)) {
let recentMsg = `Found in Activities recently (last ${this.resources.ttl.selfTTL} seconds) modified/created by this bot`;
if(force) {
this.logger.debug(`${recentMsg} but will run anyway because "force" option was true.`);