posts "question of the day" to a discord webhook

testing a mutex/lock to prevent double posts with Deploy?

+21 -16
+21 -16
main.ts
··· 10 10 11 11 Deno.cron("QOTD", Deno.env.get("CRON_STRING")!, async () => { 12 12 const date = Temporal.Now.plainDateISO(); 13 + 14 + const kv = await Deno.openKv(); 15 + 16 + // Use today's date string as a unique key for this run 17 + const lockKey = ["cron_lock", date.toString()]; 18 + const existingLock = await kv.get(lockKey); 19 + 20 + const lockResult = await kv.atomic() 21 + .check(existingLock) // only succeeds if the key hasn't changed 22 + .set(lockKey, true, { expireIn: 60_000 }) // auto-expire after 1 min 23 + .commit(); 24 + 25 + if (!lockResult.ok) { 26 + console.log("Another instance already claimed this cron run, skipping"); 27 + return; 28 + } 29 + 13 30 const { themes, questions } = await fetchData(); 14 31 const available = getAvailableThemes(date, themes); 15 32 const { themeName, theme, question } = await drawNextQuestion( ··· 17 34 questions, 18 35 ); 19 36 20 - await sendDiscordNotification( 21 - question, 22 - theme, 23 - themeName, 24 - ); 37 + await sendDiscordNotification(question, theme, themeName); 25 38 console.log( 26 39 `Cron: posted ${themeName} question of index ${theme.index} to Discord.`, 27 40 ); 28 - 29 - // @ts-ignore Deno.openKv is unstable, run with --unstable-kv flag 30 - const kv = await Deno.openKv(); 41 + 31 42 const current = await kv.get<number>([theme.kvKey]); 32 43 const index = current.value ?? 0; 33 44 const nextIndex = (index + 1) % theme.questionCount!; 34 45 35 - // Perform atomic operation to update index 36 - const result = await kv.atomic() 37 - .check(current) // Ensure the value hasn't changed 46 + await kv.atomic() 47 + .check(current) 38 48 .set([theme.kvKey], nextIndex) 39 49 .commit(); 40 - 41 - if (!result.ok) { 42 - console.log("Another instance already updated the index, skipping"); 43 - return; 44 - } 45 50 });