Skip to content

Commit

Permalink
Refactor time filters to use eventBus and rely on FROM/TO
Browse files Browse the repository at this point in the history
  • Loading branch information
insmac committed Dec 12, 2024
1 parent e5b0cb9 commit ae93d16
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 55 deletions.
1 change: 1 addition & 0 deletions packages/web-console/src/modules/EventBus/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ export enum EventType {
REACT_READY = "react.ready",
TAB_FOCUS = "tab.focus",
TAB_BLUR = "tab.blur",
METRICS_REFRESH_DATA = "metrics.refresh.data",
}
8 changes: 4 additions & 4 deletions packages/web-console/src/scenes/Editor/Metrics/graph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ const LabelValue = styled.span`

type Props = {
dateFrom: Date
dateNow: Date
lastRefresh?: number
dateTo: Date
lastRefresh?: Date
tableId?: number
tableName?: string
beforeLabel?: React.ReactNode
Expand All @@ -109,7 +109,7 @@ type Props = {

export const Graph = ({
dateFrom,
dateNow,
dateTo,
lastRefresh,
tableId,
tableName,
Expand Down Expand Up @@ -139,7 +139,7 @@ export const Graph = ({
const graphOptions = useGraphOptions({
data,
dateFrom,
dateNow,
dateTo,
colors,
duration,
timeRef,
Expand Down
39 changes: 15 additions & 24 deletions packages/web-console/src/scenes/Editor/Metrics/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
FetchMode,
SampleBy,
durationInMinutes,
MetricsRefreshPayload,
} from "./utils"
import {
GridAlt,
Expand Down Expand Up @@ -121,19 +122,11 @@ export const Metrics = () => {
const [metricViewMode, setMetricViewMode] = useState<MetricViewMode>(
MetricViewMode.GRID,
)
const [dateFrom, setDateFrom] = useState(
subMinutes(
new Date(),
durationInMinutes[metricDuration || MetricDuration.ONE_HOUR],
),
)
const [dateNow, setDateNow] = useState(new Date())
const [refreshRate, setRefreshRate] = useState<RefreshRate>()
const [sampleBy, setSampleBy] = useState<SampleBy>()
const [dialogOpen, setDialogOpen] = useState(false)
const [metrics, setMetrics] = useState<Metric[]>([])
const telemetryConfig = useSelector(selectors.telemetry.getConfig)
const [lastRefresh, setLastRefresh] = useState<number | undefined>()
const [fetchMode, setFetchMode] = useState<FetchMode>(FetchMode.OVERWRITE)

const tabInFocusRef = React.useRef<boolean>(true)
Expand Down Expand Up @@ -170,6 +163,16 @@ export const Metrics = () => {
}
}

const refreshMetricsData = () => {
const now = new Date()
const dateFrom = subMinutes(now, durationInMinutes[duration])
const dateTo = now
eventBus.publish<MetricsRefreshPayload>(EventType.METRICS_REFRESH_DATA, {
dateFrom,
dateTo,
})
}

const handleRemoveMetric = (metric: Metric) => {
if (buffer?.id && buffer?.metricsViewState?.metrics) {
updateMetrics(
Expand Down Expand Up @@ -204,7 +207,7 @@ export const Metrics = () => {
tabInFocusRef.current = true
if (refreshRateRef.current !== RefreshRate.OFF) {
setFetchMode(FetchMode.OVERWRITE)
setLastRefresh(new Date().getTime())
refreshMetricsData()
}
}, [refreshRateRef.current])

Expand All @@ -221,7 +224,7 @@ export const Metrics = () => {
() => {
if (!tabInFocusRef.current) return
setFetchMode(FetchMode.ROLLING_APPEND)
setLastRefresh(new Date().getTime())
refreshMetricsData()
},
refreshRateInSec > 0 ? refreshRateInSec * 1000 : 0,
)
Expand Down Expand Up @@ -278,17 +281,11 @@ export const Metrics = () => {
if (metricDuration && refreshRate && metricViewMode && sampleBy) {
updateBuffer(buffer.id, merged)
setFetchMode(FetchMode.OVERWRITE)
setLastRefresh(new Date().getTime())
refreshMetricsData()
}
}
}, [metricDuration, refreshRate, metricViewMode, sampleBy])

useEffect(() => {
const now = new Date()
setDateFrom(subMinutes(now, durationInMinutes[duration]))
setDateNow(now)
}, [lastRefresh])

useEffect(() => {
if (refreshRate) {
refreshRateRef.current = refreshRate
Expand Down Expand Up @@ -371,10 +368,7 @@ export const Metrics = () => {
<Box gap="0.5rem" style={{ flexShrink: 0 }}>
<IconWithTooltip
icon={
<Button
skin="secondary"
onClick={() => setLastRefresh(new Date().getTime())}
>
<Button skin="secondary" onClick={() => refreshMetricsData()}>
<Refresh size="20px" />
</Button>
}
Expand Down Expand Up @@ -461,8 +455,6 @@ export const Metrics = () => {
.sort((a, b) => a.position - b.position)
.map((metric, index) => (
<MetricComponent
dateFrom={dateFrom}
dateNow={dateNow}
key={index}
metric={metric}
metricDuration={duration}
Expand All @@ -475,7 +467,6 @@ export const Metrics = () => {
onTableChange={handleTableChange}
onColorChange={handleColorChange}
onMetricDurationChange={setMetricDuration}
lastRefresh={lastRefresh}
fetchMode={fetchMode}
rollingAppendLimit={rollingAppendLimit}
/>
Expand Down
69 changes: 45 additions & 24 deletions packages/web-console/src/scenes/Editor/Metrics/metric.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
mergeRollingData,
SampleBy,
getTimeFilter,
MetricsRefreshPayload,
} from "./utils"
import { widgets } from "./widgets"
import { QuestContext } from "../../../providers"
Expand All @@ -26,6 +27,8 @@ import { TableSelector } from "./table-selector"
import { IconWithTooltip } from "../../../components/IconWithTooltip"
import { ColorPalette } from "./color-palette"
import { subMinutes } from "date-fns"
import { eventBus } from "../../../modules/EventBus"
import { EventType } from "../../../modules/EventBus/types"

const MetricInfoRoot = styled(Box).attrs({
align: "center",
Expand All @@ -41,8 +44,6 @@ const ActionButton = styled(Button)`
`

export const Metric = ({
dateFrom,
dateNow,
metric,
metricDuration,
onRemove,
Expand All @@ -54,15 +55,13 @@ export const Metric = ({
rollingAppendLimit,
sampleBy,
}: {
dateFrom: Date
dateNow: Date
metric: MetricItem
metricDuration: MetricDuration
onRemove: (metric: MetricItem) => void
onTableChange: (metric: MetricItem, tableId: number) => void
onColorChange: (metric: MetricItem, color: string) => void
onMetricDurationChange: (duration: MetricDuration) => void
lastRefresh?: number
lastRefresh?: Date
fetchMode: FetchMode
rollingAppendLimit: number
sampleBy: SampleBy
Expand All @@ -72,6 +71,7 @@ export const Metric = ({
const [data, setData] = useState<uPlot.AlignedData>([[], []])
const [lastNotNull, setLastNotNull] = useState<number>()
const [colorPickerOpen, setColorPickerOpen] = useState(false)
const [fromTo, setFromTo] = useState<MetricsRefreshPayload>()

const tables = useSelector(selectors.query.getTables)

Expand All @@ -81,11 +81,18 @@ export const Metric = ({
durationInMinutes,
) as [MetricDuration, number][]

const isRollingAppendEnabled =
data &&
widgetConfig.querySupportsRollingAppend &&
fetchMode === FetchMode.ROLLING_APPEND

const fetchMetric = async () => {
setLoading(true)
if (!fromTo) return
const { dateFrom, dateTo } = fromTo
const timeout = setTimeout(() => setLoading(true), 250)
try {
const subtracted = subMinutes(dateNow, durationInMinutes[metricDuration])
const timeFilter = getTimeFilter(subtracted, dateNow)
const subtracted = subMinutes(dateTo, durationInMinutes[metricDuration])
const timeFilter = getTimeFilter(subtracted, dateTo)
const responses = await Promise.all<
| QuestDB.QueryResult<ResultType[MetricType]>
| QuestDB.QueryResult<LastNotNull>
Expand All @@ -96,10 +103,9 @@ export const Metric = ({
metricDuration,
sampleBy,
timeFilter,
...(widgetConfig.querySupportsRollingAppend &&
fetchMode === FetchMode.ROLLING_APPEND && {
limit: -rollingAppendLimit,
}),
...(isRollingAppendEnabled && {
limit: -rollingAppendLimit,
}),
}),
),
quest.query<LastNotNull>(
Expand All @@ -111,12 +117,7 @@ export const Metric = ({
const alignedData = widgetConfig.alignData(
responses[0].data as unknown as ResultType[MetricType],
)
if (
data &&
widgetConfig.querySupportsRollingAppend &&
fetchMode === FetchMode.ROLLING_APPEND
) {
console.log(mergeRollingData(data, alignedData, dateFrom))
if (isRollingAppendEnabled) {
setData(mergeRollingData(data, alignedData, dateFrom))
} else {
setData(alignedData)
Expand All @@ -132,6 +133,7 @@ export const Metric = ({
} catch (err) {
console.error(err)
} finally {
clearTimeout(timeout)
setLoading(false)
}
}
Expand All @@ -147,11 +149,28 @@ export const Metric = ({
}
}

const refreshMetricsData = (payload?: MetricsRefreshPayload) => {
if (payload) {
setFromTo(payload)
}
}

useEffect(() => {
if (lastRefresh && metric.tableId) {
if (metric.tableId && fromTo) {
fetchMetric()
}
}, [lastRefresh, metric.tableId])
}, [metric.tableId, fromTo])

useEffect(() => {
eventBus.subscribe<MetricsRefreshPayload>(
EventType.METRICS_REFRESH_DATA,
refreshMetricsData,
)

return () => {
eventBus.unsubscribe(EventType.METRICS_REFRESH_DATA, refreshMetricsData)
}
}, [])

if (!data && !loading && metric.tableId)
return (
Expand All @@ -164,18 +183,20 @@ export const Metric = ({
const tableName = tables.find((t) => t.id === metric.tableId)?.table_name

const canZoomToData =
tableName && lastNotNull
fromTo?.dateTo && tableName && lastNotNull
? lastNotNull >=
subMinutes(
dateNow,
fromTo.dateTo,
minuteDurations[minuteDurations.length - 1][1],
).getTime()
: false

if (!fromTo) return null

return (
<Graph
dateFrom={dateFrom}
dateNow={dateNow}
dateFrom={fromTo.dateFrom}
dateTo={fromTo.dateTo}
lastRefresh={lastRefresh}
data={metric.tableId && hasData(data) ? data : [[], []]}
canZoomToData={canZoomToData}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { MetricDuration, durationInMinutes } from "./utils"
type Params = {
data: uPlot.AlignedData
dateFrom: Date
dateNow: Date
dateTo: Date
colors: string[]
duration: MetricDuration
tickValue?: (rawValue: number) => string
Expand Down Expand Up @@ -49,7 +49,7 @@ const valuePlugin = (
export const useGraphOptions = ({
data,
dateFrom,
dateNow,
dateTo,
colors,
duration,
tickValue = (rawValue) => (+rawValue).toString(),
Expand All @@ -62,7 +62,7 @@ export const useGraphOptions = ({

const start = dateFrom.getTime()

const end = dateNow.getTime()
const end = dateTo.getTime()

const baseAxisConfig: uPlot.Axis = {
stroke: theme.color.gray2,
Expand Down
5 changes: 5 additions & 0 deletions packages/web-console/src/scenes/Editor/Metrics/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ export type Widget = {
mapYValue: (rawValue: number) => string
}

export type MetricsRefreshPayload = {
dateFrom: Date
dateTo: Date
}

export enum MetricDuration {
FIVE_MINUTES = "5m",
FIFTEEN_MINUTES = "15m",
Expand Down

0 comments on commit ae93d16

Please sign in to comment.