Rename WifiStats table to AccessPointStats

This commit is contained in:
Douglas Barone 2022-06-20 12:41:16 +00:00
parent 2c6405edc9
commit 1abb3b4716
10 changed files with 80 additions and 57 deletions

View File

@ -1,29 +0,0 @@
/*
Warnings:
- The `uptime` column on the `AccessPoint` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- The `uptime` column on the `WifiDevice` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- You are about to drop the column `avgSignal` on the `WifiStats` table. All the data in the column will be lost.
- You are about to drop the column `maxSignal` on the `WifiStats` table. All the data in the column will be lost.
- You are about to drop the column `minSignal` on the `WifiStats` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "AccessPoint" ADD COLUMN "usage" BIGINT,
DROP COLUMN "uptime",
ADD COLUMN "uptime" INTEGER;
-- AlterTable
ALTER TABLE "WifiDevice" DROP COLUMN "uptime",
ADD COLUMN "uptime" INTEGER,
ALTER COLUMN "usage" SET DATA TYPE BIGINT;
-- AlterTable
ALTER TABLE "WifiStats" DROP COLUMN "avgSignal",
DROP COLUMN "maxSignal",
DROP COLUMN "minSignal",
ADD COLUMN "avgSignalStrength" INTEGER,
ADD COLUMN "maxSignalStrength" INTEGER,
ADD COLUMN "minSignalStrength" INTEGER,
ALTER COLUMN "avgUsage" SET DATA TYPE BIGINT,
ALTER COLUMN "sumUsage" SET DATA TYPE BIGINT;

View File

@ -0,0 +1,46 @@
/*
Warnings:
- The `uptime` column on the `AccessPoint` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- The `uptime` column on the `WifiDevice` table would be dropped and recreated. This will lead to data loss if there is data in the column.
- You are about to drop the `WifiStats` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE "WifiStats" DROP CONSTRAINT "WifiStats_accessPointId_fkey";
-- AlterTable
ALTER TABLE "AccessPoint" ADD COLUMN "usage" BIGINT,
DROP COLUMN "uptime",
ADD COLUMN "uptime" INTEGER;
-- AlterTable
ALTER TABLE "WifiDevice" DROP COLUMN "uptime",
ADD COLUMN "uptime" INTEGER,
ALTER COLUMN "usage" SET DATA TYPE BIGINT;
-- DropTable
DROP TABLE "WifiStats";
-- CreateTable
CREATE TABLE "AccessPointStats" (
"id" SERIAL NOT NULL,
"timestamp" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"clients" INTEGER,
"avgSignalStrength" INTEGER,
"minSignalStrength" INTEGER,
"maxSignalStrength" INTEGER,
"avgSpeed" INTEGER,
"minSpeed" INTEGER,
"maxSpeed" INTEGER,
"avgClientUptime" INTEGER,
"maxClientUptime" INTEGER,
"avgUsage" BIGINT,
"sumUsage" BIGINT,
"accessPointId" INTEGER NOT NULL,
CONSTRAINT "AccessPointStats_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "AccessPointStats" ADD CONSTRAINT "AccessPointStats_accessPointId_fkey" FOREIGN KEY ("accessPointId") REFERENCES "AccessPoint"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@ -174,11 +174,11 @@ model AccessPoint {
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
wifiDevices WifiDevice[] @relation("wifidevice_to_ap") wifiDevices WifiDevice[] @relation("wifidevice_to_ap")
stats WifiStats[] @relation("wifistats_to_ap") stats AccessPointStats[] @relation("accesspointstats_to_ap")
} }
model WifiStats { model AccessPointStats {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
timestamp DateTime @default(now()) timestamp DateTime @default(now())
@ -199,7 +199,7 @@ model WifiStats {
sumUsage BigInt? sumUsage BigInt?
accessPointId Int accessPointId Int
accessPoint AccessPoint @relation("wifistats_to_ap", fields: [accessPointId], references: [id]) accessPoint AccessPoint @relation("accesspointstats_to_ap", fields: [accessPointId], references: [id])
} }
model Network { model Network {

View File

@ -8,7 +8,7 @@ import { updateAccessPoints } from './lib/accessPoints'
import { import {
deleteOldStats, deleteOldStats,
generateStatsForAllAccessPoints generateStatsForAllAccessPoints
} from './lib/wifiStats' } from './lib/accessPointStats'
// WARNING! All crontasks are blocking! Do not await inside it // WARNING! All crontasks are blocking! Do not await inside it

View File

@ -61,7 +61,7 @@ async function generateStatsForAccessPoint(mac) {
sumUsage: dbStats._sum.usage || 0 sumUsage: dbStats._sum.usage || 0
} }
await prisma.wifiStats.create({ await prisma.accessPointStats.create({
data: { data: {
...stats, ...stats,
accessPoint: { connect: { mac } } accessPoint: { connect: { mac } }
@ -78,13 +78,13 @@ export async function generateStatsForAllAccessPoints() {
} }
logSuccess({ logSuccess({
tags: ['wifiStats', 'generateStatsForAllAccessPoints'], tags: ['accessPointStats', 'generateStatsForAllAccessPoints'],
message: `Estatísticas geradas para ${accessPoints.length} access points` message: `Estatísticas geradas para ${accessPoints.length} access points`
}) })
} catch (e) { } catch (e) {
console.log(e) console.log(e)
logError({ logError({
tags: ['wifiStats', 'generateStatsForAllAccessPoints'], tags: ['accessPointStats', 'generateStatsForAllAccessPoints'],
message: 'Erro ao gerar estatísticas para todos os access points', message: 'Erro ao gerar estatísticas para todos os access points',
data: e data: e
}) })
@ -93,17 +93,17 @@ export async function generateStatsForAllAccessPoints() {
export async function deleteOldStats() { export async function deleteOldStats() {
try { try {
const stats = await prisma.wifiStats.deleteMany({ const stats = await prisma.accessPointStats.deleteMany({
where: { timestamp: { lt: subDays(new Date(), DAYS_TO_KEEP) } } where: { timestamp: { lt: subDays(new Date(), DAYS_TO_KEEP) } }
}) })
logSuccess({ logSuccess({
tags: ['wifiStats', 'deleteOldStats'], tags: ['accessPointStats', 'deleteOldStats'],
message: `${stats.count} estatísticas com mais de ${DAYS_TO_KEEP} dias deletadas.` message: `${stats.count} estatísticas com mais de ${DAYS_TO_KEEP} dias deletadas.`
}) })
} catch (e) { } catch (e) {
logError({ logError({
tags: ['wifiStats', 'deleteOldStats'], tags: ['accessPointStats', 'deleteOldStats'],
message: 'Erro ao deletar estatísticas antigas', message: 'Erro ao deletar estatísticas antigas',
data: e data: e
}) })

View File

@ -1,5 +1,7 @@
import prisma from '../prisma' import prisma from '../prisma'
import { getSubnetInfo } from '../lib/subnetInfo' import { getSubnetInfo } from '../lib/subnetInfo'
import { subDays } from 'date-fns'
import { distributedCopy } from '../utils/distributedCopy'
export const AccessPoint = { export const AccessPoint = {
updatedAt: (parent, data, context, info) => parent.updatedAt?.toISOString(), updatedAt: (parent, data, context, info) => parent.updatedAt?.toISOString(),
@ -21,23 +23,28 @@ export const AccessPoint = {
usage: (parent, data, context, info) => parent.usage.toString(), usage: (parent, data, context, info) => parent.usage.toString(),
stats: async (parent, { take, dateIn, dateOut }, context, info) => { stats: async (parent, { take, dateIn, dateOut }, context, info) => {
const stats = await prisma.wifiStats.findMany({ if (!dateOut) {
dateOut = new Date()
dateIn = subDays(dateOut, 1)
}
const stats = await prisma.accessPointStats.findMany({
where: { where: {
accessPoint: { accessPoint: {
id: parent.id, id: parent.id
timestamp_gte: dateIn, },
timestamp_lte: dateOut timestamp: { gte: dateIn, lte: dateOut }
}
}, },
orderBy: { timestamp: 'desc' }, orderBy: { timestamp: 'desc' }
take
}) })
return stats.reverse() if (take) return distributedCopy(stats, take)
return stats
}, },
latestStats: async (parent, data, context, info) => latestStats: async (parent, data, context, info) =>
prisma.wifiStats.findFirst({ prisma.accessPointStats.findFirst({
where: { accessPoint: { id: parent.id } }, where: { accessPoint: { id: parent.id } },
orderBy: { timestamp: 'desc' } orderBy: { timestamp: 'desc' }
}) })

View File

@ -1,7 +1,7 @@
const WifiStats = { const AccessPointStats = {
timestamp: parent => parent.timestamp.toString(), timestamp: parent => parent.timestamp.toString(),
avgUsage: parent => parent.avgUsage.toString(), avgUsage: parent => parent.avgUsage.toString(),
sumUsage: parent => parent.sumUsage.toString() sumUsage: parent => parent.sumUsage.toString()
} }
export { WifiStats } export { AccessPointStats }

View File

@ -11,7 +11,7 @@ import { Stats } from './Stats'
import { User } from './User' import { User } from './User'
import { UserPresence } from './UserPresence' import { UserPresence } from './UserPresence'
import { WifiDevice } from './WifiDevice' import { WifiDevice } from './WifiDevice'
import { WifiStats } from './WifiStats' import { AccessPointStats } from './AccessPointStats'
const resolvers = { const resolvers = {
Mutation, Mutation,
@ -27,7 +27,7 @@ const resolvers = {
User, User,
UserPresence, UserPresence,
WifiDevice, WifiDevice,
WifiStats AccessPointStats
} }
export { resolvers } export { resolvers }

View File

@ -328,12 +328,12 @@ const typeDefs = gql`
updatedAt: String updatedAt: String
wifiDevices: [WifiDevice] wifiDevices: [WifiDevice]
stats(take: Int = 50, dateIn: String, dateOut: String): [WifiStats!]! stats(take: Int = 50, dateIn: String, dateOut: String): [AccessPointStats!]!
latestStats: WifiStats! latestStats: AccessPointStats!
} }
"A Wireless Access Point stats" "A Wireless Access Point stats"
type WifiStats { type AccessPointStats {
id: ID! id: ID!
timestamp: String timestamp: String

View File

@ -16,7 +16,6 @@
<script> <script>
import { Line as LineChart } from 'vue-chartjs/legacy' import { Line as LineChart } from 'vue-chartjs/legacy'
import { time } from '../../plugins/date'
import { Chart as ChartJS, registerables } from 'chart.js' import { Chart as ChartJS, registerables } from 'chart.js'
import 'chartjs-adapter-date-fns' import 'chartjs-adapter-date-fns'