Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: OOO Nickname Update Job #11

Merged
merged 19 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const NAMESPACE_NAME = 'CronJobsTimestamp';

export { NAMESPACE_NAME };
60 changes: 59 additions & 1 deletion src/handlers/scheduledEventHandler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,66 @@
import { KVNamespace } from '@cloudflare/workers-types';

import { handleConfig } from '../config/config';
import { env } from '../types/global.types';
import { NAMESPACE_NAME } from '../constants';
import { env, NicknameUpdateResponseType } from '../types/global.types';
import { generateJwt } from '../utils/generateJwt';

export async function ping(env: env) {
const url = handleConfig(env);
const response = await fetch(`${url.baseUrl}/healthcheck`);
return response;
}

export async function callDiscordNicknameBatchUpdate(env: env) {
const namespace = env[NAMESPACE_NAME] as unknown as KVNamespace;
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
let lastNicknameUpdate: string | null = '0';
try {
lastNicknameUpdate = await namespace.get('DISCORD_NICKNAME_CHANGED');
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
if (lastNicknameUpdate === null) {
throw new Error('Error while fetching KV "DISCORD_NICKNAME_CHANGED" timestamp');
}
if (!lastNicknameUpdate) {
lastNicknameUpdate = '0';
}
} catch (err) {
console.error(err, 'Error while fetching the timestamp for last nickname update');
throw err;
}

const url = handleConfig(env);
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
let token;
try {
token = await generateJwt(env);
} catch (err) {
console.error(`Error while generating JWT token: ${err}`);
throw err;
}
const response = await fetch(`${url.baseUrl}/discord-actions/nickname/status`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
lastNicknameUpdate,
bharati-21 marked this conversation as resolved.
Show resolved Hide resolved
}),
});
if (!response.ok) {
throw new Error("Error while trying to update users' discord nickname");
}

const data: NicknameUpdateResponseType = await response.json();
if (data?.data.totalUsersStatus !== 0 && data?.data.successfulNicknameUpdates === 0) {
throw new Error("Error while trying to update users' discord nickname");
}

console.log(data);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

!


try {
await namespace.put('DISCORD_NICKNAME_CHANGED', Date.now().toString());
RitikJaiswal75 marked this conversation as resolved.
Show resolved Hide resolved
} catch (err) {
console.error('Error while trying to update the last nickname change timestamp');
}

return data;
}
9 changes: 9 additions & 0 deletions src/types/global.types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
export type env = {
[key: string]: string;
};

export type NicknameUpdateResponseType = {
message: string;
data: {
totalUsersStatus: number;
successfulNicknameUpdates: number;
unsuccessfulNicknameUpdates: number;
};
};
17 changes: 14 additions & 3 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
import { ping } from './handlers/scheduledEventHandler';
import { callDiscordNicknameBatchUpdate, ping } from './handlers/scheduledEventHandler';
import { env } from './types/global.types';

const EVERY_4_HOURS = '0 */4 * * *';
const EVERY_6_HOURS = '0 */6 * * *';

export default {
// We need to keep all 3 parameters in this format even if they are not used as as cloudflare workers need them to be present So we are disabling eslint rule of no-unused-vars
// for more details read here: https://community.cloudflare.com/t/waituntil-is-not-a-function-when-using-workers-with-modules/375781/4
// eslint-disable-next-line no-unused-vars
async scheduled(req: Request, env: env, ctx: ExecutionContext) {
ctx.waitUntil(ping(env));
async scheduled(req: ScheduledController, env: env, ctx: ExecutionContext) {
switch (req.cron) {
case EVERY_4_HOURS:
ctx.waitUntil(ping(env));
break;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this notify us when backend is down?

case EVERY_6_HOURS:
return await callDiscordNicknameBatchUpdate(env);
default:
console.error('Unknown Trigger Value!');
}
},
// We need to keep all 3 parameters in this format even if they are not used as as cloudflare workers need them to be present So we are disabling eslint rule of no-unused-vars
// for more details read here: https://community.cloudflare.com/t/waituntil-is-not-a-function-when-using-workers-with-modules/375781/4
Expand Down
24 changes: 18 additions & 6 deletions wrangler.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
name = "cron-jobs"
main = "src/worker.ts"
compatibility_date = "2023-07-17"
[triggers]
crons = ["0 */4 * * *"]

# # KV Namespace binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/kv
# [[kv_namespaces]]
# binding = "MY_KV_NAMESPACE"
# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
kv_namespaces = [
{ binding = "CronJobsTimestamp", id = "7dcf94601bec415db4b13d5d1faf0fc3" }
]

# [env.staging]
# the BINDING_NAME must be CronJobsTimestamp to override in the staging env
# kv_namespaces = [
# { binding = "<BINDING_NAME>", id = "<BINDING_ID>" }
# ]

# [env.production]
# the BINDING_NAME must be CronJobsTimestamp to override in the production env
# kv_namespaces = [
# { binding = "<BINDING_NAME>", id = "<BINDING_ID>" }
# ]

[triggers]
crons = ["0 */4 * * *", "0 */6 * * *"]

# # Durable Object binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/durable-objects
# [[durable_objects]]
Expand Down
Loading