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 9 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 = 'CRON_JOBS_TIMESTAMPS';

export { NAMESPACE_NAME };
54 changes: 53 additions & 1 deletion src/handlers/scheduledEventHandler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,60 @@
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';
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
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 | number | null = 0;
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
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');
}
} catch (err) {
console.log('Error while fetching the timestamp for last nickname update');
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
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.log(`Error while generating JWT token: ${err}`);
Copy link
Contributor

Choose a reason for hiding this comment

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

Re: console.error

Copy link
Contributor Author

Choose a reason for hiding this comment

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

In the log both console.log and console.error appears as a generic log. But I've changed it to console.error anyway now.

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");
}
try {
await namespace.put('DISCORD_NICKNAME_CHANGED', Date.now().toString());
RitikJaiswal75 marked this conversation as resolved.
Show resolved Hide resolved
} catch (err) {
console.log('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;
};
};
14 changes: 11 additions & 3 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import { ping } from './handlers/scheduledEventHandler';
import { callDiscordNicknameBatchUpdate, ping } from './handlers/scheduledEventHandler';
import { env } from './types/global.types';

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 '0 */4 * * *':
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 '0 */6 * * *':
return await callDiscordNicknameBatchUpdate(env);
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
default:
console.log('Unknown Trigger Value!');
}
prakashchoudhary07 marked this conversation as resolved.
Show resolved Hide resolved
},
// 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 = "CRON_JOBS_TIMESTAMPS", id = "a5431887e6c94dc9b3e36c35a07081b9" }
bharati-21 marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

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

What's this id?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

These are public IDs to identify namespaces bound to a single account.

]

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

# [env.production]
# the BINDING_NAME must be CRON_JOBS_TIMESTAMPS 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