@perses-dev/plugin-system 0.54.0-beta.1 → 0.54.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/components/PluginRegistry/PluginRegistry.js +11 -15
- package/dist/cjs/components/PluginRegistry/getPluginSearchHelper.js +92 -0
- package/dist/cjs/components/PluginRegistry/plugin-indexes.js +16 -13
- package/dist/cjs/components/Variables/variable-model.js +115 -29
- package/dist/cjs/context/ValidationProvider.js +3 -3
- package/dist/cjs/model/alerts-queries.js +16 -0
- package/dist/cjs/model/index.js +2 -0
- package/dist/cjs/model/log-volume-utils.js +10 -10
- package/dist/cjs/model/plugin-loading.js +24 -8
- package/dist/cjs/model/plugins.js +10 -0
- package/dist/cjs/model/silences-queries.js +16 -0
- package/dist/cjs/remote/PluginRuntime.js +38 -9
- package/dist/cjs/remote/remotePluginLoader.js +28 -5
- package/dist/cjs/runtime/DataQueriesProvider/DataQueriesProvider.js +18 -2
- package/dist/cjs/runtime/DataQueriesProvider/model.js +30 -4
- package/dist/cjs/runtime/UsageMetricsProvider.js +2 -2
- package/dist/cjs/runtime/alerts-queries.js +101 -0
- package/dist/cjs/runtime/index.js +2 -0
- package/dist/cjs/runtime/item-actions.js +3 -3
- package/dist/cjs/runtime/log-queries.js +4 -1
- package/dist/cjs/runtime/plugin-registry.js +12 -3
- package/dist/cjs/runtime/profile-queries.js +4 -1
- package/dist/cjs/runtime/silences-queries.js +101 -0
- package/dist/cjs/runtime/time-series-queries.js +4 -1
- package/dist/cjs/runtime/trace-queries.js +4 -1
- package/dist/cjs/test/mock-data.js +51 -0
- package/dist/cjs/test/test-plugins/bert/index.js +9 -12
- package/dist/cjs/test/test-plugins/ernie/index.js +9 -12
- package/dist/cjs/test/test-plugins/index.js +2 -2
- package/dist/cjs/test-utils/mock-plugin-registry.js +8 -2
- package/dist/components/CalculationSelector/CalculationSelector.js +1 -1
- package/dist/components/CalculationSelector/CalculationSelector.js.map +1 -1
- package/dist/components/DatasourceEditorForm/DatasourceEditorForm.d.ts +1 -1
- package/dist/components/DatasourceEditorForm/DatasourceEditorForm.d.ts.map +1 -1
- package/dist/components/DatasourceEditorForm/DatasourceEditorForm.js +1 -1
- package/dist/components/DatasourceEditorForm/DatasourceEditorForm.js.map +1 -1
- package/dist/components/DatasourceSelect/DatasourceSelect.js +2 -2
- package/dist/components/DatasourceSelect/DatasourceSelect.js.map +1 -1
- package/dist/components/HTTPSettingsEditor/HTTPSettingsEditor.d.ts +1 -1
- package/dist/components/HTTPSettingsEditor/HTTPSettingsEditor.d.ts.map +1 -1
- package/dist/components/HTTPSettingsEditor/HTTPSettingsEditor.js +1 -1
- package/dist/components/HTTPSettingsEditor/HTTPSettingsEditor.js.map +1 -1
- package/dist/components/ItemSelectionActionsOptionsEditor/ItemSelectionActionsOptionsEditor.js +1 -1
- package/dist/components/ItemSelectionActionsOptionsEditor/ItemSelectionActionsOptionsEditor.js.map +1 -1
- package/dist/components/LegendOptionsEditor/LegendOptionsEditor.js +1 -1
- package/dist/components/LegendOptionsEditor/LegendOptionsEditor.js.map +1 -1
- package/dist/components/MetricLabelInput/MetricLabelInput.js +1 -1
- package/dist/components/MetricLabelInput/MetricLabelInput.js.map +1 -1
- package/dist/components/MultiQueryEditor/MultiQueryEditor.js +1 -1
- package/dist/components/MultiQueryEditor/MultiQueryEditor.js.map +1 -1
- package/dist/components/MultiQueryEditor/QueryEditorContainer.js +1 -1
- package/dist/components/MultiQueryEditor/QueryEditorContainer.js.map +1 -1
- package/dist/components/OptionsEditorRadios/OptionsEditorRadios.js +1 -1
- package/dist/components/OptionsEditorRadios/OptionsEditorRadios.js.map +1 -1
- package/dist/components/OptionsEditorTabPanel/OptionsEditorTabPanel.js +1 -1
- package/dist/components/OptionsEditorTabPanel/OptionsEditorTabPanel.js.map +1 -1
- package/dist/components/OptionsEditorTabs/OptionsEditorTabs.js +1 -1
- package/dist/components/OptionsEditorTabs/OptionsEditorTabs.js.map +1 -1
- package/dist/components/PanelSpecEditor/PanelSpecEditor.js +1 -1
- package/dist/components/PanelSpecEditor/PanelSpecEditor.js.map +1 -1
- package/dist/components/PluginEditor/PluginEditor.js +1 -1
- package/dist/components/PluginEditor/PluginEditor.js.map +1 -1
- package/dist/components/PluginKindSelect/PluginKindSelect.js +1 -1
- package/dist/components/PluginKindSelect/PluginKindSelect.js.map +1 -1
- package/dist/components/PluginRegistry/PluginRegistry.d.ts.map +1 -1
- package/dist/components/PluginRegistry/PluginRegistry.js +12 -16
- package/dist/components/PluginRegistry/PluginRegistry.js.map +1 -1
- package/dist/components/PluginRegistry/getPluginSearchHelper.d.ts +12 -0
- package/dist/components/PluginRegistry/getPluginSearchHelper.d.ts.map +1 -0
- package/dist/components/PluginRegistry/getPluginSearchHelper.js +88 -0
- package/dist/components/PluginRegistry/getPluginSearchHelper.js.map +1 -0
- package/dist/components/PluginRegistry/plugin-indexes.d.ts +4 -6
- package/dist/components/PluginRegistry/plugin-indexes.d.ts.map +1 -1
- package/dist/components/PluginRegistry/plugin-indexes.js +15 -13
- package/dist/components/PluginRegistry/plugin-indexes.js.map +1 -1
- package/dist/components/PluginSpecEditor/PluginSpecEditor.d.ts.map +1 -1
- package/dist/components/PluginSpecEditor/PluginSpecEditor.js +1 -1
- package/dist/components/PluginSpecEditor/PluginSpecEditor.js.map +1 -1
- package/dist/components/SelectionOptionsEditor/SelectionOptionsEditor.js +1 -1
- package/dist/components/SelectionOptionsEditor/SelectionOptionsEditor.js.map +1 -1
- package/dist/components/TimeRangeControls/TimeRangeControls.js +1 -1
- package/dist/components/TimeRangeControls/TimeRangeControls.js.map +1 -1
- package/dist/components/Variables/VariableEditorForm/VariableEditorForm.js +1 -1
- package/dist/components/Variables/VariableEditorForm/VariableEditorForm.js.map +1 -1
- package/dist/components/Variables/VariableEditorForm/VariablePreview.js +1 -1
- package/dist/components/Variables/VariableEditorForm/VariablePreview.js.map +1 -1
- package/dist/components/Variables/variable-model.d.ts +9 -1
- package/dist/components/Variables/variable-model.d.ts.map +1 -1
- package/dist/components/Variables/variable-model.js +117 -31
- package/dist/components/Variables/variable-model.js.map +1 -1
- package/dist/context/ValidationProvider.d.ts +1 -1
- package/dist/context/ValidationProvider.d.ts.map +1 -1
- package/dist/context/ValidationProvider.js +2 -2
- package/dist/context/ValidationProvider.js.map +1 -1
- package/dist/model/alerts-queries.d.ts +33 -0
- package/dist/model/alerts-queries.d.ts.map +1 -0
- package/dist/model/alerts-queries.js +15 -0
- package/dist/model/alerts-queries.js.map +1 -0
- package/dist/model/datasource.d.ts +1 -8
- package/dist/model/datasource.d.ts.map +1 -1
- package/dist/model/datasource.js +1 -1
- package/dist/model/datasource.js.map +1 -1
- package/dist/model/index.d.ts +2 -0
- package/dist/model/index.d.ts.map +1 -1
- package/dist/model/index.js +2 -0
- package/dist/model/index.js.map +1 -1
- package/dist/model/plugin-loading.d.ts.map +1 -1
- package/dist/model/plugin-loading.js +24 -8
- package/dist/model/plugin-loading.js.map +1 -1
- package/dist/model/plugins.d.ts +21 -0
- package/dist/model/plugins.d.ts.map +1 -1
- package/dist/model/plugins.js +4 -1
- package/dist/model/plugins.js.map +1 -1
- package/dist/model/silences-queries.d.ts +33 -0
- package/dist/model/silences-queries.d.ts.map +1 -0
- package/dist/model/silences-queries.js +15 -0
- package/dist/model/silences-queries.js.map +1 -0
- package/dist/remote/PersesPlugin.types.d.ts +2 -0
- package/dist/remote/PersesPlugin.types.d.ts.map +1 -1
- package/dist/remote/PersesPlugin.types.js.map +1 -1
- package/dist/remote/PluginLoaderComponent.js +1 -1
- package/dist/remote/PluginLoaderComponent.js.map +1 -1
- package/dist/remote/PluginRuntime.d.ts +7 -1
- package/dist/remote/PluginRuntime.d.ts.map +1 -1
- package/dist/remote/PluginRuntime.js +38 -9
- package/dist/remote/PluginRuntime.js.map +1 -1
- package/dist/remote/remotePluginLoader.d.ts.map +1 -1
- package/dist/remote/remotePluginLoader.js +28 -5
- package/dist/remote/remotePluginLoader.js.map +1 -1
- package/dist/runtime/DataQueriesProvider/DataQueriesProvider.d.ts.map +1 -1
- package/dist/runtime/DataQueriesProvider/DataQueriesProvider.js +19 -3
- package/dist/runtime/DataQueriesProvider/DataQueriesProvider.js.map +1 -1
- package/dist/runtime/DataQueriesProvider/model.d.ts.map +1 -1
- package/dist/runtime/DataQueriesProvider/model.js +30 -4
- package/dist/runtime/DataQueriesProvider/model.js.map +1 -1
- package/dist/runtime/QueryCountProvider.js +1 -1
- package/dist/runtime/QueryCountProvider.js.map +1 -1
- package/dist/runtime/RouterProvider.js +1 -1
- package/dist/runtime/RouterProvider.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProvider.js +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProvider.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeSettingsProvider.js +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeSettingsProvider.js.map +1 -1
- package/dist/runtime/UsageMetricsProvider.js +2 -2
- package/dist/runtime/UsageMetricsProvider.js.map +1 -1
- package/dist/runtime/alerts-queries.d.ts +11 -0
- package/dist/runtime/alerts-queries.d.ts.map +1 -0
- package/dist/runtime/alerts-queries.js +89 -0
- package/dist/runtime/alerts-queries.js.map +1 -0
- package/dist/runtime/index.d.ts +2 -0
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/index.js +2 -0
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/item-actions.js +1 -1
- package/dist/runtime/item-actions.js.map +1 -1
- package/dist/runtime/log-queries.js +4 -1
- package/dist/runtime/log-queries.js.map +1 -1
- package/dist/runtime/plugin-registry.d.ts +2 -1
- package/dist/runtime/plugin-registry.d.ts.map +1 -1
- package/dist/runtime/plugin-registry.js +12 -3
- package/dist/runtime/plugin-registry.js.map +1 -1
- package/dist/runtime/profile-queries.js +4 -1
- package/dist/runtime/profile-queries.js.map +1 -1
- package/dist/runtime/silences-queries.d.ts +11 -0
- package/dist/runtime/silences-queries.d.ts.map +1 -0
- package/dist/runtime/silences-queries.js +89 -0
- package/dist/runtime/silences-queries.js.map +1 -0
- package/dist/runtime/time-series-queries.js +4 -1
- package/dist/runtime/time-series-queries.js.map +1 -1
- package/dist/runtime/trace-queries.js +4 -1
- package/dist/runtime/trace-queries.js.map +1 -1
- package/dist/test/mock-data.d.ts +3 -1
- package/dist/test/mock-data.d.ts.map +1 -1
- package/dist/test/mock-data.js +45 -0
- package/dist/test/mock-data.js.map +1 -1
- package/dist/test/render.js +1 -1
- package/dist/test/render.js.map +1 -1
- package/dist/test/test-plugins/bert/index.d.ts +12 -6
- package/dist/test/test-plugins/bert/index.d.ts.map +1 -1
- package/dist/test/test-plugins/bert/index.js +6 -2
- package/dist/test/test-plugins/bert/index.js.map +1 -1
- package/dist/test/test-plugins/ernie/index.d.ts +8 -6
- package/dist/test/test-plugins/ernie/index.d.ts.map +1 -1
- package/dist/test/test-plugins/ernie/index.js +6 -2
- package/dist/test/test-plugins/ernie/index.js.map +1 -1
- package/dist/test/test-plugins/index.js +2 -2
- package/dist/test/test-plugins/index.js.map +1 -1
- package/dist/test/utils.js +1 -1
- package/dist/test/utils.js.map +1 -1
- package/dist/test-utils/mock-plugin-registry.d.ts.map +1 -1
- package/dist/test-utils/mock-plugin-registry.js +8 -2
- package/dist/test-utils/mock-plugin-registry.js.map +1 -1
- package/package.json +6 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/TimeRangeProvider.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport React, { createContext, ReactElement, useCallback, useContext, useEffect, useMemo, useState } from 'react';\nimport {\n AbsoluteTimeRange,\n DurationString,\n TimeRangeValue,\n isRelativeTimeRange,\n toAbsoluteTimeRange,\n getSuggestedStepMs,\n} from '@perses-dev/spec';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { getRefreshIntervalInMs } from './refresh-interval';\n\nexport interface TimeRangeProviderProps {\n timeRange: TimeRangeValue;\n refreshInterval?: DurationString;\n setTimeRange: (value: TimeRangeValue) => void;\n setRefreshInterval: (value: DurationString) => void;\n children?: React.ReactNode;\n}\n\nexport interface TimeRange {\n timeRange: TimeRangeValue;\n absoluteTimeRange: AbsoluteTimeRange; // resolved absolute time for plugins to use\n setTimeRange: (value: TimeRangeValue) => void;\n refresh: () => void;\n refreshInterval?: DurationString;\n refreshIntervalInMs: number;\n setRefreshInterval: (value: DurationString) => void;\n}\n\nexport const TimeRangeContext = createContext<TimeRange | undefined>(undefined);\n\nexport function useTimeRangeContext(): TimeRange {\n const ctx = useContext(TimeRangeContext);\n if (ctx === undefined) {\n throw new Error('No TimeRangeContext found. Did you forget a Provider?');\n }\n return ctx;\n}\n\n/**\n * Get and set the current resolved time range at runtime.\n */\nexport function useTimeRange(): TimeRange {\n return useTimeRangeContext();\n}\n\n/**\n * Gets the suggested step for a graph query in ms for the currently selected time range.\n */\nexport function useSuggestedStepMs(width?: number): number {\n const { absoluteTimeRange } = useTimeRange();\n if (width === undefined) return 0;\n return getSuggestedStepMs(absoluteTimeRange, width);\n}\n\n/**\n * Provider implementation that supplies the time range state at runtime.\n */\nexport function TimeRangeProvider(props: TimeRangeProviderProps): ReactElement {\n const { timeRange, refreshInterval, children, setTimeRange, setRefreshInterval } = props;\n\n const queryClient = useQueryClient();\n const [absoluteTimeRange, setAbsoluteTimeRange] = useState<AbsoluteTimeRange>(\n isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange\n );\n\n const handleSetTimeRange = useCallback(\n (value: TimeRangeValue) => {\n setTimeRange(value);\n setAbsoluteTimeRange(isRelativeTimeRange(value) ? toAbsoluteTimeRange(value) : value);\n },\n [setTimeRange]\n );\n\n // Refresh is called when clicking on the refresh button, it refreshes all queries including variables\n const refresh = useCallback(() => {\n setAbsoluteTimeRange(isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange);\n queryClient\n .invalidateQueries({ queryKey: ['query'] })\n .finally(() => queryClient.removeQueries({ queryKey: ['query'], type: 'inactive' }));\n queryClient\n .invalidateQueries({ queryKey: ['variable'] })\n .finally(() => queryClient.removeQueries({ queryKey: ['variable'], type: 'inactive' }));\n }, [queryClient, timeRange]);\n\n // Auto refresh is only refreshing queries of panels\n const autoRefresh = useCallback(() => {\n setAbsoluteTimeRange(isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange);\n queryClient.invalidateQueries({ queryKey: ['query'] }).finally(() => {\n queryClient.removeQueries({ queryKey: ['query'], type: 'inactive' });\n queryClient.removeQueries({ queryKey: ['variable'], type: 'inactive' }); // Timerange is in queryKey, can lead to memory leak when using relative timerange\n });\n }, [queryClient, timeRange]);\n\n const refreshIntervalInMs = useMemo(() => getRefreshIntervalInMs(refreshInterval), [refreshInterval]);\n useEffect(() => {\n if (refreshIntervalInMs > 0) {\n const interval = setInterval(() => {\n autoRefresh();\n }, refreshIntervalInMs);\n\n return (): void => clearInterval(interval);\n }\n }, [autoRefresh, refreshIntervalInMs]);\n\n const ctx = useMemo(() => {\n return {\n timeRange: timeRange,\n setTimeRange: handleSetTimeRange,\n absoluteTimeRange: absoluteTimeRange,\n refresh,\n refreshInterval: refreshInterval,\n refreshIntervalInMs: refreshIntervalInMs,\n setRefreshInterval: setRefreshInterval,\n };\n }, [\n absoluteTimeRange,\n handleSetTimeRange,\n refresh,\n refreshInterval,\n refreshIntervalInMs,\n setRefreshInterval,\n timeRange,\n ]);\n\n return <TimeRangeContext.Provider value={ctx}>{children}</TimeRangeContext.Provider>;\n}\n"],"names":["React","createContext","useCallback","useContext","useEffect","useMemo","useState","isRelativeTimeRange","toAbsoluteTimeRange","getSuggestedStepMs","useQueryClient","getRefreshIntervalInMs","TimeRangeContext","undefined","useTimeRangeContext","ctx","Error","useTimeRange","useSuggestedStepMs","width","absoluteTimeRange","TimeRangeProvider","props","timeRange","refreshInterval","children","setTimeRange","setRefreshInterval","queryClient","setAbsoluteTimeRange","handleSetTimeRange","value","refresh","invalidateQueries","queryKey","finally","removeQueries","type","autoRefresh","refreshIntervalInMs","interval","setInterval","clearInterval","Provider"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC
|
|
1
|
+
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/TimeRangeProvider.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport React, { createContext, ReactElement, useCallback, useContext, useEffect, useMemo, useState } from 'react';\nimport {\n AbsoluteTimeRange,\n DurationString,\n TimeRangeValue,\n isRelativeTimeRange,\n toAbsoluteTimeRange,\n getSuggestedStepMs,\n} from '@perses-dev/spec';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { getRefreshIntervalInMs } from './refresh-interval';\n\nexport interface TimeRangeProviderProps {\n timeRange: TimeRangeValue;\n refreshInterval?: DurationString;\n setTimeRange: (value: TimeRangeValue) => void;\n setRefreshInterval: (value: DurationString) => void;\n children?: React.ReactNode;\n}\n\nexport interface TimeRange {\n timeRange: TimeRangeValue;\n absoluteTimeRange: AbsoluteTimeRange; // resolved absolute time for plugins to use\n setTimeRange: (value: TimeRangeValue) => void;\n refresh: () => void;\n refreshInterval?: DurationString;\n refreshIntervalInMs: number;\n setRefreshInterval: (value: DurationString) => void;\n}\n\nexport const TimeRangeContext = createContext<TimeRange | undefined>(undefined);\n\nexport function useTimeRangeContext(): TimeRange {\n const ctx = useContext(TimeRangeContext);\n if (ctx === undefined) {\n throw new Error('No TimeRangeContext found. Did you forget a Provider?');\n }\n return ctx;\n}\n\n/**\n * Get and set the current resolved time range at runtime.\n */\nexport function useTimeRange(): TimeRange {\n return useTimeRangeContext();\n}\n\n/**\n * Gets the suggested step for a graph query in ms for the currently selected time range.\n */\nexport function useSuggestedStepMs(width?: number): number {\n const { absoluteTimeRange } = useTimeRange();\n if (width === undefined) return 0;\n return getSuggestedStepMs(absoluteTimeRange, width);\n}\n\n/**\n * Provider implementation that supplies the time range state at runtime.\n */\nexport function TimeRangeProvider(props: TimeRangeProviderProps): ReactElement {\n const { timeRange, refreshInterval, children, setTimeRange, setRefreshInterval } = props;\n\n const queryClient = useQueryClient();\n const [absoluteTimeRange, setAbsoluteTimeRange] = useState<AbsoluteTimeRange>(\n isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange\n );\n\n const handleSetTimeRange = useCallback(\n (value: TimeRangeValue) => {\n setTimeRange(value);\n setAbsoluteTimeRange(isRelativeTimeRange(value) ? toAbsoluteTimeRange(value) : value);\n },\n [setTimeRange]\n );\n\n // Refresh is called when clicking on the refresh button, it refreshes all queries including variables\n const refresh = useCallback(() => {\n setAbsoluteTimeRange(isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange);\n queryClient\n .invalidateQueries({ queryKey: ['query'] })\n .finally(() => queryClient.removeQueries({ queryKey: ['query'], type: 'inactive' }));\n queryClient\n .invalidateQueries({ queryKey: ['variable'] })\n .finally(() => queryClient.removeQueries({ queryKey: ['variable'], type: 'inactive' }));\n }, [queryClient, timeRange]);\n\n // Auto refresh is only refreshing queries of panels\n const autoRefresh = useCallback(() => {\n setAbsoluteTimeRange(isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange);\n queryClient.invalidateQueries({ queryKey: ['query'] }).finally(() => {\n queryClient.removeQueries({ queryKey: ['query'], type: 'inactive' });\n queryClient.removeQueries({ queryKey: ['variable'], type: 'inactive' }); // Timerange is in queryKey, can lead to memory leak when using relative timerange\n });\n }, [queryClient, timeRange]);\n\n const refreshIntervalInMs = useMemo(() => getRefreshIntervalInMs(refreshInterval), [refreshInterval]);\n useEffect(() => {\n if (refreshIntervalInMs > 0) {\n const interval = setInterval(() => {\n autoRefresh();\n }, refreshIntervalInMs);\n\n return (): void => clearInterval(interval);\n }\n }, [autoRefresh, refreshIntervalInMs]);\n\n const ctx = useMemo(() => {\n return {\n timeRange: timeRange,\n setTimeRange: handleSetTimeRange,\n absoluteTimeRange: absoluteTimeRange,\n refresh,\n refreshInterval: refreshInterval,\n refreshIntervalInMs: refreshIntervalInMs,\n setRefreshInterval: setRefreshInterval,\n };\n }, [\n absoluteTimeRange,\n handleSetTimeRange,\n refresh,\n refreshInterval,\n refreshIntervalInMs,\n setRefreshInterval,\n timeRange,\n ]);\n\n return <TimeRangeContext.Provider value={ctx}>{children}</TimeRangeContext.Provider>;\n}\n"],"names":["React","createContext","useCallback","useContext","useEffect","useMemo","useState","isRelativeTimeRange","toAbsoluteTimeRange","getSuggestedStepMs","useQueryClient","getRefreshIntervalInMs","TimeRangeContext","undefined","useTimeRangeContext","ctx","Error","useTimeRange","useSuggestedStepMs","width","absoluteTimeRange","TimeRangeProvider","props","timeRange","refreshInterval","children","setTimeRange","setRefreshInterval","queryClient","setAbsoluteTimeRange","handleSetTimeRange","value","refresh","invalidateQueries","queryKey","finally","removeQueries","type","autoRefresh","refreshIntervalInMs","interval","setInterval","clearInterval","Provider"],"mappings":";AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC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1,4 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
1
2
|
// Copyright The Perses Authors
|
|
2
3
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
3
4
|
// you may not use this file except in compliance with the License.
|
|
@@ -10,7 +11,6 @@
|
|
|
10
11
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
12
|
// See the License for the specific language governing permissions and
|
|
12
13
|
// limitations under the License.
|
|
13
|
-
import { jsx as _jsx } from "react/jsx-runtime";
|
|
14
14
|
import { createContext, useContext, useMemo } from 'react';
|
|
15
15
|
import { buildRelativeTimeOption } from '@perses-dev/components';
|
|
16
16
|
const DEFAULT_OPTIONS = [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/TimeRangeSettingsProvider.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { createContext, ReactElement, ReactNode, useContext, useMemo } from 'react';\nimport { buildRelativeTimeOption, TimeOption } from '@perses-dev/components';\nimport { DurationString } from '@perses-dev/spec';\n\nconst DEFAULT_OPTIONS: DurationString[] = ['5m', '15m', '30m', '1h', '6h', '12h', '24h', '7d', '14d'];\nconst defaultTimeRangeSettings: TimeRangeSettings = {\n showCustom: true,\n showZoomButtons: true,\n options: DEFAULT_OPTIONS.map((duration) => buildRelativeTimeOption(duration)),\n};\n\nexport interface TimeRangeSettingsProviderProps {\n showCustom?: boolean;\n showZoomButtons?: boolean;\n options?: TimeOption[];\n children: ReactNode;\n}\n\nexport interface TimeRangeSettings {\n showCustom: boolean;\n showZoomButtons: boolean;\n options: TimeOption[];\n}\n\nexport const TimeRangeSettingsContext = createContext<TimeRangeSettings>(defaultTimeRangeSettings);\n\nexport function useTimeRangeSettingsContext(): TimeRangeSettings {\n const ctx = useContext(TimeRangeSettingsContext);\n if (ctx === undefined) {\n throw new Error('No TimeRangeContext found. Did you forget a Provider?');\n }\n return ctx;\n}\n\n/**\n * Get and set the current resolved time range at runtime.\n */\nexport function useTimeRangeSettings(): TimeRangeSettings {\n return useTimeRangeSettingsContext();\n}\n\n/**\n * Get the current value of the showCustom setting.\n * @param override If set, the value of the provider will be overridden by this value.\n */\nexport function useShowCustomTimeRangeSetting(override?: boolean): boolean {\n const showCustomTimeRange = useTimeRangeSettings().showCustom;\n if (override !== undefined) {\n return override;\n }\n return showCustomTimeRange;\n}\n\n/**\n * Get the current value of the showZoomButtons setting.\n * @param override If set, the value of the provider will be overridden by this value.\n */\nexport function useShowZoomRangeSetting(override?: boolean): boolean {\n const showZoomTimeRange = useTimeRangeSettings().showZoomButtons;\n if (override !== undefined) {\n return override;\n }\n return showZoomTimeRange;\n}\n\n/**\n * Get the current value of the options setting.\n * @param override If set, the value of the provider will be overridden by this value.\n */\nexport function useTimeRangeOptionsSetting(override?: TimeOption[]): TimeOption[] {\n const showCustomTimeRange = useTimeRangeSettings().options;\n if (override !== undefined) {\n return override;\n }\n return showCustomTimeRange;\n}\n\n/**\n * Provider implementation that supplies the time range state at runtime.\n */\nexport function TimeRangeSettingsProvider(props: TimeRangeSettingsProviderProps): ReactElement {\n const ctx = useMemo(() => {\n return {\n showCustom: props.showCustom === undefined ? defaultTimeRangeSettings.showCustom : props.showCustom,\n showZoomButtons:\n props.showZoomButtons === undefined ? defaultTimeRangeSettings.showZoomButtons : props.showZoomButtons,\n options: props.options === undefined ? defaultTimeRangeSettings.options : props.options,\n };\n }, [props.showCustom, props.showZoomButtons, props.options]);\n\n return <TimeRangeSettingsContext.Provider value={ctx}>{props.children}</TimeRangeSettingsContext.Provider>;\n}\n"],"names":["createContext","useContext","useMemo","buildRelativeTimeOption","DEFAULT_OPTIONS","defaultTimeRangeSettings","showCustom","showZoomButtons","options","map","duration","TimeRangeSettingsContext","useTimeRangeSettingsContext","ctx","undefined","Error","useTimeRangeSettings","useShowCustomTimeRangeSetting","override","showCustomTimeRange","useShowZoomRangeSetting","showZoomTimeRange","useTimeRangeOptionsSetting","TimeRangeSettingsProvider","props","Provider","value","children"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC
|
|
1
|
+
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/TimeRangeSettingsProvider.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { createContext, ReactElement, ReactNode, useContext, useMemo } from 'react';\nimport { buildRelativeTimeOption, TimeOption } from '@perses-dev/components';\nimport { DurationString } from '@perses-dev/spec';\n\nconst DEFAULT_OPTIONS: DurationString[] = ['5m', '15m', '30m', '1h', '6h', '12h', '24h', '7d', '14d'];\nconst defaultTimeRangeSettings: TimeRangeSettings = {\n showCustom: true,\n showZoomButtons: true,\n options: DEFAULT_OPTIONS.map((duration) => buildRelativeTimeOption(duration)),\n};\n\nexport interface TimeRangeSettingsProviderProps {\n showCustom?: boolean;\n showZoomButtons?: boolean;\n options?: TimeOption[];\n children: ReactNode;\n}\n\nexport interface TimeRangeSettings {\n showCustom: boolean;\n showZoomButtons: boolean;\n options: TimeOption[];\n}\n\nexport const TimeRangeSettingsContext = createContext<TimeRangeSettings>(defaultTimeRangeSettings);\n\nexport function useTimeRangeSettingsContext(): TimeRangeSettings {\n const ctx = useContext(TimeRangeSettingsContext);\n if (ctx === undefined) {\n throw new Error('No TimeRangeContext found. Did you forget a Provider?');\n }\n return ctx;\n}\n\n/**\n * Get and set the current resolved time range at runtime.\n */\nexport function useTimeRangeSettings(): TimeRangeSettings {\n return useTimeRangeSettingsContext();\n}\n\n/**\n * Get the current value of the showCustom setting.\n * @param override If set, the value of the provider will be overridden by this value.\n */\nexport function useShowCustomTimeRangeSetting(override?: boolean): boolean {\n const showCustomTimeRange = useTimeRangeSettings().showCustom;\n if (override !== undefined) {\n return override;\n }\n return showCustomTimeRange;\n}\n\n/**\n * Get the current value of the showZoomButtons setting.\n * @param override If set, the value of the provider will be overridden by this value.\n */\nexport function useShowZoomRangeSetting(override?: boolean): boolean {\n const showZoomTimeRange = useTimeRangeSettings().showZoomButtons;\n if (override !== undefined) {\n return override;\n }\n return showZoomTimeRange;\n}\n\n/**\n * Get the current value of the options setting.\n * @param override If set, the value of the provider will be overridden by this value.\n */\nexport function useTimeRangeOptionsSetting(override?: TimeOption[]): TimeOption[] {\n const showCustomTimeRange = useTimeRangeSettings().options;\n if (override !== undefined) {\n return override;\n }\n return showCustomTimeRange;\n}\n\n/**\n * Provider implementation that supplies the time range state at runtime.\n */\nexport function TimeRangeSettingsProvider(props: TimeRangeSettingsProviderProps): ReactElement {\n const ctx = useMemo(() => {\n return {\n showCustom: props.showCustom === undefined ? defaultTimeRangeSettings.showCustom : props.showCustom,\n showZoomButtons:\n props.showZoomButtons === undefined ? defaultTimeRangeSettings.showZoomButtons : props.showZoomButtons,\n options: props.options === undefined ? defaultTimeRangeSettings.options : props.options,\n };\n }, [props.showCustom, props.showZoomButtons, props.options]);\n\n return <TimeRangeSettingsContext.Provider value={ctx}>{props.children}</TimeRangeSettingsContext.Provider>;\n}\n"],"names":["createContext","useContext","useMemo","buildRelativeTimeOption","DEFAULT_OPTIONS","defaultTimeRangeSettings","showCustom","showZoomButtons","options","map","duration","TimeRangeSettingsContext","useTimeRangeSettingsContext","ctx","undefined","Error","useTimeRangeSettings","useShowCustomTimeRangeSetting","override","showCustomTimeRange","useShowZoomRangeSetting","showZoomTimeRange","useTimeRangeOptionsSetting","TimeRangeSettingsProvider","props","Provider","value","children"],"mappings":";AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,aAAa,EAA2BC,UAAU,EAAEC,OAAO,QAAQ,QAAQ;AACpF,SAASC,uBAAuB,QAAoB,yBAAyB;AAG7E,MAAMC,kBAAoC;IAAC;IAAM;IAAO;IAAO;IAAM;IAAM;IAAO;IAAO;IAAM;CAAM;AACrG,MAAMC,2BAA8C;IAClDC,YAAY;IACZC,iBAAiB;IACjBC,SAASJ,gBAAgBK,GAAG,CAAC,CAACC,WAAaP,wBAAwBO;AACrE;AAeA,OAAO,MAAMC,yCAA2BX,cAAiCK,0BAA0B;AAEnG,OAAO,SAASO;IACd,MAAMC,MAAMZ,WAAWU;IACvB,IAAIE,QAAQC,WAAW;QACrB,MAAM,IAAIC,MAAM;IAClB;IACA,OAAOF;AACT;AAEA;;CAEC,GACD,OAAO,SAASG;IACd,OAAOJ;AACT;AAEA;;;CAGC,GACD,OAAO,SAASK,8BAA8BC,QAAkB;IAC9D,MAAMC,sBAAsBH,uBAAuBV,UAAU;IAC7D,IAAIY,aAAaJ,WAAW;QAC1B,OAAOI;IACT;IACA,OAAOC;AACT;AAEA;;;CAGC,GACD,OAAO,SAASC,wBAAwBF,QAAkB;IACxD,MAAMG,oBAAoBL,uBAAuBT,eAAe;IAChE,IAAIW,aAAaJ,WAAW;QAC1B,OAAOI;IACT;IACA,OAAOG;AACT;AAEA;;;CAGC,GACD,OAAO,SAASC,2BAA2BJ,QAAuB;IAChE,MAAMC,sBAAsBH,uBAAuBR,OAAO;IAC1D,IAAIU,aAAaJ,WAAW;QAC1B,OAAOI;IACT;IACA,OAAOC;AACT;AAEA;;CAEC,GACD,OAAO,SAASI,0BAA0BC,KAAqC;IAC7E,MAAMX,MAAMX,QAAQ;QAClB,OAAO;YACLI,YAAYkB,MAAMlB,UAAU,KAAKQ,YAAYT,yBAAyBC,UAAU,GAAGkB,MAAMlB,UAAU;YACnGC,iBACEiB,MAAMjB,eAAe,KAAKO,YAAYT,yBAAyBE,eAAe,GAAGiB,MAAMjB,eAAe;YACxGC,SAASgB,MAAMhB,OAAO,KAAKM,YAAYT,yBAAyBG,OAAO,GAAGgB,MAAMhB,OAAO;QACzF;IACF,GAAG;QAACgB,MAAMlB,UAAU;QAAEkB,MAAMjB,eAAe;QAAEiB,MAAMhB,OAAO;KAAC;IAE3D,qBAAO,KAACG,yBAAyBc,QAAQ;QAACC,OAAOb;kBAAMW,MAAMG,QAAQ;;AACvE"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
1
2
|
// Copyright The Perses Authors
|
|
2
3
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
3
4
|
// you may not use this file except in compliance with the License.
|
|
@@ -10,8 +11,7 @@
|
|
|
10
11
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
12
|
// See the License for the specific language governing permissions and
|
|
12
13
|
// limitations under the License.
|
|
13
|
-
import {
|
|
14
|
-
import { fetch } from '@perses-dev/core'; // TODO
|
|
14
|
+
import { fetch } from '@perses-dev/client';
|
|
15
15
|
import { createContext, useContext } from 'react';
|
|
16
16
|
export const UsageMetricsContext = /*#__PURE__*/ createContext(undefined);
|
|
17
17
|
export const useUsageMetricsContext = ()=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/UsageMetricsProvider.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { fetch } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/UsageMetricsProvider.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { fetch } from '@perses-dev/client';\nimport { QueryDefinition } from '@perses-dev/spec';\nimport { createContext, ReactElement, ReactNode, useContext } from 'react';\n\ntype QueryState = 'pending' | 'success' | 'error';\n\ninterface UsageMetrics {\n project: string;\n dashboard: string;\n startRenderTime: number;\n renderDurationMs: number;\n renderErrorCount: number;\n pendingQueries: Map<string, QueryState>;\n apiPrefix?: string;\n}\n\ninterface UsageMetricsProps {\n project: string;\n dashboard: string;\n apiPrefix?: string;\n children: ReactNode;\n}\n\ninterface UseUsageMetricsResults {\n markQuery: (definition: QueryDefinition, state: QueryState) => void;\n}\n\nexport const UsageMetricsContext = createContext<UsageMetrics | undefined>(undefined);\n\nexport const useUsageMetricsContext = (): UsageMetrics | undefined => {\n return useContext(UsageMetricsContext);\n};\n\nexport const useUsageMetrics = (): UseUsageMetricsResults => {\n const ctx = useUsageMetricsContext();\n\n return {\n markQuery: (definition: QueryDefinition, newState: QueryState): void => {\n if (ctx === undefined) {\n return;\n }\n\n const definitionKey = JSON.stringify(definition);\n if (ctx.pendingQueries.has(definitionKey) && newState === 'pending') {\n // Never allow transitions back to pending, to avoid re-sending stats on a re-render.\n return;\n }\n\n if (ctx.pendingQueries.get(definitionKey) !== newState) {\n ctx.pendingQueries.set(definitionKey, newState);\n if (newState === 'error') {\n ctx.renderErrorCount += 1;\n }\n\n const allDone = [...ctx.pendingQueries.values()].every((p) => p !== 'pending');\n if (ctx.renderDurationMs === 0 && allDone) {\n ctx.renderDurationMs = Date.now() - ctx.startRenderTime;\n submitMetrics(ctx);\n }\n }\n },\n };\n};\n\nconst submitMetrics = async (stats: UsageMetrics): Promise<void> => {\n await fetch(`${stats.apiPrefix ?? ''}/api/v1/view`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n project: stats.project,\n dashboard: stats.dashboard,\n render_time: stats.renderDurationMs / 1000,\n render_errors: stats.renderErrorCount,\n }),\n });\n};\n\nexport const UsageMetricsProvider = ({ apiPrefix, project, dashboard, children }: UsageMetricsProps): ReactElement => {\n const ctx: UsageMetrics = {\n project: project,\n dashboard: dashboard,\n renderErrorCount: 0,\n startRenderTime: Date.now(),\n renderDurationMs: 0,\n pendingQueries: new Map(),\n apiPrefix,\n };\n\n return <UsageMetricsContext.Provider value={ctx}>{children}</UsageMetricsContext.Provider>;\n};\n"],"names":["fetch","createContext","useContext","UsageMetricsContext","undefined","useUsageMetricsContext","useUsageMetrics","ctx","markQuery","definition","newState","definitionKey","JSON","stringify","pendingQueries","has","get","set","renderErrorCount","allDone","values","every","p","renderDurationMs","Date","now","startRenderTime","submitMetrics","stats","apiPrefix","method","headers","body","project","dashboard","render_time","render_errors","UsageMetricsProvider","children","Map","Provider","value"],"mappings":";AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAA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G;YACtCa,eAAeR,MAAMV,gBAAgB;QACvC;IACF;AACF;AAEA,OAAO,MAAMmB,uBAAuB,CAAC,EAAER,SAAS,EAAEI,OAAO,EAAEC,SAAS,EAAEI,QAAQ,EAAqB;IACjG,MAAM/B,MAAoB;QACxB0B,SAASA;QACTC,WAAWA;QACXhB,kBAAkB;QAClBQ,iBAAiBF,KAAKC,GAAG;QACzBF,kBAAkB;QAClBT,gBAAgB,IAAIyB;QACpBV;IACF;IAEA,qBAAO,KAAC1B,oBAAoBqC,QAAQ;QAACC,OAAOlC;kBAAM+B;;AACpD,EAAE"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { AlertsData, QueryDefinition, UnknownSpec } from '@perses-dev/spec';
|
|
2
|
+
import { UseQueryResult } from '@tanstack/react-query';
|
|
3
|
+
export type AlertsQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'AlertsQuery', PluginSpec>;
|
|
4
|
+
export declare const ALERTS_QUERY_KEY = "AlertsQuery";
|
|
5
|
+
/**
|
|
6
|
+
* Run an alerts query using an AlertsQuery plugin and return the results.
|
|
7
|
+
* Alerts represent current state and are NOT time-range dependent.
|
|
8
|
+
* @param definitions: dashboard definition for an alerts query
|
|
9
|
+
*/
|
|
10
|
+
export declare function useAlertsQueries(definitions: AlertsQueryDefinition[]): Array<UseQueryResult<AlertsData>>;
|
|
11
|
+
//# sourceMappingURL=alerts-queries.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"alerts-queries.d.ts","sourceRoot":"","sources":["../../src/runtime/alerts-queries.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC5E,OAAO,EAAwB,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAO7E,MAAM,MAAM,qBAAqB,CAAC,UAAU,GAAG,WAAW,IAAI,eAAe,CAAC,aAAa,EAAE,UAAU,CAAC,CAAC;AACzG,eAAO,MAAM,gBAAgB,gBAAgB,CAAC;AAE9C;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,qBAAqB,EAAE,GAAG,KAAK,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC,CA6BxG"}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// Copyright The Perses Authors
|
|
2
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
3
|
+
// you may not use this file except in compliance with the License.
|
|
4
|
+
// You may obtain a copy of the License at
|
|
5
|
+
//
|
|
6
|
+
// http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
//
|
|
8
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
10
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
// See the License for the specific language governing permissions and
|
|
12
|
+
// limitations under the License.
|
|
13
|
+
import { useQueries } from '@tanstack/react-query';
|
|
14
|
+
import { useDatasourceStore } from './datasources';
|
|
15
|
+
import { usePluginRegistry, usePlugins } from './plugin-registry';
|
|
16
|
+
import { useAllVariableValues } from './variables';
|
|
17
|
+
import { filterVariableStateMap, getVariableValuesKey } from './utils';
|
|
18
|
+
export const ALERTS_QUERY_KEY = 'AlertsQuery';
|
|
19
|
+
/**
|
|
20
|
+
* Run an alerts query using an AlertsQuery plugin and return the results.
|
|
21
|
+
* Alerts represent current state and are NOT time-range dependent.
|
|
22
|
+
* @param definitions: dashboard definition for an alerts query
|
|
23
|
+
*/ export function useAlertsQueries(definitions) {
|
|
24
|
+
const { getPlugin } = usePluginRegistry();
|
|
25
|
+
const context = useAlertsQueryContext();
|
|
26
|
+
const pluginLoaderResponse = usePlugins('AlertsQuery', definitions.map((d)=>({
|
|
27
|
+
kind: d.spec.plugin.kind
|
|
28
|
+
})));
|
|
29
|
+
return useQueries({
|
|
30
|
+
queries: definitions.map((definition, idx)=>{
|
|
31
|
+
const plugin = pluginLoaderResponse[idx]?.data;
|
|
32
|
+
const { queryEnabled, queryKey } = getQueryOptions({
|
|
33
|
+
context,
|
|
34
|
+
definition,
|
|
35
|
+
plugin
|
|
36
|
+
});
|
|
37
|
+
const alertsQueryKind = definition?.spec?.plugin?.kind;
|
|
38
|
+
return {
|
|
39
|
+
enabled: queryEnabled,
|
|
40
|
+
queryKey: queryKey,
|
|
41
|
+
refetchOnMount: false,
|
|
42
|
+
refetchOnWindowFocus: false,
|
|
43
|
+
refetchOnReconnect: false,
|
|
44
|
+
staleTime: 60_000,
|
|
45
|
+
queryFn: async ({ signal })=>{
|
|
46
|
+
const plugin = await getPlugin({
|
|
47
|
+
kind: ALERTS_QUERY_KEY,
|
|
48
|
+
name: alertsQueryKind
|
|
49
|
+
});
|
|
50
|
+
const data = await plugin.getAlertsData(definition.spec.plugin.spec, context, signal);
|
|
51
|
+
return data;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
})
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function getQueryOptions({ plugin, definition, context }) {
|
|
58
|
+
const { variableState } = context;
|
|
59
|
+
const dependencies = plugin?.dependsOn ? plugin.dependsOn(definition.spec.plugin.spec, context) : {};
|
|
60
|
+
const variableDependencies = dependencies?.variables;
|
|
61
|
+
const filteredVariabledState = filterVariableStateMap(variableState, variableDependencies);
|
|
62
|
+
const variablesValueKey = getVariableValuesKey(filteredVariabledState);
|
|
63
|
+
// Note: no absoluteTimeRange in query key since alerts are current state
|
|
64
|
+
const queryKey = [
|
|
65
|
+
'query',
|
|
66
|
+
ALERTS_QUERY_KEY,
|
|
67
|
+
definition,
|
|
68
|
+
variablesValueKey
|
|
69
|
+
];
|
|
70
|
+
let waitToLoad = false;
|
|
71
|
+
if (variableDependencies) {
|
|
72
|
+
waitToLoad = variableDependencies.some((v)=>variableState[v]?.loading);
|
|
73
|
+
}
|
|
74
|
+
const queryEnabled = plugin !== undefined && !waitToLoad;
|
|
75
|
+
return {
|
|
76
|
+
queryKey,
|
|
77
|
+
queryEnabled
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function useAlertsQueryContext() {
|
|
81
|
+
const variableState = useAllVariableValues();
|
|
82
|
+
const datasourceStore = useDatasourceStore();
|
|
83
|
+
return {
|
|
84
|
+
variableState,
|
|
85
|
+
datasourceStore
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
//# sourceMappingURL=alerts-queries.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/alerts-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { AlertsData, QueryDefinition, UnknownSpec } from '@perses-dev/spec';\nimport { QueryKey, useQueries, UseQueryResult } from '@tanstack/react-query';\nimport { AlertsQueryContext, AlertsQueryPlugin } from '../model';\nimport { useDatasourceStore } from './datasources';\nimport { usePluginRegistry, usePlugins } from './plugin-registry';\nimport { useAllVariableValues } from './variables';\nimport { filterVariableStateMap, getVariableValuesKey } from './utils';\n\nexport type AlertsQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'AlertsQuery', PluginSpec>;\nexport const ALERTS_QUERY_KEY = 'AlertsQuery';\n\n/**\n * Run an alerts query using an AlertsQuery plugin and return the results.\n * Alerts represent current state and are NOT time-range dependent.\n * @param definitions: dashboard definition for an alerts query\n */\nexport function useAlertsQueries(definitions: AlertsQueryDefinition[]): Array<UseQueryResult<AlertsData>> {\n const { getPlugin } = usePluginRegistry();\n const context = useAlertsQueryContext();\n\n const pluginLoaderResponse = usePlugins(\n 'AlertsQuery',\n definitions.map((d) => ({ kind: d.spec.plugin.kind }))\n );\n\n return useQueries({\n queries: definitions.map((definition, idx) => {\n const plugin = pluginLoaderResponse[idx]?.data;\n const { queryEnabled, queryKey } = getQueryOptions({ context, definition, plugin });\n const alertsQueryKind = definition?.spec?.plugin?.kind;\n return {\n enabled: queryEnabled,\n queryKey: queryKey,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n staleTime: 60_000,\n queryFn: async ({ signal }: { signal?: AbortSignal }): Promise<AlertsData> => {\n const plugin = await getPlugin({ kind: ALERTS_QUERY_KEY, name: alertsQueryKind });\n const data = await plugin.getAlertsData(definition.spec.plugin.spec, context, signal);\n return data;\n },\n };\n }),\n });\n}\n\nfunction getQueryOptions({\n plugin,\n definition,\n context,\n}: {\n plugin?: AlertsQueryPlugin;\n definition: AlertsQueryDefinition;\n context: AlertsQueryContext;\n}): {\n queryKey: QueryKey;\n queryEnabled: boolean;\n} {\n const { variableState } = context;\n\n const dependencies = plugin?.dependsOn ? plugin.dependsOn(definition.spec.plugin.spec, context) : {};\n const variableDependencies = dependencies?.variables;\n\n const filteredVariabledState = filterVariableStateMap(variableState, variableDependencies);\n const variablesValueKey = getVariableValuesKey(filteredVariabledState);\n // Note: no absoluteTimeRange in query key since alerts are current state\n const queryKey = ['query', ALERTS_QUERY_KEY, definition, variablesValueKey] as const;\n\n let waitToLoad = false;\n if (variableDependencies) {\n waitToLoad = variableDependencies.some((v) => variableState[v]?.loading);\n }\n\n const queryEnabled = plugin !== undefined && !waitToLoad;\n return {\n queryKey,\n queryEnabled,\n };\n}\n\nfunction useAlertsQueryContext(): AlertsQueryContext {\n const variableState = useAllVariableValues();\n const datasourceStore = useDatasourceStore();\n\n return {\n variableState,\n datasourceStore,\n };\n}\n"],"names":["useQueries","useDatasourceStore","usePluginRegistry","usePlugins","useAllVariableValues","filterVariableStateMap","getVariableValuesKey","ALERTS_QUERY_KEY","useAlertsQueries","definitions","getPlugin","context","useAlertsQueryContext","pluginLoaderResponse","map","d","kind","spec","plugin","queries","definition","idx","data","queryEnabled","queryKey","getQueryOptions","alertsQueryKind","enabled","refetchOnMount","refetchOnWindowFocus","refetchOnReconnect","staleTime","queryFn","signal","name","getAlertsData","variableState","dependencies","dependsOn","variableDependencies","variables","filteredVariabledState","variablesValueKey","waitToLoad","some","v","loading","undefined","datasourceStore"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAAmBA,UAAU,QAAwB,wBAAwB;AAE7E,SAASC,kBAAkB,QAAQ,gBAAgB;AACnD,SAASC,iBAAiB,EAAEC,UAAU,QAAQ,oBAAoB;AAClE,SAASC,oBAAoB,QAAQ,cAAc;AACnD,SAASC,sBAAsB,EAAEC,oBAAoB,QAAQ,UAAU;AAGvE,OAAO,MAAMC,mBAAmB,cAAc;AAE9C;;;;CAIC,GACD,OAAO,SAASC,iBAAiBC,WAAoC;IACnE,MAAM,EAAEC,SAAS,EAAE,GAAGR;IACtB,MAAMS,UAAUC;IAEhB,MAAMC,uBAAuBV,WAC3B,eACAM,YAAYK,GAAG,CAAC,CAACC,IAAO,CAAA;YAAEC,MAAMD,EAAEE,IAAI,CAACC,MAAM,CAACF,IAAI;QAAC,CAAA;IAGrD,OAAOhB,WAAW;QAChBmB,SAASV,YAAYK,GAAG,CAAC,CAACM,YAAYC;YACpC,MAAMH,SAASL,oBAAoB,CAACQ,IAAI,EAAEC;YAC1C,MAAM,EAAEC,YAAY,EAAEC,QAAQ,EAAE,GAAGC,gBAAgB;gBAAEd;gBAASS;gBAAYF;YAAO;YACjF,MAAMQ,kBAAkBN,YAAYH,MAAMC,QAAQF;YAClD,OAAO;gBACLW,SAASJ;gBACTC,UAAUA;gBACVI,gBAAgB;gBAChBC,sBAAsB;gBACtBC,oBAAoB;gBACpBC,WAAW;gBACXC,SAAS,OAAO,EAAEC,MAAM,EAA4B;oBAClD,MAAMf,SAAS,MAAMR,UAAU;wBAAEM,MAAMT;wBAAkB2B,MAAMR;oBAAgB;oBAC/E,MAAMJ,OAAO,MAAMJ,OAAOiB,aAAa,CAACf,WAAWH,IAAI,CAACC,MAAM,CAACD,IAAI,EAAEN,SAASsB;oBAC9E,OAAOX;gBACT;YACF;QACF;IACF;AACF;AAEA,SAASG,gBAAgB,EACvBP,MAAM,EACNE,UAAU,EACVT,OAAO,EAKR;IAIC,MAAM,EAAEyB,aAAa,EAAE,GAAGzB;IAE1B,MAAM0B,eAAenB,QAAQoB,YAAYpB,OAAOoB,SAAS,CAAClB,WAAWH,IAAI,CAACC,MAAM,CAACD,IAAI,EAAEN,WAAW,CAAC;IACnG,MAAM4B,uBAAuBF,cAAcG;IAE3C,MAAMC,yBAAyBpC,uBAAuB+B,eAAeG;IACrE,MAAMG,oBAAoBpC,qBAAqBmC;IAC/C,yEAAyE;IACzE,MAAMjB,WAAW;QAAC;QAASjB;QAAkBa;QAAYsB;KAAkB;IAE3E,IAAIC,aAAa;IACjB,IAAIJ,sBAAsB;QACxBI,aAAaJ,qBAAqBK,IAAI,CAAC,CAACC,IAAMT,aAAa,CAACS,EAAE,EAAEC;IAClE;IAEA,MAAMvB,eAAeL,WAAW6B,aAAa,CAACJ;IAC9C,OAAO;QACLnB;QACAD;IACF;AACF;AAEA,SAASX;IACP,MAAMwB,gBAAgBhC;IACtB,MAAM4C,kBAAkB/C;IAExB,OAAO;QACLmC;QACAY;IACF;AACF"}
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ export * from './TimeRangeProvider';
|
|
|
6
6
|
export * from './time-series-queries';
|
|
7
7
|
export * from './trace-queries';
|
|
8
8
|
export * from './profile-queries';
|
|
9
|
+
export * from './alerts-queries';
|
|
10
|
+
export * from './silences-queries';
|
|
9
11
|
export * from './item-actions';
|
|
10
12
|
export * from './DataQueriesProvider';
|
|
11
13
|
export * from './QueryCountProvider';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":"AAaA,cAAc,qBAAqB,CAAC;AACpC,cAAc,eAAe,CAAC;AAC9B,cAAc,mBAAmB,CAAC;AAClC,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,kBAAkB,CAAC;AACjC,cAAc,wBAAwB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":"AAaA,cAAc,qBAAqB,CAAC;AACpC,cAAc,eAAe,CAAC;AAC9B,cAAc,mBAAmB,CAAC;AAClC,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,kBAAkB,CAAC;AACjC,cAAc,wBAAwB,CAAC"}
|
package/dist/runtime/index.js
CHANGED
|
@@ -18,6 +18,8 @@ export * from './TimeRangeProvider';
|
|
|
18
18
|
export * from './time-series-queries';
|
|
19
19
|
export * from './trace-queries';
|
|
20
20
|
export * from './profile-queries';
|
|
21
|
+
export * from './alerts-queries';
|
|
22
|
+
export * from './silences-queries';
|
|
21
23
|
export * from './item-actions';
|
|
22
24
|
export * from './DataQueriesProvider';
|
|
23
25
|
export * from './QueryCountProvider';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/index.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport * from './builtin-variables';\nexport * from './datasources';\nexport * from './plugin-registry';\nexport * from './variables';\nexport * from './TimeRangeProvider';\nexport * from './time-series-queries';\nexport * from './trace-queries';\nexport * from './profile-queries';\nexport * from './item-actions';\nexport * from './DataQueriesProvider';\nexport * from './QueryCountProvider';\nexport * from './RouterProvider';\nexport * from './UsageMetricsProvider';\n"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,cAAc,sBAAsB;AACpC,cAAc,gBAAgB;AAC9B,cAAc,oBAAoB;AAClC,cAAc,cAAc;AAC5B,cAAc,sBAAsB;AACpC,cAAc,wBAAwB;AACtC,cAAc,kBAAkB;AAChC,cAAc,oBAAoB;AAClC,cAAc,iBAAiB;AAC/B,cAAc,wBAAwB;AACtC,cAAc,uBAAuB;AACrC,cAAc,mBAAmB;AACjC,cAAc,yBAAyB"}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/index.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport * from './builtin-variables';\nexport * from './datasources';\nexport * from './plugin-registry';\nexport * from './variables';\nexport * from './TimeRangeProvider';\nexport * from './time-series-queries';\nexport * from './trace-queries';\nexport * from './profile-queries';\nexport * from './alerts-queries';\nexport * from './silences-queries';\nexport * from './item-actions';\nexport * from './DataQueriesProvider';\nexport * from './QueryCountProvider';\nexport * from './RouterProvider';\nexport * from './UsageMetricsProvider';\n"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,cAAc,sBAAsB;AACpC,cAAc,gBAAgB;AAC9B,cAAc,oBAAoB;AAClC,cAAc,cAAc;AAC5B,cAAc,sBAAsB;AACpC,cAAc,wBAAwB;AACtC,cAAc,kBAAkB;AAChC,cAAc,oBAAoB;AAClC,cAAc,mBAAmB;AACjC,cAAc,qBAAqB;AACnC,cAAc,iBAAiB;AAC/B,cAAc,wBAAwB;AACtC,cAAc,uBAAuB;AACrC,cAAc,mBAAmB;AACjC,cAAc,yBAAyB"}
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// See the License for the specific language governing permissions and
|
|
12
12
|
// limitations under the License.
|
|
13
13
|
import { interpolateSelectionBatch, interpolateSelectionIndividual } from '@perses-dev/components';
|
|
14
|
-
import { fetch } from '@perses-dev/
|
|
14
|
+
import { fetch } from '@perses-dev/client';
|
|
15
15
|
const BODY_METHODS = new Set([
|
|
16
16
|
'POST',
|
|
17
17
|
'PUT',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/item-actions.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport {\n ActionStatus,\n interpolateSelectionBatch,\n interpolateSelectionIndividual,\n SelectionItem,\n VariableStateMap,\n} from '@perses-dev/components';\nimport { fetch } from '@perses-dev/core'; // TODO should be part of an utils package\nimport { ItemAction, EventAction, WebhookAction } from '../components/ItemSelectionActionsOptionsEditor';\n\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH']);\n\nfunction buildWebhookHeaders(action: WebhookAction): Record<string, string> {\n const headers: Record<string, string> = { ...(action.headers ?? {}) };\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method);\n\n if (supportsBody && contentType === 'json') {\n headers['Content-Type'] = 'application/json';\n } else if (supportsBody && contentType === 'text') {\n headers['Content-Type'] = 'text/plain; charset=utf-8';\n }\n\n return headers;\n}\n\n/**\n * Parameters for executing a selection action\n */\nexport interface ExecuteActionParams<Id = unknown> {\n /** The action to execute */\n action: ItemAction;\n /** Map of selection IDs to their data */\n selectionMap: Map<Id, SelectionItem>;\n /** Optional dashboard variable state for interpolation */\n variableState?: VariableStateMap;\n /** Callback to update action status */\n setActionStatus: (actionName: string, status: Partial<ActionStatus>, itemId?: Id) => void;\n}\n\n/**\n * Result of action execution\n */\nexport interface ActionExecutionResult {\n success: boolean;\n error?: Error;\n /** For individual batch mode, results per item */\n itemResults?: Map<unknown, { success: boolean; error?: Error }>;\n}\n\n/**\n * Execute an event action by dispatching a single CustomEvent with batch data\n */\nfunction executeEventBatch<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): ActionExecutionResult {\n try {\n setActionStatus(action.name, { loading: true });\n\n const items = Array.from(selectionMap.values());\n\n // Interpolate body template if provided\n let body: string | undefined;\n if (action.bodyTemplate) {\n const bodyResult = interpolateSelectionBatch(action.bodyTemplate, items, variableState);\n body = bodyResult.text;\n } else {\n body = JSON.stringify({ items });\n }\n\n const event = new CustomEvent(action.eventName, {\n detail: body,\n bubbles: true,\n cancelable: true,\n });\n\n window.dispatchEvent(event);\n\n setActionStatus(action.name, { loading: false, success: true });\n return { success: true };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err });\n return { success: false, error: err };\n }\n}\n\n/**\n * Execute events actions by dispatching one CustomEvent per selection\n */\nfunction executeEventIndividual<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): ActionExecutionResult {\n const entries = Array.from(selectionMap.entries());\n const count = entries.length;\n const itemResults = new Map<Id, { success: boolean; error?: Error }>();\n\n // Initialize all items as loading\n setActionStatus(action.name, { loading: true, itemStatuses: new Map() });\n\n for (let index = 0; index < entries.length; index++) {\n const [id, item] = entries[index]!;\n\n setActionStatus(action.name, { loading: true }, id);\n\n try {\n // Interpolate body template if provided\n let body: string | undefined;\n if (action.bodyTemplate) {\n const bodyResult = interpolateSelectionIndividual(action.bodyTemplate, item, index, count, variableState);\n body = bodyResult.text;\n } else {\n body = JSON.stringify({ id, data: item });\n }\n\n const event = new CustomEvent(action.eventName, {\n detail: body,\n bubbles: true,\n cancelable: true,\n });\n\n window.dispatchEvent(event);\n itemResults.set(id, { success: true });\n setActionStatus(action.name, { loading: false, success: true }, id);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err }, id);\n itemResults.set(id, { success: false, error: err });\n }\n }\n\n setActionStatus(action.name, { loading: false, success: true });\n\n return {\n success: true,\n itemResults,\n };\n}\n\n/**\n * Execute a webhook action in individual mode (one request per selection)\n */\nasync function executeWebhookIndividual<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n const entries = Array.from(selectionMap.entries());\n const count = entries.length;\n const itemResults = new Map<Id, { success: boolean; error?: Error }>();\n\n // Initialize all items as loading\n setActionStatus(action.name, { loading: true, itemStatuses: new Map() });\n\n // Execute requests sequentially to avoid overwhelming the server\n for (let index = 0; index < entries.length; index++) {\n const [id, item] = entries[index]!;\n\n setActionStatus(action.name, { loading: true }, id);\n\n try {\n // Interpolate URL\n const urlResult = interpolateSelectionIndividual(action.url, item, index, count, variableState);\n\n // Interpolate body template if provided\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method) && contentType !== 'none';\n let body: string | undefined;\n if (supportsBody && action.bodyTemplate) {\n const bodyResult = interpolateSelectionIndividual(action.bodyTemplate, item, index, count, variableState);\n body = bodyResult.text;\n }\n\n // Make the request\n const response = await fetch(urlResult.text, {\n method: action.method,\n headers: buildWebhookHeaders(action),\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n setActionStatus(action.name, { loading: false, success: true }, id);\n itemResults.set(id, { success: true });\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err }, id);\n itemResults.set(id, { success: false, error: err });\n }\n }\n\n // Update overall action status\n const allSucceeded = Array.from(itemResults.values()).every((r) => r.success);\n const anyFailed = Array.from(itemResults.values()).some((r) => !r.success);\n\n if (allSucceeded) {\n setActionStatus(action.name, { loading: false, success: true });\n } else if (anyFailed) {\n setActionStatus(action.name, {\n loading: false,\n error: new Error('Some requests failed'),\n });\n }\n\n return {\n success: allSucceeded,\n itemResults,\n };\n}\n\n/**\n * Execute a webhook action in batch mode (single request with all selections)\n */\nasync function executeWebhookBatch<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n const items = Array.from(selectionMap.values());\n\n setActionStatus(action.name, { loading: true });\n\n try {\n // Interpolate URL\n const urlResult = interpolateSelectionBatch(action.url, items, variableState);\n\n // Interpolate body template if provided\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method) && contentType !== 'none';\n let body: string | undefined;\n if (supportsBody && action.bodyTemplate) {\n const bodyResult = interpolateSelectionBatch(action.bodyTemplate, items, variableState);\n body = bodyResult.text;\n }\n\n // Make the request\n const response = await fetch(urlResult.text, {\n method: action.method,\n headers: buildWebhookHeaders(action),\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n setActionStatus(action.name, { loading: false, success: true });\n return { success: true };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err });\n return { success: false, error: err };\n }\n}\n\n/**\n * Execute a webhook action\n */\nasync function executeWebhookAction<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n if (action.batchMode === 'batch') {\n return executeWebhookBatch(action, selectionMap, variableState, setActionStatus);\n } else {\n return executeWebhookIndividual(action, selectionMap, variableState, setActionStatus);\n }\n}\n\n/**\n * Execute an event action\n */\nasync function executeEventAction<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n if (action.batchMode === 'batch') {\n return executeEventBatch(action, selectionMap, variableState, setActionStatus);\n } else {\n return executeEventIndividual(action, selectionMap, variableState, setActionStatus);\n }\n}\n\n/**\n * Execute a selection action (event or webhook)\n *\n * @param params - Execution parameters including action, selections, and callbacks\n * @returns Promise resolving to the execution result\n */\nexport async function executeAction<Id = unknown>(params: ExecuteActionParams<Id>): Promise<ActionExecutionResult> {\n const { action, selectionMap, variableState, setActionStatus } = params;\n\n if (selectionMap.size === 0) {\n return { success: true };\n }\n\n if (action.type === 'event') {\n return executeEventAction(action, selectionMap, variableState, setActionStatus);\n } else if (action.type === 'webhook') {\n return executeWebhookAction(action, selectionMap, variableState, setActionStatus);\n }\n\n return { success: false, error: new Error(`Unknown action type`) };\n}\n"],"names":["interpolateSelectionBatch","interpolateSelectionIndividual","fetch","BODY_METHODS","Set","buildWebhookHeaders","action","headers","contentType","supportsBody","has","method","executeEventBatch","selectionMap","variableState","setActionStatus","name","loading","items","Array","from","values","body","bodyTemplate","bodyResult","text","JSON","stringify","event","CustomEvent","eventName","detail","bubbles","cancelable","window","dispatchEvent","success","error","err","Error","String","executeEventIndividual","entries","count","length","itemResults","Map","itemStatuses","index","id","item","data","set","executeWebhookIndividual","urlResult","url","response","ok","status","statusText","allSucceeded","every","r","anyFailed","some","executeWebhookBatch","executeWebhookAction","batchMode","executeEventAction","executeAction","params","size","type"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAEEA,yBAAyB,EACzBC,8BAA8B,QAGzB,yBAAyB;AAChC,SAASC,KAAK,QAAQ,mBAAmB,CAAC,0CAA0C;AAGpF,MAAMC,eAAe,IAAIC,IAAI;IAAC;IAAQ;IAAO;CAAQ;AAErD,SAASC,oBAAoBC,MAAqB;IAChD,MAAMC,UAAkC;QAAE,GAAID,OAAOC,OAAO,IAAI,CAAC,CAAC;IAAE;IACpE,MAAMC,cAAcF,OAAO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AcC,eAAeC;IAChE,OAAO;QACL,OAAO0B,uBAAuBnC,QAAQO,cAAcC,eAAeC;IACrE;AACF;AAEA;;;;;CAKC,GACD,OAAO,eAAesD,cAA4BC,MAA+B;IAC/E,MAAM,EAAEhE,MAAM,EAAEO,YAAY,EAAEC,aAAa,EAAEC,eAAe,EAAE,GAAGuD;IAEjE,IAAIzD,aAAa0D,IAAI,KAAK,GAAG;QAC3B,OAAO;YAAEnC,SAAS;QAAK;IACzB;IAEA,IAAI9B,OAAOkE,IAAI,KAAK,SAAS;QAC3B,OAAOJ,mBAAmB9D,QAAQO,cAAcC,eAAeC;IACjE,OAAO,IAAIT,OAAOkE,IAAI,KAAK,WAAW;QACpC,OAAON,qBAAqB5D,QAAQO,cAAcC,eAAeC;IACnE;IAEA,OAAO;QAAEqB,SAAS;QAAOC,OAAO,IAAIE,MAAM,CAAC,mBAAmB,CAAC;IAAE;AACnE"}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/item-actions.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport {\n ActionStatus,\n interpolateSelectionBatch,\n interpolateSelectionIndividual,\n SelectionItem,\n VariableStateMap,\n} from '@perses-dev/components';\nimport { fetch } from '@perses-dev/client';\nimport { ItemAction, EventAction, WebhookAction } from '../components/ItemSelectionActionsOptionsEditor';\n\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH']);\n\nfunction buildWebhookHeaders(action: WebhookAction): Record<string, string> {\n const headers: Record<string, string> = { ...(action.headers ?? {}) };\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method);\n\n if (supportsBody && contentType === 'json') {\n headers['Content-Type'] = 'application/json';\n } else if (supportsBody && contentType === 'text') {\n headers['Content-Type'] = 'text/plain; charset=utf-8';\n }\n\n return headers;\n}\n\n/**\n * Parameters for executing a selection action\n */\nexport interface ExecuteActionParams<Id = unknown> {\n /** The action to execute */\n action: ItemAction;\n /** Map of selection IDs to their data */\n selectionMap: Map<Id, SelectionItem>;\n /** Optional dashboard variable state for interpolation */\n variableState?: VariableStateMap;\n /** Callback to update action status */\n setActionStatus: (actionName: string, status: Partial<ActionStatus>, itemId?: Id) => void;\n}\n\n/**\n * Result of action execution\n */\nexport interface ActionExecutionResult {\n success: boolean;\n error?: Error;\n /** For individual batch mode, results per item */\n itemResults?: Map<unknown, { success: boolean; error?: Error }>;\n}\n\n/**\n * Execute an event action by dispatching a single CustomEvent with batch data\n */\nfunction executeEventBatch<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): ActionExecutionResult {\n try {\n setActionStatus(action.name, { loading: true });\n\n const items = Array.from(selectionMap.values());\n\n // Interpolate body template if provided\n let body: string | undefined;\n if (action.bodyTemplate) {\n const bodyResult = interpolateSelectionBatch(action.bodyTemplate, items, variableState);\n body = bodyResult.text;\n } else {\n body = JSON.stringify({ items });\n }\n\n const event = new CustomEvent(action.eventName, {\n detail: body,\n bubbles: true,\n cancelable: true,\n });\n\n window.dispatchEvent(event);\n\n setActionStatus(action.name, { loading: false, success: true });\n return { success: true };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err });\n return { success: false, error: err };\n }\n}\n\n/**\n * Execute events actions by dispatching one CustomEvent per selection\n */\nfunction executeEventIndividual<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): ActionExecutionResult {\n const entries = Array.from(selectionMap.entries());\n const count = entries.length;\n const itemResults = new Map<Id, { success: boolean; error?: Error }>();\n\n // Initialize all items as loading\n setActionStatus(action.name, { loading: true, itemStatuses: new Map() });\n\n for (let index = 0; index < entries.length; index++) {\n const [id, item] = entries[index]!;\n\n setActionStatus(action.name, { loading: true }, id);\n\n try {\n // Interpolate body template if provided\n let body: string | undefined;\n if (action.bodyTemplate) {\n const bodyResult = interpolateSelectionIndividual(action.bodyTemplate, item, index, count, variableState);\n body = bodyResult.text;\n } else {\n body = JSON.stringify({ id, data: item });\n }\n\n const event = new CustomEvent(action.eventName, {\n detail: body,\n bubbles: true,\n cancelable: true,\n });\n\n window.dispatchEvent(event);\n itemResults.set(id, { success: true });\n setActionStatus(action.name, { loading: false, success: true }, id);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err }, id);\n itemResults.set(id, { success: false, error: err });\n }\n }\n\n setActionStatus(action.name, { loading: false, success: true });\n\n return {\n success: true,\n itemResults,\n };\n}\n\n/**\n * Execute a webhook action in individual mode (one request per selection)\n */\nasync function executeWebhookIndividual<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n const entries = Array.from(selectionMap.entries());\n const count = entries.length;\n const itemResults = new Map<Id, { success: boolean; error?: Error }>();\n\n // Initialize all items as loading\n setActionStatus(action.name, { loading: true, itemStatuses: new Map() });\n\n // Execute requests sequentially to avoid overwhelming the server\n for (let index = 0; index < entries.length; index++) {\n const [id, item] = entries[index]!;\n\n setActionStatus(action.name, { loading: true }, id);\n\n try {\n // Interpolate URL\n const urlResult = interpolateSelectionIndividual(action.url, item, index, count, variableState);\n\n // Interpolate body template if provided\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method) && contentType !== 'none';\n let body: string | undefined;\n if (supportsBody && action.bodyTemplate) {\n const bodyResult = interpolateSelectionIndividual(action.bodyTemplate, item, index, count, variableState);\n body = bodyResult.text;\n }\n\n // Make the request\n const response = await fetch(urlResult.text, {\n method: action.method,\n headers: buildWebhookHeaders(action),\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n setActionStatus(action.name, { loading: false, success: true }, id);\n itemResults.set(id, { success: true });\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err }, id);\n itemResults.set(id, { success: false, error: err });\n }\n }\n\n // Update overall action status\n const allSucceeded = Array.from(itemResults.values()).every((r) => r.success);\n const anyFailed = Array.from(itemResults.values()).some((r) => !r.success);\n\n if (allSucceeded) {\n setActionStatus(action.name, { loading: false, success: true });\n } else if (anyFailed) {\n setActionStatus(action.name, {\n loading: false,\n error: new Error('Some requests failed'),\n });\n }\n\n return {\n success: allSucceeded,\n itemResults,\n };\n}\n\n/**\n * Execute a webhook action in batch mode (single request with all selections)\n */\nasync function executeWebhookBatch<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n const items = Array.from(selectionMap.values());\n\n setActionStatus(action.name, { loading: true });\n\n try {\n // Interpolate URL\n const urlResult = interpolateSelectionBatch(action.url, items, variableState);\n\n // Interpolate body template if provided\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method) && contentType !== 'none';\n let body: string | undefined;\n if (supportsBody && action.bodyTemplate) {\n const bodyResult = interpolateSelectionBatch(action.bodyTemplate, items, variableState);\n body = bodyResult.text;\n }\n\n // Make the request\n const response = await fetch(urlResult.text, {\n method: action.method,\n headers: buildWebhookHeaders(action),\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n setActionStatus(action.name, { loading: false, success: true });\n return { success: true };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err });\n return { success: false, error: err };\n }\n}\n\n/**\n * Execute a webhook action\n */\nasync function executeWebhookAction<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n if (action.batchMode === 'batch') {\n return executeWebhookBatch(action, selectionMap, variableState, setActionStatus);\n } else {\n return executeWebhookIndividual(action, selectionMap, variableState, setActionStatus);\n }\n}\n\n/**\n * Execute an event action\n */\nasync function executeEventAction<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n if (action.batchMode === 'batch') {\n return executeEventBatch(action, selectionMap, variableState, setActionStatus);\n } else {\n return executeEventIndividual(action, selectionMap, variableState, setActionStatus);\n }\n}\n\n/**\n * Execute a selection action (event or webhook)\n *\n * @param params - Execution parameters including action, selections, and callbacks\n * @returns Promise resolving to the execution result\n */\nexport async function executeAction<Id = unknown>(params: ExecuteActionParams<Id>): Promise<ActionExecutionResult> {\n const { action, selectionMap, variableState, setActionStatus } = params;\n\n if (selectionMap.size === 0) {\n return { success: true };\n }\n\n if (action.type === 'event') {\n return executeEventAction(action, selectionMap, variableState, setActionStatus);\n } else if (action.type === 'webhook') {\n return executeWebhookAction(action, selectionMap, variableState, setActionStatus);\n }\n\n return { success: false, error: new Error(`Unknown action type`) };\n}\n"],"names":["interpolateSelectionBatch","interpolateSelectionIndividual","fetch","BODY_METHODS","Set","buildWebhookHeaders","action","headers","contentType","supportsBody","has","method","executeEventBatch","selectionMap","variableState","setActionStatus","name","loading","items","Array","from","values","body","bodyTemplate","bodyResult","text","JSON","stringify","event","CustomEvent","eventName","detail","bubbles","cancelable","window","dispatchEvent","success","error","err","Error","String","executeEventIndividual","entries","count","length","itemResults","Map","itemStatuses","index","id","item","data","set","executeWebhookIndividual","urlResult","url","response","ok","status","statusText","allSucceeded","every","r","anyFailed","some","executeWebhookBatch","executeWebhookAction","batchMode","executeEventAction","executeAction","params","size","type"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAEEA,yBAAyB,EACzBC,8BAA8B,QAGzB,yBAAyB;AAChC,SAASC,KAAK,QAAQ,qBAAqB;AAG3C,MAAMC,eAAe,IAAIC,IAAI;IAAC;IAAQ;IAAO;CAAQ;AAErD,SAASC,oBAAoBC,MAAqB;IAChD,MAAMC,UAAkC;QAAE,GAAID,OAAOC,OAAO,IAAI,CAAC,CAAC;IAAE;IACpE,MAAMC,cAAcF,OAAOE,WAAW,IAAI;IAC1C,MAAMC,eAAeN,aAAaO,GAAG,CAACJ,OAAOK,MAAM;IAEnD,IAAIF,gBAAgBD,gBAAgB,QAAQ;QAC1CD,OAAO,CAAC,eAAe,GAAG;IAC5B,OAAO,IAAIE,gBAAgBD,gBAAgB,QAAQ;QACjDD,OAAO,CAAC,eAAe,GAAG;IAC5B;IAEA,OAAOA;AACT;AA0BA;;CAEC,GACD,SAASK,kBACPN,MAAmB,EACnBO,YAAoC,EACpCC,aAA2C,EAC3CC,eAA2D;IAE3D,IAAI;QACFA,gBAAgBT,OAAOU,IAAI,EAAE;YAAEC,SAAS;QAAK;QAE7C,MAAMC,QAAQC,MAAMC,IAAI,CAACP,aAAaQ,MAAM;QAE5C,wCAAwC;QACxC,IAAIC;QACJ,IAAIhB,OAAOiB,YAAY,EAAE;YACvB,MAAMC,aAAaxB,0BAA0BM,OAAOiB,YAAY,EAAEL,OAAOJ;YACzEQ,OAAOE,WAAWC,IAAI;QACxB,OAAO;YACLH,OAAOI,KAAKC,S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
|
|
45
45
|
staleTime: Infinity,
|
|
46
46
|
queryFn: async ({ signal })=>{
|
|
47
|
-
const plugin = await getPlugin(
|
|
47
|
+
const plugin = await getPlugin({
|
|
48
|
+
kind: LOG_QUERY_KEY,
|
|
49
|
+
name: logQueryKind
|
|
50
|
+
});
|
|
48
51
|
const data = await plugin.getLogData(definition.spec.plugin.spec, context, signal);
|
|
49
52
|
return data;
|
|
50
53
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/log-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryDefinition, UnknownSpec } from '@perses-dev/spec';\nimport { useQueries, UseQueryResult } from '@tanstack/react-query';\nimport { LogQueryResult } from '../model/log-queries';\nimport { useDatasourceStore } from './datasources';\nimport { usePluginRegistry } from './plugin-registry';\nimport { useTimeRange } from './TimeRangeProvider';\nimport { useVariableValues } from './variables';\n\nexport type LogQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'LogQuery', PluginSpec>;\nexport const LOG_QUERY_KEY = 'LogQuery';\n\nexport function useLogQueries(definitions: LogQueryDefinition[]): Array<UseQueryResult<LogQueryResult>> {\n const { getPlugin } = usePluginRegistry();\n const datasourceStore = useDatasourceStore();\n const { absoluteTimeRange } = useTimeRange();\n const variableValues = useVariableValues();\n\n const context = {\n timeRange: absoluteTimeRange,\n variableState: variableValues,\n datasourceStore,\n refreshKey: '',\n };\n\n return useQueries({\n queries: definitions.map((definition) => {\n const queryKey = ['query', LOG_QUERY_KEY, definition, absoluteTimeRange, variableValues] as const;\n const logQueryKind = definition?.spec?.plugin?.kind;\n return {\n queryKey: queryKey,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n staleTime: Infinity,\n queryFn: async ({ signal }: { signal?: AbortSignal }): Promise<LogQueryResult> => {\n const plugin = await getPlugin(LOG_QUERY_KEY, logQueryKind);\n const data = await plugin.getLogData(definition.spec.plugin.spec, context, signal);\n return data;\n },\n\n structuralSharing: false,\n };\n }),\n });\n}\n"],"names":["useQueries","useDatasourceStore","usePluginRegistry","useTimeRange","useVariableValues","LOG_QUERY_KEY","useLogQueries","definitions","getPlugin","datasourceStore","absoluteTimeRange","variableValues","context","timeRange","variableState","refreshKey","queries","map","definition","queryKey","logQueryKind","spec","plugin","kind","refetchOnMount","refetchOnWindowFocus","refetchOnReconnect","staleTime","Infinity","queryFn","signal","data","getLogData","structuralSharing"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAASA,UAAU,QAAwB,wBAAwB;AAEnE,SAASC,kBAAkB,QAAQ,gBAAgB;AACnD,SAASC,iBAAiB,QAAQ,oBAAoB;AACtD,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,iBAAiB,QAAQ,cAAc;AAGhD,OAAO,MAAMC,gBAAgB,WAAW;AAExC,OAAO,SAASC,cAAcC,WAAiC;IAC7D,MAAM,EAAEC,SAAS,EAAE,GAAGN;IACtB,MAAMO,kBAAkBR;IACxB,MAAM,EAAES,iBAAiB,EAAE,GAAGP;IAC9B,MAAMQ,iBAAiBP;IAEvB,MAAMQ,UAAU;QACdC,WAAWH;QACXI,eAAeH;QACfF;QACAM,YAAY;IACd;IAEA,OAAOf,WAAW;QAChBgB,SAAST,YAAYU,GAAG,CAAC,CAACC;YACxB,MAAMC,WAAW;gBAAC;gBAASd;gBAAea;gBAAYR;gBAAmBC;aAAe;YACxF,MAAMS,eAAeF,YAAYG,MAAMC,QAAQC;YAC/C,OAAO;gBACLJ,UAAUA;gBACVK,gBAAgB;gBAChBC,sBAAsB;gBACtBC,oBAAoB;gBACpBC,WAAWC;gBACXC,SAAS,OAAO,EAAEC,MAAM,EAA4B;oBAClD,MAAMR,SAAS,MAAMd,
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/log-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryDefinition, UnknownSpec } from '@perses-dev/spec';\nimport { useQueries, UseQueryResult } from '@tanstack/react-query';\nimport { LogQueryResult } from '../model/log-queries';\nimport { useDatasourceStore } from './datasources';\nimport { usePluginRegistry } from './plugin-registry';\nimport { useTimeRange } from './TimeRangeProvider';\nimport { useVariableValues } from './variables';\n\nexport type LogQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'LogQuery', PluginSpec>;\nexport const LOG_QUERY_KEY = 'LogQuery';\n\nexport function useLogQueries(definitions: LogQueryDefinition[]): Array<UseQueryResult<LogQueryResult>> {\n const { getPlugin } = usePluginRegistry();\n const datasourceStore = useDatasourceStore();\n const { absoluteTimeRange } = useTimeRange();\n const variableValues = useVariableValues();\n\n const context = {\n timeRange: absoluteTimeRange,\n variableState: variableValues,\n datasourceStore,\n refreshKey: '',\n };\n\n return useQueries({\n queries: definitions.map((definition) => {\n const queryKey = ['query', LOG_QUERY_KEY, definition, absoluteTimeRange, variableValues] as const;\n const logQueryKind = definition?.spec?.plugin?.kind;\n return {\n queryKey: queryKey,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n staleTime: Infinity,\n queryFn: async ({ signal }: { signal?: AbortSignal }): Promise<LogQueryResult> => {\n const plugin = await getPlugin({ kind: LOG_QUERY_KEY, name: logQueryKind });\n const data = await plugin.getLogData(definition.spec.plugin.spec, context, signal);\n return data;\n },\n\n structuralSharing: false,\n };\n }),\n });\n}\n"],"names":["useQueries","useDatasourceStore","usePluginRegistry","useTimeRange","useVariableValues","LOG_QUERY_KEY","useLogQueries","definitions","getPlugin","datasourceStore","absoluteTimeRange","variableValues","context","timeRange","variableState","refreshKey","queries","map","definition","queryKey","logQueryKind","spec","plugin","kind","refetchOnMount","refetchOnWindowFocus","refetchOnReconnect","staleTime","Infinity","queryFn","signal","name","data","getLogData","structuralSharing"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAASA,UAAU,QAAwB,wBAAwB;AAEnE,SAASC,kBAAkB,QAAQ,gBAAgB;AACnD,SAASC,iBAAiB,QAAQ,oBAAoB;AACtD,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,iBAAiB,QAAQ,cAAc;AAGhD,OAAO,MAAMC,gBAAgB,WAAW;AAExC,OAAO,SAASC,cAAcC,WAAiC;IAC7D,MAAM,EAAEC,SAAS,EAAE,GAAGN;IACtB,MAAMO,kBAAkBR;IACxB,MAAM,EAAES,iBAAiB,EAAE,GAAGP;IAC9B,MAAMQ,iBAAiBP;IAEvB,MAAMQ,UAAU;QACdC,WAAWH;QACXI,eAAeH;QACfF;QACAM,YAAY;IACd;IAEA,OAAOf,WAAW;QAChBgB,SAAST,YAAYU,GAAG,CAAC,CAACC;YACxB,MAAMC,WAAW;gBAAC;gBAASd;gBAAea;gBAAYR;gBAAmBC;aAAe;YACxF,MAAMS,eAAeF,YAAYG,MAAMC,QAAQC;YAC/C,OAAO;gBACLJ,UAAUA;gBACVK,gBAAgB;gBAChBC,sBAAsB;gBACtBC,oBAAoB;gBACpBC,WAAWC;gBACXC,SAAS,OAAO,EAAEC,MAAM,EAA4B;oBAClD,MAAMR,SAAS,MAAMd,UAAU;wBAAEe,MAAMlB;wBAAe0B,MAAMX;oBAAa;oBACzE,MAAMY,OAAO,MAAMV,OAAOW,UAAU,CAACf,WAAWG,IAAI,CAACC,MAAM,CAACD,IAAI,EAAET,SAASkB;oBAC3E,OAAOE;gBACT;gBAEAE,mBAAmB;YACrB;QACF;IACF;AACF"}
|
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
import { BuiltinVariableDefinition } from '@perses-dev/spec';
|
|
3
3
|
import { UseQueryOptions, UseQueryResult } from '@tanstack/react-query';
|
|
4
4
|
import { DefaultPluginKinds, PluginImplementation, PluginMetadataWithModule, PluginType } from '../model';
|
|
5
|
+
import { PluginCompoundKey } from '../components/PluginRegistry/plugin-indexes';
|
|
5
6
|
export interface PluginRegistryContextType {
|
|
6
|
-
getPlugin<T extends PluginType>(
|
|
7
|
+
getPlugin<T extends PluginType>(compoundKey: PluginCompoundKey<T>): Promise<PluginImplementation<T>>;
|
|
7
8
|
listPluginMetadata(pluginTypes: PluginType[]): Promise<PluginMetadataWithModule[]>;
|
|
8
9
|
defaultPluginKinds?: DefaultPluginKinds;
|
|
9
10
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-registry.d.ts","sourceRoot":"","sources":["../../src/runtime/plugin-registry.ts"],"names":[],"mappings":";AAaA,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAwB,eAAe,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE9F,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;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C,CAYhD;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,UAAU,EAC7C,UAAU,EAAE,CAAC,EACb,OAAO,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,GAC/B,KAAK,CAAC,cAAc,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC,CAoBhD;AAGD,KAAK,4BAA4B,GAAG,IAAI,CACtC,eAAe,CAAC,wBAAwB,EAAE,EAAE,KAAK,EAAE,wBAAwB,EAAE,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC,EAClG,UAAU,GAAG,SAAS,CACvB,CAAC;AAEF;;GAEG;AACH,wBAAgB,qBAAqB,CACnC,WAAW,EAAE,UAAU,EAAE,EACzB,OAAO,CAAC,EAAE,4BAA4B,GACrC,cAAc,CAAC,wBAAwB,EAAE,CAAC,CAO5C;AAED,wBAAgB,mCAAmC,IAAI,cAAc,CAAC,yBAAyB,EAAE,CAAC,CAkBjG"}
|
|
@@ -38,7 +38,10 @@ export const PluginRegistryContext = createContext(undefined);
|
|
|
38
38
|
pluginType,
|
|
39
39
|
kind
|
|
40
40
|
],
|
|
41
|
-
queryFn: ()=>getPlugin(
|
|
41
|
+
queryFn: ()=>getPlugin({
|
|
42
|
+
kind: pluginType,
|
|
43
|
+
name: kind
|
|
44
|
+
}),
|
|
42
45
|
...options
|
|
43
46
|
});
|
|
44
47
|
}
|
|
@@ -61,7 +64,10 @@ export const PluginRegistryContext = createContext(undefined);
|
|
|
61
64
|
pluginType,
|
|
62
65
|
kind
|
|
63
66
|
],
|
|
64
|
-
queryFn: ()=>getPlugin(
|
|
67
|
+
queryFn: ()=>getPlugin({
|
|
68
|
+
kind: pluginType,
|
|
69
|
+
name: kind
|
|
70
|
+
})
|
|
65
71
|
};
|
|
66
72
|
})
|
|
67
73
|
});
|
|
@@ -94,7 +100,10 @@ export function usePluginBuiltinVariableDefinitions() {
|
|
|
94
100
|
const datasourceNames = new Set(datasources.map((datasource)=>datasource.spec.name));
|
|
95
101
|
const result = [];
|
|
96
102
|
for (const name of datasourceNames){
|
|
97
|
-
const plugin = await getPlugin(
|
|
103
|
+
const plugin = await getPlugin({
|
|
104
|
+
kind: 'Datasource',
|
|
105
|
+
name
|
|
106
|
+
});
|
|
98
107
|
if (plugin.getBuiltinVariableDefinitions) {
|
|
99
108
|
plugin.getBuiltinVariableDefinitions().forEach((definition)=>result.push(definition));
|
|
100
109
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/plugin-registry.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { BuiltinVariableDefinition } from '@perses-dev/spec';\nimport { useQueries, useQuery, UseQueryOptions, UseQueryResult } from '@tanstack/react-query';\nimport { createContext, useContext } from 'react';\nimport { DefaultPluginKinds, PluginImplementation, PluginMetadataWithModule, PluginType } from '../model';\n\nexport interface PluginRegistryContextType {\n getPlugin<T extends PluginType>(
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/plugin-registry.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { BuiltinVariableDefinition } from '@perses-dev/spec';\nimport { useQueries, useQuery, UseQueryOptions, UseQueryResult } from '@tanstack/react-query';\nimport { createContext, useContext } from 'react';\nimport { DefaultPluginKinds, PluginImplementation, PluginMetadataWithModule, PluginType } from '../model';\nimport { PluginCompoundKey } from '../components/PluginRegistry/plugin-indexes';\n\nexport interface PluginRegistryContextType {\n getPlugin<T extends PluginType>(compoundKey: PluginCompoundKey<T>): Promise<PluginImplementation<T>>;\n listPluginMetadata(pluginTypes: PluginType[]): Promise<PluginMetadataWithModule[]>;\n defaultPluginKinds?: DefaultPluginKinds;\n}\n\nexport const PluginRegistryContext = createContext<PluginRegistryContextType | undefined>(undefined);\n\n/**\n * Use the PluginRegistry context directly. This is meant as an escape hatch for custom async flows. You should probably\n * be using `usePlugin` or `useListPluginMetadata` instead.\n */\nexport function usePluginRegistry(): PluginRegistryContextType {\n const ctx = useContext(PluginRegistryContext);\n if (ctx === undefined) {\n throw new Error('PluginRegistryContext not found. Did you forget a provider?');\n }\n return ctx;\n}\n\n// Allows consumers to pass useQuery options from react-query when loading a plugin\ntype UsePluginOptions<T extends PluginType> = Omit<\n UseQueryOptions<PluginImplementation<T>, Error, PluginImplementation<T>, [string, PluginType | undefined, string]>,\n 'queryKey' | 'queryFn'\n>;\n\n/**\n * Loads a plugin and returns the plugin implementation, along with loading/error state.\n */\nexport function usePlugin<T extends PluginType>(\n pluginType: T | undefined,\n kind: string,\n options?: UsePluginOptions<T>\n): UseQueryResult<PluginImplementation<T>, Error> {\n // We never want to ask for a plugin when the kind isn't set yet, so disable those queries automatically\n options = {\n ...options,\n enabled: (options?.enabled ?? true) && pluginType !== undefined && kind !== '',\n };\n const { getPlugin } = usePluginRegistry();\n return useQuery({\n queryKey: ['getPlugin', pluginType, kind],\n queryFn: () => getPlugin({ kind: pluginType!, name: kind }),\n ...options,\n });\n}\n\n/**\n * Loads a list of plugins and returns the plugin implementation, along with loading/error state.\n */\nexport function usePlugins<T extends PluginType>(\n pluginType: T,\n plugins: Array<{ kind: string }>\n): Array<UseQueryResult<PluginImplementation<T>>> {\n const { getPlugin } = usePluginRegistry();\n\n // useQueries() does not support queries with duplicate keys, therefore we de-duplicate the plugin kinds before running useQueries()\n // This resolves the following warning in the JS console: \"[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.\"\n // https://github.com/TanStack/query/issues/8224#issuecomment-2523554831\n // https://github.com/TanStack/query/issues/4187#issuecomment-1256336901\n const kinds = [...new Set(plugins.map((p) => p.kind))];\n\n const result: Array<UseQueryResult<PluginImplementation<T>>> = useQueries({\n queries: kinds.map((kind) => {\n return {\n queryKey: ['getPlugin', pluginType, kind],\n queryFn: () => getPlugin({ kind: pluginType, name: kind }),\n };\n }),\n });\n\n // Re-assemble array in original order\n return plugins.map((p) => result[kinds.indexOf(p.kind)]!);\n}\n\n// Allow consumers to pass useQuery options from react-query when listing metadata\ntype UseListPluginMetadataOptions = Omit<\n UseQueryOptions<PluginMetadataWithModule[], Error, PluginMetadataWithModule[], [string, string[]]>,\n 'queryKey' | 'queryFn'\n>;\n\n/**\n * Gets a list of plugin metadata for the specified plugin type and returns it, along with loading/error state.\n */\nexport function useListPluginMetadata(\n pluginTypes: PluginType[],\n options?: UseListPluginMetadataOptions\n): UseQueryResult<PluginMetadataWithModule[]> {\n const { listPluginMetadata } = usePluginRegistry();\n return useQuery({\n queryKey: ['listPluginMetadata', pluginTypes],\n queryFn: () => listPluginMetadata(pluginTypes),\n ...options,\n });\n}\n\nexport function usePluginBuiltinVariableDefinitions(): UseQueryResult<BuiltinVariableDefinition[]> {\n const { getPlugin, listPluginMetadata } = usePluginRegistry();\n\n return useQuery({\n queryKey: ['usePluginBuiltinVariableDefinitions'],\n queryFn: async () => {\n const datasources = await listPluginMetadata(['Datasource']);\n const datasourceNames = new Set(datasources.map((datasource) => datasource.spec.name));\n const result: BuiltinVariableDefinition[] = [];\n for (const name of datasourceNames) {\n const plugin = await getPlugin({ kind: 'Datasource', name });\n if (plugin.getBuiltinVariableDefinitions) {\n plugin.getBuiltinVariableDefinitions().forEach((definition) => result.push(definition));\n }\n }\n return result;\n },\n });\n}\n"],"names":["useQueries","useQuery","createContext","useContext","PluginRegistryContext","undefined","usePluginRegistry","ctx","Error","usePlugin","pluginType","kind","options","enabled","getPlugin","queryKey","queryFn","name","usePlugins","plugins","kinds","Set","map","p","result","queries","indexOf","useListPluginMetadata","pluginTypes","listPluginMetadata","usePluginBuiltinVariableDefinitions","datasources","datasourceNames","datasource","spec","plugin","getBuiltinVariableDefinitions","forEach","definition","push"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAASA,UAAU,EAAEC,QAAQ,QAAyC,wBAAwB;AAC9F,SAASC,aAAa,EAAEC,UAAU,QAAQ,QAAQ;AAUlD,OAAO,MAAMC,wBAAwBF,cAAqDG,WAAW;AAErG;;;CAGC,GACD,OAAO,SAASC;IACd,MAAMC,MAAMJ,WAAWC;IACvB,IAAIG,QAAQF,WAAW;QACrB,MAAM,IAAIG,MAAM;IAClB;IACA,OAAOD;AACT;AAQA;;CAEC,GACD,OAAO,SAASE,UACdC,UAAyB,EACzBC,IAAY,EACZC,OAA6B;IAE7B,wGAAwG;IACxGA,UAAU;QACR,GAAGA,OAAO;QACVC,SAAS,AAACD,CAAAA,SAASC,WAAW,IAAG,KAAMH,eAAeL,aAAaM,SAAS;IAC9E;IACA,MAAM,EAAEG,SAAS,EAAE,GAAGR;IACtB,OAAOL,SAAS;QACdc,UAAU;YAAC;YAAaL;YAAYC;SAAK;QACzCK,SAAS,IAAMF,UAAU;gBAAEH,MAAMD;gBAAaO,MAAMN;YAAK;QACzD,GAAGC,OAAO;IACZ;AACF;AAEA;;CAEC,GACD,OAAO,SAASM,WACdR,UAAa,EACbS,OAAgC;IAEhC,MAAM,EAAEL,SAAS,EAAE,GAAGR;I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ACF;YACA,OAAOd;QACT;IACF;AACF"}
|
|
@@ -44,7 +44,10 @@ export const PROFILE_QUERY_KEY = 'ProfileQuery';
|
|
|
44
44
|
refetchOnReconnect: false,
|
|
45
45
|
staleTime: Infinity,
|
|
46
46
|
queryFn: async ({ signal })=>{
|
|
47
|
-
const plugin = await getPlugin(
|
|
47
|
+
const plugin = await getPlugin({
|
|
48
|
+
kind: PROFILE_QUERY_KEY,
|
|
49
|
+
name: profileQueryKind
|
|
50
|
+
});
|
|
48
51
|
const data = await plugin.getProfileData(definition.spec.plugin.spec, context, signal);
|
|
49
52
|
return data;
|
|
50
53
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/profile-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryDefinition, UnknownSpec, ProfileData } from '@perses-dev/spec';\nimport { useQueries, UseQueryResult } from '@tanstack/react-query';\nimport { useDatasourceStore } from './datasources';\nimport { usePluginRegistry } from './plugin-registry';\nimport { useTimeRange } from './TimeRangeProvider';\nexport type ProfileQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'ProfileQuery', PluginSpec>;\nexport const PROFILE_QUERY_KEY = 'ProfileQuery';\n\n/**\n * Run a profile query using a ProfileQuery plugin and return the results\n * @param definitions: dashboard defintion for a profile query\n */\nexport function useProfileQueries(definitions: ProfileQueryDefinition[]): Array<UseQueryResult<ProfileData>> {\n const { getPlugin } = usePluginRegistry();\n const datasourceStore = useDatasourceStore();\n const { absoluteTimeRange } = useTimeRange();\n\n const context = {\n datasourceStore,\n absoluteTimeRange,\n };\n\n // useQueries() handles data fetching from query plugins (e.g. traceQL queries, promQL queries)\n // https://tanstack.com/query/v4/docs/react/reference/useQuery\n return useQueries({\n queries: definitions.map((definition) => {\n const queryKey = ['query', PROFILE_QUERY_KEY, definition, absoluteTimeRange] as const; // `queryKey` watches and reruns `queryFn` if keys in the array change\n const profileQueryKind = definition?.spec?.plugin?.kind;\n return {\n queryKey: queryKey,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n staleTime: Infinity,\n queryFn: async ({ signal }: { signal?: AbortSignal }): Promise<ProfileData> => {\n const plugin = await getPlugin(PROFILE_QUERY_KEY, profileQueryKind);\n const data = await plugin.getProfileData(definition.spec.plugin.spec, context, signal);\n return data;\n },\n\n structuralSharing: false,\n };\n }),\n });\n}\n"],"names":["useQueries","useDatasourceStore","usePluginRegistry","useTimeRange","PROFILE_QUERY_KEY","useProfileQueries","definitions","getPlugin","datasourceStore","absoluteTimeRange","context","queries","map","definition","queryKey","profileQueryKind","spec","plugin","kind","refetchOnMount","refetchOnWindowFocus","refetchOnReconnect","staleTime","Infinity","queryFn","signal","data","getProfileData","structuralSharing"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAASA,UAAU,QAAwB,wBAAwB;AACnE,SAASC,kBAAkB,QAAQ,gBAAgB;AACnD,SAASC,iBAAiB,QAAQ,oBAAoB;AACtD,SAASC,YAAY,QAAQ,sBAAsB;AAEnD,OAAO,MAAMC,oBAAoB,eAAe;AAEhD;;;CAGC,GACD,OAAO,SAASC,kBAAkBC,WAAqC;IACrE,MAAM,EAAEC,SAAS,EAAE,GAAGL;IACtB,MAAMM,kBAAkBP;IACxB,MAAM,EAAEQ,iBAAiB,EAAE,GAAGN;IAE9B,MAAMO,UAAU;QACdF;QACAC;IACF;IAEA,+FAA+F;IAC/F,8DAA8D;IAC9D,OAAOT,WAAW;QAChBW,SAASL,YAAYM,GAAG,CAAC,CAACC;YACxB,MAAMC,WAAW;gBAAC;gBAASV;gBAAmBS;gBAAYJ;aAAkB,EAAW,sEAAsE;YAC7J,MAAMM,mBAAmBF,YAAYG,MAAMC,QAAQC;YACnD,OAAO;gBACLJ,UAAUA;gBACVK,gBAAgB;gBAChBC,sBAAsB;gBACtBC,oBAAoB;gBACpBC,WAAWC;gBACXC,SAAS,OAAO,EAAEC,MAAM,EAA4B;oBAClD,MAAMR,SAAS,MAAMV,
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/profile-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryDefinition, UnknownSpec, ProfileData } from '@perses-dev/spec';\nimport { useQueries, UseQueryResult } from '@tanstack/react-query';\nimport { useDatasourceStore } from './datasources';\nimport { usePluginRegistry } from './plugin-registry';\nimport { useTimeRange } from './TimeRangeProvider';\nexport type ProfileQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'ProfileQuery', PluginSpec>;\nexport const PROFILE_QUERY_KEY = 'ProfileQuery';\n\n/**\n * Run a profile query using a ProfileQuery plugin and return the results\n * @param definitions: dashboard defintion for a profile query\n */\nexport function useProfileQueries(definitions: ProfileQueryDefinition[]): Array<UseQueryResult<ProfileData>> {\n const { getPlugin } = usePluginRegistry();\n const datasourceStore = useDatasourceStore();\n const { absoluteTimeRange } = useTimeRange();\n\n const context = {\n datasourceStore,\n absoluteTimeRange,\n };\n\n // useQueries() handles data fetching from query plugins (e.g. traceQL queries, promQL queries)\n // https://tanstack.com/query/v4/docs/react/reference/useQuery\n return useQueries({\n queries: definitions.map((definition) => {\n const queryKey = ['query', PROFILE_QUERY_KEY, definition, absoluteTimeRange] as const; // `queryKey` watches and reruns `queryFn` if keys in the array change\n const profileQueryKind = definition?.spec?.plugin?.kind;\n return {\n queryKey: queryKey,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n staleTime: Infinity,\n queryFn: async ({ signal }: { signal?: AbortSignal }): Promise<ProfileData> => {\n const plugin = await getPlugin({ kind: PROFILE_QUERY_KEY, name: profileQueryKind });\n const data = await plugin.getProfileData(definition.spec.plugin.spec, context, signal);\n return data;\n },\n\n structuralSharing: false,\n };\n }),\n });\n}\n"],"names":["useQueries","useDatasourceStore","usePluginRegistry","useTimeRange","PROFILE_QUERY_KEY","useProfileQueries","definitions","getPlugin","datasourceStore","absoluteTimeRange","context","queries","map","definition","queryKey","profileQueryKind","spec","plugin","kind","refetchOnMount","refetchOnWindowFocus","refetchOnReconnect","staleTime","Infinity","queryFn","signal","name","data","getProfileData","structuralSharing"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAASA,UAAU,QAAwB,wBAAwB;AACnE,SAASC,kBAAkB,QAAQ,gBAAgB;AACnD,SAASC,iBAAiB,QAAQ,oBAAoB;AACtD,SAASC,YAAY,QAAQ,sBAAsB;AAEnD,OAAO,MAAMC,oBAAoB,eAAe;AAEhD;;;CAGC,GACD,OAAO,SAASC,kBAAkBC,WAAqC;IACrE,MAAM,EAAEC,SAAS,EAAE,GAAGL;IACtB,MAAMM,kBAAkBP;IACxB,MAAM,EAAEQ,iBAAiB,EAAE,GAAGN;IAE9B,MAAMO,UAAU;QACdF;QACAC;IACF;IAEA,+FAA+F;IAC/F,8DAA8D;IAC9D,OAAOT,WAAW;QAChBW,SAASL,YAAYM,GAAG,CAAC,CAACC;YACxB,MAAMC,WAAW;gBAAC;gBAASV;gBAAmBS;gBAAYJ;aAAkB,EAAW,sEAAsE;YAC7J,MAAMM,mBAAmBF,YAAYG,MAAMC,QAAQC;YACnD,OAAO;gBACLJ,UAAUA;gBACVK,gBAAgB;gBAChBC,sBAAsB;gBACtBC,oBAAoB;gBACpBC,WAAWC;gBACXC,SAAS,OAAO,EAAEC,MAAM,EAA4B;oBAClD,MAAMR,SAAS,MAAMV,UAAU;wBAAEW,MAAMd;wBAAmBsB,MAAMX;oBAAiB;oBACjF,MAAMY,OAAO,MAAMV,OAAOW,cAAc,CAACf,WAAWG,IAAI,CAACC,MAAM,CAACD,IAAI,EAAEN,SAASe;oBAC/E,OAAOE;gBACT;gBAEAE,mBAAmB;YACrB;QACF;IACF;AACF"}
|