|
1 | 1 | import { BEAT_FREQUENCY } from '$lib'; |
| 2 | +import type { RequestEvent } from '@sveltejs/kit'; |
2 | 3 | import { SvelteMap } from 'svelte/reactivity'; |
| 4 | +import type { KVNamespace } from '@cloudflare/workers-types'; |
3 | 5 |
|
4 | 6 | export const LAST_BEAT_AGE_FOR_ACTIVE = Math.trunc(BEAT_FREQUENCY * 1.25); |
5 | 7 |
|
6 | | -const concurrencyMap: SvelteMap<string, number> = new SvelteMap(); |
| 8 | +export let localConcurrencyMap: SvelteMap<string, number> = new SvelteMap(); |
7 | 9 |
|
8 | | -export const containsId = (key: string) => { |
9 | | - return concurrencyMap.has(key); |
| 10 | +export const containsId = async (event: RequestEvent, key: string) => { |
| 11 | + if (event.locals.dev) return event.locals.localmap.has(key); |
| 12 | + else return ((await event.locals.prodmap.get(key)) != null); |
10 | 13 | }; |
11 | 14 |
|
12 | | -export const updateId = (key: string) => { |
13 | | - concurrencyMap.set(key, Date.now()); |
| 15 | +export const updateId = async (event: RequestEvent, key: string) => { |
| 16 | + if (event.locals.dev) event.locals.localmap.set(key, Date.now()); |
| 17 | + else await event.locals.prodmap.put(key, String(Date.now())); |
14 | 18 | }; |
15 | 19 |
|
16 | | -export const removeOld = (key: string) => { |
17 | | - concurrencyMap.delete(key); |
| 20 | +export const removeOld = async (event: RequestEvent, key: string) => { |
| 21 | + if (event.locals.dev) event.locals.localmap.delete(key); |
| 22 | + else await event.locals.prodmap.delete(key); |
18 | 23 | }; |
19 | 24 |
|
20 | | -export const getActive = () => { |
| 25 | +export const getActive = async (event: RequestEvent) => { |
21 | 26 | const now = Date.now(); |
22 | | - concurrencyMap.forEach((value, key, map) => { |
23 | | - if (now - value > LAST_BEAT_AGE_FOR_ACTIVE) { |
24 | | - map.delete(key); |
25 | | - } |
26 | | - }); |
27 | 27 |
|
28 | | - return concurrencyMap.size; |
| 28 | + if (event.locals.dev) { |
| 29 | + event.locals.localmap.forEach((value, key, map) => { |
| 30 | + if (now - value > LAST_BEAT_AGE_FOR_ACTIVE) { |
| 31 | + map.delete(key); |
| 32 | + } |
| 33 | + }); |
| 34 | + return event.locals.localmap.size; |
| 35 | + } |
| 36 | + else { |
| 37 | + let keys = []; |
| 38 | + let list = undefined; |
| 39 | + do { |
| 40 | + list = await event.locals.prodmap.list({ |
| 41 | + cursor: list == undefined ? undefined : list.cursor |
| 42 | + }); |
| 43 | + keys.push(...list.keys); |
| 44 | + } |
| 45 | + while (!list.list_complete); |
| 46 | + let removed = 0; |
| 47 | + for (let i = 0; i < keys.length; i++) { |
| 48 | + const key = keys[i].name; |
| 49 | + const value = parseInt(await event.locals.prodmap.get(key) as string); |
| 50 | + if (now - value > LAST_BEAT_AGE_FOR_ACTIVE) { |
| 51 | + await event.locals.prodmap.delete(key); |
| 52 | + removed++; |
| 53 | + } |
| 54 | + } |
| 55 | + return list.keys.length - removed; |
| 56 | + } |
29 | 57 | }; |
0 commit comments