Compare commits

..

1 Commits

Author SHA1 Message Date
Fred KISSIE 1580b7abff 🚧 wip: batch status histories 2026-07-10 07:02:22 +02:00
18 changed files with 163 additions and 31 deletions
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Създаване на Организационна Потребител", "createOrgUser": "Създаване на Организационна Потребител",
"actionUpdateOrg": "Актуализиране на организацията", "actionUpdateOrg": "Актуализиране на организацията",
"actionRemoveInvitation": "Премахване на поканата.", "actionRemoveInvitation": "Премахване на поканата.",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Актуализиране на потребител", "actionUpdateUser": "Актуализиране на потребител",
"actionGetUser": "Получаване на потребител", "actionGetUser": "Получаване на потребител",
"actionGetOrgUser": "Вземете потребител на организация", "actionGetOrgUser": "Вземете потребител на организация",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Въведете кода от приложението за удостоверяване или един от вашите резервни кодове за еднократна употреба.", "otpAuthDescription": "Въведете кода от приложението за удостоверяване или един от вашите резервни кодове за еднократна употреба.",
"otpAuthSubmit": "Изпрати код", "otpAuthSubmit": "Изпрати код",
"idpContinue": "Или продължете със", "idpContinue": "Или продължете със",
"idpLastUsed": "Last Used",
"otpAuthBack": "Назад към парола", "otpAuthBack": "Назад към парола",
"navbar": "Навигационно меню", "navbar": "Навигационно меню",
"navbarDescription": "Главно навигационно меню за приложението", "navbarDescription": "Главно навигационно меню за приложението",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Vytvořit Org uživatele", "createOrgUser": "Vytvořit Org uživatele",
"actionUpdateOrg": "Aktualizovat organizaci", "actionUpdateOrg": "Aktualizovat organizaci",
"actionRemoveInvitation": "Odstranit pozvání", "actionRemoveInvitation": "Odstranit pozvání",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Aktualizovat uživatele", "actionUpdateUser": "Aktualizovat uživatele",
"actionGetUser": "Získat uživatele", "actionGetUser": "Získat uživatele",
"actionGetOrgUser": "Získat uživatele organizace", "actionGetOrgUser": "Získat uživatele organizace",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Zadejte kód z vaší autentizační aplikace nebo jeden z vlastních záložních kódů.", "otpAuthDescription": "Zadejte kód z vaší autentizační aplikace nebo jeden z vlastních záložních kódů.",
"otpAuthSubmit": "Odeslat kód", "otpAuthSubmit": "Odeslat kód",
"idpContinue": "Nebo pokračovat s", "idpContinue": "Nebo pokračovat s",
"idpLastUsed": "Last Used",
"otpAuthBack": "Zpět na heslo", "otpAuthBack": "Zpět na heslo",
"navbar": "Navigation Menu", "navbar": "Navigation Menu",
"navbarDescription": "Hlavní navigační menu aplikace", "navbarDescription": "Hlavní navigační menu aplikace",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Opret organisationsbruger", "createOrgUser": "Opret organisationsbruger",
"actionUpdateOrg": "Opdater organisation", "actionUpdateOrg": "Opdater organisation",
"actionRemoveInvitation": "Fjern invitation", "actionRemoveInvitation": "Fjern invitation",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Opdater bruger", "actionUpdateUser": "Opdater bruger",
"actionGetUser": "Hent bruger", "actionGetUser": "Hent bruger",
"actionGetOrgUser": "Hent organisationsbruger", "actionGetOrgUser": "Hent organisationsbruger",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Indtast koden fra autentiseringsappen din eller en af dine engangs reservekoder.", "otpAuthDescription": "Indtast koden fra autentiseringsappen din eller en af dine engangs reservekoder.",
"otpAuthSubmit": "Send kode", "otpAuthSubmit": "Send kode",
"idpContinue": "Eller fortsæt med", "idpContinue": "Eller fortsæt med",
"idpLastUsed": "Last Used",
"otpAuthBack": "Tilbage til adgangskode", "otpAuthBack": "Tilbage til adgangskode",
"navbar": "Navigationsmenu", "navbar": "Navigationsmenu",
"navbarDescription": "Hovednavigasjonsmeny for applikationen", "navbarDescription": "Hovednavigasjonsmeny for applikationen",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Org Benutzer erstellen", "createOrgUser": "Org Benutzer erstellen",
"actionUpdateOrg": "Organisation aktualisieren", "actionUpdateOrg": "Organisation aktualisieren",
"actionRemoveInvitation": "Einladung entfernen", "actionRemoveInvitation": "Einladung entfernen",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Benutzer aktualisieren", "actionUpdateUser": "Benutzer aktualisieren",
"actionGetUser": "Benutzer abrufen", "actionGetUser": "Benutzer abrufen",
"actionGetOrgUser": "Organisationsbenutzer abrufen", "actionGetOrgUser": "Organisationsbenutzer abrufen",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Geben Sie den Code aus Ihrer Authenticator-App oder einen Ihrer einmaligen Backup-Codes ein.", "otpAuthDescription": "Geben Sie den Code aus Ihrer Authenticator-App oder einen Ihrer einmaligen Backup-Codes ein.",
"otpAuthSubmit": "Code absenden", "otpAuthSubmit": "Code absenden",
"idpContinue": "Oder weiter mit", "idpContinue": "Oder weiter mit",
"idpLastUsed": "Last Used",
"otpAuthBack": "Zurück zum Passwort", "otpAuthBack": "Zurück zum Passwort",
"navbar": "Navigationsmenü", "navbar": "Navigationsmenü",
"navbarDescription": "Hauptnavigationsmenü für die Anwendung", "navbarDescription": "Hauptnavigationsmenü für die Anwendung",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Crear usuario Org", "createOrgUser": "Crear usuario Org",
"actionUpdateOrg": "Actualizar organización", "actionUpdateOrg": "Actualizar organización",
"actionRemoveInvitation": "Eliminar invitación", "actionRemoveInvitation": "Eliminar invitación",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Actualizar usuario", "actionUpdateUser": "Actualizar usuario",
"actionGetUser": "Obtener usuario", "actionGetUser": "Obtener usuario",
"actionGetOrgUser": "Obtener usuario de la organización", "actionGetOrgUser": "Obtener usuario de la organización",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Introduzca el código de su aplicación de autenticación o uno de sus códigos de copia de seguridad de un solo uso.", "otpAuthDescription": "Introduzca el código de su aplicación de autenticación o uno de sus códigos de copia de seguridad de un solo uso.",
"otpAuthSubmit": "Enviar código", "otpAuthSubmit": "Enviar código",
"idpContinue": "O continuar con", "idpContinue": "O continuar con",
"idpLastUsed": "Last Used",
"otpAuthBack": "Volver a la contraseña", "otpAuthBack": "Volver a la contraseña",
"navbar": "Menú de navegación", "navbar": "Menú de navegación",
"navbarDescription": "Menú de navegación principal para la aplicación", "navbarDescription": "Menú de navegación principal para la aplicación",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Créer un utilisateur Org", "createOrgUser": "Créer un utilisateur Org",
"actionUpdateOrg": "Mettre à jour l'organisation", "actionUpdateOrg": "Mettre à jour l'organisation",
"actionRemoveInvitation": "Supprimer l'invitation", "actionRemoveInvitation": "Supprimer l'invitation",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Mettre à jour l'utilisateur", "actionUpdateUser": "Mettre à jour l'utilisateur",
"actionGetUser": "Obtenir l'utilisateur", "actionGetUser": "Obtenir l'utilisateur",
"actionGetOrgUser": "Obtenir l'utilisateur de l'organisation", "actionGetOrgUser": "Obtenir l'utilisateur de l'organisation",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Entrez le code de votre application d'authentification ou l'un de vos codes de secours à usage unique.", "otpAuthDescription": "Entrez le code de votre application d'authentification ou l'un de vos codes de secours à usage unique.",
"otpAuthSubmit": "Soumettre le code", "otpAuthSubmit": "Soumettre le code",
"idpContinue": "Ou continuer avec", "idpContinue": "Ou continuer avec",
"idpLastUsed": "Last Used",
"otpAuthBack": "Retour au mot de passe", "otpAuthBack": "Retour au mot de passe",
"navbar": "Menu de navigation", "navbar": "Menu de navigation",
"navbarDescription": "Menu de navigation principal de l'application", "navbarDescription": "Menu de navigation principal de l'application",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Crea Utente Org", "createOrgUser": "Crea Utente Org",
"actionUpdateOrg": "Aggiorna Organizzazione", "actionUpdateOrg": "Aggiorna Organizzazione",
"actionRemoveInvitation": "Rimuovi Invito", "actionRemoveInvitation": "Rimuovi Invito",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Aggiorna Utente", "actionUpdateUser": "Aggiorna Utente",
"actionGetUser": "Ottieni Utente", "actionGetUser": "Ottieni Utente",
"actionGetOrgUser": "Ottieni Utente Organizzazione", "actionGetOrgUser": "Ottieni Utente Organizzazione",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Inserisci il codice dalla tua app di autenticazione o uno dei tuoi codici di backup monouso.", "otpAuthDescription": "Inserisci il codice dalla tua app di autenticazione o uno dei tuoi codici di backup monouso.",
"otpAuthSubmit": "Invia Codice", "otpAuthSubmit": "Invia Codice",
"idpContinue": "O continua con", "idpContinue": "O continua con",
"idpLastUsed": "Last Used",
"otpAuthBack": "Torna alla Password", "otpAuthBack": "Torna alla Password",
"navbar": "Menu di Navigazione", "navbar": "Menu di Navigazione",
"navbarDescription": "Menu di navigazione principale dell'applicazione", "navbarDescription": "Menu di navigazione principale dell'applicazione",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "조직 사용자 생성", "createOrgUser": "조직 사용자 생성",
"actionUpdateOrg": "조직 업데이트", "actionUpdateOrg": "조직 업데이트",
"actionRemoveInvitation": "초대 제거", "actionRemoveInvitation": "초대 제거",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "사용자 업데이트", "actionUpdateUser": "사용자 업데이트",
"actionGetUser": "사용자 조회", "actionGetUser": "사용자 조회",
"actionGetOrgUser": "조직 사용자 가져오기", "actionGetOrgUser": "조직 사용자 가져오기",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "인증 앱에서 코드를 입력하거나 단일 사용 백업 코드 중 하나를 입력하세요.", "otpAuthDescription": "인증 앱에서 코드를 입력하거나 단일 사용 백업 코드 중 하나를 입력하세요.",
"otpAuthSubmit": "코드 제출", "otpAuthSubmit": "코드 제출",
"idpContinue": "또는 계속 진행하십시오.", "idpContinue": "또는 계속 진행하십시오.",
"idpLastUsed": "Last Used",
"otpAuthBack": "비밀번호로 돌아가기", "otpAuthBack": "비밀번호로 돌아가기",
"navbar": "탐색 메뉴", "navbar": "탐색 메뉴",
"navbarDescription": "애플리케이션의 주요 탐색 메뉴", "navbarDescription": "애플리케이션의 주요 탐색 메뉴",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Opprett Org bruker", "createOrgUser": "Opprett Org bruker",
"actionUpdateOrg": "Oppdater organisasjon", "actionUpdateOrg": "Oppdater organisasjon",
"actionRemoveInvitation": "Fjern invitasjon", "actionRemoveInvitation": "Fjern invitasjon",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Oppdater bruker", "actionUpdateUser": "Oppdater bruker",
"actionGetUser": "Hent bruker", "actionGetUser": "Hent bruker",
"actionGetOrgUser": "Hent organisasjonsbruker", "actionGetOrgUser": "Hent organisasjonsbruker",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Skriv inn koden fra autentiseringsappen din eller en av dine engangs reservekoder.", "otpAuthDescription": "Skriv inn koden fra autentiseringsappen din eller en av dine engangs reservekoder.",
"otpAuthSubmit": "Send inn kode", "otpAuthSubmit": "Send inn kode",
"idpContinue": "Eller fortsett med", "idpContinue": "Eller fortsett med",
"idpLastUsed": "Last Used",
"otpAuthBack": "Tilbake til passord", "otpAuthBack": "Tilbake til passord",
"navbar": "Navigasjonsmeny", "navbar": "Navigasjonsmeny",
"navbarDescription": "Hovednavigasjonsmeny for applikasjonen", "navbarDescription": "Hovednavigasjonsmeny for applikasjonen",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Org gebruiker aanmaken", "createOrgUser": "Org gebruiker aanmaken",
"actionUpdateOrg": "Organisatie bijwerken", "actionUpdateOrg": "Organisatie bijwerken",
"actionRemoveInvitation": "Verwijder uitnodiging", "actionRemoveInvitation": "Verwijder uitnodiging",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Gebruiker bijwerken", "actionUpdateUser": "Gebruiker bijwerken",
"actionGetUser": "Gebruiker ophalen", "actionGetUser": "Gebruiker ophalen",
"actionGetOrgUser": "Krijg organisatie-gebruiker", "actionGetOrgUser": "Krijg organisatie-gebruiker",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Voer de code van je authenticator-app of een van je reservekopiecodes voor het eenmalig gebruik in.", "otpAuthDescription": "Voer de code van je authenticator-app of een van je reservekopiecodes voor het eenmalig gebruik in.",
"otpAuthSubmit": "Code indienen", "otpAuthSubmit": "Code indienen",
"idpContinue": "Of ga verder met", "idpContinue": "Of ga verder met",
"idpLastUsed": "Last Used",
"otpAuthBack": "Terug naar wachtwoord", "otpAuthBack": "Terug naar wachtwoord",
"navbar": "Navigatiemenu", "navbar": "Navigatiemenu",
"navbarDescription": "Hoofd navigatie menu voor de applicatie", "navbarDescription": "Hoofd navigatie menu voor de applicatie",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Utwórz użytkownika Org", "createOrgUser": "Utwórz użytkownika Org",
"actionUpdateOrg": "Aktualizuj organizację", "actionUpdateOrg": "Aktualizuj organizację",
"actionRemoveInvitation": "Usuń zaproszenie", "actionRemoveInvitation": "Usuń zaproszenie",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Zaktualizuj użytkownika", "actionUpdateUser": "Zaktualizuj użytkownika",
"actionGetUser": "Pobierz użytkownika", "actionGetUser": "Pobierz użytkownika",
"actionGetOrgUser": "Pobierz użytkownika organizacji", "actionGetOrgUser": "Pobierz użytkownika organizacji",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Wprowadź kod z aplikacji uwierzytelniającej lub jeden z jednorazowych kodów zapasowych.", "otpAuthDescription": "Wprowadź kod z aplikacji uwierzytelniającej lub jeden z jednorazowych kodów zapasowych.",
"otpAuthSubmit": "Wyślij kod", "otpAuthSubmit": "Wyślij kod",
"idpContinue": "Lub kontynuuj z", "idpContinue": "Lub kontynuuj z",
"idpLastUsed": "Last Used",
"otpAuthBack": "Powrót do hasła", "otpAuthBack": "Powrót do hasła",
"navbar": "Menu nawigacyjne", "navbar": "Menu nawigacyjne",
"navbarDescription": "Główne menu nawigacyjne aplikacji", "navbarDescription": "Główne menu nawigacyjne aplikacji",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Criar utilizador Org", "createOrgUser": "Criar utilizador Org",
"actionUpdateOrg": "Atualizar Organização", "actionUpdateOrg": "Atualizar Organização",
"actionRemoveInvitation": "Remover Convite", "actionRemoveInvitation": "Remover Convite",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Atualizar Usuário", "actionUpdateUser": "Atualizar Usuário",
"actionGetUser": "Obter Usuário", "actionGetUser": "Obter Usuário",
"actionGetOrgUser": "Obter Utilizador da Organização", "actionGetOrgUser": "Obter Utilizador da Organização",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Insira o código da sua aplicação de autenticação ou um dos seus códigos de backup de uso único.", "otpAuthDescription": "Insira o código da sua aplicação de autenticação ou um dos seus códigos de backup de uso único.",
"otpAuthSubmit": "Submeter Código", "otpAuthSubmit": "Submeter Código",
"idpContinue": "Ou continuar com", "idpContinue": "Ou continuar com",
"idpLastUsed": "Last Used",
"otpAuthBack": "Voltar à Palavra-passe", "otpAuthBack": "Voltar à Palavra-passe",
"navbar": "Menu de Navegação", "navbar": "Menu de Navegação",
"navbarDescription": "Menu de navegação principal da aplicação", "navbarDescription": "Menu de navegação principal da aplicação",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Создать пользователя Org", "createOrgUser": "Создать пользователя Org",
"actionUpdateOrg": "Обновить организацию", "actionUpdateOrg": "Обновить организацию",
"actionRemoveInvitation": "Удалить приглашение", "actionRemoveInvitation": "Удалить приглашение",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Обновить пользователя", "actionUpdateUser": "Обновить пользователя",
"actionGetUser": "Получить пользователя", "actionGetUser": "Получить пользователя",
"actionGetOrgUser": "Получить пользователя организации", "actionGetOrgUser": "Получить пользователя организации",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Введите код из вашего приложения-аутентификатора или один из ваших одноразовых резервных кодов.", "otpAuthDescription": "Введите код из вашего приложения-аутентификатора или один из ваших одноразовых резервных кодов.",
"otpAuthSubmit": "Отправить код", "otpAuthSubmit": "Отправить код",
"idpContinue": "Или продолжить с", "idpContinue": "Или продолжить с",
"idpLastUsed": "Last Used",
"otpAuthBack": "Назад к паролю", "otpAuthBack": "Назад к паролю",
"navbar": "Навигационное меню", "navbar": "Навигационное меню",
"navbarDescription": "Главное навигационное меню приложения", "navbarDescription": "Главное навигационное меню приложения",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "Organizasyon Kullanıcısı Oluştur", "createOrgUser": "Organizasyon Kullanıcısı Oluştur",
"actionUpdateOrg": "Kuruluşu Güncelle", "actionUpdateOrg": "Kuruluşu Güncelle",
"actionRemoveInvitation": "Daveti Kaldır", "actionRemoveInvitation": "Daveti Kaldır",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "Kullanıcıyı Güncelle", "actionUpdateUser": "Kullanıcıyı Güncelle",
"actionGetUser": "Kullanıcıyı Getir", "actionGetUser": "Kullanıcıyı Getir",
"actionGetOrgUser": "Kuruluş Kullanıcısını Al", "actionGetOrgUser": "Kuruluş Kullanıcısını Al",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "Authenticator uygulamanızdan veya tek kullanımlık yedek kodlarınızdan birini girin.", "otpAuthDescription": "Authenticator uygulamanızdan veya tek kullanımlık yedek kodlarınızdan birini girin.",
"otpAuthSubmit": "Kodu Gönder", "otpAuthSubmit": "Kodu Gönder",
"idpContinue": "Veya devam et:", "idpContinue": "Veya devam et:",
"idpLastUsed": "Last Used",
"otpAuthBack": "Şifreye Geri Dön", "otpAuthBack": "Şifreye Geri Dön",
"navbar": "Navigasyon Menüsü", "navbar": "Navigasyon Menüsü",
"navbarDescription": "Uygulamanın ana navigasyon menüsü", "navbarDescription": "Uygulamanın ana navigasyon menüsü",
-2
View File
@@ -1397,7 +1397,6 @@
"createOrgUser": "创建组织用户", "createOrgUser": "创建组织用户",
"actionUpdateOrg": "更新组织", "actionUpdateOrg": "更新组织",
"actionRemoveInvitation": "移除邀请", "actionRemoveInvitation": "移除邀请",
"actionRemoveUserRole": "Remove User Role",
"actionUpdateUser": "更新用户", "actionUpdateUser": "更新用户",
"actionGetUser": "获取用户", "actionGetUser": "获取用户",
"actionGetOrgUser": "获取组织用户", "actionGetOrgUser": "获取组织用户",
@@ -1517,7 +1516,6 @@
"otpAuthDescription": "从您的身份验证程序中输入代码或您的单次备份代码。", "otpAuthDescription": "从您的身份验证程序中输入代码或您的单次备份代码。",
"otpAuthSubmit": "提交代码", "otpAuthSubmit": "提交代码",
"idpContinue": "或者继续", "idpContinue": "或者继续",
"idpLastUsed": "Last Used",
"otpAuthBack": "回到密码", "otpAuthBack": "回到密码",
"navbar": "导航菜单", "navbar": "导航菜单",
"navbarDescription": "应用程序的主导航菜单", "navbarDescription": "应用程序的主导航菜单",
+79 -1
View File
@@ -1,6 +1,6 @@
import { z } from "zod"; import { z } from "zod";
import { db, logsDb, statusHistory } from "@server/db"; import { db, logsDb, statusHistory } from "@server/db";
import { and, eq, gte, lt, asc, desc } from "drizzle-orm"; import { and, eq, gte, lt, asc, desc, inArray } from "drizzle-orm";
import { regionalCache as cache } from "#dynamic/lib/cache"; import { regionalCache as cache } from "#dynamic/lib/cache";
const STATUS_HISTORY_CACHE_TTL = 60; // seconds const STATUS_HISTORY_CACHE_TTL = 60; // seconds
@@ -273,3 +273,81 @@ export function computeBuckets(
return { buckets, totalDowntime }; return { buckets, totalDowntime };
} }
export interface BatchedStatusHistoryResponse {
entityType: string;
entityIds: number[];
days: StatusHistoryDayBucket[];
overallUptimePercent: number;
totalDowntimeSeconds: number;
}
export async function getBatchedStatusHistory(
entityType: string,
entityIds: number[],
days: number
): Promise<BatchedStatusHistoryResponse> {
// const cacheKey = statusHistoryCacheKey(entityType, entityId, days);
// const cached = await cache.get<StatusHistoryResponse>(cacheKey);
// if (cached !== undefined) {
// return cached;
// }
// Anchor to UTC midnight so the query window aligns with stable calendar days
const utcToday = new Date();
utcToday.setUTCHours(0, 0, 0, 0);
const todayMidnightSec = Math.floor(utcToday.getTime() / 1000);
const startSec = todayMidnightSec - days * 86400;
const events = await logsDb
.select()
.from(statusHistory)
.where(
and(
eq(statusHistory.entityType, entityType),
inArray(statusHistory.entityId, entityIds),
gte(statusHistory.timestamp, startSec)
)
)
.orderBy(asc(statusHistory.timestamp));
// Fetch the last known state before the window so that entities that
// haven't changed status recently still show the correct status rather
// than appearing as "no_data".
const [lastKnownEvent] = await logsDb
.select()
.from(statusHistory)
.where(
and(
eq(statusHistory.entityType, entityType),
inArray(statusHistory.entityId, entityIds),
lt(statusHistory.timestamp, startSec)
)
)
.orderBy(desc(statusHistory.timestamp))
.limit(1);
const priorStatus = lastKnownEvent?.status ?? null;
const { buckets, totalDowntime } = computeBuckets(
events,
days,
priorStatus
);
const totalWindow = days * 86400;
const overallUptime =
totalWindow > 0
? Math.max(0, ((totalWindow - totalDowntime) / totalWindow) * 100)
: 100;
const result: BatchedStatusHistoryResponse = {
entityType,
entityIds,
days: buckets,
overallUptimePercent: Math.round(overallUptime * 100) / 100,
totalDowntimeSeconds: totalDowntime
};
// await cache.set(cacheKey, result, STATUS_HISTORY_CACHE_TTL);
return result;
}
@@ -0,0 +1,62 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import {
getCachedStatusHistory,
statusHistoryQuerySchema,
StatusHistoryResponse
} from "@server/lib/statusHistory";
const siteParamsSchema = z.object({
siteId: z.string().transform((v) => parseInt(v, 10))
});
export async function getBatchedSiteStatusHistory(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = siteParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedQuery = statusHistoryQuerySchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error).toString()
)
);
}
const entityType = "site";
const entityId = parsedParams.data.siteId;
const { days } = parsedQuery.data;
const data = await getCachedStatusHistory(entityType, entityId, days);
return response<StatusHistoryResponse>(res, {
data,
success: true,
error: false,
message: "Status history retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}
+22
View File
@@ -640,6 +640,28 @@ export const orgQueries = {
}; };
} }
}), }),
batchedSiteStatusHistory: ({
siteIds,
days = 90
}: {
siteIds: number[];
days?: number;
}) =>
queryOptions({
queryKey: [
"SITE_STATUS_HISTORY",
"BATCHED",
siteIds,
days
] as const,
queryFn: async ({ signal, meta }) => {
// TODO
// const res = await meta!.api.get<
// AxiosResponse<StatusHistoryResponse>
// >(`/site/${siteId}/status-history?days=${days}`, { signal });
// return res.data.data;
}
}),
siteStatusHistory: ({ siteStatusHistory: ({
siteId, siteId,
days = 90 days = 90