Add cache warming

This commit is contained in:
Matt Isenhower 2022-09-09 17:43:48 -07:00
parent 48e8c1a521
commit 400347e277
4 changed files with 45 additions and 10 deletions

View File

@ -1,6 +1,6 @@
import { CronJob } from "cron";
import { sendTweets } from "./twitter/index.mjs";
import { warmCache } from "./splatnet/index.mjs";
export default function() {
new CronJob('1 16 * * *', sendTweets, null, true);
new CronJob('5,20,35,50 * * * *', warmCache, null, true);
}

View File

@ -39,8 +39,10 @@ export default class NsoClient
return new ValueCache(`${this.cachePrefix}.coral`);
}
async getCoralApi() {
let data = await this._getCoralCache().getData();
async getCoralApi(useCache = true) {
let data = useCache
? await this._getCoralCache().getData()
: null;
if (!data) {
data = await this._createCoralSession();
@ -66,9 +68,11 @@ export default class NsoClient
return new ValueCache(`${this.cachePrefix}.webservicetoken.${id}`);
}
async getWebServiceToken(id) {
async getWebServiceToken(id, useCache = true) {
let tokenCache = this._getWebServiceTokenCache(id);
let token = await tokenCache.getData();
let token = useCache
? await tokenCache.getData()
: null;
if (!token) {
token = await this._createWebServiceToken(id, tokenCache);

View File

@ -1,11 +1,12 @@
import ValueCache from "../common/ValueCache.mjs";
import NsoClient from "./NsoClient.mjs";
export const SPLATNET3_WEB_SERVICE_ID = '4834290508791808';
export default class SplatNet3Client
{
baseUrl = 'https://api.lp1.av5ja.srv.nintendo.net';
webViewVersion = '1.0.0-5e2bcdfb';
webServiceId = '4834290508791808';
bulletToken = null;
constructor(nsoClient = null) {
@ -35,12 +36,15 @@ export default class SplatNet3Client
}
}
async getBulletToken() {
async getBulletToken(useCache = true) {
let bulletTokenCache = new ValueCache(`${this.nsoClient.cachePrefix}.bulletToken`);
let bulletToken = await bulletTokenCache.getData();
let bulletToken = useCache
? await bulletTokenCache.getData()
: null;
if (!bulletToken) {
let webServiceToken = await this.nsoClient.getWebServiceToken(this.webServiceId);
let webServiceToken = await this.nsoClient.getWebServiceToken(SPLATNET3_WEB_SERVICE_ID);
bulletToken = await this._createBulletToken(webServiceToken, bulletTokenCache);
}

27
app/splatnet/index.mjs Normal file
View File

@ -0,0 +1,27 @@
import NsoClient from "./NsoClient.mjs";
import SplatNet3Client, { SPLATNET3_WEB_SERVICE_ID } from "./SplatNet3Client.mjs";
/**
* Cache Warming
*
* This helps ensure we have reliable access to the SplatNet 3 API,
* even if e.g. the imink API has intermittent downtime.
*/
export async function warmCache() {
console.debug('Warming caches...');
let nso = new NsoClient;
let splatnet = new SplatNet3Client;
await safe(() => nso.getCoralApi(false));
await safe(() => nso.getWebServiceToken(SPLATNET3_WEB_SERVICE_ID, false));
await safe(() => splatnet.getBulletToken(false));
}
async function safe(callable) {
try {
await callable();
} catch (e) {
console.error(e);
}
}