-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1066 lines (950 loc) · 33.5 KB
/
index.js
File metadata and controls
1066 lines (950 loc) · 33.5 KB
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
/*
`
./oso-
`oyyhhs++/.`
`ohddyo/:o+++::.` `.--.`
:hyo+/ooo+++++++/. `sdmmddy-
++o+/+ooyosoossos+``/++ossyys/` `-/syyyyy-
-sssyysos++ssysoyh+dNNNNNNNNNmd- `++++++/:.
+ssyhy/+ooos+ooyhyhNNNNNNNNNNNm` /oydddhs/
`oyyyyyysss+oossshyNNNNNNNNNNNm` -+shmNNmmmmd`.
-syyyhhhhs+++osyhhdMNNNNNNNNNd+/:+dmmNNNNNmmmmdsdy/
`+yyhhhhhoo+ooosyyyNNNNNNNNNNNNNNNNNNNNNNNmmmmdyddd:
-syhhhhhhoossosssdNNNNNNNNNNNNNNmNmmNNNNNmmmmNdyshhs+-`
oyhhhhhyso+yhhmhhMMNNNNNNNNNNNNNNNmNNNNNmNmmNmhhhdddhs+`
`yyhhhhyysyhhydhhyNMMNNNNMNNNNNNNNNNNNNNNmNmmmmdhdyydhys-
`yyhhhhdmdhdhhdhhyNMMMMMMMMMMNNNNNMNNNNNmmmmmmmmddhhyso+-
+yyhhmNNNmmNNNdosNMMMMMMMMMMNNNNNMNNNNNNmmmmmmmmhysoo+/.
`/ydmNNNNNNNNmdyhMMMMMMNNMMMMMNNMMNNNNNmmmmmmmmdyysso+-
`syysssydmNNmmshMMMMMMMMMMMMMNNNNNNNNNmmNNdydmhhyyso-
:o::////+oomNNdmMMMMMMMMMMMMNNNNMMNNNhhdmN+:/mdhhys:
`-----::::::::/+oyNMNNMMMMMMMMMMMMNNNMMMmsyo+/+ys:-/ysdhs.
`.----::/:/:::::+sNMMMMMMMMMNNNNNNNNNNNMNdyoo+/:/:--:/hh+
``.-:////::/::smMMMMMMMMNNNNNmsyNNNNNNNNmyoo//+oydmhy-
`-::::://///+s/::/hMNNNNNNNNNNNmyodNNNNNNNMNmmmNNNNNmh+
`---.``-::-:dmdhs++NNNNNmmNNNNNNmysNNNNNNNNMMNNNNNNNmy`
.::-`:mmmmmNNNMMNdsdhyssssyhsdmmNNNNNMMNNNNNNNm-
`-:.` :dmmmmNNNMMd/:/+sysys/::ymmmNNNNMMNNNNNNmh`
.hddmmmNNNNs:smmdhyhmmh+:hmmmNNNNNNNNNNNm+
oddmmNNNNo/dNmyhhyhhmNms:hNmNNNNNNNNNNNh`
.hdmmdhdo:syso:+/:/:ohdmo/hhmmNmmmmdmNm-
/dmy/++--.---:..-.::---::/+/ymmdddmNmo
`sh:+oo..----:-.--//:----oo+:ymhosyy.
.::+oh-.-/-/:-..-++-::-+yo+/:+.
`.oydmh:-:/y+:..+:yo/-:dhy+.`
.ymNNmy/:+ss+/yso+:+dy/.
`odmmmmmdhyhhsyyyo+.
:hdddmdddhyo/.
`/o+/-.`
*/
//*******************************************************************
import numberstring, { comma } from 'numberstring';
import express from 'express';
import exphbs from 'express-handlebars';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import compression from 'compression';
import timeout from 'connect-timeout';
import axios from 'axios';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, ScanCommand, PutCommand } from '@aws-sdk/lib-dynamodb';
import { TwitterApi } from 'twitter-api-v2';
import NodeCache from 'node-cache';
import dotenv from 'dotenv';
dotenv.config();
//*******************************************************************
// Simple Logger for App Runner/CloudWatch
// App Runner automatically captures stdout/stderr to CloudWatch Logs
//*******************************************************************
/**
* Sanitizes data to prevent logging sensitive information
* @param {*} data - Data to sanitize
* @returns {*} Sanitized data
*/
function sanitizeData(data) {
if (!data) return data;
const sensitiveKeys = ['password', 'secret', 'key', 'token', 'credential', 'accessKey', 'secretAccessKey', 'authorization'];
if (typeof data === 'object') {
const sanitized = Array.isArray(data) ? [] : {};
for (const [key, value] of Object.entries(data)) {
const lowerKey = String(key).toLowerCase();
if (sensitiveKeys.some(sensitive => lowerKey.includes(sensitive))) {
sanitized[key] = '[REDACTED]';
} else if (typeof value === 'object' && value !== null) {
sanitized[key] = sanitizeData(value);
} else {
sanitized[key] = value;
}
}
return sanitized;
}
return data;
}
/**
* Simple logger that uses console.log/error for App Runner/CloudWatch compatibility
* All logs go to stdout/stderr which App Runner automatically captures
*/
const logger = {
info: (message, data) => {
const timestamp = new Date().toISOString();
if (data) {
console.log(`[INFO] [${timestamp}] ${message}`, JSON.stringify(sanitizeData(data)));
} else {
console.log(`[INFO] [${timestamp}] ${message}`);
}
},
error: (message, data) => {
const timestamp = new Date().toISOString();
if (data) {
console.error(`[ERROR] [${timestamp}] ${message}`, JSON.stringify(sanitizeData(data)));
} else {
console.error(`[ERROR] [${timestamp}] ${message}`);
}
},
warn: (message, data) => {
const timestamp = new Date().toISOString();
if (data) {
console.warn(`[WARN] [${timestamp}] ${message}`, JSON.stringify(sanitizeData(data)));
} else {
console.warn(`[WARN] [${timestamp}] ${message}`);
}
},
debug: (message, data) => {
const timestamp = new Date().toISOString();
if (data) {
console.log(`[DEBUG] [${timestamp}] ${message}`, JSON.stringify(sanitizeData(data)));
} else {
console.log(`[DEBUG] [${timestamp}] ${message}`);
}
}
};
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
const errorInfo = reason instanceof Error
? { message: reason.message, name: reason.name, stack: reason.stack }
: { reason: String(reason) };
logger.error('Unhandled Promise Rejection', sanitizeData(errorInfo));
// Don't exit - allow server to continue running
});
//*******************************************************************
// Configuration Constants
//*******************************************************************
// Environment-specific configuration
const env = process.env.NODE_ENV || 'development';
const CONFIG = {
AWS: {
REGION: process.env.AWS_REGION || 'us-east-1',
TABLE_NAME: process.env.DYNAMODB_TABLE || 'voncountdown',
},
APP: {
PORT: process.env.PORT || 8080,
START_NUMBER: 1111373357579,
ENV: env,
},
COUNTDOWN: {
DELAY_MIN_MS: 1234567, // ~14 days
DELAY_MAX_MS: 7654321, // ~88 days
PHRASE_PROBABILITY: 4, // 1 in 5 chance (when random(0,4) === 4)
ERROR_RETRY_DELAY_MS: 60000, // 1 minute
},
BADGE: {
ALLOWED_DOMAIN: 'img.shields.io',
},
CACHE: {
TTL: env === 'production' ? 300 : 60, // 5 min in prod, 1 min in dev
},
};
//*******************************************************************
// Environment Variable Validation
//*******************************************************************
const requiredEnvVars = [
'AWS_ACCESS_KEY_ID',
'AWS_SECRET_ACCESS_KEY',
'TWITTER_API_KEY',
'TWITTER_API_SECRET',
'TWITTER_ACCESS_TOKEN',
'TWITTER_ACCESS_TOKEN_SECRET',
];
logger.info('Starting application initialization');
logger.info('Environment check', { nodeEnv: process.env.NODE_ENV, port: CONFIG.APP.PORT });
requiredEnvVars.forEach(varName => {
if (!process.env[varName]) {
logger.error(`Missing required environment variable: ${varName}`);
process.exit(1);
}
});
logger.info('All required environment variables present');
//*******************************************************************
// AWS DynamoDB Client Setup
//*******************************************************************
logger.info('Initializing AWS DynamoDB client', {
region: CONFIG.AWS.REGION,
tableName: CONFIG.AWS.TABLE_NAME
});
// Try to use default credential provider chain first (for local development)
// Falls back to explicit credentials if AWS_PROFILE or other chain providers aren't available
let credentials;
if (process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY) {
credentials = {
accessKeyId: process.env.AWS_ACCESS_KEY_ID.trim(),
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY.trim(),
};
logger.info('Using explicit AWS credentials from environment variables');
} else {
logger.info('No explicit credentials found, using default credential provider chain');
credentials = undefined; // Let AWS SDK use default credential chain
}
const client = new DynamoDBClient({
region: CONFIG.AWS.REGION,
...(credentials && { credentials }), // Only set credentials if provided
maxAttempts: 5, // Retry up to 5 times
retryMode: 'adaptive', // Use adaptive retry mode for throttling
});
const docClient = DynamoDBDocumentClient.from(client);
logger.info('DynamoDB client initialized successfully');
//*******************************************************************
// Twitter API Client Setup
//*******************************************************************
logger.info('Initializing Twitter API client');
const twitterClient = new TwitterApi({
appKey: process.env.TWITTER_API_KEY,
appSecret: process.env.TWITTER_API_SECRET,
accessToken: process.env.TWITTER_ACCESS_TOKEN,
accessSecret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});
logger.info('Twitter API client initialized successfully');
//*******************************************************************
// Caching Layer
//*******************************************************************
logger.info('Initializing cache', { ttl: CONFIG.CACHE.TTL });
const cache = new NodeCache({
stdTTL: CONFIG.CACHE.TTL,
checkperiod: CONFIG.CACHE.TTL * 2 // Check for expired keys
});
logger.info('Cache initialized');
//*******************************************************************
// Application State
//*******************************************************************
let current_number;
let current_string;
let current_comma;
let current_twext;
//*******************************************************************
// Utility Functions
//*******************************************************************
import { randomInt } from './src/utils/random.js';
//*******************************************************************
// Initialization
//*******************************************************************
(async () => {
logger.info('=== INITIALIZATION START ===');
try {
// Initialize the countdown from the lowest existing number in DynamoDB,
// or start fresh if no record exists.
logger.info('Checking cache for existing countdown state');
const params = {
TableName: CONFIG.AWS.TABLE_NAME,
};
// Check cache first to avoid expensive scan operation
const cachedState = cache.get('countdown_state');
if (cachedState) {
logger.info('=== USING CACHED STATE ===');
logger.info('Using cached countdown state');
current_number = cachedState.number;
current_comma = cachedState.comma;
current_string = cachedState.string;
logger.info('Loaded countdown state from cache', {
number: current_number,
string: current_string,
comma: current_comma
});
logger.info('Starting countdown from cached state');
countdown();
return;
}
// If not in cache, scan DynamoDB (expensive operation)
// TODO: Optimize by using Query with GSI or storing current number separately
logger.info('=== SCANNING DYNAMODB ===');
logger.info('Scanning DynamoDB table', { tableName: CONFIG.AWS.TABLE_NAME });
const data = await docClient.send(new ScanCommand(params));
logger.info('=== DYNAMODB SCAN COMPLETE ===');
logger.info('DynamoDB scan result', { itemCount: data.Items.length });
if (data.Items.length === 0) {
logger.info('=== NO ITEMS FOUND - INITIALIZING WITH START NUMBER ===');
logger.info('No items found in table, initializing with start number', {
startNumber: CONFIG.APP.START_NUMBER
});
current_number = CONFIG.APP.START_NUMBER;
current_comma = comma(current_number);
current_string = numberstring(current_number, { cap: 'title', punc: '!' });
logger.info('Generated initial state', {
number: current_number,
comma: current_comma,
string: current_string
});
// Insert a record if no items are found
const insertParams = {
TableName: CONFIG.AWS.TABLE_NAME,
Item: {
number: current_number,
string: current_string,
datetime: new Date().toISOString(),
status: true,
},
};
logger.info('Inserting initial record into DynamoDB');
await docClient.send(new PutCommand(insertParams));
logger.info('=== INITIAL RECORD INSERTED ===');
logger.info('Inserted new record', { number: current_number });
} else {
logger.info('=== LOADING EXISTING STATE ===');
logger.info('Found existing items', { itemCount: data.Items.length });
const lowest_number = data.Items.sort((a, b) => a.number - b.number)[0];
logger.info('Lowest number found', { number: lowest_number.number });
// Validate number format from DynamoDB
const number = parseInt(lowest_number.number);
if (isNaN(number) || !isFinite(number)) {
logger.error('Invalid number format in DynamoDB', {
rawValue: lowest_number.number,
parsedValue: number
});
throw new Error('Invalid number format in DynamoDB: ' + lowest_number.number);
}
current_number = number;
current_comma = comma(current_number);
current_string = numberstring(current_number, { 'cap': 'title', 'punc': '!' });
logger.info('Generated state from DynamoDB', {
number: current_number,
comma: current_comma,
string: current_string
});
// Cache the state
logger.debug('Caching state');
cache.set('countdown_state', {
number: current_number,
comma: current_comma,
string: current_string
});
logger.info('=== STATE LOADED AND CACHED ===');
logger.info('Loaded countdown state', {
number: current_number,
string: current_string,
comma: current_comma
});
logger.info('Starting countdown from loaded state');
countdown();
}
logger.info('=== INITIALIZATION COMPLETE ===');
} catch (error) {
logger.error('=== INITIALIZATION ERROR ===');
logger.error('Initialization error', {
error: error.message,
stack: error.stack,
name: error.name,
code: error.code,
region: CONFIG.AWS.REGION,
tableName: CONFIG.AWS.TABLE_NAME,
hasAccessKey: !!process.env.AWS_ACCESS_KEY_ID,
hasSecretKey: !!process.env.AWS_SECRET_ACCESS_KEY
});
// Provide helpful error messages for common issues
if (error.name === 'InvalidSignatureException') {
logger.error('AWS Credentials Error: The AWS Secret Access Key does not match the Access Key ID.');
logger.error('Please verify your AWS credentials in .env file are correct and match.');
} else if (error.name === 'ResourceNotFoundException') {
logger.error('DynamoDB Table Error: The table does not exist.');
logger.error(`Please create the table "${CONFIG.AWS.TABLE_NAME}" in region "${CONFIG.AWS.REGION}"`);
} else if (error.name === 'UnrecognizedClientException') {
logger.error('AWS Credentials Error: The security token included in the request is invalid.');
logger.error('Please check your AWS credentials are valid and not expired.');
}
logger.warn('Continuing without DynamoDB connection. Web server will still run.');
// Don't exit - allow web server to run even if DynamoDB fails
}
})();
//*******************************************************************
// Tweet Content Data
//*******************************************************************
// Phrases for adding random humorous or engaging variety to tweets.
const short_phrase = [
'Ha ha ha!!',
'Ah ah ah!!',
'Ah ha ha!!',
'Ah ha ha ha!!',
'Don\'t forget to count!!',
'Wonderful!!',
'I love motion pictures!!',
'I love counting!!',
'Now, that was silly!!',
'Wouldn\'t you agree, my bats?',
'I love traditions!!',
'I will count them!!',
'There\'s always something to count!!',
'Don\'t count the days, make the days count!!',
'Werry good!!',
'Yeees!!',
'You know that I am called the Count!!',
'I really love to count!!',
'I could sit and count all day!!',
'Sometimes I get carried away!!',
'Yeees!!',
'I count slowly!!',
'Once I\'ve started counting it\'s really hard to stop!!',
'I could count forever!!',
'I love counting whatever the amount!!',
'When I\'m alone, I count myself!!',
'Greetings!!',
'Counting is fun!!',
'I vant to count your numbers!!',
'I love big numbers and I cannot lie!!',
'Sometimes I just count away!!',
'Numbers are useful!!',
'I love to count things!!'
];
// List of random short tags used for Twitter posts
const short_tags = [
'@CountVonCount',
'@CountVonCount',
'@CountVonCount',
'@SesameWorkshop',
'@sesamestreet',
'@BigBird',
'@OscarTheGrouch',
'@elmo',
'@MeCookieMonster',
'@Grover',
'@KermitTheFrog',
'@ollie',
'@brianfunk_',
'@brianfunk_',
'#sesamestreet',
'#numberstring',
'#numbers',
'#count',
'#counting',
'#ilovecounting',
'#iheartcounting',
'#ilovenumbers',
'#iheartnumbers',
'#CountessVonBackwards',
'#CountessvonDahling',
'#LadyTwo',
'#TheCountess',
'#CountVonCount',
'#countmobile',
'#itsthefinalcountdown',
'#countdown',
'#countupsidedown',
'#countingisfun',
'#ahhaha',
'#yeees'
];
//*******************************************************************
// Countdown Function
//*******************************************************************
/**
* Main function that decrements the current number, tweets the new count,
* updates the record in DynamoDB, and schedules the next countdown.
*
* This function:
* 1. Decrements the current number
* 2. Formats the number as a string and comma-separated value
* 3. Randomly adds a phrase and tag (1 in 5 chance)
* 4. Posts a tweet via Twitter API v2
* 5. Updates DynamoDB with the new countdown state
* 6. Schedules the next countdown with a random delay (14-88 days)
*
* Error handling:
* - Twitter rate limits: waits for rate limit reset before retrying
* - DynamoDB throttling: uses exponential backoff with up to 5 retries
* - Other errors: retries after 1 minute delay
*
* @returns {Promise<void>}
*/
async function countdown() {
logger.info('=== COUNTDOWN FUNCTION START ===');
logger.info('Current state before decrement', {
current_number,
current_string,
current_comma
});
// Validate current_number exists and is valid
if (current_number === undefined || current_number === null) {
logger.error('Current number is undefined. Cannot continue countdown.');
return;
}
// Check for negative numbers - end countdown if reached zero or below
if (current_number <= 0) {
logger.error('Countdown reached zero or below. Countdown complete!');
// Optionally: send final tweet, update status, etc.
return;
}
logger.info('Decrementing number', { from: current_number, to: current_number - 1 });
current_number--;
current_string = numberstring(current_number, { 'cap': 'title', 'punc': '!' });
current_comma = comma(current_number);
logger.info('Updated countdown state', {
number: current_number,
string: current_string,
comma: current_comma
});
try {
// Step 1: Post a tweet with the current count
logger.info('=== PREPARING TWEET ===');
logger.debug('Preparing tweet');
current_twext = current_string;
logger.debug('Base tweet text', { text: current_twext, length: current_twext.length });
// Randomly add phrase and tag (1 in 5 chance)
const shouldAddPhrase = randomInt(0, CONFIG.COUNTDOWN.PHRASE_PROBABILITY) === CONFIG.COUNTDOWN.PHRASE_PROBABILITY;
logger.debug('Phrase probability check', {
randomValue: randomInt(0, CONFIG.COUNTDOWN.PHRASE_PROBABILITY),
probability: CONFIG.COUNTDOWN.PHRASE_PROBABILITY,
willAddPhrase: shouldAddPhrase
});
if (shouldAddPhrase) {
const twext_phrase = short_phrase[randomInt(0, short_phrase.length - 1)];
const twext_tag = short_tags[randomInt(0, short_tags.length - 1)];
logger.info('Adding phrase and tag to tweet', { phrase: twext_phrase, tag: twext_tag });
current_twext = `${current_comma}! ${twext_phrase} ${twext_tag}`;
}
// Validate tweet length (Twitter limit is 280 characters)
if (current_twext.length > 280) {
logger.warn('Tweet too long, truncating', { originalLength: current_twext.length });
current_twext = current_twext.substring(0, 277) + '...';
}
logger.info('Tweet prepared', { text: current_twext, length: current_twext.length });
// Send the tweet with rate limit handling
logger.info('=== POSTING TWEET TO TWITTER API ===');
logger.info('Twitter API client status', {
hasClient: !!twitterClient,
hasV2: !!twitterClient?.v2,
tweetText: current_twext.substring(0, 50) + '...'
});
let tweet;
try {
logger.info('Calling twitterClient.v2.tweet()', { tweetLength: current_twext.length });
tweet = await twitterClient.v2.tweet(current_twext);
logger.info('=== TWEET POSTED SUCCESSFULLY ===');
logger.info('Tweet response', {
tweetId: tweet.data?.id,
text: tweet.data?.text,
createdAt: tweet.data?.created_at
});
} catch (twitterError) {
logger.error('=== TWITTER API ERROR ===');
logger.error('Twitter API error details', {
code: twitterError.code,
status: twitterError.status,
message: twitterError.message,
rateLimit: twitterError.rateLimit,
data: twitterError.data
});
// Handle Twitter rate limits (429 Too Many Requests)
if (twitterError.code === 429 || twitterError.status === 429) {
// Check if daily limit is exhausted - use day.reset instead of general reset
const rateLimit = twitterError.rateLimit || {};
const dayLimit = rateLimit.day || {};
const userDayLimit = rateLimit.userDay || {};
// Use daily reset time if daily limit is exhausted, otherwise use general reset
let resetTimestamp = null;
if (dayLimit.remaining === 0 && dayLimit.reset) {
resetTimestamp = dayLimit.reset;
logger.warn('Daily tweet limit exhausted - waiting for daily reset', {
dailyLimit: dayLimit.limit,
dailyRemaining: dayLimit.remaining,
resetTimestamp: resetTimestamp
});
} else if (userDayLimit.remaining === 0 && userDayLimit.reset) {
resetTimestamp = userDayLimit.reset;
logger.warn('User daily tweet limit exhausted - waiting for daily reset', {
userDailyLimit: userDayLimit.limit,
userDailyRemaining: userDayLimit.remaining,
resetTimestamp: resetTimestamp
});
} else if (rateLimit.reset) {
resetTimestamp = rateLimit.reset;
}
const retryAfter = resetTimestamp
? Math.max((resetTimestamp * 1000) - Date.now(), 60000) // At least 1 minute
: 900000; // Default to 15 minutes if reset time not available
logger.warn('Twitter rate limit hit - scheduling retry', {
retryAfterMs: retryAfter,
retryAfterSeconds: Math.ceil(retryAfter / 1000),
retryAfterMinutes: Math.ceil(retryAfter / 60000),
retryAfterHours: (retryAfter / 3600000).toFixed(2),
resetTime: resetTimestamp ? new Date(resetTimestamp * 1000).toISOString() : 'unknown',
dailyLimit: dayLimit.limit,
dailyRemaining: dayLimit.remaining,
generalLimit: rateLimit.limit,
generalRemaining: rateLimit.remaining
});
setTimeout(() => countdown(), retryAfter);
return;
}
throw twitterError; // Re-throw if not a rate limit error
}
// Step 2: Update the DynamoDB record with the new number
logger.info('=== UPDATING DYNAMODB ===');
logger.debug('Updating DynamoDB', { tableName: CONFIG.AWS.TABLE_NAME });
const insertParams = {
TableName: CONFIG.AWS.TABLE_NAME,
Item: {
number: current_number,
string: current_string,
datetime: new Date().toISOString(),
status: true,
},
};
logger.debug('DynamoDB PutCommand params', {
tableName: insertParams.TableName,
number: insertParams.Item.number,
hasString: !!insertParams.Item.string,
datetime: insertParams.Item.datetime
});
// DynamoDB operations with retry handling for throttling
let retries = 0;
const maxRetries = 5;
while (retries < maxRetries) {
try {
logger.info('Sending PutCommand to DynamoDB', { attempt: retries + 1, maxRetries });
await docClient.send(new PutCommand(insertParams));
logger.info('=== DYNAMODB UPDATE SUCCESSFUL ===');
logger.info('Inserted new record', { number: current_number });
// Update cache with new state
logger.debug('Updating cache with new state');
cache.set('countdown_state', {
number: current_number,
comma: current_comma,
string: current_string
});
logger.debug('Cache updated successfully');
break; // Success, exit retry loop
} catch (dynamoError) {
logger.error('DynamoDB error', {
name: dynamoError.name,
message: dynamoError.message,
httpStatusCode: dynamoError.$metadata?.httpStatusCode,
requestId: dynamoError.$metadata?.requestId,
attempt: retries + 1
});
// Handle DynamoDB throttling (ProvisionedThroughputExceededException)
if (dynamoError.name === 'ProvisionedThroughputExceededException' ||
dynamoError.$metadata?.httpStatusCode === 400) {
retries++;
const backoffDelay = Math.min(1000 * Math.pow(2, retries), 30000); // Exponential backoff, max 30s
logger.warn('DynamoDB throttled - retrying with backoff', {
retry: retries,
maxRetries,
backoffDelayMs: backoffDelay,
backoffDelaySeconds: Math.ceil(backoffDelay / 1000)
});
await new Promise(resolve => setTimeout(resolve, backoffDelay));
} else {
throw dynamoError; // Re-throw if not a throttling error
}
}
}
if (retries >= maxRetries) {
logger.error('=== DYNAMODB UPDATE FAILED AFTER MAX RETRIES ===');
throw new Error('Failed to update DynamoDB after maximum retries');
}
// Schedule next countdown with random delay
// Delay ranges from ~14 days to ~88 days (1234567ms to 7654321ms)
logger.info('=== SCHEDULING NEXT COUNTDOWN ===');
const delay = randomInt(CONFIG.COUNTDOWN.DELAY_MIN_MS, CONFIG.COUNTDOWN.DELAY_MAX_MS);
const delayHours = delay / 3600000;
const delayDays = delayHours / 24;
logger.info('Next countdown scheduled', {
delayMs: delay,
delayHours: delayHours.toFixed(2),
delayDays: delayDays.toFixed(2),
nextRunTime: new Date(Date.now() + delay).toISOString()
});
setTimeout(() => countdown(), delay);
logger.info('=== COUNTDOWN FUNCTION COMPLETE ===');
} catch (error) {
logger.error('=== COUNTDOWN FUNCTION ERROR ===');
logger.error('Countdown error', {
error: error.message,
stack: error.stack,
name: error.name,
code: error.code
});
// Retry after shorter delay on error (1 minute)
logger.info('Retrying countdown after error', {
retryDelayMs: CONFIG.COUNTDOWN.ERROR_RETRY_DELAY_MS,
retryDelaySeconds: CONFIG.COUNTDOWN.ERROR_RETRY_DELAY_MS / 1000,
nextRetryTime: new Date(Date.now() + CONFIG.COUNTDOWN.ERROR_RETRY_DELAY_MS).toISOString()
});
setTimeout(() => countdown(), CONFIG.COUNTDOWN.ERROR_RETRY_DELAY_MS);
}
}
//*******************************************************************
// Express Application Setup
//*******************************************************************
const app = express();
// Trust proxy for accurate IP detection behind load balancers (AWS App Runner, Heroku, etc.)
// Use number 1 to trust first proxy (AWS App Runner uses 1 proxy layer)
// This prevents the express-rate-limit warning while still working correctly
app.set('trust proxy', 1);
app.engine('handlebars', exphbs.engine({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
// Compression middleware
app.use(compression());
// Request timeout (30 seconds)
app.use(timeout('30s'));
app.use((req, res, next) => {
if (!req.timedout) next();
});
// Security middleware with Content Security Policy
// Maximally permissive CSP for public site - allows all external resources
// This prevents breakage if embedded sites change their domains/scripts
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'", 'https:', 'http:', 'data:', 'blob:'],
scriptSrc: [
"'self'",
"'unsafe-inline'",
"'unsafe-eval'", // Allow eval for maximum compatibility
'https:',
'http:',
'data:',
'blob:'
],
scriptSrcElem: [
"'self'",
"'unsafe-inline'",
'https:',
'http:',
'data:',
'blob:'
],
scriptSrcAttr: [
"'self'",
"'unsafe-inline'",
'https:',
'http:'
],
styleSrc: [
"'self'",
"'unsafe-inline'",
'https:',
'http:',
'data:'
],
styleSrcElem: [
"'self'",
"'unsafe-inline'",
'https:',
'http:',
'data:'
],
fontSrc: [
"'self'",
'https:',
'http:',
'data:'
],
imgSrc: [
"'self'",
'data:',
'blob:',
'https:',
'http:'
],
frameSrc: [
"'self'",
'https:',
'http:',
'data:',
'blob:'
],
frameAncestors: [
"'self'"
],
connectSrc: [
"'self'",
'https:',
'http:',
'ws:',
'wss:',
'data:'
],
mediaSrc: [
"'self'",
'https:',
'http:',
'data:',
'blob:'
],
objectSrc: [
"'self'",
'https:',
'http:',
'data:',
'blob:'
],
baseUri: ["'self'", 'https:', 'http:'],
formAction: ["'self'", 'https:', 'http:'],
workerSrc: [
"'self'",
'blob:',
'https:',
'http:'
],
manifestSrc: [
"'self'",
'https:',
'http:'
]
}
}
}));
// Rate limiting - general
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later.'
});
// Rate limiting - health endpoint (more permissive)
const healthLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 60, // 60 requests per minute
message: 'Too many health check requests.'
});
app.use(limiter);
app.use(express.static('public'));
// Request logging middleware
app.use((req, res, next) => {
logger.info('HTTP request', {
method: req.method,
path: req.path,
ip: req.ip,
userAgent: req.get('user-agent'),
query: req.query
});
next();
});
//*******************************************************************
// Routes
//*******************************************************************
// Favicon route to prevent 404 errors
app.get('/favicon.ico', (req, res) => {
res.status(204).end();
});
app.get('/', (req, res) => {
res.render('home', {
current_number: current_number,
current_string: current_string,
current_comma: current_comma
});
});
app.get('/badge', async (req, res) => {
logger.info('Badge endpoint called');
// Use current_comma if available, otherwise fallback to START_NUMBER formatted
const badgeValue = current_comma || comma(CONFIG.APP.START_NUMBER);
logger.debug('Badge value', { badgeValue, hasCurrentComma: !!current_comma, isFallback: !current_comma });
const badge_url = `https://${CONFIG.BADGE.ALLOWED_DOMAIN}/badge/Von%20Countdown-${encodeURIComponent(badgeValue)}-a26d9e.svg`;
logger.debug('Fetching badge', { badgeUrl: badge_url, badgeValue });
try {
const response = await axios.get(badge_url, { responseType: 'stream' });
logger.info('Badge fetched successfully', { badgeValue });
res.setHeader('Content-Type', 'image/svg+xml');
res.setHeader('Cache-Control', 'public, max-age=300');
response.data.pipe(res);
} catch (error) {
logger.error('Badge fetch error', {
error: error.message,
status: error.response?.status,
statusText: error.response?.statusText,
badgeUrl: badge_url
});
res.status(500).send('Error fetching badge');
}
});
app.get('/health', healthLimiter, (req, res) => {
res.json({
status: 'ok',
current_number: current_number || null,
current_string: current_string || null,
current_comma: current_comma || null,
uptime: process.uptime(),
timestamp: new Date().toISOString()
});
});
// 404 handler
app.use((req, res) => {
res.status(404).render('error', {
status: 404,
message: 'Page not found',
layout: 'main'
}, (err, html) => {
if (err) {
res.status(404).send('Page not found');
} else {
res.send(html);
}
});
});
// Error handler
app.use((err, req, res, next) => {