Skip to content

Commit

Permalink
Code improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
MrMicky-FR committed May 12, 2024
1 parent 76ed871 commit 01327c7
Show file tree
Hide file tree
Showing 11 changed files with 499 additions and 838 deletions.
2 changes: 1 addition & 1 deletion frontend/src/charts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export async function createServersChart(
const data = mapServerStats(value)

if (!server) {
return { type: 'spline' }
return { type: 'spline' } // Will be filtered out below
}

colors[index] = server.color || '#0000ff'
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/ServersList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ function toggleServersChart() {
<div v-for="(server, i) in servers" :key="server.id" class="col-lg-6">
<ServerBox
:description="server"
:stats="stats[server.id]"
:stats="stats[server.id] || {}"
:position="i + 1"
/>
</div>
Expand Down
1,241 changes: 453 additions & 788 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,13 @@
"devDependencies": {
"@cloudflare/kv-asset-handler": "^0.3.0",
"@cloudflare/workers-types": "^4.0.0",
"@types/luxon": "^3.0.0",
"@typescript-eslint/eslint-plugin": "^5.32.0",
"@typescript-eslint/parser": "^5.32.0",
"base64-js": "^1.5.1",
"eslint": "^8.21.0",
"eslint-config-prettier": "^8.5.0",
"eslint-config-typescript": "^3.0.0",
"itty-router": "^4.0.9",
"luxon": "^3.0.1",
"prettier": "^2.7.1",
"typescript": "^5.1.3",
"wrangler": "^3.0.1"
Expand Down
47 changes: 19 additions & 28 deletions src/cron.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { DateTime } from 'luxon'
import { Env } from './index'
import { ping } from './pinger'
import {
Expand Down Expand Up @@ -36,8 +35,8 @@ export async function handleScheduled(env: Env): Promise<Response> {
}

async function pingServers(env: Env): Promise<void> {
const now = DateTime.now().set({ millisecond: 0 })
const archive = now.minute % env.GLOBAL_CHART_PING_INTERVAL === 0
const now = new Date()
const archive = now.getMinutes() % env.GLOBAL_PING_INTERVAL === 0
const playersCounts: { [serverId: string]: number } = {}
let updateServerIcons = false

Expand All @@ -60,6 +59,8 @@ async function pingServers(env: Env): Promise<void> {
if (archive && favicon && favicon !== serverIcons[server.id]) {
serverIcons[server.id] = favicon
updateServerIcons = true

console.log(`Updated favicon for ${server.address}`)
}
} catch (e) {
playersCounts[server.id] = -1
Expand All @@ -82,23 +83,17 @@ async function updateRecentStats(
env: Env,
servers: Server[],
playersCounts: Record<string, number>,
now: DateTime,
now: Date,
) {
const isoDateTime = now.toISO({ suppressMilliseconds: true })
const deleteOlder = now.minus({
minutes: env.RECENT_CHARTS_DELETE_AFTER_MINUTES,
})
const isoDateTime = now.toISOString().slice(0, 19) + 'Z' // Remove milliseconds
const deleteDate = now.getTime() - env.RECENT_DELETE_AFTER_MIN * 60 * 1000
const recentStats = await getRecentStats(env)

if (!isoDateTime) {
return
}

for (const server of servers) {
const stats = recentStats[server.id] || {}

Object.keys(stats)
.filter((date) => DateTime.fromISO(date) < deleteOlder)
.filter((date) => Date.parse(date) < deleteDate)
.forEach((date) => delete stats[date])

stats[isoDateTime] = playersCounts[server.id]
Expand All @@ -113,17 +108,13 @@ async function updateStats(
env: Env,
servers: Server[],
playersCounts: Record<string, number>,
now: DateTime,
now: Date,
) {
const currentDate = now.toISODate()
const currentDateTime = now.toISO()
const currentTime = now.toFormat('HH:mm')
const currentDateTime = now.toISOString()
const currentDate = currentDateTime.slice(0, 10) // YYYY-MM-DD
const currentTime = now.toTimeString().slice(0, 5) // HH:mm
const serverStats = await getStats(env)

if (!currentDate || !currentDateTime) {
return
}

// Add new servers in stats
for (const server of servers) {
if (!serverStats.find((value) => value.serverId === server.id)) {
Expand All @@ -150,25 +141,25 @@ async function updateStats(
stats.stats[currentDate][currentTime] = players
}

await putServersStats(env, deleteOldStats(env, serverStats, now))
await putServersStats(env, purgeStats(env, servers, serverStats, now))
}

function deleteOldStats(env: Env, stats: ServerStats[], now: DateTime) {
function purgeStats(env: Env, serv: Server[], stats: ServerStats[], now: Date) {
// Clear old stats at 4 am
if (now.hour !== 4 || now.minute !== 0) {
if (now.getHours() !== 4 || now.getMinutes() !== 0) {
return stats
}

// Delete values older than a year
const deleteOlder = now.minus({ days: env.GLOBAL_CHART_DELETE_AFTER_DAYS })
const deleteDate = now.getTime() - env.GLOBAL_DELETE_AFTER_DAYS * 86400 * 1000

for (const server of stats) {
Object.keys(server.stats)
.filter((date) => DateTime.fromISO(date) < deleteOlder)
.filter((date) => Date.parse(date) < deleteDate)
.forEach((date) => delete server.stats[date])
}

console.log('Old stats have been deleted.')

return stats
// Purge stats for deleted servers
return stats.filter((server) => serv.find((s) => s.id === server.serverId))
}
6 changes: 0 additions & 6 deletions src/icons.ts

This file was deleted.

4 changes: 4 additions & 0 deletions src/icons/unknown.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 4 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ import {
ServerIcons,
} from './storage'
import { handleScheduled } from './cron'
import { fallbackIcon } from './icons'
import fallbackIcon from './icons/unknown.svg'

import manifestJSON from '__STATIC_CONTENT_MANIFEST'

export interface Env {
GLOBAL_CHART_PING_INTERVAL: number
GLOBAL_CHART_DELETE_AFTER_DAYS: number
RECENT_CHARTS_DELETE_AFTER_MINUTES: number
GLOBAL_PING_INTERVAL: number
GLOBAL_DELETE_AFTER_DAYS: number
RECENT_DELETE_AFTER_MIN: number
WEBHOOK_URL?: string
SERVERS_EDIT_TOKEN?: string
PING_ALIASES?: string
Expand Down
5 changes: 5 additions & 0 deletions src/kv-assets-handler.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,8 @@ declare module '__STATIC_CONTENT_MANIFEST' {
const manifest: string
export default manifest
}

declare module '*.svg' {
const svg: string
export default svg
}
4 changes: 2 additions & 2 deletions src/protocol/dns.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export async function resolveSrv(name: string) {
const params = new URLSearchParams({
name,
type: 'src',
type: 'srv',
ct: 'application/dns-json',
})

Expand All @@ -19,7 +19,7 @@ export async function resolveSrv(name: string) {
const data = JSON.parse(await res.text())

if (!data.Answer?.length) {
console.error(`No DNS records for ${name}}.`)
console.error(`No DNS records for ${name}.`)
return undefined
}

Expand Down
16 changes: 10 additions & 6 deletions wrangler.example.toml
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
name = "craftstats"
main = "src/index.ts"
compatibility_date = "2022-07-01"
compatibility_date = "2024-05-12"

kv_namespaces = [
{ binding = "KV_SERVERS", id = "" },
]

rules = [
{ type = "Text", globs = ["**/*.svg"], fallthrough = true }
]

[vars]
# Retry when server ping failed
PING_ATTEMPTS = 2
Expand All @@ -14,13 +18,13 @@ PING_ATTEMPTS = 2
# WEBHOOK_URL = ""

# By default, stats in the indivudal servers charts are deleted after 2 hours (120 min)
RECENT_CHARTS_DELETE_AFTER_MINUTES = 120
RECENT_DELETE_AFTER_MIN = 120

# By default, the global server chart will have data with a 15-min interval
GLOBAL_PING_INTERVAL = 15

# By default, the global server chart will have data
# with a 15-min interval
GLOBAL_CHART_PING_INTERVAL = 15
# By default, stats in the global server chart are deleted after 6 months (180 days)
GLOBAL_CHART_DELETE_AFTER_DAYS = 180
GLOBAL_DELETE_AFTER_DAYS = 180

# You can define a token to edit the servers from the /edit page
# The token should be at least 10 characters
Expand Down

0 comments on commit 01327c7

Please sign in to comment.