160 lines
220 KiB
JavaScript
160 lines
220 KiB
JavaScript
"use strict";(self.webpackChunkgrafana_metricsdrilldown_app=self.webpackChunkgrafana_metricsdrilldown_app||[]).push([[290,605],{1233:(e,t,n)=>{n.d(t,{V:()=>r});const r={DATASOURCE:"datasource",RECENT_METRICS:"recent-metrics",BOOKMARKS:"bookmarks",METRIC_PREFS:"metric-prefs",BREAKDOWN_SORTBY:"breakdown.sortby",SIDEBAR_SECTION:"sidebar.section"}},1522:(e,t,n)=>{n.d(t,{U:()=>i,n:()=>o});var r=n(5959),a=n(8705);function i(e,t){if(e instanceof Error)return e;if("string"==typeof e)return new Error(e);if("string"==typeof e.message){const t=new Error(e.message);for(const n of Object.getOwnPropertyNames(e))t[n]=e[n];return t}return new Error(t)}function o(){const[e,t]=(0,r.useState)();return(0,r.useEffect)(()=>{const e=e=>{(function(e){var t,n,r,i;if(e.filename&&new URL(e.filename).protocol.endsWith("extension:"))return a.v.error(new Error(`Browser extension error: ${e.message}`),{filename:e.filename,lineno:null===(t=e.lineno)||void 0===t?void 0:t.toString(),colno:null===(n=e.colno)||void 0===n?void 0:n.toString()}),!1;return null!==e.error||!e.message||(a.v.error(new Error(`Non-critical error: ${e.message}`),{filename:e.filename,lineno:null===(r=e.lineno)||void 0===r?void 0:r.toString(),colno:null===(i=e.colno)||void 0===i?void 0:i.toString()}),!1)})(e)&&t(i(e.error,"Uncaught exception!"))},n=e=>{"cancelled"!==e.reason.type?t(i(e.reason,"Unhandled rejection!")):t(void 0)};return window.addEventListener("error",e),window.addEventListener("unhandledrejection",n),()=>{window.removeEventListener("unhandledrejection",n),window.removeEventListener("error",e)}},[]),[e,t]}},2290:(e,t,n)=>{n.r(t),n.d(t,{sortSeries:()=>h,wasmSupported:()=>b});var r=n(6944),a=n(7781),i=n(3241),o=n(2388),s=n(6024);function l(e){var t;const n=null===(t=e.fields[1])||void 0===t?void 0:t.labels;if(!n)return null;const r=Object.keys(n);return 0===r.length?null:n[r[0]]}var c=n(5935);const u=(e,t="asc")=>{const n="asc"===t?(e,t)=>(0,s._)(e,t):(e,t)=>(0,s._)(t,e);return e.sort((e,t)=>{const r=l(e);if(!r)return 0;const a=l(t);return a?n(r,a):0})},d=(e,t,n="asc")=>{const r=a.fieldReducers.get(t),i=e.map(e=>{var n;const i=e.fields[1];if(!i)return{value:0,dataFrame:e};var o;var s;return{value:null!==(s=(null!==(o=null===(n=r.reduce)||void 0===n?void 0:n.call(r,i,!0,!0))&&void 0!==o?o:(0,a.doStandardCalcs)(i,!0,!0))[t])&&void 0!==s?s:0,dataFrame:e}});return i.sort("asc"===n?(e,t)=>e.value-t.value:(e,t)=>t.value-e.value),i.map(({dataFrame:e})=>e)},p=e=>{const t=(0,a.outerJoinDataFrames)({frames:e});if(!t)throw new Error("Error while joining frames into a single one");const n=t.fields.filter(e=>e.type===a.FieldType.number).map(e=>new Float64Array(e.values));return r.OutlierDetector.dbscan({sensitivity:.9}).detect(n)},m=(e,t)=>e.seriesResults[t].isOutlier?-e.seriesResults[t].outlierIntervals.length:0,h=(0,i.memoize)((e,t,n="asc")=>{if(!e.length)return[];const r=[...e];if("alphabetical"===t)return u(r,"asc");if("alphabetical-reversed"===t)return u(r,"desc");if("outliers"===t)try{return((e,t="asc")=>{if(!b())throw new Error("WASM not supported");const n=p(e),r=e.map((e,t)=>({value:m(n,t),dataFrame:e}));return r.sort("asc"===t?(e,t)=>e.value-t.value:(e,t)=>t.value-e.value),r.map(({dataFrame:e})=>e)})(r,n)}catch(e){const t=`Error while sorting by outlying series: "${e.toString()}"!`;return(0,o.HA)([t,"Falling back to standard deviation to identify the most variable series."]),d(r,a.ReducerID.stdDev,n)}return d(r,t,n)},(e,t,n="asc")=>{const r=f(e)?e[0].fields[0].values[0]:0,a=f(e)?e[e.length-1].fields[0].values[e[e.length-1].fields[0].values.length-1]:0;return`${e.length>0?l(e[0]):""}_${e.length>0?l(e[e.length-1]):""}_${r}_${a}_${e.length}_${t}_${n}`});function f(e){return e.length>0&&e[0].fields.length>0&&e[0].fields[0].values.length>0}const b=()=>{const e="object"==typeof WebAssembly;return e||(0,c.z)("wasm_not_supported",{}),e}},2388:(e,t,n)=>{n.d(t,{HA:()=>c,jx:()=>l,qq:()=>u});var r=n(7781),a=n(8531),i=n(8705);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function l(e,t){const n=t.reduce((e,t,n)=>s(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){o(e,t,n[t])})}return e}({},e),{[`info${n+1}`]:t}),{handheldBy:"displayError"});i.v.error(e,n),(0,a.getAppEvents)().publish({type:r.AppEvents.alertError.name,payload:t})}function c(e){i.v.warn(e),(0,a.getAppEvents)().publish({type:r.AppEvents.alertWarning.name,payload:e})}function u(e){(0,a.getAppEvents)().publish({type:r.AppEvents.alertSuccess.name,payload:e})}},2993:(e,t,n)=>{n.d(t,{E:()=>c});var r=n(6089),a=n(2007),i=n(5959),o=n.n(i),s=n(1159),l=n(6503);function c({error:e}){const t=(0,a.useStyles2)(u),n=(0,s.useNavigate)(),{pathname:r,search:c}=(0,s.useLocation)(),d=(0,i.useCallback)(()=>{const e=new URLSearchParams(c),t=new URLSearchParams;["from","to","timezone"].filter(t=>e.has(t)).forEach(n=>t.set(n,e.get(n))),n({pathname:r,search:t.toString()}),window.location.reload()},[n,r,c]),[p,m]=(0,i.useState)(!1);return o().createElement("div",{className:t.container},o().createElement(l._,{severity:"error",title:"Fatal error!",error:e,errorContext:{handheldBy:"React error boundary"},message:o().createElement(o().Fragment,null,o().createElement("p",{className:t.message},"Please"," ",o().createElement(a.TextLink,{href:"#",onClick:d},"try reloading the page")," ","or, if the problem persists, contact your organization admin. Sorry for the inconvenience."),o().createElement("p",null,o().createElement(a.Collapse,{className:t.callStack,collapsible:!0,label:"View stack trace",isOpen:p,onToggle:()=>m(!p)},o().createElement("pre",null,o().createElement("code",null,e.stack)))))}))}function u(e){return{container:(0,r.css)({margin:e.spacing(2)}),message:(0,r.css)({margin:e.spacing(2,0,1,0)}),callStack:(0,r.css)({backgroundColor:"transparent",border:"0 none","& button":(0,r.css)({paddingLeft:e.spacing(1.5)}),"& button:focus":(0,r.css)({outline:"none",boxShadow:"none"}),"& button > svg":(0,r.css)({marginLeft:e.spacing(-2),marginRight:e.spacing(.5)}),'& [class$="collapse__loader"]':(0,r.css)({display:"none"})})}}},3179:(e,t,n)=>{n.d(t,{A:()=>i,j:()=>a});var r=n(8531);const a={sidebarOpenByDefault:"metricsDrilldownDefaultOpenSidebar"};function i(e){var t;return null!==(t=r.config.featureToggles[e])&&void 0!==t&&t}},5693:(e,t,n)=>{n.d(t,{x:()=>o});var r=n(5935),a=n(1233),i=n(2533);const o=new class{migrate(){let e=!1;const t=[{legacyKey:"metricsDrilldownDataSource",newKey:a.V.DATASOURCE},{legacyKey:"metrics-drilldown-recent-metrics/v1",newKey:a.V.RECENT_METRICS},{legacyKey:"grafana.trails.bookmarks",newKey:a.V.BOOKMARKS},{legacyKey:"grafana.trails.breakdown.sort.labels.by",newKey:a.V.BREAKDOWN_SORTBY}];for(const{legacyKey:n,newKey:r}of t){let t=localStorage.getItem(n);if(null!==t){try{t=JSON.parse(t)}catch(e){}this.setItem(r,t),localStorage.removeItem(n),e=!0}}e&&(0,r.z)("user_preferences_migrated",{})}buildStorageKey(e){return`${this.service}.${e}`}getItem(e){const t=this.buildStorageKey(e),n=localStorage.getItem(t);return null===n?null:JSON.parse(n)}setItem(e,t){const n=this.buildStorageKey(e);localStorage.setItem(n,JSON.stringify(t))}removeItem(e){const t=this.buildStorageKey(e);localStorage.removeItem(t)}clear(){localStorage.clear()}constructor(e){var t,n,r;r=void 0,(n="service")in(t=this)?Object.defineProperty(t,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[n]=r,this.service=e}}(i.id)},5935:(e,t,n)=>{n.d(t,{h:()=>h,z:()=>p});var r=n(8531),a=n(2075),i=n(5176),o=n(8943),s=n(3179);function l(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){l(e,t,n[t])})}return e}function u(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}const d="grafana_explore_metrics_";function p(e,t){var n;((0,r.reportInteraction)(`${d}${e}`,u(c({},t),{meta:{appRelease:r.config.apps[o.s].version,appVersion:i.t}})),e.includes("sidebar"))&&(null===(n=(0,a.n1)())||void 0===n||n.api.pushEvent(e,u(c({},Object.fromEntries(Object.entries(t).map(([e,t])=>[e,String(t)]))),{defaultOpenSidebar:String((0,s.A)(s.j.sidebarOpenByDefault))})))}function m(e,t){p("label_filter_changed",{label:e,action:t,cause:"adhoc_filter"})}function h(e,t){e.length===t.length?function(e,t){for(const n of t)for(const t of e)n.key===t.key&&n.value!==t.value&&m(n.key,"changed")}(e,t):e.length<t.length?function(e,t){for(const n of t)e.some(e=>e.key===n.key)||m(n.key,"removed")}(e,t):function(e,t){for(const n of e)!t.some(e=>e.key===n.key)&&m(n.key,"added")}(e,t)}},6024:(e,t,n)=>{n.d(t,{_:()=>r});const r=new Intl.Collator("en",{sensitivity:"base"}).compare},6503:(e,t,n)=>{n.d(t,{_:()=>u});var r=n(2007),a=n(5959),i=n.n(a),o=n(1522),s=n(8705);function l(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function u({severity:e,title:t,message:n,error:a,errorContext:u,children:d}){let p;return a&&(p=(0,o.U)(a,"Unknown error!"),s.v.error(p,c(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){l(e,t,n[t])})}return e}({},p.cause||{},u),{bannerTitle:t}))),i().createElement(r.Alert,{title:t,severity:e},p&&i().createElement(i().Fragment,null,function(e){const t=e.message||e.toString(),n=[];return e.statusText&&n.push(e.statusText),e.status&&n.push(`HTTP ${e.status}`),n.length?`${t} (${n.join(" - ")})`:t}(p),i().createElement("br",null)),n,d)}},7558:(e,t,n)=>{n.d(t,{UX:()=>vs,Vy:()=>fs,aO:()=>hs,kj:()=>ds,xi:()=>ms,FG:()=>ys,ef:()=>ps,fZ:()=>Ss});var r=n(7781),a=n(8531),i=n(6751),o=n(6089),s=n(1932),l=n(2007),c=n(5959),u=n.n(c),d=n(5935);function p(){(0,d.z)("give_feedback_clicked",{})}const m=()=>{const e=(0,l.useStyles2)(h);return u().createElement("div",{className:e.wrapper},u().createElement("a",{href:"https://forms.gle/dKHDM4GDXVYPny3L6",className:e.feedback,title:"Share your thoughts about Metrics in Grafana.",target:"_blank",rel:"noreferrer noopener",onClick:p},u().createElement(l.Icon,{name:"comment-alt-message"})," Give feedback"))},h=e=>({wrapper:(0,o.css)({position:"absolute",top:0,right:0}),feedback:(0,o.css)({color:e.colors.text.secondary,fontSize:e.typography.bodySmall.fontSize,"&:hover":{color:e.colors.text.link}})});function f(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function b(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){f(e,t,n[t])})}return e}function g(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}class y extends i.SceneObjectBase{constructor(e){super(b({key:"drawer",isOpen:!1},e)),f(this,"open",({title:e,subTitle:t,body:n})=>{this.setState(g(b({},this.state),{isOpen:!0,title:e,subTitle:t,body:n}))}),f(this,"close",()=>{this.setState({isOpen:!1})})}}f(y,"Component",({model:e})=>{const{isOpen:t,title:n,subTitle:r,body:a}=e.useState();return u().createElement(u().Fragment,null,a&&t&&u().createElement(l.Drawer,{size:"lg",title:n,subtitle:r,closeOnMaskClick:!0,onClose:e.close},u().createElement(a.Component,{model:a})))});var v=n(2388);var S=n(4440);function w(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const O="filters",E="${filters}",x="groupby",C="ds",P="${ds}",k="logsDs",j="other_metric_filters",_="$__logs__",T={uid:P};class I extends r.BusEventWithPayload{}w(I,"type","metric-selected-event");class D extends r.BusEventBase{}w(D,"type","refresh-metrics-event");const A={"11.6.x":function(e){const t=e.languageProvider;return"function"==typeof t.fetchLabelValues&&1===t.fetchLabelValues.length},"12.0.0":function(e){const t=e.languageProvider;return"function"==typeof t.fetchLabelValues&&t.fetchLabelValues.length>1},"12.1.0-plus":function(e){return"function"==typeof e.languageProvider.queryLabelKeys}};function L(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function B(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){L(i,r,a,o,s,"next",e)}function s(e){L(i,r,a,o,s,"throw",e)}o(void 0)})}}function N(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class R{getRuntimeDatasource(){return B(function*(){if(!this.datasource){const e=yield(0,a.getDataSourceSrv)().get(P,{__sceneObject:{value:this.trail}});this.datasource=(0,S.aQ)(e)?e:void 0}return this.datasource}).call(this)}init(){this.initialized=!0,this.reset()}reset(){this.initialized&&(this.datasource=void 0,this.cache={metadata:new Map},this.fetchMetricsMetadata().catch(()=>{}))}getMetadataForMetric(e){return B(function*(){if(this.cache.metadata.has(e))return this.cache.metadata.get(e);const t=yield this.getRuntimeDatasource();if(!t)return;let n;try{const a=yield t.languageProvider.request(`/api/v1/metadata?metric=${e}`);var r;if(a&&"object"==typeof a)n=null===(r=a[e])||void 0===r?void 0:r[0]}catch(t){(0,v.HA)([`Error while fetching ${e} metadata!`,t.toString()])}return n&&this.cache.metadata.set(e,n),n}).call(this)}fetchMetricsMetadata(){return B(function*(){const e=yield this.getRuntimeDatasource();if(!e)return;const t=function(e){if(A["12.1.0-plus"](e))return e.languageProvider.queryMetricsMetadata;if(A["12.0.0"](e)||A["11.6.x"](e))return()=>Promise.resolve(e.languageProvider.metricsMetadata);throw new Error("Unsupported language provider version")}(e);let n=yield t();if(!n){const r=function(e,t){if(A["12.1.0-plus"](e))return e.languageProvider.retrieveMetricsMetadata;if(A["12.0.0"](e)||A["11.6.x"](e))return()=>{var n,r,a;return(null!==(a=null===(n=(r=e.languageProvider).loadMetricsMetadata)||void 0===n?void 0:n.call(r))&&void 0!==a?a:Promise.resolve()).then(()=>t())};throw new Error("Unsupported language provider version")}(e,t);n=yield r()}if(n)for(const[e,t]of Object.entries(n))this.cache.metadata.set(e,t)}).call(this)}fetchRecentMetrics(e){return B(function*({interval:e,extraFilter:t}){const n=yield this.getRuntimeDatasource();if(!n)return[];const r=['__name__!=""',t,i.sceneGraph.interpolate(this.trail,E)].filter(Boolean).join(","),a=`group by (__name__) ({${r}}) unless (group by (__name__) ({${r}} offset ${e}))`,o=yield n.languageProvider.request(`/api/v1/query?query=${a}`);if(!Array.isArray(null==o?void 0:o.result))throw new Error("The query to search for recent metrics timed out or failed. Try a shorter time interval and/or add label filters to narrow the search.");return o.result.map(({metric:e})=>e.__name__)}).apply(this,arguments)}getTagKeys(e){return B(function*(){const t=yield this.getRuntimeDatasource();if(!t)return[];return yield t.getTagKeys(e)}).call(this)}getTagValues(e){return B(function*(){const t=yield this.getRuntimeDatasource();if(!t)return[];e.key=function(e){if(""===e||!function(e){return/^".*"$/.test(e)}(e))return e;return e.slice(1,-1)}(e.key);return yield t.getTagValues(e)}).call(this)}static fetchLabels(e){const{timeRange:t,matcher:n}=e,r=e.ds;if(A["12.1.0-plus"](r))return r.languageProvider.queryLabelKeys(t,n);if(A["12.0.0"](r))return r.languageProvider.fetchLabelsWithMatch(t,n).then(e=>Object.keys(e));if(A["11.6.x"](r))return r.languageProvider.fetchLabelsWithMatch(n).then(e=>Object.keys(e));throw new Error("Unsupported language provider version")}static fetchLabelValues(e){const{labelName:t,timeRange:n,matcher:r=""}=e,a=e.ds;if(A["12.1.0-plus"](a))return a.languageProvider.queryLabelValues(n,t,r);if(A["12.0.0"](a)){return(r?a.languageProvider.fetchSeriesValuesWithMatch:a.languageProvider.fetchLabelValues)(n,t,r)}if(A["11.6.x"](a)){return(r?a.languageProvider.fetchSeriesValuesWithMatch:a.languageProvider.fetchLabelValues)(t,r)}throw new Error("Unsupported language provider version")}static getPrometheusDataSourceForScene(e){return B(function*(){try{const n=i.sceneGraph.findByKey(e,C);var t;const r=null!==(t=null==n?void 0:n.state.value)&&void 0!==t?t:"";return yield(0,a.getDataSourceSrv)().get({uid:r})}catch(e){return void(0,v.jx)(e,["Error while getting the Prometheus data source!"])}})()}getPrometheusBuildInfo(){return B(function*(){const e=yield this.getRuntimeDatasource();if(!e)return;const t=yield e.languageProvider.request("/api/v1/status/buildinfo");return t.application||(t.application="Prometheus",t.repository="https://github.com/prometheus/prometheus"),t.buildDate&&(t.buildDate=t.buildDate.replace(/(\d{4})(\d{2})(\d{2})(.+)/,"$1-$2-$3")),t}).call(this)}constructor(e){N(this,"initialized",!1),N(this,"trail",void 0),N(this,"datasource",void 0),N(this,"cache",{metadata:new Map}),this.trail=e}}function M(e){if(!e)return;const{type:t,help:n,unit:r}=e;return[n,t&&`**Type:** *${t}*`,r&&`**Unit:** ${r}`].join("\n\n")}function $(e){return null!==e&&"adhoc"===(null==e?void 0:e.state.type)}function V(e){return null!==e&&"custom"===(null==e?void 0:e.state.type)}function F(e){return null!==e&&"query"===(null==e?void 0:e.state.type)}var q=n(6024);function G(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function U(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){G(i,r,a,o,s,"next",e)}function s(e){G(i,r,a,o,s,"throw",e)}o(void 0)})}}const z="(none)";class H extends i.RuntimeDataSource{query(){return U(function*(){return{state:r.LoadingState.Done,data:[{name:"Labels",fields:[{name:null,type:r.FieldType.other,values:[],config:{}}],length:0}]}})()}metricFindQuery(e,t){return U(function*(){var n,r;const a=null===(r=t.scopedVars)||void 0===r||null===(n=r.__sceneObject)||void 0===n?void 0:n.valueOf(),i=yield R.getPrometheusDataSourceForScene(a);if(!i)return[];var o;const[,s]=null!==(o=e.match(/valuesOf\((.+)\)/))&&void 0!==o?o:[];if(s){return(yield H.fetchLabelValues(s,a)).map(e=>({value:e,text:e}))}let l=[];try{l=yield this.fetchLabels(i,a,e)}catch(e){(0,v.HA)(["Error while fetching labels! Defaulting to an empty array.",e.toString()])}return[{value:z,text:"(none)"},...l]}).call(this)}fetchLabels(e,t,n){return U(function*(){if(!H.getLabelsMatchAPISupport(e)){const n=H.getFiltersFromVariable(t),r=yield e.getTagKeys(n);return this.processLabelOptions(r.map(({text:e})=>({value:e,text:e})))}const r=yield R.fetchLabels({ds:e,timeRange:i.sceneGraph.getTimeRange(t).state.value,matcher:n});return this.processLabelOptions(r.map(e=>({value:e,text:e})))}).call(this)}static getLabelsMatchAPISupport(e){try{return e.hasLabelsMatchAPISupport()}catch(e){return(0,v.HA)(["Error while checking if the current data source supports the labels match API! Defaulting to false.",e.toString()]),!1}}static getFiltersFromVariable(e){const t=i.sceneGraph.lookupVariable(O,e);return $(t)?{filters:t.state.filters}:{filters:[]}}processLabelOptions(e){return e.filter(({value:e})=>!e.startsWith("__")).sort((e,t)=>(0,q._)(e.value,t.value))}static fetchLabelValues(e,t){return U(function*(){const n=yield R.getPrometheusDataSourceForScene(t);if(!n)return[];try{return yield R.fetchLabelValues({ds:n,labelName:e,timeRange:i.sceneGraph.getTimeRange(t).state.value})}catch(t){return(0,v.HA)([`Error while retrieving label "${e}" values! Defaulting to an empty array.`,t.toString()]),[]}})()}testDatasource(){return U(function*(){return{status:"success",message:"OK"}})()}constructor(){super(H.uid,H.uid)}}var K,W,Q;Q="grafana-prometheus-labels-datasource",(W="uid")in(K=H)?Object.defineProperty(K,W,{value:Q,enumerable:!0,configurable:!0,writable:!0}):K[W]=Q;const Y="labelsWingman";class X extends i.QueryVariable{onActivate(){this.subscribeToState((e,t)=>{if(e.query!==t.query&&(this.setState({staticOptions:[{value:e.value,label:e.value}]}),this.refreshOptions()),e.options!==t.options){const{value:t}=this.state;e.options.some(e=>e.value===t)&&this.setState({staticOptions:[],options:e.options.sort((e,t)=>(0,q._)(e.label,t.label))})}}),this._subs.add(i.sceneGraph.findByKeyAndType(this,C,i.DataSourceVariable).subscribeToState((e,t)=>{e.value!==t.value&&(this.setState({value:z}),this.refreshOptions())})),this._subs.add(i.sceneGraph.findByKeyAndType(this,O,i.AdHocFiltersVariable).subscribeToState((e,t)=>{e.filterExpression!==t.filterExpression&&this.updateQuery()})),this.updateQuery()}updateQuery(){const e=i.sceneGraph.interpolate(this,E,{});this.setState({query:`{__name__=~".+",${e}}`})}constructor(){super({key:Y,name:Y,label:"Group by label",placeholder:"Group by label...",datasource:{uid:H.uid},query:"",includeAll:!1,isMulti:!1,allowCustomValue:!1,refresh:r.VariableRefresh.onTimeRangeChanged,hide:r.VariableHide.hideVariable}),this.addActivationHandler(this.onActivate.bind(this))}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(X,"Component",({model:e})=>{const t=(0,l.useStyles2)(J),{label:n}=e.useState();return u().createElement("div",{className:t.container},u().createElement(l.Label,{className:t.label},n),u().createElement(i.QueryVariable.Component,{model:e}))});const J=e=>({container:o.css`
|
|
display: flex;
|
|
align-items: center;
|
|
gap: 0;
|
|
|
|
[class*='input-wrapper'] {
|
|
width: 240px;
|
|
}
|
|
`,label:o.css`
|
|
height: 32px;
|
|
white-space: nowrap;
|
|
margin: 0;
|
|
background-color: ${e.colors.background.primary};
|
|
padding: ${e.spacing(1)};
|
|
border-radius: ${e.shape.radius.default};
|
|
border: 1px solid ${e.colors.border.weak};
|
|
border-right: none;
|
|
`});var Z=n(8705),ee=n(1233),te=n(5693);class ne extends r.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ne,"type","sort-by-changed");var re=n(6538);function ae(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function ie(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){ae(i,r,a,o,s,"next",e)}function s(e){ae(i,r,a,o,s,"throw",e)}o(void 0)})}}const oe={showSuccessAlert:!1,showErrorAlert:!1};function se(){return ie(function*(){try{const e=yield(0,a.getBackendSrv)().get("/api/v1/provisioning/alert-rules",void 0,"grafana-metricsdrilldown-app-alert-rule-metric-usage",oe),t=yield function(e){return ie(function*(){const t={},n=e.filter(e=>(null==e?void 0:e.data.length)>0);for(const e of n){const n=e.data.filter(e=>{var t;return"string"==typeof(null===(t=e.model)||void 0===t?void 0:t.expr)&&"__expr__"!==e.datasourceUid}).map(n=>ie(function*(){try{const e=yield(0,re.M)(n.model.expr);for(const n of e)t[n]=(t[n]||0)+1}catch(t){Z.v.warn(t,{message:`Failed to parse PromQL expression in alert rule ${e.title}`})}})());yield Promise.all(n)}return t})()}(e);return function(e){const t={};for(const n in e)t[n]={usageType:"alerting-usage",count:e[n]};return t}(t)}catch(e){const t="string"==typeof e?new Error(e):e;return Z.v.error(t,{message:"Failed to fetch alerting rules"}),{}}})()}var le=n(7348);function ce(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function ue(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){ce(i,r,a,o,s,"next",e)}function s(e){ce(i,r,a,o,s,"throw",e)}o(void 0)})}}function de(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function pe(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}const me={showSuccessAlert:!1,showErrorAlert:!1},he=new Map,fe=(0,le.g)((e,t,n)=>ue(function*(){let r=he.get(e);return r||(r=(0,a.getBackendSrv)().get(`/api/dashboards/uid/${e}`,void 0,`grafana-metricsdrilldown-app-dashboard-metric-usage-${e}`,me).then(({dashboard:e})=>pe(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){de(e,t,n[t])})}return e}({},e),{url:t})).catch(t=>(n<=5&&Z.v.error(t,{dashboardUid:e}),n++,Promise.resolve(null))).finally(()=>{he.delete(e)}),he.set(e,r)),r})(),{concurrency:50});function be(){return ue(function*(){try{const e=yield(0,a.getBackendSrv)().get("/api/search",{type:"dash-db",limit:500},"grafana-metricsdrilldown-app-dashboard-search",me);let t=0;return yield Promise.all(e.map(({uid:e,url:n})=>fe(e,n,t))).then(e=>ue(function*(){return yield(t=e,ue(function*(){const e={};for(const n of function(e){return e.filter(e=>{var t;return e&&(null==e||null===(t=e.panels)||void 0===t?void 0:t.length)})}(t))for(const t of ge(n.panels))yield ye(t.targets,n.title||`Dashboard ${n.uid}`,n.uid||"unknown",n.url,e);return e})());var t})())}catch(e){const t="string"==typeof e?new Error(e):e;return Z.v.error(t,{message:"Failed to fetch dashboard metrics"}),{}}})()}function ge(e){return e.filter(e=>{var t;return(0,S.aQ)(e.datasource)&&"targets"in e&&(null===(t=e.targets)||void 0===t?void 0:t.length)})}function ye(e,t,n,r,a){return ue(function*(){for(const i of e){const e="string"==typeof i.expr?i.expr:"",o=yield(0,re.M)(e);for(const e of o)ve(e,t,n,r,a)}})()}function ve(e,t,n,r,a){var i;(a[e]||(a[e]={usageType:"dashboard-usage",count:0,dashboards:{}}),a[e].count++,"dashboard-usage"===a[e].usageType)&&(a[e].dashboards[t]={count:((null===(i=a[e].dashboards[t])||void 0===i?void 0:i.count)||0)+1,uid:n||"unknown",url:r})}const Se=new Set(["dashboard-usage","alerting-usage"]),we=e=>Se.has(e);class Oe{getUsageMetrics(e){return this._usageState[e].metrics&&Object.keys(this._usageState[e].metrics).length>0?Promise.resolve(this._usageState[e].metrics):(this._usageState[e].metricsPromise||(this._usageState[e].metricsPromise=this._usageState[e].fetcher().then(t=>(this._usageState[e].metrics=t,this._usageState[e].metricsPromise=void 0,t))),this._usageState[e].metricsPromise)}getUsageForMetric(e,t){return this.getUsageMetrics(t).then(t=>{var n,r;return null!==(r=null===(n=t[e])||void 0===n?void 0:n.count)&&void 0!==r?r:0})}getUsageDetailsForMetric(e,t){return this.getUsageMetrics(t).then(n=>{var r;return null!==(r=n[e])&&void 0!==r?r:"dashboard-usage"===t?{usageType:"dashboard-usage",count:0,dashboards:{}}:{usageType:"alerting-usage",count:0}})}constructor(){!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(this,"_usageState",{"dashboard-usage":{metrics:{},metricsPromise:void 0,fetcher:be},"alerting-usage":{metrics:{},metricsPromise:void 0,fetcher:se}})}}function Ee(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function xe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Ee(e,t,n[t])})}return e}function Ce(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function Pe(){try{const e=te.x.getItem(ee.V.RECENT_METRICS)||[];if(!e.length)return[];const t=Date.now()-2592e6,n=e.filter(e=>e.timestamp>t);return n.length!==e.length&&te.x.setItem(ee.V.RECENT_METRICS,n),n}catch(e){return Z.v.error(e,{message:"Failed to get recent metrics:"}),[]}}const ke=[{label:"Default",value:"default"},{label:"Alphabetical [A-Z]",value:"alphabetical"},{label:"Alphabetical [Z-A]",value:"alphabetical-reversed"},{label:"Dashboard Usage",value:"dashboard-usage"},{label:"Alerting Usage",value:"alerting-usage"}],je="metrics-reducer-sort-by";class _e extends i.SceneObjectBase{activationHandler(){const e=i.sceneGraph.getVariables(this).getByName(je);this.supportedSortByOptions.has(e.getValue())||e.changeValueTo("default"),this._subs.add(e.subscribeToState((e,t)=>{e.value!==t.value&&this.publishEvent(new ne({sortBy:e.value}),!0)}))}getUsageDetailsForMetric(e,t){return this.usageFetcher.getUsageDetailsForMetric(e,t)}getUsageMetrics(e){return this.usageFetcher.getUsageMetrics(e).then(e=>{const t={};for(const n in e)t[n]=e[n].count;return t})}constructor(e){super(Ce(xe({},e),{key:"metrics-sorter",$variables:new i.SceneVariableSet({variables:[new i.CustomVariable({name:je,label:"Sort by",value:"default",query:ke.map(e=>`${e.label} : ${e.value}`).join(","),description:"Default metric sorting is alphabetical with recently-selected metrics first. Metrics can also be sorted purely alphabetically, by prevalence in dashboard panel queries, or by prevalence in alerting rules"})]}),inputControls:new i.VariableValueSelectors({layout:"horizontal"})})),Ee(this,"initialized",!1),Ee(this,"supportedSortByOptions",new Set(["alerting-usage","alphabetical","alphabetical-reversed","dashboard-usage","default"])),Ee(this,"usageFetcher",new Oe),this.addActivationHandler(()=>this.activationHandler())}}function Te(e,t="asc"){const n="asc"===t?(e,t)=>(0,q._)(e,t):(e,t)=>(0,q._)(t,e);return[...e].sort((e,t)=>n(e,t))}Ee(_e,"Component",({model:e})=>{const{inputControls:t}=e.useState();return u().createElement("div",{"data-testid":"sort-by-select"},u().createElement(t.Component,{model:t}))});const Ie="metrics_filters";class De extends i.AdHocFiltersVariable{constructor(){super({key:Ie,name:Ie,hide:r.VariableHide.hideVariable,allowCustomValue:!0,applyMode:"manual",expressionBuilder:e=>e.map(e=>`${(0,s.Nc)(e.key)}${e.operator}"${e.value}"`).join(","),skipUrlSync:!0}),this.addActivationHandler(()=>{const e=i.sceneGraph.findByKeyAndType(this,O,i.AdHocFiltersVariable),t=e=>{this.setState({baseFilters:e.baseFilters,filters:e.filters})};t(e.state);const n=e.subscribeToState((e,n)=>{e.baseFilters===n.baseFilters&&e.filters===n.filters||t(e)});return()=>{n.unsubscribe()}})}}class Ae extends r.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ae,"type","metrics-variable-activated");class Le extends r.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Le,"type","metrics-variable-deactivated");class Be extends r.BusEventWithPayload{}function Ne(e){const t=e.state.key;if(!t)throw new TypeError(`Variable "${e.state.name}" has no key. Please provide a key in order to publish its lifecycle events.`);return e.addActivationHandler(()=>{e.publishEvent(new Ae({key:t}),!0),!e.state.loading&&e.state.options.length&&e.publishEvent(new Be({key:t,options:e.state.options}),!0);const n=e.subscribeToState((n,r)=>{!n.loading&&r.loading&&e.publishEvent(new Be({key:t,options:n.options}),!0)});return()=>{n.unsubscribe(),e.publishEvent(new Le({key:t}),!0)}}),e}function Re(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Be,"type","metrics-variable-loaded");const Me="metrics-wingman";class $e extends i.QueryVariable{onActivate(){this.fetchAllOrRecentMetrics(),this._subs.add(i.sceneGraph.findByKeyAndType(this,C,i.DataSourceVariable).subscribeToState((e,t)=>{this.state.query||e.value===t.value||this.fetchAllOrRecentMetrics()})),this._subs.add(i.sceneGraph.findByKeyAndType(this,Ie,i.AdHocFiltersVariable).subscribeToState((e,t)=>{this.state.query||e.filterExpression===t.filterExpression||this.fetchAllOrRecentMetrics()}))}fetchAllOrRecentMetrics(){const e=new URLSearchParams(window.location.search).get("filters-recent");e?this.fetchRecentMetrics(e):this.fetchAllMetrics()}fetchAllMetrics(){this.setState({query:this.extraFilter?`label_values({${this.extraFilter},$${Ie}}, __name__)`:`label_values({$${Ie}}, __name__)`,refresh:r.VariableRefresh.onTimeRangeChanged}),this.refreshOptions()}fetchRecentMetrics(e){return(t=function*(){this.setState({query:"",refresh:r.VariableRefresh.never,options:[],loading:!0,error:null});try{const t=yield ds(this).fetchRecentMetrics({interval:e,extraFilter:this.extraFilter});this.setState({loading:!1,options:t.map(e=>({value:e,label:e}))})}catch(e){this.setState({loading:!1,error:e})}},function(){var e=this,n=arguments;return new Promise(function(r,a){var i=t.apply(e,n);function o(e){Re(i,r,a,o,s,"next",e)}function s(e){Re(i,r,a,o,s,"throw",e)}o(void 0)})}).call(this);var t}constructor({key:e,name:t,labelMatcher:n,addLifeCycleEvents:a}={}){if(super({key:e||Me,name:t||Me,label:"Metrics",datasource:T,query:"",refresh:r.VariableRefresh.never,includeAll:!0,value:"$__all",skipUrlSync:!0,sort:r.VariableSort.alphabeticalAsc,hide:r.VariableHide.hideVariable}),function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(this,"extraFilter",void 0),this.extraFilter=n?`${n.key}${n.operator}"${n.value}"`:void 0,this.addActivationHandler(this.onActivate.bind(this)),a)return Ne(this)}}function Ve(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Fe=function(e){return e.GRID="grid",e.ROWS="rows",e.SINGLE="single",e}({});class qe extends i.SceneObjectBase{getUrlState(){return{[this.state.urlSearchParamName]:this.state.layout}}updateFromUrl(e){const t={},n=e[this.state.urlSearchParamName];n!==this.state.layout&&(t.layout=this.state.options.find(e=>e.value===n)?n:qe.DEFAULT_LAYOUT),this.setState(t)}constructor({urlSearchParamName:e,options:t}){super({key:"layout-switcher",urlSearchParamName:e||"layout",options:t||qe.DEFAULT_OPTIONS,layout:qe.DEFAULT_LAYOUT}),Ve(this,"_urlSync",new i.SceneObjectUrlSyncConfig(this,{keys:[this.state.urlSearchParamName]})),Ve(this,"onChange",e=>{(0,d.z)("layout_changed",{layout:e}),this.setState({layout:e})})}}Ve(qe,"DEFAULT_OPTIONS",[{label:"Grid",value:"grid"},{label:"Rows",value:"rows"}]),Ve(qe,"DEFAULT_LAYOUT","grid"),Ve(qe,"Component",({model:e})=>{const{options:t,layout:n}=e.useState();return u().createElement(l.RadioButtonGroup,{"aria-label":"Layout switcher",options:t,value:n,onChange:e.onChange,fullWidth:!1})});const Ge="filtered-metrics-wingman";class Ue extends i.CustomVariable{onActivate(){const e=i.sceneGraph.findByKeyAndType(this,Me,$e),{loading:t,error:n,options:r}=e.state;this.setState({loading:t,error:n,options:r}),this._subs.add(e.subscribeToState(e=>{this.setState({loading:e.loading,error:e.error,options:e.options})}))}constructor(){return super({key:Ge,name:Ge,label:"Filtered Metrics",loading:!1,error:null,options:[],includeAll:!0,value:"$__all",skipUrlSync:!0}),this.addActivationHandler(this.onActivate.bind(this)),Ne(this)}}var ze=n(3241);const He=(e,t)=>e.length===t.length&&(0,ze.isEqual)(e,t);function Ke(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function We(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}class Qe extends i.SceneObjectBase{useCounts(){return this.useState().counts}constructor(e){super(We(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Ke(e,t,n[t])})}return e}({},e),{counts:{current:0,total:0}}))}}class Ye extends Qe{onActivate(){const e=i.sceneGraph.lookupVariable(Me,this),t=i.sceneGraph.lookupVariable(Ge,this);this.setInitCounts(e,t),this._subs.add(e.subscribeToState((e,n)=>{He(e.options,n.options)||this.setState({counts:{current:t.state.options.length,total:e.options.length}})})),this._subs.add(t.subscribeToState((t,n)=>{t.loading||n.loading||He(t.options,n.options)||this.setState({counts:{current:t.options.length,total:e.state.options.length}})}))}setInitCounts(e,t){const n={current:0,total:0};!e.state.loading&&e.state.options.length&&(n.total=e.state.options.length),!t.state.loading&&t.state.options.length&&(n.current=t.state.options.length),this.setState({counts:n})}constructor(){super({key:"MetricVariableCountsProvider"}),this.addActivationHandler(this.onActivate.bind(this))}}class Xe extends r.BusEventWithPayload{}function Je(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Xe,"type","quick-search-changed");class Ze extends i.SceneObjectBase{getUrlState(){return{[this.state.urlSearchParamName]:this.state.value}}updateFromUrl(e){const t=e[this.state.urlSearchParamName]||"";t!==this.state.value&&this.setState({value:t})}toggleCountsDisplay(e){this.setState({displayCounts:e})}updateValue(e){""===this.state.value&&""!==e&&(0,d.z)("quick_search_used",{}),this.setState({value:e}),this.notifyValueChange(e)}useHumanFriendlyCountsMessage(){const{targetName:e,countsProvider:t,displayCounts:n}=this.state,r=t.useCounts();return n?r.current===r.total?{tagName:`${r.current}`,tooltipContent:1!==r.current?`${r.current} ${e}s in total`:`1 ${e} in total`}:{tagName:`${r.current}/${r.total}`,tooltipContent:1!==r.current?`${r.current} out of ${r.total} ${e}s in total`:`1 out of ${r.total} ${e}s in total`}:{tagName:"",tooltipContent:""}}constructor({urlSearchParamName:e,targetName:t,countsProvider:n,displayCounts:r}){super({key:"quick-search",urlSearchParamName:e,targetName:t,countsProvider:n,displayCounts:Boolean(r),value:""}),Je(this,"_variableDependency",new i.VariableDependencyConfig(this,{variableNames:[C],onReferencedVariableValueChanged:()=>{this.setState({value:""})}})),Je(this,"_urlSync",new i.SceneObjectUrlSyncConfig(this,{keys:[this.state.urlSearchParamName]})),Je(this,"notifyValueChange",(0,ze.debounce)(e=>{this.publishEvent(new Xe({searchText:e}),!0)},250)),Je(this,"onChange",e=>{this.updateValue(e.currentTarget.value)}),Je(this,"clear",()=>{this.updateValue("")}),Je(this,"onKeyDown",e=>{"Escape"===e.key&&(e.preventDefault(),this.clear())})}}Je(Ze,"Component",({model:e})=>{const t=(0,l.useStyles2)(et),{targetName:n,value:r,countsProvider:a}=e.useState(),{tagName:i,tooltipContent:o}=e.useHumanFriendlyCountsMessage();return u().createElement(l.Input,{value:r,onChange:e.onChange,onKeyDown:e.onKeyDown,placeholder:`Quick search ${n}s`,prefix:u().createElement("i",{className:"fa fa-search"}),suffix:u().createElement(u().Fragment,null,u().createElement(a.Component,{model:a}),i&&u().createElement(l.Tooltip,{content:o,placement:"top"},u().createElement(l.Tag,{className:t.counts,name:i,colorIndex:9})),u().createElement(l.IconButton,{name:"times",variant:"secondary",tooltip:"Clear search",onClick:e.clear,disabled:!r}))})});const et=e=>({counts:o.css`
|
|
margin-right: ${e.spacing(1)};
|
|
border-radius: 11px;
|
|
padding: 2px ${e.spacing(1)};
|
|
color: ${e.colors.text.primary};
|
|
background-color: ${e.colors.background.secondary};
|
|
`});function tt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function nt(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}class rt extends i.EmbeddedScene{constructor(e){super(nt(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){tt(e,t,n[t])})}return e}({},e),{key:"list-controls",body:new i.SceneFlexLayout({direction:"row",width:"100%",maxHeight:"32px",children:[new i.SceneFlexItem({body:new Ze({urlSearchParamName:"search_txt",targetName:"metric",countsProvider:new Ye})}),new i.SceneFlexItem({width:"auto",body:new _e({})}),new i.SceneFlexItem({width:"auto",body:new qe({})})]})}))}}function at(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}tt(rt,"Component",({model:e})=>{const{body:t}=e.useState();return u().createElement(l.Stack,{direction:"row",alignItems:"center"},u().createElement(t.Component,{model:t}))});class it{setInitOptions(e){this.initOptions=(0,ze.cloneDeep)(e)}getFilters(){return this.filters}static getFilteredOptions(e,t){let n=e;return t.categories.length>0&&(n=it.applyCategoryFilters(n,t.categories)),t.prefixes.length>0&&(n=it.applyPrefixFilters(n,t.prefixes)),t.suffixes.length>0&&(n=it.applySuffixFilters(n,t.suffixes)),t.names.length>0&&(n=it.applyNameFilters(n,t.names)),n}applyFilters(e=this.filters,t={forceUpdate:!1,notify:!0}){const n=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){at(e,t,n[t])})}return e}({},this.filters,e);if(!t.forceUpdate&&(0,ze.isEqual)(this.filters,n))return;if(!(n.categories.length||n.prefixes.length||n.suffixes.length||n.names.length))return this.filters=n,this.variable.setState({options:this.initOptions}),void(t.notify&&this.notifyUpdate());this.filters=n;const r=it.getFilteredOptions(this.initOptions,this.filters);this.variable.setState({options:r}),t.notify&&this.notifyUpdate()}static applyCategoryFilters(e,t){let n=[];for(const r of t){const t=it.buildRegex(r,"i");n=n.concat(e.filter(e=>t.test(e.value)))}return n}static applyPrefixFilters(e,t){const n=t.map(e=>e.includes("|")?`${e.split("|").map(e=>`^${e}([^a-z0-9]|$)`).join("|")}`:`^${e}([^a-z0-9]|$)`).join("|"),r=it.buildRegex(`(${n})`);return e.filter(e=>r.test(e.value))}static applySuffixFilters(e,t){const n=t.map(e=>e.includes("|")?`${e.split("|").map(e=>`(^|[^a-z0-9])${e}$`).join("|")}`:`(^|[^a-z0-9])${e}$`).join("|"),r=it.buildRegex(`(${n})`);return e.filter(e=>r.test(e.value))}static applyNameFilters(e,t){const[n]=t,r=n.split(",").map(e=>e.trim()).filter(Boolean).map(e=>{try{return new RegExp(e)}catch(e){return null}}).filter(Boolean);return e.filter(e=>r.some(t=>t.test(e.value)))}static buildRegex(e,t){try{return new RegExp(e,t)}catch(e){return new RegExp(".*")}}notifyUpdate(){this.variable.publishEvent(new i.SceneVariableValueChangedEvent(this.variable),!0)}constructor(e){at(this,"variable",void 0),at(this,"initOptions",[]),at(this,"filters",{categories:[],prefixes:[],suffixes:[],names:[]}),this.variable=e}}var ot=n(902);const st=new Map;function lt(e,t){let n=st.get(e);n||(n=new Map,st.set(e,n));let r=n.get(t);if(!r){const a=e.split("_"),i=a.slice(0,a.length/2).join("_");r={halfLeven:(0,ot.A)(i,t)||0,wholeLeven:(0,ot.A)(e,t)||0},n.set(t,r)}return r}function ct(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function ut(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){ct(i,r,a,o,s,"next",e)}function s(e){ct(i,r,a,o,s,"throw",e)}o(void 0)})}}function dt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class pt{sort(){return ut(function*(e=this.sortBy,t={}){const n=this.variable.state.options.map(e=>e.value);if(e===this.sortBy&&He(n,this.lastMetrics))return;let r;switch(e){case"alphabetical":r=Te(n,"asc");break;case"alphabetical-reversed":r=Te(n,"desc");break;case"dashboard-usage":case"alerting-usage":r=yield this.sortByUsage(n,e);break;case"related":a=n,i=t.metric,r=a.sort((e,t)=>{const n=lt(e,i),r=lt(t,i);return n.halfLeven+n.wholeLeven-(r.halfLeven+r.wholeLeven)});break;default:r=function(e){const t=Pe().map(e=>e.name),n=new Set(t),[r,a]=e.reduce(([e,t],r)=>(n.has(r)?e.push(r):t.push(r),[e,t]),[[],[]]),i=Te(a);return[...t.filter(e=>r.includes(e)),...i]}(n)}var a,i;this.sortBy=e,this.lastMetrics=r,this.variable.setState({options:r.map(e=>({label:e,value:e}))}),this.notifyUpdate()}).apply(this,arguments)}sortByUsage(e,t){return ut(function*(){try{const n=i.sceneGraph.findByKeyAndType(this.variable,"metrics-sorter",_e);if(!n)return Z.v.warn("Metrics sorter not found. Returning unsorted metrics.",{usageType:t}),e;const r=yield n.getUsageMetrics(t);return function(e,t){return[...e].sort((e,n)=>{const r=t[e]||0,a=t[n]||0;return a!==r?a-r:(0,q._)(e,n)})}(e,r)}catch(n){const r="string"==typeof n?new Error(n):n;return Z.v.error(r,{usageType:t}),e}}).call(this)}notifyUpdate(){this.variable.publishEvent(new i.SceneVariableValueChangedEvent(this.variable),!0)}constructor(e){dt(this,"variable",void 0),dt(this,"lastMetrics",void 0),dt(this,"sortBy",void 0),this.variable=e,this.sortBy=void 0,this.lastMetrics=[]}}class mt extends i.SceneObjectBase{performRepeat(e){var t,n,r,a;if(e.state.error)return void this.setState({errorLayout:null===(t=(n=this.state).getLayoutError)||void 0===t?void 0:t.call(n,e.state.error),loadingLayout:void 0,emptyLayout:void 0,currentBatchSize:0});if(e.state.loading)return void this.setState({loadingLayout:null===(r=(a=this.state).getLayoutLoading)||void 0===r?void 0:r.call(a),errorLayout:void 0,emptyLayout:void 0,currentBatchSize:0});const i=ht(e);var o,s;if(!i.length)return void this.setState({emptyLayout:null===(o=(s=this.state).getLayoutEmpty)||void 0===o?void 0:o.call(s),errorLayout:void 0,loadingLayout:void 0,currentBatchSize:0});this.setState({loadingLayout:void 0,errorLayout:void 0,emptyLayout:void 0,currentBatchSize:this.state.initialPageSize});const l=i.slice(0,this.state.initialPageSize).map((e,t)=>this.state.getLayoutChild(e,t,i)).filter(Boolean);this.state.body.setState({children:l})}increaseBatchSize(){const e=ht(i.sceneGraph.lookupVariable(this.state.variableName,this)),t=this.state.currentBatchSize+this.state.pageSizeIncrement,n=e.slice(this.state.currentBatchSize,t).map((t,n)=>this.state.getLayoutChild(t,this.state.currentBatchSize+n,e)).filter(Boolean);this.state.body.setState({children:[...this.state.body.state.children,...n]}),this.setState({currentBatchSize:t})}useSizes(){const{currentBatchSize:e,pageSizeIncrement:t}=this.useState(),n=i.sceneGraph.lookupVariable(this.state.variableName,this).state.options.length,r=n-e;return{increment:r<t?r:t,current:e,total:n}}constructor({variableName:e,body:t,getLayoutChild:n,getLayoutLoading:r,getLayoutError:a,getLayoutEmpty:o,initialPageSize:s,pageSizeIncrement:l}){super({variableName:e,body:t,getLayoutChild:n,getLayoutLoading:r,getLayoutError:a,getLayoutEmpty:o,currentBatchSize:0,initialPageSize:s||6,pageSizeIncrement:l||9,loadingLayout:void 0,errorLayout:void 0,emptyLayout:void 0}),this.addActivationHandler(()=>{const e=i.sceneGraph.lookupVariable(this.state.variableName,this);if(!(e instanceof i.MultiValueVariable)){const e=new Error("SceneByVariableRepeater: variable is not a MultiValueVariable!");return void Z.v.error(e)}this.performRepeat(e),this._subs.add(e.subscribeToState((t,n)=>{t.loading===n.loading&&He(t.options,n.options)||this.performRepeat(e)}))})}}function ht(e){const{value:t,text:n,options:r}=e.state;return e.hasAllValue()?r:Array.isArray(t)&&Array.isArray(n)?t.map((e,t)=>({value:e,label:n[t]})):[{value:t,label:n}]}function ft({label:e,batchSizes:t,onClick:n,tooltip:r}){return u().createElement(l.Button,{variant:"secondary",fill:"outline",onClick:n,tooltip:r,tooltipPlacement:"top"},"Show ",t.increment," more ",1===t.increment?e:`${e}s`," (",t.current,"/",t.total,")")}function bt({usageType:e,usageCount:t,singularUsageType:n,pluralUsageType:r,icon:a,dashboardItems:i}){const s=(0,l.useStyles2)(gt);return u().createElement("div",{className:s.usageContainer,"data-testid":"usage-data-panel"},u().createElement(l.Stack,{direction:"row",justifyContent:"flex-start",alignItems:"center",gap:2},"dashboard-usage"===e?u().createElement(l.Dropdown,{placement:"right-start",overlay:u().createElement(l.Menu,{style:{maxWidth:"240px",maxHeight:"245px",overflowY:"auto"}},i.map(e=>u().createElement(l.Menu.Item,{key:e.id,label:"",url:e.url,target:"_blank",className:s.menuItem,component:()=>u().createElement(l.Tooltip,{content:`Used ${e.count} ${1===e.count?"time":"times"} in ${e.label}`,placement:"right"},u().createElement("div",{className:s.menuItemContent},u().createElement(l.Icon,{name:"external-link-alt"})," ",e.label," (",e.count,")"))})))},u().createElement(l.Button,{variant:"secondary",size:"sm",tooltip:`Metric used ${t} ${1===t?"time":"times"} in dashboard queries. Click to view the dashboards.`,className:(0,o.cx)(s.usageItem,s.clickableUsageItem)},u().createElement(l.Stack,{direction:"row",alignItems:"center",gap:.5,"data-testid":e},u().createElement(l.Icon,{name:a}),u().createElement("span",null,t)))):u().createElement(l.Tooltip,{content:`Metric is used in ${t} ${1===t?n:r}`,placement:"top"},u().createElement("span",{className:s.usageItem,"data-testid":e},u().createElement(l.Stack,{direction:"row",alignItems:"center",gap:.5},u().createElement(l.Icon,{name:a}),u().createElement("span",null,t))))))}function gt(e){return{usageContainer:(0,o.css)({padding:"8px 12px",border:`1px solid ${e.colors.border.weak}`,borderTopWidth:0,backgroundColor:e.colors.background.primary}),usageItem:(0,o.css)({color:e.colors.text.secondary,opacity:"65%"}),clickableUsageItem:(0,o.css)({backgroundColor:"transparent",border:"none"}),menuItem:(0,o.css)({color:e.colors.text.primary,textDecoration:"none","&:hover":{color:e.colors.text.link}}),menuItemContent:(0,o.css)({overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:e.colors.text.primary,"&:hover":{color:e.colors.text.link}})}}function yt(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function vt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function St(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(mt,"Component",({model:e})=>{const{body:t,loadingLayout:n,errorLayout:r,emptyLayout:a}=e.useState();return r?u().createElement(r.Component,{model:r}):n?u().createElement(n.Component,{model:n}):a?u().createElement(a.Component,{model:a}):u().createElement(t.Component,{model:t})});const wt="220px",Ot="260px";class Et extends i.SceneObjectBase{_onActivate(){let e;try{e=i.sceneGraph.getAncestor(this,ea)}catch(e){return}if(!e.state.enginesMap.get(Ge))return;const t=i.sceneGraph.findByKeyAndType(this,"metrics-sorter",_e),n=i.sceneGraph.getVariables(t).getByName(je);V(n)&&(this.updateSortBy(t,n.getValue()),this._subs.add(n.subscribeToState(({value:e})=>{this.updateSortBy(t,e)})))}updateSortBy(e,t){return(n=function*(){if(this.setState({sortBy:t}),this.updateLayout(t),!we(t))return;const n=yield e.getUsageDetailsForMetric(this.state.metric,t);switch(n.usageType){case"dashboard-usage":this.setState({usageCount:n.count,singularUsageType:"dashboard panel query",pluralUsageType:"dashboard panel queries",icon:"apps",dashboardItems:Object.entries(n.dashboards).map(([e,t])=>({id:t.uid,label:e,count:t.count,url:t.url})).sort((e,t)=>t.count-e.count)});break;case"alerting-usage":this.setState({usageCount:n.count,singularUsageType:"alert rule",pluralUsageType:"alert rules",icon:"bell"})}},function(){var e=this,t=arguments;return new Promise(function(r,a){var i=n.apply(e,t);function o(e){yt(i,r,a,o,s,"next",e)}function s(e){yt(i,r,a,o,s,"throw",e)}o(void 0)})}).call(this);var n}updateLayout(e){const t=i.sceneGraph.getAncestor(this,i.SceneCSSGridLayout),n=null==t?void 0:t.state.autoRows,r=we(e)?Ot:wt;n!==r&&t.setState({autoRows:r})}constructor(e){super(St(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){vt(e,t,n[t])})}return e}({},e),{sortBy:"default",usageCount:0,singularUsageType:"",pluralUsageType:"",icon:"",dashboardItems:[]})),this.addActivationHandler(this._onActivate.bind(this))}}function xt(){return u().createElement("svg",{stroke:"currentColor",width:"17",height:"16",viewBox:"0 0 17 16",fill:"none"},u().createElement("circle",{cx:"8.92688",cy:"3.63132",r:"2.375",strokeWidth:"1.5"}),u().createElement("path",{d:"M13.6469 4.37965C14.6813 4.76699 15.3235 7.03139 14.9362 8.06582",strokeWidth:"1.5"}),u().createElement("path",{d:"M4.35309 4.37965C3.31866 4.76699 2.67651 7.03139 3.06384 8.06582",strokeWidth:"1.5"}),u().createElement("path",{d:"M10.3408 14.2531C9.75237 14.8415 8.11813 14.7799 7.50903 14.1708",strokeWidth:"1.5"}),u().createElement("circle",{cx:"4.00195",cy:"12.251",r:"2.375",strokeWidth:"1.5"}),u().createElement("circle",{cx:"13.8478",cy:"12.251",r:"2.375",strokeWidth:"1.5"}))}vt(Et,"Component",({model:e})=>{const{vizPanelInGridItem:t,sortBy:n,usageCount:r,singularUsageType:a,pluralUsageType:i,icon:o,dashboardItems:s}=e.useState();if(t)return u().createElement("div",{"data-testid":"with-usage-data-preview-panel"},u().createElement(t.Component,{model:t}),we(n)&&u().createElement(bt,{usageType:n,usageCount:r,singularUsageType:a,pluralUsageType:i,icon:o,dashboardItems:s}));Z.v.log("no viz panel")});class Ct extends r.BusEventWithPayload{}function Pt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ct,"type","configure-panel");class kt extends i.SceneObjectBase{constructor({metric:e,disabled:t}){var n;const r=te.x.getItem(ee.V.METRIC_PREFS)||{};super({metric:e,disabled:void 0!==t&&t,isAlreadyConfigured:Boolean(null===(n=r[e.name])||void 0===n?void 0:n.config)}),Pt(this,"onClick",()=>{this.publishEvent(new Ct({metric:this.state.metric}),!0)})}}Pt(kt,"Component",({model:e})=>{const t=(0,l.useStyles2)(jt),{isAlreadyConfigured:n,disabled:r}=e.useState(),a=n?"Reconfigure Prometheus function":"Configure Prometheus function";return u().createElement(l.Button,{className:(0,o.cx)(t.selectButton,n&&t.active),"aria-label":a,variant:"secondary",size:"sm",fill:"text",onClick:e.onClick,icon:"cog",tooltip:a,tooltipPlacement:"top",disabled:r,"data-testid":"configure-panel"})});const jt=e=>({selectButton:o.css`
|
|
margin: 0;
|
|
padding: 0;
|
|
margin-left: ${e.spacing(1)};
|
|
`,active:o.css`
|
|
color: ${e.colors.text.maxContrast};
|
|
`});function _t(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Tt extends i.SceneObjectBase{constructor({metric:e,variant:t,fill:n}){super({key:`select-action-${e}`,metric:e,variant:t||"primary",fill:n||"outline"}),_t(this,"onClick",()=>{this.publishEvent(new I({metric:this.state.metric}),!0)})}}_t(Tt,"Component",({model:e})=>{const{variant:t,fill:n}=e.useState();return u().createElement(l.Button,{variant:t,fill:n,size:"sm",onClick:e.onClick,"data-testid":`select-action-${e.state.metric}`},"Select")});class It extends r.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(It,"type","panel-type-changed");const Dt={TIMESERIES_AVG:"timeseries-avg",TIMESERIES_SUM:"timeseries-sum",TIMESERIES_STDDEV:"timeseries-stddev",TIMESERIES_PERCENTILES:"timeseries-percentiles",TIMESERIES_MIN_MAX:"timeseries-minmax",TIMESERIES_COUNT:"timeseries-count",TIMESERIES_AGE_TIME_MINUS_AVG:"timeseries-age-time-minus-avg",TIMESERIES_AGE_TIME_MINUS_MIN_MAX:"timeseries-age-time-minus-min-max",HISTOGRAM_HEATMAP:"histogram-heatmap",HISTOGRAM_PERCENTILES:"histogram-percentiles",STATUS_UPDOWN_HISTORY:"status-updown-history",STATUS_UPDOWN_STAT:"status-updown-stat"};var At=n(8162);const Lt=new Map([...["avg","sum","stddev","quantile","min","max","count"].map(e=>[e,{name:e,fn:t=>At.GH[e](t)}]),["histogram_quantile",{name:"histogram_quantile",fn:({expr:e,parameter:t})=>`histogram_quantile(${t},${e})`}],["time-avg(metric)",{name:"time-avg(metric)",fn:({expr:e})=>`time()-avg(${e})`}],["time-min(metric)",{name:"time-min(metric)",fn:({expr:e})=>`time()-min(${e})`}],["time-max(metric)",{name:"time-max(metric)",fn:({expr:e})=>`time()-max(${e})`}]]),Bt=new Set(Object.values(Dt)),Nt=new Set(["heatmap","percentiles","stat","statushistory","timeseries"]);function Rt(e){var t;const n=te.x.getItem(ee.V.METRIC_PREFS)||{},r=null===(t=n[e])||void 0===t?void 0:t.config;var a;if(r)return function(e){if(!["id","panelOptions","queryOptions"].every(t=>t in e))return!1;if("string"!=typeof e.id||!Bt.has(e.id))return!1;if("string"!=typeof e.panelOptions.type||!Nt.has(e.panelOptions.type))return!1;if(!Array.isArray(e.queryOptions.queries))return!1;if(!e.queryOptions.queries.every(e=>{var t;return!!Lt.has(e.fn)&&(!["quantile","histogram_quantile"].includes(e.fn)||!(!Array.isArray(null===(t=e.params)||void 0===t?void 0:t.percentiles)||!e.params.percentiles.length)&&e.params.percentiles.every(e=>e>=1&&e<=99))}))return!1;return!0}(r)?r:((0,d.z)("invalid_metric_config",{metricConfig:r}),null===(a=n[e])||void 0===a||delete a.config,te.x.setItem(ee.V.METRIC_PREFS,n),void(0,v.HA)([`Invalid configuration found for metric ${e}!`,"The configuration has been deleted and will not be applied."]))}var Mt=function(e){return e[e.S=160]="S",e[e.M=220]="M",e[e.L=260]="L",e[e.XL=280]="XL",e}({}),$t=function(e){return e.HIGH="HIGH",e.MEDIUM="MEDIUM",e}({});const Vt=e=>e.endsWith("_bucket"),Ft=/_(count|total|sum)$/,qt=/_up$/;function Gt(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function Ut(e,t){return(n=function*(){const n=zt(e);if("gauge"===n){const n=yield t.getMetadataForMetric(e);if("histogram"===(null==n?void 0:n.type))return"native-histogram";if("counter"===(null==n?void 0:n.type))return"counter"}if("counter"===n){const n=yield t.getMetadataForMetric(e);if("gauge"===(null==n?void 0:n.type))return"gauge"}return n},function(){var e=this,t=arguments;return new Promise(function(r,a){var i=n.apply(e,t);function o(e){Gt(i,r,a,o,s,"next",e)}function s(e){Gt(i,r,a,o,s,"throw",e)}o(void 0)})})();var n}function zt(e){return(e=>Ft.test(e))(e)?"counter":Vt(e)?"classic-histogram":(e=>e.endsWith("_timestamp_seconds"))(e)?"age":(e=>"up"===e||qt.test(e))(e)?"status-updown":(e=>e.endsWith("_info"))(e)?"info":"gauge"}function Ht(e){switch(zt(e)){case"classic-histogram":return"heatmap";case"status-updown":return"statushistory";default:return"timeseries"}}var Kt=n(5938);function Wt(e){const{metric:t,labelMatchers:n=[],addIgnoreUsageFilter:r=!0,addExtremeValuesFiltering:a=!1}=e,i=n.map(e=>({label:(0,s.Nc)(e.key),operator:e.operator,value:e.value}));r&&i.push({label:"__ignore_usage__",operator:At.md.equal,value:""});!(0,s.Rq)(t.name)&&i.push({label:(0,s.Nc)(t.name),operator:At.md.equal,value:"__REMOVE__"}),i.push({label:`\${${O}:raw}`,operator:At.md.equal,value:"__REMOVE__"});const o=function(e){return e.toString().replaceAll('="__REMOVE__"',"")}(new At.r4({metric:t.name,values:{},defaultOperator:At.md.equal,defaultSelectors:i}));return a?At.GH.and({left:o,right:`${o} > -Inf`}):o}function Qt(e){const{metric:t,queryConfig:n}=e,r=Wt({metric:t,labelMatchers:n.labelMatchers,addIgnoreUsageFilter:n.addIgnoreUsageFilter,addExtremeValuesFiltering:n.addExtremeValuesFiltering}),a="native-histogram"===t.type?At.GH.sum({expr:At.GH.rate({expr:r})}):At.GH.sum({expr:At.GH.rate({expr:r}),by:["le"]});return{maxDataPoints:n.resolution===$t.HIGH?500:250,queries:[{refId:`${t.name}-heatmap`,expr:a,format:"heatmap",fromExploreMetrics:!0}]}}const Yt="none",Xt="bytes",Jt="seconds",Zt="percent",en="count",tn={[Xt]:Xt,[Jt]:"s",[Zt]:Zt,[en]:Yt},nn=Object.keys(tn),rn={[Xt]:"Bps",[Jt]:Yt,[en]:"cps",[Zt]:Zt};function an(e){const t=e.toLowerCase().split("_").slice(-2);for(let e=t.length-1;e>=Math.max(0,t.length-2);e--){const n=t[e];if(nn.includes(n))return n}return null}function on(e){const t=an(e);return t&&tn[t.toLowerCase()]||Yt}function sn(e){const t=an(e);return t&&rn[t]||"cps"}var ln=n(1625);const cn=[99,90,50];function un(e){const{metric:t,queryConfig:n}=e,r=Wt({metric:t,labelMatchers:n.labelMatchers,addIgnoreUsageFilter:n.addIgnoreUsageFilter,addExtremeValuesFiltering:n.addExtremeValuesFiltering}),a=["classic-histogram","native-histogram"].includes(t.type),i=a?function({metric:e,queryConfig:t,expr:n}){var r;const a=(null===(r=t.queries)||void 0===r?void 0:r.length)?t.queries:[{fn:"histogram_quantile",params:{percentiles:cn}}],i=[],o="native-histogram"===e.type?At.GH.sum({expr:At.GH.rate({expr:n})}):At.GH.sum({expr:At.GH.rate({expr:n}),by:["le"]});for(const{fn:t,params:n}of a){const r=Lt.get(t),a=r.name,s=(null==n?void 0:n.percentiles)||cn;for(const t of s){const n=t/100,s=r.fn({expr:o,parameter:n});i.push({refId:`${e.name}-p${t}-${a}`,expr:s,legendFormat:`${t}th Percentile`,fromExploreMetrics:!0})}}return i}({metric:t,queryConfig:n,expr:r}):function({metric:e,queryConfig:t,expr:n}){var r;const a="counter"===e.type,i=(null===(r=t.queries)||void 0===r?void 0:r.length)?t.queries:[{fn:"quantile",params:{percentiles:[99,90,50]}}],o=[],s=a?At.GH.rate({expr:n}):n;for(const{fn:t,params:n}of i){const r=Lt.get(t),i=a?`${r.name}(rate)`:r.name;for(const t of n.percentiles){const n=t/100,a=r.fn({expr:s,parameter:n});o.push({refId:`${e.name}-p${t}-${i}`,expr:a,legendFormat:`${t}th Percentile`,fromExploreMetrics:!0})}}return o}({metric:t,queryConfig:n,expr:r});return{isRateQuery:!!a||"counter"===t.type,maxDataPoints:n.resolution===$t.HIGH?500:250,queries:i}}function dn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const pn=(e=0)=>t=>{const[n]=i.sceneGraph.findDescendents(t,i.SceneQueryRunner);if(!n)return;const r=n.subscribeToState((n,r)=>{if(n.queries!==r.queries){const r=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){dn(e,t,n[t])})}return e}({},t.state.fieldConfig);r.defaults.color=void 0,r.overrides=n.queries.map((t,n)=>({matcher:{id:"byFrameRefID",options:t.refId},properties:[{id:"color",value:{mode:"fixed",fixedColor:fs(e+n)}}]})),t.setState({fieldConfig:r})}});return()=>{r.unsubscribe()}};function mn(e){const{metric:t,queryConfig:n}=e,r="counter"===t.type,a=Wt({metric:t,labelMatchers:n.labelMatchers,addIgnoreUsageFilter:n.addIgnoreUsageFilter,addExtremeValuesFiltering:n.addExtremeValuesFiltering}),i=r?At.GH.rate({expr:a,interval:"$__rate_interval"}):a;return{isRateQuery:r,maxDataPoints:n.resolution===$t.HIGH?500:250,queries:hn({metric:t,queryConfig:n,isRateQuery:r,expr:i})}}function hn({metric:e,queryConfig:t,isRateQuery:n,expr:r}){var a;const i=n?"sum":"avg",o=(null===(a=t.queries)||void 0===a?void 0:a.length)?t.queries:[{fn:i}],s=[];for(const{fn:t}of o){const a=Lt.get(t),i=a.fn({expr:r}),o=n?`${a.name}(rate)`:a.name;s.push({refId:`${e.name}-${o}`,expr:i,legendFormat:o,fromExploreMetrics:!0})}return s}var fn=n(6145);const bn=[{type:fn.dM.ValueToText,options:{0:{color:"red",text:"down"},1:{color:"green",text:"up"}}}];function gn(e){const{metric:t,queryConfig:n}=e,r=Wt({metric:t,labelMatchers:n.labelMatchers,addIgnoreUsageFilter:n.addIgnoreUsageFilter,addExtremeValuesFiltering:n.addExtremeValuesFiltering}),a=At.GH.min({expr:r});return{maxDataPoints:n.resolution===$t.HIGH?200:100,queries:[{refId:`${t.name}-status`,expr:a,legendFormat:"status",fromExploreMetrics:!0}]}}function yn(e){const{metric:t,queryConfig:n}=e,r=Wt({metric:t,labelMatchers:n.labelMatchers,addIgnoreUsageFilter:n.addIgnoreUsageFilter,addExtremeValuesFiltering:n.addExtremeValuesFiltering}),a="counter"===t.type,i=a?At.GH.rate({expr:r,interval:"$__rate_interval"}):r;return{isRateQuery:a,maxDataPoints:n.resolution===$t.HIGH?500:250,queries:n.groupBy?vn({metric:t,queryConfig:n,expr:i}):Sn({metric:t,queryConfig:n,expr:i})}}function vn({metric:e,queryConfig:t,expr:n}){let r="avg";return"counter"===e.type?r="sum":"info"===e.type&&(r="count"),[{refId:`${e.name}-by-${t.groupBy}`,expr:At.GH[r]({expr:n,by:[t.groupBy]}),legendFormat:`{{${t.groupBy}}}`,fromExploreMetrics:!0}]}function Sn({metric:e,queryConfig:t,expr:n}){var r;let a="avg";"counter"===e.type?a="sum":"info"===e.type&&(a="count");const i=(null===(r=t.queries)||void 0===r?void 0:r.length)?t.queries:[{fn:a}],o=[];for(const{fn:t}of i){const r=Lt.get(t),a=r.fn({expr:n}),i="counter"===e.type?`${r.name}(rate)`:r.name;o.push({refId:`${e.name}-${i}`,expr:a,legendFormat:i,fromExploreMetrics:!0})}return o}function wn(e){const t=e.fields.find(e=>"Value"===e.name);return!!(t&&(n=t,"entities"in n&&Array.isArray(null===(r=n.entities)||void 0===r?void 0:r.NaN)))&&t.entities.NaN.length===e.length;var n,r}function On(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function En(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){On(e,t,n[t])})}return e}function xn(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function Cn(e){if("timeseries"!==e.state.pluginId)return;const[t]=i.sceneGraph.findDescendents(e,i.SceneQueryRunner);if(!t)return;const{queries:n}=t.state;if(!(null==n?void 0:n.length))return;const{metric:a,metricType:o,queryConfig:s}=i.sceneGraph.getAncestor(e,zn).state;if("counter"===o)return;const l=t.subscribeToState((n,l)=>{var c,p,m,h;if((null===(c=n.data)||void 0===c?void 0:c.state)!==r.LoadingState.Done||!(null===(p=n.data.series)||void 0===p?void 0:p.length)||n.data.series===(null===(m=l.data)||void 0===m?void 0:m.series))return;const f=null===(h=n.data.series[0].meta)||void 0===h?void 0:h.type;if(f&&!f.startsWith("timeseries"))return;if(!n.data.series.every(wn))return;const b=yn({metric:{name:a,type:o},queryConfig:xn(En({},s),{addExtremeValuesFiltering:!0})});t.setState({queries:b.queries}),t.runQueries(),e.setState({titleItems:u().createElement(Pn,{level:"info",message:"Panel data was re-fetched with a more complex query to handle extremely small values in the series"})}),(0,d.z)("extreme_value_filter_behavior_triggered",{expression:i.sceneGraph.interpolate(t,t.state.queries[0].expr)})});return()=>{l.unsubscribe()}}function Pn({message:e,level:t}){const n=(0,l.useStyles2)(kn,t);return u().createElement("div",{className:n.extremeValuedisclaimer},u().createElement(l.Tooltip,{content:e},u().createElement("span",{className:n.warningMessage},u().createElement(l.Icon,{name:"warning"===t?"exclamation-triangle":"info-circle","aria-hidden":"true"}))))}const kn=(e,t)=>({extremeValuedisclaimer:(0,o.css)({label:"extreme-value-disclaimer",display:"flex",alignItems:"center",gap:e.spacing(1)}),warningMessage:(0,o.css)({display:"flex",alignItems:"center",gap:e.spacing(.5),color:"warning"===t?e.colors.warning.main:e.colors.info.main,fontSize:e.typography.bodySmall.fontSize})});var jn=n(1269);const _n=()=>e=>e.pipe((0,jn.map)(e=>null==e?void 0:e.map((e,t)=>(e.refId=`${e.refId}-${t}`,e))));function Tn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function In(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}const Dn=e=>()=>t=>t.pipe((0,jn.map)(t=>null==t?void 0:t.map(t=>{var n;return(null==t?void 0:t.fields[1])?((null===(n=t.fields[1].labels)||void 0===n?void 0:n[e])||(t.fields[1].labels=In(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Tn(e,t,n[t])})}return e}({},t.fields[1].labels),{[e]:`<unspecified ${e}>`})),t):t})));function An(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const Ln=(e,t)=>()=>n=>n.pipe((0,jn.map)(n=>null==n?void 0:n.slice(e,t).map(e=>{var t;return e.meta=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){An(e,t,n[t])})}return e}({},e.meta),(t=e.meta).stats||(t.stats=[]),e.meta.stats.unshift({displayName:"seriesCount",value:n.length}),e})));function Bn(e){var t;if(e.queryConfig.groupBy)return function(e){var t;const{metric:n,panelConfig:r,queryConfig:a}=e,o=yn({metric:n,queryConfig:a}),s=o.isRateQuery?sn(n.name):on(n.name),l=new i.SceneDataTransformer({$data:new i.SceneQueryRunner({datasource:T,maxDataPoints:o.maxDataPoints,queries:o.queries}),transformations:[Ln(0,Nn),Dn(a.groupBy),_n]}),{refId:c}=o.queries[0],u=r.fixedColorIndex||0,d=i.PanelBuilders.timeseries().setTitle(r.title).setDescription(r.description).setHeaderActions(r.headerActions({metric:n,panelConfig:r})).setMenu(null===(t=r.menu)||void 0===t?void 0:t.call(r,{metric:n,panelConfig:r})).setShowMenuAlways(Boolean(r.menu)).setData(l).setUnit(s).setOption("legend",r.legend||{showLegend:!0,placement:"right"}).setOption("tooltip",{mode:ln.$N.Multi,sort:ln.xB.Descending}).setOverrides(e=>{for(let t=0;t<Nn;t++)e.matchFieldsByQuery(`${c}-${t}`).overrideColor({mode:"fixed",fixedColor:fs(u+t)})}).setBehaviors(r.behaviors).build();return d}(e);const{metric:n,panelConfig:r,queryConfig:a}=e,o=yn({metric:n,queryConfig:a}),s=o.isRateQuery?sn(n.name):on(n.name),l=a.data||new i.SceneQueryRunner({datasource:T,maxDataPoints:o.maxDataPoints,queries:o.queries}),c=i.PanelBuilders.timeseries().setTitle(r.title).setDescription(r.description).setHeaderActions(r.headerActions({metric:n,panelConfig:r})).setMenu(null===(t=r.menu)||void 0===t?void 0:t.call(r,{metric:n,panelConfig:r})).setShowMenuAlways(Boolean(r.menu)).setData(l).setUnit(s).setOption("legend",r.legend||{showLegend:!0,placement:"bottom"}).setCustomFieldConfig("fillOpacity",9).setBehaviors([Cn,pn(r.fixedColorIndex),...r.behaviors||[]]);if(1===o.queries.length)c.setColor(r.fixedColorIndex?{mode:"fixed",fixedColor:fs(r.fixedColorIndex)}:void 0);else{const e=r.fixedColorIndex||0;c.setOverrides(t=>{o.queries.forEach((n,r)=>{t.matchFieldsByQuery(n.refId).overrideColor({mode:"fixed",fixedColor:fs(e+r)})})})}return c.build()}const Nn=20;const Rn=new Map([["timeseries",{buildVizPanel:Bn,getQueryRunnerParams:yn}],["heatmap",{buildVizPanel:function(e){var t;const{metric:n,panelConfig:r,queryConfig:a}=e,o=Qt({metric:n,queryConfig:a}),s=on(n.name),l=a.data||new i.SceneQueryRunner({datasource:T,maxDataPoints:o.maxDataPoints,queries:o.queries});return i.PanelBuilders.heatmap().setTitle(r.title).setDescription(r.description).setHeaderActions(r.headerActions({metric:n,panelConfig:r})).setMenu(null===(t=r.menu)||void 0===t?void 0:t.call(r,{metric:n,panelConfig:r})).setShowMenuAlways(Boolean(r.menu)).setData(l).setUnit(s).setOption("calculate",!1).setOption("color",{mode:Kt.P7.Scheme,exponent:.5,scheme:"Spectral",steps:32,reverse:!1}).setOption("legend",r.legend).build()},getQueryRunnerParams:Qt}],["percentiles",{buildVizPanel:function(e){var t;const{metric:n,panelConfig:r,queryConfig:a}=e,o=un({metric:n,queryConfig:a}),s=o.isRateQuery?sn(n.name):on(n.name),l=a.data||new i.SceneQueryRunner({datasource:T,maxDataPoints:o.maxDataPoints,queries:o.queries}),c=r.fixedColorIndex||0;return i.PanelBuilders.timeseries().setTitle(r.title).setDescription(r.description).setHeaderActions(r.headerActions({metric:n,panelConfig:r})).setMenu(null===(t=r.menu)||void 0===t?void 0:t.call(r,{metric:n,panelConfig:r})).setShowMenuAlways(Boolean(r.menu)).setData(l).setUnit(s).setOption("legend",r.legend||{showLegend:!0,placement:"bottom"}).setOption("tooltip",{mode:ln.$N.Multi,sort:ln.xB.Descending}).setCustomFieldConfig("fillOpacity",9).setOverrides(e=>{o.queries.forEach((t,n)=>{e.matchFieldsByQuery(t.refId).overrideColor({mode:"fixed",fixedColor:fs(c+n)})})}).setBehaviors([pn(c),...r.behaviors||[]]).build()},getQueryRunnerParams:un}],["statushistory",{buildVizPanel:function(e){var t;const{metric:n,panelConfig:r,queryConfig:a}=e,o=gn({metric:n,queryConfig:a}),s=a.data||new i.SceneQueryRunner({datasource:T,maxDataPoints:o.maxDataPoints,queries:o.queries});return i.PanelBuilders.statushistory().setTitle(r.title).setDescription(r.description).setHeaderActions(r.headerActions({metric:n,panelConfig:r})).setMenu(null===(t=r.menu)||void 0===t?void 0:t.call(r,{metric:n,panelConfig:r})).setShowMenuAlways(Boolean(r.menu)).setData(s).setUnit("none").setColor({mode:"palette-classic"}).setOption("showValue",ln.yL.Never).setOption("legend",r.legend||{showLegend:!0,placement:"bottom"}).setOption("perPage",0).setMappings(bn).build()},getQueryRunnerParams:gn}],["stat",{buildVizPanel:function(e){var t;const{metric:n,panelConfig:r,queryConfig:a}=e,o=mn({metric:n,queryConfig:a}),s=a.data||new i.SceneQueryRunner({datasource:T,maxDataPoints:o.maxDataPoints,queries:o.queries});return i.PanelBuilders.stat().setTitle(r.title).setDescription(r.description).setHeaderActions(r.headerActions({metric:n,panelConfig:r})).setMenu(null===(t=r.menu)||void 0===t?void 0:t.call(r,{metric:n,panelConfig:r})).setShowMenuAlways(Boolean(r.menu)).setData(s).setUnit("none").setColor({mode:"fixed",fixedColor:fs(r.fixedColorIndex||0)}).setMappings(bn).build()},getQueryRunnerParams:mn}]]);function Mn(e){const t=Rn.get(e);if(!t)throw new TypeError(`Unsupported panel type "${e}"!`);return t}const $n={buildVizPanel:e=>Mn(e.panelConfig.type).buildVizPanel(e),getQueryRunnerParams(e){const{metric:t,queryConfig:n,panelType:r}=e;return Mn(r).getQueryRunnerParams({metric:t,queryConfig:n})}};function Vn(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function Fn(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){Vn(i,r,a,o,s,"next",e)}function s(e){Vn(i,r,a,o,s,"throw",e)}o(void 0)})}}function qn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Gn(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){qn(e,t,n[t])})}return e}function Un(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}class zn extends i.SceneObjectBase{onActivate(e){return Fn(function*(){this.buildVizPanel(),this.subscribeToStateChanges(e),this.subscribeToEvents(),this.checkMetricMetadata(e)}).call(this)}checkMetricMetadata(e){return Fn(function*(){const{metric:t,metricType:n,panelConfig:r}=this.state,a=yield Ut(t,ds(this));if(n===a)return;const i={},o={};var s;"native-histogram"===a&&(i.metricType="native-histogram",o.description=null!==(s=r.description)&&void 0!==s?s:"Native Histogram",e||(o.type="heatmap"));"gauge"===a&&"counter"===n&&(i.metricType="gauge"),"counter"===a&&"gauge"===n&&(i.metricType="counter"),(Object.keys(i).length||Object.keys(o).length)&&this.setState(Un(Gn({},i),{panelConfig:Gn({},r,o)}))}).call(this)}subscribeToStateChanges(e){const{metricType:t,body:n,panelConfig:a}=this.state;if(!e&&!["classic-histogram","native-histogram"].includes(t)){var i;const e=null==n||null===(i=n.state.$data)||void 0===i?void 0:i.subscribeToState(t=>{var n,i,o,s;if((null===(n=t.data)||void 0===n?void 0:n.state)!==r.LoadingState.Done)return;const l=null===(s=t.data.series)||void 0===s||null===(o=s[0])||void 0===o||null===(i=o.meta)||void 0===i?void 0:i.type;l&&(l===r.DataFrameType.HeatmapCells&&this.setState({panelConfig:Un(Gn({description:"Native Histogram "},a),{type:"heatmap"})}),e.unsubscribe())});this._subs.add(e)}this.subscribeToState((e,t)=>{if(e.panelConfig.type===t.panelConfig.type){if(!(0,ze.isEqual)(e.panelConfig,t.panelConfig)){const n=(0,ze.omitBy)(e.panelConfig,(e,n)=>e===t.panelConfig[n]);this.updatePanelOptions(n)}e.metricType===t.metricType&&(0,ze.isEqual)(e.queryConfig,t.queryConfig)||(this.updatePanelQueries(),this.updatePanelOptions({headerActions:e.panelConfig.headerActions,menu:e.panelConfig.menu}))}else this.buildVizPanel()})}subscribeToEvents(){this.subscribeToEvent(It,e=>{this.setState({panelConfig:Un(Gn({},this.state.panelConfig),{type:e.payload.panelType})})})}buildVizPanel(){const{metric:e,metricType:t,panelConfig:n,queryConfig:r}=this.state;this.setState({body:$n.buildVizPanel({metric:{name:e,type:t},panelConfig:n,queryConfig:r})})}updatePanelOptions(e){const{metric:t,metricType:n,body:r,panelConfig:a}=this.state;if(!r)return;const i={name:t,type:n};e.description&&r.setState({description:e.description}),e.headerActions&&r.setState({headerActions:e.headerActions({metric:i,panelConfig:a})}),e.menu&&r.setState({menu:e.menu({metric:i,panelConfig:a})})}updatePanelQueries(){const{body:e,metric:t,metricType:n,panelConfig:r,queryConfig:a}=this.state;if(!e)return;const[o]=i.sceneGraph.findDescendents(e,i.SceneQueryRunner);if(!o)return;const s=$n.getQueryRunnerParams({panelType:r.type,metric:{name:t,type:n},queryConfig:a});o.setState({queries:s.queries}),o.runQueries()}update(e,t){const{panelConfig:n,queryConfig:r}=this.state;this.setState({panelConfig:Gn({},n,e),queryConfig:Gn({},r,t)})}constructor({key:e,metric:t,panelOptions:n,queryOptions:r,discardUserPrefs:a}){const i=zt(t),o=a?void 0:Rt(t);super({key:e,metric:t,metricType:i,panelConfig:Gn({type:(null==n?void 0:n.type)||Ht(t),title:t,height:Mt.M,headerActions:({metric:e})=>[new Tt({metric:e.name})]},n,null==o?void 0:o.panelOptions),queryConfig:Gn({resolution:$t.MEDIUM,labelMatchers:[],addIgnoreUsageFilter:!0},r,null==o?void 0:o.queryOptions),body:void 0}),this.addActivationHandler(()=>{this.onActivate(Boolean((null==n?void 0:n.type)||(null==o?void 0:o.panelOptions.type)))})}}function Hn(e,t){return{container:o.css`
|
|
width: 100%;
|
|
height: ${t}px;
|
|
`}}qn(zn,"Component",({model:e})=>{const{body:t,panelConfig:n}=e.useState(),r=(0,l.useStyles2)(Hn,n.height);return u().createElement("div",{className:r.container,"data-testid":"gmd-vizpanel"},t&&u().createElement(t.Component,{model:t}))});var Kn=n(6503);const Wn="repeat(auto-fit, minmax(400px, 1fr))",Qn="1fr";class Yn extends i.SceneObjectBase{onActivate(){this.subscribeToLayoutChange()}subscribeToLayoutChange(){const e=i.sceneGraph.findByKeyAndType(this,"layout-switcher",qe),t=this.state.body.state.body,n=(e,n)=>{e.layout!==(null==n?void 0:n.layout)&&t.setState({templateColumns:e.layout===Fe.ROWS?Qn:Wn})};n(e.state),this._subs.add(e.subscribeToState(n))}constructor({variableName:e}){super({key:"metrics-list",variableName:e,body:new mt({variableName:e,initialPageSize:120,pageSizeIncrement:9,body:new i.SceneCSSGridLayout({children:[],isLazy:!0,templateColumns:Wn,autoRows:wt,$behaviors:[new i.behaviors.CursorSync({key:"metricCrosshairSync",sync:fn.yV.Crosshair})]}),getLayoutLoading:()=>new i.SceneReactObject({reactNode:u().createElement(l.Spinner,{inline:!0})}),getLayoutEmpty:()=>new i.SceneReactObject({reactNode:u().createElement(Kn._,{title:"",severity:"info"},"No metrics found for the current filters and time range.")}),getLayoutError:e=>new i.SceneReactObject({reactNode:u().createElement(Kn._,{severity:"error",title:"Error while loading metrics!",error:e})}),getLayoutChild:(e,t)=>new i.SceneCSSGridItem({body:new Et({metric:e.value,vizPanelInGridItem:new zn({metric:e.value,panelOptions:{fixedColorIndex:t,headerActions:({metric:e})=>[new kt({metric:e}),new Tt({metric:e.name})]}})})})})}),this.addActivationHandler(this.onActivate.bind(this))}}function Xn(e){return{container:(0,o.css)({}),footer:(0,o.css)({display:"flex",justifyContent:"center",alignItems:"center",marginTop:e.spacing(4),"& button":{height:"40px",borderRadius:"8px"}})}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Yn,"Component",({model:e})=>{const{variableName:t,body:n}=e.useState(),r=(0,l.useStyles2)(Xn),a=i.sceneGraph.lookupVariable(t,e),{loading:o,error:s}=a.useState(),c=n.useSizes(),d=!o&&!s&&c.total>0&&c.current<c.total;return u().createElement("div",{"data-testid":"metrics-list"},u().createElement("div",{className:r.container},u().createElement(n.Component,{model:n})),d&&u().createElement("div",{className:r.footer},u().createElement(ft,{label:"metric",batchSizes:c,onClick:()=>{n.increaseBatchSize()}})))});class Jn extends i.SceneObjectBase{onActivate(){this.subscribeToLayoutChange()}subscribeToLayoutChange(){const e=i.sceneGraph.findByKeyAndType(this,"layout-switcher",qe),t=this.state.body.state.body,n=(e,n)=>{e.layout!==(null==n?void 0:n.layout)&&t.setState({templateColumns:e.layout===Fe.ROWS?Qn:Wn})};n(e.state),this._subs.add(e.subscribeToState(n))}constructor({index:e,labelName:t,labelValue:n,labelCardinality:a}){const o=`var-metrics-${t}-${n}`;super({index:e,labelName:t,labelValue:n,labelCardinality:a,key:`${t}-${n}`,$variables:new i.SceneVariableSet({variables:[new $e({key:o,name:o,labelMatcher:{key:t,operator:"=",value:n},addLifeCycleEvents:!0})]}),body:new mt({variableName:o,initialPageSize:3,body:new i.SceneCSSGridLayout({children:[],isLazy:!0,templateColumns:Wn,autoRows:Ot,$behaviors:[new i.behaviors.CursorSync({key:"metricCrosshairSync",sync:r.DashboardCursorSync.Crosshair})]}),getLayoutLoading:()=>new i.SceneReactObject({reactNode:u().createElement(l.Spinner,{inline:!0})}),getLayoutEmpty:()=>new i.SceneReactObject({reactNode:u().createElement(Kn._,{title:"",severity:"info"},"No metrics found for the current filters and time range.")}),getLayoutError:e=>new i.SceneReactObject({reactNode:u().createElement(Kn._,{severity:"error",title:"Error while loading metrics!",error:e})}),getLayoutChild:(e,r)=>new i.SceneCSSGridItem({body:new Et({metric:e.value,vizPanelInGridItem:new zn({metric:e.value,panelOptions:{fixedColorIndex:r,headerActions:({metric:e})=>[new Tt({metric:e.name}),new kt({metric:e})]},queryOptions:{labelMatchers:[{key:t,operator:"=",value:n}]}})})})})}),this.addActivationHandler(this.onActivate.bind(this))}}function Zn(e){return{container:(0,o.css)({background:e.colors.background.canvas,margin:e.spacing(1,0,0,0),"& div:focus-within":{boxShadow:"none !important"}}),containerHeader:(0,o.css)({marginBottom:"-36px",paddingBottom:e.spacing(1.5),borderBottom:`1px solid ${e.colors.border.medium}`}),headerButtons:(0,o.css)({position:"relative",top:"3px",marginLeft:"auto",marginRight:"30px",zIndex:100}),selectButton:(0,o.css)({height:"28px"}),collapsableSectionBody:(0,o.css)({padding:e.spacing(1)}),groupName:(0,o.css)({fontSize:"1.3rem",lineHeight:"1.3rem"}),labelValue:(0,o.css)({fontSize:"16px",marginLeft:"8px"}),index:(0,o.css)({fontSize:"12px",color:e.colors.text.secondary,marginLeft:"8px"}),footer:(0,o.css)({marginTop:e.spacing(1),"& button":{height:"40px"}}),variable:(0,o.css)({display:"none"})}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Jn,"Component",({model:e})=>{const[t,n]=(0,c.useState)(!1),r=(0,l.useStyles2)(Zn),{index:a,labelName:o,labelValue:s,labelCardinality:d,$variables:p,body:m}=e.useState(),h=p.state.variables[0],{loading:f,error:b}=h.useState(),g=m.useSizes(),y=!f&&!b&&g.total>0&&g.current<g.total;return u().createElement("div",{className:r.container,"data-testid":`${o}-${s}-metrics-group`},u().createElement("div",{className:r.containerHeader},u().createElement(l.Stack,{direction:"row",alignItems:"center",gap:1},u().createElement("div",{className:r.headerButtons},u().createElement(l.Button,{className:r.selectButton,variant:"secondary",onClick:()=>{var t;const n=i.sceneGraph.lookupVariable(O,e);n.setState({filters:[...n.state.filters,{key:o,operator:"=",value:s}]}),null===(t=i.sceneGraph.lookupVariable(Y,e))||void 0===t||t.changeValueTo(z)},tooltip:`See metrics with ${o}=${s}`,tooltipPlacement:"top"},"Select")))),u().createElement(l.CollapsableSection,{isOpen:!t,onToggle:()=>n(!t),label:u().createElement("div",{className:r.groupName},u().createElement(l.Stack,{direction:"row",alignItems:"center"},u().createElement(xt,null),u().createElement("div",{className:r.labelValue},s),d>1&&u().createElement("div",{className:r.index},"(",a+1,"/",d,")")))},u().createElement("div",{className:r.collapsableSectionBody},u().createElement(l.Stack,{direction:"column",gap:3},u().createElement(m.Component,{model:m}))),y&&u().createElement("div",{className:r.footer},u().createElement(l.Stack,{direction:"row",justifyContent:"center",alignItems:"center"},u().createElement(ft,{label:"metric",batchSizes:g,onClick:()=>{m.increaseBatchSize()},tooltip:`Show more metrics for ${o}="${s}"`})))),u().createElement("div",{className:r.variable},u().createElement(h.Component,{key:h.state.name,model:h})))});const er="wingmanLabelValues";class tr extends i.QueryVariable{constructor({labelName:e}){super({name:er,datasource:{uid:H.uid},query:`valuesOf(${e})`,isMulti:!1,allowCustomValue:!1,refresh:r.VariableRefresh.onTimeRangeChanged,hide:r.VariableHide.hideVariable,value:"$__all",includeAll:!0})}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(tr,"Component",()=>u().createElement(u().Fragment,null));class nr extends i.SceneObjectBase{constructor({labelName:e}){super({key:"metrics-group-list",labelName:e,$variables:new i.SceneVariableSet({variables:[new tr({labelName:e})]}),body:new mt({variableName:er,initialPageSize:20,pageSizeIncrement:10,body:new i.SceneCSSGridLayout({children:[],isLazy:!0,templateColumns:"1fr",autoRows:"auto",rowGap:1}),getLayoutLoading:()=>new i.SceneReactObject({reactNode:u().createElement(l.Spinner,{inline:!0})}),getLayoutEmpty:()=>new i.SceneReactObject({reactNode:u().createElement(Kn._,{title:"",severity:"info"},'No label values found for label "',e,'".')}),getLayoutError:t=>new i.SceneReactObject({reactNode:u().createElement(Kn._,{severity:"error",title:`Error while loading label "${e}" values!`,error:t})}),getLayoutChild:(t,n,r)=>new i.SceneCSSGridItem({body:new Jn({index:n,labelName:e,labelValue:t.value,labelCardinality:r.length})})})})}}function rr(e){return{footer:(0,o.css)({display:"flex",justifyContent:"center",alignItems:"center",margin:e.spacing(3,0,1,0),"& button":{height:"40px"}}),variable:(0,o.css)({display:"none"})}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(nr,"Component",({model:e})=>{const t=(0,l.useStyles2)(rr),{body:n,$variables:r,labelName:a}=e.useState(),i=r.state.variables[0],{loading:o,error:s}=i.useState(),c=n.useSizes(),d=!o&&!s&&c.total>0&&c.current<c.total;return u().createElement("div",{"data-testid":"metrics-groupby-list"},u().createElement(n.Component,{model:n}),d&&u().createElement("div",{className:t.footer},u().createElement(ft,{label:`"${a}" value`,batchSizes:c,onClick:()=>{n.increaseBatchSize()}})),u().createElement("div",{className:t.variable},u().createElement(i.Component,{key:i.state.name,model:i})))});class ar extends r.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ar,"type","filters-changed");const ir="Non-rules metrics",or="Recording rules";class sr extends r.BusEventWithPayload{}function lr({title:e,description:t}){const n=(0,l.useStyles2)(cr);return u().createElement("h6",{className:n.title},u().createElement("span",null,e),u().createElement(l.Tooltip,{content:t,placement:"top"},u().createElement(l.Icon,{name:"info-circle",size:"sm",className:n.infoIcon})))}function cr(e){return{title:(0,o.css)({fontSize:"15px",fontWeight:e.typography.fontWeightLight,borderBottom:`1px solid ${e.colors.border.weak}`,paddingBottom:e.spacing(.5)}),infoIcon:(0,o.css)({marginLeft:e.spacing(1),cursor:"pointer",color:e.colors.text.secondary,position:"relative",top:"-4px"})}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(sr,"type","section-value-changed");const ur=({label:e,count:t,checked:n,onChange:r})=>{const a=(0,l.useStyles2)(dr);return u().createElement("div",{className:a.checkboxWrapper,title:e},u().createElement(l.Checkbox,{label:e,value:n,onChange:r}),u().createElement("span",{className:a.count},"(",t,")"))};function dr(e){return{checkboxWrapper:(0,o.css)({display:"flex",alignItems:"center",width:"100%","& label *":{fontSize:"14px !important",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}),count:(0,o.css)({color:e.colors.text.secondary,marginLeft:e.spacing(.5),display:"inline-block"})}}function pr({groups:e,selectedGroups:t,onSelectionChange:n}){const r=(0,l.useStyles2)(mr);return u().createElement(u().Fragment,null,u().createElement("div",{className:r.checkboxListHeader},u().createElement("div",null,t.length," selected"),u().createElement(l.Button,{variant:"secondary",fill:"text",onClick:()=>n([]),disabled:!t.length},"clear")),!e.length&&u().createElement("div",{className:r.noResults},"No results."),e.length>0&&u().createElement("ul",{className:r.checkboxList,"data-testid":"checkbox-filters-list"},e.map(e=>u().createElement("li",{key:e.value,className:r.checkboxItem},u().createElement(ur,{label:e.label,count:e.count,checked:t.some(t=>t.value===e.value),onChange:r=>{const a=r.currentTarget.checked?[...t,{label:e.label,value:e.value}]:t.filter(t=>t.value!==e.value);n(a)}})))))}function mr(e){return{checkboxListHeader:(0,o.css)({display:"flex",justifyContent:"space-between",alignItems:"center",color:e.colors.text.secondary,margin:e.spacing(0),padding:e.spacing(0,0,0,1)}),checkboxList:(0,o.css)({height:"100%",margin:0,padding:e.spacing(0,1,1,1),overflowY:"auto","&::-webkit-scrollbar":{"-webkit-appearance":"none",width:"7px"},"&::-webkit-scrollbar-thumb":{borderRadius:"4px",backgroundColor:e.colors.secondary.main,"-webkit-box-shadow":`0 0 1px ${e.colors.secondary.shade}`}}),checkboxItem:(0,o.css)({display:"flex",alignItems:"center",width:"100%",padding:e.spacing(.5,0)}),noResults:(0,o.css)({fontStyle:"italic",padding:e.spacing(0,1,1,1)})}}function hr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fr(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){hr(e,t,n[t])})}return e}function br(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}class gr extends i.SceneObjectBase{getUrlState(){return{[this.state.key]:this.state.selectedGroups.map(e=>e.value).join(",")}}updateFromUrl(e){const t={};"string"==typeof e[this.state.key]&&e[this.state.key]!==this.state.selectedGroups.map(e=>e.value).join(",")&&(t.selectedGroups=e[this.state.key].split(",").map(e=>({label:e,value:e}))),this.setState(t)}onActivate(){const e=i.sceneGraph.lookupVariable(Me,this),t=i.sceneGraph.lookupVariable(Ge,this);this.updateLists(e.state.options),this.updateCounts();const{selectedGroups:n}=this.state;this.setState({loading:t.state.loading,active:n.length>0})}updateLists(e){this.setState({groups:this.state.computeGroups(e),loading:!1})}updateCounts(){var e;const{groups:t,computeGroups:n,type:r}=this.state,a=i.sceneGraph.lookupVariable(Me,this).state.options,o=null===(e=i.sceneGraph.getAncestor(this,ea).state.enginesMap.get(Ge))||void 0===e?void 0:e.filterEngine;if(!o)return void Z.v.warn("MetricsFilterSection: No filter engine found");const s=br(fr({},o.getFilters()),{[r]:[]}),l=it.getFilteredOptions(a,s),c=new Map(n(l).map(e=>[e.label,e.count])),u=t.map(e=>{var t;return br(fr({},e),{count:null!==(t=c.get(e.label))&&void 0!==t?t:0})});this.setState({groups:u,loading:!1})}constructor({key:e,type:t,title:n,description:r,icon:a,computeGroups:o,showHideEmpty:s,showSearch:l,disabled:c,active:u}){super({key:e,type:t,title:n,description:r,icon:a,groups:[],computeGroups:o,selectedGroups:[],loading:!0,showHideEmpty:null==s||s,showSearch:null==l||l,disabled:null!=c&&c,active:null!=u&&u}),hr(this,"_variableDependency",new i.VariableDependencyConfig(this,{variableNames:[Me,Ge],onReferencedVariableValueChanged:e=>{const{name:t,options:n}=e.state;t!==Me?t===Ge&&this.updateCounts():this.updateLists(n)}})),hr(this,"_urlSync",new i.SceneObjectUrlSyncConfig(this,{keys:[this.state.key]})),hr(this,"onSelectionChange",e=>{this.setState({selectedGroups:e,active:e.length>0}),this.publishEvent(new ar({type:this.state.type,filters:e.map(e=>e.value)}),!0),this.publishEvent(new sr({key:this.state.key,values:e.map(e=>e.label)}),!0),"prefixes"===this.state.type?(0,d.z)("sidebar_prefix_filter_applied",{filter_count:e.length}):"suffixes"===this.state.type&&(0,d.z)("sidebar_suffix_filter_applied",{filter_count:e.length}),"filters-rule"===this.state.key&&e.length>0&&e.forEach(e=>{let t;switch(e.label){case ir:t="non_rules_metrics";break;case or:t="recording_rules";break;default:return}(0,d.z)("sidebar_rules_filter_selected",{filter_type:t})})}),this.addActivationHandler(this.onActivate.bind(this))}}function yr(e){return{container:(0,o.css)({display:"flex",flexDirection:"column",gap:e.spacing(1),height:"100%",overflowY:"hidden"}),switchContainer:(0,o.css)({display:"flex",alignItems:"center",justifyContent:"flex-end",gap:e.spacing(1)}),switchLabel:(0,o.css)({fontSize:"12px",color:e.colors.text.primary}),searchInput:(0,o.css)({flexBasis:"32px",flexShrink:0,marginBottom:e.spacing(1),padding:e.spacing(0,.5)})}}hr(gr,"Component",({model:e})=>{const t=(0,l.useStyles2)(yr),{groups:n,selectedGroups:r,loading:a,title:i,description:o,showHideEmpty:s,showSearch:d}=e.useState(),[p,m]=(0,c.useState)(!1),[h,f]=(0,c.useState)(""),b=(0,c.useMemo)(()=>{const e=[];return p&&e.push(e=>e.count>0),e.push(e=>e.label.toLowerCase().includes(h.toLowerCase())),n.filter(t=>e.every(e=>e(t)))},[p,n,h]);return u().createElement("div",{className:t.container},u().createElement(lr,{title:i,description:o}),s&&u().createElement("div",{className:t.switchContainer},u().createElement("span",{className:t.switchLabel},"Hide empty"),u().createElement(l.Switch,{value:p,onChange:e=>m(e.currentTarget.checked)})),d&&u().createElement(l.Input,{className:t.searchInput,prefix:u().createElement(l.Icon,{name:"search"}),placeholder:"Search...",value:h,onChange:e=>f(e.currentTarget.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),f(""))},suffix:u().createElement(l.IconButton,{name:"times",variant:"secondary",tooltip:"Clear search",onClick:()=>f("")})}),a&&u().createElement(l.Spinner,{inline:!0}),!a&&u().createElement(pr,{groups:b,selectedGroups:r,onSelectionChange:e.onSelectionChange}))});function vr(e){const t=new Map;for(const r of e){const e=r.value.split(/[^a-z0-9]/i),a=e.length<=1?r.value:e[0];var n;const i=null!==(n=t.get(a))&&void 0!==n?n:[];i.push(r.value),t.set(a||"<none>",i)}const r=new Map;for(const[e,n]of t)r.set(e,n.length);return Array.from(r.entries()).sort((e,t)=>e[1]!==t[1]?t[1]-e[1]:(0,q._)(e[0],t[0])).map(([e,t])=>({value:e,count:t,label:e}))}function Sr(e){const t=new Map;for(const r of e){const e=r.value.split(/[^a-z0-9]/i),a=e.length<=1?r.value:e[e.length-1];var n;const i=null!==(n=t.get(a))&&void 0!==n?n:[];i.push(r.value),t.set(a||"<none>",i)}const r=new Map;for(const[e,n]of t)r.set(e,n.length);return Array.from(r.entries()).sort((e,t)=>e[1]!==t[1]?t[1]-e[1]:(0,q._)(e[0],t[0])).map(([e,t])=>({value:e,count:t,label:e}))}function wr(e){return/^\w*:.*?(?::\w+)?$/.test(e)}function Or(e){const t=new Map([["metrics",[]],["rules",[]]]);for(const r of e){const{value:e}=r,a=wr(e)?"rules":"metrics";var n;const i=null!==(n=t.get(a))&&void 0!==n?n:[];i.push(e),t.set(a,i)}return[{value:"^(?!.*:.*)",label:ir,count:t.get("metrics").length},{value:":",label:or,count:t.get("rules").length}]}class Er extends i.DataSourceVariable{onActivate(){this.setState({skipUrlSync:!1}),this.subscribeToState((e,t)=>{e.value&&e.value!==t.value&&te.x.setItem(ee.V.DATASOURCE,e.value)})}static getCurrentDataSource(){const e=Object.values(a.config.datasources).filter(e=>(0,S.aQ)(e)),t=new URL(window.location.href).searchParams.get(`var-${C}`),n=te.x.getItem(ee.V.DATASOURCE),r=e.find(e=>e.uid===t)||e.find(e=>e.uid===n)||e.find(e=>e.isDefault)||e[0];return r?r.uid:(Z.v.warn("Cannot find any Prometheus data source!"),"no-data-source-configured")}constructor({initialDS:e}){super({key:C,name:C,pluginId:"prometheus",label:"Data source",description:"Only prometheus data sources are supported",skipUrlSync:!e,value:e||Er.getCurrentDataSource()}),this.addActivationHandler(this.onActivate.bind(this))}}function xr(e){return JSON.stringify(function(e){return delete e.actionView,delete e.layout,delete e.refresh,Array.isArray(e["var-filters"])&&(e["var-filters"]=e["var-filters"].filter(Boolean)),e}(e))}function Cr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Pr(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Cr(e,t,n[t])})}return e}function kr(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}const jr=(e,t,n)=>e.length+2+t.length>n?t.substring(0,n-e.length-5)+"...":t;function _r(e){const t=(0,l.useStyles2)(Tr),{onSelect:n,onDelete:a,bookmark:i}=e,{createdAt:o,urlValues:s}=i,c=s.metric||"?",d=(e=>{const t=e[`var-${O}`];return t.length?t.map(e=>e.split("|")):[]})(s),p=jr("",hs(c),27),m=`${e.compactHeight&&d.length>0?t.cardTall:""}`,h=`${t.card} ${e.wide?t.cardWide:""} ${m}`;return u().createElement("article",{"data-testid":`data-trail-card ${c}`},u().createElement(l.Card,{onClick:n,className:h},u().createElement(l.Card.Heading,null,u().createElement("div",{className:t.metricValue},p)),u().createElement(l.Card.Meta,{className:t.meta},d.map(([e,n,r],a)=>u().createElement("div",{key:a,className:t.filter},u().createElement(l.Text,{variant:"bodySmall",color:"secondary"},e," ",n),u().createElement(l.Text,{variant:"bodySmall",color:"primary",weight:"medium"}," ",jr(e,r,44))))),u().createElement("div",{className:t.deleteButton},u().createElement(l.Card.SecondaryActions,null,u().createElement(l.IconButton,{key:"delete",name:"trash-alt",className:t.secondary,tooltip:"Remove bookmark",tooltipPlacement:"top",onClick:a})))),u().createElement("div",{className:t.date},u().createElement(l.Text,{variant:"bodySmall",color:"secondary"},"Date created:"," "),u().createElement(l.Text,{variant:"bodySmall",color:"primary",weight:"medium"},o>0&&(0,r.dateTimeFormat)(o,{format:"YYYY-MM-DD"}))))}function Tr(e){return{metricValue:(0,o.css)({display:"inline",color:e.colors.text.primary,fontWeight:500,wordBreak:"break-all"}),card:(0,o.css)({position:"relative",width:"318px",padding:`12px ${e.spacing(2)} ${e.spacing(1)} ${e.spacing(2)}`,alignItems:"start",marginBottom:0,borderTop:`1px solid ${e.colors.border.weak}`,borderRight:`1px solid ${e.colors.border.weak}`,borderLeft:`1px solid ${e.colors.border.weak}`,borderBottom:"none",borderRadius:"2px 2px 0 0"}),cardWide:(0,o.css)({width:"100%"}),cardTall:(0,o.css)({height:"110px"}),secondary:(0,o.css)({color:e.colors.text.secondary,fontSize:"12px"}),date:(0,o.css)({border:`1px solid ${e.colors.border.weak}`,borderRadius:"0 0 2px 2px",padding:`${e.spacing(1)} ${e.spacing(2)}`,backgroundColor:e.colors.background.primary}),meta:(0,o.css)({flexWrap:"wrap",overflow:"hidden",textOverflow:"ellipsis",maxHeight:"36px",margin:0,gridArea:"Meta",color:e.colors.text.secondary,whiteSpace:"nowrap"}),filter:(0,o.css)({overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),deleteButton:(0,o.css)({position:"absolute",bottom:e.spacing(1.5),right:e.spacing(.5)})}}class Ir extends i.SceneObjectBase{constructor({key:e,title:t,description:n,icon:r,disabled:a}){super({key:e,title:t,description:n,icon:r,disabled:null!=a&&a,active:!1})}}function Dr(e){return{bookmarksList:(0,o.css)({overflowY:"auto",paddingRight:e.spacing(1)}),emptyState:(0,o.css)({height:"100px"})}}function Ar({labels:e,selectedLabel:t,onSelectLabel:n,onClearSelection:r}){const a=(0,l.useStyles2)(Lr);return u().createElement(u().Fragment,null,u().createElement("div",{className:a.listHeader},u().createElement("div",{className:a.selected},t===z?"No selection":`Selected: "${t}"`),u().createElement(l.Button,{variant:"secondary",fill:"text",onClick:r,disabled:t===z},"clear")),!e.length&&u().createElement("div",{className:a.noResults},"No results."),e.length>0&&u().createElement("div",{className:a.list,"data-testid":"labels-list"},u().createElement(l.RadioButtonList,{name:"labels-list",options:e,onChange:n,value:t})))}function Lr(e){return{listHeader:(0,o.css)({display:"flex",justifyContent:"space-between",alignItems:"center",color:e.colors.text.secondary,margin:e.spacing(0),padding:e.spacing(0,0,0,1)}),selected:(0,o.css)({overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"}),list:(0,o.css)({display:"flex",flex:1,flexDirection:"column",gap:0,overflowY:"auto",'& [role="radiogroup"]':{gap:0},"& label":{cursor:"pointer",padding:e.spacing(.5,1),"&:hover":{background:e.colors.background.secondary}},"& label div":{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}),noResults:(0,o.css)({fontStyle:"italic",padding:e.spacing(0,1,1,1)})}}function Br(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ir,"Component",({model:e})=>{const t=(0,l.useStyles2)(Dr),{title:n,description:r}=e.useState(),{bookmarks:a,gotoBookmark:o,removeBookmark:s}=function(e){const[t,n]=(0,c.useState)({}),r=ds(e);(0,c.useEffect)(()=>{const e=te.x.getItem(ee.V.BOOKMARKS)||[],t={};for(const n of e){const e=xr(n.urlValues);t[e]=kr(Pr({},n),{key:e})}n(t)},[]);const{value:a}=i.sceneGraph.findByKeyAndType(r,C,Er).useState();return{bookmarks:(0,c.useMemo)(()=>Object.values(t).filter(e=>e.urlValues[`var-${C}`]===a),[t,a]),addBookmark:()=>{const e={urlValues:i.sceneUtils.getUrlState(r),createdAt:Date.now()},a=Object.values(t).map(e=>kr(Pr({},e),{key:void 0}));te.x.setItem(ee.V.BOOKMARKS,[...a,e]);const o=xr(e.urlValues);n(kr(Pr({},t),{[o]:kr(Pr({},e),{key:o})}))},removeBookmark:e=>{delete t[e];const r=Object.values(t).map(e=>kr(Pr({},e),{key:void 0}));te.x.setItem(ee.V.BOOKMARKS,r),n(Pr({},t))},gotoBookmark:e=>{const n=t[e];if(!n){const e=new Error("Bookmark not found!");return void(0,v.jx)(e,[e.toString()])}r.publishEvent(new I({metric:n.urlValues.metric,urlValues:n.urlValues}),!0)}}}(e);return u().createElement(l.Stack,{direction:"column",gap:1,height:"100%"},u().createElement(lr,{title:n,description:r,"data-testid":"bookmarks-list-sidebar"}),a.length>0?u().createElement("div",{className:t.bookmarksList},u().createElement(l.Stack,{direction:"column",gap:1.5},a.map(e=>u().createElement(_r,{key:e.key,bookmark:e,onSelect:()=>{return t=e.key,(0,d.z)("exploration_started",{cause:"bookmark_clicked"}),void o(t);var t},onDelete:()=>{return t=e.key,(0,d.z)("bookmark_changed",{action:"deleted"}),void s(t);var t},wide:!0,compactHeight:!0})))):u().createElement("div",{className:t.emptyState},u().createElement(l.Stack,{direction:"column",alignItems:"center"},u().createElement(l.Text,{color:"secondary",italic:!0},"No bookmarks yet for the"),u().createElement(l.Text,{color:"secondary",italic:!0},"current data source."))))});class Nr extends i.SceneObjectBase{selectLabel(e){i.sceneGraph.lookupVariable(this.state.variableName,this).changeValueTo(e);const t=Boolean(e&&e!==z);this.setState({active:t})}constructor({key:e,variableName:t,title:n,description:r,icon:a,disabled:o,active:s}){super({key:e,variableName:t,title:n,description:r,icon:a,disabled:null!=o&&o,active:null!=s&&s}),Br(this,"onSelectLabel",e=>{(0,d.z)("sidebar_group_by_label_filter_applied",{label:e}),this.selectLabel(e)}),Br(this,"onClearSelection",()=>{this.selectLabel(z)}),Br(this,"useLabelsBrowser",()=>{const{variableName:e,title:t,description:n}=this.useState(),r=i.sceneGraph.lookupVariable(e,this),{loading:a,options:o,value:s}=r.useState(),[l,u]=(0,c.useState)("");return{title:t,description:n,loading:a,selectedLabel:s,labelsList:(0,c.useMemo)(()=>{const e=[e=>e!==z,e=>e.toLowerCase().includes(l.toLowerCase())];return o.filter(t=>e.every(e=>e(t.value)))},[o,l]),searchValue:l,onInputChange:e=>{u(e.currentTarget.value)},onInputKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),u(""))},onInputClear:()=>{u("")}}})}}function Rr(e){return{container:(0,o.css)({display:"flex",flexDirection:"column",gap:e.spacing(1),height:"100%",overflowY:"hidden"}),search:(0,o.css)({marginBottom:e.spacing(1),padding:e.spacing(0,.5)})}}function Mr(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function $r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Br(Nr,"Component",({model:e})=>{const t=(0,l.useStyles2)(Rr),{title:n,description:r,loading:a,labelsList:i,selectedLabel:o,searchValue:s,onInputChange:c,onInputKeyDown:d,onInputClear:p}=e.useLabelsBrowser();return u().createElement("div",{className:t.container,"data-testid":"labels-browser"},u().createElement(lr,{title:n,description:r}),u().createElement(l.Input,{className:t.search,prefix:u().createElement(l.Icon,{name:"search"}),placeholder:"Search...",value:s,onChange:c,onKeyDown:d,suffix:u().createElement(l.IconButton,{name:"times",variant:"secondary",tooltip:"Clear search",onClick:p})}),a&&u().createElement(l.Spinner,{inline:!0}),!a&&u().createElement(Ar,{labels:i,selectedLabel:o,onSelectLabel:e.onSelectLabel,onClearSelection:e.onClearSelection}))});const Vr=[{value:"all",label:"All time"},...["1m","3m","5m","15m","30m","1h","3h","6h","12h","24h"].map(e=>({value:e,label:`Past ${e}`}))];class Fr extends i.SceneObjectBase{getUrlState(){const e="all"===this.state.currentInterval?"":this.state.currentInterval;return{[this.state.key]:e}}updateFromUrl(e){const t=e[this.state.key]||"all";t!==this.state.currentInterval&&Vr.some(e=>e.value===t)&&this.setState({currentInterval:t})}onActivate(){this.subscribeToState((e,t)=>{return(n=function*(){e.currentInterval!==t.currentInterval&&(this.setState({active:Boolean("all"!==e.currentInterval)}),this.publishEvent(new sr({key:this.state.key,values:"all"!==e.currentInterval?[e.currentInterval]:[]}),!0))},function(){var e=this,t=arguments;return new Promise(function(r,a){var i=n.apply(e,t);function o(e){Mr(i,r,a,o,s,"next",e)}function s(e){Mr(i,r,a,o,s,"throw",e)}o(void 0)})}).call(this);var n})}update(e){this.setState({currentInterval:e});const t=[...i.sceneGraph.findAllObjects(i.sceneGraph.getAncestor(this,ea),e=>e instanceof $e),i.sceneGraph.findByKeyAndType(this,Me,$e)];"all"===e?t.forEach(e=>e.fetchAllMetrics()):t.forEach(t=>t.fetchRecentMetrics(e))}constructor({key:e,title:t,description:n,icon:r,active:a,disabled:o}){super({key:e,title:t,description:n,icon:r,active:null!=a&&a,disabled:null!=o&&o,intervalOptions:Vr,currentInterval:"all"}),$r(this,"_urlSync",new i.SceneObjectUrlSyncConfig(this,{keys:[this.state.key]})),$r(this,"onChangeInterval",e=>{(0,d.z)("sidebar_recent_filter_selected",{interval:e}),this.update(e)}),this.addActivationHandler(this.onActivate.bind(this))}}function qr(e){return{container:(0,o.css)({display:"flex",flexDirection:"column",gap:e.spacing(1),height:"100%",overflowY:"hidden"}),list:(0,o.css)({height:"100%",margin:0,padding:e.spacing(0,1,1,1),overflowY:"auto"})}}$r(Fr,"Component",({model:e})=>{const t=(0,l.useStyles2)(qr),{title:n,description:r,intervalOptions:a,currentInterval:i}=e.useState();return u().createElement("div",{className:t.container,"data-testid":"new-metrics"},u().createElement(lr,{title:n,description:r}),u().createElement("div",{className:t.list},u().createElement(l.RadioButtonList,{name:"offsets",value:i,options:a,onChange:e.onChangeInterval})))});class Gr extends i.SceneObjectBase{onActivate(){}constructor({key:e,title:t,description:n,icon:r,disabled:a}){super({key:e,title:t,description:n,icon:r,disabled:null!=a&&a,active:!1}),this.addActivationHandler(this.onActivate.bind(this))}}function Ur(e){return{container:(0,o.css)({display:"flex",flexDirection:"column",gap:e.spacing(1),height:"100%",overflowY:"hidden"})}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Gr,"Component",({model:e})=>{const t=(0,l.useStyles2)(Ur),{title:n,description:r}=e.useState();return u().createElement("div",{className:t.container},u().createElement(lr,{title:n,description:r}))});const zr=new Map([["rules",function(){return u().createElement("svg",{stroke:"currentColor",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none"},u().createElement("rect",{x:"1.25",y:"1.625",width:"5.25",height:"5.25",rx:"1",strokeWidth:"1.5"}),u().createElement("circle",{cx:"12.25",cy:"4.25",r:"2.75",strokeWidth:"1.5"}),u().createElement("circle",{cx:"3.75",cy:"11.75",r:"2.75",strokeWidth:"1.5"}),u().createElement("rect",{x:"9.5",y:"9.125",width:"5.25",height:"5.25",rx:"1",strokeWidth:"1.5"}))}],["groups",xt]]);function Hr({ariaLabel:e,disabled:t,visible:n,active:a,tooltip:i,iconOrText:s,onClick:c}){const d=(0,l.useStyles2)(Kr);let p,m;return s in r.availableIconsIndex?p=s:m=zr.has(s)?zr.get(s):function(){return u().createElement(u().Fragment,null,s)},u().createElement(l.Button,{className:(0,o.cx)(d.button,t&&"disabled",n&&"visible",a&&"active"),size:"md",variant:"secondary",fill:"text",icon:p,"aria-label":e,tooltip:i,tooltipPlacement:"right",onClick:c,disabled:t},m&&u().createElement(m,null))}function Kr(e){return{button:(0,o.css)({margin:0,color:e.colors.text.secondary,"&:hover":{color:e.colors.text.maxContrast,background:"transparent"},"&.disabled":{opacity:.5},"&.disabled:hover":{color:e.colors.text.secondary},"&.visible":{color:e.colors.text.maxContrast},"&.active":{color:e.colors.text.maxContrast}})}}var Wr=n(3179);function Qr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const Yr=["filters-rule","filters-prefix","filters-suffix","filters-recent"];class Xr extends i.SceneObjectBase{onActivate(){var e;const t=this.initOtherMetricsVar();return this.subscribeToEvent(sr,e=>{const{key:t,values:n}=e.payload,{sectionValues:r}=this.state,a=new Map(r).set(t,n);this.setOtherMetricFilters(a),this.setState({sectionValues:a})}),!(null===(e=this.state.visibleSection)||void 0===e?void 0:e.state.key)&&(0,Wr.A)(Wr.j.sidebarOpenByDefault)&&this.setActiveSection(te.x.getItem(ee.V.SIDEBAR_SECTION)||"filters-prefix"),()=>{t()}}setOtherMetricFilters(e){const t=i.sceneGraph.lookupVariable(j,this);if(!$(t))return;const n={"filters-rule":"rule group","filters-prefix":"prefix","filters-suffix":"suffix","filters-recent":"recent"},a=Array.from(e.entries()).reduce((e,[t,r])=>(r.length&&Yr.includes(t)&&e.push({key:t,operator:"=",value:r.join(", "),keyLabel:n[t]}),e),[]);t.setState({filters:a,hide:a.length?r.VariableHide.hideLabel:r.VariableHide.hideVariable})}initOtherMetricsVar(){const e=ds(this).state.$variables;if(!e)return()=>{};const t=new i.AdHocFiltersVariable({name:j,readOnly:!0,skipUrlSync:!0,datasource:null,hide:r.VariableHide.hideVariable,layout:"combobox",applyMode:"manual",allowCustomValue:!0});return e.setState({variables:[...e.state.variables,t]}),this.setOtherMetricFilters(this.state.sectionValues),()=>{e.setState({variables:[...e.state.variables.filter(e=>e!==t)]})}}static getSectionValuesFromUrl(){const e=new URLSearchParams(window.location.search),t=new Map;for(const n of Yr){const r=e.get(n);t.set(n,r?r.split(",").map(e=>e.trim()):[])}return t}setActiveSection(e){const{visibleSection:t,sections:n}=this.state;if(!e||e===(null==t?void 0:t.state.key))return(0,d.z)("metrics_sidebar_toggled",{action:"closed",section:null==t?void 0:t.state.key}),void this.setState({visibleSection:null});var r;te.x.setItem(ee.V.SIDEBAR_SECTION,e),(0,d.z)("metrics_sidebar_toggled",{action:"opened",section:e}),"filters-prefix"===e?(0,d.z)("sidebar_prefix_filter_section_clicked",{}):"filters-suffix"===e?(0,d.z)("sidebar_suffix_filter_section_clicked",{}):"filters-recent"===e&&(0,d.z)("sidebar_recent_filter_section_clicked",{}),this.setState({visibleSection:null!==(r=n.find(t=>t.state.key===e))&&void 0!==r?r:null})}constructor(e){var t,n,r,a;const i=Xr.getSectionValuesFromUrl();super(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Qr(e,t,n[t])})}return e}({key:"sidebar",visibleSection:null,sections:[new gr({key:"filters-rule",type:"categories",title:"Rules filters",description:"Filter metrics and recording rules",icon:"rules",computeGroups:Or,showHideEmpty:!1,showSearch:!1,active:Boolean(null===(t=i.get("filters-rule"))||void 0===t?void 0:t.length)}),new gr({key:"filters-prefix",type:"prefixes",title:"Prefix filters",description:"Filter metrics based on their name prefix (Prometheus namespace)",icon:"A_",computeGroups:vr,active:Boolean(null===(n=i.get("filters-prefix"))||void 0===n?void 0:n.length)}),new gr({key:"filters-suffix",type:"suffixes",title:"Suffix filters",description:"Filter metrics based on their name suffix",icon:"_Z",computeGroups:Sr,active:Boolean(null===(r=i.get("filters-suffix"))||void 0===r?void 0:r.length)}),new Fr({key:"filters-recent",title:"Recent metrics filters",description:"Filter metrics based on when they started being ingested",icon:"clock-nine",active:Boolean(null===(a=i.get("filters-recent"))||void 0===a?void 0:a.length)}),new Nr({key:"groupby-labels",variableName:Y,title:"Group by labels",description:"Group metrics by their label values",icon:"groups"}),new Ir({key:"bookmarks",title:"Bookmarks",description:"Access your saved metrics for quick reference",icon:"star"}),new Gr({key:"settings",title:"Settings",description:"Settings",icon:"cog",disabled:!0})],sectionValues:i},e)),i.set("filters-rule",[]),this.addActivationHandler(this.onActivate.bind(this))}}function Jr(e){return{container:(0,o.css)({position:"relative",display:"flex",flexDirection:"row",height:"100%",overflow:"hidden"}),buttonsBar:(0,o.css)({display:"flex",flexDirection:"column",alignItems:"center",gap:0,width:"42px",padding:0,margin:0,boxSizing:"border-box",border:`1px solid ${e.colors.border.weak}`,borderRadius:e.shape.radius.default,backgroundColor:e.colors.background.primary,borderTopLeftRadius:0,borderBottomLeftRadius:0,position:"relative"}),buttonContainer:(0,o.css)({marginTop:e.spacing(1),"&::before":{transition:"0.5s ease",content:'""',position:"absolute",left:0,height:"32px",borderLeft:`2px solid ${e.colors.action.selectedBorder}`,boxSizing:"border-box",opacity:0,visibility:"hidden"},"&:hover::before":{opacity:1,visibility:"visible"},"&.visible::before":{opacity:1,visibility:"visible"},"&.disabled::before":{opacity:0,visibility:"hidden"},"&.active::after":{content:'""',position:"absolute",right:0,width:"8px",height:"8px",backgroundColor:e.colors.action.selectedBorder,borderRadius:"50%",margin:"2px 4px 0 0"}}),content:(0,o.css)({width:"calc(300px - 42px)",boxSizing:"border-box",border:`1px solid ${e.colors.border.weak}`,borderLeft:"none",borderRadius:e.shape.radius.default,backgroundColor:e.colors.background.canvas,padding:e.spacing(1.5)}),closeButton:(0,o.css)({position:"absolute",top:e.spacing(1.5),right:e.spacing(1),margin:0})}}function Zr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Qr(Xr,"Component",({model:e})=>{const t=(0,l.useStyles2)(Jr),{sections:n,visibleSection:r,sectionValues:a}=e.useState(),s=i.sceneGraph.findByKeyAndType(e,Y,X).useState().value;return u().createElement("div",{className:t.container},u().createElement("div",{className:t.buttonsBar,"data-testid":"sidebar-buttons"},n.map(n=>{const{key:i,title:l,icon:c,disabled:d,active:p}=n.state,m=(null==r?void 0:r.state.key)===i;let h,f;var b,g;"groupby-labels"===i?(h=Boolean(s&&s!==z),f=`${l}: ${s}`):(h=p,f=(null===(b=a.get(i))||void 0===b?void 0:b.length)?`${l}: ${null===(g=a.get(i))||void 0===g?void 0:g.join(", ")}`:l);return u().createElement("div",{key:i,className:(0,o.cx)(t.buttonContainer,m&&"visible",h&&"active",d&&"disabled")},u().createElement(Hr,{key:i,ariaLabel:l,disabled:d,visible:m,active:h,tooltip:f,onClick:()=>e.setActiveSection(i),iconOrText:c}))})),r&&u().createElement("div",{className:t.content,"data-testid":"sidebar-content"},u().createElement(l.IconButton,{className:t.closeButton,name:"times","aria-label":"Close",tooltip:"Close",tooltipPlacement:"top",onClick:()=>e.setActiveSection("")}),r instanceof gr&&u().createElement(r.Component,{model:r}),r instanceof Fr&&u().createElement(r.Component,{model:r}),r instanceof Nr&&u().createElement(r.Component,{model:r}),r instanceof Ir&&u().createElement(r.Component,{model:r}),r instanceof Gr&&u().createElement(r.Component,{model:r})))});class ea extends i.SceneObjectBase{onActivate(){const e=i.sceneGraph.lookupVariable(Y,this).state.value;this.updateBasedOnGroupBy(e),this.subscribeToEvents()}updateBasedOnGroupBy(e){const t=Boolean(e&&e!==z);i.sceneGraph.findByKeyAndType(this,"quick-search",Ze).toggleCountsDisplay(!t),!t&&this.state.body instanceof Yn||t&&this.state.body instanceof nr&&this.state.body.state.labelName===e||this.setState({body:t?new nr({labelName:e}):new Yn({variableName:Ge})})}subscribeToEvents(){this.initVariablesFilteringAndSorting()}initVariablesFilteringAndSorting(){this.subscribeToEvent(Ae,e=>{const{key:t}=e.payload,n=i.sceneGraph.findByKey(this,t);this.state.enginesMap.set(t,{filterEngine:new it(n),sortEngine:new pt(n)})}),this.subscribeToEvent(Le,e=>{this.state.enginesMap.delete(e.payload.key)});const e=i.sceneGraph.findByKeyAndType(this,"quick-search",Ze),t=i.sceneGraph.findAllObjects(this,e=>e instanceof gr),n=i.sceneGraph.findByKeyAndType(this,"metrics-sorter",_e).state.$variables.getByName(je);this.subscribeToEvent(Be,r=>{const{key:a,options:i}=r.payload,{filterEngine:o,sortEngine:s}=this.state.enginesMap.get(a);o.setInitOptions(i);const l={names:e.state.value?[e.state.value]:[]};for(const e of t)l[e.state.type]=e.state.selectedGroups.map(e=>e.value);o.applyFilters(l,{forceUpdate:!0,notify:!1}),s.sort(n.state.value)}),this.subscribeToEvent(Xe,e=>{const{searchText:t}=e.payload;for(const[,{filterEngine:e,sortEngine:r}]of this.state.enginesMap)e.applyFilters({names:t?[t]:[]}),r.sort(n.state.value)}),this.subscribeToEvent(ar,e=>{const{type:t,filters:r}=e.payload;for(const[,{filterEngine:e,sortEngine:a}]of this.state.enginesMap)e.applyFilters({[t]:r}),a.sort(n.state.value)}),this.subscribeToEvent(ne,e=>{const{sortBy:t}=e.payload;(0,d.z)("sorting_changed",{from:"metrics-reducer",sortBy:t});for(const[,{sortEngine:e}]of this.state.enginesMap)e.sort(t)})}constructor(){super({$variables:new i.SceneVariableSet({variables:[new Ue]}),listControls:new rt({}),sidebar:new Xr({}),body:void 0,enginesMap:new Map}),Zr(this,"_variableDependency",new i.VariableDependencyConfig(this,{variableNames:[Y],onReferencedVariableValueChanged:e=>{this.updateBasedOnGroupBy(e.state.value)}})),this.addActivationHandler(this.onActivate.bind(this))}}Zr(ea,"Component",({model:e})=>{var t;const n=null!==(t=(0,a.useChromeHeaderHeight)())&&void 0!==t?t:0,r=(0,l.useStyles2)(na),{$variables:i,body:o,listControls:s,sidebar:c}=e.useState();return u().createElement(u().Fragment,null,u().createElement("div",{className:r.listControls,"data-testid":"list-controls"},u().createElement(s.Component,{model:s})),u().createElement(l.Stack,{direction:"row",gap:1,height:`calc(100vh - ${n+ta}px)`},u().createElement("div",{className:r.sidebar,"data-testid":"sidebar"},u().createElement(c.Component,{model:c})),u().createElement("div",{className:r.list},o&&u().createElement(o.Component,{model:o}))),u().createElement("div",{className:r.variables},null==i?void 0:i.state.variables.map(e=>u().createElement(e.Component,{key:e.state.name,model:e}))))});const ta=144;function na(e){return{listControls:(0,o.css)({marginBottom:e.spacing(1.5)}),list:(0,o.css)({width:"100%",overflowY:"auto"}),sidebar:(0,o.css)({flex:"0 0 auto",overflowY:"auto"}),variables:(0,o.css)({display:"none"})}}const ra={[Dt.TIMESERIES_AGE_TIME_MINUS_AVG]:{id:Dt.TIMESERIES_AGE_TIME_MINUS_AVG,name:"Average age",panelOptions:{type:"timeseries",description:'Suitable only for metrics that store unix timestamps (usually containing "timestamp_seconds" in their name) to calculate an average age. Calculates the age by subtracting the average timestamp value from current time.'},queryOptions:{queries:[{fn:"time-avg(metric)"}]}},[Dt.TIMESERIES_AGE_TIME_MINUS_MIN_MAX]:{id:Dt.TIMESERIES_AGE_TIME_MINUS_MIN_MAX,name:"Minimum and maximum ages",panelOptions:{type:"timeseries",description:'Suitable only for metrics that store unix timestamps (usually containing "timestamp_seconds" in their name) to calculate a minimum and a maximum age. Calculates the ages by subtracting the min and the max timestamp values from current time.'},queryOptions:{queries:[{fn:"time-min(metric)"},{fn:"time-max(metric)"}]}}},aa={[Dt.HISTOGRAM_HEATMAP]:{id:Dt.HISTOGRAM_HEATMAP,name:"Heatmap (default)",panelOptions:{type:"heatmap",description:"Visualizes the full distribution of histogram data over time using color intensity. Perfect for spotting patterns, identifying performance degradation, and understanding latency distribution changes. Shows density of values across different buckets."},queryOptions:{queries:[]}},[Dt.HISTOGRAM_PERCENTILES]:{id:Dt.HISTOGRAM_PERCENTILES,name:"Percentiles",panelOptions:{type:"percentiles",description:"Extracts specific percentile values from histogram data. Essential for SLA monitoring and performance analysis, showing how response times or other metrics behave for different user experience tiers."},queryOptions:{queries:[{fn:"histogram_quantile",params:{percentiles:[99,90,50]}}]}}},ia={[Dt.TIMESERIES_COUNT]:{id:Dt.TIMESERIES_COUNT,name:"Count",panelOptions:{type:"timeseries",description:"Counts how many time series emit this info metric. Useful for validating presence of instances and tracking metadata changes (e.g. version rollouts). Combine with a group by label (such as version or instance) to see the breakdown."},queryOptions:{queries:[{fn:"count"}]}}},oa={[Dt.STATUS_UPDOWN_HISTORY]:{id:Dt.STATUS_UPDOWN_HISTORY,name:"Status History (default)",panelOptions:{type:"statushistory",description:"Displays binary status changes over time as colored bars (green=up, red=down). Perfect for monitoring service availability, health checks, or any binary state metrics. Shows patterns in uptime/downtime and helps identify recurring issues."},queryOptions:{queries:[{fn:"min"}]}},[Dt.STATUS_UPDOWN_STAT]:{id:Dt.STATUS_UPDOWN_STAT,name:"Stat with latest value",panelOptions:{type:"stat",description:'Shows the current status as a single value display with color coding (green=up, red=down). Ideal for dashboards where you need an at-a-glance view of service health or binary state. Uses minimum value to ensure any "down" status is highlighted.'},queryOptions:{queries:[{fn:"min"}]}}};function sa(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function la(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){sa(e,t,n[t])})}return e}function ca(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}const ua={[Dt.TIMESERIES_AVG]:{id:Dt.TIMESERIES_AVG,name:"Average (default)",panelOptions:{type:"timeseries",description:"Shows the average value across all time series. Ideal for understanding typical behavior and smoothing out variations between different targets. For rate queries, displays average throughput per target."},queryOptions:{queries:[{fn:"avg"}]}},[Dt.TIMESERIES_SUM]:{id:Dt.TIMESERIES_SUM,name:"Sum",panelOptions:{type:"timeseries",description:"Aggregates total values across all time series. Perfect for measuring overall system throughput, total resource consumption, or fleet-wide capacity. Essential for rate queries showing total request rates."},queryOptions:{queries:[{fn:"sum"}]}},[Dt.TIMESERIES_STDDEV]:{id:Dt.TIMESERIES_STDDEV,name:"Standard deviation",panelOptions:{type:"timeseries",description:"Measures variability and consistency across time series. High values indicate uneven load distribution or inconsistent behavior. Useful for detecting load balancing issues or identifying when some targets behave differently."},queryOptions:{queries:[{fn:"stddev"}]}},[Dt.TIMESERIES_PERCENTILES]:{id:Dt.TIMESERIES_PERCENTILES,name:"Percentiles",panelOptions:{type:"percentiles",description:"Displays percentiles to show value distribution. Excellent for SLA monitoring and understanding outlier behavior without being skewed by extreme values. Critical for performance analysis."},queryOptions:{queries:[{fn:"quantile",params:{percentiles:[99,90,50]}}]}},[Dt.TIMESERIES_MIN_MAX]:{id:Dt.TIMESERIES_MIN_MAX,name:"Minimum and maximum",panelOptions:{type:"timeseries",description:"Shows the range between lowest and highest values across time series. Useful for capacity planning, identifying idle resources (min), and spotting overloaded targets (max). Helps detect outliers and resource utilization patterns."},queryOptions:{queries:[{fn:"min"},{fn:"max"}]}}},da={[Dt.TIMESERIES_SUM]:ca(la({},ua[Dt.TIMESERIES_SUM]),{name:"Sum (default)",id:Dt.TIMESERIES_SUM}),[Dt.TIMESERIES_AVG]:ca(la({},ua[Dt.TIMESERIES_AVG]),{name:"Average"}),[Dt.TIMESERIES_STDDEV]:ua[Dt.TIMESERIES_STDDEV],[Dt.TIMESERIES_PERCENTILES]:ua[Dt.TIMESERIES_PERCENTILES],[Dt.TIMESERIES_MIN_MAX]:ua[Dt.TIMESERIES_MIN_MAX]};function pa(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function ma(e,t){return(n=function*(){switch(yield Ut(e,t)){case"counter":return Object.values(da);case"classic-histogram":case"native-histogram":return Object.values(aa);case"age":return[Object.values(ua)[0],...Object.values(ra)];case"status-updown":return Object.values(oa);case"info":return Object.values(ia);default:return Object.values(ua)}},function(){var e=this,t=arguments;return new Promise(function(r,a){var i=n.apply(e,t);function o(e){pa(i,r,a,o,s,"next",e)}function s(e){pa(i,r,a,o,s,"throw",e)}o(void 0)})})();var n}class ha extends r.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ha,"type","apply-panel-config");class fa extends r.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(fa,"type","cancel-configure-panel");const ba=[{value:99,label:"P99"},{value:95,label:"P95"},{value:90,label:"P90"},{value:75,label:"P75"},{value:50,label:"P50"}];function ga(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ya(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}class va extends i.SceneObjectBase{onActivate(){this.initPercentilesParams()}initPercentilesParams(){var e,t,n;const r=this.state.body.state.queryConfig,a=new Set((null===(n=r.queries)||void 0===n||null===(t=n.find(e=>{var t;return null===(t=e.params)||void 0===t?void 0:t.percentiles}))||void 0===t||null===(e=t.params)||void 0===e?void 0:e.percentiles)||[]),i=a.size>0?ba.map(e=>ya(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){ga(e,t,n[t])})}return e}({},e),{checked:a.has(e.value)})):[];this.setState({queryParams:{show:i.length>0,options:i}})}constructor({body:e,presetId:t,isSelected:n,onSelect:r}){super({presetId:t,body:e,isSelected:n,onSelect:r,queryParams:{show:!1,options:[]}}),ga(this,"onTogglePercentile",e=>{var t;const{queryParams:n,body:r}=this.state,a=Number(e.target.value),i=n.options.find(e=>e.value===a);if(!i)return;i.checked=!i.checked;const o=n.options.filter(e=>e.checked);if(!o.length)return;const s=(0,ze.cloneDeep)(r.state.queryConfig);null===(t=s.queries)||void 0===t||t.some(e=>{var t;return!!(null===(t=e.params)||void 0===t?void 0:t.percentiles)&&(e.params.percentiles=o.map(e=>e.value),!0)}),r.update({},s),this.setState({queryParams:n})}),ga(this,"onClickPreset",()=>{this.state.onSelect(this.state.presetId)}),this.addActivationHandler(this.onActivate.bind(this))}}function Sa(e){return{container:o.css`
|
|
display: flex;
|
|
flex-direction: column;
|
|
gap: ${e.spacing(1)};
|
|
padding: ${e.spacing(1,1,1.25,1)};
|
|
border: 1px solid transparent;
|
|
transition: all 0.2s ease-in-out;
|
|
|
|
&:hover {
|
|
border: 1px solid ${e.colors.border.weak};
|
|
border-color: ${e.colors.primary.border};
|
|
}
|
|
&:focus {
|
|
border: 1px solid ${e.colors.border.weak};
|
|
outline: 1px solid ${e.colors.primary.main};
|
|
outline-offset: 1px;
|
|
}
|
|
`,selected:o.css`
|
|
cursor: default;
|
|
border: 1px solid ${e.colors.border.weak};
|
|
border-color: ${e.colors.primary.border};
|
|
`,bodyAndParams:o.css`
|
|
display: flex;
|
|
flex-direction: row;
|
|
gap: ${e.spacing(1.25)};
|
|
width: 100%;
|
|
`,paramsContainer:o.css`
|
|
margin-top: ${e.spacing(1)};
|
|
`,param:o.css`
|
|
display: flex;
|
|
align-items: center;
|
|
gap: ${e.spacing(.5)};
|
|
margin-bottom: ${e.spacing(.5)};
|
|
font-size: 12px;
|
|
cursor: pointer;
|
|
|
|
& [type='checkbox'] {
|
|
cursor: pointer;
|
|
}
|
|
`,radioContainer:o.css`
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
|
|
& [type='radio'] {
|
|
cursor: pointer;
|
|
}
|
|
`}}function wa(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function Oa(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ea(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Oa(e,t,n[t])})}return e}function xa(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}ga(va,"Component",({model:e})=>{const t=(0,l.useStyles2)(Sa),{body:n,isSelected:r,queryParams:a}=e.useState();return u().createElement("div",{className:(0,o.cx)(t.container,r&&t.selected),onClick:r?void 0:e.onClickPreset},u().createElement("div",{className:(0,o.cx)(t.bodyAndParams)},u().createElement(n.Component,{model:n}),a.show&&u().createElement("div",{className:t.paramsContainer},a.options.map(n=>u().createElement("label",{key:n.value,className:(0,o.cx)("param",t.param),htmlFor:`checkbox-${n.value}`},u().createElement("input",{id:`checkbox-${n.value}`,type:"checkbox",value:n.value,checked:n.checked,onChange:e.onTogglePercentile}),u().createElement("span",null,n.label))))),u().createElement("div",{className:t.radioContainer},u().createElement(l.Tooltip,{content:r?"Current configuration":"Click to select this configuration",placement:"top"},u().createElement("input",{type:"radio",name:"select-config",checked:r}))))});class Ca extends i.SceneObjectBase{onActivate(){this.syncTimeRange(),this.buildBody(),this.subscribeToEvents()}syncTimeRange(){const e=i.sceneGraph.getAncestor(this,Xo),{from:t,to:n,timeZone:r,value:a}=i.sceneGraph.getTimeRange(e).state;i.sceneGraph.getTimeRange(this).setState({from:t,to:n,timeZone:r,value:a})}buildBody(){return(e=function*(){const{metric:e}=this.state,t=Rt(e.name),n=yield ma(e.name,ds(this)),a=(t||n[0]).id,o=new i.SceneCSSGridLayout({templateColumns:Wn,autoRows:Mt.M+46,isLazy:!0,$behaviors:[new i.behaviors.CursorSync({key:"metricCrosshairSync",sync:r.DashboardCursorSync.Crosshair})],children:n.map((n,r)=>new i.SceneCSSGridItem({body:new va({presetId:n.id,isSelected:a===n.id,onSelect:e=>this.onSelectPreset(e),body:new zn({key:`panel-${n.id}`,discardUserPrefs:n.id!==(null==t?void 0:t.id),metric:e.name,panelOptions:xa(Ea({},n.panelOptions),{title:n.name,fixedColorIndex:r,headerActions:()=>[]}),queryOptions:n.queryOptions})})}))});this.setState({presets:n,selectedPresetId:a,body:o})},function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){wa(i,r,a,o,s,"next",e)}function s(e){wa(i,r,a,o,s,"throw",e)}o(void 0)})}).call(this);var e}subscribeToEvents(){const{metric:e}=this.state;this.subscribeToEvent(ha,t=>{const{config:n,restoreDefault:r}=t.payload,a=te.x.getItem(ee.V.METRIC_PREFS)||{},i=a[e.name];r&&i?delete a[e.name].config:a[e.name]=xa(Ea({},i),{config:n}),te.x.setItem(ee.V.METRIC_PREFS,a)})}static getPanelConfigFromPreset(e){return(0,ze.omit)(e,["name","panelOptions.description"])}constructor({metric:e}){super({metric:e,$timeRange:new i.SceneTimeRange({}),controls:[new i.SceneTimePicker({}),new i.SceneRefreshPicker({})],isConfirmModalOpen:!1,presets:[],selectedPresetId:void 0,body:void 0}),Oa(this,"onSelectPreset",e=>{for(const t of i.sceneGraph.findDescendents(this,va))t.setState({isSelected:t.state.presetId===e});this.setState({selectedPresetId:e})}),Oa(this,"onClickRestoreDefault",()=>{this.setState({isConfirmModalOpen:!0})}),Oa(this,"onClickConfirmRestoreDefault",()=>{const{metric:e,presets:t}=this.state,[n]=t;n?(this.publishEvent(new ha({metric:e,config:Ca.getPanelConfigFromPreset(n),restoreDefault:!0}),!0),this.closeConfirmModal()):(0,v.jx)(new Error(`No default config found for metric ${e}!`),["Cannot restore default configuration."])}),Oa(this,"closeConfirmModal",()=>{this.setState({isConfirmModalOpen:!1})}),Oa(this,"onClickCancel",()=>{this.publishEvent(new fa({metric:this.state.metric}),!0)}),Oa(this,"onClickApplyConfig",()=>{const{metric:e,presets:t,selectedPresetId:n}=this.state,r=i.sceneGraph.findByKeyAndType(this,`panel-${n}`,zn);if(!r)throw new Error(`Panel not found for preset id="${n}"!`);const a=t.find(e=>e.id===n);if(!a)throw new Error(`Preset with id="${n}" not found!`);const o=(0,ze.cloneDeep)(a);o.queryOptions.queries=r.state.queryConfig.queries,this.publishEvent(new ha({metric:e,config:Ca.getPanelConfigFromPreset(o)}),!0)}),this.addActivationHandler(this.onActivate.bind(this))}}function Pa(e){return{controlsContainer:o.css`
|
|
display: flex;
|
|
justify-content: flex-end;
|
|
gap: ${e.spacing(1)};
|
|
margin-bottom: ${e.spacing(2)};
|
|
`,messageContainer:o.css`
|
|
margin: ${e.spacing(2.5,0,1,0)};
|
|
`,controls:o.css`
|
|
display: flex;
|
|
`,formButtonsContainer:o.css`
|
|
display: flex;
|
|
justify-content: center;
|
|
gap: ${e.spacing(2)};
|
|
position: sticky;
|
|
bottom: 0;
|
|
background: ${e.colors.background.primary};
|
|
padding: ${e.spacing(2,0)};
|
|
border-top: 1px solid ${e.colors.border.weak};
|
|
`}}Oa(Ca,"Component",({model:e})=>{const t=(0,l.useStyles2)(Pa),{metric:n,body:r,controls:a,isConfirmModalOpen:i}=e.useState();return u().createElement("div",null,u().createElement("div",{className:t.controlsContainer},u().createElement(l.Button,{variant:"secondary",size:"md",onClick:e.onClickRestoreDefault},"Restore default config"),u().createElement("div",{className:t.controls},a.map(e=>u().createElement(e.Component,{key:e.state.key,model:e})))),u().createElement("div",{className:t.messageContainer},u().createElement("p",null,"Select a Prometheus function that will be used by default to display the ",n.name," metric.")),r&&u().createElement(r.Component,{model:r}),u().createElement("div",{className:t.formButtonsContainer},u().createElement(l.Button,{variant:"primary",size:"md",onClick:e.onClickApplyConfig},"Apply"),u().createElement(l.Button,{variant:"secondary",size:"md",onClick:e.onClickCancel},"Cancel")),u().createElement(l.ConfirmModal,{isOpen:i,title:"Restore default configuration",body:`Are you sure you want to restore the default configuration for the ${n} metric?`,confirmText:"Restore",onConfirm:e.onClickConfirmRestoreDefault,onDismiss:e.closeConfirmModal}))});class ka extends r.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ka,"type","force-sync-y-axis");class ja extends r.BusEventWithPayload{}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ja,"type","reset-sync-y-axis");class _a extends r.BusEventWithPayload{}function Ta(){const e=e=>{let t=Number.NEGATIVE_INFINITY,n=Number.POSITIVE_INFINITY;const r=i.sceneGraph.getTimeRange(e).subscribeToState(()=>{t=Number.NEGATIVE_INFINITY,n=Number.POSITIVE_INFINITY}),a=e.subscribeToEvent(ja,()=>{t=Number.NEGATIVE_INFINITY,n=Number.POSITIVE_INFINITY}),o=e.subscribeToEvent(ka,()=>{let[r,a]=[t,n];const i=Da(e).filter(e=>{var t;const{fieldConfig:n,$data:i}=e.state;return(!("min"in n.defaults)||!("max"in n.defaults))&&([r,a]=Ia((null==i||null===(t=i.state.data)||void 0===t?void 0:t.series)||[],r,a),!0)});r===t&&a===n?Aa(e,t,n,i):([t,n]=[r,a],Aa(e,r,a))}),s=e.subscribeToEvent(_a,r=>{const{panelKey:a,series:o}=r.payload,[s,l]=Ia(o,t,n);s!==l&&s!==Number.NEGATIVE_INFINITY&&l!==Number.POSITIVE_INFINITY&&(s!==t||l!==n?([t,n]=[s,l],Aa(e,s,l)):Aa(e,t,n,[i.sceneGraph.findByKeyAndType(e,a,i.VizPanel)]))});return()=>{s.unsubscribe(),o.unsubscribe(),a.unsubscribe(),r.unsubscribe()}};return Object.defineProperty(e,"__name__",{value:"syncYAxis",configurable:!1,enumerable:!0,writable:!1}),e}function Ia(e,t,n){let[r,a]=[t,n];for(const t of e||[]){var i;const e=null===(i=t.fields[1])||void 0===i?void 0:i.values.filter(Boolean);e&&(r=Math.max(r,...e),a=Math.min(a,...e))}return[r,a]}function Da(e){return i.sceneGraph.findAllObjects(e,e=>e instanceof i.VizPanel&&"timeseries"===e.state.pluginId)}function Aa(e,t,n,r){for(const a of r||Da(e))a.clearFieldConfigCache(),a.setState({fieldConfig:(0,ze.merge)((0,ze.cloneDeep)(a.state.fieldConfig),{defaults:{min:n,max:t}})})}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(_a,"type","timeseries-data-received");var La=n(2245);const Ba={label:"All",value:"$__all"},Na="Select a label to group by";function Ra(e){const t=(0,l.useStyles2)(Ma),{loading:n,options:r,value:a,onChange:i}=e,o=(0,c.useMemo)(()=>[Ba,...r],[r]);if(n)return u().createElement(l.Combobox,{options:[],placeholder:Na,onChange:Ss});return o.length<=4?u().createElement(l.RadioButtonGroup,{"data-testid":"group-by-selector-radio-group",options:o,value:a,onChange:i}):u().createElement("div",{className:t.combobox},u().createElement(l.Combobox,{"data-testid":"group-by-selector-combobox",options:o,value:a,placeholder:Na,onChange:e=>{i(e?e.value:Ba.value)},isClearable:!0}))}function Ma(){return{combobox:(0,o.css)({marginLeft:"4px"})}}class $a extends i.QueryVariable{onActivate(){this.filterOptions(),this.subscribeToState((e,t)=>{e.value&&e.value!==t.value&&(0,d.z)("groupby_label_changed",{label:String(e.value)}),e.options!==t.options&&e.options.find(e=>"le"===e.value)&&this.filterOptions(e.options)});const e=i.sceneGraph.lookupVariable(O,this);$(e)&&e.subscribeToState((e,t)=>{e.filterExpression!==t.filterExpression&&this.changeValueTo("$__all")})}filterOptions(e=this.state.options){this.setState({options:e.filter(e=>"le"!==e.value)})}constructor(){super({name:x,label:"Group by",datasource:T,includeAll:!0,defaultToAll:!0,query:"label_names(${metric})",value:"",text:""}),this.addActivationHandler(this.onActivate.bind(this))}}function Va(){return{field:(0,o.css)({marginBottom:0})}}function Fa(e,t){return(null==t?void 0:t.state.embedded)||e.isLight?e.colors.background.primary:e.colors.background.canvas}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}($a,"Component",({model:e})=>{const t=(0,l.useStyles2)(Va),{options:n,value:r,loading:a}=e.useState(),i=(0,c.useCallback)((t,n)=>{const r="All"===t?"$__all":t;e.changeValueTo(r,void 0,!n)},[e]);return u().createElement(l.Field,{label:"By label","data-testid":"breakdown-label-selector",className:t.field},u().createElement(Ra,{options:n,value:r,onChange:i,loading:a}))});const qa=(e={})=>t=>{const[n]=i.sceneGraph.findDescendents(t,i.SceneQueryRunner);if(!n)return;const a=t.state.title,o=n.subscribeToState(n=>{var i;if((null===(i=n.data)||void 0===i?void 0:i.state)!==r.LoadingState.Done)return;const{series:o}=n.data;if(!(null==o?void 0:o.length))return;const s={title:`${a} (${o.length})`};var l,c;o.length>Nn&&(s.description=`Showing only ${Nn} series out of ${o.length} to keep the data easy to read.`,s.description+="string"==typeof(null===(l=e.description)||void 0===l?void 0:l.ctaText)?` ${null===(c=e.description)||void 0===c?void 0:c.ctaText}`:' Click on "Select" on this panel to view a breakdown of all the label\'s values.');t.setState(s)});return()=>{o.unsubscribe()}};function Ga(){return e=>{var t;if("timeseries"!==e.state.pluginId)return;let n=i.sceneGraph.getData(e);n instanceof i.SceneDataTransformer&&(n=n.state.$data);const{data:a}=n.state;(null==a?void 0:a.state)===r.LoadingState.Done&&(null===(t=a.series)||void 0===t?void 0:t.length)&&e.publishEvent(new _a({panelKey:e.state.key,series:a.series}),!0);const o=n.subscribeToState((t,n)=>{var a,i,o;if((null===(a=t.data)||void 0===a?void 0:a.state)===r.LoadingState.Done&&(null===(i=t.data.series)||void 0===i?void 0:i.length)&&t.data.series!==(null===(o=n.data)||void 0===o?void 0:o.series)){var s;const n=null===(s=t.data.series[0].meta)||void 0===s?void 0:s.type;if(n&&!n.startsWith("timeseries"))return;e.publishEvent(new _a({panelKey:e.state.key,series:t.data.series}),!0)}});return()=>{o.unsubscribe()}}}function Ua(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class za extends i.SceneObjectBase{constructor(...e){super(...e),Ua(this,"onClick",()=>{const{label:e}=this.state;(0,d.z)("breakdown_panel_selected",{label:e});const t=i.sceneGraph.lookupVariable(x,this);if(!F(t))throw new Error("Group by variable not found");t.changeValueTo(e)})}}Ua(za,"Component",({model:e})=>u().createElement(l.Button,{variant:"secondary",size:"sm",fill:"outline",onClick:e.onClick},"Select"));var Ha=n(5540);function Ka(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Wa extends i.SceneObjectBase{isCurrentStateBookmarked(){try{const e=ds(this),t=xr(i.sceneUtils.getUrlState(e));return(te.x.getItem(ee.V.BOOKMARKS)||[]).some(e=>xr(e.urlValues)===t)}catch(e){return!1}}constructor(){super({isBookmarked:!1}),Ka(this,"onClick",()=>{const e=i.sceneUtils.getUrlState(ds(this)),t=xr(e),n=te.x.getItem(ee.V.BOOKMARKS)||[],r=this.state.isBookmarked;if(r){(0,d.z)("bookmark_changed",{action:"toggled_off"});const e=n.filter(e=>xr(e.urlValues)!==t);te.x.setItem(ee.V.BOOKMARKS,e)}else{(0,d.z)("bookmark_changed",{action:"toggled_on"});const t={urlValues:e,createdAt:Date.now()};te.x.setItem(ee.V.BOOKMARKS,[...n,t])}this.setState({isBookmarked:!r})}),this.addActivationHandler(()=>{const e=this.isCurrentStateBookmarked();this.setState({isBookmarked:e})})}}Ka(Wa,"Component",({model:e})=>{const t=(0,l.useStyles2)(Qa),{isBookmarked:n}=e.useState(),r=n?"Remove bookmark":"Add bookmark";return u().createElement(l.Button,{className:(0,o.cx)(t.bookmarkButton,n&&t.active),"aria-label":r,variant:"secondary",size:"sm",fill:"text",onClick:e.onClick,icon:n?u().createElement(l.Icon,{name:"favorite",type:"mono",size:"lg"}):u().createElement(l.Icon,{name:"star",type:"default",size:"lg"}),tooltip:r,tooltipPlacement:"top","data-testid":"bookmark-header-action"})});const Qa=e=>({bookmarkButton:o.css`
|
|
margin: 0;
|
|
padding: 0;
|
|
margin-left: ${e.spacing(1)};
|
|
`,active:o.css`
|
|
color: ${e.colors.text.maxContrast};
|
|
`});function Ya(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Xa extends i.SceneObjectBase{onActivate(){const e=i.sceneGraph.getAncestor(this,zn);this.setState({currentPanelType:e.state.panelConfig.type}),this._subs.add(e.subscribeToState((e,t)=>{e.panelConfig.type!==t.panelConfig.type&&this.setState({currentPanelType:e.panelConfig.type})}))}constructor(){super({options:[{value:"percentiles",label:"percentiles"},{value:"heatmap",label:"heatmap"}],currentPanelType:void 0}),Ya(this,"onChange",e=>{(0,d.z)("histogram_panel_type_changed",{panelType:e}),this.publishEvent(new It({panelType:e}),!0)}),this.addActivationHandler(this.onActivate.bind(this))}}function Ja(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function Za(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){Ja(i,r,a,o,s,"next",e)}function s(e){Ja(i,r,a,o,s,"throw",e)}o(void 0)})}}Ya(Xa,"Component",({model:e})=>{const{options:t,currentPanelType:n}=e.useState();return t.length?u().createElement(l.RadioButtonGroup,{size:"sm",options:t,value:n,onChange:e.onChange}):null});const ei=Mt.XL,ti="topview-panel-menu";class ni extends i.SceneObjectBase{onActivate(){return Za(function*(){const{metric:e}=this.state,t=yield ds(this).getMetadataForMetric(e),[n]=i.sceneGraph.findDescendents(this,zn),{metricType:r}=n.state;if(t&&n.update({description:M(t)},{}),"classic-histogram"===r)return;const a=n.subscribeToState(t=>Za(function*(){"native-histogram"!==r&&"native-histogram"===t.metricType&&(a.unsubscribe(),n.update({headerActions:()=>[new Xa,new kt({metric:{name:e,type:t.metricType}}),new Wa]},{}))})());this._subs.add(a)}).call(this)}constructor({metric:e}){super({metric:e,topView:new i.SceneFlexLayout({direction:"column",$behaviors:[new i.behaviors.CursorSync({key:"metricCrosshairSync",sync:r.DashboardCursorSync.Crosshair})],children:[new i.SceneFlexItem({minHeight:ei,maxHeight:"40%",body:new zn({metric:e,panelOptions:{height:Mt.XL,headerActions:Vt(e)?({metric:e})=>[new Xa,new kt({metric:e}),new Wa]:({metric:e})=>[new kt({metric:e}),new Wa],menu:()=>new xi({key:ti,labelName:e})},queryOptions:{resolution:$t.HIGH}})})]}),selectedTab:void 0,actionBar:new io({})}),this.addActivationHandler(()=>{this.onActivate()})}}function ri(e,t,n){return{container:(0,o.css)({display:"flex",flexDirection:"column",position:"relative",flexGrow:1}),tabContent:(0,o.css)({height:"100%"}),topView:(0,o.css)({}),stickyTop:(0,o.css)({display:"flex",flexDirection:"row",background:Fa(e,n),position:"sticky",paddingTop:e.spacing(1),zIndex:10,top:`calc(var(--app-controls-height, 0px) + ${t}px)`}),nonSticky:(0,o.css)({display:"flex",flexDirection:"row"})}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(ni,"Component",({model:e})=>{const{topView:t,selectedTab:n,actionBar:r}=e.useState(),i=(0,a.useChromeHeaderHeight)(),s=ds(e),d=(0,l.useStyles2)(ri,s.state.embedded?0:null!=i?i:0,s),p=(0,c.useRef)(null);return(0,Ha.w)({ref:p,onResize:()=>{p.current&&requestAnimationFrame(()=>{!function(e){const t=e.current;if(!t)return;const{height:n}=t.getBoundingClientRect();document.documentElement.style.setProperty("--action-bar-height",`${n}px`)}(p)})}}),u().createElement("div",{className:d.container},u().createElement("div",{className:(0,o.cx)(d.topView,d.nonSticky),"data-testid":"top-view"},u().createElement(t.Component,{model:t})),u().createElement("div",{className:(0,o.cx)(d.topView,d.stickyTop),id:"action-bar-container",ref:p},u().createElement(r.Component,{model:r})),n&&u().createElement("div",{"data-testid":"tab-content",className:d.tabContent},u().createElement(n.Component,{model:n})))});var ai=n(8943);class ii{static create(e){return{text:"Copy URL",iconClassName:"copy",onClick:()=>{if(navigator.clipboard){(0,d.z)("selected_metric_action_clicked",{action:"share_url"});const t=`${a.config.appUrl.endsWith("/")?a.config.appUrl.slice(0,-1):a.config.appUrl}${ai.G}/${ms(e)}`;navigator.clipboard.writeText(t),(0,v.qq)(["URL copied to clipboard"])}}}}}function oi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function si(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}class li{static create(e){let t;try{const n=i.sceneGraph.getAncestor(e,i.VizPanel),r=i.sceneGraph.getData(n).state.data;if(!r)throw new Error("Cannot get link to explore, no panel data found");t=(0,i.getExploreURL)(r,e,r.timeRange,e=>"expr"in e&&"string"==typeof e.expr&&e.expr.includes("__ignore_usage__")?si(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){oi(e,t,n[t])})}return e}({},e),{expr:e.expr.replace(/,?__ignore_usage__="",?/,"")}):e)}catch(e){}return{text:"Explore",iconClassName:"compass",onClick:()=>null==t?void 0:t.then(e=>{e&&window.open(`${a.config.appSubUrl}${e}`,"_blank")}),shortcut:"p x"}}}const ci=n.p+"ac01ecbc64128d2f3e68.svg";var ui=n(2533);function di(e){return null!=e&&"state"in e&&"runQueries"in e}function pi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function mi(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){pi(e,t,n[t])})}return e}function hi(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}const fi=`${ui.id}/investigation/v1`;class bi extends i.SceneObjectBase{getPanelConfigAndDataFrames(){var e;const t=vs(this,e=>e instanceof i.VizPanel,i.VizPanel),n=i.sceneGraph.getData(this);return{fieldConfig:null==t?void 0:t.state.fieldConfig,frames:null==n||null===(e=n.state.data)||void 0===e?void 0:e.series}}constructor(e){super(hi(mi({},e),{queries:[]})),pi(this,"_onActivate",()=>{this.subscribeToState(()=>{this.getQueries(),this.getContext()});const e=i.sceneGraph.interpolate(this,P);this.setState({dsUid:e})}),pi(this,"getQueries",()=>{const e=i.sceneGraph.getData(this),t=i.sceneGraph.findObject(e,di);if(di(t)){const e=this.state.frame?gi(this.state.frame):null,n=t.state.queries.map(n=>hi(mi({},n),{expr:i.sceneGraph.interpolate(t,n.expr),legendFormat:(null==e?void 0:e.name)?`{{ ${e.name} }}`:i.sceneGraph.interpolate(t,n.legendFormat)}));JSON.stringify(n)!==JSON.stringify(this.state.queries)&&this.setState({queries:n})}}),pi(this,"updateFieldConfigOverrides",()=>{const{fieldConfig:e,frames:t}=this.getPanelConfigAndDataFrames();if(e&&(null==t?void 0:t.length)){for(const a of t)for(const t of a.fields){const a=Object.keys(t.config).map(e=>({id:e,value:t.config[e]})),i=e.overrides.find(e=>{var n,r;return e.matcher.options===(null!==(r=null!==(n=t.config.displayNameFromDS)&&void 0!==n?n:t.config.displayName)&&void 0!==r?r:t.name)&&"byName"===e.matcher.id});var n,r;if(!i)e.overrides.unshift({matcher:{id:"byName",options:null!==(r=null!==(n=t.config.displayNameFromDS)&&void 0!==n?n:t.config.displayName)&&void 0!==r?r:t.name},properties:a});i&&JSON.stringify(i.properties)!==JSON.stringify(a)&&(i.properties=a)}return e}}),pi(this,"getContext",()=>{const e=this.updateFieldConfigOverrides(),{queries:t,dsUid:n,labelName:r,fieldName:a}=this.state,o=i.sceneGraph.getTimeRange(this);if(!o||!t||!n)return;const s={origin:"Metrics Drilldown",type:"timeseries",queries:t,timeRange:mi({},o.state.value),datasource:{uid:n},url:window.location.href,id:`${JSON.stringify(t)}${r}${a}`,title:r+(a?` > ${a}`:""),logoPath:ci,drillDownLabel:a,fieldConfig:e};JSON.stringify(s)!==JSON.stringify(this.state.context)&&this.setState({context:s})}),this.addActivationHandler(this._onActivate.bind(this))}}pi(bi,"Component",({model:e})=>{const{context:t}=e.useState(),{links:n}=(0,a.usePluginLinks)({extensionPointId:fi,context:t,limitPerPlugin:1}),r=n.find(e=>"grafana-investigations-app"===e.pluginId);return r?u().createElement(l.IconButton,{tooltip:r.description,"aria-label":"add panel to exploration",key:r.id,name:null!==(i=r.icon)&&void 0!==i?i:"panel-add",onClick:e=>{r.onClick&&r.onClick(e)}}):null;var i});const gi=e=>{var t,n;const r=null!==(n=null===(t=e.fields[1])||void 0===t?void 0:t.labels)&&void 0!==n?n:{},a=Object.keys(r);if(1!==a.length)return;const i=a[0];return{name:i,value:r[i]}};function yi(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function vi(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){yi(i,r,a,o,s,"next",e)}function s(e){yi(i,r,a,o,s,"throw",e)}o(void 0)})}}class Si{static create(e,t,n,r){return vi(function*(){const a=new bi({labelName:t,fieldName:n,frame:r});e.setState({explorationsButton:a}),e.state.addExplorationsLink&&a.activate();const i=yield wi(a),o=[];return i&&o.push({text:"investigations_divider",type:"divider"},{text:"Investigations",type:"group"},{text:"Add to investigation",iconClassName:"plus-square",onClick:e=>i.onClick&&i.onClick(e)}),o})()}}const wi=e=>vi(function*(){const t=e.state.context;if(a.config.buildInfo.version.startsWith("11."))try{const e=(yield Promise.resolve().then(n.t.bind(n,8531,23))).getPluginLinkExtensions;if(void 0!==e){return e({extensionPointId:fi,context:t}).extensions[0]}}catch(e){Z.v.error(e,{message:"Error importing getPluginLinkExtensions"})}if("function"==typeof a.getObservablePluginLinks){return(yield(0,jn.firstValueFrom)((0,a.getObservablePluginLinks)({extensionPointId:fi,context:t})))[0]}})();function Oi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ei(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}class xi extends i.SceneObjectBase{addItem(e){var t;null===(t=this.state.body)||void 0===t||t.addItem(e)}setItems(e){var t;null===(t=this.state.body)||void 0===t||t.setItems(e)}constructor(e){var t;super(Ei(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Oi(e,t,n[t])})}return e}({},e),{addExplorationsLink:null===(t=e.addExplorationsLink)||void 0===t||t,body:new i.VizPanelMenu({})})),this.addActivationHandler(()=>{var e;const t=[{text:"Navigation",type:"group"},li.create(this)];this.state.key===ti&&t.push({text:"Actions",type:"group"},ii.create(ds(this))),this.state.addExplorationsLink&&Si.create(this,this.state.labelName,this.state.fieldName,this.state.frame).then(e=>{var n;e.length>0&&(null===(n=this.state.body)||void 0===n||n.setItems([...t,...e]))}),null===(e=this.state.body)||void 0===e||e.setState({items:t})})}}Oi(xi,"Component",({model:e})=>{const{body:t}=e.useState();return u().createElement("div",{"data-testid":"panel-menu"},t&&u().createElement(t.Component,{model:t}))});class Ci extends i.SceneObjectBase{onActivate(){this.subscribeToLayoutChange(),this.subscribeToEvents()}subscribeToEvents(){const e=new Map;this.subscribeToEvent(_a,t=>{const{panelKey:n,series:r}=t.payload,a=i.sceneGraph.findByKeyAndType(this,n,i.VizPanel);if(1===r.length)return e.has(n)||e.set(n,a.state.headerActions||[]),void a.setState({headerActions:[]});e.has(n)&&a.setState({headerActions:e.get(n)})})}subscribeToLayoutChange(){const e=i.sceneGraph.findByKeyAndType(this,"layout-switcher",qe),t=(e,t)=>{e.layout!==(null==t?void 0:t.layout)&&this.state.body.state.body.setState({templateColumns:e.layout===Fe.ROWS?Qn:Wn})};i.sceneUtils.syncStateFromSearchParams(e,new URLSearchParams(window.location.search)),t(e.state),this._subs.add(e.subscribeToState(t))}Controls({model:e}){const t=(0,l.useStyles2)(Pi),{layoutSwitcher:n}=e.useState();return u().createElement(l.Field,{label:"View",className:t.field},u().createElement(n.Component,{model:n}))}constructor({metric:e}){super({key:"metric-labels-list",metric:e,layoutSwitcher:new qe({}),body:new mt({variableName:x,initialPageSize:60,pageSizeIncrement:9,body:new i.SceneCSSGridLayout({children:[],isLazy:!0,templateColumns:Wn,autoRows:Mt.M,$behaviors:[new i.behaviors.CursorSync({key:"metricCrosshairSync",sync:r.DashboardCursorSync.Crosshair}),Ta()]}),getLayoutLoading:()=>new i.SceneReactObject({reactNode:u().createElement(l.Spinner,{inline:!0})}),getLayoutEmpty:()=>new i.SceneReactObject({reactNode:u().createElement(Kn._,{title:"",severity:"info"},"No labels found for the current filters and time range.")}),getLayoutError:e=>new i.SceneReactObject({reactNode:u().createElement(Kn._,{severity:"error",title:"Error while loading labels!",error:e})}),getLayoutChild:(t,n)=>{const r=t.value;return new i.SceneCSSGridItem({body:Bn({metric:e,panelConfig:{type:"timeseries",height:Mt.M,title:r,fixedColorIndex:n,behaviors:[Ga(),qa()],headerActions:()=>[new za({label:r})],menu:()=>new xi({labelName:r}),legend:{placement:"bottom"}},queryConfig:{resolution:$t.MEDIUM,groupBy:r,labelMatchers:[],addIgnoreUsageFilter:!0}})})}})}),this.addActivationHandler(this.onActivate.bind(this))}}function Pi(e){return{container:(0,o.css)({width:"100%"}),field:(0,o.css)({marginBottom:0}),footer:(0,o.css)({display:"flex",justifyContent:"center",alignItems:"center",marginTop:e.spacing(4),"& button":{height:"40px",borderRadius:"8px"}})}}function ki(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Ci,"Component",({model:e})=>{const t=(0,l.useStyles2)(Pi),{body:n}=e.useState(),r=i.sceneGraph.lookupVariable(x,e),{loading:a,error:o}=r.useState(),s=n.useSizes(),c=!a&&!o&&s.total>0&&s.current<s.total;return u().createElement("div",{"data-testid":"labels-list"},u().createElement("div",{className:t.container},u().createElement(n.Component,{model:n})),c&&u().createElement("div",{className:t.footer},u().createElement(ft,{label:"label",batchSizes:s,onClick:()=>{n.increaseBatchSize()}})))});class ji extends i.SceneObjectBase{constructor(...e){super(...e),ki(this,"onClick",()=>{const{labelName:e,labelValue:t}=this.state;(0,d.z)("label_filter_changed",{label:e,action:"added",cause:"breakdown"}),ds(this).addFilterWithoutReportingInteraction({key:e,operator:"=",value:t})})}}function _i(e){var t;const n=(null===(t=e.fields[1])||void 0===t?void 0:t.labels)||{},r=Object.keys(n);return 0===r.length?"<unspecified>":n[r[0]]}ki(ji,"Component",({model:e})=>u().createElement(l.Button,{variant:"secondary",size:"sm",fill:"outline",onClick:e.onClick},"Add to filters"));var Ti=n(2290);function Ii(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Di extends i.SceneObjectBase{constructor(e){const t=te.x.getItem(ee.V.BREAKDOWN_SORTBY);super({key:"breakdown-sort-by",target:e.target,options:Di.DEFAULT_OPTIONS,value:t&&Di.DEFAULT_OPTIONS.find(e=>e.value===t)||Di.DEFAULT_OPTIONS[0]}),Ii(this,"onChange",e=>{this.setState({value:e}),te.x.setItem(ee.V.BREAKDOWN_SORTBY,e.value)})}}function Ai(e){return{sortByTooltip:(0,o.css)({display:"flex",gap:e.spacing(1)}),field:(0,o.css)({marginBottom:0})}}function Li(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Ii(Di,"DEFAULT_OPTIONS",[{value:"outliers",label:"Outlying series",description:"Prioritizes values that show distinct behavior from others within the same label"},{value:"alphabetical",label:"Name [A-Z]",description:"Alphabetical order"},{value:"alphabetical-reversed",label:"Name [Z-A]",description:"Reversed alphabetical order"}]),Ii(Di,"Component",({model:e})=>{const t=(0,l.useStyles2)(Ai),{value:n,options:r}=e.useState();return u().createElement(l.Field,{className:t.field,"data-testid":"sort-by-select",htmlFor:"sort-by-criteria",label:u().createElement("div",{className:t.sortByTooltip},"Sort by",u().createElement(l.IconButton,{name:"info-circle",size:"sm",variant:"secondary",tooltip:"Sorts values using standard or smart time series calculations."}))},u().createElement(l.Combobox,{id:"sort-by-criteria",placeholder:"Choose criteria",width:20,options:r,value:n,onChange:e.onChange,isClearable:!1}))});class Bi extends i.SceneObjectBase{performRepeat(e){var t,n,a,i;if(e.state===r.LoadingState.Loading)return void this.setState({loadingLayout:null===(t=(n=this.state).getLayoutLoading)||void 0===t?void 0:t.call(n),errorLayout:void 0,emptyLayout:void 0,currentBatchSize:0});if(e.state===r.LoadingState.Error)return void this.setState({errorLayout:null===(a=(i=this.state).getLayoutError)||void 0===a?void 0:a.call(i,e),loadingLayout:void 0,emptyLayout:void 0,currentBatchSize:0});const o=this.filterAndSort(e.series);var s,l;if(!o.length)return void this.setState({emptyLayout:null===(s=(l=this.state).getLayoutEmpty)||void 0===s?void 0:s.call(l),errorLayout:void 0,loadingLayout:void 0,currentBatchSize:0,counts:{current:0,total:e.series.length}});this.setState({loadingLayout:void 0,errorLayout:void 0,emptyLayout:void 0,currentBatchSize:this.state.initialPageSize,counts:{current:o.length,total:e.series.length}});const c=o.slice(0,this.state.initialPageSize).map((t,n)=>this.state.getLayoutChild(e,t,n)).filter(Boolean);this.state.body.setState({children:c})}initFilterAndSort(){this.searchText=i.sceneGraph.findByKeyAndType(this,"quick-search",Ze).state.value,this.sortBy=i.sceneGraph.findByKeyAndType(this,"breakdown-sort-by",Di).state.value.value}filterAndSort(e){let t=[];if(this.searchText){const n=this.searchText.split(",").map(e=>e.trim()).filter(Boolean).map(e=>{try{return new RegExp(e)}catch(e){return null}}).filter(Boolean);for(let r=0;r<e.length;r+=1){const a=e[r];n.some(e=>e.test(_i(a)))&&t.push(a)}}else t=e;return this.sortBy&&(t=(0,Ti.sortSeries)(t,this.sortBy)),t}filter(e){this.searchText=e;const{data:t}=i.sceneGraph.getData(this).state;t&&(this.publishEvent(new ja({}),!0),this.performRepeat(t))}sort(e){this.sortBy=e;const{data:t}=i.sceneGraph.getData(this).state;t&&(this.publishEvent(new ja({}),!0),this.performRepeat(t))}increaseBatchSize(){const{data:e}=i.sceneGraph.getData(this).state;if(!e)return;const t=this.state.currentBatchSize+this.state.pageSizeIncrement,n=this.filterAndSort(e.series).slice(this.state.currentBatchSize,t).map((t,n)=>this.state.getLayoutChild(e,t,n)).filter(Boolean);this.state.body.setState({children:[...this.state.body.state.children,...n]}),this.setState({currentBatchSize:t}),this.publishEvent(new ka({}),!0)}useSizes(){const{currentBatchSize:e,pageSizeIncrement:t}=this.useState(),{data:n}=i.sceneGraph.getData(this).state,r=n?this.filterAndSort(n.series).length:0,a=r-e;return{increment:a<t?a:t,current:e,total:r}}getCounts(){const{data:e}=i.sceneGraph.getData(this).state;return{current:0,total:e?e.series.length:0}}constructor({$behaviors:e,body:t,getLayoutChild:n,getLayoutLoading:r,getLayoutError:a,getLayoutEmpty:o,initialPageSize:s,pageSizeIncrement:l,$data:c}){super({key:"breakdown-by-frame-repeater",$behaviors:e,body:t,getLayoutChild:n,getLayoutLoading:r,getLayoutError:a,getLayoutEmpty:o,currentBatchSize:0,initialPageSize:s||120,pageSizeIncrement:l||9,loadingLayout:void 0,errorLayout:void 0,emptyLayout:void 0,counts:{current:0,total:0},$data:c}),Li(this,"searchText",""),Li(this,"sortBy",void 0),this.addActivationHandler(()=>{const e=i.sceneGraph.getData(this);if(!e)throw new Error("No data provider found!");this.initFilterAndSort(),this._subs.add(e.subscribeToState(e=>{e.data&&this.performRepeat(e.data)})),e.state.data&&this.performRepeat(e.state.data)})}}Li(Bi,"Component",({model:e})=>{const{body:t,loadingLayout:n,errorLayout:r,emptyLayout:a}=e.useState();return n?u().createElement(n.Component,{model:n}):r?u().createElement(r.Component,{model:r}):a?u().createElement(a.Component,{model:a}):u().createElement(t.Component,{model:t})});class Ni extends Qe{constructor(){super({key:"LabelValuesCountsProvider"}),this.addActivationHandler(()=>{const e=i.sceneGraph.findByKeyAndType(this,"breakdown-by-frame-repeater",Bi);this._subs.add(e.subscribeToState((e,t)=>{e.counts!==t.counts&&this.setState({counts:e.counts})}))})}}function Ri(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Mi(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Ri(e,t,n[t])})}return e}function $i(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}class Vi extends i.SceneObjectBase{onActivate(){this.subscribeToLayoutChange()}subscribeToQuickSearchChange(){i.sceneUtils.syncStateFromSearchParams(this.state.quickSearch,new URLSearchParams(window.location.search)),this._subs.add(this.subscribeToEvent(Xe,e=>{const t=i.sceneGraph.findDescendents(this,Bi)[0];t&&t.filter(e.payload.searchText)}))}subscribeToSortByChange(){const{sortBySelector:e}=this.state;this._subs.add(e.subscribeToState((e,t)=>{if(e.value.value!==(null==t?void 0:t.value.value)){const t=i.sceneGraph.findDescendents(this,Bi)[0];t&&t.sort(e.value.value)}}))}subscribeToLayoutChange(){const{layoutSwitcher:e}=this.state;i.sceneUtils.syncStateFromSearchParams(e,new URLSearchParams(window.location.search));const t=(e,t)=>{e.layout!==(null==t?void 0:t.layout)&&this.updateBody(e.layout)};t(e.state),this._subs.add(e.subscribeToState(t))}updateBody(e){if(e===Fe.SINGLE)return void this.setState({body:this.buildSinglePanel()});const t=i.sceneGraph.findDescendents(this,Bi)[0],n=t||this.buildByFrameRepeater();n.state.body.setState({templateColumns:e===Fe.ROWS?Qn:Wn}),this.setState({body:n}),t||(this.subscribeToQuickSearchChange(),this.subscribeToSortByChange())}buildSinglePanel(){const{metric:e,label:t}=this.state;return new zn({metric:e.name,discardUserPrefs:!0,panelOptions:{type:"timeseries",height:Mt.XL,headerActions:()=>[],behaviors:[qa({description:{ctaText:""}})]},queryOptions:{groupBy:t,data:i.sceneGraph.getData(this)}})}buildByFrameRepeater(){const{metric:e,label:t}=this.state,n=Rt(e.name);return new Bi({$behaviors:[Ta(),new i.behaviors.CursorSync({key:"metricCrosshairSync",sync:r.DashboardCursorSync.Crosshair})],body:new i.SceneCSSGridLayout({children:[],isLazy:!0,templateColumns:Wn,autoRows:Mt.M}),getLayoutLoading:()=>new i.SceneReactObject({reactNode:u().createElement(l.Spinner,{inline:!0})}),getLayoutEmpty:()=>new i.SceneReactObject({reactNode:u().createElement(Kn._,{title:"",severity:"info"},"No label values found for the current filters and time range.")}),getLayoutError:e=>new i.SceneReactObject({reactNode:u().createElement(Kn._,{severity:"error",title:"Error while loading metrics!",error:e.errors[0]})}),getLayoutChild:(r,a,o)=>{if(a.length<2)return null;const s=_i(a),l=!s.startsWith("<unspecified"),c=new zn({metric:e.name,discardUserPrefs:!0,panelOptions:$i(Mi({},null==n?void 0:n.panelOptions),{title:s,fixedColorIndex:o,description:"",headerActions:l?()=>[new ji({labelName:t,labelValue:s})]:()=>[],menu:()=>new xi({labelName:s}),behaviors:[Ga()]}),queryOptions:$i(Mi({},null==n?void 0:n.queryOptions),{labelMatchers:[{key:t,operator:"=",value:s}]})});return new i.SceneCSSGridItem({body:c})}})}Controls({model:e}){const t=(0,l.useStyles2)(Fi),{body:n,quickSearch:r,layoutSwitcher:a,sortBySelector:i}=e.useState();return u().createElement(u().Fragment,null,n instanceof Bi&&u().createElement(u().Fragment,null,u().createElement(l.Field,{className:(0,o.cx)(t.field,t.quickSearchField),label:"Search"},u().createElement(r.Component,{model:r})),u().createElement(i.Component,{model:i})),u().createElement(l.Field,{label:"View",className:t.field},u().createElement(a.Component,{model:a})))}constructor({metric:e,label:t}){const n=yn({metric:e,queryConfig:{resolution:$t.MEDIUM,labelMatchers:[],addIgnoreUsageFilter:!1,groupBy:t}});super({key:"metric-label-values-list",metric:e,label:t,layoutSwitcher:new qe({urlSearchParamName:"breakdownLayout",options:[{label:"Single",value:Fe.SINGLE},{label:"Grid",value:Fe.GRID},{label:"Rows",value:Fe.ROWS}]}),quickSearch:new Ze({urlSearchParamName:"breakdownSearchText",targetName:"label value",countsProvider:new Ni,displayCounts:!0}),sortBySelector:new Di({target:"labels"}),$data:new i.SceneDataTransformer({$data:new i.SceneQueryRunner({datasource:T,maxDataPoints:n.maxDataPoints,queries:n.queries}),transformations:[Dn(t)]}),body:void 0}),this.addActivationHandler(this.onActivate.bind(this))}}function Fi(e){return{singlePanelContainer:(0,o.css)({width:"100%",height:"300px"}),listContainer:(0,o.css)({width:"100%"}),listFooter:(0,o.css)({display:"flex",justifyContent:"center",alignItems:"center",marginTop:e.spacing(4),"& button":{height:"40px",borderRadius:"8px"}}),quickSearchField:(0,o.css)({flexGrow:1}),field:(0,o.css)({marginBottom:0})}}function qi(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}Ri(Vi,"Component",({model:e})=>{const{body:t}=e.useState();return u().createElement(u().Fragment,null,t instanceof zn&&u().createElement(Vi.SingleMetricPanelComponent,{model:e}),t instanceof Bi&&u().createElement(Vi.ByFrameRepeaterComponent,{model:e}))}),Ri(Vi,"SingleMetricPanelComponent",({model:e})=>{const t=(0,l.useStyles2)(Fi),{body:n}=e.useState();return u().createElement("div",{"data-testid":"single-metric-panel"},u().createElement("div",{className:t.singlePanelContainer},n instanceof zn&&u().createElement(n.Component,{model:n})))}),Ri(Vi,"ByFrameRepeaterComponent",({model:e})=>{const t=(0,l.useStyles2)(Fi),{body:n}=e.useState(),a=i.sceneGraph.getData(e),{state:o,errors:s}=a.useState().data||{},c=n,d=c.useSizes(),p=o!==r.LoadingState.Loading&&!(null==s?void 0:s.length)&&d.total>0&&d.current<d.total;return u().createElement("div",{"data-testid":"label-values-list"},u().createElement("div",{className:t.listContainer},n instanceof Bi&&u().createElement(n.Component,{model:n})),p&&u().createElement("div",{className:t.listFooter},u().createElement(ft,{label:"label value",batchSizes:d,onClick:()=>{c.increaseBatchSize()}})))});class Gi extends i.SceneObjectBase{onActivate(){const e=this.getVariable();e.subscribeToState((t,n)=>{t.value!==n.value&&this.updateBody(e)}),a.config.featureToggles.enableScopesInMetricsExplore&&this.subscribeToEvent(D,()=>{this.updateBody(e)}),this.updateBody(e)}getVariable(){const e=i.sceneGraph.lookupVariable(x,this);if(!F(e))throw new Error("Group by variable not found");return e}updateBody(e){return(t=function*(){const{metric:t}=this.state,n={name:t,type:yield Ut(t,ds(this))};this.setState({body:e.hasAllValue()?new Ci({metric:n}):new Vi({metric:n,label:e.state.value})})},function(){var e=this,n=arguments;return new Promise(function(r,a){var i=t.apply(e,n);function o(e){qi(i,r,a,o,s,"next",e)}function s(e){qi(i,r,a,o,s,"throw",e)}o(void 0)})}).call(this);var t}constructor({metric:e}){super({metric:e,body:void 0}),this.addActivationHandler(this.onActivate.bind(this))}}function Ui(e,t,n){return{container:(0,o.css)({flexGrow:1,display:"flex",minHeight:"100%",flexDirection:"column"}),stickyControls:(0,o.css)({margin:e.spacing(1,0,1.5,0),position:"sticky",top:`calc(var(--app-controls-height, 0px) + ${t}px + var(--action-bar-height, 0px))`,zIndex:10,background:Fa(e,n),paddingBottom:e.spacing(1)}),controls:(0,o.css)({display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"end",flexWrap:"wrap",gap:e.spacing(1)}),searchField:(0,o.css)({flexGrow:1})}}function zi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Hi(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(Gi,"Component",({model:e})=>{const t=(0,a.useChromeHeaderHeight)(),n=ds(e),r=(0,l.useStyles2)(Ui,n.state.embedded?0:null!=t?t:0,n),{body:i}=e.useState(),o=e.getVariable();return u().createElement("div",{className:r.container},u().createElement("div",{className:r.stickyControls,"data-testid":"breakdown-controls"},u().createElement("div",{className:r.controls},u().createElement(o.Component,{model:o}),i instanceof Ci&&u().createElement(i.Controls,{model:i}),i instanceof Vi&&u().createElement(i.Controls,{model:i}))),u().createElement("div",{"data-testid":"panels-list"},i instanceof Ci&&u().createElement(i.Component,{model:i}),i instanceof Vi&&u().createElement(i.Component,{model:i})))});const Ki={label:"All metric names",value:"all"};class Wi extends i.SceneObjectBase{getUrlState(){return{metricPrefix:this.state.value}}updateFromUrl(e){"string"!=typeof e.metricPrefix?this.setState({value:Ki.value}):this.state.value!==e.metricPrefix&&this.setState({value:e.metricPrefix})}onActivate(){this.parseMetricPrefixes()}parseMetricPrefixes(){if(this._variableDependency.hasDependencyInLoadingState())return void this.setState({error:void 0,loading:!0});const e=i.sceneGraph.lookupVariable(Me,this);if(e.state.error)return void this.setState({error:e.state.error,loading:!1,options:[]});const t=vr(ht(e)),n=[Ki,...t.map(e=>({value:e.value,label:`${e.label} (${e.count})`}))],{value:r}=this.state,a=n.find(e=>e.value===r)?r:Ki.value;this.setState({error:null,loading:!1,options:n}),this.selectOption({value:a,label:a})}constructor(e){super(Hi(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){zi(e,t,n[t])})}return e}({},e),{key:"related-prefix-filter",loading:!0,error:null,options:[Ki],value:Ki.value})),zi(this,"_variableDependency",new i.VariableDependencyConfig(this,{variableNames:[Me],onVariableUpdateCompleted:()=>this.parseMetricPrefixes()})),zi(this,"_urlSync",new i.SceneObjectUrlSyncConfig(this,{keys:["metricPrefix"]})),zi(this,"selectOption",e=>{const t=null===e?Ki.value:e.value;this.setState({value:t}),this.publishEvent(new ar({type:"prefixes",filters:t===Ki.value?[]:[t]}),!0)}),this.addActivationHandler(this.onActivate.bind(this))}}function Qi(e){return{container:o.css`
|
|
display: flex;
|
|
|
|
& > div {
|
|
margin: 0;
|
|
}
|
|
`,label:o.css`
|
|
margin-right: 0;
|
|
background-color: ${e.colors.background.primary};
|
|
border: 1px solid ${e.colors.border.medium};
|
|
border-right: 0 none;
|
|
border-top-right-radius: 0;
|
|
border-bottom-right-radius: 0;
|
|
`,tooltipIcon:o.css`
|
|
margin-left: ${e.spacing(.5)};
|
|
`}}function Yi(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Xi(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}zi(Wi,"Component",({model:e})=>{const t=(0,l.useStyles2)(Qi),{loading:n,options:r,value:a,error:i}=e.useState();return u().createElement("div",{className:t.container,"data-testid":"prefix-filter-selector"},u().createElement(l.InlineField,{disabled:n,error:i&&i.toString(),label:u().createElement(l.InlineLabel,{width:"auto",className:t.label},u().createElement("span",null,"View by"),u().createElement(l.Tooltip,{content:"View by the metric prefix. A metric prefix is a single word at the beginning of the metric name, relevant to the domain the metric belongs to.",placement:"top"},u().createElement(l.Icon,{className:t.tooltipIcon,name:"info-circle",size:"sm"})))},u().createElement(l.Combobox,{value:a,onChange:e.selectOption,options:r})))});class Ji extends i.EmbeddedScene{constructor(e){super(Xi(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Yi(e,t,n[t])})}return e}({},e),{key:"related-list-controls",body:new i.SceneFlexLayout({direction:"row",width:"100%",maxHeight:"32px",children:[new i.SceneFlexItem({width:"auto",body:new Wi({})}),new i.SceneFlexItem({body:new Ze({urlSearchParamName:"gmd-relatedSearchText",targetName:"related metric",countsProvider:new Ye,displayCounts:!0})}),new i.SceneFlexItem({width:"auto",body:new qe({})})]})}))}}function Zi(){return{controls:(0,o.css)({display:"flex",alignItems:"end"})}}Yi(Ji,"Component",({model:e})=>{const t=(0,l.useStyles2)(Zi),{body:n}=e.useState();return u().createElement("div",{className:t.controls,"data-testid":"related-list-controls"},u().createElement(n.Component,{model:n}))});class eo extends i.SceneObjectBase{onActivate(){i.sceneGraph.findByKeyAndType(this,Me,$e).fetchAllMetrics(),this.subscribeToEvents()}subscribeToEvents(){this.initVariablesFilteringAndSorting()}initVariablesFilteringAndSorting(){const{metric:e}=this.state,t=new Map;this.subscribeToEvent(Ae,e=>{const{key:n}=e.payload,r=i.sceneGraph.findByKey(this,n);t.set(n,{filterEngine:new it(r),sortEngine:new pt(r)})}),this.subscribeToEvent(Le,e=>{t.delete(e.payload.key)});const n=i.sceneGraph.findByKeyAndType(this,"quick-search",Ze);this.subscribeToEvent(Be,r=>{const{key:a,options:i}=r.payload,{filterEngine:o,sortEngine:s}=t.get(a);o.setInitOptions(i);const l={names:n.state.value?[n.state.value]:[]};o.applyFilters(l,{forceUpdate:!0,notify:!1}),s.sort("related",{metric:e})}),this.subscribeToEvent(Xe,n=>{const{searchText:r}=n.payload;for(const[,{filterEngine:n,sortEngine:a}]of t)n.applyFilters({names:r?[r]:[]}),a.sort("related",{metric:e})}),this.subscribeToEvent(ar,n=>{const{type:r,filters:a}=n.payload;for(const[,{filterEngine:n,sortEngine:i}]of t)n.applyFilters({[r]:a}),i.sort("related",{metric:e})})}constructor({metric:e}){super({metric:e,$variables:new i.SceneVariableSet({variables:[new Ue]}),key:"RelatedMetricsScene",body:new Yn({variableName:Ge}),listControls:new Ji({})}),this.addActivationHandler(this.onActivate.bind(this))}}function to(e,t,n){return{variables:(0,o.css)({display:"none"}),searchSticky:(0,o.css)({margin:e.spacing(1,0,1.5,0),position:"sticky",top:`calc(var(--app-controls-height, 0px) + ${t}px + var(--action-bar-height, 0px))`,zIndex:10,background:Fa(e,n),paddingBottom:e.spacing(1)})}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(eo,"Component",({model:e})=>{const t=(0,a.useChromeHeaderHeight)(),n=ds(e),r=(0,l.useStyles2)(to,n.state.embedded?0:null!=t?t:0,n),{$variables:i,body:o,listControls:s}=e.useState();return u().createElement(u().Fragment,null,u().createElement("div",{className:r.searchSticky},u().createElement(s.Component,{model:s})),u().createElement("div",{"data-testid":"panels-list"},u().createElement(o.Component,{model:o})),u().createElement("div",{className:r.variables},null==i?void 0:i.state.variables.map(e=>u().createElement(e.Component,{key:e.state.name,model:e}))))});const no="breakdown",ro="logs",ao=[{displayName:"Breakdown",value:no,getScene:e=>new Gi({metric:e.state.metric})},{displayName:"Related metrics",value:"related",getScene:e=>new eo({metric:e.state.metric}),description:"Relevant metrics based on current label filters"},{displayName:"Related logs",value:ro,getScene:e=>e.createRelatedLogsScene(),description:"Relevant logs based on current label filters and time range"}];class io extends i.SceneObjectBase{}function oo(e){return{actions:(0,o.css)({[e.breakpoints.up(e.breakpoints.values.md)]:{position:"absolute",right:0,top:16,zIndex:2}}),customTabsBar:(0,o.css)({paddingBottom:e.spacing(1)})}}function so(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function lo(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){so(i,r,a,o,s,"next",e)}function s(e){so(i,r,a,o,s,"throw",e)}o(void 0)})}}!function(e,t,n){t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}(io,"Component",({model:e})=>{const t=i.sceneGraph.getAncestor(e,Do),n=(0,l.useStyles2)(oo),{actionView:r}=t.useState();return u().createElement(l.Box,{paddingY:1,"data-testid":"action-bar",width:"100%"},u().createElement("div",{className:n.actions},u().createElement(l.Stack,{gap:1})),u().createElement(l.TabsBar,{className:n.customTabsBar},ao.map((e,n)=>{const a=e.displayName,i=e.value===ro?t.state.relatedLogsCount:void 0,o=r===e.value,s=u().createElement(l.Tab,{key:n,label:a,counter:i,active:o,onChangeTab:()=>{o||((0,d.z)("metric_action_view_changed",{view:e.value,related_logs_count:t.relatedLogsOrchestrator.checkConditionsMetForRelatedLogs()?i:void 0}),t.setActionView(e.value))}});return e.description?u().createElement(l.Tooltip,{key:n,content:e.description,placement:"top",theme:"info"},s):s})))});const co={job:"service_name",instance:"service_instance_id"};function uo(e){return e in co?co[e]:e}const po=e=>{let t=!1;return{name:"labelsCrossReference",checkConditionsMetForRelatedLogs:()=>t,getDataSources:()=>lo(function*(){var n;const r=ds(e),o=i.sceneGraph.lookupVariable(O,r);if(!$(o)||!o.state.filters.length)return t=!1,[];t=!0;const s=o.state.filters.map(({key:e,operator:t,value:n})=>({key:e,operator:t,value:n})),l=null===(n=e.state.$timeRange)||void 0===n?void 0:n.state.value,c=yield(0,S.tS)().getHealthyDataSources("loki"),u=yield Promise.all(c.map(({uid:e,name:t})=>lo(function*(){const n=yield function(e,t,n){return lo(function*(){var r;const i=yield(0,a.getDataSourceSrv)().get(e),o=yield null===(r=i.getTagKeys)||void 0===r?void 0:r.call(i,{timeRange:n,filters:t.map(({key:e,operator:t,value:n})=>({key:uo(e),operator:t,value:n}))});if(!Array.isArray(o))return!1;const s=new Set(o.map(e=>e.text));return!!t.map(e=>uo(e.key)).every(e=>s.has(e))&&(yield Promise.all(t.map(e=>lo(function*(){var r;const a=uo(e.key),o=yield null===(r=i.getTagValues)||void 0===r?void 0:r.call(i,{key:a,timeRange:n,filters:t});return!!Array.isArray(o)&&o.some(t=>t.text===e.value)})()))).every(Boolean)})()}(e,s,l);return n?{uid:e,name:t}:null})()));return u.filter(e=>null!==e)})(),getLokiQueryExpr(){const t=ds(e),n=i.sceneGraph.lookupVariable(O,t);if(!$(n)||!n.state.filters.length)return"";return`{${n.state.filters.map(e=>`${uo(e.key)}${e.operator}"${e.value}"`).join(",")}}`}}};var mo=n(6365);function ho(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function fo(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){ho(i,r,a,o,s,"next",e)}function s(e){ho(i,r,a,o,s,"throw",e)}o(void 0)})}}function bo(e,t,n){if(!t||!n[t])return"";const r=n[t].find(t=>t.name===e);if(!r)return"";return function(e){if(function(e){if(e.trim().length<=2)return!1;let t=!1;const n=mo.K3.parse(e);return n.iterate({enter:({type:e})=>{if(e.id===mo.Yw)return t=!0,!1}}),!t}(e))return e;const t=vo(e,mo.MD);if(!t)return"";const n=e.substring(t.from,t.to),r=vo(e,mo.AL),a=r?e.substring(r.from,r.to):"";return`${n} ${a}`.trim()}(r.query)}function go(){return fo(function*(){const e=yield(0,S.tS)().getHealthyDataSources("loki"),t={};return yield Promise.all(e.map(e=>fo(function*(){try{const r=function(e,t){if(0===e.length)return[];const n=new Map;return e.forEach(e=>{e.rules.filter(e=>"recording"===e.type).forEach(({type:e,name:r,query:a})=>{if(n.has(r)){const e=n.get(r);e&&(e.hasMultipleOccurrences=!0,n.set(r,e))}else n.set(r,{type:e,name:r,query:a,datasource:{name:t.name,uid:t.uid},hasMultipleOccurrences:!1})})}),Array.from(n.values())}(yield(n=e,fo(function*(){const e={url:`api/prometheus/${n.uid}/api/v1/rules`,showErrorAlert:!1,showSuccessAlert:!1},t=yield(0,jn.lastValueFrom)((0,a.getBackendSrv)().fetch(e));return t.ok?t.data.data.groups:(Z.v.warn(`Failed to fetch recording rules from Loki data source: ${n.name}`),[])})()),e);t[e.uid]=r}catch(e){Z.v.warn(e)}var n})())),t})()}const yo=()=>{let e={},t=!1;return{name:"lokiRecordingRules",checkConditionsMetForRelatedLogs:()=>t,getDataSources:n=>fo(function*(){e=yield go();const r=function(e,t){const n=[];return Object.values(t).forEach(t=>{t.filter(t=>t.name===e).forEach(e=>{n.push(e.datasource)})}),n}(n,e);return t=Boolean(r.length),r})(),getLokiQueryExpr:(t,n)=>bo(t,n,e)}};function vo(e,t){let n;return mo.K3.parse(e).iterate({enter:e=>{if(e.type.id===t)return n=e.node,!1}}),n}function So(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function wo(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Oo{get lokiDataSources(){return this._internalState.lokiDataSources}set lokiDataSources(e){const t=this._internalState.lokiDataSources.map(e=>e.uid).join(","),n=e.map(e=>e.uid).join(",");t&&t===n||(this._internalState.lokiDataSources=e,this._changeHandlers.lokiDataSources.forEach(e=>e(this._internalState.lokiDataSources)))}set relatedLogsCount(e){this._internalState.relatedLogsCount=e,this._changeHandlers.relatedLogsCount.forEach(e=>e(this._internalState.relatedLogsCount))}addLokiDataSourcesChangeHandler(e){this._changeHandlers.lokiDataSources.push(e)}addRelatedLogsCountChangeHandler(e){this._changeHandlers.relatedLogsCount.push(e)}handleFiltersChange(){this.lokiDataSources&&(this.lokiDataSources=[],this.relatedLogsCount=0,this.findAndCheckAllDatasources())}findAndCheckAllDatasources(){return(e=function*(){const e=yield this._dataSourceFetcher.getHealthyDataSources("loki");e.length>0?this.checkLogsInDataSources(e):(this.lokiDataSources=[],this.relatedLogsCount=0)},function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){So(i,r,a,o,s,"next",e)}function s(e){So(i,r,a,o,s,"throw",e)}o(void 0)})}).call(this);var e}getLokiQueries(e,t=100){const{metric:n}=this._metricScene.state,r=this._logsConnectors.reduce((t,r,a)=>{const i=r.getLokiQueryExpr(n,e);var o;i&&(t[null!==(o=r.name)&&void 0!==o?o:`connector-${a}`]=i);return t},{});return Object.keys(r).map(e=>({refId:`RelatedLogs-${e}`,expr:r[e],maxLines:t,supportingQueryType:ui.id}))}checkLogsInDataSources(e){const t=[];let n=0,a=0;if(0===e.length)return this.lokiDataSources=[],void(this.relatedLogsCount=0);e.forEach(o=>{const s=new i.SceneQueryRunner({datasource:{uid:o.uid},queries:[],key:`related_logs_check_${o.uid}`});s.setState({queries:this.getLokiQueries(o.uid)}),s.subscribeToState(i=>{var s;if((null===(s=i.data)||void 0===s?void 0:s.state)===r.LoadingState.Done){var l;if(a++,null===(l=i.data)||void 0===l?void 0:l.series){const e=this.countLogsLines(i);e>0&&(t.push(o),n+=e)}a===e.length&&(this.lokiDataSources=t,this.relatedLogsCount=n)}}),s.activate()})}checkConditionsMetForRelatedLogs(){return this._logsConnectors.some(e=>e.checkConditionsMetForRelatedLogs())}countLogsLines(e){var t,n;return null!==(n=null===(t=e.data)||void 0===t?void 0:t.series.reduce((e,t)=>e+t.length,0))&&void 0!==n?n:0}constructor(e){wo(this,"_logsConnectors",void 0),wo(this,"_metricScene",void 0),wo(this,"_dataSourceFetcher",(0,S.tS)()),wo(this,"_changeHandlers",{lokiDataSources:[],relatedLogsCount:[]}),wo(this,"_internalState",{relatedLogsCount:0,lokiDataSources:[]}),this._metricScene=e,this._logsConnectors=[yo(),po(e)]}}function Eo(){const e=(0,l.useStyles2)(xo);return u().createElement(l.Stack,{direction:"column",gap:2},u().createElement(l.Alert,{title:"No related logs found",severity:"info"},"We couldn't find any logs related to the current metric with your selected filters."),u().createElement(l.Text,null,"To find related logs, try the following:",u().createElement("ul",{className:e.list},u().createElement("li",null,"Adjust your label filters to include labels that exist in both the current metric and your logs"),u().createElement("li",null,"Select a metric created by a"," ",u().createElement(l.TextLink,{external:!0,href:"https://grafana.com/docs/loki/latest/alert/#recording-rules"},"Loki Recording Rule")),u().createElement("li",null,"Broaden the time range to include more data"))),u().createElement(l.Text,{variant:"bodySmall",color:"secondary"},"Note: Related logs is an experimental feature."))}function xo(e){return{list:(0,o.css)({paddingLeft:e.spacing(2),marginTop:e.spacing(1)})}}function Co({context:e}){const t=(0,c.useMemo)(()=>e,[e]),{links:n,isLoading:r}=(0,a.usePluginLinks)({extensionPointId:"grafana-metricsdrilldown-app/open-in-logs-drilldown/v1",limitPerPlugin:1,context:t}),i=(0,c.useMemo)(()=>n.find(({pluginId:e})=>"grafana-lokiexplore-app"===e),[n]);if(r)return u().createElement(l.LinkButton,{variant:"secondary",size:"sm",disabled:!0},"Loading...");const o=void 0!==i;return u().createElement(l.LinkButton,{href:o?`${a.config.appSubUrl}${i.path}`:`${a.config.appSubUrl}/a/grafana-lokiexplore-app`,target:"_blank",tooltip:o?"Use the Logs Drilldown app to explore these logs":"Navigate to the Logs Drilldown app",variant:"secondary",size:"sm",onClick:()=>(0,d.z)("related_logs_action_clicked",{action:"open_logs_drilldown"})},o?"Open in Logs Drilldown":"Open Logs Drilldown")}function Po(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function ko(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function jo(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}const _o="related_logs/logs_panel_container";class To extends i.SceneObjectBase{_onActivate(){return(e=function*(){this.state.orchestrator.addLokiDataSourcesChangeHandler(()=>this.setupLogsPanel()),this.state.orchestrator.lokiDataSources.length?this.setupLogsPanel():(this.setState({loading:!0}),yield this.state.orchestrator.findAndCheckAllDatasources(),this.setState({loading:!1}))},function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){Po(i,r,a,o,s,"next",e)}function s(e){Po(i,r,a,o,s,"throw",e)}o(void 0)})}).call(this);var e}showNoLogsFound(){i.sceneGraph.findByKeyAndType(this,_o,i.SceneFlexItem).setState({body:new i.SceneReactObject({component:Eo})}),this.setState({controls:void 0}),this.state.orchestrator.relatedLogsCount=0}_buildQueryRunner(){this._queryRunner=new i.SceneQueryRunner({datasource:{uid:"${logsDs}"},queries:[],key:"related_logs/logs_query"}),this._constructLogsDrilldownLinkContext(this._queryRunner.state),this._subs.add(this._queryRunner.subscribeToState(e=>{var t;if((null===(t=e.data)||void 0===t?void 0:t.state)!==r.LoadingState.Done)return;0===this.state.orchestrator.countLogsLines(e)&&this.showNoLogsFound(),this._constructLogsDrilldownLinkContext(e)}))}setupLogsPanel(){if(this._buildQueryRunner(),!this.state.orchestrator.lokiDataSources.length)return void this.showNoLogsFound();i.sceneGraph.findByKeyAndType(this,_o,i.SceneFlexItem).setState({body:i.PanelBuilders.logs().setTitle("Logs").setOption("showLogContextToggle",!0).setOption("showTime",!0).setOption("showControls",!0).setOption("controlsStorageKey","grafana.explore.logs").setData(this._queryRunner).build()});const e=new i.CustomVariable({name:k,label:"Logs data source",query:this.state.orchestrator.lokiDataSources.map(e=>`${e.name} : ${e.uid}`).join(",")});this.setState({$variables:new i.SceneVariableSet({variables:[e]}),controls:[new i.VariableValueSelectors({layout:"vertical"})]}),this._subs.add(e.subscribeToState((e,t)=>{e.value!==t.value&&(0,d.z)("related_logs_action_clicked",{action:"logs_data_source_changed"})})),this.updateLokiQuery()}_constructLogsDrilldownLinkContext(e){var t,n;const r=null!==(n=null===(t=i.sceneGraph.lookupVariable(k,this))||void 0===t?void 0:t.getValue())&&void 0!==n?n:"",a=e.queries,o=[];r&&a.length&&a.forEach(e=>{o.push(jo(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){ko(e,t,n[t])})}return e}({},e),{datasource:{uid:r,type:"loki"}}))}),this.setState({logsDrilldownLinkContext:{targets:o,timeRange:i.sceneGraph.getTimeRange(this).state}})}updateLokiQuery(){if(!this._queryRunner)return;const e=i.sceneGraph.lookupVariable(k,this);let t;if(V(e)&&(t=e.getValue()),!t)return;const n=this.state.orchestrator.getLokiQueries(t);0!==n.length?this._queryRunner.setState({queries:n}):this.showNoLogsFound()}constructor(e){super({loading:!1,controls:[],body:new i.SceneFlexLayout({direction:"column",height:"100%",minHeight:500,children:[new i.SceneFlexItem({key:_o,body:void 0})]}),orchestrator:e.orchestrator,logsDrilldownLinkContext:{targets:[]}}),ko(this,"_queryRunner",void 0),ko(this,"_variableDependency",new i.VariableDependencyConfig(this,{variableNames:[k,O],onReferencedVariableValueChanged:e=>{e.state.name===O?this.state.orchestrator.handleFiltersChange():e.state.name===k&&this.updateLokiQuery()}})),this.addActivationHandler(()=>{this._onActivate()})}}function Io(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}ko(To,"Component",({model:e})=>{const{controls:t,body:n,logsDrilldownLinkContext:r,loading:a}=e.useState();return a?u().createElement(l.Spinner,null):u().createElement(l.Stack,{gap:1,direction:"column",grow:1,height:"100%"},u().createElement(l.Stack,{gap:1,direction:"row",justifyContent:"space-between",alignItems:"start"},u().createElement(l.Stack,{gap:1},null==t?void 0:t.map(e=>u().createElement(e.Component,{key:e.state.key,model:e}))),u().createElement(Co,{context:r})),u().createElement(n.Component,{model:n}))});class Do extends i.SceneObjectBase{_onActivate(){void 0===this.state.actionView&&this.setActionView(no),this.relatedLogsOrchestrator.findAndCheckAllDatasources(),this.relatedLogsOrchestrator.addRelatedLogsCountChangeHandler(e=>{this.setState({relatedLogsCount:e})}),this.subscribeToEvents()}subscribeToEvents(){a.config.featureToggles.enableScopesInMetricsExplore&&this.subscribeToEvent(D,e=>{var t;null===(t=this.state.body.state.selectedTab)||void 0===t||t.publishEvent(e)})}getUrlState(){return{actionView:this.state.actionView}}updateFromUrl(e){if("string"==typeof e.actionView){if(this.state.actionView!==e.actionView){const t=ao.find(t=>t.value===e.actionView);t&&this.setActionView(t.value)}}else null===e.actionView&&this.setActionView(null)}setActionView(e){const{body:t}=this.state,n=e?ao.find(t=>t.value===e):null;n&&n.value!==this.state.actionView?(t.setState({selectedTab:n.getScene(this)}),this.setState({actionView:n.value})):(t.setState({selectedTab:void 0}),this.setState({actionView:void 0}))}createRelatedLogsScene(){return new To({orchestrator:this.relatedLogsOrchestrator})}constructor(e){var t,n,r;super(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Io(e,t,n[t])})}return e}({$variables:null!==(t=e.$variables)&&void 0!==t?t:(r=e.metric,new i.SceneVariableSet({variables:[new i.ConstantVariable({name:"metric",value:r,hide:La.zL.hideVariable}),new $a]})),body:null!==(n=e.body)&&void 0!==n?n:new ni({metric:e.metric})},e)),Io(this,"relatedLogsOrchestrator",new Oo(this)),Io(this,"_urlSync",new i.SceneObjectUrlSyncConfig(this,{keys:["actionView"]})),Io(this,"_variableDependency",new i.VariableDependencyConfig(this,{variableNames:[O],onReferencedVariableValueChanged:()=>{this.relatedLogsOrchestrator.handleFiltersChange()}})),this.addActivationHandler(this._onActivate.bind(this))}}Io(Do,"Component",({model:e})=>{const{body:t}=e.useState(),n=(0,l.useStyles2)(Ao);return u().createElement("div",{className:n.container,"data-testid":"metric-scene"},u().createElement(t.Component,{model:t}))});const Ao=()=>({container:(0,o.css)({position:"relative",height:"100%",width:"100%",display:"flex",flexDirection:"column"})});var Lo=n(5176);const Bo=(0,c.memo)(function({size:e}){const t=(0,l.useStyles2)(No);return u().createElement("img",{className:(0,o.cx)(t.logo,e),src:"public/plugins/grafana-metricsdrilldown-app/img/logo.svg"})}),No=()=>({logo:o.css`
|
|
&.small {
|
|
width: 24px;
|
|
height: 24px;
|
|
margin-right: 4px;
|
|
position: relative;
|
|
top: -2px;
|
|
}
|
|
|
|
&.large {
|
|
width: 40px;
|
|
height: 40px;
|
|
}
|
|
`}),Ro=Lo.t,Mo=`https://github.com/grafana/metrics-drilldown/commit/${Ro}`,{buildInfo:$o}=a.config;function Vo(){const e=(0,l.useStyles2)(Go),{meta:{info:{version:t,updated:n}}}=(0,r.usePluginContext)()||{meta:{info:{version:"?.?.?",updated:"?"}}};return u().createElement("div",{className:e.menuHeader},u().createElement("h5",null,u().createElement(Bo,{size:"small"}),"Grafana Metrics Drilldown v",t),u().createElement("div",{className:e.subTitle},"Last update: ",n))}function Fo({getPrometheusBuildInfo:e}){const t=(0,l.useStyles2)(Go),n="dev"===Ro,r=n?Ro:Ro.slice(0,8),[a,i]=(0,c.useState)();return(0,c.useEffect)(()=>{e().then(e=>i(e)).catch(e=>{Z.v.warn("Error while fetching Prometheus build info!"),Z.v.warn(e),i(void 0)})},[e]),u().createElement(l.Menu,{header:u().createElement(Vo,null)},u().createElement(l.Menu.Item,{label:`Commit SHA: ${r}`,icon:"github",onClick:()=>window.open(Mo),disabled:n}),u().createElement(l.Menu.Item,{label:"Changelog",icon:"list-ul",onClick:()=>window.open("https://github.com/grafana/metrics-drilldown/blob/main/CHANGELOG.md","_blank","noopener,noreferrer")}),u().createElement(l.Menu.Item,{label:"Contribute",icon:"external-link-alt",onClick:()=>window.open("https://github.com/grafana/metrics-drilldown/blob/main/docs/contributing.md","_blank","noopener,noreferrer")}),u().createElement(l.Menu.Item,{label:"Documentation",icon:"document-info",onClick:()=>window.open("https://grafana.com/docs/grafana/latest/explore/simplified-exploration/metrics","_blank","noopener,noreferrer")}),u().createElement(l.Menu.Item,{label:"Report an issue",icon:"bug",onClick:()=>window.open("https://github.com/grafana/metrics-drilldown/issues/new?template=bug_report.md","_blank","noopener,noreferrer")}),u().createElement(l.Menu.Divider,null),u().createElement(l.Menu.Item,{label:`Grafana ${$o.edition} v${$o.version} (${$o.env})`,icon:"grafana",onClick:()=>window.open(`https://github.com/grafana/grafana/commit/${$o.commit}`,"_blank","noopener,noreferrer")}),a&&u().createElement(l.Menu.Item,{className:t.promBuildInfo,label:`${a.application||"?"} ${a.version} ${a.buildDate?`(${a.buildDate})`:""}`,icon:"gf-prometheus",onClick:()=>window.open(`${a.repository}/commit/${a.revision}`,"_blank","noopener,noreferrer")}))}function qo({getPrometheusBuildInfo:e}){return u().createElement(l.Dropdown,{overlay:()=>u().createElement(Fo,{getPrometheusBuildInfo:e}),placement:"bottom-end"},u().createElement(l.Button,{icon:"info-circle",variant:"secondary",tooltip:"Plugin info",tooltipPlacement:"top",title:"Plugin info","data-testid":"plugin-info-button"}))}const Go=e=>({button:o.css`
|
|
position: relative;
|
|
display: flex;
|
|
align-items: center;
|
|
width: 32px;
|
|
height: 32px;
|
|
line-height: 30px;
|
|
border: 1px solid ${e.colors.border.weak};
|
|
border-radius: 2px;
|
|
border-left: 0;
|
|
color: ${e.colors.text.primary};
|
|
background: ${e.colors.background.secondary};
|
|
|
|
&:hover {
|
|
border-color: ${e.colors.border.medium};
|
|
background-color: ${e.colors.background.canvas};
|
|
}
|
|
`,menuHeader:o.css`
|
|
padding: ${e.spacing(.5,1)};
|
|
white-space: nowrap;
|
|
`,subTitle:o.css`
|
|
color: ${e.colors.text.secondary};
|
|
font-size: ${e.typography.bodySmall.fontSize};
|
|
`,promBuildInfo:o.css`
|
|
& svg {
|
|
color: #e5502a;
|
|
}
|
|
`});var Uo=n(3781);const zo={OPEN_EXPLORE_LABEL:"Open in explore",COPY_URL_LABEL:"Copy url",BOOKMARK_LABEL:"Bookmark",SELECT_NEW_METRIC_TOOLTIP:"Remove existing metric and choose a new metric"};function Ho(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class Ko extends i.SceneObjectBase{constructor(e={}){super(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Ho(e,t,n[t])})}return e}({},e)),Ho(this,"onSelectNewMetric",()=>{const e=ds(this);(0,d.z)("selected_metric_action_clicked",{action:"unselect"}),e.publishEvent(new I({}))})}}function Wo(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function Qo(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){Wo(i,r,a,o,s,"next",e)}function s(e){Wo(i,r,a,o,s,"throw",e)}o(void 0)})}}function Yo(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Ho(Ko,"Component",({model:e})=>{const t=ds(e),{embedded:n}=t.useState();return n?u().createElement(l.LinkButton,{href:(0,Uo.Rk)(ms(t)),variant:"secondary",icon:"arrow-right",tooltip:"Open in Metrics Drilldown",onClick:()=>(0,d.z)("selected_metric_action_clicked",{action:"open_from_embedded"}),"data-testid":"open-metrics-drilldown-button"},"Metrics Drilldown"):u().createElement(l.ToolbarButton,{variant:"canvas",tooltip:zo.SELECT_NEW_METRIC_TOOLTIP,onClick:e.onSelectNewMetric,"data-testid":"select-new-metric-button"},"Select new metric")});class Xo extends i.SceneObjectBase{getUrlState(){return{metric:this.state.metric}}updateFromUrl(e){this.updateStateForNewMetric(e.metric||void 0)}onActivate(){!function(e){try{for(const t of e)(0,i.registerRuntimeDataSource)({dataSource:t})}catch(e){const{message:t}=e;/A runtime data source with uid (.+) has already been registered/.test(t)||(0,v.jx)(e,["Fail to register all the runtime data sources!","The application cannot work as expected, please try reloading the page or if the problem persists, contact your organization admin."])}}([new H]),setTimeout(()=>{this.datasourceHelper.init()},0),this.updateStateForNewMetric(this.state.metric),this.subscribeToEvent(I,e=>this.handleMetricSelectedEvent(e)),this.initFilters(),this.initConfigPrometheusFunction()}updateStateForNewMetric(e){if(!this.state.topScene||e!==this.state.metric){const t=[new i.VariableValueSelectors({layout:"vertical"}),new i.SceneControlsSpacer],n=e?[...t,new Ko,new i.SceneTimePicker({}),new i.SceneRefreshPicker({})]:[...t,new i.SceneTimePicker({}),new i.SceneRefreshPicker({})];this.setState({metric:e,topScene:e?new Do({metric:e}):new ea,controls:n})}}initFilters(){const e=i.sceneGraph.lookupVariable(O,this);$(e)&&(ys(this,e,this.datasourceHelper),null==e||e.setState({useQueriesAsFilterForOptions:Boolean(this.state.metric)}),this.subscribeToState((e,t)=>{if(e.metric!==t.metric){const t=i.sceneGraph.lookupVariable(O,this);$(t)&&t.setState({useQueriesAsFilterForOptions:Boolean(e.metric)})}}),this._subs.add(null==e?void 0:e.subscribeToState((e,t)=>{this.disableReportFiltersInteraction||e.filters===t.filters||(0,d.h)(e.filters,t.filters)})))}initConfigPrometheusFunction(){this.subscribeToState((e,t)=>{e.metric!==t.metric&&this.state.drawer.close()}),this.subscribeToEvent(Ct,e=>Qo(function*(){const{metric:t}=e.payload;(0,d.z)("configure_panel_opened",{metricType:t.type}),this.state.drawer.open({title:"Configure the Prometheus function",subTitle:`${t.name} (${t.type})`,body:new Ca({metric:t})})}).call(this)),this.subscribeToEvent(fa,()=>{this.state.drawer.close()}),this.subscribeToEvent(ha,e=>Qo(function*(){const{metric:t,config:n,restoreDefault:r}=e.payload;r?(0,d.z)("default_panel_config_restored",{metricType:t.type}):(0,d.z)("panel_config_applied",{metricType:t.type,configId:n.id}),this.state.drawer.close(),function(e){const t=i.sceneGraph.findAllObjects(e,e=>{var t;return Boolean(null===(t=e.state.$behaviors)||void 0===t?void 0:t.some(e=>"syncYAxis"===e.__name__))});for(const e of t)e.publishEvent(new ja({}),!0)}(this.state.topScene||this);const a=i.sceneGraph.findAllObjects(this.state.topScene||this,e=>e instanceof zn&&e.state.metric===t.name&&!e.state.queryConfig.groupBy);for(const e of a)e.update(n.panelOptions,n.queryOptions);(0,v.qq)([`Configuration successfully ${r?"restored":"applied"} for metric ${t.name}!`])}).call(this))}handleMetricSelectedEvent(e){return Qo(function*(){const{metric:t,urlValues:n}=e.payload;t?function(e){try{const t=Pe(),n=Date.now(),r=t.filter(t=>t.name!==e);r.unshift({name:e,timestamp:n});const a=r.slice(0,6);te.x.setItem(ee.V.RECENT_METRICS,a)}catch(t){const n=t instanceof Error?t:new Error(String(t));Z.v.error(n,Ce(xe({},n.cause||{}),{metricName:e}))}}(t):i.sceneGraph.findByKeyAndType(this,Me,$e).fetchAllOrRecentMetrics();const a=i.sceneGraph.lookupVariable(O,this);$(a)&&a.setState({baseFilters:es(t)}),this._urlSync.performBrowserHistoryAction(()=>{if(this.updateStateForNewMetric(t),n){var e;(null===(e=n[`var-${O}`])||void 0===e?void 0:e.length)||(n[`var-${O}`]=[""]);const t=r.urlUtil.renderUrl("",n);i.sceneUtils.syncStateFromSearchParams(this,new URLSearchParams(t))}})}).call(this)}addFilterWithoutReportingInteraction(e){const t=i.sceneGraph.lookupVariable(O,this);$(t)&&(this.disableReportFiltersInteraction=!0,t.setState({filters:[...t.state.filters,e]}),this.disableReportFiltersInteraction=!1)}getMetadataForMetric(e){return Qo(function*(){return this.datasourceHelper.getMetadataForMetric(e)}).call(this)}getPrometheusBuildInfo(){return Qo(function*(){return this.datasourceHelper.getPrometheusBuildInfo()}).call(this)}fetchRecentMetrics(e){return Qo(function*({interval:e,extraFilter:t}){return this.datasourceHelper.fetchRecentMetrics({interval:e,extraFilter:t})}).apply(this,arguments)}constructor(e){var t,n,r,a;super(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){Yo(e,t,n[t])})}return e}({$timeRange:null!==(t=e.$timeRange)&&void 0!==t?t:new i.SceneTimeRange({}),$variables:null!==(n=e.$variables)&&void 0!==n?n:Jo(e.initialDS,e.metric,e.initialFilters),controls:null!==(r=e.controls)&&void 0!==r?r:[new i.VariableValueSelectors({layout:"vertical"}),new i.SceneControlsSpacer,new i.SceneTimePicker({}),new i.SceneRefreshPicker({})],createdAt:null!==(a=e.createdAt)&&void 0!==a?a:(new Date).getTime(),dashboardMetrics:{},alertingMetrics:{},drawer:new y({})},e)),Yo(this,"disableReportFiltersInteraction",!1),Yo(this,"datasourceHelper",new R(this)),Yo(this,"_variableDependency",new i.VariableDependencyConfig(this,{variableNames:[C],onReferencedVariableValueChanged:()=>{this.datasourceHelper.reset()}})),Yo(this,"_urlSync",new i.SceneObjectUrlSyncConfig(this,{keys:["metric"]})),this.addActivationHandler(this.onActivate.bind(this))}}function Jo(e,t,n){let o=[new Er({initialDS:e}),new $e,new De,new i.AdHocFiltersVariable({key:O,name:O,label:"Filters",addFilterButtonText:"Add label",datasource:T,hide:r.VariableHide.dontHide,layout:"combobox",filters:null!=n?n:[],baseFilters:es(t),applyMode:"manual",allowCustomValue:!0,useQueriesAsFilterForOptions:!1,expressionBuilder:e=>e.filter(e=>"__name__"!==e.key).map(e=>`${(0,s.Nc)(e.key)}${e.operator}"${e.value}"`).join(",")}),new X];return Boolean(a.config.featureToggles.scopeFilters&&a.config.featureToggles.enableScopesInMetricsExplore&&!a.config.buildInfo.version.startsWith("11."))&&o.unshift(new i.ScopesVariable({enable:!0})),new i.SceneVariableSet({variables:o})}function Zo(e,t,n){const r=Fa(e,n);return{container:(0,o.css)({flexGrow:1,display:"flex",gap:e.spacing(1),flexDirection:"column",padding:e.spacing(1,2),position:"relative",background:r}),body:(0,o.css)({flexGrow:1,display:"flex",flexDirection:"column",minHeight:0}),controls:(0,o.css)({display:"flex",gap:e.spacing(1),padding:e.spacing(1,0),alignItems:"flex-end",flexWrap:"wrap",position:"sticky",background:r,zIndex:e.zIndex.navbarFixed,top:t,borderBottom:`1px solid ${e.colors.border.weak}`}),settingsInfo:(0,o.css)({display:"flex",gap:e.spacing(.5)})}}function es(e){return e?[{key:"__name__",operator:"=",value:e}]:[]}function ts(){const e=document.querySelector('[data-testid="app-controls"]');if(!e)return;const{height:t}=e.getBoundingClientRect();document.documentElement.style.setProperty("--app-controls-height",`${t}px`)}Yo(Xo,"Component",({model:e})=>{const{controls:t,topScene:n,embedded:r,drawer:o}=e.useState();var s;const d=null!==(s=(0,a.useChromeHeaderHeight)())&&void 0!==s?s:0,p=r?0:d,h=(0,l.useStyles2)(Zo,p,e);return(0,c.useEffect)(()=>{ts();const e=document.querySelector('[data-testid="app-controls"]');if(!e)return;const t=new ResizeObserver(ts);return t.observe(e),()=>{t.disconnect(),document.documentElement.style.removeProperty("--app-controls-height")}},[r,t]),u().createElement(u().Fragment,null,u().createElement("div",{className:h.container},t&&u().createElement("div",{className:h.controls,"data-testid":"app-controls"},u().createElement(m,null),t.map(e=>u().createElement(e.Component,{key:e.state.key,model:e})),u().createElement("div",{className:h.settingsInfo},u().createElement(qo,{getPrometheusBuildInfo:e.getPrometheusBuildInfo}))),n&&u().createElement(i.UrlSyncContextProvider,{scene:n,createBrowserHistorySteps:!0,updateUrlOnInit:!0,namespace:e.state.urlNamespace},u().createElement("div",{className:h.body},n&&u().createElement(n.Component,{model:n})))),u().createElement(o.Component,{model:o}))});var ns=n(3498);function rs(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function as(){return new is}class is extends i.SceneObjectBase{getSelectedScopes(){return this.selectedScopes}getSelectedScopesNames(){return this.selectedScopes.map(({scope:e})=>e.metadata.name)}setSelectedScopes(e){this.selectedScopes=e,this.notifySubscribers()}onScopesChange(e){return this.onScopesChangeCallbacks.push(e),()=>{this.onScopesChangeCallbacks=this.onScopesChangeCallbacks.filter(t=>t!==e)}}notifySubscribers(){for(const e of this.onScopesChangeCallbacks)e(this.selectedScopes)}get value(){return[]}constructor(){super({}),rs(this,"selectedScopes",[]),rs(this,"onScopesChangeCallbacks",[])}}function os(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function ss(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function o(e){os(i,r,a,o,s,"next",e)}function s(e){os(i,r,a,o,s,"throw",e)}o(void 0)})}}function ls(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cs(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){ls(e,t,n[t])})}return e}function us(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function ds(e){return i.sceneGraph.getAncestor(e,Xo)}function ps(e){var t,n;return new Xo(cs({initialDS:null==e?void 0:e.initialDS,$timeRange:null!==(t=null==e?void 0:e.$timeRange)&&void 0!==t?t:new i.SceneTimeRange({from:"now-1h",to:"now"}),embedded:null!==(n=null==e?void 0:e.embedded)&&void 0!==n&&n,urlNamespace:(null==e?void 0:e.embedded)?"gmd":void 0},e))}function ms(e){const t=i.sceneUtils.getUrlState(e);return r.urlUtil.renderUrl(ns.b.Drilldown,t)}function hs(e){return e?e===_?"Logs":e:"All metrics"}function fs(e){const t=a.config.theme2.visualization;return t.getColorByName(t.palette[e%8])}function bs(e){return i.sceneGraph.findAllObjects(e,di).flatMap(e=>e.state.queries.map(t=>us(cs({},t),{expr:i.sceneGraph.interpolate(e,t.expr)})))}const gs=1e4;function ys(e,t,n){$(t)&&t.setState({getTagKeysProvider:()=>ss(function*(){var r;const a={filters:t.state.filters,scopes:null===(r=as())||void 0===r?void 0:r.value,queries:t.state.useQueriesAsFilterForOptions?bs(e):[]};return a.queries.length>20&&(a.queries=[]),{replace:!0,values:(yield n.getTagKeys(a)).slice(0,gs)}})(),getTagValuesProvider:(r,a)=>ss(function*(){var r;const i=t.state.filters.filter(e=>e.key!==a.key),o={key:a.key,filters:i,scopes:null===(r=as())||void 0===r?void 0:r.value,queries:t.state.useQueriesAsFilterForOptions?bs(e):[]};o.queries.length>20&&(o.queries=[]);return{replace:!0,values:(yield n.getTagValues(o)).slice(0,gs)}})()})}function vs(e,t,n){const r=i.sceneGraph.findObject(e,t);return r instanceof n?r:(null!==r&&Z.v.warn(`invalid return type: ${n.toString()}`),null)}function Ss(){}},8092:(e,t,n)=>{n.d(t,{BR:()=>i,Hi:()=>o,KF:()=>a});var r=n(5959);const a=(0,n(7558).ef)(),i=(0,r.createContext)({trail:a});function o(){return(0,r.useContext)(i)}},8732:(e,t,n)=>{n.d(t,{S:()=>u,X:()=>l});var r=n(5959),a=n.n(r),i=n(1159),o=n(3498),s=n(8092);const l=(0,r.lazy)(()=>n.e(494).then(n.bind(n,8494))),c=()=>{const e=(0,i.useLocation)();return a().createElement(i.Navigate,{to:`${o.b.Drilldown}${e.search}`,replace:!0})},u=()=>{const{trail:e}=(0,s.Hi)();return a().createElement(i.Routes,null,a().createElement(i.Route,{path:o.b.Drilldown,element:a().createElement(l,{trail:e})}),a().createElement(i.Route,{path:o.b.Trail,element:a().createElement(c,null)}),a().createElement(i.Route,{path:"*",element:a().createElement(i.Navigate,{to:o.b.Drilldown,replace:!0})}))}}}]);
|
|
//# sourceMappingURL=605.js.map?_cache=6af7ff87010f6e6cdcac
|