|
| 1 | +import { count, desc, gt, sql } from "drizzle-orm"; |
| 2 | +import { data } from "react-router"; |
| 3 | +import * as schema from "../../database/schema.d"; |
| 4 | +import type { Route } from "./+types/status"; |
| 5 | + |
| 6 | +export async function loader({ request, context, params }: Route.LoaderArgs) { |
| 7 | + const dataReceived = await context.db |
| 8 | + .select({ count: count() }) |
| 9 | + .from(schema.Observations) |
| 10 | + .where( |
| 11 | + gt(schema.Observations.timestamp, sql`(unixepoch() - 60 * 5)`) // 5 minutes ago |
| 12 | + ); |
| 13 | + const dataReceivedDisregarded = await context.db |
| 14 | + .select({ count: count() }) |
| 15 | + .from(schema.DisregardedObservations) |
| 16 | + .where( |
| 17 | + gt(schema.DisregardedObservations.timestamp, sql`(unixepoch() - 60 * 5)`) // 5 minutes ago |
| 18 | + ); |
| 19 | + if (dataReceived[0].count > 0 || dataReceivedDisregarded[0].count > 0) { |
| 20 | + if (dataReceived[0].count > 0) |
| 21 | + return data({ |
| 22 | + status: "ok", |
| 23 | + message: "Successfully parsed data received in the last 5 minutes", |
| 24 | + }); |
| 25 | + else |
| 26 | + return data({ |
| 27 | + status: "ok", |
| 28 | + message: |
| 29 | + "No successfully parsed data received in the last 5 minutes, but data was received that was subsequently disregarded", |
| 30 | + }); |
| 31 | + } |
| 32 | + |
| 33 | + // No data received in the last 5 minutes, so we need to check when the last observation was received |
| 34 | + const lastObservation = await context.db |
| 35 | + .select({ timestamp: schema.Observations.timestamp }) |
| 36 | + .from(schema.Observations) |
| 37 | + .orderBy(desc(schema.Observations.timestamp)) |
| 38 | + .limit(1); |
| 39 | + const lastObservationDisregarded = await context.db |
| 40 | + .select({ timestamp: schema.DisregardedObservations.timestamp }) |
| 41 | + .from(schema.DisregardedObservations) |
| 42 | + .orderBy(desc(schema.DisregardedObservations.timestamp)) |
| 43 | + .limit(1); |
| 44 | + |
| 45 | + if (lastObservation.length !== 1 && lastObservationDisregarded.length !== 1) { |
| 46 | + return data({ |
| 47 | + status: "offline", |
| 48 | + message: |
| 49 | + "No data received in the last 5 minutes, could not retrieve last data received", |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + const lastObservationTimeAgo = Math.round( |
| 54 | + (new Date().getTime() - lastObservation[0].timestamp.getTime()) / 60000 |
| 55 | + ); |
| 56 | + const lastObservationDisregardedTimeAgo = Math.round( |
| 57 | + (new Date().getTime() - lastObservationDisregarded[0].timestamp.getTime()) / |
| 58 | + 60000 |
| 59 | + ); |
| 60 | + |
| 61 | + return data({ |
| 62 | + status: "offline", |
| 63 | + message: `Last observation was received ${lastObservationTimeAgo} minutes ago, and last disregarded observation was received ${lastObservationDisregardedTimeAgo} minutes ago`, |
| 64 | + }); |
| 65 | +} |
0 commit comments